Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(upgrade): probe the release tag before a pinned reinstall removes the CLI (#6662)

time-attacke0be68b42fe0
diff --git a/docs/architecture/key-files/commands-6.md b/docs/architecture/key-files/commands-6.md
index 981fc6a86c..da147044e1 100644
--- a/docs/architecture/key-files/commands-6.md
+++ b/docs/architecture/key-files/commands-6.md
@@ -12,7 +12,7 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/commands/transcripts.ts` — the transcripts command family, all local-only (`ctx.remote=false` by construction). `recent`: raw `.txt` corpus reads via `listRecentTranscripts` (same library as the gated `get_recent_transcripts` op). `ingest <path-or-glob>`: the cross-harness session importer — resolves ONE source id (6-tier chain), threads activePack once, streams progress (phase `transcripts.ingest`), and calls `runTranscriptsIngest` with the CLI's `makeContext` context, so on a writer-claimed brain each rendered part is submitted as a `put_page` write request naming the page's current revision (unmanaged brains and dry runs keep the direct importer; `recover codex --apply` passes the same context; pinned by `test/transcripts-managed-ingest.test.ts`); embedding is OFF by default (embed backfill is the catch-up lane; the embed flag opts in); the max-bytes flag (validated size string, e.g. `4gb`) overrides the per-format file/store byte caps for oversized stores while omission preserves each adapter's native default; the since-last watermark is an op-checkpoint (op `transcripts-ingest`, fingerprint = source + pathspec + format + adapter version + any explicit byte cap via `ingestCheckpointFingerprintInput` — a checkpoint written under one cap is never silently reused under another, so a capped run's skipped tail can't read as scanned; the pathspec binds the user-stated paths resolved + sorted, and the no-arg/all lane substitutes hostname + sorted harness roots so DB-backed checkpoints shared across a brain's machines never let one machine inherit another's watermark and skip sessions it never scanned) advanced ONLY after a clean, untruncated, non-dry scan; no-arg = confined discovery table, the all flag imports the discovered set. `status`: found-vs-imported gap table (disk scan vs ONE conversation-pages frontmatter query — `executeRaw`, both engines — in `src/core/transcripts/discover.ts`) — the correctness surface that catches late-arriving sessions no watermark can. The facts flag hands EVERY touched slug (including hash-skipped) to `src/core/transcripts/ingest-facts.ts`; a page that fails extraction counts in `facts.pagesFailed`, stays unfinished, and makes the command exit 1. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + SELF_HELP_WITHOUT_ENGINE (engine-free help). `expandTilde(raw)` (bare `~`, leading `~/` or `~\\` → home dir; `~user` forms and a mid-string `~` stay literal) is the one tilde expansion `expandPaths` applies to every path spec. `recover codex` (`src/commands/transcripts-recover.ts`, logic `src/core/transcripts/recover.ts`; D15 for #5163): finds codex conversation pages in one source with no `**User**` anchor, re-parses the retained rollouts (discovery root + archived store, or given paths) and classifies each session recoverable / still userless / unrecoverable (rollout gone); preview by default, `--apply` re-imports only the recoverable rollouts through `runTranscriptsIngest` (content-hash dedup, no facts, no watermark write). Pinned by `test/transcripts-recover-codex.test.ts`. `audit-secrets [--source-id S] [--json]` (`src/commands/transcripts-audit.ts`, logic `src/core/transcripts/secret-audit.ts`): the read-only installed-base audit that streams imported conversation pages (`type = 'conversation'` with `transcript_import` frontmatter) in id-keyset batches of 25, scans title and body with the transcript-lane detectors, lists slug, source, hit counts per pattern and up to 20 line numbers (never values or previews), and caches the summary without slugs in config row `transcripts.secret_audit` for the doctor check `transcript_secret_exposure` (`src/commands/doctor/checks/transcript-secrets.ts`, brain category), which counts imported conversation pages and reads that summary (never scans): no audit, an older `TRANSCRIPT_SECRET_AUDIT_VERSION` or a source-scoped audit warns with the audit as fix; hits warn with the audit's age; a clean full audit is ok. Pinned by `test/transcripts-secret-audit.test.ts`.
-- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).
+- `src/commands/upgrade.ts` — self-update CLI. It sets `GBRAIN_UPGRADE_OWNS_MIGRATIONS=1` for the install step, so package postinstall (`scripts/postinstall.ts`) skips `apply-migrations`; post-upgrade owns them. An install step that fails or times out after `gbrain --version` already reports a newer version counts as installed. The run ends with a `Binary:` line (installed version, or upgrade failed) and a `Migrations:` line: complete; running, with the lock holder's host and pid when post-upgrade exits 75; or failed, with the recovery command (`--force-retry <v>` for wedged versions). `runPostUpgrade()` enumerates migrations from the TS registry (`src/commands/migrations/index.ts`) and tail-calls `runApplyMigrations(['--yes', '--non-interactive'])` so the mechanical side of every outstanding migration runs unconditionally. After schema apply it prints the one-shot auto_chronicle default-on `[AGENT]` notice (`core/chronicle/upgrade-notice.ts`). Before the swap of a bun-link, package or ClawHub install it refuses (exit 78, nothing changed) a target whose Bun floor is above the host's Bun or unreadable (`--no-bun-floor-check` overrides, manual only; `src/core/bun-floor.ts`); after the swap it runs `gbrain --help` as a smoke that passes the startup Bun check and, on failure, exits 1 with per-method recovery (#5855). Everything the post-swap tail needs is imported statically, so the old process never loads new-release modules into its cached graph (#6604; the supervisor step constant lives in the import-free leaf `src/commands/movement-step.ts`; guard: `test/upgrade-post-swap-imports.test.ts`). A tag-pinned reinstall hint (`bunReinstallCommand`, `reinstallHintLines`) probes `git ls-remote --exit-code --tags … refs/tags/v<x>` before `bun remove -g gbrain`, prints a restore line, and on Windows prints one step per line; `planPinnedReinstall` probes the tag itself (published / not published / unknown) and falls back to the newest published `v<x>` tag (`latestPublishedVersion`) when the requested one is missing (#6662, D24; `test/upgrade-release-tag-hint.test.ts`). Tests: `upgrade-migration-outcome.test.ts`, `upgrade-no-autopilot.serial.test.ts`, `upgrade-bun-link-arc.serial.test.ts`. `post-upgrade --json` (D2, `json: 'document'`): human lines go to stderr and stdout is one report `{status, apply_migrations:{exit_code}, schema, warnings[]}`; it calls `applyMigrations()` and still ends on any status apply-migrations returns (a failure is one envelope leading with the report).
- `src/commands/watch.ts` — `gbrain watch`: the push transport. Reads turns from stdin as they arrive (`user:`/`assistant:` prefixes; unprefixed = user turn), keeps a rolling in-process window (`--window-turns`, default 4), calls `volunteerContext` per turn, streams pointers to stdout (`--json` for JSONL with turn attribution), logs `channel: 'watch'` events with a per-session id. Session dedupe feeds already-pushed slugs back as priorContext so the core's slug-only suppression dedupes. Blocks in the stdin iteration (interactive alive until Ctrl-C/Ctrl-D; piped ends at EOF) — deliberately NOT in DAEMON_COMMANDS; SIGINT closes the stream so teardown flows through finishCliTeardown. Per-turn resolution failures are fail-open. Registered in CLI_ONLY + CLI_ONLY_SELF_HELP + THIN_CLIENT_REFUSED_COMMANDS (thin clients use the `volunteer_context` MCP op). Pinned by `test/watch-command.test.ts`.
diff --git a/docs/guides/upgrades-auto-update.md b/docs/guides/upgrades-auto-update.md
index 664a625898..2b84f8d7ca 100644
--- a/docs/guides/upgrades-auto-update.md
+++ b/docs/guides/upgrades-auto-update.md
@@ -105,10 +105,22 @@ the startup Bun check, unlike `--version`). If the new release does not
start, the upgrade exits non-zero and prints recovery: `bun upgrade`, then
`gbrain post-upgrade`; or return to the previous release with
`git -C <clone> checkout <previous sha> && bun install` (bun-link) or
-`bun remove -g gbrain && bun add -g github:garrytan/gbrain#v<previous>` (package; an in-place tag swap fails or silently corrupts the global lock on current Bun, #5034). Nothing is
+`git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v<previous> && bun remove -g gbrain && bun add -g github:garrytan/gbrain#v<previous>` (package; an in-place tag swap fails or silently corrupts the global lock on current Bun, #5034). Nothing is
rolled back automatically, and the autopilot channel records that version as
failed.
+Tag-pinned package installs (`github:garrytan/gbrain#v<x>`) stay pinned through
+`bun update`, so `gbrain upgrade` prints a reinstall instead. Every printed
+reinstall checks that the release tag exists before `bun remove -g gbrain`
+runs, and ends with the line that restores the previous version if the add
+fails. The target is the newest published release tag: master's `VERSION` is
+stamped before the release checks pass and the tag is created, so a version
+can be announced before its tag exists. When the requested version's tag is
+missing, upgrade says `v<x> is not published yet`, removes nothing, and offers
+the newest published release if it is newer than yours (#6662). Windows
+PowerShell 5.1 has no `&&`, so on Windows the steps print one per line; run
+them in order and stop if the tag check fails.
+
Recovery when autopilot is holding an upgrade:
```bash
diff --git a/src/commands/upgrade.ts b/src/commands/upgrade.ts
index 039f61ade4..a835b7995d 100644
--- a/src/commands/upgrade.ts
+++ b/src/commands/upgrade.ts
@@ -2,7 +2,7 @@ import type { BrainEngine } from '../core/engine.ts';
import { execSync, execFileSync, spawnSync } from 'child_process';
import { existsSync, readFileSync, writeFileSync, mkdirSync, appendFileSync, realpathSync } from 'fs';
import { basename, join, dirname, resolve } from 'path';
-import { parseSemver, semverGt } from '../core/semver.ts';
+import { isNewerVersion, parseSemver, semverGt } from '../core/semver.ts';
import { jsonRequested, setCliExitVerdict, writeJsonDocument } from '../core/cli-force-exit.ts';
import { opError, type OperationError } from '../core/ops/contract.ts';
import { writeCliError } from '../cli/cli-error.ts';
@@ -196,14 +196,14 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
const target = opts.targetVersion;
if (target && assessUpgradeOutcome(target, newVersion) === 'mismatch') {
console.error(`Upgrade did not take effect: still running ${newVersion}, expected ${target}.`);
- console.error('Exact-tag Git installs stay pinned through `bun update`. Reinstall with:');
- console.error(` ${bunReinstallCommand(`#v${target}`)}`);
+ const plan = planPinnedReinstall(target, oldVersion);
+ printPinnedReinstall(plan, oldVersion, 'Exact-tag Git installs stay pinned through `bun update`. Reinstall with:');
recordUpgradeError({
phase: 'verify-target',
fromVersion: oldVersion,
toVersion: target,
error: `still running ${newVersion} after upgrade`,
- hint: bunReinstallCommand(`#v${target}`),
+ hint: pinnedReinstallHint(plan),
});
setCliExitVerdict(1);
return;
@@ -215,17 +215,16 @@ export async function runUpgrade(args: string[], opts: { targetVersion?: string
if (!target && method === 'bun' && newVersion && newVersion === oldVersion) {
const pin = bunGlobalExactTagPin(resolveBunGlobalRoot());
if (pin) {
- const latest = pendingUpgradeVersion(oldVersion);
- const reinstall = bunReinstallCommand(latest ? `#v${latest}` : '');
+ const published = planPinnedReinstall(null, oldVersion);
+ const plan = published.version ? published : { version: pendingUpgradeVersion(oldVersion), unpublished: null };
console.error(`Upgrade did not take effect: still running ${newVersion}, because the global install is pinned to ${pin} and \`bun update\` keeps a pinned tag.`);
- console.error('Reinstall to move off the pin:');
- console.error(` ${reinstall}`);
+ printPinnedReinstall(plan, oldVersion, 'Reinstall to move off the pin:');
recordUpgradeError({
phase: 'verify-pin',
fromVersion: oldVersion,
- toVersion: latest ?? 'latest',
+ toVersion: plan.version ?? 'latest',
error: `pinned to ${pin}; still running ${newVersion} after upgrade`,
- hint: reinstall,
+ hint: pinnedReinstallHint(plan),
});
setCliExitVerdict(1);
return;
@@ -416,7 +415,101 @@ export function resolveBunGlobalRoot(): string {
* and bun.lock.
*/
export function bunReinstallCommand(ref: string): string {
- return `bun remove -g gbrain && bun add -g github:${GBRAIN_GITHUB_REPO}${ref}`;
+ const tag = /^#(v\d[\w.]*)$/.exec(ref)?.[1];
+ const remove = `bun remove -g gbrain && bun add -g github:${GBRAIN_GITHUB_REPO}${ref}`;
+ return tag ? `${releaseTagProbeCommand(tag)} && ${remove}` : remove;
+}
+
+const GBRAIN_GIT_URL = `https://github.com/${GBRAIN_GITHUB_REPO}`;
+
+/** #6662: the shell guard a printed reinstall runs first, so a missing tag stops it before `bun remove`. */
+function releaseTagProbeCommand(tag: string): string {
+ return `git ls-remote --exit-code --tags ${GBRAIN_GIT_URL} refs/tags/${tag}`;
+}
+
+type GitRunner = (args: string[]) => { status: number | null; stdout: string };
+const runGit: GitRunner = (args) => {
+ const r = spawnSync('git', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 15_000 });
+ return { status: r.error ? null : r.status, stdout: r.stdout ?? '' };
+};
+
+/**
+ * #6662: whether release tag v<version> exists on GitHub. Master's VERSION is
+ * stamped before release.yml mints the tag (and superseded versions never get
+ * one), so a version can be offered whose tag 404s. `--exit-code` exits 2 when
+ * no ref matches; anything else (no git, offline, timeout) is unknown.
+ */
+export function probeReleaseTag(version: string, git: GitRunner = runGit): 'published' | 'not_published' | 'unknown' {
+ const { status } = git(['ls-remote', '--exit-code', '--tags', GBRAIN_GIT_URL, `refs/tags/v${version}`]);
+ return status === 0 ? 'published' : status === 2 ? 'not_published' : 'unknown';
+}
+
+/** #6662 (D24): the newest published `v<x>` release tag, or null when it cannot be read. */
+export function latestPublishedVersion(git: GitRunner = runGit): string | null {
+ const { status, stdout } = git(['ls-remote', '--tags', '--refs', GBRAIN_GIT_URL, 'v*']);
+ if (status !== 0) return null;
+ let best: string | null = null;
+ for (const line of stdout.split('\n')) {
+ const v = /\trefs\/tags\/v(\d+\.\d+\.\d+(?:\.\d+)?)$/.exec(line.trim())?.[1];
+ if (v && (!best || isNewerVersion(best, v))) best = v;
+ }
+ return best;
+}
+
+export interface PinnedReinstallPlan {
+ /** The tag-pinned version to reinstall, or null when no published newer release is known. */
+ version: string | null;
+ /** The requested version whose tag is confirmed missing on GitHub. */
+ unpublished: string | null;
+}
+
+/**
+ * #6662 (D24): tag-pinned installs reinstall a published tag. A requested
+ * version is kept unless its tag is confirmed missing; then (or with no
+ * request) the newest published tag newer than the running version is used.
+ */
+export function planPinnedReinstall(requested: string | null, oldVersion: string, git: GitRunner = runGit): PinnedReinstallPlan {
+ const state = requested ? probeReleaseTag(requested, git) : null;
+ if (requested && state !== 'not_published') return { version: requested, unpublished: null };
+ const published = latestPublishedVersion(git);
+ return { version: published && isNewerVersion(oldVersion, published) ? published : null, unpublished: requested };
+}
+
+/**
+ * #6662: the reinstall steps to print. The guarded one-liner works in POSIX
+ * shells and PowerShell 7; Windows PowerShell 5.1 has no `&&`, so on Windows
+ * each step is its own line. Always ends with the restore line for oldVersion.
+ */
+export function reinstallHintLines(version: string, oldVersion: string, platform: NodeJS.Platform = process.platform): string[] {
+ const tag = `v${version}`;
+ const restore = `If the add fails, restore ${oldVersion} with: bun add -g github:${GBRAIN_GITHUB_REPO}#v${oldVersion}`;
+ if (platform !== 'win32') return [bunReinstallCommand(`#${tag}`), restore];
+ return [
+ 'Run these one at a time, and stop if the first one fails (the tag is not published yet):',
+ releaseTagProbeCommand(tag),
+ 'bun remove -g gbrain',
+ `bun add -g github:${GBRAIN_GITHUB_REPO}#${tag}`,
+ restore,
+ ];
+}
+
+function printPinnedReinstall(plan: PinnedReinstallPlan, oldVersion: string, lead: string): void {
+ if (plan.unpublished) {
+ console.error(`v${plan.unpublished} is not published yet: its release tag is not on GitHub (tags are created after the release checks pass). Nothing was removed.`);
+ }
+ if (!plan.version) {
+ if (plan.unpublished) return console.error('Retry `gbrain upgrade` later.');
+ console.error(lead);
+ console.error(` ${bunReinstallCommand('')}`);
+ return;
+ }
+ console.error(plan.unpublished ? `The newest published release is ${plan.version}. ${lead}` : lead);
+ for (const line of reinstallHintLines(plan.version, oldVersion)) console.error(` ${line}`);
+}
+
+function pinnedReinstallHint(plan: PinnedReinstallPlan): string {
+ if (plan.version) return bunReinstallCommand(`#v${plan.version}`);
+ return plan.unpublished ? `v${plan.unpublished} is not published yet; retry gbrain upgrade later` : bunReinstallCommand('');
}
/**
diff --git a/test/upgrade-exact-tag-pin.test.ts b/test/upgrade-exact-tag-pin.test.ts
index db4a60a455..2e0b9337e3 100644
--- a/test/upgrade-exact-tag-pin.test.ts
+++ b/test/upgrade-exact-tag-pin.test.ts
@@ -27,6 +27,9 @@ async function runBareUpgrade(spec: string, observedVersion: string): Promise<{
// `gbrain --version` keeps reporting the observed version.
writeFileSync(join(bin, 'bun'), `#!/bin/sh\necho "$*" >> '${join(home, 'bun-calls.log')}'\nexit 0\n`);
writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${observedVersion}"\n`);
+ // #6662: the pin path reads published release tags with `git ls-remote`; answer with no newer tag, offline.
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase "$1" in ls-remote) echo "aaa\trefs/tags/v${observedVersion}"; exit 0;; esac\nexit 1\n`);
+ chmodSync(join(bin, 'git'), 0o755);
chmodSync(join(bin, 'bun'), 0o755);
chmodSync(join(bin, 'gbrain'), 0o755);
const globalRoot = join(home, '.bun', 'install', 'global');
@@ -69,6 +72,7 @@ describe('#5311 bare upgrade on an exact-tag pin', () => {
expect(r.stderr).toContain(`pinned to github:garrytan/gbrain#v${VERSION}`);
// #5034 / B-NEW-5: remove before add; an in-place global tag swap fails (Bun 1.3) or silently corrupts the lock (Bun 1.4).
expect(r.stderr).toContain('bun remove -g gbrain && bun add -g github:garrytan/gbrain');
+ expect(r.stderr).not.toContain('not published yet');
expect(readFileSync(join(r.home, 'bun-calls.log'), 'utf-8')).toContain('update gbrain');
// No false "just upgraded" breadcrumb for an upgrade that never happened.
expect(existsSync(join(r.home, '.gbrain', 'just-upgraded-from'))).toBe(false);
@@ -80,7 +84,8 @@ describe('#5311 bare upgrade on an exact-tag pin', () => {
}, 60_000);
test('every reinstall hint removes the global package before adding the tag (#5034, B-NEW-5)', () => {
- expect(bunReinstallCommand('#v0.60.1.0')).toBe('bun remove -g gbrain && bun add -g github:garrytan/gbrain#v0.60.1.0');
+ // #6662: a tag reinstall first proves the tag exists, so a missing tag stops before the removal.
+ expect(bunReinstallCommand('#v0.60.1.0')).toBe('git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v0.60.1.0 && bun remove -g gbrain && bun add -g github:garrytan/gbrain#v0.60.1.0');
expect(bunReinstallCommand('')).toBe('bun remove -g gbrain && bun add -g github:garrytan/gbrain');
});
diff --git a/test/upgrade-release-tag-hint.test.ts b/test/upgrade-release-tag-hint.test.ts
new file mode 100644
index 0000000000..aa03f3a6f2
--- /dev/null
+++ b/test/upgrade-release-tag-hint.test.ts
@@ -0,0 +1,126 @@
+/**
+ * #6662: the reinstall hint for a tag-pinned Bun install removed the working
+ * CLI before proving the target tag exists, and the target came from master's
+ * VERSION, which is stamped before release.yml mints the tag. Now the printed
+ * command probes the tag first and ends with a restore line, upgrade probes
+ * the tag itself (published / not published / unknown), and a tag-pinned
+ * install reinstalls the newest published tag (D24).
+ *
+ * The subprocess tests shim `git` and `bun` on PATH (Bun snapshots PATH at
+ * process start), so no test touches the network.
+ */
+import { describe, expect, test } from 'bun:test';
+import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'fs';
+import { tmpdir } from 'os';
+import { join, resolve } from 'path';
+
+import {
+ bunReinstallCommand,
+ latestPublishedVersion,
+ planPinnedReinstall,
+ probeReleaseTag,
+ reinstallHintLines,
+} from '../src/commands/upgrade.ts';
+import { VERSION } from '../src/version.ts';
+
+const REPO = resolve(import.meta.dir, '..');
+const fakeGit = (byArgs: (args: string[]) => { status: number | null; stdout?: string }) => (args: string[]) => ({ stdout: '', ...byArgs(args) });
+const TAGS = ['aaa\trefs/tags/v0.60.200.0', 'bbb\trefs/tags/v0.60.213.0', 'ccc\trefs/tags/v0.60.9.0', 'ddd\trefs/tags/latest-stable'].join('\n');
+
+describe('#6662 reinstall hint', () => {
+ test('the tag probe runs before the removal, and the removal still precedes the add (#5034)', () => {
+ const cmd = bunReinstallCommand('#v0.60.204.0');
+ expect(cmd).toBe('git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v0.60.204.0 && bun remove -g gbrain && bun add -g github:garrytan/gbrain#v0.60.204.0');
+ expect(cmd.indexOf('git ls-remote')).toBeLessThan(cmd.indexOf('bun remove -g gbrain'));
+ expect(cmd.indexOf('bun remove -g gbrain')).toBeLessThan(cmd.indexOf('bun add -g'));
+ expect(bunReinstallCommand('')).toBe('bun remove -g gbrain && bun add -g github:garrytan/gbrain');
+ });
+
+ test('POSIX hint is the guarded one-liner plus a restore line; Windows prints one step per line', () => {
+ expect(reinstallHintLines('0.60.213.0', '0.60.200.0', 'linux')).toEqual([
+ bunReinstallCommand('#v0.60.213.0'),
+ 'If the add fails, restore 0.60.200.0 with: bun add -g github:garrytan/gbrain#v0.60.200.0',
+ ]);
+ const win = reinstallHintLines('0.60.213.0', '0.60.200.0', 'win32');
+ expect(win.some(l => l.includes('&&'))).toBe(false);
+ expect(win.slice(1)).toEqual([
+ 'git ls-remote --exit-code --tags https://github.com/garrytan/gbrain refs/tags/v0.60.213.0',
+ 'bun remove -g gbrain',
+ 'bun add -g github:garrytan/gbrain#v0.60.213.0',
+ 'If the add fails, restore 0.60.200.0 with: bun add -g github:garrytan/gbrain#v0.60.200.0',
+ ]);
+ });
+
+ test('the tag probe has three outcomes', () => {
+ expect(probeReleaseTag('1.0.0', fakeGit(() => ({ status: 0 })))).toBe('published');
+ expect(probeReleaseTag('1.0.0', fakeGit(() => ({ status: 2 })))).toBe('not_published');
+ expect(probeReleaseTag('1.0.0', fakeGit(() => ({ status: 128 })))).toBe('unknown');
+ expect(probeReleaseTag('1.0.0', fakeGit(() => ({ status: null })))).toBe('unknown');
+ });
+
+ test('the newest published tag is the highest v<x> release tag', () => {
+ expect(latestPublishedVersion(fakeGit(() => ({ status: 0, stdout: TAGS })))).toBe('0.60.213.0');
+ expect(latestPublishedVersion(fakeGit(() => ({ status: 128 })))).toBeNull();
+ });
+
+ test('an unpublished target falls back to the newest published tag; unknown keeps the target', () => {
+ const missing = fakeGit(a => a.includes('--exit-code') ? { status: 2 } : { status: 0, stdout: TAGS });
+ expect(planPinnedReinstall('0.60.214.0', '0.60.200.0', missing)).toEqual({ version: '0.60.213.0', unpublished: '0.60.214.0' });
+ expect(planPinnedReinstall('0.60.214.0', '0.60.213.0', missing)).toEqual({ version: null, unpublished: '0.60.214.0' });
+ expect(planPinnedReinstall('0.60.214.0', '0.60.200.0', fakeGit(() => ({ status: 128 })))).toEqual({ version: '0.60.214.0', unpublished: null });
+ expect(planPinnedReinstall(null, '0.60.200.0', fakeGit(() => ({ status: 0, stdout: TAGS })))).toEqual({ version: '0.60.213.0', unpublished: null });
+ });
+});
+
+async function runPinnedUpgrade(gitShim: string, targetVersion: string): Promise<{ home: string; exitCode: number; stderr: string }> {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6662-'));
+ const bin = join(home, 'bin');
+ mkdirSync(bin);
+ writeFileSync(join(bin, 'bun'), '#!/bin/sh\nexit 0\n');
+ writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${VERSION}"\n`);
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\n${gitShim}\n`);
+ for (const tool of ['bun', 'gbrain', 'git']) chmodSync(join(bin, tool), 0o755);
+ const globalRoot = join(home, '.bun', 'install', 'global');
+ const pkgDir = join(globalRoot, 'node_modules', 'gbrain');
+ mkdirSync(pkgDir, { recursive: true });
+ writeFileSync(join(globalRoot, 'package.json'), JSON.stringify({ dependencies: { gbrain: `github:garrytan/gbrain#v${VERSION}` } }));
+ writeFileSync(join(pkgDir, 'package.json'), JSON.stringify({ name: 'gbrain', repository: 'github:garrytan/gbrain' }));
+ const driver = join(pkgDir, 'driver.ts');
+ writeFileSync(driver, `import { runUpgrade } from '${REPO}/src/commands/upgrade.ts';\nawait runUpgrade(['--swap-only', '--no-bun-floor-check'], { targetVersion: '${targetVersion}' });\n`);
+ const env: Record<string, string | undefined> = { ...process.env, HOME: home, GBRAIN_HOME: home, PATH: `${bin}:${process.env.PATH}` };
+ delete env.BUN_INSTALL;
+ const proc = Bun.spawn([process.execPath, 'run', driver], { cwd: REPO, env, stdout: 'pipe', stderr: 'pipe' });
+ const stderr = await new Response(proc.stderr).text();
+ return { home, exitCode: await proc.exited, stderr };
+}
+
+describe('#6662 upgrade on a pinned install whose target tag is missing', () => {
+ const target = '99.0.0.0';
+
+ test('a missing tag with no newer published release says so and prints no remove-first command', async () => {
+ const r = await runPinnedUpgrade(`case "$*" in *--exit-code*) exit 2;; *) echo "aaa\trefs/tags/v${VERSION}"; exit 0;; esac`, target);
+ try {
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain(`v${target} is not published yet`);
+ expect(r.stderr).not.toContain('bun remove -g gbrain');
+ const errors = readFileSync(join(r.home, '.gbrain', 'upgrade-errors.jsonl'), 'utf-8').trim().split('\n').map(l => JSON.parse(l));
+ expect(errors.at(-1)).toMatchObject({ phase: 'verify-target', hint: `v${target} is not published yet; retry gbrain upgrade later` });
+ } finally {
+ rmSync(r.home, { recursive: true, force: true });
+ }
+ }, 60_000);
+
+ test('a missing tag with a newer published release offers that tag, guarded, with the restore line', async () => {
+ const r = await runPinnedUpgrade(`case "$*" in *--exit-code*) exit 2;; *) echo "aaa\trefs/tags/v98.0.0.0"; exit 0;; esac`, target);
+ try {
+ expect(r.exitCode).toBe(1);
+ expect(r.stderr).toContain(`v${target} is not published yet`);
+ expect(r.stderr).toContain(`The newest published release is 98.0.0.0.`);
+ expect(r.stderr).toContain(bunReinstallCommand('#v98.0.0.0'));
+ expect(r.stderr).toContain(`restore ${VERSION} with: bun add -g github:garrytan/gbrain#v${VERSION}`);
+ expect(r.stderr).not.toContain(`gbrain#v${target}`);
+ } finally {
+ rmSync(r.home, { recursive: true, force: true });
+ }
+ }, 60_000);
+});
diff --git a/test/upgrade.serial.test.ts b/test/upgrade.serial.test.ts
index 34698b6b97..83f2be364c 100644
--- a/test/upgrade.serial.test.ts
+++ b/test/upgrade.serial.test.ts
@@ -242,6 +242,9 @@ describe('runUpgrade target verification (#4366)', () => {
writeFileSync(join(bin, 'gbrain'), `#!/bin/sh\necho "gbrain ${opts.observedVersion}"\n`);
chmodSync(join(bin, 'clawhub'), 0o755);
chmodSync(join(bin, 'gbrain'), 0o755);
+ // #6662: verify-target probes the release tag with `git ls-remote`; report it published, offline.
+ writeFileSync(join(bin, 'git'), `#!/bin/sh\ncase "$1" in ls-remote) exit 0;; esac\nexec ${JSON.stringify(Bun.which('git') ?? '/usr/bin/git')} "$@"\n`);
+ chmodSync(join(bin, 'git'), 0o755);
if (opts.recordGitAndBun) {
for (const tool of ['git', 'bun']) {
writeFileSync(join(bin, tool), `#!/bin/sh\necho "$(pwd)|$*" >> "${join(home, 'calls.log')}"\nexit 0\n`);