diff --git a/pm-stack/dispatch/src/github.ts b/pm-stack/dispatch/src/github.ts index 44dec69216..e57e16c580 100644 --- a/pm-stack/dispatch/src/github.ts +++ b/pm-stack/dispatch/src/github.ts @@ -285,6 +285,42 @@ export class GitHubClient { await this.gh(["issue", "edit", String(issueNumber), "--repo", repo, ...labels.flatMap((l) => ["--add-label", l])]); } + /** + * Close an issue with a state reason (#4917). Used to compensate a + * dispatch-created tracking issue when the launch fails before the + * dispatch becomes real, so the issue does not linger open as an + * orphan. Only ever called on issues this service created itself — + * never on attach targets a caller supplied. + */ + async closeIssue( + repo: string, + issueNumber: number, + stateReason: "not_planned" | "completed" = "not_planned", + ): 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: stateReason, + }); + if (!res.ok) throw new GitHubError(`issue close failed (HTTP ${res.status})`); + return; + } catch { + /* fall through to gh */ + } + } + await this.gh([ + "issue", + "close", + String(issueNumber), + "--repo", + repo, + "--reason", + stateReason === "not_planned" ? "not planned" : "completed", + ]); + } + async comment(repo: string, issueNumber: number, body: string): Promise { if (this.appConfigured) { try { diff --git a/pm-stack/dispatch/src/launch_failure.ts b/pm-stack/dispatch/src/launch_failure.ts index 21b2c7220c..e2f29349e0 100644 --- a/pm-stack/dispatch/src/launch_failure.ts +++ b/pm-stack/dispatch/src/launch_failure.ts @@ -13,6 +13,16 @@ // not suppress the next. The note reports the cancellation and cleanup // outcomes, and the original launch error is returned for the wait:true // path's 502. +// +// #4917: the tracking issue itself is also closed as not planned on +// every failure path. A failed launch's issue is a record of a dispatch +// that never became real; leaving it open produced 66 orphan +// 'do the thing' issues (#3499-#4899). Failures BEFORE the enqueue +// (packet validation, enqueue itself) have no task to cancel — those +// callers use compensateOrphanedIssue below, which performs the same +// note + close for the issue they created. Only issues dispatch +// created in the same request are ever closed here; attach targets +// (caller-supplied issue numbers) are never compensated. /** The slice of the queue client launch-failure handling needs. */ export interface LaunchFailureQueue { @@ -22,6 +32,41 @@ export interface LaunchFailureQueue { /** The slice of the GitHub client launch-failure handling needs. */ export interface LaunchFailureGitHub { comment(repo: string, issueNumber: number, body: string): Promise; + closeIssue(repo: string, issueNumber: number, stateReason?: "not_planned" | "completed"): Promise; +} + +/** + * Compensate a tracking issue whose dispatch failed BEFORE a queue + * task existed (#4917): note the failure on the issue and close it as + * not planned, so it does not linger open as an orphan. Both steps are + * best-effort and individually guarded; the original error message is + * returned for the caller's error response. A null issue number (no + * issue was created) is a no-op. + */ +export async function compensateOrphanedIssue( + github: LaunchFailureGitHub, + repo: string, + issueNumber: number | null, + stage: string, + e: unknown, +): Promise { + const msg = e instanceof Error ? e.message : String(e); + if (issueNumber == null) return msg; + try { + await github.comment( + repo, + issueNumber, + `Dispatch launch FAILED at ${stage} before a queue task was created, so this dispatch never became real. Closing this tracking issue as not planned so it does not linger as an orphan (#4917).\n\nError: ${msg}`, + ); + } catch { + /* issue note is best-effort on the failure path */ + } + try { + await github.closeIssue(repo, issueNumber, "not_planned"); + } catch { + /* close is best-effort; the note above still records the failure */ + } + return msg; } /** Mutable context shared by launchSession and its failure handler. */ @@ -90,6 +135,13 @@ export async function handleLaunchFailure( } catch { /* issue note is best-effort on the failure path */ } + // #4917: a failed launch's tracking issue must not stay open — + // close it as not planned after noting the failure. + try { + await github.closeIssue(repo, issueNumber, "not_planned"); + } catch { + /* close is best-effort; the note above still records the failure */ + } } return msg; } diff --git a/pm-stack/dispatch/src/server.ts b/pm-stack/dispatch/src/server.ts index fa3408577a..24f5d06f38 100644 --- a/pm-stack/dispatch/src/server.ts +++ b/pm-stack/dispatch/src/server.ts @@ -31,7 +31,12 @@ import { validatePayload, } from "./packet.ts"; import { QueueClient, QueueError, type TaskRow } from "./queue.ts"; -import { handleLaunchFailure, withCreatedSession, type LaunchFailureContext } from "./launch_failure.ts"; +import { + compensateOrphanedIssue, + handleLaunchFailure, + withCreatedSession, + type LaunchFailureContext, +} from "./launch_failure.ts"; import { annotateLaunch } from "./launch_annotations.ts"; import { GitHubClient } from "./github.ts"; import { OpenCodeClient } from "./opencode.ts"; @@ -219,14 +224,21 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise { @@ -22,6 +27,9 @@ function stubs(failCancel = false) { async comment(repo: string, issueNumber: number, body: string): Promise { calls.comments.push([repo, issueNumber, body]); }, + async closeIssue(repo: string, issueNumber: number, stateReason?: "not_planned" | "completed"): Promise { + calls.closes.push([repo, issueNumber, stateReason]); + }, }; return { calls, queue, github }; } @@ -44,6 +52,8 @@ describe("handleLaunchFailure", () => { expect(calls.comments[0][1]).toBe(2901); expect(calls.comments[0][2]).toContain("queue task #4135 was cancelled"); expect(calls.comments[0][2]).toContain("opencode refused the session"); + // #4917: the failed launch's tracking issue is closed, not orphaned. + expect(calls.closes).toEqual([["developing-today/code", 2901, "not_planned"]]); }); test("cancels without an issue note when there is no tracking issue", async () => { @@ -51,6 +61,7 @@ describe("handleLaunchFailure", () => { await handleLaunchFailure(queue, github, "developing-today/code", 7, null, new Error("boom")); expect(calls.cancels).toHaveLength(1); expect(calls.comments).toHaveLength(0); + expect(calls.closes).toHaveLength(0); }); test("still notes the issue when the cancellation itself fails", async () => { @@ -67,6 +78,9 @@ describe("handleLaunchFailure", () => { expect(calls.comments[0][2]).toContain("may still be queued or claimed and needs cleanup"); expect(calls.comments[0][2]).toContain("Cancellation error: queue unreachable"); expect(calls.comments[0][2]).not.toContain("was cancelled"); + // Even when cancellation fails, the issue is still closed (#4917): + // the launch definitively failed either way. + expect(calls.closes).toEqual([["developing-today/code", 9, "not_planned"]]); }); async function assertCreatedSessionFailure(stage: "sendPrompt" | "claim patch") { @@ -77,6 +91,7 @@ describe("handleLaunchFailure", () => { deleted: [] as string[], cancels: [] as [number, string][], comments: [] as [string, number, string][], + closes: [] as [string, number, string | undefined][], events: [] as string[], }; const opencode = { @@ -107,6 +122,10 @@ describe("handleLaunchFailure", () => { calls.events.push("comment"); calls.comments.push([repo, issueNumber, body]); }, + async closeIssue(repo: string, issueNumber: number, stateReason?: "not_planned" | "completed"): Promise { + calls.events.push("close"); + calls.closes.push([repo, issueNumber, stateReason]); + }, }; // Model the real order: session creation succeeds before the guarded @@ -146,7 +165,8 @@ describe("handleLaunchFailure", () => { expect(calls.comments[0][2]).toContain("session cleanup failed: delete failed"); expect(calls.comments[0][2]).toContain(launchError.message); expect(calls.deleted).toEqual([sessionId]); - expect(calls.events).toEqual(["cancel", "delete", "comment"]); + expect(calls.events).toEqual(["cancel", "delete", "comment", "close"]); + expect(calls.closes).toEqual([["developing-today/code", 2901, "not_planned"]]); } test("created session is cleaned up and reported after sendPrompt fails", async () => { @@ -157,3 +177,56 @@ describe("handleLaunchFailure", () => { await assertCreatedSessionFailure("claim patch"); }); }); + +describe("compensateOrphanedIssue (#4917)", () => { + test("notes and closes the issue a failed pre-enqueue dispatch created", async () => { + const { calls, github } = stubs(); + const msg = await compensateOrphanedIssue( + github, + "developing-today/code", + 4917, + "enqueue", + new Error("queue insert failed"), + ); + expect(msg).toBe("queue insert failed"); + expect(calls.comments).toHaveLength(1); + expect(calls.comments[0][0]).toBe("developing-today/code"); + expect(calls.comments[0][1]).toBe(4917); + expect(calls.comments[0][2]).toContain("FAILED at enqueue"); + expect(calls.comments[0][2]).toContain("queue insert failed"); + expect(calls.closes).toEqual([["developing-today/code", 4917, "not_planned"]]); + }); + + test("is a no-op when no issue was created", async () => { + const { calls, github } = stubs(); + const msg = await compensateOrphanedIssue(github, "developing-today/code", null, "enqueue", new Error("boom")); + expect(msg).toBe("boom"); + expect(calls.comments).toHaveLength(0); + expect(calls.closes).toHaveLength(0); + }); + + test("still closes when the note fails, and never throws when the close fails", async () => { + const closes: number[] = []; + const flaky = { + async comment(): Promise { + throw new Error("github down"); + }, + async closeIssue(_repo: string, issueNumber: number): Promise { + closes.push(issueNumber); + }, + }; + const msg = await compensateOrphanedIssue(flaky, "developing-today/code", 5, "packet validation", "bad packet"); + expect(msg).toBe("bad packet"); + expect(closes).toEqual([5]); + + const broken = { + async comment(): Promise {}, + async closeIssue(): Promise { + throw new Error("github down"); + }, + }; + await expect( + compensateOrphanedIssue(broken, "developing-today/code", 6, "enqueue", new Error("x")), + ).resolves.toBe("x"); + }); +}); diff --git a/pm-stack/dispatch/test/server.test.ts b/pm-stack/dispatch/test/server.test.ts index dcc7f43746..cdc2d99708 100644 --- a/pm-stack/dispatch/test/server.test.ts +++ b/pm-stack/dispatch/test/server.test.ts @@ -58,7 +58,14 @@ function sessionsRequest(token: string, body: Record): Request }); } -const base = { repo: "developing-today/code", prompt: "do the thing" }; +// issue:false keeps these tests hermetic (#4917): session requests +// default issue creation ON, and the GitHub client's gh-CLI fallback is +// a subprocess the fetch stub above cannot intercept — with issue left +// on, these tests file REAL tracking issues in developing-today/code +// (the exact orphan class #4917 tracks; baseline runs of this file +// filed #4937/#4938). Issue-creation and failure-compensation behaviour +// is covered hermetically by launch_failure.test.ts stubs. +const base = { repo: "developing-today/code", prompt: "do the thing", issue: false }; describe("POST /v1/sessions directory scoping (issue #2903)", () => { test("OIDC + foreign directory is rejected with 400 before any side effect", async () => {