Skip to content

Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA

TypeScript

feat(release): versions at release under merge: direct (GSTA-258 L2 PR 2) (#3978)

Garry Tan9e826b299422
diff --git a/bin/gstack-doctor-components.sh b/bin/gstack-doctor-components.sh
index d9ea2cfd5..5652eab65 100644
--- a/bin/gstack-doctor-components.sh
+++ b/bin/gstack-doctor-components.sh
@@ -352,6 +352,8 @@ gstack_result_anchor() {
QUEUE_LAND_CHECKS) printf '%s' 'queue-land-checks' ;;
QUEUE_LAND_NOT_CLEAN) printf '%s' 'queue-land-not-clean' ;;
QUEUE_LAND_UNVERIFIED) printf '%s' 'queue-land-unverified' ;;
+ RELEASE_STAMP_EMPTY) printf '%s' 'release-stamp-empty' ;;
+ RELEASE_STAMP_INVALID) printf '%s' 'release-stamp-invalid' ;;
PR_WAIT_BLOCKED) printf '%s' 'pr-wait-blocked' ;;
PR_WAIT_REFUSED) printf '%s' 'pr-wait-refused' ;;
PREGATE_HEAD_POLICY_LOOSENS) printf '%s' 'pregate-head-policy-loosens' ;;
diff --git a/bin/gstack-release-stamp b/bin/gstack-release-stamp
new file mode 100755
index 000000000..c66278484
--- /dev/null
+++ b/bin/gstack-release-stamp
@@ -0,0 +1,47 @@
+#!/usr/bin/env -S bun --no-env-file --config=/dev/null
+/**
+ * gstack-release-stamp — versions at release under merge: direct (docs/ship-policy.md#release-stamp).
+ *
+ * gstack-release-stamp open [--base <branch>] [--dry-run]
+ *
+ * Stamps a fresh worktree of origin/<base> with gstack-restamp --release (VERSION, package.json version, every
+ * changelog.d fragment folded into the CHANGELOG, release outputs, stamp_paths), commits it on release/<version>,
+ * pushes that branch and opens the release PR. The Captain lands it with gstack-ship-queue land --pr <n> --pin <head>;
+ * the stable cut then tags v<version>. Runs the base policy's release_tool. Logic: lib/release-stamp.ts.
+ */
+import { spawnSync } from 'node:child_process';
+import { EXIT, exitTableHelp, formatResult } from '../lib/headless-artifacts';
+import { openRelease } from '../lib/release-stamp';
+import { RESULT_CODES } from '../lib/result-codes';
+import { resolveBaseBranch } from '../lib/ship-policy';
+
+const HELP = `gstack-release-stamp — open the release PR that stamps versions under merge: direct (docs/ship-policy.md#release-stamp)
+
+ open stamp origin/<base> (gstack-restamp --release), push release/<version>, open its PR
+ --base <branch> base branch (default: origin/HEAD, else main)
+ --dry-run stamp in a throwaway worktree and print the diff; push and open nothing
+
+Prints RELEASE: <old> -> <new>, the stage table, PUSHED:, RELEASE_PR: and NEXT: (the land --pin command), then
+GSTACK_RESULT: skill=release-stamp status=complete|refused|incomplete.
+${exitTableHelp()}`;
+
+function main(argv: string[]): number {
+ if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }
+ if (argv[0] !== 'open') { process.stderr.write(`gstack-release-stamp: the only command is open\n${HELP}\n`); return EXIT.usage; }
+ const root = spawnSync('git', ['rev-parse', '--show-toplevel'], { encoding: 'utf8', timeout: 15_000 });
+ if (root.status !== 0) { process.stderr.write('gstack-release-stamp: not inside a git repository\n'); return EXIT.usage; }
+ const repoRoot = root.stdout.trim();
+ const i = argv.indexOf('--base');
+ const r = openRelease({ repoRoot, base: resolveBaseBranch(repoRoot, i >= 0 ? argv[i + 1] : undefined), dryRun: argv.includes('--dry-run') });
+ for (const line of r.lines) process.stdout.write(line + (line.endsWith('\n') ? '' : '\n'));
+ if (!r.ok) {
+ process.stderr.write(`gstack-release-stamp: ${r.message}; fix: ${RESULT_CODES[r.code].fix} (${r.code})\n`);
+ const refused = r.code !== 'RESTAMP_CONFLICT';
+ process.stdout.write(formatResult('release-stamp', refused ? 'refused' : 'incomplete', '-') + '\n');
+ return refused ? EXIT.refused : EXIT.fail;
+ }
+ process.stdout.write(formatResult('release-stamp', 'complete', r.url ?? r.branch) + '\n');
+ return EXIT.ok;
+}
+
+process.exitCode = main(process.argv.slice(2));
diff --git a/bin/gstack-restamp b/bin/gstack-restamp
index ef6e44c7b..e33fa228a 100755
--- a/bin/gstack-restamp
+++ b/bin/gstack-restamp
@@ -2,7 +2,7 @@
/**
* gstack-restamp — the whole stamp in one step (plan C2).
*
- * gstack-restamp --next | --version <X> | --after <pr> [--predecessor-ref <ref>]
+ * gstack-restamp --next | --version <X> | --after <pr> [--predecessor-ref <ref>] | --release
* [--base <branch>] [--bump micro|patch|minor|major] [--queue-mode stamp-at-merge|claim-at-open]
* [--pr <n>] [--expect-base <sha>] [--expect-order <pr,pr,...>]
* [--policy-from base|head] [--allow-repo-commands] [--dry-run] [--json]
@@ -33,6 +33,8 @@ const HELP = `gstack-restamp — stamp the version, release tool, CHANGELOG and
--next base version at origin/<base> plus the policy bump (stamp-at-merge ignores claims)
--version <X> stamp exactly X
--after <pr> gate-ahead: stamp a merge of HEAD and the predecessor's head in a throwaway worktree
+ --release versions at release (merge: direct): on a clean checkout of origin/<base>, fold every
+ changelog fragment there under base + their bump (gstack-release-stamp open runs this)
--predecessor-ref <ref> the predecessor's head (default refs/pull/<pr>/head; fetch it first)
--base <branch> base branch (default: origin/HEAD, else main)
--bump <level> micro|patch|minor|major (default: policy bump, else micro)
@@ -101,9 +103,10 @@ function stage(root: string, written: string[] | null): Staging | null {
function main(argv: string[]): number {
if (argv.includes('--help') || argv.includes('-h')) { process.stdout.write(HELP + '\n'); return EXIT.ok; }
const json = argv.includes('--json');
- const modes = ['--next', '--version', '--after'].filter(f => argv.includes(f));
- if (modes.length !== 1) { process.stderr.write(`gstack-restamp: pass exactly one of --next, --version <X>, --after <pr>\n${HELP}\n`); return EXIT.usage; }
+ const modes = ['--next', '--version', '--after', '--release'].filter(f => argv.includes(f));
+ if (modes.length !== 1) { process.stderr.write(`gstack-restamp: pass exactly one of --next, --version <X>, --after <pr>, --release\n${HELP}\n`); return EXIT.usage; }
const bump = flag(argv, '--bump') as Bump | undefined;
+ if (bump && argv.includes('--release')) { process.stderr.write('gstack-restamp: --release takes its bump from the fragments; drop --bump\n'); return EXIT.usage; }
if (bump && !['micro', 'patch', 'minor', 'major'].includes(bump)) { process.stderr.write('gstack-restamp: --bump needs micro|patch|minor|major\n'); return EXIT.usage; }
const queueMode = flag(argv, '--queue-mode') as 'stamp-at-merge' | 'claim-at-open' | undefined;
if (queueMode && !['stamp-at-merge', 'claim-at-open'].includes(queueMode)) { process.stderr.write('gstack-restamp: --queue-mode needs stamp-at-merge|claim-at-open\n'); return EXIT.usage; }
@@ -119,7 +122,7 @@ function main(argv: string[]): number {
repoRoot, base, version: flag(argv, '--version'), next: argv.includes('--next'), bump, queueMode,
after: after ? { pr: after, ref: flag(argv, '--predecessor-ref') } : undefined, pr: flag(argv, '--pr'),
expectBase: flag(argv, '--expect-base'), was: flag(argv, '--was'), expectOrder: flag(argv, '--expect-order')?.split(',').map(s => s.trim()).filter(Boolean),
- policyFrom, allowRepoCommands: argv.includes('--allow-repo-commands'), dryRun: argv.includes('--dry-run'),
+ policyFrom, allowRepoCommands: argv.includes('--allow-repo-commands'), dryRun: argv.includes('--dry-run'), release: argv.includes('--release'),
failAfter: process.env.GSTACK_RESTAMP_FAIL_AFTER,
};
const writes = !after && !options.dryRun;
diff --git a/changelog.d/README.md b/changelog.d/README.md
index f3d1bedbd..16edc326c 100644
--- a/changelog.d/README.md
+++ b/changelog.d/README.md
@@ -1,3 +1,3 @@
# CHANGELOG fragments
-A PR adds its CHANGELOG entry here as `changelog.d/<branch-slug>.md`: the entry text only, with no `## [x]` heading, and `bump: minor` or `bump: major` front matter only when the change warrants more than a patch. It never edits VERSION, `package.json`'s version or a released CHANGELOG section. The merge step (`gstack-ship-queue land`, or `train land` in a stamped train) assigns the version, folds every fragment into one CHANGELOG section and deletes the files. This README is skipped. See docs/ship-policy.md#changelog-fragments.
+A PR adds its CHANGELOG entry here as `changelog.d/<branch-slug>.md`: the entry text only, with no `## [x]` heading, and `bump: minor` or `bump: major` front matter only when the change warrants more than a patch. It never edits VERSION, `package.json`'s version or a released CHANGELOG section. The merge step (`gstack-ship-queue land`, or `train land` in a stamped train) assigns the version (under `merge: direct`, the release PR from `gstack-release-stamp open` does), folds every fragment into one CHANGELOG section and deletes the files. This README is skipped. See docs/ship-policy.md#changelog-fragments.
diff --git a/changelog.d/gsta258-l2-release-stamp.md b/changelog.d/gsta258-l2-release-stamp.md
new file mode 100644
index 000000000..08467f641
--- /dev/null
+++ b/changelog.d/gsta258-l2-release-stamp.md
@@ -0,0 +1,4 @@
+---
+bump: minor
+---
+- **Versions at release under `merge: direct`.** `gstack-release-stamp open` stamps `origin/main` with the new `gstack-restamp --release`, which folds every `changelog.d` fragment under one new CHANGELOG heading, bumps VERSION and `package.json` by the highest fragment bump, reruns the release tool and moves tentative `*_KEY_VERSION` constants. It then pushes `release/<version>` and opens the release PR. `gstack-ship-queue land --pin` lands a `release/<version>` head without a /ship receipt, but only when it is exactly that stamp (`RELEASE_STAMP_INVALID` otherwise), and the Version Gate applies the same check. This lets the stable cut tag a new version again now that PRs land unstamped.
diff --git a/docs/CHANGELOG_STYLE.md b/docs/CHANGELOG_STYLE.md
index ce6723fe8..769810df6 100644
--- a/docs/CHANGELOG_STYLE.md
+++ b/docs/CHANGELOG_STYLE.md
@@ -13,7 +13,9 @@ as the single source.
**Versioning invariant.** VERSION is a monotonic ordered release identifier,
not a strict semver commitment. The bump level (major/minor/patch/micro)
-expresses intent. Versions are assigned at merge, in merge order: each stamp
+expresses intent. Versions are assigned at merge, in merge order (under
+`merge: direct`, at release: one release PR folds every landed fragment under
+one new version, [ship-policy.md](ship-policy.md#release-stamp)): each stamp
takes the version before it plus the effective bump, which is the policy's
PATCH raised by any folded fragment's `bump:` front matter. If PR A and PR B
both ask for MINOR and land back to back on v1.6.0.0, A lands at v1.7.0.0 and
@@ -38,7 +40,8 @@ branch that ships writes one entry as `changelog.d/<branch-slug>.md`: the entry
text only, with no `## [x]` heading, and `bump: minor` or `bump: major` front
matter only when the change warrants more than a PATCH. A branch never edits
VERSION, package.json's version or a released CHANGELOG.md section. At merge,
-`train land` (or `gstack-ship-queue land`) assigns the version, folds the
+`train land` (or `gstack-ship-queue land`) assigns the version (under
+`merge: direct`, the release PR from `gstack-release-stamp open` does), folds the
fragment into one `## [<version>] - <date>` section at the top of CHANGELOG.md
and deletes the file. The entry describes what THIS branch adds — not what was
already on main.
diff --git a/docs/captain.md b/docs/captain.md
index 0e197f686..a6c618e9f 100644
--- a/docs/captain.md
+++ b/docs/captain.md
@@ -332,7 +332,11 @@ commits. Each PR merges at its own green head, and versions are set at release
leaves VERSION, the `package.json` version and CHANGELOG.md alone.
2. Captain: `gstack-ship-queue land --pr <n> --pin <sha>`. It merges with
`--match-head-commit`, checks main's tree and writes a land note.
-3. Release: the release gate stamps the version and folds the fragments.
+3. Release: before each stable cut (Monday and Thursday, 14:00 UTC), the Captain runs
+ `gstack-release-stamp open`, waits for the release PR's checks, then lands it with
+ `gstack-ship-queue land --pr <n> --pin <head>` (no /ship receipt or READY note needed for a
+ `release/<version>` head). The cut then tags the new version
+ ([ship-policy.md](ship-policy.md#release-stamp)).
What to do with each refusal (nothing was merged unless the code says so):
@@ -347,6 +351,8 @@ What to do with each refusal (nothing was merged unless the code says so):
| `QUEUE_TRAIN_FROZEN` / `QUEUE_LAND_LOCKED` | Captain | finish the repair or the holder first |
| `QUEUE_TRAIN_UNTRUSTED` | Captain | a fork head; rewrite on a crew branch |
| `QUEUE_LAND_UNVERIFIED` | Captain | merged, but main isn't the pin on its parent: revert the stray change, report it |
+| `RELEASE_STAMP_INVALID` | Captain | the `release/<version>` head is more than its stamp: close it, `gstack-release-stamp open` again |
+| `RELEASE_STAMP_EMPTY` | Captain | no fragment landed since the last release: nothing to release |
## Merge trains
diff --git a/docs/releases.md b/docs/releases.md
index 520a22987..fd358d6e6 100644
--- a/docs/releases.md
+++ b/docs/releases.md
@@ -1,8 +1,19 @@
# Releases and update channels
-gstack stamps a version at every merge to main, about a dozen a day. Since
-late October 2026 there is also a tagged release, cut twice a week, and
-team-mode installs follow it instead of every merge.
+gstack used to stamp a version at every merge to main. Under `merge: direct`
+PRs land unstamped, with a `changelog.d` fragment each, and the version moves
+only when the Captain lands a release PR (`gstack-release-stamp open`, see
+[ship-policy.md](ship-policy.md#release-stamp)). Since late October 2026 there
+is also a tagged release, cut twice a week, and team-mode installs follow it
+instead of every merge.
+
+Land a release PR before each cut. The cut tags the VERSION it finds, and a
+version is tagged once: if no release PR landed since the last cut, the next
+cut finds that version's tag on an older commit and refuses. A release PR
+lands only on the main it was stamped on, so open it again if main moved. The
+cut tags the newest green commit, so a PR that lands between the release PR
+and the cut ships in that tag, and its CHANGELOG entry appears in the next
+release.
## What a release is
@@ -261,7 +272,8 @@ Two edge cases are handled on purpose:
hotfix was cut below it) stays where it is until stable passes it. The
updater never moves a checkout backwards. A depth-1 clone cannot see that an
older release is its ancestor, so the VERSIONs decide: main stamps a higher
- version at every merge and stable is always a main commit.
+ version at every merge (under `merge: direct`, at every release PR) and stable is
+ always a main commit.
The local branch stays `main` either way. A stable install is a `main`
checkout parked at the last released commit, which is why fast-forward-only
@@ -270,7 +282,8 @@ still holds and nothing about version stamping changed.
## Cutting a release by hand (hotfixes)
A hotfix is an ordinary PR: it merges to main through a train and gets its
-version like any other change. To put it on stable before the next scheduled
+version like any other change (under `merge: direct`, from the next [release
+PR](ship-policy.md#release-stamp), which has to land before the cut). To put it on stable before the next scheduled
cut, run the workflow by hand with the merge commit's SHA, once the 72-hour
floor allows it (a security or regression fix uses its input instead):
diff --git a/docs/ship-policy.md b/docs/ship-policy.md
index 5c0eedd2b..6c286e92b 100644
--- a/docs/ship-policy.md
+++ b/docs/ship-policy.md
@@ -66,7 +66,7 @@ refuses the file (`POLICY_GSTACK_TOO_OLD`). `validate` ends with
| `train` | `{ gate_workflow, free_workflow, full_gate_check, record_artifact, max_size, fill_hours, screen_selection, trial_reservation_usd, land? }`, `{ gates, land, max_size, fill_hours }` or `null` | `null` | Turns on [merge trains](#run-a-merge-train), read from the base revision only. Every field is required and an unknown field is `POLICY_INVALID`: `max_size` 1 to 6, `fill_hours` above 0 and at most 24, `screen_selection` `gstack-paid` \| `none`, `trial_reservation_usd` above 0 and at most 100. A block with `gates` ([any repository](#train-gates)) takes `max_size` 1 to 5 and needs `min_gstack_version` at least `TRAIN_GATES_KEY_VERSION`. `null` keeps the per-PR queue exactly as it is. Needs `min_gstack_version`. |
| `merge` | `train` \| `direct` | `train` | `direct` lands each READY PR at its own green head with [`land --pr <n> --pin <sha>`](#land-direct): no train and no stamp commit, and `train build` refuses. A PR then leaves VERSION, the `package.json` version and the CHANGELOG at its merge base, and the release sets them. Needs `changelog_fragments`, and the stamping `land --pr <n>` refuses under it. `train` keeps merge trains. Read from the base revision only. Needs `min_gstack_version`. |
| `base_red` | `{ setup, select, timeout_sec }` or `null` | `null` | How `/ship` Step 5 proves a failure is the base branch's own before pausing on it; see [base_red](#base-red). Read from the base revision only. Needs `min_gstack_version`. |
-| `changelog_fragments` | `{ dir, required_checks? }` or `null` | `null` | PRs carry unversioned [CHANGELOG fragments](#changelog-fragments) in `dir` (one flat, repo-relative directory, no `..`) and the merge step ([`land`](#land)) assigns the version. `required_checks` (up to 50 distinct names) are the checks [`train land`](#stamped-trains-under-changelog_fragments-train-land) requires present and green on a stamp commit. `null` keeps `[Unreleased]` sections and per-PR stamps. Needs `min_gstack_version`. |
+| `changelog_fragments` | `{ dir, required_checks? }` or `null` | `null` | PRs carry unversioned [CHANGELOG fragments](#changelog-fragments) in `dir` (one flat, repo-relative directory, no `..`) and the merge step ([`land`](#land)) assigns the version (under `merge: direct`, the [release PR](#release-stamp) does). `required_checks` (up to 50 distinct names) are the checks [`train land`](#stamped-trains-under-changelog_fragments-train-land) requires present and green on a stamp commit. `null` keeps `[Unreleased]` sections and per-PR stamps. Needs `min_gstack_version`. |
Containment, checked by `validate` and again at write time: paths and globs are
repo-relative with no `..` segment, under 256 characters, at most 64 per list,
@@ -2005,9 +2005,11 @@ at a time with `gstack-ship-queue land --pr <n> --pin <sha>`, where `<sha>`
is the head the READY names. There's no train, no stamp commit, no base merge
and no extra CI round. GitHub's required checks plus `--match-head-commit`
stay the gate. Versions aren't set per PR: a PR carries only its
-`changelog.d` fragment, VERSION stays where it is, and the release stamps the
-version and folds the fragments. Land refuses, and merges nothing, unless all
-of these hold:
+`changelog.d` fragment, VERSION stays where it is, and the
+[release PR](#release-stamp) stamps the version and folds the fragments. Land
+refuses, and merges nothing, unless all of these hold (a `release/<version>`
+head is checked by the release rules below instead of the receipt, READY and
+release-file rows):
| Check | Refusal |
|---|---|
@@ -2033,6 +2035,43 @@ after GitHub merged goes straight to the tree check. `--dry-run` runs every
check and merges nothing. Under `merge: direct`, `train build` refuses and
names this command.
+<a id="release-stamp"></a>
+### Versions at release: the release PR (`merge: direct`)
+
+Under `merge: direct`, VERSION, the `package.json` version, CHANGELOG.md, the
+release outputs and the `stamp_paths` constants move only in a release PR.
+Before each stable cut, the Captain runs:
+
+```bash
+gstack-release-stamp open # --dry-run prints the stamp and creates nothing
+```
+
+It stamps a fresh worktree of `origin/main` with `gstack-restamp --release`,
+commits the result on `release/<version>`, pushes that branch and opens its PR.
+The release stamp folds every fragment in `changelog.d/` under one new CHANGELOG
+heading and deletes the files. The new version is the base's plus the highest
+bump any fragment declares (the policy `bump` when none does). It reruns the
+release tool, and it moves a tentative `stamp_paths` mention (a `*_KEY_VERSION`
+a PR wrote ahead of its release) on lines added since the last version change.
+With no fragment on main it refuses with
+[`RELEASE_STAMP_EMPTY`](troubleshooting.md#release-stamp-empty).
+
+When the release PR's checks are green, the Captain lands it like any other PR:
+`gstack-ship-queue land --pr <n> --pin <head>`. On a `release/<version>`
+branch, land needs no /ship receipt or READY note. Instead it checks that the
+head is exactly the release stamp of its merge base, and that the merge base is
+still the tip of `origin/main` (open the release again if main moved, so no PR
+ships under a version its fragment missed): every fragment there folded and
+none added, the version equal to the base's plus their bump, every
+other change a stamp by the [tree receipt](#tree-receipt)'s rules, and a
+changed release output equal to what the release tool generates at the new
+version. Anything more is
+[`RELEASE_STAMP_INVALID`](troubleshooting.md#release-stamp-invalid), and
+nothing merges. The Version Gate (`Check VERSION is not stale vs queue`)
+applies the same test, so a release head passes it while any other PR that
+changes VERSION still fails it. Once the release PR lands, the next stable cut
+tags `v<version>` ([releases.md](releases.md)).
+
<a id="migrating-to-fragments"></a>
### Migrating to fragments
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index b5b743dde..96c58f3d6 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -5234,6 +5234,32 @@ reviewed pin reached main. No land note was written.
**Fix.** Compare the merge commit with `git merge-tree --write-tree <parent>
<pin>`, revert what doesn't belong to the PR, and report it to the Captain.
+<a id="release-stamp-empty"></a>
+### `RELEASE_STAMP_EMPTY`
+
+**Meaning.** `gstack-release-stamp open` (or `gstack-restamp --release`) found
+no changelog fragment on the base, so there's nothing to release. No branch or
+PR was created.
+
+**Fix.** Nothing to do. The next release stamp folds whatever fragments PRs
+land in the meantime. The stable cut still tags the current VERSION if that
+version has no tag yet.
+
+<a id="release-stamp-invalid"></a>
+### `RELEASE_STAMP_INVALID`
+
+**Meaning.** One of two things. A release stamp was asked to run somewhere other
+than a clean checkout of `origin/<base>`, or the base policy has no
+`changelog_fragments`. Or `land --pin` (or the Version Gate) was given a
+`release/<version>` head that is more than the release stamp of its merge base:
+it changes a file outside the stamp, deletes a release output, skips or adds a
+fragment, or carries a version other than the base's plus the fragments' bump. Nothing was written or
+merged.
+
+**Fix.** Close the bad release PR and run `gstack-release-stamp open` again.
+It stamps a fresh checkout of `origin/main`. Never edit a `release/<version>`
+branch by hand.
+
<a id="queue-train-stamp-mismatch"></a>
### `QUEUE_TRAIN_STAMP_MISMATCH`
diff --git a/lib/release-stamp.ts b/lib/release-stamp.ts
new file mode 100644
index 000000000..4e23ec32c
--- /dev/null
+++ b/lib/release-stamp.ts
@@ -0,0 +1,155 @@
+/**
+ * release-stamp — versions at release under merge: direct (docs/ship-policy.md#release-stamp). PRs land unstamped,
+ * carrying only a changelog.d fragment; a release PR on a `release/<version>` branch then moves VERSION, the
+ * package.json version, the CHANGELOG (every fragment folded under the new heading), the release outputs and the
+ * tentative stamp_paths mentions in one commit on the base (`gstack-restamp --release`). openRelease makes that PR
+ * (bin/gstack-release-stamp); classifyRelease is the one test of "this head is the release stamp of its merge base"
+ * that land --pin and the Version Gate both apply.
+ */
+import { spawnSync } from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import { parseChangelog } from './changelog-check';
+import { effectiveBump, readFragments } from './changelog-fragments';
+import { restamp, versionAtRef, type RestampResult } from './restamp';
+import { matchesAny, type ShipPolicy } from './ship-policy';
+import { buildReceipt } from './tree-receipt';
+import { regeneratedAtBase } from './version-gate-train';
+import { bumpVersion, cmpVersion, fmtVersion, parseVersion, versionWidth } from './version-source';
+
+export const RELEASE_BRANCH = /^release\/(\d+(?:\.\d+){2,3})$/;
+
+export type ReleaseVerdict = { ok: true; version: string; fragments: string[] } | { ok: false; reason: string };
+
+function git(cwd: string, args: string[]): { ok: boolean; out: string; err: string } {
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000, maxBuffer: 64 * 1024 * 1024 });
+ return { ok: r.status === 0, out: (r.stdout ?? '').replace(/\n$/, ''), err: (r.stderr ?? '').trim() };
+}
+
+/**
+ * head is the release stamp of mergeBase: it deletes every fragment the merge base holds and adds none, its version
+ * is the merge base's plus the effective bump of those fragments (what gstack-restamp --release allocates), and every
+ * other change is a stamp by the tree receipt's rules (the CHANGELOG exactly the fragments folded under the new heading,
+ * stamp_paths only version rewrites). A changed release output passes only when release_tool regenerates the same bytes
+ * at the new version (GST-1176's rule, the Version Gate's regeneratedAtBase).
+ */
+export function classifyRelease(o: { repoRoot: string; policy: ShipPolicy; mergeBase: string; head: string }): ReleaseVerdict {
+ const no = (reason: string): ReleaseVerdict => ({ ok: false, reason });
+ const dir = o.policy.changelog_fragments?.dir.replace(/\/+$/, '');
+ if (!dir) return no('the base policy has no changelog_fragments, so there is no release stamp to check');
+ const [was, now] = [versionAtRef(o.repoRoot, o.mergeBase), versionAtRef(o.repoRoot, o.head)];
+ if ('error' in was || 'error' in now) return no('error' in was ? was.error : (now as { error: string }).error);
+ const status = git(o.repoRoot, ['diff', '--name-status', '--no-renames', o.mergeBase, o.head, '--', dir + '/']);
+ if (!status.ok) return no(`cannot list the fragments ${o.head.slice(0, 12)} changes: ${status.err.split('\n')[0]}`);
+ const rows = status.out.split('\n').filter(Boolean).map(l => l.split('\t') as [string, string]);
+ const touched = rows.filter(([s]) => s !== 'D').map(([, p]) => p);
+ if (touched.length) return no(`a release adds or edits no fragment, but this head changes ${touched.join(', ')}`);
+ const atBase = readFragments(o.repoRoot, o.mergeBase, dir, null, o.policy.changelog);
+ if (atBase.errors.length) return no(`${atBase.errors[0]!.path}: ${atBase.errors[0]!.message}`);
+ if (!atBase.fragments.length) return no('the merge base holds no fragment, so there is nothing to release');
+ const deleted = new Set(rows.map(([, p]) => p));
+ const kept = atBase.fragments.filter(f => !deleted.has(f.path)).map(f => f.path);
+ if (kept.length) return no(`a release folds every fragment on its merge base, but ${kept.join(', ')} stay`);
+ const base = parseVersion(was.version)!;
+ const w = versionWidth(was.version);
+ const expected = fmtVersion(bumpVersion(base, effectiveBump(o.policy.bump === 'patch' ? 'patch' : 'micro', atBase.fragments), w), w);
+ if (now.version !== expected || cmpVersion(parseVersion(now.version)!, base) <= 0) return no(`the head carries ${now.version}; the release of ${was.version} with these fragments is ${expected}`);
+ const receipt = buildReceipt({ repoRoot: o.repoRoot, gated: o.mergeBase, current: o.head, policy: o.policy, policyLabel: 'base' });
+ if ('error' in receipt) return no(receipt.error);
+ const residual = receipt.files.filter(f => f.verdict === 'changed');
+ const outside = residual.filter(f => !matchesAny(o.policy.release_outputs, f.path));
+ if (outside.length) return no(`more than the stamp changed: ${outside.map(f => `${f.path} (${f.residual ?? f.rule})`).join(', ')}`);
+ const gone = git(o.repoRoot, ['diff', '--name-only', '--no-renames', '--diff-filter=D', o.mergeBase, o.head]).out.split('\n').filter(f => f && matchesAny(o.policy.release_outputs, f));
+ if (gone.length) return no(`a release regenerates its outputs and never deletes one, but it deletes ${gone.join(', ')}`);
+ const manifest = (rev: string) => { const r = git(o.repoRoot, ['show', `${rev}:package.json`]); try { return r.ok ? (JSON.parse(r.out).version as string | undefined) ?? null : null; } catch { return null; } };
+ const npmWas = manifest(o.mergeBase);
+ const npmWant = npmWas === null ? null : expected.split('.').slice(0, npmWas.split('.').length).join('.');
+ if (now.rel !== 'package.json' && manifest(o.head) !== npmWant) return no(`package.json carries version ${manifest(o.head)}; the release sets ${npmWant}`);
+ const lock = git(o.repoRoot, ['show', `${o.head}:package-lock.json`]);
+ if (lock.ok) { try { const l = JSON.parse(lock.out); if (l.version !== npmWant || (l.packages?.[''] && l.packages[''].version !== npmWant)) return no(`package-lock.json's root version is not ${npmWant}`); } catch { return no('package-lock.json at the head is not JSON'); } }
+ if (o.policy.changelog) {
+ const sections = (rev: string) => { const r = git(o.repoRoot, ['show', `${rev}:${o.policy.changelog}`]); return r.ok ? parseChangelog(r.out).sections : []; };
+ const [was, is] = [sections(o.mergeBase).filter(s => !s.unreleased), sections(o.head)];
+ const [before, after] = [was.map(s => s.version), is.map(s => s.unreleased ? 'Unreleased' : s.version)];
+ const rewritten = was.filter((s, i) => is[i + 1]?.lines.join('\n').trimEnd() !== s.lines.join('\n').trimEnd()).map(s => s.version);
+ if (rewritten.length) return no(`${o.policy.changelog} rewrites the released section(s) ${rewritten.slice(0, 3).join(', ')}; a release only adds its own section on top`);
+ if (after[0] !== now.version || after.slice(1).join(' ') !== before.join(' ')) return no(`${o.policy.changelog} must add one [${now.version}] heading on top of the released headings it had (${after.slice(0, 3).join(', ')} …)`);
+ }
+ const outputs = !o.policy.release_tool ? residual.map(f => f.path) : [...new Set([...residual.map(f => f.path), ...git(o.repoRoot, ['ls-tree', '-r', '--name-only', o.head]).out.split('\n').filter(f => f && matchesAny(o.policy.release_outputs, f))])];
+ if (outputs.length) {
+ if (!o.policy.release_tool) return no(`${outputs.join(', ')} changed and the policy names no release_tool to regenerate them`);
+ const regen = regeneratedAtBase({ repoRoot: o.repoRoot, head: o.head, baseVersion: now.version, tool: o.policy.release_tool, outputs });
+ if (regen.kind === 'error') return no(regen.reason);
+ if (regen.kind === 'differs') return no(`${regen.files.join(', ')} is not what release_tool generates at ${now.version}`);
+ }
+ return { ok: true, version: now.version, fragments: atBase.fragments.map(f => f.path) };
+}
+
+export interface OpenOptions {
+ repoRoot: string; base: string; dryRun?: boolean; now?: Date;
+ gh?: (args: string[], cwd: string) => { ok: boolean; out: string; err: string };
+}
+export type OpenResult =
+ | { ok: true; version: string; branch: string; head?: string; pr?: string; url?: string; lines: string[] }
+ | { ok: false; code: NonNullable<RestampResult['code']>; message: string; lines: string[] };
+
+const defaultGh = (args: string[], cwd: string) => {
+ const r = spawnSync('gh', args, { cwd, encoding: 'utf8', timeout: 120_000 });
+ return { ok: r.status === 0, out: r.stdout ?? '', err: r.stderr ?? '' };
+};
+
+/**
+ * Stamp a fresh worktree of origin/<base> with gstack-restamp --release, commit only the stamped files (detached, so no
+ * local branch is left behind), force-push the commit to release/<version> (a reopen after RELEASE_STAMP_INVALID
+ * replaces the old release branch) and open the release PR. The Captain lands it with gstack-ship-queue land --pr <n> --pin <head> once its
+ * checks are green; the stable cut then tags the new version. --dry-run stamps and prints the diff, and creates nothing.
+ */
+export function openRelease(o: OpenOptions): OpenResult {
+ const gh = o.gh ?? defaultGh;
+ const lines: string[] = [];
+ const fail = (code: NonNullable<RestampResult['code']>, message: string): OpenResult => ({ ok: false, code, message, lines });
+ const fetch = git(o.repoRoot, ['fetch', '-q', 'origin', o.base]);
+ if (!fetch.ok) return fail('RELEASE_STAMP_INVALID', `git fetch origin ${o.base} failed: ${fetch.err.split('\n')[0]}`);
+ const baseSha = git(o.repoRoot, ['rev-parse', `origin/${o.base}`]).out;
+ const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-release-stamp-'));
+ const dir = path.join(tmp, 'worktree');
+ try {
+ const add = git(o.repoRoot, ['worktree', 'add', '--detach', '-q', dir, baseSha]);
+ if (!add.ok) return fail('RELEASE_STAMP_INVALID', `cannot create the release worktree: ${add.err}`);
+ const nm = path.join(o.repoRoot, 'node_modules');
+ if (fs.existsSync(nm)) fs.symlinkSync(nm, path.join(dir, 'node_modules'), 'dir');
+ const stamp = restamp({ repoRoot: dir, base: o.base, release: true, policyFrom: 'base', allowRepoCommands: true, dryRun: !!o.dryRun, now: o.now });
+ for (const s of stamp.stages) lines.push(`STAGE: ${s.name} ${s.status}${s.detail ? ` (${s.detail})` : ''}`);
+ if (stamp.status === 'refused' || stamp.status === 'failed') return fail(stamp.code ?? 'RESTAMP_CONFLICT', stamp.message ?? 'the release stamp did not complete');
+ const version = stamp.newVersion!;
+ const branch = `release/${version}`;
+ lines.push(`RELEASE: ${stamp.oldVersion} -> ${version} at origin/${o.base} ${baseSha.slice(0, 12)}`);
+ if (o.dryRun) return { ok: true, version, branch, lines: [...lines, stamp.diff ?? ''] };
+ const folded = /folded (.+?)(;|$)/.exec(stamp.stages.find(s => s.name === 'changelog')?.detail ?? '')?.[1] ?? 'see the CHANGELOG diff';
+ for (const step of [['add', '-A', '--', ...(stamp.files ?? [])], ['commit', '-q', '-m', `v${version} release: fold the changelog fragments`]]) {
+ const r = git(dir, step);
+ if (!r.ok) return fail('RELEASE_STAMP_INVALID', `git ${step[0]} failed in the release worktree: ${r.err.split('\n')[0]}`);
+ }
+ const head = git(dir, ['rev-parse', 'HEAD']).out;
+ const push = git(dir, ['push', '-q', '--force', 'origin', `HEAD:refs/heads/${branch}`]);
+ if (!push.ok) return fail('RELEASE_STAMP_INVALID', `git push origin ${branch} failed: ${push.err.split('\n')[0]}`);
+ lines.push(`PUSHED: ${branch} ${head}`);
+ const body = [
+ `Release stamp for v${version}, made by \`gstack-release-stamp open\` (\`gstack-restamp --release\`) on origin/${o.base} ${baseSha.slice(0, 12)}: VERSION, the package.json version, the CHANGELOG and the release outputs.`,
+ '', `Folds: ${folded}`, '',
+ `Land it with \`gstack-ship-queue land --pr <this PR> --pin ${head}\` once its checks are green. land checks that this head is exactly the release stamp of its merge base (RELEASE_STAMP_INVALID otherwise), so a release PR needs no /ship receipt.`,
+ ].join('\n');
+ const open = gh(['pr', 'list', '--head', branch, '--state', 'open', '--json', 'url,isCrossRepository', '--jq', '[.[] | select(.isCrossRepository | not)][0].url // ""'], dir);
+ const pr = open.ok && open.out.trim() ? open : gh(['pr', 'create', '--base', o.base, '--head', branch, '--title', `v${version} release`, '--body', body], dir);
+ if (!pr.ok) return fail('RELEASE_STAMP_INVALID', `gh pr create failed (${pr.err.trim().split('\n')[0]}); ${branch} is pushed, so open its PR by hand`);
+ const url = pr.out.trim().split('\n').pop() ?? '';
+ const n = /\/pull\/(\d+)/.exec(url)?.[1];
+ lines.push(`RELEASE_PR: ${n ? `#${n} ` : ''}${url}`, `NEXT: gstack-ship-queue land --pr ${n ?? '<n>'} --pin ${head} once its checks are green`);
+ return { ok: true, version, branch, head, pr: n, url, lines };
+ } finally {
+ git(o.repoRoot, ['worktree', 'remove', '--force', dir]);
+ fs.rmSync(tmp, { recursive: true, force: true });
+ git(o.repoRoot, ['worktree', 'prune']);
+ }
+}
diff --git a/lib/restamp-release.ts b/lib/restamp-release.ts
new file mode 100644
index 000000000..993eee13a
--- /dev/null
+++ b/lib/restamp-release.ts
@@ -0,0 +1,17 @@
+/**
+ * restamp-release — the precondition of `gstack-restamp --release` (lib/release-stamp.ts, docs/ship-policy.md#release-stamp):
+ * a release stamp runs on a clean checkout of origin/<base> under changelog_fragments, so the release PR carries only the stamp.
+ */
+import { spawnSync } from 'node:child_process';
+
+const git = (cwd: string, args: string[]) => (spawnSync('git', args, { cwd, encoding: 'utf8', timeout: 60_000 }).stdout ?? '').trim();
+
+/** Why a release stamp cannot run here, or null when it can. */
+export function releaseRefusal(repoRoot: string, base: string, baseRef: string | undefined, fragDir: string | null): { message: string; fix?: string } | null {
+ if (!fragDir) return { message: '--release needs changelog_fragments in the base policy (a release folds the fragments); nothing written' };
+ const tip = git(repoRoot, ['rev-parse', '--verify', '--quiet', `${baseRef ?? `origin/${base}`}^{commit}`]);
+ if (!tip || git(repoRoot, ['rev-parse', 'HEAD']) !== tip) return { message: `--release runs on a checkout of origin/${base} (${tip.slice(0, 12) || 'unresolved'}), not on ${git(repoRoot, ['rev-parse', '--short', 'HEAD'])}; nothing written`, fix: `git fetch origin ${base} && git checkout --detach origin/${base}` };
+ const dirty = git(repoRoot, ['status', '--porcelain', '--untracked-files=no']);
+ if (dirty) return { message: `--release needs a clean checkout; commit or stash: ${dirty.split('\n').slice(0, 5).map(l => l.slice(3)).join(', ')}; nothing written` };
+ return null;
+}
diff --git a/lib/restamp.ts b/lib/restamp.ts
index dbe9ecf8b..a47f81e80 100644
--- a/lib/restamp.ts
+++ b/lib/restamp.ts
@@ -27,6 +27,7 @@ import * as path from 'node:path';
import { bunIsolationArgs } from './bun-isolation';
import { checkChangelog, mergeChangelogs, parseChangelog, reheadChangelog } from './changelog-check';
import { effectiveBump, foldIntoUnreleased, readFragments, type FragmentSet } from './changelog-fragments';
+import { releaseRefusal } from './restamp-release';
import { type ResultCodeName } from './result-codes';
import { runScriptSync, wtreeFingerprint } from './script-invocation';
import {
@@ -58,6 +59,7 @@ export interface RestampOptions {
after?: { pr: string; ref?: string }; pr?: string; expectBase?: string; expectOrder?: string[]; was?: string;
policyFrom: 'base' | 'head'; allowRepoCommands: boolean; dryRun: boolean; now?: Date; env?: NodeJS.ProcessEnv;
gh?: (args: string[]) => { ok: boolean; out: string }; failAfter?: string; gateWorktree?: string; baseRef?: string;
+ /** Versions at release (lib/restamp-release.ts): fold every fragment on the base, from a clean checkout of it. */ release?: boolean;
}
export interface RestampResult {
status: 'stamped' | 'noop' | 'dry-run' | 'refused' | 'failed' | 'gate-ahead';
@@ -197,7 +199,7 @@ function planVersions(o: RestampOptions, loaded: LoadedPolicy, policyLabel: stri
} else if (o.version) {
if (!parseVersion(o.version)) throw new Refusal('RESTAMP_VERSION_SOURCE', `--version ${o.version} is not MAJOR.MINOR.PATCH[.MICRO]; nothing written`);
newVersion = o.version;
- } else if (queueMode === 'stamp-at-merge') {
+ } else if (queueMode === 'stamp-at-merge' || o.release) {
newVersion = bumped(atBase.version, level);
claims = 'ignored (stamp-at-merge)';
} else {
@@ -488,7 +490,7 @@ function runStages(o: RestampOptions, plan: Plan, staging: string, since: string
const date = (o.now ?? new Date()).toISOString().slice(0, 10);
const from = o.was ?? plan.branchStamp;
const dir = plan.policy.changelog_fragments?.dir;
- const frags = dir ? readFragments(staging, null, dir, plan.baseSha, clRel) : null;
+ const frags = dir ? readFragments(staging, null, dir, o.release ? null : plan.baseSha, clRel) : null;
if (frags?.errors.length) { cl.status = 'failed'; cl.detail = `${frags.errors[0]!.path}: ${frags.errors[0]!.message}`; throw new Refusal('CHANGELOG_FRAGMENT_INVALID', `${cl.detail}; nothing written to the branch`); }
for (const f of frags?.fragments ?? []) fs.rmSync(path.join(staging, f.path));
const r = reheadChangelog(foldIntoUnreleased(fs.readFileSync(clPath, 'utf8'), frags?.fragments ?? []), { from, to: plan.newVersion, date, file: clRel! });
@@ -540,7 +542,7 @@ function rewriteStampPaths(o: RestampOptions, plan: Plan, staging: string, since
const why = assertInsideRoot(staging, rel);
if (why) throw new Refusal('POLICY_CONTAINMENT', `${why}; nothing written`);
}
- const baseAdded = branchAddedLines(o.repoRoot, since, files, plan.baseSha);
+ const baseAdded = o.release ? new Map<string, AddedLines>() : branchAddedLines(o.repoRoot, since, files, plan.baseSha);
const added = branchAddedLines(staging, since, files, undefined, baseAdded);
const explicit = new Set([...(o.was ? [o.was] : []), ...(plan.branchStamp ? [plan.branchStamp] : [])].filter(v => v !== plan.newVersion));
const tentative = new Set(tentativeMentions(new Map([...added].map(([rel, own]) => [rel, own.text])), plan.forkVersion, plan.newVersion, templates, plan.recorded).filter(v => !explicit.has(v)));
@@ -678,7 +680,9 @@ export function restamp(o: RestampOptions): RestampResult {
throw new Refusal('REPO_COMMANDS_NOT_ALLOWED', `repo commands not executed (pass --allow-repo-commands): ${commands.map(c => `${c.key}: ${c.command}`).join('; ')}; nothing written`, { commands });
}
const fragDir = loaded.policy.changelog_fragments?.dir ?? null;
- const frags = fragDir ? fragmentsOf(o, fragDir, loaded.policy.changelog) : null;
+ if (o.release) { const why = releaseRefusal(o.repoRoot, o.base, o.baseRef, fragDir); if (why) throw new Refusal('RELEASE_STAMP_INVALID', why.message, { fix: why.fix }); }
+ const frags = !fragDir ? null : o.release ? readFragments(o.repoRoot, 'HEAD', fragDir, null, loaded.policy.changelog) : fragmentsOf(o, fragDir, loaded.policy.changelog);
+ if (o.release && !frags!.fragments.length) throw new Refusal('RELEASE_STAMP_EMPTY', `${fragDir} holds no fragment at origin/${o.base}, so there is nothing to release; nothing written`);
const plan = planVersions(frags && !o.bump ? { ...o, bump: effectiveBump(loaded.policy.bump === 'patch' ? 'patch' : 'micro', frags.fragments) } : o, loaded, label);
const headSha = git(o.repoRoot, ['rev-parse', 'HEAD']).out;
const common: Partial<RestampResult> = {
@@ -713,7 +717,7 @@ export function restamp(o: RestampOptions): RestampResult {
if (!seed.ok) throw new Refusal('RESTAMP_CONFLICT', `cannot seed the staging worktree: ${seed.err}; nothing written`);
linkIgnoredDeps(o.repoRoot, staging);
- runStages(o, plan, staging, git(o.repoRoot, ['merge-base', plan.baseRef, 'HEAD']).out || plan.baseSha, stages);
+ runStages(o, plan, staging, git(o.repoRoot, o.release ? ['log', '-1', '--format=%H', plan.baseSha, '--', plan.versionRel] : ['merge-base', plan.baseRef, 'HEAD']).out || plan.baseSha, stages);
const files = changedPaths(staging).sort();
git(staging, ['add', '-A']);
const diff = git(staging, ['diff', '--cached', wtree]).out;
diff --git a/lib/result-codes-release.ts b/lib/result-codes-release.ts
index 065645bc9..478d30ac7 100644
--- a/lib/result-codes-release.ts
+++ b/lib/result-codes-release.ts
@@ -498,6 +498,17 @@ export const RELEASE_RESULT_CODES = {
summary: 'after the merge, the base branch tree is not the pin merged onto the merge commit\'s parent, so something besides the reviewed pin reached main',
fix: 'compare the merge commit with the pin merged onto its parent, revert what does not belong to the PR, and report it to the Captain',
},
+ // gstack-restamp --release, gstack-release-stamp and the release route of land --pin (lib/release-stamp.ts): versions at release.
+ RELEASE_STAMP_EMPTY: {
+ anchor: 'release-stamp-empty',
+ summary: 'the base holds no changelog fragment, so there is nothing to release and no release PR was opened',
+ fix: 'nothing to do: the next release stamp folds the fragments the PRs landed since; the cut tags the current VERSION if it has no tag yet',
+ },
+ RELEASE_STAMP_INVALID: {
+ anchor: 'release-stamp-invalid',
+ summary: 'a release stamp ran off a clean checkout of the base, or a release/<version> head is more than the release stamp of its merge base',
+ fix: 'open the release again with gstack-release-stamp open (it stamps a fresh checkout of origin/main); never edit a release/<version> branch by hand',
+ },
// gstack-pr-wait (lib/pr-wait.ts): the landing-path PR watcher's two terminal codes.
PR_WAIT_BLOCKED: {
anchor: 'pr-wait-blocked',
diff --git a/lib/ship-queue-land-direct.ts b/lib/ship-queue-land-direct.ts
index dcc08dc98..ef5ded962 100644
--- a/lib/ship-queue-land-direct.ts
+++ b/lib/ship-queue-land-direct.ts
@@ -8,6 +8,7 @@
* merge commit's tree is the pin merged onto that commit's parent, and a land note on refs/notes/gstack-trains. A rerun
* after GitHub merged goes straight to the tree check.
*/
+import { classifyRelease, RELEASE_BRANCH } from './release-stamp';
import { versionAtRef } from './restamp';
import type { ShipPolicy } from './ship-policy';
import { ciAtHead, loadBasePolicy, type QueueContext, type StepOutput } from './ship-queue';
@@ -49,12 +50,15 @@ function havePin(root: string, pr: string, pin: string, branch?: string): boolea
}
/** The merge commit's tree is the pin merged onto the merge commit's first parent: GitHub merged exactly the pin. A read that fails is "cannot verify", never a mismatch. */
-function verifyMerge(ctx: QueueContext, root: string, pr: string, pin: string, merge: string, lines: string[], run: string, now: Date): StepOutput {
+function verifyMerge(ctx: QueueContext, root: string, pr: string, pin: string, merge: string, lines: string[], run: string, now: Date, stamped?: string | 'pin-parent'): StepOutput {
const cannot = (why: string): StepOutput => ({ ok: false, run, lines, failure: { code: 'QUEUE_NOT_READY', message: `#${pr} merged as ${merge.slice(0, 12)}, but land cannot verify it: ${why}`, fix: `fix the read named, then rerun gstack-ship-queue land --pr ${pr} --pin ${pin}; it goes straight to the tree check` } });
if (!git(root, ['fetch', '-q', 'origin', ctx.base]).ok) return cannot(`git fetch origin ${ctx.base} failed`);
if (!havePin(root, pr, pin)) return cannot(`the pin ${pin.slice(0, 12)} is not in this clone and refs/pull/${pr}/head did not fetch it`);
+ const stampedOn = stamped === 'pin-parent' ? git(root, ['rev-parse', '--verify', '-q', `${pin}^1^{commit}`]).out : stamped;
+ if (stampedOn !== undefined && !isSha(stampedOn)) return cannot(`cannot read the parent of the release pin ${pin.slice(0, 12)}, the ${ctx.base} commit it was stamped on`);
if (!git(root, ['merge-base', '--is-ancestor', merge, `origin/${ctx.base}`]).ok) return { ok: false, run, lines, failure: { code: 'QUEUE_LAND_UNVERIFIED', message: `the merge commit ${merge.slice(0, 12)} is not on origin/${ctx.base}` } };
const parent = git(root, ['rev-parse', `${merge}^1`]).out;
+ if (stampedOn && parent !== stampedOn) return { ok: false, run, lines, failure: { code: 'QUEUE_LAND_UNVERIFIED', message: `the release merged as ${merge.slice(0, 12)} onto ${parent.slice(0, 12)}, not onto ${stampedOn.slice(0, 12)} it was stamped on: a PR landed in between and ships under this version while its fragment waits for the next release`, fix: 'tell the Captain; the next release folds that fragment, so note the PR in its release notes' } };
const tree = git(root, ['rev-parse', `${merge}^{tree}`]).out;
const mt = git(root, ['merge-tree', '--write-tree', parent, pin]);
const expected = mt.out.split('\n')[0] ?? '';
@@ -85,26 +89,35 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
if (info.baseRefName && info.baseRefName !== ctx.base) return fail(lines, { code: 'QUEUE_NOT_READY', message: `#${o.pr} targets ${info.baseRefName}, not ${ctx.base}`, fix: `retarget it to ${ctx.base}, or land its parent first` });
if (info.state === 'MERGED' && info.headRefOid === o.pin && isSha(info.mergeCommit?.oid)) {
lines.push(`#${o.pr} is already merged as ${info.mergeCommit!.oid.slice(0, 12)}; checking the tree`);
- return verifyMerge(ctx, root, o.pr, o.pin, info.mergeCommit!.oid, lines, run, now());
+ return verifyMerge(ctx, root, o.pr, o.pin, info.mergeCommit!.oid, lines, run, now(), RELEASE_BRANCH.test(info.headRefName) ? 'pin-parent' : undefined);
}
if (info.state !== 'OPEN') return fail(lines, { code: 'QUEUE_NOT_READY', message: `#${o.pr} is ${info.state}` });
if (info.headRefOid !== o.pin) return fail(lines, { code: 'QUEUE_LAND_PIN_MOVED', message: `#${o.pr}'s head is ${info.headRefOid.slice(0, 12)}, not the pin ${o.pin.slice(0, 12)}`, fix: `the lane runs /ship and gstack-ship-queue ready --pr ${o.pr} at the new head and reports READY with it` });
if (!havePin(root, o.pr, o.pin, info.headRefName)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot fetch the pin ${o.pin.slice(0, 12)} from ${info.headRefName} or refs/pull/${o.pr}/head`, fix: 'fix the fetch, then rerun land' });
- const receipt = bindShippedReceipt(root, `origin/${ctx.base}`, info.body ?? '', o.pr, [o.pin]);
- lines.push(receipt.line, ...(receipt.depthLine ? [receipt.depthLine] : []), ...(receipt.targetedLine ? [receipt.targetedLine] : []));
- if (!receipt.ok) return fail(lines, { code: receipt.code, message: receipt.message, fix: `run /ship at the pin, then gstack-ship-queue ready --pr ${o.pr}` });
+ const mergeBase = git(root, ['merge-base', `origin/${ctx.base}`, o.pin]).out;
+ if (!isSha(mergeBase)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot compute the merge base of the pin ${o.pin.slice(0, 12)} and origin/${ctx.base}, so the release-file check cannot run`, fix: `git fetch origin ${ctx.base} and the PR head (an unshallow clone), then rerun land` });
+ const named = RELEASE_BRANCH.exec(info.headRefName)?.[1];
+ const release = named ? classifyRelease({ repoRoot: root, policy, mergeBase, head: o.pin }) : null;
+ if (release?.ok && release.version !== named) return fail(lines, { code: 'RELEASE_STAMP_INVALID', message: `${info.headRefName} stamps v${release.version}, not the version its branch names`, fix: 'close it and run gstack-release-stamp open again' });
+ if (release && !release.ok) return fail(lines, { code: 'RELEASE_STAMP_INVALID', message: `${info.headRefName} is not the release stamp of its merge base ${mergeBase.slice(0, 12)}: ${release.reason}`, fix: 'close it and run gstack-release-stamp open again; never edit a release branch by hand' });
+ const tip = git(root, ['rev-parse', `origin/${ctx.base}`]).out;
+ if (release && mergeBase !== tip) return fail(lines, { code: 'RELEASE_STAMP_INVALID', message: `origin/${ctx.base} moved to ${tip.slice(0, 12)} since ${info.headRefName} was stamped on ${mergeBase.slice(0, 12)}; the PRs that landed since would ship under this version while their fragments wait for the next release`, fix: 'run gstack-release-stamp open again (it replaces the release branch), then land the new head' });
const keys = repoIdentity(root).keys;
rebuildFromNotes(root, ctx.remote ?? 'origin');
- if (!loadReady(keys, o.pr, o.pin)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `no READY note for #${o.pr} at the pin ${o.pin.slice(0, 12)}`, fix: `the lane runs gstack-ship-queue ready --pr ${o.pr} --no-screen at the pin` });
+ if (release) lines.push(`RELEASE: v${release.version} folds ${release.fragments.length} fragment(s) and changes nothing but the stamp, so it needs no /ship receipt or READY note`);
+ else {
+ const receipt = bindShippedReceipt(root, `origin/${ctx.base}`, info.body ?? '', o.pr, [o.pin]);
+ lines.push(receipt.line, ...(receipt.depthLine ? [receipt.depthLine] : []), ...(receipt.targetedLine ? [receipt.targetedLine] : []));
+ if (!receipt.ok) return fail(lines, { code: receipt.code, message: receipt.message, fix: `run /ship at the pin, then gstack-ship-queue ready --pr ${o.pr}` });
+ if (!loadReady(keys, o.pr, o.pin)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `no READY note for #${o.pr} at the pin ${o.pin.slice(0, 12)}`, fix: `the lane runs gstack-ship-queue ready --pr ${o.pr} --no-screen at the pin` });
+ }
const freeze = activeFreeze(keys);
if (freeze) return fail(lines, { code: 'QUEUE_TRAIN_FROZEN', message: `main is frozen by train ${freeze.train} (${freeze.reason})` });
const lock = readLock(root, ctx.remote ?? 'origin');
if (lock.state === 'held') return fail(lines, { code: 'QUEUE_LAND_LOCKED', message: `${lockLabel(lock.lock)} holds the land lock; a direct land would race it onto main` });
- const mergeBase = git(root, ['merge-base', `origin/${ctx.base}`, o.pin]).out;
- if (!isSha(mergeBase)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot compute the merge base of the pin ${o.pin.slice(0, 12)} and origin/${ctx.base}, so the release-file check cannot run`, fix: `git fetch origin ${ctx.base} and the PR head (an unshallow clone), then rerun land` });
- const stamped = stampedFiles(root, policy, mergeBase, o.pin);
+ const stamped = release ? [] : stampedFiles(root, policy, mergeBase, o.pin);
if ('error' in stamped) return fail(lines, { code: 'QUEUE_NOT_READY', message: `cannot read the version at the pin or its merge base: ${stamped.error}` });
if (stamped.length) {
const files = stamped.filter(f => f !== 'package.json version');
@@ -132,5 +145,5 @@ export function landDirect(ctx: QueueContext, o: DirectOptions): StepOutput {
}
if (!isSha(merge) && m.ok) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr merge accepted #${o.pr}, but GitHub does not show it merged yet; nothing is verified`, fix: `rerun gstack-ship-queue land --pr ${o.pr} --pin ${o.pin} in a minute; once GitHub shows the merge it goes straight to the tree check` });
if (!isSha(merge)) return fail(lines, { code: 'QUEUE_NOT_READY', message: `gh pr merge refused: ${(m.err ?? m.out).trim().slice(0, 200) || 'the PR is not merged'}`, fix: `read the refusal; rerun land --pr ${o.pr} --pin ${o.pin} once it is fixed` });
- return verifyMerge(ctx, root, o.pr, o.pin, merge!, lines, run, now());
+ return verifyMerge(ctx, root, o.pr, o.pin, merge!, lines, run, now(), release ? mergeBase : undefined);
}
diff --git a/lib/version-gate-train.ts b/lib/version-gate-train.ts
index 818f18730..4c5ac2c3b 100644
--- a/lib/version-gate-train.ts
+++ b/lib/version-gate-train.ts
@@ -14,12 +14,14 @@ import * as path from 'node:path';
import { parseChangelog } from './changelog-check';
import { effectiveBump, readFragments } from './changelog-fragments';
import { HistoryReadError, readHistoryFile } from './history-read';
-import { matchesAny } from './ship-policy';
+import { classifyRelease } from './release-stamp';
+import { isUnavailable, loadPolicyFromBase, matchesAny } from './ship-policy';
export type TrainHead =
| { kind: 'off' }
| { kind: 'unstamped'; fragments?: number; entry?: 'fragment' | 'unreleased' | 'none-bot' | 'kept' }
| { kind: 'stamped'; expected: string; fragments?: boolean }
+ | { kind: 'release'; version: string; fragments: number }
| { kind: 'invalid'; reason: string };
function git(repoRoot: string, args: string[]): string | null {
@@ -128,6 +130,13 @@ function classify(o: { repoRoot: string; baseRef: string; head: string; author?:
// A merge-step stamp commit has parents [pin, base]: the fragments it folded are the pin's own.
const second = git(o.repoRoot, ['rev-parse', '--verify', '--quiet', `${o.head}^2`])?.trim();
const pin = second ? `${o.head}^1` : mergeBase;
+ if (fragDir && !second && policy.merge === 'direct') {
+ const loaded = loadPolicyFromBase(o.repoRoot, base.replace(/^origin\//, ''));
+ if (isUnavailable(loaded)) return { kind: 'invalid', reason: `cannot read the base policy to check a release stamp: ${loaded.detail}` };
+ const release = classifyRelease({ repoRoot: o.repoRoot, policy: loaded.policy, mergeBase, head: o.head });
+ if (release.ok) return { kind: 'release', version: release.version, fragments: release.fragments.length };
+ return { kind: 'invalid', reason: `under merge: direct a PR leaves VERSION, package.json and the release outputs at its merge base's values and adds a fragment; only a release PR stamps, and this head is not the release stamp of its merge base (RELEASE_STAMP_INVALID): ${release.reason}` };
+ }
if (fragDir && (!second || git(o.repoRoot, ['merge-base', '--is-ancestor', second, base]) === null)) return { kind: 'invalid', reason: `under changelog_fragments only the merge step stamps (a commit with parents [pin, ${base}]); leave VERSION, package.json and the release outputs at the merge base's values and add a fragment` };
const folded = fragDir ? readFragments(o.repoRoot, pin, fragDir, base, typeof policy.changelog === 'string' ? policy.changelog : 'CHANGELOG.md', 'skip') : null;
if (folded?.errors.length) return { kind: 'invalid', reason: `${folded.errors[0]!.path}: ${folded.errors[0]!.message}` };
diff --git a/scripts/compare-pr-version.ts b/scripts/compare-pr-version.ts
index 0adee42eb..1afafc2b3 100644
--- a/scripts/compare-pr-version.ts
+++ b/scripts/compare-pr-version.ts
@@ -49,6 +49,10 @@ if (process.env.BASE_REF && process.env.HEAD_SHA) {
console.log(`✓ ${tag} is unstamped under the base's ship policy: VERSION and package.json match its merge base, any changed release output is what the release tool generates at the merge base's VERSION, and ${entry}. The merge step stamps it.`);
process.exit(0);
}
+ if (train.kind === "release") {
+ console.log(`✓ ${tag} is the release stamp of its merge base: v${train.version} folds its ${train.fragments} changelog fragment(s), and everything else it changes is the stamp (docs/ship-policy.md#release-stamp).`);
+ process.exit(0);
+ }
if (train.kind === "invalid") {
console.log(`::error::${tag}: ${train.reason}.`);
process.exit(1);
diff --git a/test/release-stamp.test.ts b/test/release-stamp.test.ts
new file mode 100644
index 000000000..450e14542
--- /dev/null
+++ b/test/release-stamp.test.ts
@@ -0,0 +1,188 @@
+/**
+ * Versions at release (docs/ship-policy.md#release-stamp): gstack-restamp --release folds every fragment on the base
+ * under base + their bump, classifyRelease accepts exactly that stamp, gstack-release-stamp open pushes it as
+ * release/<version> and opens its PR, the Version Gate passes it, and land --pin merges it without a receipt.
+ */
+import { afterEach, describe, expect, test } from 'bun:test';
+import * as fs from 'node:fs';
+import * as path from 'node:path';
+import { classifyRelease, openRelease } from '../lib/release-stamp';
+import { loadPolicyFromBase, MERGE_KEY_VERSION } from '../lib/ship-policy';
+import { classifyTrainHead } from '../lib/version-gate-train';
+import { BASE_POLICY, cleanup, makeFixtureRepo, readFile, runBin, type FixtureRepo } from './helpers/restamp-fixture';
+
+const POLICY = { ...BASE_POLICY, changelog_fragments: { dir: 'changelog.d', required_checks: ['free-tests'] }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION };
+const repos: FixtureRepo[] = [];
+afterEach(() => { while (repos.length) cleanup(repos.pop()!); });
+
+/** A fixture whose main carries two landed fragments (one bump: minor) and a tentative stamp_paths mention, like PRs landed unstamped under merge: direct. */
+function landed(fragments: Record<string, string> = { 'a.md': '- a change\n', 'b.md': '---\nbump: minor\n---\n- b feature\n' }): FixtureRepo {
+ const repo = makeFixtureRepo({ policy: POLICY, prefix: 'gstack-release-stamp-fx-' });
+ repos.push(repo);
+ fs.mkdirSync(path.join(repo.work, 'changelog.d'), { recursive: true });
+ for (const [name, body] of Object.entries(fragments)) fs.writeFileSync(path.join(repo.work, 'changelog.d', name), body);
+ fs.writeFileSync(path.join(repo.work, 'docs', 'feature.md'), 'since: 1.2.9.0\n');
+ fs.writeFileSync(path.join(repo.work, 'feature.txt'), 'product\n');
+ repo.git('add', '-A');
+ repo.git('commit', '-q', '-m', 'land unstamped PRs');
+ repo.git('push', '-q', 'origin', 'main');
+ repo.git('checkout', '-q', '--detach', 'origin/main');
+ return repo;
+}
+const policyOf = (repo: FixtureRepo) => { const l = loadPolicyFromBase(repo.work, 'main'); if ('detail' in l && !('policy' in l)) throw new Error('no policy'); return (l as any).policy; };
+function stampRelease(repo: FixtureRepo): string {
+ const r = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
+ expect(r.status).toBe(0);
+ repo.git('add', '-A');
+ repo.git('commit', '-q', '-m', 'release');
+ return repo.git('rev-parse', 'HEAD');
+}
+
+describe('gstack-restamp --release', () => {
+ test('folds every fragment on the base under base + their bump, regenerates outputs and moves the tentative mention', () => {
+ const repo = landed();
+ const r = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
+ expect(r.status).toBe(0);
+ expect(r.out).toContain('STAMP_VERSION: 1.3.0.0');
+ expect(readFile(repo, 'VERSION').trim()).toBe('1.3.0.0');
+ expect(JSON.parse(readFile(repo, 'package.json')).version).toBe('1.3.0');
+ const cl = readFile(repo, 'CHANGELOG.md');
+ expect(cl).toMatch(/## \[1\.3\.0\.0\] - \d{4}-\d{2}-\d{2}\n\n- a change\n\n- b feature\n/);
+ expect(cl).toContain('## [1.2.3.0] - 2026-10-01\n\n- base release');
+ expect(fs.existsSync(path.join(repo.work, 'changelog.d', 'a.md'))).toBe(false);
+ expect(fs.existsSync(path.join(repo.work, 'changelog.d', 'b.md'))).toBe(false);
+ expect(readFile(repo, 'generated/digest.md')).toBe('# digest v1.3.0.0\nbody\n');
+ expect(readFile(repo, 'docs/feature.md')).toBe('since: 1.3.0.0\n');
+ expect(readFile(repo, 'docs/notes.md')).toContain('Previous release v1.2.3.0.');
+ });
+
+ test('takes its bump from the fragments: --bump with --release is a usage error', () => {
+ const repo = landed();
+ const r = runBin(repo, 'gstack-restamp', ['--release', '--bump', 'major', '--base', 'main', '--allow-repo-commands']);
+ expect(r.status).not.toBe(0);
+ expect(r.err).toContain('drop --bump');
+ expect(readFile(repo, 'VERSION').trim()).toBe('1.2.3.0');
+ });
+
+ test('refuses off a clean checkout of origin/<base>, and with no fragment to release', () => {
+ const repo = landed();
+ repo.git('checkout', '-q', '-b', 'side');
+ fs.writeFileSync(path.join(repo.work, 'side.txt'), 'x\n');
+ repo.git('add', '-A');
+ repo.git('commit', '-q', '-m', 'side');
+ const off = runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
+ expect(off.status).not.toBe(0);
+ expect(off.err).toContain('RELEASE_STAMP_INVALID');
+ expect(readFile(repo, 'VERSION').trim()).toBe('1.2.3.0');
+ const empty = landed({});
+ const none = runBin(empty, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
+ expect(none.status).not.toBe(0);
+ expect(none.err).toContain('RELEASE_STAMP_EMPTY');
+ });
+});
+
+describe('classifyRelease and the Version Gate', () => {
+ test('accept exactly the release stamp of the merge base', () => {
+ const repo = landed();
+ const base = repo.git('rev-parse', 'origin/main');
+ const head = stampRelease(repo);
+ expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head })).toEqual({ ok: true, version: '1.3.0.0', fragments: ['changelog.d/a.md', 'changelog.d/b.md'] });
+ expect(classifyTrainHead({ repoRoot: repo.work, baseRef: 'main', head })).toEqual({ kind: 'release', version: '1.3.0.0', fragments: 2 });
+ });
+
+ test.each([
+ ['a product change rides along', (w: string) => fs.writeFileSync(path.join(w, 'feature.txt'), 'sneaked\n'), 'feature.txt'],
+ ['a fragment stays unfolded', (w: string) => fs.writeFileSync(path.join(w, 'changelog.d', 'a.md'), '- a change\n'), 'changelog.d/a.md'],
+ ['the CHANGELOG entry is edited', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('- a change', '- a rewritten change')), 'CHANGELOG.md'],
+ ['the release output is hand-edited', (w: string) => fs.writeFileSync(path.join(w, 'generated', 'digest.md'), '# digest v1.3.0.0\nedited\n'), 'generated/digest.md'],
+ ['package.json keeps the old version', (w: string) => fs.writeFileSync(path.join(w, 'package.json'), fs.readFileSync(path.join(w, 'package.json'), 'utf8').replace('"version": "1.3.0"', '"version": "1.2.3"')), 'package.json'],
+ ['the CHANGELOG heading names another version', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('## [1.3.0.0]', '## [9.0.0.0]')), 'CHANGELOG.md'],
+ ['two released sections swap their entries', (w: string) => fs.writeFileSync(path.join(w, 'CHANGELOG.md'), fs.readFileSync(path.join(w, 'CHANGELOG.md'), 'utf8').replace('- base release\n', '\0').replace('- older\n', '- base release\n').replace('\0', '- older\n')), 'rewrites the released section(s) 1.2.3.0'],
+ ['the release output is deleted', (w: string) => fs.rmSync(path.join(w, 'generated', 'digest.md')), 'generated/digest.md'],
+ ['the release output keeps the old version', (w: string) => fs.writeFileSync(path.join(w, 'generated', 'digest.md'), '# digest v1.2.3.0\nbody\n'), 'generated/digest.md'],
+ ['the version is not base + the fragments\' bump', (w: string) => fs.writeFileSync(path.join(w, 'VERSION'), '1.4.0.0\n'), 'is 1.3.0.0'],
+ ])('refuse a release head where %s', (_name, tamper, named) => {
+ const repo = landed();
+ const base = repo.git('rev-parse', 'origin/main');
+ runBin(repo, 'gstack-restamp', ['--release', '--base', 'main', '--allow-repo-commands']);
+ tamper(repo.work);
+ repo.git('add', '-A');
+ repo.git('commit', '-q', '-m', 'release');
+ const head = repo.git('rev-parse', 'HEAD');
+ const v = classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: base, head });
+ expect(v.ok).toBe(false);
+ expect((v as { reason: string }).reason).toContain(named);
+ const gate = classifyTrainHead({ repoRoot: repo.work, baseRef: 'main', head });
+ expect(gate.kind).toBe('invalid');
+ expect((gate as { reason: string }).reason).toContain('RELEASE_STAMP_INVALID');
+ });
+
+});
+
+describe('gstack-release-stamp open', () => {
+ test('pushes release/<version> stamped from origin/main and opens its PR', () => {
+ const repo = landed();
+ repo.git('checkout', '-q', '-b', 'elsewhere');
+ const calls: string[][] = [];
+ const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => { calls.push(args); return { ok: true, out: args[1] === 'list' ? '' : 'https://github.com/o/r/pull/42\n', err: '' }; } });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.branch).toBe('release/1.3.0.0');
+ expect(r.pr).toBe('42');
+ expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/release/1.3.0.0')).toBe(r.head!);
+ expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/main')).toBe(repo.git('rev-parse', 'origin/main'));
+ expect(calls.map(a => a[1])).toEqual(['list', 'create']);
+ expect(calls[1]!.slice(0, 7)).toEqual(['pr', 'create', '--base', 'main', '--head', 'release/1.3.0.0', '--title']);
+ expect(r.lines.join('\n')).toContain('NEXT: gstack-ship-queue land --pr 42 --pin ' + r.head);
+ expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: repo.git('rev-parse', 'origin/main'), head: r.head! }).ok).toBe(true);
+ expect(repo.git('branch', '--show-current')).toBe('elsewhere');
+ expect(repo.git('worktree', 'list').split('\n')).toHaveLength(1);
+ });
+
+ test('a fork PR on release/<version> is never reused: open lists same-repo heads only and opens its own PR', () => {
+ const repo = landed();
+ const calls: string[][] = [];
+ const fork = [{ url: 'https://github.com/fork/r/pull/9', isCrossRepository: true }];
+ const r = openRelease({ repoRoot: repo.work, base: 'main', gh: (args) => {
+ calls.push(args);
+ if (args[1] !== 'list') return { ok: true, out: 'https://github.com/o/r/pull/43\n', err: '' };
+ const jq = args[args.indexOf('--jq') + 1] ?? '';
+ return { ok: true, out: jq.includes('select(.isCrossRepository | not)') ? '' : fork[0]!.url + '\n', err: '' };
+ } });
+ expect(r.ok).toBe(true);
+ if (!r.ok) return;
+ expect(r.pr).toBe('43');
+ expect(calls.map(a => a[1])).toEqual(['list', 'create']);
+ });
+
+ test('a checkout with node_modules commits only the stamp, and opening again at the same base replaces the release branch', () => {
+ const repo = landed();
+ fs.writeFileSync(path.join(repo.work, '.gitignore'), 'node_modules/\n');
+ repo.git('add', '.gitignore');
+ repo.git('commit', '-q', '-m', 'ignore node_modules');
+ repo.git('push', '-q', 'origin', 'HEAD:refs/heads/main');
+ fs.mkdirSync(path.join(repo.work, 'node_modules'));
+ const gh = () => ({ ok: true, out: 'https://github.com/o/r/pull/43\n', err: '' });
+ const first = openRelease({ repoRoot: repo.work, base: 'main', gh });
+ expect(first.ok).toBe(true);
+ if (!first.ok) return;
+ expect(repo.git('show', '--name-only', '--format=', first.head!).split('\n')).not.toContain('node_modules');
+ expect(classifyRelease({ repoRoot: repo.work, policy: policyOf(repo), mergeBase: repo.git('rev-parse', 'origin/main'), head: first.head! }).ok).toBe(true);
+ const again = openRelease({ repoRoot: repo.work, base: 'main', gh, now: new Date('2030-01-02T00:00:00Z') });
+ expect(again.ok).toBe(true);
+ if (!again.ok) return;
+ expect(repo.git('--git-dir', repo.origin, 'rev-parse', 'refs/heads/' + again.branch)).toBe(again.head!);
+ expect(repo.git('branch', '--list', 'release/*')).toBe('');
+ });
+
+ test('--dry-run creates nothing; an empty base is refused', () => {
+ const repo = landed();
+ const dry = openRelease({ repoRoot: repo.work, base: 'main', dryRun: true, gh: () => { throw new Error('no gh in a dry run'); } });
+ expect(dry.ok).toBe(true);
+ expect(repo.git('--git-dir', repo.origin, 'branch', '--list', 'release/*')).toBe('');
+ const empty = landed({});
+ const none = openRelease({ repoRoot: empty.work, base: 'main', gh: () => { throw new Error('no gh when empty'); } });
+ expect(none.ok).toBe(false);
+ expect((none as { code: string }).code).toBe('RELEASE_STAMP_EMPTY');
+ });
+});
diff --git a/test/ship-queue-land-direct.test.ts b/test/ship-queue-land-direct.test.ts
index 0657f0717..bb8d32a34 100644
--- a/test/ship-queue-land-direct.test.ts
+++ b/test/ship-queue-land-direct.test.ts
@@ -16,6 +16,7 @@ import { shippedBody } from './helpers/ship-queue-train-fixture';
import { persist, repoIdentity } from '../lib/ship-queue-train-record';
import { rewriteStamps, tentativeMentions } from '../lib/restamp';
import { bumpVersion } from '../lib/version-gate-train';
+import { openRelease } from '../lib/release-stamp';
const REQUIRED = ['free-tests', 'Check VERSION is not stale vs queue'];
const POLICY = { ...BASE_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d', required_checks: REQUIRED }, merge: 'direct', min_gstack_version: MERGE_KEY_VERSION };
@@ -417,3 +418,92 @@ describe('merge: direct | train', () => {
if ('merge' in raw) expect(validatePolicy(raw, { gstackVersion: fork })).toEqual([]);
});
});
+
+describe('land --pin: the release PR (docs/ship-policy.md#release-stamp)', () => {
+ /** Land PR 7 (a fragment), then open the release PR from origin/main with gstack-release-stamp open's code path. */
+ function release(fx: Fx, tamper?: (work: string) => void): { pin: string; base: string } {
+ expect(land(fx, '7', openPr(fx, '7')).status).toBe(EXIT.ok);
+ const base = remote(fx, 'main');
+ const r = openRelease({ repoRoot: fx.repo.work, base: 'main', gh: () => ({ ok: true, out: 'https://github.com/o/r/pull/50\n', err: '' }) });
+ if (!r.ok) throw new Error(r.message);
+ let pin = r.head!;
+ if (tamper) {
+ fx.repo.git('fetch', '-q', 'origin', '+refs/heads/*:refs/remotes/origin/*');
+ fx.repo.git('checkout', '-q', '--detach', pin);
+ tamper(fx.repo.work);
+ fx.repo.git('add', '-A');
+ fx.repo.git('commit', '-q', '-m', 'hand edit');
+ fx.repo.git('push', '-q', '-f', 'origin', 'HEAD:refs/heads/' + r.branch);
+ pin = fx.repo.git('rev-parse', 'HEAD');
+ fx.repo.git('checkout', '-q', '--detach', 'origin/main');
+ }
+ fx.write(d => { d.prs['50'] = { state: 'OPEN', baseRefName: 'main', headRefName: r.branch, isCrossRepository: false, title: 'v' + r.version + ' release', body: '' }; });
+ return { pin, base };
+ }
+
+ test('a release/<version> head that is exactly the release stamp lands with no /ship receipt or READY note, and main moves to the new version', () => {
+ const fx = setup();
+ const { pin, base } = release(fx);
+ const next = bumpVersion(show(fx, base + ':VERSION'), 'patch')!;
+ const r = land(fx, '50', pin);
+ expect(r.err).toBe('');
+ expect(r.status).toBe(EXIT.ok);
+ expect(r.out).toContain('RELEASE: v' + next + ' folds 1 fragment(s)');
+ const main = remote(fx, 'main');
+ expect(show(fx, main + ':VERSION')).toBe(next);
+ expect(show(fx, main + ':CHANGELOG.md')).toContain('- #7 change');
+ expect(spawnSync('git', ['-C', fx.repo.work, 'cat-file', '-e', main + ':changelog.d/pr-7.md'], { timeout: 30_000 }).status).not.toBe(0);
+ }, 120_000);
+
+ test('a release/<version> head with a hand edit beyond the stamp is refused with RELEASE_STAMP_INVALID and nothing merges', () => {
+ const fx = setup();
+ const { pin, base } = release(fx, work => fs.writeFileSync(path.join(work, 'pr-7.txt'), 'changed in the release\n'));
+ const r = land(fx, '50', pin);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('RELEASE_STAMP_INVALID');
+ expect(r.err).toContain('pr-7.txt');
+ expect(remote(fx, 'main')).toBe(base);
+ }, 120_000);
+
+ test('a release head on a branch naming another version is refused with RELEASE_STAMP_INVALID', () => {
+ const fx = setup();
+ const { pin, base } = release(fx);
+ fx.repo.git('push', '-q', 'origin', pin + ':refs/heads/release/9.9.9.9');
+ fx.write(d => { d.prs['50'].headRefName = 'release/9.9.9.9'; });
+ const r = land(fx, '50', pin);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('not the version its branch names');
+ expect(remote(fx, 'main')).toBe(base);
+ }, 120_000);
+
+ test('a rerun after the release merged, from a fresh clone without the pin, fetches it and lands against the main it was stamped on', () => {
+ const fx = setup();
+ const { pin, base } = release(fx);
+ expect(land(fx, '50', pin).status).toBe(EXIT.ok);
+ const branch = fx.read().prs['50'].headRefName as string;
+ const g = (...a: string[]) => fx.repo.git('--git-dir', fx.repo.origin, ...a);
+ g('update-ref', 'refs/pull/50/head', pin);
+ fx.write(d => { d.prs['50'].headRefOid = pin; });
+ g('update-ref', '-d', 'refs/heads/' + branch);
+ const fresh = fx.repo.root + '/fresh';
+ fx.repo.git('clone', '-q', '--no-local', '--single-branch', '--branch', 'main', fx.repo.origin, fresh);
+ expect(spawnCheck(fresh, pin)).toBe(false);
+ const r = runBin(fx.repo, 'gstack-ship-queue', ['land', '--pr', '50', '--pin', pin, '--base', 'main'], fx.env, fresh);
+ expect(r.err).toBe('');
+ expect(r.status).toBe(EXIT.ok);
+ expect(r.out).toContain('already merged');
+ expect(r.out).toMatch(/^LANDED: .* equals the pin merged onto /m);
+ expect(r.out).toContain(base);
+ }, 120_000);
+
+ test('a release head stamped on an older main is refused: PRs that landed since would ship under its version', () => {
+ const fx = setup();
+ const { pin } = release(fx);
+ const moved = moveMain(fx, 'later.txt', 'landed after the stamp\n');
+ const r = land(fx, '50', pin);
+ expect(r.status).not.toBe(EXIT.ok);
+ expect(r.err).toContain('RELEASE_STAMP_INVALID');
+ expect(r.err).toContain('moved to ' + moved.slice(0, 12));
+ expect(remote(fx, 'main')).toBe(moved);
+ }, 120_000);
+});