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.

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