Make gstack's shell locks hold when mkdir reports a race it lost (GST-2247) (#4262)

* Make gstack's shell locks hold when mkdir reports a race it lost (GST-2247)

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Fix lock tests and fixtures for gstack_lock_take; trim setup-gbrain lock prose

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Ship the lock helper with every copied runtime and fixture that runs a lock

The Claude Code wrapper's copied runtime now includes bin/gstack-lock.sh, and
bin/gstack-render-claude.sh sources it beside itself, so gstack-config set
works in a copied runtime and the render lock is taken by every caller.
Test fixtures that copy single bin scripts now copy the helper too, and the
mkdir lock guard is registered as a repo-wide docs reader.

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Release a lock whose owner file could not be fully written

gstack_lock_take created the owner file with a noclobber redirect and, when
that redirect failed, treated an existing file as a competing holder. If the
file was created but the write then failed (disk full, quota, ulimit -f), the
helper found its own empty file, returned 1 and left a lock nobody held;
freeze's state lock has no stale recovery, so it stayed busy until removed by
hand. The helper now tells "opened but write failed" from "already held",
removes its own file and directory, and returns 3. The inline copy in
gstack-ff-update is updated byte for byte, and a new test under ulimit -f 0
fails on the old helper.

Review-Finding: s11/outside-voice#1 reader=outside-voice
Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

* Describe the lease lock as gstack_lock_take's O_EXCL owner file

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>

---------

Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com>
This commit is contained in:
Garry Tanandcapy-ai[bot] authored and GitHub committed 2026-11-17 09:05:25 +00:00
1 parent 76fad3edd9
commit bcece3fbcd
50 files changed
+621 -154

No files matched your search

+1 -1
View File
@@ -51,7 +51,7 @@ const STUB_INSTALLER = [
/** What bin/gstack-capy-session's self-upgrade runs: bin/gstack-upgrade and its sourced helpers. */
const UPGRADE_DEPS = [
'bin/gstack-upgrade', 'bin/gstack-bun-version.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh',
'bin/gstack-upgrade', 'bin/gstack-bun-version.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh', 'bin/gstack-lock.sh',
'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'lib/egress-receipt.ts', 'lib/state-root.ts',
'bin/gstack-lease', 'bin/gstack-harness-pid.sh',
// Sourced by gstack-upgrade: without gstack-config in the fixture it resolves main unless GSTACK_UPDATE_CHANNEL says stable.
+5 -4
View File
@@ -74,13 +74,14 @@ describe('bounded multi-signature probe cache', () => {
expect(fs.realpathSync(lock).startsWith(`${fs.realpathSync(f.home)}${path.sep}`)).toBe(true);
fs.writeFileSync(path.join(lock, 'owner'), `${process.pid} ${os.hostname()} ${Math.floor(Date.now() / 1000)}\n`);
fs.writeFileSync(once, 'armed');
fs.writeFileSync(path.join(f.home, 'bin/mkdir'), `#!/usr/bin/env bash
if [ "$#" -eq 1 ] && [ "$1" = "$RACE_LOCK" ] && [ -f "$RACE_ONCE" ]; then
// The holder releases right after the writer's take failed: gstack_lock_take never runs mkdir on a held
// lock, so the release lands on the writer's first wait instead of inside a failed mkdir.
fs.writeFileSync(path.join(f.home, 'bin/sleep'), `#!/usr/bin/env bash
if [ -f "$RACE_ONCE" ]; then
rm -f "$RACE_ONCE" "$RACE_LOCK/owner"
rmdir "$RACE_LOCK"
exit 1
fi
exec ${JSON.stringify(Bun.which('mkdir'))} "$@"
exec ${JSON.stringify(Bun.which('sleep'))} "$@"
`, { mode: 0o755 });
const result = probe(f, { ...model('gpt-race'), STUB_MODE: 'quota', RACE_LOCK: lock, RACE_ONCE: once });
expect(result.stdout).toContain('rc=4');
+1 -1
View File
@@ -50,7 +50,7 @@ beforeEach(() => {
env = { ...process.env, HOME: join(root, 'home'), GSTACK_HOME: join(root, 'state'), CLAUDE_PLUGIN_DATA: '', CLAUDE_PLUGIN_ROOT: '' };
mkdirSync(env.GSTACK_HOME!);
state = join(env.GSTACK_HOME!, 'freeze-dir.txt');
for (const file of ['freeze/bin/check-freeze.sh', 'freeze/bin/freeze-state.sh', 'careful/bin/hook-extract.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh']) {
for (const file of ['freeze/bin/check-freeze.sh', 'freeze/bin/freeze-state.sh', 'careful/bin/hook-extract.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh', 'bin/gstack-lock.sh']) {
if (!existsSync(join(ROOT, file))) continue;
const dest = join(env.HOME!, '.claude/skills/gstack', file);
mkdirSync(dirname(dest), { recursive: true });
+1 -1
View File
@@ -2061,7 +2061,7 @@ describe('office-hours closing reads the builder profile before logging the sess
const home = path.join(dir, 'home'), state = path.join(dir, 'state');
const bin = path.join(home, '.claude/skills/gstack/bin');
fs.mkdirSync(bin, { recursive: true });
for (const file of ['gstack-builder-profile', 'gstack-developer-profile', 'gstack-state-root.sh', 'gstack-slug', 'gstack-remote-identity.sh']) {
for (const file of ['gstack-builder-profile', 'gstack-developer-profile', 'gstack-lock.sh', 'gstack-state-root.sh', 'gstack-slug', 'gstack-remote-identity.sh']) {
fs.copyFileSync(path.join(ROOT, 'bin', file), path.join(bin, file));
fs.chmodSync(path.join(bin, file), 0o755);
}
+1
View File
@@ -35,6 +35,7 @@ function fixture(opts: { playwright?: boolean } = {}) {
fs.mkdirSync(path.join(root, 'bin'), { recursive: true });
fs.copyFileSync(path.join(REPO, 'bin/gstack-browser-ensure'), path.join(root, 'bin/gstack-browser-ensure'));
fs.chmodSync(path.join(root, 'bin/gstack-browser-ensure'), 0o755);
fs.copyFileSync(path.join(REPO, 'bin/gstack-lock.sh'), path.join(root, 'bin/gstack-lock.sh'));
if (opts.playwright !== false) {
write(path.join(root, 'node_modules/playwright/index.js'), [
'const fs = require("fs");',
+7
View File
@@ -556,6 +556,13 @@ describe('gstack-ff-update: self-contained, with twins pinned', () => {
expect(ffSrc).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null');
});
// Value: protects=the self-contained bin takes its lock exactly like every other gstack lock; fails_when=the inlined gstack_lock_take drifts from bin/gstack-lock.sh; why_new=the lock moved off mkdir's exit status (Ubuntu 26.04 uutils); seam=none; no_claim=the race itself, proven in test/gstack-lock-race.test.ts
test('the inlined gstack_lock_take is byte-identical to bin/gstack-lock.sh', () => {
const lockSrc = fs.readFileSync(path.join(path.dirname(FF), 'gstack-lock.sh'), 'utf8');
expect(fn(ffSrc, 'gstack_lock_take')).toBeDefined();
expect(fn(ffSrc, 'gstack_lock_take')).toBe(fn(lockSrc, 'gstack_lock_take'));
});
test.skipIf(process.platform === 'win32')('ff_flatten flattens newlines and strips control characters and escape sequences', () => {
const r = spawnSync('bash', ['-c', `eval "$(sed -n '/^ff_flatten() {/,/^}/p' "${FF}")"; ff_flatten "$(printf 'bad\\nstages=x \\033[31mred\\033[0m\\001end')" 200`], { encoding: 'utf8', timeout: 30_000 });
expect(r.stdout).toBe('bad stages=x redend');
+2 -1
View File
@@ -552,7 +552,8 @@ describe('gstack-lease', () => {
test('a lock whose owner cannot be published is removed, not left ownerless, and touch fails at once', () => {
const { dir, leases } = checkout();
const holder = sleeper();
const shim = bashEnv(dir, 'mv() { case "$*" in *".lock.claim."*) return 1 ;; esac; command mv "$@"; }\n');
// The owner file is created inside the new lock directory; a directory that refuses writes stands in for any failed publish.
const shim = bashEnv(dir, 'mkdir() { command mkdir "$@" || return; case "$*" in *"/.lock") command chmod a-w "${@: -1}" ;; esac; }\n');
const r = run(['touch', '--root', dir, '--pid', String(holder)], { BASH_ENV: shim });
expect(r.status, r.stdout + r.stderr).toBe(3);
expect(r.stderr).toContain('cannot take the lease directory lock');
+186
View File
@@ -0,0 +1,186 @@
/**
* bin/gstack-lock.sh: a lock that stays exclusive when mkdir lies.
*
* Ubuntu 26.04 (GitHub's ubuntu-latest from 2026-11-09) ships Rust coreutils
* (uutils) 0.8.0 as mkdir. It checks that the path is missing, creates it, and
* exits 0 even when another process created the directory first, so the
* `mkdir "$LOCK" && ...` pattern let two racing holders both win (GBEV-3 saw
* 60 double wins in 300 races; GNU mkdir never did). The PATH shim below
* reproduces that behaviour on any runner image, so this file runs in the free
* suite without depending on which coreutils the machine has.
*/
import { afterAll, describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
const ROOT = path.resolve(import.meta.dir, '..');
const HELPER = path.join(ROOT, 'bin', 'gstack-lock.sh');
const REAL_MKDIR = Bun.which('mkdir') ?? '/bin/mkdir';
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-lock-'));
afterAll(() => fs.rmSync(tmp, { recursive: true, force: true }));
// uutils 0.8.0 mkdir, as observed on ubuntu-26.04 image 20261101.186.1: an
// existing path fails, a missing one is created after a window and reported as
// created even when another process won the create. -p passes through.
const SHIM = path.join(tmp, 'lying-bin');
fs.mkdirSync(SHIM);
fs.writeFileSync(path.join(SHIM, 'mkdir'), [
'#!/bin/bash',
'for a in "$@"; do case "$a" in -p|-*p*|--parents) exec "$REAL_MKDIR" "$@" ;; esac; done',
'for a in "$@"; do case "$a" in -*) ;; *) t="$a" ;; esac; done',
'if [ -e "$t" ]; then echo "mkdir: cannot create directory \'$t\': File exists" >&2; exit 1; fi',
'sleep "${LYING_MKDIR_WINDOW:-0.05}"',
'"$REAL_MKDIR" "$t" 2>/dev/null',
'exit 0',
'',
].join('\n'), { mode: 0o755 });
const LYING = { PATH: `${SHIM}:${process.env.PATH ?? ''}`, REAL_MKDIR };
let seq = 0;
function bash(script: string, env: Record<string, string> = {}, timeout = 60_000) {
const r = spawnSync('bash', ['--noprofile', '--norc', '-c', script], {
cwd: tmp,
env: { ...process.env, ...env },
encoding: 'utf8',
timeout,
});
return { code: r.status, out: r.stdout ?? '', err: r.stderr ?? '' };
}
const fresh = () => { const d = path.join(tmp, `case-${++seq}`); fs.mkdirSync(d); return d; };
// One trial: RACERS shells wait on a start file, then all try the lock once and
// keep whatever they got. Prints the winner count of each trial, one per line.
function raceTrials(take: string, trials: number, racers: number): number[] {
const dir = fresh();
const r = bash(`
. '${HELPER}'
for t in $(seq 1 ${trials}); do
L="${dir}/lock.$t"; S="${dir}/start.$t"; W="${dir}/winners.$t"; : > "$W"
for i in $(seq 1 ${racers}); do
( while [ ! -e "$S" ]; do sleep 0.005; done; if ${take}; then echo "$BASHPID" >> "$W"; fi ) &
done
sleep 0.05; : > "$S"; wait
wc -l < "$W" | tr -d ' '
done`, LYING, 120_000);
expect(r.err).toBe('');
expect(r.code).toBe(0);
return r.out.trim().split('\n').map(Number);
}
describe('a mkdir that lies (uutils 0.8.0 shim)', () => {
// Value: protects=the repro: the old mkdir lock admits two holders under uutils-style mkdir; fails_when=the shim stops lying (then nothing below proves the fix); why_new=no test ran a lock against a lying mkdir; seam=PATH shim; no_claim=that real uutils races at this rate (GBEV-3 measured 60/300 on the image)
test('the old `mkdir "$LOCK"` pattern lets two racing holders both win', () => {
const wins = raceTrials('mkdir "$L" 2>/dev/null', 10, 4);
expect(wins.length).toBe(10);
expect(wins.filter(n => n > 1).length).toBeGreaterThan(0);
}, 120_000);
// Value: protects=exactly one holder per race whatever mkdir reports; fails_when=gstack_lock_take trusts mkdir's status or drops the O_EXCL create; why_new=first lock test with a lying mkdir; seam=PATH shim; no_claim=behaviour on filesystems without O_EXCL (old NFS)
test('gstack_lock_take never lets two win across many races', () => {
const wins = raceTrials('gstack_lock_take "$L" pid "$BASHPID"', 60, 4);
expect(wins.length).toBe(60);
expect(wins.filter(n => n !== 1)).toEqual([]);
}, 120_000);
// Value: protects=mutual exclusion through take, hold and release cycles; fails_when=a release (rm -rf) races a taker into a second holder; why_new=the races above never release; seam=PATH shim; no_claim=fairness or wait bounds, which stay each caller's
test('take, hold and release loops never overlap inside the lock', () => {
const dir = fresh();
const r = bash(`
. '${HELPER}'
L="${dir}/lock"; IN="${dir}/inside"; OV="${dir}/overlaps"; DONE="${dir}/done"
for i in 1 2 3 4; do
( for k in 1 2 3 4 5 6 7 8; do
until gstack_lock_take "$L"; do sleep 0.005; done
( set -o noclobber; : > "$IN" ) 2>/dev/null || echo overlap >> "$OV"
sleep 0.01; rm -f "$IN"; rm -rf "$L"; echo x >> "$DONE"
done ) &
done
wait; wc -l < "$DONE" | tr -d ' '; [ -e "$OV" ] && cat "$OV"; true`, LYING, 120_000);
expect(r.err).toBe('');
expect(r.out.trim()).toBe('32');
}, 120_000);
// Value: protects=gstack-config's concurrent writers keep every key under a lying mkdir; fails_when=gstack-config's lock goes back to mkdir's status; why_new=the existing parallel-writer test runs only on GNU mkdir; seam=PATH shim; no_claim=the other converted callers, covered by the source guard below
test('parallel gstack-config writers lose no key', () => {
const state = fresh();
const r = bash(`
for i in $(seq 1 8); do bash '${path.join(ROOT, 'bin', 'gstack-config')}' set "race_key_$i" "v$i" >/dev/null & done
wait`, { ...LYING, GSTACK_STATE_ROOT: state }, 120_000);
expect(r.code).toBe(0);
const yaml = fs.readFileSync(path.join(state, 'config.yaml'), 'utf8');
const missing = Array.from({ length: 8 }, (_, i) => `race_key_${i + 1}: v${i + 1}`).filter(l => !yaml.includes(l));
expect(missing).toEqual([]);
}, 120_000);
});
describe('gstack_lock_take contract (real mkdir)', () => {
// Value: protects=the return codes and owner file callers rely on; fails_when=take steals an existing or ownerless lock, follows a symlink, reports an unwritable parent as contention, or leaks noclobber; why_new=new helper; seam=none; no_claim=each caller's stale-lock recovery, tested in its own file
test('takes a free lock once, writes the owner file, and refuses a held one', () => {
const d = fresh();
const r = bash(`. '${HELPER}'
gstack_lock_take "${d}/a"; echo "first=$?"
gstack_lock_take "${d}/a" pid other; echo "second=$?"
gstack_lock_take "${d}/b" owner "tok 1"; echo "custom=$?"`);
expect(r.out).toBe('first=0\nsecond=1\ncustom=0\n');
expect(fs.readFileSync(path.join(d, 'a', 'pid'), 'utf8')).toMatch(/^\d+\n$/);
expect(fs.readFileSync(path.join(d, 'b', 'owner'), 'utf8')).toBe('tok 1\n');
});
test('an existing directory, even with no owner file, stays held', () => {
const d = fresh();
fs.mkdirSync(path.join(d, 'lock'));
const r = bash(`. '${HELPER}'; gstack_lock_take "${d}/lock"; echo "rc=$?"`);
expect(r.out).toBe('rc=1\n');
expect(fs.readdirSync(path.join(d, 'lock'))).toEqual([]);
});
test('a symlink at the lock path is held, never followed', () => {
const d = fresh();
fs.mkdirSync(path.join(d, 'elsewhere'));
fs.symlinkSync(path.join(d, 'elsewhere'), path.join(d, 'lock'));
const r = bash(`. '${HELPER}'; gstack_lock_take "${d}/lock"; echo "rc=$?"`);
expect(r.out).toBe('rc=1\n');
expect(fs.readdirSync(path.join(d, 'elsewhere'))).toEqual([]);
});
test('an owner file that cannot be written is 3 and leaves no directory behind', () => {
const d = fresh();
const r = bash(`. '${HELPER}'; umask 0777; gstack_lock_take "${d}/lock"; echo "rc=$?"`);
expect(r.out).toMatch(/^rc=(3|0)\n$/);
if (r.out === 'rc=3\n') expect(fs.existsSync(path.join(d, 'lock'))).toBe(false);
});
test.skipIf(process.platform === 'win32')('an owner file whose write fails is 3, leaves no lock behind, and the next take succeeds', () => {
const d = fresh();
const r = bash(`. '${HELPER}'
( ulimit -f 0; gstack_lock_take "${d}/lock"; echo "full=$?" )
gstack_lock_take "${d}/lock"; echo "next=$?"`);
expect(r.out).toBe('full=3\nnext=0\n');
expect(fs.readFileSync(path.join(d, 'lock', 'pid'), 'utf8')).toMatch(/^\d+\n$/);
});
test('a missing or unwritable parent is 2, not contention', () => {
const d = fresh();
const ro = path.join(d, 'ro');
fs.mkdirSync(ro, { mode: 0o555 });
const r = bash(`. '${HELPER}'
gstack_lock_take "${d}/missing/lock"; echo "missing=$?"
[ -w '${ro}' ] && echo "ro=skip" || { gstack_lock_take '${ro}/lock'; echo "ro=$?"; }`);
expect(r.out).toMatch(/^missing=2\nro=(2|skip)\n$/);
expect(fs.existsSync(path.join(d, 'missing'))).toBe(false);
fs.chmodSync(ro, 0o755);
});
test('runs under set -euo pipefail and leaves noclobber off in the caller', () => {
const d = fresh();
fs.writeFileSync(path.join(d, 'existing'), 'old\n');
const r = bash(`set -euo pipefail; . '${HELPER}'
gstack_lock_take "${d}/lock"
rc=0; gstack_lock_take "${d}/lock" || rc=$?; echo "held=$rc"
echo new > "${d}/existing"; echo "clobber=$(cat "${d}/existing")"`);
expect(r.err).toBe('');
expect(r.out).toBe('held=1\nclobber=new\n');
});
});
+5 -4
View File
@@ -265,12 +265,13 @@ describe('settings hook preserves the resolved settings target', () => {
fs.writeFileSync(target + '.lock/owner', 'fixture-owner');
const bin = path.join(root, 'bin');
fs.mkdirSync(bin);
const realMkdir = spawnSync('which', ['mkdir'], { encoding: 'utf8', timeout: 5_000 }).stdout.trim();
expect(realMkdir).not.toBe('');
// The writer is seen waiting when it reads the held lock's age (gstack_lock_take never runs mkdir on a held lock).
const realStat = spawnSync('which', ['stat'], { encoding: 'utf8', timeout: 5_000 }).stdout.trim();
expect(realStat).not.toBe('');
const observed = path.join(root, 'lock-observed');
fs.writeFileSync(path.join(bin, 'mkdir'), '#!/bin/bash\nif [ "$1" = "$LOCK_EXPECTED" ]; then printf seen > "$LOCK_OBSERVED"; fi\nexec "$REAL_MKDIR" "$@"\n', { mode: 0o755 });
fs.writeFileSync(path.join(bin, 'stat'), '#!/bin/bash\nif [ "${@: -1}" = "$LOCK_EXPECTED" ]; then printf seen > "$LOCK_OBSERVED"; fi\nexec "$REAL_STAT" "$@"\n', { mode: 0o755 });
const child = spawn('bash', [hook, ...addArgs()], {
env: { ...env(), PATH: `${bin}:${process.env.PATH}`, LOCK_EXPECTED: target + '.lock', LOCK_OBSERVED: observed, REAL_MKDIR: realMkdir },
env: { ...env(), PATH: `${bin}:${process.env.PATH}`, LOCK_EXPECTED: target + '.lock', LOCK_OBSERVED: observed, REAL_STAT: realStat },
stdio: ['ignore', 'pipe', 'pipe'], timeout: 5_000,
});
let stderr = '';
+1 -1
View File
@@ -17,7 +17,7 @@ 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-upgrade', 'bin/gstack-bun-version.sh', 'bin/gstack-paths', 'bin/gstack-state-root.sh', 'bin/gstack-lock.sh',
'bin/gstack-egress-lib.sh', 'bin/gstack-egress-receipt', 'lib/egress-receipt.ts', 'lib/state-root.ts',
'bin/gstack-lease', 'bin/gstack-harness-pid.sh', 'bin/gstack-install-verdict.sh', 'bin/gstack-ff-update',
];
+5 -3
View File
@@ -6,8 +6,10 @@
* (`./evals.sh case <id>`) and a gate command (`./evals.sh gate`), all local
* stubs that cost nothing. The rule case `queue-priorities` reads a task list
* that storage returns in seed-dependent order and compares it to the sorted
* expectation. Each `case` invocation claims the lowest free trial slot with
* an atomic `mkdir` (slots reset per ship-measure round, keyed on the round
* expectation. Each `case` invocation claims the lowest free trial slot by
* creating its slot file with noclobber, which the shell opens O_EXCL (not
* mkdir, whose exit status lies on Ubuntu 26.04's uutils mkdir; slots reset
* per ship-measure round, keyed on the round
* directory), and the slot is the seed: while src/priorities.js leaves the
* list unsorted, slots whose number mod 10 is 2, 5 or 9 fail (3 of 10). The
* failure prints `failure_cause` and `failure_detail` naming the line. The
@@ -84,7 +86,7 @@ case "\${1:-}" in
case "$id" in ${SEEDED_CASE}|${STABLE_CASE}) ;; *) echo "unknown case: $id (cases: ${SEEDED_CASE}, ${STABLE_CASE})" >&2; exit 2 ;; esac
if [ -n "\${GSTACK_SHIP_MEASURE_DIR:-}" ]; then slots="$(dirname "$GSTACK_SHIP_MEASURE_DIR")/slots"; else slots="$here/.evals/slots"; fi
mkdir -p "$slots"
n=1; until mkdir "$slots/$n" 2>/dev/null; do n=$((n + 1)); done
n=1; until (set -o noclobber; : > "$slots/$n") 2>/dev/null; do n=$((n + 1)); done
out=$(run "$id" "$n" 2>&1); rc=$?
printf '%s\\n' "$out"
echo "case id=$id slot=$n sorted=$(sorted_of "$out") result=$([ $rc = 0 ] && echo pass || echo fail) measure_dir=\${GSTACK_SHIP_MEASURE_DIR:--}" >>"$log"
+131
View File
@@ -0,0 +1,131 @@
/**
* Source guard: no shell code takes a lock with mkdir's exit status.
*
* Rust coreutils (uutils) 0.8.0, the mkdir on Ubuntu 26.04 and GitHub's
* ubuntu-latest from 2026-11-09, reports success when another process created
* the directory first, so `if mkdir "$LOCK"`, `while ! mkdir`, `until mkdir`
* and `mkdir "$LOCK" && ...` / `|| ...` let two holders in at once. Every lock
* goes through gstack_lock_take (bin/gstack-lock.sh), which arbitrates with an
* O_EXCL create. This guard flags any mkdir without -p whose exit status
* decides what happens next, in shipped shell, templates, workflows, Markdown
* bash fences and TypeScript that embeds shell. Plain `mkdir -p` and a mkdir
* whose status is discarded (`|| :`, `|| true`) are ordinary and pass.
* Test files (test/...test.ts) are out of scope: they plant locks and shim mkdir on purpose.
*/
import { describe, expect, test } from 'bun:test';
import { spawnSync } from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
const ROOT = path.resolve(import.meta.dir, '..');
// Status-consuming mkdir calls that are not locks: each creates a fresh
// directory inside a private temp dir or fixture that nothing else contends for.
const NOT_LOCKS: Array<{ file: string; line: string; why: string }> = [
{ file: 'bin/gstack-capy-install', line: 'mkdir "$TMP/pub" &&', why: 'fresh dir inside a private mktemp dir while unpacking Bun' },
{ file: 'bin/gstack-node-runtime.sh', line: 'mkdir "$tmp/pub" &&', why: 'fresh dir inside a private mktemp dir while unpacking Node' },
{ file: 'test/fixtures/session-update-heartbeat.sh', line: 'mkdir "$FIXTURE/bin" || exit 90', why: 'fixture setup in a private temp dir' },
{ file: 'test/fixtures/session-update-heartbeat.sh', line: 'mkdir "$LOCK_DIR" || exit 92', why: 'plants the single holder of a private fixture lock; no contender exists' },
];
const SHELL_EXT = /\.(sh|bash|tmpl|ya?ml)$/;
const CODE_EXT = /\.(ts|js|mjs|cjs)$/;
function trackedFiles(): string[] {
const r = spawnSync('git', ['ls-files', '-z'], { cwd: ROOT, encoding: 'utf8', timeout: 30_000 });
expect(r.status).toBe(0);
return r.stdout.split('\0').filter(Boolean).filter(f => {
if (f.startsWith('node_modules/') || /^CHANGELOG\.md$|^TODOS\.md$|^changelog\.d\//.test(f)) return false;
if (/^test\/.*\.test\.ts$/.test(f)) return false;
return fs.statSync(path.join(ROOT, f), { throwIfNoEntry: false })?.isFile() ?? false;
});
}
/** The lines of a file that run as shell (or embed it), comments dropped. */
function shellLines(file: string, text: string): Array<[number, string]> {
const lines = text.split('\n');
const out: Array<[number, string]> = [];
if (file.endsWith('.md')) {
let inBash = false;
lines.forEach((l, i) => {
if (/^\s*```/.test(l)) { inBash = /^\s*```(bash|sh|shell)\s*$/.test(l) && !inBash; return; }
if (inBash && !/^\s*#/.test(l)) out.push([i + 1, l]);
});
return out;
}
const shellish = SHELL_EXT.test(file) || /^#!.*\b(ba|z|da)?sh\b/.test(lines[0] ?? '');
if (!shellish && !CODE_EXT.test(file)) return out;
lines.forEach((l, i) => {
if (shellish ? /^\s*#/.test(l) : /^\s*(\/\/|\*|\/\*)/.test(l)) return;
out.push([i + 1, l]);
});
return out;
}
/** mkdir calls without -p whose exit status a condition or && / || consumes. */
export function statusConsumingMkdirs(line: string): string[] {
const hits: string[] = [];
const re = /(^|[^A-Za-z0-9_.$\/-])mkdir\b(?!Sync|Secure|\s*\(|\s*[,:}]|['"`])/g;
let m: RegExpExecArray | null;
while ((m = re.exec(line))) {
const start = m.index + m[1]!.length;
const rest = line.slice(start + 'mkdir'.length);
const end = rest.search(/;|&&|\|\||\||\)|\}|`|\s(then|do)\b|$/);
const args = rest.slice(0, end);
if (/(^|\s)(-[A-Za-z]*p[A-Za-z]*|--parents)\b/.test(args)) continue;
const before = line.slice(0, start).replace(/\s+$/, '');
const after = rest.slice(end).replace(/^\s+/, '');
const conditioned = /(^|[\s;({])(if|elif|while|until)(\s+!)?$|(&&|\|\||!)$/.test(before);
const chained = /^(&&|\|\|)/.test(after) && !/^\|\|\s*(:|true)\s*($|[;)}])/.test(after);
if (conditioned || chained) hits.push(line.slice(start, start + 'mkdir'.length + end + 12).trim());
}
return hits;
}
describe('mkdir is never a lock', () => {
// Value: protects=every lock keeps going through gstack_lock_take; fails_when=a new if/while/until mkdir or mkdir && / || appears outside the reasoned allowlist; why_new=Ubuntu 26.04's uutils mkdir made the pattern unsafe; seam=none; no_claim=locks written in other languages, or a mkdir whose status reaches a later `$?` test
test('no shipped shell, template, workflow or embedded shell decides on mkdir\'s exit status', () => {
const found: string[] = [];
for (const file of trackedFiles()) {
if (!SHELL_EXT.test(file) && !CODE_EXT.test(file) && !file.endsWith('.md') && path.extname(file) !== '') continue;
const text = fs.readFileSync(path.join(ROOT, file), 'utf8');
if (text.includes('\0')) continue;
for (const [n, line] of shellLines(file, text)) {
if (!line.includes('mkdir')) continue;
if (NOT_LOCKS.some(a => a.file === file && line.includes(a.line))) continue;
for (const hit of statusConsumingMkdirs(line)) found.push(`${file}:${n}: ${hit}`);
}
}
expect(found).toEqual([]);
});
test('every allowlist entry still matches a line, so stale entries cannot hide a new lock', () => {
const stale = NOT_LOCKS.filter(a => !fs.readFileSync(path.join(ROOT, a.file), 'utf8').includes(a.line));
expect(stale).toEqual([]);
});
// Value: protects=the detector itself; fails_when=it misses a lock form FOUN-32 found or flags ordinary mkdir -p; why_new=new guard; seam=none; no_claim=forms outside these samples
test('the detector flags each lock form and passes ordinary mkdir', () => {
for (const lock of [
'while ! mkdir "$LOCK" 2>/dev/null; do',
'until mkdir "$LOCK_DIR" 2>/dev/null; do',
' if mkdir "$_dir" 2>/dev/null; then',
'if ! mkdir "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; then',
' mkdir "$LOCK_DIR" 2>/dev/null && return 0',
' mkdir "$LOCK_DIR" 2>/dev/null || refuse "busy"',
' && mkdir -p "$(dirname "$L")" 2>/dev/null && mkdir "$L" 2>/dev/null && echo "$$" > "$L/pid"; }; then',
'n=1; until mkdir "$slots/$n" 2>/dev/null; do n=$((n + 1)); done',
]) expect({ lock, hits: statusConsumingMkdirs(lock).length }).toEqual({ lock, hits: 1 });
for (const plain of [
'mkdir -p "$STATE_DIR"',
'mkdir -p "$STATE_DIR/locks" 2>/dev/null || { _err "cannot create"; return 5; }',
'if ! mkdir -p "$GSTACK_STATE_ROOT"; then',
'mkdir -pm 700 "$d" && cd "$d"',
'mkdir "$_gl_dir" 2>/dev/null || :',
'mkdir "$x" 2>/dev/null || true',
'mkdir /work',
'fs.mkdirSync(lock);',
"const { mkdir } = await import('node:fs/promises');",
]) expect({ plain, hits: statusConsumingMkdirs(plain) }).toEqual({ plain, hits: [] });
});
});
+1 -1
View File
@@ -62,7 +62,7 @@ describe('every installed-skill render carries the plan-mode arg', () => {
});
describe('gstack-relink router re-render', () => {
const BINS = ['gstack-config', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh'];
const BINS = ['gstack-config', 'gstack-lock.sh', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh'];
const SAFE = '## Plan Mode Safe Operations';
function relinkFixture() {
+1 -1
View File
@@ -12,7 +12,7 @@ import * as os from 'os';
import * as path from 'path';
const ROOT = path.resolve(import.meta.dir, '..');
const BINS = ['gstack-config', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh'];
const BINS = ['gstack-config', 'gstack-lock.sh', 'gstack-relink', 'gstack-patch-names', 'gstack-skill-name.sh', 'gstack-state-root.sh', 'gstack-install-registry.sh'];
let tmp: string;
let install: string;
+1
View File
@@ -58,6 +58,7 @@ function setupMockInstall(skills: string[]): void {
fs.chmodSync(path.join(mockBin, 'gstack-config'), 0o755);
// A real install always ships the state-root twin beside the bins that source it.
fs.copyFileSync(path.join(BIN, 'gstack-state-root.sh'), path.join(mockBin, 'gstack-state-root.sh'));
fs.copyFileSync(path.join(BIN, 'gstack-lock.sh'), path.join(mockBin, 'gstack-lock.sh'));
fs.copyFileSync(path.join(BIN, 'gstack-skill-name.sh'), path.join(mockBin, 'gstack-skill-name.sh'));
if (fs.existsSync(path.join(BIN, 'gstack-relink'))) {
fs.copyFileSync(path.join(BIN, 'gstack-relink'), path.join(mockBin, 'gstack-relink'));
+1 -1
View File
@@ -337,7 +337,7 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
expect(cleanup!).toContain('[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR"');
// MYPID is written to the pidfile (the identity the trap compares against).
expect(src).toContain('MYPID="${BASHPID:-$(sh -c \'echo $PPID\')}"');
expect(src).toContain('echo "$MYPID" > "$LOCK_DIR/pid"');
expect(src).toContain('gstack_lock_take "$LOCK_DIR" pid "$MYPID"');
// (b) In-flight heartbeat: the step-boundary touches only fire AFTER the
// pull / setup return, so a legitimately-slow step past the 30-min TTL
// got reclaimed while ALIVE. The loop re-checks ownership each beat and
+1 -1
View File
@@ -172,7 +172,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update: the incomi
function installedUpdater(fx: Fx, checker: string): string {
const bin = path.join(fx.base, 'installed-bin');
fs.mkdirSync(bin, { recursive: true });
for (const f of ['gstack-session-update', 'gstack-state-root.sh', 'gstack-egress-lib.sh', 'gstack-egress-receipt', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-ff-update']) {
for (const f of ['gstack-session-update', 'gstack-state-root.sh', 'gstack-egress-lib.sh', 'gstack-egress-receipt', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-ff-update', 'gstack-lock.sh']) {
fs.copyFileSync(path.join(ROOT, 'bin', f), path.join(bin, f));
}
fs.writeFileSync(path.join(bin, 'gstack-hook-check'), `#!/usr/bin/env bash\n${checker}\n`, { mode: 0o755 });
+1 -1
View File
@@ -31,7 +31,7 @@ function fixture(copy: boolean) {
put(path.join(root, 'VERSION'), '2.0.0.0\n');
put(path.join(root, 'ETHOS.md'), 'Fixture ethos\n');
put(path.join(root, 'package.json'), JSON.stringify({ type: 'module', scripts: { 'gen:skill-docs': 'bun run scripts/gen-skill-docs.ts' } }));
for (const bin of ['gstack-config', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code', 'gstack-models', 'gstack-state-root.sh', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-skill-name.sh', 'gstack-claude-root.sh', 'gstack-install-registry.sh', 'gstack-render-claude.sh', 'gstack-host-renders.sh']) {
for (const bin of ['gstack-config', 'gstack-lock.sh', 'gstack-patch-names', 'gstack-relink', 'gstack-migrate-claude-code', 'gstack-claude-code', 'gstack-models', 'gstack-state-root.sh', 'gstack-bun-version.sh', 'gstack-path-spelling.sh', 'gstack-skill-name.sh', 'gstack-claude-root.sh', 'gstack-install-registry.sh', 'gstack-render-claude.sh', 'gstack-host-renders.sh']) {
const target = path.join(root, 'bin', bin);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.copyFileSync(path.join(ROOT, 'bin', bin), target);
+4 -2
View File
@@ -36,7 +36,7 @@ describe('setup-gbrain documented lock acquisition', () => {
// The block resolves the state root through the installed gstack-paths.
const installBin = path.join(home, '.claude', 'skills', 'gstack', 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-paths', 'gstack-state-root.sh']) fs.copyFileSync(path.join(import.meta.dir, '..', 'bin', b), path.join(installBin, b));
for (const b of ['gstack-paths', 'gstack-state-root.sh', 'gstack-lock.sh']) fs.copyFileSync(path.join(import.meta.dir, '..', 'bin', b), path.join(installBin, b));
fs.chmodSync(path.join(installBin, 'gstack-paths'), 0o755);
const source = fs.readFileSync(path.join(import.meta.dir, '..', 'setup-gbrain', 'SKILL.md.tmpl'), 'utf8');
const script = source.match(/\*\*Concurrent-run lock\.\*\*[\s\S]*?```bash\n([\s\S]*?)\n ```/)?.[1];
@@ -46,8 +46,10 @@ describe('setup-gbrain documented lock acquisition', () => {
if (scenario === 'fresh-home') {
expect(fs.statSync(lock).isDirectory()).toBe(true);
expect(result.stderr).toBe('');
expect(fs.readFileSync(path.join(lock, 'pid'), 'utf8')).toMatch(/^\d+\n$/);
} else {
expect(result.stderr).toContain('mkdir:');
// gstack_lock_take never runs mkdir on an existing path, so only the parent's mkdir -p error reaches stderr.
if (scenario === 'parent-file') expect(result.stderr).toContain('mkdir:');
expect(result.stderr.includes('Another /setup-gbrain instance')).toBe(scenario === 'existing-lock');
if (scenario === 'existing-lock') expect(fs.readFileSync(path.join(lock, 'owner'), 'utf8')).toBe('preserve owner');
if (scenario === 'parent-file') {
@@ -160,6 +160,8 @@ function runBlock(opts: {
'cleanup_copied_bun() { echo cleanup >> "$MARK.exit"; }',
'trap cleanup_copied_bun EXIT',
'_clear_playwright_quarantine() { :; }',
// setup sources the shared lock helper near its top; the block takes its lock with it.
`. '${path.join(ROOT, 'bin', 'gstack-lock.sh')}'`,
probeFn,
opts.prelude ?? '',
`BUN_CMD='${opts.bunCmd ?? 'bun'}'`,
+2 -2
View File
@@ -40,11 +40,11 @@ function sliceFunction(source: string, name: string): string {
return source.slice(start + 1, end + 3);
}
/** install_runtime_deps and the helpers it calls, sliced out of setup in definition order. */
/** install_runtime_deps and the helpers it calls, sliced out of setup in definition order, after the lock helper setup sources. */
function depsFunctions(setup: string): string {
const names = ['bun_cmd', '_deps_role', '_deps_has_dev', '_deps_verified', '_deps_lock', '_deps_unlock', '_deps_recover',
'_deps_migration_start', '_deps_migration_finish', 'install_runtime_deps'];
return names.map((n) => (n === '_deps_unlock' ? setup.split('\n').find((l) => l.startsWith('_deps_unlock() {'))! + '\n' : sliceFunction(setup, n))).join('\n');
return `. ${JSON.stringify(path.join(ROOT, 'bin', 'gstack-lock.sh'))}\n` + names.map((n) => (n === '_deps_unlock' ? setup.split('\n').find((l) => l.startsWith('_deps_unlock() {'))! + '\n' : sliceFunction(setup, n))).join('\n');
}
/** A git repository marked as a contributor's checkout (what bin/dev-setup writes). */
+1 -1
View File
@@ -147,7 +147,7 @@ describe('SWITCH_DEFAULT is the one default (a flip PR changes one line)', () =>
copy = tmpDir('gstack-switch-default-');
fs.cpSync(path.join(ROOT, 'lib'), path.join(copy, 'lib'), { recursive: true });
fs.cpSync(path.join(ROOT, 'hosts', 'claude', 'hooks'), path.join(copy, 'hosts', 'claude', 'hooks'), { recursive: true });
for (const f of ['gstack-config', 'gstack-state-root.sh', 'gstack-skill-route']) fs.cpSync(path.join(ROOT, 'bin', f), path.join(copy, 'bin', f));
for (const f of ['gstack-config', 'gstack-lock.sh', 'gstack-state-root.sh', 'gstack-skill-route']) fs.cpSync(path.join(ROOT, 'bin', f), path.join(copy, 'bin', f));
fs.symlinkSync(path.join(ROOT, 'node_modules'), path.join(copy, 'node_modules'));
skills = skillsDir(['verify']);
work = tmpDir('gstack-switch-default-work-');
+1 -1
View File
@@ -454,7 +454,7 @@ describe('setup --team / --no-team / -q', () => {
};
try {
for (const rel of [
'setup', 'VERSION', 'SKILL.md', 'qa/SKILL.md', 'bin/gstack-config', 'bin/gstack-patch-names',
'setup', 'VERSION', 'SKILL.md', 'qa/SKILL.md', 'bin/gstack-config', 'bin/gstack-lock.sh', 'bin/gstack-patch-names',
'bin/gstack-state-root.sh', 'bin/gstack-bun-version.sh', 'bin/gstack-path-spelling.sh', 'bin/gstack-skill-name.sh', 'bin/gstack-claude-root.sh', 'bin/gstack-install-registry.sh', 'bin/gstack-render-claude.sh', 'bin/gstack-host-renders.sh',
'scripts/resolve-codex-generation-model.ts', 'scripts/models.ts', 'scripts/preflight-codex-overlap.ts',
'scripts/discover-skills.ts', 'scripts/external-skill-names.ts', 'scripts/host-config.ts',
+7 -7
View File
@@ -298,7 +298,7 @@ describe('hook cleanup runs before the install root is deleted', () => {
fs.mkdirSync(installBin, { recursive: true });
// The installed copies — the uninstaller under test IS the one inside
// the root it deletes.
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
const src = path.join(ROOT, 'bin', b);
const dst = path.join(installBin, b);
fs.copyFileSync(src, dst);
@@ -357,7 +357,7 @@ describe('the Memorable bridge hook is removed by name and the kept config is le
const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack');
const installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
const dst = path.join(installBin, b);
fs.copyFileSync(path.join(ROOT, 'bin', b), dst);
fs.chmodSync(dst, 0o755);
@@ -400,7 +400,7 @@ describe('the Memorable arm stays quiet when nothing of its is registered', () =
const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack');
const installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
const dst = path.join(installBin, b);
fs.copyFileSync(path.join(ROOT, 'bin', b), dst);
fs.chmodSync(dst, 0o755);
@@ -432,7 +432,7 @@ describe('hook cleanup under lock contention is loud, never silent (review-army)
const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack');
const installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
const dst = path.join(installBin, b);
fs.copyFileSync(path.join(ROOT, 'bin', b), dst);
fs.chmodSync(dst, 0o755);
@@ -489,7 +489,7 @@ describe('the consent key never outlives the hook, even when the config lives ou
const installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
fs.mkdirSync(otherRoot, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-settings-hook', 'gstack-session-update', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
const dst = path.join(installBin, b);
fs.copyFileSync(path.join(ROOT, 'bin', b), dst);
fs.chmodSync(dst, 0o755);
@@ -520,7 +520,7 @@ describe('the consent flip does not depend on the hook manager being present', (
const installRoot = path.join(mockHome, '.claude', 'skills', 'gstack');
const installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh']) { // no settings hook, no session-update
for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) { // no settings hook, no session-update
const dst = path.join(installBin, b);
fs.copyFileSync(path.join(ROOT, 'bin', b), dst);
fs.chmodSync(dst, 0o755);
@@ -548,7 +548,7 @@ describe('state-root safety: only the default root is deleted (docs/state-root.m
installRoot = path.join(mockHome, '.claude', 'skills', 'gstack');
installBin = path.join(installRoot, 'bin');
fs.mkdirSync(installBin, { recursive: true });
for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh']) {
for (const b of ['gstack-uninstall', 'gstack-config', 'gstack-state-root.sh', 'gstack-lock.sh']) {
fs.copyFileSync(path.join(ROOT, 'bin', b), path.join(installBin, b));
fs.chmodSync(path.join(installBin, b), 0o755);
}
+2 -2
View File
@@ -113,7 +113,7 @@ function world(opts: { installAt?: 'A' | 'C'; stable?: boolean } = {}) {
git(seed, 'remote', 'add', 'origin', origin);
write(path.join(seed, 'bin', 'gstack-config'), CONFIG_STUB, 0o755);
write(path.join(seed, 'bin', 'gstack-patch-names'), '#!/usr/bin/env bash\nexit 0\n', 0o755);
for (const rel of ['bin/gstack-sanitize-echo.sh', 'bin/gstack-update-channel.sh', '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', 'bin/gstack-lease', 'bin/gstack-harness-pid.sh', 'bin/gstack-install-verdict.sh', 'bin/gstack-upgrade']) {
for (const rel of ['bin/gstack-sanitize-echo.sh', 'bin/gstack-update-channel.sh', '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', 'bin/gstack-lease', 'bin/gstack-lock.sh', 'bin/gstack-harness-pid.sh', 'bin/gstack-install-verdict.sh', 'bin/gstack-upgrade']) {
if (!fs.existsSync(path.join(ROOT, rel))) continue;
fs.mkdirSync(path.dirname(path.join(seed, rel)), { recursive: true });
fs.copyFileSync(path.join(ROOT, rel), path.join(seed, rel));
@@ -328,7 +328,7 @@ describe.skipIf(process.platform === 'win32')('gstack-update-check on the stable
const realGit = execFileSync('bash', ['-c', 'command -v git'], { encoding: 'utf8', timeout: 10_000, env: ENV }).trim();
const gitLog = path.join(base, 'git.log');
fs.writeFileSync(path.join(shim, 'git'), '#!/usr/bin/env bash\ncase "$1" in ls-remote) echo "git $*" >> "' + gitLog + '" ;; esac\nexec "' + realGit + '" "$@"\n', { mode: 0o755 });
for (const name of ['gstack-config', 'gstack-egress-lib.sh', 'gstack-state-root.sh', 'gstack-egress-receipt', 'gstack-update-channel.sh']) fs.symlinkSync(path.join(ROOT, 'bin', name), path.join(gstack, 'bin', name));
for (const name of ['gstack-config', 'gstack-lock.sh', 'gstack-egress-lib.sh', 'gstack-state-root.sh', 'gstack-egress-receipt', 'gstack-update-channel.sh']) fs.symlinkSync(path.join(ROOT, 'bin', name), path.join(gstack, 'bin', name));
fs.writeFileSync(path.join(gstack, 'VERSION'), '1.0.0\n');
fs.writeFileSync(path.join(gstack, '.gitignore'), 'bin/\n');
execFileSync('git', ['init', '-q', '--bare', '-b', 'main', origin], { timeout: 30_000, env: ENV });