Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions pm-stack/dispatch/src/enqueue_failure.ts
Original file line number Diff line number Diff line change
@@ -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<void>;
closeIssue(repo: string, issueNumber: number): Promise<void>;
}

export interface EnqueueFailureOutcome {
commented: boolean;
closed: boolean;
}

export async function handleEnqueueFailure(
github: EnqueueFailureGitHub,
repo: string,
issueNumber: number,
stage: string,
e: unknown,
): Promise<EnqueueFailureOutcome> {
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 };
}
20 changes: 20 additions & 0 deletions pm-stack/dispatch/src/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<void> {
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"]);
}
}
65 changes: 61 additions & 4 deletions pm-stack/dispatch/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";
Expand Down Expand Up @@ -219,15 +220,38 @@ async function handleSessions(req: Request, caller: CallerIdentity): Promise<Res
);
const payloadErrors = validatePayload(packet.payload);
if (payloadErrors.length) {
return json(500, { error: `internal packet validation failed: ${payloadErrors.join("; ")}` });
const msg = `internal packet validation failed: ${payloadErrors.join("; ")}`;
// The tracking issue already exists at this point (#4925): never
// leave it dangling for a task that will never be enqueued.
if (issue) {
const outcome = await handleEnqueueFailure(github, body.repo, issue.number, "packet validation", new Error(msg));
warnings.push(
outcome.closed
? `tracking issue #${issue.number} was closed as not planned after the packet validation failure`
: `tracking issue #${issue.number} could not be closed after the packet validation failure — it needs manual cleanup`,
);
}
return json(500, { error: msg, ...(warnings.length ? { warnings } : {}) });
}
let task: TaskRow;
try {
task = await requireQueue().enqueue(packet, body.repo);
} catch (e) {
// Same no-orphan rule on the enqueue itself (#4925): comment the
// failure on the issue this request created and close it as not
// planned; the response names the issue and whether it closed.
let issueClosed: boolean | undefined;
if (issue) {
const outcome = await handleEnqueueFailure(github, body.repo, issue.number, "queue enqueue", e);
issueClosed = outcome.closed;
if (!outcome.closed) {
warnings.push(`tracking issue #${issue.number} could not be closed after the enqueue failure — it needs manual cleanup`);
}
}
return json(502, {
error: e instanceof Error ? e.message : String(e),
issue_number: issue?.number ?? null,
...(issue ? { issue_closed: issueClosed } : {}),
...(warnings.length ? { warnings } : {}),
});
}
Expand Down Expand Up @@ -408,6 +432,10 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise<Respon
// NOT create an issue — the task attaches to that existing issue in
// body.repo (canonical dedupe key + agent-note comment + labels below).
let issue: IssueRef | null = null;
// Only an issue this request creates may be closed on an enqueue
// failure (#4925); an attached issue (issue_number) is the caller's
// and is never closed by dispatch.
let createdIssue: IssueRef | null = null;
if (body.issueNumber !== undefined) {
issue = {
number: body.issueNumber,
Expand All @@ -418,6 +446,7 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise<Respon
}
} else if (body.issue) {
issue = await maybeCreateIssue(body.repo, body.title, body.prompt, ["queue/queued", "source/dispatch"], warnings);
createdIssue = issue;
}

// Verify the attach target before enqueueing (#3007): a nonexistent
Expand Down Expand Up @@ -463,7 +492,18 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise<Respon
const packet = buildPacket(packetInput, dedupeKey);
const payloadErrors = validatePayload(packet.payload);
if (payloadErrors.length) {
return json(500, { error: `internal packet validation failed: ${payloadErrors.join("; ")}` });
const msg = `internal packet validation failed: ${payloadErrors.join("; ")}`;
// No-orphan rule (#4925), create path only: an issue this request
// created must not dangle for a task that will never be enqueued.
if (createdIssue) {
const outcome = await handleEnqueueFailure(github, body.repo, createdIssue.number, "packet validation", new Error(msg));
warnings.push(
outcome.closed
? `tracking issue #${createdIssue.number} was closed as not planned after the packet validation failure`
: `tracking issue #${createdIssue.number} could not be closed after the packet validation failure — it needs manual cleanup`,
);
}
return json(500, { error: msg, ...(warnings.length ? { warnings } : {}) });
}
let outcome: EnqueueDispatchOutcome;
try {
Expand All @@ -480,12 +520,29 @@ async function handleTasks(req: Request, caller: CallerIdentity): Promise<Respon
callerSuppliedKey: body.dedupeKey !== undefined,
});
} catch (e) {
if (e instanceof QueueError && e.message.startsWith("internal packet validation failed")) {
return json(500, { error: e.message });
const validationFailure = e instanceof QueueError && e.message.startsWith("internal packet validation failed");
// No-orphan rule (#4925), create path only (see createdIssue).
let issueClosed: boolean | undefined;
if (createdIssue) {
const outcome = await handleEnqueueFailure(
github,
body.repo,
createdIssue.number,
validationFailure ? "packet validation" : "queue enqueue",
e,
);
issueClosed = outcome.closed;
if (!outcome.closed) {
warnings.push(`tracking issue #${createdIssue.number} could not be closed after the enqueue failure — it needs manual cleanup`);
}
}
if (validationFailure) {
return json(500, { error: (e as Error).message, ...(warnings.length ? { warnings } : {}) });
}
return json(502, {
error: e instanceof Error ? e.message : String(e),
issue_number: issue?.number ?? null,
...(createdIssue ? { issue_closed: issueClosed } : {}),
...(body.issueNumber !== undefined && issue ? { issue_url: issue.url } : {}),
...(warnings.length ? { warnings } : {}),
});
Expand Down
20 changes: 19 additions & 1 deletion pm-stack/dispatch/src/validate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -135,10 +135,20 @@ export interface SessionRequest {
wait: boolean;
}

/** Minimum prompt length (chars, after trim) for a session request that
* carries no explicit title (issue #4925). Below this, the request is a
* placeholder, not a spec: titleFromPrompt would turn it into a real
* repo issue title (the "do the thing" family — 59 open placeholders
* accumulated before this gate), and the tracking issue's whole body
* would be that prompt. An explicit title exempts the request: the
* caller has named the work, so the title is no longer derived from
* the placeholder prompt. */
export const MIN_DERIVED_TITLE_PROMPT_CHARS = 40;

export function parseSessionRequest(body: unknown): SessionRequest {
if (typeof body !== "object" || body === null) throw new ValidationError("body: must be a JSON object");
const b = body as Record<string, unknown>;
return {
const req: SessionRequest = {
repo: reqString(b, "repo"),
prompt: reqString(b, "prompt"),
title: optNonBlankString(b, "title"),
Expand All @@ -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).
Expand Down
68 changes: 68 additions & 0 deletions pm-stack/dispatch/test/enqueue_failure.test.ts
Original file line number Diff line number Diff line change
@@ -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<void> {
calls.comments.push([repo, issueNumber, body]);
calls.events.push("comment");
if (failComment) throw new Error("github unreachable");
},
async closeIssue(repo: string, issueNumber: number): Promise<void> {
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);
});
});
4 changes: 3 additions & 1 deletion pm-stack/dispatch/test/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,9 @@ function sessionsRequest(token: string, body: Record<string, unknown>): 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 () => {
Expand Down
37 changes: 33 additions & 4 deletions pm-stack/dispatch/test/validate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand All @@ -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,
Expand All @@ -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", () => {
Expand Down Expand Up @@ -284,15 +313,15 @@ 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: "",
});
expect(r.title).toBeUndefined();
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 ",
});
Expand Down