Repository navigation
ci(openspec): gate every PR in a stack on its tip archiving #727
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,354 @@ | ||
| // SPDX-License-Identifier: MIT | ||
| "use strict"; | ||
|
|
||
| /** | ||
| * OpenSpec stack gate: a pull request is green only when the tip of its stack | ||
| * leaves no unarchived change under `openspec/changes/`. | ||
| * | ||
| * WHY THIS EXISTS. The label (`openspec-label.yml`) and the daily sweep on | ||
| * `main` (`openspec-tracking.yml`, `openspec-sweep.yml`) report rot, and | ||
| * reporting was not enough: changes kept reaching `main` unarchived, and the | ||
| * tracking issue only appears after the damage has landed. This check moves | ||
| * the question to the moment it can still be answered cheaply, before merge. | ||
| * | ||
| * WHAT DECIDES. For a pull request P, walk UP its stack to every tip: an open | ||
| * pull request in P's subtree that has no open pull request based on it. If P | ||
| * has no children, P is its own tip. P passes when every one of those tips' | ||
| * head trees carries no directory under `openspec/changes/` other than | ||
| * `archive/`. A tip contains every commit below it, so its head tree is the | ||
| * state the whole stack will leave on `main` when it lands. That is the only | ||
| * position whose answer matters, and every member of the stack gets it. | ||
| * | ||
| * WHY A COMMIT STATUS, NOT A FAILING JOB. Archiving happens on the tip, so the | ||
| * push that fixes the stack is a push to a DIFFERENT pull request than the | ||
| * ones it turns green. GitHub never re-runs a pull request's checks because | ||
| * another pull request changed, so a failing job on a lower layer would stay | ||
| * red after the tip archived. Instead, every run recomputes the whole stack it | ||
| * belongs to and writes a status on each open member's head SHA. Any event on | ||
| * any layer refreshes every layer. | ||
| * | ||
| * WHY THE EARLIER GATES WERE DELETED, AND WHAT IS DIFFERENT. They guessed at | ||
| * stack position from one pull request's point of view (`gh pr list --base`) | ||
| * and failed the job on an API error, so a `gh` timeout reddened a pull | ||
| * request for a reason unrelated to it. Here an API error fails THIS run and | ||
| * writes no status at all: whatever the previous run decided stays in place, | ||
| * and the run is visible as an errored workflow instead of a verdict. | ||
| */ | ||
|
|
||
| const CONTEXT = "OpenSpec: stack archived"; | ||
| const ARCHIVE_DIRECTORY = "archive"; | ||
| const CHANGES_PATH = "openspec/changes"; | ||
|
|
||
| /** | ||
| * Index open pull requests by number and by head branch. Same-repository | ||
| * pull requests only: the stack is keyed by branch name, and a fork sharing a | ||
| * branch name would attach itself to an unrelated stack. | ||
| */ | ||
| function indexPullRequests(pullRequests) { | ||
| const byNumber = new Map(); | ||
| const childrenOf = new Map(); | ||
| const byHead = new Map(); | ||
| for (const pullRequest of pullRequests) { | ||
| byNumber.set(pullRequest.number, pullRequest); | ||
| byHead.set(pullRequest.headRefName, pullRequest); | ||
| childrenOf.set(pullRequest.number, []); | ||
| } | ||
| for (const pullRequest of pullRequests) { | ||
| const parent = byHead.get(pullRequest.baseRefName); | ||
| if (parent && parent.number !== pullRequest.number) { | ||
| childrenOf.get(parent.number).push(pullRequest.number); | ||
| } | ||
| } | ||
| return { byNumber, byHead, childrenOf }; | ||
| } | ||
|
|
||
| /** Walk base pointers down to the pull request that targets a non-PR branch. */ | ||
| function findRoot(number, index) { | ||
| let current = index.byNumber.get(number); | ||
| if (!current) { | ||
| return undefined; | ||
| } | ||
| const seen = new Set([current.number]); | ||
| for ( | ||
| let parent = index.byHead.get(current.baseRefName); | ||
| parent && !seen.has(parent.number); | ||
| parent = index.byHead.get(current.baseRefName) | ||
| ) { | ||
| seen.add(parent.number); | ||
| current = parent; | ||
| } | ||
| return current.number; | ||
| } | ||
|
|
||
| /** Every member of the subtree rooted at `number`, in DFS pre-order. */ | ||
| function subtree(number, index) { | ||
| const members = []; | ||
| const visited = new Set(); | ||
| const visit = (n) => { | ||
| if (visited.has(n) || !index.byNumber.has(n)) { | ||
| return; | ||
| } | ||
| visited.add(n); | ||
| members.push(n); | ||
| for (const child of index.childrenOf.get(n) ?? []) { | ||
| visit(child); | ||
| } | ||
| }; | ||
| visit(number); | ||
| return members; | ||
| } | ||
|
|
||
| /** The tips above `number`: members of its subtree with no open child. */ | ||
| function tipsOf(number, index) { | ||
| return subtree(number, index).filter( | ||
| (n) => (index.childrenOf.get(n) ?? []).length === 0 | ||
| ); | ||
| } | ||
|
|
||
| /** | ||
| * The stack(s) an event touches. An open pull request touches its own stack. | ||
| * A pull request that closed or moved away touches the stack it left: the one | ||
| * containing the pull request whose head is its (old) base, because that | ||
| * parent may just have become a tip. | ||
| */ | ||
| function affectedRoots(trigger, index) { | ||
| const roots = new Set(); | ||
| const add = (number) => { | ||
| const root = number === undefined ? undefined : findRoot(number, index); | ||
| if (root !== undefined) { | ||
| roots.add(root); | ||
| } | ||
| }; | ||
| if (index.byNumber.has(trigger.number)) { | ||
| add(trigger.number); | ||
| } | ||
| for (const base of trigger.formerBases ?? []) { | ||
| add(index.byHead.get(base)?.number); | ||
| } | ||
| return [...roots].toSorted((a, b) => a - b); | ||
| } | ||
|
|
||
| /** Directory entries from the contents API, reduced to unarchived changes. */ | ||
| function unarchivedFromEntries(entries) { | ||
| return entries | ||
| .filter((entry) => entry.type === "dir" && entry.name !== ARCHIVE_DIRECTORY) | ||
| .map((entry) => entry.name) | ||
| .toSorted(); | ||
| } | ||
|
|
||
| /** | ||
| * Decide the status for one member given what each tip carries. Pure: the | ||
| * caller has already read `changesByTip` (tip number → unarchived names). | ||
| */ | ||
| function verdictFor(number, index, changesByTip) { | ||
| const tips = tipsOf(number, index); | ||
| const offending = tips.filter((tip) => changesByTip.get(tip)?.length > 0); | ||
| if (offending.length === 0) { | ||
| const where = | ||
| tips.length === 1 && tips[0] === number | ||
| ? "This pull request is the tip" | ||
| : `Tip ${tips.map((t) => `#${t}`).join(", ")}`; | ||
| return { | ||
| state: "success", | ||
| description: `${where}: no unarchived OpenSpec change`, | ||
| offending: [], | ||
| }; | ||
| } | ||
| const names = [ | ||
| ...new Set(offending.flatMap((tip) => changesByTip.get(tip))), | ||
| ].toSorted(); | ||
| const tipLabel = | ||
| offending.length === 1 && offending[0] === number | ||
| ? "this tip" | ||
| : `tip ${offending.map((t) => `#${t}`).join(", ")}`; | ||
| return { | ||
| state: "failure", | ||
| // Commit status descriptions are capped at 140 characters. | ||
| description: truncate(`Archive on ${tipLabel}: ${names.join(", ")}`, 140), | ||
| offending, | ||
| names, | ||
| }; | ||
| } | ||
|
|
||
| function truncate(text, length) { | ||
| return text.length <= length ? text : `${text.slice(0, length - 1)}…`; | ||
| } | ||
|
|
||
| /** | ||
| * Evaluate every open member of the given stacks. `readChanges(sha)` returns | ||
| * the unarchived change names in that commit's tree and throws when it cannot | ||
| * tell; one throw aborts the run before any status is written, so a partial | ||
| * read never turns into a partial verdict. | ||
| */ | ||
| async function evaluate(roots, index, readChanges) { | ||
| const members = [...new Set(roots.flatMap((root) => subtree(root, index)))]; | ||
| const tips = members.filter( | ||
| (n) => (index.childrenOf.get(n) ?? []).length === 0 | ||
| ); | ||
| const changesByTip = new Map( | ||
| await Promise.all( | ||
| tips.map(async (tip) => [ | ||
| tip, | ||
| await readChanges(index.byNumber.get(tip).headSha), | ||
| ]) | ||
| ) | ||
| ); | ||
| return members.map((number) => ({ | ||
| number, | ||
| headSha: index.byNumber.get(number).headSha, | ||
| ...verdictFor(number, index, changesByTip), | ||
| })); | ||
| } | ||
|
|
||
| /** | ||
| * Entry point for `actions/github-script`. Same-repository pull requests get | ||
| * a status on every member of their stack. A fork cannot be part of a stack | ||
| * here (no pull request in this repository can base on a fork's branch) and | ||
| * its token cannot write statuses, so a fork is judged on its own head tree | ||
| * and the verdict is the job's own result. | ||
| */ | ||
| async function run({ github, context, core }) { | ||
| const { owner, repo } = context.repo; | ||
| const event = context.payload.pull_request; | ||
|
|
||
| const readChanges = async (ref) => { | ||
| try { | ||
| // Read from this repository even for a fork: a pull request's head | ||
| // commit is reachable here through `refs/pull/<n>/head`. | ||
| const { data } = await github.rest.repos.getContent({ | ||
| owner, | ||
| repo, | ||
| path: CHANGES_PATH, | ||
| ref, | ||
| }); | ||
| if (!Array.isArray(data)) { | ||
| throw new Error(`${CHANGES_PATH} is not a directory at ${ref}`); | ||
| } | ||
| return unarchivedFromEntries(data); | ||
| } catch (error) { | ||
| // No `openspec/changes/` at all means nothing is unarchived. | ||
| if (error.status === 404) { | ||
| return []; | ||
| } | ||
| throw error; | ||
| } | ||
| }; | ||
|
|
||
| if (event.head.repo?.full_name !== `${owner}/${repo}`) { | ||
| if (event.state === "closed") { | ||
| return; | ||
| } | ||
| const names = await readChanges(event.head.sha); | ||
| if (names.length > 0) { | ||
| core.setFailed( | ||
| `This pull request leaves unarchived OpenSpec change(s): ${names.join(", ")}. Run 'pnpm openspec archive <change>' for each.` | ||
| ); | ||
| } else { | ||
| core.info("No unarchived OpenSpec change on this branch."); | ||
| } | ||
| return; | ||
| } | ||
|
|
||
| const listOpen = async () => { | ||
| const rawPulls = await github.paginate(github.rest.pulls.list, { | ||
| owner, | ||
| repo, | ||
| state: "open", | ||
| per_page: 100, | ||
| }); | ||
| return rawPulls | ||
| .filter((pr) => pr.head.repo?.full_name === `${owner}/${repo}`) | ||
| .map((pr) => ({ | ||
| number: pr.number, | ||
| headRefName: pr.head.ref, | ||
| baseRefName: pr.base.ref, | ||
| headSha: pr.head.sha, | ||
| })); | ||
| }; | ||
| const index = indexPullRequests(await listOpen()); | ||
|
|
||
| const formerBases = [event.base.ref]; | ||
| const changedBase = context.payload.changes?.base?.ref?.from; | ||
| if (changedBase) { | ||
| formerBases.push(changedBase); | ||
| } | ||
| const roots = affectedRoots({ number: event.number, formerBases }, index); | ||
| if (roots.length === 0) { | ||
| core.info(`#${event.number} belongs to no open stack; nothing to report.`); | ||
| return; | ||
| } | ||
|
|
||
| const results = await evaluate(roots, index, readChanges); | ||
|
|
||
| // Runs are not serialized, so a run that read the stack before a newer push | ||
| // can finish after the run that push triggered. Before writing, read the | ||
| // stack again: if any member's head or base moved, this run's verdict may | ||
| // be stale and the newer run will write the current one, so write nothing. | ||
| const fresh = indexPullRequests(await listOpen()); | ||
| const moved = results.filter((result) => { | ||
| const before = index.byNumber.get(result.number); | ||
| const after = fresh.byNumber.get(result.number); | ||
| return ( | ||
| !after || | ||
| after.headSha !== before.headSha || | ||
| after.baseRefName !== before.baseRefName || | ||
| (fresh.childrenOf.get(result.number) ?? []).join() !== | ||
| (index.childrenOf.get(result.number) ?? []).join() | ||
| ); | ||
| }); | ||
| if (moved.length > 0) { | ||
| core.info( | ||
| `The stack changed while this run read it (${moved.map((r) => `#${r.number}`).join(", ")}); leaving the statuses to the newer run.` | ||
| ); | ||
| return; | ||
| } | ||
| const targetUrl = `${context.serverUrl}/${owner}/${repo}/actions/runs/${context.runId}`; | ||
| for (const result of results) { | ||
| await github.rest.repos.createCommitStatus({ | ||
| owner, | ||
| repo, | ||
| sha: result.headSha, | ||
| state: result.state, | ||
| context: CONTEXT, | ||
| description: result.description, | ||
| target_url: targetUrl, | ||
| }); | ||
| core.info(`#${result.number} ${result.state}: ${result.description}`); | ||
| } | ||
|
|
||
| const failing = results.filter((r) => r.state === "failure"); | ||
| const summary = [`### ${CONTEXT}`, ""]; | ||
| if (failing.length === 0) { | ||
| summary.push( | ||
| `Every tip in this stack leaves \`${CHANGES_PATH}/\` archived. ${results.length} pull request(s) marked green.` | ||
| ); | ||
| } else { | ||
| const tips = [...new Set(failing.flatMap((r) => r.offending))].toSorted( | ||
| (a, b) => a - b | ||
| ); | ||
| const names = [...new Set(failing.flatMap((r) => r.names))].toSorted(); | ||
| summary.push( | ||
| `The tip of this stack (${tips.map((t) => `#${t}`).join(", ")}) still carries unarchived OpenSpec change(s), so every pull request below it is marked failing. Archive on the tip:`, | ||
| "", | ||
| "```bash", | ||
| ...names.map((name) => `pnpm openspec archive ${name} -y`), | ||
| "```", | ||
| "", | ||
| "Read the pre-archive check in `AGENTS.md` first: a `MODIFIED` delta replaces the standing requirement in full." | ||
| ); | ||
| } | ||
| await core.summary.addRaw(summary.join("\n")).write(); | ||
| } | ||
|
|
||
| module.exports = { | ||
| CONTEXT, | ||
| indexPullRequests, | ||
| findRoot, | ||
| subtree, | ||
| tipsOf, | ||
| affectedRoots, | ||
| unarchivedFromEntries, | ||
| verdictFor, | ||
| evaluate, | ||
| run, | ||
| }; | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[New]
indexPullRequests(and thereforebyHead/childrenOf) is built only from currently-open pull requests. When a parent PR merges with--delete-branch(the documented workflow perAGENTS.md), there's a window between GitHub'sclosedwebhook for the parent and the separate auto-retargeteditedwebhook(s) it sends to each child once the branch is actually deleted. Aclosedevent processed in that window sees the child'sbaseRefNamestill pointing at the now-closed parent's branch, which is no longer a key inbyHead— so the child is (temporarily) treated as its own root/tip, judged only on its own head tree rather than the stack it's actually still logically part of, and a status can be written for that wrong, narrower verdict.This self-heals once the
editedretarget event arrives and triggers another run, so it's a transient-consistency gap rather than a lasting bug, and it matches the stated "any event on any layer refreshes every layer" design — but it's not covered by a test, and it's worth confirming the self-heal always actually fires in practice (e.g., if a user retargets a child manually after noticing instead of GitHub doing it automatically, or if branch deletion is delayed/skipped).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Not changing this. A member's verdict depends only on the tips ABOVE it, never on its ancestors. When a parent closes, the child's subtree (and so its tips) is the same whether or not the child is momentarily treated as a root, so the verdict written in that window is the correct one, not a narrower one. A merged parent's own head SHA is never written to, since only open PRs get statuses.