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.

372 linesCodeBlameRaw
1import assert from "node:assert/strict";
2import { test } from "node:test";
3
4import type { Claim, Decision, G1tEvent, WorkSession } from "@g1t/contracts";
5
6import {
7 ENDED_BY_HAND,
8 checkHref,
9 endReasonText,
10 evidenceOf,
11 expiresIn,
12 feedLine,
13 harnessName,
14 intentTitle,
15 awakeAndIdle,
16 liveByIssue,
17 sessionTitle,
18 duration,
19 mayEndSession,
20 mergeSessions,
21 numberedParts,
22 parseBlockedBy,
23 pendingLines,
24 resolutionOf,
25 sessionTree,
26 span,
27 standingFailure,
28 touchedByKind,
29 treeSize,
30 viaLabel,
31} from "./coordination.ts";
32
33const ana = { id: "usr_ana", username: "ana" };
34const bo = { id: "usr_bo", username: "bo" };
35
36function claim(issue: number, over: Partial<Claim> = {}): Claim {
37 return {
38 id: `clm_${issue}_${over.actor?.username ?? "ana"}`,
39 repoId: "rep_1",
40 issue,
41 sessionId: null,
42 actor: ana,
43 harness: "claude_code",
44 note: null,
45 state: "active",
46 createdAt: "2026-10-12T10:00:00Z",
47 expiresAt: "2026-10-12T10:30:00Z",
48 endedAt: null,
49 endReason: null,
50 handoffTo: null,
51 ...over,
52 };
53}
54
55function session(id: string, over: Partial<WorkSession> = {}): WorkSession {
56 return {
57 id,
58 repoId: "rep_1",
59 issue: null,
60 pull: null,
61 branch: null,
62 actor: bo,
63 harness: "codex",
64 harnessSessionId: null,
65 title: null,
66 state: "active",
67 headCommit: null,
68 startedAt: "2026-10-12T10:00:00Z",
69 lastSeenAt: "2026-10-12T10:05:00Z",
70 endedAt: null,
71 endReason: null,
72 ...over,
73 };
74}
75
76function decision(kind: Decision["kind"], at: string, over: Partial<Decision> = {}): Decision {
77 return {
78 id: `dec_${kind}_${at}`,
79 issue: 2,
80 pull: 5,
81 sessionId: null,
82 actor: null,
83 kind,
84 confidence: "tested",
85 summary: kind,
86 evidence: {},
87 createdAt: at,
88 ...over,
89 };
90}
91
92const event = (type: string, data: unknown): G1tEvent =>
93 ({ id: `evt_${type}`, type, source: "work", time: "2026-10-12T10:00:00Z", repoId: "rep_1", actor: "usr_ana", data }) as G1tEvent;
94
95test("harnesses are named as people know them", () => {
96 assert.equal(harnessName("claude_code"), "Claude Code");
97 assert.equal(harnessName("codex"), "Codex");
98 assert.equal(harnessName("claude_managed_agents"), "Claude Managed Agents");
99 assert.equal(harnessName(null), null);
100});
101
102test("a claim says when it lapses; one that ended says nothing", () => {
103 const now = Date.parse("2026-10-12T10:07:00Z");
104 assert.equal(expiresIn(claim(1), now), "expires in 23m");
105 assert.equal(expiresIn(claim(1, { expiresAt: "2026-10-12T12:00:00Z" }), now), "expires in 1h 53m");
106 assert.equal(expiresIn(claim(1, { expiresAt: "2026-10-12T10:00:00Z" }), now), "expiring now");
107 assert.equal(expiresIn(claim(1, { state: "released" }), now), null);
108 assert.equal(span(30_000), "less than a minute");
109 assert.equal(span(2 * 3_600_000), "2h");
110});
111
112test("Live now lists sessions heard from lately and folds away the idle, the latest first", () => {
113 const { awake, idle } = awakeAndIdle([
114 session("ses_a", { state: "active" }),
115 session("ses_b", { state: "idle", title: "Tidy the README", lastSeenAt: "2026-10-12T10:00:00Z" }),
116 session("ses_c", { state: "idle", lastSeenAt: "2026-10-12T10:10:00Z" }),
117 ]);
118 assert.deepEqual(awake.map((one) => one.id), ["ses_a"]);
119 assert.deepEqual(idle.map((one) => one.id), ["ses_c", "ses_b"]);
120 // A tab opened and never typed in is in neither; once it says what it is for, it shows.
121 const opened = session("ses_d", { state: "active", title: null, startedAt: "2026-10-12T10:00:00Z", lastSeenAt: "2026-10-12T10:00:00Z" });
122 assert.deepEqual(awakeAndIdle([opened]), { awake: [], idle: [] });
123 assert.equal(awakeAndIdle([{ ...opened, lastSeenAt: "2026-10-12T10:00:05Z" }]).awake.length, 1);
124 assert.equal(awakeAndIdle([{ ...opened, title: "Fix the build" }]).awake.length, 1);
125});
126
127test("live work is grouped by issue, most recent first, with sessions on no issue apart", () => {
128 const { issues, loose } = liveByIssue(
129 [claim(1), claim(2, { createdAt: "2026-10-12T10:20:00Z" }), claim(2, { actor: bo })],
130 [session("ses_a", { issue: 1, lastSeenAt: "2026-10-12T10:30:00Z" }), session("ses_b")],
131 );
132 assert.deepEqual(
133 issues.map((group) => [group.issue, group.claims.length, group.sessions.length]),
134 [
135 [1, 1, 1],
136 [2, 2, 0],
137 ],
138 );
139 assert.deepEqual(loose.map((one) => one.id), ["ses_b"]);
140});
141
142test("sessions on no issue are grouped by pull request, then by a branch of their own, then the rest together", () => {
143 const seen = (minute: number) => `2026-10-12T10:${String(minute).padStart(2, "0")}:00Z`;
144 const { issues, groups, loose } = liveByIssue(
145 [],
146 [
147 session("ses_main", { branch: "main", lastSeenAt: seen(50) }),
148 session("ses_fix1", { branch: "fix-previews", lastSeenAt: seen(10) }),
149 session("ses_pr", { pull: 12, branch: "tidy-readme", lastSeenAt: seen(20) }),
150 session("ses_fix2", { branch: "fix-previews", lastSeenAt: seen(40) }),
151 session("ses_none", { lastSeenAt: seen(30) }),
152 session("ses_issue", { issue: 3, branch: "3-x", lastSeenAt: seen(5) }),
153 ],
154 "main",
155 );
156 assert.deepEqual(issues.map((group) => group.issue), [3]);
157 assert.deepEqual(
158 groups.map((group) => [group.kind === "pull" ? `#${group.pull}` : group.kind === "branch" ? group.branch : "none", group.sessions.map((one) => one.id)]),
159 [
160 // The most recently heard from first; the rest, on no branch of their own (the default branch is none), last.
161 ["fix-previews", ["ses_fix2", "ses_fix1"]],
162 ["#12", ["ses_pr"]],
163 ["none", ["ses_main", "ses_none"]],
164 ],
165 );
166 assert.deepEqual(loose.map((one) => one.id), ["ses_fix2", "ses_fix1", "ses_pr", "ses_main", "ses_none"]);
167 // Without the default branch known, its sessions are a branch's.
168 assert.equal(liveByIssue([], [session("ses_main", { branch: "main" })]).groups[0].kind, "branch");
169});
170
171test("a session is never title-less: its title, its first prompt's intent, its branch, or untitled", () => {
172 assert.equal(sessionTitle({ title: "Rewrite the auth flow", branch: "auth", firstPrompt: "fix it" }), "Rewrite the auth flow");
173 // A title that is only a pasted block's tag reads as none: the first prompt's words title it.
174 assert.equal(sessionTitle({ title: '<pasted_content id="5c50">', branch: "main", firstPrompt: '<pasted_content id="5c50">\nlog\n</pasted_content>\nship the runner setup' }), "Ship the runner setup");
175 assert.equal(sessionTitle({ title: '<pasted_content id="5c50">', branch: "main", firstPrompt: null }), "Session on main");
176 assert.equal(sessionTitle({ title: null, branch: "auth", firstPrompt: "fix the login redirect. It loops." }), "Fix the login redirect");
177 assert.equal(sessionTitle({ title: " ", branch: "auth", firstPrompt: "/clear" }), "Session on auth");
178 assert.equal(sessionTitle({ title: null, branch: null }), "Untitled session");
179 assert.equal(sessionTitle({ title: null, branch: null }, "look at the CI"), "Look at the CI", "a first prompt given stands in");
180});
181
182test("a prompt's intent is its first line or sentence, plain, clipped on a word", () => {
183 assert.equal(intentTitle("Make preview builds faster. They time out on big repositories."), "Make preview builds faster");
184 // What an editor puts ahead of the prompt is not the prompt.
185 assert.equal(intentTitle("<ide_opened_file>The user opened a.ts in the IDE.</ide_opened_file>\nWhy is the page crashing?"), "Why is the page crashing?");
186 assert.equal(intentTitle("Why does `src/app.ts` fail? It worked yesterday."), "Why does src/app.ts fail?");
187 assert.equal(intentTitle("```js\nconst a = 1;\n```\n## Clean **this** up\nmore"), "Clean this up");
188 assert.equal(intentTitle("\n\n- look at [the docs](https://docs.g1t.sh) for g1t.mjs"), "Look at the docs for g1t.mjs");
189 const long = intentTitle("Tidy up the README and then look at the CI pipeline, which keeps failing on the Windows runners every night")!;
190 assert.ok(long.length <= 80 && long.endsWith("…") && !long.endsWith(" …"), long);
191 for (const prompt of ["/clear", "/g1t:status 4", "<command-name>/clear</command-name>", "```\ncode only\n```", "?", "", null]) {
192 assert.equal(intentTitle(prompt), null, String(prompt));
193 }
194});
195
196test("evidence is read as far as it goes", () => {
197 const failed = decision("integration_failure", "2026-10-12T10:00:00Z", {
198 evidence: { commit: "abc1234", check: { name: "CI / merge_group", conclusion: "failure", url: "https://g1t.sh/acme/web/actions/runs/run_1" }, combination: [4, 5], suspects: [4], bisected: false },
199 });
200 assert.deepEqual(evidenceOf(failed), {
201 commit: "abc1234",
202 check: { name: "CI / merge_group", conclusion: "failure", url: "https://g1t.sh/acme/web/actions/runs/run_1" },
203 combination: [4, 5],
204 suspects: [4],
205 bisected: false,
206 });
207 assert.deepEqual(evidenceOf(decision("note", "2026-10-12T10:00:00Z", { evidence: { combination: "nope" } })).combination, []);
208 assert.equal(checkHref("https://g1t.sh/acme/web/actions/runs/run_1"), "/acme/web/actions/runs/run_1");
209 assert.equal(checkHref("https://ci.example.com/build/9"), "https://ci.example.com/build/9");
210 assert.equal(checkHref(null), null);
211});
212
213test("a failure stands until the pull request passes in the queue or merges, and a fix after it answers it", () => {
214 const failed = decision("integration_failure", "2026-10-12T10:00:00Z");
215 const fix = decision("fix", "2026-10-12T10:10:00Z", { confidence: "claimed" });
216 const passed = decision("integration_passed", "2026-10-12T10:20:00Z");
217 assert.equal(standingFailure([failed], 5), failed);
218 assert.equal(standingFailure([failed, fix], 5), failed);
219 assert.equal(standingFailure([passed, failed], 5), null);
220 assert.equal(standingFailure([failed], 6), null);
221 assert.deepEqual(resolutionOf([failed, fix, passed], failed), { fix, passed });
222 assert.deepEqual(resolutionOf([fix, failed], { ...failed, createdAt: "2026-10-12T10:15:00Z" }), { fix: null, passed: null });
223});
224
225test("coordination events read as lines of the feed", () => {
226 const claimed = feedLine(event("work.claimed", { repoId: "rep_1", number: 2, issue: 2, claim: claim(2, { actor: bo, harness: "codex" }), others: [claim(2)] }))!;
227 assert.equal(claimed.who, "bo");
228 assert.equal(claimed.harness, "codex");
229 assert.equal(claimed.text, "claimed #2 (ana is on it too)");
230 assert.equal(claimed.tone, "warn");
231
232 const failed = feedLine(
233 event("integration.failed", {
234 repoId: "rep_1", pullId: "pul_5", number: 5, pull: 5, issue: 2, combination: [4, 5],
235 check: { name: "CI / merge_group", conclusion: "failure", url: null }, bisected: false, suspects: [4], otherPulls: [4], commit: null,
236 }),
237 )!;
238 assert.equal(failed.who, null);
239 assert.equal(failed.text, "#5 failed in the merge queue combined as #4, #5: CI / merge_group; fails with #4");
240 assert.equal(failed.tone, "danger");
241
242 const unblocked = feedLine(
243 event("dependency.changed", { repoId: "rep_1", number: 2, issue: 2, blockedBy: [1], added: [], removed: [], cleared: [1], remaining: [], mergedPull: 4 }),
244 )!;
245 assert.equal(unblocked.text, "#2 #1 landed (#4 merged); unblocked");
246
247 const overlap = feedLine(event("overlap.detected", { repoId: "rep_1", number: 5, pull: 5, otherPull: 4, files: ["src/auth.rs"] }))!;
248 assert.equal(overlap.text, "#5 and #4 change the same file: src/auth.rs");
249 assert.equal(overlap.session, undefined);
250
251 const sessions = feedLine(
252 event("overlap.detected", { repoId: "rep_1", sessionId: "ses_a", otherSessionId: "ses_b", otherActor: "bo", files: ["a.rs", "b.rs", "c.rs", "d.rs"], issue: 2 }),
253 )!;
254 assert.equal(sessions.who, "bo");
255 assert.equal(sessions.text, "touched the same files in a session as another session: a.rs, b.rs, c.rs and 1 more");
256 assert.equal(sessions.session, "ses_a");
257 assert.equal(sessions.number, 2);
258 assert.equal(feedLine(event("session.progressed", { repoId: "rep_1", number: 2, sessionId: "ses_a" })), null);
259
260 const started = feedLine(event("session.started", { repoId: "rep_1", session: session("ses_a", { issue: 2 }) }))!;
261 assert.equal(started.text, "started a session on #2");
262 assert.equal(feedLine(event("session.appended", { repoId: "rep_1", number: 5, pullId: "p", count: 3 })), null);
263});
264
265test("a session is ended by hand by whoever runs it, or by anyone who can write", () => {
266 const live = session("ses_a");
267 assert.equal(mayEndSession(live, bo.id, false), true);
268 assert.equal(mayEndSession(live, ana.id, false), false);
269 assert.equal(mayEndSession(live, ana.id, true), true);
270 assert.equal(mayEndSession(session("ses_b", { state: "idle" }), ana.id, true), true);
271 // Ended already, or nobody signed in: nothing to offer.
272 assert.equal(mayEndSession(session("ses_c", { state: "ended" }), bo.id, true), false);
273 assert.equal(mayEndSession(live, null, true), false);
274 // One g1t runs is stopped from its page, which stops the run too.
275 assert.equal(mayEndSession(session("ses_d", { harness: "claude_managed_agents" }), bo.id, true), false);
276 assert.equal(endReasonText("timed_out"), "timed out");
277 assert.equal(endReasonText(`${ENDED_BY_HAND}ana`), "ended by hand by @ana");
278 assert.equal(endReasonText(null), null);
279});
280
281test("a session ended by hand says who ended it in the feed", () => {
282 const own = feedLine(event("session.ended", { repoId: "rep_1", session: session("ses_a", { issue: 2, state: "ended", endReason: `${ENDED_BY_HAND}bo` }) }))!;
283 assert.equal(own.who, "bo");
284 assert.equal(own.text, "ended a session on #2 by hand");
285 const theirs = feedLine(event("session.ended", { repoId: "rep_1", session: session("ses_a", { state: "ended", endReason: `${ENDED_BY_HAND}ana` }) }))!;
286 assert.equal(theirs.who, "ana");
287 assert.equal(theirs.harness, null);
288 assert.equal(theirs.text, "ended bo's session by hand");
289 const timedOut = feedLine(event("session.ended", { repoId: "rep_1", session: session("ses_a", { state: "ended", endReason: "timed_out" }) }))!;
290 assert.equal(timedOut.text, "ended a session (timed out)");
291});
292
293test("sessions become trees by their parents; one whose parent is missing is a root", () => {
294 const roots = sessionTree([
295 session("ses_root"),
296 session("ses_a", { parentId: "ses_root" }),
297 session("ses_a1", { parentId: "ses_a" }),
298 session("ses_b", { parentId: "ses_root" }),
299 session("ses_orphan", { parentId: "ses_gone" }),
300 session("ses_other"),
301 ]);
302 const shape = (nodes: ReturnType<typeof sessionTree>): unknown[] => nodes.map((node) => [node.session.id, shape(node.children)]);
303 assert.deepEqual(shape(roots), [
304 ["ses_root", [["ses_a", [["ses_a1", []]]], ["ses_b", []]]],
305 ["ses_orphan", []],
306 ["ses_other", []],
307 ]);
308 assert.equal(treeSize(roots[0]!), 3);
309 // A child listed before its parent still lands under it.
310 assert.deepEqual(shape(sessionTree([session("ses_c", { parentId: "ses_p" }), session("ses_p")])), [["ses_p", [["ses_c", []]]]]);
311 // A cycle does not lose sessions.
312 const cycle = sessionTree([session("ses_x", { parentId: "ses_y" }), session("ses_y", { parentId: "ses_x" })]);
313 assert.equal(cycle.length + cycle.reduce((n, node) => n + treeSize(node), 0), 2);
314 assert.deepEqual(sessionTree([]), []);
315 assert.deepEqual(
316 mergeSessions([session("ses_a"), session("ses_b")], null, [session("ses_b", { title: "later" }), session("ses_c")]).map((one) => [one.id, one.title]),
317 [
318 ["ses_a", null],
319 ["ses_b", null],
320 ["ses_c", null],
321 ],
322 );
323});
324
325test("how a session was tied to its work, what it touched, and how long it ran", () => {
326 assert.equal(viaLabel("attached"), "attached");
327 assert.equal(viaLabel("claim"), "claimed");
328 assert.equal(viaLabel("branch"), "its branch");
329 assert.equal(viaLabel("commit"), "its commit");
330 assert.equal(viaLabel("trailer"), "commit trailer");
331 assert.equal(viaLabel("opened"), "opened it");
332 assert.equal(viaLabel("ref"), "named it");
333 assert.deepEqual(
334 touchedByKind([
335 { kind: "commit", value: "abc" },
336 { kind: "file", value: "b.rs" },
337 { kind: "file", value: "a.rs" },
338 { kind: "file", value: "b.rs" },
339 ]),
340 [
341 { kind: "file", values: ["b.rs", "a.rs"] },
342 { kind: "commit", values: ["abc"] },
343 ],
344 );
345 const now = Date.parse("2026-10-12T10:30:00Z");
346 assert.equal(duration(session("ses_a"), now), "30m");
347 assert.equal(duration(session("ses_a", { state: "ended", endedAt: "2026-10-12T10:00:42Z" }), now), "42s");
348 assert.equal(duration(session("ses_a", { state: "ended", endedAt: null }), now), "5m");
349});
350
351test("numbers in a sentence are found for linking", () => {
352 assert.deepEqual(numberedParts("#5 fails with #4."), [5, " fails with ", 4, "."]);
353 assert.deepEqual(numberedParts("no numbers"), ["no numbers"]);
354});
355
356test("blocked_by is typed as numbers", () => {
357 assert.deepEqual(parseBlockedBy("#12, 14 #12"), [12, 14]);
358 assert.deepEqual(parseBlockedBy(""), []);
359 assert.equal(parseBlockedBy("#12, soon"), null);
360 assert.equal(parseBlockedBy("0"), null);
361});
362
363test("a session's pending updates read as the feed does, leaving out what it does not show", () => {
364 const lines = pendingLines([
365 { id: "upd_1", kind: "work.claimed", at: "2026-10-14T10:00:00Z", data: { repoId: "rep_1", number: 4, issue: 4, claim: claim(4, { actor: bo, harness: "codex" }) } },
366 { id: "upd_2", kind: "session.progressed", at: "2026-10-14T10:00:01Z", data: {} },
367 ]);
368 assert.equal(lines.length, 1);
369 assert.equal(lines[0].id, "upd_1");
370 assert.equal(lines[0].who, "bo");
371 assert.match(lines[0].text, /claimed #4/);
372});