Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(release): bun run release:restamp makes a branch next-to-merge in one command
garrytan6d52837a0555
diff --git a/package.json b/package.jsonindex 5c77b8ef0d..b4ac111f01 100644--- a/package.json+++ b/package.json@@ -157,6 +157,7 @@"check:compile-autoload": "bash scripts/check-compile-autoload.sh","check:structural-manifest": "bash scripts/check-structural-manifest.sh","regen:all": "bun scripts/regen-all.ts",+ "release:restamp": "bun scripts/release-restamp.ts","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/lib/restamp.ts b/scripts/lib/restamp.tsnew file mode 100644index 0000000000..1fe69b555b--- /dev/null+++ b/scripts/lib/restamp.ts@@ -0,0 +1,331 @@+/**+ * Pure helpers for `bun run release:restamp` (scripts/release-restamp.ts):+ * version arithmetic, CHANGELOG entry capture and re-insertion, version-stamp+ * rewriters for the CLAUDE.md "Version locations" table, schema-migration+ * renumbering with a payload identity check, the leftover-reference scan, and+ * version-only merge-conflict hunk resolution. No git, no filesystem, no+ * database: the CLI owns every side effect.+ */+import ts from 'typescript';+import { normalizeTokens } from './normalize-tokens.ts';++export const RESTAMP_DOCS = 'docs/RELEASING.md#release-restamp';+export const COLLISION_DOCS = 'docs/TESTING.md#schema-migration-registry';++export class RestampError extends Error {}++/** FAIL/Why/Fix/See block (agent operator protocol); thrown, printed by the CLI. */+export function fail(what: string, why: string, fix: string | string[], see = RESTAMP_DOCS): never {+ const fixLines = Array.isArray(fix) ? fix : [fix];+ throw new RestampError([`FAIL: ${what}`, `Why: ${why}`, ...fixLines.map((l, i) => `${i === 0 ? 'Fix: ' : ' '}${l}`), `See: ${see}`].join('\n'));+}++const VERSION_RE = /^(\d+)\.(\d+)\.(\d+)(?:\.(\d+))?(?:-[0-9A-Za-z.-]+)?$/;++/** master's MAJOR.MINOR.(PATCH+1).0 */+export function nextPatchVersion(masterVersion: string): string {+ const m = VERSION_RE.exec(masterVersion.trim());+ if (!m) {+ fail(`master's VERSION "${masterVersion.trim()}" is not MAJOR.MINOR.PATCH.MICRO`,+ 'restamp derives the branch version from master\'s VERSION file.',+ 'fix VERSION on master first (CLAUDE.md "Version locations"), then rerun: bun run release:restamp');+ }+ return `${m[1]}.${m[2]}.${Number(m[3]) + 1}.0`;+}++// ---------------------------------------------------------------- CHANGELOG++export interface ChangelogSection { header: string; text: string }++/** Split a Keep-a-Changelog file into the preamble and `## [` sections (each section text keeps its header line). */+export function splitChangelog(text: string): { preamble: string; sections: ChangelogSection[] } {+ const lines = text.split('\n');+ const starts = lines.flatMap((l, i) => (l.startsWith('## [') ? [i] : []));+ if (starts.length === 0) return { preamble: text, sections: [] };+ const preamble = lines.slice(0, starts[0]).join('\n');+ const sections = starts.map((s, k) => {+ const end = k + 1 < starts.length ? starts[k + 1]! : lines.length;+ return { header: lines[s]!, text: lines.slice(s, end).join('\n') };+ });+ return { preamble, sections };+}++/**+ * The branch's own CHANGELOG entry: the sections above the merge base's top+ * section header. Returns [] when the branch has not written one yet.+ */+export function branchEntrySections(branchText: string, baseText: string): ChangelogSection[] {+ const baseTop = splitChangelog(baseText).sections[0]?.header;+ const branch = splitChangelog(branchText).sections;+ if (!baseTop) return [];+ const idx = branch.findIndex((s) => s.header === baseTop);+ if (idx < 0) {+ fail(`CHANGELOG.md on this branch no longer contains the merge base's top entry "${baseTop}"`,+ 'restamp finds the branch\'s own entry as the sections above the newest entry the branch shares with master; a rewritten or reordered master entry hides it.',+ ['restore master\'s entries (git checkout origin/master -- CHANGELOG.md, then re-add only your entry on top), commit,',+ 'then rerun: bun run release:restamp']);+ }+ return branch.slice(0, idx);+}++export function versionOfHeader(header: string): string | null {+ return /^## \[([^\]]+)\]/.exec(header)?.[1] ?? null;+}++function replaceVersionToken(text: string, oldVersion: string, newVersion: string): string {+ const esc = oldVersion.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');+ return text.replace(new RegExp(`(?<![\\d.])${esc}(?![\\d.]*\\d)`, 'g'), newVersion);+}++/**+ * Put the branch entry back on top of `currentText` (the merged CHANGELOG),+ * re-stamped: header `## [new] - date`, every other mention of the branch's+ * old version inside the entry rewritten. A copy of the entry already in+ * `currentText` (a clean merge kept it, or an earlier restamp pass wrote it)+ * is removed first, so the rebuild is idempotent.+ */+export function rebuildChangelog(currentText: string, entry: ChangelogSection, oldVersion: string, newVersion: string, date: string): string {+ const { preamble, sections } = splitChangelog(currentText);+ const bodyOf = (text: string) => text.split('\n').slice(1).join('\n').replace(/\n+$/, '');+ const body = replaceVersionToken(bodyOf(entry.text), oldVersion, newVersion);+ const ours = new Set([bodyOf(entry.text), body]);+ const rest = sections.filter((s) => {+ const v = versionOfHeader(s.header);+ return !((v === oldVersion || v === newVersion) && ours.has(bodyOf(s.text)));+ });+ const stamped = `## [${newVersion}] - ${date}\n${body}\n`;+ return [preamble, stamped, ...rest.map((s) => s.text)].join('\n');+}++// ---------------------------------------------------------------- stamps++export interface Stamp {+ file: string;+ read(text: string): string | null;+ write(text: string, version: string): string;+}++function jsonVersionStamp(file: string): Stamp {+ return {+ file,+ read: (text) => {+ try {+ const v = (JSON.parse(text) as { version?: unknown }).version;+ return typeof v === 'string' ? v : null;+ } catch {+ return null;+ }+ },+ write(text, version) {+ const current = this.read(text);+ if (current === null) fail(`${file} has no top-level "version" string`, 'restamp rewrites that field in place.', `add "version": "${version}" to ${file}, then rerun with --continue`);+ return text.replace(`"version": "${current}"`, `"version": "${version}"`);+ },+ };+}++const RUNBOOK_STAMP = /<!-- gbrain-runbook-stamp: ([^ ]+) -->/;++/**+ * Hand-maintained rows of the CLAUDE.md "Version locations" Required table+ * (CHANGELOG.md, TODOS.md and the generated template repo are handled by the+ * CLI). test/scripts/release-restamp.test.ts fails when the table names a file+ * restamp does not cover.+ */+export const STAMPS: Stamp[] = [+ {+ file: 'VERSION',+ read: (text) => text.trim() || null,+ write: (text, version) => `${version}${text.endsWith('\n') ? '\n' : ''}`,+ },+ jsonVersionStamp('package.json'),+ jsonVersionStamp('openclaw.plugin.json'),+ jsonVersionStamp('.codex-plugin/plugin.json'),+ jsonVersionStamp('.claude-plugin/plugin.json'),+ {+ file: 'BOOTSTRAP_FOR_AGENTS.md',+ read: (text) => RUNBOOK_STAMP.exec(text)?.[1] ?? null,+ write: (text, version) => {+ if (!RUNBOOK_STAMP.test(text)) fail('BOOTSTRAP_FOR_AGENTS.md has no <!-- gbrain-runbook-stamp: X.Y.Z.W --> line', 'scripts/check-bootstrap-tag.sh requires it to equal VERSION.', `restore line 1 as <!-- gbrain-runbook-stamp: ${version} -->, then rerun with --continue`);+ return text.replace(RUNBOOK_STAMP, `<!-- gbrain-runbook-stamp: ${version} -->`);+ },+ },+];++/** Files restamp keeps in step beyond STAMPS (named so the coverage test can match the CLAUDE.md table). */+export const OTHER_STAMPED_FILES = ['CHANGELOG.md', 'TODOS.md', 'templates/bootstrap/template-repo/'];++/** Rewrite `vOLD` to `vNEW` in branch-added TODOS.md lines (1-based line numbers). */+export function restampTodoLines(text: string, addedLines: Set<number>, oldVersion: string, newVersion: string): string {+ if (oldVersion === newVersion) return text;+ return text.split('\n').map((l, i) => (addedLines.has(i + 1) ? l.split(`v${oldVersion}`).join(`v${newVersion}`) : l)).join('\n');+}++// ---------------------------------------------------------------- migrations++export const MIGRATIONS_DIR = 'src/core/schema-migrations';+export const MIGRATION_FILE_RE = /^v(\d{3,})-([a-z0-9]+(?:-[a-z0-9]+)*)\.ts$/;++export function padVersion(version: number): string {+ return String(version).padStart(3, '0');+}++interface MigrationLiteral { exportName: string; exportStart: number; version: number; versionStart: number; versionEnd: number }++function migrationLiteral(text: string, file: string): MigrationLiteral {+ const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, ts.ScriptKind.TS);+ for (const stmt of sf.statements) {+ if (!ts.isVariableStatement(stmt) || !stmt.modifiers?.some((m) => m.kind === ts.SyntaxKind.ExportKeyword)) continue;+ for (const d of stmt.declarationList.declarations) {+ if (!ts.isIdentifier(d.name) || !d.initializer || !ts.isObjectLiteralExpression(d.initializer) || d.type?.getText(sf) !== 'Migration') continue;+ for (const p of d.initializer.properties) {+ if (ts.isPropertyAssignment(p) && ts.isIdentifier(p.name) && p.name.text === 'version' && ts.isNumericLiteral(p.initializer)) {+ return { exportName: d.name.text, exportStart: d.name.getStart(sf), version: Number(p.initializer.text), versionStart: p.initializer.getStart(sf), versionEnd: p.initializer.getEnd() };+ }+ }+ }+ }+ return fail(`${file} has no \`export const v<NNN>: Migration = { version: <NNN>, ... }\``,+ 'restamp renumbers a migration by rewriting exactly its export name and version literal.',+ `fix the file so bun run build:schema-migrations accepts it, then rerun: bun run release:restamp`, COLLISION_DOCS);+}++/** Rewrite only the export identifier and the `version:` literal. */+export function renumberMigrationText(text: string, file: string, newVersion: number): string {+ const lit = migrationLiteral(text, file);+ const exportEnd = lit.exportStart + lit.exportName.length;+ return text.slice(0, lit.exportStart) + `v${padVersion(newVersion)}` + text.slice(exportEnd, lit.versionStart) + String(newVersion) + text.slice(lit.versionEnd);+}++/**+ * Payload identity key: the comment- and whitespace-insensitive token stream+ * with the export name and version literal replaced, so the same migration+ * under two numbers has the same key and any other edit changes it.+ */+export function migrationPayloadKey(text: string, file: string): string {+ const lit = migrationLiteral(text, file);+ const exportEnd = lit.exportStart + lit.exportName.length;+ const neutral = text.slice(0, lit.exportStart) + '__restamp_export__' + text.slice(exportEnd, lit.versionStart) + '0' + text.slice(lit.versionEnd);+ return normalizeTokens(neutral).join(' ');+}++export interface BranchMigration { path: string; version: number; slug: string }+export interface Renumber { from: BranchMigration; toVersion: number; toPath: string }++/** Branch migrations, in original version order, renumbered consecutively from masterMax + 1. */+export function planRenumber(branch: BranchMigration[], masterMax: number): Renumber[] {+ return [...branch]+ .sort((a, b) => a.version - b.version)+ .map((m, i) => ({ from: m, toVersion: masterMax + 1 + i, toPath: `${MIGRATIONS_DIR}/v${padVersion(masterMax + 1 + i)}-${m.slug}.ts` }))+ .filter((r) => r.toVersion !== r.from.version);+}++// ---------------------------------------------------------------- leftover references++export interface AddedLine { file: string; line: number; text: string }+export interface LeftoverRef extends AddedLine { oldVersion: number }++/** Generated or regenerated paths: never scanned for leftover references. */+export const GENERATED_PATHS = [+ `${MIGRATIONS_DIR}/registry.generated.ts`,+ 'test/fixtures/goldens/migrations/records.json',+ 'llms.txt',+ 'llms-full.txt',+ 'bun.lock',+ 'plugin/',+ 'plugin-variants/',+ 'templates/bootstrap/template-repo/',+];++export function isGenerated(path: string): boolean {+ return GENERATED_PATHS.some((g) => (g.endsWith('/') ? path.startsWith(g) : path === g));+}++/** Migration-reference shapes restamp lists (never rewrites): `v209`, `v209-name`, `migration 209`, `schema_version ... 209`, `version: 209`. */+export function referencePatterns(oldVersion: number): RegExp[] {+ const n = String(oldVersion);+ return [+ new RegExp(`\\bv0*${n}\\b`),+ new RegExp(`\\b(?:migrations?|schema[_ ]version|LATEST_VERSION|version)\\b[^0-9\\n]{0,12}\\b${n}\\b`, 'i'),+ ];+}++const OWN_CONSTANT_LINE = /^\s*(?:version:\s*\d+,?|export const v\d{3,}: Migration = \{)\s*$/;++/** Branch-added lines that still reference a renumbered migration's old number. */+export function findLeftoverRefs(added: AddedLine[], oldVersions: number[], renamedPaths: Set<string>): LeftoverRef[] {+ const out: LeftoverRef[] = [];+ for (const l of added) {+ if (isGenerated(l.file)) continue;+ if (renamedPaths.has(l.file) && OWN_CONSTANT_LINE.test(l.text)) continue;+ for (const v of oldVersions) {+ if (referencePatterns(v).some((re) => re.test(l.text))) {+ out.push({ ...l, oldVersion: v });+ break;+ }+ }+ }+ return out;+}++/** Parse `git diff -U0` output into the added lines with their new-file line numbers. */+export function parseAddedLines(diff: string): AddedLine[] {+ const out: AddedLine[] = [];+ let file = '';+ let line = 0;+ for (const raw of diff.split('\n')) {+ if (raw.startsWith('+++ ')) {+ file = raw === '+++ /dev/null' ? '' : raw.slice(4).replace(/^b\//, '');+ continue;+ }+ const hunk = /^@@ -\d+(?:,\d+)? \+(\d+)(?:,\d+)? @@/.exec(raw);+ if (hunk) {+ line = Number(hunk[1]);+ continue;+ }+ if (raw.startsWith('+') && file) {+ out.push({ file, line, text: raw.slice(1) });+ line++;+ }+ }+ return out;+}++// ---------------------------------------------------------------- merge conflicts++const ANY_VERSION = /\d+\.\d+\.\d+(?:\.\d+)?/g;++/**+ * Resolve conflict hunks whose two sides differ only in version strings+ * (keep ours: the stamps are rewritten right after). Returns the text and the+ * number of hunks left unresolved (their markers stay in place).+ */+export function resolveVersionOnlyHunks(text: string): { text: string; unresolved: number } {+ const lines = text.split('\n');+ const out: string[] = [];+ let unresolved = 0;+ for (let i = 0; i < lines.length; i++) {+ if (!lines[i]!.startsWith('<<<<<<< ')) {+ out.push(lines[i]!);+ continue;+ }+ const start = i;+ const ours: string[] = [];+ const theirs: string[] = [];+ let section: 'ours' | 'base' | 'theirs' = 'ours';+ for (i++; i < lines.length && !lines[i]!.startsWith('>>>>>>> '); i++) {+ const l = lines[i]!;+ if (section === 'ours' && l.startsWith('||||||| ')) section = 'base';+ else if (section !== 'theirs' && l === '=======') section = 'theirs';+ else if (section === 'ours') ours.push(l);+ else if (section === 'theirs') theirs.push(l);+ }+ const norm = (side: string[]) => side.join('\n').replace(ANY_VERSION, '<v>');+ if (norm(ours) === norm(theirs)) out.push(...ours);+ else {+ unresolved++;+ out.push(...lines.slice(start, i + 1));+ }+ }+ return { text: out.join('\n'), unresolved };+}diff --git a/scripts/release-restamp.ts b/scripts/release-restamp.tsnew file mode 100644index 0000000000..c2eeb11b86--- /dev/null+++ b/scripts/release-restamp.ts@@ -0,0 +1,567 @@+#!/usr/bin/env bun+/**+ * bun run release:restamp — make a branch next-to-merge in one command.+ *+ * bun run release:restamp merge origin/master, restamp, regenerate, check, commit+ * bun run release:restamp --dry-run print every planned edit; change nothing (fetches origin/master)+ * bun run release:restamp --no-commit same, but leave the restamp edits staged+ * bun run release:restamp --continue resume after resolving a stop (conflicts, references, generator, drift)+ * 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+ *+ * Steps: refuse a dirty tree; fetch origin/master; capture the branch's+ * CHANGELOG entry and migration inventory; merge origin/master with a merge+ * commit (version-only stamp hunks, CHANGELOG and generated files resolve+ * mechanically, anything else stops with the file list); set VERSION to+ * master's MAJOR.MINOR.(PATCH+1).0; renumber the branch's own schema+ * migrations (files origin/master does not have) consecutively from master's+ * latest + 1, changing only the filename, the export name and the `version:`+ * literal, with a payload identity check; rewrite every required stamp from+ * the CLAUDE.md "Version locations" table; run the generators; stop on any+ * branch-added line that still names an old migration number; run the+ * version and plugin/template drift checks; commit once. A second run with+ * nothing to change commits nothing. It never touches a database: generators+ * run with database URLs and provider keys removed.+ *+ * Test seams (test/scripts/release-restamp.test.ts): GBRAIN_RESTAMP_STEPS and+ * GBRAIN_RESTAMP_CHECKS (JSON arrays of { name, argv, env?, migrationsOnly? })+ * replace the generator and drift-check commands; GBRAIN_RESTAMP_DATE pins the+ * CHANGELOG date; GBRAIN_RESTAMP_PR_TITLE replaces the `gh pr view` lookup.+ *+ * 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 { join, resolve } from 'node:path';+import {+ COLLISION_DOCS, MIGRATION_FILE_RE, MIGRATIONS_DIR, RESTAMP_DOCS, RestampError, STAMPS,+ branchEntrySections, fail, findLeftoverRefs, isGenerated, migrationPayloadKey, nextPatchVersion, parseAddedLines,+ planRenumber, rebuildChangelog, renumberMigrationText, resolveVersionOnlyHunks, restampTodoLines, versionOfHeader,+ type BranchMigration, type ChangelogSection, type LeftoverRef, type Renumber,+} from './lib/restamp.ts';+import { offlineEnv } from './regen-all.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>]++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+version stamp (CLAUDE.md "Version locations"), regenerates derived files, runs the drift checks+and commits once. Run it when your PR is next to merge.++Migration renumbering changes only the filename, the \`export const v<NNN>\` name and the+\`version: <NNN>\` literal. Branch-added lines that still name an old number in one of these+shapes stop the run (they are listed, never rewritten):+ v<old> v<old>-<name> migration <old> schema_version ... <old> version: <old> LATEST_VERSION ... <old>++Docs: ${RESTAMP_DOCS}`;++export const DEFAULT_STEPS: Step[] = [+ { name: 'schema migration registry', argv: ['bun', 'run', 'scripts/build-schema-migrations.ts'] },+ { name: 'migrations golden (records.json)', argv: ['bun', 'test', 'test/migrations-golden.test.ts'], env: { GBRAIN_TEST_UPDATE_GOLDENS: '1' }, migrationsOnly: true },+ { name: 'bun.lock', argv: ['bun', 'install', '--lockfile-only'] },+ { name: 'bootstrap template repo', argv: ['bun', 'run', 'scripts/generate-template-repo.ts', '--out', 'templates/bootstrap/template-repo'] },+ { name: 'regen:all (plugin trees, llms, registries)', argv: ['bun', 'scripts/regen-all.ts'] },+];++export const DEFAULT_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: 'schema migration registry fresh', argv: ['bash', 'scripts/check-schema-migrations-fresh.sh'] },+ { name: 'schema migration order', argv: ['bun', 'scripts/check-schema-migration-order.ts'] },+];++interface State {+ phase: 'merge' | 'merge-conflict' | 'restamp';+ preHead: string;+ masterRef: string;+ branchVersion: string;+ entry: ChangelogSection | null;+ inventory: BranchMigration[];+ conflicted: string[];+ mapping: Array<{ from: number; to: number; fromPath: string; toPath: string }>;+ flaggedRefs: string[];+ merged: boolean;+}++class Ctx {+ constructor(readonly root: string, readonly log: (line: string) => void, readonly env: Record<string, string | undefined>) {}++ run(argv: string[], extraEnv: Record<string, string> = {}, input?: string): { code: number; out: string } {+ const r = Bun.spawnSync(argv, { cwd: this.root, env: { ...offlineEnv(this.env), GBRAIN_GUARD_ROOT: this.root, GBRAIN_BOOTSTRAP_GUARD_ROOT: this.root, ...extraEnv }, stdout: 'pipe', stderr: 'pipe', stdin: input === undefined ? 'ignore' : new TextEncoder().encode(input) });+ return { code: r.exitCode ?? 1, out: `${r.stdout.toString()}${r.stderr.toString()}` };+ }++ git(...args: string[]): string {+ const r = Bun.spawnSync(['git', ...args], { cwd: this.root, env: { ...this.env, GIT_MERGE_AUTOEDIT: 'no' } as Record<string, string>, stdout: 'pipe', stderr: 'pipe' });+ if (r.exitCode !== 0) throw new RestampError(`git ${args.join(' ')} failed (exit ${r.exitCode}): ${r.stderr.toString().trim()}`);+ return r.stdout.toString();+ }++ gitOk(...args: string[]): boolean {+ return Bun.spawnSync(['git', ...args], { cwd: this.root, stdout: 'ignore', stderr: 'ignore' }).exitCode === 0;+ }++ read(path: string): string {+ return readFileSync(join(this.root, path), 'utf8');+ }++ write(path: string, text: string): boolean {+ const file = join(this.root, path);+ if (existsSync(file) && readFileSync(file, 'utf8') === text) return false;+ writeFileSync(file, text);+ return true;+ }++ get statePath(): string {+ return resolve(this.root, this.git('rev-parse', '--git-path', 'gbrain-restamp.json').trim());+ }++ loadState(): State | null {+ return existsSync(this.statePath) ? (JSON.parse(readFileSync(this.statePath, 'utf8')) as State) : null;+ }++ saveState(state: State): void {+ writeFileSync(this.statePath, JSON.stringify(state, null, 2) + '\n');+ }++ steps(key: 'GBRAIN_RESTAMP_STEPS' | 'GBRAIN_RESTAMP_CHECKS', fallback: Step[]): Step[] {+ const raw = this.env[key];+ return raw ? (JSON.parse(raw) as Step[]) : fallback;+ }+}++const RESUME = ['then: bun run release:restamp --continue', 'or return to the pre-run commit: bun run release:restamp --abort'];++function stop(state: State, ctx: Ctx, what: string, why: string, fix: string[]): never {+ ctx.saveState(state);+ return fail(what, why, [...fix, ...RESUME]);+}++/** Blob text of `<ref>:<path>` for many paths in one git process. */+function catFiles(ctx: Ctx, ref: string, paths: string[]): Map<string, string> {+ const out = new Map<string, string>();+ if (paths.length === 0) return out;+ const r = Bun.spawnSync(['git', 'cat-file', '--batch'], { cwd: ctx.root, stdin: new TextEncoder().encode(paths.map((p) => `${ref}:${p}`).join('\n') + '\n'), stdout: 'pipe' });+ const buf = Buffer.from(r.stdout);+ let pos = 0;+ for (const p of paths) {+ const nl = buf.indexOf(10, pos);+ const header = buf.subarray(pos, nl).toString();+ pos = nl + 1;+ if (header.endsWith(' missing')) continue;+ const size = Number(header.split(' ')[2]);+ out.set(p, buf.subarray(pos, pos + size).toString('utf8'));+ pos += size + 1;+ }+ return out;+}++function migrationPaths(names: string[]): Array<{ path: string; version: number; slug: string }> {+ return names.flatMap((n) => {+ const m = MIGRATION_FILE_RE.exec(n);+ return m ? [{ path: `${MIGRATIONS_DIR}/${n}`, version: Number(m[1]), slug: m[2]! }] : [];+ });+}++interface MigrationAnalysis { masterMax: number; branch: BranchMigration[]; plan: Renumber[] }++/**+ * Split `head` migrations into published (on the master ref) and branch-only,+ * with the payload identity rules: a published file must keep master's+ * payload, and a branch file must not be a copy of a published one.+ */+function analyzeMigrations(ctx: Ctx, masterRef: string, head: Map<string, string>): MigrationAnalysis {+ const masterFiles = migrationPaths(ctx.git('ls-tree', '--name-only', `${masterRef}:${MIGRATIONS_DIR}`).split('\n'));+ const masterText = catFiles(ctx, masterRef, masterFiles.map((m) => m.path));+ const masterMax = Math.max(...masterFiles.map((m) => m.version));+ const masterKeys = new Map(masterFiles.map((m) => [migrationPayloadKey(masterText.get(m.path)!, m.path), m.path]));+ const branch: BranchMigration[] = [];+ for (const m of migrationPaths([...head.keys()].map((p) => p.slice(MIGRATIONS_DIR.length + 1)))) {+ const text = head.get(m.path)!;+ const published = masterText.get(m.path);+ if (published !== undefined) {+ if (published !== text && migrationPayloadKey(published, m.path) !== migrationPayloadKey(text, m.path)) {+ fail(`${m.path} is published on ${masterRef} but this branch changes its payload`,+ 'brains that already applied it never run it again, so an edit to a published migration silently never lands; restamp never renumbers or edits published migrations.',+ [`put the change in a new migration (bun run new:migration <name>) and restore the file: git checkout ${masterRef} -- ${m.path}`, 'commit, then rerun: bun run release:restamp'], COLLISION_DOCS);+ }+ continue;+ }+ const twin = masterKeys.get(migrationPayloadKey(text, m.path));+ if (twin) {+ fail(`${m.path} has the same payload as ${twin}, which ${masterRef} already publishes`,+ 'the migration already landed on master under another number (squash-merged or cherry-picked and renumbered); renumbering this copy would apply it twice.',+ [`drop this branch's copy: git rm ${m.path} && bun run build:schema-migrations`, `point references at ${twin}, commit, then rerun: bun run release:restamp`], COLLISION_DOCS);+ }+ branch.push(m);+ }+ return { masterMax, branch, plan: planRenumber(branch, masterMax) };+}++function workingMigrations(ctx: Ctx): Map<string, string> {+ const dir = join(ctx.root, MIGRATIONS_DIR);+ return new Map(readdirSync(dir).filter((n) => MIGRATION_FILE_RE.test(n)).map((n) => [`${MIGRATIONS_DIR}/${n}`, readFileSync(join(dir, n), 'utf8')]));+}++function headMigrations(ctx: Ctx): Map<string, string> {+ const names = ctx.git('ls-tree', '--name-only', `HEAD:${MIGRATIONS_DIR}`).split('\n').filter((n) => MIGRATION_FILE_RE.test(n));+ return catFiles(ctx, 'HEAD', names.map((n) => `${MIGRATIONS_DIR}/${n}`));+}++function addedLines(ctx: Ctx, from: string, to: string[] = []) {+ return parseAddedLines(ctx.git('diff', '-U0', '--no-renames', '--no-color', '--no-ext-diff', from, ...to));+}++function refKey(r: { file: string; text: string }): string {+ return `${r.file}\u0000${r.text}`;+}++function describeRefs(refs: LeftoverRef[], mapping: State['mapping']): string[] {+ return refs.map((r) => ` ${r.file}:${r.line}: ${r.text.trim()} (v${r.oldVersion} is now v${mapping.find((m) => m.from === r.oldVersion)?.to ?? '?'})`);+}++function prTitle(ctx: Ctx, version: string): string {+ const fromEnv = ctx.env.GBRAIN_RESTAMP_PR_TITLE;+ let current = fromEnv ?? '';+ if (fromEnv === undefined) {+ const r = Bun.spawnSync(['gh', 'pr', 'view', '--json', 'title', '--jq', '.title'], { cwd: ctx.root, stdout: 'pipe', stderr: 'ignore', timeout: 20_000 });+ current = r.exitCode === 0 ? r.stdout.toString().trim() : '';+ }+ if (!current) return `v${version} <type>(<scope>): <summary>`;+ return `v${version} ${current.replace(/^v?\d+\.\d+\.\d+(?:\.\d+)?(?:-\S+)?\s+/, '')}`;+}++function capture(ctx: Ctx, masterRef: string): 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) {+ 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 };+}++function merge(ctx: Ctx, state: State): void {+ if (ctx.gitOk('merge-base', '--is-ancestor', state.masterRef, 'HEAD')) {+ ctx.log(`restamp: branch already contains ${state.masterRef}; no merge needed.`);+ return;+ }+ Bun.spawnSync(['git', 'merge', '--no-ff', '--no-commit', state.masterRef], { cwd: ctx.root, env: { ...ctx.env, GIT_MERGE_AUTOEDIT: 'no' } as Record<string, string>, stdout: 'pipe', stderr: 'pipe' });+ const conflicted = ctx.git('diff', '--name-only', '--diff-filter=U').split('\n').filter(Boolean);+ const genuine: string[] = [];+ const stampFiles = new Set(STAMPS.map((s) => s.file));+ for (const f of conflicted) {+ if (f === 'CHANGELOG.md') {+ ctx.write(f, ctx.git('show', `${state.masterRef}:CHANGELOG.md`));+ } else if (isGenerated(f)) {+ if (!ctx.gitOk('checkout', '--theirs', '--', f)) {+ genuine.push(f);+ continue;+ }+ } else if (stampFiles.has(f) && existsSync(join(ctx.root, f))) {+ const r = resolveVersionOnlyHunks(ctx.read(f));+ if (r.unresolved > 0) {+ genuine.push(f);+ continue;+ }+ ctx.write(f, r.text);+ } else {+ genuine.push(f);+ continue;+ }+ ctx.git('add', '--', f);+ }+ state.merged = true;+ if (genuine.length > 0) {+ state.phase = 'merge-conflict';+ state.conflicted = genuine;+ stop(state, ctx, `merging ${state.masterRef} left ${genuine.length} conflict(s) restamp cannot resolve mechanically:\n${genuine.map((f) => ` ${f}`).join('\n')}`,+ 'version-only stamp hunks, CHANGELOG.md and generated files resolve mechanically; these files have real edits on both sides.',+ ['resolve each file, then git add <file> (do not commit; restamp writes the merge commit)']);+ }+ ctx.git('commit', '--no-edit', '--quiet');+ ctx.log(`restamp: merged ${state.masterRef} with a merge commit (${conflicted.length} conflict(s) resolved mechanically).`);+}++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)));+ if (unmerged.length > 0 || marked.length > 0) {+ stop(state, ctx, `conflicts are still unresolved: ${[...new Set([...unmerged, ...marked])].join(', ')}`,+ 'restamp writes the merge commit only after every conflicted file is resolved and staged.',+ ['remove the conflict markers, git add <file>']);+ }+ if (ctx.gitOk('rev-parse', '-q', '--verify', 'MERGE_HEAD')) ctx.git('commit', '--no-edit', '--quiet');+ state.phase = 'restamp';+ ctx.saveState(state);+}++function applyRenumber(ctx: Ctx, state: State, plan: Renumber[]): void {+ const staged = plan.map((r, i) => ({ r, tmp: `${MIGRATIONS_DIR}/.restamp-${i}-${r.from.slug}.ts` }));+ for (const { r, tmp } of staged) ctx.git('mv', r.from.path, tmp);+ for (const { r, tmp } of staged) {+ const before = ctx.read(tmp);+ const after = renumberMigrationText(before, r.toPath, r.toVersion);+ if (migrationPayloadKey(after, r.toPath) !== migrationPayloadKey(before, r.from.path)) {+ fail(`renumbering ${r.from.path} would change more than its version`, 'restamp may change only the filename, export name and version literal.', 'report this with the file attached; renumber it by hand (docs below), then rerun', COLLISION_DOCS);+ }+ writeFileSync(join(ctx.root, tmp), after);+ ctx.git('mv', tmp, r.toPath);+ ctx.git('add', '--', r.toPath);+ const prior = state.mapping.find((m) => m.to === r.from.version);+ if (prior) {+ prior.to = r.toVersion;+ prior.toPath = r.toPath;+ } else state.mapping.push({ from: r.from.version, to: r.toVersion, fromPath: r.from.path, toPath: r.toPath });+ }+}++interface Outcome { version: string; masterVersion: string }++function restampTree(ctx: Ctx, state: State, opts: { acceptRefs: boolean; date: string }): Outcome {+ const masterVersion = ctx.git('show', `${state.masterRef}:VERSION`).trim();+ const version = nextPatchVersion(masterVersion);++ const migrations = analyzeMigrations(ctx, state.masterRef, workingMigrations(ctx));+ applyRenumber(ctx, state, migrations.plan);+ ctx.saveState(state);++ for (const stamp of 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));+ if (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'))) {+ 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);+ ctx.write('TODOS.md', text);+ }++ const hasMigrations = migrations.branch.length > 0;+ for (const step of ctx.steps('GBRAIN_RESTAMP_STEPS', DEFAULT_STEPS)) {+ if (step.migrationsOnly && !hasMigrations) 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')}`,+ 'restamp regenerates every derived file after the version and migration edits; a failing generator leaves them stale.',+ [`run it directly (${step.argv.join(' ')}) and fix what it reports`]);+ }+ ctx.log(`restamp: regenerated ${step.name}`);+ }++ if (state.mapping.length > 0) {+ const renamed = new Set(state.mapping.map((m) => m.toPath));+ ctx.git('add', '-A');+ const flagged = new Set(state.flaggedRefs);+ let refs = findLeftoverRefs(addedLines(ctx, state.masterRef), state.mapping.map((m) => m.from), renamed);+ if (flagged.size > 0) refs = refs.filter((r) => flagged.has(refKey(r)));+ if (refs.length > 0 && opts.acceptRefs) {+ ctx.log(`restamp: kept ${refs.length} reference line(s) as written (--accept-references):\n${describeRefs(refs, state.mapping).join('\n')}`);+ state.flaggedRefs = [];+ } else if (refs.length > 0) {+ state.flaggedRefs = refs.map(refKey);+ stop(state, ctx, `${refs.length} line(s) this branch added still name a renumbered migration's old number:\n${describeRefs(refs, state.mapping).join('\n')}`,+ 'restamp renames only the migration file, its export name and its version literal; any other mention may mean the old migration or the published one that now owns that number, so it is listed instead of rewritten.',+ ['edit each line to the new number shown (an edited line is not listed again),',+ 'or, when a line means the published migration that now owns that number, add --accept-references to --continue']);+ }+ }++ const drift = driftProblems(ctx, version, masterVersion, state);+ for (const check of ctx.steps('GBRAIN_RESTAMP_CHECKS', DEFAULT_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')}`);+ }+ if (drift.length > 0) {+ stop(state, ctx, `drift check(s) failed after restamping to ${version}:\n${drift.map((d) => ` - ${d}`).join('\n')}`,+ '/ship\'s idempotency check and CI require every version stamp and generated tree to agree before the PR merges.',+ ['fix each item listed']);+ }+ return { version, masterVersion };+}++function driftProblems(ctx: Ctx, version: string, masterVersion: string, state: State): string[] {+ const out: string[] = [];+ for (const stamp of STAMPS) {+ const v = stamp.read(ctx.read(stamp.file));+ if (v !== version) out.push(`${stamp.file} says ${v ?? '<none>'}, expected ${version}`);+ }+ const top = /^## \[([^\]]+)\]/m.exec(ctx.read('CHANGELOG.md'))?.[1];+ if (top !== version) {+ out.push(state.entry+ ? `CHANGELOG.md top entry is ${top}, expected ${version}`+ : `CHANGELOG.md has no entry for this branch (top entry ${top} is master's); write one with /ship: \`## [${version}] - <date>\` on top`);+ }+ if (version === masterVersion) out.push(`VERSION ${version} is not newer than master's ${masterVersion}`);+ return out;+}++function printDryRun(ctx: Ctx, state: State, date: string): void {+ const masterVersion = ctx.git('show', `${state.masterRef}:VERSION`).trim();+ const version = nextPatchVersion(masterVersion);+ const L = ctx.log;+ L(`restamp --dry-run: nothing will be changed. ${state.masterRef} is at VERSION ${masterVersion}; this branch becomes ${version}.`);+ if (ctx.gitOk('merge-base', '--is-ancestor', state.masterRef, 'HEAD')) L(`Merge: the branch already contains ${state.masterRef}; no merge commit.`);+ else {+ const count = ctx.git('rev-list', '--count', `HEAD..${state.masterRef}`).trim();+ L(`Merge: would merge ${count} commit(s) from ${state.masterRef} with a merge commit.`);+ const r = Bun.spawnSync(['git', 'merge-tree', '--write-tree', '--name-only', '--no-messages', 'HEAD', state.masterRef], { cwd: ctx.root, stdout: 'pipe' });+ const files = r.stdout.toString().split('\n').slice(1).filter(Boolean);+ const stampFiles = new Set(STAMPS.map((s) => s.file));+ for (const f of files) {+ const how = f === 'CHANGELOG.md' ? 'mechanical: master\'s file plus this branch\'s entry on top'+ : isGenerated(f) ? 'mechanical: take master\'s side, then regenerate'+ : stampFiles.has(f) ? 'mechanical when the hunks differ only in version strings, otherwise a stop'+ : 'genuine: the run stops for you to resolve it, then --continue';+ L(` predicted conflict ${f} (${how})`);+ }+ }+ L('Edits:');+ for (const stamp of STAMPS) {+ const cur = stamp.read(ctx.git('show', `HEAD:${stamp.file}`));+ L(` ${stamp.file}: ${cur} -> ${version}${cur === version ? ' (unchanged)' : ''}`);+ }+ L(state.entry+ ? ` CHANGELOG.md: "${state.entry.header}" -> "## [${version}] - ${date}", kept above master's entries`+ : ' CHANGELOG.md: this branch has no entry yet; the drift check will stop until /ship writes one');+ L(` TODOS.md: branch-added lines naming v${state.branchVersion} -> v${version}`);+ const plan = planRenumber(state.inventory, analyzeMigrations(ctx, state.masterRef, headMigrations(ctx)).masterMax);+ if (plan.length === 0) L(`Migrations: ${state.inventory.length ? `${state.inventory.length} branch migration(s) already follow master's latest` : 'none on this branch'}; nothing to renumber.`);+ else {+ L('Migrations (filename, export name and version literal only):');+ for (const r of plan) L(` v${r.from.version} -> v${r.toVersion} ${r.from.path} -> ${r.toPath}`);+ const mergeBase = ctx.git('merge-base', 'HEAD', state.masterRef).trim();+ const refs = findLeftoverRefs(addedLines(ctx, mergeBase, ['HEAD']), plan.map((r) => r.from.version), new Set(plan.map((r) => r.from.path)));+ const mapping = plan.map((r) => ({ from: r.from.version, to: r.toVersion, fromPath: r.from.path, toPath: r.toPath }));+ if (refs.length) L(`References that will stop the run until edited:\n${describeRefs(refs, mapping).join('\n')}`);+ }+ L('Regenerate:');+ for (const s of ctx.steps('GBRAIN_RESTAMP_STEPS', DEFAULT_STEPS)) L(` ${s.argv.join(' ')}${s.migrationsOnly ? ' (branch has migrations only)' : ''}`);+ L('Drift checks:');+ for (const s of ctx.steps('GBRAIN_RESTAMP_CHECKS', DEFAULT_CHECKS)) L(` ${s.argv.join(' ')}`);+ L(`Commit: one commit "v${version} chore(release): restamp onto master v${masterVersion}" (--no-commit leaves it staged).`);+ L(`PR title: ${prTitle(ctx, version)}`);+ L('Run it: bun run release:restamp');+}++function report(ctx: Ctx, state: State, outcome: Outcome, committed: string | null, staged: boolean): void {+ const L = ctx.log;+ L(`restamp: ${state.branchVersion} -> ${outcome.version} (master ${outcome.masterVersion}).`);+ if (state.mapping.length > 0) {+ L('Migration renumbering (source only; no database was touched):');+ for (const m of state.mapping) L(` v${m.from} -> v${m.to} ${m.fromPath} -> ${m.toPath}`);+ L('If a database already applied an old number: a disposable dev DB is rebuilt and replayed;');+ L('retained data needs explicit schema_version reconciliation, never a counter edit.');+ L(` Collision recovery: ${COLLISION_DOCS}`);+ L('Golden regeneration reason (PR body): test/fixtures/goldens/migrations/records.json regenerated by release:restamp for the renumbered migrations listed above.');+ }+ L(`Drift checks: VERSION, package.json, plugin manifests, BOOTSTRAP stamp, CHANGELOG, plugin and template trees agree on ${outcome.version}.`);+ if (committed) L(`Committed ${committed.slice(0, 12)}: v${outcome.version} chore(release): restamp onto master v${outcome.masterVersion}`);+ else if (!staged) L(`Nothing to change: the branch was already restamped onto current master${state.merged ? ' (only the merge commit was added)' : ''}; no restamp commit.`);+ else L(`Edits are staged (--no-commit). Commit them: git commit -m "v${outcome.version} chore(release): restamp onto master v${outcome.masterVersion}"`);+ L(`PR title: ${prTitle(ctx, outcome.version)} (set it: gh pr edit --title "<that title>")`);+ L('Verify: bun run verify (full gate before merge: bun run ci:ubicloud or bun run ci:local), then git push');+}++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;+ 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 valueOf = (flag: string, fallback: string) => (argv.includes(flag) ? argv[argv.indexOf(flag) + 1] ?? '' : fallback);+ const remote = valueOf('--remote', 'origin');+ const base = valueOf('--base', 'master');+ const stray = argv.filter((a, i) => !a.startsWith('--') && argv[i - 1] !== '--remote' && argv[i - 1] !== '--base');+ if (flags.has('--help')) {+ 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'))) {+ log(USAGE);+ return 2;+ }+ const top = Bun.spawnSync(['git', 'rev-parse', '--show-toplevel'], { cwd: opts.cwd ?? process.cwd(), stdout: 'pipe', stderr: 'pipe' });+ if (top.exitCode !== 0) {+ log(`FAIL: not inside a git checkout\nWhy: restamp edits and commits the current branch.\nFix: cd into your gbrain checkout and rerun: bun run release:restamp\nSee: ${RESTAMP_DOCS}`);+ return 1;+ }+ const ctx = new Ctx(top.stdout.toString().trim(), log, env);+ const date = env.GBRAIN_RESTAMP_DATE ?? new Date().toISOString().slice(0, 10);+ try {+ let state = ctx.loadState();+ if (flags.has('--abort')) {+ if (!state) fail('no restamp is in progress', 'there is no saved pre-run commit to return to.', 'nothing to abort; run: bun run release:restamp');+ if (ctx.gitOk('rev-parse', '-q', '--verify', 'MERGE_HEAD')) ctx.git('merge', '--abort');+ ctx.git('reset', '--hard', '--quiet', state.preHead);+ rmSync(ctx.statePath);+ const left = ctx.git('status', '--porcelain').trim();+ log(`restamp --abort: returned to ${state.preHead.slice(0, 12)}.${left ? ` Untracked files restamp did not create remain:\n${left}` : ''}`);+ return 0;+ }+ if (flags.has('--continue')) {+ if (!state) fail('no restamp is in progress', '--continue resumes a run that stopped.', 'start one: bun run release:restamp');+ if (state.phase === 'merge-conflict' || ctx.gitOk('rev-parse', '-q', '--verify', 'MERGE_HEAD')) finishMerge(ctx, state);+ else if (state.phase === 'merge') merge(ctx, state);+ } else {+ if (state) {+ fail(`a restamp is already in progress (stopped in phase "${state.phase}")`, 'starting over would lose the saved pre-run commit and migration mapping.',+ ['finish it: bun run release:restamp --continue', 'or return to the pre-run commit: bun run release:restamp --abort']);+ }+ const dirty = ctx.git('status', '--porcelain').trim();+ if (dirty && !flags.has('--dry-run')) {+ fail(`the working tree is not clean:\n${dirty.split('\n').slice(0, 10).map((l) => ` ${l}`).join('\n')}`,+ 'restamp commits its own edits as one commit and --abort resets to the pre-run commit; uncommitted work would be swept in or lost.',+ 'commit or stash your changes (git stash -u), then rerun: bun run release:restamp');+ }+ const fetch = Bun.spawnSync(['git', 'fetch', '--quiet', remote, `+refs/heads/${base}:refs/remotes/${remote}/${base}`], { cwd: ctx.root, stdout: 'pipe', stderr: 'pipe' });+ if (fetch.exitCode !== 0) {+ fail(`could not fetch ${remote}/${base}: ${fetch.stderr.toString().trim().split('\n').pop()}`,+ '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}`);+ if (flags.has('--dry-run')) {+ printDryRun(ctx, state, date);+ return 0;+ }+ ctx.saveState(state);+ merge(ctx, state);+ state.phase = 'restamp';+ ctx.saveState(state);+ }+ const outcome = restampTree(ctx, state, { acceptRefs: flags.has('--accept-references'), date });+ ctx.git('add', '-A');+ const staged = !ctx.gitOk('diff', '--cached', '--quiet');+ 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}`);+ committed = ctx.git('rev-parse', 'HEAD').trim();+ }+ rmSync(ctx.statePath, { force: true });+ report(ctx, state, outcome, committed, staged);+ return 0;+ } catch (e) {+ if (e instanceof RestampError) {+ log(e.message);+ return 1;+ }+ throw e;+ }+}++if (import.meta.main) process.exit(main(process.argv.slice(2)));diff --git a/test/scripts/release-restamp.test.ts b/test/scripts/release-restamp.test.tsnew file mode 100644index 0000000000..395c0ec43a--- /dev/null+++ b/test/scripts/release-restamp.test.ts@@ -0,0 +1,487 @@+/**+ * `bun run release:restamp` (scripts/release-restamp.ts) against throwaway git+ * repositories: a bare origin, a master clone that lands competing releases,+ * and a work clone holding the branch. The generator and drift-check commands+ * are replaced through GBRAIN_RESTAMP_STEPS / GBRAIN_RESTAMP_CHECKS with the+ * real schema-migration registry generator, registry freshness check and+ * migration-order guard, pointed at the fixture.+ *+ * Fixtures: collision-heavy branch (concurrent CHANGELOG entry, colliding+ * version and migration, TODO stamp) within the 5-minute target, idempotent+ * second run, repeated restamp after master moves again, squash-merged and+ * cherry-picked migrations, a decoy integer, leftover references, genuine+ * conflicts with --continue / --abort, dirty tree, offline fetch, --dry-run,+ * --no-commit, a missing CHANGELOG entry, and the CLAUDE.md coverage contract.+ */+import { afterAll, describe, expect, test } from 'bun:test';+import { execFileSync } from 'node:child_process';+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { dirname, join } from 'node:path';+import { main } from '../../scripts/release-restamp.ts';+import {+ COLLISION_DOCS, OTHER_STAMPED_FILES, RESTAMP_DOCS, STAMPS, findLeftoverRefs, migrationPayloadKey, nextPatchVersion,+ rebuildChangelog, renumberMigrationText, resolveVersionOnlyHunks, splitChangelog,+} from '../../scripts/lib/restamp.ts';++const REPO = join(import.meta.dir, '..', '..');+const GEN = join(REPO, 'scripts', 'build-schema-migrations.ts');+const ORDER = join(REPO, 'scripts', 'check-schema-migration-order.ts');+const DIR = 'src/core/schema-migrations';+const roots: string[] = [];+afterAll(() => {+ for (const r of roots) rmSync(r, { recursive: true, force: true });+});++function git(cwd: string, ...args: string[]): string {+ return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });+}++function put(root: string, files: Record<string, string | null>): void {+ for (const [path, text] of Object.entries(files)) {+ const file = join(root, path);+ if (text === null) {+ rmSync(file, { force: true });+ continue;+ }+ mkdirSync(dirname(file), { recursive: true });+ writeFileSync(file, text);+ }+}++function read(root: string, path: string): string {+ return readFileSync(join(root, path), 'utf8');+}++function migration(version: number, name: string, sql = `CREATE TABLE IF NOT EXISTS ${name} (id INT);`, comment = ''): string {+ return `import type { Migration } from './types.ts';\n\n${comment}export const v${String(version).padStart(3, '0')}: Migration = {\n version: ${version},\n name: '${name}',\n idempotent: true,\n sql: \`\n ${sql}\n \`,\n};\n`;+}++function migrationFile(version: number, name: string): string {+ return `${DIR}/v${String(version).padStart(3, '0')}-${name.replace(/_/g, '-')}.ts`;+}++function release(version: string, date: string, body: string): string {+ return `## [${version}] - ${date}\n\n${body}\n`;+}++function stamps(version: string): Record<string, string> {+ const json = (name: string) => `{\n "name": "${name}",\n "version": "${version}"\n}\n`;+ return {+ VERSION: `${version}\n`,+ 'package.json': `{\n "name": "fixture",\n "version": "${version}",\n "dependencies": {}\n}\n`,+ 'openclaw.plugin.json': json('openclaw-fixture'),+ '.codex-plugin/plugin.json': json('codex-fixture'),+ '.claude-plugin/plugin.json': json('claude-fixture'),+ 'BOOTSTRAP_FOR_AGENTS.md': `<!-- gbrain-runbook-stamp: ${version} -->\n# Bootstrap\n`,+ };+}++function changelog(...entries: string[]): string {+ return `# Changelog\n\nAll notable changes.\n\n${entries.join('\n')}`;+}++function regen(root: string): void {+ execFileSync('bun', [GEN, '--dir', DIR], { cwd: root, stdio: 'ignore' });+}++function commit(root: string, message: string): void {+ git(root, 'add', '-A');+ git(root, 'commit', '-q', '-m', message);+}++interface Fixture { origin: string; master: string; work: string }++/** origin (bare) seeded with v0.1.0.0 and migrations 207-208; `master` lands releases; `work` holds the branch. */+function fixture(): Fixture {+ const root = mkdtempSync(join(tmpdir(), 'gbrain-restamp-'));+ roots.push(root);+ const origin = join(root, 'origin.git');+ const master = join(root, 'master');+ const work = join(root, 'work');+ git(root, 'init', '-q', '--bare', '-b', 'master', origin);+ git(root, 'clone', '-q', origin, master);+ for (const r of [master]) {+ git(r, 'config', 'user.email', '[email protected]');+ git(r, 'config', 'user.name', 't');+ git(r, 'checkout', '-q', '-b', 'master');+ }+ put(master, {+ ...stamps('0.1.0.0'),+ 'CHANGELOG.md': changelog(release('0.1.0.0', '2026-01-01', 'First release.')),+ 'TODOS.md': '# TODOS\n',+ 'src/shared.ts': 'export const GREETING = "hello";\n',+ [`${DIR}/types.ts`]: 'export interface Migration { version: number; name: string; idempotent?: boolean; sql?: string }\n',+ [migrationFile(207, 'seed_one')]: migration(207, 'seed_one'),+ [migrationFile(208, 'seed_two')]: migration(208, 'seed_two'),+ });+ regen(master);+ commit(master, 'v0.1.0.0 seed');+ git(master, 'push', '-q', 'origin', 'master');+ git(root, 'clone', '-q', origin, work);+ git(work, 'config', 'user.email', '[email protected]');+ git(work, 'config', 'user.name', 't');+ git(work, 'checkout', '-q', '-b', 'feature');+ return { origin, master, work };+}++/** master ships `version` with one migration and a CHANGELOG entry. */+function landOnMaster(fx: Fixture, version: string, mig: [number, string] | null, extra: Record<string, string | null> = {}): void {+ const prev = read(fx.master, 'CHANGELOG.md');+ const { preamble, sections } = splitChangelog(prev);+ put(fx.master, {+ ...stamps(version),+ 'CHANGELOG.md': [preamble, release(version, '2026-10-04', `Master release ${version}.`), ...sections.map((s) => s.text)].join('\n'),+ ...(mig ? { [migrationFile(mig[0], mig[1])]: migration(mig[0], mig[1]) } : {}),+ ...extra,+ });+ regen(fx.master);+ commit(fx.master, `v${version} master release`);+ git(fx.master, 'push', '-q', 'origin', 'master');+}++/** The branch bumps to `version`, writes its CHANGELOG entry and adds `files`. */+function branchWork(fx: Fixture, version: string, files: Record<string, string | null>, body = 'Widgets now sync twice as fast.'): void {+ const { preamble, sections } = splitChangelog(read(fx.work, 'CHANGELOG.md'));+ put(fx.work, {+ ...stamps(version),+ 'CHANGELOG.md': [preamble, release(version, '2026-10-03', `${body} Upgrade to v${version}.`), ...sections.map((s) => s.text)].join('\n'),+ ...files,+ });+ regen(fx.work);+ commit(fx.work, `v${version} feat: widgets`);+}++const STEPS = JSON.stringify([{ name: 'schema migration registry', argv: ['bun', GEN, '--dir', DIR] }]);+const CHECKS = JSON.stringify([+ { name: 'schema migration registry fresh', argv: ['bun', GEN, '--dir', DIR, '--check'] },+ { name: 'schema migration order', argv: ['bun', ORDER] },+]);++function restamp(cwd: string, args: string[] = [], env: Record<string, string> = {}): { code: number; out: string } {+ const lines: string[] = [];+ const code = main(args, {+ cwd,+ log: (l) => lines.push(l),+ env: { ...process.env, GBRAIN_RESTAMP_STEPS: STEPS, GBRAIN_RESTAMP_CHECKS: CHECKS, GBRAIN_RESTAMP_DATE: '2026-10-05', GBRAIN_RESTAMP_PR_TITLE: 'v0.1.1.0 feat(sync): faster widgets', ...env },+ });+ return { code, out: lines.join('\n') };+}++const head = (r: string) => git(r, 'rev-parse', 'HEAD').trim();+const subject = (r: string, rev = 'HEAD') => git(r, 'log', '-1', '--format=%s', rev).trim();+const parents = (r: string, rev: string) => git(r, 'log', '-1', '--format=%P', rev).trim().split(' ').filter(Boolean).length;+const status = (r: string) => git(r, 'status', '--porcelain').trim();+const stateFile = (r: string) => join(r, '.git', 'gbrain-restamp.json');++describe('release:restamp end to end', () => {+ test('collision-heavy branch: concurrent CHANGELOG entry, colliding version and migration, finishes within 5 minutes', () => {+ const started = performance.now();+ const fx = fixture();+ branchWork(fx, '0.1.1.0', {+ [migrationFile(209, 'branch_widgets')]: migration(209, 'branch_widgets'),+ 'TODOS.md': '# TODOS\n\n## Widget follow-ups (follow-up from v0.1.1.0)\n',+ 'src/shared.ts': 'export const GREETING = "hello";\nexport const WIDGETS = true;\n',+ });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets']);+ const before = read(fx.work, migrationFile(209, 'branch_widgets'));++ const r = restamp(fx.work);+ expect(r.code).toBe(0);+ expect(performance.now() - started).toBeLessThan(300_000);++ expect(subject(fx.work)).toBe('v0.1.2.0 chore(release): restamp onto master v0.1.1.0');+ expect(parents(fx.work, 'HEAD^')).toBe(2);+ expect(status(fx.work)).toBe('');+ expect(existsSync(stateFile(fx.work))).toBe(false);+ for (const s of STAMPS) expect(s.read(read(fx.work, s.file))).toBe('0.1.2.0');++ const log = splitChangelog(read(fx.work, 'CHANGELOG.md')).sections;+ expect(log.map((s) => s.header)).toEqual(['## [0.1.2.0] - 2026-10-05', '## [0.1.1.0] - 2026-10-04', '## [0.1.0.0] - 2026-01-01']);+ expect(log[0]!.text).toContain('Widgets now sync twice as fast. Upgrade to v0.1.2.0.');+ expect(log[1]!.text).toContain('Master release 0.1.1.0.');+ expect(read(fx.work, 'TODOS.md')).toContain('(follow-up from v0.1.2.0)');++ expect(existsSync(join(fx.work, migrationFile(209, 'branch_widgets')))).toBe(false);+ const moved = read(fx.work, migrationFile(210, 'branch_widgets'));+ expect(moved).toContain('export const v210: Migration');+ expect(moved).toContain('version: 210,');+ expect(migrationPayloadKey(moved, 'x.ts')).toBe(migrationPayloadKey(before, 'x.ts'));+ expect(read(fx.work, migrationFile(209, 'master_gadgets'))).toBe(migration(209, 'master_gadgets'));+ expect(read(fx.work, `${DIR}/registry.generated.ts`)).toContain("import { v210 } from './v210-branch-widgets.ts';");+ expect(read(fx.work, 'src/shared.ts')).toContain('WIDGETS');++ expect(r.out).toContain(`v209 -> v210 ${migrationFile(209, 'branch_widgets')} -> ${migrationFile(210, 'branch_widgets')}`);+ expect(r.out).toContain(COLLISION_DOCS);+ expect(r.out).toContain('no database was touched');+ expect(r.out).toContain('PR title: v0.1.2.0 feat(sync): faster widgets');+ expect(r.out).toContain('Verify: bun run verify');++ const again = restamp(fx.work);+ expect(again.code).toBe(0);+ expect(again.out).toContain('Nothing to change');+ expect(subject(fx.work)).toBe('v0.1.2.0 chore(release): restamp onto master v0.1.1.0');+ }, 300_000);++ test('repeated restamp after master moves again renumbers and re-stamps once more', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { [migrationFile(209, 'branch_widgets')]: migration(209, 'branch_widgets') });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets']);+ expect(restamp(fx.work).code).toBe(0);+ landOnMaster(fx, '0.1.2.0', [210, 'master_sprockets']);++ const r = restamp(fx.work);+ expect(r.code).toBe(0);+ expect(subject(fx.work)).toBe('v0.1.3.0 chore(release): restamp onto master v0.1.2.0');+ expect(existsSync(join(fx.work, migrationFile(211, 'branch_widgets')))).toBe(true);+ expect(existsSync(join(fx.work, migrationFile(210, 'branch_widgets')))).toBe(false);+ const headers = splitChangelog(read(fx.work, 'CHANGELOG.md')).sections.map((s) => s.header);+ expect(headers).toEqual(['## [0.1.3.0] - 2026-10-05', '## [0.1.2.0] - 2026-10-04', '## [0.1.1.0] - 2026-10-04', '## [0.1.0.0] - 2026-01-01']);+ expect(read(fx.work, 'CHANGELOG.md')).toContain('Upgrade to v0.1.3.0.');+ }, 120_000);++ test('a migration squash-merged to master at the same path is published: never renumbered', () => {+ const fx = fixture();+ const shared = { [migrationFile(209, 'shared_index')]: migration(209, 'shared_index') };+ branchWork(fx, '0.1.1.0', { ...shared, [migrationFile(210, 'branch_extra')]: migration(210, 'branch_extra') });+ landOnMaster(fx, '0.1.1.0', null, shared);+ const r = restamp(fx.work);+ expect(r.code).toBe(0);+ expect(read(fx.work, migrationFile(209, 'shared_index'))).toBe(migration(209, 'shared_index'));+ expect(existsSync(join(fx.work, migrationFile(210, 'branch_extra')))).toBe(true);+ expect(r.out).not.toContain('Migration renumbering');+ }, 120_000);++ test('a branch copy of a migration master published under another number stops before touching anything', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { [migrationFile(209, 'shared_index')]: migration(209, 'shared_index') });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets'], { [migrationFile(210, 'shared_index')]: migration(210, 'shared_index') });+ const pre = head(fx.work);+ const r = restamp(fx.work);+ expect(r.code).toBe(1);+ expect(r.out).toContain(`FAIL: ${migrationFile(209, 'shared_index')} has the same payload as ${migrationFile(210, 'shared_index')}`);+ expect(r.out).toContain(`Fix: drop this branch's copy: git rm ${migrationFile(209, 'shared_index')}`);+ expect(head(fx.work)).toBe(pre);+ expect(existsSync(stateFile(fx.work))).toBe(false);+ }, 120_000);++ test('a cherry-picked master migration stays put while the branch migration it collides with moves', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { [migrationFile(209, 'branch_widgets')]: migration(209, 'branch_widgets') });+ landOnMaster(fx, '0.1.1.0', [209, 'master_hotfix']);+ git(fx.work, 'fetch', '-q', 'origin');+ const pick = git(fx.work, 'rev-parse', 'origin/master').trim();+ put(fx.work, { [migrationFile(209, 'master_hotfix')]: git(fx.work, 'show', `${pick}:${migrationFile(209, 'master_hotfix')}`) });+ commit(fx.work, 'cherry-pick master hotfix migration');+ const r = restamp(fx.work);+ expect(r.code).toBe(0);+ expect(read(fx.work, migrationFile(209, 'master_hotfix'))).toBe(migration(209, 'master_hotfix'));+ expect(read(fx.work, migrationFile(210, 'branch_widgets'))).toContain('version: 210,');+ }, 120_000);++ test('a decoy integer equal to the old number is never rewritten and does not stop the run', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', {+ [migrationFile(209, 'retry_budget')]: migration(209, 'retry_budget', 'ALTER TABLE jobs ADD COLUMN IF NOT EXISTS max_attempts INTEGER DEFAULT 209;'),+ 'src/limits.ts': 'export const MAX_ATTEMPTS = 209;\n',+ });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets']);+ const r = restamp(fx.work);+ expect(r.code).toBe(0);+ const moved = read(fx.work, migrationFile(210, 'retry_budget'));+ expect(moved).toContain('version: 210,');+ expect(moved).toContain('DEFAULT 209;');+ expect(read(fx.work, 'src/limits.ts')).toBe('export const MAX_ATTEMPTS = 209;\n');+ }, 120_000);++ test('leftover references stop the run, are listed, and --continue resumes once they are edited', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', {+ [migrationFile(209, 'branch_widgets')]: migration(209, 'branch_widgets'),+ 'test/widgets.test.ts': "import { v209 } from '../src/core/schema-migrations/v209-branch-widgets.ts';\n",+ 'docs/widgets.md': '# Widgets\n\nMigration v209 adds the widgets table.\nIt applies after migration 208.\n',+ });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets']);+ const r = restamp(fx.work);+ expect(r.code).toBe(1);+ expect(r.out).toContain("2 line(s) this branch added still name a renumbered migration's old number");+ expect(r.out).toContain('test/widgets.test.ts:1:');+ expect(r.out).toContain('docs/widgets.md:3: Migration v209 adds the widgets table. (v209 is now v210)');+ expect(r.out).toContain('then: bun run release:restamp --continue');+ expect(read(fx.work, 'test/widgets.test.ts')).toContain('v209-branch-widgets.ts');+ expect(existsSync(stateFile(fx.work))).toBe(true);++ expect(restamp(fx.work).out).toContain('a restamp is already in progress');+ put(fx.work, { 'test/widgets.test.ts': "import { v210 } from '../src/core/schema-migrations/v210-branch-widgets.ts';\n" });+ const partial = restamp(fx.work, ['--continue']);+ expect(partial.code).toBe(1);+ expect(partial.out).toContain('1 line(s) this branch added');+ const done = restamp(fx.work, ['--continue', '--accept-references']);+ expect(done.code).toBe(0);+ expect(done.out).toContain('kept 1 reference line(s) as written');+ expect(subject(fx.work)).toBe('v0.1.2.0 chore(release): restamp onto master v0.1.1.0');+ expect(status(fx.work)).toBe('');+ }, 120_000);++ test('a genuine conflict stops with the file list; --continue writes the merge commit after it is resolved', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { 'src/shared.ts': 'export const GREETING = "hi from the branch";\n' });+ landOnMaster(fx, '0.1.1.0', null, { 'src/shared.ts': 'export const GREETING = "hi from master";\n' });+ const r = restamp(fx.work);+ expect(r.code).toBe(1);+ expect(r.out).toContain("conflict(s) restamp cannot resolve mechanically:\n src/shared.ts");+ expect(r.out).not.toContain('CHANGELOG.md\n');+ expect(restamp(fx.work, ['--continue']).out).toContain('conflicts are still unresolved: src/shared.ts');+ put(fx.work, { 'src/shared.ts': 'export const GREETING = "hi from both";\n' });+ git(fx.work, 'add', 'src/shared.ts');+ const done = restamp(fx.work, ['--continue']);+ expect(done.code).toBe(0);+ expect(parents(fx.work, 'HEAD^')).toBe(2);+ expect(splitChangelog(read(fx.work, 'CHANGELOG.md')).sections.map((s) => s.header)[0]).toBe('## [0.1.2.0] - 2026-10-05');+ }, 120_000);++ test('--abort returns to the pre-run commit', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { 'src/shared.ts': 'export const GREETING = "hi from the branch";\n' });+ landOnMaster(fx, '0.1.1.0', null, { 'src/shared.ts': 'export const GREETING = "hi from master";\n' });+ const pre = head(fx.work);+ expect(restamp(fx.work).code).toBe(1);+ const r = restamp(fx.work, ['--abort']);+ expect(r.code).toBe(0);+ expect(r.out).toContain(`returned to ${pre.slice(0, 12)}`);+ expect(head(fx.work)).toBe(pre);+ expect(status(fx.work)).toBe('');+ expect(existsSync(stateFile(fx.work))).toBe(false);+ expect(restamp(fx.work, ['--abort']).out).toContain('FAIL: no restamp is in progress');+ }, 120_000);++ test('refuses a dirty tree and reports an unreachable remote with the next step', () => {+ const fx = fixture();+ put(fx.work, { 'scratch.txt': 'wip\n' });+ const dirty = restamp(fx.work);+ expect(dirty.code).toBe(1);+ expect(dirty.out).toContain('FAIL: the working tree is not clean');+ expect(dirty.out).toContain('git stash -u');+ rmSync(join(fx.work, 'scratch.txt'));+ git(fx.work, 'remote', 'set-url', 'origin', join(fx.origin, 'missing.git'));+ const offline = restamp(fx.work);+ expect(offline.code).toBe(1);+ expect(offline.out).toContain('FAIL: could not fetch origin/master');+ expect(offline.out).toContain('git fetch origin master && bun run release:restamp');+ }, 120_000);++ test('--dry-run prints every planned edit and changes nothing', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', {+ [migrationFile(209, 'branch_widgets')]: migration(209, 'branch_widgets'),+ 'docs/widgets.md': 'Migration v209 adds widgets.\n',+ });+ landOnMaster(fx, '0.1.1.0', [209, 'master_gadgets']);+ const pre = head(fx.work);+ const r = restamp(fx.work, ['--dry-run']);+ expect(r.code).toBe(0);+ expect(head(fx.work)).toBe(pre);+ expect(status(fx.work)).toBe('');+ expect(r.out).toContain('this branch becomes 0.1.2.0');+ expect(r.out).toContain('predicted conflict CHANGELOG.md (mechanical');+ expect(r.out).toContain(' VERSION: 0.1.1.0 -> 0.1.2.0');+ expect(r.out).toContain('"## [0.1.1.0] - 2026-10-03" -> "## [0.1.2.0] - 2026-10-05"');+ expect(r.out).toContain(`v209 -> v210 ${migrationFile(209, 'branch_widgets')} -> ${migrationFile(210, 'branch_widgets')}`);+ expect(r.out).toContain('docs/widgets.md:1: Migration v209 adds widgets.');+ expect(r.out).toContain('PR title: v0.1.2.0 feat(sync): faster widgets');+ }, 120_000);++ test('--no-commit leaves the restamp edits staged on top of the merge commit', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', {});+ landOnMaster(fx, '0.1.1.0', null);+ const r = restamp(fx.work, ['--no-commit']);+ expect(r.code).toBe(0);+ expect(parents(fx.work, 'HEAD')).toBe(2);+ expect(git(fx.work, 'diff', '--cached', '--name-only')).toContain('VERSION');+ expect(r.out).toContain('Edits are staged (--no-commit)');+ }, 120_000);++ test('a branch without its CHANGELOG entry stops at the drift check until one is written', () => {+ const fx = fixture();+ put(fx.work, { ...stamps('0.1.1.0') });+ commit(fx.work, 'bump only');+ landOnMaster(fx, '0.1.1.0', null);+ const r = restamp(fx.work);+ expect(r.code).toBe(1);+ expect(r.out).toContain('CHANGELOG.md has no entry for this branch');+ const { preamble, sections } = splitChangelog(read(fx.work, 'CHANGELOG.md'));+ put(fx.work, { 'CHANGELOG.md': [preamble, release('0.1.2.0', '2026-10-05', 'Now with entry.'), ...sections.map((s) => s.text)].join('\n') });+ expect(restamp(fx.work, ['--continue']).code).toBe(0);+ expect(subject(fx.work)).toBe('v0.1.2.0 chore(release): restamp onto master v0.1.1.0');+ }, 120_000);++ test('an edit to a published migration stops: published migrations are never renumbered or edited', () => {+ const fx = fixture();+ branchWork(fx, '0.1.1.0', { [migrationFile(208, 'seed_two')]: migration(208, 'seed_two', 'CREATE TABLE IF NOT EXISTS seed_two (id BIGINT);') });+ landOnMaster(fx, '0.1.1.0', null);+ const r = restamp(fx.work);+ expect(r.code).toBe(1);+ expect(r.out).toContain(`FAIL: ${migrationFile(208, 'seed_two')} is published on origin/master but this branch changes its payload`);+ }, 120_000);+});++describe('release:restamp helpers', () => {+ test('version: master MAJOR.MINOR.(PATCH+1).0', () => {+ expect(nextPatchVersion('0.60.69.0\n')).toBe('0.60.70.0');+ expect(nextPatchVersion('0.31.1.1-fixwave')).toBe('0.31.2.0');+ expect(() => nextPatchVersion('banana')).toThrow(/is not MAJOR.MINOR.PATCH.MICRO/);+ });++ test('version-only conflict hunks resolve; real edits stay conflicted', () => {+ const versionOnly = '{\n<<<<<<< HEAD\n "version": "0.1.1.0",\n=======\n "version": "0.1.2.0",\n>>>>>>> origin/master\n}\n';+ expect(resolveVersionOnlyHunks(versionOnly)).toEqual({ text: '{\n "version": "0.1.1.0",\n}\n', unresolved: 0 });+ const real = '<<<<<<< HEAD\n"dep": "1"\n=======\n"dep": "2"\n>>>>>>> origin/master\n';+ expect(resolveVersionOnlyHunks(real).unresolved).toBe(1);+ });++ test('renumbering changes only the export name and the version literal', () => {+ const text = migration(209, 'widgets', 'SELECT 209;', '// v209 note\n');+ const moved = renumberMigrationText(text, 'x.ts', 212);+ expect(moved).toBe(text.replace('export const v209', 'export const v212').replace('version: 209,', 'version: 212,'));+ expect(migrationPayloadKey(moved, 'x.ts')).toBe(migrationPayloadKey(text, 'x.ts'));+ expect(migrationPayloadKey(text.replace('SELECT 209', 'SELECT 1'), 'x.ts')).not.toBe(migrationPayloadKey(text, 'x.ts'));+ });++ test('leftover scan lists reference shapes, skips decoys, generated files and the renamed constant lines', () => {+ const added = [+ { file: 'src/a.ts', line: 1, text: 'const LIMIT = 209;' },+ { file: 'docs/a.md', line: 2, text: 'schema_version moves to 209' },+ { file: 'test/a.test.ts', line: 3, text: "import { v209 } from './v209-widgets.ts';" },+ { file: 'llms-full.txt', line: 4, text: 'Migration v209' },+ { file: `${DIR}/v210-widgets.ts`, line: 5, text: ' version: 210,' },+ ];+ expect(findLeftoverRefs(added, [209, 210], new Set([`${DIR}/v210-widgets.ts`])).map((r) => r.line)).toEqual([2, 3]);+ });++ test('CHANGELOG rebuild keeps master entries and is idempotent', () => {+ const entry = { header: '## [0.1.1.0] - 2026-10-03', text: '## [0.1.1.0] - 2026-10-03\n\nBranch v0.1.1.0 notes.\n' };+ const merged = changelog(release('0.1.1.0', '2026-10-04', 'Master.'), release('0.1.0.0', '2026-01-01', 'First.'));+ const once = rebuildChangelog(merged, entry, '0.1.1.0', '0.1.2.0', '2026-10-05');+ expect(rebuildChangelog(once, entry, '0.1.1.0', '0.1.2.0', '2026-10-05')).toBe(once);+ expect(once).toBe(changelog(release('0.1.2.0', '2026-10-05', 'Branch v0.1.2.0 notes.'), release('0.1.1.0', '2026-10-04', 'Master.'), release('0.1.0.0', '2026-01-01', 'First.')));+ });++ test('every required row of the CLAUDE.md "Version locations" table is restamped', () => {+ const claude = read(REPO, 'CLAUDE.md');+ const table = claude.slice(claude.indexOf('**Required (every release must update every row):**'), claude.indexOf('**Auto-derived'));+ const files = [...table.matchAll(/^\| (.+?) \|/gm)].flatMap(([, cell]) => [...cell!.matchAll(/`([^`]+)`/g)].map((m) => m[1]!));+ expect(files.length).toBeGreaterThan(5);+ const covered = new Set([...STAMPS.map((s) => s.file), ...OTHER_STAMPED_FILES]);+ expect(files.filter((f) => !covered.has(f))).toEqual([]);+ });++ test('every docs anchor restamp prints resolves', () => {+ const anchor = (h: string) => h.trim().toLowerCase().replace(/[^\p{L}\p{N}\s_-]/gu, '').replace(/\s/g, '-');+ for (const ref of [RESTAMP_DOCS, COLLISION_DOCS]) {+ const [path, id] = ref.split('#');+ const headings = [...read(REPO, path!).replace(/^```[\s\S]*?^```/gm, '').matchAll(/^#{1,6}\s+(.+)$/gm)].map(([, h]) => anchor(h!));+ expect(headings, `${ref} does not resolve`).toContain(id!);+ }+ });+});