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