From 08107edd3be1838748e6cc63c97cb46b69cf0e38 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 21:05:48 -0600 Subject: [PATCH 1/2] feat(projector): integrated queue/PM view, machine face (#7078) Read-only queue-view CLI + join module (#2072 slice 3, first landable piece): joins fleet queue task records with the slice-2 hot list consumed through a consumer checkpoint (pin high-water, ack after emit). Emits queued items in broker claim order, items claimed in the window with claiming worker/lane/platform, snapshot counts by status, and links to the existing aggregator/projector trend stores. No new ingestion, no new collectors, no writes. --- pm-stack/projector/README.md | 14 + pm-stack/projector/src/cli.ts | 53 +++- pm-stack/projector/src/queue-view.ts | 305 +++++++++++++++++++++ pm-stack/projector/test/queue-view.test.ts | 224 +++++++++++++++ 4 files changed, 594 insertions(+), 2 deletions(-) create mode 100644 pm-stack/projector/src/queue-view.ts create mode 100644 pm-stack/projector/test/queue-view.test.ts diff --git a/pm-stack/projector/README.md b/pm-stack/projector/README.md index ea5336796c..f3f9ccb8ee 100644 --- a/pm-stack/projector/README.md +++ b/pm-stack/projector/README.md @@ -110,6 +110,20 @@ local source you don't commit. | `/hot/checkpoints` | POST | bearer | ack a checkpoint `{consumer, cursor, highWater}` | | `/reconcile` | POST | bearer | trigger a reconciliation poll | +### Integrated queue/PM view — machine face (#7078, #2072 slice 3) + +`bun run src/cli.ts queue-view --tasks [--window-hours 24] [--consumer queue-view] [--no-ack]` +prints one read-only JSON view joining fleet queue task records (JSON +exported from the queue broker: an array, or `{ "tasks": [...] }`) with +this projector's slice-2 hot list, consumed through a consumer +checkpoint (pinned high-water; the checkpoint is acked only after the +view prints, unless `--no-ack`). The view lists queued items in claim +order, items claimed inside the window with their claiming +system/lane, snapshot counts by status (which reconcile with +`fleet queue health` when fed the full task list), and links to the +existing aggregator/projector trend stores. It writes nothing and +collects nothing new; the human face is a later slice-3 piece. + **Subjects** are external keys: - `kaneo:/` — a Kaneo board item (e.g. `kaneo:code/CODE-107`) diff --git a/pm-stack/projector/src/cli.ts b/pm-stack/projector/src/cli.ts index ea746b86c9..f1868026f1 100644 --- a/pm-stack/projector/src/cli.ts +++ b/pm-stack/projector/src/cli.ts @@ -1,18 +1,67 @@ -// CLI: one-off reconciliation against the live GitHub API. +// CLI: one-off jobs against the live stores. // bun run src/cli.ts reconcile +// bun run src/cli.ts queue-view --tasks [--window-hours 24] +// [--consumer queue-view] [--no-ack] +// +// queue-view (#7078, #2072 slice 3 first piece) is the read-only +// integrated queue/PM view, machine face: it joins fleet queue task +// records (JSON exported from the queue broker — an array, or an object +// with a `tasks` array) with the slice-2 hot list consumed through a +// consumer checkpoint, and prints the view as JSON on stdout. The +// checkpoint is acked only after the view has been printed, unless +// --no-ack is passed. +import { readFileSync } from "node:fs"; import { openDb, migrate } from "./store"; -import { reconcileRepos } from "./reconcile"; +import { buildQueueView, consumeHotList, defaultTrendLinks, type QueueTaskRecord } from "./queue-view"; const cmd = process.argv[2] ?? "reconcile"; const env = process.env as Record; +function arg(name: string): string | undefined { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 ? process.argv[i + 1] : undefined; +} + const db = openDb(env); await migrate(db); if (cmd === "reconcile") { + const { reconcileRepos } = await import("./reconcile"); console.log("[projector] reconcile start:", env.PM_REPOS); const result = await reconcileRepos(db, env); console.log(JSON.stringify(result, null, 2)); +} else if (cmd === "queue-view") { + const tasksPath = arg("tasks"); + if (!tasksPath) { + console.error("queue-view: --tasks is required (queue task records as JSON)"); + process.exit(2); + } + const parsed = JSON.parse(readFileSync(tasksPath, "utf8")) as + | QueueTaskRecord[] + | { tasks: QueueTaskRecord[] }; + const tasks = Array.isArray(parsed) ? parsed : parsed.tasks; + if (!Array.isArray(tasks)) { + console.error("queue-view: tasks file must be a JSON array or { tasks: [...] }"); + process.exit(2); + } + const windowHours = Number(arg("window-hours") ?? "24"); + const until = new Date(); + const since = new Date(until.getTime() - windowHours * 3_600_000); + const consumer = arg("consumer") ?? "queue-view"; + const consumed = await consumeHotList(db, consumer); + const view = buildQueueView(tasks, consumed.events, { + since: since.toISOString(), + until: until.toISOString(), + consumer, + fromSeq: consumed.fromSeq, + highWater: consumed.highWater, + links: defaultTrendLinks(env), + }); + console.log(JSON.stringify(view, null, 2)); + if (!process.argv.includes("--no-ack")) { + const cursor = await consumed.ack(); + console.error(`[projector] queue-view: consumer ${consumer} checkpoint acked at ${cursor}`); + } } else { console.error(`unknown command: ${cmd}`); process.exit(2); diff --git a/pm-stack/projector/src/queue-view.ts b/pm-stack/projector/src/queue-view.ts new file mode 100644 index 0000000000..6a12da38f2 --- /dev/null +++ b/pm-stack/projector/src/queue-view.ts @@ -0,0 +1,305 @@ +// Integrated queue/PM view — machine face (#7078, #2072 slice 3, first piece). +// +// One read model over two existing sources, no new ingestion and no new +// source of truth: +// 1. fleet queue task records (the broker's task JSON, as emitted by +// `fleet queue claim` / the queue-broker /list rich response), and +// 2. the slice-2 hot list (#5204, PR #5327): the projector's append-only +// `pmp_hot_events` ledger, consumed through a consumer checkpoint +// exactly as slice 2 designed it (pin the high-water, page inside it, +// ack only after the view has been emitted). +// +// The view answers, for a given window: +// - what is queued, in claim order (the broker's pick order: +// (priority IS NULL), priority ASC, created_at ASC) — a current +// snapshot, because "what is queued, in what order" is a now-question; +// - what was picked up inside the window, and by which system +// (worker_id / lane_id / platform carried on the task record); +// - snapshot counts by status, which reconcile with `fleet queue +// health` when the caller feeds the full task list; +// - links (never copies) to the existing usage/quota/job trend stores. +// +// Join key: the repo-qualified issue ref `owner/repo#N`, taken from the +// task payload (`payload.repo` + `payload.issue.number`) or, failing +// that, parsed out of the dedupe key +// (`repo-health:v1:::issue:`). Hot events carry the +// same ref shape, so the join needs no hand reconstruction. + +import type { Client } from "@libsql/client"; +import { + ackConsumerCheckpoint, + getConsumerCheckpoint, + hotHighWater, + listHotEvents, + type HotEventRow, +} from "./store"; + +/** A fleet queue task record (subset of the broker's task JSON we read). */ +export interface QueueTaskRecord { + id: number; + queue?: string | null; + title?: string | null; + status: string; + priority?: number | null; + created_at?: string | null; + claimed_at?: string | null; + worker_id?: string | null; + lane_id?: string | null; + platform?: string | null; + dedupe_key?: string | null; + progress?: { + last_checkpoint?: { at?: string | null } | null; + } | null; + payload?: { + repo?: string | null; + kind?: string | null; + issue?: { number?: number | null } | null; + } | null; +} + +export interface ViewHotEvent { + seq: number; + event: string; + action: string | null; + actor: string | null; + received_at: string; + source_url: string | null; +} + +export interface QueuedEntry { + task_id: number; + queue: string | null; + title: string | null; + priority: number | null; + created_at: string | null; + ref: string | null; + kind: string | null; + hot_events: ViewHotEvent[]; +} + +export interface ClaimedEntry extends QueuedEntry { + claimed_at: string | null; + claimed_by: { + worker_id: string | null; + lane_id: string | null; + platform: string | null; + }; +} + +export interface TrendLink { + label: string; + store: string; + ref: string; +} + +export interface QueueView { + generated_at: string; + window: { since: string; until: string }; + counts: Record; + queued: QueuedEntry[]; + claimed: ClaimedEntry[]; + hot_list: { + consumer: string | null; + from_seq: number; + high_water: number; + events_consumed: number; + }; + links: TrendLink[]; +} + +export interface QueueViewOptions { + /** Window start (ISO-8601). Claimed entries and hot events are filtered to it. */ + since: string; + /** Window end (ISO-8601). Defaults to `since + 24h` at the CLI layer. */ + until: string; + consumer?: string | null; + fromSeq?: number; + highWater?: number; + links?: TrendLink[]; + now?: string; +} + +const DEDUPE_REF_RE = /:((?:[A-Za-z0-9_.-]+\/){1,2}[A-Za-z0-9_.-]+):issue:(\d+)$/; + +/** The repo-qualified issue ref for a task, or null when it carries none. */ +export function taskRef(task: QueueTaskRecord): string | null { + const repo = task.payload?.repo; + const num = task.payload?.issue?.number; + if (repo && typeof num === "number") return `${repo}#${num}`; + if (task.dedupe_key) { + const m = DEDUPE_REF_RE.exec(task.dedupe_key); + if (m) return `${m[1]}#${m[2]}`; + } + return null; +} + +/** The broker's claim order: (priority IS NULL), priority ASC, created_at ASC. */ +export function claimOrder(a: QueueTaskRecord, b: QueueTaskRecord): number { + const an = a.priority == null ? 1 : 0; + const bn = b.priority == null ? 1 : 0; + if (an !== bn) return an - bn; + if (an === 0 && a.priority !== b.priority) return (a.priority as number) - (b.priority as number); + const ac = a.created_at ?? ""; + const bc = b.created_at ?? ""; + if (ac !== bc) return ac < bc ? -1 : 1; + return a.id - b.id; +} + +function inWindow(iso: string | null | undefined, since: string, until: string): boolean { + if (!iso) return false; + return iso >= since && iso <= until; +} + +/** + * When the task was picked up, as far as the record can say: the full + * task JSON carries `claimed_at`, but the broker's rich /list rows omit + * it — there the claim's own checkpoint timestamp is the best activity + * evidence. Null when the record carries neither. + */ +export function claimTimestamp(task: QueueTaskRecord): string | null { + return task.claimed_at ?? task.progress?.last_checkpoint?.at ?? null; +} + +function toViewEvents(events: HotEventRow[]): ViewHotEvent[] { + return events.map((e) => ({ + seq: e.seq, + event: e.event, + action: e.action, + actor: e.actor, + received_at: e.received_at, + source_url: e.source_url, + })); +} + +/** + * Build the integrated view from task records + already-consumed hot + * events. Pure: the same inputs always produce the same view, so the + * join is unit-testable without a database or a live broker. + */ +export function buildQueueView( + tasks: QueueTaskRecord[], + hotEvents: HotEventRow[], + opts: QueueViewOptions, +): QueueView { + const counts: Record = {}; + for (const t of tasks) counts[t.status] = (counts[t.status] ?? 0) + 1; + + const byRef = new Map(); + for (const e of hotEvents) { + if (!e.ref) continue; + if (!inWindow(e.received_at, opts.since, opts.until)) continue; + const list = byRef.get(e.ref) ?? []; + list.push(e); + byRef.set(e.ref, list); + } + + const entry = (t: QueueTaskRecord): QueuedEntry => { + const ref = taskRef(t); + return { + task_id: t.id, + queue: t.queue ?? null, + title: t.title ?? null, + priority: t.priority ?? null, + created_at: t.created_at ?? null, + ref, + kind: t.payload?.kind ?? null, + hot_events: ref ? toViewEvents(byRef.get(ref) ?? []) : [], + }; + }; + + const queued = tasks + .filter((t) => t.status === "queued") + .sort(claimOrder) + .map(entry); + + const claimed = tasks + .filter((t) => { + if (t.status !== "claimed") return false; + const at = claimTimestamp(t); + // A claimed record with no claim timestamp cannot be proven out + // of window; its claimed state is a now-fact, so it is listed. + return at === null || inWindow(at, opts.since, opts.until); + }) + .sort((a, b) => (claimTimestamp(a) ?? "9999").localeCompare(claimTimestamp(b) ?? "9999") || a.id - b.id) + .map((t) => ({ + ...entry(t), + claimed_at: claimTimestamp(t), + claimed_by: { + worker_id: t.worker_id ?? null, + lane_id: t.lane_id ?? null, + platform: t.platform ?? null, + }, + })); + + const seqs = hotEvents.map((e) => e.seq); + return { + generated_at: opts.now ?? new Date().toISOString(), + window: { since: opts.since, until: opts.until }, + counts, + queued, + claimed, + hot_list: { + consumer: opts.consumer ?? null, + from_seq: opts.fromSeq ?? 0, + high_water: opts.highWater ?? (seqs.length ? Math.max(...seqs) : 0), + events_consumed: hotEvents.length, + }, + links: opts.links ?? defaultTrendLinks(), + }; +} + +/** + * Links to the existing trend stores — references, never copies. Bases + * are env-overridable at the CLI layer; the defaults are the projector's + * documented local API (127.0.0.1:7801) and the aggregator's repo paths. + */ +export function defaultTrendLinks(env: Record = {}): TrendLink[] { + const projector = env.PM_PROJECTOR_URL ?? "http://127.0.0.1:7801"; + const aggregator = env.PM_AGGREGATOR_URL ?? "pm-stack/aggregator"; + return [ + { label: "Hot list (slice-2 event stream)", store: "projector", ref: `${projector}/hot` }, + { label: "Joined items + comment activity", store: "projector", ref: `${projector}/items` }, + { label: "Usage & billing trends", store: "aggregator", ref: `${aggregator}/src/burn-history.ts` }, + { label: "Plan quota snapshots", store: "aggregator", ref: `${aggregator}/scripts/gather-quota.ts` }, + { label: "Scheduled-job activity stream", store: "aggregator", ref: `${aggregator}/src/activity.ts` }, + ]; +} + +export interface ConsumedHotList { + events: HotEventRow[]; + fromSeq: number; + highWater: number; + /** Ack the consumer checkpoint at the pinned high-water. Call ONLY + * after the view built from `events` has been emitted successfully; + * without the ack the same events are re-consumed next run. */ + ack: () => Promise; +} + +/** + * Consume the hot list for `consumer` per the slice-2 protocol: read the + * acked checkpoint, pin the server's current high-water, page ascending + * strictly after the checkpoint and never past the pin. + */ +export async function consumeHotList( + db: Client, + consumer: string, + opts: { pageSize?: number } = {}, +): Promise { + const pageSize = opts.pageSize ?? 500; + const fromSeq = await getConsumerCheckpoint(db, consumer); + const highWater = await hotHighWater(db); + const events: HotEventRow[] = []; + let after = fromSeq; + for (;;) { + const page = await listHotEvents(db, { after, limit: pageSize, highWater }); + events.push(...page); + if (page.length < pageSize) break; + after = page[page.length - 1].seq; + } + return { + events, + fromSeq, + highWater, + ack: () => ackConsumerCheckpoint(db, consumer, highWater, highWater), + }; +} diff --git a/pm-stack/projector/test/queue-view.test.ts b/pm-stack/projector/test/queue-view.test.ts new file mode 100644 index 0000000000..e9b774b73f --- /dev/null +++ b/pm-stack/projector/test/queue-view.test.ts @@ -0,0 +1,224 @@ +// Integrated queue/PM view (#7078, #2072 slice 3 first piece): the join +// of fleet queue task records with the slice-2 hot list, claim-order +// sorting, claimed-by attribution, count reconciliation, and consumer- +// checkpoint consumption. Oracles are stated per test: the broker's +// documented claim order, the input record set itself (counts), and the +// slice-2 checkpoint protocol from test/hot.test.ts. +import { describe, test, expect, beforeAll, afterAll } from "bun:test"; +import { createClient, type Client } from "@libsql/client"; +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + migrate, + appendHotEvents, + getConsumerCheckpoint, + type HotEventInput, +} from "../src/store"; +import { + buildQueueView, + claimOrder, + consumeHotList, + taskRef, + type QueueTaskRecord, +} from "../src/queue-view"; +import type { HotEventRow } from "../src/store"; + +const SINCE = "2026-11-10T00:00:00Z"; +const UNTIL = "2026-11-11T00:00:00Z"; + +const task = (over: Partial): QueueTaskRecord => ({ + id: 1, + queue: "repo-health-code-pilot", + title: "task", + status: "queued", + priority: 30, + created_at: "2026-11-09T00:00:00Z", + claimed_at: null, + worker_id: null, + lane_id: null, + platform: null, + dedupe_key: null, + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 100 } }, + ...over, +}); + +const hotRow = (over: Partial): HotEventRow => ({ + seq: 1, + event_id: "d1:issue:100", + delivery_id: "d1", + repo: "developing-today/code", + event: "issues", + action: "opened", + ref: "developing-today/code#100", + actor: "dezren39", + source_url: "https://github.com/developing-today/code/issues/100", + source_timestamp: "2026-11-10T01:00:00Z", + received_at: "2026-11-10T01:00:00Z", + ...over, +}); + +describe("queue-view: refs and claim order", () => { + test("taskRef prefers payload repo+issue, falls back to the dedupe key", () => { + expect(taskRef(task({}))).toBe("developing-today/code#100"); + expect( + taskRef( + task({ + payload: null, + dedupe_key: "repo-health:v1:fix:developing-today/code:issue:5497", + }), + ), + ).toBe("developing-today/code#5497"); + expect(taskRef(task({ payload: null, dedupe_key: null }))).toBeNull(); + }); + + test("claimOrder is the broker order: non-null priority first, then priority ASC, then created_at ASC", () => { + const rows = [ + task({ id: 1, priority: null, created_at: "2026-11-01T00:00:00Z" }), + task({ id: 2, priority: 30, created_at: "2026-11-09T00:00:00Z" }), + task({ id: 3, priority: 10, created_at: "2026-11-08T00:00:00Z" }), + task({ id: 4, priority: 30, created_at: "2026-11-08T00:00:00Z" }), + ]; + expect([...rows].sort(claimOrder).map((t) => t.id)).toEqual([3, 4, 2, 1]); + }); +}); + +describe("queue-view: buildQueueView", () => { + const tasks = [ + task({ id: 11, priority: 20, created_at: "2026-11-09T02:00:00Z" }), + task({ id: 12, priority: 10, created_at: "2026-11-09T01:00:00Z", payload: { repo: "developing-today/code", kind: "triage", issue: { number: 200 } } }), + task({ + id: 13, + status: "claimed", + claimed_at: "2026-11-10T05:00:00Z", + worker_id: "repo-worker-code", + lane_id: "code-d", + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 300 } }, + }), + task({ + id: 14, + status: "claimed", + claimed_at: "2026-11-01T05:00:00Z", // claimed before the window + worker_id: "repo-worker-code", + lane_id: "code-a", + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 400 } }, + }), + task({ id: 15, status: "done", payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 500 } } }), + ]; + const events = [ + hotRow({ seq: 7, ref: "developing-today/code#100" }), + hotRow({ seq: 8, ref: "developing-today/code#999", event_id: "d2:issue:999" }), // no task carries this ref + hotRow({ seq: 9, ref: "developing-today/code#100", received_at: "2026-11-12T01:00:00Z", event_id: "d3:issue:100" }), // outside window + ]; + + test("queued lists only queued tasks, in claim order, with their in-window hot events joined by ref", () => { + const view = buildQueueView(tasks, events, { since: SINCE, until: UNTIL, now: UNTIL }); + expect(view.queued.map((q) => q.task_id)).toEqual([12, 11]); + const first = view.queued.find((q) => q.task_id === 11); + expect(first?.ref).toBe("developing-today/code#100"); + expect(first?.hot_events.map((e) => e.seq)).toEqual([7]); // seq 9 is outside the window + }); + + test("claimed lists only claims inside the window, with claiming system/lane", () => { + const view = buildQueueView(tasks, events, { since: SINCE, until: UNTIL, now: UNTIL }); + expect(view.claimed.map((c) => c.task_id)).toEqual([13]); + expect(view.claimed[0].claimed_by).toEqual({ + worker_id: "repo-worker-code", + lane_id: "code-d", + platform: null, + }); + }); + + test("claimed falls back to the progress checkpoint timestamp when claimed_at is absent (rich /list rows)", () => { + const rich = [ + task({ + id: 21, + status: "claimed", + claimed_at: null, + progress: { last_checkpoint: { at: "2026-11-10T06:00:00Z" } }, + worker_id: "repo-worker-code", + lane_id: "code-l", + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 600 } }, + }), + task({ + id: 22, + status: "claimed", + claimed_at: null, + progress: { last_checkpoint: { at: "2026-11-01T06:00:00Z" } }, // stale: before the window + worker_id: "repo-worker-code", + lane_id: "code-a", + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 700 } }, + }), + task({ + id: 23, + status: "claimed", + claimed_at: null, + progress: null, // no timestamp anywhere: listed, claimed_at null + worker_id: "repo-worker-code", + lane_id: null, + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 800 } }, + }), + ]; + const view = buildQueueView(rich, [], { since: SINCE, until: UNTIL, now: UNTIL }); + expect(view.claimed.map((c) => c.task_id)).toEqual([21, 23]); + expect(view.claimed[0].claimed_at).toBe("2026-11-10T06:00:00Z"); + expect(view.claimed[1].claimed_at).toBeNull(); + }); + + test("counts reconcile with the input snapshot: every record counted once, by status", () => { + const view = buildQueueView(tasks, events, { since: SINCE, until: UNTIL, now: UNTIL }); + expect(view.counts).toEqual({ queued: 2, claimed: 2, done: 1 }); + expect(Object.values(view.counts).reduce((a, b) => a + b, 0)).toBe(tasks.length); + }); +}); + +describe("queue-view: consumeHotList checkpoint protocol", () => { + let db: Client; + let dir: string; + + const ev = (over: Partial): HotEventInput => ({ + eventId: "e1:issue:100", + deliveryId: "e1", + repo: "developing-today/code", + event: "issues", + action: "opened", + ref: "developing-today/code#100", + actor: "dezren39", + sourceUrl: "https://github.com/developing-today/code/issues/100", + sourceTimestamp: "2026-11-10T01:00:00Z", + ...over, + }); + + beforeAll(async () => { + dir = mkdtempSync(join(tmpdir(), "pm-projector-qv-")); + db = createClient({ url: `file:${join(dir, "test.db")}` }); + await migrate(db); + await appendHotEvents(db, [ + ev({}), + ev({ eventId: "e2:issue:200", deliveryId: "e2", ref: "developing-today/code#200" }), + ev({ eventId: "e3:issue:300", deliveryId: "e3", ref: "developing-today/code#300" }), + ]); + }); + + afterAll(() => { + db.close(); + rmSync(dir, { recursive: true, force: true }); + }); + + test("consumption without ack re-reads the same events; ack advances the checkpoint monotonically", async () => { + const first = await consumeHotList(db, "queue-view-test"); + expect(first.fromSeq).toBe(0); + expect(first.events.map((e) => e.seq)).toEqual([1, 2, 3]); + expect(first.highWater).toBe(3); + // No ack yet: the checkpoint has not moved. + expect(await getConsumerCheckpoint(db, "queue-view-test")).toBe(0); + + const again = await consumeHotList(db, "queue-view-test"); + expect(again.events.map((e) => e.seq)).toEqual([1, 2, 3]); + + expect(await first.ack()).toBe(3); + const after = await consumeHotList(db, "queue-view-test"); + expect(after.fromSeq).toBe(3); + expect(after.events).toEqual([]); + }); +}); From cf87bc49137f9ae87c25195b39d69180dea03a80 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 22:18:37 -0600 Subject: [PATCH 2/2] fix(projector): claimed_at is authoritative; pin hot-list high-water before window end (#7078) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex findings on PR #8481 (both P2): (1) claimTimestamp substituted progress.last_checkpoint.at for claimed_at on rich broker rows, but verb_checkpoint overwrites that timestamp on every checkpoint, mis-dating claims both directions — now claimed_at only, unknown reported as null and listed as a now-fact. (2) The queue-view CLI captured its window end before consumeHotList pinned the hot-list high-water, so an event appended after until but before the pin could be consumed, window-filtered out, and acked past (lost) — the CLI now consumes first and captures until after the pin. Tests: queue-view suite 7/7 (fallback test replaced with the authoritative-claimed_at oracle, incl. the in-window-checkpoint exclusion case); full projector suite 120 pass. --- pm-stack/projector/src/cli.ts | 12 ++++++++-- pm-stack/projector/src/queue-view.ts | 17 +++++++++----- pm-stack/projector/test/queue-view.test.ts | 26 +++++++++++++++++----- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/pm-stack/projector/src/cli.ts b/pm-stack/projector/src/cli.ts index f1868026f1..e5a7045ad5 100644 --- a/pm-stack/projector/src/cli.ts +++ b/pm-stack/projector/src/cli.ts @@ -45,10 +45,18 @@ if (cmd === "reconcile") { process.exit(2); } const windowHours = Number(arg("window-hours") ?? "24"); - const until = new Date(); - const since = new Date(until.getTime() - windowHours * 3_600_000); const consumer = arg("consumer") ?? "queue-view"; + // Consume BEFORE capturing the window end: consumeHotList pins the + // hot-list high-water, and the window end must be at or after that + // pin. Capturing `until` first would let an event appended after + // `until` but before the pin be consumed, filtered out of the view + // by the window, and then acked past — lost for good. With this + // order every consumed event has received_at <= pin <= until, and + // anything appended after the pin is neither consumed nor acked. + // (Codex finding on PR #8481, 2026-11-11.) const consumed = await consumeHotList(db, consumer); + const until = new Date(); + const since = new Date(until.getTime() - windowHours * 3_600_000); const view = buildQueueView(tasks, consumed.events, { since: since.toISOString(), until: until.toISOString(), diff --git a/pm-stack/projector/src/queue-view.ts b/pm-stack/projector/src/queue-view.ts index 6a12da38f2..dd50d50c31 100644 --- a/pm-stack/projector/src/queue-view.ts +++ b/pm-stack/projector/src/queue-view.ts @@ -151,13 +151,20 @@ function inWindow(iso: string | null | undefined, since: string, until: string): } /** - * When the task was picked up, as far as the record can say: the full - * task JSON carries `claimed_at`, but the broker's rich /list rows omit - * it — there the claim's own checkpoint timestamp is the best activity - * evidence. Null when the record carries neither. + * When the task was picked up, as far as the record can say: ONLY the + * record's own `claimed_at` is a claim time. The broker's rich /list + * rows omit `claimed_at` and carry `progress.last_checkpoint.at` + * instead, but that timestamp is overwritten by every checkpoint + * (verb_checkpoint), so it is activity evidence, never a claim time: + * substituting it mis-dates claims in both directions (a task claimed + * before the window but checkpointed inside it reads as newly + * claimed; a fresh claim carrying an old checkpoint reads as stale). + * Rows without `claimed_at` report null (unknown); buildQueueView + * lists such claimed rows as now-facts rather than dating them by a + * checkpoint. (Codex finding on PR #8481, 2026-11-11.) */ export function claimTimestamp(task: QueueTaskRecord): string | null { - return task.claimed_at ?? task.progress?.last_checkpoint?.at ?? null; + return task.claimed_at ?? null; } function toViewEvents(events: HotEventRow[]): ViewHotEvent[] { diff --git a/pm-stack/projector/test/queue-view.test.ts b/pm-stack/projector/test/queue-view.test.ts index e9b774b73f..c4b6d1b89f 100644 --- a/pm-stack/projector/test/queue-view.test.ts +++ b/pm-stack/projector/test/queue-view.test.ts @@ -129,13 +129,19 @@ describe("queue-view: buildQueueView", () => { }); }); - test("claimed falls back to the progress checkpoint timestamp when claimed_at is absent (rich /list rows)", () => { + test("claimed_at is authoritative: a progress checkpoint timestamp is never substituted for it (rich /list rows)", () => { + // Oracle: Codex finding on PR #8481 — verb_checkpoint overwrites + // progress.last_checkpoint.at on every checkpoint, so it cannot + // date a claim. Rows without claimed_at are listed as now-facts + // with claimed_at null (unknown), whatever their checkpoints say; + // a row whose claimed_at is outside the window stays out even + // when a checkpoint landed inside it. const rich = [ task({ id: 21, status: "claimed", claimed_at: null, - progress: { last_checkpoint: { at: "2026-11-10T06:00:00Z" } }, + progress: { last_checkpoint: { at: "2026-11-10T06:00:00Z" } }, // in-window checkpoint, no claim time worker_id: "repo-worker-code", lane_id: "code-l", payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 600 } }, @@ -144,7 +150,7 @@ describe("queue-view: buildQueueView", () => { id: 22, status: "claimed", claimed_at: null, - progress: { last_checkpoint: { at: "2026-11-01T06:00:00Z" } }, // stale: before the window + progress: { last_checkpoint: { at: "2026-11-01T06:00:00Z" } }, // stale checkpoint, no claim time worker_id: "repo-worker-code", lane_id: "code-a", payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 700 } }, @@ -158,11 +164,19 @@ describe("queue-view: buildQueueView", () => { lane_id: null, payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 800 } }, }), + task({ + id: 24, + status: "claimed", + claimed_at: "2026-11-01T05:00:00Z", // claimed before the window + progress: { last_checkpoint: { at: "2026-11-10T07:00:00Z" } }, // in-window checkpoint must not pull it in + worker_id: "repo-worker-code", + lane_id: "code-b", + payload: { repo: "developing-today/code", kind: "small_fix", issue: { number: 900 } }, + }), ]; const view = buildQueueView(rich, [], { since: SINCE, until: UNTIL, now: UNTIL }); - expect(view.claimed.map((c) => c.task_id)).toEqual([21, 23]); - expect(view.claimed[0].claimed_at).toBe("2026-11-10T06:00:00Z"); - expect(view.claimed[1].claimed_at).toBeNull(); + expect(view.claimed.map((c) => c.task_id)).toEqual([21, 22, 23]); + expect(view.claimed.map((c) => c.claimed_at)).toEqual([null, null, null]); }); test("counts reconcile with the input snapshot: every record counted once, by status", () => {