Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Releases per batch: PRs carry a changelog fragment, a release PR writes the version

garrytan58e17ac816f4
diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml
index d89ca45116..4ae0554fb9 100644
--- a/.github/workflows/e2e.yml
+++ b/.github/workflows/e2e.yml
@@ -35,8 +35,10 @@ permissions:
# push runs. Scheduled runs get their own `-nightly` group (as in test.yml):
# sharing refs/heads/master with push runs let the next merge cancel the
# nightly full corpus mid-shard (#6040).
+# A push to master is keyed by its commit, so a newer push never cancels it: the Release gate
+# (scripts/release-gate.ts) publishes only the release commit's own green runs.
concurrency:
- group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.full_corpus && '-full-corpus' || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.sha) || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.full_corpus && '-full-corpus' || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}
cancel-in-progress: true
jobs:
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 37887a8b61..cbfb7edf37 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -22,11 +22,17 @@ name: Release
# CI gate (docs/RELEASING.md#release-ci-gate): the `ci-gate` job waits for
# the push-to-master runs of Test and E2E Tests on the release commit
# (scripts/release-gate.ts). Build, publication and the latest-stable move
-# run only after both succeed. A failed run publishes nothing and the job
-# fails with the next step; a run cancelled by a newer push is followed to
-# the next master commit with the same VERSION (published there) or marks
-# this version superseded; workflow_dispatch backfills master HEAD's VERSION
-# through the same gate.
+# run only after both succeed. A failed or cancelled run publishes nothing
+# and the job fails with the next step; master push runs are keyed by commit,
+# so no newer push cancels them, and no later commit is published in the
+# release commit's place (it may carry unreleased changes under the same
+# VERSION). workflow_dispatch backfills master HEAD's VERSION through the
+# same gate.
+#
+# Releases per batch (docs/RELEASING.md#releases-per-batch): PRs land with
+# changelog.d fragments and no version; a release PR moves VERSION, so this
+# workflow runs once per release. Its ci-gate refuses a commit that still
+# holds an unfolded fragment or a stale behavior-change table.
on:
push:
@@ -87,13 +93,18 @@ jobs:
with:
persist-credentials: false
sparse-checkout: |
+ .gstack
scripts
+ changelog.d
+ behavior-changes.d
src/core/behavior-change-notice.ts
+ src/core/behavior-changes.generated.ts
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
with:
bun-version: 1.4.4
- # A since: 'TBD' BEHAVIOR_CHANGES row never ships (scripts/check-behavior-since.ts).
- - name: Refuse a since 'TBD' BEHAVIOR_CHANGES row
+ # A since: 'TBD' BEHAVIOR_CHANGES row never ships, and a release commit folds every changelog
+ # fragment and dates every behavior-change row (scripts/check-behavior-since.ts --stamped).
+ - name: Refuse a since 'TBD' row, an unfolded fragment or a stale behavior-change table
run: bun scripts/check-behavior-since.ts --stamped
- id: gate
name: Wait for Test and E2E Tests on the release commit
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 904e1c13e1..684d4df8dc 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -61,8 +61,10 @@ permissions:
# replay never cancels another or a full run.
# Event parity (docs/TESTING.md#event-parity): the event suffixes only separate
# runs that must not cancel each other; they change no job, matrix or parameter.
+# A push to master is keyed by its commit, so a newer push never cancels it: the Release gate
+# (scripts/release-gate.ts) publishes only the release commit's own green runs.
concurrency:
- group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && '-native-only' || '' }}${{ github.event_name == 'workflow_dispatch' && (inputs.race_hunt == true || inputs.stress_files != '' || inputs.stress_base != '') && format('-diagnostic-{0}', github.run_id) || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}
+ group: ${{ github.workflow }}-${{ github.event.pull_request.number || (github.event_name == 'push' && github.sha) || github.ref }}${{ github.event_name == 'workflow_dispatch' && inputs.native_only == true && '-native-only' || '' }}${{ github.event_name == 'workflow_dispatch' && (inputs.race_hunt == true || inputs.stress_files != '' || inputs.stress_base != '') && format('-diagnostic-{0}', github.run_id) || '' }}${{ github.event_name == 'schedule' && '-nightly' || '' }}
cancel-in-progress: true
jobs:
diff --git a/.gstack/ship-policy.json b/.gstack/ship-policy.json
index c1ce10a2f7..e1c36bb53d 100644
--- a/.gstack/ship-policy.json
+++ b/.gstack/ship-policy.json
@@ -1,24 +1,28 @@
{
"bump": "patch",
- "min_gstack_version": "1.94.16.0",
+ "min_gstack_version": "1.98.0.0",
"queue_mode": "stamp-at-merge",
+ "history": "merge-only",
+ "merge": "direct",
"changelog": "CHANGELOG.md",
+ "changelog_fragments": { "dir": "changelog.d" },
+ "restamp_command": "bun scripts/release-restamp.ts --stamp-only",
+ "release_tool": "bun scripts/build-behavior-changes.ts",
+ "release_outputs": ["src/core/behavior-changes.generated.ts"],
+ "land": { "merged_checks": ["bun run typecheck", "bun run verify"] },
"stamp_files": [
"VERSION", "package.json", "CHANGELOG.md", "openclaw.plugin.json",
".claude-plugin/plugin.json", ".codex-plugin/plugin.json",
"plugin-variants/*/.claude-plugin/plugin.json", "plugin-variants/*/.codex-plugin/plugin.json",
"plugin-variants/*/README.md", "plugin/README.md",
- "BOOTSTRAP_FOR_AGENTS.md", "templates/bootstrap/template-repo/README.md",
- "src/core/behavior-change-notice.ts"
+ "BOOTSTRAP_FOR_AGENTS.md", "templates/bootstrap/template-repo/README.md"
],
"stamp_patterns": [
"\"version\": \"{version}\"",
- "since: '{version}'",
"<!-- gbrain-plugin-tree-stamp: {version} -->",
"<!-- gbrain-template-stamp: {version} -->",
"<!-- gbrain-runbook-stamp: {version} -->"
],
- "stamp_placeholders": ["TBD"],
"review_exclude_paths": ["docs/**", "test/fixtures/goldens/**"],
"migrations": { "dir": "src/core/schema-migrations", "id": "^v(\\d+)-" }
}
diff --git a/AGENTS.md b/AGENTS.md
index 3421302a8e..e35ca0d5c1 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -371,9 +371,9 @@ Ship via the `/ship` skill, not by hand. Pass its test lanes the exact commands
(CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave) lives in
[`./docs/RELEASING.md`](./docs/RELEASING.md); read it before shipping.
-**Always use PATCH without asking**, including the initial release choice;
-override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
-version stamps and the PR title, then report the number. This changes numbering
+**PRs carry no version** ([releases per batch](docs/RELEASING.md#releases-per-batch)):
+/ship writes a `changelog.d` fragment, and the release PR picks the next PATCH
+(never MINOR or MAJOR) and syncs every stamp. This changes numbering
only: scope, merge, deployment, paid-work and validation approvals still apply.
## Privacy
diff --git a/CLAUDE.md b/CLAUDE.md
index 7751dfc9e8..dae514f717 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -301,10 +301,11 @@ checkpoint resume, or DB-contention-aware pace mode.
## Version locations (single source of truth: `VERSION` file)
-Every release updates the required version stamps in the table below.
-`bun run release:restamp` rewrites all of them, renumbers the branch's own
-schema migrations after master's and runs the auto-derived regenerations;
-run it when the PR is next to merge ([how](docs/RELEASING.md#release-restamp)).
+Every release updates the required version stamps in the table below. PRs do
+not: a PR carries a `changelog.d` fragment, and the release PR
+(`gstack-release-stamp open`, which runs `bun scripts/release-restamp.ts
+--stamp-only <version>`) rewrites every row at once
+([releases per batch](docs/RELEASING.md#releases-per-batch)).
Update TODOS only when filing new work. `/ship`'s Step 12 idempotency check
catches VERSION vs package.json drift; the canonical list lives here.
@@ -469,8 +470,10 @@ This applies to README, CHANGELOG, docs, PRs, commits, issues, and release pages
## PR title format — version FIRST (IRON RULE)
-PR titles and version-bump commit subjects start with the version, followed by
-the conventional-commit subject:
+A PR that carries no version (every PR under
+[releases per batch](docs/RELEASING.md#releases-per-batch)) is titled in
+plain words. Release PR titles and version-bump commit subjects start with the
+version, followed by the conventional-commit subject:
```
vMAJOR.MINOR.PATCH.MICRO <type>(<scope>): <summary> (#issue or wave ref)
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 89e586540d..900450fc14 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -440,7 +440,7 @@ to a sibling module. Every row also adds a behavior test of its own; the
| CLI-only command | The implementation in `src/commands/<name>.ts`; the dispatch module `src/cli/commands/<name>.ts`; a help line in `printHelp` (`src/cli.ts`, so raise its `module-size-limits.tsv` ceiling by one) | A record in `CLI_COMMANDS` (`src/cli/command-table.ts`): `phase: 'pre-connect'` when the command never touches the database, `'post-connect'` when its `run(engine, args, ctx)` needs an engine; `thinClient: 'none'` unless remote brains must refuse it (`'refuse'`, or `'route-then-refuse'` for subcommand routing); `selfHelp: true` when the command has flags or subcommands (its `run` then prints its own `--help`); optional `skipStartupHooks`; `load: () => import('<literal>')` | `bun run build:flag-registry`; the CLI goldens, deliberately: `GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/cli-goldens.test.ts test/cli-dispatch-phase.test.ts test/cli-dispatch-thin-client.test.ts` | `test/<name>.test.ts` spawning `bun src/cli.ts <name>` and asserting output and exit code, plus `bun test test/cli-command-table.test.ts test/cli-flag-validation.test.ts` |
| HTTP route (`gbrain serve --http`) | The route inside `mount<Area>(app, ctx)` in `src/commands/serve-http-<area>.ts` (`/admin/api/*` goes in `serve-http-admin-api.ts`, `/mcp` in `serve-http-mcp.ts`, OAuth in `serve-http-oauth.ts`); a new area is a new module plus one mount call in `buildServeHttpApp` (`src/commands/serve-http.ts`). An `/admin` route takes `ctx.requireAdmin` before its handler | None for a route in an existing area; a new area adds its mount call in `buildServeHttpApp` (order matters) | The route goldens, deliberately: `GBRAIN_TEST_UPDATE_GOLDENS=1 bun test test/serve-http-route-golden.test.ts test/serve-http-route-runtime-golden.test.ts` | A behavior test (`test/serve-http-<area>-<route>.test.ts`: mount the area on a bare `express()` app with a stub ctx; `mountAdminApi` reads `requireAdmin`, `sseClients` and `mcpResourceUrl` at mount time) plus `bun test test/serve-http-admin-route-guard.test.ts`, which finds the new route by itself |
| Sync phase | A module under `src/commands/sync/` taking `(run, Pick<SyncPlan, ...>, ...)` and returning `SyncResult \| undefined`; state it shares across awaits becomes a field on `SyncRun` (`src/commands/sync/sync-run.ts`). A value for the final summary flows `SyncRun` field -> `finalizeIncrementalSync` (`sync/finalize.ts`) -> `SyncResult` (`src/commands/sync.ts`, raise its ceiling) -> `printSyncResult` (`sync/report.ts`) when it should print | The phase call order in `performSyncInner` (`src/commands/sync/incremental.ts`) | Nothing | A case in `test/sync-run-ordering.serial.test.ts` (it has the git-repo + PGLite harness: `commitPages`, `performSync`), plus `bun test test/sync.test.ts test/sync-run-ordering.serial.test.ts` |
-| Release version and migration numbers | Nothing by hand: when your PR is next to merge, `bun run release:restamp` (preview with `--dry-run`) merges `origin/master`, sets the PATCH version, renumbers your own migrations and commits once | None: it rewrites every required row of the CLAUDE.md "Version locations" table | It runs the generators itself and prints the golden-regeneration reason for the PR body | `bun run verify`; `bun test test/scripts/release-restamp.test.ts` when you change restamp itself ([docs](docs/RELEASING.md#release-restamp)) |
+| Release version and migration numbers | `changelog.d/<branch-slug>.md` (your entry, no version heading; /ship writes it) and one `behavior-changes.d/<id>.md` per new upgrade-notice row; number a new migration master's latest + 1 | None: the release PR writes every version stamp; never edit VERSION, the manifests or a released CHANGELOG section | On a migration-number collision, `bun run migrations:renumber`; a PR stamped the old way converts with `bun run release:unstamp` | `bun run verify` (check:regen-all builds the behavior-change table); `bun test test/scripts/release-restamp.test.ts test/scripts/build-behavior-changes.test.ts` when you change those scripts ([docs](docs/RELEASING.md#releases-per-batch)) |
| Stress-test a touched test (flake hunt) | Nothing: `bun run test:stress [files…] [--iterations N] [--base <ref>] [--postgres]` (defaults: files changed versus `origin/master`, 10 iterations, a fresh database per iteration) | None | Nothing | The same command; a failing iteration prints its reproduce line |
The PR stress gate (`stress-changed-tests`) runs every test file the PR adds or
@@ -732,15 +732,14 @@ gstack reads both from master, so a branch's edits take effect after it merges.
`ship_lanes_from` maps /ship's unit, serial, slow and E2E lane commands to
those runs, so /ship carries a lane from full-ci instead of running it again
([/ship lanes](docs/ci-event-parity.md#ship-lanes)).
-- `.gstack/ship-policy.json`: the stamp rule (the release stamp files and
- version patterns) and the migration numbering `gstack-pregate regate` and
- `gstack-tree-receipt` use to decide whether a restamped head is the same tree
- that passed the gate, plus `min_gstack_version` (1.94.16.0, the first gstack
- that reads `stamp_placeholders`; 1.94.0.0 is the first that reads
- `ship_lanes_from`; an older one refuses with an upgrade fix).
- `stamp_placeholders: ["TBD"]` lets a branch's own `since: 'TBD'` row become
- `since: '<version>'` at the slot and still count as a stamp, so /ship's
- finish step does not read the restamp as a change made after review.
+- `.gstack/ship-policy.json`: releases per batch (`changelog_fragments` in
+ `changelog.d`, `merge: "direct"`, `restamp_command` and `release_tool` /
+ `release_outputs` for the release PR; [how](docs/RELEASING.md#releases-per-batch)),
+ the stamp rule (the release stamp files and version patterns) and the
+ migration numbering `gstack-pregate regate` and `gstack-tree-receipt` use
+ to decide whether a head is the same tree that passed the gate, plus
+ `min_gstack_version` (1.98.0.0, the gstack this policy was checked
+ against; an older one refuses with an upgrade fix).
`review_exclude_paths: ["docs/**", "test/fixtures/goldens/**"]` (gstack
1.93.33.0 or newer, read from master only) keeps docs and generated goldens
out of /ship's reviewer diffs, so a large wave stays under the reviewers'
diff --git a/behavior-changes.d/README.md b/behavior-changes.d/README.md
new file mode 100644
index 0000000000..e9675ced1d
--- /dev/null
+++ b/behavior-changes.d/README.md
@@ -0,0 +1,51 @@
+# behavior-changes.d
+
+One file per behavior change that gbrain's one-time upgrade notice discloses
+(`behavior_changes`, src/core/behavior-change-notice.ts). A PR adds its
+rows here instead of editing the table, so two PRs never touch the same
+line and nobody picks a version before the release.
+
+## Add a row
+
+1. Write the notice text, one paragraph of plain text (at most 2,000
+ characters, no markup), in `behavior-changes.d/<id>.md`. The id is
+ lowercase letters, digits and `_`, unique across the table, for example
+ `sync_holds_unparsable_8123`.
+2. Name the id in your PR's changelog fragment (`changelog.d/<slug>.md`)
+ on its own line:
+
+ ```markdown
+ <!-- behavior-change: sync_holds_unparsable_8123 -->
+ ```
+
+That is all. `bun run verify` (check:regen-all) refuses a fragment with no
+marker, a marker with no fragment, a duplicate id and an over-long text.
+
+## What the release does
+
+The release (`gstack-release-stamp open`) folds every changelog fragment
+into one CHANGELOG section under the new version, so each marker now sits
+under that version's heading. It then runs `bun scripts/build-behavior-changes.ts`,
+which writes src/core/behavior-changes.generated.ts: every fragment whose
+marker sits in a released section, with that section's version as its
+`since`. The files here are never edited or deleted, so the release changes
+only version stamps, the CHANGELOG and that generated file, which gstack's
+land check regenerates byte for byte.
+
+Until a release folds its marker, a fragment is pending: it generates
+nothing, the notice does not show it, and the generated file does not change
+on a PR.
+
+## A row whose text is a function
+
+Rows that compute their text (for example from the brain's config) stay in
+the `BEHAVIOR_CHANGES` table, dated by their marker:
+
+```ts
+{ since: releasedIn('chat_chain_disclosure_8123'), id: 'chat_chain_disclosure_8123', text: (chain, remote) => ... },
+```
+
+with the same `<!-- behavior-change: <id> -->` line in the changelog
+fragment. `releasedIn` reads the release from the generated file and is
+`'TBD'` until then, which the notice never shows. A literal
+`since: 'TBD'` row is refused (scripts/check-behavior-since.ts).
diff --git a/changelog.d/README.md b/changelog.d/README.md
new file mode 100644
index 0000000000..960e7f226b
--- /dev/null
+++ b/changelog.d/README.md
@@ -0,0 +1,23 @@
+# changelog.d
+
+One file per PR: the PR's CHANGELOG entry, without a version heading. gstack
+`/ship` writes it as `changelog.d/<branch-slug>.md`; nobody edits VERSION,
+the package.json version or CHANGELOG.md in a PR.
+
+```markdown
+**What changed, in one sentence.**
+
+### Fixed
+- ...
+```
+
+Optional front matter marks the change important for the stable channel
+(`important: security|regression|data-loss|blocker`), which makes the merge
+lane open a release right after it lands the PR. Releases are PATCH only, so
+there is no `bump:` line.
+A PR that changes behavior also names its behavior-changes.d row here
+(`<!-- behavior-change: <id> -->`, see behavior-changes.d/README.md).
+
+The release PR (`gstack-release-stamp open`) folds every fragment into one
+`## [<version>]` section, deletes the fragments and writes the version
+stamps. Format and rules: docs/RELEASING.md#releases-per-batch.
diff --git a/docs/RELEASING.md b/docs/RELEASING.md
index 04934b3e8a..a6a4a53433 100644
--- a/docs/RELEASING.md
+++ b/docs/RELEASING.md
@@ -134,8 +134,97 @@ queued commit against `master`.
actually merged (`gh pr view <n> --json state,mergedAt`) before tagging,
announcing or starting dependent work.
+## Releases per batch
+
+PRs no longer pick a version. A PR adds a changelog fragment and lands;
+a release PR, opened a few times a day, gives every fragment that reached
+master since the last release one version and writes all the stamps at once.
+`.gstack/ship-policy.json` turns this on (`changelog_fragments`,
+`merge: "direct"`), and gstack's /ship, receipt and land commands follow it.
+
+**What a PR carries.**
+
+- `changelog.d/<branch-slug>.md`: the PR's CHANGELOG entry with no version
+ heading (bold one-line summary, then the itemized sections; voice rules
+ below). /ship writes it. Front matter may say
+ `important: security|regression|data-loss|blocker`; releases are PATCH
+ only, so there is no `bump:` line. Format:
+ [changelog.d/README.md](../changelog.d/README.md).
+- One `behavior-changes.d/<id>.md` file per new upgrade-notice row, named
+ in the fragment as `<!-- behavior-change: <id> -->`
+ ([behavior-changes.d/README.md](../behavior-changes.d/README.md)).
+- Its own schema migrations, numbered master's latest + 1 when written.
+- Nothing else that carries a version: no edit to VERSION, the package.json
+ version, the plugin manifests, the BOOTSTRAP stamp, the plugin or template
+ trees, a released CHANGELOG section or a released `since:` row. The PR
+ title is plain words with no version in front.
+
+**The release PR.** The merge lane runs `gstack-release-stamp open`. On a
+fresh worktree of `origin/master` it sets VERSION to master's PATCH + 1,
+folds every `changelog.d` fragment under one `## [<version>] - <date>`
+heading and deletes the fragments, then runs
+`bun scripts/release-restamp.ts --stamp-only <version>` (every required row
+of the CLAUDE.md "Version locations" table plus the plugin, variant and
+template stamp lines; no fetch, no merge, no commit) and
+`bun scripts/build-behavior-changes.ts`, which dates each
+`behavior-changes.d` row whose marker now sits under the new heading. It
+pushes `release/<version>` and opens the PR. The lane lands it with
+`gstack-ship-queue land --pr <n> --pin <head>`, which accepts only a head
+that is exactly the release stamp of master's tip. The release PR runs the
+cheap tier; release.yml's ci-gate waits for the full Test and E2E push runs
+on the release commit before anything publishes.
+
+**When releases happen.** At 00:00, 06:00, 12:00 and 18:00 UTC the merge
+lane opens a release when master holds at least one fragment and the last
+release is 4 hours old or more. It also opens one right after landing a PR
+whose fragment says `important:`, so an important fix is in a published
+release within about an hour and can go to the stable channel (see "Daily
+stable check").
+
+**What refuses a bad release.** gstack's land refuses a release head that
+changes anything but stamps, the CHANGELOG fold and `release_outputs` (here
+`src/core/behavior-changes.generated.ts`, which it regenerates and compares
+byte for byte). release.yml runs `bun scripts/check-behavior-since.ts --stamped`,
+which refuses a release commit that still holds a `changelog.d` fragment,
+a literal `since: 'TBD'` row or a stale behavior-change table. A cancelled
+or skipped Test or E2E push run fails the gate with the `gh run rerun <id>`
+to run; the gate no longer follows to a later commit with the same VERSION,
+because between releases every master commit shares one.
+
+**Migration collisions.** Two open PRs can take the same migration number.
+GitHub then reports the second one conflicting (both edit the generated
+registry), and `check:schema-migration-order` fails on the merged tree.
+`bun run migrations:renumber` renumbers the branch's own migrations after
+master's latest (file name, export name and `version:` literal; the rest
+must be token-identical) and regenerates the registry, as step 5 of
+[Release restamp](#release-restamp) describes. That makes a new head, which
+needs a new full CI run. Migration numbers stay sequential for the reason
+given there.
+
+**Converting an open stamped PR.** A PR written before this switch still
+carries a version. `bun run release:unstamp` merges `origin/master`, puts
+every stamp back to master's version, moves the branch's CHANGELOG entry to
+`changelog.d/<branch-slug>.md` and its appended plain-text
+`BEHAVIOR_CHANGES` rows to `behavior-changes.d/` (with their markers),
+puts the notice file and its size-table row back to master's, and commits
+once. It refuses, with the fix, a branch with no entry of its own, one that
+edits a released CHANGELOG section, one that carries other PRs' entries (land
+or convert those first), and notice rows it can't move (rows without an id,
+rows whose text is a function, edits other than appending). Plain
+`release:restamp` refuses once master's policy says `merge: "direct"`.
+
+**Why notice rows are files.** Every PR used to append its row to the end of
+one array in `src/core/behavior-change-notice.ts`, which also raised that
+file's line in `scripts/module-size-limits.tsv`; those two lines were the
+second-largest source of master conflicts after the stamps. Rows in their
+own files, which the release never edits or deletes, touch neither line.
+
## CHANGELOG + VERSION are branch-scoped
+Under [releases per batch](#releases-per-batch) a PR writes only its
+`changelog.d` fragment; the voice rules below apply to that text, and the
+version and placement rules apply to the release PR.
+
**VERSION and CHANGELOG describe what THIS branch adds vs master, not how we got
here.** Every feature branch that ships gets its own version bump and CHANGELOG
entry. The entry is product release notes for users; it is not a log of internal
@@ -182,6 +271,11 @@ If any answer is no, fix it before continuing.
## Release restamp
+Under [releases per batch](#releases-per-batch) PRs do not restamp: the
+release PR stamps, and `release:restamp` refuses. Its renumbering runs on its
+own as `bun run migrations:renumber`, and `bun run release:unstamp` converts a
+PR stamped the old way. The steps below describe the shared machinery.
+
`bun run release:restamp` makes a branch next-to-merge in one command. Run it
when your PR is next in the merge line, not earlier: the merge coordinator
merges one PR at a time, so restamping at that moment allocates the version
@@ -554,10 +648,10 @@ succeed on the release commit.
- **Failed run:** nothing is published and the job fails with the run and the
master-red issue. After master is green again, publish the current VERSION
with `gh workflow run release.yml --ref master`.
-- **Run cancelled by a newer push:** the gate follows the next master commit.
- If it contains the release commit and carries the same VERSION, that commit
- is gated and published. If VERSION moved on, this version is skipped and the
- newer VERSION's release run publishes.
+- **Cancelled or skipped run:** nothing is published and the job fails with
+ `gh run rerun <id>`. Master push runs are keyed by commit, so a newer push
+ no longer cancels them; and between releases many master commits share one
+ VERSION, so the gate never follows to a later commit.
- **Backfill:** `gh workflow run release.yml --ref master` gates and publishes
master HEAD's VERSION. Other refs are refused.
- The gate waits up to 110 minutes, then fails with the backfill command.
diff --git a/docs/architecture/key-files/agent-contract.md b/docs/architecture/key-files/agent-contract.md
index bb019e0e4a..05036c5d73 100644
--- a/docs/architecture/key-files/agent-contract.md
+++ b/docs/architecture/key-files/agent-contract.md
@@ -31,7 +31,7 @@ Spec: `docs/designs/AGENT_OPERATOR_WAVE.md`; wire goldens: `test/fixtures/agent-
- `src/mcp/initialize-context.ts` — per-initialize inputs for the generated instructions (`httpInstructionTools`: the tools/list filters with publish gates read on initialize; `instructionReadiness`: config plane + probed tier within 250 ms, HTTP view redacted) and `stdioCapabilityReadiness` (F2). Test: `test/mcp-capabilities-readiness.test.ts`.
- `src/mcp/hidden-tool-hint.ts` + `src/core/ops/cli-equivalent.ts` — F6: on the owner's stdio pipe a real tool outside the surface/read-only access gets `unknown_tool` naming itself and its CLI equivalent (`cliEquivalent`: `cliOnly` argv, curated overrides, `cliHints.name`, else `gbrain call`). Where `request_tools` is callable and session widening is on, the fix is `request_tools {surface:'full'}` (`next: run`, argv kept); otherwise the CLI equivalent with actor `user` and a `user_message`; `why` names the lasting route (`GBRAIN_SURFACE=full` in the harness's per-server env, or a `--surface full` re-registration) and that an inherited `GBRAIN_SURFACE` overrides a pinned `--surface`. Read-only access never offers a widen. HTTP stays opaque. `scripts/generate-plugin-tree.ts` appends the same map as a per-skill note to generated starter-gap skills. Test: `test/hidden-tool-hint.test.ts`. D2: `hiddenToolRoute(op, ToolConnection)` is the one decision for every transport (`callable` | `widen {surface}` | `host {read_only|surface|grant}`): a widen is offered only when the widened connection could call the tool (read-only access, `GBRAIN_MCP_FORCE_SURFACE`, the grant's snapshot/scopes and an operator pin all hold); dispatch builds the connection with `toolConnection(opts)`. `hiddenToolNext` turns a route into the D2 fix (the call itself; request_tools; on HTTP the D4 grant repair; on stdio the CLI equivalent with the call's arguments as flags).
- `Operation.cliOnly` + `cliOnlyRefusal` (`src/core/ops/callable.ts`) — F5: owner-only ops (they refuse every MCP caller) are never listed on MCP; a call gets `trusted_local_only` (error `permission_denied`) with the exact CLI command.
-- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)
+- `src/core/behavior-change-notice.ts` — the one-time `behavior_changes` safety notice: a live `chat_fallback_chain` (local view: entries, providers, refusal behavior, removal fix; HTTP view: only that a chain is configured), managed-brain lint repairs (`cycle.lint_fix`), smaller transcript parts re-embedded once (`TRANSCRIPT_REINGEST_MULTIPLIER`), a mention-linker rescan (v0.60.68.0), and fix wave 9's six upgrade-visible changes (v0.60.74.0). `BEHAVIOR_CHANGES` is the one table of disclosed changes, each with the release that introduced it; rows a PR adds live in `behavior-changes.d/<id>.md` and reach the table through `src/core/behavior-changes.generated.ts` (`RELEASED_BEHAVIOR_CHANGES`, spread at its end) once a release dates them, and function rows use `since: releasedIn(id)` (`FENCE_REPAIR_MEASURED` is the automatic fence repair row's measurement sentence, replaced by the Tier 3 eval's measured rates); `BEHAVIOR_NOTICE_SINCE` is the newest row's release (never `VERSION`), so the notice id `behavior_changes@<since>` moves only when a release appends rows. Content: the rows newer than the last notice release this brain × channel (× HTTP client) was shown, or than its baseline when never shown. Baseline: the brain's baseline under `GBRAIN_HOME/notices/behavior-changes/<brainKey>.baseline` (`gbrain init` stamps a database it creates; otherwise the first look records `0` when `upgrade-state.json` shows an upgrade from an older release or the oldest `sources.created_at` is past `FRESH_BRAIN_GRACE_MS`). Markers: CLI and stdio claim a `wx` file per notice × brain × channel (an unwritable home still delivers, once per process); the newest marker names the last release shown; HTTP keeps up to `HTTP_SHOWN_CAP` client ids, each with the release it was shown, in the `notices.behavior_changes.http` config row (a row from an older build counts its clients as shown its id's release) (no migration; a failed write still delivers). Delivery: `completeEngineStartup` in `src/cli.ts` (stderr; not `serve` or `doctor`), and `sessionSafetyNotices` in `src/mcp/dispatch.ts` on success and failure results. `gbrain doctor --only behavior_changes` reads every row newer than the baseline without writing. Pinned by `test/behavior-c... (line truncated to 2000 chars)
- `src/core/post-upgrade-notice.ts` — F7 `post_upgrade` safety notice (contract_version + behavior-table URL): `gbrain post-upgrade` writes it once; the first stdio MCP session per upgraded version gets it (persisted under GBRAIN_HOME). `src/cli/op-notices.ts` (also `retrievalIncompleteLine`, search/query's `Retrieval incomplete:` line: `projection_pending` only when `coverage` says some pending page could match, with the count, once per window across calls) renders op notices on the local CLI (`--json` objects gain `notices`; human output on stderr).
- `src/core/ops/op-fix.ts` — Lane B builders for filled, surface-correct op errors (type-only agent-output import: ops sit in the snapshot-schema closure). `opTransport(ctx)` (cli/stdio/http from `remote`+`transport`), `paramUse(ctx, param, value?)` (`--no-pull` vs `no_pull: true`), `readFix` (diagnostic step, `mcp` + `argv`), `hostFix`/`hostOnlyError` (B6: host-only command, actor agent on CLI / user on stdio / host_admin on http with relay `user_message`), `invalidParam` (B2/B3: param, choices or type+description, one example; never echoes the raw value), `scopeDeniedError` (B5: `insufficient_scope`, frozen `error` via `legacy_error`, client id + current scopes in `why`, the exact `gbrain auth rescope`/`rescope-token` command, consent `credentials`). Test: `test/op-fix.test.ts`, `test/scope-denial-contract.test.ts`.
- `src/core/persistence/page-identity.ts` — B4: `pageIdentityError(present, msg)` (a deleted page throws canonical `page_not_found` with the frozen wire/journal `error` `page_identity_changed`; a replaced page keeps `page_identity_changed`), `isMissingPageMessage` (replays recover the distinction from the stored message; no schema change), `yamlLocator` (content-free ` at line L, column C`). Replays (`writeResponse` in `persistence/service.ts`) set `OperationError.receiptFields` (never serialized); `toAgentError` fills the registry fix template (`{slug}`/`{source_id}`/`{request_id}`/`{operation}`, strict per-field patterns, unfillable → dropped) and applies the principal-aware receipt rule (CLI principal → `gbrain write-request`; same-principal MCP → `get_write_request` when callable; otherwise host inspection, actor host_admin). Test: `test/write-receipt-remediation.test.ts`.
diff --git a/docs/architecture/key-files/ci-health-and-test-guards.md b/docs/architecture/key-files/ci-health-and-test-guards.md
index 46f3a15d00..5002ec1848 100644
--- a/docs/architecture/key-files/ci-health-and-test-guards.md
+++ b/docs/architecture/key-files/ci-health-and-test-guards.md
@@ -9,12 +9,14 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `scripts/lib/master-red.ts` — master-red reconciliation for push-to-master runs of Test and E2E Tests (`PUSH_ALLOWLIST`). Each watch evaluates every completed push run above the high-water mark (`evaluated`: run number, then attempt) stored in the newest `Master red: <workflow>` issue's `master-red:json` block (`applyRun` folds runs; cancelled runs change nothing); a missing or malformed block is rebuilt from the actions API (`pendingRuns`). It opens on red with the suspect range (`suspectRange`: compare plus commit-to-PR lookups), updates while red, closes when every previously failing job (E2E Tests: every failing file, from the manifest) ran and passed with complete evidence, records an incident that opened and closed between watches, and keeps a not-run-since failure open with the manual-close step. A newest issue closed by hand while its block is red ends that incident (`closed_by_hand`): later runs are recorded on it as green, and only a new red run opens a new issue. `externalPass` lets a scheduled run or an issue-bound E2E replay clear failures. Closing without a merged linked repair PR opens `flake` issues (`flakeFor`, `flake:json`); `closeFlakes` closes one after its repair PR merged and a later complete run passed its file and arm. Writes re-read the issue first and re-plan when it moved; a create race closes the newer duplicate. Tests: `test/scripts/nightly-issue.test.ts`. Docs: `docs/ci-red-runbook.md`.
- `scripts/lib/ci-run.ts` — one run's failure evidence (`collectEvidence`): jobs, failing jobs' annotations and, for test.yml and e2e.yml, the `ci-manifest` artifact, returned as structured records (job, step, every failing test file and identity) apart from sanitized excerpts; a cancelled job is not run (listed in `cancelled`) unless its annotation says it timed out, and a red run whose only failures are aggregators of cancelled jobs is `ignored`; with `complete`/`problems` (an unreadable page, annotation or manifest is incomplete evidence, never zero failures). A push run with a succeeded `reused-full-suite` job is judged by the run its `reuse.json` names (`checkRecord` from `scripts/ci-reuse.ts`, recorded attempt, identical commit tree): that run's succeeded jobs and complete `ci-manifest` stand in for the push, and any gap is incomplete. `reproduceCommand` builds `bun run test:stress <file> --iterations 10 [--postgres]` from a validated test path only. `exemptionRows` turns failing identities with an exact test name and signature into the stress gate's `<!-- gbrain-stress-exemption -->` records (backend per `stressBackend`, owner `agent on release duty`), written into master-red, flake and nightly-red bodies; `test/fixtures/nightly-watch/stress-exemption-contract.ts` vendors the gate's parser so the tests prove it accepts them.
- `scripts/ci-manifest.ts` — the versioned failure and execution manifest (`gbrain-ci-manifest/v1`). The `executed-receipts` job of test.yml and e2e.yml builds it from every lane's receipts (via `scripts/ci-executed-counts.ts`, declared skips from the expected-deltas TSV), binds it to the workflow, event, SHA, run id and attempt, and uploads it as `ci-manifest`; each failure carries the JUnit message (credentials redacted) and the stress gate's `failureSignature` (omitted when the message holds a credential); `checkManifest` refuses a manifest for another run or attempt; `passedFiles` lists files that executed tests and failed none. Docs: `docs/ci-red-runbook.md#ci-failure-manifest`.
-- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a run cancelled by a newer push is followed to the next master commit with the same VERSION (published there) or marks the version superseded; non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.
+- `scripts/release-gate.ts` — release.yml's `ci-gate` job. Polls the push-to-master runs of Test and E2E Tests on the release commit and writes `publish`/`sha`: both green publishes; a failed run publishes nothing and fails with the next step; a cancelled or skipped run publishes nothing and fails with `gh run rerun <id>` (master push runs are keyed by sha, and between releases many commits share one VERSION, so it never follows to a later commit); non-master refs are refused; it fails with the backfill command after 110 minutes. Build, release, `latest-stable` and the publish jobs use the gated commit. Tests: `test/scripts/release-gate.test.ts`. Docs: `docs/RELEASING.md#release-ci-gate`.
- `.github/workflows/promote-stable.yml` + `scripts/promote-stable.ts` — stable channel promotion (`workflow_dispatch`: `version`, `soak_run_url`, `scoreboard_url`, `rollback`, `reason`, `withdraw`; concurrency group `promote-stable`). `promote()` refuses unless the actor's `role_name` is admin or maintain (`authorize()`; the one exception is `PromoteDeps.scheduled`, set by `scheduleAuthorized()` only for a schedule event of `stable-daily.yml` on the default branch, which also requires the release commit on master and records `promoted_by: schedule (.github/workflows/stable-daily.yml)`), `v<VERSION>` exists with a `VERSION` file naming it and a published (non-draft) GitHub release, the soak run URL names a completed, successful run of this repository's `STABLE_SOAK_WORKFLOW` workflow (repository variable; bare file name or path), the run's head commit has the release tag's exact tree (fetched when missing), and the version is newer than the current stable (the highest `v*` tag on `refs/tags/stable^{commit}`), or older with `rollback` and a reason. Re-promoting the current stable (no rollback) moves no tag: `recordCurrentStable()` writes `stable.json` from the stable tag's message (`parseTagMessage()`, which must name the same commit, tree and soak run) when the published record does not name that release, leasing `stable` unchanged and the record branch, and refuses as a no-op otherwise (GBRA-346 backfill for releases promoted before the record existed). It creates the immutable annotated `stable-v<VERSION>` record (refused when it exists, except on a rollback re-promotion of the same commit) and moves the annotated `stable` tag, both with `renderTagMessage()`'s `key: value` body, commits the evidence record (`renderRecord()`, `stable.json`, `known_bad` carried forward and merged with `withdraw` by `mergeKnownBad()`) on the `stable-record` branch, then pushes all three in one `--atomic` push (`stable` and `stable-record` leased on the values it read, so a failed push changes nothing) and writes the step summary. Side effects come in through `PromoteDeps`. Tests: `test/scripts/promote-stable.test.ts`. Docs: `docs/RELEASING.md#stable-channel-promotion`.
- `.github/workflows/stable-daily.yml` + `scripts/stable-daily.ts` — the daily stable check (05:17 and 13:17 UTC; dispatch defaults to `dry_run`, and `dry_run=false` needs admin or maintain; concurrency group `promote-stable`). Off when `STABLE_AUTO_PROMOTE` is `off`, paused while the stable record says `rollback: true`. Acts only on a reason: a merged `stable:important` PR released but not in stable, or stable older than `WEEKLY_FLOOR_DAYS` (7) with a newer release. Promotes, through `promote()`, the newest release on master newer than stable whose exact tree passed a full `SOAK_SHAPE` `STABLE_SOAK_WORKFLOW` run with every `INTEGRITY_GATES` gate passing in every cell (on the important-only path it must contain the fix); otherwise dispatches one soak on the newest release's tag, never while a soak runs or after a soak on a newer release failed to qualify. Tests: `test/scripts/stable-daily.test.ts`. Docs: `docs/RELEASING.md#daily-stable-check`.
- `scripts/check-install-ref.ts` (`bun run check:install-ref`, in verify) — every install pin, bootstrap runbook fetch and setup-helper fetch in tracked files (not CHANGELOG.md or test/) names `INSTALL_REF` from `src/core/install-ref.ts`; exact `v<version>` and commit pins are left alone; TypeScript must import the constant; `--write` rewrites the text surfaces. `scripts/check-bootstrap-tag.sh` reads its sanctioned ref from the same constant. Tests: `test/install-ref.test.ts`.
- `scripts/regen-all.ts` — one entry point for every generated artifact (`ARTIFACTS`: regen and check command per artifact). `bun run regen:all` regenerates offline and keyless (provider keys and database URLs removed) and lists what changed; a second run changes nothing. `--check` is read-only and runs in `verify` as `check:regen-all`; `--goldens` also regenerates the offline contract goldens. Postgres goldens are named with their own commands, and `llms.txt` regenerates last because it inlines other generated docs. Every `bun test` it spawns (two checks and the goldens) carries `--timeout=60000` through one `BUN_TEST` prefix, because Bun does not apply bunfig.toml's `[test] timeout`. Tests: `test/scripts/regen-all.test.ts`.
-- `scripts/release-restamp.ts` + `scripts/lib/restamp.ts` — `bun run release:restamp`, run when a PR is next to merge. The CLI refuses a dirty tree, fetches `origin/master`, captures the branch CHANGELOG entry and migration inventory, merges master with a merge commit (version-only stamp hunks, `CHANGELOG.md` and the `GENERATED_PATHS` files resolve mechanically; anything else stops), sets VERSION to master's PATCH + 1, renumbers branch-only migrations from master's latest + 1 (filename, export name and `version:` literal only; `migrationPayloadKey` proves the rest is token-identical and refuses a copy of a published migration or an edited published one), rewrites `STAMPS` (the CLAUDE.md "Version locations" Required rows) plus CHANGELOG and TODOS, runs `DEFAULT_STEPS`, lists branch-added lines that still name an old number (`findLeftoverRefs`, never rewritten), runs `DEFAULT_CHECKS` and commits once. Stops save `.git/gbrain-restamp.json` for `--continue` / `--abort`; `--dry-run` prints the plan, `--no-commit` stages. Generators run through `offlineEnv` (no database URLs, no provider keys). Tests: `test/scripts/release-restamp.test.ts` (fixture repos with the real migration generator; also pins CLAUDE.md table coverage and docs anchors).
+- `scripts/build-behavior-changes.ts` — writes (or `--check`s) `src/core/behavior-changes.generated.ts` from `behavior-changes.d/<id>.md` and the `<!-- behavior-change: <id> -->` markers in released CHANGELOG sections (and in `changelog.d` fragments while VERSION is newer than the top heading, i.e. inside a release PR): `RELEASED_BEHAVIOR_CHANGES` rows dated by their section, `BEHAVIOR_CHANGE_RELEASES` for `releasedIn(id)` rows. Refuses unmarked files, dangling markers, duplicate ids, bad names and texts over 2,000 characters. The release PR's `release_tool`; in `regen:all`. Tests: `test/scripts/build-behavior-changes.test.ts`.
+- `scripts/check-behavior-since.ts` — refuses a literal `since: 'TBD'` row under `merge: "direct"`; `--stamped` (release.yml ci-gate) also refuses an unfolded `changelog.d` fragment and a stale behavior-change table. Tests: `test/scripts/check-behavior-since.test.ts`.
+- `scripts/release-restamp.ts` + `scripts/lib/restamp.ts` — `bun run release:restamp`, run when a PR is next to merge. The CLI refuses a dirty tree, fetches `origin/master`, captures the branch CHANGELOG entry and migration inventory, merges master with a merge commit (version-only stamp hunks, `CHANGELOG.md` and the `GENERATED_PATHS` files resolve mechanically; anything else stops), sets VERSION to master's PATCH + 1, renumbers branch-only migrations from master's latest + 1 (filename, export name and `version:` literal only; `migrationPayloadKey` proves the rest is token-identical and refuses a copy of a published migration or an edited published one), rewrites `STAMPS` (the CLAUDE.md "Version locations" Required rows) plus CHANGELOG and TODOS, runs `DEFAULT_STEPS`, lists branch-added lines that still name an old number (`findLeftoverRefs`, never rewritten), runs `DEFAULT_CHECKS` and commits once. Stops save `.git/gbrain-restamp.json` for `--continue` / `--abort`; `--dry-run` prints the plan, `--no-commit` stages. Generators run through `offlineEnv` (no database URLs, no provider keys). Modes for releases per batch (`docs/RELEASING.md#releases-per-batch`): `--stamp-only <version>` (the release PR's `restamp_command`: every `STAMPS` row plus the plugin, variant and template stamp lines; no fetch, merge or commit), `--unstamp` (`bun run release:unstamp`: merge master, stamps back to master's version, the entry to `changelog.d/<branch-slug>.md`, appended plain-text notice rows to `behavior-changes.d/`; refuses multi-entry branches, released-section edits and rows it cannot move) and `--renumber` (`bun run migrations:renumber`); plain restamp refuses when master's policy says `merge: "direct"`. Tests: `test/scripts/release-restamp.test.ts` (fixture repos with the real migration generator; also pins CLAUDE.md table coverage and docs anchors).
- `scripts/ci-convergence-scope.sh` — #6712 PR 0: classifies a pull request's changed files (stdin) for the managed-sync convergence gate (`persistence-validation.yml` `convergence`): `run` for persistence, sync commands and sync core, page projections and storage, `bun.lock` and `vendor/postgres/`, the harness (`test/sync-convergence.serial.test.ts`, `test/fixtures/convergence-fault-kill.ts`), this script and its workflows (`persistence-validation.yml`, `convergence-nightly.yml`); `skip` otherwise, and never selected by `package.json` alone, so a release-stamp PR does not run it; an empty list runs. test.yml `changes` calls it for pull requests only (step `convergence`, passed as the `convergence` input). Tests: `test/scripts/ci-pr-scope.test.ts`.
- `scripts/ci-manifest-diff.sh` — parsed-JSON classification of manifest diffs for CI scoping: `version-only` (only the top-level `version` differs), `dependency-change` (any dependency field differs), `dependency-scope` (whether a changed-file list touches lockfiles, `patches/` or dependency fields) and `drop-version-only` (filters version-only `package.json` and `openclaw.plugin.json` entries out of a changed-file list, so a release bump does not widen the native scope). Used by test.yml's `changes` job (before `scripts/ci-native-scope.sh`) and its dependency-audit scope step. Tests: `test/scripts/ci-manifest-diff.test.ts`.
- `scripts/ci-dependency-audit.sh` — runs `bun audit` for the root and `admin/` lockfiles. It blocks (`BLOCKING=true`) on pushes, schedules and dispatches, on lockfile, `patches/` or dependency-field changes, with the `dependency-audit` label, or when the diff cannot be read; elsewhere an advisory is a `::warning::` naming why the run does not block.
diff --git a/llms-full.txt b/llms-full.txt
index b8356e3356..601bb11482 100644
--- a/llms-full.txt
+++ b/llms-full.txt
@@ -2143,9 +2143,9 @@ Ship via the `/ship` skill, not by hand. Pass its test lanes the exact commands
(CHANGELOG voice, version-locations sync, PR conventions, community-PR-wave) lives in
[`./docs/RELEASING.md`](./docs/RELEASING.md); read it before shipping.
-**Always use PATCH without asking**, including the initial release choice;
-override `/ship`'s MINOR/MAJOR prompts. Auto-allocate past collisions, sync all
-version stamps and the PR title, then report the number. This changes numbering
+**PRs carry no version** ([releases per batch](docs/RELEASING.md#releases-per-batch)):
+/ship writes a `changelog.d` fragment, and the release PR picks the next PATCH
+(never MINOR or MAJOR) and syncs every stamp. This changes numbering
only: scope, merge, deployment, paid-work and validation approvals still apply.
## Privacy
@@ -2468,10 +2468,11 @@ checkpoint resume, or DB-contention-aware pace mode.
## Version locations (single source of truth: `VERSION` file)
-Every release updates the required version stamps in the table below.
-`bun run release:restamp` rewrites all of them, renumbers the branch's own
-schema migrations after master's and runs the auto-derived regenerations;
-run it when the PR is next to merge ([how](docs/RELEASING.md#release-restamp)).
+Every release updates the required version stamps in the table below. PRs do
+not: a PR carries a `changelog.d` fragment, and the release PR
+(`gstack-release-stamp open`, which runs `bun scripts/release-restamp.ts
+--stamp-only <version>`) rewrites every row at once
+([releases per batch](docs/RELEASING.md#releases-per-batch)).
Update TODOS only when filing new work. `/ship`'s Step 12 idempotency check
catches VERSION vs package.json drift; the canonical list lives here.
@@ -2636,8 +2637,10 @@ This applies to README, CHANGELOG, docs, PRs, commits, issues, and release pages
## PR title format — version FIRST (IRON RULE)
-PR titles and version-bump commit subjects start with the version, followed by
-the conventional-commit subject:
+A PR that carries no version (every PR under
+[releases per batch](docs/RELEASING.md#releases-per-batch)) is titled in
+plain words. Release PR titles and version-bump commit subjects start with the
+version, followed by the conventional-commit subject:
```
vMAJOR.MINOR.PATCH.MICRO <type>(<scope>): <summary> (#issue or wave ref)
diff --git a/package.json b/package.json
index 156bd6f2b1..b8a89655f5 100644
--- a/package.json
+++ b/package.json
@@ -189,6 +189,8 @@
"check:structural-manifest": "bash scripts/check-structural-manifest.sh",
"regen:all": "bun scripts/regen-all.ts",
"release:restamp": "bun scripts/release-restamp.ts",
+ "release:unstamp": "bun scripts/release-restamp.ts --unstamp",
+ "migrations:renumber": "bun scripts/release-restamp.ts --renumber",
"check:regen-all": "bun scripts/regen-all.ts --check",
"check:orphan-modules": "node scripts/check-orphan-modules.mjs",
"check:test-placeholders": "node scripts/check-test-placeholders.mjs",
diff --git a/scripts/build-behavior-changes.ts b/scripts/build-behavior-changes.ts
new file mode 100644
index 0000000000..a7b14628d3
--- /dev/null
+++ b/scripts/build-behavior-changes.ts
@@ -0,0 +1,154 @@
+#!/usr/bin/env bun
+/**
+ * Build src/core/behavior-changes.generated.ts: the BEHAVIOR_CHANGES rows a release disclosed from
+ * behavior-changes.d/, and the release of every marked id.
+ *
+ * bun scripts/build-behavior-changes.ts write the generated file
+ * bun scripts/build-behavior-changes.ts --check read-only: refuse a stale file or a broken fragment
+ *
+ * A PR that changes behavior adds behavior-changes.d/<id>.md (the notice text, one paragraph) and names the id in
+ * its changelog.d fragment as `<!-- behavior-change: <id> -->`. The release folds that fragment into the CHANGELOG
+ * under its version, so the marker's section is the row's `since`; nothing in behavior-changes.d is edited. A row
+ * whose text is a function stays in src/core/behavior-change-notice.ts as `{ since: releasedIn('<id>'), id: '<id>', ... }`
+ * with a marker, and takes its release from BEHAVIOR_CHANGE_RELEASES.
+ *
+ * Unreleased markers (changelog.d, `## [Unreleased]`) count only while a release is being stamped: VERSION is
+ * newer than the CHANGELOG's top release heading (gstack-restamp --release runs this before it folds the
+ * fragments). On every other tree they are pending and generate nothing, so a PR never changes the generated file.
+ * Dependency-free and history-free: gstack's release check reruns it in a bare worktree of the release head.
+ *
+ * Exit: 0 written or fresh, 1 stale or invalid (FAIL/Why/Fix printed), 2 usage.
+ * Docs: behavior-changes.d/README.md
+ */
+import { existsSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';
+
+export const FRAGMENT_DIR = 'behavior-changes.d';
+export const CHANGELOG_FRAGMENT_DIR = 'changelog.d';
+export const OUT = 'src/core/behavior-changes.generated.ts';
+export const NOTICE_FILE = 'src/core/behavior-change-notice.ts';
+export const MARKER = /<!--\s*behavior-change:\s*([^\s]+)\s*-->/g;
+export const ID = /^[a-z0-9][a-z0-9_]{2,95}$/;
+const NOTICE_CAP = 2_000;
+const DOCS = 'behavior-changes.d/README.md';
+
+export interface Release { version: string | null; ids: string[] }
+export interface Built { text: string; problems: string[] }
+
+const read = (root: string, rel: string) => (existsSync(join(root, rel)) ? readFileSync(join(root, rel), 'utf8') : '');
+const cmp = (a: string, b: string) => {
+ const [pa, pb] = [a, b].map(v => v.split('.').map(n => parseInt(n, 10) || 0));
+ for (let i = 0; i < Math.max(pa.length, pb.length); i++) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0) ? -1 : 1;
+ return 0;
+};
+const markers = (text: string) => [...text.matchAll(MARKER)].map(m => m[1]!);
+
+/** CHANGELOG sections oldest first: each release heading with the ids its text marks; `## [Unreleased]` has version null. */
+export function changelogReleases(changelog: string): Release[] {
+ const out: Release[] = [];
+ let cur: Release | null = null;
+ for (const line of changelog.split('\n')) {
+ const h = /^## \[([^\]]+)\]/.exec(line);
+ if (h) { cur = { version: /^unreleased$/i.test(h[1]!) ? null : h[1]!, ids: [] }; out.push(cur); continue; }
+ if (cur) cur.ids.push(...markers(line));
+ }
+ return out.reverse();
+}
+
+/** The ids the source table holds, and the ids its function rows date with releasedIn('<id>'). */
+export function tableIds(notice: string): { ids: Set<string>; tbd: Set<string> } {
+ return {
+ ids: new Set([...notice.matchAll(/\{ since: [^,]+, id: '([^']+)'/g)].map(m => m[1]!)),
+ tbd: new Set([...notice.matchAll(/\{ since: releasedIn\('([a-z0-9_]+)'\)/g)].map(m => m[1]!)),
+ };
+}
+
+export function build(root: string): Built {
+ const problems: string[] = [];
+ const version = read(root, 'VERSION').trim();
+ const releases = changelogReleases(read(root, 'CHANGELOG.md'));
+ const released = releases.filter(r => r.version);
+ const top = released.at(-1)?.version ?? null;
+ const stamping = !!version && (!top || cmp(version, top) > 0);
+ const pendingFiles = existsSync(join(root, CHANGELOG_FRAGMENT_DIR))
+ ? readdirSync(join(root, CHANGELOG_FRAGMENT_DIR)).filter(f => f.endsWith('.md') && f !== 'README.md').sort() : [];
+ const pending = [...releases.filter(r => !r.version).flatMap(r => r.ids), ...pendingFiles.flatMap(f => markers(read(root, join(CHANGELOG_FRAGMENT_DIR, f))))];
+ const sinceOf = new Map<string, string>();
+ const order: string[] = [];
+ const mark = (id: string, v: string) => {
+ if (sinceOf.has(id)) { problems.push(`${id} is marked in two releases (${sinceOf.get(id)} and ${v})`); return; }
+ sinceOf.set(id, v); order.push(id);
+ };
+ for (const r of released) for (const id of r.ids) mark(id, r.version!);
+ const pendingIds = new Set(pending);
+ if (stamping) for (const id of pending) if (!sinceOf.has(id)) mark(id, version);
+
+ const files = existsSync(join(root, FRAGMENT_DIR)) ? readdirSync(join(root, FRAGMENT_DIR)).filter(f => f !== 'README.md').sort() : [];
+ const texts = new Map<string, string>();
+ for (const f of files) {
+ const id = f.replace(/\.md$/, '');
+ if (!f.endsWith('.md') || !ID.test(id)) { problems.push(`${FRAGMENT_DIR}/${f}: a fragment is named <id>.md, the id lowercase letters, digits and _ (3-96 characters)`); continue; }
+ const text = read(root, join(FRAGMENT_DIR, f)).trim().replace(/\s*\n\s*/g, ' ');
+ if (!text) problems.push(`${FRAGMENT_DIR}/${f} is empty`);
+ else if (text.length > NOTICE_CAP) problems.push(`${FRAGMENT_DIR}/${f} is ${text.length} characters; the notice renders at most ${NOTICE_CAP}`);
+ else if (/<!--|^---/.test(text)) problems.push(`${FRAGMENT_DIR}/${f} holds markup; it is the notice text only`);
+ texts.set(id, text);
+ }
+ const table = tableIds(read(root, NOTICE_FILE));
+ for (const id of texts.keys()) {
+ if (table.ids.has(id)) problems.push(`${FRAGMENT_DIR}/${id}.md repeats the id of a row in ${NOTICE_FILE}`);
+ if (!sinceOf.has(id) && !pendingIds.has(id)) problems.push(`${FRAGMENT_DIR}/${id}.md has no <!-- behavior-change: ${id} --> marker in a changelog.d fragment or the CHANGELOG, so no release would disclose it`);
+ }
+ for (const id of [...sinceOf.keys(), ...pendingIds]) {
+ if (!texts.has(id) && !table.tbd.has(id) && !table.ids.has(id)) problems.push(`the marker <!-- behavior-change: ${id} --> names no ${FRAGMENT_DIR}/${id}.md and no function row dated releasedIn('${id}')`);
+ }
+ for (const id of table.tbd) if (!sinceOf.has(id) && !pendingIds.has(id)) problems.push(`the releasedIn('${id}') row in ${NOTICE_FILE} has no <!-- behavior-change: ${id} --> marker, so no release would date it`);
+
+ const rows = order.filter(id => texts.has(id)).map(id => ` { since: '${sinceOf.get(id)}', id: '${id}', text: ${JSON.stringify(texts.get(id))} },`);
+ const map = order.map(id => ` ${id}: '${sinceOf.get(id)}',`);
+ const text = [
+ '// Generated by scripts/build-behavior-changes.ts from behavior-changes.d/ and the CHANGELOG markers; do not edit.',
+ '// Regenerate: bun scripts/build-behavior-changes.ts (the release does it). Docs: behavior-changes.d/README.md',
+ '',
+ '/** The plain-text rows of behavior-changes.d/, each dated by the release whose CHANGELOG section marks it. */',
+ 'export const RELEASED_BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; id: string; text: string }> = [',
+ ...rows,
+ '];',
+ '',
+ '/** The release of every marked id, so a function row dated releasedIn(id) takes the release that disclosed it. */',
+ 'export const BEHAVIOR_CHANGE_RELEASES: Readonly<Record<string, string>> = {',
+ ...map,
+ '};',
+ '',
+ ].join('\n');
+ return { text, problems };
+}
+
+export function main(argv: string[], opts: { cwd?: string; log?: (line: string) => void } = {}): number {
+ const log = opts.log ?? ((l: string) => console.log(l));
+ const root = resolve(opts.cwd ?? join(import.meta.dir, '..'));
+ if (argv.some(a => a !== '--check')) { log('usage: bun scripts/build-behavior-changes.ts [--check]'); return 2; }
+ const { text, problems } = build(root);
+ if (problems.length) {
+ log(`FAIL: ${problems.length} behavior-change fragment problem(s):`);
+ for (const p of problems) log(` - ${p}`);
+ log('Why: each notice row needs its text and a marker in its PR\'s changelog.d fragment; the release dates it from the marker.');
+ log('Fix: correct the files named above, then rerun bun scripts/build-behavior-changes.ts --check');
+ log(`See: ${DOCS}`);
+ return 1;
+ }
+ const current = read(root, OUT);
+ if (argv.includes('--check')) {
+ if (current === text) { log(`build-behavior-changes: ok (${OUT} is fresh)`); return 0; }
+ log(`FAIL: ${OUT} is stale.`);
+ log('Why: it must equal what scripts/build-behavior-changes.ts generates from behavior-changes.d/ and the CHANGELOG.');
+ log('Fix: bun scripts/build-behavior-changes.ts, then commit the file');
+ log(`See: ${DOCS}`);
+ return 1;
+ }
+ if (current !== text) writeFileSync(join(root, OUT), text);
+ log(current === text ? `build-behavior-changes: ${OUT} unchanged` : `build-behavior-changes: wrote ${OUT}`);
+ return 0;
+}
+
+if (import.meta.main) process.exit(main(process.argv.slice(2)));
diff --git a/scripts/check-behavior-since.ts b/scripts/check-behavior-since.ts
index aa2d62afa8..fb71931f5e 100644
--- a/scripts/check-behavior-since.ts
+++ b/scripts/check-behavior-since.ts
@@ -18,13 +18,19 @@
* the base ref's VERSION (a stamped PR head, stamped by tool or by hand).
* Otherwise VERSION equals the base's (an unstamped branch) and TBD rows pass.
*
+ * Under .gstack/ship-policy.json `merge: direct` versions are written at release, which never edits this file, so
+ * a TBD row is refused on every tree: a plain-text row is a behavior-changes.d/<id>.md fragment and a function row
+ * is dated `since: releasedIn('<id>')` (behavior-changes.d/README.md). With --stamped (the Release workflow) the
+ * release commit must also hold no unfolded changelog.d fragment and a fresh behavior-change table.
+ *
* Base ref: $GBRAIN_RELEASE_BASE_REF, default origin/master. When it is
* unavailable the check fails under CI=true and skips locally.
* Exit: 0 ok or skipped, 1 refused, 2 usage. Docs: docs/RELEASING.md#release-restamp
*/
import { spawnSync } from 'node:child_process';
-import { existsSync, readFileSync } from 'node:fs';
+import { existsSync, readdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
+import { build, CHANGELOG_FRAGMENT_DIR, OUT } from './build-behavior-changes.ts';
export const NOTICE_FILE = 'src/core/behavior-change-notice.ts';
const TBD = /since:\s*'TBD'/;
@@ -56,7 +62,27 @@ export function main(argv: string[], opts: { cwd?: string; env?: Record<string,
log(SEE);
return 1;
}
+ const direct = (() => { try { return JSON.parse(read('.gstack/ship-policy.json') || '{}').merge === 'direct'; } catch { return false; } })();
+ if (direct && argv.includes('--stamped')) {
+ const unfolded = existsSync(join(root, CHANGELOG_FRAGMENT_DIR)) ? readdirSync(join(root, CHANGELOG_FRAGMENT_DIR)).filter((f) => f.endsWith('.md') && f !== 'README.md') : [];
+ const table = build(root);
+ const stale = table.problems.length > 0 || read(OUT) !== table.text;
+ if (unfolded.length || stale) {
+ log(`FAIL: the release commit (VERSION ${read('VERSION').trim()}) ${unfolded.length ? `still holds ${unfolded.length} unfolded ${CHANGELOG_FRAGMENT_DIR} fragment(s): ${unfolded.join(', ')}` : `has a stale ${OUT}`}${table.problems.length ? ` (${table.problems[0]})` : ''}.`);
+ log('Why: a release folds every changelog fragment into its CHANGELOG section and dates its behavior-change rows; a commit that did not is not a release.');
+ log('Fix: open the release again with gstack-release-stamp open, which stamps a fresh checkout of master; never edit a release/<version> branch by hand.');
+ log('See: docs/RELEASING.md#releases-per-batch');
+ return 1;
+ }
+ }
const lines = tbdLines(read(NOTICE_FILE));
+ if (direct && lines.length) {
+ log(`FAIL: ${lines.length} BEHAVIOR_CHANGES row(s) in ${NOTICE_FILE} say since: 'TBD' (line ${lines.join(', ')}).`);
+ log('Why: under merge: direct the release writes versions and never edits this file, so a TBD row would never be dated or disclosed.');
+ log("Fix: move a plain-text row to behavior-changes.d/<id>.md and name <!-- behavior-change: <id> --> in your changelog.d fragment; a function row keeps its line as since: releasedIn('<id>') with the same marker (bun run release:unstamp converts a branch).");
+ log('See: behavior-changes.d/README.md');
+ return 1;
+ }
if (lines.length === 0) {
log(`check-behavior-since: ok (no since: 'TBD' row in ${NOTICE_FILE})`);
return 0;
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsv
index 71d0966adc..b1721dc6ea 100644
--- a/scripts/module-size-limits.tsv
+++ b/scripts/module-size-limits.tsv
@@ -47,4 +47,4 @@ src/commands/doctor/checks/extraction-sync.ts 1500 ratchet +7 GBRA-130 A-1: link
src/core/search/evidence-delivery.ts 1759 ratchet +5 W5: EvidencePlan.rankCut resolved with the plan (logic in search/page-rank-cut.ts); +20 W5 whole_pages: wholeCost prices a block as delivery would emit it whole (needs the private Block/enrichBlock internals) and the cut is wired before allocate (cutWholePages lives in search/page-rank-cut.ts); new row: crossed the 1500 unlisted cap at the #6367 merge (master 1479, its explicit-budget cap) by the C1 date header threaded through every block path, cap included; pagePlanHits (search/page-plan-hits.ts) and the header loader (evidence-date.ts blockDateHeaders) were peeled first; peel candidate: allocateCapped; +8 at the #6396 merge: page evidence text cut through the fence-chunk trust overlay and the caller minTrust floor (re-summed: our 1504 + master +8); +119 Cat 40 next wave F2: the search.long_page_unit policy (withLongPagePolicy, selectLongPages size preflight with page/byte/deadline limits) and the long-page fetch and fallback in deliverEvidence, kept in the shared seam the plan names (gbrain-evals docs/plans/2026-10-11-cat40-next-wave, F2); +17 F2 rework to the frozen-comparison policy: search.long_page_min_chars (rendered-body characters, default 20,000) read in withLongPagePolicy, a character count in the preflight, the rendered-body confirmation in deliverEvidence, and the long-page row exemption in capDeliveredSnippets (re-summed at the 0.60.225.0 merge: master 1537 + F2 136); +39 Wave B PR 2 lane 2b: planSegmentedBlock joins the windows search/segmented-evidence.ts reads around a segmented page's hits into one run-marked document (needs the private Doc/Piece/buildDoc/locateAnchor internals), planBlock's unit cut split into blockFromDoc for both, sections bounded by their run, selectionCost counts a gap between runs, and the fetch skips the whole-body fence overlay for a segmented page; +4 segmented pages read at once before planning (segmentedReads; the read is search/segmented-evidence.ts, the statements page-body/read-range.ts); +17 GBRA-156: tail trim plan flag, DeliverOptions.query, DeliveryMeta.tail_trim, the trim call and the frozen-hit score/query library fields (logic in search/evidence-tail-trim.ts; interface fields cannot move); +7 GBRA-205: EvidencePlan.titleHeader and DeliveryMeta.title_header (interface fields cannot move) and the titles option on the header loader (logic in search/evidence-date.ts; the query budget key lives in search/evidence-packing.ts); +11 #7600: assemble_evidence quotes conversation rows and capEvidenceToBudget counts the quote fence (logic in search/transcript-quote.ts); +2 GBRA-156 /ship review: the cut-path admission and title room count the quote fence; +2 GBRA-156 /ship review pass 2: capEvidenceToBudget counts the fence only for the paths that fence (quote flag; recall counts the text as returned); +4 GST-687: page evidence and the extractive fallback quote below-owner-tier text for untrusted readers (untrusted flag; logic in search/transcript-quote.ts)
src/commands/config.ts 1526 ratchet +1 GBRA-216: recall.* config set value refusal (facts/recall-config.ts); +1 GBRA-216: config set refuses a dream.claim_conflicts.mode other than propose|off (refusal in facts/claim-conflicts.ts); new row: crossed the 1500 unlisted cap in wave 15 P7.4 #5461: set-time validation of think.pages_budget_chars / think.excerpt_ceiling_chars (range + parser live in core/think/pages-budget.ts), mirroring the cycle.consolidate.cluster_threshold hook; +1 wave 16 G5.1 (#6495): set-time refusal hook for search.keyword_statement_timeout_ms (check lives in commands/config/keyword-timeout-value.ts); +1 wave 18b lane 5 (#5012 item 6): search.contextual_retrieval prints the existing-pages hint after the write (text lives in commands/config/contextual-mode-hint.ts); +1 #6712 PR 2: retired/rollback sync key dispatch line (logic in core/sync-config-keys.ts handleSyncKeyConfig); +1 #6865: sync.slug_conflicts.auto_remove boolean validation at set time (refusal text in repair/slug-autoheal.ts); +1 #6948: sync.origin_twins.auto_resolve boolean validation at set time (refusal text in repair/origin-twins-heal.ts); +2 #6795: config set chat_model/expansion_model help line and the model-pin import (shadow report and file-pin unset live in commands/config/model-pin-shadow.ts); +1 #6712 PR 4b: sync.admission set-time hook (value logic in commands/config/sync-admission-value.ts); +4 #7130: set-time refusal hook for sync.max_deletes / sync.max_delete_ratio (and .source.<id>) / purge.retention_hours (check lives in core/sync-reconcile.ts deleteSafetyConfigRefusal); +1 GBRA-150: sync.metafile_pages set-time route (body in config/sync-metafile-pages-value.ts); re-summed at the v0.60.330.0 merge (1520 measured); +2 #7242 minions.terminal_hook file-plane key and its set branch (logic in minions/terminal-hook.ts); +1 GBRA-161: generations.* set-time route (refusal in commands/config/generations-values.ts); +1 GBRA-207 #7630: sync.repo_path set-time refusal hook (refusal in core/sync-config-keys.ts syncRepoPathRefusal)
src/commands/mcp-expose.ts 1519 ratchet hosted_option: Session carries the gbrain.io coaching notice on the first-receipt run and Tailscale/service friction exits (copy, refs and gating live in core/onboard/hosted-option.ts); +7 GBRA-199: --surface help lines, surfaceChosen option field and the advertise pass-through (registrationAdvertise in core/mcp-registration.ts)
-src/core/behavior-change-notice.ts 1692 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1)
+src/core/behavior-change-notice.ts 1701 ratchet +4 train R: #7491/#7492 keyword_identifier_probe and keyword_slug_handles rows and their comment, #7175 keyword phrase row; the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +1 GBRA-156 #7593: private_pages_granted_sources row (re-summed at the 0.60.527.0 merge: 1574 + 1); +3 GBRA-200 comment, write-grant refusal and degraded-stamp rows (re-summed at the 0.60.562.0 merge: 1615 + 3); +2 GBRA-280 get_page selector-precedence row and comment (re-summed at the 0.60.569.0 merge: 1619 + 2); the BEHAVIOR_CHANGES table grows by one row per disclosed change: +4 the #7891 provenance-drift and #7917/#7918 maintenance-lowering rows and their comments (re-summed at the 0.60.495.0 merge: 1547 + 4); +2 GBRA-205 saved_facts_stems row and its comment (re-summed at the #7901 0.60.492.0 merge: 1541 + 2); +2 GBRA-205 search.query_facts_block default-on row and its approval comment (re-summed at the #7610 0.60.490.0 merge: 1539 + 2); +2 the #7900 content checkpoint host-move row (since TBD until the merge slot), +2 the #7897 private-hold sweep row (since TBD until the merge slot), +2 the #7880 ingest_capture and company-brain private-hold row (since TBD until the merge slot), +5 the frozen-source wave comment and four rows (#7868, #7850, #7869/#7870, #7871), +2 the #7848 visibility_noncanonical hold row (since TBD until the merge slot), +2 the #7846 extract_atoms session-source row (re-summed at the 0.60.481.0 merge: master 1524 + 2), +2 the #7805 synthesize session-source and #7841 visibility_not_applied rows (re-summed at the 0.60.480.0 merge: master 1522 + 2), +2 strict door planned-state row (#7705, re-summed at the 0.60.470.0 merge: master 1514 + 2), +2 Bun floor 1.4.4 row (#7644), the GBRA-95 RLS backfill row (+2), +3 rows for #7596 pass_interrupted, #7599 read-only serve and the --access=read-only ceiling, +1 G5 lane C trust_release row, +1 #7619 cli_flag_equals, +3 GBRA-207 #7630 relative-anchor and stalled-write rows, +2 the #7632 function search_path disclosure row and +2 the #7679 orphaned worktree refresh row (re-summed at the 0.60.471.0 merge: master 1516 + 2), +2 the #7814 retired v0.13.1 grandfather row, +2 the #7618 conversion withhold/progress/push row (master 1520 + 2); the behavior-change table split (#7607) retires this row; +4 GBRA-188 #7489: the wave comment and three rows (brain-first instructions, starter surface default, per-turn rule); +1 GBRA-188 plugin_turn_hook_gbra188 row; +1 GBRA-242 provider_key_rules_7959 row (#7959), +2 the GBRA-199 registration_lists_verbs row (since TBD until the merge slot); +2 GBRA-133 #7652: the #7611 pass_abandoned reader row and the lean read-only serve socket row (re-summed at the 0.60.503.0 merge: master 1555 + 2); +1 GBRA-243: the per-turn hook disclosure row (rows are data and cannot move); +4 GBRA-156 #7598 harness wave comment and rows (remote page cap, sources_not_readable refusal, sources add next step); +4 GBRA-156 #7601 search_quotes_transcript_rows comment and row; +1 GBRA-175 #7475 autopilot_restarts_serve_7475 row (re-summed at the #8012 merge: 1566 + 1); +3 #7997/#8014/#8015 rows (redaction markers, company db_only keep, ignored supabase_only scope); +2 #7199 (re-port of #7228) classic_drift_rescreen_7199 comment and row; +2 #7931 file_drift_agrees_7931 comment and row; +1 #7950 file_drift_slug_release_7950 row; +1 #7974 file_drift_followups_7974 row; +1 #8059 quoted_fence_marker_8059 row; +2 GBRA-247 #8009 provenance_repair_held_8009 and #7982 pass_transient_streak_7982 rows; +4 GBRA-247 #7973 plain_directory_sync_7973, #7988 managed_marker_own_directory_7988, #7985 former_binding_parked_group_7985 and settle_effects_retire_7985 rows Train S merge: 1570 base + 5 (master since the #8077 base) + 13 (#8077) = 1588.; +2 GST-687 remote_quotes_unverified_text_gst687 row and its comment (re-summed at the gate-ahead on train S 0.60.534.0: 1588 + 2); +2 #8377: the quote fence follow-ups row and its comment; +2 #8384: the quote fence follow-ups 2 row and its comment; +2 #8384 wave 3: the quote fence follow-ups 3 row and its comment; +5 GBRA-218 train M rows (A1 member_read_access_gbra218 and member_access_hatch_scope_gbra218, B shared_agent_audience_gbra231, A2 folder_access_rules_gbra218, folder_access_scoped_role_gbra218), re-summed at the train M merge of master v0.60.541.0: 1596 + 5 = 1601 measured; +3 GST-359 train C rows (C1 qm_attested_actor_gst359, C2 member_facts_gst359, D qm_memory_provider_gst359), re-summed at the train C merge of master v0.60.543.0: 1601 + 3 = 1604 measured; +2 #8424: hook_launcher_8424 row and its comment (rows are data and cannot move), re-summed at the #8418 v0.60.546.0 merge: 1604 + 2 = 1606 measured; +2 #8426: mcp_lane_launcher_8426 row and its comment (rows are data and cannot move); +2 GST-927: empty_nonstring_args_gst927 row and its comment, re-summed at the gate-ahead on master v0.60.550.0 plus #8420: 1610 measured; +2 GBRA-283 Wave A (#8460): engine_keyed_caches_gbra283 row and its comment (rows are data and cannot move); +2 GBRA-287: segmented_freeze_hold_gbra287 and segmented_reexport_gbra287 rows (rows are data and cannot move); +1 GST-1209: segmented_tiling_gst1209 row (rows are data and cannot move); +1 GST-1251: skillopt_loop_deprecated_gst1251 row (rows are data and cannot move); +1 GST-1209 follow-up: untiled_hold_repair_gst1209 row (rows are data and cannot move); +1 GBRA-283 B3a: embedded_scope_required_gbra283 row (rows are data and cannot move); re-summed at the train R merge with v0.60.574.0: 1623 + 4; +2 GST-1387: refresh_fence_refusal_gst1387 row and its comment (rows are data and cannot move); re-summed at the memory train #8481 merge with v0.60.578.0 (1643 measured); +3 GBRA-253 #8109 rows (frontmatter_drift_write_8109, contacts_activity_advance_8109, contact_rows_dedupe_8109; rows are data and cannot move), re-summed at the master v0.60.581.0 merge: 1643 + 3 = 1646 measured; +3 #8123 part C rows: sync_write_through_off_writeback_7084, managed_sync_dry_run_counts_7087, frontmatter_missing_source_dir_7889 (since TBD until the merge slot; re-summed at the 0.60.583.0 merge: 1646 + 3); +4 PR B commit_ledger_prb, doctor_foreign_writers_prb and sources_guard_prb rows and their comment (rows are data and cannot move; since TBD until the merge slot); +1 PR B #8615: file_drift_held_needs_prefer_8615 row; +1 PR B #8617: refresh_source_changed_retry_8617 row; +1 PR B #8662: commit_push_checkout_not_a_source_8662 row (since TBD until the merge slot; rows are data and cannot move); +2 PR B refresh_barrier_prb and commit_push_base_prb rows (re-summed: 1658 measured); +3 convergence PR A: the wave comment and two rows (conversion_content_evidence_pr_a, git_gap_live_pages_pr_a; since TBD until the merge slot; rows are data and cannot move); re-summed at the gate-ahead on master v0.60.592.0 plus #8711: 1658 + 3 = 1661 measured; +4 GST-1094/GST-900 rows (memory_recall scope-read, member-bound acting_user, recall max_chars, unknown_param _meta-only) and +1 qm_scope_writes_gst1113 and +1 recall_question_terms_gst1304 rows (rows are data and cannot move), re-summed at the 0.60.595.0 slot merge: 1661 + 6; +1 GST-1582 refresh_barrier_import_gst1582 row (since TBD until the merge slot; rows are data and cannot move); +2 GST-1601 source_changed_origin_gst1601 and adopt_local_edits_gst1601 rows (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.596.0 merge: 1668 + 2; +1 GST-1623 refresh_barrier_capacity_gst1623 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.599.0 merge: 1670 + 1; +2 GBRA-224 W1 release_channel_stable_default row and its comment; +1 GST-1623 refresh_barrier_later_write_gst1623 row (#8765; rows are data and cannot move); +5 #8766 GST-1623 items 4/6-9 and #8755: the wave comment and four rows (doctor_foreign_writers_partial_gst1623, commit_push_enclosing_repo_gst1623, owner_guard_fail_closed_gst1623, adopt_local_edits_hardening_8755) and +1 managed_sync_kind_reserved_8765 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on master v0.60.608.0 plus #8798: 1674 + 6; +1 GST-1853 refresh_barrier_aborted_refresh_sync_gst1853 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.613.0 merge: 1680 + 1; +1 GST-1674 refresh_refused_merge_recovery_gst1674 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the master v0.60.614.0 merge: 1681 + 1; +1 #8824/#8826/#8767: adopt_local_edits_replay_markers_8824 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8837: 1682 + 1; +1 url_source_origin row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8834: 1683 + 1; +1 #8828: the refresh_replan_own_commits_8828 row (1684 + 1 at the 0.60.618.0 slot); +1 the managed commit-push unpublished-count row; +1 the refresh publish-diverged default row; +1 GST-2051 ungranted_member_writes_gst2051 row (since TBD until the merge slot; rows are data and cannot move); +1 GST-731 think_window_trajectory_gst731 row and +1 GST-1602 purge_cancels_deferred_write_gst1602 row (since TBD until the merge slot; rows are data and cannot move), re-summed at the gate-ahead on #8915 v0.60.621.0: 1688 + 2; +1 GST-2059: owner_reads_private row; +1 #8888: the record-origin checkout lock-down row (re-summed at the Q6 stack on #8934 v0.60.625.0: 1691 + 1); +9 releases per batch: the generated-table import, the releasedIn helper and its comment, the spread of RELEASED_BEHAVIOR_CHANGES; new rows now live in behavior-changes.d/ and stop growing this file
diff --git a/scripts/regen-all.ts b/scripts/regen-all.ts
index feafc1cd88..8214adda44 100644
--- a/scripts/regen-all.ts
+++ b/scripts/regen-all.ts
@@ -39,6 +39,7 @@ const BUN_TEST = ['bun', 'test', '--timeout=60000'];
export const ARTIFACTS: Artifact[] = [
{ name: 'schema (src/schema-embedded)', regen: ['bun', 'run', 'scripts/build-schema.ts'], check: ['bash', 'scripts/check-schema-fresh.sh'] },
{ name: 'schema migrations bundle', regen: ['bun', 'run', 'scripts/build-schema-migrations.ts'], check: ['bash', 'scripts/check-schema-migrations-fresh.sh'] },
+ { name: 'behavior-change table (behavior-changes.d)', regen: ['bun', 'scripts/build-behavior-changes.ts'], check: ['bun', 'scripts/build-behavior-changes.ts', '--check'] },
{ name: 'error-code registry docs', regen: ['bun', 'scripts/build-error-codes.ts'], check: ['bun', 'scripts/build-error-codes.ts', '--check'] },
{ name: 'agent operator protocol blocks', regen: ['bun', 'scripts/build-agent-protocol.ts'], check: ['bun', 'scripts/build-agent-protocol.ts', '--check'] },
{ name: 'lookup table copies', regen: ['bun', 'scripts/build-lookup-table.ts'], check: ['bun', 'scripts/build-lookup-table.ts', '--check'] },
diff --git a/scripts/release-gate.ts b/scripts/release-gate.ts
index 83a819677a..29cce07c23 100644
--- a/scripts/release-gate.ts
+++ b/scripts/release-gate.ts
@@ -12,11 +12,11 @@
* - both green: publish that SHA;
* - either failed (failure, timed out, startup failure): no publish; the
* job fails naming the run, the master-red issue and the next command;
- * - either cancelled by a newer push: follow the next push-to-master run of
- * that workflow. When its commit contains the release SHA and carries the
- * same VERSION, the gate re-evaluates both workflows there and publishes
- * that commit; when VERSION moved on, this version is superseded (the
- * newer VERSION's own release run publishes; exit 0, publish=false);
+ * - either cancelled or skipped: no publish; the job fails naming the re-run.
+ * Master push runs are keyed by commit (test.yml, e2e.yml concurrency), so
+ * a newer push never cancels them, and under releases per batch a later
+ * master commit with the same VERSION may carry unreleased changes, so the
+ * gate never publishes another commit in the release commit's place;
* - still running, or not created yet: wait, up to --timeout-minutes, then
* fail with the dispatch backfill command.
*
@@ -32,7 +32,7 @@
* `test_reused_run_id` / `e2e_reused_run_id` (empty when the push ran in
* full). A reused job whose record is missing or names another workflow or
* commit publishes nothing.
- * Exit 0 publish or superseded, 1 no publish (failed, timed out, not master),
+ * Exit 0 publish, 1 no publish (failed, timed out, not master),
* 2 usage. Docs: docs/RELEASING.md#release-ci-gate
*/
import { appendFileSync } from 'node:fs';
@@ -42,7 +42,6 @@ import { fetchArtifactJson, restClient, type GitHubClient } from './lib/gh-issue
export const GATED = [{ file: 'test.yml', name: 'Test', key: 'test' }, { file: 'e2e.yml', name: 'E2E Tests', key: 'e2e' }] as const;
export const DOCS = 'docs/RELEASING.md#release-ci-gate';
const RED = new Set(['failure', 'timed_out', 'startup_failure', 'action_required']);
-const MAX_HOPS = 10;
export interface GateRun { id: number; run_number: number; run_attempt: number; status: string; conclusion: string | null; head_sha: string; head_branch: string; event: string; html_url?: string }
export interface ReusedRun { run_id: number; run_attempt: number; sha: string }
@@ -51,15 +50,11 @@ export type Provenance = { reused: false } | ({ reused: true } & ReusedRun) | {
export interface Source { workflow: string; key: string; run_id: number; reused?: ReusedRun }
export type Verdict =
| { kind: 'publish'; sha: string; why: string; sources: Source[] }
- | { kind: 'superseded'; sha: string; why: string }
| { kind: 'wait'; sha: string; why: string }
| { kind: 'fail'; sha: string; why: string; next: string };
export interface GateDeps {
runsFor(file: string, sha: string): Promise<GateRun[]>;
- newerRuns(file: string, after: number): Promise<GateRun[]>;
- versionAt(sha: string): Promise<string>;
- contains(base: string, head: string): Promise<boolean>;
provenance(file: string, run: GateRun): Promise<Provenance>;
}
@@ -67,45 +62,37 @@ const newest = (runs: GateRun[]) => [...runs].sort((a, b) => b.run_number - a.ru
/** One evaluation of the gate for a release SHA (pure over its dependencies). */
export async function evaluate(deps: GateDeps, sha: string, version: string): Promise<Verdict> {
- let candidate = sha;
- for (let hop = 0; hop < MAX_HOPS; hop++) {
- const runs = await Promise.all(GATED.map(async wf => ({ wf, run: newest((await deps.runsFor(wf.file, candidate)).filter(r => r.event === 'push' && r.head_branch === 'master')) })));
- const failed = runs.find(r => r.run && r.run.status === 'completed' && RED.has(r.run.conclusion ?? ''));
- if (failed) {
- return {
- kind: 'fail', sha: candidate,
- why: `${failed.wf.name} run ${failed.run!.id} (${failed.run!.html_url ?? `run ${failed.run!.run_number}`}) ended ${failed.run!.conclusion} on ${candidate.slice(0, 12)}, so v${version} is not published and latest-stable does not move. Releases publish only commits master CI passed.`,
- next: `Repair master (the open "Master red: ${failed.wf.name}" issue names the failing tests; docs/RELEASING.md#master-red-issues). Once a later push-to-master run of Test and E2E Tests is green, publish the current VERSION with: gh workflow run release.yml --ref master`,
- };
- }
- const cancelled = runs.find(r => r.run && r.run.status === 'completed' && (r.run.conclusion === 'cancelled' || r.run.conclusion === 'skipped'));
- if (cancelled) {
- const successor = (await deps.newerRuns(cancelled.wf.file, cancelled.run!.run_number))
- .filter(r => r.event === 'push' && r.head_branch === 'master' && r.head_sha !== candidate)
- .sort((a, b) => a.run_number - b.run_number)[0];
- if (!successor) return { kind: 'wait', sha: candidate, why: `${cancelled.wf.name} run ${cancelled.run!.id} was cancelled (superseded by a newer push); waiting for the newer push-to-master run` };
- const [moved, inside] = [await deps.versionAt(successor.head_sha), await deps.contains(sha, successor.head_sha)];
- if (!inside) return { kind: 'fail', sha: candidate, why: `${cancelled.wf.name} on ${candidate.slice(0, 12)} was cancelled and the next master run (${successor.head_sha.slice(0, 12)}) does not contain the release commit`, next: 'Re-run the gate after master settles: gh workflow run release.yml --ref master' };
- if (moved !== version) return { kind: 'superseded', sha: successor.head_sha, why: `${cancelled.wf.name} on ${candidate.slice(0, 12)} was cancelled by a newer push that carries VERSION ${moved}; v${version} is superseded and v${moved}'s own release run publishes` };
- candidate = successor.head_sha;
- continue;
- }
- const pending = runs.filter(r => !r.run || r.run.status !== 'completed');
- if (pending.length) return { kind: 'wait', sha: candidate, why: pending.map(r => `${r.wf.name} ${r.run ? `run ${r.run.id} is ${r.run.status}` : 'has no push run yet'} on ${candidate.slice(0, 12)}`).join('; ') };
- const proven = await Promise.all(runs.map(async r => ({ wf: r.wf, run: r.run!, prov: await deps.provenance(r.wf.file, r.run!) })));
- const unproven = proven.find(p => 'problem' in p.prov);
- if (unproven && 'problem' in unproven.prov) {
- return {
- kind: 'fail', sha: candidate,
- why: `${unproven.wf.name} run ${unproven.run.id} reused an earlier full-suite run on ${candidate.slice(0, 12)}, but its reuse record cannot name that run (${unproven.prov.problem}), so v${version} is not published. A release names the run that proved its tree.`,
- next: `Re-run that push run (gh run rerun ${unproven.run.id}); it decides reuse again and records it, or runs the full suite. Once it is green: gh workflow run release.yml --ref master`,
- };
- }
- const sources: Source[] = proven.map(p => ({ workflow: p.wf.name, key: p.wf.key, run_id: p.run.id, ...('run_id' in p.prov ? { reused: { run_id: p.prov.run_id, run_attempt: p.prov.run_attempt, sha: p.prov.sha } } : {}) }));
- const how = sources.map(s => s.reused ? `${s.workflow} reused full-suite run ${s.reused.run_id} attempt ${s.reused.run_attempt} (pull request head ${s.reused.sha.slice(0, 12)}, identical tree)` : `${s.workflow} ran in full in run ${s.run_id}`).join('; ');
- return { kind: 'publish', sha: candidate, sources, why: `Test and E2E Tests both succeeded on ${candidate.slice(0, 12)}${candidate === sha ? '' : ` (the newer master commit that replaced the cancelled runs of ${sha.slice(0, 12)}; same VERSION)`}: ${how}` };
+ const runs = await Promise.all(GATED.map(async wf => ({ wf, run: newest((await deps.runsFor(wf.file, sha)).filter(r => r.event === 'push' && r.head_branch === 'master')) })));
+ const failed = runs.find(r => r.run && r.run.status === 'completed' && RED.has(r.run.conclusion ?? ''));
+ if (failed) {
+ return {
+ kind: 'fail', sha,
+ why: `${failed.wf.name} run ${failed.run!.id} (${failed.run!.html_url ?? `run ${failed.run!.run_number}`}) ended ${failed.run!.conclusion} on ${sha.slice(0, 12)}, so v${version} is not published and latest-stable does not move. Releases publish only commits master CI passed.`,
+ next: `Repair master (the open "Master red: ${failed.wf.name}" issue names the failing tests; docs/RELEASING.md#master-red-issues). Once a later push-to-master run of Test and E2E Tests is green, publish the current VERSION with: gh workflow run release.yml --ref master`,
+ };
+ }
+ const cancelled = runs.find(r => r.run && r.run.status === 'completed' && (r.run.conclusion === 'cancelled' || r.run.conclusion === 'skipped'));
+ if (cancelled) {
+ return {
+ kind: 'fail', sha,
+ why: `${cancelled.wf.name} run ${cancelled.run!.id} on ${sha.slice(0, 12)} ended ${cancelled.run!.conclusion}, so v${version} is not published. Master push runs are keyed by commit, so a newer push never cancels them, and a later master commit may carry unreleased changes under the same VERSION, so the gate never publishes one in its place.`,
+ next: `Re-run it (gh run rerun ${cancelled.run!.id}); once Test and E2E Tests are green on ${sha.slice(0, 12)}: gh workflow run release.yml --ref master`,
+ };
+ }
+ const pending = runs.filter(r => !r.run || r.run.status !== 'completed');
+ if (pending.length) return { kind: 'wait', sha, why: pending.map(r => `${r.wf.name} ${r.run ? `run ${r.run.id} is ${r.run.status}` : 'has no push run yet'} on ${sha.slice(0, 12)}`).join('; ') };
+ const proven = await Promise.all(runs.map(async r => ({ wf: r.wf, run: r.run!, prov: await deps.provenance(r.wf.file, r.run!) })));
+ const unproven = proven.find(p => 'problem' in p.prov);
+ if (unproven && 'problem' in unproven.prov) {
+ return {
+ kind: 'fail', sha,
+ why: `${unproven.wf.name} run ${unproven.run.id} reused an earlier full-suite run on ${sha.slice(0, 12)}, but its reuse record cannot name that run (${unproven.prov.problem}), so v${version} is not published. A release names the run that proved its tree.`,
+ next: `Re-run that push run (gh run rerun ${unproven.run.id}); it decides reuse again and records it, or runs the full suite. Once it is green: gh workflow run release.yml --ref master`,
+ };
}
- return { kind: 'fail', sha: candidate, why: `followed ${MAX_HOPS} cancelled runs without a completed one`, next: 'Wait for master to settle, then: gh workflow run release.yml --ref master' };
+ const sources: Source[] = proven.map(p => ({ workflow: p.wf.name, key: p.wf.key, run_id: p.run.id, ...('run_id' in p.prov ? { reused: { run_id: p.prov.run_id, run_attempt: p.prov.run_attempt, sha: p.prov.sha } } : {}) }));
+ const how = sources.map(s => s.reused ? `${s.workflow} reused full-suite run ${s.reused.run_id} attempt ${s.reused.run_attempt} (pull request head ${s.reused.sha.slice(0, 12)}, identical tree)` : `${s.workflow} ran in full in run ${s.run_id}`).join('; ');
+ return { kind: 'publish', sha, sources, why: `Test and E2E Tests both succeeded on ${sha.slice(0, 12)}: ${how}` };
}
export function apiDeps(client: GitHubClient): GateDeps {
@@ -113,18 +100,6 @@ export function apiDeps(client: GitHubClient): GateDeps {
async runsFor(file, sha) {
return (await client.request<{ workflow_runs: GateRun[] }>('GET', `repos/{repo}/actions/workflows/${file}/runs?head_sha=${sha}&event=push&per_page=20`)).workflow_runs;
},
- async newerRuns(file, after) {
- return (await client.request<{ workflow_runs: GateRun[] }>('GET', `repos/{repo}/actions/workflows/${file}/runs?event=push&branch=master&per_page=30`)).workflow_runs.filter(r => r.run_number > after);
- },
- async versionAt(sha) {
- const file = await client.request<{ content: string }>('GET', `repos/{repo}/contents/VERSION?ref=${sha}`);
- return Buffer.from(file.content, 'base64').toString('utf8').trim();
- },
- async contains(base, head) {
- if (base === head) return true;
- const cmp = await client.request<{ status: string }>('GET', `repos/{repo}/compare/${base}...${head}`);
- return cmp.status === 'ahead' || cmp.status === 'identical';
- },
async provenance(file, run) {
const name = GATED.find(g => g.file === file)?.name ?? file;
const marker = (await attemptJobs(client, run.id, run.run_attempt)).filter(j => j.name === REUSE_JOB);
@@ -183,9 +158,6 @@ if (import.meta.main) {
console.log(`[release-gate] publish v${version} at ${v.sha}: ${v.why}.`);
write(true, v.sha);
if (output) appendFileSync(output, reuseOutputs(v.sources));
- } else if (v.kind === 'superseded') {
- console.log(`::notice::Release v${version} skipped: ${v.why}. Nothing to do. Docs: ${DOCS}`);
- write(false, v.sha);
} else {
console.log(`::error::Release v${version} not published: ${v.kind === 'fail' ? v.why : 'gate ended while waiting'}. Next: ${v.kind === 'fail' ? v.next : 'gh workflow run release.yml --ref master'}. Docs: ${DOCS}`);
write(false, v.sha);
diff --git a/scripts/release-restamp.ts b/scripts/release-restamp.ts
index 00b5242bb6..8df91f6277 100644
--- a/scripts/release-restamp.ts
+++ b/scripts/release-restamp.ts
@@ -9,6 +9,16 @@
* bun run release:restamp --continue --accept-references
* resume and keep the listed reference lines as written
* bun run release:restamp --abort return the branch to its pre-run commit
+ * bun run release:unstamp under merge: direct, convert a stamped branch: merge origin/master, put every
+ * version stamp back to master's, move the branch's CHANGELOG entry to
+ * changelog.d/<branch-slug>.md and its plain-text BEHAVIOR_CHANGES rows to
+ * behavior-changes.d/, renumber its migrations, commit once
+ * bun run migrations:renumber merge origin/master and renumber this branch's own schema migrations
+ * after master's latest; no version stamp
+ * bun scripts/release-restamp.ts --stamp-only <version>
+ * the release stamp (.gstack/ship-policy.json restamp_command): write <version>
+ * into every stamp in the working tree and nothing else; no fetch, merge,
+ * generator or commit
*
* Steps: refuse a dirty tree; fetch origin/master; capture the branch's
* CHANGELOG entry and migration inventory; merge origin/master with a merge
@@ -32,7 +42,7 @@
* Exit: 0 done (or nothing to change), 1 stopped (FAIL/Why/Fix/See printed), 2 usage.
* Docs: docs/RELEASING.md#release-restamp
*/
-import { existsSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import {
BEHAVIOR_NOTICE_FILE, COLLISION_DOCS, MIGRATION_FILE_RE, MIGRATIONS_DIR, RESTAMP_DOCS, RestampError, STAMPS,
@@ -41,10 +51,12 @@ import {
type BranchMigration, type ChangelogSection, type LeftoverRef, type Renumber,
} from './lib/restamp.ts';
import { offlineEnv } from './regen-all.ts';
+import { CHANGELOG_FRAGMENT_DIR, FRAGMENT_DIR } from './build-behavior-changes.ts';
interface Step { name: string; argv: string[]; env?: Record<string, string>; migrationsOnly?: boolean }
const USAGE = `Usage: bun run release:restamp [--dry-run] [--no-commit] [--continue [--accept-references] | --abort] [--remote <name>] [--base <branch>]
+ bun scripts/release-restamp.ts --stamp-only <version>
Merges origin/master with a merge commit, sets VERSION to master's MAJOR.MINOR.(PATCH+1).0,
renumbers this branch's own schema migrations after master's latest, rewrites every required
@@ -76,7 +88,30 @@ export const DEFAULT_CHECKS: Step[] = [
{ name: 'CHANGELOG keeps every master release heading', argv: ['bun', 'scripts/check-changelog-headings.ts'] },
];
+type Mode = 'restamp' | 'unstamp' | 'renumber';
+
+/** What release:unstamp leaves true: versions back to master's, every fragment valid, no TBD row. */
+export const UNSTAMP_CHECKS: Step[] = [
+ { name: 'bootstrap runbook stamp', argv: ['bash', 'scripts/check-bootstrap-tag.sh'] },
+ { name: 'plugin tree drift', argv: ['bash', 'scripts/check-plugin-tree.sh'] },
+ { name: 'bootstrap template drift', argv: ['bash', 'scripts/check-bootstrap-templates.sh'] },
+ { name: 'behavior-change fragments', argv: ['bun', 'scripts/build-behavior-changes.ts', '--check'] },
+ { name: "no since: 'TBD' BEHAVIOR_CHANGES row", argv: ['bun', 'scripts/check-behavior-since.ts'] },
+ { name: 'CHANGELOG keeps every master release heading', argv: ['bun', 'scripts/check-changelog-headings.ts'] },
+];
+
+export const RENUMBER_CHECKS: Step[] = [
+ { name: 'schema migration registry fresh', argv: ['bash', 'scripts/check-schema-migrations-fresh.sh'] },
+ { name: 'schema migration order', argv: ['bun', 'scripts/check-schema-migration-order.ts'] },
+];
+
+/** gstack's changelog fragment name for a branch (lib/changelog-fragments.ts fragmentSlug). */
+export const fragmentSlug = (branch: string): string =>
+ branch.replace(/[\\/]+/g, '-').replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-.]+|[-.]+$/g, '').slice(0, 100) || 'change';
+
interface State {
+ mode?: Mode;
+ rows?: Array<{ id: string; text: string }>;
phase: 'merge' | 'merge-conflict' | 'restamp';
preHead: string;
masterRef: string;
@@ -237,18 +272,74 @@ function prTitle(ctx: Ctx, version: string): string {
return `v${version} ${current.replace(/^v?\d+\.\d+\.\d+(?:\.\d+)?(?:-\S+)?\s+/, '')}`;
}
-function capture(ctx: Ctx, masterRef: string): State {
+const SIZE_LIMITS = 'scripts/module-size-limits.tsv';
+const limitLine = (text: string) => text.split('\n').find((l) => l.startsWith(`${BEHAVIOR_NOTICE_FILE}\t`));
+const ROW_DUMP = `import { BEHAVIOR_CHANGES } from './${BEHAVIOR_NOTICE_FILE}';
+console.log(JSON.stringify(BEHAVIOR_CHANGES.map((r) => ({ id: r.id ?? null, text: typeof r.text === 'string' ? r.text : null }))));`;
+
+/**
+ * The BEHAVIOR_CHANGES rows this branch appended (ids its merge base does not hold), read from the evaluated table at
+ * HEAD. release:unstamp moves them to behavior-changes.d/, so it refuses a branch whose notice-file diff is anything
+ * but appended table lines, a row without an id, and a row whose text is a function (convert that one by hand).
+ */
+function branchNoticeRows(ctx: Ctx, masterRef: string, mergeBase: string): Array<{ id: string; text: string }> {
+ const added = addedLines(ctx, mergeBase, ['HEAD', '--', BEHAVIOR_NOTICE_FILE]);
+ if (added.length === 0) return [];
+ const why = 'release:unstamp moves appended plain-text rows to behavior-changes.d/; anything else in the notice file is a product edit to make by hand.';
+ const how = ['move each row to behavior-changes.d/<id>.md and name <!-- behavior-change: <id> --> in changelog.d/<slug>.md (behavior-changes.d/README.md), commit,', 'then rerun: bun run release:unstamp'];
+ const removed = ctx.git('diff', '--numstat', '--no-renames', mergeBase, 'HEAD', '--', BEHAVIOR_NOTICE_FILE).trim().split('\t')[1];
+ const head = ctx.git('show', `HEAD:${BEHAVIOR_NOTICE_FILE}`).split('\n');
+ const open = head.findIndex((l) => l.startsWith('export const BEHAVIOR_CHANGES')) + 1;
+ const close = head.findIndex((l, i) => i >= open && l === '];') + 1;
+ const outside = added.filter((l) => l.line <= open || l.line >= close);
+ if (removed !== '0' || outside.length > 0) fail(`this branch changes ${BEHAVIOR_NOTICE_FILE} beyond appending BEHAVIOR_CHANGES rows${outside.length ? ` (line ${outside.slice(0, 5).map((l) => l.line).join(', ')})` : ''}`, why, how);
+ const noId = added.filter((l) => /\{ since:/.test(l.text) && !/\bid: '/.test(l.text));
+ if (noId.length > 0) fail(`${noId.length} BEHAVIOR_CHANGES row(s) this branch added have no id (line ${noId.map((l) => l.line).join(', ')})`, 'a moved row is named behavior-changes.d/<id>.md and dated by its id.', 'give each row an id (lowercase letters, digits and _), commit, then rerun: bun run release:unstamp');
+ const r = ctx.run(['bun', '-e', ROW_DUMP]);
+ const rows = (() => { try { return JSON.parse(r.out.trim().split('\n').at(-1) ?? '') as Array<{ id: string | null; text: string | null }>; } catch { return null; } })();
+ if (r.code !== 0 || !rows) fail(`could not read the BEHAVIOR_CHANGES table at HEAD (exit ${r.code}): ${r.out.trim().split('\n').slice(-3).join(' ')}`, 'release:unstamp reads each appended row\'s text from the evaluated table.', 'fix the table so bun can import it, then rerun: bun run release:unstamp');
+ const ids = (text: string) => new Set([...text.matchAll(/\bid: '([^']+)'/g)].map((m) => m[1]!));
+ const baseIds = ids(ctx.git('show', `${mergeBase}:${BEHAVIOR_NOTICE_FILE}`));
+ const mine = rows.filter((row): row is { id: string; text: string | null } => !!row.id && !baseIds.has(row.id));
+ const fn = mine.filter((row) => row.text === null).map((row) => row.id);
+ if (fn.length > 0) fail(`${fn.length} appended row(s) compute their text (${fn.join(', ')})`, 'a function row stays in the table, dated since: releasedIn(\'<id>\'), which release:unstamp does not write for you.', ["change each to { since: releasedIn('<id>'), id: '<id>', ... }, name <!-- behavior-change: <id> --> in changelog.d/<slug>.md, commit,", 'then rerun: bun run release:unstamp']);
+ const taken = [...ids(ctx.git('show', `${masterRef}:${BEHAVIOR_NOTICE_FILE}`))].filter((id) => mine.some((row) => row.id === id));
+ const files = ctx.git('ls-tree', '--name-only', `${masterRef}`, '--', `${FRAGMENT_DIR}/`).split('\n').map((f) => f.replace(/^.*\//, '').replace(/\.md$/, ''));
+ const dup = [...taken, ...mine.filter((row) => files.includes(row.id)).map((row) => row.id)];
+ if (dup.length > 0) fail(`${dup.join(', ')} already name a row on ${masterRef}`, 'every behavior-change id is unique across the table and behavior-changes.d/.', 'rename the row\'s id, commit, then rerun: bun run release:unstamp');
+ return mine.map((row) => ({ id: row.id, text: row.text! }));
+}
+
+function capture(ctx: Ctx, masterRef: string, mode: Mode = 'restamp'): State {
const preHead = ctx.git('rev-parse', 'HEAD').trim();
const mergeBase = ctx.git('merge-base', 'HEAD', masterRef).trim();
const entries = branchEntrySections(ctx.git('show', 'HEAD:CHANGELOG.md'), ctx.git('show', `${mergeBase}:CHANGELOG.md`));
if (entries.length > 1) {
+ if (mode === 'unstamp') {
+ fail(`this branch has ${entries.length} CHANGELOG entries above master's (${entries.map((e) => versionOfHeader(e.header)).join(', ')})`,
+ 'a branch that carries other PRs (a stack or train) holds their entries too; each PR converts on its own, and its entry leaves this branch once it reaches master.',
+ ['land or convert the PRs this branch carries first, merge master into this branch,', 'then rerun: bun run release:unstamp (or write changelog.d/<branch-slug>.md for your own entry by hand)']);
+ }
fail(`this branch has ${entries.length} CHANGELOG entries above master's (${entries.map((e) => versionOfHeader(e.header)).join(', ')})`,
'a branch ships one unified entry (docs/RELEASING.md "CHANGELOG + VERSION are branch-scoped"); restamp re-stamps exactly one.',
'fold them into one `## [X.Y.Z.W] - date` entry, commit, then rerun: bun run release:restamp');
}
const head = headMigrations(ctx);
const inventory = analyzeMigrations(ctx, masterRef, head).branch;
- return { phase: 'merge', preHead, masterRef, branchVersion: ctx.git('show', 'HEAD:VERSION').trim(), entry: entries[0] ?? null, inventory, conflicted: [], mapping: [], flaggedRefs: [], merged: false };
+ if (mode === 'unstamp') {
+ if (entries.length === 0) {
+ fail(`this branch has no CHANGELOG entry above ${masterRef}'s`, 'release:unstamp moves the branch\'s own top entry into its changelog fragment; an edit inside a released section is not one.',
+ `write changelog.d/<branch-slug>.md yourself (changelog.d/README.md), put CHANGELOG.md back to the merge base's, commit, then rerun: bun run release:unstamp`);
+ }
+ const ownLines = new Set(entries[0]!.text.split('\n'));
+ const rest = ctx.git('show', 'HEAD:CHANGELOG.md').replace(entries[0]!.text + '\n', '');
+ if (rest !== ctx.git('show', `${mergeBase}:CHANGELOG.md`) && ownLines.size > 0) {
+ fail('this branch also edits released CHANGELOG sections', 'under releases per batch a PR changes the CHANGELOG only through its changelog.d fragment; a release never rewrites a released section.',
+ 'move those edits into your entry (or drop them), commit, then rerun: bun run release:unstamp');
+ }
+ }
+ const rows = mode === 'unstamp' ? branchNoticeRows(ctx, masterRef, mergeBase) : [];
+ return { mode, rows, phase: 'merge', preHead, masterRef, branchVersion: ctx.git('show', 'HEAD:VERSION').trim(), entry: entries[0] ?? null, inventory, conflicted: [], mapping: [], flaggedRefs: [], merged: false };
}
function merge(ctx: Ctx, state: State): void {
@@ -273,6 +364,15 @@ function merge(ctx: Ctx, state: State): void {
genuine.push(f);
continue;
}
+ } else if (state.mode === 'unstamp' && (state.rows ?? []).length > 0 && f === BEHAVIOR_NOTICE_FILE) {
+ ctx.write(f, ctx.git('show', `${state.masterRef}:${f}`));
+ } else if (state.mode === 'unstamp' && (state.rows ?? []).length > 0 && f === SIZE_LIMITS) {
+ const merged = mergeLimitsWithMastersNoticeRow(ctx);
+ if (merged === null) {
+ genuine.push(f);
+ continue;
+ }
+ ctx.write(f, merged);
} else if (stampFiles.has(f) && existsSync(join(ctx.root, f))) {
const r = resolveVersionOnlyHunks(ctx.read(f));
if (r.unresolved > 0) {
@@ -298,6 +398,23 @@ function merge(ctx: Ctx, state: State): void {
ctx.log(`restamp: merged ${state.masterRef} with a merge commit (${conflicted.length} conflict(s) resolved mechanically).`);
}
+/** The size table merged with the notice file's row taken from master on every side (its rows leave the file), or null on a real conflict. */
+function mergeLimitsWithMastersNoticeRow(ctx: Ctx): string | null {
+ const stage = (n: number) => ctx.git('show', `:${n}:${SIZE_LIMITS}`);
+ const [base, ours, theirs] = [stage(1), stage(2), stage(3)];
+ const master = limitLine(theirs);
+ const pin = (text: string) => { const own = limitLine(text); return own && master ? text.replace(own, master) : text; };
+ const dir = resolve(ctx.root, ctx.git('rev-parse', '--git-path', 'gbrain-unstamp-limits').trim());
+ const at = (name: string) => join(dir, name);
+ mkdirSync(dir, { recursive: true });
+ writeFileSync(at('base'), pin(base));
+ writeFileSync(at('ours'), pin(ours));
+ writeFileSync(at('theirs'), pin(theirs));
+ const r = Bun.spawnSync(['git', 'merge-file', '-p', at('ours'), at('base'), at('theirs')], { cwd: ctx.root, stdout: 'pipe', stderr: 'pipe' });
+ rmSync(dir, { recursive: true, force: true });
+ return r.exitCode === 0 ? r.stdout.toString() : null;
+}
+
function finishMerge(ctx: Ctx, state: State): void {
const unmerged = ctx.git('diff', '--name-only', '--diff-filter=U').split('\n').filter(Boolean);
const marked = state.conflicted.filter((f) => existsSync(join(ctx.root, f)) && /^(<<<<<<<|>>>>>>>) /m.test(ctx.read(f)));
@@ -333,32 +450,61 @@ function applyRenumber(ctx: Ctx, state: State, plan: Renumber[]): void {
interface Outcome { version: string; masterVersion: string }
+/**
+ * release:unstamp's one conversion: every version stamp back to master's, the branch's CHANGELOG entry to its
+ * changelog fragment, its appended rows to behavior-changes.d/ with a marker each, and the notice file and its size
+ * row to master's. Nothing else changes, so gstack-ship-receipt carry can read the commit as an unstamp.
+ */
+function unstampFiles(ctx: Ctx, state: State, masterVersion: string): void {
+ if (!state.entry) {
+ fail(`this branch has no CHANGELOG entry above ${state.masterRef}'s`, 'release:unstamp moves the branch\'s own entry into its changelog fragment.',
+ `write ${CHANGELOG_FRAGMENT_DIR}/<branch-slug>.md yourself (docs/RELEASING.md#releases-per-batch), commit, then rerun: bun run release:unstamp`);
+ }
+ stampOnly(ctx.root, masterVersion, [state.branchVersion]);
+ ctx.write('CHANGELOG.md', ctx.git('show', `${state.masterRef}:CHANGELOG.md`));
+ const frag = `${CHANGELOG_FRAGMENT_DIR}/${fragmentSlug(ctx.git('rev-parse', '--abbrev-ref', 'HEAD').trim())}.md`;
+ if (existsSync(join(ctx.root, frag))) fail(`${frag} already exists`, 'release:unstamp writes the branch\'s entry there and never merges two entries.', `fold your CHANGELOG entry into ${frag} by hand, put CHANGELOG.md back to ${state.masterRef}'s, commit, then rerun`);
+ const rows = state.rows ?? [];
+ const body = state.entry.text.split('\n').slice(1).join('\n').trim();
+ mkdirSync(join(ctx.root, CHANGELOG_FRAGMENT_DIR), { recursive: true });
+ ctx.write(frag, [body, ...(rows.length ? ['', ...rows.map((r) => `<!-- behavior-change: ${r.id} -->`)] : [])].join('\n') + '\n');
+ if (rows.length === 0) return;
+ mkdirSync(join(ctx.root, FRAGMENT_DIR), { recursive: true });
+ for (const row of rows) ctx.write(`${FRAGMENT_DIR}/${row.id}.md`, `${row.text}\n`);
+ ctx.write(BEHAVIOR_NOTICE_FILE, ctx.git('show', `${state.masterRef}:${BEHAVIOR_NOTICE_FILE}`));
+ const limits = ctx.read(SIZE_LIMITS);
+ const [own, master] = [limitLine(limits), limitLine(ctx.git('show', `${state.masterRef}:${SIZE_LIMITS}`))];
+ if (own && master && own !== master) ctx.write(SIZE_LIMITS, limits.replace(own, master));
+}
+
function restampTree(ctx: Ctx, state: State, opts: { acceptRefs: boolean; date: string }): Outcome {
+ const mode = state.mode ?? 'restamp';
const masterVersion = ctx.git('show', `${state.masterRef}:VERSION`).trim();
- const version = nextPatchVersion(masterVersion);
+ const version = mode === 'restamp' ? nextPatchVersion(masterVersion) : masterVersion;
const migrations = analyzeMigrations(ctx, state.masterRef, workingMigrations(ctx));
applyRenumber(ctx, state, migrations.plan);
ctx.saveState(state);
- for (const stamp of STAMPS) {
+ if (mode === 'unstamp') unstampFiles(ctx, state, masterVersion);
+ for (const stamp of mode === 'restamp' ? STAMPS : []) {
if (!existsSync(join(ctx.root, stamp.file))) fail(`${stamp.file} is missing`, 'it is a required row of the CLAUDE.md "Version locations" table.', `restore it from ${state.masterRef} (git checkout ${state.masterRef} -- ${stamp.file}), then rerun with --continue`);
const text = ctx.read(stamp.file);
if (stamp.read(text) !== version) ctx.write(stamp.file, stamp.write(text, version));
}
const olds = new Set([state.branchVersion, state.entry ? versionOfHeader(state.entry.header) ?? '' : ''].filter((v) => v && v !== version && isVersionToken(v)));
- if (existsSync(join(ctx.root, BEHAVIOR_NOTICE_FILE))) {
+ if (mode === 'restamp' && existsSync(join(ctx.root, BEHAVIOR_NOTICE_FILE))) {
const notice = ctx.read(BEHAVIOR_NOTICE_FILE);
const lines = new Set(addedLines(ctx, state.masterRef, ['--', BEHAVIOR_NOTICE_FILE]).map((l) => l.line));
let stamped = stampTbdSince(notice, version);
for (const old of olds) stamped = restampSinceLines(stamped, lines, old, version);
if (stamped !== notice) ctx.write(BEHAVIOR_NOTICE_FILE, stamped);
}
- if (state.entry) {
+ if (mode === 'restamp' && state.entry) {
const old = versionOfHeader(state.entry.header) ?? state.branchVersion;
ctx.write('CHANGELOG.md', rebuildChangelog(ctx.read('CHANGELOG.md'), state.entry, old, version, opts.date));
}
- if (existsSync(join(ctx.root, 'TODOS.md'))) {
+ if (mode === 'restamp' && existsSync(join(ctx.root, 'TODOS.md'))) {
const lines = new Set(addedLines(ctx, state.masterRef, ['--', 'TODOS.md']).map((l) => l.line));
let text = ctx.read('TODOS.md');
for (const old of olds) text = restampTodoLines(text, lines, old, version);
@@ -368,6 +514,7 @@ function restampTree(ctx: Ctx, state: State, opts: { acceptRefs: boolean; date:
const hasMigrations = migrations.branch.length > 0;
for (const step of ctx.steps('GBRAIN_RESTAMP_STEPS', DEFAULT_STEPS)) {
if (step.migrationsOnly && !hasMigrations) continue;
+ if (mode !== 'restamp' && !(hasMigrations && (step.migrationsOnly || step.name === 'schema migration registry'))) continue;
const r = ctx.run(step.argv, step.env);
if (r.code !== 0) {
stop(state, ctx, `generator "${step.name}" failed (${step.argv.join(' ')}, exit ${r.code}):\n${r.out.trim().split('\n').slice(-15).map((l) => ` | ${l}`).join('\n')}`,
@@ -395,8 +542,9 @@ function restampTree(ctx: Ctx, state: State, opts: { acceptRefs: boolean; date:
}
}
- const drift = driftProblems(ctx, version, masterVersion, state);
- for (const check of ctx.steps('GBRAIN_RESTAMP_CHECKS', DEFAULT_CHECKS)) {
+ const drift = mode === 'restamp' ? driftProblems(ctx, version, masterVersion, state)
+ : mode === 'unstamp' ? STAMPS.flatMap((stamp) => { const v = stamp.read(ctx.read(stamp.file)); return v === masterVersion ? [] : [`${stamp.file} says ${v ?? '<none>'}, expected master's ${masterVersion}`]; }) : [];
+ for (const check of ctx.steps('GBRAIN_RESTAMP_CHECKS', mode === 'restamp' ? DEFAULT_CHECKS : mode === 'unstamp' ? UNSTAMP_CHECKS : hasMigrations ? RENUMBER_CHECKS : [])) {
const r = ctx.run(check.argv, check.env);
if (r.code !== 0) drift.push(`${check.name} (${check.argv.join(' ')}, exit ${r.code}):\n${r.out.trim().split('\n').slice(-10).map((l) => ` | ${l}`).join('\n')}`);
}
@@ -475,6 +623,16 @@ function printDryRun(ctx: Ctx, state: State, date: string): void {
function report(ctx: Ctx, state: State, outcome: Outcome, committed: string | null, staged: boolean): void {
const L = ctx.log;
+ if (state.mode === 'unstamp' || state.mode === 'renumber') {
+ const what = state.mode === 'unstamp'
+ ? `unstamp: ${state.branchVersion} -> master's ${outcome.masterVersion}; the entry is in changelog.d/${fragmentSlug(ctx.git('rev-parse', '--abbrev-ref', 'HEAD').trim())}.md${state.rows?.length ? ` and ${state.rows.length} row(s) in behavior-changes.d/ (${state.rows.map((r) => r.id).join(', ')})` : ''}`
+ : `renumber: onto master v${outcome.masterVersion}`;
+ L(what);
+ for (const m of state.mapping) L(` v${m.from} -> v${m.to} ${m.fromPath} -> ${m.toPath}`);
+ L(committed ? `Committed ${committed.slice(0, 12)}.` : `Nothing to change${state.merged ? ' (only the merge commit was added)' : ''}.`);
+ if (state.mode === 'unstamp') L('PR title: drop the version prefix; the release names the version.');
+ return;
+ }
L(`restamp: ${state.branchVersion} -> ${outcome.version} (master ${outcome.masterVersion}).`);
if (state.mapping.length > 0) {
L('Migration renumbering (source only; no database was touched):');
@@ -492,11 +650,61 @@ function report(ctx: Ctx, state: State, outcome: Outcome, committed: string | nu
L('Verify: bun run verify (full gate before merge: bun run ci:ubicloud or bun run ci:local), then git push');
}
+/** Generated trees whose stamp lines name the release; their other bytes do not depend on VERSION. */
+const GENERATED_STAMP_ROOTS = ['plugin', 'plugin-variants', 'templates/bootstrap/template-repo'];
+
+/**
+ * The release stamp under merge: direct: every STAMPS row and every stamp line of the generated trees moves from the
+ * tree's VERSION to `version`. Returns the files written. gstack-restamp --release runs it in a clean checkout of the
+ * base and then folds the changelog fragments itself.
+ */
+export function stampOnly(root: string, version: string, from: string[] = []): string[] {
+ if (!/^\d+\.\d+\.\d+\.\d+$/.test(version)) fail(`--stamp-only needs a four-part version, got "${version}"`, 'the release stamp writes exactly the version gstack-restamp allocated.', 'pass it as the argument: bun scripts/release-restamp.ts --stamp-only <X.Y.Z.W>');
+ const old = readFileSync(join(root, 'VERSION'), 'utf8').trim();
+ const written: string[] = [];
+ const put = (rel: string, text: string) => {
+ if (readFileSync(join(root, rel), 'utf8') === text) return;
+ writeFileSync(join(root, rel), text);
+ written.push(rel);
+ };
+ for (const stamp of STAMPS) {
+ if (!existsSync(join(root, stamp.file))) fail(`${stamp.file} is missing`, 'it is a required row of the CLAUDE.md "Version locations" table.', `restore it, then rerun: bun scripts/release-restamp.ts --stamp-only ${version}`);
+ const text = readFileSync(join(root, stamp.file), 'utf8'); if (stamp.read(text) !== version) put(stamp.file, stamp.write(text, version));
+ }
+ const olds = [...new Set([old, ...from])].filter((v) => v && v !== version);
+ if (olds.length === 0) return written;
+ const lines = olds.flatMap((v) => [`"version": "${v}"`, `<!-- gbrain-plugin-tree-stamp: ${v} -->`, `<!-- gbrain-template-stamp: ${v} -->`]);
+ const walk = (rel: string): string[] => readdirSync(join(root, rel), { withFileTypes: true }).flatMap(e => e.isDirectory() ? walk(join(rel, e.name)) : e.isFile() && /\.(json|md)$/.test(e.name) ? [join(rel, e.name)] : []);
+ for (const dir of GENERATED_STAMP_ROOTS.filter(d => existsSync(join(root, d)))) {
+ for (const rel of walk(dir)) {
+ const text = readFileSync(join(root, rel), 'utf8');
+ let next = text;
+ for (const l of lines) next = next.split(l).join(l.replace(/\d+\.\d+\.\d+\.\d+/, version));
+ put(rel, next);
+ }
+ }
+ return written;
+}
+
export function main(argv: string[], opts: { cwd?: string; env?: Record<string, string | undefined>; log?: (line: string) => void } = {}): number {
const log = opts.log ?? ((l: string) => console.log(l));
const env = opts.env ?? process.env;
+ if (argv[0] === '--stamp-only') {
+ if (argv.length !== 2) { log(USAGE); return 2; }
+ const top = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { cwd: opts.cwd ?? process.cwd(), stdout: 'pipe', stderr: 'pipe' });
+ const root = top.exitCode === 0 ? top.stdout.toString().trim() : resolve(opts.cwd ?? process.cwd());
+ try {
+ const files = stampOnly(root, argv[1]!);
+ log(`restamp --stamp-only: ${argv[1]} written to ${files.length} file(s)${files.length ? `: ${files.join(', ')}` : ''}`);
+ return 0;
+ } catch (e) {
+ if (e instanceof RestampError) { log(e.message); return 1; }
+ throw e;
+ }
+ }
const flags = new Set(argv.filter((a) => a.startsWith('--')));
- const known = new Set(['--dry-run', '--no-commit', '--continue', '--abort', '--accept-references', '--remote', '--base', '--help']);
+ const known = new Set(['--dry-run', '--no-commit', '--continue', '--abort', '--accept-references', '--remote', '--base', '--help', '--unstamp', '--renumber']);
+ const mode: Mode = flags.has('--unstamp') ? 'unstamp' : flags.has('--renumber') ? 'renumber' : 'restamp';
const valueOf = (flag: string, fallback: string) => (argv.includes(flag) ? argv[argv.indexOf(flag) + 1] ?? '' : fallback);
const remote = valueOf('--remote', 'origin');
const base = valueOf('--base', 'master');
@@ -505,7 +713,7 @@ export function main(argv: string[], opts: { cwd?: string; env?: Record<string,
log(USAGE);
return 0;
}
- if ([...flags].some((f) => !known.has(f)) || stray.length || !remote || !base || (flags.has('--continue') && flags.has('--abort')) || (flags.has('--accept-references') && !flags.has('--continue'))) {
+ if ([...flags].some((f) => !known.has(f)) || stray.length || !remote || !base || (flags.has('--continue') && flags.has('--abort')) || (flags.has('--accept-references') && !flags.has('--continue')) || (flags.has('--unstamp') && flags.has('--renumber')) || (mode !== 'restamp' && flags.has('--dry-run'))) {
log(USAGE);
return 2;
}
@@ -548,7 +756,13 @@ export function main(argv: string[], opts: { cwd?: string; env?: Record<string,
'restamp numbers the version and migrations after the latest master; a stale ref would allocate a taken number.',
`check network access and the remote, then run: git fetch ${remote} ${base} && bun run release:restamp`);
}
- state = capture(ctx, `${remote}/${base}`);
+ const policy = Bun.spawnSync(['git', 'show', `${remote}/${base}:.gstack/ship-policy.json`], { cwd: ctx.root, stdout: 'pipe', stderr: 'ignore' });
+ const direct = (() => { try { return JSON.parse(policy.stdout.toString() || '{}').merge === 'direct'; } catch { return false; } })();
+ if (direct && mode === 'restamp') {
+ fail(`${remote}/${base} lands PRs directly and writes versions at release (.gstack/ship-policy.json merge: direct)`, 'a PR branch carries no version, so there is nothing to restamp.',
+ ['a branch stamped before the switch: bun run release:unstamp', 'a branch whose schema migration number master took: bun run migrations:renumber']);
+ }
+ state = capture(ctx, `${remote}/${base}`, mode);
if (flags.has('--dry-run')) {
printDryRun(ctx, state, date);
return 0;
@@ -564,7 +778,10 @@ export function main(argv: string[], opts: { cwd?: string; env?: Record<string,
let committed: string | null = null;
if (staged && !flags.has('--no-commit')) {
const body = state.mapping.length ? `\n\nMigrations renumbered (filename, export name, version literal):\n${state.mapping.map((m) => ` v${m.from} -> v${m.to} ${m.toPath}`).join('\n')}\nGolden regeneration: migrations/records.json follows the renumbered versions.` : '';
- ctx.git('commit', '--quiet', '-m', `v${outcome.version} chore(release): restamp onto master v${outcome.masterVersion}${body}`);
+ const subject = state.mode === 'unstamp' ? `chore(release): unstamp onto master v${outcome.masterVersion}; versions are written at release`
+ : state.mode === 'renumber' ? `chore(migrations): renumber onto master v${outcome.masterVersion}`
+ : `v${outcome.version} chore(release): restamp onto master v${outcome.masterVersion}`;
+ ctx.git('commit', '--quiet', '-m', `${subject}${body}`);
committed = ctx.git('rev-parse', 'HEAD').trim();
}
rmSync(ctx.statePath, { force: true });
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 9368f567d1..98312cf0b4 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -67,6 +67,7 @@ import {
import { mergedProviderEnv } from './ai/provider-env.ts';
import { FENCE_REPAIR_MEASURED } from './fence-repair/measured.ts';
import { CONTENT_REPAIR_MEASURED } from './content-repair/measured.ts';
+import { BEHAVIOR_CHANGE_RELEASES, RELEASED_BEHAVIOR_CHANGES } from './behavior-changes.generated.ts';
/** The measured re-ingest page multiplier, as prose (scripts/measure-transcript-split-cost.ts: 4 → 27 pages on a 1 MB session). */
export const TRANSCRIPT_REINGEST_MULTIPLIER = 'about 6.75x';
@@ -222,7 +223,14 @@ const DOCTOR_ARGV = ['gbrain', 'doctor', '--only', BEHAVIOR_NOTICE_CODE, '--json
type ChangeText = string | ((chain: ChainDisclosure | null, remote: boolean) => string | null);
-/** Every disclosed behavior change, with the release that introduced it. Append new rows; never edit a shipped `since`. */
+/** A function row's release: the version whose CHANGELOG section marks its id (behavior-changes.d/README.md), 'TBD' until a release does. */
+const releasedIn = (id: string): string => BEHAVIOR_CHANGE_RELEASES[id] ?? 'TBD';
+
+/**
+ * Every disclosed behavior change, with the release that introduced it; never edit a shipped `since`. A new plain-text
+ * row is a behavior-changes.d/<id>.md fragment (RELEASED_BEHAVIOR_CHANGES once a release dates it); a new function row
+ * goes here as `{ since: releasedIn('<id>'), id: '<id>', text: ... }`.
+ */
export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText; id?: string }> = [
{ since: '0.60.68.0', text: (chain, remote) => {
if (!chain) return null;
@@ -1494,6 +1502,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.622.0', id: 'purge_cancels_deferred_write_gst1602', text: 'With `persistence.refresh_barrier` on, `gbrain forget <id> --purge` no longer refuses `purge_blocked_pending_recovery` while a write deferred behind a refresh holds the claim in its staged body: the deferred write was never claimed, so the purge cancels it with `purged_content`, as it does a queued one, and removes the content at once instead of up to 15 minutes later.' },
{ since: '0.60.623.0', id: 'owner_reads_private_gst2059', text: 'A brain can now name its owner: `gbrain access owner set <member>` (config `access.owner_member`, an enabled member). Every remote credential or stdio server bound to that member reads the whole brain, `visibility: private` pages, privacy-alias pages (`access: private`, ...), derived and pinned-question pages included, through `get_page`, `search`, `query`, `recall` and the other page reads in the sources its grant reads, and `recall` returns its private facts. `readable_by` and folder rules still bind it, and it is not relaxed when it speaks for a shared-room audience. A page the owner\'s credential creates in `default` through `put_page` is not kept to the owner (no `readable_by: [member:<id>]`). Other members, unbound and public callers are unchanged. `_meta.access.relaxation` reads `owner` for such a call, and `gbrain access check --token <name>` reports it. `gbrain repair private-labels` (named runs only) previews the `access: private` labels stamped on ordinary pages with counts per category, keeps real restrictions, and clears the rest in reviewed batches (`--apply --expect <hash>`), recording each change so `--class restore` can put it back. The bulk-ingestion page template no longer writes an `access:` line; what each designation means is in docs/guides/access-designations.md.' },
{ since: '0.60.626.0', id: 'record_origin_checkout_lockdown_8888', text: '`gbrain sources record-origin <id>... --remote --apply` now also turns git-lfs downloads and hooks off in each recorded source\'s existing checkout (its `.git/config`: `lfs.fetchexclude=*`, `core.hooksPath=/dev/null`, `lfs.locksverify=false`), not only on later reclones, in the repository\'s shared config, and refuses `write_failed` naming the key when a worktree-scoped or included setting still overrides one; a source already recorded as remote gets the lock-down on the next `--remote --apply` when its checkout lacks it, even when its files now use git-lfs, and a key that holds several values in that config is replaced by the one clone-time value. On a managed brain it takes the same worktree locks a reclone takes, refusing the id `source_busy` while a reclone, refresh or write holds them, and a reclone reads the record under its own locks. A write that fails is reported for its own id (`write_failed`) instead of ending the run. The git-lfs check reads a committed `.gitattributes` under a directory whose name holds a tab, ignores commented-out `filter=lfs` lines, says when a committed rule only declares an LFS filter, records a clone of an empty repository instead of refusing it, and names the cause of an `lfs_unknown` refusal.' },
+ ...RELEASED_BEHAVIOR_CHANGES,
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/behavior-changes.generated.ts b/src/core/behavior-changes.generated.ts
new file mode 100644
index 0000000000..2cb52dc57b
--- /dev/null
+++ b/src/core/behavior-changes.generated.ts
@@ -0,0 +1,10 @@
+// Generated by scripts/build-behavior-changes.ts from behavior-changes.d/ and the CHANGELOG markers; do not edit.
+// Regenerate: bun scripts/build-behavior-changes.ts (the release does it). Docs: behavior-changes.d/README.md
+
+/** The plain-text rows of behavior-changes.d/, each dated by the release whose CHANGELOG section marks it. */
+export const RELEASED_BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; id: string; text: string }> = [
+];
+
+/** The release of every marked id, so a function row dated releasedIn(id) takes the release that disclosed it. */
+export const BEHAVIOR_CHANGE_RELEASES: Readonly<Record<string, string>> = {
+};
diff --git a/test/behavior-change-notice-6712-block.test.ts b/test/behavior-change-notice-6712-block.test.ts
index 563e82b6f9..11292e40cc 100644
--- a/test/behavior-change-notice-6712-block.test.ts
+++ b/test/behavior-change-notice-6712-block.test.ts
@@ -10,6 +10,7 @@ import { describe, expect, test } from 'bun:test';
import { readFileSync } from 'node:fs';
import { join } from 'node:path';
import { BEHAVIOR_CHANGES, compareReleases } from '../src/core/behavior-change-notice.ts';
+import { RELEASED_BEHAVIOR_CHANGES } from '../src/core/behavior-changes.generated.ts';
const MARKER = '// #6712 PR 4b (the level-triggered sync pass';
const ROWS = 33;
@@ -25,7 +26,7 @@ function locateBlock(source: string): { rowLines: number; first: number; count:
const trimmed = line.trimStart();
if (trimmed.startsWith(MARKER)) { inBlock = true; first = rowLines; continue; }
if (trimmed.startsWith('//')) inBlock = false;
- const rows = line.match(/\{ since: '/g)?.length ?? 0;
+ const rows = line.match(/\{ since: /g)?.length ?? 0;
rowLines += rows;
if (inBlock) count += rows;
}
@@ -40,7 +41,7 @@ describe('#6712 PR 4b BEHAVIOR_CHANGES block', () => {
const block = BEHAVIOR_CHANGES.slice(first, first + count);
test('the narrow parse sees every exported row and finds the block', () => {
- expect(rowLines).toBe(BEHAVIOR_CHANGES.length);
+ expect(rowLines).toBe(BEHAVIOR_CHANGES.length - RELEASED_BEHAVIOR_CHANGES.length);
expect(first).toBeGreaterThan(0);
});
diff --git a/test/scripts/build-behavior-changes.test.ts b/test/scripts/build-behavior-changes.test.ts
new file mode 100644
index 0000000000..73ebcabcb8
--- /dev/null
+++ b/test/scripts/build-behavior-changes.test.ts
@@ -0,0 +1,221 @@
+/**
+ * scripts/build-behavior-changes.ts against throwaway trees: behavior-changes.d/<id>.md fragments dated by the
+ * <!-- behavior-change: <id> --> marker's CHANGELOG section, pending markers (changelog.d, [Unreleased]) counted only
+ * while VERSION is newer than the top release heading, the fragment problems, releasedIn('<id>') function rows, the
+ * --check exit codes, and the byte-identity between a release in progress and the same release folded, which
+ * gstack's release check relies on.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { dirname, join } from 'node:path';
+import { build, main, NOTICE_FILE, OUT } from '../../scripts/build-behavior-changes.ts';
+
+const roots: string[] = [];
+afterAll(() => { for (const r of roots) rmSync(r, { recursive: true, force: true }); });
+
+function tree(files: Record<string, string>): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-behavior-changes-'));
+ roots.push(root);
+ for (const [path, text] of Object.entries(files)) {
+ mkdirSync(dirname(join(root, path)), { recursive: true });
+ writeFileSync(join(root, path), text);
+ }
+ return root;
+}
+
+const marker = (id: string) => `<!-- behavior-change: ${id} -->`;
+const section = (version: string, ...lines: string[]) => `## [${version}] - 2026-11-01\n\n${lines.join('\n')}\n`;
+const changelog = (...sections: string[]) => `# Changelog\n\n${sections.join('\n')}`;
+const notice = (...rows: string[]) => ['export const BEHAVIOR_CHANGES = [', ...rows.map((r) => ` ${r}`), '];', ''].join('\n');
+
+function run(root: string, argv: string[]): { code: number; out: string } {
+ const lines: string[] = [];
+ const code = main(argv, { cwd: root, log: (l) => lines.push(l) });
+ return { code, out: lines.join('\n') };
+}
+
+const rowsOf = (text: string) => [...text.matchAll(/^ {2}\{ since: '([^']+)', id: '([^']+)', text: (".*") \},$/gm)].map((m) => ({ since: m[1], id: m[2], text: JSON.parse(m[3]!) }));
+const releasesOf = (text: string) => Object.fromEntries([...text.matchAll(/^ {2}([a-z0-9_]+): '([^']+)',$/gm)].map((m) => [m[1], m[2]]));
+
+describe('build()', () => {
+ test('a pending fragment (marker in changelog.d, VERSION at the top heading) generates nothing', () => {
+ const root = tree({
+ VERSION: '0.1.0.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.0.0', 'First.')),
+ 'changelog.d/feature-x.md': `**Faster sync.**\n\n${marker('faster_sync_abc')}\n`,
+ 'behavior-changes.d/faster_sync_abc.md': 'Sync is faster now.\n',
+ });
+ const { text, problems } = build(root);
+ expect(problems).toEqual([]);
+ expect(rowsOf(text)).toEqual([]);
+ expect(releasesOf(text)).toEqual({});
+ });
+
+ test('an [Unreleased] marker is pending too until a release is being stamped', () => {
+ const files = {
+ 'CHANGELOG.md': changelog(`## [Unreleased]\n\n${marker('faster_sync_abc')}\n`, section('0.1.0.0', 'First.')),
+ 'behavior-changes.d/faster_sync_abc.md': 'Sync is faster now.\n',
+ };
+ expect(rowsOf(build(tree({ VERSION: '0.1.0.0\n', ...files })).text)).toEqual([]);
+ expect(rowsOf(build(tree({ VERSION: '0.1.1.0\n', ...files })).text)).toEqual([{ since: '0.1.1.0', id: 'faster_sync_abc', text: 'Sync is faster now.' }]);
+ });
+
+ test('a marker under a released CHANGELOG heading dates the row with that version, text joined to one line', () => {
+ const root = tree({
+ VERSION: '0.1.1.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.1.0', 'Second.', marker('newer_row_abc')), section('0.1.0.0', 'First.', marker('older_row_abc'))),
+ 'behavior-changes.d/older_row_abc.md': 'Older\n change.\n',
+ 'behavior-changes.d/newer_row_abc.md': 'Newer change.\n',
+ });
+ const { text, problems } = build(root);
+ expect(problems).toEqual([]);
+ expect(rowsOf(text)).toEqual([
+ { since: '0.1.0.0', id: 'older_row_abc', text: 'Older change.' },
+ { since: '0.1.1.0', id: 'newer_row_abc', text: 'Newer change.' },
+ ]);
+ expect(releasesOf(text)).toEqual({ older_row_abc: '0.1.0.0', newer_row_abc: '0.1.1.0' });
+ });
+
+ test('stamping (VERSION newer than the top heading) dates pending changelog.d markers with VERSION', () => {
+ const root = tree({
+ VERSION: '0.1.1.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.0.0', 'First.', marker('older_row_abc'))),
+ 'changelog.d/feature-x.md': `**Faster sync.**\n\n${marker('faster_sync_abc')}\n`,
+ 'changelog.d/README.md': `Docs mention ${marker('readme_only_abc')} and are not a fragment.\n`,
+ 'behavior-changes.d/older_row_abc.md': 'Older change.\n',
+ 'behavior-changes.d/faster_sync_abc.md': 'Sync is faster now.\n',
+ });
+ const { text, problems } = build(root);
+ expect(problems).toEqual([]);
+ expect(rowsOf(text)).toEqual([
+ { since: '0.1.0.0', id: 'older_row_abc', text: 'Older change.' },
+ { since: '0.1.1.0', id: 'faster_sync_abc', text: 'Sync is faster now.' },
+ ]);
+ });
+
+ test('problems: fragment without marker, marker without fragment, id repeating a table row, over-long text, bad filename', () => {
+ const root = tree({
+ VERSION: '0.1.0.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.0.0', marker('no_fragment_abc'), marker('old_table_row'), marker('too_long_abc'))),
+ [NOTICE_FILE]: notice("{ since: '0.0.9.0', id: 'old_table_row', text: 'Released long ago.' },"),
+ 'behavior-changes.d/no_marker_abc.md': 'Nobody names me.\n',
+ 'behavior-changes.d/old_table_row.md': 'Same id as a table row.\n',
+ 'behavior-changes.d/too_long_abc.md': 'x'.repeat(2001),
+ 'behavior-changes.d/Bad-Name.md': 'Bad name.\n',
+ 'behavior-changes.d/notes.txt': 'Not markdown.\n',
+ });
+ const { problems } = build(root);
+ expect(problems.sort()).toEqual([
+ 'behavior-changes.d/Bad-Name.md: a fragment is named <id>.md, the id lowercase letters, digits and _ (3-96 characters)',
+ 'behavior-changes.d/no_marker_abc.md has no <!-- behavior-change: no_marker_abc --> marker in a changelog.d fragment or the CHANGELOG, so no release would disclose it',
+ 'behavior-changes.d/notes.txt: a fragment is named <id>.md, the id lowercase letters, digits and _ (3-96 characters)',
+ `behavior-changes.d/old_table_row.md repeats the id of a row in ${NOTICE_FILE}`,
+ 'behavior-changes.d/too_long_abc.md is 2001 characters; the notice renders at most 2000',
+ `the marker <!-- behavior-change: no_fragment_abc --> names no behavior-changes.d/no_fragment_abc.md and no function row dated releasedIn('no_fragment_abc')`,
+ ]);
+ });
+
+ test('text at exactly 2000 characters is accepted', () => {
+ const root = tree({
+ VERSION: '0.1.0.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.0.0', marker('cap_row_abc'))),
+ 'behavior-changes.d/cap_row_abc.md': 'y'.repeat(2000) + '\n',
+ });
+ expect(build(root).problems).toEqual([]);
+ });
+
+ test("releasedIn('<id>') function rows need a marker and take their release from BEHAVIOR_CHANGE_RELEASES", () => {
+ const fnRow = "{ since: releasedIn('fn_row_abc'), id: 'fn_row_abc', text: (chain) => `chain ${chain}` },";
+ const unmarked = build(tree({ VERSION: '0.1.0.0\n', 'CHANGELOG.md': changelog(section('0.1.0.0', 'First.')), [NOTICE_FILE]: notice(fnRow) }));
+ expect(unmarked.problems).toEqual([`the releasedIn('fn_row_abc') row in ${NOTICE_FILE} has no <!-- behavior-change: fn_row_abc --> marker, so no release would date it`]);
+
+ const pending = build(tree({ VERSION: '0.1.0.0\n', 'CHANGELOG.md': changelog(section('0.1.0.0', 'First.')), 'changelog.d/fn.md': `${marker('fn_row_abc')}\n`, [NOTICE_FILE]: notice(fnRow) }));
+ expect(pending.problems).toEqual([]);
+ expect(releasesOf(pending.text)).toEqual({});
+
+ const released = build(tree({ VERSION: '0.1.1.0\n', 'CHANGELOG.md': changelog(section('0.1.1.0', marker('fn_row_abc')), section('0.1.0.0', 'First.')), [NOTICE_FILE]: notice(fnRow) }));
+ expect(released.problems).toEqual([]);
+ expect(rowsOf(released.text)).toEqual([]);
+ expect(releasesOf(released.text)).toEqual({ fn_row_abc: '0.1.1.0' });
+ });
+
+ test('release in progress and release folded generate byte-identical text', () => {
+ const fnRow = "{ since: releasedIn('fn_row_abc'), id: 'fn_row_abc', text: () => 'computed' },";
+ const shared = {
+ [NOTICE_FILE]: notice("{ since: '0.0.9.0', id: 'table_row_abc', text: 'Old.' },", fnRow),
+ 'behavior-changes.d/older_row_abc.md': 'Older change.\n',
+ 'behavior-changes.d/alpha_row_abc.md': 'Alpha change.\n',
+ 'behavior-changes.d/beta_row_abc.md': 'Beta\nchange.\n',
+ 'changelog.d/README.md': 'One file per PR.\n',
+ };
+ const released = section('0.1.0.0', 'First.', marker('older_row_abc'));
+ const alpha = `**Alpha.**\n\n${marker('alpha_row_abc')}\n${marker('fn_row_abc')}`;
+ const beta = `**Beta.**\n\n${marker('beta_row_abc')}`;
+ const fragments = { 'changelog.d/a-alpha.md': `${alpha}\n`, 'changelog.d/b-beta.md': `${beta}\n` };
+ const inProgress = build(tree({ ...shared, ...fragments, VERSION: '0.1.1.0\n', 'CHANGELOG.md': changelog(released) }));
+ const folded = build(tree({ ...shared, VERSION: '0.1.1.0\n', 'CHANGELOG.md': changelog(section('0.1.1.0', alpha, '', beta), released) }));
+ expect(inProgress.problems).toEqual([]);
+ expect(folded.problems).toEqual([]);
+ expect(folded.text).toBe(inProgress.text);
+ expect(rowsOf(folded.text).map((r) => `${r.id}@${r.since}`)).toEqual(['[email protected]', '[email protected]', '[email protected]']);
+ expect(releasesOf(folded.text)).toEqual({ older_row_abc: '0.1.0.0', alpha_row_abc: '0.1.1.0', fn_row_abc: '0.1.1.0', beta_row_abc: '0.1.1.0' });
+
+ const notStamping = build(tree({ ...shared, ...fragments, VERSION: '0.1.0.0\n', 'CHANGELOG.md': changelog(released) }));
+ expect(notStamping.problems).toEqual([]);
+ expect(rowsOf(notStamping.text).map((r) => r.id)).toEqual(['older_row_abc']);
+ });
+
+ test('the same id marked in two releases is a problem', () => {
+ const root = tree({
+ VERSION: '0.1.1.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.1.0', marker('twice_row_abc')), section('0.1.0.0', marker('twice_row_abc'))),
+ 'behavior-changes.d/twice_row_abc.md': 'Twice.\n',
+ });
+ expect(build(root).problems).toEqual(['twice_row_abc is marked in two releases (0.1.0.0 and 0.1.1.0)']);
+ });
+});
+
+describe('main()', () => {
+ const files = () => ({
+ VERSION: '0.1.0.0\n',
+ 'CHANGELOG.md': changelog(section('0.1.0.0', marker('older_row_abc'))),
+ 'behavior-changes.d/older_row_abc.md': 'Older change.\n',
+ 'src/core/.keep': '',
+ });
+
+ test('--check: stale exits 1 without writing, fresh exits 0; a write makes it fresh', () => {
+ const root = tree(files());
+ const missing = run(root, ['--check']);
+ expect(missing.code).toBe(1);
+ expect(missing.out).toContain(`FAIL: ${OUT} is stale.`);
+ expect(existsSync(join(root, OUT))).toBe(false);
+
+ const write = run(root, []);
+ expect(write.code).toBe(0);
+ expect(write.out).toContain(`wrote ${OUT}`);
+ expect(readFileSync(join(root, OUT), 'utf8')).toBe(build(root).text);
+ expect(run(root, []).out).toContain('unchanged');
+
+ const fresh = run(root, ['--check']);
+ expect(fresh.code).toBe(0);
+ expect(fresh.out).toContain('is fresh');
+
+ writeFileSync(join(root, OUT), readFileSync(join(root, OUT), 'utf8').replace("since: '0.1.0.0'", "since: '0.0.1.0'"));
+ expect(run(root, ['--check']).code).toBe(1);
+ });
+
+ test('a fragment problem exits 1 with FAIL/Why/Fix and writes nothing', () => {
+ const root = tree({ ...files(), 'behavior-changes.d/orphan_row_abc.md': 'No marker.\n' });
+ const r = run(root, []);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('FAIL: 1 behavior-change fragment problem(s):');
+ expect(r.out).toContain('Why:');
+ expect(r.out).toContain('Fix:');
+ expect(existsSync(join(root, OUT))).toBe(false);
+ });
+
+ test('an unknown argument is a usage error', () => {
+ expect(run(tree(files()), ['--nope']).code).toBe(2);
+ });
+});
diff --git a/test/scripts/check-behavior-since.test.ts b/test/scripts/check-behavior-since.test.ts
index da8b89c05c..bf5083abf1 100644
--- a/test/scripts/check-behavior-since.test.ts
+++ b/test/scripts/check-behavior-since.test.ts
@@ -12,6 +12,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { main, NOTICE_FILE, tbdLines } from '../../scripts/check-behavior-since.ts';
+import { build, OUT } from '../../scripts/build-behavior-changes.ts';
import { DEFAULT_CHECKS } from '../../scripts/release-restamp.ts';
import { BEHAVIOR_NOTICE_FILE, restampSinceLines, stampTbdSince } from '../../scripts/lib/restamp.ts';
@@ -160,3 +161,78 @@ describe('release:restamp and the TBD rows', () => {
expect(DEFAULT_CHECKS.map((c) => c.argv.join(' '))).toContain('bun scripts/check-behavior-since.ts --stamped');
});
});
+
+describe('check:behavior-since under merge: direct', () => {
+ const POLICY = { '.gstack/ship-policy.json': JSON.stringify({ merge: 'direct' }) + '\n' };
+ const marker = '<!-- behavior-change: faster_sync_abc -->';
+ const fragment = { 'behavior-changes.d/faster_sync_abc.md': 'Sync is faster now.\n' };
+
+ /** origin/master already switched to merge: direct; the feature branch starts from it. */
+ function directRepo(): string {
+ const root = repo();
+ git(root, 'checkout', '-q', 'master');
+ put(root, POLICY);
+ commit(root, 'merge: direct');
+ git(root, 'update-ref', 'refs/remotes/origin/master', 'HEAD');
+ git(root, 'checkout', '-q', '-B', 'feature');
+ return root;
+ }
+
+ test('a literal TBD row is refused even on an unstamped branch (VERSION equals origin/master)', () => {
+ const root = directRepo();
+ put(root, { [NOTICE_FILE]: notice('0.60.321.0', '0.60.322.0', 'TBD') });
+ commit(root, 'feature');
+ const r = run(root);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain("FAIL: 1 BEHAVIOR_CHANGES row(s) in " + NOTICE_FILE + " say since: 'TBD' (line 4)");
+ expect(r.out).toContain('under merge: direct');
+ expect(r.out).toContain('behavior-changes.d/<id>.md');
+ expect(run(root, ['--stamped']).code).toBe(1);
+ });
+
+ test('a branch with a pending fragment and no TBD row passes without --stamped', () => {
+ const root = directRepo();
+ put(root, { ...fragment, 'changelog.d/feature.md': '**Faster sync.**\n\n' + marker + '\n' });
+ commit(root, 'feature');
+ expect(run(root).code).toBe(0);
+ });
+
+ test('--stamped refuses a release commit that still holds an unfolded changelog.d fragment', () => {
+ const root = directRepo();
+ put(root, { ...fragment, VERSION: '0.60.323.0\n', 'changelog.d/feature.md': '**Faster sync.**\n\n' + marker + '\n', 'changelog.d/README.md': 'docs\n' });
+ put(root, { [OUT]: build(root).text });
+ commit(root, 'release, fragments not folded');
+ const r = run(root, ['--stamped']);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('still holds 1 unfolded changelog.d fragment(s): feature.md');
+ expect(r.out).toContain('VERSION 0.60.323.0');
+ });
+
+ test('--stamped refuses a folded release whose generated table is stale, and passes once it is fresh', () => {
+ const root = directRepo();
+ put(root, { ...fragment, VERSION: '0.60.323.0\n', 'CHANGELOG.md': changelog('0.60.322.0').replace('# Changelog\n\n', '# Changelog\n\n## [0.60.323.0] - 2026-11-09\n\n**Faster sync.**\n\n' + marker + '\n\n'), 'changelog.d/README.md': 'docs\n' });
+ commit(root, 'release, table not regenerated');
+ const stale = run(root, ['--stamped']);
+ expect(stale.code).toBe(1);
+ expect(stale.out).toContain('has a stale ' + OUT);
+
+ const { text, problems } = build(root);
+ expect(problems).toEqual([]);
+ expect(text).toContain("{ since: '0.60.323.0', id: 'faster_sync_abc'");
+ put(root, { [OUT]: text });
+ commit(root, 'release, table regenerated');
+ const ok = run(root, ['--stamped']);
+ expect(ok.code).toBe(0);
+ expect(ok.out).toContain("no since: 'TBD' row");
+ });
+
+ test('--stamped names the first fragment problem when the table cannot be built', () => {
+ const root = directRepo();
+ put(root, { ...fragment, VERSION: '0.60.323.0\n' });
+ put(root, { [OUT]: build(root).text });
+ commit(root, 'release with an orphan fragment');
+ const r = run(root, ['--stamped']);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('has a stale ' + OUT + ' (behavior-changes.d/faster_sync_abc.md has no');
+ });
+});
diff --git a/test/scripts/release-gate.test.ts b/test/scripts/release-gate.test.ts
index 15f9ffd3c1..821110bf9a 100644
--- a/test/scripts/release-gate.test.ts
+++ b/test/scripts/release-gate.test.ts
@@ -1,9 +1,8 @@
/**
* scripts/release-gate.ts + release.yml wiring: publication and the
* latest-stable move wait for Test and E2E Tests success on the release
- * commit; a failed run publishes nothing with the next step; a run cancelled
- * by a newer push is followed to the next master commit with the same
- * VERSION (or marks the version superseded); dispatch backfills through the
+ * commit; a failed or cancelled run publishes nothing with the next step (no
+ * later commit is published in its place); dispatch backfills through the
* same gate; non-master refs are refused.
*/
import { describe, expect, test } from 'bun:test';
@@ -19,14 +18,11 @@ const B = 'b'.repeat(40);
const C = 'c'.repeat(40);
const run = (id: number, n: number, sha: string, status: string, conclusion: string | null, attempt = 1): GateRun => ({ id, run_number: n, run_attempt: attempt, status, conclusion, head_sha: sha, head_branch: 'master', event: 'push' });
-function deps(runs: Record<string, GateRun[]>, versions: Record<string, string> = {}, outside: string[] = [], reused: Record<number, Provenance> = {}): GateDeps & { calls: string[] } {
+function deps(runs: Record<string, GateRun[]>, reused: Record<number, Provenance> = {}): GateDeps & { calls: string[] } {
const calls: string[] = [];
return {
calls,
async runsFor(file, sha) { calls.push(`runs ${file} ${sha.slice(0, 1)}`); return (runs[file] ?? []).filter(r => r.head_sha === sha); },
- async newerRuns(file, after) { return (runs[file] ?? []).filter(r => r.run_number > after); },
- async versionAt(sha) { return versions[sha] ?? '0.60.70.0'; },
- async contains(_base, head) { return !outside.includes(head); },
async provenance(_file, r) { return reused[r.id] ?? { reused: false }; },
};
}
@@ -54,29 +50,21 @@ describe('release gate', () => {
expect((await evaluate(rerunGreen, A, '0.60.70.0')).kind).toBe('publish');
});
- test('a run cancelled by a newer push is followed to the next master commit with the same VERSION, which is published', async () => {
- const d = deps({
- 'test.yml': [run(1, 10, A, 'completed', 'cancelled'), run(3, 11, B, 'completed', 'success')],
- 'e2e.yml': [run(2, 20, A, 'completed', 'success'), run(4, 21, B, 'completed', 'success')],
- });
- const v = await evaluate(d, A, '0.60.70.0');
- expect(v).toMatchObject({ kind: 'publish', sha: B });
- expect(v.why).toContain('same VERSION');
- const notYet = deps({ 'test.yml': [run(1, 10, A, 'completed', 'cancelled')], 'e2e.yml': [run(2, 20, A, 'completed', 'success')] });
- expect((await evaluate(notYet, A, '0.60.70.0')).why).toContain('waiting for the newer push-to-master run');
- const redSuccessor = deps({ 'test.yml': [run(1, 10, A, 'completed', 'cancelled'), run(3, 11, B, 'completed', 'failure')], 'e2e.yml': [run(4, 21, B, 'completed', 'success')] });
- expect(await evaluate(redSuccessor, A, '0.60.70.0')).toMatchObject({ kind: 'fail', sha: B });
- });
-
- test('a cancellation by a push that moved VERSION marks this version superseded; a successor that lacks the release commit fails', async () => {
- const moved = deps({ 'test.yml': [run(1, 10, A, 'completed', 'cancelled'), run(3, 11, B, 'in_progress', null)], 'e2e.yml': [] }, { [B]: '0.60.71.0' });
- expect(await evaluate(moved, A, '0.60.70.0')).toMatchObject({ kind: 'superseded', sha: B });
- const stray = deps({ 'test.yml': [run(1, 10, A, 'completed', 'cancelled'), run(3, 11, C, 'completed', 'success')], 'e2e.yml': [] }, {}, [C]);
- expect((await evaluate(stray, A, '0.60.70.0')).kind).toBe('fail');
+ test('a cancelled or skipped run publishes nothing, and no later master commit is published in its place', async () => {
+ for (const conclusion of ['cancelled', 'skipped']) {
+ const d = deps({
+ 'test.yml': [run(1, 10, A, 'completed', conclusion), run(3, 11, B, 'completed', 'success')],
+ 'e2e.yml': [run(2, 20, A, 'completed', 'success'), run(4, 21, B, 'completed', 'success')],
+ });
+ const v = await evaluate(d, A, '0.60.70.0');
+ expect(v).toMatchObject({ kind: 'fail', sha: A });
+ expect(v.kind === 'fail' && v.next).toContain('gh run rerun 1');
+ expect(d.calls.some(c => c.endsWith(' b'))).toBe(false);
+ }
});
test('a publish names the full-suite run each workflow reused, and writes both ids', async () => {
- const d = deps({ 'test.yml': [run(1, 10, A, 'completed', 'success')], 'e2e.yml': [run(2, 20, A, 'completed', 'success')] }, {}, [], { 1: { reused: true, run_id: 900, run_attempt: 2, sha: B } });
+ const d = deps({ 'test.yml': [run(1, 10, A, 'completed', 'success')], 'e2e.yml': [run(2, 20, A, 'completed', 'success')] }, { 1: { reused: true, run_id: 900, run_attempt: 2, sha: B } });
const v = await evaluate(d, A, '0.60.70.0');
expect(v).toMatchObject({ kind: 'publish', sha: A, sources: [{ workflow: 'Test', run_id: 1, reused: { run_id: 900, run_attempt: 2, sha: B } }, { workflow: 'E2E Tests', run_id: 2 }] });
expect(v.why).toContain('Test reused full-suite run 900 attempt 2');
@@ -86,7 +74,7 @@ describe('release gate', () => {
});
test('a reused push run whose reuse record cannot be read publishes nothing and names the re-run', async () => {
- const d = deps({ 'test.yml': [run(1, 10, A, 'completed', 'success')], 'e2e.yml': [run(2, 20, A, 'completed', 'success')] }, {}, [], { 2: { problem: "run 2 has no 'reused-full-suite' artifact" } });
+ const d = deps({ 'test.yml': [run(1, 10, A, 'completed', 'success')], 'e2e.yml': [run(2, 20, A, 'completed', 'success')] }, { 2: { problem: "run 2 has no 'reused-full-suite' artifact" } });
const v = await evaluate(d, A, '0.60.70.0');
expect(v.kind).toBe('fail');
if (v.kind !== 'fail') return;
@@ -104,7 +92,6 @@ describe('release gate', () => {
let i = 0;
const d: GateDeps = {
async runsFor(file) { return file === 'test.yml' ? [states[Math.min(i++, 2)]!] : [run(2, 20, A, 'completed', 'success')]; },
- async newerRuns() { return []; }, async versionAt() { return '0.60.70.0'; }, async contains() { return true; },
async provenance() { return { reused: false }; },
};
const v = await gate(d, { sha: A, version: '0.60.70.0', timeoutMs: 10 * 60_000, pollMs: 60_000, log: l => lines.push(l), sleep: async ms => { t += ms; }, now: () => t });
diff --git a/test/scripts/release-restamp.test.ts b/test/scripts/release-restamp.test.ts
index d174886e60..67efaebdb9 100644
--- a/test/scripts/release-restamp.test.ts
+++ b/test/scripts/release-restamp.test.ts
@@ -509,3 +509,163 @@ describe('release:restamp helpers', () => {
}
});
});
+
+const NOTICE = 'src/core/behavior-change-notice.ts';
+const LIMITS = 'scripts/module-size-limits.tsv';
+const POLICY_DIRECT = { '.gstack/ship-policy.json': JSON.stringify({ merge: 'direct' }) + '\n' };
+const SEED_ROW = " { since: '0.0.9.0', id: 'seed_row_abc', text: 'Seed.' },";
+const BRANCH_ROW = " { since: '0.1.1.0', id: 'faster_sync_abc', text: 'Sync is faster now.' },";
+const MASTER_ROW = " { since: '0.1.1.0', id: 'master_row_abc', text: 'Master change.' },";
+const noticeFile = (...rows: string[]) => ['export const BEHAVIOR_CHANGES: Array<{ since: string; id?: string; text: string | (() => string) }> = [', SEED_ROW, ...rows, '];', ''].join('\n');
+const limitsFile = (n: number) => `path\tlimit\tkind\tnote\nsrc/shared.ts\t10\tratchet\tshared\n${NOTICE}\t${n}\tratchet\tthe notice table\n`;
+const QUIET = { GBRAIN_RESTAMP_STEPS: '[]', GBRAIN_RESTAMP_CHECKS: '[]' };
+
+/** fixture() plus the BEHAVIOR_CHANGES table and its size row on master, fast-forwarded into the feature branch. */
+function noticeFixture(): Fixture {
+ const fx = fixture();
+ put(fx.master, { [NOTICE]: noticeFile(), [LIMITS]: limitsFile(10) });
+ commit(fx.master, 'notice table');
+ git(fx.master, 'push', '-q', 'origin', 'master');
+ git(fx.work, 'fetch', '-q', 'origin');
+ git(fx.work, 'merge', '-q', '--ff-only', 'origin/master');
+ return fx;
+}
+
+describe('release-restamp --stamp-only', () => {
+ function stampTree(): string {
+ const root = mkdtempSync(join(tmpdir(), 'gbrain-stamp-only-'));
+ roots.push(root);
+ put(root, {
+ ...stamps('0.1.0.0'),
+ 'CHANGELOG.md': changelog(release('0.1.0.0', '2026-01-01', 'First release 0.1.0.0.')),
+ [NOTICE]: "export const BEHAVIOR_CHANGES = [\n { since: '0.1.0.0', id: 'seed_row_abc', text: 'Seed.' },\n];\n",
+ 'docs/notes.md': '"version": "0.1.0.0"\n<!-- gbrain-plugin-tree-stamp: 0.1.0.0 -->\n',
+ 'plugin/README.md': '<!-- gbrain-plugin-tree-stamp: 0.1.0.0 -->\n# Plugin\n\nSince v0.1.0.0.\n',
+ 'plugin/skills/rules.json': '{\n "version": "0.1.0.0",\n "since": "0.1.0.0"\n}\n',
+ 'plugin/skills/other.json': '{\n "version": "2.0.0"\n}\n',
+ 'plugin/skills/helper.ts': 'export const v = { "version": "0.1.0.0" };\n',
+ 'plugin-variants/daily/README.md': '<!-- gbrain-plugin-tree-stamp: 0.1.0.0 -->\n',
+ 'plugin-variants/daily/.claude-plugin/plugin.json': '{\n "name": "daily",\n "version": "0.1.0.0"\n}\n',
+ 'plugin-variants/daily/.codex-plugin/plugin.json': '{\n "name": "daily",\n "version": "0.1.0.0"\n}\n',
+ 'templates/bootstrap/template-repo/README.md': '# Brain\n\n<!-- gbrain-template-stamp: 0.1.0.0 -->\nBuilt with 0.1.0.0.\n',
+ });
+ return root;
+ }
+
+ test('moves every STAMPS file and the plugin, plugin-variants and template stamp lines, nothing else', () => {
+ const root = stampTree();
+ const before = (p: string) => readFileSync(join(root, p), 'utf8');
+ const untouched = ['CHANGELOG.md', NOTICE, 'docs/notes.md', 'plugin/skills/other.json', 'plugin/skills/helper.ts'];
+ const snapshot = Object.fromEntries(untouched.map((p) => [p, before(p)]));
+ const r = restamp(root, ['--stamp-only', '0.1.1.0']);
+ expect(r.code).toBe(0);
+ const written = r.out.replace(/^.*file\(s\): /, '').split(', ').sort();
+ expect(written).toEqual([
+ '.claude-plugin/plugin.json', '.codex-plugin/plugin.json', 'BOOTSTRAP_FOR_AGENTS.md', 'VERSION', 'openclaw.plugin.json', 'package.json',
+ 'plugin-variants/daily/.claude-plugin/plugin.json', 'plugin-variants/daily/.codex-plugin/plugin.json', 'plugin-variants/daily/README.md',
+ 'plugin/README.md', 'plugin/skills/rules.json', 'templates/bootstrap/template-repo/README.md',
+ ].sort());
+ for (const s of STAMPS) expect(s.read(read(root, s.file))).toBe('0.1.1.0');
+ expect(read(root, 'plugin/README.md')).toBe('<!-- gbrain-plugin-tree-stamp: 0.1.1.0 -->\n# Plugin\n\nSince v0.1.0.0.\n');
+ expect(read(root, 'plugin/skills/rules.json')).toBe('{\n "version": "0.1.1.0",\n "since": "0.1.0.0"\n}\n');
+ expect(read(root, 'plugin-variants/daily/.codex-plugin/plugin.json')).toContain('"version": "0.1.1.0"');
+ expect(read(root, 'templates/bootstrap/template-repo/README.md')).toBe('# Brain\n\n<!-- gbrain-template-stamp: 0.1.1.0 -->\nBuilt with 0.1.0.0.\n');
+ for (const p of untouched) expect(read(root, p)).toBe(snapshot[p]!);
+
+ const again = restamp(root, ['--stamp-only', '0.1.1.0']);
+ expect(again.code).toBe(0);
+ expect(again.out).toContain('written to 0 file(s)');
+ });
+
+ test('refuses a version that is not four-part and a missing argument', () => {
+ const root = stampTree();
+ const bad = restamp(root, ['--stamp-only', 'banana']);
+ expect(bad.code).toBe(1);
+ expect(bad.out).toContain('--stamp-only needs a four-part version');
+ expect(read(root, 'VERSION')).toBe('0.1.0.0\n');
+ for (const v of ['0.1.1', '0.1.1.0-x']) expect(restamp(root, ['--stamp-only', v]).code).toBe(1);
+ expect(read(root, 'VERSION')).toBe('0.1.0.0\n');
+ expect(restamp(root, ['--stamp-only']).code).toBe(2);
+ });
+});
+
+describe('release:unstamp and merge: direct', () => {
+ test('a stamped branch with one CHANGELOG entry and one appended row converts in one commit after the merge', () => {
+ const fx = noticeFixture();
+ branchWork(fx, '0.1.1.0', { [NOTICE]: noticeFile(BRANCH_ROW), [LIMITS]: limitsFile(11), 'src/widgets.ts': 'export const W = 1;\n' });
+ landOnMaster(fx, '0.1.1.0', null, { [NOTICE]: noticeFile(MASTER_ROW), [LIMITS]: limitsFile(12) });
+ landOnMaster(fx, '0.1.2.0', null, POLICY_DIRECT);
+ const pre = head(fx.work);
+
+ const r = restamp(fx.work, ['--unstamp'], QUIET);
+ expect(r.code).toBe(0);
+ expect(r.out).toContain("unstamp: 0.1.1.0 -> master's 0.1.2.0; the entry is in changelog.d/feature.md and 1 row(s) in behavior-changes.d/ (faster_sync_abc)");
+ expect(subject(fx.work)).toBe('chore(release): unstamp onto master v0.1.2.0; versions are written at release');
+ expect(parents(fx.work, 'HEAD')).toBe(1);
+ expect(parents(fx.work, 'HEAD^')).toBe(2);
+ expect(git(fx.work, 'rev-parse', 'HEAD^^').trim()).toBe(pre);
+ expect(git(fx.work, 'rev-parse', 'HEAD^^2').trim()).toBe(git(fx.work, 'rev-parse', 'origin/master').trim());
+ expect(status(fx.work)).toBe('');
+ expect(existsSync(stateFile(fx.work))).toBe(false);
+
+ expect(read(fx.work, 'changelog.d/feature.md')).toBe('Widgets now sync twice as fast. Upgrade to v0.1.1.0.\n\n<!-- behavior-change: faster_sync_abc -->\n');
+ expect(read(fx.work, 'behavior-changes.d/faster_sync_abc.md')).toBe('Sync is faster now.\n');
+ for (const s of STAMPS) expect(s.read(read(fx.work, s.file))).toBe('0.1.2.0');
+ for (const p of ['VERSION', 'CHANGELOG.md', NOTICE, LIMITS]) expect(read(fx.work, p), p).toBe(git(fx.work, 'show', `origin/master:${p}`));
+ expect(git(fx.work, 'diff', '--name-only', 'origin/master', 'HEAD').trim().split('\n').sort()).toEqual(['behavior-changes.d/faster_sync_abc.md', 'changelog.d/feature.md', 'src/widgets.ts']);
+ expect(git(fx.work, 'diff', '--name-only', 'HEAD^', 'HEAD').trim().split('\n')).toContain('changelog.d/feature.md');
+ }, 120_000);
+
+ test('a branch that also edits a released CHANGELOG section is refused before any merge', () => {
+ const fx = noticeFixture();
+ const { preamble, sections } = splitChangelog(read(fx.work, 'CHANGELOG.md'));
+ put(fx.work, {
+ ...stamps('0.1.1.0'),
+ 'CHANGELOG.md': [preamble, release('0.1.1.0', '2026-10-03', 'Widgets.'), ...sections.map((s) => s.text.replace('First release.', 'First release, reworded.'))].join('\n'),
+ });
+ commit(fx.work, 'v0.1.1.0 feat: widgets');
+ landOnMaster(fx, '0.1.1.0', null, POLICY_DIRECT);
+ const pre = head(fx.work);
+ const r = restamp(fx.work, ['--unstamp'], QUIET);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('FAIL: this branch also edits released CHANGELOG sections');
+ expect(head(fx.work)).toBe(pre);
+ expect(status(fx.work)).toBe('');
+ expect(existsSync(stateFile(fx.work))).toBe(false);
+ expect(git(fx.work, 'rev-list', '--count', 'HEAD..origin/master').trim()).not.toBe('0');
+ }, 120_000);
+
+ test('refuses a branch with no entry, a function row, a row without an id and a non-append notice edit', () => {
+ const cases: Array<[string, Record<string, string>, string]> = [
+ ['no entry', { 'src/widgets.ts': 'export const W = 1;\n' }, "this branch has no CHANGELOG entry above origin/master's"],
+ ['function row', { [NOTICE]: noticeFile(" { since: '0.1.1.0', id: 'fn_row_abc', text: () => 'computed' },") }, 'appended row(s) compute their text (fn_row_abc)'],
+ ['row without id', { [NOTICE]: noticeFile(" { since: '0.1.1.0', text: 'No id.' },") }, 'have no id (line 3)'],
+ ['non-append edit', { [NOTICE]: noticeFile().replace("'Seed.'", "'Seed, reworded.'") }, 'beyond appending BEHAVIOR_CHANGES rows'],
+ ];
+ for (const [name, files, message] of cases) {
+ const fx = noticeFixture();
+ if (name === 'no entry') {
+ put(fx.work, files);
+ commit(fx.work, 'feat: widgets');
+ } else branchWork(fx, '0.1.1.0', files);
+ landOnMaster(fx, '0.1.1.0', null, POLICY_DIRECT);
+ const pre = head(fx.work);
+ const r = restamp(fx.work, ['--unstamp'], QUIET);
+ expect({ name, code: r.code, refused: r.out.includes(message) }).toEqual({ name, code: 1, refused: true });
+ expect(head(fx.work)).toBe(pre);
+ }
+ }, 120_000);
+
+ test('plain restamp is refused when origin/master says merge: direct', () => {
+ const fx = noticeFixture();
+ branchWork(fx, '0.1.1.0', {});
+ landOnMaster(fx, '0.1.1.0', null, POLICY_DIRECT);
+ const pre = head(fx.work);
+ const r = restamp(fx.work);
+ expect(r.code).toBe(1);
+ expect(r.out).toContain('FAIL: origin/master lands PRs directly and writes versions at release (.gstack/ship-policy.json merge: direct)');
+ expect(r.out).toContain('bun run release:unstamp');
+ expect(head(fx.work)).toBe(pre);
+ expect(existsSync(stateFile(fx.work))).toBe(false);
+ }, 120_000);
+});