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.

1,108 linesCodeBlameRaw
1/**
2 * Home, the workspace's front page: where you're needed now, what happened
3 * since you were last here, and what is running. It never depends on the
4 * calendar: what needs you has no time window, and what happened is
5 * counted over a span you choose, since your last visit by default. Every
6 * number is worked out here from what the services return, so each
7 * definition is tested on its own (home.test.ts) and written down in the
8 * Home guide (apps/docs/.../guides/home.md). Imports only types.
9 */
10import type {
11 ActivityDigest,
12 ActorCount,
13 ChatActivity,
14 Deployment,
15 InboxItem,
16 ProjectDeploys,
17 Pull,
18 RepoDigest,
19 RepoPath,
20 Statement,
21 WorkflowRun,
22} from "@g1t/contracts";
23
24const MINUTE = 60_000;
25const HOUR = 60 * MINUTE;
26const DAY = 24 * HOUR;
27
28/** A day's date in a time zone, as `YYYY-MM-DD`; UTC when the zone is unknown or invalid. */
29export function dayIn(at: number, timeZone: string | null): string {
30 try {
31 return new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: timeZone || "UTC" }).format(at);
32 } catch {
33 return new Date(at).toISOString().slice(0, 10);
34 }
35}
36
37/** The hour of the day (0–23) in a time zone; UTC when it is unknown. */
38export function hourIn(at: number, timeZone: string | null): number {
39 const read = (zone: string) => Number(new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: zone }).format(at)) % 24;
40 try {
41 return read(timeZone || "UTC");
42 } catch {
43 return read("UTC");
44 }
45}
46
47function formatIn(at: number, timeZone: string | null, options: Intl.DateTimeFormatOptions): string {
48 try {
49 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timeZone || "UTC" }).format(at);
50 } catch {
51 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format(at);
52 }
53}
54
55/** "Oct 9", in the reader's time zone. */
56export function shortDate(at: number, timeZone: string | null): string {
57 return formatIn(at, timeZone, { month: "short", day: "numeric" });
58}
59
60// --- The span -----------------------------------------------------------------
61
62/** Which span "what happened" covers: since your last visit, or a fixed one. */
63export type WindowKey = "last" | "24h" | "7d";
64
65export const WINDOWS: { key: WindowKey; label: string }[] = [
66 { key: "last", label: "Since last visit" },
67 { key: "24h", label: "Last 24 hours" },
68 { key: "7d", label: "Last 7 days" },
69];
70
71/** The furthest back "since your last visit" looks. */
72export const MAX_AWAY_DAYS = 14;
73
74/** A `?window=` value, or the default: since your last visit. */
75export function parseWindow(value: string | null | undefined): WindowKey {
76 return value === "24h" || value === "7d" ? value : "last";
77}
78
79export type Span = {
80 key: WindowKey;
81 /** Epoch ms: the start of the span. */
82 from: number;
83 now: number;
84 /** "Since Tuesday evening", "In the last 24 hours". */
85 words: string;
86 /** How long it covers: "3 days", "45 minutes". */
87 length: string;
88 /**
89 * Why "since your last visit" covers something else: `first` when there
90 * is no visit on record (it shows the last 24 hours), `capped` when the
91 * last one was longer ago than MAX_AWAY_DAYS, `unknown` when it could
92 * not be read (it shows the last 24 hours).
93 */
94 note: "first" | "capped" | "unknown" | null;
95};
96
97const plural = (n: number, one: string, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
98
99/** How long a stretch of time is, roughly: "a moment", "40 minutes", "3 hours", "3 days", "2 weeks". */
100export function duration(ms: number): string {
101 const minutes = Math.floor(Math.max(0, ms) / MINUTE);
102 if (minutes < 1) return "a moment";
103 if (minutes < 60) return plural(minutes, "minute");
104 const hours = Math.floor(minutes / 60);
105 if (hours < 24) return plural(hours, "hour");
106 const days = Math.floor(hours / 24);
107 if (days < 14) return plural(days, "day");
108 return plural(Math.floor(days / 7), "week");
109}
110
111type Part = "night" | "morning" | "afternoon" | "evening";
112
113/**
114 * When `from` was, in words, from `now`: "a moment ago", "40 minutes ago",
115 * "2 hours ago", "this morning", "last night", "yesterday evening",
116 * "Tuesday evening", "Oct 2". The small hours belong to the night before:
117 * 2 a.m. on Wednesday is Tuesday night.
118 */
119export function sinceWords(from: number, now: number, timeZone: string | null): string {
120 const ago = now - from;
121 if (ago < MINUTE) return "a moment ago";
122 if (ago < HOUR) return `${plural(Math.floor(ago / MINUTE), "minute")} ago`;
123 if (ago < 3 * HOUR) return Math.floor(ago / HOUR) === 1 ? "an hour ago" : `${Math.floor(ago / HOUR)} hours ago`;
124 const hour = hourIn(from, timeZone);
125 const part: Part = hour < 5 ? "night" : hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
126 // The night is the evening's day's.
127 const day = dayIn(part === "night" ? from - 6 * HOUR : from, timeZone);
128 const today = dayIn(now, timeZone);
129 const yesterday = dayIn(now - DAY, timeZone);
130 const twoDaysAgo = dayIn(now - 2 * DAY, timeZone);
131 if (day === today) return `this ${part === "night" ? "evening" : part}`;
132 if (day === yesterday) return part === "night" ? "last night" : `yesterday ${part}`;
133 if (part === "night" && day === twoDaysAgo) return "the night before last";
134 if (ago < 6 * DAY) return `${formatIn(part === "night" ? from - 6 * HOUR : from, timeZone, { weekday: "long" })} ${part}`;
135 return shortDate(from, timeZone);
136}
137
138/**
139 * The span for `key`: since `lastSeen` (your last visit, kept by notify),
140 * or the last 24 hours or 7 days. Since your last visit falls back to the
141 * last 24 hours when there is none (`null`) or it could not be read
142 * (`undefined`), and to MAX_AWAY_DAYS when it was longer ago.
143 */
144export function spanFor(key: WindowKey, now: number, lastSeen: number | null | undefined, timeZone: string | null): Span {
145 if (key === "7d") return { key, from: now - 7 * DAY, now, words: "In the last 7 days", length: "7 days", note: null };
146 if (key === "24h" || lastSeen == null || lastSeen > now) {
147 const note = key !== "last" ? null : lastSeen === undefined ? "unknown" : "first";
148 return { key, from: now - DAY, now, words: "In the last 24 hours", length: "24 hours", note };
149 }
150 const furthest = now - MAX_AWAY_DAYS * DAY;
151 if (lastSeen < furthest) return { key, from: furthest, now, words: `In the last ${MAX_AWAY_DAYS} days`, length: `${MAX_AWAY_DAYS} days`, note: "capped" };
152 return { key, from: lastSeen, now, words: `Since ${sinceWords(lastSeen, now, timeZone)}`, length: duration(now - lastSeen), note: null };
153}
154
155/** Whether `at` (epoch ms or RFC 3339) falls in the span. */
156export function within(at: number | string | null | undefined, span: Pick<Span, "from" | "now">): boolean {
157 if (at == null) return false;
158 const ms = typeof at === "number" ? at : Date.parse(at);
159 return Number.isFinite(ms) && ms >= span.from && ms <= span.now;
160}
161
162// --- Code read for the span -----------------------------------------------------
163
164/** A pull request with where it is: what Home reads from Code. */
165export type CodePull = Pick<Pull, "number" | "title" | "status" | "mergedAt" | "createdAt" | "updatedAt"> & {
166 repo: RepoPath;
167 author: { username: string; kind?: string };
168 /** Who merged it, when it merged. */
169 mergedBy?: string | null;
170};
171
172/** Whether a pull request was opened by g1t itself, as older ones were: shown as `@g1t`. */
173export function isAgentPull(pull: { author: { username: string; kind?: string } }): boolean {
174 const name = pull.author.username;
175 return pull.author.kind === "agent" || name === "g1t" || name.endsWith("-agent");
176}
177
178/** `acme/web#12`, lowercase: how a pull request is matched. */
179export function pullKey(repo: RepoPath, number: number): string {
180 return `${repo.namespace}/${repo.name}#${number}`.toLowerCase();
181}
182
183export type CodeWork = {
184 pulls: CodePull[];
185 /** Whether every list read reached back to 7 days before the span. */
186 complete: boolean;
187};
188
189// --- People in the span -----------------------------------------------------------
190
191/**
192 * Who an actor is. Actors are member keys, as the events and chat services
193 * return them: `user:<id>` for an account, `agent:<id>` for an agent of
194 * older rows, `""` for nobody (a push an import made). g1t itself and
195 * older agents are not people; everyone else is. `agents` names more keys
196 * that are agents' (accounts of kind `agent`), when known.
197 */
198export type ActorKind = "person" | "agent";
199
200/** g1t's own account, as events name it (identity's `AGENT_ID`). */
201export const G1T_ACTOR = "user:usr_g1t_agent";
202
203export function actorKind(key: string, agents?: ReadonlySet<string>): ActorKind {
204 return key.startsWith("agent:") || key === G1T_ACTOR || isRobotKey(key) || agents?.has(key) ? "agent" : "person";
205}
206
207/**
208 * A member key that names a robot under `user:`: an agent of older rows by
209 * its own id, a workspace (its own token, or g1t's upkeep as it), or `g1t`.
210 * Events name a workspace this way (services/events digest).
211 */
212export function isRobotKey(key: string): boolean {
213 return key.startsWith("user:agt_") || key.startsWith("user:wsp_") || key === "user:g1t";
214}
215
216/** Whether a username is g1t's own: g1t, or an agent account of older rows. */
217export function isAgentName(name: string | null | undefined): boolean {
218 return name === "g1t" || (name != null && name.endsWith("-agent"));
219}
220
221/** A repository as the digest's links and lines need it. */
222export type RepoRef = RepoPath & { defaultBranch: string };
223
224/** Someone who did something in the span: for the faces beside the card. */
225export type DigestActor = {
226 key: string;
227 /** Their username; `someone` when it could not be read. */
228 name: string;
229 /** How many things they did, over every line: the order of the faces. */
230 count: number;
231};
232
233/** One line: what was done, with its count, and where that is listed. */
234export type DigestLine = {
235 key: string;
236 text: string;
237 to: string | null;
238};
239
240export type DigestColumn = {
241 lines: DigestLine[];
242 /** Most active first. */
243 actors: DigestActor[];
244};
245
246/** What the sentence under the heading needs. */
247export type DigestSummary = {
248 /** Distinct people who did anything. */
249 people: number;
250 /** Commits people pushed. */
251 commits: number;
252 /** Pull requests people merged. */
253 merged: number;
254 /** Messages people sent. */
255 said: number;
256 /** Whether anything at all was counted. */
257 anything: boolean;
258 /** Whether what people did could be read at all (events and chat both silent: no). */
259 peopleRead: boolean;
260};
261
262export type Digest = {
263 people: DigestColumn;
264 summary: DigestSummary;
265 /** Sources that did not answer, by name, for the card to say so: Code, Chat. */
266 missing: string[];
267 /** True when a source was cut short, so some counts are low. */
268 partial: boolean;
269};
270
271export type DigestInput = {
272 slug: string;
273 /** The workspace's repositories by id: for links, and to count projects. */
274 repos: Record<string, RepoRef>;
275 /** Events' digest; null when events did not answer. Without Code access it has no repositories. */
276 activity: ActivityDigest | null;
277 /** Chat's; null when chat did not answer. */
278 chat: ChatActivity | null;
279 /** Names for member keys: a username. */
280 names: Record<string, string>;
281 /** Keys of accounts that are not people, beyond g1t. */
282 agentKeys?: ReadonlySet<string>;
283 code: boolean;
284};
285
286const people = (n: number) => plural(n, "person", "people");
287
288/** `a, b and c`. */
289export const listOf = (names: string[]) => (names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`);
290
291/** What people did, from a tally: how many, and by whom (non-empty keys). */
292function part(counts: ActorCount[], agents?: ReadonlySet<string>): { count: number; actors: Map<string, number> } {
293 const actors = new Map<string, number>();
294 let count = 0;
295 for (const entry of counts) {
296 if (actorKind(entry.actor, agents) !== "person") continue;
297 count += entry.count;
298 if (entry.actor) actors.set(entry.actor, (actors.get(entry.actor) ?? 0) + entry.count);
299 }
300 return { count, actors };
301}
302
303/** Where a line points: the one project's page, or the workspace's projects when several. */
304function placeFor(slug: string, repos: Record<string, RepoRef>, repoIds: Iterable<string>, page: string): string {
305 const ids = [...new Set(repoIds)];
306 const only = ids.length === 1 ? repos[ids[0]!] : null;
307 return only ? `/${only.namespace}/${only.name}/${page}` : `/${slug}/-/repositories`;
308}
309
310/**
311 * What people did in the span, as lines with counts and links, and who
312 * did it. Pure: everything comes from the services' counts and the names
313 * looked up for them.
314 */
315export function digestColumn(input: DigestInput): DigestColumn {
316 const { slug, repos, activity, chat, names, agentKeys } = input;
317 const lines: DigestLine[] = [];
318 const did = new Map<string, number>();
319 const credit = (actors: Map<string, number>) => {
320 for (const [key, n] of actors) did.set(key, (did.get(key) ?? 0) + n);
321 };
322
323 if (activity) {
324 // Pushes: commits, projects, and who.
325 const pushers = new Map<string, number>();
326 const pushed = new Set<string>();
327 let commits = 0;
328 let pushes = 0;
329 for (const repo of activity.repos) {
330 let any = false;
331 for (const by of repo.pushes.by) {
332 if (actorKind(by.actor, agentKeys) !== "person") continue;
333 any = true;
334 commits += by.commits;
335 pushes += by.count;
336 if (by.actor) pushers.set(by.actor, (pushers.get(by.actor) ?? 0) + by.count);
337 }
338 if (any) pushed.add(repo.repo_id);
339 }
340 if (pushes > 0) {
341 const where = `to ${plural(pushed.size, "project")}`;
342 const text = pushers.size > 0 ? `${people(pushers.size)} pushed ${plural(commits, "commit")} ${where}` : `${plural(commits, "commit")} pushed ${where}`;
343 lines.push({ key: "pushes", text, to: placeFor(slug, repos, pushed, "activity") });
344 credit(pushers);
345 }
346
347 // Pull requests, reviews, issues, comments, deploys, releases, packages: summed over projects.
348 const sum = (pick: (repo: RepoDigest) => ActorCount[]) => {
349 const total = { count: 0, actors: new Map<string, number>(), repoIds: [] as string[] };
350 for (const repo of activity.repos) {
351 const { count, actors } = part(pick(repo), agentKeys);
352 if (count === 0) continue;
353 total.count += count;
354 total.repoIds.push(repo.repo_id);
355 for (const [key, n] of actors) total.actors.set(key, (total.actors.get(key) ?? 0) + n);
356 }
357 return total;
358 };
359 const opened = sum((repo) => repo.pulls.opened);
360 const merged = sum((repo) => repo.pulls.merged);
361 const closed = sum((repo) => repo.pulls.closed);
362 if (opened.count + merged.count + closed.count > 0) {
363 const parts: string[] = [];
364 if (opened.count > 0) parts.push(`opened ${plural(opened.count, "pull request")}`);
365 if (merged.count > 0) parts.push(`merged ${opened.count > 0 ? merged.count.toLocaleString("en-US") : plural(merged.count, "pull request")}`);
366 if (closed.count > 0) parts.push(`closed ${closed.count.toLocaleString("en-US")} without merging`);
367 lines.push({ key: "pulls", text: parts.join(", "), to: placeFor(slug, repos, [...opened.repoIds, ...merged.repoIds, ...closed.repoIds], "pulls") });
368 credit(opened.actors);
369 credit(merged.actors);
370 credit(closed.actors);
371 }
372 const reviews = sum((repo) => repo.reviews);
373 if (reviews.count > 0) {
374 lines.push({ key: "reviews", text: `reviewed ${plural(reviews.count, "pull request")}`, to: placeFor(slug, repos, reviews.repoIds, "pulls") });
375 credit(reviews.actors);
376 }
377 const issuesOpened = sum((repo) => repo.issues.opened);
378 const issuesClosed = sum((repo) => repo.issues.closed);
379 if (issuesOpened.count + issuesClosed.count > 0) {
380 const parts: string[] = [];
381 if (issuesOpened.count > 0) parts.push(`opened ${plural(issuesOpened.count, "issue")}`);
382 if (issuesClosed.count > 0) parts.push(`closed ${issuesOpened.count > 0 ? issuesClosed.count.toLocaleString("en-US") : plural(issuesClosed.count, "issue")}`);
383 lines.push({ key: "issues", text: parts.join(", "), to: placeFor(slug, repos, [...issuesOpened.repoIds, ...issuesClosed.repoIds], "issues") });
384 credit(issuesOpened.actors);
385 credit(issuesClosed.actors);
386 }
387 const comments = sum((repo) => repo.comments);
388 if (comments.count > 0) {
389 lines.push({ key: "comments", text: `left ${plural(comments.count, "comment")}`, to: placeFor(slug, repos, comments.repoIds, "issues") });
390 credit(comments.actors);
391 }
392 const succeeded = sum((repo) => repo.deployments.succeeded);
393 const failed = sum((repo) => repo.deployments.failed);
394 if (succeeded.count + failed.count > 0) {
395 const text = succeeded.count > 0 ? `${plural(succeeded.count, "deploy")} went out${failed.count > 0 ? `, ${failed.count.toLocaleString("en-US")} failed` : ""}` : `${plural(failed.count, "deploy")} failed`;
396 lines.push({ key: "deploys", text, to: placeFor(slug, repos, [...succeeded.repoIds, ...failed.repoIds], "deployments") });
397 credit(succeeded.actors);
398 credit(failed.actors);
399 }
400 const releases = sum((repo) => tallyOf(repo.releases.map((release) => release.actor)));
401 if (releases.count > 0) {
402 lines.push({ key: "releases", text: `published ${plural(releases.count, "release")}`, to: placeFor(slug, repos, releases.repoIds, "releases") });
403 credit(releases.actors);
404 }
405 const packages = sum((repo) => tallyOf(repo.packages.map((pkg) => pkg.actor)));
406 if (packages.count > 0) {
407 lines.push({ key: "packages", text: `published ${plural(packages.count, "package version")}`, to: `/${slug}/-/packages` });
408 credit(packages.actors);
409 }
410
411 // Artifacts: made, and whose content changed.
412 if (activity.folios) {
413 const made = part(activity.folios.created, agentKeys);
414 const edited = new Set<string>();
415 const editors = new Map<string, number>();
416 let allDocs = true;
417 for (const folio of activity.folios.edited) {
418 const mine = folio.authors.filter((author) => actorKind(author, agentKeys) === "person");
419 if (mine.length === 0) continue;
420 edited.add(folio.folio_id);
421 if (folio.kind !== "doc") allDocs = false;
422 for (const author of mine) editors.set(author, (editors.get(author) ?? 0) + 1);
423 }
424 const what = (n: number) => plural(n, allDocs ? "doc" : "artifact");
425 if (made.count + edited.size > 0) {
426 const parts: string[] = [];
427 if (made.count > 0) parts.push(`created ${what(made.count)}`);
428 if (edited.size > 0) parts.push(`edited ${what(edited.size)}`);
429 lines.push({ key: "docs", text: parts.join(", "), to: `/${slug}/-/artifacts` });
430 credit(made.actors);
431 credit(editors);
432 }
433 }
434 }
435
436 // Chat: what people said.
437 if (chat) {
438 const said = part(
439 chat.authors.map((author) => ({ actor: author.key, count: author.messages })),
440 agentKeys,
441 );
442 if (said.count > 0) {
443 lines.push({ key: "chat", text: `sent ${plural(said.count, "message")} in ${plural(chat.channels, "conversation")}`, to: `/${slug}/-/chat` });
444 credit(said.actors);
445 }
446 }
447
448 const actors: DigestActor[] = [...did]
449 .map(([key, count]) => ({ key, name: names[key] ?? "someone", count }))
450 .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
451 return { lines, actors };
452}
453
454/** A tally with one of each actor, for lists that name an actor per item. */
455function tallyOf(actors: string[]): ActorCount[] {
456 const counts = new Map<string, number>();
457 for (const actor of actors) counts.set(actor, (counts.get(actor) ?? 0) + 1);
458 return [...counts].map(([actor, count]) => ({ actor, count }));
459}
460
461/** What people did, what the sentence needs, and which sources were silent. */
462export function digestOf(input: DigestInput): Digest {
463 const column = digestColumn(input);
464 const missing: string[] = [];
465 if (input.code && !input.activity) missing.push("Code");
466 if (!input.chat) missing.push("Chat");
467 let commits = 0;
468 let merged = 0;
469 for (const repo of input.activity?.repos ?? []) {
470 for (const by of repo.pushes.by) if (actorKind(by.actor, input.agentKeys) === "person") commits += by.commits;
471 merged += part(repo.pulls.merged, input.agentKeys).count;
472 }
473 const said = part(
474 (input.chat?.authors ?? []).map((author) => ({ actor: author.key, count: author.messages })),
475 input.agentKeys,
476 ).count;
477 return {
478 people: column,
479 summary: {
480 people: column.actors.length,
481 commits,
482 merged,
483 said,
484 anything: column.lines.length > 0,
485 peopleRead: input.activity != null || input.chat != null,
486 },
487 missing,
488 partial: input.activity != null && !input.activity.complete,
489 };
490}
491
492// --- What landed in the span -----------------------------------------------------
493
494/**
495 * A change that landed: a pull request merged; commits pushed straight to
496 * a default branch; a production build that went live; a release or a
497 * package version published.
498 */
499export type LandedChange = {
500 key: string;
501 kind: "merge" | "push" | "deploy" | "release" | "package";
502 title: string;
503 /** One line under it: where, and by whom. */
504 detail: string;
505 to: string;
506 at: number;
507};
508
509/** Every pull request that merged in the span, newest first. */
510export function landedIn(pulls: CodePull[], span: Pick<Span, "from" | "now">): LandedChange[] {
511 return pulls
512 .filter((pull) => pull.status === "merged" && within(pull.mergedAt, span))
513 .map((pull) => {
514 const agent = isAgentPull(pull);
515 const mergedBy = pull.mergedBy && pull.mergedBy !== pull.author.username ? `, merged by ${pull.mergedBy}` : "";
516 return {
517 key: `landed:${pullKey(pull.repo, pull.number)}`,
518 kind: "merge" as const,
519 title: pull.title,
520 detail: `${pull.repo.name}#${pull.number} · by ${agent ? `@${pull.author.username}` : pull.author.username}${mergedBy}`,
521 to: `/${pull.repo.namespace}/${pull.repo.name}/pull/${pull.number}`,
522 at: Date.parse(pull.mergedAt!),
523 };
524 })
525 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
526}
527
528/** The names behind member keys, for a line: `ana and bo`, `@margo`, `an import` for nobody. */
529function namesOf(keys: string[], names: Record<string, string>, agentKeys?: ReadonlySet<string>): string {
530 const shown = keys.map((key) => {
531 if (!key) return "an import";
532 const name = names[key] ?? (key === G1T_ACTOR ? "g1t" : "someone");
533 return actorKind(key, agentKeys) === "agent" ? `@${name}` : name;
534 });
535 return listOf([...new Set(shown)]);
536}
537
538/**
539 * Commits pushed straight to a default branch, one row per project with
540 * any: what landed without a pull request. Releases and package versions
541 * published, one row each. Pushes within the span only: the digest was
542 * asked for the span.
543 */
544export function landedFromActivity(activity: ActivityDigest | null, repos: Record<string, RepoRef>, names: Record<string, string>, slug: string, agentKeys?: ReadonlySet<string>): LandedChange[] {
545 const rows: LandedChange[] = [];
546 for (const repo of activity?.repos ?? []) {
547 const path = repos[repo.repo_id];
548 if (!path) continue;
549 const direct = repo.pushes.default_branch;
550 if (direct.count > 0 && direct.last_at) {
551 const by = direct.by.map((entry) => entry.actor);
552 rows.push({
553 key: `push:${repo.repo_id}`,
554 kind: "push",
555 title: `${plural(direct.commits, "commit")} pushed to ${path.defaultBranch}`,
556 detail: `${path.name} · ${plural(direct.count, "push", "pushes")} by ${namesOf(by, names, agentKeys)}`,
557 to: `/${path.namespace}/${path.name}/activity`,
558 at: Date.parse(direct.last_at),
559 });
560 }
561 for (const release of repo.releases) {
562 rows.push({
563 key: `release:${repo.repo_id}:${release.tag}`,
564 kind: "release",
565 title: release.name ? `${release.tag} · ${release.name}` : release.tag,
566 detail: `${path.name} · released by ${namesOf([release.actor], names, agentKeys)}`,
567 to: `/${path.namespace}/${path.name}/releases/tag/${encodeURIComponent(release.tag)}`,
568 at: Date.parse(release.at),
569 });
570 }
571 for (const pkg of repo.packages) {
572 rows.push({
573 key: `package:${repo.repo_id}:${pkg.ecosystem}:${pkg.name}:${pkg.version}`,
574 kind: "package",
575 title: `${pkg.name} ${pkg.version}`,
576 detail: `${pkg.ecosystem} package · published by ${namesOf([pkg.actor], names, agentKeys)}`,
577 to: `/${slug}/-/packages`,
578 at: Date.parse(pkg.at),
579 });
580 }
581 }
582 return rows;
583}
584
585/** Production builds that went live in the span, as landed changes; previews stay in Deploys. */
586export function landedDeploys(deploys: DeployRow[]): LandedChange[] {
587 return deploys
588 .filter((row) => row.kind === "production" && row.outcome === "live")
589 .map((row) => ({
590 key: `landed:${row.key}`,
591 kind: "deploy" as const,
592 title: `Production of ${row.project} went live`,
593 detail: `${row.commit} · by ${row.by ?? "someone"}`,
594 to: row.to,
595 at: row.at,
596 }));
597}
598
599/** Everything that landed, newest first. */
600export function landed(parts: LandedChange[][]): LandedChange[] {
601 return parts.flat().sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
602}
603
604/** A deployment's maker as a member key: an id becomes `user:<id>`, a key stays as it is. */
605export function deployActorKey(createdBy: string | null | undefined): string | null {
606 const by = (createdBy ?? "").trim();
607 if (!by) return null;
608 return /^(user|agent):/.test(by) ? by : `user:${by}`;
609}
610
611/** A build that finished in the span. */
612export type DeployRow = {
613 key: string;
614 project: string;
615 kind: Deployment["kind"];
616 /** `live`: built and served (it may have been replaced since); `failed`: it did not build. */
617 outcome: "live" | "failed";
618 commit: string;
619 branch: string | null;
620 at: number;
621 to: string;
622 /** Who made it, as a name (`@g1t` for g1t itself); null when the deployment does not say. */
623 by: string | null;
624};
625
626/**
627 * Builds that finished in the span, newest first: production builds each,
628 * and previews too. A build that went live and was replaced since still
629 * went live. Skipped builds are left out.
630 */
631export function deploysIn(projects: { slug: string; deployments: Deployment[] }[], workspace: string, span: Pick<Span, "from" | "now">, names: Record<string, string> = {}, agentKeys?: ReadonlySet<string>): DeployRow[] {
632 const rows: DeployRow[] = [];
633 for (const project of projects) {
634 for (const deploy of project.deployments) {
635 // Who made it: the deployment names them by id, so it reads as a name, or as someone when identity doesn't know it.
636 const key = deployActorKey(deploy.createdBy);
637 const ended = deploy.finishedAt ?? null;
638 if (!within(ended, span)) continue;
639 const outcome = deploy.status === "failed" ? "failed" : deploy.status === "ready" || deploy.status === "replaced" || deploy.status === "down" ? "live" : null;
640 if (!outcome) continue;
641 rows.push({
642 key: `deploy:${project.slug}:${deploy.id}`,
643 project: project.slug,
644 kind: deploy.kind,
645 outcome,
646 commit: deploy.commit.slice(0, 7),
647 branch: deploy.branch,
648 at: Date.parse(ended!),
649 to: `/${workspace}/${project.slug}/deployments/${deploy.id}`,
650 by: key ? namesOf([key], names, agentKeys) : null,
651 });
652 }
653 }
654 return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
655}
656
657// --- Running now ----------------------------------------------------------------
658
659/** Something going right now: a workflow run or a build. */
660export type RunningRow = {
661 key: string;
662 kind: "workflow" | "deploy";
663 title: string;
664 /** One line: who and where. */
665 detail: string;
666 /** "Running", "Queued", "Building". */
667 status: string;
668 /** Epoch ms: when it started. */
669 at: number;
670 to: string;
671};
672
673/** Builds queued or going now, one per project (its newest). */
674export function runningDeploys(overview: ProjectDeploys[], slug: string): RunningRow[] {
675 return overview.flatMap((project) => {
676 const latest = project.latest;
677 if (!latest || (latest.status !== "queued" && latest.status !== "building")) return [];
678 return [
679 {
680 key: `deploy:${project.slug}:${latest.id}`,
681 kind: "deploy" as const,
682 title: `${latest.kind === "production" ? "Production" : `Preview of ${latest.branch ?? "a branch"}`} of ${project.slug}`,
683 detail: `${latest.commit.slice(0, 7)} · by ${latest.createdBy}`,
684 status: latest.status === "queued" ? "Queued" : "Building",
685 at: Date.parse(latest.createdAt),
686 to: `/${slug}/${project.slug}/deployments/${latest.id}`,
687 },
688 ];
689 });
690}
691
692const RUN_STATUS: Partial<Record<WorkflowRun["status"], string>> = {
693 pending: "Queued",
694 queued: "Queued",
695 action_required: "Needs approval",
696 in_progress: "Running",
697 waiting: "Waiting",
698};
699
700/** Workflow runs not finished, in the projects read: queued, waiting, running, or waiting for approval. */
701export function runningWorkflows(projects: { repo: RepoPath; runs: WorkflowRun[] }[]): RunningRow[] {
702 return projects.flatMap(({ repo, runs }) =>
703 runs.flatMap((run) => {
704 const status = RUN_STATUS[run.status];
705 if (!status) return [];
706 return [
707 {
708 key: `workflow:${repo.namespace}/${repo.name}:${run.id}`.toLowerCase(),
709 kind: "workflow" as const,
710 title: run.title ? `${run.name}: ${run.title}` : run.name,
711 detail: `${repo.namespace}/${repo.name} ${run.ref.replace(/^refs\/heads\//, "")}${run.actor ? ` · by ${run.actor}` : ""}`,
712 status,
713 at: Date.parse(run.startedAt ?? run.createdAt),
714 to: `/${repo.namespace}/${repo.name}/actions/runs/${run.id}`,
715 },
716 ];
717 }),
718 );
719}
720
721/** Everything running, longest-going first within each kind: workflow runs, then builds. */
722export function running(parts: RunningRow[][]): RunningRow[] {
723 const order = { workflow: 0, deploy: 1 } as const;
724 return parts.flat().sort((a, b) => order[a.kind] - order[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
725}
726
727// --- Needs you ------------------------------------------------------------------
728
729/**
730 * What a row is. Tiers, most pressing first:
731 * 0. production is down to an older build (`deploy`);
732 * 1. a change that can't land until someone acts on it (`pull_blocked`);
733 * 2. something waiting only for you (a review, an invitation, your pull
734 * request that is ready to merge);
735 * 3. a job waiting for a runner that is not there;
736 * 4. an unread notification that is a warning or a failure;
737 * 5. a mention or a direct message.
738 */
739export type AttentionKind = "deploy" | "pull_blocked" | "review" | "invitation" | "ready" | "runner" | "notification" | "chat";
740
741export const TIER: Record<AttentionKind, number> = {
742 deploy: 0,
743 pull_blocked: 1,
744 review: 2,
745 invitation: 2,
746 ready: 2,
747 runner: 3,
748 notification: 4,
749 chat: 5,
750};
751
752export type Stake = { text: string; tone: "danger" | "warn" | "accent" | null };
753
754/** One row of Needs you. */
755export type AttentionRow = {
756 key: string;
757 kind: AttentionKind;
758 title: string;
759 /** One line: what it is and where. */
760 detail: string;
761 /** What is at stake, in a few words. */
762 stake: Stake | null;
763 /** The action, right there. */
764 action: { label: string; to: string };
765 /** Who is on it: the person who asked, or g1t on older rows. */
766 owner: { name: string; agent: boolean } | null;
767 /** Epoch ms: when it started waiting. */
768 at: number;
769 /** Where it came from, for a member without Code access never `code`. */
770 from: "code" | "notifications" | "chat";
771};
772
773/**
774 * Most pressing first: by tier, then what has waited longest, then by key
775 * so the order never depends on the order rows were read. One of each key,
776 * and one of each place: a notification about a pull request already on
777 * the list is left out.
778 */
779export function rankAttention(rows: AttentionRow[]): AttentionRow[] {
780 const sorted = [...rows].sort((a, b) => TIER[a.kind] - TIER[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
781 const keys = new Set<string>();
782 const places = new Set<string>();
783 return sorted.filter((row) => {
784 const place = row.action.to.split(/[?#]/)[0];
785 if (keys.has(row.key) || (row.kind === "notification" && places.has(place))) return false;
786 keys.add(row.key);
787 places.add(place);
788 return true;
789 });
790}
791
792/** Start here: the first row by `rankAttention`, with why it was picked. */
793export function startHere(ranked: AttentionRow[]): { row: AttentionRow; why: string } | null {
794 const row = ranked[0];
795 if (!row) return null;
796 const sameTier = ranked.filter((other) => TIER[other.kind] === TIER[row.kind]).length;
797 const tail = sameTier > 1 ? ` Of the ${sameTier} like it, it has waited longest.` : "";
798 return { row, why: `${WHY[row.kind]}${tail}` };
799}
800
801const WHY: Record<AttentionKind, string> = {
802 deploy: "Production is serving an older build until this is fixed, so it comes before anything else.",
803 pull_blocked: "This change can't land until someone fixes it.",
804 review: "You were asked by name, so it waits for your verdict.",
805 invitation: "It is addressed to you; no one else can answer it.",
806 ready: "Everything it needs is met; it lands when you merge it.",
807 runner: "A job is waiting for a runner that is not there.",
808 notification: "It is the most pressing unread notification.",
809 chat: "Nothing else is waiting, and this is the oldest message for you.",
810};
811
812// --- Rows from each source ----------------------------------------------------
813
814/** A Code Overview need row, as Home reads it (lib/mission-control.ts `NeedRow`). */
815export type CodeNeed = {
816 key: string;
817 reason: string;
818 repo: RepoPath | null;
819 ref: string | null;
820 title: string;
821 ask: string;
822 by: { name: string; agent: boolean } | null;
823 at: number;
824 to: string;
825 facts: { label: string; value: string; tone: string | null }[];
826};
827
828const fact = (need: CodeNeed, label: string) => need.facts.find((f) => f.label === label)?.value ?? null;
829
830const REASON_STAKE: Record<string, Stake> = {
831 blocking: { text: "Blocking", tone: "danger" },
832 checks_failing: { text: "Checks failing", tone: "danger" },
833 needs_review: { text: "Needs a verdict", tone: "warn" },
834 stalled: { text: "Stalled", tone: "warn" },
835};
836
837/** A Code need (failed deploy, pull request, review, invitation, runner) as a row. */
838export function codeRow(need: CodeNeed): AttentionRow {
839 const prefix = need.key.split(":")[0];
840 const where = need.repo ? `${need.repo.namespace}/${need.repo.name}${need.ref ? ` ${need.ref}` : ""}` : null;
841 const detail = where ? `${where} · ${need.ask}` : need.ask;
842 const owner = need.by;
843 const base = { key: need.key, title: need.title, detail, owner, at: need.at, from: "code" as const };
844 switch (prefix) {
845 case "deploy":
846 return {
847 ...base,
848 kind: "deploy",
849 stake: { text: fact(need, "Production") === "Not live yet" ? "Not live yet" : "Production on an older build", tone: "danger" },
850 action: { label: "See the build", to: need.to },
851 };
852 case "invitation":
853 return { ...base, kind: "invitation", stake: { text: `${fact(need, "Role") ?? "A"} role`, tone: null }, action: { label: "Respond", to: need.to } };
854 case "review": {
855 const lines = fact(need, "Lines");
856 return { ...base, kind: "review", stake: { text: lines ?? "Your review", tone: null }, action: { label: "Review", to: need.to } };
857 }
858 case "runner":
859 return { ...base, kind: "runner", stake: { text: `Waiting ${fact(need, "Waiting") ?? ""}`.trim(), tone: "warn" }, action: { label: "Look", to: need.to } };
860 // Your pull request, which meets everything its branch asks for.
861 case "ready":
862 return { ...base, kind: "ready", stake: { text: "Ready to merge", tone: null }, action: { label: "Merge", to: need.to } };
863 default:
864 return {
865 ...base,
866 kind: "pull_blocked",
867 stake: REASON_STAKE[need.reason] ?? { text: "Waiting on you", tone: "warn" },
868 action: { label: need.reason === "needs_review" ? "Review" : "Look", to: need.to },
869 };
870 }
871}
872
873const NOTIFICATION_STAKE: Record<string, string> = {
874 review_requested: "Review requested",
875 assign: "Assigned to you",
876 mention: "Mentioned",
877 team_mention: "Team mentioned",
878 ci_activity: "CI activity",
879 security_alert: "Security alert",
880 state_change: "State changed",
881 author: "Your work",
882 comment: "Comment",
883 manual: "Subscribed",
884 subscribed: "Watching",
885};
886
887/**
888 * An unread notification that is a warning (someone or something is
889 * waiting) or a failure, in this workspace. A member without Code access
890 * gets none about a repository. A reason this page does not know (older
891 * ones included) reads as a plain notification.
892 */
893export function notificationRow(item: InboxItem, slug: string, code: boolean): AttentionRow | null {
894 if (item.readAt != null || item.doneAt != null) return null;
895 if (item.severity !== "warning" && item.severity !== "error") return null;
896 const inWorkspace = (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug;
897 if (!inWorkspace) return null;
898 if (!code && item.repo) return null;
899 return {
900 key: `notification:${item.id}`,
901 kind: "notification",
902 title: item.body || item.title,
903 detail: item.body ? item.title : (item.repo ?? "A notification"),
904 stake: { text: NOTIFICATION_STAKE[item.reason] ?? "Notification", tone: item.severity === "error" ? "danger" : "warn" },
905 action: { label: "Open", to: item.url },
906 owner: item.actor ? { name: item.actor, agent: isAgentName(item.actor) } : null,
907 at: Date.parse(item.updatedAt),
908 from: "notifications",
909 };
910}
911
912export type ChatEntryLike = {
913 channel: { id: string; kind: "channel" | "dm"; name: string | null; last_message_at?: string | null };
914 title: string;
915 muted: boolean;
916 unread: number;
917 mentions: number;
918};
919
920/** A conversation with a mention of you, or a direct message you haven't read. */
921export function chatRow(entry: ChatEntryLike, slug: string): AttentionRow | null {
922 if (entry.muted) return null;
923 if (!(entry.mentions > 0 || (entry.channel.kind === "dm" && entry.unread > 0))) return null;
924 const to = entry.channel.kind === "dm" || !entry.channel.name ? `/${slug}/-/chat/dm/${entry.channel.id}` : `/${slug}/-/chat/${entry.channel.name}`;
925 const dm = entry.channel.kind === "dm";
926 return {
927 key: `chat:${entry.channel.id}`,
928 kind: "chat",
929 title: dm ? entry.title : `#${entry.title}`,
930 detail: dm ? "A direct message you haven't read." : "You were mentioned.",
931 stake: {
932 text: entry.mentions > 0 ? `${entry.mentions} ${entry.mentions === 1 ? "mention" : "mentions"}` : `${entry.unread} unread`,
933 tone: entry.mentions > 0 ? "accent" : null,
934 },
935 action: { label: "Reply", to },
936 owner: null,
937 at: entry.channel.last_message_at ? Date.parse(entry.channel.last_message_at) : 0,
938 from: "chat",
939 };
940}
941
942/** What Needs you and Start here show, and which sources did not answer. */
943export type Attention = {
944 rows: AttentionRow[];
945 start: { row: AttentionRow; why: string } | null;
946 /** Sources that did not answer, by name, for the card to say so. */
947 missing: string[];
948};
949
950export function attention(input: {
951 slug: string;
952 code: boolean;
953 codeNeeds: CodeNeed[] | null;
954 notifications: InboxItem[] | null;
955 chat: ChatEntryLike[] | null;
956}): Attention {
957 const rows: AttentionRow[] = [];
958 const missing: string[] = [];
959 if (input.code) {
960 if (input.codeNeeds) rows.push(...input.codeNeeds.map(codeRow));
961 else missing.push("Code");
962 }
963 if (input.notifications) {
964 for (const item of input.notifications) {
965 const row = notificationRow(item, input.slug, input.code);
966 if (row) rows.push(row);
967 }
968 } else missing.push("Notifications");
969 if (input.chat) {
970 for (const entry of input.chat) {
971 const row = chatRow(entry, input.slug);
972 if (row) rows.push(row);
973 }
974 } else missing.push("Chat");
975 const ranked = rankAttention(rows);
976 return { rows: ranked, start: startHere(ranked), missing };
977}
978
979// --- Spend in the span ----------------------------------------------------------
980
981/** Money in, which the statement lists but which is not spend. */
982const MONEY_IN: ReadonlySet<string> = new Set(["Payments", "AI credit", "Credits from g1t", "Refunds", "Tax", "Card processing fees"]);
983
984export type Spend = {
985 /** The statement days counted, `YYYY-MM-DD` in UTC, first and last. */
986 from: string;
987 to: string;
988 /** Usage at price over those days, in micros. */
989 totalMicros: number;
990 /** A line per kind of charge, as the statement names it, most first. */
991 lines: { kind: string; micros: number; count: number }[];
992 /** Usage at price this month so far, the top bar's and Usage's figure; null when it could not be read. */
993 monthMicros: number | null;
994};
995
996/** The UTC months (`YYYY-MM`) the span touches, oldest first: the statements Home reads. */
997export function spanMonths(span: Pick<Span, "from" | "now">): string[] {
998 const months: string[] = [];
999 const first = new Date(span.from);
1000 let year = first.getUTCFullYear();
1001 let month = first.getUTCMonth();
1002 const last = new Date(span.now).toISOString().slice(0, 7);
1003 for (let i = 0; i < 3; i++) {
1004 const key = `${year}-${String(month + 1).padStart(2, "0")}`;
1005 months.push(key);
1006 if (key >= last) break;
1007 month++;
1008 if (month === 12) {
1009 month = 0;
1010 year++;
1011 }
1012 }
1013 return months;
1014}
1015
1016/**
1017 * The span's spend from the statements grouped by day: each usage line at
1018 * its price (what was charged, plus what the plan, a trial, a pool or a
1019 * discount paid of it), leaving out money in. The statement keeps whole
1020 * UTC days, so the span is counted from the start of the UTC day it began.
1021 * `statements` is the months of `spanMonths`, the current one last.
1022 * `monthMicros` is this month so far as billing's usage report counts it,
1023 * the month's usage not yet closed included: the figure Usage
1024 * shows, so Home shows no other.
1025 */
1026export function spendIn(statements: Pick<Statement, "groups" | "totals">[], span: Pick<Span, "from" | "now">, monthMicros: number | null): Spend {
1027 const from = new Date(span.from).toISOString().slice(0, 10);
1028 const to = new Date(span.now).toISOString().slice(0, 10);
1029 const byKind = new Map<string, { micros: number; count: number }>();
1030 for (const statement of statements) {
1031 for (const group of statement.groups) {
1032 if (group.key < from || group.key > to) continue;
1033 for (const line of group.lines) {
1034 if (MONEY_IN.has(line.kind)) continue;
1035 const micros = line.priceMicros ?? line.chargedMicros;
1036 const kept = byKind.get(line.kind) ?? { micros: 0, count: 0 };
1037 byKind.set(line.kind, { micros: kept.micros + micros, count: kept.count + line.count });
1038 }
1039 }
1040 }
1041 const lines = [...byKind]
1042 .map(([kind, value]) => ({ kind, ...value }))
1043 .filter((line) => line.micros > 0)
1044 .sort((a, b) => b.micros - a.micros || a.kind.localeCompare(b.kind));
1045 return {
1046 from,
1047 to,
1048 totalMicros: lines.reduce((sum, line) => sum + line.micros, 0),
1049 lines,
1050 monthMicros,
1051 };
1052}
1053
1054// --- The sentence -----------------------------------------------------------
1055
1056/**
1057 * The sentence under the heading, honest about what happened: "Since
1058 * Tuesday evening, 3 people pushed 41 commits and merged 5 changes, and
1059 * 12 changes landed." What people did comes first (commits and merges;
1060 * else what they said), then everything that landed. When nothing at all
1061 * was counted: "Quiet since Tuesday evening: nothing pushed, merged,
1062 * deployed or said." When what people did could not be read, it says so.
1063 */
1064export function spanSentence(span: Pick<Span, "words">, digest: Pick<Digest, "summary"> | null, landed: number | null): string {
1065 const lead = span.words;
1066 if (!digest) return `${lead}, what happened couldn't be read.`;
1067 const { people: count, commits, merged, said, anything, peopleRead } = digest.summary;
1068 const landedCount = landed ?? 0;
1069 if (!anything && landedCount === 0) {
1070 if (!peopleRead) return `${lead}, what people did couldn't be read.`;
1071 return `Quiet ${lead.charAt(0).toLowerCase()}${lead.slice(1)}: nothing pushed, merged, deployed or said.`;
1072 }
1073 const parts: string[] = [];
1074 if (count > 0) {
1075 if (commits > 0 || merged > 0) {
1076 const did: string[] = [];
1077 if (commits > 0) did.push(`pushed ${plural(commits, "commit")}`);
1078 if (merged > 0) did.push(`merged ${plural(merged, "change")}`);
1079 parts.push(`${people(count)} ${did.join(" and ")}`);
1080 } else if (said > 0) parts.push(`${people(count)} sent ${plural(said, "message")}`);
1081 else parts.push(`${people(count)} ${count === 1 ? "was" : "were"} active`);
1082 }
1083 if (landedCount > 0) parts.push(`${plural(landedCount, "change")} landed`);
1084 const tail = peopleRead ? "" : "; what people did couldn't be read";
1085 if (parts.length === 0) return `${lead}, work went on, but nothing landed${tail}.`;
1086 const joined = parts.length > 2 ? `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}` : parts.join(" and ");
1087 return `${lead}, ${joined}${tail}.`;
1088}
1089
1090/** "8 things need you.", or that nothing does. */
1091export function waitingSentence(total: number): string {
1092 if (total === 0) return "Nothing needs you right now.";
1093 return `${plural(total, "thing")} ${total === 1 ? "needs" : "need"} you.`;
1094}
1095
1096/** How long something has waited: "45 min", "17 h", "2 d". */
1097export function waited(at: number, now: number): string {
1098 const minutes = Math.max(0, Math.floor((now - at) / MINUTE));
1099 if (minutes < 60) return `${minutes} min`;
1100 if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h`;
1101 return `${Math.floor(minutes / (24 * 60))} d`;
1102}
1103
1104/** "3:40 PM" when it is the same day as `now`, else "Oct 7". */
1105export function whenShort(at: number, now: number, timeZone: string | null): string {
1106 if (dayIn(at, timeZone) === dayIn(now, timeZone)) return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1107 return now - at < 6 * DAY ? formatIn(at, timeZone, { weekday: "short", hour: "numeric" }) : shortDate(at, timeZone);
1108}