From 7589552e242f1ea9975285c70f388d58b18754b5 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Tue, 3 Nov 2026 08:07:53 -0600 Subject: [PATCH] =?UTF-8?q?fix(pm-dispatch):=20no=20orphan=20spec-less=20i?= =?UTF-8?q?ssues=20=E2=80=94=20spec=20gate=20+=20enqueue-failure=20cleanup?= =?UTF-8?q?=20(#4925)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pm-stack/dispatch/src/enqueue_failure.ts | 60 ++++++++++++++++ pm-stack/dispatch/src/github.ts | 20 ++++++ pm-stack/dispatch/src/server.ts | 65 ++++++++++++++++-- pm-stack/dispatch/src/validate.ts | 20 +++++- .../dispatch/test/enqueue_failure.test.ts | 68 +++++++++++++++++++ pm-stack/dispatch/test/server.test.ts | 4 +- pm-stack/dispatch/test/validate.test.ts | 37 ++++++++-- 7 files changed, 264 insertions(+), 10 deletions(-) create mode 100644 pm-stack/dispatch/src/enqueue_failure.ts create mode 100644 pm-stack/dispatch/test/enqueue_failure.test.ts diff --git a/pm-stack/dispatch/src/enqueue_failure.ts b/pm-stack/dispatch/src/enqueue_failure.ts new file mode 100644 index 0000000000..94af74c410 --- /dev/null +++ b/pm-stack/dispatch/src/enqueue_failure.ts @@ -0,0 +1,60 @@ +// Shared enqueue-failure handling for pm-dispatch (issue #4925). +// +// Both POST /v1/sessions and POST /v1/tasks create their GitHub +// tracking issue BEFORE enqueueing the queue task (the packet's +// canonical dedupe key names the issue number). When the enqueue — or +// the packet validation just before it — then fails, the old code +// returned the error with the issue left open and unannotated: a +// spec-less placeholder whose footer promised task/session ids that +// would never arrive. 59 open "do the thing" issues accumulated that +// way, each then consuming a coverage triage lane. +// +// This helper is the enqueue-side mirror of launch_failure.ts: when a +// dispatch fails before its task exists, an issue THIS dispatch +// created is commented with the failure and closed as not planned, so +// nothing dangles. Each step is best-effort and individually guarded — +// a comment failure must not suppress the close — and the outcome is +// returned so the HTTP response can say exactly what happened to the +// issue. Callers must only pass an issue the same request created: +// an issue attached via `issue_number` belongs to the caller and is +// never closed here. + +/** The slice of the GitHub client enqueue-failure handling needs. */ +export interface EnqueueFailureGitHub { + comment(repo: string, issueNumber: number, body: string): Promise; + closeIssue(repo: string, issueNumber: number): Promise; +} + +export interface EnqueueFailureOutcome { + commented: boolean; + closed: boolean; +} + +export async function handleEnqueueFailure( + github: EnqueueFailureGitHub, + repo: string, + issueNumber: number, + stage: string, + e: unknown, +): Promise { + const msg = e instanceof Error ? e.message : String(e); + let commented = false; + try { + await github.comment( + repo, + issueNumber, + `Dispatch FAILED at the ${stage} step, before any queue task existed for this issue.\n\nError: ${msg}\n\nClosing as not planned so this issue does not dangle as a spec-less placeholder (#4925). Re-dispatch with a fuller prompt if the work is still wanted.`, + ); + commented = true; + } catch { + /* best-effort — the close below must still run */ + } + let closed = false; + try { + await github.closeIssue(repo, issueNumber); + closed = true; + } catch { + /* best-effort — the caller reports the outcome on the response */ + } + return { commented, closed }; +} diff --git a/pm-stack/dispatch/src/github.ts b/pm-stack/dispatch/src/github.ts index 44dec69216..0cfbf17fcf 100644 --- a/pm-stack/dispatch/src/github.ts +++ b/pm-stack/dispatch/src/github.ts @@ -298,4 +298,24 @@ export class GitHubClient { } await this.gh(["issue", "comment", String(issueNumber), "--repo", repo, "--body", body]); } + + /** Close an issue as not planned. Used by enqueue-failure cleanup + * (#4925): an issue dispatch created for a task that never got + * enqueued must not be left dangling open. */ + async closeIssue(repo: string, issueNumber: number): Promise { + if (this.appConfigured) { + try { + const token = await this.installationToken(repo); + const res = await this.appApi("PATCH", `/repos/${repo}/issues/${issueNumber}`, token, { + state: "closed", + state_reason: "not_planned", + }); + if (!res.ok) throw new GitHubError(`close issue failed (HTTP ${res.status})`); + return; + } catch { + /* fall through to gh */ + } + } + await this.gh(["issue", "close", String(issueNumber), "--repo", repo, "--reason", "not planned"]); + } } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index fa3408577a..9b11bbd743 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -32,6 +32,7 @@ import { } from "./packet.ts"; import { QueueClient, QueueError, type TaskRow } from "./queue.ts"; import { handleLaunchFailure, withCreatedSession, type LaunchFailureContext } from "./launch_failure.ts"; +import { handleEnqueueFailure } from "./enqueue_failure.ts"; import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; import { OpenCodeClient } from "./opencode.ts"; @@ -219,15 +220,38 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise; - return { + const req: SessionRequest = { repo: reqString(b, "repo"), prompt: reqString(b, "prompt"), title: optNonBlankString(b, "title"), @@ -148,6 +158,14 @@ export function parseSessionRequest(body: unknown): SessionRequest { issue: optBool(b, "issue", true), wait: optBool(b, "wait", true), }; + // The spec gate runs after every other field validates, so existing + // field errors (repo, priority, ...) keep their precedence. + if (req.title === undefined && req.prompt.length < MIN_DERIVED_TITLE_PROMPT_CHARS) { + throw new ValidationError( + `prompt: ${req.prompt.length} chars is too short to derive a tracking-issue title from (minimum ${MIN_DERIVED_TITLE_PROMPT_CHARS}) — provide an explicit title or a fuller prompt`, + ); + } + return req; } /** Session-directory scoping for POST /v1/sessions (issues #2903, #2664). diff --git a/pm-stack/dispatch/test/enqueue_failure.test.ts b/pm-stack/dispatch/test/enqueue_failure.test.ts new file mode 100644 index 0000000000..ea7264a80a --- /dev/null +++ b/pm-stack/dispatch/test/enqueue_failure.test.ts @@ -0,0 +1,68 @@ +import { describe, expect, test } from "bun:test"; +import { handleEnqueueFailure } from "../src/enqueue_failure.ts"; + +// Regression tests for #4925: dispatch created the tracking issue +// before the enqueue, and an enqueue (or packet-validation) failure +// returned with the issue left open and unannotated — a spec-less +// orphan. handleEnqueueFailure comments the failure on the created +// issue and closes it as not planned; these tests pin that behaviour +// with a stubbed GitHub client, mirroring launch_failure.test.ts. + +function stubs(failComment = false, failClose = false) { + const calls: { comments: [string, number, string][]; closes: [string, number][]; events: string[] } = { + comments: [], + closes: [], + events: [], + }; + const github = { + async comment(repo: string, issueNumber: number, body: string): Promise { + calls.comments.push([repo, issueNumber, body]); + calls.events.push("comment"); + if (failComment) throw new Error("github unreachable"); + }, + async closeIssue(repo: string, issueNumber: number): Promise { + calls.closes.push([repo, issueNumber]); + calls.events.push("close"); + if (failClose) throw new Error("github unreachable"); + }, + }; + return { calls, github }; +} + +describe("handleEnqueueFailure", () => { + test("comments the failure and closes the created issue as not planned", async () => { + const { calls, github } = stubs(); + const outcome = await handleEnqueueFailure( + github, + "developing-today/code", + 4925, + "queue enqueue", + new Error("supabase insert failed"), + ); + expect(outcome).toEqual({ commented: true, closed: true }); + // The evidence lands before the close. + expect(calls.events).toEqual(["comment", "close"]); + expect(calls.comments).toHaveLength(1); + expect(calls.comments[0][0]).toBe("developing-today/code"); + expect(calls.comments[0][1]).toBe(4925); + expect(calls.comments[0][2]).toContain("queue enqueue"); + expect(calls.comments[0][2]).toContain("supabase insert failed"); + expect(calls.comments[0][2]).toContain("not planned"); + expect(calls.closes).toEqual([["developing-today/code", 4925]]); + }); + + test("still closes when the comment itself fails", async () => { + const { calls, github } = stubs(true); + const outcome = await handleEnqueueFailure(github, "developing-today/code", 7, "packet validation", "string failure"); + expect(outcome).toEqual({ commented: false, closed: true }); + expect(calls.closes).toEqual([["developing-today/code", 7]]); + }); + + test("reports honestly when the close fails", async () => { + const { calls, github } = stubs(false, true); + const outcome = await handleEnqueueFailure(github, "developing-today/code", 7, "queue enqueue", new Error("boom")); + expect(outcome).toEqual({ commented: true, closed: false }); + expect(calls.comments).toHaveLength(1); + expect(calls.closes).toHaveLength(1); + }); +}); diff --git a/pm-stack/dispatch/test/server.test.ts b/pm-stack/dispatch/test/server.test.ts index dcc7f43746..d8a57881bb 100644 --- a/pm-stack/dispatch/test/server.test.ts +++ b/pm-stack/dispatch/test/server.test.ts @@ -58,7 +58,9 @@ function sessionsRequest(token: string, body: Record): Request }); } -const base = { repo: "developing-today/code", prompt: "do the thing" }; +// The prompt clears the #4925 spec gate (>= 40 chars, no explicit +// title) so these tests exercise the directory/body gates behind it. +const base = { repo: "developing-today/code", prompt: "do the thing properly, with a real spec and acceptance criteria" }; describe("POST /v1/sessions directory scoping (issue #2903)", () => { test("OIDC + foreign directory is rejected with 400 before any side effect", async () => { diff --git a/pm-stack/dispatch/test/validate.test.ts b/pm-stack/dispatch/test/validate.test.ts index 288c032cfe..f2ac2adabd 100644 --- a/pm-stack/dispatch/test/validate.test.ts +++ b/pm-stack/dispatch/test/validate.test.ts @@ -132,7 +132,10 @@ describe("request validation", () => { } }); test("sessions require repo and prompt; defaults issue+wait on", () => { - const r = parseSessionRequest({ repo: "developing-today/code", prompt: "do the thing" }); + const r = parseSessionRequest({ + repo: "developing-today/code", + prompt: "do the thing properly, with a real spec and acceptance criteria", + }); expect(r.issue).toBe(true); expect(r.wait).toBe(true); expect(r.priority).toBe(40); @@ -141,6 +144,26 @@ describe("request validation", () => { expect(() => parseSessionRequest("nope")).toThrow(ValidationError); }); + test("a short prompt with no explicit title is rejected by the spec gate (issue #4925)", () => { + // The specimen: this exact prompt titled 59 orphan placeholder issues. + expect(() => parseSessionRequest({ repo: "developing-today/code", prompt: "do the thing" })).toThrow(/too short/); + expect(() => parseSessionRequest({ repo: "developing-today/code", prompt: "do the thing" })).toThrow(ValidationError); + // An explicit title exempts the request: the caller named the work. + const titled = parseSessionRequest({ repo: "developing-today/code", prompt: "do the thing", title: "Named work" }); + expect(titled.title).toBe("Named work"); + // A fuller prompt needs no title. + const full = parseSessionRequest({ + repo: "developing-today/code", + prompt: "do the thing properly, with a real spec and acceptance criteria", + }); + expect(full.title).toBeUndefined(); + // Field errors keep precedence over the gate: a bad priority on a + // short prompt still reports the priority, not the gate. + expect(() => parseSessionRequest({ repo: "developing-today/code", prompt: "x", priority: "bogus" })).toThrow( + /priority/, + ); + }); + test("a prototype-spelling priority 400s at parse time, so no non-number reaches the packet (#2757)", () => { expect(() => parseSessionRequest({ repo: "developing-today/code", prompt: "x", priority: "constructor" })).toThrow( ValidationError, @@ -155,7 +178,13 @@ describe("request validation", () => { parseTaskRequest({ repo: "developing-today/code", title: "t", prompt: "p", priority: "__proto__" }), ).toThrow(ValidationError); // A valid named priority still parses to a number. - expect(parseSessionRequest({ repo: "developing-today/code", prompt: "x", priority: "high" }).priority).toBe(20); + expect( + parseSessionRequest({ + repo: "developing-today/code", + prompt: "do the thing properly, with a real spec and acceptance criteria", + priority: "high", + }).priority, + ).toBe(20); }); test("tasks accept prompt or body, default kind triage and issue off", () => { @@ -284,7 +313,7 @@ describe("session blank title/directory parsing (issue #2664)", () => { test("empty and whitespace-only title/directory parse as omitted", () => { const r = parseSessionRequest({ repo: "developing-today/code", - prompt: "do the thing", + prompt: "do the thing properly, with a real spec and acceptance criteria", title: " ", directory: "", }); @@ -292,7 +321,7 @@ describe("session blank title/directory parsing (issue #2664)", () => { expect(r.directory).toBeUndefined(); const r2 = parseSessionRequest({ repo: "developing-today/code", - prompt: "do the thing", + prompt: "do the thing properly, with a real spec and acceptance criteria", title: "", directory: " \t ", });