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