diff --git a/apps/board/assets/latch-band.png b/apps/board/assets/latch-band.png deleted file mode 100644 index acdf2ea63b..0000000000 Binary files a/apps/board/assets/latch-band.png and /dev/null differ diff --git a/apps/board/assets/latch/approved.png b/apps/board/assets/latch/approved.png new file mode 100644 index 0000000000..6db1f21c95 Binary files /dev/null and b/apps/board/assets/latch/approved.png differ diff --git a/apps/board/assets/latch/armed.png b/apps/board/assets/latch/armed.png new file mode 100644 index 0000000000..c1fcd6371c Binary files /dev/null and b/apps/board/assets/latch/armed.png differ diff --git a/apps/board/assets/latch/done-approved.png b/apps/board/assets/latch/done-approved.png new file mode 100644 index 0000000000..32d2d05b25 Binary files /dev/null and b/apps/board/assets/latch/done-approved.png differ diff --git a/apps/board/assets/latch/done-comments-1.png b/apps/board/assets/latch/done-comments-1.png new file mode 100644 index 0000000000..34fabbffb2 Binary files /dev/null and b/apps/board/assets/latch/done-comments-1.png differ diff --git a/apps/board/assets/latch/done-comments-10.png b/apps/board/assets/latch/done-comments-10.png new file mode 100644 index 0000000000..893be4e0b0 Binary files /dev/null and b/apps/board/assets/latch/done-comments-10.png differ diff --git a/apps/board/assets/latch/done-comments-11.png b/apps/board/assets/latch/done-comments-11.png new file mode 100644 index 0000000000..399b3ce850 Binary files /dev/null and b/apps/board/assets/latch/done-comments-11.png differ diff --git a/apps/board/assets/latch/done-comments-12.png b/apps/board/assets/latch/done-comments-12.png new file mode 100644 index 0000000000..5906af8ddc Binary files /dev/null and b/apps/board/assets/latch/done-comments-12.png differ diff --git a/apps/board/assets/latch/done-comments-13.png b/apps/board/assets/latch/done-comments-13.png new file mode 100644 index 0000000000..2ddab02d33 Binary files /dev/null and b/apps/board/assets/latch/done-comments-13.png differ diff --git a/apps/board/assets/latch/done-comments-14.png b/apps/board/assets/latch/done-comments-14.png new file mode 100644 index 0000000000..deb2bed749 Binary files /dev/null and b/apps/board/assets/latch/done-comments-14.png differ diff --git a/apps/board/assets/latch/done-comments-15.png b/apps/board/assets/latch/done-comments-15.png new file mode 100644 index 0000000000..91669f0f5d Binary files /dev/null and b/apps/board/assets/latch/done-comments-15.png differ diff --git a/apps/board/assets/latch/done-comments-16.png b/apps/board/assets/latch/done-comments-16.png new file mode 100644 index 0000000000..3acac150d2 Binary files /dev/null and b/apps/board/assets/latch/done-comments-16.png differ diff --git a/apps/board/assets/latch/done-comments-17.png b/apps/board/assets/latch/done-comments-17.png new file mode 100644 index 0000000000..569f36f558 Binary files /dev/null and b/apps/board/assets/latch/done-comments-17.png differ diff --git a/apps/board/assets/latch/done-comments-18.png b/apps/board/assets/latch/done-comments-18.png new file mode 100644 index 0000000000..106b6aa091 Binary files /dev/null and b/apps/board/assets/latch/done-comments-18.png differ diff --git a/apps/board/assets/latch/done-comments-19.png b/apps/board/assets/latch/done-comments-19.png new file mode 100644 index 0000000000..ac514c8d13 Binary files /dev/null and b/apps/board/assets/latch/done-comments-19.png differ diff --git a/apps/board/assets/latch/done-comments-2.png b/apps/board/assets/latch/done-comments-2.png new file mode 100644 index 0000000000..3f9f20314c Binary files /dev/null and b/apps/board/assets/latch/done-comments-2.png differ diff --git a/apps/board/assets/latch/done-comments-20.png b/apps/board/assets/latch/done-comments-20.png new file mode 100644 index 0000000000..9ea7fd5b80 Binary files /dev/null and b/apps/board/assets/latch/done-comments-20.png differ diff --git a/apps/board/assets/latch/done-comments-20plus.png b/apps/board/assets/latch/done-comments-20plus.png new file mode 100644 index 0000000000..f849e0eca3 Binary files /dev/null and b/apps/board/assets/latch/done-comments-20plus.png differ diff --git a/apps/board/assets/latch/done-comments-3.png b/apps/board/assets/latch/done-comments-3.png new file mode 100644 index 0000000000..ff6e8c85bc Binary files /dev/null and b/apps/board/assets/latch/done-comments-3.png differ diff --git a/apps/board/assets/latch/done-comments-4.png b/apps/board/assets/latch/done-comments-4.png new file mode 100644 index 0000000000..eb2bf15346 Binary files /dev/null and b/apps/board/assets/latch/done-comments-4.png differ diff --git a/apps/board/assets/latch/done-comments-5.png b/apps/board/assets/latch/done-comments-5.png new file mode 100644 index 0000000000..fea99577ec Binary files /dev/null and b/apps/board/assets/latch/done-comments-5.png differ diff --git a/apps/board/assets/latch/done-comments-6.png b/apps/board/assets/latch/done-comments-6.png new file mode 100644 index 0000000000..f295af565e Binary files /dev/null and b/apps/board/assets/latch/done-comments-6.png differ diff --git a/apps/board/assets/latch/done-comments-7.png b/apps/board/assets/latch/done-comments-7.png new file mode 100644 index 0000000000..0d333bf210 Binary files /dev/null and b/apps/board/assets/latch/done-comments-7.png differ diff --git a/apps/board/assets/latch/done-comments-8.png b/apps/board/assets/latch/done-comments-8.png new file mode 100644 index 0000000000..c517c41ac4 Binary files /dev/null and b/apps/board/assets/latch/done-comments-8.png differ diff --git a/apps/board/assets/latch/done-comments-9.png b/apps/board/assets/latch/done-comments-9.png new file mode 100644 index 0000000000..63ecae1e14 Binary files /dev/null and b/apps/board/assets/latch/done-comments-9.png differ diff --git a/apps/board/assets/latch/done-comments-none.png b/apps/board/assets/latch/done-comments-none.png new file mode 100644 index 0000000000..fe248bba9c Binary files /dev/null and b/apps/board/assets/latch/done-comments-none.png differ diff --git a/apps/board/assets/latch/error-retrying-budget.png b/apps/board/assets/latch/error-retrying-budget.png new file mode 100644 index 0000000000..32efaf6512 Binary files /dev/null and b/apps/board/assets/latch/error-retrying-budget.png differ diff --git a/apps/board/assets/latch/error-retrying-cooldown.png b/apps/board/assets/latch/error-retrying-cooldown.png new file mode 100644 index 0000000000..6c00964bf6 Binary files /dev/null and b/apps/board/assets/latch/error-retrying-cooldown.png differ diff --git a/apps/board/assets/latch/error-retrying-next-sweep.png b/apps/board/assets/latch/error-retrying-next-sweep.png new file mode 100644 index 0000000000..cf965d61ab Binary files /dev/null and b/apps/board/assets/latch/error-retrying-next-sweep.png differ diff --git a/apps/board/assets/latch/error-stuck.png b/apps/board/assets/latch/error-stuck.png new file mode 100644 index 0000000000..f8cb693dba Binary files /dev/null and b/apps/board/assets/latch/error-stuck.png differ diff --git a/apps/board/assets/latch/index.ts b/apps/board/assets/latch/index.ts new file mode 100644 index 0000000000..ae5f60b943 --- /dev/null +++ b/apps/board/assets/latch/index.ts @@ -0,0 +1,76 @@ +// generated by scripts/build-latch-band.ts; do not edit +import s33 from './approved.png' with { type: 'file' }; +import s0 from './armed.png' with { type: 'file' }; +import s32 from './done-approved.png' with { type: 'file' }; +import s10 from './done-comments-1.png' with { type: 'file' }; +import s11 from './done-comments-2.png' with { type: 'file' }; +import s12 from './done-comments-3.png' with { type: 'file' }; +import s13 from './done-comments-4.png' with { type: 'file' }; +import s14 from './done-comments-5.png' with { type: 'file' }; +import s15 from './done-comments-6.png' with { type: 'file' }; +import s16 from './done-comments-7.png' with { type: 'file' }; +import s17 from './done-comments-8.png' with { type: 'file' }; +import s18 from './done-comments-9.png' with { type: 'file' }; +import s19 from './done-comments-10.png' with { type: 'file' }; +import s20 from './done-comments-11.png' with { type: 'file' }; +import s21 from './done-comments-12.png' with { type: 'file' }; +import s22 from './done-comments-13.png' with { type: 'file' }; +import s23 from './done-comments-14.png' with { type: 'file' }; +import s24 from './done-comments-15.png' with { type: 'file' }; +import s25 from './done-comments-16.png' with { type: 'file' }; +import s26 from './done-comments-17.png' with { type: 'file' }; +import s27 from './done-comments-18.png' with { type: 'file' }; +import s28 from './done-comments-19.png' with { type: 'file' }; +import s29 from './done-comments-20.png' with { type: 'file' }; +import s30 from './done-comments-20plus.png' with { type: 'file' }; +import s31 from './done-comments-none.png' with { type: 'file' }; +import s8 from './error-retrying-budget.png' with { type: 'file' }; +import s7 from './error-retrying-cooldown.png' with { type: 'file' }; +import s6 from './error-retrying-next-sweep.png' with { type: 'file' }; +import s9 from './error-stuck.png' with { type: 'file' }; +import s3 from './queued-budget.png' with { type: 'file' }; +import s2 from './queued-cooldown.png' with { type: 'file' }; +import s1 from './queued-next-sweep.png' with { type: 'file' }; +import s4 from './queued-review-in-flight.png' with { type: 'file' }; +import s5 from './running.png' with { type: 'file' }; +import s34 from './superseded.png' with { type: 'file' }; + +export const STRIPS: Record = { + armed: s0, + 'queued-next-sweep': s1, + 'queued-cooldown': s2, + 'queued-budget': s3, + 'queued-review-in-flight': s4, + running: s5, + 'error-retrying-next-sweep': s6, + 'error-retrying-cooldown': s7, + 'error-retrying-budget': s8, + 'error-stuck': s9, + 'done-comments-1': s10, + 'done-comments-2': s11, + 'done-comments-3': s12, + 'done-comments-4': s13, + 'done-comments-5': s14, + 'done-comments-6': s15, + 'done-comments-7': s16, + 'done-comments-8': s17, + 'done-comments-9': s18, + 'done-comments-10': s19, + 'done-comments-11': s20, + 'done-comments-12': s21, + 'done-comments-13': s22, + 'done-comments-14': s23, + 'done-comments-15': s24, + 'done-comments-16': s25, + 'done-comments-17': s26, + 'done-comments-18': s27, + 'done-comments-19': s28, + 'done-comments-20': s29, + 'done-comments-20plus': s30, + 'done-comments-none': s31, + 'done-approved': s32, + approved: s33, + superseded: s34, +}; + +export { default as LAYOUT } from './layout.json'; diff --git a/apps/board/assets/latch/layout.json b/apps/board/assets/latch/layout.json new file mode 100644 index 0000000000..c2debc4d42 --- /dev/null +++ b/apps/board/assets/latch/layout.json @@ -0,0 +1,142 @@ +{ + "armed": { + "dotsX": 777, + "dotsY": 52 + }, + "queued-next-sweep": { + "dotsX": 759, + "dotsY": 52 + }, + "queued-cooldown": { + "dotsX": 759, + "dotsY": 52 + }, + "queued-budget": { + "dotsX": 759, + "dotsY": 52 + }, + "queued-review-in-flight": { + "dotsX": 759, + "dotsY": 52 + }, + "running": { + "dotsX": 797, + "dotsY": 52 + }, + "error-retrying-next-sweep": { + "dotsX": 853, + "dotsY": 52 + }, + "error-retrying-cooldown": { + "dotsX": 853, + "dotsY": 52 + }, + "error-retrying-budget": { + "dotsX": 853, + "dotsY": 52 + }, + "error-stuck": { + "dotsX": 735, + "dotsY": 52 + }, + "done-comments-1": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-2": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-3": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-4": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-5": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-6": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-7": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-8": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-9": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-10": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-11": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-12": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-13": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-14": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-15": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-16": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-17": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-18": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-19": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-20": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-20plus": { + "dotsX": 710, + "dotsY": 52 + }, + "done-comments-none": { + "dotsX": 710, + "dotsY": 52 + }, + "done-approved": { + "dotsX": 710, + "dotsY": 52 + }, + "approved": { + "dotsX": 378, + "dotsY": 52 + }, + "superseded": { + "dotsX": 423, + "dotsY": 52 + } +} diff --git a/apps/board/assets/latch/queued-budget.png b/apps/board/assets/latch/queued-budget.png new file mode 100644 index 0000000000..e2f263b1ff Binary files /dev/null and b/apps/board/assets/latch/queued-budget.png differ diff --git a/apps/board/assets/latch/queued-cooldown.png b/apps/board/assets/latch/queued-cooldown.png new file mode 100644 index 0000000000..27034c552c Binary files /dev/null and b/apps/board/assets/latch/queued-cooldown.png differ diff --git a/apps/board/assets/latch/queued-next-sweep.png b/apps/board/assets/latch/queued-next-sweep.png new file mode 100644 index 0000000000..c557bb4755 Binary files /dev/null and b/apps/board/assets/latch/queued-next-sweep.png differ diff --git a/apps/board/assets/latch/queued-review-in-flight.png b/apps/board/assets/latch/queued-review-in-flight.png new file mode 100644 index 0000000000..feacec522a Binary files /dev/null and b/apps/board/assets/latch/queued-review-in-flight.png differ diff --git a/apps/board/assets/latch/running.png b/apps/board/assets/latch/running.png new file mode 100644 index 0000000000..e2c89b15e3 Binary files /dev/null and b/apps/board/assets/latch/running.png differ diff --git a/apps/board/assets/latch/superseded.png b/apps/board/assets/latch/superseded.png new file mode 100644 index 0000000000..2b777c87f1 Binary files /dev/null and b/apps/board/assets/latch/superseded.png differ diff --git a/apps/board/bin/triage.ts b/apps/board/bin/triage.ts index b2eb3aeb83..8b9debe17b 100644 --- a/apps/board/bin/triage.ts +++ b/apps/board/bin/triage.ts @@ -2,7 +2,12 @@ // rt cron is the intended caller (spec §5); a human running it by hand gets // the same one idempotent evaluation pass. The board server NEVER runs this. import { deckAppUrl } from '@mattstack/app-server/event-bridge'; -import { GitLabProvider, parseRepoId, type MRDetail } from '@mattstack/glance'; +import { + GitLabProvider, + MRDetailFetcher, + parseRepoId, + type MRDetail, +} from '@mattstack/glance'; import { listOrgs, readDiscussions, @@ -23,6 +28,13 @@ import { } from '../src/doctor-state.ts'; import { launchDoctor, sendPaneText } from '../src/herdr.ts'; import { latchGateway } from '../src/latch/gateway.ts'; +import { fetchNewDiscussionCount } from '../src/latch/land.ts'; +import { + casLatch, + putLatchRow, + readLatchRow, + readLatchRows, +} from '../src/latch/latch-state.ts'; import { packForLaunch } from '../src/manifest-bindings.ts'; import { makeSwitchboardClient } from '../src/peer/client.ts'; import { makeEnvelope } from '../src/peer/envelope.ts'; @@ -54,7 +66,11 @@ import { loadTriageConfig, } from '../src/triage/config.ts'; import type { OwnMrFacts } from '../src/triage/edge.ts'; -import { runLatchPass, type LatchMrFacts } from '../src/triage/latch.ts'; +import { + latchInScope, + runLatchPass, + type LatchMrFacts, +} from '../src/triage/latch.ts'; import { CRON_CLAIM_STALE_MS, readMemory, @@ -132,12 +148,15 @@ try { // once per run and only when something actually notifies. Null (deck not // answering) sends the notification without a click target. let boardUrl: Promise | undefined; - const notify = async (title: string, message: string, mrUrl: string) => { - if (triage.notify !== 'rt') return; + const boardLinkFor = async (mrUrl: string): Promise => { boardUrl ??= deckAppUrl('board'); const base = await boardUrl; + return base ? boardMrLink(base, mrUrl) : null; + }; + const notify = async (title: string, message: string, mrUrl: string) => { + if (triage.notify !== 'rt') return; await notifyEscalation(title, message, triage.notify, { - url: base ? boardMrLink(base, mrUrl) : null, + url: await boardLinkFor(mrUrl), }); }; @@ -185,40 +204,33 @@ try { .map(m => ownMrFacts({ ...m, webUrl: m.webUrl! })); }; - // The latch pass's mirror image of fetchOwnMrs: every MR this board holds a - // done review state for, whatever its outcome, rather than the MRs this - // identity authored. Approve-outcome states stay in scope so a half-finished - // spend can be repaired; without them nothing ever would be. A commented - // TOMBSTONE also qualifies: its MR left the board with review state and came - // back without it, and the pass decides between resurrecting and dropping. + // The latch pass's mirror image of fetchOwnMrs: MRs this board reviewed + // rather than the MRs this identity authored (latchInScope says which). const fetchLatchMrs = async (): Promise => { - const states = readReviewStates(); - const pruned = readPrunedReviewStates(); - const inScope = (url: string | null | undefined): boolean => { - if (!url) return false; - if (states.get(url)?.status === 'done') return true; - const tomb = pruned.get(url); - return tomb?.status === 'done' && tomb.outcome === 'comment'; - }; const { prs, tags, windows } = await collectProjectPRs( boardConfig, readProjectMRs ); - return buildBoard(prs, boardConfig, undefined, tags, windows) - .filter(m => inScope(m.webUrl)) - .map(m => ({ - mrUrl: m.webUrl!, - iid: m.iid, - projectId: parseRepoId(m.repositoryId), - projectPath: - projectPathFromWebUrl(m.webUrl!, boardConfig.gitlabHost) ?? '', - // Encoded, not the bare rtRepos value: readDetail below passes this - // straight to readDiscussions, which is daemon-identity-keyed. - rtRepo: repoIdentityField(m.rtRepo) ?? '', - approvedBySelf: m.reviews.approvedBy.some( - r => r.username.toLowerCase() === username.toLowerCase() - ), - })); + return latchInScope( + buildBoard(prs, boardConfig, undefined, tags, windows), + { + rows: readLatchRows(), + states: readReviewStates(), + pruned: readPrunedReviewStates(), + } + ).map(m => ({ + mrUrl: m.webUrl!, + iid: m.iid, + projectId: parseRepoId(m.repositoryId), + projectPath: + projectPathFromWebUrl(m.webUrl!, boardConfig.gitlabHost) ?? '', + // Encoded, not the bare rtRepos value: readDetail below passes this + // straight to readDiscussions, which is daemon-identity-keyed. + rtRepo: repoIdentityField(m.rtRepo) ?? '', + approvedBySelf: m.reviews.approvedBy.some( + r => r.username.toLowerCase() === username.toLowerCase() + ), + })); }; if (!peerMode) { @@ -355,6 +367,24 @@ try { reReview, appendAudit, notify, + notifyStuck: async (title, message, mrUrl) => + notifyEscalation(title, message, 'rt', { + url: await boardLinkFor(mrUrl), + }), + countNew: (mr, launchAt) => + fetchNewDiscussionCount( + () => + new MRDetailFetcher( + boardConfig.gitlabHost, + latchToken + ).fetchDetail(mr.projectId, mr.iid), + username, + launchAt + ), + readLatchRow: mrUrl => readLatchRow(mrUrl), + casLatch: (mrUrl, from, patch, at, opts) => + casLatch(mrUrl, from, patch, at, undefined, opts), + putLatchRow: row => putLatchRow(row), now: () => Date.now(), }); console.log(`latch pass: ${JSON.stringify(latchResult)}`); diff --git a/apps/board/docs/superpowers/plans/2026-10-29-latch-animated-states.md b/apps/board/docs/superpowers/plans/2026-10-29-latch-animated-states.md new file mode 100644 index 0000000000..18a1f88717 --- /dev/null +++ b/apps/board/docs/superpowers/plans/2026-10-29-latch-animated-states.md @@ -0,0 +1,274 @@ +# Latch Animated States Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** The re-review latch shows where its follow-up review is (armed, queued, running, error, done) with a per-MR animated GIF strip, and the latch pass queues, retries and lands follow-ups instead of refusing them. + +**Architecture:** A new `latch_state` table in the board's state db is the latch's record; the GitLab note is its projection, rewritten after each compare-and-set transition. `banner.ts` composites committed text strips with the MR's invadr animated frame by frame and encodes a GIF with `gifenc`. The cron latch pass drives queue, dispatch, error and retry; the server and the pass share one `landFollowUp` for done. + +**Tech Stack:** Bun, TypeScript, bun:sqlite, pngjs, gifenc, invadrs 1.3.1 (`resolveInvadr`), Playwright (build-time only), `@mattstack/glance` (GitLab writes, `MRDetailFetcher`). + +**Spec:** `apps/board/docs/superpowers/specs/2026-10-29-latch-animated-states-design.md` + +## Global Constraints + +- Banner: 1040x128 px GIF, posted as `![](<url>){width=520}`; background `#2a2638`; title Silkscreen 18 `#ece8f4` letter-spacing 1; subtitle IBM Plex Mono 13 `#b7b0c8`; layout in CSS px at 2x: left padding 14, creature box 45x33, gap 10, right padding 24. +- Accents: armed `#f08fb0`, queued `#e6b860`, running `#7fbfe8`, error `#f2917e`, done-comments `#b9a0f2`, approved and done-approved `#86cfa0`, superseded `#8e88a0`. Eye cells `#ece8f4`. Ring unlit `#5d5775`, tail `accent + 'e0'` then `accent + 'b0'`. +- Each GIF under 80 KB. +- Detection stays marker-only; first line; `v1` family. New markers exactly: `<!-- mattstack:board re-review-latch v1 queued -->`, `<!-- mattstack:board re-review-latch v1 running -->`, `<!-- mattstack:board re-review-latch v1 error -->`. +- One author request never launches two reviews. +- Thread replies only on: follow-up finished (comments or approved) and stuck. No "Follow-up review started" reply. Hard refusals keep today's "Not yet" reply. +- Stuck always calls `notifyEscalation(..., 'rt', ...)`, whatever `triage.notify` says. +- Stuck after 3 failed attempts in one request cycle. +- All copy is verbatim from the spec's state table and wait-reason lists. +- Run board tests from `apps/board` (`bun test <file>`); the root run skips the board preload. Run only the targeted files locally. +- Invented names only in tests and fixtures (the repo is public). + +## Review Focus + +- A stale daemon read shows the note as `queued` or `armed`+resolved after the row says `running`: no second launch, no banner rewrite back. (Task 6 test `stale note never re-requests a running latch`.) +- The cron pass and the server both try to land the same follow-up: exactly one reply and one note rewrite. (Task 8 test `landFollowUp is idempotent across server and pass`.) +- A latch posted before this change (no row, old PNG body, old `![re-review latch](...)` image without `{width=...}`) keeps working and upgrades on its next transition. (Task 6 test `pre-change latch with no row is adopted`.) +- A review parked for hours at its post gate (`reviewing`) is never treated as failed. (Task 7 test `long reviewing is still running`.) +- Approval by the reviewer in GitLab while the latch is queued, running or error spends it with the Approved strip and launches nothing. (Task 6 test `own approval spends from every phase`.) + +--- + +### Task 1: New latch markers in rt-client + +**Files:** +- Modify: `packages/rt-client/src/latch.ts` +- Modify: `packages/rt-client/src/index.ts:266` +- Test: `packages/rt-client/src/__tests__/latch.test.ts` +- Modify: `apps/board/src/latch/markers.ts` (re-exports) + +**Interfaces:** +- Produces: `LATCH_MARKER_QUEUED`, `LATCH_MARKER_RUNNING`, `LATCH_MARKER_ERROR` (strings, verbatim from Global Constraints); `type LatchKind = 'armed' | 'queued' | 'running' | 'error' | 'spent'`; `latchKindOf(body)` returns the new kinds. + +- [ ] **Step 1: Write the failing tests** in `latch.test.ts`: `latchKindOf` returns `'queued'`, `'running'`, `'error'` for bodies whose first line is the new marker; returns `null` when the marker is on line 2; `'v2 running'` returns `null`. +- [ ] **Step 2: Run** `bun test packages/rt-client/src/__tests__/latch.test.ts` from the repo root. Expected: FAIL (new markers undefined). +- [ ] **Step 3: Implement** the three constants and the widened `latchKindOf`; export them from `index.ts` beside the existing two; re-export from `apps/board/src/latch/markers.ts`. +- [ ] **Step 4: Run** the test. Expected: PASS. Then `bun test lib/mcp` targeted file covering `mr-read-tools` if one exists, to confirm resolved-first dropping is unchanged. +- [ ] **Step 5: Commit** `rt-client: queued, running and error latch markers`. + +### Task 2: The latch state table + +**Files:** +- Modify: `apps/board/src/state/db.ts` (SCHEMA_VERSION 6 → 7, migration v7) +- Create: `apps/board/src/latch/latch-state.ts` +- Test: `apps/board/src/__tests__/latch-state.test.ts` + +**Interfaces:** +- Produces: + ```ts + export type LatchPhase = 'armed' | 'queued' | 'running' | 'error' | 'spent'; + export type WaitReason = 'next-sweep' | 'cooldown' | 'budget' | 'review-in-flight'; + export interface LatchRow { + mrUrl: string; discussionId: string; rootNoteId: number; + phase: LatchPhase; wait: WaitReason | null; + launchAt: number | null; // ms; the follow-up this latch waits on started at or after this + failures: number; stuck: boolean; + variant: string | null; // variantKey of the banner last written to the note + updatedAt: number; + } + readLatchRow(mrUrl: string, db?: Database): LatchRow | null + readLatchRows(db?: Database): LatchRow[] + /** Inserts or replaces the row; for adoption and first post only. */ + putLatchRow(row: LatchRow, db?: Database): void + /** Applies `patch` only while the row's phase is in `from`; true when it moved. */ + casLatch(mrUrl: string, from: LatchPhase[], patch: Partial<Omit<LatchRow, 'mrUrl'>>, now: number, db?: Database): boolean + cachedUpload(mrUrl: string, variantKey: string, db?: Database): string | null + rememberUpload(mrUrl: string, variantKey: string, markdown: string, db?: Database): void + ``` +- Tables: `latch_state (mr_url TEXT PRIMARY KEY, discussion_id TEXT NOT NULL, root_note_id INTEGER NOT NULL, phase TEXT NOT NULL, wait TEXT, launch_at INTEGER, failures INTEGER NOT NULL DEFAULT 0, stuck INTEGER NOT NULL DEFAULT 0, variant TEXT, updated_at INTEGER NOT NULL)` and `latch_uploads (mr_url TEXT NOT NULL, variant TEXT NOT NULL, markdown TEXT NOT NULL, PRIMARY KEY (mr_url, variant))`. One row per MR: this board is one reviewer. + +- [ ] **Step 1: Write failing tests** (temp db the way `state-db.test.ts` does): `casLatch moves only from a listed phase` (row `queued`, `casLatch(..., ['armed'], {phase:'running'})` returns false and phase stays `queued`; with `['queued']` returns true); `two cas racing from the same phase, only one wins`; `upload cache round-trips per variant`; `migration takes a v6 db to v7` (user_version 7, both tables exist). +- [ ] **Step 2: Run** `bun test src/__tests__/latch-state.test.ts` from `apps/board`. Expected: FAIL. +- [ ] **Step 3: Implement** the migration (append to `MIGRATIONS`, bump `SCHEMA_VERSION` to 7, comment in the existing `// vN:` style) and `latch-state.ts` in the `respond-rounds.ts` accessor style (default `db = getStateDb()`). `casLatch` is one `UPDATE ... WHERE mr_url = ? AND phase IN (...)` checked by `changes`. +- [ ] **Step 4: Run** the test and `bun test src/__tests__/state-db.test.ts`. Expected: PASS. +- [ ] **Step 5: Commit** `board: latch_state and latch_uploads tables`. + +### Task 3: Banner variants, copy and committed strips + +**Files:** +- Create: `apps/board/src/latch/variants.ts` +- Modify: `apps/board/scripts/build-latch-band.ts` (renders every variant) +- Create: `apps/board/assets/latch/*.png` (generated, committed) +- Test: `apps/board/src/__tests__/latch-variants.test.ts` + +**Interfaces:** +- Consumes: `WaitReason` (Task 2). +- Produces: + ```ts + export type BannerState = 'armed' | 'queued' | 'running' | 'error-retrying' | 'error-stuck' + | 'done-comments' | 'done-approved' | 'approved' | 'superseded'; + export interface BannerVariant { state: BannerState; wait?: WaitReason; count?: number | null } + export type Indicator = 'none' | 'dots' | 'ring'; + export interface VariantCopy { title: string; sub: string; accent: string; indicator: Indicator; sentence: string } + variantKey(v: BannerVariant): string // e.g. 'queued-cooldown', 'done-comments-3', 'done-comments-20plus', 'done-comments-none' + copyFor(v: BannerVariant): VariantCopy + allVariantKeys(): string[] // every strip the build script renders + variantOfKey(key: string): BannerVariant | null // inverse of variantKey + ``` +- Copy: titles and subtitles verbatim from the spec. Done-comments: count 1 → `1 new comment. Resolve when ready`; 2..20 → `N new comments. Resolve when ready`; >20 → `20+ new comments. Resolve when ready`; 0 or null → `Review posted. Resolve when ready`. Error-retrying subtitles by wait: next-sweep `Retrying on the next sweep`, cooldown `Retrying after the cooldown`, budget `Daily limit hit; retrying tomorrow`. Queued by wait: next-sweep `Starts on the next sweep`, cooldown `Waiting out the cooldown`, budget `Daily limit hit; starts tomorrow`, review-in-flight `Waiting for the running review`. +- `sentence` is the plain body line under the image: armed keeps today's `ARMED_COPY`; approved and superseded keep `SPENT_COPY` and `DUPLICATE_COPY`; queued `Follow-up review requested. I'll start it as soon as I can.`; running `Follow-up review in progress. I'll reply here when it's done.`; error-retrying `The follow-up review didn't finish. I'll try again.`; error-stuck `The follow-up review didn't finish after 3 tries. The reviewer has been told.`; done-comments `Follow-up review done. Resolve this thread again when you've addressed the new comments.`; done-approved `Follow-up review done and approved, so this latch is spent.` + +- [ ] **Step 1: Write failing tests**: `variantKey` is unique across `allVariantKeys()`; each copy row matches the spec strings above; `allVariantKeys()` has every queued and error wait, done-comments 1..20, `20plus` and `none`; indicator is `dots` for queued and error-retrying, `ring` for running, else `none`. +- [ ] **Step 2: Run** `bun test src/__tests__/latch-variants.test.ts`. Expected: FAIL. +- [ ] **Step 3: Implement** `variants.ts`; rewrite `build-latch-band.ts` to loop `allVariantKeys()` and screenshot each 520x64 strip at `deviceScaleFactor: 2` into `assets/latch/<key>.png`, leaving the creature box (x 14..59) and, for `dots`, the 3 dot slots after the title, and for `ring`, a 22x22 box at the right padding empty. Record the dot slot origin per key by measuring the title's right edge in the page and writing `assets/latch/layout.json` (`{ [key]: { dotsX: number, dotsY: number } }`, in 2x px). The board ships as a `bun build --compile` binary, and a `with { type: 'file' }` import embeds one file, never a directory, so the script also generates `assets/latch/index.ts`: one `import s<n> from './<key>.png' with { type: 'file' };` per key, `export const STRIPS: Record<string, string> = { '<key>': s<n>, ... }`, and `export { default as LAYOUT } from './layout.json';`. Add a test `every variant key has an embedded strip` (`allVariantKeys()` all present in `STRIPS` and `LAYOUT`). +- [ ] **Step 4: Run** `bun run scripts/build-latch-band.ts` (needs network for Google Fonts) then the test. Expected: PASS; `assets/latch/` holds one PNG per key plus `layout.json` and `index.ts`. +- [ ] **Step 5: Commit** `board: latch banner variants and their committed text strips`. + +### Task 4: The animated GIF compositor + +**Files:** +- Modify: `apps/board/src/latch/banner.ts` (replace `latchBannerPng`) +- Modify: `package.json` root catalog (`"gifenc": "1.0.3"`) and `apps/board/package.json` (`"gifenc": "catalog:"`) +- Test: `apps/board/src/__tests__/latch-banner.test.ts` (rewrite) + +**Interfaces:** +- Consumes: `BannerVariant`, `variantKey`, `copyFor` (Task 3); `resolveInvadr(mrUrl, { accent: true })` from invadrs. +- Produces: `latchBannerGif(mrUrl: string, variant: BannerVariant): Uint8Array`; `GIF_W = 1040`, `GIF_H = 128`; `legShuffle(grid: boolean[][]): boolean[][]` (exported for tests). + +Frame plans (delay ms; `legs` 0 = grid, 1 = `legShuffle(grid)`; `dx`/`dy` in sprite cells; one cell = 6 px at 2x): +- armed: (0,900) (1,900) (0,900) (0 blink,140) (0,700) (1,900) +- queued: 8 frames of 420 ms, dots 0,1,2,3,0,1,2,3, legs 0 for the first 4 then 1, blink on the last +- running: 8 frames of 130 ms, `dx` 0,1,2,1,0,-1,-2,-1, legs alternate, ring head at index i (clockwise from top-left, 8 cells of 12 px with 4 px gaps in a 3x3 square, centre empty) +- error-retrying and error-stuck: (dx0,700) (dx1 legs1,70) (dx-1,70) (dx1 legs1,70) (dx0,500) (600) (blink,140) (600); retrying also ticks dots 1,1,2,2,2,3,3,0 +- done-comments, done-approved, approved: (900) (dy1 legs1,90) (dy2 legs1,140) (dy1 legs1,90) (220) (900) (blink,140) (900); the approved two draw three `#ece8f4` sparkle cells at sprite cells (0,-3), (7,-5), (14,-2) on frames 3-5 +- superseded: one frame + +`legShuffle` (generic for all 16 creatures): copy the grid; in its bottom two rows move each filled cell one column toward the vertical centre line (left half +1, right half -1, centre column stays), dropping a move onto an already-filled target. + +- [ ] **Step 1: Write failing tests**: `encodes a 1040x128 GIF for every variant key` (parse width/height from GIF bytes 6..9 little-endian); `frame count matches the plan` (count `0x2C` image descriptors via a small parser, or `gifenc` frame log); `every GIF is under 80 KB`; `deterministic for one MR`; `differs between MRs`; `legShuffle changes the bottom rows of all 16 INVADR_SPRITES and nothing above them`; `paints the creature in the variant accent` (decode frame 0 with a minimal LZW-free check: sample the palette index at a known creature cell and compare its palette colour). +- [ ] **Step 2: Run** `bun test src/__tests__/latch-banner.test.ts`. Expected: FAIL. +- [ ] **Step 3: Implement**: read the variant's strip with pngjs once per call; per frame copy it, paint creature cells (6x6 px each, origin x 28 + (2+dx)*6, y centred in 128 minus dy*6), eye cells from `accent.cells`, dots (8x8 px, 4 px apart, at `layout.json`'s origin), ring (as above); `quantize` one global 256-colour palette from all frames concatenated; `applyPalette` per frame; `GIFEncoder().writeFrame(index, GIF_W, GIF_H, { palette (first frame only), delay, repeat: 0 })`. Read strips only through Task 3's `STRIPS[variantKey(v)]` and `LAYOUT` (never a path built from `import.meta.dir`), so the compiled binary finds them. If a GIF misses the 80 KB bound, give unchanged pixels a transparent index with `dispose: 1` rather than dropping frames. Remove `latchBannerPng`, `BAND_W`, `BAND_H` and `assets/latch-band.png`. +- [ ] **Step 4: Run** the test. Expected: PASS. Run `bun run board:typecheck` from the repo root. Expected: clean. +- [ ] **Step 5: Commit** `board: animated latch banner GIFs from committed strips`. + +### Task 5: Bodies and the rewrite write + +**Files:** +- Modify: `apps/board/src/latch/markers.ts` +- Modify: `apps/board/src/latch/post.ts` +- Test: `apps/board/src/__tests__/latch-markers.test.ts`, `apps/board/src/__tests__/latch-post.test.ts` + +**Interfaces:** +- Consumes: Task 1 markers; Task 2 `cachedUpload`/`rememberUpload`; Task 3 `variantKey`/`copyFor`; Task 4 `latchBannerGif`. +- Produces: + ```ts + latchBody(phase: LatchPhase, imageMarkdown: string, sentence: string): string // marker line, blank, image, blank, sentence + imageMarkdownFor(title: string, markdownFromUpload: string): string // '![title](url){width=520}' + imageMarkdownOf(body: string): string | null // also matches a trailing {width=N} + bannerMarkdown(gw: LatchGateway, projectId: number, mrUrl: string, iid: number, variant: BannerVariant): Promise<string> // upload cache first + rewriteLatch(gw: LatchGateway, t: LatchTarget, phase: LatchPhase, variant: BannerVariant, thread: 'resolve' | 'unresolve' | 'keep'): Promise<void> + interface LatchTarget { projectId: number; projectPath: string; iid: number; mrUrl: string; discussionId: string; rootNoteId: number } + ``` + `postLatch` keeps its signature, posts the `armed` variant through `bannerMarkdown`, and returns `{ discussionId, rootNoteId }`; every caller (the pass's step 0 and `applyReviewLatch`) then writes the row with `putLatchRow` (phase `armed`, variant `armed`), so a second writer sees the post before the daemon's discussion store does. `spendLatch(gw, projectId, projectPath, mrUrl, iid, latch, variant)` and `spendAllLatches(gw, projectId, projectPath, mrUrl, iid, latches, variant)` gain `mrUrl` (for the banner upload) and take a `BannerVariant` (`approved`, `done-approved` or `superseded`) in place of `SpentReason`; they keep rewrite-before-resolve ordering. Spending the canonical latch also moves the row: `casLatch(mrUrl, ['armed','queued','running','error'], { phase: 'spent', variant })`. `spendLatch` rewrites and resolves the note whether or not its own cas moved the row (a caller such as `landFollowUp` may already have moved it to `spent`); it skips the note only when the note's kind is already `spent`. Every write that changes the note records its `variantKey` in the row's `variant`. +- `rewriteLatch` ordering: rewrite the body first, then change the thread; a crash between leaves the phase visible on the note and the row decides recovery. + +- [ ] **Step 1: Write failing tests**: `latchBody` puts each phase's marker on line 1 and `latchKindOf` reads it back; `imageMarkdownOf` finds `![x](/uploads/a/b.gif){width=520}` and the old `![re-review latch](/uploads/a/b.png)`; `bannerMarkdown uploads once per variant` (second call with the same key makes no `uploadFile` call); `rewriteLatch writes the note before unresolving` (recorded gateway call order). +- [ ] **Step 2: Run** the two test files. Expected: FAIL. +- [ ] **Step 3: Implement**; upload filename `latch-<iid>-<variantKey>.gif`, content type `image/gif`. +- [ ] **Step 4: Run** both files plus `latch-review-step.test.ts`. Expected: PASS (update fixtures that asserted the PNG upload). +- [ ] **Step 5: Commit** `board: latch bodies per phase and the banner rewrite`. + +### Task 6: The pass queues and dispatches + +**Files:** +- Modify: `apps/board/src/triage/latch.ts` +- Modify: `apps/board/src/latch/discussions.ts` (`hasArmedLatch` → `hasLiveLatch`: any kind but `spent`) +- Test: `apps/board/src/__tests__/triage-latch.test.ts` + +**Interfaces:** +- Consumes: Tasks 2, 3, 5. +- Produces: `LatchPassDeps` gains `readLatchRow`, `casLatch`, `putLatchRow` (default to the Task 2 functions in `bin/triage.ts`). `waitReasonOf(decision: { action: string; reason: string }): WaitReason | null` (`dispatch` → next-sweep, `cooldown` → cooldown, `budget-exhausted` → budget, `review-in-flight` → review-in-flight, else null). `runStamp(r: ReviewState): number` = `r.runStartedAt ?? r.updatedAt` (`startedAt` is the lane's first-ever write and never resets, so it must not be used for a run). + +Per MR, after the existing spent and approval steps (which still win, from every phase, using the `approved` strip, and move the row to `spent` per Task 5): +1. No row but a latch on the note: adopt it with `putLatchRow` from the note's kind (a `spent` note writes a `spent` row). +2. Row `armed`, note shows a request: `decideRequest` as today. `dispatch` → launch, `casLatch(['armed'], {phase:'running', launchAt: now, wait: null})`, `rewriteLatch(..., 'running', 'keep')`, charge memory as today, no reply. Wait-able reason → `casLatch(['armed'], {phase:'queued', wait})`, rewrite to the queued variant for that wait, keep resolved, no reply, no notify. Other reasons → today's refusal path unchanged. +3. Row `queued`: if the review is `queued` or `reviewing` → `casLatch(['queued'], {phase:'running', launchAt: runStamp(review)})` and rewrite (any review satisfies). Else re-decide: dispatch as in 2 from `['queued']`; a changed wait reason rewrites the strip; the same variant as `row.variant` touches nothing. Withdrawal is the note carrying the `queued` marker AND unresolved (the marker proves the read post-dates the pass's own rewrite; an `armed` unresolved note is a stale pre-request read and is ignored) → `casLatch(['queued'], {phase:'armed'})`, rewrite armed, no reply. +4. Row `running`, `error` or `queued` is never a request, whatever the note shows. +5. Repair: row `armed` and the note's kind is `queued`, `running` or `error` is either the crash shape (row moved, note rewrite never landed) or a stale read of a note that did land; the note alone cannot tell them apart. Repair only when `now - row.updatedAt >= LATCH_POST_GRACE_MS` (the same staleness window the pass already waits out), so a request the author made on the freshly re-armed latch is never unresolved by a repair. Then rewrite the body to `armed` with `variantOfKey(row.variant)` (so a done-comments count survives) and unresolve; audit `repaired`. +- Re-deciding a `queued` or `error` row, and Task 7's transition-time decide for a `running` row whose lane reads `error`, hands `decideRequest` a review of `{ ...review, status: 'done', outcome: 'comment' }`: the row is the record that a commented review existed, and the lane may since read `error` (a dead follow-up) or have been rewritten, which would otherwise fail the `no-commented-review` gate (`nudge.ts:85-91`) and turn a retry into a hard refusal. This is safe because the in-flight case (`queued`/`reviewing` lane → `running`) is checked before any re-decide. +6. `consume`'s duplicate spends (`reason 'duplicate'`) use the `superseded` variant; approval spends use `approved`. +8. A live row whose review state is gone (pruned, undefined) is treated as having no lane: `queued`/`error` rows re-decide with the synthetic review `{ mrUrl, iid, status: 'done', outcome: 'comment', startedAt: 0, updatedAt: 0 }`; a `running` row is skipped that tick. `runStamp` and the spread are never reached with `undefined`. +7. The pass's scope check widens: an MR with a row in `queued`, `running` or `error` is processed whatever its review status (today only `done` states are). + +- [ ] **Step 1: Write failing tests**: `cooldown queues instead of replying Not yet` (no `createNote`; note rewritten with the queued marker and `queued-cooldown` upload; row `queued`); `queued dispatches when the block clears` (row `running`, one launch, no reply); `wait reason change swaps the strip`; `a hand-launched review satisfies a queued request` (review `reviewing`, no launch, row `running`); `stale note never re-requests a running latch` (row `running`, note armed+resolved: no launch, no rewrite); `author reopening a queued latch withdraws it` (queued marker, unresolved); `a stale armed unresolved read does not withdraw a queued latch`; `crash shape is repaired after the grace window` (row armed `updatedAt` older than `LATCH_POST_GRACE_MS`, note running: rewritten armed with `row.variant`, unresolved); `no repair inside the grace window` (row armed just now, note running and resolved: nothing written); `queued row re-decides past an error lane` (lane `status: 'error'`, cooldown clear: dispatches, no "Not yet"); `pre-change latch with no row is adopted`; `own approval spends from every phase` (queued, running, error rows; `approved` strip; row phase `spent`; no launch); `no-commented-review still refuses with Not yet`. +- [ ] **Step 2: Run** `bun test src/__tests__/triage-latch.test.ts`. Expected: new tests FAIL. +- [ ] **Step 3: Implement** in `runLatchPass`; keep the per-MR try/catch and audit entries (`event: 'latch'`, actions `queued`, `dispatched`, `withdrawn`, `adopted`). +- [ ] **Step 4: Run** the file plus `latch-discussions.test.ts`. Expected: PASS. +- [ ] **Step 5: Commit** `board: latch pass queues blocked follow-ups and dispatches from the queue`. + +### Task 7: Error, retry and stuck + +**Files:** +- Modify: `apps/board/src/triage/latch.ts` +- Test: `apps/board/src/__tests__/triage-latch.test.ts` + +**Interfaces:** +- Consumes: Task 6. +- Produces: `LatchPassDeps.notifyStuck(title: string, message: string, mrUrl: string): Promise<void>`; `export const LATCH_MAX_FAILURES = 3`. + +Rules: +- Dead-pane detection already exists: the server's closed-pane reconciler settles the review lane to `status: 'error', message: 'pane closed'` (`server.ts` ~3793). "Review `error`" is the liveness contract; add no timeout. +- The error transition is pass-only by design (a banner lag of at most one sweep); the server's latch step handles `done` only (Task 8). +- Row `running` and review `error`, or launch returned `kind: 'error'` → failures + 1. Below 3: `casLatch(['running', 'queued', 'armed', 'error'], {phase:'error', failures, wait})` where `wait = waitReasonOf(decideRequest(...))` run that tick, rewrite `error-retrying` for that wait, keep resolved, no reply. At 3: also `stuck: true`, rewrite `error-stuck`, post the stuck reply (`variants` sentence for error-stuck), call `notifyStuck` once. +- Row `error`, not stuck: re-decide like queued; dispatch → `running` (retry), a launch charges memory like any launch. +- Row `error`, stuck: never dispatch; if the review becomes `queued` or `reviewing` → `running` with `launchAt: runStamp(review)`, `stuck: false` (failures kept until it lands). +- Review `reviewing` for any length of time is running (post gate parks count as alive). + +- [ ] **Step 1: Write failing tests**: `review error moves running to error-retrying` (no reply); `retry dispatch returns error to running and charges memory`; `launch-failed counts as a failure`; `third failure is stuck: one reply, one notifyStuck, no more launches` (run the pass twice more: still no launch, no second reply); `relaunch from the board clears stuck`; `long reviewing is still running` (review `reviewing`, `runStartedAt` 6 h ago: row stays `running`, no rewrite); `retry blocked by budget shows the budget wait`. +- [ ] **Step 2: Run** the file. Expected: new tests FAIL. +- [ ] **Step 3: Implement**; audit actions `error`, `retried`, `stuck`, `recovered`. +- [ ] **Step 4: Run** the file. Expected: PASS. +- [ ] **Step 5: Commit** `board: latch retries failed follow-ups and stops after three`. + +### Task 8: Landing a follow-up (server and pass) + +**Files:** +- Create: `apps/board/src/latch/land.ts` +- Modify: `apps/board/src/latch/review-step.ts` +- Modify: `apps/board/src/server.ts` (the latch step at the `signal.kind === 'review'` block, ~line 4911) +- Modify: `apps/board/src/triage/latch.ts` (backstop) +- Test: `apps/board/src/__tests__/latch-land.test.ts`, `apps/board/src/__tests__/latch-review-step.test.ts` + +**Interfaces:** +- Consumes: Tasks 2, 3, 5. +- Produces: + ```ts + export interface LandInput { + target: LatchTarget; outcome: 'comment' | 'approve' | null; + reviewRunStartedAt: number; // runStamp(review) from Task 6 + gateway: LatchGateway; self: string; + countNew: () => Promise<number | null>; // reviewer's discussions created at or after launchAt, fresh from GitLab + now: number; + } + landFollowUp(i: LandInput): Promise<'landed' | 'not-mine' | 'none'> + ``` +- Rules: only when the row is `running` (or `error` with a review that reached done) and `reviewRunStartedAt >= row.launchAt`; a `spent` row never lands. `comment` → `casLatch(['running','error'], {phase:'armed', failures:0, stuck:false, wait:null, launchAt:null, variant})`, rewrite `done-comments` with `count`, unresolve, post the finished reply (`Follow-up review done: N new comments.` / `Follow-up review done.` when count is 0 or null). `approve` → cas to `spent`, `spendLatch` with `done-approved`, finished reply `Follow-up review done: approved.`. `null` (abandoned) → cas to `armed`, rewrite plain `armed`, unresolve, no reply. A lost cas returns `'none'` and writes nothing. +- `countNew` in the server and in `bin/triage.ts` uses `new MRDetailFetcher(host, token).fetchDetail(projectId, iid)` and counts discussions whose root note author is `self`, created at or after `launchAt`, excluding latch discussions and system notes. +- `applyReviewLatch` posts a fresh armed latch only when `!hasLiveLatch(latches)` and no row is live; a done review with a `running` row goes through `landFollowUp` instead. + +- [ ] **Step 1: Write failing tests**: `comment lands as done-comments with the count and reopens`; `count null shows Review posted`; `approve spends with done-approved and one reply`; `abandoned review re-arms quietly`; `landFollowUp is idempotent across server and pass` (call twice with the same row: one rewrite, one reply, second returns `'none'`); `a review whose runStartedAt is before launchAt does not land`; `a spent row never lands` (approval spent it first: no rewrite, no reopen); `review step never posts a duplicate beside a queued latch`. +- [ ] **Step 2: Run** both files. Expected: FAIL. +- [ ] **Step 3: Implement** `land.ts`; call it from the server's latch step for `status === 'done'` (with or without outcome) and from the pass when it sees a `running` row whose review is `done`. +- [ ] **Step 4: Run** both files and `triage-latch.test.ts`. Expected: PASS. +- [ ] **Step 5: Commit** `board: land follow-up reviews on the latch from the server or the pass`. + +### Task 9: Wiring, scope and the visual check + +**Files:** +- Modify: `apps/board/bin/triage.ts` (deps, scope, `notifyStuck`, `countNew`) +- Create: `apps/board/scripts/preview-latch-banners.ts` +- Modify: `apps/board/docs/superpowers/specs/2026-09-01-re-review-latch-design.md` (a one-line pointer to the new spec at the top) + +**Interfaces:** +- Consumes: everything above. + +- [ ] **Step 1:** In `bin/triage.ts`, extend `fetchLatchMrs`'s `inScope` with `readLatchRows()` phases `queued | running | error`; pass `readLatchRow`, `casLatch`, `putLatchRow`, `countNew`, and `notifyStuck` (calls `notifyEscalation(title, message, 'rt', { url })` with the same board link the existing `notify` builds, ignoring `triage.notify`). +- [ ] **Step 2:** Write `preview-latch-banners.ts`: for one invented MR URL, write `latchBannerGif` for every `allVariantKeys()` entry into a temp dir plus an `index.html` showing each at 520 px inside a GitLab-like comment card, once on `#fbfafd`/`#ffffff` and once on `#18171d`/`#232128`; print the path. +- [ ] **Step 3: Run** the preview script, open the page in Fast Browser, screenshot both schemes, and look: every strip readable, nothing clipped, the ring visible, dots after the title, creature not touching the text. Fix anything that reads wrong before continuing. +- [ ] **Step 4: Run** `bun test src/__tests__/latch-*.test.ts src/__tests__/triage-latch.test.ts` from `apps/board`, `bun test packages/rt-client/src/__tests__/latch.test.ts` from the root, and `bun run board:typecheck`. Expected: all pass. +- [ ] **Step 5: Commit** `board: wire the latch states into triage and add the banner preview`. diff --git a/apps/board/docs/superpowers/specs/2026-09-01-re-review-latch-design.md b/apps/board/docs/superpowers/specs/2026-09-01-re-review-latch-design.md index 2e7b7483b5..d1c72b3b8b 100644 --- a/apps/board/docs/superpowers/specs/2026-09-01-re-review-latch-design.md +++ b/apps/board/docs/superpowers/specs/2026-09-01-re-review-latch-design.md @@ -1,5 +1,7 @@ # Re-review latch +> Banner states and the queue/retry lifecycle are superseded by [2026-10-29-latch-animated-states-design.md](2026-10-29-latch-animated-states-design.md). + Give an MR author a way to ask for a re-review from inside the MR, so a re-review no longer depends on another board user poking the reviewer through the switchboard. diff --git a/apps/board/docs/superpowers/specs/2026-10-29-latch-animated-states-design.md b/apps/board/docs/superpowers/specs/2026-10-29-latch-animated-states-design.md new file mode 100644 index 0000000000..b01e8a9d48 --- /dev/null +++ b/apps/board/docs/superpowers/specs/2026-10-29-latch-animated-states-design.md @@ -0,0 +1,286 @@ +# Re-review latch: animated state banners + +Status: design, awaiting approval. Builds on the shipped latch +(`2026-09-01-re-review-latch-design.md`). + +## Why + +The latch is the board's comment on a GitLab MR: after a review leaves +comments, the author resolves it to ask for a follow-up review. Today it +carries one big static banner (1200x208, near-black and hot pink) that +never changes. A teammate resolves it and the latch keeps asking "Ready +for re-review?" while the board queues, runs, or fails the follow-up. +Nobody on the MR can tell what the board is doing. + +The latch should show where the follow-up review is, at a glance, and be +smaller and calmer than today's banner. + +## Goals + +- One banner per latch state, swapped on the same note as the state + changes: armed, queued, running, error, done (comments or approved). +- Each banner is an animated GIF strip: this MR's invadr creature plus + short copy, 520 CSS px wide. +- A follow-up the board cannot start yet waits in queued instead of being + refused with "Not yet". +- A follow-up that fails is retried by the board; after three failures it + stops and tells the reviewer. + +## Non-goals + +- No change to who may request a follow-up, or to the cooldown and daily + budget values. +- No board UI changes; this is the GitLab comment only. +- No separate images for GitLab dark mode; one strip reads on both. + +## Anti-goals + +- The image must never be load-bearing. Detection stays marker-only + (rt-client's rule today): a missing or blocked image changes nothing. +- One author request never launches two reviews, whatever order sweeps, + server signals and retries land in. +- No constant attention-grabbing motion. Loops stay slow; terminal states + move little. + +## The states + +Every banner is a 520x64 strip (1040x128 pixels, 2x for Retina) on +`#2a2638`, the creature on the left, a title in Silkscreen 18 (`#ece8f4`) +and a subtitle in IBM Plex Mono 13 (`#b7b0c8`). The accent colours the +creature and its indicator. + +| State | Marker kind | Thread | Title | Subtitle | Accent | Motion | +|---|---|---|---|---|---|---| +| Armed (first time) | `armed` | open | Ready for another pass? | Resolve this thread to ask | `#f08fb0` | leg shuffle, eye blink | +| Queued | `queued` | resolved | Follow-up review queued | why it is waiting (below) | `#e6b860` | dots tick after the title | +| Running | `running` | resolved | Follow-up review running | Results post here when done | `#7fbfe8` | creature marches; ring loader on the right | +| Error, retrying | `error` | resolved | Follow-up review hit a snag | Retrying on the next sweep | `#f2917e` | quick shake, dots tick | +| Error, stuck | `error` | resolved | Follow-up review stuck | Reviewer notified | `#f2917e` | quick shake, blink | +| Done, comments | `armed` | open | Follow-up review done | N new comments. Resolve when ready | `#b9a0f2` | one hop, blink | +| Done, approved | `spent` | resolved | Follow-up review done | Approved. Nothing more to do | `#86cfa0` | hop with sparkles | +| Approved, no follow-up | `spent` | resolved | Approved | Nothing more to do | `#86cfa0` | hop with sparkles | +| Superseded | `spent` | resolved | Superseded | A newer latch is live | `#8e88a0` | still | + +Queued subtitles, by why the request is waiting: "Starts on the next +sweep" (nothing blocks it), "Waiting out the cooldown", "Daily limit hit; +starts tomorrow", "Waiting for the running review" (`review-in-flight`). +These are the only reasons `decideRequest` can give a latch request that +clear by themselves; respond never blocks a latch. + +Error, retrying names the wait the same way when a retry is blocked: +"Retrying on the next sweep", "Retrying after the cooldown", "Daily limit +hit; retrying tomorrow". + +Done-comments counts what actually landed: the reviewer's discussions on +the MR created after the follow-up launched (the launch stamp, below). +"1 new comment", "N new comments" up to 20, "20+ new comments". Zero, or a +count the board cannot read, shows "Review posted. Resolve when ready". +(My call: the report JSON's findings are the drafted set, and the +reviewer can drop findings before posting.) + +The note body under the image keeps a plain sentence per state, so +blocked images still say what is happening. The current armed and spent +copy stays; new states get one sentence each. + +## Replies and notifications + +GitLab emails on a new note, not on an edit, so banner swaps are silent. +The board posts a thread reply only when the author or reviewer needs to +know (Matt's call): + +- the follow-up finished: one reply with the outcome (comments with the + count, or approved); +- the latch is stuck: one reply saying the reviewer has been told. + +Queued, running, retries and wait-reason changes are banner edits only. +Today's "Follow-up review started" reply goes away; the running banner +replaces it. No latch gets today's "Not yet" reply: the pass gives every +latch it acts on a row (adopting one from the note when none exists), the +row proves a commented review, so no reason that never clears can reach +it, and a pane that fails to start is a counted failure (step 5). + +A stuck latch always sends the reviewer the rt desktop notification, even +when `triage.notify` is `badge-only` (Matt's call: it is rare and needs a +person). + +The prototype GIFs and preview this design was reviewed from were rendered +by a throwaway Chromium script; they are the visual reference for frame +timing and layout, not code to keep. + +## The lifecycle + +1. A review lands with comments and no latch exists: post an armed latch + (unchanged trigger, new banner). +2. The author resolves it. The next latch pass sees the request and + decides it. A decision to dispatch launches straight from armed (step + 3's launch, no queued hop). Otherwise the pass stamps the request time + on the row, rewrites the note to `queued` with the banner for the + current wait reason (cooldown, budget, review in flight), and leaves + the thread resolved. Queued shows only when the request must wait. +3. Each pass re-decides every queued latch. When the decision becomes + dispatch, it re-reads the review lane, launches the review, rewrites to + `running`, and charges cooldown and budget exactly as today. A review + found in flight on that re-read is adopted instead (see "Any review + satisfies the request"). If the wait reason changes, the banner changes + with it. +4. The review lands (server signal, with the pass as backstop): + - comments: rewrite to `armed` with the done-comments banner, reopen + the thread. The next resolve starts again at step 2. + - approve: rewrite to `spent` with done-approved, keep resolved. +5. The review errors, or its pane dies under the run liveness contract, + while the latch is `running`: rewrite to `error` (retrying), keep + resolved, and treat it as queued for the next pass. Retries obey + cooldown and budget. A retry that launches flips it back to `running`. +6. After three failed attempts in one request cycle, the latch stays + `error` with the stuck banner, retries stop, the thread gets the stuck + reply, and the reviewer gets a desktop notification. It leaves stuck only when that MR's review runs + again (the reviewer relaunches it from the board): the pass sees the + review `reviewing` and flips the latch to `running`. + +Approvals keep today's precedence: the reviewer's own approval (via +review or GitLab) spends every copy from any state, and spent still wins +over everything in the pass. + +Edge cases (my calls): + +- **Any review satisfies the request.** A review that starts while the + latch is queued or error, even one the reviewer launched by hand from + the board, is the follow-up: the latch goes to `running` and lands like + any other. One ask never gets two reviews. The review must start at or + after the row's stamp (the request for a queued latch, the last launch + for an error one). A review already running when the author resolved + cannot have seen the fixes, so the request waits it out ("Waiting for + the running review") and is decided again once it ends. +- **A review parked at its post gate is running**, however long it waits; + the liveness check must not read a parked gate as dead. +- **A follow-up that ends done with no outcome** (the reviewer abandoned + the post gate) consumed the request: back to the plain armed banner, + thread reopened, no reply. The next resolve is a new request cycle, so + the failure count resets. +- **Retries count like launches.** A retry charges cooldown and budget + exactly as a first launch. A pane that fails to start counts as a + failure. Failures count per request cycle, across days, and reset when + a follow-up lands, with an outcome or abandoned. +- **The author reopens a queued latch**: the request is withdrawn; back + to armed. Reopening a running or error latch changes nothing until the + run lands. +- **The review step never posts a duplicate.** `applyReviewLatch` posts a + fresh armed latch only when this reviewer has no latch in any non-spent + kind. + +## Where the latch's state lives (my call) + +The note is what people see; the board's state db is the record. A new +table keyed by MR and latch discussion holds the kind, the request cycle, +the stamp a follow-up must start at or after (the request while queued, +the launch once running), and the failure count. The cron pass (`bin/triage.ts`) and the board server both +read and write it; every transition is a compare-and-set on the row's +current kind, and the note is rewritten only after the row moves. +A landing (comment or approve) or a stuck transition also writes the reply +it owes into the row's `reply_due` in that same compare-and-set; the writer +posts it at once and clears it, and a post that fails stays owed until a +later cron tick, past the post grace, posts it to the canonical latch +(at least once). An owed reply is dropped, with an audit line, a day after +its transition, when its latch is gone, or when it is the stuck reply and +the row has left stuck. + +This is what makes the daemon's stale discussion reads harmless: a +stale note showing `queued` or `armed`+resolved after the row already +says `running` is ignored, so it can never re-request or clobber the +banner. The note's marker stays the fallback when no row exists (latches +posted before this change, or a lost db), read exactly as today; a +queued, running or error note adopted that way takes its post time as the +stamp, so the review that armed it can never land as the follow-up. The +failure count lives in this row, not in the cron's dispatch memory file, +because the server records errors and outcomes too. + +## Markers + +rt-client's `latch.ts` gains three markers beside the two it has, same +`v1` family, first line only: + +- `<!-- mattstack:board re-review-latch v1 queued -->` +- `<!-- mattstack:board re-review-latch v1 running -->` +- `<!-- mattstack:board re-review-latch v1 error -->` + +`LatchKind` becomes `armed | queued | running | error | spent`. A request +is still exactly "armed and resolved". Queued, running and error are +acknowledged states the pass owns; resolving or reopening them is not a +new request. + +Older rt builds read the new markers as "not a latch" (null). They only +ever appear on resolved threads, which rt's MCP MR tools drop before +checking markers, so an older rt shows nothing different. rt-client and +the board ship in this repo, so both land together. + +## How the banner is made (approach A, chosen) + +Build time: `scripts/build-latch-band.ts` (Playwright, as today) renders +one text strip per state and wait reason, plus the done-comments count +variants, into `apps/board/assets/latch/`, committed. Each strip leaves +the creature box and the indicator box empty. Today's +`assets/latch-band.png` goes once nothing reads it. + +Runtime: `banner.ts` takes (mrUrl, state variant) and returns GIF bytes. +It reads the strip, paints this MR's creature from +`resolveInvadr(mrUrl, { accent: true })` frame by frame (eye cells from +`accent.cells`), paints the dots or ring, and encodes with `gifenc` +(pure JS, so `bun build --compile` keeps working). Frame timings follow +the prototype: armed ~4.4s loop, queued 420ms ticks, running 130ms +frames, done and error ~3.5s loops. + +The posted markdown is `![<state title>](<upload url>){width=520}` so +GitLab shows it at 520 CSS px instead of stretching it to the column. +`imageMarkdownOf` must keep matching with that suffix. + +Alternative B (one committed GIF per state, same creature for every MR) +was rejected: it drops the per-MR creature for a simpler runtime. +Rendering in Chromium at runtime was ruled out: it would put a browser in +the compiled binary. + +## Uploads + +Every state change uploads the new GIF (30-60 KB) and rewrites the note. +The board caches each upload's markdown per MR and state variant in its +state db and reuses it when the latch returns to a variant it has shown +(error, then running again). Existing latches keep their old PNG until +their next state change, then get the new banner. + +## Where it changes + +- `packages/rt-client/src/latch.ts`: markers and `LatchKind`. +- `apps/board/src/latch/markers.ts`: bodies per state. +- `apps/board/src/latch/banner.ts`: GIF compositor. +- `apps/board/src/latch/post.ts`: a state-rewrite write beside + `postLatch` and `spendLatch`. +- `apps/board/src/latch/discussions.ts`: request and canonical rules for + the new kinds. +- `apps/board/src/triage/latch.ts`: queue instead of refuse, dispatch + from queued, error and retry, stuck and recovery. +- `apps/board/src/latch/review-step.ts` and the server's latch step: + done transitions from running, error transition on a review error. +- `apps/board/scripts/build-latch-band.ts` and `assets/latch/`. +- `apps/board/src/state/db.ts`: the latch state table. +- `apps/board/src/triage/notify.ts` or its caller: the stuck + notification that ignores `triage.notify`. + +## Calls the builder makes + +- The two-frame leg shuffle has to work for all 16 invadr creatures; + derive it from the bottom rows generically and check every sprite in + the build preview. +- The latch table's exact schema and its `SCHEMA_VERSION` claim. +- Audit entries for each new transition, in the existing `latch` event + shape. +- How the pass detects a dead running review: reuse the run liveness + contract, never a new timeout. + +## Verification + +- Unit tests for every transition in the lifecycle, including the + ordering cases (server signal and pass racing, retry after error, + approval from each state). +- A banner test that each state encodes, has the expected frame count, + stays under 80 KB, and is 1040x128. +- Render every state and wait reason into a preview page and look at it + in GitLab light and dark styling before calling it done. diff --git a/apps/board/package.json b/apps/board/package.json index f679f90ed9..a0635845d0 100644 --- a/apps/board/package.json +++ b/apps/board/package.json @@ -26,6 +26,7 @@ "@mattstack/settings-kit": "workspace:*", "@mattstack/tui-kit": "workspace:*", "@pierre/diffs": "catalog:", + "gifenc": "catalog:", "invadrs": "^1.3.1", "lucide-react": "catalog:", "motion": "14.2.0", @@ -39,12 +40,15 @@ "@happy-dom/global-registrator": "^20.14.0", "@types/bun": "latest", "@types/node": "catalog:", + "@types/omggif": "catalog:", "@types/pixelmatch": "^5.2.6", "@types/pngjs": "^6.0.5", "@types/react": "catalog:", "@types/react-dom": "catalog:", + "omggif": "catalog:", "pixelmatch": "^7.2.0", "playwright": "^1.62.1", + "prettier": "catalog:", "typescript": "^7.0.2" }, "//soribashi": "No @soribashi/* DEPENDENCY here, deliberately: registerTheme/SoribashiProvider come from @mattstack/tui-kit/provider, which keeps them on the same resolved path as the kit's own recipes. A direct @soribashi/core dep would bundle a SECOND copy of factory and silently break theming. The kit now resolves @soribashi/core from the registry (no file: deps in its own package.json), so no overrides block is needed here either. See docs/tui-kit-devloop.md." diff --git a/apps/board/scripts/build-latch-band.ts b/apps/board/scripts/build-latch-band.ts index 5dccf499b3..bd04de5c83 100644 --- a/apps/board/scripts/build-latch-band.ts +++ b/apps/board/scripts/build-latch-band.ts @@ -1,62 +1,156 @@ /** - * Renders the latch banner's fixed artwork to assets/latch-band.png, once, at - * build time. Text is the only reason a browser is involved: the runtime - * compositor paints sprite pixels and cannot render glyphs. Re-run by hand - * after changing the band's look, and commit the result. + * Renders the text strip behind every latch banner variant to + * assets/latch/<key>.png, once, at build time. Text is the only reason a + * browser is involved: the runtime compositor paints the creature and the + * indicator and cannot render glyphs. Re-run by hand after changing the + * copy or the look, and commit the result. * * bun run scripts/build-latch-band.ts + * + * Also writes assets/latch/layout.json (where the runtime paints the dots, + * in 2x px) and assets/latch/index.ts, which embeds each strip by file: + * `bun build --compile` embeds single files, never a directory. */ -import { mkdirSync } from 'fs'; +import { mkdirSync, writeFileSync } from 'fs'; import { join } from 'path'; import { chromium } from 'playwright'; +import { format, resolveConfig } from 'prettier'; + +import { + allVariantKeys, + copyFor, + DOT_GAP_PX, + DOT_PX, + variantOfKey, +} from '../src/latch/variants.ts'; -const W = 1200; -const H = 208; -// Left inset reserved for the sprite the runtime paints in; the artwork must -// leave it empty or the sprite lands on top of the band's own pixels. -const SPRITE_BOX = 120 + 60 * 2; +const W = 520; +const H = 64; +const SCALE = 2; +const OUT = join(import.meta.dir, '..', 'assets', 'latch'); + +const escape = (s: string) => + s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); const html = `<!doctype html><meta charset="utf-8"> -<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Silkscreen:wght@400;700&family=IBM+Plex+Mono:wght@500&display=swap"> +<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Silkscreen&family=IBM+Plex+Mono:wght@400&display=swap"> <style> - html, body { margin: 0; padding: 0; } - .band { - width: ${W}px; height: ${H}px; box-sizing: border-box; - display: flex; align-items: center; - padding: 0 60px 0 ${SPRITE_BOX}px; - background: #161224; - background-image: repeating-linear-gradient(0deg, rgba(255,255,255,0.035) 0 2px, transparent 2px 6px); - } - .stack { display: flex; flex-direction: column; gap: 16px; width: 100%; } - /* GitLab shows the band at about half width. Silkscreen draws on an 8px - grid, so 48px lands on whole pixels at 50% where 50px smeared; weight 400 - keeps the counters open that 700 filled in. */ - .title { font-family: 'Silkscreen', 'Courier New', monospace; font-weight: 400; - font-size: 48px; letter-spacing: 0.06em; color: #f6f2ff; line-height: 1; } - .rule { height: 4px; background: #ff6b9d; width: 100%; } - .sub { font-family: 'IBM Plex Mono', ui-monospace, monospace; font-size: 30px; - letter-spacing: 0.08em; color: #ffd0e0; text-transform: uppercase; line-height: 1; } + html, body { margin: 0; padding: 0; background: #2a2638; } + /* The sprite and ring boxes stay bare background: the runtime paints into them. */ + .band { width: ${W}px; height: ${H}px; box-sizing: border-box; display: flex; align-items: center; + gap: 10px; padding: 0 24px 0 14px; background: #2a2638; } + .sprite { width: 45px; height: 33px; flex: none; } + .copy { display: flex; flex-direction: column; gap: 5px; flex: 1; min-width: 0; } + /* The title row lays the dots out as the approved prototype did: flex + children 4px apart, bottom-aligned 2px above the title's line box. */ + .titlerow { display: flex; align-items: flex-end; gap: ${DOT_GAP_PX / SCALE}px; } + .title { font-family: 'Silkscreen'; font-size: 18px; letter-spacing: 1px; color: #ece8f4; + line-height: 1; white-space: nowrap; } + .dot { width: ${DOT_PX / SCALE}px; height: ${DOT_PX / SCALE}px; margin-bottom: 2px; flex: none; } + .sub { font-family: 'IBM Plex Mono'; font-size: 13px; color: #b7b0c8; line-height: 1; + white-space: nowrap; } + .ring { width: 22px; height: 22px; flex: none; } </style> -<div class="band"><div class="stack"> - <div class="title">READY FOR RE-REVIEW?</div> - <div class="rule"></div> - <div class="sub">resolve this thread to summon another pass</div> -</div></div>`; +<div class="band" id="band"></div>`; const browser = await chromium.launch(); -const page = await browser.newPage({ viewport: { width: W, height: H } }); +const page = await browser.newPage({ + viewport: { width: W, height: H }, + deviceScaleFactor: SCALE, +}); await page.setContent(html, { waitUntil: 'networkidle' }); -await page.evaluate( - () => - ( - globalThis as unknown as { - document: { fonts: { ready: Promise<unknown> } }; - } - ).document.fonts.ready -); -mkdirSync(join(import.meta.dir, '..', 'assets'), { recursive: true }); -await page.locator('.band').screenshot({ - path: join(import.meta.dir, '..', 'assets', 'latch-band.png'), +// FontFaceSet.check() is true when no face is registered at all, which is +// what a failed stylesheet fetch leaves, so require each load to find a face. +const fontsOk = await page.evaluate(async () => { + const fonts = ( + globalThis as unknown as { + document: { fonts: { load(f: string): Promise<{ status: string }[]> } }; + } + ).document.fonts; + const silkscreen = await fonts.load("18px 'Silkscreen'"); + const plex = await fonts.load("13px 'IBM Plex Mono'"); + return [silkscreen, plex].every( + faces => faces.length > 0 && faces.every(f => f.status === 'loaded') + ); }); +if (!fontsOk) { + await browser.close(); + throw new Error( + 'Google Fonts did not load; refusing to render strips with fallback fonts' + ); +} + +mkdirSync(OUT, { recursive: true }); +const keys = allVariantKeys(); +const layout: Record<string, { dotsX: number; dotsY: number }> = {}; + +for (const key of keys) { + const copy = copyFor(variantOfKey(key)!); + const inner = `<div class="sprite"></div> + <div class="copy"><div class="titlerow"><div class="title">${escape( + copy.title.toUpperCase() + )}</div>${'<div class="dot"></div>'.repeat(3)}</div> + <div class="sub">${escape(copy.sub)}</div></div>${ + copy.indicator === 'ring' ? '<div class="ring"></div>' : '' + }`; + const m = await page.evaluate(markup => { + const doc = (globalThis as unknown as { document: any }).document; + const band = doc.getElementById('band'); + band.innerHTML = markup; + const box = (sel: string) => + band.querySelector(sel).getBoundingClientRect(); + const copyBox = box('.copy'); + const dots = [...band.querySelectorAll('.dot')].map((d: any) => + d.getBoundingClientRect() + ); + const sub = box('.sub'); + return { + copyRight: copyBox.right, + titleRight: box('.title').right, + dotsLeft: dots[0].left, + dotsTop: dots[0].top, + dotsRight: dots[2].right, + subRight: sub.right, + }; + }, inner); + + const titleEnd = copy.indicator === 'dots' ? m.dotsRight : m.titleRight; + if (titleEnd > m.copyRight || m.subRight > m.copyRight) { + throw new Error(`${key}: copy overflows its box`); + } + layout[key] = { + dotsX: Math.round(m.dotsLeft * SCALE), + dotsY: Math.round(m.dotsTop * SCALE), + }; + await page.locator('#band').screenshot({ path: join(OUT, `${key}.png`) }); +} await browser.close(); -console.log(`wrote assets/latch-band.png (${W}x${H})`); + +writeFileSync(join(OUT, 'layout.json'), `${JSON.stringify(layout, null, 2)}\n`); +const imports = keys.map( + (k, i) => `import s${i} from './${k}.png' with { type: 'file' };` +); +const entries = keys.map((k, i) => ` '${k}': s${i},`); +const indexPath = join(OUT, 'index.ts'); +const indexSource = [ + '// generated by scripts/build-latch-band.ts; do not edit', + ...imports, + '', + 'export const STRIPS: Record<string, string> = {', + ...entries, + '};', + '', + "export { default as LAYOUT } from './layout.json';", + '', +].join('\n'); +// format:check covers this file, so it is written in the repo's Prettier shape. +writeFileSync( + indexPath, + await format(indexSource, { + ...(await resolveConfig(indexPath)), + filepath: indexPath, + }) +); +console.log( + `wrote ${keys.length} strips to assets/latch (${W * SCALE}x${H * SCALE})` +); diff --git a/apps/board/scripts/preview-latch-banners.ts b/apps/board/scripts/preview-latch-banners.ts new file mode 100644 index 0000000000..ba2e7993fe --- /dev/null +++ b/apps/board/scripts/preview-latch-banners.ts @@ -0,0 +1,168 @@ +/** + * Writes a static preview of every latch banner to a temp dir and prints its + * path. Two sections: the seven approved prototype GIFs beside the runtime's + * rendering of the same creature, then every variant as a GitLab comment + * would show it. light.html and dark.html hold the two page schemes. + * + * bun run scripts/preview-latch-banners.ts + */ +import { copyFileSync, mkdirSync, mkdtempSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; + +import { PROTOTYPE_CREATURE } from '../src/__tests__/fixtures/latch-prototype-creature.ts'; +import { latchBannerGif, renderBannerGif } from '../src/latch/banner.ts'; +import { + allVariantKeys, + copyFor, + variantOfKey, + type BannerVariant, +} from '../src/latch/variants.ts'; + +const REFERENCE = join( + import.meta.dir, + '..', + 'src', + '__tests__', + 'fixtures', + 'latch-reference' +); + +const PARITY: [string, BannerVariant][] = [ + ['armed', { state: 'armed' }], + ['queued', { state: 'queued', wait: 'next-sweep' }], + ['running', { state: 'running' }], + ['done-comments', { state: 'done-comments', count: 3 }], + ['done-approved', { state: 'done-approved' }], + ['error-retrying', { state: 'error-retrying', wait: 'next-sweep' }], + ['error-stuck', { state: 'error-stuck' }], +]; + +const MR = 'https://gitlab.example.com/acme/widgets/-/merge_requests/42'; +const EXTRA_ARMED = [ + 'https://gitlab.example.com/acme/widgets/-/merge_requests/108', + 'https://gitlab.example.com/acme/gadgets/-/merge_requests/7', + 'https://gitlab.example.com/acme/sprockets/-/merge_requests/2317', +]; + +const SCHEMES = { + light: { + page: '#fbfafd', + card: '#ffffff', + text: '#28272d', + muted: '#737278', + border: '#dcdcde', + }, + dark: { + page: '#18171d', + card: '#232128', + text: '#ececef', + muted: '#a4a3a8', + border: '#3a383f', + }, +} as const; + +const out = mkdtempSync(join(tmpdir(), 'latch-preview-')); +mkdirSync(join(out, 'gifs')); + +const esc = (s: string) => + s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>'); + +/** The markdown the note bodies use: blank-line paragraphs and bold. */ +function markdown(s: string): string { + return s + .split(/\n\s*\n/) + .map( + p => `<p>${esc(p).replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')}</p>` + ) + .join('\n '); +} + +function write(name: string, bytes: Uint8Array): string { + writeFileSync(join(out, 'gifs', name), bytes); + return `gifs/${name}`; +} + +function card(src: string, sentence: string, caption?: string): string { + return `<figure class="card"> + ${caption ? `<figcaption>${esc(caption)}</figcaption>` : ''} + <div class="note-head"><span class="avatar"></span><b>Board reviewer</b> <span class="muted">@reviewer, just now</span></div> + <img src="${src}" width="520" alt=""> + ${markdown(sentence)} +</figure>`; +} + +const parityRows = PARITY.map(([name, variant]) => { + copyFileSync( + join(REFERENCE, `latch-${name}.gif`), + join(out, 'gifs', `approved-${name}.gif`) + ); + const runtime = write( + `runtime-${name}.gif`, + renderBannerGif(PROTOTYPE_CREATURE, variant) + ); + const sentence = copyFor(variant).sentence; + return `<h3>${esc(name)}</h3> +<div class="pair"> + ${card(`gifs/approved-${name}.gif`, sentence, 'approved')} + ${card(runtime, sentence, 'runtime')} +</div>`; +}).join('\n'); + +const variantCards = allVariantKeys().map(key => { + const variant = variantOfKey(key)!; + const src = write(`variant-${key}.gif`, latchBannerGif(MR, variant)); + return card(src, copyFor(variant).sentence, key); +}); +const armedCards = EXTRA_ARMED.map((url, i) => { + const src = write( + `armed-extra-${i}.gif`, + latchBannerGif(url, { state: 'armed' }) + ); + return card( + src, + copyFor({ state: 'armed' }).sentence, + `armed (${url.split('/-/')[0]!.split('/').pop()} !${url.split('/').pop()})` + ); +}); + +function page(scheme: keyof typeof SCHEMES): string { + const c = SCHEMES[scheme]; + return `<!doctype html> +<html><head><meta charset="utf-8"><title>Latch banners (${scheme}) + + +

index   ${scheme === 'light' ? 'dark' : 'light'}

+

Parity

+${parityRows} +

All variants

+
+${[...variantCards, ...armedCards].join('\n')} +
+`; +} + +writeFileSync(join(out, 'light.html'), page('light')); +writeFileSync(join(out, 'dark.html'), page('dark')); +writeFileSync( + join(out, 'index.html'), + `Latch banners +` +); + +console.log(out); diff --git a/apps/board/src/__tests__/fixtures/latch-prototype-creature.ts b/apps/board/src/__tests__/fixtures/latch-prototype-creature.ts new file mode 100644 index 0000000000..5cc5a17686 --- /dev/null +++ b/apps/board/src/__tests__/fixtures/latch-prototype-creature.ts @@ -0,0 +1,31 @@ +/** + * The hand-made creature the approved prototype banners were drawn with + * (fixtures/latch-reference/*.gif), so the parity test can render the same + * creature through the runtime compositor. + */ +import type { Creature } from '../../latch/banner.ts'; + +const BODY = [ + 'X.........X', + 'XX.......XX', + '.XX.....XX.', + '..XXXXXXX..', + '.XX.XXX.XX.', + '.XXXXXXXXX.', + '..XXXXXXX..', + '..XXXXXXX..', +]; +const LEGS = [ + ['...X...X...', '..X.....X..', '.XX.....XX.'], + ['...X...X...', '...X...X...', '..XX...XX..'], +]; + +const grid = (rows: string[]) => rows.map(r => [...r].map(c => c === 'X')); + +export const PROTOTYPE_CREATURE: Creature = { + frames: [grid([...BODY, ...LEGS[0]!]), grid([...BODY, ...LEGS[1]!])], + eyes: [ + [3, 4], + [7, 4], + ], +}; diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-armed.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-armed.gif new file mode 100644 index 0000000000..439784967d Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-armed.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-done-approved.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-done-approved.gif new file mode 100644 index 0000000000..517faa595d Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-done-approved.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-done-comments.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-done-comments.gif new file mode 100644 index 0000000000..b88d5b41ab Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-done-comments.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-error-retrying.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-error-retrying.gif new file mode 100644 index 0000000000..242cc568cc Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-error-retrying.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-error-stuck.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-error-stuck.gif new file mode 100644 index 0000000000..5335feda38 Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-error-stuck.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-queued.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-queued.gif new file mode 100644 index 0000000000..0fda4d2525 Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-queued.gif differ diff --git a/apps/board/src/__tests__/fixtures/latch-reference/latch-running.gif b/apps/board/src/__tests__/fixtures/latch-reference/latch-running.gif new file mode 100644 index 0000000000..077128f194 Binary files /dev/null and b/apps/board/src/__tests__/fixtures/latch-reference/latch-running.gif differ diff --git a/apps/board/src/__tests__/latch-banner-parity.test.ts b/apps/board/src/__tests__/latch-banner-parity.test.ts new file mode 100644 index 0000000000..90ee3b8482 --- /dev/null +++ b/apps/board/src/__tests__/latch-banner-parity.test.ts @@ -0,0 +1,164 @@ +import { mkdirSync, readFileSync, writeFileSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { describe, expect, test } from 'bun:test'; +import { GifReader } from 'omggif'; +import { PNG } from 'pngjs'; + +import { renderBannerGif } from '../latch/banner.ts'; +import type { BannerVariant } from '../latch/variants.ts'; +import { PROTOTYPE_CREATURE } from './fixtures/latch-prototype-creature.ts'; + +const REFERENCE = join(import.meta.dir, 'fixtures', 'latch-reference'); +const OUT = process.env.LATCH_PARITY_OUT ?? join(tmpdir(), 'latch-parity'); + +/** A pixel differs when any channel is off by more than this. */ +const CHANNEL_TOLERANCE = 24; +/** The share of pixels per frame allowed to differ. */ +const MAX_DIFFERING = 0.005; + +const CASES: [string, BannerVariant][] = [ + ['armed', { state: 'armed' }], + ['queued', { state: 'queued', wait: 'next-sweep' }], + ['running', { state: 'running' }], + ['done-comments', { state: 'done-comments', count: 3 }], + ['done-approved', { state: 'done-approved' }], + ['error-retrying', { state: 'error-retrying', wait: 'next-sweep' }], + ['error-stuck', { state: 'error-stuck' }], +]; + +interface Decoded { + width: number; + height: number; + delays: number[]; + frames: Uint8Array[]; +} + +function decode(bytes: Uint8Array): Decoded { + const gif = new GifReader(bytes); + const { width, height } = gif; + const canvas = new Uint8Array(width * height * 4); + const delays: number[] = []; + const frames: Uint8Array[] = []; + for (let i = 0; i < gif.numFrames(); i++) { + const info = gif.frameInfo(i); + const before = info.disposal === 3 ? canvas.slice() : null; + gif.decodeAndBlitFrameRGBA(i, canvas); + frames.push(canvas.slice()); + delays.push(info.delay * 10); + if (info.disposal === 2) { + for (let y = info.y; y < info.y + info.height; y++) { + canvas.fill( + 0, + (y * width + info.x) * 4, + (y * width + info.x + info.width) * 4 + ); + } + } else if (before) { + canvas.set(before); + } + } + return { width, height, delays, frames }; +} + +function writePng( + path: string, + width: number, + height: number, + rgba: Uint8Array +) { + const png = new PNG({ width, height }); + png.data = Buffer.from(rgba); + writeFileSync(path, PNG.sync.write(png)); +} + +interface Verdict { + share: number; + /** 2x2 blocks where every pixel differs: a missing or moved feature cell. */ + blocks: number; + diff: Uint8Array; +} + +function compare(ref: Uint8Array, got: Uint8Array, width: number): Verdict { + const diff = new Uint8Array(ref.length); + const bad = new Uint8Array(ref.length / 4); + for (let p = 0; p < bad.length; p++) { + const i = p * 4; + const off = Math.max( + Math.abs(ref[i]! - got[i]!), + Math.abs(ref[i + 1]! - got[i + 1]!), + Math.abs(ref[i + 2]! - got[i + 2]!) + ); + bad[p] = off > CHANNEL_TOLERANCE ? 1 : 0; + diff[i] = bad[p] ? 255 : got[i]! >> 2; + diff[i + 1] = bad[p] ? 0 : got[i + 1]! >> 2; + diff[i + 2] = bad[p] ? 0 : got[i + 2]! >> 2; + diff[i + 3] = 255; + } + let differing = 0; + let blocks = 0; + for (let p = 0; p < bad.length; p++) { + if (!bad[p]) continue; + differing++; + const x = p % width; + if (x + 1 < width && bad[p + 1] && bad[p + width] && bad[p + width + 1]) + blocks++; + } + return { share: differing / bad.length, blocks, diff }; +} + +const passes = (v: Verdict) => v.share <= MAX_DIFFERING && v.blocks === 0; + +const pct = (share: number) => `${(share * 100).toFixed(3)}%`; + +describe('latch banner parity with the approved prototype', () => { + for (const [name, variant] of CASES) { + test(name, () => { + const ref = decode(readFileSync(join(REFERENCE, `latch-${name}.gif`))); + const got = decode(renderBannerGif(PROTOTYPE_CREATURE, variant)); + expect([got.width, got.height]).toEqual([ref.width, ref.height]); + expect(got.frames.length).toBe(ref.frames.length); + expect(got.delays).toEqual(ref.delays); + + const failures: string[] = []; + const shares: string[] = []; + ref.frames.forEach((refFrame, i) => { + const v = compare(refFrame, got.frames[i]!, ref.width); + shares.push(`${pct(v.share)}/${v.blocks}`); + if (passes(v)) return; + mkdirSync(OUT, { recursive: true }); + const stem = join(OUT, `${name}-f${i}`); + writePng(`${stem}-reference.png`, ref.width, ref.height, refFrame); + writePng(`${stem}-runtime.png`, ref.width, ref.height, got.frames[i]!); + writePng(`${stem}-diff.png`, ref.width, ref.height, v.diff); + failures.push( + `frame ${i}: ${pct(v.share)} differ, ${v.blocks} whole 2x2 blocks; see ${stem}-{reference,runtime,diff}.png` + ); + }); + if (process.env.LATCH_PARITY_REPORT) + console.log(`${name}: ${shares.join(' ')}`); + expect(failures).toEqual([]); + }); + } +}); + +// Each pair is two frames of one approved GIF that differ by a single +// feature, so the gate must reject either as a stand-in for the other. +const FEATURE_PAIRS: [string, string, number, number][] = [ + ['one queued dot', 'queued', 0, 1], + ['three queued dots', 'queued', 0, 3], + ['the approved sparkles', 'done-approved', 0, 4], + ['the blink', 'armed', 2, 3], + ['the second leg pose', 'armed', 0, 1], +]; + +describe('the parity gate rejects a missing feature', () => { + for (const [feature, name, a, b] of FEATURE_PAIRS) { + test(feature, () => { + const ref = decode(readFileSync(join(REFERENCE, `latch-${name}.gif`))); + const v = compare(ref.frames[a]!, ref.frames[b]!, ref.width); + expect(v.share).toBeLessThanOrEqual(MAX_DIFFERING); + expect(passes(v)).toBe(false); + }); + } +}); diff --git a/apps/board/src/__tests__/latch-banner.test.ts b/apps/board/src/__tests__/latch-banner.test.ts index 8c29bc4e7c..aa8977b946 100644 --- a/apps/board/src/__tests__/latch-banner.test.ts +++ b/apps/board/src/__tests__/latch-banner.test.ts @@ -1,48 +1,278 @@ import { describe, expect, test } from 'bun:test'; -import { PNG } from 'pngjs'; +import { INVADR_SPRITES, resolveInvadr } from 'invadrs'; -import { BAND_H, BAND_W, latchBannerPng } from '../latch/banner.ts'; +import { LAYOUT } from '../../assets/latch/index.ts'; +import { + GIF_H, + GIF_W, + latchBannerGif, + legShuffle, + renderBannerGif, +} from '../latch/banner.ts'; +import { + allVariantKeys, + copyFor, + DOT_GAP_PX, + DOT_PX, + variantOfKey, + type BannerVariant, +} from '../latch/variants.ts'; +import { PROTOTYPE_CREATURE } from './fixtures/latch-prototype-creature.ts'; const MR_A = 'https://gitlab.com/acme/web/-/merge_requests/2317'; const MR_B = 'https://gitlab.com/acme/web/-/merge_requests/2318'; -function decode(buf: Buffer): PNG { - return PNG.sync.read(buf); +interface GifFrame { + delay: number; + pixels: Uint8Array; } -describe('latchBannerPng', () => { - test("returns a PNG at the band's dimensions", () => { - const png = decode(latchBannerPng(MR_A)); - expect(png.width).toBe(BAND_W); - expect(png.height).toBe(BAND_H); +interface Gif { + width: number; + height: number; + palette: [number, number, number][]; + frames: GifFrame[]; +} + +function readSubBlocks(b: Uint8Array, p: number): [Uint8Array, number] { + const parts: number[] = []; + while (b[p] !== 0) { + const n = b[p]!; + for (let i = 1; i <= n; i++) parts.push(b[p + i]!); + p += n + 1; + } + return [Uint8Array.from(parts), p + 1]; +} + +function lzwDecode( + data: Uint8Array, + minSize: number, + count: number +): Uint8Array { + const out = new Uint8Array(count); + const clear = 1 << minSize; + const end = clear + 1; + let size = minSize + 1; + let dict: number[][] = []; + const reset = () => { + dict = []; + for (let i = 0; i < clear; i++) dict[i] = [i]; + dict[clear] = []; + dict[end] = []; + size = minSize + 1; + }; + reset(); + let prev: number[] | null = null; + let o = 0; + let bit = 0; + while (o < count) { + let code = 0; + for (let i = 0; i < size; i++, bit++) { + code |= ((data[bit >> 3]! >> (bit & 7)) & 1) << i; + } + if (code === clear) { + reset(); + prev = null; + continue; + } + if (code === end) break; + let entry: number[]; + if (code < dict.length) entry = dict[code]!; + else entry = [...prev!, prev![0]!]; + for (const v of entry) out[o++] = v; + if (prev) dict.push([...prev, entry[0]!]); + prev = entry; + if (dict.length === 1 << size && size < 12) size++; + } + return out; +} + +function parseGif(b: Uint8Array): Gif { + const width = b[6]! | (b[7]! << 8); + const height = b[8]! | (b[9]! << 8); + const packed = b[10]!; + let p = 13; + const palette: [number, number, number][] = []; + if (packed & 0x80) { + const n = 1 << ((packed & 7) + 1); + for (let i = 0; i < n; i++, p += 3) + palette.push([b[p]!, b[p + 1]!, b[p + 2]!]); + } + const frames: GifFrame[] = []; + let delay = 0; + while (p < b.length) { + const tag = b[p]!; + if (tag === 0x3b) break; + if (tag === 0x21) { + const label = b[p + 1]!; + if (label === 0xf9) delay = (b[p + 4]! | (b[p + 5]! << 8)) * 10; + [, p] = readSubBlocks(b, p + 2); + } else if (tag === 0x2c) { + const w = b[p + 5]! | (b[p + 6]! << 8); + const h = b[p + 7]! | (b[p + 8]! << 8); + if (b[p + 9]! & 0x80) throw new Error('local colour tables not expected'); + const minSize = b[p + 10]!; + const [data, next] = readSubBlocks(b, p + 11); + frames.push({ delay, pixels: lzwDecode(data, minSize, w * h) }); + p = next; + } else { + throw new Error(`unexpected GIF block 0x${tag.toString(16)} at ${p}`); + } + } + return { width, height, palette, frames }; +} + +function rgbAt(gif: Gif, frame: number, x: number, y: number): string { + const [r, g, b] = gif.palette[gif.frames[frame]!.pixels[y * gif.width + x]!]!; + return `#${[r, g, b].map(v => v.toString(16).padStart(2, '0')).join('')}`; +} + +const cache = new Map(); +function gifFor(key: string, mrUrl = MR_A): Uint8Array { + const id = `${mrUrl} ${key}`; + let bytes = cache.get(id); + if (!bytes) { + bytes = latchBannerGif(mrUrl, variantOfKey(key)!); + cache.set(id, bytes); + } + return bytes; +} + +const FRAMES: Record = { + armed: 6, + queued: 8, + running: 8, + 'error-retrying': 8, + 'error-stuck': 8, + 'done-comments': 8, + 'done-approved': 8, + approved: 8, + superseded: 1, +}; + +function toGrid(rows: readonly string[]): boolean[][] { + return rows.map(row => [...row].map(c => c === '#')); +} + +/** Centre of sprite cell (col, row) at rest, for the 11-wide creatures. */ +function cellCentre(col: number, row: number): [number, number] { + return [28 + (2 + col) * 6 + 3, 32 + row * 6 + 3]; +} + +describe('latchBannerGif', () => { + test('encodes a 1040x128 GIF for every variant key', () => { + for (const key of allVariantKeys()) { + const b = gifFor(key); + expect(String.fromCharCode(...b.slice(0, 6))).toBe('GIF89a'); + expect(b[6]! | (b[7]! << 8)).toBe(GIF_W); + expect(b[8]! | (b[9]! << 8)).toBe(GIF_H); + } + }, 60_000); + + test('frame count matches the plan', () => { + for (const key of allVariantKeys()) { + const v = variantOfKey(key)!; + expect({ key, frames: parseGif(gifFor(key)).frames.length }).toEqual({ + key, + frames: FRAMES[v.state], + }); + } + }, 60_000); + + test('every GIF is under 80 KB', () => { + for (const key of allVariantKeys()) { + expect({ key, small: gifFor(key).length < 80 * 1024 }).toEqual({ + key, + small: true, + }); + } + }, 60_000); + + test('deterministic for one MR', () => { + const again = latchBannerGif(MR_A, { state: 'running' }); + expect(Buffer.from(again).equals(Buffer.from(gifFor('running')))).toBe( + true + ); }); - // The sprite is the per-MR part, so two MRs must not produce identical bytes. test('differs between MRs', () => { - expect(latchBannerPng(MR_A).equals(latchBannerPng(MR_B))).toBe(false); - }); - - // invadrs freezes its hash, so the same MR must render the same banner forever. - test('is deterministic for one MR', () => { - expect(latchBannerPng(MR_A).equals(latchBannerPng(MR_A))).toBe(true); - }); - - test('paints the sprite in the board pink, not a palette colour', () => { - const png = decode(latchBannerPng(MR_A)); - // Count ONLY inside the sprite box. The band's own pink rule spans the full - // width, so a whole-image count would pass even with sprite painting broken. - let pink = 0; - for (let y = 44; y < 44 + 120; y++) { - for (let x = 60; x < 60 + 120; x++) { - const i = (png.width * y + x) << 2; - if ( - png.data[i] === 0xff && - png.data[i + 1] === 0x6b && - png.data[i + 2] === 0x9d - ) - pink++; - } - } - expect(pink).toBeGreaterThan(1000); + expect( + Buffer.from(gifFor('running', MR_B)).equals( + Buffer.from(gifFor('running')) + ) + ).toBe(false); + }); + + test('paints every creature cell and eye in its exact colour, for every variant', () => { + const { grid, accent } = resolveInvadr(MR_A, { accent: true }); + const filled = grid.flatMap((r, row) => + r.flatMap((on, col) => (on ? [[col, row] as [number, number]] : [])) + ); + for (const key of allVariantKeys()) { + const gif = parseGif(gifFor(key)); + const want = copyFor(variantOfKey(key)!).accent; + const bodies = new Set( + filled.map(c => rgbAt(gif, 0, ...cellCentre(...c))) + ); + const eyes = new Set( + accent!.cells.map(c => rgbAt(gif, 0, ...cellCentre(...c))) + ); + expect({ key, bodies: [...bodies], eyes: [...eyes] }).toEqual({ + key, + bodies: [want], + eyes: ['#ece8f4'], + }); + } + }, 60_000); + + test('names the variant when its strip is missing', () => { + expect(() => + renderBannerGif(PROTOTYPE_CREATURE, { state: 'nope' as never }) + ).toThrow('no latch strip for nope'); + }); + + test('lights the queued dots beside the title', () => { + const gif = parseGif(gifFor('queued-cooldown')); + const { dotsX, dotsY } = ( + LAYOUT as Record + )['queued-cooldown']!; + const dot = (i: number, frame: number) => + rgbAt(gif, frame, dotsX + i * (DOT_PX + DOT_GAP_PX) + 4, dotsY + 4); + expect([0, 1, 2].map(i => dot(i, 0))).toEqual(Array(3).fill('#2a2638')); + expect([0, 1, 2].map(i => dot(i, 3))).toEqual(Array(3).fill('#e6b860')); + expect(gif.frames.map(f => f.delay)).toEqual(Array(8).fill(420)); + }); + + test('moves the running ring head clockwise', () => { + const gif = parseGif(gifFor('running')); + const topLeft: [number, number] = [948 + 6, 42 + 6]; + const topMid: [number, number] = [964 + 6, 42 + 6]; + expect(rgbAt(gif, 0, ...topLeft)).toBe('#7fbfe8'); + expect(rgbAt(gif, 0, ...topMid)).toBe('#5d5775'); + expect(rgbAt(gif, 1, ...topMid)).toBe('#7fbfe8'); + }); +}); + +describe('legShuffle', () => { + test('changes the bottom rows of all 16 INVADR_SPRITES and nothing above them', () => { + expect(INVADR_SPRITES).toHaveLength(16); + for (const rows of INVADR_SPRITES) { + const grid = toGrid(rows); + const out = legShuffle(grid); + const h = grid.length; + expect(out.slice(0, h - 2)).toEqual(grid.slice(0, h - 2)); + expect(out.slice(h - 2)).not.toEqual(grid.slice(h - 2)); + expect(grid).toEqual(toGrid(rows)); + } + }); + + test('moves cells toward the centre and keeps the centre column', () => { + const grid = toGrid(['.....', '#.#.#', '##.##']); + expect(legShuffle(grid)).toEqual(toGrid(['.....', '.###.', '.###.'])); + }); + + test("turns the prototype's first leg pose into its second", () => { + const [first, second] = PROTOTYPE_CREATURE.frames; + expect(legShuffle(first)).toEqual(second); }); }); diff --git a/apps/board/src/__tests__/latch-discussions.test.ts b/apps/board/src/__tests__/latch-discussions.test.ts index e556014f29..13e47417bf 100644 --- a/apps/board/src/__tests__/latch-discussions.test.ts +++ b/apps/board/src/__tests__/latch-discussions.test.ts @@ -4,12 +4,12 @@ import type { MRDetail } from '@mattstack/glance'; import { canonicalLatch, findLatches, - hasArmedLatch, + hasLiveLatch, hasRequest, requestCarriers, reviewerLatches, } from '../latch/discussions.ts'; -import { armedLatchBody, spentLatchBody } from '../latch/markers.ts'; +import { armedLatchBody, latchBody, spentLatchBody } from '../latch/markers.ts'; const IMG = '![re-review latch](/uploads/ab12/latch.png)'; @@ -196,14 +196,14 @@ describe('requestCarriers / hasRequest', () => { }); }); -describe('hasArmedLatch', () => { +describe('hasLiveLatch', () => { test('false with no latch at all', () => { - expect(hasArmedLatch(findLatches(detail(), 'matt'))).toBe(false); + expect(hasLiveLatch(findLatches(detail(), 'matt'))).toBe(false); }); test('true for an armed latch, resolved or not', () => { expect( - hasArmedLatch( + hasLiveLatch( findLatches( detail( disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', false) @@ -213,7 +213,7 @@ describe('hasArmedLatch', () => { ) ).toBe(true); expect( - hasArmedLatch( + hasLiveLatch( findLatches( detail(disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true)), 'matt' @@ -222,6 +222,28 @@ describe('hasArmedLatch', () => { ).toBe(true); }); + // A queued, running or errored latch is still the live one: posting beside + // it would hand the author a second latch for the same ask. + test('true for a queued, running or error latch', () => { + for (const kind of ['queued', 'running', 'error'] as const) { + expect( + hasLiveLatch( + findLatches( + detail( + disc( + 'd1', + latchBody(kind, IMG, 'x'), + '2026-09-01T10:00:00Z', + true + ) + ), + 'matt' + ) + ) + ).toBe(true); + } + }); + // The bug this guards: canonicalLatch returns the newest latch of EITHER // kind, so a spent-only MR must read as unlatched here, not as latched. test('false when only a spent latch exists, even though canonicalLatch returns it', () => { @@ -230,7 +252,7 @@ describe('hasArmedLatch', () => { 'matt' ); expect(canonicalLatch(latches)).not.toBeNull(); - expect(hasArmedLatch(latches)).toBe(false); + expect(hasLiveLatch(latches)).toBe(false); }); }); diff --git a/apps/board/src/__tests__/latch-land.test.ts b/apps/board/src/__tests__/latch-land.test.ts new file mode 100644 index 0000000000..fbeb0f3637 --- /dev/null +++ b/apps/board/src/__tests__/latch-land.test.ts @@ -0,0 +1,425 @@ +import { afterAll, describe, expect, test } from 'bun:test'; + +import type { MRDetail } from '@mattstack/glance'; +import { + countNewDiscussions, + fetchNewDiscussionCount, + landFollowUp, + type LandInput, +} from '../latch/land.ts'; +import { + putLatchRow, + readLatchRow, + type LatchRow, +} from '../latch/latch-state.ts'; +import { armedLatchBody, latchBody } from '../latch/markers.ts'; +import type { LatchGateway } from '../latch/post.ts'; +import { copyFor, variantOfKey } from '../latch/variants.ts'; +import { removeTempDbs, tempDb } from './latch-temp-db.ts'; + +afterAll(removeTempDbs); + +const NOW = 2_000_000; +const MR = 'https://gitlab.com/acme/web/-/merge_requests/2317'; +const IMG = '![re-review latch](/uploads/ab12/latch-2317.png)'; +const ARMED = ''; +const SPENT = ''; + +function row(over: Partial = {}): LatchRow { + return { + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, + phase: 'running', + wait: null, + launchAt: 1_000, + failures: 2, + stuck: false, + variant: 'running', + replyDue: null, + updatedAt: 1, + ...over, + }; +} + +function harness( + over: Partial = {}, + stored: LatchRow | null = row() +) { + const db = tempDb(); + if (stored) putLatchRow(stored, db); + const calls: string[] = []; + const uploads: string[] = []; + const replies: string[] = []; + const noteBodies = new Map(); + let counted = 0; + const gateway: LatchGateway = { + async uploadFile(_p, filename) { + calls.push('upload'); + uploads.push(filename); + return { alt: '', url: '', full_path: '', markdown: IMG }; + }, + async createDiscussion() { + calls.push('createDiscussion'); + return { id: 'new', notes: [{ id: 1 }] }; + }, + async updateNote(_p, _i, id, body) { + calls.push(`updateNote:${id}`); + noteBodies.set(id, body); + }, + async resolveDiscussion(_p, _i, id) { + calls.push(`resolve:${id}`); + }, + async unresolveDiscussion(_p, _i, id) { + calls.push(`unresolve:${id}`); + }, + async createNote(_p, _i, body, d) { + calls.push(`reply:${d}`); + replies.push(body); + return { id: 9 }; + }, + }; + const input: LandInput = { + target: { + projectId: 42, + projectPath: 'acme/web', + iid: 2317, + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, + }, + outcome: 'comment', + reviewRunStartedAt: 1_500, + gateway, + self: 'matt', + countNew: async () => { + counted++; + return 3; + }, + now: NOW, + ...over, + }; + return { + db, + input, + calls, + uploads, + replies, + noteBodies, + land: () => landFollowUp(input, db), + counted: () => counted, + }; +} + +describe('landFollowUp', () => { + test('comment lands as done-comments with the count and reopens', async () => { + const h = harness(); + expect(await h.land()).toBe('landed'); + expect(h.uploads).toEqual(['latch-2317-done-comments-3.gif']); + expect(h.calls).toEqual([ + 'upload', + 'updateNote:1', + 'unresolve:d1', + 'reply:d1', + ]); + expect(h.noteBodies.get(1)).toStartWith(ARMED); + expect(h.replies).toEqual(['Follow-up review done: 3 new comments.']); + expect(readLatchRow(MR, h.db)).toMatchObject({ + phase: 'armed', + failures: 0, + stuck: false, + wait: null, + launchAt: null, + variant: 'done-comments-3', + replyDue: null, + updatedAt: NOW, + }); + }); + + test('a reply that fails to post is still owed, and the approval still spends the extras', async () => { + const h = harness({ + outcome: 'approve', + latches: [ + { + discussionId: 'd2', + rootNoteId: 2, + kind: 'armed', + resolved: false, + createdAt: '', + body: '', + }, + ], + }); + h.input.gateway.createNote = async () => { + throw new Error('gitlab 500'); + }; + expect(await h.land()).toBe('landed'); + expect(h.calls).toContain('updateNote:2'); + expect(readLatchRow(MR, h.db)).toMatchObject({ + phase: 'spent', + replyDue: 'Follow-up review done: approved.', + }); + }); + + test('an abandoned landing owes no reply, and drops a stuck reply still owed', async () => { + const h = harness( + { outcome: null }, + row({ + phase: 'error', + stuck: true, + variant: 'error-stuck', + replyDue: copyFor({ state: 'error-stuck' }).sentence, + }) + ); + expect(await h.land()).toBe('landed'); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, h.db)?.replyDue).toBeNull(); + }); + + test('one new comment reads singular', async () => { + const h = harness({ countNew: async () => 1 }); + await h.land(); + expect(h.replies).toEqual(['Follow-up review done: 1 new comment.']); + }); + + test('count null shows Review posted', async () => { + const h = harness({ countNew: async () => null }); + expect(await h.land()).toBe('landed'); + expect(h.uploads).toEqual(['latch-2317-done-comments-none.gif']); + const variant = variantOfKey(readLatchRow(MR, h.db)!.variant!); + expect(copyFor(variant!).sub).toBe('Review posted. Resolve when ready'); + expect(h.replies).toEqual(['Follow-up review done.']); + }); + + test('a count of zero also replies without a number', async () => { + const h = harness({ countNew: async () => 0 }); + await h.land(); + expect(h.uploads).toEqual(['latch-2317-done-comments-none.gif']); + expect(h.replies).toEqual(['Follow-up review done.']); + }); + + test('approve spends with done-approved and one reply', async () => { + const h = harness({ outcome: 'approve' }); + expect(await h.land()).toBe('landed'); + expect(h.uploads).toEqual(['latch-2317-done-approved.gif']); + expect(h.calls).toEqual([ + 'upload', + 'updateNote:1', + 'resolve:d1', + 'reply:d1', + ]); + expect(h.noteBodies.get(1)).toStartWith(SPENT); + expect(h.replies).toEqual(['Follow-up review done: approved.']); + expect(h.counted()).toBe(0); + expect(readLatchRow(MR, h.db)).toMatchObject({ + phase: 'spent', + variant: 'done-approved', + }); + }); + + test('abandoned review re-arms quietly', async () => { + const h = harness({ outcome: null }); + expect(await h.land()).toBe('landed'); + expect(h.uploads).toEqual(['latch-2317-armed.gif']); + expect(h.calls).toEqual(['upload', 'updateNote:1', 'unresolve:d1']); + expect(h.noteBodies.get(1)).toStartWith(ARMED); + expect(h.replies).toEqual([]); + expect(h.counted()).toBe(0); + expect(readLatchRow(MR, h.db)).toMatchObject({ + phase: 'armed', + wait: null, + launchAt: null, + stuck: false, + variant: 'armed', + }); + }); + + test('landFollowUp is idempotent across server and pass', async () => { + const h = harness(); + expect(await h.land()).toBe('landed'); + expect(await h.land()).toBe('none'); + expect(h.calls.filter(c => c.startsWith('updateNote'))).toHaveLength(1); + expect(h.replies).toHaveLength(1); + expect(h.counted()).toBe(1); + }); + + // The server's signal and the pass overlap: B lands while A waits on its + // GitLab count, and A's move then finds the row already armed. + test('an interleaved second landing writes nothing', async () => { + const h = harness(); + const b: string[] = []; + h.input.countNew = async () => { + b.push(await landFollowUp({ ...h.input, countNew: async () => 3 }, h.db)); + return 3; + }; + expect(await h.land()).toBe('none'); + expect(b).toEqual(['landed']); + expect(h.calls.filter(c => c.startsWith('updateNote'))).toHaveLength(1); + expect(h.replies).toEqual(['Follow-up review done: 3 new comments.']); + }); + + test('a review whose runStartedAt is before launchAt does not land', async () => { + const h = harness({ reviewRunStartedAt: 999 }); + expect(await h.land()).toBe('not-mine'); + expect(h.calls).toEqual([]); + expect(readLatchRow(MR, h.db)).toEqual(row()); + }); + + test('a spent row never lands', async () => { + const spent = row({ phase: 'spent', variant: 'approved' }); + const h = harness({}, spent); + expect(await h.land()).toBe('none'); + expect(h.calls).toEqual([]); + expect(readLatchRow(MR, h.db)).toEqual(spent); + }); + + test('an error row with no launch stamp never lands', async () => { + const failedFirst = row({ phase: 'error', launchAt: null, failures: 1 }); + const h = harness({ reviewRunStartedAt: NOW }, failedFirst); + expect(await h.land()).toBe('not-mine'); + expect(h.calls).toEqual([]); + expect(readLatchRow(MR, h.db)).toEqual(failedFirst); + }); + + test('a stuck error row whose review finished lands and clears stuck', async () => { + const stuck = row({ + phase: 'error', + failures: 3, + stuck: true, + variant: 'error-stuck', + }); + const h = harness({}, stuck); + expect(await h.land()).toBe('landed'); + expect(readLatchRow(MR, h.db)).toMatchObject({ + phase: 'armed', + failures: 0, + stuck: false, + }); + }); + + // The abandoned run consumed the request, so the next one is a new cycle. + test('an abandoned review resets the failure count', async () => { + const h = harness({ outcome: null }); + await h.land(); + expect(readLatchRow(MR, h.db)?.failures).toBe(0); + }); + + test('an approve landing spends the other copies approved', async () => { + const extra = { + discussionId: 'extra', + rootNoteId: 2, + kind: 'armed' as const, + resolved: false, + createdAt: '2026-09-01T10:00:00Z', + body: armedLatchBody(IMG), + }; + const self = { + ...extra, + discussionId: 'd1', + rootNoteId: 1, + kind: 'running' as const, + }; + const h = harness({ outcome: 'approve', latches: [self, extra] }); + expect(await h.land()).toBe('landed'); + expect(h.uploads).toEqual([ + 'latch-2317-done-approved.gif', + 'latch-2317-approved.gif', + ]); + expect(h.calls).toEqual([ + 'upload', + 'updateNote:1', + 'resolve:d1', + 'reply:d1', + 'upload', + 'updateNote:2', + 'resolve:extra', + ]); + expect(h.noteBodies.get(2)).toStartWith(SPENT); + }); + + test('a row tracking another latch is not this one to land', async () => { + const h = harness({}, row({ discussionId: 'other' })); + expect(await h.land()).toBe('not-mine'); + expect(h.calls).toEqual([]); + }); + + test('no row lands nothing', async () => { + const h = harness({}, null); + expect(await h.land()).toBe('none'); + expect(h.calls).toEqual([]); + }); +}); + +describe('countNewDiscussions', () => { + function disc( + id: string, + body: string, + author: string, + createdAt: string, + system = false + ) { + return { + id, + resolvable: true, + resolved: false, + notes: [ + { + id: 1, + body, + author: { id: 1, username: author, name: author, avatarUrl: null }, + createdAt, + system, + type: 'DiscussionNote', + resolvable: true, + resolved: false, + position: null, + }, + ], + }; + } + const launchAt = Date.parse('2026-09-01T10:00:00Z'); + + test("counts the reviewer's own threads opened at or after the launch", () => { + const detail = { + mrIid: 2317, + repositoryId: 'gitlab:42', + discussions: [ + disc('a', 'Rename this', 'Matt', '2026-09-01T10:00:00Z'), + disc('b', 'Missing test', 'matt', '2026-09-01T10:05:00Z'), + disc('c', 'Older thread', 'matt', '2026-09-01T09:59:59Z'), + disc('d', 'Not mine', 'lee', '2026-09-01T10:05:00Z'), + disc( + 'e', + latchBody('running', IMG, 'x'), + 'matt', + '2026-09-01T10:05:00Z' + ), + disc('f', armedLatchBody(IMG), 'matt', '2026-09-01T10:06:00Z'), + disc('g', 'added 1 commit', 'matt', '2026-09-01T10:06:00Z', true), + ], + } as unknown as MRDetail; + expect(countNewDiscussions(detail, 'matt', launchAt)).toBe(2); + }); + + test('fetchNewDiscussionCount counts a fresh read the same way', async () => { + const detail = { + mrIid: 2317, + repositoryId: 'gitlab:42', + discussions: [ + disc('a', 'Rename this', 'matt', '2026-09-01T10:01:00Z'), + disc('b', armedLatchBody(IMG), 'matt', '2026-09-01T10:02:00Z'), + disc('c', 'Before launch', 'matt', '2026-09-01T09:00:00Z'), + ], + } as unknown as MRDetail; + expect( + await fetchNewDiscussionCount(async () => detail, 'matt', launchAt) + ).toBe(1); + }); + + test('fetchNewDiscussionCount is null when the read fails', async () => { + const failing = async (): Promise => { + throw new Error('gitlab down'); + }; + expect(await fetchNewDiscussionCount(failing, 'matt', launchAt)).toBeNull(); + }); +}); diff --git a/apps/board/src/__tests__/latch-markers.test.ts b/apps/board/src/__tests__/latch-markers.test.ts index 02514a41c3..b263bb9f3b 100644 --- a/apps/board/src/__tests__/latch-markers.test.ts +++ b/apps/board/src/__tests__/latch-markers.test.ts @@ -1,10 +1,17 @@ import { describe, expect, test } from 'bun:test'; +import type { LatchPhase } from '../latch/latch-state.ts'; import { armedLatchBody, + imageMarkdownFor, imageMarkdownOf, LATCH_MARKER, + LATCH_MARKER_ERROR, + LATCH_MARKER_QUEUED, + LATCH_MARKER_RUNNING, LATCH_MARKER_SPENT, + latchBody, + latchKindOf, spentLatchBody, } from '../latch/markers.ts'; @@ -28,23 +35,61 @@ describe('bodies', () => { expect(spentLatchBody(IMG)).toContain('Approved, so this latch is spent'); }); - // A duplicate consumed by a dispatch or a cooldown refusal must never read - // as an approval that did not happen, however the MR's real outcome lands. - test('a duplicate reason gets the superseded wording, not approved', () => { - const body = spentLatchBody(IMG, 'duplicate'); - expect(body).toContain('Superseded by a newer latch on this MR'); - expect(body).not.toContain('Approved'); - }); - test('neither body uses an em dash or en dash', () => { expect(armedLatchBody(IMG)).not.toMatch(/[–—]/); expect(spentLatchBody(IMG)).not.toMatch(/[–—]/); }); }); +describe('latchBody', () => { + const GIF = '![Follow-up review queued](/uploads/a/b.gif){width=520}'; + const MARKERS: Record = { + armed: LATCH_MARKER, + queued: LATCH_MARKER_QUEUED, + running: LATCH_MARKER_RUNNING, + error: LATCH_MARKER_ERROR, + spent: LATCH_MARKER_SPENT, + }; + + for (const phase of Object.keys(MARKERS) as LatchPhase[]) { + test(`a ${phase} body leads with its marker and reads back as ${phase}`, () => { + const body = latchBody(phase, GIF, 'A sentence.'); + expect(body.split('\n')[0]).toBe(MARKERS[phase]); + expect(latchKindOf(body)).toBe(phase); + }); + } + + test('marker, blank, image, blank, sentence', () => { + expect(latchBody('running', GIF, 'In progress.')).toBe( + `${LATCH_MARKER_RUNNING}\n\n${GIF}\n\nIn progress.\n` + ); + }); +}); + +describe('imageMarkdownFor', () => { + test('titles the upload and sizes it to 520 px', () => { + expect( + imageMarkdownFor( + 'Follow-up review running', + '![latch-7-running.gif](/uploads/c0ffee/latch-7-running.gif)' + ) + ).toBe( + '![Follow-up review running](/uploads/c0ffee/latch-7-running.gif){width=520}' + ); + }); +}); + describe('imageMarkdownOf', () => { - // The spend reuses the already-uploaded banner rather than uploading again, - // so it has to read the path back out of the armed body. + test('matches a gif with a width suffix', () => { + const img = '![x](/uploads/a/b.gif){width=520}'; + expect(imageMarkdownOf(latchBody('queued', img, 'Queued.'))).toBe(img); + }); + + test('still matches the old png banner', () => { + const img = '![re-review latch](/uploads/a/b.png)'; + expect(imageMarkdownOf(armedLatchBody(img))).toBe(img); + }); + test('round-trips the image out of an armed body', () => { expect(imageMarkdownOf(armedLatchBody(IMG))).toBe(IMG); }); diff --git a/apps/board/src/__tests__/latch-post.test.ts b/apps/board/src/__tests__/latch-post.test.ts index 33dfbe08ad..85893ab970 100644 --- a/apps/board/src/__tests__/latch-post.test.ts +++ b/apps/board/src/__tests__/latch-post.test.ts @@ -1,28 +1,42 @@ -import { describe, expect, test } from 'bun:test'; +import { afterAll, describe, expect, test } from 'bun:test'; import type { LatchRef } from '../latch/discussions.ts'; +import { + putLatchRow, + readLatchRow, + type LatchRow, +} from '../latch/latch-state.ts'; import { latchKindOf } from '../latch/markers.ts'; import { + bannerMarkdown, postLatch, + rewriteLatch, spendAllLatches, spendLatch, type LatchGateway, + type LatchTarget, } from '../latch/post.ts'; +import { removeTempDbs, tempDb } from './latch-temp-db.ts'; + +afterAll(removeTempDbs); const MR = 'https://gitlab.com/acme/web/-/merge_requests/2317'; -const IMG = '![re-review latch](/uploads/ab12/latch-2317.png)'; +const NOW = 1_700_000_000_000; +const OLD_IMG = '![re-review latch](/uploads/ab12/latch-2317.png)'; function gateway() { const calls: string[] = []; const bodies: string[] = []; + const uploads: Array<{ filename: string; contentType?: string }> = []; const gw: LatchGateway = { - async uploadFile(_p, filename) { + async uploadFile(_p, filename, _bytes, contentType) { calls.push(`upload:${filename}`); + uploads.push({ filename, contentType }); return { - alt: 'latch', - url: '/uploads/ab12/latch-2317.png', + alt: filename, + url: `/uploads/ab12/${filename}`, full_path: 'x', - markdown: IMG, + markdown: `![${filename}](/uploads/ab12/${filename})`, }; }, async createDiscussion(_p, _iid, body) { @@ -46,16 +60,155 @@ function gateway() { return { id: 9 } as never; }, }; - return { gw, calls, bodies }; + return { gw, calls, bodies, uploads }; +} + +function row(overrides: Partial = {}): LatchRow { + return { + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: 1, + ...overrides, + }; } +const target: LatchTarget = { + projectId: 42, + projectPath: 'acme/web', + iid: 2317, + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, +}; + +describe('bannerMarkdown', () => { + test('uploads a gif named for the variant and titles it', async () => { + const db = tempDb(); + const { gw, uploads } = gateway(); + const md = await bannerMarkdown(gw, 42, MR, 2317, { state: 'armed' }, db); + expect(uploads).toEqual([ + { filename: 'latch-2317-armed.gif', contentType: 'image/gif' }, + ]); + expect(md).toBe( + '![Ready for another pass?](/uploads/ab12/latch-2317-armed.gif){width=520}' + ); + }); + + test('uploads once per variant', async () => { + const db = tempDb(); + const { gw, calls } = gateway(); + const v = { state: 'queued' as const, wait: 'cooldown' as const }; + const first = await bannerMarkdown(gw, 42, MR, 2317, v, db); + const second = await bannerMarkdown(gw, 42, MR, 2317, v, db); + expect(second).toBe(first); + expect(calls).toEqual(['upload:latch-2317-queued-cooldown.gif']); + }); + + test('a different variant uploads its own banner', async () => { + const db = tempDb(); + const { gw, calls } = gateway(); + await bannerMarkdown(gw, 42, MR, 2317, { state: 'running' }, db); + await bannerMarkdown(gw, 42, MR, 2317, { state: 'armed' }, db); + expect(calls).toEqual([ + 'upload:latch-2317-running.gif', + 'upload:latch-2317-armed.gif', + ]); + }); +}); + describe('postLatch', () => { test('uploads the banner then creates a resolvable discussion', async () => { + const db = tempDb(); + const { gw, calls, bodies } = gateway(); + const posted = await postLatch(gw, 42, 'acme/web', MR, 2317, db); + expect(posted).toEqual({ discussionId: 'd1', rootNoteId: 1 }); + expect(calls).toEqual(['upload:latch-2317-armed.gif', 'createDiscussion']); + expect(latchKindOf(bodies[0]!)).toBe('armed'); + expect(bodies[0]).toContain( + '/uploads/ab12/latch-2317-armed.gif){width=520}' + ); + expect(bodies[0]).toContain('Resolve this thread'); + }); +}); + +describe('rewriteLatch', () => { + // A crash between the two writes leaves the phase visible on the note, + // and the row decides recovery. + test('writes the note before unresolving', async () => { + const db = tempDb(); const { gw, calls, bodies } = gateway(); - await postLatch(gw, 42, 'acme/web', MR, 2317); - expect(calls).toEqual(['upload:latch-2317.png', 'createDiscussion']); + await rewriteLatch( + gw, + target, + 'armed', + { state: 'done-comments', count: 3 }, + 'unresolve', + NOW, + db + ); + expect(calls).toEqual([ + 'upload:latch-2317-done-comments-3.gif', + 'updateNote:1', + 'unresolve:d1', + ]); expect(latchKindOf(bodies[0]!)).toBe('armed'); - expect(bodies[0]).toContain(IMG); + expect(bodies[0]).toContain('addressed the new comments'); + }); + + test('resolve resolves after the write, keep leaves the thread', async () => { + const db = tempDb(); + const { gw, calls } = gateway(); + await rewriteLatch( + gw, + target, + 'running', + { state: 'running' }, + 'resolve', + NOW, + db + ); + await rewriteLatch( + gw, + target, + 'running', + { state: 'running' }, + 'keep', + NOW, + db + ); + expect(calls).toEqual([ + 'upload:latch-2317-running.gif', + 'updateNote:1', + 'resolve:d1', + 'updateNote:1', + ]); + }); + + test("records the variant on this latch's row", async () => { + const db = tempDb(); + putLatchRow(row({ phase: 'queued', variant: 'queued-next-sweep' }), db); + const { gw } = gateway(); + await rewriteLatch( + gw, + target, + 'queued', + { state: 'queued', wait: 'budget' }, + 'keep', + NOW, + db + ); + expect(readLatchRow(MR, db)).toMatchObject({ + variant: 'queued-budget', + updatedAt: NOW, + }); }); }); @@ -66,60 +219,153 @@ describe('spendLatch', () => { kind: 'armed', resolved: true, createdAt: '2026-09-01T10:00:00Z', - body: `\n\n${IMG}\n\nbody`, + body: `\n\n${OLD_IMG}\n\nbody`, }; // Rewrite BEFORE resolve. A crash between them leaves a spent-but-unresolved // latch, which the pass repairs. The reverse leaves a resolved-but-unspent // latch, which is indistinguishable from a human request. test('rewrites the body before resolving', async () => { + const db = tempDb(); const { gw, calls, bodies } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, armed); - expect(calls).toEqual(['updateNote:1', 'resolve:d1']); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + armed, + { state: 'approved' }, + NOW, + db + ); + expect(calls).toEqual([ + 'upload:latch-2317-approved.gif', + 'updateNote:1', + 'resolve:d1', + ]); expect(latchKindOf(bodies[0]!)).toBe('spent'); - }); - - // The banner is already uploaded; spending must not upload it again. - test('reuses the uploaded banner instead of re-uploading', async () => { - const { gw, calls, bodies } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, armed); - expect(calls.some(c => c.startsWith('upload:'))).toBe(false); - expect(bodies[0]).toContain(IMG); + expect(bodies[0]).toContain('Approved, so this latch is spent'); + expect(bodies[0]).toContain('![Approved]('); }); test('an already-spent latch that is resolved draws no writes', async () => { + const db = tempDb(); const { gw, calls } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, { - ...armed, - kind: 'spent', - resolved: true, - }); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + { ...armed, kind: 'spent', resolved: true }, + { state: 'approved' }, + NOW, + db + ); expect(calls).toEqual([]); }); // The crash-repair path: body already spent, thread still open. test('an already-spent latch that is unresolved is only re-resolved', async () => { + const db = tempDb(); const { gw, calls } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, { - ...armed, - kind: 'spent', - resolved: false, - }); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + { ...armed, kind: 'spent', resolved: false }, + { state: 'approved' }, + NOW, + db + ); expect(calls).toEqual(['resolve:d1']); }); - test('defaults to the approved reason', async () => { + test('a superseded variant writes the superseded wording instead', async () => { + const db = tempDb(); const { gw, bodies } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, armed); - expect(bodies[0]).toContain('Approved, so this latch is spent'); - }); - - test('a duplicate reason writes the superseded wording instead', async () => { - const { gw, bodies } = gateway(); - await spendLatch(gw, 42, 'acme/web', 2317, armed, 'duplicate'); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + armed, + { state: 'superseded' }, + NOW, + db + ); expect(bodies[0]).toContain('Superseded by a newer latch on this MR'); expect(bodies[0]).not.toContain('Approved'); }); + + test('spending the canonical latch moves its row to spent', async () => { + const db = tempDb(); + putLatchRow(row({ phase: 'running', variant: 'running' }), db); + const { gw } = gateway(); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + armed, + { state: 'approved' }, + NOW, + db + ); + const r = readLatchRow(MR, db); + expect(r?.phase).toBe('spent'); + expect(r?.variant).toBe('approved'); + expect(r?.updatedAt).toBe(NOW); + }); + + test("spending a duplicate leaves the canonical latch's row alone", async () => { + const db = tempDb(); + putLatchRow(row({ discussionId: 'canon', rootNoteId: 7 }), db); + const { gw } = gateway(); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + armed, + { state: 'superseded' }, + NOW, + db + ); + const r = readLatchRow(MR, db); + expect(r?.phase).toBe('armed'); + expect(r?.variant).toBe('armed'); + }); + + // landFollowUp may already have moved the row; the note still needs writing. + test('a row already spent still gets the note rewritten and resolved', async () => { + const db = tempDb(); + putLatchRow(row({ phase: 'spent', variant: 'running' }), db); + const { gw, calls } = gateway(); + await spendLatch( + gw, + 42, + 'acme/web', + MR, + 2317, + armed, + { state: 'done-approved' }, + NOW, + db + ); + expect(calls).toEqual([ + 'upload:latch-2317-done-approved.gif', + 'updateNote:1', + 'resolve:d1', + ]); + expect(readLatchRow(MR, db)?.variant).toBe('done-approved'); + }); }); describe('spendAllLatches', () => { @@ -129,14 +375,26 @@ describe('spendAllLatches', () => { kind: 'armed', resolved: true, createdAt: '2026-09-01T10:00:00Z', - body: `\n\n${IMG}\n\nbody`, + body: `\n\n${OLD_IMG}\n\nbody`, }; - test('spends every latch given, deduped by discussion id', async () => { + test('spends every latch given, deduped by discussion id, one upload', async () => { + const db = tempDb(); const { gw, calls } = gateway(); const other: LatchRef = { ...armed, discussionId: 'd2', rootNoteId: 2 }; - await spendAllLatches(gw, 42, 'acme/web', 2317, [armed, other, armed]); + await spendAllLatches( + gw, + 42, + 'acme/web', + MR, + 2317, + [armed, other, armed], + { state: 'approved' }, + NOW, + db + ); expect(calls).toEqual([ + 'upload:latch-2317-approved.gif', 'updateNote:1', 'resolve:d1', 'updateNote:2', @@ -144,16 +402,20 @@ describe('spendAllLatches', () => { ]); }); - test('passes the reason through to every latch spent', async () => { + test('passes the variant through to every latch spent', async () => { + const db = tempDb(); const { gw, bodies } = gateway(); const other: LatchRef = { ...armed, discussionId: 'd2', rootNoteId: 2 }; await spendAllLatches( gw, 42, 'acme/web', + MR, 2317, [armed, other], - 'duplicate' + { state: 'superseded' }, + NOW, + db ); expect( bodies.every(b => b.includes('Superseded by a newer latch on this MR')) diff --git a/apps/board/src/__tests__/latch-review-step.test.ts b/apps/board/src/__tests__/latch-review-step.test.ts index 972dfe12a4..e739da079e 100644 --- a/apps/board/src/__tests__/latch-review-step.test.ts +++ b/apps/board/src/__tests__/latch-review-step.test.ts @@ -1,12 +1,20 @@ -import { describe, expect, test } from 'bun:test'; +import { afterAll, describe, expect, test } from 'bun:test'; import type { MRDetail } from '@mattstack/glance'; -import { armedLatchBody, spentLatchBody } from '../latch/markers.ts'; +import { + putLatchRow, + readLatchRow, + type LatchRow, +} from '../latch/latch-state.ts'; +import { armedLatchBody, latchBody, spentLatchBody } from '../latch/markers.ts'; import type { LatchGateway } from '../latch/post.ts'; import { applyReviewLatch, type ReviewLatchStep, } from '../latch/review-step.ts'; +import { removeTempDbs, tempDb } from './latch-temp-db.ts'; + +afterAll(removeTempDbs); const MR = 'https://gitlab.com/acme/web/-/merge_requests/2317'; const IMG = '![re-review latch](/uploads/ab12/latch-2317.png)'; @@ -38,8 +46,26 @@ const detail = (...d: ReturnType[]) => discussions: d, }) as unknown as MRDetail; +function latchRow(over: Partial = {}): LatchRow { + return { + mrUrl: MR, + discussionId: 'mine', + rootNoteId: 1, + phase: 'running', + wait: null, + launchAt: 1_000, + failures: 0, + stuck: false, + variant: 'running', + replyDue: null, + updatedAt: 1, + ...over, + }; +} + function step(over: Partial) { const calls: string[] = []; + const replies: string[] = []; const gateway: LatchGateway = { async uploadFile() { calls.push('upload'); @@ -58,13 +84,18 @@ function step(over: Partial) { async unresolveDiscussion(_p, _i, id) { calls.push(`unresolve:${id}`); }, - async createNote(_p, _i, _b, d) { + async createNote(_p, _i, body, d) { calls.push(`reply:${d}`); + replies.push(body); return { id: 9 }; }, }; const s: ReviewLatchStep = { outcome: 'comment', + arm: true, + reviewRunStartedAt: 2_000, + countNew: async () => 2, + now: 5_000, self: 'matt', approvedBy: [], detail: detail(), @@ -73,9 +104,10 @@ function step(over: Partial) { projectPath: 'acme/web', mrUrl: MR, iid: 2317, + db: tempDb(), ...over, }; - return { s, calls }; + return { s, calls, replies }; } describe('applyReviewLatch', () => { @@ -87,6 +119,20 @@ describe('applyReviewLatch', () => { expect(calls).toEqual(['upload', 'createDiscussion']); }); + test('a post records the latch as an armed row', async () => { + const db = tempDb(); + const { s } = step({ db }); + await applyReviewLatch(s); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'new', + rootNoteId: 1, + phase: 'armed', + variant: 'armed', + failures: 0, + stuck: false, + }); + }); + test('a comment posts nothing while this reviewer has an armed latch', async () => { const { s, calls } = step({ detail: detail(disc('mine', armedLatchBody(IMG), 'Matt')), @@ -122,6 +168,135 @@ describe('applyReviewLatch', () => { ), }); expect(await applyReviewLatch(s)).toBe('spent'); - expect(calls).toEqual(['updateNote:1', 'resolve:mine']); + expect(calls).toEqual(['upload', 'updateNote:1', 'resolve:mine']); + }); + + test('review step never posts a duplicate beside a queued latch', async () => { + const queued = latchBody('queued', IMG, 'queued'); + const { s, calls } = step({ detail: detail(disc('mine', queued, 'matt')) }); + expect(await applyReviewLatch(s)).toBe('none'); + expect(calls).toEqual([]); + }); + + // The daemon's discussion read can lag the row; the row alone proves a + // live latch. + test('a live row blocks the post when the read shows no latch yet', async () => { + const db = tempDb(); + putLatchRow(latchRow({ phase: 'queued', variant: 'queued-cooldown' }), db); + const { s, calls } = step({ db }); + expect(await applyReviewLatch(s)).toBe('none'); + expect(calls).toEqual([]); + }); + + test('a done review lands a running latch instead of posting', async () => { + const db = tempDb(); + putLatchRow(latchRow(), db); + const running = latchBody('running', IMG, 'running'); + const { s, calls, replies } = step({ + db, + detail: detail(disc('mine', running, 'matt')), + }); + expect(await applyReviewLatch(s)).toBe('landed'); + expect(calls).toEqual([ + 'upload', + 'updateNote:1', + 'unresolve:mine', + 'reply:mine', + ]); + expect(replies).toEqual(['Follow-up review done: 2 new comments.']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + variant: 'done-comments-2', + }); + }); + + test('countNew is asked from the latch launch stamp', async () => { + const db = tempDb(); + putLatchRow(latchRow({ launchAt: 1_234 }), db); + const asked: number[] = []; + const { s } = step({ + db, + countNew: async at => { + asked.push(at); + return 1; + }, + }); + await applyReviewLatch(s); + expect(asked).toEqual([1_234]); + }); + + test('an approve lands done-approved and spends the other copies approved', async () => { + const db = tempDb(); + putLatchRow(latchRow(), db); + const { s, calls, replies } = step({ + db, + outcome: 'approve', + detail: detail( + disc('mine', latchBody('running', IMG, 'running'), 'matt', 1), + disc('extra', armedLatchBody(IMG), 'matt', 2) + ), + }); + expect(await applyReviewLatch(s)).toBe('landed'); + expect(calls).toEqual([ + 'upload', + 'updateNote:1', + 'resolve:mine', + 'reply:mine', + 'upload', + 'updateNote:2', + 'resolve:extra', + ]); + expect(replies).toEqual(['Follow-up review done: approved.']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + variant: 'done-approved', + }); + }); + + test('an approve after the pass landed it keeps the done-approved banner', async () => { + const db = tempDb(); + putLatchRow(latchRow({ phase: 'spent', variant: 'done-approved' }), db); + const uploads: string[] = []; + const { s } = step({ + db, + outcome: 'approve', + detail: detail(disc('mine', latchBody('running', IMG, 'r'), 'matt', 1)), + }); + const upload = s.gateway.uploadFile; + s.gateway.uploadFile = async (p, f, b, ct) => { + uploads.push(f); + return upload(p, f, b, ct); + }; + expect(await applyReviewLatch(s)).toBe('spent'); + expect(uploads).toEqual(['latch-2317-done-approved.gif']); + expect(readLatchRow(MR, db)?.variant).toBe('done-approved'); + }); + + test('an abandoned review re-arms a running latch with no reply', async () => { + const db = tempDb(); + putLatchRow(latchRow(), db); + const { s, calls, replies } = step({ db, outcome: null }); + expect(await applyReviewLatch(s)).toBe('landed'); + expect(calls).toEqual(['upload', 'updateNote:1', 'unresolve:mine']); + expect(replies).toEqual([]); + }); + + test('a done review the board cannot vouch for never lands', async () => { + const db = tempDb(); + putLatchRow(latchRow(), db); + const { s, calls } = step({ db, reviewRunStartedAt: null }); + expect(await applyReviewLatch(s)).toBe('none'); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('with re-review off a comment still lands a running latch but never posts', async () => { + const db = tempDb(); + putLatchRow(latchRow(), db); + const landed = step({ db, arm: false }); + expect(await applyReviewLatch(landed.s)).toBe('landed'); + const fresh = step({ arm: false }); + expect(await applyReviewLatch(fresh.s)).toBe('none'); + expect(fresh.calls).toEqual([]); }); }); diff --git a/apps/board/src/__tests__/latch-state.test.ts b/apps/board/src/__tests__/latch-state.test.ts new file mode 100644 index 0000000000..0eca138854 --- /dev/null +++ b/apps/board/src/__tests__/latch-state.test.ts @@ -0,0 +1,188 @@ +import { mkdtempSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import { describe, expect, test } from 'bun:test'; + +import { + cachedUpload, + casLatch, + clearReplyDue, + putLatchRow, + readLatchRow, + readLatchRows, + rememberUpload, + type LatchRow, +} from '../latch/latch-state.ts'; +import { openStateDb } from '../state/db.ts'; + +const MR = 'https://gitlab.example/g/p/-/merge_requests/1'; + +function tempPath(): string { + return join(mkdtempSync(join(tmpdir(), 'board-latch-')), 'state.db'); +} + +function row(overrides: Partial = {}): LatchRow { + return { + mrUrl: MR, + discussionId: 'disc-1', + rootNoteId: 11, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: null, + replyDue: null, + updatedAt: 100, + ...overrides, + }; +} + +describe('latch state', () => { + test('put and read round-trip every field', () => { + const db = openStateDb(tempPath()); + const r = row({ + phase: 'queued', + wait: 'cooldown', + launchAt: 500, + failures: 2, + stuck: true, + variant: 'queued-cooldown', + replyDue: 'Follow-up review done.', + }); + putLatchRow(r, db); + expect(readLatchRow(MR, db)).toEqual(r); + expect(readLatchRows(db)).toEqual([r]); + expect(readLatchRow('https://gitlab.example/none', db)).toBeNull(); + }); + + test('casLatch moves only from a listed phase', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ phase: 'queued' }), db); + expect(casLatch(MR, ['armed'], { phase: 'running' }, 200, db)).toBe(false); + expect(readLatchRow(MR, db)!.phase).toBe('queued'); + expect(casLatch(MR, ['queued'], { phase: 'running' }, 200, db)).toBe(true); + const after = readLatchRow(MR, db)!; + expect(after.phase).toBe('running'); + expect(after.updatedAt).toBe(200); + }); + + test('casLatch guarded by another discussion does not move the row', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ phase: 'armed', discussionId: 'disc-1' }), db); + const patch = { phase: 'spent' as const }; + expect( + casLatch(MR, ['armed'], patch, 200, db, { discussionId: 'disc-2' }) + ).toBe(false); + expect(readLatchRow(MR, db)!.phase).toBe('armed'); + expect( + casLatch(MR, ['armed'], patch, 200, db, { discussionId: 'disc-1' }) + ).toBe(true); + expect(readLatchRow(MR, db)!.phase).toBe('spent'); + }); + + test('casLatch clears a field patched to null and ignores a missing row', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ phase: 'error', wait: 'budget', launchAt: 5 }), db); + const patch = { phase: 'armed' as const, wait: null, launchAt: null }; + expect(casLatch(MR, ['error'], patch, 300, db)).toBe(true); + const after = readLatchRow(MR, db)!; + expect(after.wait).toBeNull(); + expect(after.launchAt).toBeNull(); + expect( + casLatch( + 'https://gitlab.example/none', + ['armed'], + { phase: 'spent' }, + 1, + db + ) + ).toBe(false); + }); + + test('casLatch ignores undefined patch values', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ phase: 'queued', wait: 'budget', launchAt: 9 }), db); + expect( + casLatch(MR, ['queued'], { phase: 'running', wait: undefined }, 200, db) + ).toBe(true); + const after = readLatchRow(MR, db)!; + expect(after.phase).toBe('running'); + expect(after.wait).toBe('budget'); + expect(after.launchAt).toBe(9); + }); + + test('two cas racing from the same phase, only one wins', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ phase: 'queued' }), db); + const first = casLatch(MR, ['queued'], { phase: 'running' }, 200, db); + const second = casLatch(MR, ['queued'], { phase: 'error' }, 201, db); + expect([first, second]).toEqual([true, false]); + expect(readLatchRow(MR, db)!.phase).toBe('running'); + }); + + test('upload cache round-trips per variant', () => { + const db = openStateDb(tempPath()); + expect(cachedUpload(MR, 'armed', db)).toBeNull(); + rememberUpload(MR, 'armed', '![a](/uploads/a.png)', db); + rememberUpload(MR, 'queued', '![q](/uploads/q.png)', db); + expect(cachedUpload(MR, 'armed', db)).toBe('![a](/uploads/a.png)'); + expect(cachedUpload(MR, 'queued', db)).toBe('![q](/uploads/q.png)'); + rememberUpload(MR, 'armed', '![b](/uploads/b.png)', db); + expect(cachedUpload(MR, 'armed', db)).toBe('![b](/uploads/b.png)'); + }); + + test('migration takes a v6 db to v7', () => { + const path = tempPath(); + const first = openStateDb(path); + first.run('DROP TABLE latch_state'); + first.run('DROP TABLE latch_uploads'); + first.run('PRAGMA user_version = 6'); + first.close(); + const db = openStateDb(path); + expect( + (db.query('PRAGMA user_version').get() as { user_version: number }) + .user_version + ).toBe(7); + const tables = ( + db.query("SELECT name FROM sqlite_master WHERE type='table'").all() as { + name: string; + }[] + ).map(t => t.name); + expect(tables).toContain('latch_state'); + expect(tables).toContain('latch_uploads'); + const cols = ( + db.query('PRAGMA table_info(latch_state)').all() as { name: string }[] + ).map(c => c.name); + expect(cols).toContain('reply_due'); + }); + + test('clearReplyDue clears only the reply still owed', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ replyDue: 'Follow-up review done.' }), db); + expect(clearReplyDue(MR, 'Other reply.', db)).toBe(false); + expect(readLatchRow(MR, db)!.replyDue).toBe('Follow-up review done.'); + expect(clearReplyDue(MR, 'Follow-up review done.', db)).toBe(true); + expect(readLatchRow(MR, db)!.replyDue).toBeNull(); + }); + + test('clearReplyDue still clears after a re-point moved the row to another copy', () => { + const db = openStateDb(tempPath()); + putLatchRow(row({ replyDue: 'Follow-up review done.' }), db); + expect( + casLatch( + MR, + ['armed'], + { discussionId: 'disc-2', rootNoteId: 12 }, + 200, + db, + { discussionId: 'disc-1' } + ) + ).toBe(true); + expect(clearReplyDue(MR, 'Follow-up review done.', db)).toBe(true); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'disc-2', + replyDue: null, + }); + }); +}); diff --git a/apps/board/src/__tests__/latch-temp-db.ts b/apps/board/src/__tests__/latch-temp-db.ts new file mode 100644 index 0000000000..04ad2374f3 --- /dev/null +++ b/apps/board/src/__tests__/latch-temp-db.ts @@ -0,0 +1,25 @@ +import { mkdtempSync, rmSync } from 'fs'; +import { tmpdir } from 'os'; +import { join } from 'path'; +import type { Database } from 'bun:sqlite'; + +import { openStateDb } from '../state/db.ts'; + +// Bun shares this module across test files, so a hook registered here would +// fire for the first importer only: each file calls afterAll(removeTempDbs). +const opened: Array<{ db: Database; dir: string }> = []; + +/** A throwaway state db for latch tests. */ +export function tempDb(): Database { + const dir = mkdtempSync(join(tmpdir(), 'board-latch-test-')); + const db = openStateDb(join(dir, 'state.db')); + opened.push({ db, dir }); + return db; +} + +export function removeTempDbs(): void { + for (const { db, dir } of opened.splice(0)) { + db.close(); + rmSync(dir, { recursive: true, force: true }); + } +} diff --git a/apps/board/src/__tests__/latch-variants.test.ts b/apps/board/src/__tests__/latch-variants.test.ts new file mode 100644 index 0000000000..db853795a7 --- /dev/null +++ b/apps/board/src/__tests__/latch-variants.test.ts @@ -0,0 +1,261 @@ +import { describe, expect, test } from 'bun:test'; + +import { LAYOUT, STRIPS } from '../../assets/latch/index.ts'; +import { + allVariantKeys, + copyFor, + DOT_GAP_PX, + DOT_PX, + variantKey, + variantOfKey, + type BannerVariant, +} from '../latch/variants.ts'; + +const SUB = (v: BannerVariant) => copyFor(v).sub; + +describe('variant keys', () => { + test('every key is unique and round-trips through variantOfKey', () => { + const keys = allVariantKeys(); + expect(new Set(keys).size).toBe(keys.length); + for (const key of keys) { + const v = variantOfKey(key); + expect(v).not.toBeNull(); + expect(variantKey(v!)).toBe(key); + } + }); + + test('covers every queued and error wait and every done-comments count', () => { + const keys = allVariantKeys(); + for (const w of ['next-sweep', 'cooldown', 'budget', 'review-in-flight']) { + expect(keys).toContain(`queued-${w}`); + } + for (const w of ['next-sweep', 'cooldown', 'budget']) { + expect(keys).toContain(`error-retrying-${w}`); + } + expect(keys).not.toContain('error-retrying-review-in-flight'); + for (let n = 1; n <= 20; n++) expect(keys).toContain(`done-comments-${n}`); + expect(keys).toContain('done-comments-20plus'); + expect(keys).toContain('done-comments-none'); + for (const k of [ + 'armed', + 'running', + 'error-stuck', + 'done-approved', + 'approved', + 'superseded', + ]) { + expect(keys).toContain(k); + } + }); + + test('counts map to their keys', () => { + expect(variantKey({ state: 'done-comments', count: 3 })).toBe( + 'done-comments-3' + ); + expect(variantKey({ state: 'done-comments', count: 21 })).toBe( + 'done-comments-20plus' + ); + expect(variantKey({ state: 'done-comments', count: 0 })).toBe( + 'done-comments-none' + ); + expect(variantKey({ state: 'done-comments', count: null })).toBe( + 'done-comments-none' + ); + expect(variantKey({ state: 'queued', wait: 'cooldown' })).toBe( + 'queued-cooldown' + ); + }); + + test('fractional counts floor and non-finite counts read as none', () => { + expect(variantKey({ state: 'done-comments', count: 2.5 })).toBe( + 'done-comments-2' + ); + expect(variantKey({ state: 'done-comments', count: NaN })).toBe( + 'done-comments-none' + ); + expect(variantKey({ state: 'done-comments', count: Infinity })).toBe( + 'done-comments-none' + ); + expect(SUB({ state: 'done-comments', count: 2.5 })).toBe( + '2 new comments. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: NaN })).toBe( + 'Review posted. Resolve when ready' + ); + }); + + test('a null wait reads as the next sweep', () => { + expect(variantKey({ state: 'queued', wait: null })).toBe( + 'queued-next-sweep' + ); + expect(variantKey({ state: 'error-retrying', wait: null })).toBe( + 'error-retrying-next-sweep' + ); + }); + + test('dot pitch is shared in 2x px', () => { + expect(DOT_PX).toBe(8); + expect(DOT_GAP_PX).toBe(8); + }); + + test('unknown keys have no variant', () => { + expect(variantOfKey('queued-sometime')).toBeNull(); + expect(variantOfKey('done-comments-21')).toBeNull(); + expect(variantOfKey('nonsense')).toBeNull(); + }); +}); + +describe('copy', () => { + test('titles and fixed subtitles match the spec', () => { + const rows: [BannerVariant, string, string, string][] = [ + [ + { state: 'armed' }, + 'Ready for another pass?', + 'Resolve this thread to ask', + '#f08fb0', + ], + [ + { state: 'running' }, + 'Follow-up review running', + 'Results post here when done', + '#7fbfe8', + ], + [ + { state: 'error-stuck' }, + 'Follow-up review stuck', + 'Reviewer notified', + '#f2917e', + ], + [ + { state: 'done-approved' }, + 'Follow-up review done', + 'Approved. Nothing more to do', + '#86cfa0', + ], + [{ state: 'approved' }, 'Approved', 'Nothing more to do', '#86cfa0'], + [ + { state: 'superseded' }, + 'Superseded', + 'A newer latch is live', + '#8e88a0', + ], + ]; + for (const [v, title, sub, accent] of rows) { + expect(copyFor(v)).toMatchObject({ title, sub, accent }); + } + expect(copyFor({ state: 'queued', wait: 'next-sweep' })).toMatchObject({ + title: 'Follow-up review queued', + accent: '#e6b860', + }); + expect( + copyFor({ state: 'error-retrying', wait: 'next-sweep' }) + ).toMatchObject({ + title: 'Follow-up review hit a snag', + accent: '#f2917e', + }); + expect(copyFor({ state: 'done-comments', count: 2 })).toMatchObject({ + title: 'Follow-up review done', + accent: '#b9a0f2', + }); + }); + + test('queued subtitles name the wait', () => { + expect(SUB({ state: 'queued', wait: 'next-sweep' })).toBe( + 'Starts on the next sweep' + ); + expect(SUB({ state: 'queued', wait: 'cooldown' })).toBe( + 'Waiting out the cooldown' + ); + expect(SUB({ state: 'queued', wait: 'budget' })).toBe( + 'Daily limit hit; starts tomorrow' + ); + expect(SUB({ state: 'queued', wait: 'review-in-flight' })).toBe( + 'Waiting for the running review' + ); + }); + + test('error-retrying subtitles name the wait', () => { + expect(SUB({ state: 'error-retrying', wait: 'next-sweep' })).toBe( + 'Retrying on the next sweep' + ); + expect(SUB({ state: 'error-retrying', wait: 'cooldown' })).toBe( + 'Retrying after the cooldown' + ); + expect(SUB({ state: 'error-retrying', wait: 'budget' })).toBe( + 'Daily limit hit; retrying tomorrow' + ); + }); + + test('done-comments subtitles count what landed', () => { + expect(SUB({ state: 'done-comments', count: 1 })).toBe( + '1 new comment. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: 2 })).toBe( + '2 new comments. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: 20 })).toBe( + '20 new comments. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: 21 })).toBe( + '20+ new comments. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: 0 })).toBe( + 'Review posted. Resolve when ready' + ); + expect(SUB({ state: 'done-comments', count: null })).toBe( + 'Review posted. Resolve when ready' + ); + }); + + test('sentences under the image', () => { + expect(copyFor({ state: 'armed' }).sentence).toBe( + "**Addressed everything?** Resolve this thread and I'll take another pass over the MR.\n\nLeave it open while there's still work in flight." + ); + expect(copyFor({ state: 'approved' }).sentence).toBe( + 'Approved, so this latch is spent. Nothing further to do here.' + ); + expect(copyFor({ state: 'superseded' }).sentence).toBe( + 'Superseded by a newer latch on this MR; nothing to do here.' + ); + expect(copyFor({ state: 'queued', wait: 'budget' }).sentence).toBe( + "Follow-up review requested. I'll start it as soon as I can." + ); + expect(copyFor({ state: 'running' }).sentence).toBe( + "Follow-up review in progress. I'll reply here when it's done." + ); + expect( + copyFor({ state: 'error-retrying', wait: 'cooldown' }).sentence + ).toBe("The follow-up review didn't finish. I'll try again."); + expect(copyFor({ state: 'error-stuck' }).sentence).toBe( + "The follow-up review didn't finish after 3 tries. The reviewer has been told." + ); + expect(copyFor({ state: 'done-comments', count: 4 }).sentence).toBe( + "Follow-up review done. Resolve this thread again when you've addressed the new comments." + ); + expect(copyFor({ state: 'done-approved' }).sentence).toBe( + 'Follow-up review done and approved, so this latch is spent.' + ); + }); + + test('indicator follows the state', () => { + for (const key of allVariantKeys()) { + const v = variantOfKey(key)!; + const expected = + v.state === 'queued' || v.state === 'error-retrying' + ? 'dots' + : v.state === 'running' + ? 'ring' + : 'none'; + expect(copyFor(v).indicator).toBe(expected); + } + }); +}); + +describe('committed strips', () => { + test('every variant key has an embedded strip', () => { + for (const key of allVariantKeys()) { + expect(STRIPS[key]).toBeString(); + expect(LAYOUT[key as keyof typeof LAYOUT]).toBeDefined(); + } + }); +}); diff --git a/apps/board/src/__tests__/state-db.test.ts b/apps/board/src/__tests__/state-db.test.ts index 12b3adf77e..860c98161a 100644 --- a/apps/board/src/__tests__/state-db.test.ts +++ b/apps/board/src/__tests__/state-db.test.ts @@ -132,7 +132,7 @@ describe('state db', () => { expect(again.query('SELECT COUNT(*) AS n FROM agent_states').get()).toEqual( { n: 1 } ); - expect(SCHEMA_VERSION).toBe(6); + expect(SCHEMA_VERSION).toBe(7); }); test('v5 adds respond_rounds, and a v4 db upgrades in place with its rows intact', () => { diff --git a/apps/board/src/__tests__/triage-latch.test.ts b/apps/board/src/__tests__/triage-latch.test.ts index a1b385405e..71debd88a7 100644 --- a/apps/board/src/__tests__/triage-latch.test.ts +++ b/apps/board/src/__tests__/triage-latch.test.ts @@ -1,16 +1,33 @@ -import { describe, expect, test } from 'bun:test'; +import { afterAll, describe, expect, test } from 'bun:test'; import type { MRDetail } from '@mattstack/glance'; -import { armedLatchBody, spentLatchBody } from '../latch/markers.ts'; +import { + casLatch as casLatchIn, + putLatchRow, + readLatchRow, + type LatchRow, +} from '../latch/latch-state.ts'; +import { armedLatchBody, latchBody, spentLatchBody } from '../latch/markers.ts'; import type { LatchGateway } from '../latch/post.ts'; +import { copyFor } from '../latch/variants.ts'; import type { ReviewState } from '../review-state.ts'; +import type { AuditEntry } from '../triage/audit.ts'; import { parseTriageBlock } from '../triage/config.ts'; import { + LATCH_MAX_FAILURES, + LATCH_POST_GRACE_MS, + LATCH_REPLY_GIVE_UP_MS, + latchInScope, runLatchPass, + runStamp, + waitReasonOf, type LatchMrFacts, type LatchPassDeps, } from '../triage/latch.ts'; import { emptyMrMemory, type DispatchMemory } from '../triage/memory.ts'; +import { removeTempDbs, tempDb } from './latch-temp-db.ts'; + +afterAll(removeTempDbs); const NOW = 1_000_000_000; const MR = 'https://gitlab.com/acme/web/-/merge_requests/2317'; @@ -38,6 +55,33 @@ const commented: ReviewState = { updatedAt: 0, }; +const noOutcome: ReviewState = { ...commented, outcome: undefined }; +const RUNNING = ''; +const QUEUED = ''; +const ARMED = ''; +const SPENT = ''; +const ERROR = ''; +const queuedBody = () => latchBody('queued', IMG, 'queued'); +const runningBody = () => latchBody('running', IMG, 'running'); +const errorBody = () => latchBody('error', IMG, 'error'); + +function row(over: Partial = {}): LatchRow { + return { + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: 1, + ...over, + }; +} + function disc( id: string, body: string, @@ -75,11 +119,13 @@ function harness( over: Partial & { detail?: MRDetail | null } = {} ) { const calls: string[] = []; + const uploads: string[] = []; const launches: string[] = []; const noteBodies = new Map(); const gateway: LatchGateway = { - async uploadFile() { + async uploadFile(_p, filename) { calls.push('upload'); + uploads.push(filename); return { alt: '', url: '', full_path: '', markdown: IMG }; }, async createDiscussion() { @@ -96,15 +142,20 @@ function harness( async unresolveDiscussion(_p, _i, id) { calls.push(`unresolve:${id}`); }, - async createNote(_p, _i, _b, d) { + async createNote(_p, _i, body, d) { calls.push(`reply:${d}`); + replies.push(body); return { id: 9 }; }, }; + const replies: string[] = []; + const audits: AuditEntry[] = []; const memory: DispatchMemory = { identity: null, mrs: {} }; const resurrects: string[] = []; const drops: string[] = []; const notifies: Array<{ title: string; message: string; mrUrl: string }> = []; + const stuckNotices: Array<{ title: string; message: string; mrUrl: string }> = + []; const deps: LatchPassDeps = { readReviewStates: () => new Map([[MR, commented]]), readPrunedReviewStates: () => new Map(), @@ -127,22 +178,44 @@ function harness( self: 'matt', cfg, reReview: { enabled: true }, - appendAudit: () => {}, + appendAudit: entry => { + audits.push(entry); + }, notify: async (title, message, mrUrl) => { notifies.push({ title, message, mrUrl }); }, + notifyStuck: async (title, message, mrUrl) => { + stuckNotices.push({ title, message, mrUrl }); + }, now: () => NOW, + db: tempDb(), ...over, }; return { deps, calls, + uploads, launches, memory, noteBodies, resurrects, drops, notifies, + stuckNotices, + replies, + audits, + }; +} + +function failNextReply(gw: LatchGateway): void { + const create = gw.createNote; + let broken = true; + gw.createNote = async (...args) => { + if (broken) { + broken = false; + throw new Error('gitlab 500'); + } + return create(...args); }; } @@ -154,6 +227,26 @@ describe('step 0: no latch', () => { expect(calls).toEqual(['upload', 'createDiscussion']); }); + // A second writer must see the post before the daemon's discussion store does. + test('records the posted latch as an armed row', async () => { + const db = tempDb(); + const { deps } = harness({ detail: detail(), db }); + await runLatchPass(deps); + expect(readLatchRow(MR, db)).toEqual({ + mrUrl: MR, + discussionId: 'new', + rootNoteId: 1, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: NOW, + }); + }); + test('posts nothing on an approve-outcome state', async () => { const approved: ReviewState = { ...commented, outcome: 'approve' }; const { deps, calls } = harness({ @@ -262,7 +355,41 @@ describe('step 2: armed and unresolved', () => { readReviewStates: () => new Map([[MR, approved]]), }); expect((await runLatchPass(deps)).spent).toBe(1); - expect(calls).toEqual(['updateNote:1', 'resolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1', 'resolve:d1']); + }); + + test("the spend stamps the row with the pass's clock", async () => { + const db = tempDb(); + putLatchRow( + { + mrUrl: MR, + discussionId: 'd1', + rootNoteId: 1, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: 1, + }, + db + ); + const approved: ReviewState = { ...commented, outcome: 'approve' }; + const { deps } = harness({ + db, + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', false) + ), + readReviewStates: () => new Map([[MR, approved]]), + }); + await runLatchPass(deps); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + variant: 'approved', + updatedAt: NOW, + }); }); // Step 2 must spend every duplicate, not just the canonical latch. @@ -296,12 +423,15 @@ describe('the re-review switch is board.reReview, not board.triage', () => { expect(r).toEqual({ posted: 0, dispatched: 0, - rejected: 0, + queued: 0, spent: 0, repaired: 0, resurrected: 0, skipped: 0, failed: 0, + landed: 0, + errored: 0, + stuck: 0, }); expect(calls).toEqual([]); expect(launches).toEqual([]); @@ -320,20 +450,29 @@ describe('the re-review switch is board.reReview, not board.triage', () => { }); expect((await runLatchPass(deps)).dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toEqual(['reply:d1', 'unresolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1']); }); }); describe('step 3: armed and resolved', () => { - test('dispatches, replies, and unresolves to rearm', async () => { - const { deps, calls, launches, memory } = harness({ + test('dispatches and shows running on the resolved latch, with no reply', async () => { + const db = tempDb(); + const { deps, calls, launches, memory, noteBodies } = harness({ + db, detail: detail( disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) ), }); expect((await runLatchPass(deps)).dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toEqual(['reply:d1', 'unresolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW, + wait: null, + variant: 'running', + }); expect(memory.mrs[MR]?.attemptsToday).toBe(1); expect(memory.mrs[MR]?.lastDispatchAt).toBe(NOW); }); @@ -347,7 +486,7 @@ describe('step 3: armed and resolved', () => { }); expect((await runLatchPass(deps)).spent).toBe(1); expect(launches).toEqual([]); - expect(calls).toEqual(['updateNote:1', 'resolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1', 'resolve:d1']); }); // Spending only canon and the resolved carriers would strand an @@ -367,30 +506,10 @@ describe('step 3: armed and resolved', () => { expect(calls).toContain('resolve:extra'); }); - test('a refusal replies with the reason and still unresolves', async () => { - const memory: DispatchMemory = { - identity: null, - mrs: { - [MR]: { ...emptyMrMemory('1970-01-12'), lastDispatchAt: NOW - 60_000 }, - }, - }; - const { deps, calls, launches } = harness({ - detail: detail( - disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) - ), - memory, - }); - expect((await runLatchPass(deps)).rejected).toBe(1); - expect(launches).toEqual([]); - expect(calls).toEqual(['reply:d1', 'unresolve:d1']); - expect(memory.mrs[MR]?.attemptsToday).toBe(0); - expect(memory.mrs[MR]?.lastDispatchAt).toBe(NOW - 60_000); - }); - // A GitLab write failing after a successful launch must still charge the // attempt, or the next tick reads the same resolved latch as a fresh // request and dispatches again every tick for as long as the write fails. - test('a successful launch with a failing createNote still charges the attempt', async () => { + test('a successful launch with a failing note rewrite still charges the attempt', async () => { const { deps, launches, memory } = harness({ detail: detail( disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) @@ -402,11 +521,13 @@ describe('step 3: armed and resolved', () => { async createDiscussion() { return { id: 'new', notes: [{ id: 1 }] }; }, - async updateNote() {}, + async updateNote() { + throw new Error('gitlab 500'); + }, async resolveDiscussion() {}, async unresolveDiscussion() {}, async createNote() { - throw new Error('gitlab 500'); + return { id: 9 }; }, }, }); @@ -418,18 +539,21 @@ describe('step 3: armed and resolved', () => { expect(memory.mrs[MR]?.lastDispatchAt).toBe(NOW); }); - test('a failed launch replies, consumes the request, and counts a rejection', async () => { - const { deps, calls, launches } = harness({ + test('a failed launch never replies and supersedes the extra copy', async () => { + const db = tempDb(); + const { deps, calls, replies } = harness({ + db, detail: detail( disc('canon', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true), disc('extra', armedLatchBody(IMG), '2026-08-01T10:00:00Z', true) ), launchReReview: async () => ({ kind: 'error', message: 'boom' }), }); - expect((await runLatchPass(deps)).rejected).toBe(1); - expect(launches).toEqual([]); - expect(calls).toContain('reply:canon'); + expect((await runLatchPass(deps)).errored).toBe(1); + expect(replies).toEqual([]); + expect(calls.some(c => c.startsWith('reply:'))).toBe(false); expect(calls).toContain('resolve:extra'); + expect(readLatchRow(MR, db)?.phase).toBe('error'); }); test('a dispatch notifies in plain words, pointing at the MR', async () => { @@ -447,29 +571,6 @@ describe('step 3: armed and resolved', () => { }, ]); }); - - test('a refusal notifies the plain reason, never the code', async () => { - const memory: DispatchMemory = { - identity: null, - mrs: { - [MR]: { ...emptyMrMemory('1970-01-12'), attemptsToday: 3 }, - }, - }; - const { deps, notifies } = harness({ - detail: detail( - disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) - ), - memory, - }); - await runLatchPass(deps); - expect(notifies).toEqual([ - { - title: 'Follow-up review skipped on !2317', - message: "Hit today's limit of 3 automatic runs", - mrUrl: MR, - }, - ]); - }); }); describe('idempotence across ticks', () => { @@ -510,16 +611,7 @@ describe('dedupe', () => { }); expect((await runLatchPass(deps)).dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toEqual( - [ - 'reply:fresh', - 'unresolve:fresh', - 'updateNote:1', - 'resolve:relic', - ].filter( - c => !c.startsWith('updateNote') && !c.startsWith('resolve:relic') - ) - ); + expect(calls).toEqual(['upload', 'updateNote:1']); }); // Resolving the duplicate is still asking, and the request must be consumed @@ -533,15 +625,15 @@ describe('dedupe', () => { }); expect((await runLatchPass(deps)).dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toContain('reply:canon'); + expect(calls).toContain('resolve:canon'); expect(calls).toContain('updateNote:1'); expect(calls).toContain('resolve:extra'); + expect(calls.some(c => c.startsWith('reply:'))).toBe(false); }); - // The request bit must be consumed on the refusal path too, not just on - // dispatch. Left in the extra, it re-fires on every re-entry into scope: - // one unrequested dispatch per cooldown expiry, forever. - test('a refusal consumes a resolved extra, not just the canonical latch', async () => { + // The request bit must be consumed when the request queues too, not just + // on dispatch. Left in the extra, it re-fires once the latch is armed again. + test('queueing consumes a resolved extra, not just the canonical latch', async () => { const memory: DispatchMemory = { identity: null, mrs: { @@ -555,10 +647,9 @@ describe('dedupe', () => { ), memory, }); - expect((await runLatchPass(deps)).rejected).toBe(1); + expect((await runLatchPass(deps)).queued).toBe(1); expect(launches).toEqual([]); - expect(calls).toContain('reply:canon'); - expect(calls).toContain('unresolve:canon'); + expect(calls).not.toContain('unresolve:canon'); expect(calls).toContain('resolve:extra'); }); @@ -621,7 +712,7 @@ describe('tombstone resurrection', () => { expect(result.resurrected).toBe(1); expect(result.dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toEqual(['reply:d1', 'unresolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1']); }); test('an armed unresolved latch revives the tombstone and waits', async () => { @@ -698,7 +789,7 @@ describe('tombstone resurrection', () => { const result = await runLatchPass(deps); expect(resurrects).toEqual([MR]); expect(result.spent).toBe(1); - expect(calls).toEqual(['updateNote:1', 'resolve:d1']); + expect(calls).toEqual(['upload', 'updateNote:1', 'resolve:d1']); }); test('an unreadable detail leaves the tombstone in place for the next tick', async () => { @@ -776,7 +867,7 @@ describe('one latch per reviewer', () => { }); expect((await runLatchPass(deps)).dispatched).toBe(1); expect(launches).toEqual([MR]); - expect(calls).toEqual(['reply:mine', 'unresolve:mine']); + expect(calls).toEqual(['upload', 'updateNote:1']); }); test("approving in GitLab spends this reviewer's armed latch and no other", async () => { @@ -788,7 +879,7 @@ describe('one latch per reviewer', () => { fetchLatchMrs: async () => [{ ...facts, approvedBySelf: true }], }); expect((await runLatchPass(deps)).spent).toBe(1); - expect(calls).toEqual(['updateNote:1', 'resolve:mine']); + expect(calls).toEqual(['upload', 'updateNote:1', 'resolve:mine']); }); test('posts nothing for a reviewer who already approved in GitLab', async () => { @@ -800,3 +891,1823 @@ describe('one latch per reviewer', () => { expect(calls).toEqual([]); }); }); + +describe('the queue', () => { + const cooling = (): DispatchMemory => ({ + identity: null, + mrs: { + [MR]: { ...emptyMrMemory('1970-01-12'), lastDispatchAt: NOW - 60_000 }, + }, + }); + const queuedRow = (over: Partial = {}) => + row({ + phase: 'queued', + wait: 'cooldown', + variant: 'queued-cooldown', + ...over, + }); + + test('cooldown queues instead of replying Not yet', async () => { + const db = tempDb(); + const { deps, calls, uploads, noteBodies, notifies, launches, audits } = + harness({ + db, + memory: cooling(), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).queued).toBe(1); + expect(launches).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(uploads).toEqual(['latch-2317-queued-cooldown.gif']); + expect(noteBodies.get(1)).toStartWith(QUEUED); + expect(notifies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'cooldown', + variant: 'queued-cooldown', + }); + expect(audits.map(a => a.action)).toContain('queued'); + }); + + test('queued dispatches when the block clears', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, calls, launches, noteBodies, memory, audits } = harness({ + db, + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(calls.some(c => c.startsWith('reply:'))).toBe(false); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(memory.mrs[MR]?.attemptsToday).toBe(1); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW, + wait: null, + }); + expect(audits.map(a => a.action)).toContain('dispatched'); + }); + + test('wait reason change swaps the strip', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, uploads, launches, noteBodies, calls } = harness({ + db, + memory: { + identity: null, + mrs: { + [MR]: { + ...emptyMrMemory('1970-01-12'), + attemptsToday: 3, + lastDispatchAt: NOW - 60_000, + }, + }, + }, + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-queued-budget.gif']); + expect(noteBodies.get(1)).toStartWith(QUEUED); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'budget', + variant: 'queued-budget', + }); + }); + + test('an unchanged wait touches nothing', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, calls } = harness({ + db, + memory: cooling(), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.updatedAt).toBe(1); + }); + + test('a hand-launched review satisfies a queued request', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: NOW - 2_000 }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + startedAt: 5, + runStartedAt: NOW - 1_000, + }; + const { deps, launches, noteBodies, memory } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(memory.mrs[MR]).toBeUndefined(); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW - 1_000, + }); + }); + + // The run began before the author resolved, so it cannot have seen the + // fixes the request is about. + test('a review already running when the request came in is not adopted', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: NOW - 2_000 }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 3_000, + }; + const { deps, launches, uploads, memory } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).queued).toBe(1); + expect(launches).toEqual([]); + expect(memory.mrs[MR]?.attemptsToday ?? 0).toBe(0); + expect(uploads).toEqual(['latch-2317-queued-review-in-flight.gif']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'review-in-flight', + launchAt: NOW - 2_000, + }); + }); + + test('a queued row with no request stamp never adopts a run in flight', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: null }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 1_000, + }; + const { deps, launches } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'review-in-flight', + }); + }); + + test('a review the board launched since the snapshot is adopted, not launched again', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: NOW - 2_000 }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 500, + }; + let reads = 0; + const { deps, launches, memory, noteBodies, audits } = harness({ + db, + readReviewStates: () => + new Map([[MR, reads++ === 0 ? commented : reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(memory.mrs[MR]?.attemptsToday ?? 0).toBe(0); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW - 500, + }); + expect(audits).toContainEqual( + expect.objectContaining({ + action: 'dispatched', + outcome: 'review already running', + }) + ); + }); + + test('an armed request finding a run launched since the snapshot adopts it', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW - LATCH_POST_GRACE_MS }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW, + }; + let reads = 0; + const { deps, launches, memory } = harness({ + db, + readReviewStates: () => + new Map([[MR, reads++ === 0 ? commented : reviewing]]), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(memory.mrs[MR]?.attemptsToday ?? 0).toBe(0); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW, + }); + }); + + test('a run that began before the request, found at launch time, keeps the request waiting', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: NOW - 2_000 }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 3_000, + }; + let reads = 0; + const { deps, launches, uploads } = harness({ + db, + readReviewStates: () => + new Map([[MR, reads++ === 0 ? commented : reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-queued-review-in-flight.gif']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'review-in-flight', + }); + }); + + test('a running row whose note never showed running is healed', async () => { + const db = tempDb(); + putLatchRow( + row({ phase: 'running', launchAt: NOW - 1_000, variant: 'armed' }), + db + ); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 1_000, + }; + const { deps, calls, launches, noteBodies, audits } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).repaired).toBe(1); + expect(launches).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + variant: 'running', + }); + expect(audits.map(a => a.action)).toContain('repaired'); + + await runLatchPass(deps); + expect(calls).toHaveLength(2); + }); + + test('stale note never re-requests a running latch', async () => { + const db = tempDb(); + putLatchRow( + row({ phase: 'running', launchAt: NOW - 1_000, variant: 'running' }), + db + ); + const { deps, calls, launches } = harness({ + db, + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('a running row whose lane is gone is skipped', async () => { + const db = tempDb(); + putLatchRow( + row({ phase: 'running', launchAt: NOW - 1_000, variant: 'running' }), + db + ); + const { deps, calls, launches } = harness({ + db, + readReviewStates: () => new Map(), + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).skipped).toBe(1); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + }); + + test('author reopening a queued latch withdraws it', async () => { + const db = tempDb(); + putLatchRow(queuedRow({ launchAt: NOW - 5_000 }), db); + const { deps, calls, launches, noteBodies, audits } = harness({ + db, + memory: cooling(), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', false)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(noteBodies.get(1)).toStartWith(ARMED + '\n'); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + wait: null, + launchAt: null, + variant: 'armed', + }); + expect(audits.map(a => a.action)).toContain('withdrawn'); + }); + + test('a stale armed unresolved read does not withdraw a queued latch', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, calls, launches } = harness({ + db, + memory: cooling(), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', false) + ), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('queued'); + }); + + test('crash shape is repaired after the grace window', async () => { + const db = tempDb(); + putLatchRow( + row({ variant: 'done-comments-3', updatedAt: NOW - LATCH_POST_GRACE_MS }), + db + ); + const { deps, calls, uploads, launches, noteBodies, audits } = harness({ + db, + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).repaired).toBe(1); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-done-comments-3.gif']); + expect(calls).toEqual(['upload', 'updateNote:1', 'unresolve:d1']); + expect(noteBodies.get(1)).toStartWith(ARMED + '\n'); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + variant: 'done-comments-3', + }); + expect(audits.map(a => a.action)).toContain('repaired'); + }); + + test('no repair inside the grace window', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const { deps, calls, launches } = harness({ + db, + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + }); + + test('queued row re-decides past an error lane', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const failed: ReviewState = { + ...commented, + status: 'error', + outcome: undefined, + }; + const { deps, launches, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('a queued row whose lane is gone re-decides as a commented review', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, launches } = harness({ + db, + readReviewStates: () => new Map(), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('pre-change latch with no row is adopted', async () => { + const db = tempDb(); + const { deps, calls, audits } = harness({ + db, + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', false) + ), + }); + await runLatchPass(deps); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'd1', + rootNoteId: 1, + phase: 'armed', + updatedAt: NOW, + }); + expect(audits.map(a => a.action)).toContain('adopted'); + }); + + test('a spent note with no row is adopted as spent', async () => { + const db = tempDb(); + const { deps } = harness({ + db, + detail: detail( + disc('d1', spentLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + await runLatchPass(deps); + expect(readLatchRow(MR, db)?.phase).toBe('spent'); + }); + + // A post race can leave the row on an older copy while the newest copy is + // the one the author sees and acts on. + test('a row on an older copy is re-pointed to the canonical latch', async () => { + const db = tempDb(); + putLatchRow(row({ discussionId: 'old', updatedAt: NOW }), db); + const { deps, launches, calls, audits } = harness({ + db, + detail: detail( + disc('new', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true), + disc('old', armedLatchBody(IMG), '2026-08-01T10:00:00Z', false) + ), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(calls).not.toContain('resolve:old'); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'new', + phase: 'running', + variant: 'running', + }); + expect(audits.map(a => a.action)).toContain('repointed'); + }); + + test('own approval spends from every phase', async () => { + const bodies = { + queued: queuedBody, + running: runningBody, + error: errorBody, + }; + for (const phase of ['queued', 'running', 'error'] as const) { + const db = tempDb(); + putLatchRow(row({ phase }), db); + const { deps, launches, uploads, noteBodies } = harness({ + db, + fetchLatchMrs: async () => [{ ...facts, approvedBySelf: true }], + detail: detail( + disc('d1', bodies[phase](), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).spent).toBe(1); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-approved.gif']); + expect(noteBodies.get(1)).toStartWith(SPENT); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + variant: 'approved', + }); + } + }); + + test('an errored lane does not refuse an armed request', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const failed: ReviewState = { + ...commented, + status: 'error', + outcome: undefined, + }; + const { deps, launches, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('an abandoned follow-up lane does not refuse an armed request', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const { deps, launches, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, noOutcome]]), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('an armed row whose lane is gone still takes a request', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const { deps, launches, replies } = harness({ + db, + readReviewStates: () => new Map(), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(replies).toEqual([]); + }); + + test('a request during a running review queues behind it', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const reviewing: ReviewState = { ...commented, status: 'reviewing' }; + const { deps, launches, uploads } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).queued).toBe(1); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-queued-review-in-flight.gif']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'queued', + wait: 'review-in-flight', + launchAt: NOW, + }); + }); + + test('reopening a queued latch while a hand-launched review runs withdraws it and leaves the thread open', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 1_000, + }; + const { deps, calls, launches, noteBodies } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', false)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(noteBodies.get(1)).toStartWith(ARMED + '\n'); + expect(readLatchRow(MR, db)).toMatchObject({ phase: 'armed', wait: null }); + }); + + test('a wait change that loses its cas writes and counts nothing', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, calls, audits } = harness({ + db, + casLatch: () => false, + memory: { + identity: null, + mrs: { + [MR]: { ...emptyMrMemory('1970-01-12'), attemptsToday: 3 }, + }, + }, + detail: detail(disc('d1', queuedBody(), '2026-09-01T10:00:00Z', true)), + }); + const result = await runLatchPass(deps); + expect(result.queued).toBe(0); + expect(calls).toEqual([]); + expect(audits.map(a => a.action)).not.toContain('queued'); + }); + + // A read that cannot see the row's latch yet, beside an old spent relic, + // must not overwrite the row with the relic. + test('a live row is kept when the read shows only a spent latch elsewhere', async () => { + const db = tempDb(); + putLatchRow(queuedRow(), db); + const { deps, calls } = harness({ + db, + detail: detail( + disc('relic', spentLatchBody(IMG), '2026-08-01T10:00:00Z', true) + ), + }); + await runLatchPass(deps); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'd1', + phase: 'queued', + }); + }); + + test('a re-point that loses its cas skips the tick', async () => { + const db = tempDb(); + putLatchRow(row({ discussionId: 'old', updatedAt: NOW }), db); + const { deps, calls, launches } = harness({ + db, + casLatch: () => false, + detail: detail( + disc('new', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true), + disc('old', armedLatchBody(IMG), '2026-08-01T10:00:00Z', false) + ), + }); + expect((await runLatchPass(deps)).skipped).toBe(1); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.discussionId).toBe('old'); + }); +}); + +describe('error, retry and stuck', () => { + const failed: ReviewState = { + ...commented, + status: 'error', + outcome: undefined, + message: 'pane closed', + }; + const cooling = (): DispatchMemory => ({ + identity: null, + mrs: { + [MR]: { ...emptyMrMemory('1970-01-12'), lastDispatchAt: NOW - 60_000 }, + }, + }); + const runningRow = (over: Partial = {}) => + row({ + phase: 'running', + launchAt: NOW - 60_000, + variant: 'running', + ...over, + }); + const errorRow = (over: Partial = {}) => + row({ + phase: 'error', + wait: 'next-sweep', + launchAt: NOW - 60 * 60_000, + failures: 1, + variant: 'error-retrying-next-sweep', + ...over, + }); + + test('review error moves running to error-retrying', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, calls, uploads, launches, noteBodies, replies, audits } = + harness({ + db, + memory: cooling(), + readReviewStates: () => new Map([[MR, failed]]), + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).errored).toBe(1); + expect(launches).toEqual([]); + expect(replies).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(uploads).toEqual(['latch-2317-error-retrying-cooldown.gif']); + expect(noteBodies.get(1)).toStartWith(ERROR); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'error', + failures: 1, + stuck: false, + wait: 'cooldown', + variant: 'error-retrying-cooldown', + }); + expect(audits.map(a => a.action)).toContain('error'); + }); + + test('retry dispatch returns error to running and charges memory', async () => { + const db = tempDb(); + putLatchRow(errorRow(), db); + const { deps, launches, noteBodies, memory, replies, audits } = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + expect(replies).toEqual([]); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(memory.mrs[MR]?.attemptsToday).toBe(1); + expect(memory.mrs[MR]?.lastDispatchAt).toBe(NOW); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW, + wait: null, + failures: 1, + variant: 'running', + }); + expect(audits.map(a => a.action)).toContain('retried'); + }); + + test('launch-failed counts as a failure', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW }), db); + const phases: string[] = []; + const { deps, calls, uploads, replies, memory, audits } = harness({ + db, + launchReReview: async () => ({ kind: 'error', message: 'boom' }), + casLatch: (url, from, patch, at, opts) => { + if (patch.phase) phases.push(patch.phase); + return casLatchIn(url, from, patch, at, db, opts); + }, + detail: detail( + disc('d1', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + expect((await runLatchPass(deps)).errored).toBe(1); + expect(replies).toEqual([]); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(uploads).toEqual(['latch-2317-error-retrying-next-sweep.gif']); + expect(phases).toEqual(['error']); + expect(memory.mrs[MR]?.attemptsToday ?? 0).toBe(0); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'error', + failures: 1, + wait: 'next-sweep', + }); + expect(audits.find(a => a.action === 'error')?.outcome).toBe('boom'); + }); + + test('third failure is stuck: one reply, one notifyStuck, no more launches', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + let note = runningBody(); + const { deps, launches, uploads, replies, calls, stuckNotices, audits } = + harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + readDetail: async () => + detail(disc('d1', note, '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).stuck).toBe(1); + expect(uploads).toEqual(['latch-2317-error-stuck.gif']); + expect(calls).toEqual(['upload', 'updateNote:1', 'reply:d1']); + expect(replies).toEqual([copyFor({ state: 'error-stuck' }).sentence]); + expect(stuckNotices).toEqual([ + { + title: 'Follow-up review stuck on !2317', + message: 'It failed 3 times. Relaunch it from the board.', + mrUrl: MR, + }, + ]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'error', + failures: 3, + stuck: true, + variant: 'error-stuck', + }); + expect(audits.map(a => a.action)).toContain('stuck'); + + note = errorBody(); + await runLatchPass(deps); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(replies).toHaveLength(1); + expect(stuckNotices).toHaveLength(1); + expect(readLatchRow(MR, db)).toMatchObject({ phase: 'error', stuck: true }); + }); + + test('relaunch from the board clears stuck', async () => { + const db = tempDb(); + putLatchRow( + errorRow({ + failures: 3, + stuck: true, + wait: null, + variant: 'error-stuck', + }), + db + ); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 1_000, + }; + const { deps, launches, noteBodies, replies, memory, audits } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(replies).toEqual([]); + expect(memory.mrs[MR]).toBeUndefined(); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW - 1_000, + stuck: false, + failures: 3, + variant: 'running', + }); + expect(audits.map(a => a.action)).toContain('recovered'); + }); + + test('long reviewing is still running', async () => { + const db = tempDb(); + const sixHours = 6 * 60 * 60_000; + putLatchRow(runningRow({ launchAt: NOW - sixHours }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - sixHours, + updatedAt: NOW - sixHours, + }; + const { deps, calls, launches } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + updatedAt: 1, + }); + }); + + test('retry blocked by budget shows the budget wait', async () => { + const db = tempDb(); + putLatchRow(errorRow(), db); + const { deps, launches, uploads, calls, noteBodies, audits } = harness({ + db, + memory: { + identity: null, + mrs: { [MR]: { ...emptyMrMemory('1970-01-12'), attemptsToday: 3 } }, + }, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).errored).toBe(1); + expect(audits.find(a => a.action === 'error')?.reason).toBe('budget'); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-error-retrying-budget.gif']); + expect(calls).toEqual(['upload', 'updateNote:1']); + expect(noteBodies.get(1)).toStartWith(ERROR); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'error', + wait: 'budget', + failures: 1, + variant: 'error-retrying-budget', + }); + }); + + test('a stuck transition whose banner write throws still notifies, and the next pass finishes it', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + const h = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + const upload = h.deps.gateway.uploadFile; + let broken = true; + h.deps.gateway.uploadFile = async (...args) => { + if (broken) { + broken = false; + throw new Error('gitlab 500'); + } + return upload(...args); + }; + expect((await runLatchPass(h.deps)).failed).toBe(1); + expect(h.stuckNotices).toHaveLength(1); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ phase: 'error', stuck: true }); + + expect((await runLatchPass(h.deps)).repaired).toBe(1); + expect(h.calls).toEqual(['upload', 'updateNote:1', 'reply:d1']); + expect(h.noteBodies.get(1)).toStartWith(ERROR); + expect(h.replies).toEqual([copyFor({ state: 'error-stuck' }).sentence]); + expect(h.stuckNotices).toHaveLength(1); + expect(readLatchRow(MR, db)?.variant).toBe('error-stuck'); + + await runLatchPass(h.deps); + expect(h.replies).toHaveLength(1); + expect(h.stuckNotices).toHaveLength(1); + }); + + test('a stuck reply that fails to post goes out once on a later pass, with no second notice', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + let note = runningBody(); + const h = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + readDetail: async () => + detail(disc('d1', note, '2026-09-01T10:00:00Z', true)), + }); + failNextReply(h.deps.gateway); + const stuck = copyFor({ state: 'error-stuck' }).sentence; + expect((await runLatchPass(h.deps)).stuck).toBe(1); + expect(h.stuckNotices).toHaveLength(1); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + variant: 'error-stuck', + replyDue: stuck, + }); + + note = errorBody(); + h.deps.now = () => NOW + LATCH_POST_GRACE_MS; + await runLatchPass(h.deps); + expect(h.replies).toEqual([stuck]); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + + await runLatchPass(h.deps); + expect(h.replies).toHaveLength(1); + expect(h.stuckNotices).toHaveLength(1); + }); + + test('a stuck reply still owed when a relaunch adopts the latch is never posted', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + let note = runningBody(); + let lane: ReviewState = failed; + const h = harness({ + db, + readReviewStates: () => new Map([[MR, lane]]), + readDetail: async () => + detail(disc('d1', note, '2026-09-01T10:00:00Z', true)), + }); + failNextReply(h.deps.gateway); + expect((await runLatchPass(h.deps)).stuck).toBe(1); + expect(readLatchRow(MR, db)?.replyDue).toBe( + copyFor({ state: 'error-stuck' }).sentence + ); + + note = errorBody(); + lane = { ...commented, status: 'reviewing', runStartedAt: NOW }; + await runLatchPass(h.deps); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + stuck: false, + replyDue: null, + }); + + note = runningBody(); + h.deps.now = () => NOW + LATCH_POST_GRACE_MS; + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + }); + + test('a stuck latch that gets spent never posts its stuck reply', async () => { + const db = tempDb(); + const stuck = copyFor({ state: 'error-stuck' }).sentence; + putLatchRow( + errorRow({ + failures: 3, + stuck: true, + wait: null, + variant: 'error-stuck', + replyDue: stuck, + updatedAt: NOW, + }), + db + ); + let note = errorBody(); + const h = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + fetchLatchMrs: async () => [{ ...facts, approvedBySelf: true }], + readDetail: async () => + detail(disc('d1', note, '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(h.deps)).spent).toBe(1); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + replyDue: stuck, + }); + + note = spentLatchBody(IMG); + h.deps.now = () => NOW + LATCH_POST_GRACE_MS; + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + expect(h.audits.map(a => a.action)).toContain('reply-dropped'); + }); + + test('a relaunch mid-pass is not a failure', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW, + }; + let reads = 0; + const { deps, calls, replies, stuckNotices } = harness({ + db, + readReviewStates: () => + new Map([[MR, reads++ === 0 ? failed : reviewing]]), + detail: detail(disc('d1', runningBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).stuck).toBe(0); + expect(calls).toEqual([]); + expect(replies).toEqual([]); + expect(stuckNotices).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + failures: LATCH_MAX_FAILURES - 1, + stuck: false, + }); + }); + + test('a launch error on a retry at two failures is stuck', async () => { + const db = tempDb(); + putLatchRow(errorRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + const { deps, replies, stuckNotices, memory } = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + launchReReview: async () => ({ kind: 'error', message: 'boom' }), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + expect((await runLatchPass(deps)).stuck).toBe(1); + expect(replies).toEqual([copyFor({ state: 'error-stuck' }).sentence]); + expect(stuckNotices).toHaveLength(1); + expect(memory.mrs[MR]?.attemptsToday ?? 0).toBe(0); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'error', + failures: LATCH_MAX_FAILURES, + stuck: true, + variant: 'error-stuck', + }); + }); + + test('a review starting on a retrying error row moves it to running', async () => { + const db = tempDb(); + putLatchRow(errorRow(), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 1_000, + }; + const { deps, launches, noteBodies, audits } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW - 1_000, + failures: 1, + stuck: false, + }); + expect(audits.map(a => a.action)).toContain('recovered'); + }); + + test('a queued lane recovers a stuck latch', async () => { + const db = tempDb(); + putLatchRow( + errorRow({ + failures: 3, + stuck: true, + wait: null, + variant: 'error-stuck', + }), + db + ); + const queuedLane: ReviewState = { + ...commented, + status: 'queued', + runStartedAt: NOW - 2_000, + }; + const { deps, launches, noteBodies, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, queuedLane]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(replies).toEqual([]); + expect(noteBodies.get(1)).toStartWith(RUNNING); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: NOW - 2_000, + stuck: false, + failures: 3, + }); + }); + + test('a run in flight that began before the last launch does not recover an error row', async () => { + const db = tempDb(); + putLatchRow(errorRow(), db); + const reviewing: ReviewState = { + ...commented, + status: 'reviewing', + runStartedAt: NOW - 2 * 60 * 60_000, + }; + const { deps, launches, calls } = harness({ + db, + readReviewStates: () => new Map([[MR, reviewing]]), + detail: detail(disc('d1', errorBody(), '2026-09-01T10:00:00Z', true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ phase: 'error', failures: 1 }); + }); + + test('the stuck reply goes out before the extra copies are spent', async () => { + const db = tempDb(); + putLatchRow(runningRow({ failures: LATCH_MAX_FAILURES - 1 }), db); + const h = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + detail: detail( + disc('d1', runningBody(), '2026-09-02T10:00:00Z', true), + disc('d2', armedLatchBody(IMG), '2026-09-01T10:00:00Z', true) + ), + }); + const update = h.deps.gateway.updateNote; + h.deps.gateway.updateNote = async (p, i, id, body) => { + if (body.startsWith(SPENT)) throw new Error('gitlab 500'); + return update(p, i, id, body); + }; + expect((await runLatchPass(h.deps)).failed).toBe(1); + expect(h.replies).toEqual([copyFor({ state: 'error-stuck' }).sentence]); + expect(readLatchRow(MR, db)?.variant).toBe('error-stuck'); + }); +}); + +describe('a lost db mid follow-up', () => { + const POSTED = '2026-09-01T10:00:00Z'; + const POSTED_MS = Date.parse(POSTED); + + test('the commented review from before the post never lands as the follow-up', async () => { + const db = tempDb(); + const earlier: ReviewState = { + ...commented, + runStartedAt: POSTED_MS - 60_000, + updatedAt: POSTED_MS - 1_000, + }; + const { deps, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, earlier]]), + detail: detail(disc('d1', runningBody(), POSTED, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(0); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + launchAt: POSTED_MS, + }); + }); + + test('a follow-up that started after the post lands', async () => { + const db = tempDb(); + const finished: ReviewState = { + ...commented, + runStartedAt: POSTED_MS + 60_000, + updatedAt: NOW - 60_000, + }; + const { deps, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, finished]]), + detail: detail(disc('d1', runningBody(), POSTED, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(1); + expect(replies).toEqual(['Follow-up review done.']); + expect(readLatchRow(MR, db)?.phase).toBe('armed'); + }); +}); + +describe('landing a follow-up from the pass', () => { + const LAUNCH = NOW - 60 * 60_000; + const lane = (over: Partial = {}): ReviewState => ({ + ...commented, + runStartedAt: LAUNCH + 60_000, + updatedAt: NOW - 60_000, + ...over, + }); + const runningRow = (over: Partial = {}) => + row({ phase: 'running', launchAt: LAUNCH, variant: 'running', ...over }); + const errorRow = (over: Partial = {}) => + row({ + phase: 'error', + wait: 'next-sweep', + launchAt: LAUNCH, + failures: 1, + variant: 'error-retrying-next-sweep', + ...over, + }); + // A day before NOW: a latch posted long before the row last moved. + const OLD = new Date(NOW - 24 * 60 * 60_000).toISOString(); + + test('a running row whose review finished lands with the count', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const asked: number[] = []; + const { deps, calls, uploads, launches, replies, audits, noteBodies } = + harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + countNew: async (_mr, launchAt) => { + asked.push(launchAt); + return 2; + }, + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + const r = await runLatchPass(deps); + expect(r.landed).toBe(1); + expect(asked).toEqual([LAUNCH]); + expect(launches).toEqual([]); + expect(uploads).toEqual(['latch-2317-done-comments-2.gif']); + expect(calls).toEqual([ + 'upload', + 'updateNote:1', + 'unresolve:d1', + 'reply:d1', + ]); + expect(noteBodies.get(1)).toStartWith(ARMED); + expect(replies).toEqual(['Follow-up review done: 2 new comments.']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + launchAt: null, + failures: 0, + variant: 'done-comments-2', + }); + expect(audits).toContainEqual( + expect.objectContaining({ action: 'landed', outcome: 'comment' }) + ); + }); + + test('with no countNew the pass lands as Review posted', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, uploads, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + await runLatchPass(deps); + expect(uploads).toEqual(['latch-2317-done-comments-none.gif']); + expect(replies).toEqual(['Follow-up review done.']); + }); + + test('a running row whose lane reads done approve spends done-approved', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, uploads, replies, noteBodies } = harness({ + db, + fetchLatchMrs: async () => [{ ...facts, approvedBySelf: true }], + readReviewStates: () => new Map([[MR, lane({ outcome: 'approve' })]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(1); + expect(uploads).toEqual(['latch-2317-done-approved.gif']); + expect(noteBodies.get(1)).toStartWith(SPENT); + expect(replies).toEqual(['Follow-up review done: approved.']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + variant: 'done-approved', + }); + }); + + test('a stale read after an approve landing keeps done-approved', async () => { + const db = tempDb(); + putLatchRow(runningRow({ phase: 'spent', variant: 'done-approved' }), db); + const { deps, uploads } = harness({ + db, + readReviewStates: () => new Map([[MR, lane({ outcome: 'approve' })]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + await runLatchPass(deps); + expect(uploads).toEqual(['latch-2317-done-approved.gif']); + expect(readLatchRow(MR, db)?.variant).toBe('done-approved'); + }); + + test('an abandoned follow-up re-arms quietly from the pass', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, calls, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, lane({ outcome: undefined })]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(1); + expect(calls).toEqual(['upload', 'updateNote:1', 'unresolve:d1']); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + variant: 'armed', + replyDue: null, + }); + }); + + test('a finished reply that fails to post goes out once on a later pass', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + let note = runningBody(); + const h = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + countNew: async () => 2, + readDetail: async () => detail(disc('d1', note, OLD, false)), + }); + failNextReply(h.deps.gateway); + expect((await runLatchPass(h.deps)).landed).toBe(1); + expect(h.replies).toEqual([]); + const reply = 'Follow-up review done: 2 new comments.'; + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + replyDue: reply, + }); + + note = armedLatchBody(IMG); + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + + h.deps.now = () => NOW + LATCH_POST_GRACE_MS; + await runLatchPass(h.deps); + expect(h.replies).toEqual([reply]); + expect(h.calls.filter(c => c.startsWith('reply:'))).toEqual(['reply:d1']); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + expect(h.audits.map(a => a.action)).toContain('replied'); + + await runLatchPass(h.deps); + expect(h.replies).toHaveLength(1); + }); + + test('a spent row still owing its approved reply is followed until it posts', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + let note = runningBody(); + let lanes = new Map([[MR, lane({ outcome: 'approve' })]]); + const h = harness({ + db, + readReviewStates: () => lanes, + readDetail: async () => detail(disc('d1', note, OLD, true)), + }); + failNextReply(h.deps.gateway); + expect((await runLatchPass(h.deps)).landed).toBe(1); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + replyDue: 'Follow-up review done: approved.', + }); + + note = spentLatchBody(IMG); + lanes = new Map(); + h.deps.now = () => NOW + LATCH_POST_GRACE_MS; + await runLatchPass(h.deps); + expect(h.replies).toEqual(['Follow-up review done: approved.']); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + + expect((await runLatchPass(h.deps)).skipped).toBe(1); + expect(h.replies).toHaveLength(1); + }); + + test('a reply GitLab keeps refusing does not stop the rest of the tick', async () => { + const db = tempDb(); + putLatchRow( + row({ + replyDue: 'Follow-up review done.', + updatedAt: NOW - LATCH_POST_GRACE_MS, + }), + db + ); + const h = harness({ + db, + detail: detail(disc('d1', armedLatchBody(IMG), OLD, true)), + }); + h.deps.gateway.createNote = async () => { + throw new Error('gitlab 500'); + }; + const r = await runLatchPass(h.deps); + expect(r.failed).toBe(0); + expect(r.dispatched).toBe(1); + expect(h.launches).toEqual([MR]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'running', + replyDue: 'Follow-up review done.', + }); + }); + + test('an owed reply older than a day is dropped and audited, never posted', async () => { + const db = tempDb(); + putLatchRow( + row({ + replyDue: 'Follow-up review done.', + updatedAt: NOW - LATCH_REPLY_GIVE_UP_MS - 1, + }), + db + ); + const h = harness({ + db, + detail: detail(disc('d1', armedLatchBody(IMG), OLD, false)), + }); + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + expect(h.audits.map(a => a.action)).toContain('reply-dropped'); + }); + + test('an owed reply whose latch is gone is dropped and audited', async () => { + const db = tempDb(); + putLatchRow( + row({ + phase: 'spent', + variant: 'done-approved', + replyDue: 'Follow-up review done: approved.', + }), + db + ); + const h = harness({ + db, + readReviewStates: () => new Map(), + detail: detail(disc('x1', 'Nice catch.', OLD, false, 'river')), + now: () => NOW + LATCH_POST_GRACE_MS, + }); + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)?.replyDue).toBeNull(); + expect(h.audits.map(a => a.action)).toContain('reply-dropped'); + }); + + test('an owed reply is never posted to a latch other than the canon', async () => { + const db = tempDb(); + putLatchRow( + row({ + discussionId: 'old', + phase: 'spent', + variant: 'done-approved', + replyDue: 'Follow-up review done: approved.', + }), + db + ); + const h = harness({ + db, + readReviewStates: () => new Map(), + detail: detail(disc('d1', spentLatchBody(IMG), OLD, true)), + now: () => NOW + LATCH_POST_GRACE_MS, + }); + await runLatchPass(h.deps); + expect(h.replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + discussionId: 'd1', + replyDue: null, + }); + }); + + test('a retrying error row whose review finished lands instead of retrying', async () => { + const db = tempDb(); + putLatchRow(errorRow(), db); + const { deps, launches, memory } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', errorBody(), OLD, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(1); + expect(launches).toEqual([]); + expect(memory.mrs[MR]).toBeUndefined(); + expect(readLatchRow(MR, db)?.phase).toBe('armed'); + }); + + test('a stuck error row whose review finished lands', async () => { + const db = tempDb(); + putLatchRow( + errorRow({ + failures: 3, + stuck: true, + wait: null, + variant: 'error-stuck', + }), + db + ); + const { deps, launches, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', errorBody(), OLD, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(1); + expect(launches).toEqual([]); + expect(replies).toEqual(['Follow-up review done.']); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + stuck: false, + }); + }); + + test('an error row with no launch stamp is retried, never landed', async () => { + const db = tempDb(); + putLatchRow(errorRow({ launchAt: null }), db); + const { deps, launches, audits } = harness({ + db, + readReviewStates: () => new Map([[MR, lane({ runStartedAt: NOW })]]), + detail: detail(disc('d1', errorBody(), OLD, true)), + }); + const r = await runLatchPass(deps); + expect(r.landed).toBe(0); + expect(launches).toEqual([MR]); + expect(audits.some(a => a.action === 'landed')).toBe(false); + }); + + test('a review that started before the launch does not land a running row', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, calls } = harness({ + db, + readReviewStates: () => + new Map([[MR, lane({ runStartedAt: LAUNCH - 1 })]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + expect((await runLatchPass(deps)).landed).toBe(0); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)?.phase).toBe('running'); + }); + + test('a landed latch ignores a stale armed resolved read inside the grace window', async () => { + const db = tempDb(); + const landed = row({ variant: 'done-comments-2', updatedAt: NOW - 60_000 }); + putLatchRow(landed, db); + const { deps, calls, launches } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', armedLatchBody(IMG), OLD, true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(readLatchRow(MR, db)).toEqual(landed); + }); + + test('an abandoned landing is guarded the same way', async () => { + const db = tempDb(); + putLatchRow(row({ variant: 'armed', updatedAt: NOW - 60_000 }), db); + const { deps, calls, launches } = harness({ + db, + readReviewStates: () => new Map([[MR, lane({ outcome: undefined })]]), + detail: detail(disc('d1', armedLatchBody(IMG), OLD, true)), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + }); + + // A follow-up requested, run and landed within minutes of the post is + // still a move after the post. + test('a landing three minutes after the post still guards a stale read', async () => { + const db = tempDb(); + const posted = NOW - 4 * 60_000; + const landed = row({ + variant: 'done-comments-1', + updatedAt: posted + 3 * 60_000, + }); + putLatchRow(landed, db); + const { deps, calls, launches, memory } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail( + disc('d1', armedLatchBody(IMG), new Date(posted).toISOString(), true) + ), + }); + await runLatchPass(deps); + expect(launches).toEqual([]); + expect(calls).toEqual([]); + expect(memory.mrs[MR]).toBeUndefined(); + expect(readLatchRow(MR, db)).toEqual(landed); + }); + + test("the landing stamp is the pass's clock at the landing, not the tick start", async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + let clock = NOW; + const { deps } = harness({ + db, + now: () => clock++, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + await runLatchPass(deps); + expect(readLatchRow(MR, db)!.updatedAt).toBeGreaterThan(NOW); + }); + + test('a GitLab approval beats a commented follow-up: plain Approved, no reply', async () => { + const db = tempDb(); + putLatchRow(runningRow(), db); + const { deps, uploads, replies, audits } = harness({ + db, + fetchLatchMrs: async () => [{ ...facts, approvedBySelf: true }], + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', runningBody(), OLD, true)), + }); + const r = await runLatchPass(deps); + expect(r.landed).toBe(0); + expect(r.spent).toBe(1); + expect(uploads).toEqual(['latch-2317-approved.gif']); + expect(replies).toEqual([]); + expect(audits.some(a => a.action === 'landed')).toBe(false); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'spent', + variant: 'approved', + }); + }); + + test('the armed repair skips once another writer moved the row', async () => { + const db = tempDb(); + putLatchRow(row({ variant: 'done-comments-1', updatedAt: 1 }), db); + const { deps, calls, audits } = harness({ + db, + readDetail: async () => { + casLatchIn( + MR, + ['armed'], + { phase: 'queued', wait: 'cooldown' }, + NOW, + db + ); + return detail(disc('d1', runningBody(), OLD, true)); + }, + }); + const r = await runLatchPass(deps); + expect(r.repaired).toBe(0); + expect(calls).toEqual([]); + expect(audits.some(a => a.action === 'repaired')).toBe(false); + }); + + test('past the grace window the same read is a request', async () => { + const db = tempDb(); + putLatchRow( + row({ + variant: 'done-comments-2', + updatedAt: NOW - LATCH_POST_GRACE_MS, + }), + db + ); + const { deps, launches } = harness({ + db, + readReviewStates: () => new Map([[MR, lane()]]), + detail: detail(disc('d1', armedLatchBody(IMG), OLD, true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + }); + + test('a request on a latch posted moments ago is not held', async () => { + const db = tempDb(); + putLatchRow(row({ updatedAt: NOW - 60_000 }), db); + const posted = new Date(NOW - 61_000).toISOString(); + const { deps, launches } = harness({ + db, + detail: detail(disc('d1', armedLatchBody(IMG), posted, true)), + }); + expect((await runLatchPass(deps)).dispatched).toBe(1); + expect(launches).toEqual([MR]); + }); + + test('the stuck repair skips once a landing moved the row', async () => { + const db = tempDb(); + putLatchRow( + errorRow({ + failures: 3, + stuck: true, + wait: null, + variant: 'error-retrying-next-sweep', + }), + db + ); + const failed: ReviewState = { + ...commented, + status: 'error', + outcome: undefined, + }; + const { deps, calls, replies } = harness({ + db, + readReviewStates: () => new Map([[MR, failed]]), + readDetail: async () => { + casLatchIn( + MR, + ['error'], + { phase: 'armed', stuck: false, variant: 'done-comments-1' }, + NOW, + db + ); + return detail(disc('d1', errorBody(), OLD, true)); + }, + }); + await runLatchPass(deps); + expect(calls).toEqual([]); + expect(replies).toEqual([]); + expect(readLatchRow(MR, db)).toMatchObject({ + phase: 'armed', + variant: 'done-comments-1', + }); + }); +}); + +describe('latchInScope', () => { + const OTHER = 'https://gitlab.com/acme/web/-/merge_requests/2400'; + const mrs = [{ webUrl: MR }, { webUrl: OTHER }, { webUrl: null }]; + const none = new Map(); + const urls = (got: { webUrl?: string | null }[]) => got.map(m => m.webUrl); + + // A request can arrive while the lane reads error (a hand-launched review + // died) or reviewing; the pass must still see the latch. + test('every live row phase is in scope whatever the lane reads, armed included', () => { + for (const phase of ['armed', 'queued', 'running', 'error'] as const) { + const got = latchInScope(mrs, { + rows: [{ mrUrl: MR, phase }], + states: new Map([[MR, { ...commented, status: 'error' }]]), + pruned: none, + }); + expect(urls(got)).toEqual([MR]); + } + }); + + test('a spent row or no row falls back to the done and tombstone checks', () => { + const scope = (rows: { mrUrl: string; phase: 'spent' }[]) => + latchInScope(mrs, { + rows, + states: new Map([ + [MR, { ...commented, status: 'reviewing' }], + [OTHER, { ...commented, mrUrl: OTHER, outcome: 'approve' }], + ]), + pruned: none, + }); + expect(urls(scope([{ mrUrl: MR, phase: 'spent' }]))).toEqual([OTHER]); + expect(urls(scope([]))).toEqual([OTHER]); + }); + + test('a commented tombstone is in scope, an approved one is not', () => { + const got = latchInScope(mrs, { + rows: [], + states: none, + pruned: new Map([ + [MR, commented], + [OTHER, { ...commented, mrUrl: OTHER, outcome: 'approve' }], + ]), + }); + expect(urls(got)).toEqual([MR]); + }); + + test('an MR listed twice and matched twice is read once', () => { + const got = latchInScope([{ webUrl: MR }, { webUrl: MR }], { + rows: [{ mrUrl: MR, phase: 'queued' }], + states: new Map([[MR, commented]]), + pruned: new Map([[MR, commented]]), + }); + expect(urls(got)).toEqual([MR]); + }); +}); + +describe('waitReasonOf', () => { + test('maps the reasons that clear by themselves', () => { + expect(waitReasonOf({ action: 'dispatch', reason: 'latch' })).toBe( + 'next-sweep' + ); + expect(waitReasonOf({ action: 'reject', reason: 'cooldown' })).toBe( + 'cooldown' + ); + expect(waitReasonOf({ action: 'reject', reason: 'budget-exhausted' })).toBe( + 'budget' + ); + expect(waitReasonOf({ action: 'reject', reason: 'review-in-flight' })).toBe( + 'review-in-flight' + ); + }); + + test('null for reasons that never clear', () => { + expect( + waitReasonOf({ action: 'reject', reason: 'no-commented-review' }) + ).toBeNull(); + expect( + waitReasonOf({ action: 'reject', reason: 'already-reviewed' }) + ).toBeNull(); + }); +}); + +describe('runStamp', () => { + test('the run start, falling back to the last write, never startedAt', () => { + expect(runStamp({ ...commented, startedAt: 1, runStartedAt: 7 })).toBe(7); + expect(runStamp({ ...commented, startedAt: 1, updatedAt: 9 })).toBe(9); + }); +}); diff --git a/apps/board/src/latch/banner.ts b/apps/board/src/latch/banner.ts index b9f13856ed..6616d685d3 100644 --- a/apps/board/src/latch/banner.ts +++ b/apps/board/src/latch/banner.ts @@ -1,63 +1,316 @@ /** - * The per-MR latch banner: the committed band artwork with this MR's invadrs - * creature painted into the reserved box on its left. + * The per-MR latch banner: a committed text strip for the variant, with this + * MR's invadrs creature, the title's dots and the running ring painted in per + * frame, encoded as a looping GIF. * - * The sprite colour is forced rather than taken from the palette. A palette - * pick like ocean's #1d3557 would be invisible on the near-black band; the - * per-MR character comes from the creature's shape, and pink holds 6.84:1. + * The creature colour is the variant accent rather than the invadrs palette + * pick, which can vanish on the dark strip; the per-MR character comes from + * the creature's shape. */ import { readFileSync } from 'fs'; -import { resolveSpawn } from 'invadrs'; +import { applyPalette, GIFEncoder, quantize } from 'gifenc'; +import { resolveInvadr } from 'invadrs'; import { PNG } from 'pngjs'; -import bandAsset from '../../assets/latch-band.png' with { type: 'file' }; +import { LAYOUT, STRIPS } from '../../assets/latch/index.ts'; +import { + copyFor, + DOT_GAP_PX, + DOT_PX, + variantKey, + type BannerVariant, +} from './variants.ts'; -export const BAND_W = 1200; -export const BAND_H = 208; +export const GIF_W = 1040; +export const GIF_H = 128; -const SPRITE_PINK = { r: 0xff, g: 0x6b, b: 0x9d }; -/** Top-left of the sprite box inside the band, and its side, in band pixels. - Centred in the 240px gutter that scripts/build-latch-band.ts reserves as - the band's left padding, so the leading margin matches the band's own 60px - trailing padding. */ -const SPRITE_X = 60; -const SPRITE_Y = 44; -const SPRITE_SIDE = 120; +const CELL = 6; +const BOX_X = 28; +const BOX_W = 90; +const BOX_H = 66; +/** The approved prototype centred the 33px CSS box at y 15.5, which Chromium + painted from device row 32, one below the arithmetic centre. */ +const BOX_Y = (GIF_H - BOX_H) / 2 + 1; -// The `with { type: "file" }` import resolves to a real path in both a -// checkout and a compiled binary: Bun embeds the file and extracts it to a -// temp path at runtime, so readFileSync works unchanged either way. -const DEFAULT_BAND = bandAsset; +const RING_X = 948; +const RING_Y = (GIF_H - 44) / 2; +const RING_CELL = 12; +const RING_PITCH = 16; +/** Clockwise from the top-left, in ring cells. */ +const RING: [number, number][] = [ + [0, 0], + [1, 0], + [2, 0], + [2, 1], + [2, 2], + [1, 2], + [0, 2], + [0, 1], +]; -export function latchBannerPng( - mrUrl: string, - bandPath: string = DEFAULT_BAND -): Buffer { - const band = PNG.sync.read(readFileSync(bandPath)); - const { grid, padding } = resolveSpawn(mrUrl); - - // resolveSpawn's viewBox spans grid + padding on every side, so a cell at - // index i sits at unit (i + padding) and one unit is side / (n + 2 * padding). - const units = grid.length + padding * 2; - const cell = SPRITE_SIDE / units; - - for (let row = 0; row < grid.length; row++) { - for (let col = 0; col < grid[row]!.length; col++) { - if (!grid[row]![col]) continue; - const x0 = Math.round(SPRITE_X + (col + padding) * cell); - const y0 = Math.round(SPRITE_Y + (row + padding) * cell); - const x1 = Math.round(SPRITE_X + (col + padding + 1) * cell); - const y1 = Math.round(SPRITE_Y + (row + padding + 1) * cell); - for (let y = y0; y < y1; y++) { - for (let x = x0; x < x1; x++) { - const i = (band.width * y + x) << 2; - band.data[i] = SPRITE_PINK.r; - band.data[i + 1] = SPRITE_PINK.g; - band.data[i + 2] = SPRITE_PINK.b; - band.data[i + 3] = 0xff; - } +const EYE = '#ece8f4'; +const RING_UNLIT = '#5d5775'; +const SPARKLES: [number, number][] = [ + [0, -3], + [7, -5], + [14, -2], +]; + +interface Frame { + delay: number; + legs?: 0 | 1; + dx?: number; + dy?: number; + dots?: number; + head?: number; + blink?: boolean; + spark?: boolean; +} + +const MARCH = [0, 1, 2, 1, 0, -1, -2, -1]; +const RETRY_DOTS = [1, 1, 2, 2, 2, 3, 3, 0]; + +function shake(dots: boolean): Frame[] { + const frames: Frame[] = [ + { dx: 0, delay: 700 }, + { dx: 1, legs: 1, delay: 70 }, + { dx: -1, delay: 70 }, + { dx: 1, legs: 1, delay: 70 }, + { dx: 0, delay: 500 }, + { delay: 600 }, + { blink: true, delay: 140 }, + { delay: 600 }, + ]; + return dots ? frames.map((f, i) => ({ ...f, dots: RETRY_DOTS[i] })) : frames; +} + +function hop(spark: boolean): Frame[] { + return [ + { delay: 900 }, + { dy: 1, legs: 1, delay: 90 }, + { dy: 2, legs: 1, spark, delay: 140 }, + { dy: 1, legs: 1, spark, delay: 90 }, + { spark, delay: 220 }, + { delay: 900 }, + { blink: true, delay: 140 }, + { delay: 900 }, + ]; +} + +function framesFor(state: BannerVariant['state']): Frame[] { + switch (state) { + case 'armed': + return [ + { delay: 900 }, + { legs: 1, delay: 900 }, + { delay: 900 }, + { blink: true, delay: 140 }, + { delay: 700 }, + { legs: 1, delay: 900 }, + ]; + case 'queued': + return [0, 1, 2, 3, 0, 1, 2, 3].map((dots, i) => ({ + dots, + legs: i < 4 ? 0 : 1, + blink: i === 7, + delay: 420, + })); + case 'running': + return MARCH.map((dx, i) => ({ + dx, + legs: (i % 2) as 0 | 1, + head: i, + delay: 130, + })); + case 'error-retrying': + return shake(true); + case 'error-stuck': + return shake(false); + case 'done-comments': + return hop(false); + case 'done-approved': + case 'approved': + return hop(true); + case 'superseded': + return [{ delay: 0 }]; + } +} + +/** The second leg pose: the bottom two rows step one column toward the centre. */ +export function legShuffle(grid: boolean[][]): boolean[][] { + const out = grid.map(row => [...row]); + for (let y = Math.max(0, grid.length - 2); y < grid.length; y++) { + const row = grid[y]!; + const w = row.length; + const next = new Array(w).fill(false); + for (let x = 0; x < w; x++) { + if (!row[x]) continue; + const toCentre = 2 * x + 1 - w; + next[x + (toCentre < 0 ? 1 : toCentre > 0 ? -1 : 0)] = true; + } + out[y] = next; + } + return out; +} + +type Rgb = [number, number, number]; + +function hex(c: string): Rgb { + const n = parseInt(c.slice(1, 7), 16); + return [(n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]; +} + +/** Ids for every colour painted in one GIF, shared across its frames. */ +class PaintedColours { + readonly ids = new Map(); + readonly colours: Rgb[] = []; + + idOf(c: Rgb): number { + const key = c.join(','); + let id = this.ids.get(key); + if (id === undefined) { + id = this.colours.length; + this.ids.set(key, id); + this.colours.push(c); + } + return id; + } +} + +class Canvas { + /** The painted colour id per pixel, or -1 where the strip shows through. */ + readonly owner = new Int16Array(GIF_W * GIF_H).fill(-1); + + constructor( + readonly data: Uint8Array, + private readonly painted: PaintedColours + ) {} + + rect(x0: number, y0: number, w: number, h: number, colour: Rgb, alpha = 1) { + for (let y = Math.max(0, y0); y < Math.min(GIF_H, y0 + h); y++) { + for (let x = Math.max(0, x0); x < Math.min(GIF_W, x0 + w); x++) { + const p = y * GIF_W + x; + const i = p << 2; + const c: Rgb = [0, 1, 2].map(k => + Math.round(colour[k]! * alpha + this.data[i + k]! * (1 - alpha)) + ) as Rgb; + this.data[i] = c[0]; + this.data[i + 1] = c[1]; + this.data[i + 2] = c[2]; + this.data[i + 3] = 0xff; + this.owner[p] = this.painted.idOf(c); } } } - return PNG.sync.write(band); +} + +/** A creature to paint: its two leg poses and its eye cells as [col, row]. */ +export interface Creature { + frames: [boolean[][], boolean[][]]; + eyes: [number, number][]; +} + +export function latchBannerGif( + mrUrl: string, + variant: BannerVariant +): Uint8Array { + const { grid, accent } = resolveInvadr(mrUrl, { accent: true }); + return renderBannerGif( + { frames: [grid, legShuffle(grid)], eyes: accent?.cells ?? [] }, + variant + ); +} + +export function renderBannerGif( + creature: Creature, + variant: BannerVariant +): Uint8Array { + const key = variantKey(variant); + const copy = copyFor(variant); + const stripPath = STRIPS[key]; + const layout = ( + LAYOUT as Record + )[key]; + if (!stripPath || !layout) throw new Error(`no latch strip for ${key}`); + const strip = PNG.sync.read(readFileSync(stripPath)); + const [grid, shuffled] = creature.frames; + const body = hex(copy.accent); + const eye = hex(EYE); + + const spriteW = grid[0]!.length * CELL; + const restX = BOX_X + Math.floor((BOX_W - spriteW) / CELL / 2) * CELL; + const restY = BOX_Y; + + const plan = framesFor(variant.state); + const painted = new PaintedColours(); + const canvases = plan.map(f => { + const canvas = new Canvas(new Uint8Array(strip.data), painted); + const cells = f.legs ? shuffled : grid; + const ox = Math.min( + Math.max(restX + (f.dx ?? 0) * CELL, BOX_X), + BOX_X + BOX_W - spriteW + ); + const oy = restY - (f.dy ?? 0) * CELL; + cells.forEach((row, y) => + row.forEach((on, x) => { + if (on) canvas.rect(ox + x * CELL, oy + y * CELL, CELL, CELL, body); + }) + ); + // invadrs' accent cells hold every enclosed hole, mouths included; only + // the upper-half ones are eyes, so only those close on a blink. + for (const [x, y] of creature.eyes) { + if (cells[y]?.[x]) continue; + const shut = f.blink && y < grid.length / 2; + canvas.rect(ox + x * CELL, oy + y * CELL, CELL, CELL, shut ? body : eye); + } + if (f.spark) { + for (const [x, y] of SPARKLES) { + canvas.rect(BOX_X + x * CELL, BOX_Y + y * CELL, CELL, CELL, eye); + } + } + if (copy.indicator === 'dots') { + for (let i = 0; i < (f.dots ?? 0); i++) { + const x = layout.dotsX + i * (DOT_PX + DOT_GAP_PX); + canvas.rect(x, layout.dotsY, DOT_PX, DOT_PX, body); + } + } + if (copy.indicator === 'ring') { + RING.forEach(([cx, cy], k) => { + const d = ((((f.head ?? 0) - k) % 8) + 8) % 8; + const x = RING_X + cx * RING_PITCH; + const y = RING_Y + cy * RING_PITCH; + if (d === 0) canvas.rect(x, y, RING_CELL, RING_CELL, body); + else if (d === 1) + canvas.rect(x, y, RING_CELL, RING_CELL, body, 0xe0 / 255); + else if (d === 2) + canvas.rect(x, y, RING_CELL, RING_CELL, body, 0xb0 / 255); + else canvas.rect(x, y, RING_CELL, RING_CELL, hex(RING_UNLIT)); + }); + } + return canvas; + }); + + const size = GIF_W * GIF_H * 4; + const all = new Uint8Array(canvases.length * size); + canvases.forEach((c, i) => all.set(c.data, i * size)); + const quantized = quantize(all, 256 - painted.colours.length); + const palette = [...quantized, ...painted.colours]; + + const gif = GIFEncoder(); + canvases.forEach((c, i) => { + // applyPalette caches its nearest match per rgb565 bucket, so a strip + // pixel can hand a painted colour the wrong index; painted pixels get + // their own exact entry instead. + const index = applyPalette(c.data, palette); + for (let p = 0; p < c.owner.length; p++) { + if (c.owner[p]! >= 0) index[p] = quantized.length + c.owner[p]!; + } + gif.writeFrame(index, GIF_W, GIF_H, { + palette: i === 0 ? palette : undefined, + delay: plan[i]!.delay, + repeat: 0, + }); + }); + gif.finish(); + return gif.bytes(); } diff --git a/apps/board/src/latch/discussions.ts b/apps/board/src/latch/discussions.ts index 20e6d2683b..9a2f2ca2f0 100644 --- a/apps/board/src/latch/discussions.ts +++ b/apps/board/src/latch/discussions.ts @@ -93,12 +93,13 @@ export function canonicalLatch(latches: LatchRef[]): LatchRef | null { return latches[0] ?? null; } -/** Whether the MR already has a live (unspent) latch, for gating a fresh - post. A spent latch must never suppress a new one -- canonicalLatch - returns the newest latch of EITHER kind, so testing against it would read - an MR whose only latch was ever spent as still latched, forever. */ -export function hasArmedLatch(latches: LatchRef[]): boolean { - return latches.some(l => l.kind === 'armed'); +/** Whether the MR already has a live (unspent) latch, in any phase, for + gating a fresh post. A spent latch must never suppress a new one -- + canonicalLatch returns the newest latch of EITHER kind, so testing against + it would read an MR whose only latch was ever spent as still latched, + forever. */ +export function hasLiveLatch(latches: LatchRef[]): boolean { + return latches.some(l => l.kind !== 'spent'); } /** Every latch holding an unconsumed request. Disposing of a request must diff --git a/apps/board/src/latch/gifenc.d.ts b/apps/board/src/latch/gifenc.d.ts new file mode 100644 index 0000000000..12a47eb5e0 --- /dev/null +++ b/apps/board/src/latch/gifenc.d.ts @@ -0,0 +1,15 @@ +declare module 'gifenc' { + export type Palette = number[][]; + export function quantize(rgba: Uint8Array, maxColors: number): Palette; + export function applyPalette(rgba: Uint8Array, palette: Palette): Uint8Array; + export function GIFEncoder(): { + writeFrame( + index: Uint8Array, + width: number, + height: number, + opts?: { palette?: Palette; delay?: number; repeat?: number } + ): void; + finish(): void; + bytes(): Uint8Array; + }; +} diff --git a/apps/board/src/latch/land.ts b/apps/board/src/latch/land.ts new file mode 100644 index 0000000000..fb890849e5 --- /dev/null +++ b/apps/board/src/latch/land.ts @@ -0,0 +1,255 @@ +/** + * Landing a finished follow-up review on the latch it was launched for. The + * server's done signal and the latch pass's backstop both call this; the + * compare-and-set on the row lets exactly one of them write the note and + * post the reply. + */ +import type { Database } from 'bun:sqlite'; + +import type { MRDetail } from '@mattstack/glance'; +import { getStateDb } from '../state/index.ts'; +import type { LatchRef } from './discussions.ts'; +import { + casLatch, + readLatchRow, + type LatchPhase, + type LatchRow, +} from './latch-state.ts'; +import { latchKindOf } from './markers.ts'; +import { + postReplyDue, + rewriteLatch, + spendAllLatches, + spendLatch, + type LatchGateway, + type LatchTarget, +} from './post.ts'; +import { variantKey, type BannerVariant } from './variants.ts'; + +export interface LandInput { + target: LatchTarget; + outcome: 'comment' | 'approve' | null; + /** runStamp(review) of the review that finished. */ + reviewRunStartedAt: number; + gateway: LatchGateway; + self: string; + /** The reviewer's discussions created at or after launchAt, fresh from + GitLab; null when they cannot be read. */ + countNew: () => Promise; + now: number; + /** Every latch copy of this reviewer's found on the MR. An approve landing + spends all but the target as approved, so an extra cannot strand live + once the canon is spent. */ + latches?: LatchRef[]; +} + +export type LandResult = 'landed' | 'not-mine' | 'none'; + +const DONE_APPROVED: BannerVariant = { state: 'done-approved' }; +const ARMED: BannerVariant = { state: 'armed' }; + +function check(row: LatchRow | null, i: LandInput): LandResult | 'ok' { + if (!row || (row.phase !== 'running' && row.phase !== 'error')) return 'none'; + if (row.discussionId !== i.target.discussionId) return 'not-mine'; + // A first launch that failed never stamped one, so no review can be shown + // to be this latch's follow-up. + if (row.launchAt === null || i.reviewRunStartedAt < row.launchAt) + return 'not-mine'; + return 'ok'; +} + +export function finishedReply( + outcome: 'comment' | 'approve', + count: number | null +): string { + if (outcome === 'approve') return 'Follow-up review done: approved.'; + if (count == null || count <= 0) return 'Follow-up review done.'; + return count === 1 + ? 'Follow-up review done: 1 new comment.' + : `Follow-up review done: ${count} new comments.`; +} + +export async function landFollowUp( + i: LandInput, + db: Database = getStateDb() +): Promise { + const { target, now } = i; + const first = check(readLatchRow(target.mrUrl, db), i); + if (first !== 'ok') return first; + + const count = i.outcome === 'comment' ? await i.countNew() : null; + const variant: BannerVariant = + i.outcome === 'approve' + ? DONE_APPROVED + : i.outcome === 'comment' + ? { state: 'done-comments', count } + : ARMED; + const key = variantKey(variant); + // Owed in the same write that lands, so a reply that fails to post is + // still owed to the latch pass rather than lost. An abandoned landing owes + // nothing, and replaces any stuck reply still owed from before the run. + const reply = i.outcome ? finishedReply(i.outcome, count) : null; + const patch: Partial> = + i.outcome === 'approve' + ? { phase: 'spent', variant: key, replyDue: reply } + : { + phase: 'armed', + failures: 0, + stuck: false, + wait: null, + launchAt: null, + variant: key, + replyDue: reply, + }; + + // The re-check and the move share one write transaction: a retry that + // re-stamped launchAt since the first read must not be landed by an older + // review. + const from = db + .transaction((): LatchPhase | null => { + const row = readLatchRow(target.mrUrl, db); + if (check(row, i) !== 'ok') return null; + const moved = casLatch( + target.mrUrl, + ['running', 'error'], + patch, + now, + db, + { discussionId: target.discussionId } + ); + return moved ? row!.phase : null; + }) + .immediate(); + if (from === null) return 'none'; + + if (i.outcome === 'approve') { + const latch: LatchRef = { + discussionId: target.discussionId, + rootNoteId: target.rootNoteId, + kind: from, + resolved: true, + createdAt: '', + body: '', + }; + await spendLatch( + i.gateway, + target.projectId, + target.projectPath, + target.mrUrl, + target.iid, + latch, + variant, + now, + db + ); + } else { + await rewriteLatch( + i.gateway, + target, + 'armed', + variant, + 'unresolve', + now, + db + ); + } + if (reply !== null) { + try { + await postReplyDue(i.gateway, target, target.discussionId, reply, db); + } catch (err) { + // Still owed on the row: the latch pass posts it on a later tick. + console.error( + `latch: !${target.iid} finished reply not posted: ${err instanceof Error ? err.message : err}` + ); + } + } + if (i.outcome === 'approve') { + await spendAllLatches( + i.gateway, + target.projectId, + target.projectPath, + target.mrUrl, + target.iid, + (i.latches ?? []).filter(l => l.discussionId !== target.discussionId), + { state: 'approved' }, + now, + db + ); + } + return 'landed'; +} + +/** The reviewer's own threads opened at or after `launchAt`, leaving out + latch threads and system notes. */ +export function countNewDiscussions( + detail: MRDetail, + self: string, + launchAt: number +): number { + const owner = self.toLowerCase(); + let n = 0; + for (const d of detail.discussions) { + const root = d.notes[0]; + if (!root || root.system) continue; + if (root.author?.username.toLowerCase() !== owner) continue; + if (latchKindOf(root.body ?? '')) continue; + const at = Date.parse(root.createdAt); + if (Number.isFinite(at) && at >= launchAt) n++; + } + return n; +} + +/** countNewDiscussions over a fresh read; null when the read fails. */ +export async function fetchNewDiscussionCount( + fetchDetail: () => Promise, + self: string, + launchAt: number +): Promise { + try { + return countNewDiscussions(await fetchDetail(), self, launchAt); + } catch { + return null; + } +} + +/** An approval spends every copy. The copy a landing already marked + done-approved keeps that banner, so a later spend from a stale read + cannot turn the follow-up's verdict back into a plain approval. */ +export async function spendForApproval( + gw: LatchGateway, + mr: Pick, + latches: LatchRef[], + row: LatchRow | null, + now: number, + db: Database = getStateDb() +): Promise { + const landed = + row?.phase === 'spent' && row.variant === variantKey(DONE_APPROVED) + ? row.discussionId + : null; + const own = latches.find(l => l.discussionId === landed); + if (own) { + await spendLatch( + gw, + mr.projectId, + mr.projectPath, + mr.mrUrl, + mr.iid, + own, + DONE_APPROVED, + now, + db + ); + } + await spendAllLatches( + gw, + mr.projectId, + mr.projectPath, + mr.mrUrl, + mr.iid, + latches.filter(l => l.discussionId !== landed), + { state: 'approved' }, + now, + db + ); +} diff --git a/apps/board/src/latch/latch-state.ts b/apps/board/src/latch/latch-state.ts new file mode 100644 index 0000000000..be922c2235 --- /dev/null +++ b/apps/board/src/latch/latch-state.ts @@ -0,0 +1,182 @@ +import { Database } from 'bun:sqlite'; + +import { getStateDb } from '../state/index.ts'; + +export type LatchPhase = 'armed' | 'queued' | 'running' | 'error' | 'spent'; +export type WaitReason = + 'next-sweep' | 'cooldown' | 'budget' | 'review-in-flight'; + +export interface LatchRow { + mrUrl: string; + discussionId: string; + rootNoteId: number; + phase: LatchPhase; + wait: WaitReason | null; + /** ms; the follow-up this latch waits on started at or after this. */ + launchAt: number | null; + failures: number; + stuck: boolean; + /** variantKey of the banner last written to the note. */ + variant: string | null; + /** The reply this latch still owes its discussion, verbatim. GitLab emails + new notes, never edits, so the reply is the author's only notice. */ + replyDue: string | null; + updatedAt: number; +} + +interface LatchRecord { + mr_url: string; + discussion_id: string; + root_note_id: number; + phase: LatchPhase; + wait: WaitReason | null; + launch_at: number | null; + failures: number; + stuck: number; + variant: string | null; + reply_due: string | null; + updated_at: number; +} + +const COLUMNS: Record, string> = { + discussionId: 'discussion_id', + rootNoteId: 'root_note_id', + phase: 'phase', + wait: 'wait', + launchAt: 'launch_at', + failures: 'failures', + stuck: 'stuck', + variant: 'variant', + replyDue: 'reply_due', + updatedAt: 'updated_at', +}; + +function toRow(r: LatchRecord): LatchRow { + return { + mrUrl: r.mr_url, + discussionId: r.discussion_id, + rootNoteId: r.root_note_id, + phase: r.phase, + wait: r.wait, + launchAt: r.launch_at, + failures: r.failures, + stuck: r.stuck !== 0, + variant: r.variant, + replyDue: r.reply_due, + updatedAt: r.updated_at, + }; +} + +export function readLatchRow( + mrUrl: string, + db: Database = getStateDb() +): LatchRow | null { + const r = db + .query('SELECT * FROM latch_state WHERE mr_url = ?') + .get(mrUrl) as LatchRecord | null; + return r ? toRow(r) : null; +} + +export function readLatchRows(db: Database = getStateDb()): LatchRow[] { + return ( + db.query('SELECT * FROM latch_state ORDER BY mr_url').all() as LatchRecord[] + ).map(toRow); +} + +/** Inserts or replaces the row; for adoption and first post only. */ +export function putLatchRow(row: LatchRow, db: Database = getStateDb()): void { + db.run( + `INSERT OR REPLACE INTO latch_state + (mr_url, discussion_id, root_note_id, phase, wait, launch_at, + failures, stuck, variant, reply_due, updated_at) + VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, + [ + row.mrUrl, + row.discussionId, + row.rootNoteId, + row.phase, + row.wait, + row.launchAt, + row.failures, + row.stuck ? 1 : 0, + row.variant, + row.replyDue, + row.updatedAt, + ] + ); +} + +/** Clears the reply owed, only while the row still owes that same reply; true + when it cleared. Not guarded on the discussion: a re-point between a post + and this clear must not leave the reply owed to the new copy. */ +export function clearReplyDue( + mrUrl: string, + body: string, + db: Database = getStateDb() +): boolean { + const result = db.run( + `UPDATE latch_state SET reply_due = NULL + WHERE mr_url = ? AND reply_due = ?`, + [mrUrl, body] + ); + return result.changes > 0; +} + +/** Applies `patch` only while the row's phase is in `from` (and, with + `discussionId`, only while the row tracks that latch); true when it moved. */ +export function casLatch( + mrUrl: string, + from: LatchPhase[], + patch: Partial>, + now: number, + db: Database = getStateDb(), + opts: { discussionId?: string } = {} +): boolean { + if (from.length === 0) return false; + const sets: string[] = []; + const values: Array = []; + for (const key of Object.keys(COLUMNS) as Array) { + if (key === 'updatedAt' || !(key in patch)) continue; + const value = patch[key]; + if (value === undefined) continue; + sets.push(`${COLUMNS[key]} = ?`); + values.push(typeof value === 'boolean' ? (value ? 1 : 0) : (value ?? null)); + } + sets.push('updated_at = ?'); + values.push(now); + const marks = from.map(() => '?').join(', '); + const guard = opts.discussionId === undefined ? '' : ' AND discussion_id = ?'; + const guardValues = + opts.discussionId === undefined ? [] : [opts.discussionId]; + const result = db.run( + `UPDATE latch_state SET ${sets.join(', ')} + WHERE mr_url = ? AND phase IN (${marks})${guard}`, + [...values, mrUrl, ...from, ...guardValues] + ); + return result.changes > 0; +} + +export function cachedUpload( + mrUrl: string, + variantKey: string, + db: Database = getStateDb() +): string | null { + const r = db + .query( + 'SELECT markdown FROM latch_uploads WHERE mr_url = ? AND variant = ?' + ) + .get(mrUrl, variantKey) as { markdown: string } | null; + return r ? r.markdown : null; +} + +export function rememberUpload( + mrUrl: string, + variantKey: string, + markdown: string, + db: Database = getStateDb() +): void { + db.run( + 'INSERT OR REPLACE INTO latch_uploads (mr_url, variant, markdown) VALUES (?, ?, ?)', + [mrUrl, variantKey, markdown] + ); +} diff --git a/apps/board/src/latch/markers.ts b/apps/board/src/latch/markers.ts index 2038f7ff1a..34d89f3639 100644 --- a/apps/board/src/latch/markers.ts +++ b/apps/board/src/latch/markers.ts @@ -5,47 +5,75 @@ import { LATCH_MARKER, + LATCH_MARKER_ERROR, + LATCH_MARKER_QUEUED, + LATCH_MARKER_RUNNING, LATCH_MARKER_SPENT, latchKindOf, type LatchKind, } from '@mattstack/rt-client'; -export { LATCH_MARKER, LATCH_MARKER_SPENT, latchKindOf }; +export { + LATCH_MARKER, + LATCH_MARKER_ERROR, + LATCH_MARKER_QUEUED, + LATCH_MARKER_RUNNING, + LATCH_MARKER_SPENT, + latchKindOf, +}; export type { LatchKind }; -const ARMED_COPY = [ +export const ARMED_COPY = [ "**Addressed everything?** Resolve this thread and I'll take another pass over the MR.", '', "Leave it open while there's still work in flight.", ].join('\n'); -/** Why a latch was spent -- the wording differs because only one of these is - a real reviewer verdict. "approved" is the terminal outcome; "duplicate" - is an extra copy going defunct because another latch on the same MR - already carries the live state, which must never read as an approval - that did not happen. */ -export type SpentReason = 'approved' | 'duplicate'; - -const SPENT_COPY = +export const SPENT_COPY = 'Approved, so this latch is spent. Nothing further to do here.'; -const DUPLICATE_COPY = +export const DUPLICATE_COPY = 'Superseded by a newer latch on this MR; nothing to do here.'; +// Typed by LatchKind, not latch-state's LatchPhase: the client bundle reaches +// this file, and latch-state pulls in bun:sqlite. +const PHASE_MARKER: Record = { + armed: LATCH_MARKER, + queued: LATCH_MARKER_QUEUED, + running: LATCH_MARKER_RUNNING, + error: LATCH_MARKER_ERROR, + spent: LATCH_MARKER_SPENT, +}; + +export function latchBody( + phase: LatchKind, + imageMarkdown: string, + sentence: string +): string { + return `${PHASE_MARKER[phase]}\n\n${imageMarkdown}\n\n${sentence}\n`; +} + export function armedLatchBody(imageMarkdown: string): string { - return `${LATCH_MARKER}\n\n${imageMarkdown}\n\n${ARMED_COPY}\n`; + return latchBody('armed', imageMarkdown, ARMED_COPY); } -export function spentLatchBody( - imageMarkdown: string, - reason: SpentReason = 'approved' +export function spentLatchBody(imageMarkdown: string): string { + return latchBody('spent', imageMarkdown, SPENT_COPY); +} + +/** GitLab stretches an unsized image to the column; 520 CSS px shows the + 1040 px banner at 2x. */ +export function imageMarkdownFor( + title: string, + markdownFromUpload: string ): string { - const copy = reason === 'duplicate' ? DUPLICATE_COPY : SPENT_COPY; - return `${LATCH_MARKER_SPENT}\n\n${imageMarkdown}\n\n${copy}\n`; + const url = + markdownFromUpload.match(/\]\(([^)]+)\)/)?.[1] ?? markdownFromUpload; + return `![${title}](${url}){width=520}`; } -/** The banner's markdown image, pulled back out of a latch body so the spend - can reuse the uploaded path instead of uploading the banner a second time. */ +/** The banner's markdown image, pulled back out of a latch body. Matches the + sized GIF form and the older unsized PNG. */ export function imageMarkdownOf(body: string): string | null { - const m = body.match(/!\[[^\]]*\]\([^)]+\)/); + const m = body.match(/!\[[^\]]*\]\([^)]+\)(?:\{width=\d+\})?/); return m ? m[0] : null; } diff --git a/apps/board/src/latch/post.ts b/apps/board/src/latch/post.ts index 99c991bc30..6697fcf947 100644 --- a/apps/board/src/latch/post.ts +++ b/apps/board/src/latch/post.ts @@ -2,14 +2,20 @@ * The latch's GitLab writes, behind one injected gateway so the pass and the * server share them and tests need no network. */ -import { latchBannerPng } from './banner.ts'; +import type { Database } from 'bun:sqlite'; + +import { getStateDb } from '../state/index.ts'; +import { latchBannerGif } from './banner.ts'; import type { LatchRef } from './discussions.ts'; import { - armedLatchBody, - imageMarkdownOf, - spentLatchBody, - type SpentReason, -} from './markers.ts'; + cachedUpload, + casLatch, + clearReplyDue, + rememberUpload, + type LatchPhase, +} from './latch-state.ts'; +import { imageMarkdownFor, latchBody } from './markers.ts'; +import { copyFor, variantKey, type BannerVariant } from './variants.ts'; export interface LatchGateway { uploadFile( @@ -47,22 +53,113 @@ export interface LatchGateway { ): Promise<{ id: number }>; } -/** Arm a fresh latch: upload this MR's banner, then open a resolvable thread. */ +export interface LatchTarget { + projectId: number; + projectPath: string; + iid: number; + mrUrl: string; + discussionId: string; + rootNoteId: number; +} + +/** Posts the reply a row owes its latch's discussion, then clears it. */ +export async function postReplyDue( + gw: LatchGateway, + mr: Pick, + discussionId: string, + body: string, + db: Database = getStateDb() +): Promise { + await gw.createNote(mr.projectId, mr.iid, body, discussionId); + clearReplyDue(mr.mrUrl, body, db); +} + +/** This MR's banner for `variant`, uploaded only the first time the MR shows it. */ +export async function bannerMarkdown( + gw: LatchGateway, + projectId: number, + mrUrl: string, + iid: number, + variant: BannerVariant, + db: Database = getStateDb() +): Promise { + const key = variantKey(variant); + const cached = cachedUpload(mrUrl, key, db); + if (cached) return cached; + const up = await gw.uploadFile( + projectId, + `latch-${iid}-${key}.gif`, + latchBannerGif(mrUrl, variant), + 'image/gif' + ); + const markdown = imageMarkdownFor(copyFor(variant).title, up.markdown); + rememberUpload(mrUrl, key, markdown, db); + return markdown; +} + +async function writeNote( + gw: LatchGateway, + t: Pick, + phase: LatchPhase, + variant: BannerVariant, + db: Database +): Promise { + const img = await bannerMarkdown( + gw, + t.projectId, + t.mrUrl, + t.iid, + variant, + db + ); + const body = latchBody(phase, img, copyFor(variant).sentence); + await gw.updateNote(t.projectId, t.iid, t.rootNoteId, body); +} + +/** + * Show `phase` on the note with `variant`'s banner, then change the thread. + * Body first: a crash between the two leaves the phase visible on the note, + * and the row decides recovery. + */ +export async function rewriteLatch( + gw: LatchGateway, + t: LatchTarget, + phase: LatchPhase, + variant: BannerVariant, + thread: 'resolve' | 'unresolve' | 'keep', + now: number = Date.now(), + db: Database = getStateDb() +): Promise { + await writeNote(gw, t, phase, variant, db); + casLatch(t.mrUrl, [phase], { variant: variantKey(variant) }, now, db, { + discussionId: t.discussionId, + }); + if (thread === 'resolve') + await gw.resolveDiscussion(t.projectPath, t.iid, t.discussionId); + else if (thread === 'unresolve') + await gw.unresolveDiscussion(t.projectPath, t.iid, t.discussionId); +} + +/** Arm a fresh latch: upload this MR's banner, then open a resolvable thread. + The caller writes the latch row from the returned ids. */ export async function postLatch( gw: LatchGateway, projectId: number, _projectPath: string, mrUrl: string, - iid: number -): Promise { - const png = latchBannerPng(mrUrl); - const up = await gw.uploadFile( + iid: number, + db: Database = getStateDb() +): Promise<{ discussionId: string; rootNoteId: number }> { + const variant: BannerVariant = { state: 'armed' }; + const img = await bannerMarkdown(gw, projectId, mrUrl, iid, variant, db); + const d = await gw.createDiscussion( projectId, - `latch-${iid}.png`, - png, - 'image/png' + iid, + latchBody('armed', img, copyFor(variant).sentence) ); - await gw.createDiscussion(projectId, iid, armedLatchBody(up.markdown)); + const root = d.notes[0]; + if (!root) throw new Error(`latch post on !${iid} returned no root note`); + return { discussionId: d.id, rootNoteId: root.id }; } /** @@ -72,14 +169,20 @@ export async function postLatch( * spent-but-unresolved latch, which the pass repairs by re-resolving. The * reverse order leaves a resolved-but-unspent latch, which reads as a human * request and costs a dispatch nobody asked for. + * + * The note is written whether or not this call moved the row: a caller may + * already have moved it to spent. */ export async function spendLatch( gw: LatchGateway, projectId: number, projectPath: string, + mrUrl: string, iid: number, latch: LatchRef, - reason: SpentReason = 'approved' + variant: BannerVariant, + now: number = Date.now(), + db: Database = getStateDb() ): Promise { if (latch.kind === 'spent') { // Idempotent: an already-spent latch is left alone, except for the crash @@ -88,28 +191,57 @@ export async function spendLatch( await gw.resolveDiscussion(projectPath, iid, latch.discussionId); return; } - const img = imageMarkdownOf(latch.body); - const body = spentLatchBody(img ?? '', reason); - await gw.updateNote(projectId, iid, latch.rootNoteId, body); + // The guard keeps a duplicate's spend off the row, which tracks one latch. + const key = variantKey(variant); + const guard = { discussionId: latch.discussionId }; + const moved = casLatch( + mrUrl, + ['armed', 'queued', 'running', 'error'], + { phase: 'spent', variant: key }, + now, + db, + guard + ); + if (!moved) casLatch(mrUrl, ['spent'], { variant: key }, now, db, guard); + await writeNote( + gw, + { projectId, iid, mrUrl, rootNoteId: latch.rootNoteId }, + 'spent', + variant, + db + ); await gw.resolveDiscussion(projectPath, iid, latch.discussionId); } /** Terminal disposal of every latch copy found on an MR, deduped by - discussion id. Every copy shares the same reason: whatever made the + discussion id. Every copy shares the same variant: whatever made the canonical latch terminal (an approval, most often) applies to the whole set, not just the newest one. */ export async function spendAllLatches( gw: LatchGateway, projectId: number, projectPath: string, + mrUrl: string, iid: number, latches: LatchRef[], - reason: SpentReason = 'approved' + variant: BannerVariant, + now: number = Date.now(), + db: Database = getStateDb() ): Promise { const seen = new Set(); for (const latch of latches) { if (seen.has(latch.discussionId)) continue; seen.add(latch.discussionId); - await spendLatch(gw, projectId, projectPath, iid, latch, reason); + await spendLatch( + gw, + projectId, + projectPath, + mrUrl, + iid, + latch, + variant, + now, + db + ); } } diff --git a/apps/board/src/latch/review-step.ts b/apps/board/src/latch/review-step.ts index 7299dc872b..023647ab45 100644 --- a/apps/board/src/latch/review-step.ts +++ b/apps/board/src/latch/review-step.ts @@ -1,15 +1,30 @@ /** - * What a finished review does to its reviewer's latch: a comment outcome arms - * one, an approve outcome spends every copy. Only latches `self` posted are - * read or touched, so reviewers on the same MR never block or spend each - * other's. + * What a finished review does to its reviewer's latch: it lands the follow-up + * a running latch waits on, a comment outcome arms a fresh latch, an approve + * outcome spends every copy. Only latches `self` posted are read or touched, + * so reviewers on the same MR never block or spend each other's. */ +import type { Database } from 'bun:sqlite'; + import type { MRDetail } from '@mattstack/glance'; -import { findLatches, hasArmedLatch } from './discussions.ts'; -import { postLatch, spendAllLatches, type LatchGateway } from './post.ts'; +import { getStateDb } from '../state/index.ts'; +import { findLatches, hasLiveLatch } from './discussions.ts'; +import { landFollowUp, spendForApproval } from './land.ts'; +import { putLatchRow, readLatchRow } from './latch-state.ts'; +import { postLatch, type LatchGateway } from './post.ts'; export interface ReviewLatchStep { - outcome: 'comment' | 'approve'; + /** null: the review ended done with no verdict (an abandoned post gate). */ + outcome: 'comment' | 'approve' | null; + /** board.reReview: whether a comment may arm a fresh latch. Landing a + follow-up and spending never depend on it. */ + arm: boolean; + /** runStamp of the finished review; null when the lane no longer reads + done, so this signal cannot vouch for the run and nothing lands. */ + reviewRunStartedAt: number | null; + /** The reviewer's discussions created at or after `launchAt`, fresh from + GitLab; null when they cannot be read. */ + countNew: (launchAt: number) => Promise; self: string; /** Usernames GitLab lists as approvers of the MR. */ approvedBy: string[]; @@ -19,34 +34,100 @@ export interface ReviewLatchStep { projectPath: string; mrUrl: string; iid: number; + now?: number; + /** The board's state db; the default is the live one. */ + db?: Database; } export async function applyReviewLatch( s: ReviewLatchStep -): Promise<'posted' | 'spent' | 'none'> { +): Promise<'posted' | 'spent' | 'landed' | 'none'> { + const db = s.db ?? getStateDb(); + const now = s.now ?? Date.now(); const latches = findLatches(s.detail, s.self); + const mr = { + projectId: s.projectId, + projectPath: s.projectPath, + mrUrl: s.mrUrl, + iid: s.iid, + }; + const row = readLatchRow(s.mrUrl, db); + if ( + row && + (row.phase === 'running' || row.phase === 'error') && + s.reviewRunStartedAt !== null + ) { + const launchAt = row.launchAt; + const landed = await landFollowUp( + { + target: { + ...mr, + discussionId: row.discussionId, + rootNoteId: row.rootNoteId, + }, + outcome: s.outcome, + reviewRunStartedAt: s.reviewRunStartedAt, + gateway: s.gateway, + self: s.self, + countNew: () => + launchAt === null ? Promise.resolve(null) : s.countNew(launchAt), + now, + latches, + }, + db + ); + if (landed === 'landed') return 'landed'; + } if (s.outcome === 'approve') { // Every copy, not just the canonical one: an armed duplicate left behind // here is unreachable to the triage pass's repair step once the canon it // stops at is spent. if (latches.length === 0) return 'none'; - await spendAllLatches( + await spendForApproval( s.gateway, - s.projectId, - s.projectPath, - s.iid, - latches + mr, + latches, + readLatchRow(s.mrUrl, db), + now, + db ); return 'spent'; } + if (s.outcome !== 'comment' || !s.arm) return 'none'; // A standing GitLab approval from this reviewer makes the triage pass spend // any armed latch of theirs on its next tick, so posting one here would // only show the author a latch that turns into an approval at once. const self = s.self.toLowerCase(); if (s.approvedBy.some(u => u.toLowerCase() === self)) return 'none'; // A spent latch must never suppress a fresh post, or the feature disables - // itself forever the first time a latch is ever spent. - if (hasArmedLatch(latches)) return 'none'; - await postLatch(s.gateway, s.projectId, s.projectPath, s.mrUrl, s.iid); + // itself forever the first time a latch is ever spent. A live row does: + // the discussion read can lag the row's latch. + if (hasLiveLatch(latches)) return 'none'; + const live = readLatchRow(s.mrUrl, db); + if (live && live.phase !== 'spent') return 'none'; + const { discussionId, rootNoteId } = await postLatch( + s.gateway, + s.projectId, + s.projectPath, + s.mrUrl, + s.iid, + db + ); + putLatchRow( + { + mrUrl: s.mrUrl, + discussionId, + rootNoteId, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: now, + }, + db + ); return 'posted'; } diff --git a/apps/board/src/latch/variants.ts b/apps/board/src/latch/variants.ts new file mode 100644 index 0000000000..5037828fe4 --- /dev/null +++ b/apps/board/src/latch/variants.ts @@ -0,0 +1,212 @@ +/** + * Every banner the latch can show, keyed so each one maps to a committed + * text strip (assets/latch/.png), plus the copy painted on the strip + * and the plain sentence posted under it. + */ + +import type { WaitReason } from './latch-state.ts'; +import { ARMED_COPY, DUPLICATE_COPY, SPENT_COPY } from './markers.ts'; + +export type BannerState = + | 'armed' + | 'queued' + | 'running' + | 'error-retrying' + | 'error-stuck' + | 'done-comments' + | 'done-approved' + | 'approved' + | 'superseded'; + +export interface BannerVariant { + state: BannerState; + wait?: WaitReason | null; + count?: number | null; +} + +export type Indicator = 'none' | 'dots' | 'ring'; + +export interface VariantCopy { + title: string; + sub: string; + accent: string; + indicator: Indicator; + sentence: string; +} + +const STATES: BannerState[] = [ + 'armed', + 'queued', + 'running', + 'error-retrying', + 'error-stuck', + 'done-comments', + 'done-approved', + 'approved', + 'superseded', +]; + +const QUEUED_SUB: Record = { + 'next-sweep': 'Starts on the next sweep', + cooldown: 'Waiting out the cooldown', + budget: 'Daily limit hit; starts tomorrow', + 'review-in-flight': 'Waiting for the running review', +}; + +const RETRY_SUB: Partial> = { + 'next-sweep': 'Retrying on the next sweep', + cooldown: 'Retrying after the cooldown', + budget: 'Daily limit hit; retrying tomorrow', +}; + +const WAITS = Object.keys(QUEUED_SUB) as WaitReason[]; +const RETRY_WAITS = Object.keys(RETRY_SUB) as WaitReason[]; + +const MAX_COUNT = 20; + +/** The indicator's dots, in 2x px: each dot is DOT_PX square, DOT_GAP_PX apart. */ +export const DOT_PX = 8; +export const DOT_GAP_PX = 8; + +function cleanCount(count: number | null | undefined): number | null { + if (count == null || !Number.isFinite(count)) return null; + const n = Math.floor(count); + return n > 0 ? n : null; +} + +function countSlug(raw: number | null | undefined): string { + const count = cleanCount(raw); + if (count == null) return 'none'; + if (count > MAX_COUNT) return '20plus'; + return String(count); +} + +export function variantKey(v: BannerVariant): string { + switch (v.state) { + case 'queued': + return `queued-${v.wait ?? 'next-sweep'}`; + case 'error-retrying': + return `error-retrying-${v.wait && RETRY_SUB[v.wait] ? v.wait : 'next-sweep'}`; + case 'done-comments': + return `done-comments-${countSlug(v.count)}`; + default: + return v.state; + } +} + +function allVariants(): BannerVariant[] { + const out: BannerVariant[] = []; + for (const state of STATES) { + if (state === 'queued') { + for (const wait of WAITS) out.push({ state, wait }); + } else if (state === 'error-retrying') { + for (const wait of RETRY_WAITS) out.push({ state, wait }); + } else if (state === 'done-comments') { + for (let n = 1; n <= MAX_COUNT + 1; n++) out.push({ state, count: n }); + out.push({ state, count: null }); + } else { + out.push({ state }); + } + } + return out; +} + +const BY_KEY = new Map(allVariants().map(v => [variantKey(v), v])); + +/** Stable order: BannerState order, then waits, then counts 1..20, 20plus, none. */ +export function allVariantKeys(): string[] { + return [...BY_KEY.keys()]; +} + +export function variantOfKey(key: string): BannerVariant | null { + const v = BY_KEY.get(key); + return v ? { ...v } : null; +} + +function doneCommentsSub(raw: number | null | undefined): string { + const count = cleanCount(raw); + if (count == null) return 'Review posted. Resolve when ready'; + if (count === 1) return '1 new comment. Resolve when ready'; + if (count > MAX_COUNT) return '20+ new comments. Resolve when ready'; + return `${count} new comments. Resolve when ready`; +} + +export function copyFor(v: BannerVariant): VariantCopy { + switch (v.state) { + case 'armed': + return { + title: 'Ready for another pass?', + sub: 'Resolve this thread to ask', + accent: '#f08fb0', + indicator: 'none', + sentence: ARMED_COPY, + }; + case 'queued': + return { + title: 'Follow-up review queued', + sub: QUEUED_SUB[v.wait ?? 'next-sweep'], + accent: '#e6b860', + indicator: 'dots', + sentence: "Follow-up review requested. I'll start it as soon as I can.", + }; + case 'running': + return { + title: 'Follow-up review running', + sub: 'Results post here when done', + accent: '#7fbfe8', + indicator: 'ring', + sentence: + "Follow-up review in progress. I'll reply here when it's done.", + }; + case 'error-retrying': + return { + title: 'Follow-up review hit a snag', + sub: (v.wait && RETRY_SUB[v.wait]) || 'Retrying on the next sweep', + accent: '#f2917e', + indicator: 'dots', + sentence: "The follow-up review didn't finish. I'll try again.", + }; + case 'error-stuck': + return { + title: 'Follow-up review stuck', + sub: 'Reviewer notified', + accent: '#f2917e', + indicator: 'none', + sentence: + "The follow-up review didn't finish after 3 tries. The reviewer has been told.", + }; + case 'done-comments': + return { + title: 'Follow-up review done', + sub: doneCommentsSub(v.count), + accent: '#b9a0f2', + indicator: 'none', + sentence: + "Follow-up review done. Resolve this thread again when you've addressed the new comments.", + }; + case 'done-approved': + return { + title: 'Follow-up review done', + sub: 'Approved. Nothing more to do', + accent: '#86cfa0', + indicator: 'none', + sentence: 'Follow-up review done and approved, so this latch is spent.', + }; + case 'approved': + return { + title: 'Approved', + sub: 'Nothing more to do', + accent: '#86cfa0', + indicator: 'none', + sentence: SPENT_COPY, + }; + case 'superseded': + return { + title: 'Superseded', + sub: 'A newer latch is live', + accent: '#8e88a0', + indicator: 'none', + sentence: DUPLICATE_COPY, + }; + } +} diff --git a/apps/board/src/server.ts b/apps/board/src/server.ts index d5da31894f..c892965f1b 100644 --- a/apps/board/src/server.ts +++ b/apps/board/src/server.ts @@ -9,6 +9,7 @@ import { import { shellHandoff } from '@mattstack/app-server/shell-handoff'; import { GitLabProvider, + MRDetailFetcher, NoteMutator, parseRepoId, ReadBackFailedError, @@ -185,6 +186,8 @@ import { } from './herdr.ts'; import { reviewerLatches } from './latch/discussions.ts'; import { latchGateway } from './latch/gateway.ts'; +import { fetchNewDiscussionCount } from './latch/land.ts'; +import { readLatchRow } from './latch/latch-state.ts'; import { acceptedReReview, isStaleSignal, @@ -395,6 +398,7 @@ import { parseTriageBlock, type TriageConfig, } from './triage/config.ts'; +import { runStamp } from './triage/latch.ts'; import { attachStandDown, clearHandoffs, @@ -4904,24 +4908,29 @@ async function handleAgentSignal( kickOutbox(pc); } } - // Arm a latch when a review lands with a comment outcome, spend it when - // one lands approved. Best-effort, like every other side effect here: - // the triage latch pass reconciles anything a down or throwing board - // misses, so a failure must never fail the agent's status write. + // Land the follow-up a running latch waits on, arm a latch when a review + // lands with a comment outcome, spend it when one lands approved. + // Best-effort, like every other side effect here: the triage latch pass + // reconciles anything a down or throwing board misses, so a failure must + // never fail the agent's status write. if (signal.kind === 'review' && signal.status === 'done' && gitlabToken) { try { - // Arming honours board.reReview; spending never does, since a latch - // left armed on a team that switched re-review off is a promise - // nothing keeps. + // Arming honours board.reReview; landing and spending never do, since + // a latch left running or armed on a team that switched re-review off + // is a promise nothing keeps. const outcome = - signal.outcome === 'approve' - ? 'approve' - : signal.outcome === 'comment' && loadReReviewConfig().enabled - ? 'comment' - : null; - const snapshot = outcome ? await cache.get() : null; + signal.outcome === 'approve' || signal.outcome === 'comment' + ? signal.outcome + : null; + const arm = loadReReviewConfig().enabled; + const row = readLatchRow(signal.mrUrl); + const landing = + !!row && (row.phase === 'running' || row.phase === 'error'); + const acts = + landing || outcome === 'approve' || (outcome === 'comment' && arm); + const snapshot = acts ? await cache.get() : null; const mr = snapshot?.mrs.find(m => m.webUrl === signal.mrUrl); - if (outcome && mr) { + if (acts && mr) { // Latches belong to the reviewer whose token posted them. With no // resolvable identity this board cannot tell its own apart, so it // leaves the work to the triage pass rather than guess. @@ -4934,13 +4943,33 @@ async function handleAgentSignal( `latch step skipped for ${signal.mrUrl}: no gitlab identity for this token` ); } else if (detail) { + const projectId = parseRepoId(mr.repositoryId); + // A lane no longer reading done was relaunched after this signal + // was emitted, and one done with another outcome is a later run + // than this replayed event: either way the signal cannot vouch for + // the run the latch waits on. + const lane = readReviewStates().get(signal.mrUrl); + const vouched = + lane?.status === 'done' && (lane.outcome ?? null) === outcome; await applyReviewLatch({ outcome, + arm, + reviewRunStartedAt: vouched ? runStamp(lane) : null, + countNew: launchAt => + fetchNewDiscussionCount( + () => + new MRDetailFetcher( + config.gitlabHost, + gitlabToken + ).fetchDetail(projectId, mr.iid), + self, + launchAt + ), self, approvedBy: mr.reviews.approvedBy.map(r => r.username), detail, gateway: latchGateway(config.gitlabHost, gitlabToken), - projectId: parseRepoId(mr.repositoryId), + projectId, projectPath: projectPathFromWebUrl(signal.mrUrl, config.gitlabHost) ?? '', mrUrl: signal.mrUrl, diff --git a/apps/board/src/state/db.ts b/apps/board/src/state/db.ts index fe03cb49c2..6c3509c018 100644 --- a/apps/board/src/state/db.ts +++ b/apps/board/src/state/db.ts @@ -8,7 +8,7 @@ import { getKvValue } from './kv-blob.ts'; import { importLegacyState } from './legacy-import.ts'; export type DbFlavor = 'server' | 'cli'; -export const SCHEMA_VERSION = 6; +export const SCHEMA_VERSION = 7; const BUSY_TIMEOUT_MS: Record = { server: 250, cli: 5000 }; const MIGRATION_BUSY_TIMEOUT_MS = 5000; @@ -163,6 +163,29 @@ const MIGRATIONS: Migration[] = [ if (!cols.some(c => c.name === 'outcome')) db.run('ALTER TABLE respond_rounds ADD COLUMN outcome TEXT'); }, + // v7: the re-review latch's record (one row per MR, since this board is one + // reviewer) and the banner uploads already made per variant. + db => { + db.run(`CREATE TABLE IF NOT EXISTS latch_state ( + mr_url TEXT PRIMARY KEY, + discussion_id TEXT NOT NULL, + root_note_id INTEGER NOT NULL, + phase TEXT NOT NULL, + wait TEXT, + launch_at INTEGER, + failures INTEGER NOT NULL DEFAULT 0, + stuck INTEGER NOT NULL DEFAULT 0, + variant TEXT, + reply_due TEXT, + updated_at INTEGER NOT NULL +)`); + db.run(`CREATE TABLE IF NOT EXISTS latch_uploads ( + mr_url TEXT NOT NULL, + variant TEXT NOT NULL, + markdown TEXT NOT NULL, + PRIMARY KEY (mr_url, variant) +)`); + }, ]; // SCHEMA_VERSION is the public constant other modules reason about; diff --git a/apps/board/src/triage/latch.ts b/apps/board/src/triage/latch.ts index c99a629bf2..48f426e6c2 100644 --- a/apps/board/src/triage/latch.ts +++ b/apps/board/src/triage/latch.ts @@ -1,31 +1,63 @@ /** - * The latch pass: read every done review state's MR, and act on the latch. + * The latch pass: read every MR whose review is done, whose commented review + * was pruned, or whose latch row is not spent, and act on the latch. * * Branch order is the design's safety property, not a style choice. The spent * check is unconditional and runs first, so no board-made resolve can ever be * read back as a human request, whatever the MR's approval state does * afterwards. + * + * The latch row is the record and the note is what people see. Every + * transition moves the row first and rewrites the note after, so a stale + * discussion read still showing an older note never re-requests or clobbers a + * latch the row has already moved on. */ +import type { Database } from 'bun:sqlite'; + import type { MRDetail } from '@mattstack/glance'; import { canonicalLatch, findLatches, - hasArmedLatch, + hasLiveLatch, requestCarriers, type LatchRef, } from '../latch/discussions.ts'; +import { landFollowUp, spendForApproval } from '../latch/land.ts'; +import { + casLatch as casLatchIn, + clearReplyDue, + putLatchRow as putLatchRowIn, + readLatchRow as readLatchRowIn, + type LatchPhase, + type LatchRow, + type WaitReason, +} from '../latch/latch-state.ts'; import { postLatch, - spendAllLatches, + postReplyDue, + rewriteLatch, spendLatch, type LatchGateway, + type LatchTarget, } from '../latch/post.ts'; +import { + copyFor, + variantKey, + variantOfKey, + type BannerVariant, +} from '../latch/variants.ts'; import type { ReReviewLaunch } from '../review-launch.ts'; import type { ReviewState } from '../review-state.ts'; import type { AuditEntry } from './audit.ts'; import type { ReReviewConfig, TriageConfig } from './config.ts'; -import { emptyMrMemory, rollDay, type DispatchMemory } from './memory.ts'; -import { decideRequest, plainReason } from './nudge.ts'; +import { + emptyMrMemory, + rollDay, + type DispatchMemory, + type MrMemory, +} from './memory.ts'; +import { notifyEscalation } from './notify.ts'; +import { decideRequest, type ReReviewRequest } from './nudge.ts'; export interface LatchMrFacts { mrUrl: string; @@ -42,11 +74,13 @@ export interface LatchMrFacts { approvedBySelf: boolean; } +type LatchPatch = Partial>; + export interface LatchPassDeps { readReviewStates(): Map; /** Tombstoned review rows (pruned while the MR was off the board). A - commented one whose MR is back in scope and still carries an armed - latch is resurrected; one whose latch is gone is dropped for good. */ + commented one whose MR is back in scope and still carries a live latch + is resurrected; one whose latch is gone is dropped for good. */ readPrunedReviewStates(): Map; /** False when the claim is lost (the row already went live again): the snapshot's tombstone is stale and must not drive a dispatch. */ @@ -66,18 +100,43 @@ export interface LatchPassDeps { reReview: ReReviewConfig; appendAudit(entry: AuditEntry): void; notify(title: string, message: string, mrUrl: string): Promise; + /** The reviewer's discussions on the MR created at or after `launchAt`, + fresh from GitLab; null when they cannot be read. Absent, a landing + shows the uncounted done banner. */ + countNew?(mr: LatchMrFacts, launchAt: number): Promise; + /** A stuck latch needs a person, so the default ignores `triage.notify` + and always sends the rt desktop notification. */ + notifyStuck?(title: string, message: string, mrUrl: string): Promise; now(): number; + /** The board's state db; the default is the live one. */ + db?: Database; + /** The latch row store; each defaults to the latch-state function on `db`. */ + readLatchRow?(mrUrl: string): LatchRow | null; + casLatch?( + mrUrl: string, + from: LatchPhase[], + patch: LatchPatch, + now: number, + opts?: { discussionId?: string } + ): boolean; + putLatchRow?(row: LatchRow): void; } export interface LatchPassResult { posted: number; dispatched: number; - rejected: number; + queued: number; spent: number; repaired: number; resurrected: number; skipped: number; failed: number; + /** Follow-ups this pass landed on their latch. */ + landed: number; + /** Error banners written this tick: failed attempts (stuck ones + included) and retry-wait changes. */ + errored: number; + stuck: number; } /** How long a freshly-done review is left to the server before this pass will @@ -85,13 +144,132 @@ export interface LatchPassResult { both writers check for an existing latch through the daemon's discussion store, which within its staleness window cannot show a post seconds old: posting here inside that window double-posts. A genuinely missed post - (server down or throwing) still lands on the first tick past the window. */ + (server down or throwing) still lands on the first tick past the window. + The same window guards the repair of a row the note has not caught up to. */ export const LATCH_POST_GRACE_MS = 5 * 60_000; -const DISPATCH_REPLY = - "Follow-up review started. I'll comment again when the pass is done, and this latch is armed for next time."; -const refusalReply = (reason: string) => - `Not yet: ${reason}. Resolve this thread again once that clears and I'll pick it up.`; +/** Failed attempts in one request cycle before the latch stops retrying. */ +export const LATCH_MAX_FAILURES = 3; + +/** How long an owed reply keeps being retried after the transition that owed + it; a failed retry never moves the row, so this measures from the + transition. */ +export const LATCH_REPLY_GIVE_UP_MS = 24 * 60 * 60_000; + +const STUCK: BannerVariant = { state: 'error-stuck' }; +const STUCK_REPLY = copyFor(STUCK).sentence; + +/** The wait a decision maps to, or null for a refusal that never clears by + itself. */ +export function waitReasonOf(decision: { + action: string; + reason: string; +}): WaitReason | null { + if (decision.action === 'dispatch') return 'next-sweep'; + switch (decision.reason) { + case 'cooldown': + return 'cooldown'; + case 'budget-exhausted': + return 'budget'; + case 'review-in-flight': + return 'review-in-flight'; + default: + return null; + } +} + +/** When the lane's current run began. `startedAt` is the lane's first-ever + write and never resets, so it cannot stand in for a run. */ +export function runStamp(r: ReviewState): number { + return r.runStartedAt ?? r.updatedAt; +} + +const IN_FLIGHT: ReadonlySet = new Set([ + 'queued', + 'running', + 'error', +]); + +export interface LatchScope { + rows: Pick[]; + states: Map; + pruned: Map; +} + +/** The MRs the latch pass reads, once each: every MR with a done review + state (approve ones too, so a half-finished spend is repaired), a + commented tombstone (the pass decides between resurrecting and dropping), + or a latch row that is not spent. A live row is owed an answer, a launch + or a landing whatever its review lane now reads: an armed row's request + can arrive while the lane reads error or reviewing. */ +export function latchInScope( + mrs: T[], + scope: LatchScope +): T[] { + const owed = new Set( + scope.rows.filter(r => r.phase !== 'spent').map(r => r.mrUrl) + ); + const seen = new Set(); + return mrs.filter(m => { + const url = m.webUrl; + if (!url || seen.has(url)) return false; + const tomb = scope.pruned.get(url); + const hit = + owed.has(url) || + scope.states.get(url)?.status === 'done' || + (tomb?.status === 'done' && tomb.outcome === 'comment'); + if (hit) seen.add(url); + return hit; + }); +} + +function inFlight(review: ReviewState | undefined): review is ReviewState { + return review?.status === 'queued' || review?.status === 'reviewing'; +} + +/** A run in flight is the follow-up only when it started at or after the + stamp: a queued row's request, or an error row's last launch. A run that + began before the request is an earlier review that cannot have seen the + author's fixes. An error row with no stamp never launched for this + request, so any run in flight is the reviewer's relaunch. */ +function followUpInFlight( + review: ReviewState | undefined, + phase: LatchPhase, + stamp: number | null +): review is ReviewState { + if (!inFlight(review)) return false; + if (stamp === null) return phase === 'error'; + return runStamp(review) >= stamp; +} + +interface Rows { + read(mrUrl: string): LatchRow | null; + cas( + mrUrl: string, + from: LatchPhase[], + patch: LatchPatch, + now: number, + opts?: { discussionId?: string } + ): boolean; + put(row: LatchRow): void; +} + +/** One MR's latch on one tick, past the spent and approval checks. */ +interface Tick { + deps: LatchPassDeps; + rows: Rows; + mr: LatchMrFacts; + canon: LatchRef; + carriers: LatchRef[]; + row: LatchRow; + review: ReviewState | undefined; + target: LatchTarget; + policy: TriageConfig; + notifyStuck: NonNullable; + dayStamp: string; + now: number; + result: LatchPassResult; +} export async function runLatchPass( deps: LatchPassDeps @@ -99,18 +277,32 @@ export async function runLatchPass( const result: LatchPassResult = { posted: 0, dispatched: 0, - rejected: 0, + queued: 0, spent: 0, repaired: 0, resurrected: 0, skipped: 0, failed: 0, + landed: 0, + errored: 0, + stuck: 0, }; if (!deps.reReview.enabled) return result; // decideRequest refuses with "disabled" on cfg.enabled, which is the // doctor/nudge switch. A team with those sweeps off but re-review on must // not see every resolved latch answered "Not yet: disabled". const policy: TriageConfig = { ...deps.cfg, enabled: true }; + const rows: Rows = { + read: deps.readLatchRow ?? (url => readLatchRowIn(url, deps.db)), + cas: + deps.casLatch ?? + ((url, from, patch, at, opts) => + casLatchIn(url, from, patch, at, deps.db, opts)), + put: deps.putLatchRow ?? (row => putLatchRowIn(row, deps.db)), + }; + const notifyStuck = + deps.notifyStuck ?? + ((title, message, url) => notifyEscalation(title, message, 'rt', { url })); const reviews = deps.readReviewStates(); const pruned = deps.readPrunedReviewStates(); @@ -123,6 +315,12 @@ export async function runLatchPass( // transient 500) must not abort the tick and starve every MR queued // after it while the condition lasts. try { + const stored = rows.read(mr.mrUrl); + // A live row is followed whatever its lane reads: the lane moves + // through queued, reviewing and error while the latch waits on it. A + // spent row that still owes a reply is followed until it posts. + const held = + !!stored && (stored.phase !== 'spent' || stored.replyDue !== null); const live = reviews.get(mr.mrUrl); // Only a commented tombstone is a resurrection candidate: an approve // outcome's latch is already spent-terminal, so reviving its row buys @@ -135,8 +333,9 @@ export async function runLatchPass( // A done state with no outcome records no verdict, so there is nothing to // arm and nothing to spend. decideRequest treats it the same way. if ( - (!live && !tomb) || - (live && (live.status !== 'done' || !live.outcome)) + !held && + ((!live && !tomb) || + (live && (live.status !== 'done' || !live.outcome))) ) { result.skipped++; continue; @@ -148,7 +347,7 @@ export async function runLatchPass( } const latches = findLatches(detail, deps.self); let review = live; - if (!review) { + if (!review && tomb) { // Zero discussions is indistinguishable from the daemon's // empty-but-ok answer for an unrecognized identity (see // LatchMrFacts.rtRepo), so the tombstone is kept for the next tick @@ -157,10 +356,10 @@ export async function runLatchPass( result.skipped++; continue; } - // The armed latch is the proof the tombstone still matters: without + // The live latch is the proof the tombstone still matters: without // one there is nothing a revived row could ever act on, and dropping // the tombstone keeps this MR out of every later tick's reads. - if (!hasArmedLatch(latches)) { + if (!hasLiveLatch(latches)) { deps.dropPrunedReviewState(mr.mrUrl); result.skipped++; continue; @@ -182,27 +381,50 @@ export async function runLatchPass( result.resurrected++; review = tomb; } - if (!review) { - result.skipped++; - continue; - } const canon = canonicalLatch(latches); // Step 0: nothing to act on. A spent relic with no live latch is the - // descoped case: arming a second review cycle is the server's job. + // descoped case: arming a second review cycle is the server's job. A + // row mid-request proves a latch exists the read cannot show yet. if (!canon) { + // The latch a reply is owed to is gone. An empty read can be the + // daemon's empty-but-ok answer, so only a read showing threads, or + // the give-up age, drops it. if ( + stored?.replyDue != null && + (detail.discussions.length > 0 || + now - stored.updatedAt > LATCH_REPLY_GIVE_UP_MS) + ) { + dropOwedReply(deps, mr, stored.replyDue, now); + } + if ( + !(stored && IN_FLIGHT.has(stored.phase)) && + review?.status === 'done' && review.outcome === 'comment' && !mr.approvedBySelf && now - review.updatedAt >= LATCH_POST_GRACE_MS ) { - await postLatch( + const { discussionId, rootNoteId } = await postLatch( deps.gateway, mr.projectId, mr.projectPath, mr.mrUrl, - mr.iid + mr.iid, + deps.db ); + rows.put({ + mrUrl: mr.mrUrl, + discussionId, + rootNoteId, + phase: 'armed', + wait: null, + launchAt: null, + failures: 0, + stuck: false, + variant: 'armed', + replyDue: null, + updatedAt: now, + }); deps.appendAudit({ ts: now, mrUrl: mr.mrUrl, @@ -217,6 +439,14 @@ export async function runLatchPass( continue; } + const row = trackCanon(deps, rows, mr, canon, stored, now); + if (!row) { + result.skipped++; + continue; + } + + await settleOwedReply(deps, rows, mr, canon, now); + // Step 1: spent wins over everything, unconditionally. if (canon.kind === 'spent') { if (!canon.resolved) { @@ -224,8 +454,12 @@ export async function runLatchPass( deps.gateway, mr.projectId, mr.projectPath, + mr.mrUrl, mr.iid, - canon + canon, + { state: 'approved' }, + now, + deps.db ); deps.appendAudit({ ts: now, @@ -241,37 +475,47 @@ export async function runLatchPass( continue; } - const carriers = requestCarriers(latches); + const target: LatchTarget = { + projectId: mr.projectId, + projectPath: mr.projectPath, + iid: mr.iid, + mrUrl: mr.mrUrl, + discussionId: canon.discussionId, + rootNoteId: canon.rootNoteId, + }; - // Step 2: armed and nobody has asked. Every duplicate gets spent here too: - // the canon alone would leave an older armed-unresolved duplicate stuck - // forever, since the next tick sees the now-spent canon and stops at step 1 - // before ever looking at it. - if (carriers.length === 0) { - if (review.outcome === 'approve' || mr.approvedBySelf) { - await spendAll(deps, mr, latches); - deps.appendAudit({ - ts: now, - mrUrl: mr.mrUrl, - iid: mr.iid, - event: 'latch', - action: 'spent', - }); - result.spent++; - } else { - result.skipped++; - } + // The landing backstop runs before the approval spend, so a follow-up + // that approved shows done-approved, and before the error handling, so + // a finished run is never retried into a second review. This + // reviewer's standing GitLab approval still beats a comment or + // abandoned outcome: step 2 spends that as a plain approval. + if ( + landable(row, review) && + (review.outcome === 'approve' || !mr.approvedBySelf) + ) { + await landBackstop(deps, mr, row, review, target, latches, result); continue; } - // Step 3: a human resolved a latch. This reviewer's own approval spends - // rather than dispatching, whether it came through a review or GitLab; - // anyone else's approval leaves the request standing. Every own latch, - // not just canon and the request carriers: an armed-unresolved extra - // left out here would strand live on the next tick, which stops at step - // 1 on the now-spent canon and never looks at it again. - if (mr.approvedBySelf || review.outcome === 'approve') { - await spendAll(deps, mr, latches); + // Step 2: this reviewer's own approval spends from every phase, whether + // it came through a review or GitLab; anyone else's approval leaves the + // latch standing. Every own latch, not just canon: an armed-unresolved + // extra left out here would strand live on the next tick, which stops + // at step 1 on the now-spent canon and never looks at it again. A row + // already reading spent is no proof the note is: the spend moves the + // row first, so this branch is also what heals a spend cut short. + if ( + mr.approvedBySelf || + (review?.status === 'done' && review.outcome === 'approve') + ) { + await spendForApproval( + deps.gateway, + mr, + latches, + rows.read(mr.mrUrl), + deps.now(), + deps.db + ); deps.appendAudit({ ts: now, mrUrl: mr.mrUrl, @@ -283,144 +527,734 @@ export async function runLatchPass( continue; } - const m = rollDay( - deps.memory.mrs[mr.mrUrl] ?? emptyMrMemory(dayStamp), - dayStamp - ); - deps.memory.mrs[mr.mrUrl] = m; - const decision = decideRequest( - { - mrUrl: mr.mrUrl, - iid: mr.iid, - source: 'latch', - receivedAt: null, - handled: false, - }, + const tick: Tick = { + deps, + rows, + mr, + canon, + carriers: requestCarriers(latches), + row, review, - m, + target, policy, - now + notifyStuck, + dayStamp, + now, + result, + }; + // Running and error rows are never a request, whatever the note shows: + // they wait on the run landing. + if (row.phase === 'armed') await armedLatch(tick); + else if (row.phase === 'queued') await queuedLatch(tick); + else if (row.phase === 'running') await runningLatch(tick); + else if (row.phase === 'error') await erroredLatch(tick); + else result.skipped++; + } catch (err) { + console.error( + `latch pass: !${mr.iid} (${mr.mrUrl}) failed: ${err instanceof Error ? err.message : err}` ); - deps.appendAudit({ - ts: now, - mrUrl: mr.mrUrl, - iid: mr.iid, - event: 'latch', - decision: decision.action, - reason: decision.reason, - attempt: m.attemptsToday + 1, - }); - - if (decision.action !== 'dispatch') { - await deps.gateway.createNote( - mr.projectId, - mr.iid, - refusalReply(decision.reason), - canon.discussionId - ); - await consume(deps, mr, canon, carriers); - await deps.notify( - `Follow-up review skipped on !${mr.iid}`, - plainReason(decision.reason, policy), - mr.mrUrl - ); - result.rejected++; - continue; - } + result.failed++; + } + } + return result; +} - const launch = await deps.launchReReview(mr.mrUrl, mr.iid); - if (launch.kind === 'error') { - await deps.gateway.createNote( - mr.projectId, - mr.iid, - refusalReply('the pane failed to start'), - canon.discussionId - ); - await consume(deps, mr, canon, carriers); - deps.appendAudit({ - ts: now, - mrUrl: mr.mrUrl, - iid: mr.iid, - event: 'latch', - action: 'launch-failed', - outcome: launch.message, - }); - result.rejected++; - continue; +/** Posts the reply a landing or stuck transition owes but failed to post. + At least once: a post that landed but whose response errored stays owed + and goes out again on a later tick. A failure is logged and the tick goes + on, so a reply GitLab keeps refusing never blocks the latch. */ +async function settleOwedReply( + deps: LatchPassDeps, + rows: Rows, + mr: LatchMrFacts, + canon: LatchRef, + now: number +): Promise { + const owing = rows.read(mr.mrUrl); + const body = owing?.replyDue; + if (!owing || body == null) return; + const age = now - owing.updatedAt; + // A spend moves the row without touching stuck, so a spent row can still + // read stuck while owing a stuck reply that no longer applies. + const staleStuck = + body === STUCK_REPLY && (!owing.stuck || owing.phase !== 'error'); + if (age > LATCH_REPLY_GIVE_UP_MS || staleStuck) { + dropOwedReply(deps, mr, body, now); + return; + } + // The server may still be posting a reply it owed seconds ago. + if (owing.discussionId !== canon.discussionId || age < LATCH_POST_GRACE_MS) + return; + try { + await postReplyDue(deps.gateway, mr, owing.discussionId, body, deps.db); + } catch (err) { + console.error( + `latch pass: !${mr.iid} owed reply not posted: ${err instanceof Error ? err.message : err}` + ); + return; + } + deps.appendAudit({ + ts: now, + mrUrl: mr.mrUrl, + iid: mr.iid, + event: 'latch', + action: 'replied', + }); +} + +function dropOwedReply( + deps: LatchPassDeps, + mr: LatchMrFacts, + body: string, + now: number +): void { + if (!clearReplyDue(mr.mrUrl, body, deps.db)) return; + deps.appendAudit({ + ts: now, + mrUrl: mr.mrUrl, + iid: mr.iid, + event: 'latch', + action: 'reply-dropped', + }); +} + +/** The row for the canonical latch: adopted from the note when there is + none, or re-pointed when a post race left it on an older copy. Null when + another writer moved the row since this tick read it. */ +function trackCanon( + deps: LatchPassDeps, + rows: Rows, + mr: LatchMrFacts, + canon: LatchRef, + stored: LatchRow | null, + now: number +): LatchRow | null { + if (stored && stored.discussionId === canon.discussionId) return stored; + const audit = (action: string) => + deps.appendAudit({ + ts: now, + mrUrl: mr.mrUrl, + iid: mr.iid, + event: 'latch', + action, + }); + // A live row beside a read that shows only a spent latch elsewhere is a + // read that cannot see the row's latch yet, as in step 0. + if (stored && stored.phase !== 'spent' && canon.kind === 'spent') { + return stored; + } + // An acknowledged note with no row (a lost db) takes the post's time as its + // stamp: the commented review that armed the latch began before the post, + // so it can never land as the follow-up, and a later run still can. + const posted = Date.parse(canon.createdAt); + const acked = IN_FLIGHT.has(canon.kind) && Number.isFinite(posted); + const fresh: Omit = { + discussionId: canon.discussionId, + rootNoteId: canon.rootNoteId, + phase: canon.kind, + wait: null, + launchAt: acked ? posted : null, + failures: 0, + stuck: false, + variant: null, + replyDue: null, + }; + if (!stored) { + const adopted: LatchRow = { mrUrl: mr.mrUrl, ...fresh, updatedAt: now }; + rows.put(adopted); + audit('adopted'); + return adopted; + } + // Guarded on the copy this tick read, so a row another writer moved in the + // meantime is never overwritten from a stale snapshot. + const live = stored.phase !== 'spent'; + const moved = rows.cas( + mr.mrUrl, + [stored.phase], + live + ? { discussionId: canon.discussionId, rootNoteId: canon.rootNoteId } + : fresh, + now, + { discussionId: stored.discussionId } + ); + if (!moved) return null; + audit(live ? 'repointed' : 'adopted'); + return live + ? { + ...stored, + discussionId: canon.discussionId, + rootNoteId: canon.rootNoteId, + updatedAt: now, } + : { mrUrl: mr.mrUrl, ...fresh, updatedAt: now }; +} - // The launch already happened, so the attempt is charged before the - // follow-up GitLab writes run: a write failing here must still count - // against cooldown and budget, or a failing write turns into a launch - // every tick. - m.lastDispatchAt = now; - m.attemptsToday++; - await deps.gateway.createNote( - mr.projectId, - mr.iid, - DISPATCH_REPLY, - canon.discussionId - ); - await consume(deps, mr, canon, carriers); - await deps.notify( - `Follow-up review started on !${mr.iid}`, - 'The author asked for a follow-up review', - mr.mrUrl +/** A running or error row whose follow-up has finished: the lane reads done + for a run that started at or after the launch. A row with no launch stamp + (a first launch that failed) has no follow-up to land. */ +function landable( + row: LatchRow, + review: ReviewState | undefined +): review is ReviewState { + return ( + (row.phase === 'running' || row.phase === 'error') && + review?.status === 'done' && + row.launchAt !== null && + runStamp(review) >= row.launchAt + ); +} + +async function landBackstop( + deps: LatchPassDeps, + mr: LatchMrFacts, + row: LatchRow, + review: ReviewState, + target: LatchTarget, + latches: LatchRef[], + result: LatchPassResult +): Promise { + // The tick's clock may be minutes old by now; the landing stamp is what + // the re-arm grace measures from. + const now = deps.now(); + const outcome = review.outcome ?? null; + const launchAt = row.launchAt; + const landed = await landFollowUp( + { + target, + outcome, + reviewRunStartedAt: runStamp(review), + gateway: deps.gateway, + self: deps.self, + countNew: () => + deps.countNew && launchAt !== null + ? deps.countNew(mr, launchAt) + : Promise.resolve(null), + now, + latches, + }, + deps.db + ); + // Another writer (the server's done signal) moved the row first. + if (landed !== 'landed') { + result.skipped++; + return; + } + deps.appendAudit({ + ts: now, + mrUrl: mr.mrUrl, + iid: mr.iid, + event: 'latch', + action: 'landed', + outcome: outcome ?? 'none', + }); + result.landed++; +} + +/** The lane decideRequest sees for a latch the row holds. The row is the + record that a commented review existed, so a lane reading error, done with + no outcome, or gone must not be refused as having none. A lane in flight + passes through, so it still reads review-in-flight. */ +function rowLane( + mr: LatchMrFacts, + review: ReviewState | undefined +): ReviewState { + if (review && (review.status === 'queued' || review.status === 'reviewing')) { + return review; + } + return { + ...(review ?? { + mrUrl: mr.mrUrl, + iid: mr.iid, + status: 'done', + startedAt: 0, + updatedAt: 0, + }), + status: 'done', + outcome: 'comment', + }; +} + +/** decideRequest over the row's synthetic commented lane. Its never-clearing + reasons cannot come back for a row-backed latch, so every non-dispatch + decision carries a wait. */ +function decide(t: Tick, m: MrMemory) { + const decision = decideRequest( + requestOf(t), + rowLane(t.mr, t.review), + m, + t.policy, + t.now + ); + return { decision, wait: waitReasonOf(decision) ?? 'next-sweep' }; +} + +async function armedLatch(t: Tick): Promise { + if (t.canon.kind !== 'armed') return repairArmed(t); + if (t.carriers.length === 0 || insideRearmGrace(t)) { + t.result.skipped++; + return; + } + const m = memoryFor(t); + const { decision, wait } = decide(t, m); + auditDecision(t, decision, m); + if (decision.action === 'dispatch') return dispatch(t, 'armed', m); + return queue(t, wait); +} + +async function queuedLatch(t: Tick): Promise { + const { rows, mr, canon, now, review } = t; + const guard = { discussionId: canon.discussionId }; + // The queued marker proves this read post-dates the pass's own rewrite, so + // an open thread is the author taking the request back, even while a review + // runs. An armed open note is a read from before the request and proves + // nothing. + if (canon.kind === 'queued' && !canon.resolved) { + const moved = rows.cas( + mr.mrUrl, + ['queued'], + { phase: 'armed', wait: null, launchAt: null }, + now, + guard + ); + if (moved) { + await show(t, 'armed', { state: 'armed' }, 'keep'); + audit(t, 'withdrawn'); + } + return; + } + // Any review that starts while the request waits is the follow-up, even one + // launched by hand: one ask never gets two reviews. One already running + // when the request came in is not; the request waits it out. + if (followUpInFlight(review, 'queued', t.row.launchAt)) { + return adoptRun(t, 'queued', review); + } + const m = memoryFor(t); + const { decision, wait } = decide(t, m); + if (decision.action === 'dispatch') { + auditDecision(t, decision, m); + return dispatch(t, 'queued', m); + } + return waitQueued(t, wait); +} + +async function waitQueued(t: Tick, wait: WaitReason): Promise { + const variant: BannerVariant = { state: 'queued', wait }; + if (variantKey(variant) === t.row.variant) { + t.result.skipped++; + return; + } + const moved = t.rows.cas(t.mr.mrUrl, ['queued'], { wait }, t.now, { + discussionId: t.canon.discussionId, + }); + if (!moved) { + t.result.skipped++; + return; + } + await show(t, 'queued', variant, 'keep'); + audit(t, 'queued', { reason: wait }); + t.result.queued++; +} + +/** A run in flight that is this request's follow-up becomes the latch's + launch: no second review starts and nothing is charged. */ +async function adoptRun( + t: Tick, + from: 'armed' | 'queued' | 'error', + review: ReviewState +): Promise { + const moved = t.rows.cas( + t.mr.mrUrl, + [from], + { + phase: 'running', + launchAt: runStamp(review), + wait: null, + stuck: false, + ...leavingError(t, from), + }, + t.now, + { discussionId: t.canon.discussionId } + ); + if (!moved) { + t.result.skipped++; + return; + } + await show(t, 'running', { state: 'running' }, threadClosed(t)); + if (from === 'armed') await supersede(t.deps, t.mr, t.canon, t.carriers); + if (from === 'error') audit(t, 'recovered'); + else audit(t, 'dispatched', { outcome: 'review already running' }); +} + +/** A row leaving error drops the stuck reply it may still owe; a finished + reply still owed from an earlier landing stands. */ +function leavingError(t: Tick, from: LatchPhase): LatchPatch { + return from === 'error' && t.row.replyDue === STUCK_REPLY + ? { replyDue: null } + : {}; +} + +/** The row moved to armed but the note still shows a later phase: either the + rewrite never landed, or this read predates one that did. Only a row + older than the read's staleness window tells the two apart. */ +async function repairArmed(t: Tick): Promise { + if (t.now - t.row.updatedAt < LATCH_POST_GRACE_MS) { + t.result.skipped++; + return; + } + if (!(await show(t, 'armed', armedVariantOf(t.row.variant), 'unresolve'))) { + t.result.skipped++; + return; + } + audit(t, 'repaired'); + t.result.repaired++; +} + +/** How far the board's clock may run ahead of GitLab's. Both post paths + stamp the row with a clock read before the post, so a row that never + moved after it sits at or before the latch's createdAt. */ +const LATCH_CLOCK_SKEW_MS = 60_000; + +/** A landing or a withdrawal re-arms the row, and a read from before that + move still shows the request it answered as armed and resolved. Only time + tells the two apart. A latch the row never moved past its post has no + older read to fear, so a quick resolve there is a request at once. */ +function insideRearmGrace(t: Tick): boolean { + if (t.now - t.row.updatedAt >= LATCH_POST_GRACE_MS) return false; + const posted = Date.parse(t.canon.createdAt); + return ( + Number.isFinite(posted) && t.row.updatedAt - posted > LATCH_CLOCK_SKEW_MS + ); +} + +/** The armed banner the row last showed, so a done-comments count survives a + repair; anything else falls back to the plain armed banner. */ +function armedVariantOf(key: string | null): BannerVariant { + const v = key ? variantOfKey(key) : null; + return v && (v.state === 'armed' || v.state === 'done-comments') + ? v + : { state: 'armed' }; +} + +async function dispatch( + t: Tick, + from: 'armed' | 'queued' | 'error', + m: MrMemory +): Promise { + const { deps, rows, mr, canon, now } = t; + // A review the board launched since this tick's snapshot is live in a pane; + // launching now would resume a second prompt into it. + const lane = deps.readReviewStates().get(mr.mrUrl); + if (inFlight(lane)) { + const stamp = from === 'armed' ? now : t.row.launchAt; + if (followUpInFlight(lane, from, stamp)) return adoptRun(t, from, lane); + if (from === 'armed') return queue(t, 'review-in-flight'); + if (from === 'queued') return waitQueued(t, 'review-in-flight'); + return waitError(t, 'review-in-flight'); + } + const launch = await deps.launchReReview(mr.mrUrl, mr.iid); + if (launch.kind === 'error') return fail(t, launch.message); + + // The launch already happened, so the attempt is charged before the + // follow-up GitLab writes run: a write failing here must still count + // against cooldown and budget, or a failing write turns into a launch + // every tick. + m.lastDispatchAt = now; + m.attemptsToday++; + const moved = rows.cas( + mr.mrUrl, + [from], + { phase: 'running', launchAt: now, wait: null, ...leavingError(t, from) }, + now, + { discussionId: canon.discussionId } + ); + if (moved) await show(t, 'running', { state: 'running' }, threadClosed(t)); + await supersede(deps, mr, canon, t.carriers); + audit(t, from === 'error' ? 'retried' : 'dispatched'); + await deps.notify( + `Follow-up review started on !${mr.iid}`, + 'The author asked for a follow-up review', + mr.mrUrl + ); + t.result.dispatched++; +} + +/** The run this latch waits on is alive while its lane is queued or + reviewing, however long a post gate parks it; only the lane reading + error (the closed-pane reconciler's verdict included) is a failure. */ +async function runningLatch(t: Tick): Promise { + if (t.review?.status === 'error') return fail(t, t.review.message); + // The row moves before the note, so a rewrite that threw leaves the note + // showing the request for the whole run unless a later pass shows running. + if ( + t.row.variant !== variantKey({ state: 'running' }) && + (await show(t, 'running', { state: 'running' }, threadClosed(t))) + ) { + audit(t, 'repaired'); + t.result.repaired++; + return; + } + t.result.skipped++; +} + +async function erroredLatch(t: Tick): Promise { + if (followUpInFlight(t.review, 'error', t.row.launchAt)) { + return adoptRun(t, 'error', t.review); + } + if (t.row.stuck) { + // The stuck transition notifies before its GitLab writes, so a write cut + // short there leaves the banner and reply for this pass to finish. + if (t.row.variant === variantKey({ state: 'error-stuck' })) { + t.result.skipped++; + return; + } + if (await showStuck(t)) { + audit(t, 'repaired'); + t.result.repaired++; + } else { + t.result.skipped++; + } + return; + } + const m = memoryFor(t); + const { decision, wait } = decide(t, m); + if (decision.action === 'dispatch') { + auditDecision(t, decision, m); + return dispatch(t, 'error', m); + } + return waitError(t, wait); +} + +async function waitError(t: Tick, wait: WaitReason): Promise { + const variant = retryingVariant(wait); + if (variantKey(variant) === t.row.variant) { + t.result.skipped++; + return; + } + const moved = t.rows.cas(t.mr.mrUrl, ['error'], { wait }, t.now, { + discussionId: t.canon.discussionId, + }); + if (!moved) { + t.result.skipped++; + return; + } + await show(t, 'error', variant, 'keep'); + audit(t, 'error', { reason: wait }); + t.result.errored++; +} + +/** The error strip has no review-in-flight wait: a run in flight would have + moved the latch to running instead. */ +function retryingVariant(wait: WaitReason): BannerVariant { + return { + state: 'error-retrying', + wait: wait === 'review-in-flight' ? 'next-sweep' : wait, + }; +} + +/** One failed attempt: the run errored, or its pane never started. The cas + on the phase this tick read keeps a server write in between (a landing) + from being overwritten; the cron lock is what keeps two passes from both + recording the same attempt. */ +async function fail(t: Tick, message: string | undefined): Promise { + const { deps, rows, mr, canon, now } = t; + // A relaunch from the board mid-pass is the follow-up running again, not + // a failure: this tick's lane snapshot is older than that launch. + const lane = deps.readReviewStates().get(mr.mrUrl); + if (lane && (lane.status === 'queued' || lane.status === 'reviewing')) { + t.result.skipped++; + return; + } + const failures = t.row.failures + 1; + const stuck = failures >= LATCH_MAX_FAILURES; + const { wait } = decide(t, memoryFor(t)); + const moved = rows.cas( + mr.mrUrl, + [t.row.phase], + stuck + ? { + phase: 'error', + failures, + wait: null, + stuck: true, + replyDue: STUCK_REPLY, + } + : { phase: 'error', failures, wait }, + now, + { discussionId: canon.discussionId } + ); + if (!moved) { + t.result.skipped++; + return; + } + const outcome = message ? { outcome: message } : {}; + if (!stuck) { + await show(t, 'error', retryingVariant(wait), threadClosed(t)); + await supersede(deps, mr, canon, t.carriers); + audit(t, 'error', { reason: wait, ...outcome }); + t.result.errored++; + return; + } + // Stuck needs a person, and the stuck repair redoes the banner and reply + // but never re-notifies, so the notification goes before any GitLab write + // that could throw. + await t.notifyStuck( + `Follow-up review stuck on !${mr.iid}`, + `It failed ${LATCH_MAX_FAILURES} times. Relaunch it from the board.`, + mr.mrUrl + ); + audit(t, 'stuck', outcome); + t.result.errored++; + t.result.stuck++; + await showStuck(t); +} + +/** The stuck banner, then the stuck reply while the row still owes it. A row + still showing another variant has not had the banner, which is how a + cut-short write is repaired. False when a landing moved the row first and + nothing was written. */ +async function showStuck(t: Tick): Promise { + if (!t.rows.read(t.mr.mrUrl)?.stuck) return false; + if (!(await show(t, 'error', STUCK, threadClosed(t)))) return false; + const reply = STUCK_REPLY; + if (t.rows.read(t.mr.mrUrl)?.replyDue === reply) { + try { + await postReplyDue( + t.deps.gateway, + t.mr, + t.canon.discussionId, + reply, + t.deps.db ); - result.dispatched++; } catch (err) { + // Still owed on the row: a later tick posts it. console.error( - `latch pass: !${mr.iid} (${mr.mrUrl}) failed: ${err instanceof Error ? err.message : err}` + `latch pass: !${t.mr.iid} stuck reply not posted: ${err instanceof Error ? err.message : err}` ); - result.failed++; } } - return result; + await supersede(t.deps, t.mr, t.canon, t.carriers); + return true; } -/** Rearm the canonical latch and spend every OTHER copy carrying the request. - Consuming the extras is what stops the request bit re-firing on the next - re-entry into scope. */ -async function consume( +async function queue(t: Tick, wait: WaitReason): Promise { + const moved = t.rows.cas( + t.mr.mrUrl, + ['armed'], + { phase: 'queued', wait, launchAt: t.now }, + t.now, + { discussionId: t.canon.discussionId } + ); + if (!moved) { + t.result.skipped++; + return; + } + await show(t, 'queued', { state: 'queued', wait }, threadClosed(t)); + await supersede(t.deps, t.mr, t.canon, t.carriers); + audit(t, 'queued', { reason: wait }); + t.result.queued++; +} + +/** Queued and running latches sit on a resolved thread; a request carried by + an extra copy leaves the canon open until the rewrite closes it. */ +function threadClosed(t: Tick): 'keep' | 'resolve' { + return t.canon.resolved ? 'keep' : 'resolve'; +} + +/** Writes the note only while the row still shows `phase` for this latch: + a landing that moved it since this tick read it owns the note. False when + it wrote nothing. */ +async function show( + t: Tick, + phase: LatchPhase, + variant: BannerVariant, + thread: 'resolve' | 'unresolve' | 'keep' +): Promise { + const cur = t.rows.read(t.mr.mrUrl); + if (cur?.phase !== phase || cur.discussionId !== t.target.discussionId) + return false; + await rewriteLatch( + t.deps.gateway, + t.target, + phase, + variant, + thread, + t.now, + t.deps.db + ); + return true; +} + +function memoryFor(t: Tick): MrMemory { + const m = rollDay( + t.deps.memory.mrs[t.mr.mrUrl] ?? emptyMrMemory(t.dayStamp), + t.dayStamp + ); + t.deps.memory.mrs[t.mr.mrUrl] = m; + return m; +} + +function requestOf(t: Tick): ReReviewRequest { + return { + mrUrl: t.mr.mrUrl, + iid: t.mr.iid, + source: 'latch', + receivedAt: null, + handled: false, + }; +} + +function audit( + t: Tick, + action: string, + extra: Pick = {} +): void { + t.deps.appendAudit({ + ts: t.now, + mrUrl: t.mr.mrUrl, + iid: t.mr.iid, + event: 'latch', + action, + ...extra, + }); +} + +function auditDecision( + t: Tick, + decision: { action: string; reason: string }, + m: MrMemory +): void { + t.deps.appendAudit({ + ts: t.now, + mrUrl: t.mr.mrUrl, + iid: t.mr.iid, + event: 'latch', + decision: decision.action, + reason: decision.reason, + attempt: m.attemptsToday + 1, + }); +} + +/** Spend every request carrier but the canon. "superseded", not approved: the + canon carries the request on, so these copies go defunct rather than + recording a verdict that did not happen. */ +async function supersede( deps: LatchPassDeps, mr: LatchMrFacts, canon: LatchRef, carriers: LatchRef[] ): Promise { - if (canon.resolved) { - await deps.gateway.unresolveDiscussion( - mr.projectPath, - mr.iid, - canon.discussionId - ); - } for (const c of carriers) { if (c.discussionId === canon.discussionId) continue; - // "duplicate", not the approved default: the canon is being rearmed for - // another cycle here, not approved, so this extra copy is going defunct - // rather than recording a verdict that did not happen. await spendLatch( deps.gateway, mr.projectId, mr.projectPath, + mr.mrUrl, mr.iid, c, - 'duplicate' + { state: 'superseded' }, + deps.now(), + deps.db ); } } - -/** Terminal disposal of every copy of this reviewer's latch once they approve. */ -async function spendAll( - deps: LatchPassDeps, - mr: LatchMrFacts, - latches: LatchRef[] -): Promise { - await spendAllLatches( - deps.gateway, - mr.projectId, - mr.projectPath, - mr.iid, - latches - ); -} diff --git a/bun.lock b/bun.lock index 3f41f9f79e..da1d6a2e03 100644 --- a/bun.lock +++ b/bun.lock @@ -53,7 +53,7 @@ "hono": "catalog:", "jsdom": "^29.1.1", "node-pty": "^1.1.0", - "prettier": "^3.9.5", + "prettier": "catalog:", "react": "catalog:", "react-dom": "catalog:", "storybook": "^10.5.2", @@ -77,6 +77,7 @@ "@mattstack/settings-kit": "workspace:*", "@mattstack/tui-kit": "workspace:*", "@pierre/diffs": "catalog:", + "gifenc": "catalog:", "invadrs": "^1.3.1", "lucide-react": "catalog:", "motion": "14.2.0", @@ -90,12 +91,15 @@ "@happy-dom/global-registrator": "^20.14.0", "@types/bun": "latest", "@types/node": "catalog:", + "@types/omggif": "catalog:", "@types/pixelmatch": "^5.2.6", "@types/pngjs": "^6.0.5", "@types/react": "catalog:", "@types/react-dom": "catalog:", + "omggif": "catalog:", "pixelmatch": "^7.2.0", "playwright": "^1.62.1", + "prettier": "catalog:", "typescript": "^7.0.2", }, }, @@ -621,6 +625,7 @@ "@testing-library/react": "^16.3.2", "@types/css-tree": "^2.3.10", "@types/node": "^24.13.2", + "@types/omggif": "1.0.5", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.3", @@ -630,8 +635,11 @@ "clsx": "^2.1.1", "css-tree": "^3.1.0", "elkjs": "^0.12.0", + "gifenc": "1.0.3", "hono": "^4.13.3", "lucide-react": "^0.577.0", + "omggif": "1.0.10", + "prettier": "^3.9.5", "radix-ui": "^1.4.3", "react": "^19.2.7", "react-dom": "^19.2.7", @@ -1593,6 +1601,8 @@ "@types/normalize-package-data": ["@types/normalize-package-data@2.4.4", "", {}, "sha512-37i+OaWTh9qeK4LSHPsyRC7NahnGotNuZvjLSgcPzblpHB3rrCJxAOgI5gCdKm7coonsaX1Of0ILiTcnZjbfxA=="], + "@types/omggif": ["@types/omggif@1.0.5", "", {}, "sha512-gDQJflz1rOgEcUXkMAl80bDGN46f5mp8GbcM5dyvq+zsFV6YRBRtmNxlJJ5mjY77T7BRkRFzdIBVmK90QYhCxA=="], + "@types/parse-json": ["@types/parse-json@4.0.2", "", {}, "sha512-dISoDXWWQwUquiKsyZ4Ng+HX2KsPL7LyHKHQwgGFEA3IaKac4Obd+h2a/a6waisAoepJlBcx9paWqjA8/HVjCw=="], "@types/picomatch": ["@types/picomatch@3.0.2", "", {}, "sha512-n0i8TD3UDB7paoMMxA3Y65vUncFJXjcUf7lQY7YyKGl6031FNjfsLs6pdLFCy2GNFxItPJG8GvvpbZc2skH7WA=="], @@ -2207,6 +2217,8 @@ "get-proto": ["get-proto@1.0.1", "", { "dependencies": { "dunder-proto": "^1.0.1", "es-object-atoms": "^1.0.0" } }, "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g=="], + "gifenc": ["gifenc@1.0.3", "", {}, "sha512-xdr6AdrfGBcfzncONUOlXMBuc5wJDtOueE3c5rdG0oNgtINLD+f2iFZltrBRZYzACRbKr+mSVU/x98zv2u3jmw=="], + "gitdiff-parser": ["gitdiff-parser@0.3.1", "", {}, "sha512-YQJnY8aew65id8okGxKCksH3efDCJ9HzV7M9rsvd65habf39Pkh4cgYJ27AaoDMqo1X98pgNJhNMrm/kpV7UVQ=="], "github-from-package": ["github-from-package@0.0.0", "", {}, "sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw=="], @@ -2645,6 +2657,8 @@ "obug": ["obug@2.2.1", "", {}, "sha512-XrsrhT5sybtKI6wakr2SPOlGZWWYbUXZ7a0jT8/QOeAPau+1X/bSegNe5YR75oJmEZQbKningirmGOEJCIk61Q=="], + "omggif": ["omggif@1.0.10", "", {}, "sha512-LMJTtvgc/nugXj0Vcrrs68Mn2D1r0zf630VNtqtpI1FEO7e+O9FP4gqs9AcnBaSEeoHIPm28u6qgPR0oyEpGSw=="], + "on-exit-leak-free": ["on-exit-leak-free@2.1.2", "", {}, "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA=="], "on-finished": ["on-finished@2.4.1", "", { "dependencies": { "ee-first": "1.1.1" } }, "sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg=="], diff --git a/package.json b/package.json index 9a9039b93b..931b89fb9b 100644 --- a/package.json +++ b/package.json @@ -31,6 +31,7 @@ "@testing-library/react": "^16.3.2", "@types/css-tree": "^2.3.10", "@types/node": "^24.13.2", + "@types/omggif": "1.0.5", "@types/react": "^19.2.17", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react": "^6.0.3", @@ -40,8 +41,11 @@ "clsx": "^2.1.1", "css-tree": "^3.1.0", "elkjs": "^0.12.0", + "gifenc": "1.0.3", "hono": "^4.13.3", "lucide-react": "^0.577.0", + "omggif": "1.0.10", + "prettier": "^3.9.5", "radix-ui": "^1.4.3", "recharts": "^3.2.1", "tailwind-merge": "^3.5.0", @@ -156,7 +160,7 @@ "hono": "catalog:", "jsdom": "^29.1.1", "node-pty": "^1.1.0", - "prettier": "^3.9.5", + "prettier": "catalog:", "react": "catalog:", "react-dom": "catalog:", "storybook": "^10.5.2", diff --git a/packages/rt-client/src/__tests__/latch.test.ts b/packages/rt-client/src/__tests__/latch.test.ts index ad564e8c52..5ddcf910cf 100644 --- a/packages/rt-client/src/__tests__/latch.test.ts +++ b/packages/rt-client/src/__tests__/latch.test.ts @@ -1,7 +1,28 @@ import { describe, expect, test } from "bun:test"; -import { LATCH_MARKER, LATCH_MARKER_SPENT, latchKindOf } from "../latch.ts"; +import { + LATCH_MARKER, + LATCH_MARKER_ERROR, + LATCH_MARKER_QUEUED, + LATCH_MARKER_RUNNING, + LATCH_MARKER_SPENT, + latchKindOf, +} from "../latch.ts"; describe("latchKindOf", () => { + test("recognizes queued, running and error latches", () => { + expect(latchKindOf(`${LATCH_MARKER_QUEUED}\n\nbanner`)).toBe("queued"); + expect(latchKindOf(`${LATCH_MARKER_RUNNING}\n\nbanner`)).toBe("running"); + expect(latchKindOf(`${LATCH_MARKER_ERROR}\n\nbanner`)).toBe("error"); + }); + + test("ignores a new marker that is not on the first line", () => { + expect(latchKindOf(`intro\n${LATCH_MARKER_RUNNING}`)).toBeNull(); + }); + + test("treats an unknown v2 running marker as null", () => { + expect(latchKindOf("")).toBeNull(); + }); + test("recognizes an armed latch", () => { expect(latchKindOf(`${LATCH_MARKER}\n\nbanner`)).toBe("armed"); }); diff --git a/packages/rt-client/src/index.ts b/packages/rt-client/src/index.ts index bb13bf66ba..4cc5d8f40a 100644 --- a/packages/rt-client/src/index.ts +++ b/packages/rt-client/src/index.ts @@ -263,5 +263,7 @@ export { } from "./ci-lease.ts"; export type { CiLease, CiLeaseHolder, CiLeaseOpts, ClaimRequest, ClaimResult, HeartbeatResult, ReleaseResult } from "./ci-lease.ts"; export * from "./evidence.ts"; -export { LATCH_MARKER, LATCH_MARKER_SPENT, latchKindOf } from "./latch.ts"; +export { + LATCH_MARKER, LATCH_MARKER_ERROR, LATCH_MARKER_QUEUED, LATCH_MARKER_RUNNING, LATCH_MARKER_SPENT, latchKindOf, +} from "./latch.ts"; export type { LatchKind } from "./latch.ts"; diff --git a/packages/rt-client/src/latch.ts b/packages/rt-client/src/latch.ts index c7544b8e9e..0e9d708da7 100644 --- a/packages/rt-client/src/latch.ts +++ b/packages/rt-client/src/latch.ts @@ -10,13 +10,20 @@ export const LATCH_MARKER = ""; export const LATCH_MARKER_SPENT = ""; -export type LatchKind = "armed" | "spent"; +export const LATCH_MARKER_QUEUED = ""; +export const LATCH_MARKER_RUNNING = ""; +export const LATCH_MARKER_ERROR = ""; + +export type LatchKind = "armed" | "queued" | "running" | "error" | "spent"; /** Which latch a note body is, or null if it is not a latch this reader knows. An unrecognized version (v2 from a newer board) is null, not armed. */ export function latchKindOf(body: string): LatchKind | null { const firstLine = body.split(/\r?\n/, 1)[0]; if (firstLine === LATCH_MARKER_SPENT) return "spent"; + if (firstLine === LATCH_MARKER_QUEUED) return "queued"; + if (firstLine === LATCH_MARKER_RUNNING) return "running"; + if (firstLine === LATCH_MARKER_ERROR) return "error"; if (firstLine === LATCH_MARKER) return "armed"; return null; }