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.

672 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 tone: "neutral" | "accent" | "success" | "warn" | "danger" | "info";
409};
410
411const list = (all: number[]) => all.map((n) => `#${n}`).join(", ");
412const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
413
414/** A session's pending updates as lines of the feed, oldest first. */
415export function pendingLines(updates: { id: string; kind: string; data: unknown; at: string }[]): FeedLine[] {
416 return updates.flatMap((update) => {
417 if (!(COORDINATION_TYPES as readonly string[]).includes(update.kind)) return [];
418 const event = { id: update.id, type: update.kind, time: update.at, source: "work", repoId: null, actor: null, data: update.data } as G1tEvent;
419 return feedLine(event) ?? [];
420 });
421}
422
423/** A coordination event as a line of the feed, or null for one it does not show. */
424export function feedLine(event: G1tEvent): FeedLine | null {
425 const base = { id: event.id, time: event.time, harness: null as Harness | null, number: null as number | null };
426 const data = event.data as Record<string, unknown> & { number?: number };
427 const number = typeof data.number === "number" ? data.number : null;
428 switch (event.type) {
429 case "work.claimed": {
430 const { claim, others = [], tookOver } = event.data;
431 const also = others.length > 0 ? ` (${others.map((other) => other.actor.username).join(", ")} ${plural(others.length, "is", "are")} on it too)` : "";
432 return {
433 ...base,
434 type: event.type,
435 who: claim.actor.username,
436 harness: claim.harness,
437 text: `${tookOver ? "took over" : "claimed"} #${claim.item}${also}`,
438 number: claim.item,
439 tone: others.length > 0 ? "warn" : "accent",
440 };
441 }
442 case "work.released": {
443 const { claim, reason } = event.data;
444 return {
445 ...base,
446 type: event.type,
447 who: claim.actor.username,
448 harness: claim.harness,
449 text: reason === "item_closed" ? `no longer holds #${claim.item}: the work item closed` : `released #${claim.item}${reason ? `: ${reason}` : ""}`,
450 number: claim.item,
451 tone: "neutral",
452 };
453 }
454 case "work.claim_expired": {
455 const { claim } = event.data;
456 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" };
457 }
458 case "work.handoff_requested": {
459 const { claim, to, note } = event.data;
460 return {
461 ...base,
462 type: event.type,
463 who: claim.actor.username,
464 harness: claim.harness,
465 text: `handed #${claim.item} off to ${to ?? "anyone"}${note ? `: ${note}` : ""}`,
466 number: claim.item,
467 tone: "info",
468 };
469 }
470 case "session.started":
471 case "session.ended": {
472 const { session } = event.data;
473 const on = session.item != null ? ` on #${session.item}` : session.pull != null ? ` on #${session.pull}` : "";
474 const why = event.type === "session.ended" && session.endReason === "timed_out" ? " (timed out)" : "";
475 // Ended by hand: by whoever ran it, or by someone with write access for them.
476 const byHand = event.type === "session.ended" && session.endReason?.startsWith(ENDED_BY_HAND) ? session.endReason.slice(ENDED_BY_HAND.length) : null;
477 if (byHand) {
478 const own = byHand === session.actor.username;
479 return {
480 ...base,
481 type: event.type,
482 who: byHand,
483 harness: own ? session.harness : null,
484 text: own ? `ended a session${on} by hand` : `ended ${session.actor.username}'s session${on} by hand`,
485 number: session.item ?? session.pull,
486 tone: "neutral",
487 };
488 }
489 return {
490 ...base,
491 type: event.type,
492 who: session.actor.username,
493 harness: session.harness,
494 text: `${event.type === "session.started" ? "started a session" : "ended a session"}${on}${why}`,
495 number: session.item ?? session.pull,
496 tone: event.type === "session.started" ? "accent" : "neutral",
497 };
498 }
499 case "dependency.changed": {
500 const { item, added, removed, cleared, remaining, mergedPull } = event.data;
501 const parts = [
502 added.length > 0 && `now waits on ${list(added)}`,
503 removed.length > 0 && `no longer waits on ${list(removed)}`,
504 cleared.length > 0 && `${list(cleared)} ${mergedPull ? `landed (#${mergedPull} merged)` : "closed"}`,
505 ].filter(Boolean);
506 // What it still waits on, unless that is only what was just added.
507 const said = remaining.every((n) => added.includes(n)) && parts.length > 0;
508 const left = remaining.length === 0 ? "unblocked" : said ? null : `still waits on ${list(remaining)}`;
509 return {
510 ...base,
511 type: event.type,
512 who: null,
513 text: `#${item} ${[...parts, left].filter(Boolean).join("; ")}`,
514 number: item,
515 tone: remaining.length === 0 ? "success" : "info",
516 };
517 }
518 case "overlap.detected": {
519 if ("sessionId" in event.data) {
520 const { sessionId, otherActor, files, item } = event.data;
521 return {
522 ...base,
523 type: event.type,
524 who: otherActor,
525 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` : ""}`,
526 number: item ?? number,
527 session: sessionId,
528 tone: "warn",
529 };
530 }
531 const { pull, otherPull, files } = event.data;
532 return {
533 ...base,
534 type: event.type,
535 who: null,
536 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` : ""}`,
537 number: pull,
538 tone: "warn",
539 };
540 }
541 case "integration.failed": {
542 const { pull, combination, check, suspects } = event.data;
543 const together = combination.length > 1 ? ` combined as ${list(combination)}` : " on its own";
544 const with_ = suspects.length > 0 ? `; fails with ${list(suspects)}` : "";
545 return { ...base, type: event.type, who: null, text: `#${pull} failed in the merge queue${together}: ${check.name}${with_}`, number: pull, tone: "danger" };
546 }
547 case "integration.passed": {
548 const { pull, combination } = event.data;
549 return {
550 ...base,
551 type: event.type,
552 who: null,
553 text: combination.length > 1 ? `#${pull} passed in the merge queue combined as ${list(combination)}` : `#${pull} passed in the merge queue`,
554 number: pull,
555 tone: "success",
556 };
557 }
558 case "decision.recorded": {
559 const { decision } = event.data;
560 const kind = DECISION_KINDS[decision.kind as Decision["kind"]]?.toLowerCase() ?? decision.kind;
561 return {
562 ...base,
563 type: event.type,
564 who: decision.actor,
565 text: `recorded ${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}, ${decision.confidence}: ${decision.summary}`,
566 number: decision.pull ?? decision.item ?? number,
567 tone: decision.kind === "integration_failure" ? "danger" : decision.confidence === "approved" ? "success" : "neutral",
568 };
569 }
570 // Steps of a session as it goes: for the pages showing it, not the feed.
571 case "session.progressed":
572 default:
573 return null;
574 }
575}
576
577// ── Session trees ───────────────────────────────────────────────────────
578
579/** A session with its subagents under it, and theirs under them. */
580export type SessionNode = { session: WorkSession; children: SessionNode[] };
581
582/**
583 * Sessions as trees, by `parentId`: the roots in the order given, each
584 * with its subagents in the order given. One whose parent is not in the
585 * list is a root of its own.
586 */
587export function sessionTree(sessions: WorkSession[]): SessionNode[] {
588 const nodes = new Map<string, SessionNode>();
589 for (const session of sessions) if (!nodes.has(session.id)) nodes.set(session.id, { session, children: [] });
590 const roots: SessionNode[] = [];
591 for (const node of nodes.values()) {
592 const parent = node.session.parentId ? nodes.get(node.session.parentId) : undefined;
593 // A parent that is the session itself or under it (a cycle) does not count.
594 if (parent && !contains(node, parent)) parent.children.push(node);
595 else roots.push(node);
596 }
597 return roots;
598}
599
600/** The sessions of several lists, each once (as the first list to have it says), in the order first given. */
601export function mergeSessions(...lists: (WorkSession[] | null | undefined)[]): WorkSession[] {
602 const seen = new Map<string, WorkSession>();
603 for (const list of lists) for (const session of list ?? []) if (!seen.has(session.id)) seen.set(session.id, session);
604 return [...seen.values()];
605}
606
607function contains(node: SessionNode, target: SessionNode): boolean {
608 return node === target || node.children.some((child) => contains(child, target));
609}
610
611/** How many sessions are under a tree's root, at any depth. */
612export function treeSize(node: SessionNode): number {
613 return node.children.reduce((total, child) => total + 1 + treeSize(child), 0);
614}
615
616/** How a session was tied to a work item or pull request, in a few words. */
617export const VIA_LABELS: Record<LinkVia, string> = {
618 attached: "attached",
619 claim: "claimed",
620 branch: "its branch",
621 commit: "its commit",
622 trailer: "commit trailer",
623 opened: "opened it",
624 ref: "named it",
625};
626
627export function viaLabel(via: LinkVia): string {
628 return VIA_LABELS[via] ?? via;
629}
630
631/** What each kind of thing a session touched is called. */
632export const TOUCH_KINDS: Record<TouchKind, string> = {
633 file: "Files",
634 commit: "Commits",
635 branch: "Branches",
636 pull: "Pull requests",
637 item: "Work items",
638};
639
640/** What was touched, grouped by kind in TOUCH_KINDS' order, each value once, in the order given. */
641export function touchedByKind(touched: { kind: TouchKind; value: string }[]): { kind: TouchKind; values: string[] }[] {
642 return (Object.keys(TOUCH_KINDS) as TouchKind[])
643 .map((kind) => ({ kind, values: [...new Set(touched.filter((one) => one.kind === kind).map((one) => one.value))] }))
644 .filter((group) => group.values.length > 0);
645}
646
647/** "12s", "4m", "1h 20m": how long a session ran, or has run until `now`. */
648export function duration(session: Pick<WorkSession, "startedAt" | "endedAt" | "lastSeenAt" | "state">, now: number): string {
649 const end = session.endedAt ? Date.parse(session.endedAt) : session.state === "ended" ? Date.parse(session.lastSeenAt) : now;
650 const ms = Math.max(0, end - Date.parse(session.startedAt));
651 return ms < MINUTE ? `${Math.floor(ms / 1000)}s` : span(ms);
652}
653
654/** Splits text at `#N`, for linking each number. */
655export function numberedParts(text: string): (string | number)[] {
656 const parts: (string | number)[] = [];
657 let last = 0;
658 for (const match of text.matchAll(/#(\d+)\b/g)) {
659 if (match.index > last) parts.push(text.slice(last, match.index));
660 parts.push(Number(match[1]));
661 last = match.index + match[0].length;
662 }
663 if (last < text.length) parts.push(text.slice(last));
664 return parts;
665}
666
667/** `blocked_by` as typed: numbers, with or without `#`, by commas or spaces; null when any is not one. */
668export function parseBlockedBy(text: string): number[] | null {
669 const words = text.split(/[\s,]+/).map((word) => word.trim().replace(/^#/, "")).filter(Boolean);
670 if (words.some((word) => !/^\d+$/.test(word) || Number(word) <= 0)) return null;
671 return [...new Set(words.map(Number))];
672}