diff --git a/README.md b/README.md index c0755cf7..759fd0e6 100644 --- a/README.md +++ b/README.md @@ -581,6 +581,7 @@ comes last, and a missing value prints as `-`: | `signal` | `finding` or `decision`, its URL, who posted it, and its text, for each [signal](#signals-that-hold-a-head) holding the head. | | `hold` | Label, acquisition token, acquisition time, verified GitHub event API URL, and age; `hold -` when no label holds it. Unknown acquisition facts print as `-` and `unknown age`. | | `starter-hold` | A draft its starter owns: last activity time, PR URL, and `last active` age. Last activity is not when ownership began. | +| `duplicate` | For an open PR, each quest it adds that another open PR also adds, at the same path or under the same title compared without its size, case, or spacing: the quest's path, the other PR's URL, and the other quest's path. A follow-up another PR already owns is dropped, or moved into that PR's quest, before a pick asks about it. | The node ID is what GraphQL's `addPullRequestReviewThreadReply` and `resolveReviewThread` take. Neutral and skipped checks pass. Only each check's @@ -602,7 +603,7 @@ requirement names one, its app, as GitHub and `quest land` do, and leaves out same facts as one object with the fields `url`, `state`, `draft`, `head`, `mergeable`, `mergeState`, `reviewDecision`, `autoMerge`, `mergeQueue`, `landingStopped`, `checks` (`state`, `passed`, `failing`, `pending`), `reviews`, `checkpoints` (`reviewer`, `round`, `url`), `reactions`, -`threads`, `signals` (`kind`, `url`, `author`, `text`), `holds` (`label`, `token`, `takenAt`, `age`, `eventUrl`), and `starterHold` (`lastActive`, `age`, `url`, or null). Ownership uses the state commands' shared reader without changing labels, and event links match the opaque acquisition token against GitHub's event listing. Long lists are paged; reactions are the newest 100 per PR or review, +`threads`, `signals` (`kind`, `url`, `author`, `text`), `holds` (`label`, `token`, `takenAt`, `age`, `eventUrl`), `starterHold` (`lastActive`, `age`, `url`, or null), and `duplicates` (`path`, `url`, `other`). Ownership uses the state commands' shared reader without changing labels, and event links match the opaque acquisition token against GitHub's event listing. Long lists are paged; reactions are the newest 100 per PR or review, as in `quest wait`. Any PR state exits 0, invalid arguments exit 2, and other failures exit 1. diff --git a/assets/AGENTS.md b/assets/AGENTS.md index 591a959a..42c2f43c 100644 --- a/assets/AGENTS.md +++ b/assets/AGENTS.md @@ -107,12 +107,14 @@ End every quest skill with a final summary in sections, such as the PRs and thei ## Creation Quests are created in PRs and reviewed. -Search the tree and git history before making a new quest. +Before making a new quest, search the tree, git history, and the quest files each open PR adds or changes, which `gh pr list --limit 1000 --json number,url,files` lists, up to 100 files a PR (`gh api --paginate 'repos/{owner}/{repo}/pulls//files'` lists the rest); a search of PR titles and bodies misses a PR that never names the subject. Split independently completable work into separate quests. Group related quests in an epic; its README holds the work no child owns. Work found along the way that is worth a quest is a follow-up: add it to the PR that found it, as a new quest placed and sized by these rules and the repository's, or an edit to the quest that owns the work; never as an agent-session task or a GitHub issue. +When another open PR's quest owns the work, add nothing: name that PR and quest in the PR body instead. +`quest status ` prints a `duplicate` line for each quest the PR adds that another open PR also adds, by path or title; resolve each before marking the PR ready or picking it, unless both PRs need the quest. Drop one you would call optional or worth doing only if it matters. Answer each of its decisions you can with your recommendation in its Plan, and list each you cannot as a `Maintainer:` decision item under its `Waiting`. The PR body's `## Follow-ups` section links each one with its open decisions, which neither keep the PR a draft nor stop its pick. diff --git a/assets/skills/review.md b/assets/skills/review.md index 4e082e04..09dbcd28 100644 --- a/assets/skills/review.md +++ b/assets/skills/review.md @@ -45,7 +45,7 @@ A reviewer out of quota or logged out is an outage, not a skip: stop reviewing, Its `## Waiting` item names the reviewer, its error, and the check, such as `Codex: out of quota until 2026-11-03 15:00 UTC; check that quest review runs`, with the reset time `quest review` prints when it exits 3 on a usage limit; a logged-out reviewer waits on `Maintainer:`, with the login command `quest review` prints. Once the reset passes or the login is restored, the item has cleared: whoever finds it runs `/quest-review` on the PR. -Push, then mark the PR ready for review: with `quest ready `, which also drops its `## Waiting` section, or with `gh pr ready ` for a draft you reviewed without a hold. +Push, resolve each `duplicate` line `quest status ` then prints as the guide's Creation describes, then mark the PR ready for review: with `quest ready `, which also drops its `## Waiting` section, or with `gh pr ready ` for a draft you reviewed without a hold. Summarize the review, with its last round's score and rationale, and CI from `quest status `. Name any decisions the review raised without answering them, then ask the user with your recommended action: diff --git a/quest/m0/follow-up-duplicates.md b/quest/m0/follow-up-duplicates.md deleted file mode 100644 index 4b220b1e..00000000 --- a/quest/m0/follow-up-duplicates.md +++ /dev/null @@ -1,14 +0,0 @@ -# [S] Agents stop adding follow-ups an open PR already owns - -## Goal - -Before an agent adds a follow-up quest, it finds any quest that already owns the work, on the base branch or in an open PR's quest files, and edits or links that one instead, so a run's merge picks stop asking to drop the same duplicate again. - -## Plan - -Planned 2026-11-15 with the maintainer in kixel-ai/rind's `/quest-run` of 2026-11-14 and 2026-11-15: - -- That run's agents added the rind-fips fork-test hang as a new follow-up five times and the dart-ios hang three times, in separate PRs, each while another open PR or main already had the quest. Each cost a pick round and a manual `quest rm` on the PR. -- `assets/AGENTS.md` says to "search the tree and git history before making a new quest", which covers main but not open PRs. Extend it to open PRs' quest files: read the `quest/**` files each open PR adds or changes. A `gh pr list --search` on the quest's subject is only a supplement, since GitHub's PR search does not read changed files and misses a PR whose text never names the subject. -- Have `quest check`, or the PR flow, warn when a PR adds a quest whose path or title another open PR also adds. A warning, not an error: two PRs may legitimately touch one quest. -- ✅ m0: duplicates cost a pick round each time in every repository using quest (rejected: m1). diff --git a/src/cli/main.ts b/src/cli/main.ts index f2b9d20c..3181c786 100644 --- a/src/cli/main.ts +++ b/src/cli/main.ts @@ -654,8 +654,10 @@ export function main(argv: string[], out: Output): number | Promise { "reviewer that approves or requests changes, its round, and its review, when that review is of the " + "head, while its latest verdict on the head is neither an approval nor a dismissal, and ends its third, sixth, ... round (one commit it reviewed), as " + "/quest-review's design checkpoint; a reacted: line per " + - "reaction on the PR or a review; a thread line per unresolved review thread, led by its node ID; and a " + - "signal line per finding or decision that holds the head from landing (see the README). " + + "reaction on the PR or a review; a thread line per unresolved review thread, led by its node ID; a " + + "signal line per finding or decision that holds the head from landing (see the README); and last, " + + "for an open PR, a duplicate line per quest it adds that another open PR also adds, at the same path or under the same title " + + "compared without its size, case, or spacing, giving the quest's path, the other PR's URL, and the other quest's path last. " + "A missing value prints as -. --json prints the same facts as one deterministic object.\n\n" + "Uses GH_TOKEN, GITHUB_TOKEN, or gh auth token. " + FORGE_READS.replace("these reads", "the read") + diff --git a/src/cli/status.ts b/src/cli/status.ts index 5298de47..c77cc0b3 100644 --- a/src/cli/status.ts +++ b/src/cli/status.ts @@ -53,5 +53,6 @@ export function statusLines(status: Status): string[] { `starter-hold ${status.starterHold.lastActive} ${status.starterHold.url} last active ${status.starterHold.age}`, ] : []), + ...status.duplicates.map((d) => `duplicate ${d.path} ${d.url} ${d.other}`), ]; } diff --git a/src/core/forge.ts b/src/core/forge.ts index eec5632d..ef66b87f 100644 --- a/src/core/forge.ts +++ b/src/core/forge.ts @@ -99,6 +99,16 @@ export interface StarterHold { url: string; } +/** A quest the PR adds that another open PR also adds, at the same path or under the same title. */ +export interface Duplicate { + /** The quest file the PR adds. */ + path: string; + /** The other open PR. */ + url: string; + /** The quest file the other PR adds: `path` itself, or another path with the same title. */ + other: string; +} + /** Everything `quest status` reports about a PR. */ export interface Status { url: string; @@ -136,6 +146,8 @@ export interface Status { signals: Signal[]; holds: HoldFact[]; starterHold: StarterHold | null; + /** Quests an open PR adds that another open PR also adds; none for a PR no longer open. */ + duplicates: Duplicate[]; } /** An open PR, from any head repository, as the claim checks read it. */ @@ -422,6 +434,7 @@ const status = shape({ }), ), starterHold: nullable(shape({ lastActive: time, age: string, url: string })), + duplicates: list(shape({ path: string, url: string, other: string })), }); const openPull = shape({ diff --git a/src/core/index.ts b/src/core/index.ts index 59559928..74896677 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -128,6 +128,7 @@ export { type Claim, type ClaimSource, type ClaimSources, + type Duplicate, FORGE_CALLS, type Forge, type ForgeCall, diff --git a/src/github/duplicates.ts b/src/github/duplicates.ts new file mode 100644 index 00000000..4a87e82e --- /dev/null +++ b/src/github/duplicates.ts @@ -0,0 +1,122 @@ +// Quests a PR adds that another open PR also adds, so a follow-up some other PR already owns is +// caught before a pick round asks about it. +import { type Duplicate, type PullRequest, isQuest, parse } from "../core"; +import { type GitHub, array, object, repositoryPath, string } from "./client"; + +/** An open PR's added quest files, each with its title, or null when it has none. */ +export interface Added { + number: number; + url: string; + quests: { path: string; title: string | null }[]; +} + +const OPEN = `query OpenQuests($owner: String!, $repo: String!, $after: String) { + repository(owner: $owner, name: $repo) { + pullRequests(states: OPEN, first: 50, after: $after) { + pageInfo { hasNextPage endCursor } + nodes { number url headRefOid files(first: 100) { pageInfo { hasNextPage } nodes { path changeType } } } + } + } +}`; + +/** Blobs read per title query. */ +const BATCH = 100; + +/** A file under a `quest/` directory, at the root or in a subdirectory holding a tree, that is a quest document. */ +const questFile = (path: string) => /(?:^|\/)quest\/./.test(path) && isQuest(path); + +/** A title compared without its size, case, or spacing, which agents vary for the same work. */ +export function titleKey(title: string): string { + return title + .replace(/^\[[^\]]*\]\s*/, "") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); +} + +/** Each quest `self` adds that another of `pulls` adds at the same path or with the same title. */ +export function duplicates(self: number, pulls: Added[]): Duplicate[] { + const own = pulls.find((pull) => pull.number === self); + if (own === undefined) return []; + const found: Duplicate[] = []; + for (const quest of own.quests) { + const key = quest.title === null ? null : titleKey(quest.title); + for (const pull of pulls) { + if (pull.number === self) continue; + for (const other of pull.quests) + if ( + other.path === quest.path || + (key !== "" && key !== null && other.title !== null && titleKey(other.title) === key) + ) + found.push({ path: quest.path, url: pull.url, other: other.path }); + } + } + return found; +} + +/** + * The quests `pr` adds that another open PR in its repository also adds. Reads every open PR's added + * files, then the titles of their quests at each PR's head, only when `pr` adds a quest. + */ +export async function duplicateQuests(github: GitHub, pr: PullRequest): Promise { + const pulls: { number: number; url: string; head: string; paths: string[] }[] = []; + for (let after: string | null = null, more = true; more;) { + const data = await github.graphql(OPEN, { owner: pr.owner, repo: pr.repo, after }); + if (data.repository === null) + throw new Error(`cannot read ${pr.owner}/${pr.repo}; check the repository and token`); + const list = object(object(data.repository).pullRequests); + for (const node of array(list.nodes)) { + const files = object(node.files); + const number = Number(node.number); + // GraphQL lists at most 100 files; REST lists up to 3,000, enough for any PR adding quests. + const added = + object(files.pageInfo).hasNextPage === true + ? (await github.all(`${repositoryPath(pr)}/pulls/${number}/files?per_page=100`)) + .filter((row) => row.status === "added") + .map((row) => string(row.filename)) + : array(files.nodes) + .filter((file) => file.changeType === "ADDED") + .map((file) => string(file.path)); + pulls.push({ + number, + url: string(node.url), + head: string(node.headRefOid), + paths: added.filter(questFile), + }); + } + const info = object(list.pageInfo); + more = info.hasNextPage === true; + after = more ? string(info.endCursor) : null; + } + const own = pulls.find((pull) => pull.number === pr.number); + if (own === undefined || own.paths.length === 0) return []; + const blobs = pulls.flatMap((pull) => pull.paths.map((path) => `${pull.head}:${path}`)); + const titles = new Map(); + for (let start = 0; start < blobs.length; start += BATCH) { + const batch = blobs.slice(start, start + BATCH); + const query = + `query($owner: String!, $repo: String!, ${batch.map((_, i) => `$e${i}: String!`).join(", ")}) { repository(owner: $owner, name: $repo) { ` + + batch.map((_, i) => `f${i}: object(expression: $e${i}) { ... on Blob { text } }`).join(" ") + + " } }"; + const data = await github.graphql(query, { + owner: pr.owner, + repo: pr.repo, + ...Object.fromEntries(batch.map((blob, i) => [`e${i}`, blob])), + }); + const repository = object(data.repository); + batch.forEach((blob, i) => { + const node = repository[`f${i}`]; + const text = node === null || node === undefined ? null : object(node).text; + const path = blob.slice(blob.indexOf(":") + 1); + titles.set(blob, typeof text === "string" ? (parse(path, text).title?.text ?? null) : null); + }); + } + return duplicates( + pr.number, + pulls.map((pull) => ({ + number: pull.number, + url: pull.url, + quests: pull.paths.map((path) => ({ path, title: titles.get(`${pull.head}:${path}`) ?? null })), + })), + ); +} diff --git a/src/github/status.ts b/src/github/status.ts index 8ea3e0e2..077b7323 100644 --- a/src/github/status.ts +++ b/src/github/status.ts @@ -29,6 +29,7 @@ import { } from "../core"; import { readHoldStatus } from "./hold"; import { readSignals } from "./signals"; +import { duplicateQuests } from "./duplicates"; /** * One query covers the PR; each connection pages by its own cursor, and a @@ -168,7 +169,8 @@ export async function pullRequestStatus(pr: PullRequest, deps: GitHubDependencie if (signaled.head !== first!.headRefOid) throw new Error("the PR head changed while reading its signals; rerun quest status"); status.signals = signaled.signals; - return { ...status, holds: ownership.holds, starterHold: ownership.starter }; + const duplicates = first!.state === "OPEN" ? await duplicateQuests(github, pr) : []; + return { ...status, holds: ownership.holds, starterHold: ownership.starter, duplicates }; } /** The risk the PR body records, judged against the head as {@link Status.risk} describes. */ @@ -467,6 +469,7 @@ function summarize( signals: [], holds: [], starterHold: null, + duplicates: [], }; } diff --git a/test/status-fakes.ts b/test/status-fakes.ts index 05b113c5..4ce6ac30 100644 --- a/test/status-fakes.ts +++ b/test/status-fakes.ts @@ -125,6 +125,8 @@ export function setup( noBase?: boolean; /** The head's workflow runs, as `GET /actions/runs` lists them. */ runs?: Node[]; + /** The open PRs as the duplicate read lists them, and each `:` blob's text. */ + open?: { pulls: Node[]; blobs?: Record; files?: Record }; } = {}, ) { const queries: Record[] = []; @@ -160,6 +162,8 @@ export function setup( : Response.json({ protection: { enabled: false } }); if (path.pathname === "/repos/example/project/rules/branches/main") return Response.json(options.rules ?? []); + const changed = /^\/repos\/example\/project\/pulls\/(\d+)\/files$/.exec(path.pathname); + if (changed) return Response.json(options.open?.files?.[Number(changed[1])] ?? []); if (path.pathname === "/repos/example/project/actions/runs") { if (!options.runs) throw new Error("unexpected workflow run request"); return Response.json({ total_count: options.runs.length, workflow_runs: options.runs }); @@ -181,6 +185,23 @@ export function setup( return Response.json(page.rows, { headers: page.next ? { Link: `<${page.next}>; rel="next"` } : {} }); } const request = JSON.parse(String(init?.body)); + if (request.query.includes("query OpenQuests(")) { + const nodes = options.open?.pulls ?? []; + return Response.json({ + data: { + repository: { pullRequests: { pageInfo: { hasNextPage: false, endCursor: null }, nodes } }, + }, + }); + } + if (request.query.includes("object(expression:")) { + const repository: Node = {}; + for (const [key, value] of Object.entries(request.variables as Record)) + if (key.startsWith("e")) { + const text = options.open?.blobs?.[value]; + repository[`f${key.slice(1)}`] = text === undefined ? null : { text }; + } + return Response.json({ data: { repository } }); + } if (request.query.includes("p1: pullRequest(number: 1)")) { if (!last) throw new Error("signals read before PR state"); const head = last.data.repository.pullRequest.headRefOid; diff --git a/test/status.test.ts b/test/status.test.ts index 3fe38ecb..b209760f 100644 --- a/test/status.test.ts +++ b/test/status.test.ts @@ -949,3 +949,89 @@ describe("checkpoint", () => { expect(await line(person)).toEqual([]); }); }); + +describe("duplicate quests", () => { + const other = "https://github.com/example/project/pull/2"; + const third = "https://github.com/example/project/pull/3"; + const files = (paths: [string, string][], more = false) => ({ + pageInfo: { hasNextPage: more }, + nodes: paths.map(([path, changeType]) => ({ path, changeType })), + }); + + test("reports each quest the PR adds that another open PR adds at its path or under its title", async () => { + const body = pull({ checks: null, reviews: page([]), threads: page([]) }); + const status = await pullRequestStatus( + pr, + setup([body], { + open: { + pulls: [ + { + number: 1, + url: URL_, + headRefOid: A, + files: files([ + ["quest/m0/hang.md", "ADDED"], + ["quest/m1/fips.md", "ADDED"], + ["quest/m0/edited.md", "MODIFIED"], + ["quest/AGENTS.md", "ADDED"], + ["src/a.ts", "ADDED"], + ]), + }, + { + number: 2, + url: other, + headRefOid: B, + files: files([ + ["quest/m0/hang.md", "ADDED"], + ["quest/m0/edited.md", "ADDED"], + ]), + }, + { + number: 3, + url: third, + headRefOid: "c".repeat(40), + // Over 100 files, so REST lists them. + files: files([["quest/m0/edited.md", "MODIFIED"]], true), + }, + ], + files: { + 3: [ + { filename: "quest/m0/fips-hang.md", status: "added" }, + { filename: "quest/m0/edited.md", status: "modified" }, + ], + }, + blobs: { + [`${A}:quest/m0/hang.md`]: "# [S] Dart iOS hang\n\n## Goal\n\nx\n", + [`${A}:quest/m1/fips.md`]: "# [M] Fix the FIPS fork-test hang\n\n## Goal\n\nx\n", + [`${B}:quest/m0/hang.md`]: "# [S] Something else\n\n## Goal\n\nx\n", + [`${B}:quest/m0/edited.md`]: "# [S] Edited\n\n## Goal\n\nx\n", + [`${"c".repeat(40)}:quest/m0/fips-hang.md`]: + "# [S] fix the fips fork-test hang\n\n## Goal\n\nx\n", + }, + }, + }).deps, + ); + expect(status.duplicates).toEqual([ + { path: "quest/m0/hang.md", url: other, other: "quest/m0/hang.md" }, + { path: "quest/m1/fips.md", url: third, other: "quest/m0/fips-hang.md" }, + ]); + expect(statusLines(status).filter((line) => line.startsWith("duplicate "))).toEqual([ + `duplicate quest/m0/hang.md ${other} quest/m0/hang.md`, + `duplicate quest/m1/fips.md ${third} quest/m0/fips-hang.md`, + ]); + }); + + test("a PR that adds no quest reads no titles, and a closed one reads no open PRs", async () => { + const open = { + pulls: [ + { number: 1, url: URL_, headRefOid: A, files: files([["quest/m0/a.md", "MODIFIED"]]) }, + { number: 2, url: other, headRefOid: B, files: files([["quest/m0/a.md", "ADDED"]]) }, + ], + }; + const body = pull({ checks: null, reviews: page([]), threads: page([]) }); + expect((await pullRequestStatus(pr, setup([body], { open }).deps)).duplicates).toEqual([]); + const closed = pull({ checks: null, reviews: page([]), threads: page([]), state: "CLOSED" }); + const opened = { pulls: [{ ...open.pulls[0]!, files: files([["quest/m0/a.md", "ADDED"]]) }, open.pulls[1]!] }; + expect((await pullRequestStatus(pr, setup([closed], { open: opened }).deps)).duplicates).toEqual([]); + }); +});