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