feat(upgrade): bin/gstack-upgrade, the unattended fast-forward every fix line names

--check fetches and prints current|behind <installed> -> <remote> (<n>
commits); the default fast-forwards to the remote default branch tip and
reinstalls (bin/gstack-capy-install on a Capy install, else ./setup
--refresh-registered), completing a pending reinstall on the next run. It
refuses (UPGRADE_REFUSED, exit 3, nothing changed) a dirty tracked byte, a
diverged commit, a pinned checkout, the incoming Bun floor and a held
.setup-lock; never stashes or resets; an unreachable remote is
UPGRADE_FETCH_FAILED. Fetches are receipted (fail-open). The unattended
skill-end UPGRADE_AVAILABLE line is followed by UPGRADE_COMMAND naming it.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
garrytanandcapy-ai[bot] committed 2026-10-13 01:22:26 +00:00
1 parent 55e0d9bb6f
commit d6c04d71a8
4 files changed
+398 -1

No files matched your search

+2 -1
View File
@@ -43,7 +43,8 @@ if [ "$_SESSION_KIND" = "unattended" ]; then
_TEL="off"
_CACHED_UPD=$(head -1 "$_GH/last-update-check" 2>/dev/null | tr -cd 'A-Za-z0-9._ ' || true)
case "$_CACHED_UPD" in
UPGRADE_AVAILABLE*) echo "UPGRADE_AVAILABLE: ${_CACHED_UPD##* }; run /gstack-upgrade" ;;
UPGRADE_AVAILABLE*) echo "UPGRADE_AVAILABLE: ${_CACHED_UPD##* }; run /gstack-upgrade"
echo "UPGRADE_COMMAND: $(cd "$_BIN/.." 2>/dev/null && pwd -P)/bin/gstack-upgrade" ;;
esac
echo "ARTIFACTS_SYNC: skipped (unattended session)"
fi
+109
View File
@@ -0,0 +1,109 @@
#!/usr/bin/env bash
# gstack-upgrade — move this gstack checkout to the tip of its remote default
# branch, unattended and fast-forward only. The deterministic twin of the
# /gstack-upgrade skill's git fast path, for parent agents and fix lines.
#
# Usage:
# gstack-upgrade --check fetch (refs only) and print `gstack-upgrade: current <ver>`
# (exit 0) or `gstack-upgrade: behind <installed> -> <remote>
# (<n> commits)` (exit 1); changes nothing else
# gstack-upgrade fast-forward, then reinstall: bin/gstack-capy-install on a
# Capy install (the marker it writes in the git dir),
# else ./setup --refresh-registered (setup runs migrations)
#
# Refuses with exit 3 and changes nothing (UPGRADE_REFUSED) when the directory
# is not a gstack checkout, HEAD is detached or not on the remote default
# branch (a pin), any tracked byte is dirty, a local commit diverged, the
# incoming release's Bun floor holds, or another updater holds the setup
# lock; never stashes, never resets. An unreachable remote is
# UPGRADE_FETCH_FAILED (exit 3). Prints `gstack-upgrade: upgraded <old> -> <new>`
# before reinstalling; a failed reinstall exits 1 and the next run completes it.
# Bash 3.2 plus git; the fetch is bounded by `timeout` when present.
set -u
BASH_COMPAT=50
ROOT="$(cd "$(dirname "$0")/.." && pwd -P)"
CHECK=0
case "${1:-}" in
--check) CHECK=1 ;;
'') ;;
-h|--help) sed -n '2,21p' "$0" | sed 's/^# \{0,1\}//'; exit 0 ;;
*) echo "gstack-upgrade: unknown argument '$1'" >&2; exit 2 ;;
esac
refuse() { echo "gstack-upgrade: $1; nothing was changed; fix: $2 (UPGRADE_REFUSED)" >&2; exit 3; }
fetch_failed() { echo "gstack-upgrade: could not reach origin ($1); fix: check network access to $(git -C "$ROOT" remote get-url origin 2>/dev/null || echo origin), then re-run $ROOT/bin/gstack-upgrade (UPGRADE_FETCH_FAILED)" >&2; exit 3; }
bounded() { if command -v timeout >/dev/null 2>&1; then timeout "${GSTACK_UPGRADE_FETCH_TIMEOUT:-60}" "$@"; else "$@"; fi; }
# Egress receipts (_receipted_git), fail-open like the session-start updater:
# a user-run upgrade must not die over an audit-log hiccup.
# shellcheck source=bin/gstack-egress-lib.sh
. "$ROOT/bin/gstack-egress-lib.sh" 2>/dev/null || _receipted_git() { shift 5; "$@"; }
[ -f "$ROOT/VERSION" ] && [ -f "$ROOT/setup" ] && [ "$(git -C "$ROOT" rev-parse --show-toplevel 2>/dev/null)" = "$ROOT" ] \
|| refuse "$ROOT is not a gstack checkout" "run gstack-upgrade from a git checkout of https://github.com/garrytan/gstack"
export GIT_TERMINAL_PROMPT=0
HOST=$(git -C "$ROOT" remote get-url origin 2>/dev/null); HOST="${HOST#*://}"; HOST="${HOST#*@}"; HOST="${HOST%%[/:]*}"
R="user ran gstack-upgrade"
INSTALLED=$(head -1 "$ROOT/VERSION")
BRANCH=$(git -C "$ROOT" symbolic-ref -q --short HEAD) \
|| refuse "HEAD is detached at $(git -C "$ROOT" rev-parse --short HEAD) (a pinned revision)" "git -C $ROOT checkout <default branch>, then re-run"
DEFAULT=$(_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" ls-remote --symref origin HEAD 2>/dev/null | sed -n 's|^ref: refs/heads/\([^[:space:]]*\)[[:space:]]*HEAD$|\1|p' | head -1)
[ -n "$DEFAULT" ] || fetch_failed "git ls-remote origin HEAD failed"
[ "$BRANCH" = "$DEFAULT" ] || refuse "on branch $BRANCH, not the remote default branch $DEFAULT (a pin)" "git -C $ROOT checkout $DEFAULT, then re-run"
_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" bounded git -C "$ROOT" fetch --quiet origin "$DEFAULT" 2>/dev/null || fetch_failed "git fetch origin $DEFAULT failed"
INCOMING=$(git -C "$ROOT" rev-parse FETCH_HEAD)
REMOTE_VER=$(git -C "$ROOT" show FETCH_HEAD:VERSION 2>/dev/null | head -1)
PENDING="$(git -C "$ROOT" rev-parse --absolute-git-dir)/gstack-upgrade.pending"
reinstall() { # FROM — run the install step; a pending marker survives a failure
printf '%s\n' "$1" > "$PENDING"
cd "$ROOT" || exit 1
if [ -f "$(git rev-parse --absolute-git-dir 2>/dev/null)/gstack-capy-install.state" ] && [ -x "$ROOT/bin/gstack-capy-install" ]; then
GSTACK_CAPY_UPGRADED_FROM="$1" "$ROOT/bin/gstack-capy-install" </dev/null
else
./setup --refresh-registered </dev/null
fi
_rc=$?
[ "$_rc" -eq 0 ] && { rm -f "$PENDING"; exit 0; }
echo "gstack-upgrade: the checkout is at $(head -1 "$ROOT/VERSION") but its reinstall failed (exit $_rc); fix: re-run $ROOT/bin/gstack-upgrade (it completes the pending reinstall)" >&2
exit 1
}
if [ "$INCOMING" = "$(git -C "$ROOT" rev-parse HEAD)" ] || git -C "$ROOT" merge-base --is-ancestor FETCH_HEAD HEAD 2>/dev/null; then
if [ -f "$PENDING" ]; then
echo "gstack-upgrade: current $INSTALLED; reinstall pending from $(head -1 "$PENDING")"
[ "$CHECK" -eq 1 ] && exit 1
reinstall "$(head -1 "$PENDING")"
fi
echo "gstack-upgrade: current $INSTALLED"
exit 0
fi
if [ "$CHECK" -eq 1 ]; then
echo "gstack-upgrade: behind $INSTALLED -> ${REMOTE_VER:-unknown} ($(git -C "$ROOT" rev-list --count HEAD..FETCH_HEAD 2>/dev/null || echo '?') commits)"
exit 1
fi
DIRTY=$(git -C "$ROOT" status --porcelain --untracked-files=no 2>/dev/null | cut -c4- | tr '\n' ' ' | sed 's/ $//')
[ -z "$DIRTY" ] || refuse "tracked files changed: $DIRTY" "commit or move those changes (git -C $ROOT status --short), then re-run"
if ! git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null; then
_receipted_git open gstack-upgrade "${HOST:-unknown}" gstack-self-update-pull "$R" git -C "$ROOT" fetch --quiet --unshallow origin "$DEFAULT" 2>/dev/null || true
git -C "$ROOT" merge-base --is-ancestor HEAD FETCH_HEAD 2>/dev/null \
|| refuse "diverged: $(git -C "$ROOT" rev-list --count FETCH_HEAD..HEAD 2>/dev/null || echo '?') local commits are not on origin/$DEFAULT" "git -C $ROOT log --oneline FETCH_HEAD..HEAD shows them; move them to another branch, then re-run"
fi
# shellcheck source=bin/gstack-bun-version.sh
. "$ROOT/bin/gstack-bun-version.sh" 2>/dev/null && HOLD=$(gstack_bun_incoming_hold "$ROOT" "$INCOMING") \
&& refuse "the incoming release holds: $HOLD" "install Bun $(git -C "$ROOT" show "$INCOMING:bin/gstack-bun-version.sh" 2>/dev/null | sed -n 's/^GSTACK_BUN_TESTED="\(.*\)"/\1/p') (bin/gstack-capy-install on Capy), then re-run"
# The same lock directory the session-start auto-updater (bin/gstack-session-update)
# holds while it pulls and runs setup; a live holder means refuse, never wait.
GSTACK_STATE_ROOT=$("$ROOT/bin/gstack-paths" --get GSTACK_STATE_ROOT); : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"
LOCK_DIR="$GSTACK_STATE_ROOT/.setup-lock"
mkdir -p "$GSTACK_STATE_ROOT" 2>/dev/null
mkdir "$LOCK_DIR" 2>/dev/null || refuse "another gstack updater holds $LOCK_DIR (pid $(cat "$LOCK_DIR/pid" 2>/dev/null || echo unknown))" "wait for it to finish, then re-run"
echo "$$" > "$LOCK_DIR/pid"
trap '[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXIT
git -C "$ROOT" merge --ff-only -q FETCH_HEAD 2>/dev/null || refuse "git merge --ff-only FETCH_HEAD failed" "git -C $ROOT status, then re-run"
NEW=$(head -1 "$ROOT/VERSION")
echo "gstack-upgrade: upgraded $INSTALLED -> $NEW"
rm -rf "$LOCK_DIR"; trap - EXIT
reinstall "$INSTALLED"
+108
View File
@@ -394,6 +394,7 @@ describe('gstack-skill-start behavior', () => {
expect(out).not.toContain('UPGRADE_AVAILABLE');
const endOut = end({ GSTACK_SESSION_KIND: 'unattended' });
expect(endOut).toMatch(/^UPGRADE_AVAILABLE: 9\.9\.9; run \/gstack-upgrade$/m);
expect(endOut).toMatch(/^UPGRADE_COMMAND: \/.*\/bin\/gstack-upgrade$/m);
expect(endOut).toMatch(/^ARTIFACTS_SYNC: skipped \(unattended session\)$/m);
expect(fs.existsSync(log)).toBe(false);
expect(fs.existsSync(path.join(gh, 'analytics', 'skill-usage.jsonl'))).toBe(false);
@@ -764,3 +765,110 @@ describe('gstack-skill-end', () => {
expect(fs.existsSync(pending)).toBe(false);
});
});
// Field wave lane A (item 2): an unattended or Capy-spawned workflow refuses
// to start on an unsupported PATH Bun, and on a Capy machine (GSTACK_CAPY=1)
// without a matching install verdict for this checkout, HEAD and workflow.
describe('gstack-skill-start install admission', () => {
const { spawnSync } = require('child_process') as typeof import('child_process');
const { createHash } = require('crypto') as typeof import('crypto');
const { writeBunStub } = require('./helpers/capy-host') as typeof import('./helpers/capy-host');
const head = execFileSync('git', ['-C', ROOT, 'rev-parse', 'HEAD'], { encoding: 'utf-8' }).trim();
const real = fs.realpathSync(ROOT);
const scratch = () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-admit-'));
fs.writeFileSync(path.join(dir, 'config.yaml'), 'update_check: false\n');
return dir;
};
const stubDir = (version: string) => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-bun-'));
writeBunStub(path.join(dir, 'bun'), version);
return dir;
};
const verdict = (gh: string, over: Record<string, unknown> = {}, file?: string) => {
const target = file ?? path.join(gh, 'install-verdicts', `${createHash('sha256').update(real).digest('hex')}.json`);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, JSON.stringify({
schema_version: 1, checkout: real, head, for: 'autoplan',
required: ['claude', 'codex', 'patch', 'runtime', 'pins', 'state-root', 'privacy', 'cores', 'revision'],
pins_planning_only: false, ok: true, trailer: 'gstack: ok 1.91.95.0 for=autoplan', min_revision: '1.91.95.0', launch_path: '', time: '2026-10-12T00:00:00Z', ...over,
}, null, 1) + '\n');
return target;
};
const start = (gh: string, skill: string, env: Record<string, string>, bin = START) => spawnSync(bin, ['--skill', skill], {
timeout: 30_000, encoding: 'utf-8', cwd: tmpHome,
env: { PATH: process.env.PATH!, HOME: tmpHome, GSTACK_HOME: gh, ...env },
});
test('unattended with Bun 1.3.14 first on PATH: the runtime row with its fix, status=refused, exit 3; interactive keeps running', () => {
const gh = scratch();
const bun = stubDir('1.3.14');
const PATH = `${bun}${path.delimiter}${process.env.PATH}`;
const r = start(gh, 'autoplan', { GSTACK_SESSION_KIND: 'unattended', PATH });
expect(r.status, r.stdout + r.stderr).toBe(3);
expect(r.stdout).toMatch(/^SESSION_KIND: unattended$/m);
expect(r.stdout).toContain(`INSTALL: fail runtime — bun 1.3.14 at ${bun}/bun is below the supported minimum 1.4.2`);
expect(r.stdout).toContain('(RUNTIME_BELOW_MINIMUM)');
expect(r.stdout.trim().split('\n').at(-1)).toBe('GSTACK_RESULT: skill=autoplan status=refused run=-');
const human = start(gh, 'autoplan', { PATH });
expect(human.status).toBe(0);
expect(human.stdout).not.toContain('status=refused');
const openclaw = start(gh, 'autoplan', { OPENCLAW_SESSION: '1', PATH });
expect(openclaw.status).toBe(0);
expect(openclaw.stdout).toContain('INSTALL: warn runtime');
const overridden = start(gh, 'autoplan', { GSTACK_SESSION_KIND: 'unattended', PATH, GSTACK_ALLOW_UNSUPPORTED_RUNTIME: '1' });
expect(overridden.status).toBe(0);
expect(overridden.stdout).toContain('INSTALL_VERDICT: overridden (GSTACK_ALLOW_UNSUPPORTED_RUNTIME=1)');
});
test('GSTACK_CAPY=1: a missing, failing, other-HEAD or narrower verdict refuses; a matching one admits; other unattended hosts need no verdict', () => {
const gh = scratch();
const capy = { GSTACK_SESSION_KIND: 'unattended', GSTACK_CAPY: '1' };
const missing = start(gh, 'autoplan', capy);
expect(missing.status, missing.stdout + missing.stderr).toBe(3);
expect(missing.stdout).toContain('INSTALL: fail verdict — no install verdict');
expect(missing.stdout).toContain('(INSTALL_UNVERIFIED)');
expect(start(gh, 'autoplan', { GSTACK_SESSION_KIND: 'unattended' }).status).toBe(0);
verdict(gh);
const ok = start(gh, 'autoplan', capy);
expect(ok.status, ok.stdout + ok.stderr).toBe(0);
expect(ok.stdout).toMatch(/^INSTALL_VERDICT: ok gstack: ok 1\.91\.95\.0 for=autoplan$/m);
const spawned = start(gh, 'autoplan', { GSTACK_SESSION_KIND: 'spawned', GSTACK_CAPY: '1' });
expect(spawned.status).toBe(0);
verdict(gh, { ok: false, trailer: 'gstack: fail runtime' });
const failed = start(gh, 'autoplan', capy);
expect(failed.status).toBe(3);
expect(failed.stdout).toContain('gstack: fail runtime');
verdict(gh, { head: '0'.repeat(40) });
const moved = start(gh, 'autoplan', capy);
expect(moved.status).toBe(3);
expect(moved.stdout).toContain('another HEAD');
verdict(gh, { pins_planning_only: true });
expect(start(gh, 'autoplan', capy).status).toBe(0);
const tests = start(gh, 'review', capy);
expect(tests.status).toBe(3);
expect(tests.stdout).toContain('planning-only');
verdict(gh);
const browser = start(gh, 'qa', capy);
expect(browser.status).toBe(3);
expect(browser.stdout).toContain('browse-bundle');
const elsewhere = verdict(gh, {}, path.join(gh, 'named.json'));
fs.rmSync(path.join(gh, 'install-verdicts'), { recursive: true, force: true });
expect(start(gh, 'autoplan', { ...capy, GSTACK_INSTALL_VERDICT: elsewhere }).status).toBe(0);
});
test('an installed runtime root follows its .source-path to the source checkout for the verdict and HEAD', () => {
const gh = scratch();
const runtime = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-ss-runtime-'));
fs.symlinkSync(path.join(ROOT, 'bin'), path.join(runtime, 'bin'));
fs.writeFileSync(path.join(runtime, '.source-path'), `${ROOT}\n`);
fs.copyFileSync(path.join(ROOT, 'VERSION'), path.join(runtime, 'VERSION'));
verdict(gh);
const r = start(gh, 'autoplan', { GSTACK_SESSION_KIND: 'unattended', GSTACK_CAPY: '1' }, path.join(runtime, 'bin/gstack-skill-start'));
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(r.stdout).toContain('INSTALL_VERDICT: ok');
});
});
+179
View File
@@ -0,0 +1,179 @@
/**
* bin/gstack-upgrade: the deterministic, unattended upgrade every fix line
* names. Pinned on its machine lines (`gstack-upgrade: current|behind|upgraded`),
* exit codes (0 ok, 1 behind on --check, 3 refused with nothing changed) and
* what it refuses: a dirty tracked byte, a diverged local commit, a pinned
* (detached or off-default) checkout, an unreachable remote. Never stash,
* never reset: HEAD, file bytes and the reflog are unchanged on refusal.
* Fixture: a bare remote with commits A (1.0.0) and B (1.0.1), a depth-1
* file:// clone at A, ./setup and bin/gstack-capy-install stubs that log argv,
* on the simulated Capy host (test/helpers/capy-host.ts).
*/
import { afterEach, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import { capyHost, type CapyHost } from './helpers/capy-host';
const REPO = path.resolve(import.meta.dir, '..');
const DEPS = [
'bin/gstack-upgrade', 'bin/gstack-bun-version.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh',
'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'lib/egress-receipt.ts', 'lib/state-root.ts',
];
const hosts: CapyHost[] = [];
afterEach(() => { for (const h of hosts.splice(0)) h.cleanup(); });
const write = (file: string, text: string, mode = 0o644) => {
fs.mkdirSync(path.dirname(file), { recursive: true });
fs.writeFileSync(file, text, { mode });
};
function fixture() {
const host = capyHost({ systemBun: '1.4.2' });
hosts.push(host);
const git = (args: string[], cwd: string) => {
const r = spawnSync('git', args, { cwd, encoding: 'utf8', env: host.env, timeout: 30_000 });
if (r.status !== 0) throw new Error(`git ${args.join(' ')}: ${r.stderr}`);
return r.stdout.trim();
};
const log = path.join(host.base, 'calls.log');
const seed = path.join(host.base, 'seed');
const bare = path.join(host.base, 'remote.git');
fs.mkdirSync(seed, { recursive: true });
git(['init', '-q', '-b', 'main'], seed);
for (const rel of DEPS) {
if (!fs.existsSync(path.join(REPO, rel))) continue;
fs.mkdirSync(path.dirname(path.join(seed, rel)), { recursive: true });
fs.copyFileSync(path.join(REPO, rel), path.join(seed, rel));
fs.chmodSync(path.join(seed, rel), fs.statSync(path.join(REPO, rel)).mode);
}
write(path.join(seed, 'VERSION'), '1.0.0\n');
write(path.join(seed, 'README.md'), 'gstack fixture\n');
write(path.join(seed, 'bin/gstack-config'), '#!/usr/bin/env bash\nexit 0\n', 0o755);
write(path.join(seed, 'setup'), '#!/usr/bin/env bash\necho "setup $*" >> "$UPGRADE_LOG"\nexit "${STUB_SETUP_EXIT:-0}"\n', 0o755);
git(['add', '-A'], seed);
git(['commit', '-qm', 'A'], seed);
const a = git(['rev-parse', 'HEAD'], seed);
git(['init', '-q', '--bare', '-b', 'main', bare], host.base);
git(['push', '-q', bare, 'main'], seed);
const root = path.join(host.base, 'gstack');
git(['clone', '-q', '--single-branch', '--depth', '1', `file://${bare}`, root], host.base);
write(path.join(seed, 'VERSION'), '1.0.1\n');
git(['commit', '-qam', 'B'], seed);
const b = git(['rev-parse', 'HEAD'], seed);
git(['push', '-q', bare, 'main'], seed);
const env = { ...host.env, UPGRADE_LOG: log };
const run = (args: string[] = [], extra: Record<string, string> = {}) =>
spawnSync('bash', [path.join(root, 'bin/gstack-upgrade'), ...args], { cwd: host.home, encoding: 'utf8', env: { ...env, ...extra }, timeout: 60_000 });
return {
host, root, bare, a, b, run, git: (args: string[]) => git(args, root),
calls: () => fs.existsSync(log) ? fs.readFileSync(log, 'utf8').trim().split('\n').filter(Boolean) : [],
};
}
describe('gstack-upgrade', () => {
test('--check: behind prints both versions and the commit count, exit 1, writes nothing', () => {
const f = fixture();
expect(f.git(['rev-parse', '--is-shallow-repository'])).toBe('true');
const r = f.run(['--check']);
expect(r.status, r.stdout + r.stderr).toBe(1);
expect(r.stdout).toContain('gstack-upgrade: behind 1.0.0 -> 1.0.1 (1 commits)');
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.a);
expect(f.calls()).toEqual([]);
});
test('default: fast-forwards to the remote default branch and runs setup --refresh-registered; --check is then current', () => {
const f = fixture();
const r = f.run();
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
expect(r.stdout).toContain('gstack-upgrade: upgraded 1.0.0 -> 1.0.1');
expect(f.calls()).toEqual(['setup --refresh-registered']);
const again = f.run(['--check']);
expect(again.status).toBe(0);
expect(again.stdout).toContain('gstack-upgrade: current 1.0.1');
});
test('a reinstall that fails after the fast-forward exits 1; the next run completes it instead of saying current', () => {
const f = fixture();
const failed = f.run([], { STUB_SETUP_EXIT: '1' });
expect(failed.status).toBe(1);
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.b);
expect(failed.stderr).toContain('reinstall failed');
expect(f.run(['--check']).status).toBe(1);
const retry = f.run();
expect(retry.status, retry.stdout + retry.stderr).toBe(0);
expect(retry.stdout).toContain('reinstall pending from 1.0.0');
expect(f.calls()).toEqual(['setup --refresh-registered', 'setup --refresh-registered']);
expect(f.run().stdout).toContain('gstack-upgrade: current 1.0.1');
});
test('a Capy install (the installer marker) runs bin/gstack-capy-install instead of setup', () => {
const f = fixture();
write(path.join(f.root, 'bin/gstack-capy-install'), '#!/usr/bin/env bash\necho "capy-install $*" >> "$UPGRADE_LOG"\necho "gstack: ok $(cat VERSION) for=autoplan"\n', 0o755);
write(path.join(f.root, '.git/gstack-capy-install.state'), `head=${f.a}\n`);
const r = f.run();
expect(r.status, r.stdout + r.stderr).toBe(0);
expect(f.calls()).toEqual(['capy-install']);
expect(r.stdout.trim().split('\n').at(-1)).toBe('gstack: ok 1.0.1 for=autoplan');
});
test('a dirty tracked byte refuses with UPGRADE_REFUSED: exit 3, HEAD, bytes and reflog unchanged', () => {
const f = fixture();
fs.writeFileSync(path.join(f.root, 'README.md'), 'local edit\n');
const reflog = f.git(['reflog']);
const r = f.run();
expect(r.status).toBe(3);
expect(r.stderr).toContain('(UPGRADE_REFUSED)');
expect(r.stderr).toContain('README.md');
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.a);
expect(fs.readFileSync(path.join(f.root, 'README.md'), 'utf8')).toBe('local edit\n');
expect(f.git(['reflog'])).toBe(reflog);
expect(f.git(['stash', 'list'])).toBe('');
expect(f.calls()).toEqual([]);
});
test('a diverged local commit refuses with UPGRADE_REFUSED: never stash, never reset', () => {
const f = fixture();
fs.writeFileSync(path.join(f.root, 'README.md'), 'local commit\n');
f.git(['commit', '-qam', 'local']);
const head = f.git(['rev-parse', 'HEAD']);
const reflog = f.git(['reflog']);
const r = f.run();
expect(r.status).toBe(3);
expect(r.stderr).toContain('(UPGRADE_REFUSED)');
expect(f.git(['rev-parse', 'HEAD'])).toBe(head);
expect(f.git(['reflog'])).toBe(reflog);
expect(f.calls()).toEqual([]);
});
test('a detached (pinned) checkout refuses; an unreachable remote is UPGRADE_FETCH_FAILED (exit 3) for --check and default', () => {
const f = fixture();
f.git(['checkout', '-q', '--detach', 'HEAD']);
const pinned = f.run();
expect(pinned.status).toBe(3);
expect(pinned.stderr).toContain('(UPGRADE_REFUSED)');
expect(pinned.stderr).toContain('detached');
f.git(['checkout', '-q', 'main']);
fs.rmSync(f.bare, { recursive: true, force: true });
for (const args of [['--check'], []]) {
const offline = f.run(args);
expect(offline.status).toBe(3);
expect(offline.stderr).toContain('(UPGRADE_FETCH_FAILED)');
expect(f.git(['rev-parse', 'HEAD'])).toBe(f.a);
}
});
test('every bin a trailer or fix line names exists in the repo', () => {
const sources = ['bin/gstack-capy-install', 'bin/gstack-doctor-check.sh', 'bin/gstack-skill-end', 'bin/gstack-upgrade', 'docs/capy-install.md'];
const named = new Set<string>();
for (const rel of sources) {
expect(fs.existsSync(path.join(REPO, rel)), rel).toBe(true);
const lines = fs.readFileSync(path.join(REPO, rel), 'utf8').split('\n').filter(l => /fix:|\brun |gstack: (ok|fail)/.test(l));
for (const m of lines.join('\n').matchAll(/(?:bin\/|\brun |\bfix: )(gstack-[a-z0-9-]+(?:\.sh|\.ts)?)\b/g)) named.add(m[1]);
}
expect(named.has('gstack-upgrade')).toBe(true);
const missing = [...named].filter(n => !fs.existsSync(path.join(REPO, 'bin', n)));
expect(missing).toEqual([]);
});
});