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.

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