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,494 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 Commit,
15 Deployment,
16 Harness,
17 InboxItem,
18 ProjectDeploys,
19 Pull,
20 PullSessions,
21 RepoDigest,
22 RepoPath,
23 ShipState,
24 ShippedRepo,
25 Statement,
26 WorkflowRun,
27} from "@g1t/contracts";
28
29import { HARNESS_NAMES } from "./coordination.ts";
30import { type PushRecord, pushedByPerson, pushedCommits } from "./mission-control.ts";
31import { settledLine } from "./inbox.ts";
32import { sessionPath } from "./work-items.ts";
33
34const MINUTE = 60_000;
35const HOUR = 60 * MINUTE;
36const DAY = 24 * HOUR;
37
38/** A day's date in a time zone, as `YYYY-MM-DD`; UTC when the zone is unknown or invalid. */
39export function dayIn(at: number, timeZone: string | null): string {
40 try {
41 return new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: timeZone || "UTC" }).format(at);
42 } catch {
43 return new Date(at).toISOString().slice(0, 10);
44 }
45}
46
47/** The hour of the day (0–23) in a time zone; UTC when it is unknown. */
48export function hourIn(at: number, timeZone: string | null): number {
49 const read = (zone: string) => Number(new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: zone }).format(at)) % 24;
50 try {
51 return read(timeZone || "UTC");
52 } catch {
53 return read("UTC");
54 }
55}
56
57function formatIn(at: number, timeZone: string | null, options: Intl.DateTimeFormatOptions): string {
58 try {
59 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timeZone || "UTC" }).format(at);
60 } catch {
61 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format(at);
62 }
63}
64
65/** "Oct 9", in the reader's time zone. */
66export function shortDate(at: number, timeZone: string | null): string {
67 return formatIn(at, timeZone, { month: "short", day: "numeric" });
68}
69
70// --- The span -----------------------------------------------------------------
71
72/** Which span "what happened" covers: since your last visit, or a fixed one. */
73export type WindowKey = "last" | "24h" | "7d";
74
75export const WINDOWS: { key: WindowKey; label: string }[] = [
76 { key: "last", label: "Since last visit" },
77 { key: "24h", label: "Last 24 hours" },
78 { key: "7d", label: "Last 7 days" },
79];
80
81/** The furthest back "since your last visit" looks. */
82export const MAX_AWAY_DAYS = 14;
83
84/** A `?window=` value, or the default: since your last visit. */
85export function parseWindow(value: string | null | undefined): WindowKey {
86 return value === "24h" || value === "7d" ? value : "last";
87}
88
89export type Span = {
90 key: WindowKey;
91 /** Epoch ms: the start of the span. */
92 from: number;
93 now: number;
94 /** "Since Tuesday evening", "In the last 24 hours". */
95 words: string;
96 /** How long it covers: "3 days", "45 minutes". */
97 length: string;
98 /**
99 * Why "since your last visit" covers something else: `first` when there
100 * is no visit on record (it shows the last 24 hours), `capped` when the
101 * last one was longer ago than MAX_AWAY_DAYS, `unknown` when it could
102 * not be read (it shows the last 24 hours).
103 */
104 note: "first" | "capped" | "unknown" | null;
105};
106
107export const plural = (n: number, one: string, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
108
109/** How long a stretch of time is, roughly: "a moment", "40 minutes", "3 hours", "3 days", "2 weeks". */
110export function duration(ms: number): string {
111 const minutes = Math.floor(Math.max(0, ms) / MINUTE);
112 if (minutes < 1) return "a moment";
113 if (minutes < 60) return plural(minutes, "minute");
114 const hours = Math.floor(minutes / 60);
115 if (hours < 24) return plural(hours, "hour");
116 const days = Math.floor(hours / 24);
117 if (days < 14) return plural(days, "day");
118 return plural(Math.floor(days / 7), "week");
119}
120
121type Part = "night" | "morning" | "afternoon" | "evening";
122
123/**
124 * When `from` was, in words, from `now`: "a moment ago", "40 minutes ago",
125 * "2 hours ago", "this morning", "last night", "yesterday evening",
126 * "Tuesday evening", "Oct 2". The small hours belong to the night before:
127 * 2 a.m. on Wednesday is Tuesday night.
128 */
129export function sinceWords(from: number, now: number, timeZone: string | null): string {
130 const ago = now - from;
131 if (ago < MINUTE) return "a moment ago";
132 if (ago < HOUR) return `${plural(Math.floor(ago / MINUTE), "minute")} ago`;
133 if (ago < 3 * HOUR) return Math.floor(ago / HOUR) === 1 ? "an hour ago" : `${Math.floor(ago / HOUR)} hours ago`;
134 const hour = hourIn(from, timeZone);
135 const part: Part = hour < 5 ? "night" : hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
136 // The night is the evening's day's.
137 const day = dayIn(part === "night" ? from - 6 * HOUR : from, timeZone);
138 const today = dayIn(now, timeZone);
139 const yesterday = dayIn(now - DAY, timeZone);
140 const twoDaysAgo = dayIn(now - 2 * DAY, timeZone);
141 if (day === today) return `this ${part === "night" ? "evening" : part}`;
142 if (day === yesterday) return part === "night" ? "last night" : `yesterday ${part}`;
143 if (part === "night" && day === twoDaysAgo) return "the night before last";
144 if (ago < 6 * DAY) return `${formatIn(part === "night" ? from - 6 * HOUR : from, timeZone, { weekday: "long" })} ${part}`;
145 return shortDate(from, timeZone);
146}
147
148/**
149 * The span for `key`: since `lastSeen` (your last visit, kept by notify),
150 * or the last 24 hours or 7 days. Since your last visit falls back to the
151 * last 24 hours when there is none (`null`) or it could not be read
152 * (`undefined`), and to MAX_AWAY_DAYS when it was longer ago.
153 */
154export function spanFor(key: WindowKey, now: number, lastSeen: number | null | undefined, timeZone: string | null): Span {
155 if (key === "7d") return { key, from: now - 7 * DAY, now, words: "In the last 7 days", length: "7 days", note: null };
156 if (key === "24h" || lastSeen == null || lastSeen > now) {
157 const note = key !== "last" ? null : lastSeen === undefined ? "unknown" : "first";
158 return { key, from: now - DAY, now, words: "In the last 24 hours", length: "24 hours", note };
159 }
160 const furthest = now - MAX_AWAY_DAYS * DAY;
161 if (lastSeen < furthest) return { key, from: furthest, now, words: `In the last ${MAX_AWAY_DAYS} days`, length: `${MAX_AWAY_DAYS} days`, note: "capped" };
162 return { key, from: lastSeen, now, words: `Since ${sinceWords(lastSeen, now, timeZone)}`, length: duration(now - lastSeen), note: null };
163}
164
165/** Whether `at` (epoch ms or RFC 3339) falls in the span. */
166export function within(at: number | string | null | undefined, span: Pick<Span, "from" | "now">): boolean {
167 if (at == null) return false;
168 const ms = typeof at === "number" ? at : Date.parse(at);
169 return Number.isFinite(ms) && ms >= span.from && ms <= span.now;
170}
171
172// --- Code read for the span -----------------------------------------------------
173
174/** A pull request with where it is: what Home reads from Code. */
175export type CodePull = Pick<Pull, "number" | "title" | "status" | "mergedAt" | "createdAt" | "updatedAt"> & {
176 repo: RepoPath;
177 /** The repository's id, and the commit the merge put on the base branch: what deployments ship. */
178 repoId?: string;
179 mergeCommit?: string | null;
180 author: { username: string; kind?: string };
181 /** Who merged it, when it merged. */
182 mergedBy?: string | null;
183};
184
185/** Whether a pull request was opened by g1t itself, as older ones were: shown as `@g1t`. */
186export function isAgentPull(pull: { author: { username: string; kind?: string } }): boolean {
187 const name = pull.author.username;
188 return pull.author.kind === "agent" || name === "g1t" || name.endsWith("-agent");
189}
190
191/** `acme/web#12`, lowercase: how a pull request is matched. */
192export function pullKey(repo: RepoPath, number: number): string {
193 return `${repo.namespace}/${repo.name}#${number}`.toLowerCase();
194}
195
196export type CodeWork = {
197 pulls: CodePull[];
198 /** Whether every list read reached back to 7 days before the span. */
199 complete: boolean;
200};
201
202// --- People in the span -----------------------------------------------------------
203
204/**
205 * Who an actor is. Actors are member keys, as the events and chat services
206 * return them: `user:<id>` for an account, `agent:<id>` for an agent of
207 * older rows, `""` for nobody (a push an import made). g1t itself and
208 * older agents are not people; everyone else is. `agents` names more keys
209 * that are agents' (accounts of kind `agent`), when known.
210 */
211export type ActorKind = "person" | "agent";
212
213/** g1t's own account, as events name it (identity's `AGENT_ID`). */
214export const G1T_ACTOR = "user:usr_g1t_agent";
215
216export function actorKind(key: string, agents?: ReadonlySet<string>): ActorKind {
217 return key.startsWith("agent:") || key.startsWith("system:") || key === G1T_ACTOR || isRobotKey(key) || agents?.has(key) ? "agent" : "person";
218}
219
220/**
221 * A member key that names a robot under `user:`: an agent of older rows by
222 * its own id, a workspace (its own token, or g1t's upkeep as it), or `g1t`.
223 * Events name a workspace this way (services/events digest).
224 */
225export function isRobotKey(key: string): boolean {
226 return key.startsWith("user:agt_") || key.startsWith("user:wsp_") || key === "user:g1t";
227}
228
229/** Whether a username is g1t's own: g1t, or an agent account of older rows. */
230export function isAgentName(name: string | null | undefined): boolean {
231 return name === "g1t" || (name != null && name.endsWith("-agent"));
232}
233
234/** A repository as the digest's links and lines need it. */
235export type RepoRef = RepoPath & { defaultBranch: string };
236
237/**
238 * The kinds of work the span's chart is split into, in the order the
239 * legend and each bar show them (and the chart's colour slots).
240 */
241export const WORK_KINDS = ["pushes", "pulls", "items", "shipped", "docs", "chat"] as const;
242export type WorkKind = (typeof WORK_KINDS)[number];
243
244/** Each kind's name in the legend. */
245export const WORK_LABEL: Record<WorkKind, string> = {
246 pushes: "Pushes",
247 pulls: "Pull requests",
248 items: "Work items",
249 shipped: "Shipped",
250 docs: "Docs",
251 chat: "Chat",
252};
253
254/** A person, or an agent, who did something in the span: a row of the chart. */
255export type DigestActor = {
256 key: string;
257 /** Their username; g1t for g1t; `unknown account` when it could not be read. */
258 name: string;
259 kind: ActorKind;
260 /** How many things they did, over every kind: the order of the rows. */
261 count: number;
262 /** The same things by kind (a push counts once, however many commits). */
263 parts: Partial<Record<WorkKind, number>>;
264 /** Commits in their pushes. */
265 commits: number;
266};
267
268/** One kind of work: what was done, with its count, and where that is listed. */
269export type DigestLine = {
270 key: WorkKind;
271 text: string;
272 /** Things of this kind, in the bars' units. */
273 count: number;
274 to: string | null;
275};
276
277export type DigestColumn = {
278 lines: DigestLine[];
279 /** Most active first: people and agents, each marked. */
280 actors: DigestActor[];
281};
282
283/** What the sentence under the heading needs. */
284export type DigestSummary = {
285 /** Distinct people (not agents) who did anything. */
286 people: number;
287 /** Commits people pushed. */
288 commits: number;
289 /** Pull requests people merged. */
290 merged: number;
291 /** Messages people sent. */
292 said: number;
293 /** Whether anything at all was counted. */
294 anything: boolean;
295 /** Whether what people did could be read at all (events and chat both silent: no). */
296 peopleRead: boolean;
297};
298
299export type Digest = {
300 people: DigestColumn;
301 summary: DigestSummary;
302 /** Sources that did not answer, by name, for the card to say so: Code, Chat. */
303 missing: string[];
304 /** True when a source was cut short, so some counts are low. */
305 partial: boolean;
306};
307
308export type DigestInput = {
309 slug: string;
310 /** The workspace's repositories by id: for links, and to count projects. */
311 repos: Record<string, RepoRef>;
312 /** Events' digest; null when events did not answer. Without Code access it has no repositories. */
313 activity: ActivityDigest | null;
314 /** Chat's; null when chat did not answer. */
315 chat: ChatActivity | null;
316 /** Names for member keys: a username. */
317 names: Record<string, string>;
318 /** Keys of accounts that are not people, beyond g1t. */
319 agentKeys?: ReadonlySet<string>;
320 code: boolean;
321};
322
323const people = (n: number) => plural(n, "person", "people");
324
325/** `a, b and c`. */
326export const listOf = (names: string[]) => (names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`);
327
328/** What people did, from a tally: how many, and by whom (non-empty keys). */
329function part(counts: ActorCount[], agents?: ReadonlySet<string>): { count: number; actors: Map<string, number> } {
330 const actors = new Map<string, number>();
331 let count = 0;
332 for (const entry of counts) {
333 if (actorKind(entry.actor, agents) !== "person") continue;
334 count += entry.count;
335 if (entry.actor) actors.set(entry.actor, (actors.get(entry.actor) ?? 0) + entry.count);
336 }
337 return { count, actors };
338}
339
340/** Where a line points: the one project's page, or the workspace's projects when several. */
341function placeFor(slug: string, repos: Record<string, RepoRef>, repoIds: Iterable<string>, page: string): string {
342 const ids = [...new Set(repoIds)];
343 const only = ids.length === 1 ? repos[ids[0]!] : null;
344 return only ? `/${only.namespace}/${only.name}/${page}` : `/${slug}/-/repositories`;
345}
346
347/** `3 opened, 5 merged`: the non-zero counts, `#` standing for each. */
348function counted(parts: [number, string][]): string {
349 return parts
350 .filter(([count]) => count > 0)
351 .map(([count, words]) => words.replace("#", count.toLocaleString("en-US")))
352 .join(", ");
353}
354
355/**
356 * What was done in the span, by kind, with counts and links, and who did
357 * it: people and agents both, each marked, so g1t and the agents show
358 * beside the people instead of being left out (or showing as nobody).
359 * g1t's keys (its account, its chat key, a workspace acting as it) are one
360 * row. Pure: everything comes from the services' counts and the names
361 * looked up for them.
362 */
363export function digestColumn(input: DigestInput): DigestColumn {
364 const { slug, repos, activity, chat, names, agentKeys } = input;
365 const lines: DigestLine[] = [];
366 const rows = new Map<string, DigestActor>();
367 const row = (key: string): DigestActor | null => {
368 if (!key) return null;
369 const kind = actorKind(key, agentKeys);
370 const name = names[key] ?? (kind === "agent" ? (key.endsWith(":g1t") || key === G1T_ACTOR ? "g1t" : "agent") : "unknown account");
371 const id = name === "g1t" ? "g1t" : key;
372 let found = rows.get(id);
373 if (!found) {
374 found = { key: id, name, kind, count: 0, parts: {}, commits: 0 };
375 rows.set(id, found);
376 }
377 return found;
378 };
379 /** Credits each actor with their part of a tally; the tally's total. */
380 const credit = (kind: WorkKind, counts: ActorCount[]) => {
381 let total = 0;
382 for (const { actor, count } of counts) {
383 total += count;
384 const who = row(actor);
385 if (!who) continue;
386 who.count += count;
387 who.parts[kind] = (who.parts[kind] ?? 0) + count;
388 }
389 return total;
390 };
391
392 if (activity) {
393 // Pushes: commits, projects, and who.
394 const pushed = new Set<string>();
395 let commits = 0;
396 let pushes = 0;
397 for (const repo of activity.repos) {
398 for (const by of repo.pushes.by) {
399 if (by.count === 0) continue;
400 pushed.add(repo.repo_id);
401 commits += by.commits;
402 pushes += credit("pushes", [{ actor: by.actor, count: by.count }]);
403 const who = row(by.actor);
404 if (who) who.commits += by.commits;
405 }
406 }
407 if (pushes > 0) {
408 lines.push({
409 key: "pushes",
410 text: `${plural(commits, "commit")} to ${plural(pushed.size, "project")}`,
411 count: pushes,
412 to: placeFor(slug, repos, pushed, "activity"),
413 });
414 }
415
416 // The other kinds, summed over projects: how many, and where.
417 const sum = (kind: WorkKind, pick: (repo: RepoDigest) => ActorCount[]) => {
418 let count = 0;
419 const repoIds: string[] = [];
420 for (const repo of activity.repos) {
421 const n = credit(kind, pick(repo));
422 if (n === 0) continue;
423 count += n;
424 repoIds.push(repo.repo_id);
425 }
426 return { count, repoIds };
427 };
428
429 const opened = sum("pulls", (repo) => repo.pulls.opened);
430 const merged = sum("pulls", (repo) => repo.pulls.merged);
431 const closed = sum("pulls", (repo) => repo.pulls.closed);
432 const reviews = sum("pulls", (repo) => repo.reviews);
433 const pulls = opened.count + merged.count + closed.count + reviews.count;
434 if (pulls > 0) {
435 const text = counted([
436 [opened.count, "# opened"],
437 [merged.count, "# merged"],
438 [closed.count, "# closed without merging"],
439 [reviews.count, "# reviewed"],
440 ]);
441 lines.push({
442 key: "pulls",
443 text,
444 count: pulls,
445 to: placeFor(slug, repos, [...opened.repoIds, ...merged.repoIds, ...closed.repoIds, ...reviews.repoIds], "pulls"),
446 });
447 }
448
449 const itemsOpened = sum("items", (repo) => repo.items.opened);
450 const itemsClosed = sum("items", (repo) => repo.items.closed);
451 const comments = sum("items", (repo) => repo.comments);
452 const items = itemsOpened.count + itemsClosed.count + comments.count;
453 if (items > 0) {
454 const text = counted([
455 [itemsOpened.count, "# opened"],
456 [itemsClosed.count, "# closed"],
457 [comments.count, comments.count === 1 ? "# comment" : "# comments"],
458 ]);
459 // Work items are the workspace's: its Work list, filtered to the one project they were in, if one.
460 const ids = new Set([...itemsOpened.repoIds, ...itemsClosed.repoIds, ...comments.repoIds]);
461 const only = ids.size === 1 ? repos[[...ids][0]!] : null;
462 lines.push({ key: "items", text, count: items, to: only ? `/${slug}/-/work?repo=${encodeURIComponent(only.name)}` : `/${slug}/-/work` });
463 }
464
465 const succeeded = sum("shipped", (repo) => repo.deployments.succeeded);
466 const failed = sum("shipped", (repo) => repo.deployments.failed);
467 const releases = sum("shipped", (repo) => tallyOf(repo.releases.map((release) => release.actor)));
468 const packages = sum("shipped", (repo) => tallyOf(repo.packages.map((pkg) => pkg.actor)));
469 const shipped = succeeded.count + failed.count + releases.count + packages.count;
470 if (shipped > 0) {
471 const text = counted([
472 [succeeded.count, succeeded.count === 1 ? "# deploy" : "# deploys"],
473 [failed.count, "# failed"],
474 [releases.count, releases.count === 1 ? "# release" : "# releases"],
475 [packages.count, packages.count === 1 ? "# package version" : "# package versions"],
476 ]);
477 const deployed = [...succeeded.repoIds, ...failed.repoIds];
478 const to =
479 deployed.length > 0
480 ? placeFor(slug, repos, deployed, "deployments")
481 : releases.count > 0
482 ? placeFor(slug, repos, releases.repoIds, "releases")
483 : `/${slug}/-/packages`;
484 lines.push({ key: "shipped", text, count: shipped, to });
485 }
486
487 // Artifacts: made, and whose content changed.
488 if (activity.folios) {
489 const made = credit("docs", activity.folios.created);
490 const edits: ActorCount[] = [];
491 let edited = 0;
492 let allDocs = true;
493 for (const folio of activity.folios.edited) {
494 if (folio.authors.length === 0) continue;
495 edited += 1;
496 if (folio.kind !== "doc") allDocs = false;
497 for (const author of folio.authors) edits.push({ actor: author, count: 1 });
498 }
499 credit("docs", edits);
500 const what = (count: number) => plural(count, allDocs ? "doc" : "artifact");
501 if (made + edited > 0) {
502 const parts: string[] = [];
503 if (made > 0) parts.push(`${what(made)} created`);
504 if (edited > 0) parts.push(`${what(edited)} edited`);
505 lines.push({ key: "docs", text: parts.join(", "), count: made + edits.length, to: `/${slug}/-/artifacts` });
506 }
507 }
508 }
509
510 // Chat: what was said.
511 if (chat) {
512 const said = credit(
513 "chat",
514 chat.authors.map((author) => ({ actor: author.key, count: author.messages })),
515 );
516 if (said > 0) {
517 lines.push({ key: "chat", text: `${plural(said, "message")} in ${plural(chat.channels, "conversation")}`, count: said, to: `/${slug}/-/chat` });
518 }
519 }
520
521 const actors = [...rows.values()].filter((actor) => actor.count > 0).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
522 return { lines, actors };
523}
524
525/** A tally with one of each actor, for lists that name an actor per item. */
526function tallyOf(actors: string[]): ActorCount[] {
527 const counts = new Map<string, number>();
528 for (const actor of actors) counts.set(actor, (counts.get(actor) ?? 0) + 1);
529 return [...counts].map(([actor, count]) => ({ actor, count }));
530}
531
532/** What people did, what the sentence needs, and which sources were silent. */
533export function digestOf(input: DigestInput): Digest {
534 const column = digestColumn(input);
535 const missing: string[] = [];
536 if (input.code && !input.activity) missing.push("Code");
537 if (!input.chat) missing.push("Chat");
538 let commits = 0;
539 let merged = 0;
540 for (const repo of input.activity?.repos ?? []) {
541 for (const by of repo.pushes.by) if (actorKind(by.actor, input.agentKeys) === "person") commits += by.commits;
542 merged += part(repo.pulls.merged, input.agentKeys).count;
543 }
544 const said = part(
545 (input.chat?.authors ?? []).map((author) => ({ actor: author.key, count: author.messages })),
546 input.agentKeys,
547 ).count;
548 return {
549 people: column,
550 summary: {
551 people: column.actors.filter((actor) => actor.kind === "person").length,
552 commits,
553 merged,
554 said,
555 anything: column.lines.length > 0,
556 peopleRead: input.activity != null || input.chat != null,
557 },
558 missing,
559 partial: input.activity != null && !input.activity.complete,
560 };
561}
562
563// --- What landed in the span -----------------------------------------------------
564
565/**
566 * A change that landed: a pull request merged; commits pushed straight to
567 * a default branch; a production build that went live; a release or a
568 * package version published.
569 */
570export type LandedChange = {
571 key: string;
572 kind: "merge" | "push" | "deploy" | "release" | "package";
573 title: string;
574 /** One line under it: where, and by whom. */
575 detail: string;
576 to: string;
577 at: number;
578 /** A merge's or a push's commit on the default branch, and its repository's id: what a deployment ships. */
579 sha?: string | null;
580 repoId?: string | null;
581 /** Whether it is live yet (`withShipped`); null when its project does not deploy, or it could not be read. */
582 shipped?: ShipInfo | null;
583 /** Made in a harness session (`withSessions`, or a `G1t-Session:` trailer): the agent marker, and the session. */
584 agent?: AgentMark | null;
585 /** A title that is a commit's subject: its repository (`owner/name`), which its `#12`s are read in. */
586 refsIn?: string;
587 /** A production build that failed (`landedDeploys`). */
588 failed?: boolean;
589};
590
591/** Whether a change is live: shipped by a production deployment, on its way, waiting, or the deployment after it failed. */
592export type ShipInfo = {
593 state: ShipState;
594 /** Epoch ms: when the deployment that shipped it went live. */
595 at: number | null;
596 /** The deployment (or the run that deploys it). */
597 to: string | null;
598};
599
600/** A change made in a harness session: which harness when known, and the session's page. */
601export type AgentMark = { harness: Harness | null; to: string | null };
602
603/** Every pull request that merged in the span, newest first. */
604export function landedIn(pulls: CodePull[], span: Pick<Span, "from" | "now">): LandedChange[] {
605 return pulls
606 .filter((pull) => pull.status === "merged" && within(pull.mergedAt, span))
607 .map((pull) => {
608 const agent = isAgentPull(pull);
609 const mergedBy = pull.mergedBy && pull.mergedBy !== pull.author.username ? `, merged by ${pull.mergedBy}` : "";
610 return {
611 key: `landed:${pullKey(pull.repo, pull.number)}`,
612 kind: "merge" as const,
613 title: pull.title,
614 detail: `${pull.repo.name}#${pull.number} · by ${agent ? `@${pull.author.username}` : pull.author.username}${mergedBy}`,
615 to: `/${pull.repo.namespace}/${pull.repo.name}/pull/${pull.number}`,
616 at: Date.parse(pull.mergedAt!),
617 sha: pull.mergeCommit ?? null,
618 repoId: pull.repoId ?? null,
619 };
620 })
621 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
622}
623
624/** The names behind member keys, for a line: `ana and bo`, `@margo`, `an import` for nobody. */
625function namesOf(keys: string[], names: Record<string, string>, agentKeys?: ReadonlySet<string>): string {
626 const shown = keys.map((key) => {
627 if (!key) return "an import";
628 const name = names[key] ?? (key === G1T_ACTOR ? "g1t" : "someone");
629 return actorKind(key, agentKeys) === "agent" ? `@${name}` : name;
630 });
631 return listOf([...new Set(shown)]);
632}
633
634/**
635 * Commits pushed straight to a default branch, one row per project with
636 * any: what landed without a pull request. Releases and package versions
637 * published, one row each. Pushes within the span only: the digest was
638 * asked for the span.
639 */
640export function landedFromActivity(
641 activity: ActivityDigest | null,
642 repos: Record<string, RepoRef>,
643 names: Record<string, string>,
644 slug: string,
645 agentKeys?: ReadonlySet<string>,
646): LandedChange[] {
647 const rows: LandedChange[] = [];
648 for (const repo of activity?.repos ?? []) {
649 const path = repos[repo.repo_id];
650 if (!path) continue;
651 const direct = repo.pushes.default_branch;
652 if (direct.count > 0 && direct.last_at) {
653 const by = direct.by.map((entry) => entry.actor);
654 rows.push({
655 key: `push:${repo.repo_id}`,
656 kind: "push",
657 title: `${plural(direct.commits, "commit")} pushed to ${path.defaultBranch}`,
658 detail: `${path.name} · ${plural(direct.count, "push", "pushes")} by ${namesOf(by, names, agentKeys)}`,
659 to: `/${path.namespace}/${path.name}/activity`,
660 at: Date.parse(direct.last_at),
661 });
662 }
663 for (const release of repo.releases) {
664 rows.push({
665 key: `release:${repo.repo_id}:${release.tag}`,
666 kind: "release",
667 title: release.name ? `${release.tag} · ${release.name}` : release.tag,
668 detail: `${path.name} · released by ${namesOf([release.actor], names, agentKeys)}`,
669 to: `/${path.namespace}/${path.name}/releases/tag/${encodeURIComponent(release.tag)}`,
670 at: Date.parse(release.at),
671 });
672 }
673 for (const pkg of repo.packages) {
674 rows.push({
675 key: `package:${repo.repo_id}:${pkg.ecosystem}:${pkg.name}:${pkg.version}`,
676 kind: "package",
677 title: `${pkg.name} ${pkg.version}`,
678 detail: `${pkg.ecosystem} package · published by ${namesOf([pkg.actor], names, agentKeys)}`,
679 to: `/${slug}/-/packages`,
680 at: Date.parse(pkg.at),
681 });
682 }
683 }
684 return rows;
685}
686
687/**
688 * Production builds of the span as landed changes, only where nothing on
689 * the list already says so: a merge or push whose live label links to the
690 * build (`shipped.to`), or whose commit it built. So a build that shipped
691 * a merge is that merge's "Live" label, not a row of its own; a redeploy,
692 * a rollback or a build of a project whose pushes weren't read is a row,
693 * and so is one that failed (`failed`). Previews stay on their project's
694 * Deployments.
695 */
696export function landedDeploys(deploys: DeployRow[], shown: readonly LandedChange[] = []): LandedChange[] {
697 const said = (row: DeployRow) =>
698 shown.some((change) => (change.shipped?.to != null && change.shipped.to === row.to) || (!!change.sha && !!row.commit && change.sha.startsWith(row.commit)));
699 return deploys
700 .filter((row) => row.kind === "production" && !said(row))
701 .map((row) => ({
702 key: `landed:${row.key}`,
703 kind: "deploy" as const,
704 title: row.outcome === "failed" ? `Production of ${row.project} failed to deploy` : `Production of ${row.project} went live`,
705 detail: `${row.commit} · by ${row.by ?? "someone"}`,
706 to: row.to,
707 at: row.at,
708 ...(row.outcome === "failed" ? { failed: true } : {}),
709 }));
710}
711
712/** Everything that landed, newest first. */
713export function landed(parts: LandedChange[][]): LandedChange[] {
714 return parts.flat().sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
715}
716
717// --- Pushes straight to a default branch, each ---------------------------------
718
719/** A push to a default branch, with the history it brought read back. */
720export type DirectPush = {
721 repoId: string;
722 repo: RepoRef;
723 push: PushRecord & { id: string };
724 /** Who pushed, by name; `someone` when it could not be read. */
725 by: string;
726};
727
728/** The sessions a commit message names in `G1t-Session:` trailers. */
729export function sessionTrailers(message: string): string[] {
730 const ids = [...message.matchAll(/^G1t-Session:\s*(ses_[0-9a-z]+)\s*$/gim)].map((match) => match[1]!.toLowerCase());
731 return [...new Set(ids)];
732}
733
734/** A commit message's first line. */
735const subject = (message: string) => message.split("\n", 1)[0]!.trim();
736
737/**
738 * Each person's push to a default branch in the span, newest first, as a
739 * landed change: its commit when it brought one ("Fix the bell's count"),
740 * else how many; the session a commit names in a `G1t-Session:` trailer
741 * as its agent mark. `history` is each repository's default branch read
742 * back from its newest push, newest first; a push whose commits are not
743 * in it (rewritten since) is left out, and so is g1t's own (a pull
744 * request landing: Landed lists the merge).
745 */
746export function pushRows(
747 pushes: DirectPush[],
748 history: Record<string, Pick<Commit, "hash" | "parents" | "message">[]>,
749 span: Pick<Span, "from" | "now">,
750 byG1t: (commit: Pick<Commit, "hash" | "parents" | "message">) => boolean = () => false,
751): LandedChange[] {
752 const rows: LandedChange[] = [];
753 for (const { repoId, repo, push, by } of pushes) {
754 if (!pushedByPerson(push) || !within(push.time, span)) continue;
755 const commits = history[repoId] ?? [];
756 const start = commits.findIndex((commit) => commit.hash === push.data.after);
757 if (start === -1) continue;
758 const brought = pushedCommits(commits.slice(start), push.data.before, byG1t);
759 if (brought.length === 0) continue;
760 const newest = brought[0]!;
761 const session = brought.flatMap((commit) => sessionTrailers(commit.message))[0] ?? null;
762 const branch = repo.defaultBranch;
763 rows.push({
764 key: `push:${repoId}:${push.id}`,
765 kind: "push",
766 title: brought.length === 1 ? subject(newest.message) || `1 commit pushed to ${branch}` : `${plural(brought.length, "commit")} pushed to ${branch}`,
767 detail: `${repo.name} · ${brought.length === 1 ? `pushed to ${branch}` : subject(newest.message)} · by ${by}`,
768 to: brought.length === 1 ? `/${repo.namespace}/${repo.name}/commit/${newest.hash}` : `/${repo.namespace}/${repo.name}/activity`,
769 at: Date.parse(push.time),
770 sha: push.data.after,
771 repoId,
772 agent: session ? { harness: null, to: sessionPath(repo.namespace, session) } : null,
773 ...(brought.length === 1 && subject(newest.message) ? { refsIn: `${repo.namespace}/${repo.name}` } : {}),
774 });
775 }
776 return rows;
777}
778
779// --- Shipped: merge to deploy --------------------------------------------------
780
781/**
782 * Each merge and push with whether it is live yet, from what deployments
783 * recorded as production deployed (`shipped`). A project that does not
784 * deploy says nothing; a change deployments did not answer for keeps none.
785 */
786export function withShipped(rows: LandedChange[], answers: ShippedRepo[] | null): LandedChange[] {
787 if (!answers) return rows;
788 const byRepo = new Map(answers.map((answer) => [answer.repo_id, answer]));
789 return rows.map((row) => {
790 if (!row.sha || !row.repoId || (row.kind !== "merge" && row.kind !== "push")) return row;
791 const answer = byRepo.get(row.repoId);
792 const commit = answer?.deploys ? answer.commits.find((c) => c.sha === row.sha) : null;
793 if (!commit) return row;
794 return { ...row, shipped: { state: commit.state, at: commit.deployed_at ? Date.parse(commit.deployed_at) : null, to: commit.url } };
795 });
796}
797
798/** What to ask deployments: each repository's merges and pushes with their commit and when they landed. */
799export function shippedAsks(rows: LandedChange[]): { repo_id: string; commits: { sha: string; landed_at: string }[] }[] {
800 const byRepo = new Map<string, { sha: string; landed_at: string }[]>();
801 for (const row of rows) {
802 if (!row.sha || !row.repoId || (row.kind !== "merge" && row.kind !== "push")) continue;
803 const list = byRepo.get(row.repoId) ?? [];
804 list.push({ sha: row.sha, landed_at: new Date(row.at).toISOString() });
805 byRepo.set(row.repoId, list);
806 }
807 return [...byRepo].map(([repo_id, commits]) => ({ repo_id, commits }));
808}
809
810/** How long something took, short: "1 min", "45 min", "3 h", "2 d". */
811function took(ms: number): string {
812 const minutes = Math.max(1, Math.round(ms / MINUTE));
813 if (minutes < 60) return `${minutes} min`;
814 const hours = Math.round(minutes / 60);
815 if (hours < 48) return `${hours} h`;
816 return `${Math.round(hours / 24)} d`;
817}
818
819/** "Live 9 min after merge", "Waiting to deploy", "Deploying", "Deploy failed". */
820export function shippedLabel(ship: ShipInfo, row: Pick<LandedChange, "kind" | "at">): string {
821 switch (ship.state) {
822 case "live":
823 return ship.at != null ? `Live ${took(ship.at - row.at)} after ${row.kind === "merge" ? "merge" : "push"}` : "Live";
824 case "deploying":
825 return "Deploying";
826 case "failed":
827 return "Deploy failed";
828 default:
829 return "Waiting to deploy";
830 }
831}
832
833// --- Done with an agent --------------------------------------------------------
834
835/**
836 * Each merged pull request with the harness session that made it, when
837 * work tied one to it (`pullSessions`): the first, by when it started.
838 */
839export function withSessions(rows: LandedChange[], sessions: { repo: RepoPath; pulls: PullSessions[] }[] | null): LandedChange[] {
840 if (!sessions) return rows;
841 const found = new Map<string, AgentMark>();
842 for (const { repo, pulls } of sessions) {
843 for (const pull of pulls) {
844 const first = pull.sessions[0];
845 if (first) found.set(`landed:${pullKey(repo, pull.number)}`, { harness: first.harness, to: sessionPath(repo.namespace, first.id) });
846 }
847 }
848 return rows.map((row) => (row.agent || !found.has(row.key) ? row : { ...row, agent: found.get(row.key)! }));
849}
850
851/** The agent mark's words: "Made in a Claude Code session", or "Made in a session". */
852export function agentLabel(mark: AgentMark): string {
853 return mark.harness ? `Made in a ${HARNESS_NAMES[mark.harness] ?? "harness"} session` : "Made in a session";
854}
855
856// --- Day by day ----------------------------------------------------------------
857
858/** What landed on one day, newest first: "Today", "Yesterday", "Mon, Oct 12". */
859export type LandedDay = { key: string; label: string; rows: LandedChange[] };
860
861/** What landed, by the day it landed in the reader's time zone, newest day first. */
862export function landedByDay(rows: LandedChange[], now: number, timeZone: string | null): LandedDay[] {
863 const days: LandedDay[] = [];
864 const today = dayIn(now, timeZone);
865 const yesterday = dayIn(now - DAY, timeZone);
866 for (const row of [...rows].sort((a, b) => b.at - a.at || a.key.localeCompare(b.key))) {
867 const key = dayIn(row.at, timeZone);
868 let day = days.find((d) => d.key === key);
869 if (!day) {
870 const label =
871 key === today ? "Today" : key === yesterday ? "Yesterday" : formatIn(row.at, timeZone, { weekday: "short", month: "short", day: "numeric" });
872 day = { key, label, rows: [] };
873 days.push(day);
874 }
875 day.rows.push(row);
876 }
877 return days;
878}
879
880// --- While you were away -------------------------------------------------------
881
882/** Something that settled by itself in the span: what it was, why it settled, where. */
883export type SettledRow = { key: string; title: string; why: string; where: string | null; to: string; at: number };
884
885/** What g1t settled for you, what shipped, and what still needs you, in the span. */
886export type Away = {
887 settled: SettledRow[];
888 /** Merges and pushes in the span that went live, are waiting, deploying, or whose deployment failed. */
889 shipped: number;
890 waiting: number;
891 deploying: number;
892 failed: number;
893 /** Rows in Where you're needed. */
894 needs: number;
895};
896
897/**
898 * Your notifications that settled by themselves in the span (a later run
899 * passed, it merged, it deployed), newest first; one marked done by hand
900 * is yours, not g1t's. Only this workspace's, and none about a repository
901 * for a member without Code access.
902 */
903export function settledIn(items: InboxItem[] | null, slug: string, code: boolean, span: Pick<Span, "from" | "now">): SettledRow[] {
904 return (items ?? [])
905 .filter((item) => item.doneAt != null && settledLine(item) && within(item.doneAt, span))
906 .filter((item) => (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug && (code || !item.repo))
907 .map((item) => ({
908 key: `settled:${item.id}`,
909 // A work item's or pull request's own title; else the entry's ("CI failed on main in acme/web").
910 title: item.number != null ? item.body || item.title : item.title,
911 why: settledLine(item),
912 where: item.repo ? `${item.repo}${item.number != null ? `#${item.number}` : ""}` : null,
913 to: item.url,
914 at: Date.parse(item.doneAt!),
915 }))
916 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
917}
918
919export function awayOf(input: { settled: SettledRow[]; landed: LandedChange[] | null; needs: number }): Away {
920 const count = (state: ShipState) => (input.landed ?? []).filter((row) => row.shipped?.state === state).length;
921 return {
922 settled: input.settled,
923 shipped: count("live"),
924 waiting: count("waiting"),
925 deploying: count("deploying"),
926 failed: count("failed"),
927 needs: input.needs,
928 };
929}
930
931/** A deployment's maker as a member key: an id becomes `user:<id>`, a key stays as it is. */
932export function deployActorKey(createdBy: string | null | undefined): string | null {
933 const by = (createdBy ?? "").trim();
934 if (!by) return null;
935 return /^(user|agent):/.test(by) ? by : `user:${by}`;
936}
937
938/** A build that finished in the span. */
939export type DeployRow = {
940 key: string;
941 project: string;
942 kind: Deployment["kind"];
943 /** `live`: built and served (it may have been replaced since); `failed`: it did not build. */
944 outcome: "live" | "failed";
945 commit: string;
946 branch: string | null;
947 at: number;
948 to: string;
949 /** Who made it, as a name (`@g1t` for g1t itself); null when the deployment does not say. */
950 by: string | null;
951};
952
953/**
954 * Builds that finished in the span, newest first: production builds each,
955 * and previews too. A build that went live and was replaced since still
956 * went live. Skipped builds are left out.
957 */
958export function deploysIn(
959 projects: { slug: string; deployments: Deployment[] }[],
960 workspace: string,
961 span: Pick<Span, "from" | "now">,
962 names: Record<string, string> = {},
963 agentKeys?: ReadonlySet<string>,
964): DeployRow[] {
965 const rows: DeployRow[] = [];
966 for (const project of projects) {
967 for (const deploy of project.deployments) {
968 // Who made it: the deployment names them by id, so it reads as a name, or as someone when identity doesn't know it.
969 const key = deployActorKey(deploy.createdBy);
970 const ended = deploy.finishedAt ?? null;
971 if (!within(ended, span)) continue;
972 const outcome =
973 deploy.status === "failed" ? "failed" : deploy.status === "ready" || deploy.status === "replaced" || deploy.status === "down" ? "live" : null;
974 if (!outcome) continue;
975 rows.push({
976 key: `deploy:${project.slug}:${deploy.id}`,
977 project: project.slug,
978 kind: deploy.kind,
979 outcome,
980 commit: deploy.commit.slice(0, 7),
981 branch: deploy.branch,
982 at: Date.parse(ended!),
983 to: `/${workspace}/${project.slug}/deployments/${deploy.id}`,
984 by: key ? namesOf([key], names, agentKeys) : null,
985 });
986 }
987 }
988 return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
989}
990
991// --- Running now ----------------------------------------------------------------
992
993/** Something going right now: a workflow run or a build. */
994export type RunningRow = {
995 key: string;
996 kind: "workflow" | "deploy";
997 title: string;
998 /** One line: who and where. */
999 detail: string;
1000 /** "Running", "Queued", "Building". */
1001 status: string;
1002 /** Epoch ms: when it started. */
1003 at: number;
1004 to: string;
1005};
1006
1007/** Builds queued or going now, one per project (its newest). */
1008export function runningDeploys(overview: ProjectDeploys[], slug: string): RunningRow[] {
1009 return overview.flatMap((project) => {
1010 const latest = project.latest;
1011 if (!latest || (latest.status !== "queued" && latest.status !== "building")) return [];
1012 return [
1013 {
1014 key: `deploy:${project.slug}:${latest.id}`,
1015 kind: "deploy" as const,
1016 title: `${latest.kind === "production" ? "Production" : `Preview of ${latest.branch ?? "a branch"}`} of ${project.slug}`,
1017 detail: `${latest.commit.slice(0, 7)} · by ${latest.createdBy}`,
1018 status: latest.status === "queued" ? "Queued" : "Building",
1019 at: Date.parse(latest.createdAt),
1020 to: `/${slug}/${project.slug}/deployments/${latest.id}`,
1021 },
1022 ];
1023 });
1024}
1025
1026const RUN_STATUS: Partial<Record<WorkflowRun["status"], string>> = {
1027 pending: "Queued",
1028 queued: "Queued",
1029 action_required: "Needs approval",
1030 in_progress: "Running",
1031 waiting: "Waiting",
1032};
1033
1034/** Workflow runs not finished, in the projects read: queued, waiting, running, or waiting for approval. */
1035export function runningWorkflows(projects: { repo: RepoPath; runs: WorkflowRun[] }[]): RunningRow[] {
1036 return projects.flatMap(({ repo, runs }) =>
1037 runs.flatMap((run) => {
1038 const status = RUN_STATUS[run.status];
1039 if (!status) return [];
1040 return [
1041 {
1042 key: `workflow:${repo.namespace}/${repo.name}:${run.id}`.toLowerCase(),
1043 kind: "workflow" as const,
1044 title: run.title ? `${run.name}: ${run.title}` : run.name,
1045 detail: `${repo.namespace}/${repo.name} ${run.ref.replace(/^refs\/heads\//, "")}${run.actor ? ` · by ${run.actor}` : ""}`,
1046 status,
1047 at: Date.parse(run.startedAt ?? run.createdAt),
1048 to: `/${repo.namespace}/${repo.name}/actions/runs/${run.id}`,
1049 },
1050 ];
1051 }),
1052 );
1053}
1054
1055/** Everything running, longest-going first within each kind: workflow runs, then builds. */
1056export function running(parts: RunningRow[][]): RunningRow[] {
1057 const order = { workflow: 0, deploy: 1 } as const;
1058 return parts.flat().sort((a, b) => order[a.kind] - order[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
1059}
1060
1061// --- Needs you ------------------------------------------------------------------
1062
1063/**
1064 * What a row is. Tiers, most pressing first:
1065 * 0. production is down to an older build (`deploy`);
1066 * 1. a change that can't land until someone acts on it (`pull_blocked`);
1067 * 2. something waiting only for you (a review, an invitation, your pull
1068 * request that is ready to merge);
1069 * 3. a job waiting for a runner that is not there;
1070 * 4. an unread notification that is a warning or a failure;
1071 * 5. a mention or a direct message.
1072 */
1073export type AttentionKind = "deploy" | "pull_blocked" | "review" | "invitation" | "ready" | "runner" | "notification" | "chat";
1074
1075export const TIER: Record<AttentionKind, number> = {
1076 deploy: 0,
1077 pull_blocked: 1,
1078 review: 2,
1079 invitation: 2,
1080 ready: 2,
1081 runner: 3,
1082 notification: 4,
1083 chat: 5,
1084};
1085
1086export type Stake = { text: string; tone: "danger" | "warn" | "accent" | null };
1087
1088/** One row of Needs you. */
1089export type AttentionRow = {
1090 key: string;
1091 kind: AttentionKind;
1092 title: string;
1093 /** One line: what it is and where. */
1094 detail: string;
1095 /** What is at stake, in a few words. */
1096 stake: Stake | null;
1097 /** The action, right there. */
1098 action: { label: string; to: string };
1099 /** Who is on it: the person who asked, or g1t on older rows. */
1100 owner: { name: string; agent: boolean } | null;
1101 /** Epoch ms: when it started waiting. */
1102 at: number;
1103 /** Where it came from, for a member without Code access never `code`. */
1104 from: "code" | "notifications" | "chat";
1105};
1106
1107/**
1108 * Most pressing first: by tier, then what has waited longest, then by key
1109 * so the order never depends on the order rows were read. One of each key,
1110 * and one of each place: a notification about a pull request already on
1111 * the list is left out.
1112 */
1113export function rankAttention(rows: AttentionRow[]): AttentionRow[] {
1114 const sorted = [...rows].sort((a, b) => TIER[a.kind] - TIER[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
1115 const keys = new Set<string>();
1116 const places = new Set<string>();
1117 return sorted.filter((row) => {
1118 const place = row.action.to.split(/[?#]/)[0];
1119 if (keys.has(row.key) || (row.kind === "notification" && places.has(place))) return false;
1120 keys.add(row.key);
1121 places.add(place);
1122 return true;
1123 });
1124}
1125
1126/** Start here: the first row by `rankAttention`, with why it was picked. */
1127export function startHere(ranked: AttentionRow[]): { row: AttentionRow; why: string } | null {
1128 const row = ranked[0];
1129 if (!row) return null;
1130 const sameTier = ranked.filter((other) => TIER[other.kind] === TIER[row.kind]).length;
1131 const tail = sameTier > 1 ? ` Of the ${sameTier} like it, it has waited longest.` : "";
1132 return { row, why: `${WHY[row.kind]}${tail}` };
1133}
1134
1135const WHY: Record<AttentionKind, string> = {
1136 deploy: "Production is serving an older build until this is fixed, so it comes before anything else.",
1137 pull_blocked: "This change can't land until someone fixes it.",
1138 review: "You were asked by name, so it waits for your verdict.",
1139 invitation: "It is addressed to you; no one else can answer it.",
1140 ready: "Everything it needs is met; it lands when you merge it.",
1141 runner: "A job is waiting for a runner that is not there.",
1142 notification: "It is the most pressing unread notification.",
1143 chat: "Nothing else is waiting, and this is the oldest message for you.",
1144};
1145
1146// --- Rows from each source ----------------------------------------------------
1147
1148/** A Code Overview need row, as Home reads it (lib/mission-control.ts `NeedRow`). */
1149export type CodeNeed = {
1150 key: string;
1151 reason: string;
1152 repo: RepoPath | null;
1153 ref: string | null;
1154 title: string;
1155 ask: string;
1156 by: { name: string; agent: boolean } | null;
1157 at: number;
1158 to: string;
1159 facts: { label: string; value: string; tone: string | null }[];
1160};
1161
1162const fact = (need: CodeNeed, label: string) => need.facts.find((f) => f.label === label)?.value ?? null;
1163
1164const REASON_STAKE: Record<string, Stake> = {
1165 blocking: { text: "Blocking", tone: "danger" },
1166 checks_failing: { text: "Checks failing", tone: "danger" },
1167 needs_review: { text: "Needs a verdict", tone: "warn" },
1168 stalled: { text: "Stalled", tone: "warn" },
1169};
1170
1171/** A Code need (failed deploy, pull request, review, invitation, runner) as a row. */
1172export function codeRow(need: CodeNeed): AttentionRow {
1173 const prefix = need.key.split(":")[0];
1174 const where = need.repo ? `${need.repo.namespace}/${need.repo.name}${need.ref ? ` ${need.ref}` : ""}` : null;
1175 const detail = where ? `${where} · ${need.ask}` : need.ask;
1176 const owner = need.by;
1177 const base = { key: need.key, title: need.title, detail, owner, at: need.at, from: "code" as const };
1178 switch (prefix) {
1179 case "deploy":
1180 return {
1181 ...base,
1182 kind: "deploy",
1183 stake: { text: fact(need, "Production") === "Not live yet" ? "Not live yet" : "Production on an older build", tone: "danger" },
1184 action: { label: "See the build", to: need.to },
1185 };
1186 case "invitation":
1187 return { ...base, kind: "invitation", stake: { text: `${fact(need, "Role") ?? "A"} role`, tone: null }, action: { label: "Respond", to: need.to } };
1188 case "review": {
1189 const lines = fact(need, "Lines");
1190 return { ...base, kind: "review", stake: { text: lines ?? "Your review", tone: null }, action: { label: "Review", to: need.to } };
1191 }
1192 case "runner":
1193 return {
1194 ...base,
1195 kind: "runner",
1196 stake: { text: `Waiting ${fact(need, "Waiting") ?? ""}`.trim(), tone: "warn" },
1197 action: { label: "Look", to: need.to },
1198 };
1199 // Your pull request, which meets everything its branch asks for.
1200 case "ready":
1201 return { ...base, kind: "ready", stake: { text: "Ready to merge", tone: null }, action: { label: "Merge", to: need.to } };
1202 default:
1203 return {
1204 ...base,
1205 kind: "pull_blocked",
1206 stake: REASON_STAKE[need.reason] ?? { text: "Waiting on you", tone: "warn" },
1207 action: { label: need.reason === "needs_review" ? "Review" : "Look", to: need.to },
1208 };
1209 }
1210}
1211
1212const NOTIFICATION_STAKE: Record<string, string> = {
1213 review_requested: "Review requested",
1214 assign: "Assigned to you",
1215 mention: "Mentioned",
1216 team_mention: "Team mentioned",
1217 ci_activity: "CI activity",
1218 security_alert: "Security alert",
1219 state_change: "State changed",
1220 author: "Your work",
1221 comment: "Comment",
1222 manual: "Subscribed",
1223 subscribed: "Watching",
1224};
1225
1226/**
1227 * An unread notification that is a warning (someone or something is
1228 * waiting) or a failure, in this workspace. A member without Code access
1229 * gets none about a repository. A reason this page does not know (older
1230 * ones included) reads as a plain notification.
1231 */
1232export function notificationRow(item: InboxItem, slug: string, code: boolean): AttentionRow | null {
1233 if (item.readAt != null || item.doneAt != null) return null;
1234 if (item.severity !== "warning" && item.severity !== "error") return null;
1235 const inWorkspace = (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug;
1236 if (!inWorkspace) return null;
1237 if (!code && item.repo) return null;
1238 return {
1239 key: `notification:${item.id}`,
1240 kind: "notification",
1241 title: item.body || item.title,
1242 detail: item.body ? item.title : (item.repo ?? "A notification"),
1243 stake: { text: NOTIFICATION_STAKE[item.reason] ?? "Notification", tone: item.severity === "error" ? "danger" : "warn" },
1244 action: { label: "Open", to: item.url },
1245 owner: item.actor ? { name: item.actor, agent: isAgentName(item.actor) } : null,
1246 at: Date.parse(item.updatedAt),
1247 from: "notifications",
1248 };
1249}
1250
1251export type ChatEntryLike = {
1252 channel: { id: string; kind: "channel" | "dm"; name: string | null; last_message_at?: string | null };
1253 title: string;
1254 muted: boolean;
1255 unread: number;
1256 mentions: number;
1257};
1258
1259/** A conversation with a mention of you, or a direct message you haven't read. */
1260export function chatRow(entry: ChatEntryLike, slug: string): AttentionRow | null {
1261 if (entry.muted) return null;
1262 if (!(entry.mentions > 0 || (entry.channel.kind === "dm" && entry.unread > 0))) return null;
1263 const to = entry.channel.kind === "dm" || !entry.channel.name ? `/${slug}/-/chat/dm/${entry.channel.id}` : `/${slug}/-/chat/${entry.channel.name}`;
1264 const dm = entry.channel.kind === "dm";
1265 return {
1266 key: `chat:${entry.channel.id}`,
1267 kind: "chat",
1268 title: dm ? entry.title : `#${entry.title}`,
1269 detail: dm ? "A direct message you haven't read." : "You were mentioned.",
1270 stake: {
1271 text: entry.mentions > 0 ? `${entry.mentions} ${entry.mentions === 1 ? "mention" : "mentions"}` : `${entry.unread} unread`,
1272 tone: entry.mentions > 0 ? "accent" : null,
1273 },
1274 action: { label: "Reply", to },
1275 owner: null,
1276 at: entry.channel.last_message_at ? Date.parse(entry.channel.last_message_at) : 0,
1277 from: "chat",
1278 };
1279}
1280
1281/** What Needs you and Start here show, and which sources did not answer. */
1282export type Attention = {
1283 rows: AttentionRow[];
1284 start: { row: AttentionRow; why: string } | null;
1285 /** Sources that did not answer, by name, for the card to say so. */
1286 missing: string[];
1287};
1288
1289export function attention(input: {
1290 slug: string;
1291 code: boolean;
1292 codeNeeds: CodeNeed[] | null;
1293 notifications: InboxItem[] | null;
1294 chat: ChatEntryLike[] | null;
1295}): Attention {
1296 const rows: AttentionRow[] = [];
1297 const missing: string[] = [];
1298 if (input.code) {
1299 if (input.codeNeeds) rows.push(...input.codeNeeds.map(codeRow));
1300 else missing.push("Code");
1301 }
1302 if (input.notifications) {
1303 for (const item of input.notifications) {
1304 const row = notificationRow(item, input.slug, input.code);
1305 if (row) rows.push(row);
1306 }
1307 } else missing.push("Notifications");
1308 if (input.chat) {
1309 for (const entry of input.chat) {
1310 const row = chatRow(entry, input.slug);
1311 if (row) rows.push(row);
1312 }
1313 } else missing.push("Chat");
1314 const ranked = rankAttention(rows);
1315 return { rows: ranked, start: startHere(ranked), missing };
1316}
1317
1318// --- Spend in the span ----------------------------------------------------------
1319
1320/** Money in, which the statement lists but which is not spend. */
1321const MONEY_IN: ReadonlySet<string> = new Set(["Payments", "AI credit", "Credits from g1t", "Refunds", "Tax", "Card processing fees"]);
1322
1323export type Spend = {
1324 /** The statement days counted, `YYYY-MM-DD` in UTC, first and last. */
1325 from: string;
1326 to: string;
1327 /** Usage at price over those days, in micros. */
1328 totalMicros: number;
1329 /** A line per kind of charge, as the statement names it, most first. */
1330 lines: { kind: string; micros: number; count: number }[];
1331 /** Usage at price this month so far, the top bar's and Usage's figure; null when it could not be read. */
1332 monthMicros: number | null;
1333};
1334
1335/** The UTC months (`YYYY-MM`) the span touches, oldest first: the statements Home reads. */
1336export function spanMonths(span: Pick<Span, "from" | "now">): string[] {
1337 const months: string[] = [];
1338 const first = new Date(span.from);
1339 let year = first.getUTCFullYear();
1340 let month = first.getUTCMonth();
1341 const last = new Date(span.now).toISOString().slice(0, 7);
1342 for (let i = 0; i < 3; i++) {
1343 const key = `${year}-${String(month + 1).padStart(2, "0")}`;
1344 months.push(key);
1345 if (key >= last) break;
1346 month++;
1347 if (month === 12) {
1348 month = 0;
1349 year++;
1350 }
1351 }
1352 return months;
1353}
1354
1355/**
1356 * The span's spend from the statements grouped by day: each usage line at
1357 * its price (what was charged, plus what the plan, a trial, a pool or a
1358 * discount paid of it), leaving out money in. The statement keeps whole
1359 * UTC days, so the span is counted from the start of the UTC day it began.
1360 * `statements` is the months of `spanMonths`, the current one last.
1361 * `monthMicros` is this month so far as billing's usage report counts it,
1362 * the month's usage not yet closed included: the figure Usage
1363 * shows, so Home shows no other.
1364 */
1365export function spendIn(statements: Pick<Statement, "groups" | "totals">[], span: Pick<Span, "from" | "now">, monthMicros: number | null): Spend {
1366 const from = new Date(span.from).toISOString().slice(0, 10);
1367 const to = new Date(span.now).toISOString().slice(0, 10);
1368 const byKind = new Map<string, { micros: number; count: number }>();
1369 for (const statement of statements) {
1370 for (const group of statement.groups) {
1371 if (group.key < from || group.key > to) continue;
1372 for (const line of group.lines) {
1373 if (MONEY_IN.has(line.kind)) continue;
1374 const micros = line.priceMicros ?? line.chargedMicros;
1375 const kept = byKind.get(line.kind) ?? { micros: 0, count: 0 };
1376 byKind.set(line.kind, { micros: kept.micros + micros, count: kept.count + line.count });
1377 }
1378 }
1379 }
1380 const lines = [...byKind]
1381 .map(([kind, value]) => ({ kind, ...value }))
1382 .filter((line) => line.micros > 0)
1383 .sort((a, b) => b.micros - a.micros || a.kind.localeCompare(b.kind));
1384 return {
1385 from,
1386 to,
1387 totalMicros: lines.reduce((sum, line) => sum + line.micros, 0),
1388 lines,
1389 monthMicros,
1390 };
1391}
1392
1393// --- The sentence -----------------------------------------------------------
1394
1395/**
1396 * The sentence under the heading, honest about what happened: "Since
1397 * Tuesday evening, 3 people pushed 41 commits and merged 5 changes, and
1398 * 12 changes landed." What people did comes first (commits and merges;
1399 * else what they said), then everything that landed. When nothing at all
1400 * was counted: "Quiet since Tuesday evening: nothing pushed, merged,
1401 * deployed or said." When what people did could not be read, it says so.
1402 */
1403export function spanSentence(span: Pick<Span, "words">, digest: Pick<Digest, "summary"> | null, landed: number | null): string {
1404 const lead = span.words;
1405 if (!digest) return `${lead}, what happened couldn't be read.`;
1406 const { people: count, commits, merged, said, anything, peopleRead } = digest.summary;
1407 const landedCount = landed ?? 0;
1408 if (!anything && landedCount === 0) {
1409 if (!peopleRead) return `${lead}, what people did couldn't be read.`;
1410 return `Quiet ${lead.charAt(0).toLowerCase()}${lead.slice(1)}: nothing pushed, merged, deployed or said.`;
1411 }
1412 const parts: string[] = [];
1413 if (count > 0) {
1414 if (commits > 0 || merged > 0) {
1415 const did: string[] = [];
1416 if (commits > 0) did.push(`pushed ${plural(commits, "commit")}`);
1417 if (merged > 0) did.push(`merged ${plural(merged, "change")}`);
1418 parts.push(`${people(count)} ${did.join(" and ")}`);
1419 } else if (said > 0) parts.push(`${people(count)} sent ${plural(said, "message")}`);
1420 else parts.push(`${people(count)} ${count === 1 ? "was" : "were"} active`);
1421 }
1422 if (landedCount > 0) parts.push(`${plural(landedCount, "change")} landed`);
1423 const tail = peopleRead ? "" : "; what people did couldn't be read";
1424 if (parts.length === 0) return `${lead}, work went on, but nothing landed${tail}.`;
1425 const joined = parts.length > 2 ? `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}` : parts.join(" and ");
1426 return `${lead}, ${joined}${tail}.`;
1427}
1428
1429/** "8 things need you.", or that nothing does. */
1430export function waitingSentence(total: number): string {
1431 if (total === 0) return "Nothing needs you right now.";
1432 return `${plural(total, "thing")} ${total === 1 ? "needs" : "need"} you.`;
1433}
1434
1435/** How long something has waited: "45 min", "17 h", "2 d". */
1436export function waited(at: number, now: number): string {
1437 const minutes = Math.max(0, Math.floor((now - at) / MINUTE));
1438 if (minutes < 60) return `${minutes} min`;
1439 if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h`;
1440 return `${Math.floor(minutes / (24 * 60))} d`;
1441}
1442
1443/** "3:40 PM": the time of day alone, for a row under its day's heading. */
1444export function timeOfDay(at: number, timeZone: string | null): string {
1445 return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1446}
1447
1448/** "3:40 PM" when it is the same day as `now`, else "Oct 7". */
1449export function whenShort(at: number, now: number, timeZone: string | null): string {
1450 if (dayIn(at, timeZone) === dayIn(now, timeZone)) return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1451 return now - at < 6 * DAY ? formatIn(at, timeZone, { weekday: "short", hour: "numeric" }) : shortDate(at, timeZone);
1452}
1453
1454// --- Asking g1t from Home ------------------------------------------------------------
1455
1456type AskedSpan = Pick<Span, "key" | "note" | "words" | "from" | "now">;
1457
1458/** The span as a person would say it: "since I was last here (2:12 PM)", "in the last 24 hours". */
1459function spanSaid(span: AskedSpan, timeZone: string | null): string {
1460 if (span.key === "last" && span.note == null) return `since I was last here (${whenShort(span.from, span.now, timeZone)})`;
1461 return `${span.words.charAt(0).toLowerCase()}${span.words.slice(1)}`;
1462}
1463
1464/**
1465 * Home's Summarize: what changed in the span, in plain English, as a person
1466 * would ask it. g1t is told the page and the viewer's zone, and its prompt
1467 * says how to read what shipped (services/integrations ask.rs).
1468 */
1469export function summarizeQuestion(span: AskedSpan, timeZone: string | null): string {
1470 return `Summarize what changed ${spanSaid(span, timeZone)} in plain English.`;
1471}
1472
1473/** What a change's page is, in words: "pull request #47 in acme/web", "commit f2c1aa0 in acme/web"; else its path. */
1474export function changeRef(to: string): string {
1475 const pull = to.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)/);
1476 if (pull) return `pull request #${pull[3]} in ${pull[1]}/${pull[2]}`;
1477 const commit = to.match(/^\/([^/]+)\/([^/]+)\/commit\/([0-9a-f]{7,40})/i);
1478 if (commit) return `commit ${commit[3]!.slice(0, 7)} in ${commit[1]}/${commit[2]}`;
1479 return to;
1480}
1481
1482/** A Landed row's Explain: what one change did and why, in plain English. */
1483export function explainQuestion(change: Pick<LandedChange, "kind" | "title" | "to">): string {
1484 if (change.kind === "deploy") return `What went out in this deployment (${change.to}), in plain English?`;
1485 if (change.kind === "release" || change.kind === "package") return `What's new in ${change.title} (${change.to}), in plain English?`;
1486 return `Explain ${changeRef(change.to)} in plain English: what changed, why, and is it live?`;
1487}
1488
1489/** What Home's Ask box offers to ask first, after Summarize: a label, and the question it asks. */
1490export const HOME_STARTERS: { label: string; question: string }[] = [
1491 { label: "What needs me first?", question: "What needs me first? Most urgent first, one line each on what to do." },
1492 { label: "What shipped today?", question: "What shipped today? What's live, what's still deploying, and what failed." },
1493 { label: "Who's working on what?", question: "Who's working on what right now, and is anything stuck?" },
1494];