Skip to content
1,122 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 Deployment,
15 InboxItem,
16 Memory,
17 ProjectDeploys,
18 Pull,
19 RepoDigest,
20 RepoPath,
21 Statement,
22 WorkflowRun,
23} from "@g1t/contracts";
24
25const MINUTE = 60_000;
26const HOUR = 60 * MINUTE;
27const DAY = 24 * HOUR;
28
29/** A day's date in a time zone, as `YYYY-MM-DD`; UTC when the zone is unknown or invalid. */
30export function dayIn(at: number, timeZone: string | null): string {
31 try {
32 return new Intl.DateTimeFormat("en-CA", { year: "numeric", month: "2-digit", day: "2-digit", timeZone: timeZone || "UTC" }).format(at);
33 } catch {
34 return new Date(at).toISOString().slice(0, 10);
35 }
36}
37
38/** The hour of the day (0–23) in a time zone; UTC when it is unknown. */
39export function hourIn(at: number, timeZone: string | null): number {
40 const read = (zone: string) => Number(new Intl.DateTimeFormat("en-US", { hour: "numeric", hourCycle: "h23", timeZone: zone }).format(at)) % 24;
41 try {
42 return read(timeZone || "UTC");
43 } catch {
44 return read("UTC");
45 }
46}
47
48function formatIn(at: number, timeZone: string | null, options: Intl.DateTimeFormatOptions): string {
49 try {
50 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: timeZone || "UTC" }).format(at);
51 } catch {
52 return new Intl.DateTimeFormat("en-US", { ...options, timeZone: "UTC" }).format(at);
53 }
54}
55
56/** "Oct 9", in the reader's time zone. */
57export function shortDate(at: number, timeZone: string | null): string {
58 return formatIn(at, timeZone, { month: "short", day: "numeric" });
59}
60
61// --- The span -----------------------------------------------------------------
62
63/** Which span "what happened" covers: since your last visit, or a fixed one. */
64export type WindowKey = "last" | "24h" | "7d";
65
66export const WINDOWS: { key: WindowKey; label: string }[] = [
67 { key: "last", label: "Since last visit" },
68 { key: "24h", label: "Last 24 hours" },
69 { key: "7d", label: "Last 7 days" },
70];
71
72/** The furthest back "since your last visit" looks. */
73export const MAX_AWAY_DAYS = 14;
74
75/** A `?window=` value, or the default: since your last visit. */
76export function parseWindow(value: string | null | undefined): WindowKey {
77 return value === "24h" || value === "7d" ? value : "last";
78}
79
80export type Span = {
81 key: WindowKey;
82 /** Epoch ms: the start of the span. */
83 from: number;
84 now: number;
85 /** "Since Tuesday evening", "In the last 24 hours". */
86 words: string;
87 /** How long it covers: "3 days", "45 minutes". */
88 length: string;
89 /**
90 * Why "since your last visit" covers something else: `first` when there
91 * is no visit on record (it shows the last 24 hours), `capped` when the
92 * last one was longer ago than MAX_AWAY_DAYS, `unknown` when it could
93 * not be read (it shows the last 24 hours).
94 */
95 note: "first" | "capped" | "unknown" | null;
96};
97
98const plural = (n: number, one: string, many = `${one}s`) => `${n.toLocaleString("en-US")} ${n === 1 ? one : many}`;
99
100/** How long a stretch of time is, roughly: "a moment", "40 minutes", "3 hours", "3 days", "2 weeks". */
101export function duration(ms: number): string {
102 const minutes = Math.floor(Math.max(0, ms) / MINUTE);
103 if (minutes < 1) return "a moment";
104 if (minutes < 60) return plural(minutes, "minute");
105 const hours = Math.floor(minutes / 60);
106 if (hours < 24) return plural(hours, "hour");
107 const days = Math.floor(hours / 24);
108 if (days < 14) return plural(days, "day");
109 return plural(Math.floor(days / 7), "week");
110}
111
112type Part = "night" | "morning" | "afternoon" | "evening";
113
114/**
115 * When `from` was, in words, from `now`: "a moment ago", "40 minutes ago",
116 * "2 hours ago", "this morning", "last night", "yesterday evening",
117 * "Tuesday evening", "Oct 2". The small hours belong to the night before:
118 * 2 a.m. on Wednesday is Tuesday night.
119 */
120export function sinceWords(from: number, now: number, timeZone: string | null): string {
121 const ago = now - from;
122 if (ago < MINUTE) return "a moment ago";
123 if (ago < HOUR) return `${plural(Math.floor(ago / MINUTE), "minute")} ago`;
124 if (ago < 3 * HOUR) return Math.floor(ago / HOUR) === 1 ? "an hour ago" : `${Math.floor(ago / HOUR)} hours ago`;
125 const hour = hourIn(from, timeZone);
126 const part: Part = hour < 5 ? "night" : hour < 12 ? "morning" : hour < 17 ? "afternoon" : "evening";
127 // The night is the evening's day's.
128 const day = dayIn(part === "night" ? from - 6 * HOUR : from, timeZone);
129 const today = dayIn(now, timeZone);
130 const yesterday = dayIn(now - DAY, timeZone);
131 const twoDaysAgo = dayIn(now - 2 * DAY, timeZone);
132 if (day === today) return `this ${part === "night" ? "evening" : part}`;
133 if (day === yesterday) return part === "night" ? "last night" : `yesterday ${part}`;
134 if (part === "night" && day === twoDaysAgo) return "the night before last";
135 if (ago < 6 * DAY) return `${formatIn(part === "night" ? from - 6 * HOUR : from, timeZone, { weekday: "long" })} ${part}`;
136 return shortDate(from, timeZone);
137}
138
139/**
140 * The span for `key`: since `lastSeen` (your last visit, kept by notify),
141 * or the last 24 hours or 7 days. Since your last visit falls back to the
142 * last 24 hours when there is none (`null`) or it could not be read
143 * (`undefined`), and to MAX_AWAY_DAYS when it was longer ago.
144 */
145export function spanFor(key: WindowKey, now: number, lastSeen: number | null | undefined, timeZone: string | null): Span {
146 if (key === "7d") return { key, from: now - 7 * DAY, now, words: "In the last 7 days", length: "7 days", note: null };
147 if (key === "24h" || lastSeen == null || lastSeen > now) {
148 const note = key !== "last" ? null : lastSeen === undefined ? "unknown" : "first";
149 return { key, from: now - DAY, now, words: "In the last 24 hours", length: "24 hours", note };
150 }
151 const furthest = now - MAX_AWAY_DAYS * DAY;
152 if (lastSeen < furthest) return { key, from: furthest, now, words: `In the last ${MAX_AWAY_DAYS} days`, length: `${MAX_AWAY_DAYS} days`, note: "capped" };
153 return { key, from: lastSeen, now, words: `Since ${sinceWords(lastSeen, now, timeZone)}`, length: duration(now - lastSeen), note: null };
154}
155
156/** Whether `at` (epoch ms or RFC 3339) falls in the span. */
157export function within(at: number | string | null | undefined, span: Pick<Span, "from" | "now">): boolean {
158 if (at == null) return false;
159 const ms = typeof at === "number" ? at : Date.parse(at);
160 return Number.isFinite(ms) && ms >= span.from && ms <= span.now;
161}
162
163// --- Code read for the span -----------------------------------------------------
164
165/** A pull request with where it is: what Home reads from Code. */
166export type CodePull = Pick<Pull, "number" | "title" | "status" | "mergedAt" | "createdAt" | "updatedAt"> & {
167 repo: RepoPath;
168 author: { username: string; kind?: string };
169 /** Who merged it, when it merged. */
170 mergedBy?: string | null;
171};
172
173/** Whether a pull request was opened by g1t itself, as older ones were: shown as `@g1t`. */
174export function isAgentPull(pull: { author: { username: string; kind?: string } }): boolean {
175 const name = pull.author.username;
176 return pull.author.kind === "agent" || name === "g1t" || name.endsWith("-agent");
177}
178
179/** `acme/web#12`, lowercase: how a pull request is matched. */
180export function pullKey(repo: RepoPath, number: number): string {
181 return `${repo.namespace}/${repo.name}#${number}`.toLowerCase();
182}
183
184export type CodeWork = {
185 pulls: CodePull[];
186 /** Whether every list read reached back to 7 days before the span. */
187 complete: boolean;
188};
189
190// --- People in the span -----------------------------------------------------------
191
192/**
193 * Who an actor is. Actors are member keys, as the events and chat services
194 * return them: `user:<id>` for an account, `agent:<id>` for an agent of
195 * older rows, `""` for nobody (a push a mirror copied in). g1t itself and
196 * older agents are not people; everyone else is.
197 */
198export type ActorKind = "person" | "agent";
199
200/** g1t's own account, as events name it (identity's `AGENT_ID`). */
201export const G1T_ACTOR = "user:usr_g1t_agent";
202
203export function actorKind(key: string, agents?: ReadonlySet<string>): ActorKind {
204 return key.startsWith("agent:") || key === G1T_ACTOR || isRobotKey(key) || agents?.has(key) ? "agent" : "person";
205}
206
207/**
208 * A member key that names a robot under `user:`: an agent of older rows by
209 * its own id, or g1t's upkeep as the workspace or as `g1t`. Events
210 * normalise these (services/events digest), so this is the safety net for
211 * older ones.
212 */
213export function isRobotKey(key: string): boolean {
214 return key.startsWith("user:agt_") || key.startsWith("user:wsp_") || key === "user:g1t";
215}
216
217/** Whether a username is g1t's own: g1t, or an agent account of older rows. */
218export function isAgentName(name: string | null | undefined): boolean {
219 return name === "g1t" || (name != null && name.endsWith("-agent"));
220}
221
222/** A repository as the digest's links and lines need it. */
223export type RepoRef = RepoPath & { defaultBranch: string };
224
225/** Someone who did something in the span: for the faces beside the card. */
226export type DigestActor = {
227 key: string;
228 /** Their username; `someone` when it could not be read. */
229 name: string;
230 /** How many things they did, over every line: the order of the faces. */
231 count: number;
232};
233
234/** One line: what was done, with its count, and where that is listed. */
235export type DigestLine = {
236 key: string;
237 text: string;
238 to: string | null;
239};
240
241export type DigestColumn = {
242 lines: DigestLine[];
243 /** Most active first. */
244 actors: DigestActor[];
245};
246
247/** What the sentence under the heading needs. */
248export type DigestSummary = {
249 /** Distinct people who did anything. */
250 people: number;
251 /** Commits people pushed. */
252 commits: number;
253 /** Pull requests people merged. */
254 merged: number;
255 /** Messages people sent. */
256 said: number;
257 /** Whether anything at all was counted. */
258 anything: boolean;
259 /** Whether what people did could be read at all (events and chat both silent: no). */
260 peopleRead: boolean;
261};
262
263export type Digest = {
264 people: DigestColumn;
265 summary: DigestSummary;
266 /** Sources that did not answer, by name, for the card to say so: Code, Chat. */
267 missing: string[];
268 /** True when a source was cut short, so some counts are low. */
269 partial: boolean;
270};
271
272export type DigestInput = {
273 slug: string;
274 /** The workspace's repositories by id: for links, and to count projects. */
275 repos: Record<string, RepoRef>;
276 /** Events' digest; null when events did not answer. Without Code access it has no repositories. */
277 activity: ActivityDigest | null;
278 /** Chat's; null when chat did not answer. */
279 chat: ChatActivity | null;
280 /** Names for member keys: a username. */
281 names: Record<string, string>;
282 /** Keys of accounts that are not people, beyond g1t. */
283 agentKeys?: ReadonlySet<string>;
284 code: boolean;
285};
286
287const people = (n: number) => plural(n, "person", "people");
288
289/** `a, b and c`. */
290export const listOf = (names: string[]) => (names.length <= 1 ? (names[0] ?? "") : `${names.slice(0, -1).join(", ")} and ${names.at(-1)}`);
291
292/** What people did, from a tally: how many, and by whom (non-empty keys). */
293function part(counts: ActorCount[], agents?: ReadonlySet<string>): { count: number; actors: Map<string, number> } {
294 const actors = new Map<string, number>();
295 let count = 0;
296 for (const entry of counts) {
297 if (actorKind(entry.actor, agents) !== "person") continue;
298 count += entry.count;
299 if (entry.actor) actors.set(entry.actor, (actors.get(entry.actor) ?? 0) + entry.count);
300 }
301 return { count, actors };
302}
303
304/** Where a line points: the one project's page, or the workspace's projects when several. */
305function placeFor(slug: string, repos: Record<string, RepoRef>, repoIds: Iterable<string>, page: string): string {
306 const ids = [...new Set(repoIds)];
307 const only = ids.length === 1 ? repos[ids[0]!] : null;
308 return only ? `/${only.namespace}/${only.name}/${page}` : `/${slug}/-/repositories`;
309}
310
311/**
312 * What people did in the span, as lines with counts and links, and who
313 * did it. Pure: everything comes from the services' counts and the names
314 * looked up for them.
315 */
316export function digestColumn(input: DigestInput): DigestColumn {
317 const { slug, repos, activity, chat, names, agentKeys } = input;
318 const lines: DigestLine[] = [];
319 const did = new Map<string, number>();
320 const credit = (actors: Map<string, number>) => {
321 for (const [key, n] of actors) did.set(key, (did.get(key) ?? 0) + n);
322 };
323
324 if (activity) {
325 // Pushes: commits, projects, and who.
326 const pushers = new Map<string, number>();
327 const pushed = new Set<string>();
328 let commits = 0;
329 let pushes = 0;
330 for (const repo of activity.repos) {
331 let any = false;
332 for (const by of repo.pushes.by) {
333 if (actorKind(by.actor, agentKeys) !== "person") continue;
334 any = true;
335 commits += by.commits;
336 pushes += by.count;
337 if (by.actor) pushers.set(by.actor, (pushers.get(by.actor) ?? 0) + by.count);
338 }
339 if (any) pushed.add(repo.repo_id);
340 }
341 if (pushes > 0) {
342 const where = `to ${plural(pushed.size, "project")}`;
343 const text = pushers.size > 0 ? `${people(pushers.size)} pushed ${plural(commits, "commit")} ${where}` : `${plural(commits, "commit")} pushed ${where}`;
344 lines.push({ key: "pushes", text, to: placeFor(slug, repos, pushed, "activity") });
345 credit(pushers);
346 }
347
348 // Pull requests, reviews, issues, comments, deploys, releases, packages: summed over projects.
349 const sum = (pick: (repo: RepoDigest) => ActorCount[]) => {
350 const total = { count: 0, actors: new Map<string, number>(), repoIds: [] as string[] };
351 for (const repo of activity.repos) {
352 const { count, actors } = part(pick(repo), agentKeys);
353 if (count === 0) continue;
354 total.count += count;
355 total.repoIds.push(repo.repo_id);
356 for (const [key, n] of actors) total.actors.set(key, (total.actors.get(key) ?? 0) + n);
357 }
358 return total;
359 };
360 const opened = sum((repo) => repo.pulls.opened);
361 const merged = sum((repo) => repo.pulls.merged);
362 const closed = sum((repo) => repo.pulls.closed);
363 if (opened.count + merged.count + closed.count > 0) {
364 const parts: string[] = [];
365 if (opened.count > 0) parts.push(`opened ${plural(opened.count, "pull request")}`);
366 if (merged.count > 0) parts.push(`merged ${opened.count > 0 ? merged.count.toLocaleString("en-US") : plural(merged.count, "pull request")}`);
367 if (closed.count > 0) parts.push(`closed ${closed.count.toLocaleString("en-US")} without merging`);
368 lines.push({ key: "pulls", text: parts.join(", "), to: placeFor(slug, repos, [...opened.repoIds, ...merged.repoIds, ...closed.repoIds], "pulls") });
369 credit(opened.actors);
370 credit(merged.actors);
371 credit(closed.actors);
372 }
373 const reviews = sum((repo) => repo.reviews);
374 if (reviews.count > 0) {
375 lines.push({ key: "reviews", text: `reviewed ${plural(reviews.count, "pull request")}`, to: placeFor(slug, repos, reviews.repoIds, "pulls") });
376 credit(reviews.actors);
377 }
378 const issuesOpened = sum((repo) => repo.issues.opened);
379 const issuesClosed = sum((repo) => repo.issues.closed);
380 if (issuesOpened.count + issuesClosed.count > 0) {
381 const parts: string[] = [];
382 if (issuesOpened.count > 0) parts.push(`opened ${plural(issuesOpened.count, "issue")}`);
383 if (issuesClosed.count > 0) parts.push(`closed ${issuesOpened.count > 0 ? issuesClosed.count.toLocaleString("en-US") : plural(issuesClosed.count, "issue")}`);
384 lines.push({ key: "issues", text: parts.join(", "), to: placeFor(slug, repos, [...issuesOpened.repoIds, ...issuesClosed.repoIds], "issues") });
385 credit(issuesOpened.actors);
386 credit(issuesClosed.actors);
387 }
388 const comments = sum((repo) => repo.comments);
389 if (comments.count > 0) {
390 lines.push({ key: "comments", text: `left ${plural(comments.count, "comment")}`, to: placeFor(slug, repos, comments.repoIds, "issues") });
391 credit(comments.actors);
392 }
393 const succeeded = sum((repo) => repo.deployments.succeeded);
394 const failed = sum((repo) => repo.deployments.failed);
395 if (succeeded.count + failed.count > 0) {
396 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`;
397 lines.push({ key: "deploys", text, to: placeFor(slug, repos, [...succeeded.repoIds, ...failed.repoIds], "deployments") });
398 credit(succeeded.actors);
399 credit(failed.actors);
400 }
401 const releases = sum((repo) => tallyOf(repo.releases.map((release) => release.actor)));
402 if (releases.count > 0) {
403 lines.push({ key: "releases", text: `published ${plural(releases.count, "release")}`, to: placeFor(slug, repos, releases.repoIds, "releases") });
404 credit(releases.actors);
405 }
406 const packages = sum((repo) => tallyOf(repo.packages.map((pkg) => pkg.actor)));
407 if (packages.count > 0) {
408 lines.push({ key: "packages", text: `published ${plural(packages.count, "package version")}`, to: `/${slug}/-/packages` });
409 credit(packages.actors);
410 }
411
412 // Artifacts: made, and whose content changed.
413 if (activity.folios) {
414 const made = part(activity.folios.created, agentKeys);
415 const edited = new Set<string>();
416 const editors = new Map<string, number>();
417 let allDocs = true;
418 for (const folio of activity.folios.edited) {
419 const mine = folio.authors.filter((author) => actorKind(author, agentKeys) === "person");
420 if (mine.length === 0) continue;
421 edited.add(folio.folio_id);
422 if (folio.kind !== "doc") allDocs = false;
423 for (const author of mine) editors.set(author, (editors.get(author) ?? 0) + 1);
424 }
425 const what = (n: number) => plural(n, allDocs ? "doc" : "artifact");
426 if (made.count + edited.size > 0) {
427 const parts: string[] = [];
428 if (made.count > 0) parts.push(`created ${what(made.count)}`);
429 if (edited.size > 0) parts.push(`edited ${what(edited.size)}`);
430 lines.push({ key: "docs", text: parts.join(", "), to: `/${slug}/-/artifacts` });
431 credit(made.actors);
432 credit(editors);
433 }
434 }
435 }
436
437 // Chat: what people said.
438 if (chat) {
439 const said = part(
440 chat.authors.map((author) => ({ actor: author.key, count: author.messages })),
441 agentKeys,
442 );
443 if (said.count > 0) {
444 lines.push({ key: "chat", text: `sent ${plural(said.count, "message")} in ${plural(chat.channels, "conversation")}`, to: `/${slug}/-/chat` });
445 credit(said.actors);
446 }
447 }
448
449 const actors: DigestActor[] = [...did]
450 .map(([key, count]) => ({ key, name: names[key] ?? "someone", count }))
451 .sort((a, b) => b.count - a.count || a.name.localeCompare(b.name));
452 return { lines, actors };
453}
454
455/** A tally with one of each actor, for lists that name an actor per item. */
456function tallyOf(actors: string[]): ActorCount[] {
457 const counts = new Map<string, number>();
458 for (const actor of actors) counts.set(actor, (counts.get(actor) ?? 0) + 1);
459 return [...counts].map(([actor, count]) => ({ actor, count }));
460}
461
462/** What people did, what the sentence needs, and which sources were silent. */
463export function digestOf(input: DigestInput): Digest {
464 const column = digestColumn(input);
465 const missing: string[] = [];
466 if (input.code && !input.activity) missing.push("Code");
467 if (!input.chat) missing.push("Chat");
468 let commits = 0;
469 let merged = 0;
470 for (const repo of input.activity?.repos ?? []) {
471 for (const by of repo.pushes.by) if (actorKind(by.actor, input.agentKeys) === "person") commits += by.commits;
472 merged += part(repo.pulls.merged, input.agentKeys).count;
473 }
474 const said = part(
475 (input.chat?.authors ?? []).map((author) => ({ actor: author.key, count: author.messages })),
476 input.agentKeys,
477 ).count;
478 return {
479 people: column,
480 summary: {
481 people: column.actors.length,
482 commits,
483 merged,
484 said,
485 anything: column.lines.length > 0,
486 peopleRead: input.activity != null || input.chat != null,
487 },
488 missing,
489 partial: input.activity != null && !input.activity.complete,
490 };
491}
492
493// --- What landed in the span -----------------------------------------------------
494
495/**
496 * A change that landed: a pull request merged; commits pushed straight to
497 * a default branch; a production build that went live; a release or a
498 * package version published.
499 */
500export type LandedChange = {
501 key: string;
502 kind: "merge" | "push" | "deploy" | "release" | "package";
503 title: string;
504 /** One line under it: where, and by whom. */
505 detail: string;
506 to: string;
507 at: number;
508};
509
510/** Every pull request that merged in the span, newest first. */
511export function landedIn(pulls: CodePull[], span: Pick<Span, "from" | "now">): LandedChange[] {
512 return pulls
513 .filter((pull) => pull.status === "merged" && within(pull.mergedAt, span))
514 .map((pull) => {
515 const agent = isAgentPull(pull);
516 const mergedBy = pull.mergedBy && pull.mergedBy !== pull.author.username ? `, merged by ${pull.mergedBy}` : "";
517 return {
518 key: `landed:${pullKey(pull.repo, pull.number)}`,
519 kind: "merge" as const,
520 title: pull.title,
521 detail: `${pull.repo.name}#${pull.number} · by ${agent ? `@${pull.author.username}` : pull.author.username}${mergedBy}`,
522 to: `/${pull.repo.namespace}/${pull.repo.name}/pull/${pull.number}`,
523 at: Date.parse(pull.mergedAt!),
524 };
525 })
526 .sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
527}
528
529/** The names behind member keys, for a line: `ana and bo`, `@margo`, `a mirror` for nobody. */
530function namesOf(keys: string[], names: Record<string, string>, agentKeys?: ReadonlySet<string>): string {
531 const shown = keys.map((key) => {
532 if (!key) return "a mirror";
533 const name = names[key] ?? (key === G1T_ACTOR ? "g1t" : "someone");
534 return actorKind(key, agentKeys) === "agent" ? `@${name}` : name;
535 });
536 return listOf([...new Set(shown)]);
537}
538
539/**
540 * Commits pushed straight to a default branch, one row per project with
541 * any: what landed without a pull request. Releases and package versions
542 * published, one row each. Pushes within the span only: the digest was
543 * asked for the span.
544 */
545export function landedFromActivity(activity: ActivityDigest | null, repos: Record<string, RepoRef>, names: Record<string, string>, slug: string, agentKeys?: ReadonlySet<string>): LandedChange[] {
546 const rows: LandedChange[] = [];
547 for (const repo of activity?.repos ?? []) {
548 const path = repos[repo.repo_id];
549 if (!path) continue;
550 const direct = repo.pushes.default_branch;
551 if (direct.count > 0 && direct.last_at) {
552 const by = direct.by.map((entry) => entry.actor);
553 rows.push({
554 key: `push:${repo.repo_id}`,
555 kind: "push",
556 title: `${plural(direct.commits, "commit")} pushed to ${path.defaultBranch}`,
557 detail: `${path.name} · ${plural(direct.count, "push", "pushes")} by ${namesOf(by, names, agentKeys)}`,
558 to: `/${path.namespace}/${path.name}/activity`,
559 at: Date.parse(direct.last_at),
560 });
561 }
562 for (const release of repo.releases) {
563 rows.push({
564 key: `release:${repo.repo_id}:${release.tag}`,
565 kind: "release",
566 title: release.name ? `${release.tag} · ${release.name}` : release.tag,
567 detail: `${path.name} · released by ${namesOf([release.actor], names, agentKeys)}`,
568 to: `/${path.namespace}/${path.name}/releases/tag/${encodeURIComponent(release.tag)}`,
569 at: Date.parse(release.at),
570 });
571 }
572 for (const pkg of repo.packages) {
573 rows.push({
574 key: `package:${repo.repo_id}:${pkg.ecosystem}:${pkg.name}:${pkg.version}`,
575 kind: "package",
576 title: `${pkg.name} ${pkg.version}`,
577 detail: `${pkg.ecosystem} package · published by ${namesOf([pkg.actor], names, agentKeys)}`,
578 to: `/${slug}/-/packages`,
579 at: Date.parse(pkg.at),
580 });
581 }
582 }
583 return rows;
584}
585
586/** Production builds that went live in the span, as landed changes; previews stay in Deploys. */
587export function landedDeploys(deploys: DeployRow[]): LandedChange[] {
588 return deploys
589 .filter((row) => row.kind === "production" && row.outcome === "live")
590 .map((row) => ({
591 key: `landed:${row.key}`,
592 kind: "deploy" as const,
593 title: `Production of ${row.project} went live`,
594 detail: `${row.commit} · by ${row.by ?? "someone"}`,
595 to: row.to,
596 at: row.at,
597 }));
598}
599
600/** Everything that landed, newest first. */
601export function landed(parts: LandedChange[][]): LandedChange[] {
602 return parts.flat().sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
603}
604
605/** A deployment's maker as a member key: an id becomes `user:<id>`, a key stays as it is. */
606export function deployActorKey(createdBy: string | null | undefined): string | null {
607 const by = (createdBy ?? "").trim();
608 if (!by) return null;
609 return /^(user|agent):/.test(by) ? by : `user:${by}`;
610}
611
612/** A build that finished in the span. */
613export type DeployRow = {
614 key: string;
615 project: string;
616 kind: Deployment["kind"];
617 /** `live`: built and served (it may have been replaced since); `failed`: it did not build. */
618 outcome: "live" | "failed";
619 commit: string;
620 branch: string | null;
621 at: number;
622 to: string;
623 /** Who made it, as a name (`@g1t` for g1t itself); null when the deployment does not say. */
624 by: string | null;
625};
626
627/**
628 * Builds that finished in the span, newest first: production builds each,
629 * and previews too. A build that went live and was replaced since still
630 * went live. Skipped builds are left out.
631 */
632export function deploysIn(projects: { slug: string; deployments: Deployment[] }[], workspace: string, span: Pick<Span, "from" | "now">, names: Record<string, string> = {}, agentKeys?: ReadonlySet<string>): DeployRow[] {
633 const rows: DeployRow[] = [];
634 for (const project of projects) {
635 for (const deploy of project.deployments) {
636 // Who made it: the deployment names them by id, so it reads as a name, or as someone when identity doesn't know it.
637 const key = deployActorKey(deploy.createdBy);
638 const ended = deploy.finishedAt ?? null;
639 if (!within(ended, span)) continue;
640 const outcome = deploy.status === "failed" ? "failed" : deploy.status === "ready" || deploy.status === "replaced" || deploy.status === "down" ? "live" : null;
641 if (!outcome) continue;
642 rows.push({
643 key: `deploy:${project.slug}:${deploy.id}`,
644 project: project.slug,
645 kind: deploy.kind,
646 outcome,
647 commit: deploy.commit.slice(0, 7),
648 branch: deploy.branch,
649 at: Date.parse(ended!),
650 to: `/${workspace}/${project.slug}/deployments/${deploy.id}`,
651 by: key ? namesOf([key], names, agentKeys) : null,
652 });
653 }
654 }
655 return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
656}
657
658/** A decision made in the span: one recorded in the workspace's memory. */
659export type DecisionRow = {
660 key: string;
661 text: string;
662 by: string | null;
663 at: number;
664 to: string;
665};
666
667/** Decisions kept in the workspace's memory that were recorded in the span, newest first. */
668export function decisionsIn(memories: Memory[] | null, slug: string, span: Pick<Span, "from" | "now">): DecisionRow[] {
669 const rows: DecisionRow[] = [];
670 for (const memory of memories ?? []) {
671 if (memory.kind !== "decision" || (memory.status != null && memory.status !== "kept") || !within(memory.createdAt, span)) continue;
672 rows.push({ key: `memory:${memory.id}`, text: memory.text, by: memory.createdBy, at: Date.parse(memory.createdAt), to: `/${slug}/-/memory` });
673 }
674 return rows.sort((a, b) => b.at - a.at || a.key.localeCompare(b.key));
675}
676
677// --- Running now ----------------------------------------------------------------
678
679/** Something going right now: a workflow run or a build. */
680export type RunningRow = {
681 key: string;
682 kind: "workflow" | "deploy";
683 title: string;
684 /** One line: who and where. */
685 detail: string;
686 /** "Running", "Queued", "Building". */
687 status: string;
688 /** Epoch ms: when it started. */
689 at: number;
690 to: string;
691};
692
693/** Builds queued or going now, one per project (its newest). */
694export function runningDeploys(overview: ProjectDeploys[], slug: string): RunningRow[] {
695 return overview.flatMap((project) => {
696 const latest = project.latest;
697 if (!latest || (latest.status !== "queued" && latest.status !== "building")) return [];
698 return [
699 {
700 key: `deploy:${project.slug}:${latest.id}`,
701 kind: "deploy" as const,
702 title: `${latest.kind === "production" ? "Production" : `Preview of ${latest.branch ?? "a branch"}`} of ${project.slug}`,
703 detail: `${latest.commit.slice(0, 7)} · by ${latest.createdBy}`,
704 status: latest.status === "queued" ? "Queued" : "Building",
705 at: Date.parse(latest.createdAt),
706 to: `/${slug}/${project.slug}/deployments/${latest.id}`,
707 },
708 ];
709 });
710}
711
712const RUN_STATUS: Partial<Record<WorkflowRun["status"], string>> = {
713 pending: "Queued",
714 queued: "Queued",
715 action_required: "Needs approval",
716 in_progress: "Running",
717 waiting: "Waiting",
718};
719
720/** Workflow runs not finished, in the projects read: queued, waiting, running, or waiting for approval. */
721export function runningWorkflows(projects: { repo: RepoPath; runs: WorkflowRun[] }[]): RunningRow[] {
722 return projects.flatMap(({ repo, runs }) =>
723 runs.flatMap((run) => {
724 const status = RUN_STATUS[run.status];
725 if (!status) return [];
726 return [
727 {
728 key: `workflow:${repo.namespace}/${repo.name}:${run.id}`.toLowerCase(),
729 kind: "workflow" as const,
730 title: run.title ? `${run.name}: ${run.title}` : run.name,
731 detail: `${repo.namespace}/${repo.name} ${run.ref.replace(/^refs\/heads\//, "")}${run.actor ? ` · by ${run.actor}` : ""}`,
732 status,
733 at: Date.parse(run.startedAt ?? run.createdAt),
734 to: `/${repo.namespace}/${repo.name}/actions/runs/${run.id}`,
735 },
736 ];
737 }),
738 );
739}
740
741/** Everything running, longest-going first within each kind: workflow runs, then builds. */
742export function running(parts: RunningRow[][]): RunningRow[] {
743 const order = { workflow: 0, deploy: 1 } as const;
744 return parts.flat().sort((a, b) => order[a.kind] - order[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
745}
746
747// --- Needs you ------------------------------------------------------------------
748
749/**
750 * What a row is. Tiers, most pressing first:
751 * 0. production is down to an older build (`deploy`);
752 * 1. a change that can't land until someone acts on it (`pull_blocked`);
753 * 2. something waiting only for you (a review, an invitation);
754 * 3. a job waiting for a runner that is not there;
755 * 4. an unread notification that is a warning or a failure;
756 * 5. a mention or a direct message.
757 */
758export type AttentionKind = "deploy" | "pull_blocked" | "review" | "invitation" | "runner" | "notification" | "chat";
759
760export const TIER: Record<AttentionKind, number> = {
761 deploy: 0,
762 pull_blocked: 1,
763 review: 2,
764 invitation: 2,
765 runner: 3,
766 notification: 4,
767 chat: 5,
768};
769
770export type Stake = { text: string; tone: "danger" | "warn" | "accent" | null };
771
772/** One row of Needs you. */
773export type AttentionRow = {
774 key: string;
775 kind: AttentionKind;
776 title: string;
777 /** One line: what it is and where. */
778 detail: string;
779 /** What is at stake, in a few words. */
780 stake: Stake | null;
781 /** The action, right there. */
782 action: { label: string; to: string };
783 /** Who is on it: the person who asked, or g1t on older rows. */
784 owner: { name: string; agent: boolean } | null;
785 /** Epoch ms: when it started waiting. */
786 at: number;
787 /** Where it came from, for a member without Code access never `code`. */
788 from: "code" | "notifications" | "chat";
789};
790
791/**
792 * Most pressing first: by tier, then what has waited longest, then by key
793 * so the order never depends on the order rows were read. One of each key,
794 * and one of each place: a notification about a pull request already on
795 * the list is left out.
796 */
797export function rankAttention(rows: AttentionRow[]): AttentionRow[] {
798 const sorted = [...rows].sort((a, b) => TIER[a.kind] - TIER[b.kind] || a.at - b.at || a.key.localeCompare(b.key));
799 const keys = new Set<string>();
800 const places = new Set<string>();
801 return sorted.filter((row) => {
802 const place = row.action.to.split(/[?#]/)[0];
803 if (keys.has(row.key) || (row.kind === "notification" && places.has(place))) return false;
804 keys.add(row.key);
805 places.add(place);
806 return true;
807 });
808}
809
810/** Start here: the first row by `rankAttention`, with why it was picked. */
811export function startHere(ranked: AttentionRow[]): { row: AttentionRow; why: string } | null {
812 const row = ranked[0];
813 if (!row) return null;
814 const sameTier = ranked.filter((other) => TIER[other.kind] === TIER[row.kind]).length;
815 const tail = sameTier > 1 ? ` Of the ${sameTier} like it, it has waited longest.` : "";
816 return { row, why: `${WHY[row.kind]}${tail}` };
817}
818
819const WHY: Record<AttentionKind, string> = {
820 deploy: "Production is serving an older build until this is fixed, so it comes before anything else.",
821 pull_blocked: "This change can't land until someone fixes it.",
822 review: "You were asked by name, so it waits for your verdict.",
823 invitation: "It is addressed to you; no one else can answer it.",
824 runner: "A job is waiting for a runner that is not there.",
825 notification: "It is the most pressing unread notification.",
826 chat: "Nothing else is waiting, and this is the oldest message for you.",
827};
828
829// --- Rows from each source ----------------------------------------------------
830
831/** A Code Overview need row, as Home reads it (lib/mission-control.ts `NeedRow`). */
832export type CodeNeed = {
833 key: string;
834 reason: string;
835 repo: RepoPath | null;
836 ref: string | null;
837 title: string;
838 ask: string;
839 by: { name: string; agent: boolean } | null;
840 at: number;
841 to: string;
842 facts: { label: string; value: string; tone: string | null }[];
843};
844
845const fact = (need: CodeNeed, label: string) => need.facts.find((f) => f.label === label)?.value ?? null;
846
847const REASON_STAKE: Record<string, Stake> = {
848 blocking: { text: "Blocking", tone: "danger" },
849 checks_failing: { text: "Checks failing", tone: "danger" },
850 needs_review: { text: "Needs a verdict", tone: "warn" },
851 stalled: { text: "Stalled", tone: "warn" },
852};
853
854/** A Code need (failed deploy, pull request, review, invitation, runner) as a row. */
855export function codeRow(need: CodeNeed): AttentionRow {
856 const prefix = need.key.split(":")[0];
857 const where = need.repo ? `${need.repo.namespace}/${need.repo.name}${need.ref ? ` ${need.ref}` : ""}` : null;
858 const detail = where ? `${where} · ${need.ask}` : need.ask;
859 const owner = need.by;
860 const base = { key: need.key, title: need.title, detail, owner, at: need.at, from: "code" as const };
861 switch (prefix) {
862 case "deploy":
863 return {
864 ...base,
865 kind: "deploy",
866 stake: { text: fact(need, "Production") === "Not live yet" ? "Not live yet" : "Production on an older build", tone: "danger" },
867 action: { label: "See the build", to: need.to },
868 };
869 case "invitation":
870 return { ...base, kind: "invitation", stake: { text: `${fact(need, "Role") ?? "A"} role`, tone: null }, action: { label: "Respond", to: need.to } };
871 case "review": {
872 const lines = fact(need, "Lines");
873 return { ...base, kind: "review", stake: { text: lines ?? "Your review", tone: null }, action: { label: "Review", to: need.to } };
874 }
875 case "runner":
876 return { ...base, kind: "runner", stake: { text: `Waiting ${fact(need, "Waiting") ?? ""}`.trim(), tone: "warn" }, action: { label: "Look", to: need.to } };
877 default:
878 return {
879 ...base,
880 kind: "pull_blocked",
881 stake: REASON_STAKE[need.reason] ?? { text: "Waiting on you", tone: "warn" },
882 action: { label: need.reason === "needs_review" ? "Review" : "Look", to: need.to },
883 };
884 }
885}
886
887const NOTIFICATION_STAKE: Record<string, string> = {
888 review_requested: "Review requested",
889 assign: "Assigned to you",
890 mention: "Mentioned",
891 team_mention: "Team mentioned",
892 ci_activity: "CI activity",
893 security_alert: "Security alert",
894 state_change: "State changed",
895 author: "Your work",
896 comment: "Comment",
897 manual: "Subscribed",
898 subscribed: "Watching",
899};
900
901/**
902 * An unread notification that is a warning (someone or something is
903 * waiting) or a failure, in this workspace. A member without Code access
904 * gets none about a repository. A reason this page does not know (older
905 * ones included) reads as a plain notification.
906 */
907export function notificationRow(item: InboxItem, slug: string, code: boolean): AttentionRow | null {
908 if (item.readAt != null || item.doneAt != null) return null;
909 if (item.severity !== "warning" && item.severity !== "error") return null;
910 const inWorkspace = (item.workspace ?? item.repo?.split("/")[0] ?? "").toLowerCase() === slug;
911 if (!inWorkspace) return null;
912 if (!code && item.repo) return null;
913 return {
914 key: `notification:${item.id}`,
915 kind: "notification",
916 title: item.body || item.title,
917 detail: item.body ? item.title : (item.repo ?? "A notification"),
918 stake: { text: NOTIFICATION_STAKE[item.reason] ?? "Notification", tone: item.severity === "error" ? "danger" : "warn" },
919 action: { label: "Open", to: item.url },
920 owner: item.actor ? { name: item.actor, agent: isAgentName(item.actor) } : null,
921 at: Date.parse(item.updatedAt),
922 from: "notifications",
923 };
924}
925
926export type ChatEntryLike = {
927 channel: { id: string; kind: "channel" | "dm"; name: string | null; last_message_at?: string | null };
928 title: string;
929 muted: boolean;
930 unread: number;
931 mentions: number;
932};
933
934/** A conversation with a mention of you, or a direct message you haven't read. */
935export function chatRow(entry: ChatEntryLike, slug: string): AttentionRow | null {
936 if (entry.muted) return null;
937 if (!(entry.mentions > 0 || (entry.channel.kind === "dm" && entry.unread > 0))) return null;
938 const to = entry.channel.kind === "dm" || !entry.channel.name ? `/${slug}/-/chat/dm/${entry.channel.id}` : `/${slug}/-/chat/${entry.channel.name}`;
939 const dm = entry.channel.kind === "dm";
940 return {
941 key: `chat:${entry.channel.id}`,
942 kind: "chat",
943 title: dm ? entry.title : `#${entry.title}`,
944 detail: dm ? "A direct message you haven't read." : "You were mentioned.",
945 stake: {
946 text: entry.mentions > 0 ? `${entry.mentions} ${entry.mentions === 1 ? "mention" : "mentions"}` : `${entry.unread} unread`,
947 tone: entry.mentions > 0 ? "accent" : null,
948 },
949 action: { label: "Reply", to },
950 owner: null,
951 at: entry.channel.last_message_at ? Date.parse(entry.channel.last_message_at) : 0,
952 from: "chat",
953 };
954}
955
956/** What Needs you and Start here show, and which sources did not answer. */
957export type Attention = {
958 rows: AttentionRow[];
959 start: { row: AttentionRow; why: string } | null;
960 /** Sources that did not answer, by name, for the card to say so. */
961 missing: string[];
962};
963
964export function attention(input: {
965 slug: string;
966 code: boolean;
967 codeNeeds: CodeNeed[] | null;
968 notifications: InboxItem[] | null;
969 chat: ChatEntryLike[] | null;
970}): Attention {
971 const rows: AttentionRow[] = [];
972 const missing: string[] = [];
973 if (input.code) {
974 if (input.codeNeeds) rows.push(...input.codeNeeds.map(codeRow));
975 else missing.push("Code");
976 }
977 if (input.notifications) {
978 for (const item of input.notifications) {
979 const row = notificationRow(item, input.slug, input.code);
980 if (row) rows.push(row);
981 }
982 } else missing.push("Notifications");
983 if (input.chat) {
984 for (const entry of input.chat) {
985 const row = chatRow(entry, input.slug);
986 if (row) rows.push(row);
987 }
988 } else missing.push("Chat");
989 const ranked = rankAttention(rows);
990 return { rows: ranked, start: startHere(ranked), missing };
991}
992
993// --- Spend in the span ----------------------------------------------------------
994
995/** Money in, which the statement lists but which is not spend. */
996const MONEY_IN: ReadonlySet<string> = new Set(["Payments", "AI credit", "Credits from g1t", "Refunds", "Tax", "Card processing fees"]);
997
998export type Spend = {
999 /** The statement days counted, `YYYY-MM-DD` in UTC, first and last. */
1000 from: string;
1001 to: string;
1002 /** Usage at price over those days, in micros. */
1003 totalMicros: number;
1004 /** A line per kind of charge, as the statement names it, most first. */
1005 lines: { kind: string; micros: number; count: number }[];
1006 /** Usage at price this month so far, the top bar's and Usage's figure; null when it could not be read. */
1007 monthMicros: number | null;
1008};
1009
1010/** The UTC months (`YYYY-MM`) the span touches, oldest first: the statements Home reads. */
1011export function spanMonths(span: Pick<Span, "from" | "now">): string[] {
1012 const months: string[] = [];
1013 const first = new Date(span.from);
1014 let year = first.getUTCFullYear();
1015 let month = first.getUTCMonth();
1016 const last = new Date(span.now).toISOString().slice(0, 7);
1017 for (let i = 0; i < 3; i++) {
1018 const key = `${year}-${String(month + 1).padStart(2, "0")}`;
1019 months.push(key);
1020 if (key >= last) break;
1021 month++;
1022 if (month === 12) {
1023 month = 0;
1024 year++;
1025 }
1026 }
1027 return months;
1028}
1029
1030/**
1031 * The span's spend from the statements grouped by day: each usage line at
1032 * its price (what was charged, plus what the plan, a trial, a pool or a
1033 * discount paid of it), leaving out money in. The statement keeps whole
1034 * UTC days, so the span is counted from the start of the UTC day it began.
1035 * `statements` is the months of `spanMonths`, the current one last.
1036 * `monthMicros` is this month so far as billing's usage report counts it,
1037 * the month's usage not yet closed included: the figure Usage
1038 * shows, so Home shows no other.
1039 */
1040export function spendIn(statements: Pick<Statement, "groups" | "totals">[], span: Pick<Span, "from" | "now">, monthMicros: number | null): Spend {
1041 const from = new Date(span.from).toISOString().slice(0, 10);
1042 const to = new Date(span.now).toISOString().slice(0, 10);
1043 const byKind = new Map<string, { micros: number; count: number }>();
1044 for (const statement of statements) {
1045 for (const group of statement.groups) {
1046 if (group.key < from || group.key > to) continue;
1047 for (const line of group.lines) {
1048 if (MONEY_IN.has(line.kind)) continue;
1049 const micros = line.priceMicros ?? line.chargedMicros;
1050 const kept = byKind.get(line.kind) ?? { micros: 0, count: 0 };
1051 byKind.set(line.kind, { micros: kept.micros + micros, count: kept.count + line.count });
1052 }
1053 }
1054 }
1055 const lines = [...byKind]
1056 .map(([kind, value]) => ({ kind, ...value }))
1057 .filter((line) => line.micros > 0)
1058 .sort((a, b) => b.micros - a.micros || a.kind.localeCompare(b.kind));
1059 return {
1060 from,
1061 to,
1062 totalMicros: lines.reduce((sum, line) => sum + line.micros, 0),
1063 lines,
1064 monthMicros,
1065 };
1066}
1067
1068// --- The sentence -----------------------------------------------------------
1069
1070/**
1071 * The sentence under the heading, honest about what happened: "Since
1072 * Tuesday evening, 3 people pushed 41 commits and merged 5 changes, and
1073 * 12 changes landed." What people did comes first (commits and merges;
1074 * else what they said), then everything that landed. When nothing at all
1075 * was counted: "Quiet since Tuesday evening: nothing pushed, merged,
1076 * deployed or said." When what people did could not be read, it says so.
1077 */
1078export function spanSentence(span: Pick<Span, "words">, digest: Pick<Digest, "summary"> | null, landed: number | null): string {
1079 const lead = span.words;
1080 if (!digest) return `${lead}, what happened couldn't be read.`;
1081 const { people: count, commits, merged, said, anything, peopleRead } = digest.summary;
1082 const landedCount = landed ?? 0;
1083 if (!anything && landedCount === 0) {
1084 if (!peopleRead) return `${lead}, what people did couldn't be read.`;
1085 return `Quiet ${lead.charAt(0).toLowerCase()}${lead.slice(1)}: nothing pushed, merged, deployed or said.`;
1086 }
1087 const parts: string[] = [];
1088 if (count > 0) {
1089 if (commits > 0 || merged > 0) {
1090 const did: string[] = [];
1091 if (commits > 0) did.push(`pushed ${plural(commits, "commit")}`);
1092 if (merged > 0) did.push(`merged ${plural(merged, "change")}`);
1093 parts.push(`${people(count)} ${did.join(" and ")}`);
1094 } else if (said > 0) parts.push(`${people(count)} sent ${plural(said, "message")}`);
1095 else parts.push(`${people(count)} ${count === 1 ? "was" : "were"} active`);
1096 }
1097 if (landedCount > 0) parts.push(`${plural(landedCount, "change")} landed`);
1098 const tail = peopleRead ? "" : "; what people did couldn't be read";
1099 if (parts.length === 0) return `${lead}, work went on, but nothing landed${tail}.`;
1100 const joined = parts.length > 2 ? `${parts.slice(0, -1).join(", ")}, and ${parts.at(-1)}` : parts.join(" and ");
1101 return `${lead}, ${joined}${tail}.`;
1102}
1103
1104/** "8 things need you.", or that nothing does. */
1105export function waitingSentence(total: number): string {
1106 if (total === 0) return "Nothing needs you right now.";
1107 return `${plural(total, "thing")} ${total === 1 ? "needs" : "need"} you.`;
1108}
1109
1110/** How long something has waited: "45 min", "17 h", "2 d". */
1111export function waited(at: number, now: number): string {
1112 const minutes = Math.max(0, Math.floor((now - at) / MINUTE));
1113 if (minutes < 60) return `${minutes} min`;
1114 if (minutes < 24 * 60) return `${Math.floor(minutes / 60)} h`;
1115 return `${Math.floor(minutes / (24 * 60))} d`;
1116}
1117
1118/** "3:40 PM" when it is the same day as `now`, else "Oct 7". */
1119export function whenShort(at: number, now: number, timeZone: string | null): string {
1120 if (dayIn(at, timeZone) === dayIn(now, timeZone)) return formatIn(at, timeZone, { hour: "numeric", minute: "2-digit" });
1121 return now - at < 6 * DAY ? formatIn(at, timeZone, { weekday: "short", hour: "numeric" }) : shortDate(at, timeZone);
1122}