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.

699 linesCodeBlameRaw
1/**
2 * Coordinating work, as the site shows it: who is on which work item (claims),
3 * which harness sessions are running, what the merge queue found when it
4 * combined changes, and the decision records behind the result. Pure: the
5 * pages and components/coordination.tsx draw what these say.
6 */
7import type {
8 Claim,
9 ClaimState,
10 Decision,
11 DecisionConfidence,
12 EventType,
13 G1tEvent,
14 Harness,
15 LinkVia,
16 SessionState,
17 TouchKind,
18 WorkSession,
19} from "@g1t/contracts";
20
21/** How each harness is named. */
22export const HARNESS_NAMES: Record<Harness, string> = {
23 claude_code: "Claude Code",
24 claude_managed_agents: "Claude Managed Agents",
25 codex: "Codex",
26 cursor: "Cursor",
27 copilot: "Copilot",
28 other: "Another harness",
29};
30
31export function harnessName(harness: Harness | null | undefined): string | null {
32 return harness ? (HARNESS_NAMES[harness] ?? harness) : null;
33}
34
35/** The coordination events the Sessions page lists, newest first. */
36export const COORDINATION_TYPES = [
37 "work.claimed",
38 "work.released",
39 "work.claim_expired",
40 "work.handoff_requested",
41 "session.started",
42 "session.ended",
43 "dependency.changed",
44 "overlap.detected",
45 "integration.failed",
46 "integration.passed",
47 "decision.recorded",
48] as const satisfies readonly EventType[];
49
50export type CoordinationType = (typeof COORDINATION_TYPES)[number];
51
52// ── Time ────────────────────────────────────────────────────────────────
53
54const MINUTE = 60_000;
55
56/** "4m", "1h 20m", "2h": a span, for "expires in …". */
57export function span(ms: number): string {
58 const minutes = Math.max(0, Math.floor(ms / MINUTE));
59 if (minutes < 1) return "less than a minute";
60 if (minutes < 60) return `${minutes}m`;
61 const hours = Math.floor(minutes / 60);
62 const rest = minutes % 60;
63 return rest === 0 ? `${hours}h` : `${hours}h ${rest}m`;
64}
65
66/** When an active claim lapses, in words; null for one that is not active. */
67export function expiresIn(claim: Pick<Claim, "state" | "expiresAt">, now: number): string | null {
68 if (claim.state !== "active") return null;
69 const left = new Date(claim.expiresAt).getTime() - now;
70 return left <= 0 ? "expiring now" : `expires in ${span(left)}`;
71}
72
73/** What became of a claim that is no longer active. */
74export const CLAIM_ENDED: Record<Exclude<ClaimState, "active">, string> = {
75 released: "Released",
76 expired: "Expired",
77 handed_off: "Handed off",
78};
79
80export const SESSION_STATES: Record<SessionState, { label: string; hint: string }> = {
81 active: { label: "Active", hint: "Heard from in the last 15 minutes." },
82 idle: { label: "Idle", hint: "Not heard from for 15 minutes. It may still come back." },
83 ended: { label: "Ended", hint: "Ended, or not heard from for 30 minutes. One that went quiet comes back when it is heard from again." },
84};
85
86// ── Ending a session by hand ────────────────────────────────────────────
87
88/** How the reason of a session ended by hand starts (g1t_contracts::work::ENDED_BY_HAND). */
89export const ENDED_BY_HAND = "ended by hand by @";
90
91/**
92 * Whether the viewer may end a session by hand, for one its harness left
93 * behind: one not ended yet, their own, or anyone's when they have write
94 * access (`canPush`) to the repository. The work service checks the same.
95 * One g1t runs on the workspace's Anthropic account is stopped from its
96 * page instead, which stops the run too.
97 */
98export function mayEndSession(
99 session: Pick<WorkSession, "state" | "actor" | "harness">,
100 viewerId: string | null | undefined,
101 canPush: boolean,
102): boolean {
103 if (!viewerId || session.state === "ended" || session.harness === "claude_managed_agents") return false;
104 return session.actor.id === viewerId || canPush;
105}
106
107/** Who may end which session from a list: the viewer, and whether they may end anyone's. */
108export type SessionEnder = { viewerId: string | null; canPush: boolean };
109
110/** Why a session ended, in words: "timed out", "ended by hand by @ana", or what its harness said. */
111export function endReasonText(reason: string | null | undefined): string | null {
112 if (!reason) return null;
113 return reason === "timed_out" ? "timed out" : reason;
114}
115
116// ── Session titles ──────────────────────────────────────────────────────
117
118/** The most of a prompt's intent that titles a session. */
119export const TITLE_LIMIT = 80;
120
121/** A turn the harness starts itself, as a tag: `<command-name>`, `<task-notification>`, one with attributes. */
122const HARNESS_TAG = /^\s*<[a-z][\w-]*(?:\s[^>]*)?>/i;
123
124/** What an editor adds ahead of a prompt, a whole block at a time: `<ide_opened_file>…</ide_opened_file>`. */
125const IDE_CONTEXT = /^\s*<(ide_[a-z_]+|system-reminder)\b[^>]*>[\s\S]*?<\/\1>/i;
126
127/**
128 * What a prompt is for, as a session's title: its first line or sentence,
129 * without code blocks or markdown, whitespace collapsed, clipped at
130 * TITLE_LIMIT on a word with "…". Null for a slash command, a turn the
131 * harness starts itself, or nothing to say. The work service gives a
132 * session its provisional title the same way, from its first prompt
133 * (services/work/src/coordination/titles.rs `intent_title`).
134 */
135export function intentTitle(prompt: string | null | undefined): string | null {
136 let text = String(prompt ?? "").replace(/^\uFEFF/, "");
137 // What the harness pasted in or attached is not what the prompt is for:
138 // pasted text (Claude Code's <pasted_content id="…">…</pasted_content>)
139 // and image placeholders ([Image #1], [Image: source: …]) go first.
140 text = text
141 .replace(/<pasted_content\b[^>]*>[\s\S]*?(?:<\/pasted_content[^>]*>|$)/gi, "\n")
142 .replace(/\[Image(?: #\d+)?(?::[^\]\n]*)?\]/g, " ");
143 // Context an editor puts before what was typed (VS Code's
144 // <ide_opened_file>, <ide_selection>) is not a turn the harness started.
145 while (IDE_CONTEXT.test(text)) text = text.replace(IDE_CONTEXT, "");
146 if (/^\s*\//.test(text) || HARNESS_TAG.test(text)) return null;
147 text = text
148 .replace(/```[\s\S]*?(```|$)/g, "\n")
149 .replace(/~~~[\s\S]*?(~~~|$)/g, "\n")
150 .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
151 .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
152 .replace(/`([^`]*)`/g, "$1");
153 const line = text
154 .split(/\r?\n/)
155 .map((l) => l.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)+/, "").replace(/(\*\*|__|~~)(.+?)\1/g, "$2").trim())
156 .find((l) => /[\p{L}\p{N}]/u.test(l));
157 if (!line) return null;
158 let intent = line.replace(/\s+/g, " ").split(/(?<=[.!?])\s+(?=\S)/)[0].trim();
159 if (intent.length > TITLE_LIMIT) {
160 const cut = intent.slice(0, TITLE_LIMIT - 1);
161 const space = cut.lastIndexOf(" ");
162 intent = `${(space > TITLE_LIMIT / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:.\-–—]+$/, "")}…`;
163 } else {
164 intent = intent.replace(/[\s,;:.]+$/, "");
165 }
166 if (intent.length < 2) return null;
167 return intent[0].toLocaleUpperCase() + intent.slice(1);
168}
169
170/**
171 * What a session is called, never nothing: its title, else what its first
172 * prompt was for, else the branch it is on, else "Untitled session".
173 * `firstPrompt` stands in for the session's own when given.
174 */
175export function sessionTitle(
176 session: Pick<WorkSession, "title" | "branch" | "firstPrompt">,
177 firstPrompt: string | null | undefined = session.firstPrompt,
178): string {
179 // A title that is only a harness tag (an early plugin's from a pasted prompt) reads as none.
180 const title = session.title?.trim();
181 if (title && !HARNESS_TAG.test(title)) return title;
182 const intent = intentTitle(firstPrompt);
183 if (intent) return intent;
184 return session.branch ? `Session on ${session.branch}` : "Untitled session";
185}
186
187/**
188 * Whether what a session is called is still provisional: what its first
189 * prompt asked, until g1t settles a title from all it did. Shown muted. A
190 * subagent goes by its task, which is never provisional.
191 */
192export function titleIsProvisional(session: Pick<WorkSession, "title" | "titleSource" | "parentId">): boolean {
193 if (session.parentId) return false;
194 return session.titleSource === "prompt" || (!session.title?.trim() && session.titleSource == null);
195}
196
197/** Why a title reads as it does, for a hint on it. */
198export function titleHint(session: Pick<WorkSession, "title" | "titleSource" | "parentId">): string | undefined {
199 if (session.parentId) return undefined;
200 switch (session.titleSource) {
201 case "person":
202 return "Named by a person: g1t keeps this title.";
203 case "agent":
204 return "Named by its agent.";
205 case "item":
206 case "pull":
207 case "summary":
208 return "Named by g1t from what the session did.";
209 default:
210 return titleIsProvisional(session) ? "From its first prompt, for now: g1t names it once what it is doing is clear." : undefined;
211 }
212}
213
214// ── Live now ────────────────────────────────────────────────────────────
215
216/** One work item being worked on: its claims and the sessions on it. */
217export type LiveItem = { item: number; claims: Claim[]; sessions: WorkSession[] };
218
219/** Sessions on no work item yet, together: on one pull request, on one branch of their own, or on neither. */
220export type LiveGroup =
221 | { kind: "pull"; pull: number; sessions: WorkSession[] }
222 | { kind: "branch"; branch: string; sessions: WorkSession[] }
223 | { kind: "none"; sessions: WorkSession[] };
224
225/**
226 * Whether a session has done nothing since it started: no title, no work item
227 * or pull request, never heard from again. Opening a Claude Code tab starts
228 * one before anything is typed in it, and it is nothing to show yet.
229 */
230export function startedOnly(session: WorkSession): boolean {
231 return !session.title && session.item == null && session.pull == null && session.lastSeenAt === session.startedAt;
232}
233
234/**
235 * The sessions Live now lists, and those it folds away: one not heard from
236 * for 15 minutes (idle) is someone's open tab more often than work going
237 * on, so it waits under the list until it is heard from or times out. One
238 * that has done nothing since it started is in neither.
239 */
240export function awakeAndIdle(sessions: WorkSession[]): { awake: WorkSession[]; idle: WorkSession[] } {
241 const awake: WorkSession[] = [];
242 const idle: WorkSession[] = [];
243 for (const session of sessions) {
244 if (!startedOnly(session)) (session.state === "idle" ? idle : awake).push(session);
245 }
246 idle.sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt));
247 return { awake, idle };
248}
249
250const latestSeen = (sessions: WorkSession[]) => Math.max(0, ...sessions.map((session) => Date.parse(session.lastSeenAt)));
251
252/**
253 * Active claims and sessions grouped by the work item they are on, the item
254 * with the most recent activity first. Sessions on no work item are grouped
255 * after them (`groups`): by their pull request, else by their branch when
256 * it is not `defaultBranch`, the most recently heard from first; the rest,
257 * on no branch of their own, last together. `loose` is every session on no
258 * work item, as the groups hold them.
259 */
260export function liveByItem(
261 claims: Claim[],
262 sessions: WorkSession[],
263 defaultBranch?: string | null,
264): { items: LiveItem[]; groups: LiveGroup[]; loose: WorkSession[] } {
265 const byItem = new Map<number, LiveItem>();
266 const at = (item: number) => {
267 let group = byItem.get(item);
268 if (!group) byItem.set(item, (group = { item, claims: [], sessions: [] }));
269 return group;
270 };
271 for (const claim of claims) at(claim.item).claims.push(claim);
272 const byPull = new Map<number, LiveGroup & { kind: "pull" }>();
273 const byBranch = new Map<string, LiveGroup & { kind: "branch" }>();
274 const rest: WorkSession[] = [];
275 for (const session of sessions) {
276 if (session.item != null) at(session.item).sessions.push(session);
277 else if (session.pull != null) {
278 const group = byPull.get(session.pull) ?? { kind: "pull" as const, pull: session.pull, sessions: [] };
279 byPull.set(session.pull, group);
280 group.sessions.push(session);
281 } else if (session.branch && session.branch !== defaultBranch) {
282 const group = byBranch.get(session.branch) ?? { kind: "branch" as const, branch: session.branch, sessions: [] };
283 byBranch.set(session.branch, group);
284 group.sessions.push(session);
285 } else rest.push(session);
286 }
287 const latest = (group: LiveItem) => Math.max(latestSeen(group.sessions), ...group.claims.map((claim) => Date.parse(claim.createdAt)));
288 const recent = (a: LiveGroup, b: LiveGroup) => latestSeen(b.sessions) - latestSeen(a.sessions);
289 const groups: LiveGroup[] = [...byPull.values(), ...byBranch.values()].sort(recent);
290 if (rest.length > 0) groups.push({ kind: "none", sessions: rest });
291 for (const group of groups) group.sessions.sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt));
292 return {
293 items: [...byItem.values()].sort((a, b) => latest(b) - latest(a) || a.item - b.item),
294 groups,
295 loose: groups.flatMap((group) => group.sessions),
296 };
297}
298
299// ── Decisions ───────────────────────────────────────────────────────────
300
301export const CONFIDENCE: Record<DecisionConfidence, { label: string; hint: string; tone: "neutral" | "info" | "success" }> = {
302 claimed: { label: "Claimed", hint: "Someone said so: an agent or a person recorded it.", tone: "neutral" },
303 tested: { label: "Tested", hint: "A check or the merge queue proved it.", tone: "info" },
304 approved: { label: "Approved", hint: "A person approved it.", tone: "success" },
305};
306
307export const DECISION_KINDS: Record<Decision["kind"], string> = {
308 proposal: "Proposal",
309 claim: "Claim",
310 integration_failure: "Failed together",
311 integration_passed: "Passed together",
312 fix: "Fix",
313 approval: "Approval",
314 merge: "Merge",
315 note: "Note",
316};
317
318/** The check a decision's evidence names. */
319export type EvidenceCheck = { name: string; conclusion: string; url: string | null };
320
321/** What a decision rests on, read from its evidence as far as it says. */
322export type Evidence = {
323 commit: string | null;
324 check: EvidenceCheck | null;
325 /** The pull requests tested together, in queue order. */
326 combination: number[];
327 /** Those ahead it fails with. */
328 suspects: number[];
329 bisected: boolean;
330};
331
332function numbers(value: unknown): number[] {
333 return Array.isArray(value) ? value.filter((n): n is number => typeof n === "number" && Number.isInteger(n)) : [];
334}
335
336export function evidenceOf(decision: Pick<Decision, "evidence">): Evidence {
337 const raw = (decision.evidence ?? {}) as Record<string, unknown>;
338 const check = raw.check && typeof raw.check === "object" ? (raw.check as Record<string, unknown>) : null;
339 return {
340 commit: typeof raw.commit === "string" ? raw.commit : null,
341 check:
342 check && typeof check.name === "string"
343 ? {
344 name: check.name,
345 conclusion: typeof check.conclusion === "string" ? check.conclusion : "failure",
346 url: typeof check.url === "string" && check.url ? check.url : null,
347 }
348 : null,
349 combination: numbers(raw.combination),
350 suspects: numbers(raw.suspects),
351 bisected: raw.bisected === true,
352 };
353}
354
355/** Where a check's address leads on the site: its path when it is g1t's own, else the address as it is. */
356export function checkHref(url: string | null): string | null {
357 if (!url) return null;
358 try {
359 const parsed = new URL(url);
360 if (parsed.hostname === "g1t.sh" || parsed.hostname.endsWith(".g1t.sh")) return parsed.pathname + parsed.search;
361 return url;
362 } catch {
363 return url.startsWith("/") ? url : null;
364 }
365}
366
367/**
368 * The integration failure a pull request still answers for: its latest
369 * `integration_failure`, unless it passed in the queue or merged since.
370 * `decisions` in any order.
371 */
372export function standingFailure(decisions: Decision[], pull?: number): Decision | null {
373 const mine = decisions
374 .filter((decision) => pull == null || decision.pull === pull)
375 .filter((decision) => ["integration_failure", "integration_passed", "merge"].includes(decision.kind))
376 .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
377 return mine[0]?.kind === "integration_failure" ? mine[0] : null;
378}
379
380/** The decisions after a failure that answer it: a fix recorded since, and a combination that then passed. */
381export function resolutionOf(decisions: Decision[], failure: Decision): { fix: Decision | null; passed: Decision | null } {
382 const after = decisions
383 .filter((decision) => Date.parse(decision.createdAt) > Date.parse(failure.createdAt))
384 .sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
385 return {
386 fix: after.find((decision) => decision.kind === "fix" && (decision.pull === failure.pull || decision.item === failure.item)) ?? null,
387 passed: after.find((decision) => decision.kind === "integration_passed" && decision.pull === failure.pull) ?? null,
388 };
389}
390
391// ── The feed ────────────────────────────────────────────────────────────
392
393/** One line of the coordination feed: what happened, in words, and what it links to. */
394export type FeedLine = {
395 id: string;
396 time: string;
397 type: CoordinationType;
398 /** Who did it, by username; null for g1t itself. */
399 who: string | null;
400 /** The harness it came from, when it says. */
401 harness: Harness | null;
402 /** The sentence, after the name. Numbers in it are written `#N`. */
403 text: string;
404 /** The work item or pull request it is about. */
405 number: number | null;
406 /** The harness session it is about, by id, for a link to its page. */
407 session?: string;
408 /** The repository it happened in, `owner/name`, in a feed across a workspace's. */
409 repo?: string;
410 tone: "neutral" | "accent" | "success" | "warn" | "danger" | "info";
411};
412
413const list = (all: number[]) => all.map((n) => `#${n}`).join(", ");
414const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
415
416/** A session's pending updates as lines of the feed, oldest first. */
417export function pendingLines(updates: { id: string; kind: string; data: unknown; at: string }[]): FeedLine[] {
418 return updates.flatMap((update) => {
419 if (!(COORDINATION_TYPES as readonly string[]).includes(update.kind)) return [];
420 const event = { id: update.id, type: update.kind, time: update.at, source: "work", repoId: null, actor: null, data: update.data } as G1tEvent;
421 return feedLine(event) ?? [];
422 });
423}
424
425/** A coordination event as a line of the feed, or null for one it does not show. */
426export function feedLine(event: G1tEvent): FeedLine | null {
427 const base = { id: event.id, time: event.time, harness: null as Harness | null, number: null as number | null };
428 const data = event.data as Record<string, unknown> & { number?: number };
429 const number = typeof data.number === "number" ? data.number : null;
430 switch (event.type) {
431 case "work.claimed": {
432 const { claim, others = [], tookOver } = event.data;
433 const also = others.length > 0 ? ` (${others.map((other) => other.actor.username).join(", ")} ${plural(others.length, "is", "are")} on it too)` : "";
434 return {
435 ...base,
436 type: event.type,
437 who: claim.actor.username,
438 harness: claim.harness,
439 text: `${tookOver ? "took over" : "claimed"} #${claim.item}${also}`,
440 number: claim.item,
441 tone: others.length > 0 ? "warn" : "accent",
442 };
443 }
444 case "work.released": {
445 const { claim, reason } = event.data;
446 return {
447 ...base,
448 type: event.type,
449 who: claim.actor.username,
450 harness: claim.harness,
451 text: reason === "item_closed" ? `no longer holds #${claim.item}: the work item closed` : `released #${claim.item}${reason ? `: ${reason}` : ""}`,
452 number: claim.item,
453 tone: "neutral",
454 };
455 }
456 case "work.claim_expired": {
457 const { claim } = event.data;
458 return { ...base, type: event.type, who: claim.actor.username, harness: claim.harness, text: `let the claim on #${claim.item} expire`, number: claim.item, tone: "neutral" };
459 }
460 case "work.handoff_requested": {
461 const { claim, to, note } = event.data;
462 return {
463 ...base,
464 type: event.type,
465 who: claim.actor.username,
466 harness: claim.harness,
467 text: `handed #${claim.item} off to ${to ?? "anyone"}${note ? `: ${note}` : ""}`,
468 number: claim.item,
469 tone: "info",
470 };
471 }
472 case "session.started":
473 case "session.ended": {
474 const { session } = event.data;
475 const on = session.item != null ? ` on #${session.item}` : session.pull != null ? ` on #${session.pull}` : "";
476 const why = event.type === "session.ended" && session.endReason === "timed_out" ? " (timed out)" : "";
477 // Ended by hand: by whoever ran it, or by someone with write access for them.
478 const byHand = event.type === "session.ended" && session.endReason?.startsWith(ENDED_BY_HAND) ? session.endReason.slice(ENDED_BY_HAND.length) : null;
479 if (byHand) {
480 const own = byHand === session.actor.username;
481 return {
482 ...base,
483 type: event.type,
484 who: byHand,
485 harness: own ? session.harness : null,
486 text: own ? `ended a session${on} by hand` : `ended ${session.actor.username}'s session${on} by hand`,
487 number: session.item ?? session.pull,
488 tone: "neutral",
489 };
490 }
491 return {
492 ...base,
493 type: event.type,
494 who: session.actor.username,
495 harness: session.harness,
496 text: `${event.type === "session.started" ? "started a session" : "ended a session"}${on}${why}`,
497 number: session.item ?? session.pull,
498 tone: event.type === "session.started" ? "accent" : "neutral",
499 };
500 }
501 case "dependency.changed": {
502 const { item, added, removed, cleared, remaining, mergedPull } = event.data;
503 const parts = [
504 added.length > 0 && `now waits on ${list(added)}`,
505 removed.length > 0 && `no longer waits on ${list(removed)}`,
506 cleared.length > 0 && `${list(cleared)} ${mergedPull ? `landed (#${mergedPull} merged)` : "closed"}`,
507 ].filter(Boolean);
508 // What it still waits on, unless that is only what was just added.
509 const said = remaining.every((n) => added.includes(n)) && parts.length > 0;
510 const left = remaining.length === 0 ? "unblocked" : said ? null : `still waits on ${list(remaining)}`;
511 return {
512 ...base,
513 type: event.type,
514 who: null,
515 text: `#${item} ${[...parts, left].filter(Boolean).join("; ")}`,
516 number: item,
517 tone: remaining.length === 0 ? "success" : "info",
518 };
519 }
520 case "overlap.detected": {
521 if ("sessionId" in event.data) {
522 const { sessionId, otherActor, files, item } = event.data;
523 return {
524 ...base,
525 type: event.type,
526 who: otherActor,
527 text: `touched the same ${plural(files.length, "file", "files")} in a session as another session: ${files.slice(0, 3).join(", ")}${files.length > 3 ? ` and ${files.length - 3} more` : ""}`,
528 number: item ?? number,
529 session: sessionId,
530 tone: "warn",
531 };
532 }
533 const { pull, otherPull, files } = event.data;
534 return {
535 ...base,
536 type: event.type,
537 who: null,
538 text: `#${pull} and #${otherPull} change the same ${plural(files.length, "file", "files")}: ${files.slice(0, 3).join(", ")}${files.length > 3 ? ` and ${files.length - 3} more` : ""}`,
539 number: pull,
540 tone: "warn",
541 };
542 }
543 case "integration.failed": {
544 const { pull, combination, check, suspects } = event.data;
545 const together = combination.length > 1 ? ` combined as ${list(combination)}` : " on its own";
546 const with_ = suspects.length > 0 ? `; fails with ${list(suspects)}` : "";
547 return { ...base, type: event.type, who: null, text: `#${pull} failed in the merge queue${together}: ${check.name}${with_}`, number: pull, tone: "danger" };
548 }
549 case "integration.passed": {
550 const { pull, combination } = event.data;
551 return {
552 ...base,
553 type: event.type,
554 who: null,
555 text: combination.length > 1 ? `#${pull} passed in the merge queue combined as ${list(combination)}` : `#${pull} passed in the merge queue`,
556 number: pull,
557 tone: "success",
558 };
559 }
560 case "decision.recorded": {
561 const { decision } = event.data;
562 const kind = DECISION_KINDS[decision.kind as Decision["kind"]]?.toLowerCase() ?? decision.kind;
563 return {
564 ...base,
565 type: event.type,
566 who: decision.actor,
567 text: `recorded ${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}, ${decision.confidence}: ${decision.summary}`,
568 number: decision.pull ?? decision.item ?? number,
569 tone: decision.kind === "integration_failure" ? "danger" : decision.confidence === "approved" ? "success" : "neutral",
570 };
571 }
572 // Steps of a session as it goes: for the pages showing it, not the feed.
573 case "session.progressed":
574 default:
575 return null;
576 }
577}
578
579// ── Session trees ───────────────────────────────────────────────────────
580
581/** A session with its subagents under it, and theirs under them. */
582export type SessionNode = { session: WorkSession; children: SessionNode[] };
583
584/**
585 * Sessions as trees, by `parentId`: the roots in the order given, each
586 * with its subagents in the order given. One whose parent is not in the
587 * list is a root of its own.
588 */
589export function sessionTree(sessions: WorkSession[]): SessionNode[] {
590 const nodes = new Map<string, SessionNode>();
591 for (const session of sessions) if (!nodes.has(session.id)) nodes.set(session.id, { session, children: [] });
592 const roots: SessionNode[] = [];
593 for (const node of nodes.values()) {
594 const parent = node.session.parentId ? nodes.get(node.session.parentId) : undefined;
595 // A parent that is the session itself or under it (a cycle) does not count.
596 if (parent && !contains(node, parent)) parent.children.push(node);
597 else roots.push(node);
598 }
599 return roots;
600}
601
602/** The sessions of several lists, each once (as the first list to have it says), in the order first given. */
603export function mergeSessions(...lists: (WorkSession[] | null | undefined)[]): WorkSession[] {
604 const seen = new Map<string, WorkSession>();
605 for (const list of lists) for (const session of list ?? []) if (!seen.has(session.id)) seen.set(session.id, session);
606 return [...seen.values()];
607}
608
609function contains(node: SessionNode, target: SessionNode): boolean {
610 return node === target || node.children.some((child) => contains(child, target));
611}
612
613/** How many sessions are under a tree's root, at any depth. */
614export function treeSize(node: SessionNode): number {
615 return node.children.reduce((total, child) => total + 1 + treeSize(child), 0);
616}
617
618/** How a session was tied to a work item or pull request, in a few words. */
619export const VIA_LABELS: Record<LinkVia, string> = {
620 attached: "attached",
621 claim: "claimed",
622 branch: "its branch",
623 commit: "its commit",
624 trailer: "commit trailer",
625 opened: "opened it",
626 ref: "named it",
627};
628
629export function viaLabel(via: LinkVia): string {
630 return VIA_LABELS[via] ?? via;
631}
632
633/** What each kind of thing a session touched is called. */
634export const TOUCH_KINDS: Record<TouchKind, string> = {
635 file: "Files",
636 commit: "Commits",
637 branch: "Branches",
638 pull: "Pull requests",
639 item: "Work items",
640};
641
642/** What was touched, grouped by kind in TOUCH_KINDS' order, each value once, in the order given. */
643export function touchedByKind(touched: { kind: TouchKind; value: string }[]): { kind: TouchKind; values: string[] }[] {
644 return (Object.keys(TOUCH_KINDS) as TouchKind[])
645 .map((kind) => ({ kind, values: [...new Set(touched.filter((one) => one.kind === kind).map((one) => one.value))] }))
646 .filter((group) => group.values.length > 0);
647}
648
649/** "12s", "4m", "1h 20m": how long a session ran, or has run until `now`. */
650export function duration(session: Pick<WorkSession, "startedAt" | "endedAt" | "lastSeenAt" | "state">, now: number): string {
651 const end = session.endedAt ? Date.parse(session.endedAt) : session.state === "ended" ? Date.parse(session.lastSeenAt) : now;
652 const ms = Math.max(0, end - Date.parse(session.startedAt));
653 return ms < MINUTE ? `${Math.floor(ms / 1000)}s` : span(ms);
654}
655
656/** Splits text at `#N`, for linking each number. */
657export function numberedParts(text: string): (string | number)[] {
658 const parts: (string | number)[] = [];
659 let last = 0;
660 for (const match of text.matchAll(/#(\d+)\b/g)) {
661 if (match.index > last) parts.push(text.slice(last, match.index));
662 parts.push(Number(match[1]));
663 last = match.index + match[0].length;
664 }
665 if (last < text.length) parts.push(text.slice(last));
666 return parts;
667}
668
669/** `blocked_by` as typed: numbers, with or without `#`, by commas or spaces; null when any is not one. */
670export function parseBlockedBy(text: string): number[] | null {
671 const words = text.split(/[\s,]+/).map((word) => word.trim().replace(/^#/, "")).filter(Boolean);
672 if (words.some((word) => !/^\d+$/.test(word) || Number(word) <= 0)) return null;
673 return [...new Set(words.map(Number))];
674}
675
676/** Where a pull request a work item's decisions name is, by its number: null when it is not known. */
677export type PullHref = (number: number) => string | null;
678
679/**
680 * Where each of a work item's pull requests is, from its repositories and
681 * their pull requests: `/<owner>/<repo>/pull/<n>` in the one repository
682 * that has it. A number none of them has (or that two have, from before
683 * numbers were the workspace's) is not linked, rather than linked to the
684 * wrong repository. A deleted repository, with no path, has none.
685 */
686export function pullHrefs(repos: readonly { path: string; pulls: readonly { number: number }[] }[]): PullHref {
687 const where = new Map<number, string | null>();
688 for (const repo of repos) {
689 if (!repo.path) continue;
690 for (const pull of repo.pulls) {
691 const seen = where.get(pull.number);
692 where.set(pull.number, seen === undefined || seen === repo.path ? repo.path : null);
693 }
694 }
695 return (number) => {
696 const path = where.get(number);
697 return path ? `/${path}/pull/${number}` : null;
698 };
699}