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,454 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({ key: "pushes", text: `${plural(commits, "commit")} to ${plural(pushed.size, "project")}`, count: pushes, to: placeFor(slug, repos, pushed, "activity") });
409 }
410
411 // The other kinds, summed over projects: how many, and where.
412 const sum = (kind: WorkKind, pick: (repo: RepoDigest) => ActorCount[]) => {
413 let count = 0;
414 const repoIds: string[] = [];
415 for (const repo of activity.repos) {
416 const n = credit(kind, pick(repo));
417 if (n === 0) continue;
418 count += n;
419 repoIds.push(repo.repo_id);
420 }
421 return { count, repoIds };
422 };
423
424 const opened = sum("pulls", (repo) => repo.pulls.opened);
425 const merged = sum("pulls", (repo) => repo.pulls.merged);
426 const closed = sum("pulls", (repo) => repo.pulls.closed);
427 const reviews = sum("pulls", (repo) => repo.reviews);
428 const pulls = opened.count + merged.count + closed.count + reviews.count;
429 if (pulls > 0) {
430 const text = counted([
431 [opened.count, "# opened"],
432 [merged.count, "# merged"],
433 [closed.count, "# closed without merging"],
434 [reviews.count, "# reviewed"],
435 ]);
436 lines.push({ key: "pulls", text, count: pulls, to: placeFor(slug, repos, [...opened.repoIds, ...merged.repoIds, ...closed.repoIds, ...reviews.repoIds], "pulls") });
437 }
438
439 const itemsOpened = sum("items", (repo) => repo.items.opened);
440 const itemsClosed = sum("items", (repo) => repo.items.closed);
441 const comments = sum("items", (repo) => repo.comments);
442 const items = itemsOpened.count + itemsClosed.count + comments.count;
443 if (items > 0) {
444 const text = counted([
445 [itemsOpened.count, "# opened"],
446 [itemsClosed.count, "# closed"],
447 [comments.count, comments.count === 1 ? "# comment" : "# comments"],
448 ]);
449 // Work items are the workspace's: its Work list, filtered to the one project they were in, if one.
450 const ids = new Set([...itemsOpened.repoIds, ...itemsClosed.repoIds, ...comments.repoIds]);
451 const only = ids.size === 1 ? repos[[...ids][0]!] : null;
452 lines.push({ key: "items", text, count: items, to: only ? `/${slug}/-/work?repo=${encodeURIComponent(only.name)}` : `/${slug}/-/work` });
453 }
454
455 const succeeded = sum("shipped", (repo) => repo.deployments.succeeded);
456 const failed = sum("shipped", (repo) => repo.deployments.failed);
457 const releases = sum("shipped", (repo) => tallyOf(repo.releases.map((release) => release.actor)));
458 const packages = sum("shipped", (repo) => tallyOf(repo.packages.map((pkg) => pkg.actor)));
459 const shipped = succeeded.count + failed.count + releases.count + packages.count;
460 if (shipped > 0) {
461 const text = counted([
462 [succeeded.count, succeeded.count === 1 ? "# deploy" : "# deploys"],
463 [failed.count, "# failed"],
464 [releases.count, releases.count === 1 ? "# release" : "# releases"],
465 [packages.count, packages.count === 1 ? "# package version" : "# package versions"],
466 ]);
467 const deployed = [...succeeded.repoIds, ...failed.repoIds];
468 const to =
469 deployed.length > 0 ? placeFor(slug, repos, deployed, "deployments") : releases.count > 0 ? placeFor(slug, repos, releases.repoIds, "releases") : `/${slug}/-/packages`;
470 lines.push({ key: "shipped", text, count: shipped, to });
471 }
472
473 // Artifacts: made, and whose content changed.
474 if (activity.folios) {
475 const made = credit("docs", activity.folios.created);
476 const edits: ActorCount[] = [];
477 let edited = 0;
478 let allDocs = true;
479 for (const folio of activity.folios.edited) {
480 if (folio.authors.length === 0) continue;
481 edited += 1;
482 if (folio.kind !== "doc") allDocs = false;
483 for (const author of folio.authors) edits.push({ actor: author, count: 1 });
484 }
485 credit("docs", edits);
486 const what = (count: number) => plural(count, allDocs ? "doc" : "artifact");
487 if (made + edited > 0) {
488 const parts: string[] = [];
489 if (made > 0) parts.push(`${what(made)} created`);
490 if (edited > 0) parts.push(`${what(edited)} edited`);
491 lines.push({ key: "docs", text: parts.join(", "), count: made + edits.length, to: `/${slug}/-/artifacts` });
492 }
493 }
494 }
495
496 // Chat: what was said.
497 if (chat) {
498 const said = credit(
499 "chat",
500 chat.authors.map((author) => ({ actor: author.key, count: author.messages })),
501 );
502 if (said > 0) {
503 lines.push({ key: "chat", text: `${plural(said, "message")} in ${plural(chat.channels, "conversation")}`, count: said, to: `/${slug}/-/chat` });
504 }
505 }
506
507 const actors = [...rows.values()].filter((actor) => actor.count > 0).sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
508 return { lines, actors };
509}
510
511/** A tally with one of each actor, for lists that name an actor per item. */
512function tallyOf(actors: string[]): ActorCount[] {
513 const counts = new Map<string, number>();
514 for (const actor of actors) counts.set(actor, (counts.get(actor) ?? 0) + 1);
515 return [...counts].map(([actor, count]) => ({ actor, count }));
516}
517
518/** What people did, what the sentence needs, and which sources were silent. */
519export function digestOf(input: DigestInput): Digest {
520 const column = digestColumn(input);
521 const missing: string[] = [];
522 if (input.code && !input.activity) missing.push("Code");
523 if (!input.chat) missing.push("Chat");
524 let commits = 0;
525 let merged = 0;
526 for (const repo of input.activity?.repos ?? []) {
527 for (const by of repo.pushes.by) if (actorKind(by.actor, input.agentKeys) === "person") commits += by.commits;
528 merged += part(repo.pulls.merged, input.agentKeys).count;
529 }
530 const said = part(
531 (input.chat?.authors ?? []).map((author) => ({ actor: author.key, count: author.messages })),
532 input.agentKeys,
533 ).count;
534 return {
535 people: column,
536 summary: {
537 people: column.actors.filter((actor) => actor.kind === "person").length,
538 commits,
539 merged,
540 said,
541 anything: column.lines.length > 0,
542 peopleRead: input.activity != null || input.chat != null,
543 },
544 missing,
545 partial: input.activity != null && !input.activity.complete,
546 };
547}
548
549// --- What landed in the span -----------------------------------------------------
550
551/**
552 * A change that landed: a pull request merged; commits pushed straight to
553 * a default branch; a production build that went live; a release or a
554 * package version published.
555 */
556export type LandedChange = {
557 key: string;
558 kind: "merge" | "push" | "deploy" | "release" | "package";
559 title: string;
560 /** One line under it: where, and by whom. */
561 detail: string;
562 to: string;
563 at: number;
564 /** A merge's or a push's commit on the default branch, and its repository's id: what a deployment ships. */
565 sha?: string | null;
566 repoId?: string | null;
567 /** Whether it is live yet (`withShipped`); null when its project does not deploy, or it could not be read. */
568 shipped?: ShipInfo | null;
569 /** Made in a harness session (`withSessions`, or a `G1t-Session:` trailer): the agent marker, and the session. */
570 agent?: AgentMark | null;
571 /** A title that is a commit's subject: its repository (`owner/name`), which its `#12`s are read in. */
572 refsIn?: string;
573 /** A production build that failed (`landedDeploys`). */
574 failed?: boolean;
575};
576
577/** Whether a change is live: shipped by a production deployment, on its way, waiting, or the deployment after it failed. */
578export type ShipInfo = {
579 state: ShipState;
580 /** Epoch ms: when the deployment that shipped it went live. */
581 at: number | null;
582 /** The deployment (or the run that deploys it). */
583 to: string | null;
584};
585
586/** A change made in a harness session: which harness when known, and the session's page. */
587export type AgentMark = { harness: Harness | null; to: string | null };
588
589/** Every pull request that merged in the span, newest first. */
590export function landedIn(pulls: CodePull[], span: Pick<Span, "from" | "now">): LandedChange[] {
591 return pulls
592 .filter((pull) => pull.status === "merged" && within(pull.mergedAt, span))
593 .map((pull) => {
594 const agent = isAgentPull(pull);
595 const mergedBy = pull.mergedBy && pull.mergedBy !== pull.author.username ? `, merged by ${pull.mergedBy}` : "";
596 return {
597 key: `landed:${pullKey(pull.repo, pull.number)}`,
598 kind: "merge" as const,
599 title: pull.title,
600 detail: `${pull.repo.name}#${pull.number} · by ${agent ? `@${pull.author.username}` : pull.author.username}${mergedBy}`,
601 to: `/${pull.repo.namespace}/${pull.repo.name}/pull/${pull.number}`,
602 at: Date.parse(pull.mergedAt!),
603 sha: pull.mergeCommit ?? null,
604 repoId: pull.repoId ?? null,
605 };
606 })
607 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
608}
609
610/** The names behind member keys, for a line: `ana and bo`, `@margo`, `an import` for nobody. */
611function namesOf(keys: string[], names: Record<string, string>, agentKeys?: ReadonlySet<string>): string {
612 const shown = keys.map((key) => {
613 if (!key) return "an import";
614 const name = names[key] ?? (key === G1T_ACTOR ? "g1t" : "someone");
615 return actorKind(key, agentKeys) === "agent" ? `@${name}` : name;
616 });
617 return listOf([...new Set(shown)]);
618}
619
620/**
621 * Commits pushed straight to a default branch, one row per project with
622 * any: what landed without a pull request. Releases and package versions
623 * published, one row each. Pushes within the span only: the digest was
624 * asked for the span.
625 */
626export function landedFromActivity(activity: ActivityDigest | null, repos: Record<string, RepoRef>, names: Record<string, string>, slug: string, agentKeys?: ReadonlySet<string>): LandedChange[] {
627 const rows: LandedChange[] = [];
628 for (const repo of activity?.repos ?? []) {
629 const path = repos[repo.repo_id];
630 if (!path) continue;
631 const direct = repo.pushes.default_branch;
632 if (direct.count > 0 && direct.last_at) {
633 const by = direct.by.map((entry) => entry.actor);
634 rows.push({
635 key: `push:${repo.repo_id}`,
636 kind: "push",
637 title: `${plural(direct.commits, "commit")} pushed to ${path.defaultBranch}`,
638 detail: `${path.name} · ${plural(direct.count, "push", "pushes")} by ${namesOf(by, names, agentKeys)}`,
639 to: `/${path.namespace}/${path.name}/activity`,
640 at: Date.parse(direct.last_at),
641 });
642 }
643 for (const release of repo.releases) {
644 rows.push({
645 key: `release:${repo.repo_id}:${release.tag}`,
646 kind: "release",
647 title: release.name ? `${release.tag} · ${release.name}` : release.tag,
648 detail: `${path.name} · released by ${namesOf([release.actor], names, agentKeys)}`,
649 to: `/${path.namespace}/${path.name}/releases/tag/${encodeURIComponent(release.tag)}`,
650 at: Date.parse(release.at),
651 });
652 }
653 for (const pkg of repo.packages) {
654 rows.push({
655 key: `package:${repo.repo_id}:${pkg.ecosystem}:${pkg.name}:${pkg.version}`,
656 kind: "package",
657 title: `${pkg.name} ${pkg.version}`,
658 detail: `${pkg.ecosystem} package · published by ${namesOf([pkg.actor], names, agentKeys)}`,
659 to: `/${slug}/-/packages`,
660 at: Date.parse(pkg.at),
661 });
662 }
663 }
664 return rows;
665}
666
667/**
668 * Production builds of the span as landed changes, only where nothing on
669 * the list already says so: a merge or push whose live label links to the
670 * build (`shipped.to`), or whose commit it built. So a build that shipped
671 * a merge is that merge's "Live" label, not a row of its own; a redeploy,
672 * a rollback or a build of a project whose pushes weren't read is a row,
673 * and so is one that failed (`failed`). Previews stay on their project's
674 * Deployments.
675 */
676export function landedDeploys(deploys: DeployRow[], shown: readonly LandedChange[] = []): LandedChange[] {
677 const said = (row: DeployRow) =>
678 shown.some((change) => (change.shipped?.to != null && change.shipped.to === row.to) || (!!change.sha && !!row.commit && change.sha.startsWith(row.commit)));
679 return deploys
680 .filter((row) => row.kind === "production" && !said(row))
681 .map((row) => ({
682 key: `landed:${row.key}`,
683 kind: "deploy" as const,
684 title: row.outcome === "failed" ? `Production of ${row.project} failed to deploy` : `Production of ${row.project} went live`,
685 detail: `${row.commit} · by ${row.by ?? "someone"}`,
686 to: row.to,
687 at: row.at,
688 ...(row.outcome === "failed" ? { failed: true } : {}),
689 }));
690}
691
692/** Everything that landed, newest first. */
693export function landed(parts: LandedChange[][]): LandedChange[] {
694 return parts.flat().sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
695}
696
697// --- Pushes straight to a default branch, each ---------------------------------
698
699/** A push to a default branch, with the history it brought read back. */
700export type DirectPush = {
701 repoId: string;
702 repo: RepoRef;
703 push: PushRecord & { id: string };
704 /** Who pushed, by name; `someone` when it could not be read. */
705 by: string;
706};
707
708/** The sessions a commit message names in `G1t-Session:` trailers. */
709export function sessionTrailers(message: string): string[] {
710 const ids = [...message.matchAll(/^G1t-Session:\s*(ses_[0-9a-z]+)\s*$/gim)].map((match) => match[1]!.toLowerCase());
711 return [...new Set(ids)];
712}
713
714/** A commit message's first line. */
715const subject = (message: string) => message.split("\n", 1)[0]!.trim();
716
717/**
718 * Each person's push to a default branch in the span, newest first, as a
719 * landed change: its commit when it brought one ("Fix the bell's count"),
720 * else how many; the session a commit names in a `G1t-Session:` trailer
721 * as its agent mark. `history` is each repository's default branch read
722 * back from its newest push, newest first; a push whose commits are not
723 * in it (rewritten since) is left out, and so is g1t's own (a pull
724 * request landing: Landed lists the merge).
725 */
726export function pushRows(
727 pushes: DirectPush[],
728 history: Record<string, Pick<Commit, "hash" | "parents" | "message">[]>,
729 span: Pick<Span, "from" | "now">,
730 byG1t: (commit: Pick<Commit, "hash" | "parents" | "message">) => boolean = () => false,
731): LandedChange[] {
732 const rows: LandedChange[] = [];
733 for (const { repoId, repo, push, by } of pushes) {
734 if (!pushedByPerson(push) || !within(push.time, span)) continue;
735 const commits = history[repoId] ?? [];
736 const start = commits.findIndex((commit) => commit.hash === push.data.after);
737 if (start === -1) continue;
738 const brought = pushedCommits(commits.slice(start), push.data.before, byG1t);
739 if (brought.length === 0) continue;
740 const newest = brought[0]!;
741 const session = brought.flatMap((commit) => sessionTrailers(commit.message))[0] ?? null;
742 const branch = repo.defaultBranch;
743 rows.push({
744 key: `push:${repoId}:${push.id}`,
745 kind: "push",
746 title: brought.length === 1 ? subject(newest.message) || `1 commit pushed to ${branch}` : `${plural(brought.length, "commit")} pushed to ${branch}`,
747 detail: `${repo.name} · ${brought.length === 1 ? `pushed to ${branch}` : subject(newest.message)} · by ${by}`,
748 to: brought.length === 1 ? `/${repo.namespace}/${repo.name}/commit/${newest.hash}` : `/${repo.namespace}/${repo.name}/activity`,
749 at: Date.parse(push.time),
750 sha: push.data.after,
751 repoId,
752 agent: session ? { harness: null, to: sessionPath(repo.namespace, session) } : null,
753 ...(brought.length === 1 && subject(newest.message) ? { refsIn: `${repo.namespace}/${repo.name}` } : {}),
754 });
755 }
756 return rows;
757}
758
759// --- Shipped: merge to deploy --------------------------------------------------
760
761/**
762 * Each merge and push with whether it is live yet, from what deployments
763 * recorded as production deployed (`shipped`). A project that does not
764 * deploy says nothing; a change deployments did not answer for keeps none.
765 */
766export function withShipped(rows: LandedChange[], answers: ShippedRepo[] | null): LandedChange[] {
767 if (!answers) return rows;
768 const byRepo = new Map(answers.map((answer) => [answer.repo_id, answer]));
769 return rows.map((row) => {
770 if (!row.sha || !row.repoId || (row.kind !== "merge" && row.kind !== "push")) return row;
771 const answer = byRepo.get(row.repoId);
772 const commit = answer?.deploys ? answer.commits.find((c) => c.sha === row.sha) : null;
773 if (!commit) return row;
774 return { ...row, shipped: { state: commit.state, at: commit.deployed_at ? Date.parse(commit.deployed_at) : null, to: commit.url } };
775 });
776}
777
778/** What to ask deployments: each repository's merges and pushes with their commit and when they landed. */
779export function shippedAsks(rows: LandedChange[]): { repo_id: string; commits: { sha: string; landed_at: string }[] }[] {
780 const byRepo = new Map<string, { sha: string; landed_at: string }[]>();
781 for (const row of rows) {
782 if (!row.sha || !row.repoId || (row.kind !== "merge" && row.kind !== "push")) continue;
783 const list = byRepo.get(row.repoId) ?? [];
784 list.push({ sha: row.sha, landed_at: new Date(row.at).toISOString() });
785 byRepo.set(row.repoId, list);
786 }
787 return [...byRepo].map(([repo_id, commits]) => ({ repo_id, commits }));
788}
789
790/** How long something took, short: "1 min", "45 min", "3 h", "2 d". */
791function took(ms: number): string {
792 const minutes = Math.max(1, Math.round(ms / MINUTE));
793 if (minutes < 60) return `${minutes} min`;
794 const hours = Math.round(minutes / 60);
795 if (hours < 48) return `${hours} h`;
796 return `${Math.round(hours / 24)} d`;
797}
798
799/** "Live 9 min after merge", "Waiting to deploy", "Deploying", "Deploy failed". */
800export function shippedLabel(ship: ShipInfo, row: Pick<LandedChange, "kind" | "at">): string {
801 switch (ship.state) {
802 case "live":
803 return ship.at != null ? `Live ${took(ship.at - row.at)} after ${row.kind === "merge" ? "merge" : "push"}` : "Live";
804 case "deploying":
805 return "Deploying";
806 case "failed":
807 return "Deploy failed";
808 default:
809 return "Waiting to deploy";
810 }
811}
812
813// --- Done with an agent --------------------------------------------------------
814
815/**
816 * Each merged pull request with the harness session that made it, when
817 * work tied one to it (`pullSessions`): the first, by when it started.
818 */
819export function withSessions(rows: LandedChange[], sessions: { repo: RepoPath; pulls: PullSessions[] }[] | null): LandedChange[] {
820 if (!sessions) return rows;
821 const found = new Map<string, AgentMark>();
822 for (const { repo, pulls } of sessions) {
823 for (const pull of pulls) {
824 const first = pull.sessions[0];
825 if (first) found.set(`landed:${pullKey(repo, pull.number)}`, { harness: first.harness, to: sessionPath(repo.namespace, first.id) });
826 }
827 }
828 return rows.map((row) => (row.agent || !found.has(row.key) ? row : { ...row, agent: found.get(row.key)! }));
829}
830
831/** The agent mark's words: "Made in a Claude Code session", or "Made in a session". */
832export function agentLabel(mark: AgentMark): string {
833 return mark.harness ? `Made in a ${HARNESS_NAMES[mark.harness] ?? "harness"} session` : "Made in a session";
834}
835
836// --- Day by day ----------------------------------------------------------------
837
838/** What landed on one day, newest first: "Today", "Yesterday", "Mon, Oct 12". */
839export type LandedDay = { key: string; label: string; rows: LandedChange[] };
840
841/** What landed, by the day it landed in the reader's time zone, newest day first. */
842export function landedByDay(rows: LandedChange[], now: number, timeZone: string | null): LandedDay[] {
843 const days: LandedDay[] = [];
844 const today = dayIn(now, timeZone);
845 const yesterday = dayIn(now - DAY, timeZone);
846 for (const row of [...rows].sort((a, b) => b.at - a.at || a.key.localeCompare(b.key))) {
847 const key = dayIn(row.at, timeZone);
848 let day = days.find((d) => d.key === key);
849 if (!day) {
850 const label = key === today ? "Today" : key === yesterday ? "Yesterday" : formatIn(row.at, timeZone, { weekday: "short", month: "short", day: "numeric" });
851 day = { key, label, rows: [] };
852 days.push(day);
853 }
854 day.rows.push(row);
855 }
856 return days;
857}
858
859// --- While you were away -------------------------------------------------------
860
861/** Something that settled by itself in the span: what it was, why it settled, where. */
862export type SettledRow = { key: string; title: string; why: string; where: string | null; to: string; at: number };
863
864/** What g1t settled for you, what shipped, and what still needs you, in the span. */
865export type Away = {
866 settled: SettledRow[];
867 /** Merges and pushes in the span that went live, are waiting, deploying, or whose deployment failed. */
868 shipped: number;
869 waiting: number;
870 deploying: number;
871 failed: number;
872 /** Rows in Where you're needed. */
873 needs: number;
874};
875
876/**
877 * Your notifications that settled by themselves in the span (a later run
878 * passed, it merged, it deployed), newest first; one marked done by hand
879 * is yours, not g1t's. Only this workspace's, and none about a repository
880 * for a member without Code access.
881 */
882export function settledIn(items: InboxItem[] | null, slug: string, code: boolean, span: Pick<Span, "from" | "now">): SettledRow[] {
883 return (items ?? [])
884 .filter((item) => item.doneAt != null && settledLine(item) && within(item.doneAt, span))
885 .filter((item) => (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug && (code || !item.repo))
886 .map((item) => ({
887 key: `settled:${item.id}`,
888 // A work item's or pull request's own title; else the entry's ("CI failed on main in acme/web").
889 title: item.number != null ? item.body || item.title : item.title,
890 why: settledLine(item),
891 where: item.repo ? `${item.repo}${item.number != null ? `#${item.number}` : ""}` : null,
892 to: item.url,
893 at: Date.parse(item.doneAt!),
894 }))
895 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
896}
897
898export function awayOf(input: { settled: SettledRow[]; landed: LandedChange[] | null; needs: number }): Away {
899 const count = (state: ShipState) => (input.landed ?? []).filter((row) => row.shipped?.state === state).length;
900 return { settled: input.settled, shipped: count("live"), waiting: count("waiting"), deploying: count("deploying"), failed: count("failed"), needs: input.needs };
901}
902
903/** A deployment's maker as a member key: an id becomes `user:<id>`, a key stays as it is. */
904export function deployActorKey(createdBy: string | null | undefined): string | null {
905 const by = (createdBy ?? "").trim();
906 if (!by) return null;
907 return /^(user|agent):/.test(by) ? by : `user:${by}`;
908}
909
910/** A build that finished in the span. */
911export type DeployRow = {
912 key: string;
913 project: string;
914 kind: Deployment["kind"];
915 /** `live`: built and served (it may have been replaced since); `failed`: it did not build. */
916 outcome: "live" | "failed";
917 commit: string;
918 branch: string | null;
919 at: number;
920 to: string;
921 /** Who made it, as a name (`@g1t` for g1t itself); null when the deployment does not say. */
922 by: string | null;
923};
924
925/**
926 * Builds that finished in the span, newest first: production builds each,
927 * and previews too. A build that went live and was replaced since still
928 * went live. Skipped builds are left out.
929 */
930export function deploysIn(projects: { slug: string; deployments: Deployment[] }[], workspace: string, span: Pick<Span, "from" | "now">, names: Record<string, string> = {}, agentKeys?: ReadonlySet<string>): DeployRow[] {
931 const rows: DeployRow[] = [];
932 for (const project of projects) {
933 for (const deploy of project.deployments) {
934 // Who made it: the deployment names them by id, so it reads as a name, or as someone when identity doesn't know it.
935 const key = deployActorKey(deploy.createdBy);
936 const ended = deploy.finishedAt ?? null;
937 if (!within(ended, span)) continue;
938 const outcome = deploy.status === "failed" ? "failed" : deploy.status === "ready" || deploy.status === "replaced" || deploy.status === "down" ? "live" : null;
939 if (!outcome) continue;
940 rows.push({
941 key: `deploy:${project.slug}:${deploy.id}`,
942 project: project.slug,
943 kind: deploy.kind,
944 outcome,
945 commit: deploy.commit.slice(0, 7),
946 branch: deploy.branch,
947 at: Date.parse(ended!),
948 to: `/${workspace}/${project.slug}/deployments/${deploy.id}`,
949 by: key ? namesOf([key], names, agentKeys) : null,
950 });
951 }
952 }
953 return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
954}
955
956// --- Running now ----------------------------------------------------------------
957
958/** Something going right now: a workflow run or a build. */
959export type RunningRow = {
960 key: string;
961 kind: "workflow" | "deploy";
962 title: string;
963 /** One line: who and where. */
964 detail: string;
965 /** "Running", "Queued", "Building". */
966 status: string;
967 /** Epoch ms: when it started. */
968 at: number;
969 to: string;
970};
971
972/** Builds queued or going now, one per project (its newest). */
973export function runningDeploys(overview: ProjectDeploys[], slug: string): RunningRow[] {
974 return overview.flatMap((project) => {
975 const latest = project.latest;
976 if (!latest || (latest.status !== "queued" && latest.status !== "building")) return [];
977 return [
978 {
979 key: `deploy:${project.slug}:${latest.id}`,
980 kind: "deploy" as const,
981 title: `${latest.kind === "production" ? "Production" : `Preview of ${latest.branch ?? "a branch"}`} of ${project.slug}`,
982 detail: `${latest.commit.slice(0, 7)} · by ${latest.createdBy}`,
983 status: latest.status === "queued" ? "Queued" : "Building",
984 at: Date.parse(latest.createdAt),
985 to: `/${slug}/${project.slug}/deployments/${latest.id}`,
986 },
987 ];
988 });
989}
990
991const RUN_STATUS: Partial<Record<WorkflowRun["status"], string>> = {
992 pending: "Queued",
993 queued: "Queued",
994 action_required: "Needs approval",
995 in_progress: "Running",
996 waiting: "Waiting",
997};
998
999/** Workflow runs not finished, in the projects read: queued, waiting, running, or waiting for approval. */
1000export function runningWorkflows(projects: { repo: RepoPath; runs: WorkflowRun[] }[]): RunningRow[] {
1001 return projects.flatMap(({ repo, runs }) =>
1002 runs.flatMap((run) => {
1003 const status = RUN_STATUS[run.status];
1004 if (!status) return [];
1005 return [
1006 {
1007 key: `workflow:${repo.namespace}/${repo.name}:${run.id}`.toLowerCase(),
1008 kind: "workflow" as const,
1009 title: run.title ? `${run.name}: ${run.title}` : run.name,
1010 detail: `${repo.namespace}/${repo.name} ${run.ref.replace(/^refs\/heads\//, "")}${run.actor ? ` · by ${run.actor}` : ""}`,
1011 status,
1012 at: Date.parse(run.startedAt ?? run.createdAt),
1013 to: `/${repo.namespace}/${repo.name}/actions/runs/${run.id}`,
1014 },
1015 ];
1016 }),
1017 );
1018}
1019
1020/** Everything running, longest-going first within each kind: workflow runs, then builds. */
1021export function running(parts: RunningRow[][]): RunningRow[] {
1022 const order = { workflow: 0, deploy: 1 } as const;
1023 return parts.flat().sort((a, b) => order[a.kind] - order[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
1024}
1025
1026// --- Needs you ------------------------------------------------------------------
1027
1028/**
1029 * What a row is. Tiers, most pressing first:
1030 * 0. production is down to an older build (`deploy`);
1031 * 1. a change that can't land until someone acts on it (`pull_blocked`);
1032 * 2. something waiting only for you (a review, an invitation, your pull
1033 * request that is ready to merge);
1034 * 3. a job waiting for a runner that is not there;
1035 * 4. an unread notification that is a warning or a failure;
1036 * 5. a mention or a direct message.
1037 */
1038export type AttentionKind = "deploy" | "pull_blocked" | "review" | "invitation" | "ready" | "runner" | "notification" | "chat";
1039
1040export const TIER: Record<AttentionKind, number> = {
1041 deploy: 0,
1042 pull_blocked: 1,
1043 review: 2,
1044 invitation: 2,
1045 ready: 2,
1046 runner: 3,
1047 notification: 4,
1048 chat: 5,
1049};
1050
1051export type Stake = { text: string; tone: "danger" | "warn" | "accent" | null };
1052
1053/** One row of Needs you. */
1054export type AttentionRow = {
1055 key: string;
1056 kind: AttentionKind;
1057 title: string;
1058 /** One line: what it is and where. */
1059 detail: string;
1060 /** What is at stake, in a few words. */
1061 stake: Stake | null;
1062 /** The action, right there. */
1063 action: { label: string; to: string };
1064 /** Who is on it: the person who asked, or g1t on older rows. */
1065 owner: { name: string; agent: boolean } | null;
1066 /** Epoch ms: when it started waiting. */
1067 at: number;
1068 /** Where it came from, for a member without Code access never `code`. */
1069 from: "code" | "notifications" | "chat";
1070};
1071
1072/**
1073 * Most pressing first: by tier, then what has waited longest, then by key
1074 * so the order never depends on the order rows were read. One of each key,
1075 * and one of each place: a notification about a pull request already on
1076 * the list is left out.
1077 */
1078export function rankAttention(rows: AttentionRow[]): AttentionRow[] {
1079 const sorted = [...rows].sort((a, b) => TIER[a.kind] - TIER[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
1080 const keys = new Set<string>();
1081 const places = new Set<string>();
1082 return sorted.filter((row) => {
1083 const place = row.action.to.split(/[?#]/)[0];
1084 if (keys.has(row.key) || (row.kind === "notification" && places.has(place))) return false;
1085 keys.add(row.key);
1086 places.add(place);
1087 return true;
1088 });
1089}
1090
1091/** Start here: the first row by `rankAttention`, with why it was picked. */
1092export function startHere(ranked: AttentionRow[]): { row: AttentionRow; why: string } | null {
1093 const row = ranked[0];
1094 if (!row) return null;
1095 const sameTier = ranked.filter((other) => TIER[other.kind] === TIER[row.kind]).length;
1096 const tail = sameTier > 1 ? ` Of the ${sameTier} like it, it has waited longest.` : "";
1097 return { row, why: `${WHY[row.kind]}${tail}` };
1098}
1099
1100const WHY: Record<AttentionKind, string> = {
1101 deploy: "Production is serving an older build until this is fixed, so it comes before anything else.",
1102 pull_blocked: "This change can't land until someone fixes it.",
1103 review: "You were asked by name, so it waits for your verdict.",
1104 invitation: "It is addressed to you; no one else can answer it.",
1105 ready: "Everything it needs is met; it lands when you merge it.",
1106 runner: "A job is waiting for a runner that is not there.",
1107 notification: "It is the most pressing unread notification.",
1108 chat: "Nothing else is waiting, and this is the oldest message for you.",
1109};
1110
1111// --- Rows from each source ----------------------------------------------------
1112
1113/** A Code Overview need row, as Home reads it (lib/mission-control.ts `NeedRow`). */
1114export type CodeNeed = {
1115 key: string;
1116 reason: string;
1117 repo: RepoPath | null;
1118 ref: string | null;
1119 title: string;
1120 ask: string;
1121 by: { name: string; agent: boolean } | null;
1122 at: number;
1123 to: string;
1124 facts: { label: string; value: string; tone: string | null }[];
1125};
1126
1127const fact = (need: CodeNeed, label: string) => need.facts.find((f) => f.label === label)?.value ?? null;
1128
1129const REASON_STAKE: Record<string, Stake> = {
1130 blocking: { text: "Blocking", tone: "danger" },
1131 checks_failing: { text: "Checks failing", tone: "danger" },
1132 needs_review: { text: "Needs a verdict", tone: "warn" },
1133 stalled: { text: "Stalled", tone: "warn" },
1134};
1135
1136/** A Code need (failed deploy, pull request, review, invitation, runner) as a row. */
1137export function codeRow(need: CodeNeed): AttentionRow {
1138 const prefix = need.key.split(":")[0];
1139 const where = need.repo ? `${need.repo.namespace}/${need.repo.name}${need.ref ? ` ${need.ref}` : ""}` : null;
1140 const detail = where ? `${where} · ${need.ask}` : need.ask;
1141 const owner = need.by;
1142 const base = { key: need.key, title: need.title, detail, owner, at: need.at, from: "code" as const };
1143 switch (prefix) {
1144 case "deploy":
1145 return {
1146 ...base,
1147 kind: "deploy",
1148 stake: { text: fact(need, "Production") === "Not live yet" ? "Not live yet" : "Production on an older build", tone: "danger" },
1149 action: { label: "See the build", to: need.to },
1150 };
1151 case "invitation":
1152 return { ...base, kind: "invitation", stake: { text: `${fact(need, "Role") ?? "A"} role`, tone: null }, action: { label: "Respond", to: need.to } };
1153 case "review": {
1154 const lines = fact(need, "Lines");
1155 return { ...base, kind: "review", stake: { text: lines ?? "Your review", tone: null }, action: { label: "Review", to: need.to } };
1156 }
1157 case "runner":
1158 return { ...base, kind: "runner", stake: { text: `Waiting ${fact(need, "Waiting") ?? ""}`.trim(), tone: "warn" }, action: { label: "Look", to: need.to } };
1159 // Your pull request, which meets everything its branch asks for.
1160 case "ready":
1161 return { ...base, kind: "ready", stake: { text: "Ready to merge", tone: null }, action: { label: "Merge", to: need.to } };
1162 default:
1163 return {
1164 ...base,
1165 kind: "pull_blocked",
1166 stake: REASON_STAKE[need.reason] ?? { text: "Waiting on you", tone: "warn" },
1167 action: { label: need.reason === "needs_review" ? "Review" : "Look", to: need.to },
1168 };
1169 }
1170}
1171
1172const NOTIFICATION_STAKE: Record<string, string> = {
1173 review_requested: "Review requested",
1174 assign: "Assigned to you",
1175 mention: "Mentioned",
1176 team_mention: "Team mentioned",
1177 ci_activity: "CI activity",
1178 security_alert: "Security alert",
1179 state_change: "State changed",
1180 author: "Your work",
1181 comment: "Comment",
1182 manual: "Subscribed",
1183 subscribed: "Watching",
1184};
1185
1186/**
1187 * An unread notification that is a warning (someone or something is
1188 * waiting) or a failure, in this workspace. A member without Code access
1189 * gets none about a repository. A reason this page does not know (older
1190 * ones included) reads as a plain notification.
1191 */
1192export function notificationRow(item: InboxItem, slug: string, code: boolean): AttentionRow | null {
1193 if (item.readAt != null || item.doneAt != null) return null;
1194 if (item.severity !== "warning" && item.severity !== "error") return null;
1195 const inWorkspace = (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug;
1196 if (!inWorkspace) return null;
1197 if (!code && item.repo) return null;
1198 return {
1199 key: `notification:${item.id}`,
1200 kind: "notification",
1201 title: item.body || item.title,
1202 detail: item.body ? item.title : (item.repo ?? "A notification"),
1203 stake: { text: NOTIFICATION_STAKE[item.reason] ?? "Notification", tone: item.severity === "error" ? "danger" : "warn" },
1204 action: { label: "Open", to: item.url },
1205 owner: item.actor ? { name: item.actor, agent: isAgentName(item.actor) } : null,
1206 at: Date.parse(item.updatedAt),
1207 from: "notifications",
1208 };
1209}
1210
1211export type ChatEntryLike = {
1212 channel: { id: string; kind: "channel" | "dm"; name: string | null; last_message_at?: string | null };
1213 title: string;
1214 muted: boolean;
1215 unread: number;
1216 mentions: number;
1217};
1218
1219/** A conversation with a mention of you, or a direct message you haven't read. */
1220export function chatRow(entry: ChatEntryLike, slug: string): AttentionRow | null {
1221 if (entry.muted) return null;
1222 if (!(entry.mentions > 0 || (entry.channel.kind === "dm" && entry.unread > 0))) return null;
1223 const to = entry.channel.kind === "dm" || !entry.channel.name ? `/${slug}/-/chat/dm/${entry.channel.id}` : `/${slug}/-/chat/${entry.channel.name}`;
1224 const dm = entry.channel.kind === "dm";
1225 return {
1226 key: `chat:${entry.channel.id}`,
1227 kind: "chat",
1228 title: dm ? entry.title : `#${entry.title}`,
1229 detail: dm ? "A direct message you haven't read." : "You were mentioned.",
1230 stake: {
1231 text: entry.mentions > 0 ? `${entry.mentions} ${entry.mentions === 1 ? "mention" : "mentions"}` : `${entry.unread} unread`,
1232 tone: entry.mentions > 0 ? "accent" : null,
1233 },
1234 action: { label: "Reply", to },
1235 owner: null,
1236 at: entry.channel.last_message_at ? Date.parse(entry.channel.last_message_at) : 0,
1237 from: "chat",
1238 };
1239}
1240
1241/** What Needs you and Start here show, and which sources did not answer. */
1242export type Attention = {
1243 rows: AttentionRow[];
1244 start: { row: AttentionRow; why: string } | null;
1245 /** Sources that did not answer, by name, for the card to say so. */
1246 missing: string[];
1247};
1248
1249export function attention(input: {
1250 slug: string;
1251 code: boolean;
1252 codeNeeds: CodeNeed[] | null;
1253 notifications: InboxItem[] | null;
1254 chat: ChatEntryLike[] | null;
1255}): Attention {
1256 const rows: AttentionRow[] = [];
1257 const missing: string[] = [];
1258 if (input.code) {
1259 if (input.codeNeeds) rows.push(...input.codeNeeds.map(codeRow));
1260 else missing.push("Code");
1261 }
1262 if (input.notifications) {
1263 for (const item of input.notifications) {
1264 const row = notificationRow(item, input.slug, input.code);
1265 if (row) rows.push(row);
1266 }
1267 } else missing.push("Notifications");
1268 if (input.chat) {
1269 for (const entry of input.chat) {
1270 const row = chatRow(entry, input.slug);
1271 if (row) rows.push(row);
1272 }
1273 } else missing.push("Chat");
1274 const ranked = rankAttention(rows);
1275 return { rows: ranked, start: startHere(ranked), missing };
1276}
1277
1278// --- Spend in the span ----------------------------------------------------------
1279
1280/** Money in, which the statement lists but which is not spend. */
1281const MONEY_IN: ReadonlySet<string> = new Set(["Payments", "AI credit", "Credits from g1t", "Refunds", "Tax", "Card processing fees"]);
1282
1283export type Spend = {
1284 /** The statement days counted, `YYYY-MM-DD` in UTC, first and last. */
1285 from: string;
1286 to: string;
1287 /** Usage at price over those days, in micros. */
1288 totalMicros: number;
1289 /** A line per kind of charge, as the statement names it, most first. */
1290 lines: { kind: string; micros: number; count: number }[];
1291 /** Usage at price this month so far, the top bar's and Usage's figure; null when it could not be read. */
1292 monthMicros: number | null;
1293};
1294
1295/** The UTC months (`YYYY-MM`) the span touches, oldest first: the statements Home reads. */
1296export function spanMonths(span: Pick<Span, "from" | "now">): string[] {
1297 const months: string[] = [];
1298 const first = new Date(span.from);
1299 let year = first.getUTCFullYear();
1300 let month = first.getUTCMonth();
1301 const last = new Date(span.now).toISOString().slice(0, 7);
1302 for (let i = 0; i < 3; i++) {
1303 const key = `${year}-${String(month + 1).padStart(2, "0")}`;
1304 months.push(key);
1305 if (key >= last) break;
1306 month++;
1307 if (month === 12) {
1308 month = 0;
1309 year++;
1310 }
1311 }
1312 return months;
1313}
1314
1315/**
1316 * The span's spend from the statements grouped by day: each usage line at
1317 * its price (what was charged, plus what the plan, a trial, a pool or a
1318 * discount paid of it), leaving out money in. The statement keeps whole
1319 * UTC days, so the span is counted from the start of the UTC day it began.
1320 * `statements` is the months of `spanMonths`, the current one last.
1321 * `monthMicros` is this month so far as billing's usage report counts it,
1322 * the month's usage not yet closed included: the figure Usage
1323 * shows, so Home shows no other.
1324 */
1325export function spendIn(statements: Pick<Statement, "groups" | "totals">[], span: Pick<Span, "from" | "now">, monthMicros: number | null): Spend {
1326 const from = new Date(span.from).toISOString().slice(0, 10);
1327 const to = new Date(span.now).toISOString().slice(0, 10);
1328 const byKind = new Map<string, { micros: number; count: number }>();
1329 for (const statement of statements) {
1330 for (const group of statement.groups) {
1331 if (group.key < from || group.key > to) continue;
1332 for (const line of group.lines) {
1333 if (MONEY_IN.has(line.kind)) continue;
1334 const micros = line.priceMicros ?? line.chargedMicros;
1335 const kept = byKind.get(line.kind) ?? { micros: 0, count: 0 };
1336 byKind.set(line.kind, { micros: kept.micros + micros, count: kept.count + line.count });
1337 }
1338 }
1339 }
1340 const lines = [...byKind]
1341 .map(([kind, value]) => ({ kind, ...value }))
1342 .filter((line) => line.micros > 0)
1343 .sort((a, b) => b.micros - a.micros || a.kind.localeCompare(b.kind));
1344 return {
1345 from,
1346 to,
1347 totalMicros: lines.reduce((sum, line) => sum + line.micros, 0),
1348 lines,
1349 monthMicros,
1350 };
1351}
1352
1353// --- The sentence -----------------------------------------------------------
1354
1355/**
1356 * The sentence under the heading, honest about what happened: "Since
1357 * Tuesday evening, 3 people pushed 41 commits and merged 5 changes, and
1358 * 12 changes landed." What people did comes first (commits and merges;
1359 * else what they said), then everything that landed. When nothing at all
1360 * was counted: "Quiet since Tuesday evening: nothing pushed, merged,
1361 * deployed or said." When what people did could not be read, it says so.
1362 */
1363export function spanSentence(span: Pick<Span, "words">, digest: Pick<Digest, "summary"> | null, landed: number | null): string {
1364 const lead = span.words;
1365 if (!digest) return `${lead}, what happened couldn't be read.`;
1366 const { people: count, commits, merged, said, anything, peopleRead } = digest.summary;
1367 const landedCount = landed ?? 0;
1368 if (!anything && landedCount === 0) {
1369 if (!peopleRead) return `${lead}, what people did couldn't be read.`;
1370 return `Quiet ${lead.charAt(0).toLowerCase()}${lead.slice(1)}: nothing pushed, merged, deployed or said.`;
1371 }
1372 const parts: string[] = [];
1373 if (count > 0) {
1374 if (commits > 0 || merged > 0) {
1375 const did: string[] = [];
1376 if (commits > 0) did.push(`pushed ${plural(commits, "commit")}`);
1377 if (merged > 0) did.push(`merged ${plural(merged, "change")}`);
1378 parts.push(`${people(count)} ${did.join(" and ")}`);
1379 } else if (said > 0) parts.push(`${people(count)} sent ${plural(said, "message")}`);
1380 else parts.push(`${people(count)} ${count === 1 ? "was" : "were"} active`);
1381 }
1382 if (landedCount > 0) parts.push(`${plural(landedCount, "change")} landed`);
1383 const tail = peopleRead ? "" : "; what people did couldn't be read";
1384 if (parts.length === 0) return `${lead}, work went on, but nothing landed${tail}.`;
1385 const joined = parts.length > 2 ? `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}` : parts.join(" and ");
1386 return `${lead}, ${joined}${tail}.`;
1387}
1388
1389/** "8 things need you.", or that nothing does. */
1390export function waitingSentence(total: number): string {
1391 if (total === 0) return "Nothing needs you right now.";
1392 return `${plural(total, "thing")} ${total === 1 ? "needs" : "need"} you.`;
1393}
1394
1395/** How long something has waited: "45 min", "17 h", "2 d". */
1396export function waited(at: number, now: number): string {
1397 const minutes = Math.max(0, Math.floor((now - at) / MINUTE));
1398 if (minutes < 60) return `${minutes} min`;
1399 if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h`;
1400 return `${Math.floor(minutes / (24 * 60))} d`;
1401}
1402
1403/** "3:40 PM": the time of day alone, for a row under its day's heading. */
1404export function timeOfDay(at: number, timeZone: string | null): string {
1405 return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1406}
1407
1408/** "3:40 PM" when it is the same day as `now`, else "Oct 7". */
1409export function whenShort(at: number, now: number, timeZone: string | null): string {
1410 if (dayIn(at, timeZone) === dayIn(now, timeZone)) return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1411 return now - at < 6 * DAY ? formatIn(at, timeZone, { weekday: "short", hour: "numeric" }) : shortDate(at, timeZone);
1412}
1413
1414// --- Asking g1t from Home ------------------------------------------------------------
1415
1416type AskedSpan = Pick<Span, "key" | "note" | "words" | "from" | "now">;
1417
1418/** The span as a person would say it: "since I was last here (2:12 PM)", "in the last 24 hours". */
1419function spanSaid(span: AskedSpan, timeZone: string | null): string {
1420 if (span.key === "last" && span.note == null) return `since I was last here (${whenShort(span.from, span.now, timeZone)})`;
1421 return `${span.words.charAt(0).toLowerCase()}${span.words.slice(1)}`;
1422}
1423
1424/**
1425 * Home's Summarize: what changed in the span, in plain English, as a person
1426 * would ask it. g1t is told the page and the viewer's zone, and its prompt
1427 * says how to read what shipped (services/integrations ask.rs).
1428 */
1429export function summarizeQuestion(span: AskedSpan, timeZone: string | null): string {
1430 return `Summarize what changed ${spanSaid(span, timeZone)} in plain English.`;
1431}
1432
1433/** What a change's page is, in words: "pull request #47 in acme/web", "commit f2c1aa0 in acme/web"; else its path. */
1434export function changeRef(to: string): string {
1435 const pull = to.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)/);
1436 if (pull) return `pull request #${pull[3]} in ${pull[1]}/${pull[2]}`;
1437 const commit = to.match(/^\/([^/]+)\/([^/]+)\/commit\/([0-9a-f]{7,40})/i);
1438 if (commit) return `commit ${commit[3]!.slice(0, 7)} in ${commit[1]}/${commit[2]}`;
1439 return to;
1440}
1441
1442/** A Landed row's Explain: what one change did and why, in plain English. */
1443export function explainQuestion(change: Pick<LandedChange, "kind" | "title" | "to">): string {
1444 if (change.kind === "deploy") return `What went out in this deployment (${change.to}), in plain English?`;
1445 if (change.kind === "release" || change.kind === "package") return `What's new in ${change.title} (${change.to}), in plain English?`;
1446 return `Explain ${changeRef(change.to)} in plain English: what changed, why, and is it live?`;
1447}
1448
1449/** What Home's Ask box offers to ask first, after Summarize: a label, and the question it asks. */
1450export const HOME_STARTERS: { label: string; question: string }[] = [
1451 { label: "What needs me first?", question: "What needs me first? Most urgent first, one line each on what to do." },
1452 { label: "What shipped today?", question: "What shipped today? What's live, what's still deploying, and what failed." },
1453 { label: "Who's working on what?", question: "Who's working on what right now, and is anything stuck?" },
1454];