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.

644 linesCodeBlameRaw
1/**
2 * Coordinating work, as the site shows it: who is on which issue (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 Work 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 Claude Code plugin
132 * (plugins/claude-code/hooks/g1t.mjs) titles its sessions the same way.
133 */
134export function intentTitle(prompt: string | null | undefined): string | null {
135 let text = String(prompt ?? "").replace(/^\uFEFF/, "");
136 // What the harness pasted in or attached is not what the prompt is for:
137 // pasted text (Claude Code's <pasted_content id="…">…</pasted_content>)
138 // and image placeholders ([Image #1], [Image: source: …]) go first.
139 text = text
140 .replace(/<pasted_content\b[^>]*>[\s\S]*?(?:<\/pasted_content[^>]*>|$)/gi, "\n")
141 .replace(/\[Image(?: #\d+)?(?::[^\]\n]*)?\]/g, " ");
142 // Context an editor puts before what was typed (VS Code's
143 // <ide_opened_file>, <ide_selection>) is not a turn the harness started.
144 while (IDE_CONTEXT.test(text)) text = text.replace(IDE_CONTEXT, "");
145 if (/^\s*\//.test(text) || HARNESS_TAG.test(text)) return null;
146 text = text
147 .replace(/```[\s\S]*?(```|$)/g, "\n")
148 .replace(/~~~[\s\S]*?(~~~|$)/g, "\n")
149 .replace(/!\[([^\]]*)\]\([^)]*\)/g, "$1")
150 .replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
151 .replace(/`([^`]*)`/g, "$1");
152 const line = text
153 .split(/\r?\n/)
154 .map((l) => l.replace(/^\s*(?:#{1,6}\s+|>\s*|[-*+]\s+|\d+[.)]\s+)+/, "").replace(/(\*\*|__|~~)(.+?)\1/g, "$2").trim())
155 .find((l) => /[\p{L}\p{N}]/u.test(l));
156 if (!line) return null;
157 let intent = line.replace(/\s+/g, " ").split(/(?<=[.!?])\s+(?=\S)/)[0].trim();
158 if (intent.length > TITLE_LIMIT) {
159 const cut = intent.slice(0, TITLE_LIMIT - 1);
160 const space = cut.lastIndexOf(" ");
161 intent = `${(space > TITLE_LIMIT / 2 ? cut.slice(0, space) : cut).replace(/[\s,;:.\-–—]+$/, "")}…`;
162 } else {
163 intent = intent.replace(/[\s,;:.]+$/, "");
164 }
165 if (intent.length < 2) return null;
166 return intent[0].toLocaleUpperCase() + intent.slice(1);
167}
168
169/**
170 * What a session is called, never nothing: its title, else what its first
171 * prompt was for, else the branch it is on, else "Untitled session".
172 * `firstPrompt` stands in for the session's own when given.
173 */
174export function sessionTitle(
175 session: Pick<WorkSession, "title" | "branch" | "firstPrompt">,
176 firstPrompt: string | null | undefined = session.firstPrompt,
177): string {
178 // A title that is only a harness tag (an early plugin's from a pasted prompt) reads as none.
179 const title = session.title?.trim();
180 if (title && !HARNESS_TAG.test(title)) return title;
181 const intent = intentTitle(firstPrompt);
182 if (intent) return intent;
183 return session.branch ? `Session on ${session.branch}` : "Untitled session";
184}
185
186// ── Live now ────────────────────────────────────────────────────────────
187
188/** One issue being worked on: its claims and the sessions on it. */
189export type LiveIssue = { issue: number; claims: Claim[]; sessions: WorkSession[] };
190
191/** Sessions on no issue yet, together: on one pull request, on one branch of their own, or on neither. */
192export type LiveGroup =
193 | { kind: "pull"; pull: number; sessions: WorkSession[] }
194 | { kind: "branch"; branch: string; sessions: WorkSession[] }
195 | { kind: "none"; sessions: WorkSession[] };
196
197/**
198 * Whether a session has done nothing since it started: no title, no issue
199 * or pull request, never heard from again. Opening a Claude Code tab starts
200 * one before anything is typed in it, and it is nothing to show yet.
201 */
202export function startedOnly(session: WorkSession): boolean {
203 return !session.title && session.issue == null && session.pull == null && session.lastSeenAt === session.startedAt;
204}
205
206/**
207 * The sessions Live now lists, and those it folds away: one not heard from
208 * for 15 minutes (idle) is someone's open tab more often than work going
209 * on, so it waits under the list until it is heard from or times out. One
210 * that has done nothing since it started is in neither.
211 */
212export function awakeAndIdle(sessions: WorkSession[]): { awake: WorkSession[]; idle: WorkSession[] } {
213 const awake: WorkSession[] = [];
214 const idle: WorkSession[] = [];
215 for (const session of sessions) {
216 if (!startedOnly(session)) (session.state === "idle" ? idle : awake).push(session);
217 }
218 idle.sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt));
219 return { awake, idle };
220}
221
222const latestSeen = (sessions: WorkSession[]) => Math.max(0, ...sessions.map((session) => Date.parse(session.lastSeenAt)));
223
224/**
225 * Active claims and sessions grouped by the issue they are on, the issue
226 * with the most recent activity first. Sessions on no issue are grouped
227 * after them (`groups`): by their pull request, else by their branch when
228 * it is not `defaultBranch`, the most recently heard from first; the rest,
229 * on no branch of their own, last together. `loose` is every session on no
230 * issue, as the groups hold them.
231 */
232export function liveByIssue(
233 claims: Claim[],
234 sessions: WorkSession[],
235 defaultBranch?: string | null,
236): { issues: LiveIssue[]; groups: LiveGroup[]; loose: WorkSession[] } {
237 const byIssue = new Map<number, LiveIssue>();
238 const at = (issue: number) => {
239 let group = byIssue.get(issue);
240 if (!group) byIssue.set(issue, (group = { issue, claims: [], sessions: [] }));
241 return group;
242 };
243 for (const claim of claims) at(claim.issue).claims.push(claim);
244 const byPull = new Map<number, LiveGroup & { kind: "pull" }>();
245 const byBranch = new Map<string, LiveGroup & { kind: "branch" }>();
246 const rest: WorkSession[] = [];
247 for (const session of sessions) {
248 if (session.issue != null) at(session.issue).sessions.push(session);
249 else if (session.pull != null) {
250 const group = byPull.get(session.pull) ?? { kind: "pull" as const, pull: session.pull, sessions: [] };
251 byPull.set(session.pull, group);
252 group.sessions.push(session);
253 } else if (session.branch && session.branch !== defaultBranch) {
254 const group = byBranch.get(session.branch) ?? { kind: "branch" as const, branch: session.branch, sessions: [] };
255 byBranch.set(session.branch, group);
256 group.sessions.push(session);
257 } else rest.push(session);
258 }
259 const latest = (group: LiveIssue) => Math.max(latestSeen(group.sessions), ...group.claims.map((claim) => Date.parse(claim.createdAt)));
260 const recent = (a: LiveGroup, b: LiveGroup) => latestSeen(b.sessions) - latestSeen(a.sessions);
261 const groups: LiveGroup[] = [...byPull.values(), ...byBranch.values()].sort(recent);
262 if (rest.length > 0) groups.push({ kind: "none", sessions: rest });
263 for (const group of groups) group.sessions.sort((a, b) => Date.parse(b.lastSeenAt) - Date.parse(a.lastSeenAt));
264 return {
265 issues: [...byIssue.values()].sort((a, b) => latest(b) - latest(a) || a.issue - b.issue),
266 groups,
267 loose: groups.flatMap((group) => group.sessions),
268 };
269}
270
271// ── Decisions ───────────────────────────────────────────────────────────
272
273export const CONFIDENCE: Record<DecisionConfidence, { label: string; hint: string; tone: "neutral" | "info" | "success" }> = {
274 claimed: { label: "Claimed", hint: "Someone said so: an agent or a person recorded it.", tone: "neutral" },
275 tested: { label: "Tested", hint: "A check or the merge queue proved it.", tone: "info" },
276 approved: { label: "Approved", hint: "A person approved it.", tone: "success" },
277};
278
279export const DECISION_KINDS: Record<Decision["kind"], string> = {
280 proposal: "Proposal",
281 claim: "Claim",
282 integration_failure: "Failed together",
283 integration_passed: "Passed together",
284 fix: "Fix",
285 approval: "Approval",
286 merge: "Merge",
287 note: "Note",
288};
289
290/** The check a decision's evidence names. */
291export type EvidenceCheck = { name: string; conclusion: string; url: string | null };
292
293/** What a decision rests on, read from its evidence as far as it says. */
294export type Evidence = {
295 commit: string | null;
296 check: EvidenceCheck | null;
297 /** The pull requests tested together, in queue order. */
298 combination: number[];
299 /** Those ahead it fails with. */
300 suspects: number[];
301 bisected: boolean;
302};
303
304function numbers(value: unknown): number[] {
305 return Array.isArray(value) ? value.filter((n): n is number => typeof n === "number" && Number.isInteger(n)) : [];
306}
307
308export function evidenceOf(decision: Pick<Decision, "evidence">): Evidence {
309 const raw = (decision.evidence ?? {}) as Record<string, unknown>;
310 const check = raw.check && typeof raw.check === "object" ? (raw.check as Record<string, unknown>) : null;
311 return {
312 commit: typeof raw.commit === "string" ? raw.commit : null,
313 check:
314 check && typeof check.name === "string"
315 ? {
316 name: check.name,
317 conclusion: typeof check.conclusion === "string" ? check.conclusion : "failure",
318 url: typeof check.url === "string" && check.url ? check.url : null,
319 }
320 : null,
321 combination: numbers(raw.combination),
322 suspects: numbers(raw.suspects),
323 bisected: raw.bisected === true,
324 };
325}
326
327/** Where a check's address leads on the site: its path when it is g1t's own, else the address as it is. */
328export function checkHref(url: string | null): string | null {
329 if (!url) return null;
330 try {
331 const parsed = new URL(url);
332 if (parsed.hostname === "g1t.sh" || parsed.hostname.endsWith(".g1t.sh")) return parsed.pathname + parsed.search;
333 return url;
334 } catch {
335 return url.startsWith("/") ? url : null;
336 }
337}
338
339/**
340 * The integration failure a pull request still answers for: its latest
341 * `integration_failure`, unless it passed in the queue or merged since.
342 * `decisions` in any order.
343 */
344export function standingFailure(decisions: Decision[], pull?: number): Decision | null {
345 const mine = decisions
346 .filter((decision) => pull == null || decision.pull === pull)
347 .filter((decision) => ["integration_failure", "integration_passed", "merge"].includes(decision.kind))
348 .sort((a, b) => Date.parse(b.createdAt) - Date.parse(a.createdAt));
349 return mine[0]?.kind === "integration_failure" ? mine[0] : null;
350}
351
352/** The decisions after a failure that answer it: a fix recorded since, and a combination that then passed. */
353export function resolutionOf(decisions: Decision[], failure: Decision): { fix: Decision | null; passed: Decision | null } {
354 const after = decisions
355 .filter((decision) => Date.parse(decision.createdAt) > Date.parse(failure.createdAt))
356 .sort((a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt));
357 return {
358 fix: after.find((decision) => decision.kind === "fix" && (decision.pull === failure.pull || decision.issue === failure.issue)) ?? null,
359 passed: after.find((decision) => decision.kind === "integration_passed" && decision.pull === failure.pull) ?? null,
360 };
361}
362
363// ── The feed ────────────────────────────────────────────────────────────
364
365/** One line of the coordination feed: what happened, in words, and what it links to. */
366export type FeedLine = {
367 id: string;
368 time: string;
369 type: CoordinationType;
370 /** Who did it, by username; null for g1t itself. */
371 who: string | null;
372 /** The harness it came from, when it says. */
373 harness: Harness | null;
374 /** The sentence, after the name. Numbers in it are written `#N`. */
375 text: string;
376 /** The issue or pull request it is about. */
377 number: number | null;
378 /** The harness session it is about, by id, for a link to its page. */
379 session?: string;
380 tone: "neutral" | "accent" | "success" | "warn" | "danger" | "info";
381};
382
383const list = (all: number[]) => all.map((n) => `#${n}`).join(", ");
384const plural = (n: number, one: string, many: string) => (n === 1 ? one : many);
385
386/** A session's pending updates as lines of the feed, oldest first. */
387export function pendingLines(updates: { id: string; kind: string; data: unknown; at: string }[]): FeedLine[] {
388 return updates.flatMap((update) => {
389 if (!(COORDINATION_TYPES as readonly string[]).includes(update.kind)) return [];
390 const event = { id: update.id, type: update.kind, time: update.at, source: "work", repoId: null, actor: null, data: update.data } as G1tEvent;
391 return feedLine(event) ?? [];
392 });
393}
394
395/** A coordination event as a line of the feed, or null for one it does not show. */
396export function feedLine(event: G1tEvent): FeedLine | null {
397 const base = { id: event.id, time: event.time, harness: null as Harness | null, number: null as number | null };
398 const data = event.data as Record<string, unknown> & { number?: number };
399 const number = typeof data.number === "number" ? data.number : null;
400 switch (event.type) {
401 case "work.claimed": {
402 const { claim, others = [], tookOver } = event.data;
403 const also = others.length > 0 ? ` (${others.map((other) => other.actor.username).join(", ")} ${plural(others.length, "is", "are")} on it too)` : "";
404 return {
405 ...base,
406 type: event.type,
407 who: claim.actor.username,
408 harness: claim.harness,
409 text: `${tookOver ? "took over" : "claimed"} #${claim.issue}${also}`,
410 number: claim.issue,
411 tone: others.length > 0 ? "warn" : "accent",
412 };
413 }
414 case "work.released": {
415 const { claim, reason } = event.data;
416 return {
417 ...base,
418 type: event.type,
419 who: claim.actor.username,
420 harness: claim.harness,
421 text: reason === "issue_closed" ? `no longer holds #${claim.issue}: the issue closed` : `released #${claim.issue}${reason ? `: ${reason}` : ""}`,
422 number: claim.issue,
423 tone: "neutral",
424 };
425 }
426 case "work.claim_expired": {
427 const { claim } = event.data;
428 return { ...base, type: event.type, who: claim.actor.username, harness: claim.harness, text: `let the claim on #${claim.issue} expire`, number: claim.issue, tone: "neutral" };
429 }
430 case "work.handoff_requested": {
431 const { claim, to, note } = event.data;
432 return {
433 ...base,
434 type: event.type,
435 who: claim.actor.username,
436 harness: claim.harness,
437 text: `handed #${claim.issue} off to ${to ?? "anyone"}${note ? `: ${note}` : ""}`,
438 number: claim.issue,
439 tone: "info",
440 };
441 }
442 case "session.started":
443 case "session.ended": {
444 const { session } = event.data;
445 const on = session.issue != null ? ` on #${session.issue}` : session.pull != null ? ` on #${session.pull}` : "";
446 const why = event.type === "session.ended" && session.endReason === "timed_out" ? " (timed out)" : "";
447 // Ended by hand: by whoever ran it, or by someone with write access for them.
448 const byHand = event.type === "session.ended" && session.endReason?.startsWith(ENDED_BY_HAND) ? session.endReason.slice(ENDED_BY_HAND.length) : null;
449 if (byHand) {
450 const own = byHand === session.actor.username;
451 return {
452 ...base,
453 type: event.type,
454 who: byHand,
455 harness: own ? session.harness : null,
456 text: own ? `ended a session${on} by hand` : `ended ${session.actor.username}'s session${on} by hand`,
457 number: session.issue ?? session.pull,
458 tone: "neutral",
459 };
460 }
461 return {
462 ...base,
463 type: event.type,
464 who: session.actor.username,
465 harness: session.harness,
466 text: `${event.type === "session.started" ? "started a session" : "ended a session"}${on}${why}`,
467 number: session.issue ?? session.pull,
468 tone: event.type === "session.started" ? "accent" : "neutral",
469 };
470 }
471 case "dependency.changed": {
472 const { issue, added, removed, cleared, remaining, mergedPull } = event.data;
473 const parts = [
474 added.length > 0 && `now waits on ${list(added)}`,
475 removed.length > 0 && `no longer waits on ${list(removed)}`,
476 cleared.length > 0 && `${list(cleared)} ${mergedPull ? `landed (#${mergedPull} merged)` : "closed"}`,
477 ].filter(Boolean);
478 // What it still waits on, unless that is only what was just added.
479 const said = remaining.every((n) => added.includes(n)) && parts.length > 0;
480 const left = remaining.length === 0 ? "unblocked" : said ? null : `still waits on ${list(remaining)}`;
481 return {
482 ...base,
483 type: event.type,
484 who: null,
485 text: `#${issue} ${[...parts, left].filter(Boolean).join("; ")}`,
486 number: issue,
487 tone: remaining.length === 0 ? "success" : "info",
488 };
489 }
490 case "overlap.detected": {
491 if ("sessionId" in event.data) {
492 const { sessionId, otherActor, files, issue } = event.data;
493 return {
494 ...base,
495 type: event.type,
496 who: otherActor,
497 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` : ""}`,
498 number: issue ?? number,
499 session: sessionId,
500 tone: "warn",
501 };
502 }
503 const { pull, otherPull, files } = event.data;
504 return {
505 ...base,
506 type: event.type,
507 who: null,
508 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` : ""}`,
509 number: pull,
510 tone: "warn",
511 };
512 }
513 case "integration.failed": {
514 const { pull, combination, check, suspects } = event.data;
515 const together = combination.length > 1 ? ` combined as ${list(combination)}` : " on its own";
516 const with_ = suspects.length > 0 ? `; fails with ${list(suspects)}` : "";
517 return { ...base, type: event.type, who: null, text: `#${pull} failed in the merge queue${together}: ${check.name}${with_}`, number: pull, tone: "danger" };
518 }
519 case "integration.passed": {
520 const { pull, combination } = event.data;
521 return {
522 ...base,
523 type: event.type,
524 who: null,
525 text: combination.length > 1 ? `#${pull} passed in the merge queue combined as ${list(combination)}` : `#${pull} passed in the merge queue`,
526 number: pull,
527 tone: "success",
528 };
529 }
530 case "decision.recorded": {
531 const { decision } = event.data;
532 const kind = DECISION_KINDS[decision.kind as Decision["kind"]]?.toLowerCase() ?? decision.kind;
533 return {
534 ...base,
535 type: event.type,
536 who: decision.actor,
537 text: `recorded ${/^[aeiou]/.test(kind) ? "an" : "a"} ${kind}, ${decision.confidence}: ${decision.summary}`,
538 number: decision.pull ?? decision.issue ?? number,
539 tone: decision.kind === "integration_failure" ? "danger" : decision.confidence === "approved" ? "success" : "neutral",
540 };
541 }
542 // Steps of a session as it goes: for the pages showing it, not the feed.
543 case "session.progressed":
544 default:
545 return null;
546 }
547}
548
549// ── Session trees ───────────────────────────────────────────────────────
550
551/** A session with its subagents under it, and theirs under them. */
552export type SessionNode = { session: WorkSession; children: SessionNode[] };
553
554/**
555 * Sessions as trees, by `parentId`: the roots in the order given, each
556 * with its subagents in the order given. One whose parent is not in the
557 * list is a root of its own.
558 */
559export function sessionTree(sessions: WorkSession[]): SessionNode[] {
560 const nodes = new Map<string, SessionNode>();
561 for (const session of sessions) if (!nodes.has(session.id)) nodes.set(session.id, { session, children: [] });
562 const roots: SessionNode[] = [];
563 for (const node of nodes.values()) {
564 const parent = node.session.parentId ? nodes.get(node.session.parentId) : undefined;
565 // A parent that is the session itself or under it (a cycle) does not count.
566 if (parent && !contains(node, parent)) parent.children.push(node);
567 else roots.push(node);
568 }
569 return roots;
570}
571
572/** The sessions of several lists, each once (as the first list to have it says), in the order first given. */
573export function mergeSessions(...lists: (WorkSession[] | null | undefined)[]): WorkSession[] {
574 const seen = new Map<string, WorkSession>();
575 for (const list of lists) for (const session of list ?? []) if (!seen.has(session.id)) seen.set(session.id, session);
576 return [...seen.values()];
577}
578
579function contains(node: SessionNode, target: SessionNode): boolean {
580 return node === target || node.children.some((child) => contains(child, target));
581}
582
583/** How many sessions are under a tree's root, at any depth. */
584export function treeSize(node: SessionNode): number {
585 return node.children.reduce((total, child) => total + 1 + treeSize(child), 0);
586}
587
588/** How a session was tied to an issue or pull request, in a few words. */
589export const VIA_LABELS: Record<LinkVia, string> = {
590 attached: "attached",
591 claim: "claimed",
592 branch: "its branch",
593 commit: "its commit",
594 trailer: "commit trailer",
595 opened: "opened it",
596 ref: "named it",
597};
598
599export function viaLabel(via: LinkVia): string {
600 return VIA_LABELS[via] ?? via;
601}
602
603/** What each kind of thing a session touched is called. */
604export const TOUCH_KINDS: Record<TouchKind, string> = {
605 file: "Files",
606 commit: "Commits",
607 branch: "Branches",
608 pull: "Pull requests",
609 issue: "Issues",
610};
611
612/** What was touched, grouped by kind in TOUCH_KINDS' order, each value once, in the order given. */
613export function touchedByKind(touched: { kind: TouchKind; value: string }[]): { kind: TouchKind; values: string[] }[] {
614 return (Object.keys(TOUCH_KINDS) as TouchKind[])
615 .map((kind) => ({ kind, values: [...new Set(touched.filter((one) => one.kind === kind).map((one) => one.value))] }))
616 .filter((group) => group.values.length > 0);
617}
618
619/** "12s", "4m", "1h 20m": how long a session ran, or has run until `now`. */
620export function duration(session: Pick<WorkSession, "startedAt" | "endedAt" | "lastSeenAt" | "state">, now: number): string {
621 const end = session.endedAt ? Date.parse(session.endedAt) : session.state === "ended" ? Date.parse(session.lastSeenAt) : now;
622 const ms = Math.max(0, end - Date.parse(session.startedAt));
623 return ms < MINUTE ? `${Math.floor(ms / 1000)}s` : span(ms);
624}
625
626/** Splits text at `#N`, for linking each number. */
627export function numberedParts(text: string): (string | number)[] {
628 const parts: (string | number)[] = [];
629 let last = 0;
630 for (const match of text.matchAll(/#(\d+)\b/g)) {
631 if (match.index > last) parts.push(text.slice(last, match.index));
632 parts.push(Number(match[1]));
633 last = match.index + match[0].length;
634 }
635 if (last < text.length) parts.push(text.slice(last));
636 return parts;
637}
638
639/** `blocked_by` as typed: numbers, with or without `#`, by commas or spaces; null when any is not one. */
640export function parseBlockedBy(text: string): number[] | null {
641 const words = text.split(/[\s,]+/).map((word) => word.trim().replace(/^#/, "")).filter(Boolean);
642 if (words.some((word) => !/^\d+$/.test(word) || Number(word) <= 0)) return null;
643 return [...new Set(words.map(Number))];
644}