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.

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