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