From 598fca0b122f4d3effb3fd68bdd8f7b92652393c Mon Sep 17 00:00:00 2001 From: Jakob Heuser Date: Sun, 29 Nov 2026 16:43:04 -0800 Subject: [PATCH 1/2] ci(openspec): gate every PR in a stack on its tip archiving openspec-stack.yml resolves the stack a pull request belongs to, reads the head tree of each tip, and writes an 'OpenSpec: stack archived' commit status on every open member. Every layer fails while a tip still carries an unarchived change under openspec/changes/, and turns green when the tip archives, since each run recomputes the whole stack. --- .github/scripts/openspec-stack.cjs | 325 ++++++++++++++++++++++++ .github/scripts/openspec-stack.test.cjs | 219 ++++++++++++++++ .github/workflows/openspec-label.yml | 4 + .github/workflows/openspec-stack.yml | 53 ++++ AGENTS.md | 4 +- 5 files changed, 603 insertions(+), 2 deletions(-) create mode 100644 .github/scripts/openspec-stack.cjs create mode 100644 .github/scripts/openspec-stack.test.cjs create mode 100644 .github/workflows/openspec-stack.yml diff --git a/.github/scripts/openspec-stack.cjs b/.github/scripts/openspec-stack.cjs new file mode 100644 index 000000000..df5cc8e4c --- /dev/null +++ b/.github/scripts/openspec-stack.cjs @@ -0,0 +1,325 @@ +// 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(); + for (const tip of tips) { + changesByTip.set(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//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 ' for each.` + ); + } else { + core.info("No unarchived OpenSpec change on this branch."); + } + return; + } + + const rawPulls = await github.paginate(github.rest.pulls.list, { + owner, + repo, + state: "open", + per_page: 100, + }); + const pullRequests = 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(pullRequests); + + 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); + 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, +}; diff --git a/.github/scripts/openspec-stack.test.cjs b/.github/scripts/openspec-stack.test.cjs new file mode 100644 index 000000000..595ad5789 --- /dev/null +++ b/.github/scripts/openspec-stack.test.cjs @@ -0,0 +1,219 @@ +// SPDX-License-Identifier: MIT +"use strict"; + +const test = require("node:test"); +const assert = require("node:assert/strict"); + +const { + CONTEXT, + indexPullRequests, + findRoot, + tipsOf, + affectedRoots, + unarchivedFromEntries, + verdictFor, + evaluate, + run, +} = require("./openspec-stack.cjs"); + +function pr(number, head, base, headSha = `sha${number}`) { + return { number, headRefName: head, baseRefName: base, headSha }; +} + +// main <- a(#1) <- b(#2) <- c(#3) +// \<- d(#4) +// main <- solo(#9) +const STACK = [ + pr(1, "a", "main"), + pr(2, "b", "a"), + pr(3, "c", "b"), + pr(4, "d", "b"), + pr(9, "solo", "main"), +]; + +test("findRoot walks down to the pull request on main", () => { + const index = indexPullRequests(STACK); + assert.equal(findRoot(3, index), 1); + assert.equal(findRoot(1, index), 1); + assert.equal(findRoot(9, index), 9); + assert.equal(findRoot(42, index), undefined); +}); + +test("tipsOf returns the leaves above a pull request", () => { + const index = indexPullRequests(STACK); + assert.deepEqual(tipsOf(1, index), [3, 4]); + assert.deepEqual(tipsOf(2, index), [3, 4]); + assert.deepEqual(tipsOf(3, index), [3]); + assert.deepEqual(tipsOf(9, index), [9]); +}); + +test("findRoot survives a base cycle", () => { + const index = indexPullRequests([pr(1, "x", "y"), pr(2, "y", "x")]); + assert.ok([1, 2].includes(findRoot(1, index))); +}); + +test("affectedRoots follows a closed pull request to the stack it left", () => { + const index = indexPullRequests(STACK.filter((p) => p.number !== 3)); + assert.deepEqual( + affectedRoots({ number: 3, formerBases: ["b"] }, index), + [1] + ); + assert.deepEqual( + affectedRoots({ number: 9, formerBases: ["main", "c"] }, index), + [9] + ); +}); + +test("unarchivedFromEntries keeps directories other than archive", () => { + assert.deepEqual( + unarchivedFromEntries([ + { type: "dir", name: "archive" }, + { type: "dir", name: "zeta" }, + { type: "file", name: "README.md" }, + { type: "dir", name: "alpha" }, + ]), + ["alpha", "zeta"] + ); +}); + +test("verdictFor fails every layer below an unarchived tip", () => { + const index = indexPullRequests(STACK); + const changes = new Map([ + [3, []], + [4, ["my-change"]], + ]); + assert.equal(verdictFor(1, index, changes).state, "failure"); + assert.match(verdictFor(2, index, changes).description, /#4: my-change/); + assert.equal(verdictFor(3, index, changes).state, "success"); + const tip = verdictFor(4, index, changes); + assert.equal(tip.state, "failure"); + assert.match(tip.description, /this tip/); +}); + +test("verdictFor passes when every tip is archived", () => { + const index = indexPullRequests(STACK); + const changes = new Map([ + [3, []], + [4, []], + ]); + for (const n of [1, 2, 3, 4]) { + assert.equal(verdictFor(n, index, changes).state, "success"); + } +}); + +test("verdictFor keeps the description within the status limit", () => { + const index = indexPullRequests([pr(1, "a", "main")]); + const names = Array.from({ length: 30 }, (_, i) => `change-${i}`); + const verdict = verdictFor(1, index, new Map([[1, names]])); + assert.ok(verdict.description.length <= 140); +}); + +test("evaluate reads only tips and aborts on a read error", async () => { + const index = indexPullRequests(STACK); + const read = []; + const results = await evaluate([1], index, async (sha) => { + read.push(sha); + return []; + }); + assert.deepEqual(read, ["sha3", "sha4"]); + assert.deepEqual( + results.map((r) => r.number), + [1, 2, 3, 4] + ); + + await assert.rejects( + evaluate([1], index, async () => { + throw new Error("boom"); + }), + /boom/ + ); +}); + +function fakeGitHub({ pulls, contents }) { + const statuses = []; + const github = { + paginate: async (_method, _options) => pulls, + rest: { + pulls: { list: () => {} }, + repos: { + getContent: async ({ ref }) => { + if (!(ref in contents)) { + const error = new Error("Not Found"); + error.status = 404; + throw error; + } + return { data: contents[ref] }; + }, + createCommitStatus: async (status) => { + statuses.push(status); + }, + }, + }, + }; + return { github, statuses }; +} + +function rawPull(number, head, base, sha, repo = "o/r") { + return { + number, + head: { ref: head, sha, repo: { full_name: repo } }, + base: { ref: base }, + }; +} + +function fakeCore() { + const core = { + failed: undefined, + info: () => {}, + setFailed: (message) => { + core.failed = message; + }, + summary: { addRaw: () => ({ write: async () => {} }) }, + }; + return core; +} + +test("run writes a status on every member of the stack", async () => { + const pulls = [ + rawPull(1, "a", "main", "s1"), + rawPull(2, "b", "a", "s2"), + rawPull(7, "other", "main", "s7"), + ]; + const { github, statuses } = fakeGitHub({ + pulls, + contents: { s2: [{ type: "dir", name: "pending-change" }] }, + }); + const context = { + repo: { owner: "o", repo: "r" }, + serverUrl: "https://github.com", + runId: 5, + payload: { pull_request: { ...pulls[0], state: "open" } }, + }; + await run({ github, context, core: fakeCore() }); + assert.deepEqual( + statuses.map((s) => [s.sha, s.state, s.context]), + [ + ["s1", "failure", CONTEXT], + ["s2", "failure", CONTEXT], + ] + ); +}); + +test("run fails a fork with unarchived changes without writing statuses", async () => { + const fork = rawPull(3, "main", "main", "f3", "someone/r"); + const { github, statuses } = fakeGitHub({ + pulls: [fork], + contents: { f3: [{ type: "dir", name: "x" }] }, + }); + const core = fakeCore(); + await run({ + github, + context: { + repo: { owner: "o", repo: "r" }, + payload: { pull_request: { ...fork, state: "open" } }, + }, + core, + }); + assert.equal(statuses.length, 0); + assert.match(core.failed, /x/); +}); diff --git a/.github/workflows/openspec-label.yml b/.github/workflows/openspec-label.yml index 1441db36d..bbb87c68c 100644 --- a/.github/workflows/openspec-label.yml +++ b/.github/workflows/openspec-label.yml @@ -11,6 +11,10 @@ name: OpenSpec Label # to be red is not a signal. A label costs a shrug when it is wrong, which is # what lets the predicate stay simple enough to be dependable. # +# THE GATE LIVES ELSEWHERE. `openspec-stack.yml` is the blocking check: it +# resolves the whole stack, judges its tip, and writes one commit status on +# every member. This workflow stays as the label and the tip warning. +# # THE LABEL PREDICATE ASKS NOTHING ABOUT STACK POSITION. It reads the head tree: # does any directory other than `archive/` exist under `openspec/changes/`? A # stack has not resolved its OpenSpec change until one of its branches archives diff --git a/.github/workflows/openspec-stack.yml b/.github/workflows/openspec-stack.yml new file mode 100644 index 000000000..b559f2285 --- /dev/null +++ b/.github/workflows/openspec-stack.yml @@ -0,0 +1,53 @@ +name: OpenSpec Stack + +# Fails every pull request in a stack whose tip still carries an unarchived +# OpenSpec change. The verdict is a commit status, `OpenSpec: stack archived`, +# written on EVERY open member's head SHA, because the push that fixes a stack +# (archiving on the tip) lands on a different pull request than the ones it +# turns green. The reasoning, and why this differs from the gates deleted in +# 8d1f3a1, lives in `.github/scripts/openspec-stack.cjs`. +# +# The job itself only fails when it cannot read the stack (an API error) or, +# for a fork pull request, when the fork's own branch is unarchived: a fork's +# token cannot write statuses, and a fork can never be part of a stack here. + +on: + # No `branches:` filter: a filter is not a dependable way to scope a workflow + # on stacked pull requests (see AGENTS.md, "`branches:` filters do not tell + # you where a workflow runs"). + # + # - opened / synchronize / reopened / ready_for_review: the head changed. + # - edited: a retarget moves a pull request into or out of a stack. + # - closed: the closed pull request's parent may have just become the tip. + pull_request: + types: [opened, reopened, synchronize, ready_for_review, edited, closed] + +# No cancel-in-progress: two runs can belong to two different stacks, and +# cancelling one would leave its stack's statuses stale. Each run rewrites +# every status from fresh API reads, so overlapping runs converge. + +permissions: + contents: read + pull-requests: read + statuses: write + +jobs: + stack: + name: OpenSpec Stack + runs-on: ubuntu-latest + # An `edited` event that is not a retarget (title or body) changes nothing + # this check reads. + if: github.event.action != 'edited' || github.event.changes.base != null + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + # The head commit rather than the default merge ref, which no longer + # exists once a pull request has closed. + ref: ${{ github.event.pull_request.head.sha }} + sparse-checkout: .github/scripts + + - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + const gate = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/openspec-stack.cjs`); + await gate.run({ github, context, core }); diff --git a/AGENTS.md b/AGENTS.md index f1a2aa91e..0f475518b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -140,7 +140,7 @@ The proposal states which of these the change is, and why. Decide it while writi **Merge down only for a vendor upgrade, or laterally when the upgrade is a machine-generated PR.** Bumping a vendored engine (ast-grep, Vale) is the one case where a red layer is the point. The bump goes in its own layer, so a reviewer sees exactly what the new version broke, and the layers above it are the codemods and fixes that make it green. That bottom layer cannot be green on its own by construction, so `gh stack merge` cannot land the stack, and it merges down instead (below). When the bump arrives as a PR the upgrade workflow opened, do not stack on it: merging down would land the fixes into a machine-generated branch. Merge laterally instead (below). -Note how this interacts with archiving: a change is archived exactly once, on whichever PR is the tip. **No check gates that anywhere any more, though the state is reported.** A PR-time gate could only guess at stack position, and guessed wrong often enough to be ignored; a `main`-only gate replaced it and turned `main` red for the entire time a stack merged one PR at a time was draining, which is a red that means "work is in progress" rather than "something is wrong". A signal that is expected to be red is not a signal. Archiving is a step you perform on the tip, and what replaced the gates reports instead of failing: an `Open OpenSpec` label and a tip warning on pull requests, and on `main` a tracking issue and a stale-work sweep, which is the abandoned work neither gate measured. +Note how this interacts with archiving: a change is archived exactly once, on whichever PR is the tip. **Every PR in a stack is gated on its tip having archived.** `openspec-stack.yml` walks each PR up to the tip(s) of its stack, reads the tip's head tree, and writes an `OpenSpec: stack archived` commit status on every open member: failing on all of them while any tip still carries a directory under `openspec/changes/` other than `archive/`, passing on all of them once the tip archives. It is a status rather than a failing job because the push that fixes the stack lands on the tip, a different PR from the ones it turns green; every run recomputes the whole stack, so any event on any layer refreshes every layer. This replaces a reporting-only setup that let changes reach `main` unarchived. Earlier gates were deleted for guessing at stack position from one PR's point of view and for reddening a PR when `gh` timed out; this one resolves the whole stack, and an API error fails its own run without writing any status. Expect the lower layers of a stack to be red while you are still building it: the tip is the last branch pushed, and it has not archived yet. Archive on the tip and the whole stack turns green. The `Open OpenSpec` label, the tip warning, and the tracking issue and stale-work sweep on `main` still run as reporting. ### One changeset, at the bottom of the stack, grown as the stack grows @@ -331,7 +331,7 @@ This happens when the **parent** PR is merged with `--delete-branch`: deleting t - **Projects-classic deprecation** breaks some GraphQL-backed `gh` commands (e.g. `gh pr reopen`). Workaround: use the REST API for PR state changes (`gh api --method PATCH .../pulls/ -f state=open`). - **`gh pr update-branch` may not exist** in the installed `gh`; update locally (`git merge origin/main` on the up-to-date remote branch) and push. -- **Nothing fails over an unarchived change, but it is reported.** An unarchived change directory is expected on a pull request AND on `main` while a stack merged one PR at a time drains. Neither is a failure: no check status reports it, nothing blocks a merge, and `openspec-label.yml` is deliberately not a step in `Validate`, so an unarchived change cannot gate a nightly publish. It is still reported. That workflow reads the head tree on every pull request, asking only whether any directory other than `archive/` exists under `openspec/changes/`, and applies the `Open OpenSpec` label. The predicate asks nothing about stack position, so every PR in a stack gets the same answer and the label clears once a branch archives the change. On the tip, where no open PR bases on the head branch, it adds a `::warning::` annotation and a job summary naming the `pnpm openspec archive` line to run; read the `OpenSpec Label` job for it, since nothing is posted to the conversation. On `main`, `openspec-tracking.yml` opens a tracking issue for an unarchived change no open pull request is working on, and `openspec-sweep.yml` escalates it once the directory has gone seven days without activity. Archive the change on the tip slice, and treat the tip warning as feedback to act on rather than as a gate. +- **An unarchived change fails the whole stack until its tip archives.** `openspec-stack.yml` writes the `OpenSpec: stack archived` status described under **Every OpenSpec proposal declares its delivery shape**. It is deliberately not a step in `Validate`, so it cannot gate a nightly publish. Read the `OpenSpec Stack` job summary on any layer for the `pnpm openspec archive` lines to run on the tip. Alongside it, `openspec-label.yml` applies the `Open OpenSpec` label when a head tree carries an unarchived change and adds a `::warning::` on the tip; on `main`, `openspec-tracking.yml` opens a tracking issue for an unarchived change no open pull request is working on, and `openspec-sweep.yml` escalates it after seven days without activity. - **Clean up local branches** once the stack lands: `git fetch --prune`, then delete the branches that merged (`git branch --merged main`). ## A spec delta REPLACES a requirement, it does not patch it From 35151c69100e268a929ffc9d6df3a6fdb42ee146 Mon Sep 17 00:00:00 2001 From: Jakob Heuser Date: Sun, 29 Nov 2026 16:51:16 -0800 Subject: [PATCH 2/2] fix(ci): run the OpenSpec stack gate from main, and skip stale writes - Check out the default branch's script: the job holds statuses: write and a same-repository token is not downgraded, so a PR-supplied script could forge a green status. - Re-read the stack before writing and write nothing if any member moved, so a run that finishes late cannot overwrite a newer verdict. - Read tips concurrently. --- .github/scripts/openspec-stack.cjs | 67 ++++++++++++++++++------- .github/scripts/openspec-stack.test.cjs | 22 ++++++++ .github/workflows/openspec-stack.yml | 28 ++++++++--- 3 files changed, 91 insertions(+), 26 deletions(-) diff --git a/.github/scripts/openspec-stack.cjs b/.github/scripts/openspec-stack.cjs index df5cc8e4c..243baf758 100644 --- a/.github/scripts/openspec-stack.cjs +++ b/.github/scripts/openspec-stack.cjs @@ -185,10 +185,14 @@ async function evaluate(roots, index, readChanges) { const tips = members.filter( (n) => (index.childrenOf.get(n) ?? []).length === 0 ); - const changesByTip = new Map(); - for (const tip of tips) { - changesByTip.set(tip, await readChanges(index.byNumber.get(tip).headSha)); - } + 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, @@ -245,21 +249,23 @@ async function run({ github, context, core }) { return; } - const rawPulls = await github.paginate(github.rest.pulls.list, { - owner, - repo, - state: "open", - per_page: 100, - }); - const pullRequests = 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(pullRequests); + 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; @@ -273,6 +279,29 @@ async function run({ github, context, core }) { } 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({ diff --git a/.github/scripts/openspec-stack.test.cjs b/.github/scripts/openspec-stack.test.cjs index 595ad5789..550590fba 100644 --- a/.github/scripts/openspec-stack.test.cjs +++ b/.github/scripts/openspec-stack.test.cjs @@ -217,3 +217,25 @@ test("run fails a fork with unarchived changes without writing statuses", async assert.equal(statuses.length, 0); assert.match(core.failed, /x/); }); + +test("run writes nothing when the stack moved while it was read", async () => { + const before = [rawPull(1, "a", "main", "s1"), rawPull(2, "b", "a", "s2")]; + const after = [rawPull(1, "a", "main", "s1"), rawPull(2, "b", "a", "s2b")]; + const { github, statuses } = fakeGitHub({ + pulls: before, + contents: { s2: [{ type: "dir", name: "pending-change" }] }, + }); + let calls = 0; + github.paginate = async () => (calls++ === 0 ? before : after); + await run({ + github, + context: { + repo: { owner: "o", repo: "r" }, + serverUrl: "https://github.com", + runId: 6, + payload: { pull_request: { ...before[0], state: "open" } }, + }, + core: fakeCore(), + }); + assert.equal(statuses.length, 0); +}); diff --git a/.github/workflows/openspec-stack.yml b/.github/workflows/openspec-stack.yml index b559f2285..b9b116e11 100644 --- a/.github/workflows/openspec-stack.yml +++ b/.github/workflows/openspec-stack.yml @@ -22,9 +22,10 @@ on: pull_request: types: [opened, reopened, synchronize, ready_for_review, edited, closed] -# No cancel-in-progress: two runs can belong to two different stacks, and -# cancelling one would leave its stack's statuses stale. Each run rewrites -# every status from fresh API reads, so overlapping runs converge. +# No concurrency group: two runs can belong to two different stacks, and a +# group would cancel one stack's pending run in favour of another's. Instead a +# run re-reads the stack just before writing and writes nothing if any member +# moved meanwhile, leaving the verdict to the run that move triggered. permissions: contents: read @@ -39,15 +40,28 @@ jobs: # this check reads. if: github.event.action != 'edited' || github.event.changes.base != null steps: + # The DEFAULT branch's copy of the script, never the PR head: this job + # holds `statuses: write`, and a same-repository branch's token is not + # downgraded, so a PR-supplied script could forge a green status on any + # pull request. Same rule as the dispatch job in `stack-breadcrumb.yml`. + # A change to the script therefore takes effect only once it is merged. - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 with: - # The head commit rather than the default merge ref, which no longer - # exists once a pull request has closed. - ref: ${{ github.event.pull_request.head.sha }} + ref: ${{ github.event.repository.default_branch }} sparse-checkout: .github/scripts - uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 with: script: | - const gate = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/openspec-stack.cjs`); + let gate; + try { + gate = require(`${process.env.GITHUB_WORKSPACE}/.github/scripts/openspec-stack.cjs`); + } catch (error) { + // Bootstrap: before this lands, the default branch has no script. + if (error.code === "MODULE_NOT_FOUND") { + core.info("openspec-stack script not on the default branch yet; skipping until merged."); + return; + } + throw error; + } await gate.run({ github, context, core });