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