From bf3a140df15673f531af58f89d55ec7de869e4ac Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 04:19:45 -0600 Subject: [PATCH 1/2] =?UTF-8?q?fix(aggregator):=20close=20the=20ref=20cont?= =?UTF-8?q?ract=20=E2=80=94=20Phase=204=20inventory=20fixes=20(#6243)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - model.ts: land the #6242 ref contract statement beside the #4952 isValidRef comment (validity is isValidRef only; drop-at-gate; producers mint only valid refs; refUrl only through a guard). - live.ts: Kaneo board links mint only valid refs (rule 3, traced drop); mapProjectorComment refUrl fallback fires only for a valid stored ref (rule 4); titleRefs traces dropped candidates via onInvalid so in-flight drops are logged (rule 2 — also fixes the pre-existing board-in-flight failure on main). - test/ref-contract-6243.test.ts: pinning probes for both fixed sites (unsafe-integer and non-GitHub bad refs, valid controls unchanged). Phase 4 of #6242; full inventory + the seven required dispositions are recorded on #6243. --- pm-stack/aggregator/src/model.ts | 13 ++ pm-stack/aggregator/src/sources/live.ts | 28 +++- .../aggregator/test/ref-contract-6243.test.ts | 120 ++++++++++++++++++ 3 files changed, 156 insertions(+), 5 deletions(-) create mode 100644 pm-stack/aggregator/test/ref-contract-6243.test.ts diff --git a/pm-stack/aggregator/src/model.ts b/pm-stack/aggregator/src/model.ts index a26c795a72..2d2831f147 100644 --- a/pm-stack/aggregator/src/model.ts +++ b/pm-stack/aggregator/src/model.ts @@ -500,6 +500,19 @@ export function parseRef(key: RefKey): GhRef { * number. Boundary validators and store-load gates route through this * instead of re-checking the shape with a local regex whose \d+ group * admits numbers parseRef (and refUrl) then throw on. */ +/** The ref contract (design #6242, closed out by the Phase 4 inventory on + * #6243): a ref is an annotation, not identity. (1) Validity is + * isValidRef only - no local shape checks. (2) An invalid ref is dropped + * at the consumption step beside its gate: the item survives, the drop + * is traced (log or count). (3) Producers mint only valid refs: scrapes + * route through refsInText / titleRefs, which filter with isValidRef, + * and constructors validate before minting. (4) Rendering or deriving + * reaches refUrl for stored or feed-derived refs only through a guard + * (an isValidRef check, a load/read gate upstream, or a safe-link + * helper); an invalid ref renders as plain text, never a throw. + * Code-built refs (issue(n), fixture literals, validated config) are + * exempt from (4): parseRef's throw is their test-time assertion. */ + export function isValidRef(value: unknown): value is RefKey { if (typeof value !== "string") return false; try { diff --git a/pm-stack/aggregator/src/sources/live.ts b/pm-stack/aggregator/src/sources/live.ts index dec5b1addd..7458bf4e20 100644 --- a/pm-stack/aggregator/src/sources/live.ts +++ b/pm-stack/aggregator/src/sources/live.ts @@ -222,7 +222,16 @@ async function kaneoBoard(cfg: Config, cookie: string): Promise<{ items: BoardIt // refs are never invented from a guessed repo. const m = /github\.com\/([\w.-]+\/[\w.-]+)\//.exec(l.url); if (!m) return []; - return [{ ref: `${m[1]}#${l.externalId}`, relation: "tracks" as const }]; + const ref = `${m[1]}#${l.externalId}` as RefKey; + // #6243 (ref contract rule 3): a producer mints only valid + // refs - an externalId parseRef would reject (unsafe integer, + // non-numeric) must not become a board link renderers throw + // on; the card survives, the drop is traced. + if (!isValidRef(ref)) { + console.error(`[board] WARNING: dropping Kaneo link with invalid ref ${JSON.stringify(ref)} for task ${t.id} (#6243)`); + return []; + } + return [{ ref, relation: "tracks" as const }]; }); out.push({ // Registry subject: kaneo:/ (Session J). @@ -368,7 +377,11 @@ export function mapProjectorComment(row: ProjectorCommentRow): Comment { author: row.author ?? "", body: row.body ?? "", createdAt: row.created_at, - url: row.url ?? refUrl(row.ref, row.kind === "issue_comment" ? "issue" : "pr"), + // #6243 (ref contract rule 4): row.ref is stored projector data; the + // stored url wins, and the refUrl fallback fires only for a ref the + // shared rule accepts - an invalid stored ref yields no URL instead + // of throwing out of the map (cf. the #6211 read gate for links). + url: row.url ?? (isValidRef(row.ref) ? refUrl(row.ref, row.kind === "issue_comment" ? "issue" : "pr") : ""), path: row.path ?? undefined, line: row.line ?? undefined, reviewState: row.review_state ?? undefined, @@ -550,10 +563,15 @@ const TITLE_REPO_ALIASES: Record = { * also carries queue/task numbers — so it is left unlinked rather * than guessed at. */ -export function titleRefs(title: string): RefKey[] { +export function titleRefs(title: string, onInvalid?: (ref: string) => void): RefKey[] { const out: RefKey[] = []; const add = (ref: RefKey) => { - if (!isValidRef(ref)) return; + // #6243 (ref contract rule 2): a dropped candidate is traced, never + // silent - callers that own a trace surface pass onInvalid. + if (!isValidRef(ref)) { + onInvalid?.(ref); + return; + } if (!out.includes(ref)) out.push(ref); }; for (const ref of refsInText(title)) add(ref); @@ -643,7 +661,7 @@ export function inFlightBoardItems(section: OrchestrationSection, existing: Boar if (!refs.includes(ref)) refs.push(ref); }; if (item.ref !== undefined && item.ref !== null && item.ref !== "") add(item.ref); - for (const ref of titleRefs(item.title)) add(ref); + for (const ref of titleRefs(item.title, (bad) => add(bad))) add(ref); const remainingRefs = refs.filter((ref) => !existingRefs.has(ref)); if (refs.length > 0 && remainingRefs.length === 0) continue; const titleKey = normTitle(item.title); diff --git a/pm-stack/aggregator/test/ref-contract-6243.test.ts b/pm-stack/aggregator/test/ref-contract-6243.test.ts new file mode 100644 index 0000000000..cbcc6a2a16 --- /dev/null +++ b/pm-stack/aggregator/test/ref-contract-6243.test.ts @@ -0,0 +1,120 @@ +// Ref contract Phase 4 (#6243, design #6242): the two producer/consumer +// sites the closing inventory found still minting or dereferencing refs +// without the shared isValidRef rule, pinned: +// - Kaneo board links are minted from a GitHub URL + externalId; an +// externalId parseRef rejects (unsafe integer, non-numeric) used to +// become a board link that renderers throw on in refUrl. The board +// reader now drops it at minting (rule 3), traced, card survives. +// - mapProjectorComment fell back to refUrl(row.ref) for a stored +// projector comment with no stored url; an invalid stored ref threw +// out of the map. The fallback now fires only for a valid ref +// (rule 4); a stored url still wins over any ref. +// +// Run: bun test test/ref-contract-6243.test.ts +import { describe, expect, test } from "bun:test"; +import { mkdtemp, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { loadConfig } from "../src/config.ts"; +import { liveSource, mapProjectorComment, type ProjectorCommentRow } from "../src/sources/live.ts"; + +describe("mapProjectorComment refUrl fallback (#6243)", () => { + const row = (over: Partial): ProjectorCommentRow => ({ + id: "1", + ref: "developing-today/code#6243", + kind: "issue_comment", + created_at: "2026-11-08T00:00:00Z", + ...over, + }); + + test("valid ref without a stored url derives the comment url", () => { + expect(mapProjectorComment(row({})).url).toBe("https://github.com/developing-today/code/issues/6243"); + }); + + test("unsafe-integer ref without a stored url yields no url, never a throw", () => { + const bad = row({ ref: "developing-today/code#99999999999999999999" }); + expect(() => mapProjectorComment(bad)).not.toThrow(); + expect(mapProjectorComment(bad).url).toBe(""); + }); + + test("non-ref stored value without a stored url yields no url, never a throw", () => { + const bad = row({ ref: "not-a-ref" }); + expect(() => mapProjectorComment(bad)).not.toThrow(); + expect(mapProjectorComment(bad).url).toBe(""); + }); + + test("a stored url wins even when the ref is invalid", () => { + const stored = row({ ref: "not-a-ref", url: "https://github.com/example/x" }); + expect(mapProjectorComment(stored).url).toBe("https://github.com/example/x"); + }); +}); + +const FEED = { + version: 1, + generatedAt: new Date().toISOString(), + quota: { pools: [], burn: [], choices: { hasHeadroom: [], burnBeforeReset: [], doNotStart: [] } }, + attention: [], +}; + +async function driveBoard(externalLinks: unknown[]) { + const dir = await mkdtemp(join(tmpdir(), "pm-ref-contract-")); + const feedFile = join(dir, "fleet-feed.json"); + await writeFile(feedFile, JSON.stringify(FEED)); + const projectsFile = join(dir, "kaneo-projects.json"); + await writeFile( + projectsFile, + JSON.stringify({ projects: [{ slug: "code", projectId: "p1", repository: "example-org/example-repo", installationId: 1 }] }), + ); + const realFetch = globalThis.fetch; + globalThis.fetch = (async (input: unknown) => { + const url = String(input); + const json = (body: unknown, headers: Record = {}) => + new Response(JSON.stringify(body), { status: 200, headers: { "Content-Type": "application/json", ...headers } }); + if (url.includes("/api/auth/sign-in/email")) return json({}, { "set-cookie": "session=test; Path=/" }); + if (url.includes("/api/workspace")) return json([{ id: "ws1" }]); + if (url.includes("/api/project?")) return json([{ id: "p1", slug: "code", name: "Code" }]); + if (url.includes("/api/task/tasks/")) { + return json({ + data: { + columns: [ + { + id: "in-progress", + name: "In Progress", + tasks: [{ id: "t-p1", number: 7, title: "Work in p1", status: "in-progress", externalLinks }], + }, + ], + }, + pagination: { totalPages: 1 }, + }); + } + return new Response("not found", { status: 404 }); + }) as typeof fetch; + try { + const cfg = loadConfig({ + ...Bun.env, + PM_AGG_SOURCE: "live", + PM_AGG_FEED_FILE: feedFile, + PM_PROJECTOR_URL: "off", + PM_KANEO_PROJECTS_FILE: projectsFile, + KANEO_URL: "http://kaneo.test", + KANEO_ADMIN_EMAIL: "test@example.com", + KANEO_ADMIN_PASSWORD: "test-password", + }); + return (await liveSource(cfg).board()).filter((b) => b.source === "kaneo"); + } finally { + globalThis.fetch = realFetch; + } +} + +describe("Kaneo board link minting (#6243)", () => { + test("only valid refs are minted: unsafe-integer and non-numeric externalIds drop, the card survives", async () => { + const board = await driveBoard([ + { resourceType: "issue", externalId: "42", url: "https://github.com/example-org/example-repo/issues/42" }, + { resourceType: "issue", externalId: "99999999999999999999", url: "https://github.com/example-org/example-repo/issues/99999999999999999999" }, + { resourceType: "issue", externalId: "abc", url: "https://github.com/example-org/example-repo/issues/abc" }, + ]); + const card = board.find((b) => b.title === "Work in p1"); + expect(card).toBeDefined(); + expect(card?.links.map((l) => l.ref)).toEqual(["example-org/example-repo#42"]); + }); +}); From 9162bfd5261a77bce7c2c3e9680308c18e8a0945 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Sun, 8 Nov 2026 07:02:01 -0600 Subject: [PATCH 2/2] feat(aggregator): salvage sessionRecordLine plain-text alignment from PR #7642 (#6243) Phase 4 disposition 5: sessionRecordLine renders invalid stored refs as plain text (ref contract rule 4) instead of silently omitting them. render.ts and its pinning tests salvaged verbatim from PR #7642 (task 13017) into canonical PR #7639 (task 12925) per the duplicate-PR protocol; registry-taskrefs-2485 pin updated from omit to plain-text for sessionRecordLine/renderSessions. Tests: 60/60 pass across 7 files (ref-contract-6243 incl. salvaged tests, board-in-flight, projector, registry-ref-filter-6211, registry-taskrefs-2485, queue-view, kaneo-project-repos-1201) on the laptop worktree. --- pm-stack/aggregator/src/render.ts | 15 +++-- .../aggregator/test/ref-contract-6243.test.ts | 60 +++++++++++++++++++ .../test/registry-taskrefs-2485.test.ts | 12 ++-- 3 files changed, 75 insertions(+), 12 deletions(-) diff --git a/pm-stack/aggregator/src/render.ts b/pm-stack/aggregator/src/render.ts index 09e9bc20bd..b8dd38ae00 100644 --- a/pm-stack/aggregator/src/render.ts +++ b/pm-stack/aggregator/src/render.ts @@ -1934,14 +1934,13 @@ export function sessionRecordLine( const parent = r.parentId ? ` · sub of ${esc(r.parentId)}` : ""; - const renderedRefs = r.taskRefs.flatMap((ref) => { - try { - return [`${esc(ref)}`]; - } catch { - // A malformed ref may still exist in an older or ungated in-memory - // record. Keep the session visible and omit only the invalid link. - return []; - } + const renderedRefs = r.taskRefs.map((ref) => { + // #6243 (ref contract rule 4, #6242): a malformed ref may still + // exist in an older or ungated in-memory record. Keep the session + // visible and render the invalid ref as plain text — the same + // treatment tierItemCard (#6149) and poolRefLink give it — never + // a throw, and never silently omitted. + return isValidRef(ref) ? `${esc(ref)}` : esc(ref); }); const refs = renderedRefs.length ? ` · ${renderedRefs.join(" ")}` : ""; // #1156: live records carry the session action set on the merged diff --git a/pm-stack/aggregator/test/ref-contract-6243.test.ts b/pm-stack/aggregator/test/ref-contract-6243.test.ts index cbcc6a2a16..ccdbbb1c56 100644 --- a/pm-stack/aggregator/test/ref-contract-6243.test.ts +++ b/pm-stack/aggregator/test/ref-contract-6243.test.ts @@ -11,12 +11,17 @@ // (rule 4); a stored url still wins over any ref. // // Run: bun test test/ref-contract-6243.test.ts +// Salvage (task 12925): the sessionRecordLine disposition-5 tests below +// come from PR #7642 (task 13017), whose render.ts fix is salvaged into +// this PR; see the salvage note on PR #7639. import { describe, expect, test } from "bun:test"; import { mkdtemp, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { loadConfig } from "../src/config.ts"; import { liveSource, mapProjectorComment, type ProjectorCommentRow } from "../src/sources/live.ts"; +import { isValidRef, parseRef, refUrl, type RefKey, type SessionRecord } from "../src/model.ts"; +import { sessionRecordLine } from "../src/render.ts"; describe("mapProjectorComment refUrl fallback (#6243)", () => { const row = (over: Partial): ProjectorCommentRow => ({ @@ -118,3 +123,58 @@ describe("Kaneo board link minting (#6243)", () => { expect(card?.links.map((l) => l.ref)).toEqual(["example-org/example-repo#42"]); }); }); + +// ---- Salvaged from PR #7642: sessionRecordLine alignment (disposition 5) ---- + +function rec(taskRefs: string[]): SessionRecord { + return { + id: "ses_phase4", + source: "claude-code", + label: "Phase 4 probe", + agentId: "claude-code", + agentLabel: "Muse", + parentId: null, + status: "succeeded", + startedAt: "2026-11-08T00:00:00Z", + lastSeenAt: "2026-11-08T01:00:00Z", + taskRefs: taskRefs as RefKey[], + } as SessionRecord; +} + +const GOOD = "developing-today/code#6243"; +const BAD_UNSAFE = "developing-today/code#99999999999999999999"; +const BAD_SHAPE = "goal:keep-the-four-repos-healthy"; + +describe("sessionRecordLine renders invalid stored refs as plain text (#6243)", () => { + test("unsafe-integer ref: no throw, ref visible as plain text, no anchor", () => { + const html = sessionRecordLine(rec([BAD_UNSAFE])); + expect(html).toContain(BAD_UNSAFE); + expect(html).not.toContain(`href="https://github.com/developing-today/code/issues/99999999999999999999"`); + }); + test("non-GitHub ref: no throw, ref visible as plain text", () => { + const html = sessionRecordLine(rec([BAD_SHAPE])); + expect(html).toContain(BAD_SHAPE); + expect(html).not.toContain(" { + const html = sessionRecordLine(rec([GOOD])); + expect(html).toContain(`${GOOD}`); + }); + test("mixed refs: valid anchors, invalid is plain text, session survives", () => { + const html = sessionRecordLine(rec([GOOD, BAD_UNSAFE])); + expect(html).toContain(`${GOOD}`); + expect(html).toContain(BAD_UNSAFE); + }); +}); + +describe("the internal ref assertion stays total-checked (#6242 rule 1)", () => { + test("isValidRef is the shared rule", () => { + expect(isValidRef(GOOD)).toBe(true); + expect(isValidRef(BAD_UNSAFE)).toBe(false); + expect(isValidRef(BAD_SHAPE)).toBe(false); + }); + test("parseRef and refUrl still throw on invalid refs", () => { + expect(() => parseRef(BAD_UNSAFE as RefKey)).toThrow(); + expect(() => refUrl(BAD_SHAPE as RefKey)).toThrow(); + }); +}); diff --git a/pm-stack/aggregator/test/registry-taskrefs-2485.test.ts b/pm-stack/aggregator/test/registry-taskrefs-2485.test.ts index 85929bef49..549b15a153 100644 --- a/pm-stack/aggregator/test/registry-taskrefs-2485.test.ts +++ b/pm-stack/aggregator/test/registry-taskrefs-2485.test.ts @@ -47,7 +47,7 @@ describe("registry task-ref validation (#2485)", () => { expect(() => refUrl("owner/repo#12345678901234567890123")).toThrow(); }); - test("rendering skips poisoned refs while retaining valid links", () => { + test("rendering renders poisoned refs as plain text while retaining valid links (#6243 disposition 5 supersedes the #2485 omit pin for sessionRecordLine)", () => { const poisoned = rec({ id: "ses_poisoned", taskRefs: ["code#2480", "developing-today/code#2485", "owner/repo#12345678901234567890123"], @@ -56,12 +56,16 @@ describe("registry task-ref validation (#2485)", () => { expect(() => sessionRecordLine(poisoned)).not.toThrow(); const line = sessionRecordLine(poisoned); expect(line).toContain('href="https://github.com/developing-today/code/issues/2485"'); - expect(line).not.toContain("code#2480"); - expect(line).not.toContain("12345678901234567890123"); + // #6243 disposition 5 (ref contract rule 4): invalid stored refs render + // as plain text - visible, never a throw, never an anchor. + expect(line).toContain("code#2480"); + expect(line).not.toContain('href="https://github.com/code'); + expect(line).toContain("12345678901234567890123"); + expect(line).not.toContain('href="https://github.com/owner/repo/issues/12345678901234567890123"'); const html = renderSessions([poisoned], fixtureSource().provenance()); expect(html).toContain('href="https://github.com/developing-today/code/issues/2485"'); - expect(html).not.toContain("code#2480"); + expect(html).toContain("code#2480"); }); test("launch writer refuses malformed --task values without writing a record", async () => {