Use Garry Tan's exact Claude Code setup: 23 opinionated tools that serve as CEO, Designer, Eng Manager, Release Manager, Doc Engineer, and QA
TypeScript
Make gstack's shell locks hold when mkdir reports a race it lost (GST-2247) (#4262)
Garry Tanbcece3fbcdf0
diff --git a/USING_GBRAIN_WITH_GSTACK.md b/USING_GBRAIN_WITH_GSTACK.mdindex d4a59d370..457bdeea3 100644--- a/USING_GBRAIN_WITH_GSTACK.md+++ b/USING_GBRAIN_WITH_GSTACK.md@@ -243,7 +243,7 @@ Gbrain itself ships with these that gstack wraps:|---|---|| `~/.gbrain/config.json` | Engine (pglite/postgres), database URL or path, API keys. Mode 0600. Written by `gbrain init`. When `GBRAIN_HOME` is set, gbrain and gstack's helpers read `$GBRAIN_HOME/.gbrain/config.json` instead. || `~/.gstack/gbrain-repo-policy.json` | Per-remote trust triad. Schema v2. Mode 0600. |-| `~/.gstack/.setup-gbrain.lock.d` | Concurrent-run lock (atomic mkdir). Released on normal exit + SIGINT. |+| `~/.gstack/.setup-gbrain.lock.d` | Concurrent-run lock: a directory whose `pid` file is created with O_EXCL (`gstack_lock_take`, `bin/gstack-lock.sh`), so it holds even where `mkdir` misreports a race. Released on normal exit + SIGINT. || `~/.gstack/.brain-queue.d/` | Pending sync records for gstack memory sync — maildir-style spool, one file per record. A legacy `.brain-queue.jsonl` from older releases migrates automatically on the next drain. || `~/.gstack/.brain-last-push` | Timestamp of last sync push (for `/health` scoring) || `~/.gstack-artifacts-remote.txt` | URL of your gstack memory sync remote (safe to copy between machines; legacy name `~/.gstack-brain-remote.txt` still read) |diff --git a/bin/gstack-brain-lock.sh b/bin/gstack-brain-lock.shindex 2f60ac942..110caebb0 100644--- a/bin/gstack-brain-lock.sh+++ b/bin/gstack-brain-lock.sh@@ -23,10 +23,14 @@# gstack_brain_lock_release# Removes the lock only when this process took it and still owns it.#-# The lock is a directory (mkdir is atomic on every POSIX filesystem; flock(1)-# is not on macOS) holding `pid` and `owner`. A lock whose pid is dead is-# stale and is cleared. A lock directory with no pid file is a holder killed-# between mkdir and the pid write once it is older than 10 minutes.+# The lock is a directory holding `pid` and `owner`, taken with+# gstack_lock_take (bin/gstack-lock.sh), which creates `pid` with O_EXCL:+# mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir, and+# flock(1) is not on macOS. A lock whose pid is dead is stale and is cleared.+# A lock directory with no pid file is a holder killed between mkdir and the+# pid write once it is older than 10 minutes.++. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; }_GSTACK_BRAIN_LOCK_DIR=""_GSTACK_BRAIN_LOCK_MINE=0@@ -34,10 +38,9 @@ _GSTACK_BRAIN_LOCK_HOLDER=""_gstack_brain_lock_try_once() {local dir="$1" pid- if mkdir "$dir" 2>/dev/null; then+ if gstack_lock_take "$dir" pid "$$"; thenGSTACK_BRAIN_LOCK_TOKEN="$$-${RANDOM:-0}-$(date +%s 2>/dev/null || echo 0)"export GSTACK_BRAIN_LOCK_TOKEN- printf '%s\n' "$$" > "$dir/pid" 2>/dev/null || trueprintf '%s\n' "$GSTACK_BRAIN_LOCK_TOKEN" > "$dir/owner" 2>/dev/null || true_GSTACK_BRAIN_LOCK_MINE=1return 0diff --git a/bin/gstack-browser-ensure b/bin/gstack-browser-ensureindex 0f87e3274..95e1d1824 100755--- a/bin/gstack-browser-ensure+++ b/bin/gstack-browser-ensure@@ -101,8 +101,9 @@ BUN=$(command -v bun 2>/dev/null) || fail "Chromium is not installed and bun is# Same lock ./setup takes (#2136), so two installs never race on the cache.LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock"+. "$ROOT/bin/gstack-lock.sh" 2>/dev/null || fail "$ROOT/bin/gstack-lock.sh is missing" "reinstall with cd $ROOT && ./setup"tries=0-while ! mkdir "$LOCK" 2>/dev/null; do+while ! gstack_lock_take "$LOCK" pid "$$"; doholder=$(cat "$LOCK/pid" 2>/dev/null || true)case "$holder" in ''|*[!0-9]*) holder=0 ;; esacif [ "$holder" -eq 0 ] || ! kill -0 "$holder" 2>/dev/null; then rm -rf "$LOCK" 2>/dev/null; continue; fi@@ -110,7 +111,6 @@ while ! mkdir "$LOCK" 2>/dev/null; do[ "$tries" -ge "$TIMEOUT" ] && fail "another gstack install holds the Chromium lock ($LOCK, pid $holder)" "wait for it, or remove a stale lock: rm -rf \"$LOCK\""sleep 1done-echo "$$" > "$LOCK/pid" 2>/dev/null || truetrap 'rm -rf "$LOCK" 2>/dev/null' EXIT INT TERMOVERRIDE=""diff --git a/bin/gstack-capy-session b/bin/gstack-capy-sessionindex 314390708..64b83926f 100755--- a/bin/gstack-capy-session+++ b/bin/gstack-capy-session@@ -283,7 +283,7 @@ EOF_OWNreport_behind "$RERUN"export GSTACK_CAPY_BEHIND_BLOCKED="$REASON"elif [ -n "$SWITCH" ] && ! { SETUP_LOCK="$("$ROOT/bin/gstack-paths" --get GSTACK_STATE_ROOT 2>/dev/null)/.setup-lock"; [ "$SETUP_LOCK" != /.setup-lock ] \- && mkdir -p "$(dirname "$SETUP_LOCK")" 2>/dev/null && mkdir "$SETUP_LOCK" 2>/dev/null && echo "$$" > "$SETUP_LOCK/pid"; }; then+ && mkdir -p "$(dirname "$SETUP_LOCK")" 2>/dev/null && . "$ROOT/bin/gstack-lock.sh" && gstack_lock_take "$SETUP_LOCK" pid "$$"; }; then# The switch and the fast-forward happen under gstack-upgrade's setup lock,# taken here and handed over in GSTACK_SETUP_LOCK_OWNER, so a concurrent# updater never sees the checkout between the two.diff --git a/bin/gstack-codex-probe b/bin/gstack-codex-probeindex 9f0a4f115..afbcadab0 100755--- a/bin/gstack-codex-probe+++ b/bin/gstack-codex-probe@@ -103,6 +103,7 @@ fi# === end gstack self-locate ===_GSTACK_CODEX_BIN="$_gstack_helper_dir"unset _gstack_helper _gstack_helper_dir _gstack_helper_shell+. "$_GSTACK_CODEX_BIN/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { return 2; }# --- Auth probe -------------------------------------------------------------@@ -631,19 +632,16 @@ _gstack_codex_probe_cache_store() {_gstack_codex_lock_acquire() {# $1 lock directory, $2 seconds to wait, $3 seconds after which even a live- # owner is abandoned. mkdir is atomic on every platform bash runs on. A dead- # owner on this host is recovered at once; a missing owner file is the+ # owner is abandoned. gstack_lock_take (bin/gstack-lock.sh) creates the owner+ # file with O_EXCL, since mkdir's exit status is not a lock on Ubuntu 26.04's+ # uutils mkdir. A dead owner on this host is recovered at once; a missing owner file is the# creation window and becomes stale after 5 seconds. 0 = held, 1 = timed# out, 2 = the lock or its owner record cannot be created.local _dir="$1" _tries=$(( ${2:-45} * 10 )) _stale="${3:-90}" _host _owner _pid _ohost _ts _now _i=0 _dead_host=$(uname -n 2>/dev/null || echo unknown)while :; do- if mkdir "$_dir" 2>/dev/null; then- printf '%s %s %s\n' "$$" "$_host" "$(date +%s 2>/dev/null || echo 0)" > "$_dir/owner" 2>/dev/null && return 0- rm -f "$_dir/owner" 2>/dev/null- rmdir "$_dir" 2>/dev/null- return 2- fi+ gstack_lock_take "$_dir" owner "$$ $_host $(date +%s 2>/dev/null || echo 0)"+ case $? in 0) return 0 ;; 3) return 2 ;; esacif [ ! -d "$_dir" ]; then{ [ -e "$_dir" ] || [ -L "$_dir" ]; } && return 2{ [ -d "${_dir%/*}" ] && [ -w "${_dir%/*}" ] && [ -x "${_dir%/*}" ]; } || return 2@@ -677,15 +675,15 @@ _gstack_codex_lock_break() {# Breakers serialize on $1.break and remove the lock only if it still has the# owner they judged abandoned, so a lock re-taken meanwhile survives.local _dir="$1" _seen="$2" _bt _now- if mkdir "$_dir.break" 2>/dev/null; then+ if gstack_lock_take "$_dir.break" pid "$$"; then[ "$(cat "$_dir/owner" 2>/dev/null)" = "$_seen" ] && rm -rf "$_dir" 2>/dev/null- rmdir "$_dir.break" 2>/dev/null+ rm -rf "$_dir.break" 2>/dev/nullreturn 0fi_now=$(date +%s 2>/dev/null || echo 0)_bt=$(stat -c %Y "$_dir.break" 2>/dev/null || stat -f %m "$_dir.break" 2>/dev/null || echo "$_now")case "$_bt" in ''|*[!0-9]*) _bt="$_now" ;; esac- [ $((_now - _bt)) -ge 10 ] && rmdir "$_dir.break" 2>/dev/null+ [ $((_now - _bt)) -ge 10 ] && rm -rf "$_dir.break" 2>/dev/nullreturn 0}diff --git a/bin/gstack-config b/bin/gstack-configindex 8eb26cf72..89c4a8150 100755--- a/bin/gstack-config+++ b/bin/gstack-config@@ -552,18 +552,21 @@ read_config_value() {# ── Config writes: one lock, one read-modify-write rename ──────────────────# Every mutation of config.yaml (set, unset, the transcript_repos pair, the-# user-slug writer) holds an atomic mkdir lock and replaces the file with one+# user-slug writer) holds one lock directory and replaces the file with one# rename, so concurrent writers never lose each other's keys and an-# interrupted write leaves the old file. The pid file holds "<pid> <epoch>";-# a lock whose holder is dead or older than 10 s is taken over. No flock(1):-# stock macOS does not ship it.+# interrupted write leaves the old file. The lock is taken with+# gstack_lock_take (bin/gstack-lock.sh), which creates the pid file with+# O_EXCL because mkdir's exit status is not a lock on Ubuntu 26.04's uutils+# mkdir. The pid file holds "<pid> <epoch>"; a lock whose holder is dead or+# older than 10 s is taken over. No flock(1): stock macOS does not ship it.CONFIG_LOCK="$STATE_DIR/.config-yaml.lock"_config_locked=""config_lock() {mkdir -p "$STATE_DIR"+ . "$(dirname "$0")/gstack-lock.sh" 2>/dev/null || { echo "Error: $(dirname "$0")/gstack-lock.sh is missing. Existing value left unchanged. fix: reinstall with ./setup or /gstack-upgrade" >&2; exit 1; }local waited=0 held pid ts stale- while ! mkdir "$CONFIG_LOCK" 2>/dev/null; do+ while ! gstack_lock_take "$CONFIG_LOCK" pid "$$ $(date +%s)"; doif [ ! -w "$STATE_DIR" ]; thenecho "Error: cannot write to $STATE_DIR (its config lock could not be created). Existing value left unchanged." >&2exit 1@@ -589,7 +592,6 @@ config_lock() {fisleep 0.05done- printf '%s %s\n' "$$" "$(date +%s)" > "$CONFIG_LOCK/pid"_config_locked=1trap 'config_unlock' EXIT}diff --git a/bin/gstack-developer-profile b/bin/gstack-developer-profileindex 624dc723c..2db44df2e 100755--- a/bin/gstack-developer-profile+++ b/bin/gstack-developer-profile@@ -66,16 +66,18 @@ shift || true# changes and renames the whole file, and gstack-question-log starts a# background --derive after every append, so writers overlap: a shared temp# name made renames fail and an unlocked rewrite dropped a concurrent-# --log-session. Writers hold a mkdir lock (<profile>.lock/, whose owner file+# --log-session. Writers hold a lock directory (<profile>.lock/, whose owner file# names the holder's pid and a random token; release is ownership-checked)# from before their read until after their rename, and write a unique temp# file. A lock whose holder process is gone is taken over at once; one older# than 5 minutes is taken over even when its pid is alive, since no writer-# runs that long and the pid may have been reused. Takeovers are serialized by a second mkdir lock+# runs that long and the pid may have been reused. Takeovers are serialized by a second lock# (<profile>.lock.takeover/) and re-read the owner under it, so two waiters# cannot both take over or remove a lock a third writer just took. A lock or# takeover directory older than 30 s with no owner belongs to a writer that-# died before writing one; cleanup removes a takeover lock this writer holds. A writer that cannot get the lock within the+# died before writing one; cleanup removes a takeover lock this writer holds. Both locks+# are taken with gstack_lock_take (bin/gstack-lock.sh): mkdir's exit status is not+# a lock on Ubuntu 26.04's uutils mkdir, so the owner file is created with O_EXCL. A writer that cannot get the lock within the# give-up window writes nothing and exits 5. Writers outside this binary# (gstack-distill-apply, /plan-tune's declared edits) do not take it yet.# -----------------------------------------------------------------------@@ -87,7 +89,7 @@ PROFILE_TMP=""cleanup() {if [ -n "$PROFILE_TMP" ]; then rm -f "$PROFILE_TMP"; fi- if [ -n "$HOLDS_TAKEOVER" ]; then rmdir "$TAKEOVER_DIR" 2>/dev/null || true; fi+ if [ -n "$HOLDS_TAKEOVER" ]; then rm -rf "$TAKEOVER_DIR" 2>/dev/null || true; fiif [ -n "$LOCK_TOKEN" ] && [ "$(cat "$LOCK_DIR/owner" 2>/dev/null || true)" = "$LOCK_TOKEN" ]; thenrm -rf "$LOCK_DIR"fi@@ -117,8 +119,9 @@ acquire_lock() {# GSTACK_PROFILE_LOCK_TIMEOUT_MS: test-only override for the give-up.local give_up_ms="${GSTACK_PROFILE_LOCK_TIMEOUT_MS:-10000}" waited_ms=0 started=$SECONDS vanished=0 ownerlocal token="$$-$RANDOM$RANDOM"- until mkdir "$LOCK_DIR" 2>/dev/null; do- # mkdir failed with no lock to wait for: retry once in case a holder just+ . "$SCRIPT_DIR/gstack-lock.sh" 2>/dev/null || { echo "gstack-developer-profile: $SCRIPT_DIR/gstack-lock.sh is missing, so nothing was written (exit 5). fix: reinstall with ./setup or /gstack-upgrade" >&2; exit 5; }+ until gstack_lock_take "$LOCK_DIR" owner "$token"; do+ # The take failed with no lock to wait for: retry once in case a holder just# released it, then report the directory instead of waiting out the window.if [ ! -e "$LOCK_DIR" ]; thenif [ "$vanished" -eq 0 ]; then vanished=1; continue; fi@@ -128,13 +131,13 @@ acquire_lock() {vanished=0owner=$(cat "$LOCK_DIR/owner" 2>/dev/null || true)if [ -d "$LOCK_DIR" ] && lock_abandoned "$owner"; then- if [ -d "$TAKEOVER_DIR" ] && [ "$(dir_age_s "$TAKEOVER_DIR")" -gt 30 ]; then rmdir "$TAKEOVER_DIR" 2>/dev/null || true; fi- if mkdir "$TAKEOVER_DIR" 2>/dev/null; then+ if [ -d "$TAKEOVER_DIR" ] && [ "$(dir_age_s "$TAKEOVER_DIR")" -gt 30 ]; then rm -rf "$TAKEOVER_DIR" 2>/dev/null || true; fi+ if gstack_lock_take "$TAKEOVER_DIR" pid "$$"; thenHOLDS_TAKEOVER=1if [ "$(cat "$LOCK_DIR/owner" 2>/dev/null || true)" = "$owner" ] && lock_abandoned "$owner"; thenrm -rf "$LOCK_DIR" 2>/dev/null || truefi- rmdir "$TAKEOVER_DIR" 2>/dev/null || true+ rm -rf "$TAKEOVER_DIR" 2>/dev/null || trueHOLDS_TAKEOVER=""if [ ! -e "$LOCK_DIR" ]; then continue; fifi@@ -146,7 +149,6 @@ acquire_lock() {sleep 0.05waited_ms=$(( waited_ms + 50 ))done- printf '%s\n' "$token" > "$LOCK_DIR/owner"LOCK_TOKEN="$token"}diff --git a/bin/gstack-ff-update b/bin/gstack-ff-updateindex 8ee22267a..a385fe80e 100755--- a/bin/gstack-ff-update+++ b/bin/gstack-ff-update@@ -9,7 +9,8 @@# the new revision (git show FETCH_HEAD:bin/gstack-ff-update) and run it in a# private temp directory, so it sources nothing. The lock and the# flatten-and-strip sanitizer are inlined; test/gstack-ff-update.test.ts pins-# them to their twins in bin/gstack-session-update.+# them to their twins in bin/gstack-session-update, and gstack_lock_take to+# bin/gstack-lock.sh.## Inside an install-scoped lock (<git-common-dir>/gstack-ff.lock):# 1. The working tree is captured as-is through a private index (tracked@@ -115,18 +116,38 @@ LOCK_DIR="$COMMON/gstack-ff.lock"LOCK_TTL_MINUTES=30MYPID=$$OWN_INDEX_LOCK="" TMP="" HB_PID=""+# Twin of bin/gstack-lock.sh (test-pinned): mkdir's exit status is not a lock+# on Ubuntu 26.04's uutils mkdir, so the pid file is created with O_EXCL.+gstack_lock_take() {+ local _gl_dir="$1" _gl_file="${2:-pid}" _gl_content="${3:-$$}"+ if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi+ mkdir "$_gl_dir" 2>/dev/null || :+ if [ ! -d "$_gl_dir" ] || [ -L "$_gl_dir" ]; then+ if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi+ return 2+ fi+ local _gl_opened+ _gl_opened=$(set -o noclobber; { echo o; printf '%s\n' "$_gl_content" >&3; } 2>/dev/null 3> "$_gl_dir/$_gl_file") && return 0+ if [ "$_gl_opened" = o ]; then+ rm -f "$_gl_dir/$_gl_file"; rmdir "$_gl_dir" 2>/dev/null || :+ return 3+ fi+ if [ -e "$_gl_dir/$_gl_file" ] || [ -L "$_gl_dir/$_gl_file" ] || [ ! -d "$_gl_dir" ]; then return 1; fi+ rmdir "$_gl_dir" 2>/dev/null || :+ return 3+}lock_is_expired() {_hb="$LOCK_DIR/pid"[ -f "$_hb" ] || _hb="$LOCK_DIR"[ -n "$(find "$_hb" -maxdepth 0 -mmin +$LOCK_TTL_MINUTES 2>/dev/null)" ]}lock_try() {- mkdir "$LOCK_DIR" 2>/dev/null && return 0+ gstack_lock_take "$LOCK_DIR" pid "$MYPID" && return 0_lp=$(cat "$LOCK_DIR/pid" 2>/dev/null)if lock_is_expired || { [ "${_lp:-0}" -gt 0 ] 2>/dev/null && ! kill -0 "$_lp" 2>/dev/null; }; thenmv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || return 1rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null- mkdir "$LOCK_DIR" 2>/dev/null && return 0+ gstack_lock_take "$LOCK_DIR" pid "$MYPID" && return 0fireturn 1}@@ -145,7 +166,6 @@ until lock_try; do[ "$_wait" -gt 0 ] || refuse 75 ff-busy "another gstack update is moving $DIR (lock $LOCK_DIR held by pid $(cat "$LOCK_DIR/pid" 2>/dev/null || echo unknown)); nothing was changed, retry in a minute"sleep 1; _wait=$((_wait - 1))done-echo "$MYPID" > "$LOCK_DIR/pid" 2>/dev/nulltrap cleanup_ff_update EXITtrap 'exit 129' HUPtrap 'exit 130' INTdiff --git a/bin/gstack-install-registry.sh b/bin/gstack-install-registry.shindex a56caf180..7f53f9330 100644--- a/bin/gstack-install-registry.sh+++ b/bin/gstack-install-registry.sh@@ -23,10 +23,12 @@# render render directory, or 'committed'## Callers must set GSTACK_STATE_ROOT first (bin/gstack-state-root.sh). Bash 3.2-# clean; no flock (macOS lacks it), so the lock is an atomic mkdir.+# clean; no flock (macOS lacks it), so the lock is gstack_lock_take+# (bin/gstack-lock.sh).# Same-path and containment checks (bin/gstack-path-spelling.sh).. "$(dirname "${BASH_SOURCE[0]}")/gstack-path-spelling.sh" 2>/dev/null || true+. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; }# gstack_install_move_hint SRC HOST — when HOST's runtime root ROOT is SRC (the# checkout) or contains it, `./setup --host HOST` would replace the checkout@@ -53,15 +55,17 @@ gstack_install_registry_file() {printf '%s/installs.tsv\n' "${GSTACK_STATE_ROOT:?gstack-install-registry: GSTACK_STATE_ROOT is not set}"}-# _gstack_registry_lock — take the registry lock (mkdir is atomic). A lock whose-# owner pid is gone is stale and is broken. Gives up after ~10 s.+# _gstack_registry_lock — take the registry lock (gstack_lock_take, which+# creates the pid file with O_EXCL; mkdir's exit status is not a lock on Ubuntu+# 26.04's uutils mkdir). A lock whose owner pid is gone is stale and is broken.+# Gives up after ~10 s._gstack_registry_lock() {local file lock tries ownerfile="$(gstack_install_registry_file)" || return 1lock="$file.lock"mkdir -p "$(dirname "$file")" || return 1tries=0- while ! mkdir "$lock" 2>/dev/null; do+ while ! gstack_lock_take "$lock" pid "$$"; doowner="$(cat "$lock/pid" 2>/dev/null || true)"if [ -n "$owner" ] && ! kill -0 "$owner" 2>/dev/null; thenrm -rf "$lock"@@ -74,7 +78,6 @@ _gstack_registry_lock() {fisleep 0.1done- echo "$$" > "$lock/pid"}_gstack_registry_unlock() {diff --git a/bin/gstack-lease b/bin/gstack-leaseindex 25b508700..ea6b05f42 100755--- a/bin/gstack-lease+++ b/bin/gstack-lease@@ -55,6 +55,8 @@ BIN="$(cd "$(dirname "$0")" && pwd -P)"gstack_harness_pid() { printf '%s\n' "$1"; }gstack_shared_harness() { [ "$(ps -o comm= -p "$1" 2>/dev/null | head -1 | sed 's|.*/||; s/^-//')" = capy-server ]; }}+# shellcheck source=bin/gstack-lock.sh+. "$BIN/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack-lease: $BIN/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; }VERB="${1:-}"; [ $# -gt 0 ] && shiftROOT="" PID="" EXCLUDE="" FROM="" SHARED=0 RUN=""@@ -119,21 +121,22 @@ state() {# The lease directory's lock: touch's publish and prune, and reclaim's# reread-and-delete, run under it, so a reclaim never deletes a renewal and a# lease never disappears while it is live. The lock is a directory, .lock,-# whose owner file names its holder (`<pid> <start identity>`); mkdir is-# atomic everywhere gstack runs, Git Bash on Windows included, where ln -s to a-# target that does not exist always fails (#3330). A taker publishes its token-# as a claim (.lock.claim.<pid>) before its mkdir and renames the claim into-# the lock as its owner after, so a lock without an owner is either being+# whose owner file names its holder (`<pid> <start identity>`). It is taken+# with gstack_lock_take (bin/gstack-lock.sh), which creates the owner file+# with O_EXCL: mkdir's exit status is not a lock on Ubuntu 26.04's uutils+# mkdir, and ln -s to a target that does not exist always fails on Git Bash+# (#3330). A taker publishes its token as a claim (.lock.claim.<pid>) before+# its mkdir and creates the owner file after, so a lock without an owner is either being# taken by a live claimant or orphaned by a dead one. A lock is broken only# when its holder is dead or its pid now belongs to another process, never by# age, and unlock removes only the caller's own lock. An ownerless lock is# broken once no claimant lives and it is at least 2 s old (and unchanged-# while it was checked), so a taker between its mkdir and its owner rename is+# while it was checked), so a taker between its mkdir and its owner create is# never taken for a crash, even when its claim landed after the claims were# read. A claim is honored while its claimant lives; one that records no# start identity (so a reused pid cannot be told apart) is abandoned after 2# minutes, since a live taker holds one for milliseconds. Known limit: on such-# a host a taker stalled over 2 minutes between its mkdir and its owner rename+# a host a taker stalled over 2 minutes between its mkdir and its owner create# can be broken and then publish into its successor's lock. An owner whose# pid is 0, zero-padded or not a number counts as a dead holder, and a lock# whose owner file exists but cannot be read is never treated as ownerless. A symlink .lock left by an older@@ -148,10 +151,7 @@ LOCK="$DIR/.lock" TOKEN=""take() {if [ -e "$1" ] || [ -L "$1" ]; then return 1; fi{ printf '%s\n' "$TOKEN" > "$1.claim.$$"; } 2>/dev/null || { rm -f "$1.claim.$$"; return 1; }- if mkdir "$1" 2>/dev/null; then- [ ! -e "$1/owner" ] && mv -f "$1.claim.$$" "$1/owner" && return 0- [ -e "$1/owner" ] || rm -rf "$1"- fi+ if gstack_lock_take "$1" owner "$TOKEN"; then rm -f "$1.claim.$$"; return 0; firm -f "$1.claim.$$"return 1}@@ -162,8 +162,9 @@ mtime() { stat -c %Y "$1" 2>/dev/null || stat -f %m "$1" 2>/dev/null; }# missing or readable and empty, has no live claimant, is at least 2 s old and kept# its mtime throughout. The clock is read before the first mtime, so a pause# only makes the lock look younger, and a lock made since (a new generation)-# has a newer mtime. Claims are read before the owner, so a taker that renames-# its claim in between is seen as the owner. An empty claim is a taker that+# has a newer mtime. Claims are read before the owner, and a taker removes its+# claim only after its owner file is written, so a taker that finishes in+# between is seen as the owner. An empty claim is a taker that# has not reached its mkdir, so it never made this lock. An mtime a minute or# more in the future (clock skew) counts as old.orphaned() {diff --git a/bin/gstack-lock.sh b/bin/gstack-lock.shnew file mode 100644index 000000000..fee3e71ad--- /dev/null+++ b/bin/gstack-lock.sh@@ -0,0 +1,48 @@+# shellcheck shell=bash+# gstack-lock.sh — the one way gstack shell code takes a lock directory.+#+# Source it, then call:+#+# gstack_lock_take DIR [FILE] [CONTENT]+# Take the lock DIR by creating DIR/FILE (default `pid`) holding CONTENT+# (default $$). Returns 0 when this shell took the lock, 1 when it is held+# (DIR already existed, or another process created FILE first), 2 when DIR+# could not be created (missing or unwritable parent, read-only filesystem)+# and 3 when DIR was made but FILE could not be created or fully written+# in it (disk full, quota, a file-size limit; FILE and DIR are removed+# again, so a failed write never leaves a lock nobody holds). Neither 2+# nor 3 is evidence of a competing holder.+#+# Why not `mkdir DIR && ...`: mkdir's exit status is not a lock. Rust+# coreutils (uutils) 0.8.0, the mkdir on Ubuntu 26.04 and on GitHub's+# ubuntu-latest from 2026-11-09, reports success when another process created+# the directory first, so two racing callers could both think they held it.+# Here mkdir only makes the directory and its status is ignored. The arbiter is+# the shell's noclobber redirect, which bash, zsh and dash open with+# O_CREAT|O_EXCL themselves (no external binary), so the kernel lets exactly one+# caller create FILE. flock(1) is not used: stock macOS does not ship it.+#+# A DIR that exists before the call is never taken, even with no FILE in it, so+# a lock left by a holder killed between mkdir and FILE stays held until the+# caller's own stale-lock recovery removes it, exactly as before. Callers keep+# their own waiting, staleness, takeover and release logic; the owner still+# releases with `rm -rf DIR`. Safe under set -e and set -u, and noclobber never+# leaks into the caller's shell.+gstack_lock_take() {+ local _gl_dir="$1" _gl_file="${2:-pid}" _gl_content="${3:-$$}"+ if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi+ mkdir "$_gl_dir" 2>/dev/null || :+ if [ ! -d "$_gl_dir" ] || [ -L "$_gl_dir" ]; then+ if [ -e "$_gl_dir" ] || [ -L "$_gl_dir" ]; then return 1; fi+ return 2+ fi+ local _gl_opened+ _gl_opened=$(set -o noclobber; { echo o; printf '%s\n' "$_gl_content" >&3; } 2>/dev/null 3> "$_gl_dir/$_gl_file") && return 0+ if [ "$_gl_opened" = o ]; then+ rm -f "$_gl_dir/$_gl_file"; rmdir "$_gl_dir" 2>/dev/null || :+ return 3+ fi+ if [ -e "$_gl_dir/$_gl_file" ] || [ -L "$_gl_dir/$_gl_file" ] || [ ! -d "$_gl_dir" ]; then return 1; fi+ rmdir "$_gl_dir" 2>/dev/null || :+ return 3+}diff --git a/bin/gstack-memorable b/bin/gstack-memorableindex 558767b14..0556c0101 100755--- a/bin/gstack-memorable+++ b/bin/gstack-memorable@@ -105,11 +105,14 @@ _lock_release() {_lock_acquire() {mkdir -p "$STATE_DIR/locks" 2>/dev/null || { _err "cannot create $STATE_DIR/locks (state directory not writable; nothing can be recorded there)"; return 5; }local tries=0 mtime now stale judged moved owner_pid- while ! mkdir "$LOCK_DIR" 2>/dev/null; do+ . "$SCRIPT_DIR/gstack-lock.sh" 2>/dev/null || { _err "$SCRIPT_DIR/gstack-lock.sh is missing (fix: reinstall with ./setup or /gstack-upgrade)"; return 5; }+ while ! gstack_lock_take "$LOCK_DIR" owner "$$"; dotries=$((tries + 1))- # Staleness from the directory's own mtime (set atomically by the holder's- # mkdir), never from a file written after it: a contender that looks in- # the gap between mkdir and bookkeeping must wait, not reclaim. GNU stat+ # Staleness from the directory's own mtime (set by the holder's mkdir and+ # owner create), never from the owner's content: a contender that looks in+ # the gap between mkdir and the owner file must wait, not reclaim. The+ # owner file is the lock (gstack_lock_take creates it with O_EXCL, since+ # mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir). GNU stat# first, BSD stat second, garbage -> no takeover (same idiom as# bin/gstack-settings-hook).mtime="$(stat -c %Y "$LOCK_DIR" 2>/dev/null || stat -f %m "$LOCK_DIR" 2>/dev/null || echo "")"@@ -143,7 +146,6 @@ _lock_acquire() {if [ "$tries" -ge "$LOCK_TRIES" ]; then _err "another gstack-memorable is running (lock $LOCK_DIR; stale but not reclaimable if older than ${LOCK_STALE_S}s); try again"; return 5; fisleep "$LOCK_SLEEP"done- printf '%s\n' "$$" > "$LOCK_DIR/owner"LOCK_HELD=1trap _lock_release EXIT}diff --git a/bin/gstack-render-claude.sh b/bin/gstack-render-claude.shindex c7b06c4cd..f626461cc 100644--- a/bin/gstack-render-claude.sh+++ b/bin/gstack-render-claude.sh@@ -1,5 +1,6 @@# gstack-render-claude.sh — the Claude skill render shared by ./setup and-# `gstack-config gbrain-refresh`. Source it; it only defines functions.+# `gstack-config gbrain-refresh`. Source it; it only defines functions, and+# sources bin/gstack-lock.sh beside it for the render lock.# bash-3.2-clean and safe under `set -euo pipefail`.## Overlay selection is opt-in: the overlay is the family of the persisted@@ -26,6 +27,8 @@# their tested copy) and may define `log` and `bun_cmd`; plain echo and bun# are used otherwise.+. "$(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh" 2>/dev/null || gstack_lock_take() { echo "gstack: $(dirname "${BASH_SOURCE[0]}")/gstack-lock.sh is missing; reinstall with ./setup" >&2; return 2; }+_gstack_render_say() {if declare -F log >/dev/null 2>&1; then log "$@"; else echo "$@"; fi}@@ -84,12 +87,13 @@ gstack_claude_overlay_field() {}# gstack_render_lock DIR / gstack_render_unlock DIR — serialize the swap and-# record write of concurrent renders (mkdir lock, no flock). A lock whose-# holder is gone is broken; after 30 s the swap proceeds unlocked.+# record write of concurrent renders (gstack_lock_take from bin/gstack-lock.sh,+# no flock). A lock whose holder is gone is broken; after 30 s the swap+# proceeds unlocked.gstack_render_lock() {local lock="$1.lock" i=0 pidmkdir -p "$(dirname "$1")" 2>/dev/null || true- while ! mkdir "$lock" 2>/dev/null; do+ while ! gstack_lock_take "$lock" pid "$$"; dopid="$(cat "$lock/pid" 2>/dev/null || true)"if [ -n "$pid" ] && ! kill -0 "$pid" 2>/dev/null; thenrm -rf "$lock"@@ -99,7 +103,6 @@ gstack_render_lock() {[ "$i" -lt 300 ] || return 0sleep 0.1done- echo "$$" > "$lock/pid"}gstack_render_unlock() {rm -rf "$1.lock"diff --git a/bin/gstack-session-update b/bin/gstack-session-updateindex 60ac42c99..78a8cdfa5 100755--- a/bin/gstack-session-update+++ b/bin/gstack-session-update@@ -315,7 +315,10 @@ CALLER_PID=$(gstack_harness_pid "$PPID")# holder touches the pidfile at step boundaries (after the pull, after# setup), so a legitimately-slow run keeps itself alive. The TTL also# bounds the missing/empty-pidfile states: inside the window they mean- # "just acquired, between mkdir and echo" and are respected.+ # "just acquired, between mkdir and the pid write" and are respected.+ # The take itself is gstack_lock_take (bin/gstack-lock.sh): it creates the+ # pidfile with O_EXCL, because mkdir's exit status is not a lock on Ubuntu+ # 26.04's uutils mkdir (two racing updaters both "won" it).LOCK_TTL_MINUTES=30lock_is_expired() {_hb="$LOCK_DIR/pid"@@ -327,11 +330,18 @@ CALLER_PID=$(gstack_harness_pid "$PPID")# mkdir (one rm can land between the other's rm and mkdir). `mv` of the lock# dir is atomic — exactly one contender's mv succeeds; the loser's mv fails# (ENOENT) and it backs off. The winner reaps the moved-aside dir at leisure.- if ! mkdir "$LOCK_DIR" 2>/dev/null; then+ #+ # The pidfile holds the HOLDER's PID (see #2613 note above; macOS ships+ # bash 3.2 with no BASHPID — the sh child's $PPID IS this subshell, so the+ # fallback is exact there). MYPID is captured once, before the take, so the+ # trap below can prove ownership before removing.+ MYPID="${BASHPID:-$(sh -c 'echo $PPID')}"+ . "$(cd "$(dirname "$0")" && pwd)/gstack-lock.sh" 2>/dev/null || { log_entry "SKIP lock_helper_missing"; exit 0; }+ if ! gstack_lock_take "$LOCK_DIR" pid "$MYPID"; thenif lock_is_expired; thenmv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; }rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null- mkdir "$LOCK_DIR" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; }+ gstack_lock_take "$LOCK_DIR" pid "$MYPID" || { log_entry "SKIP lock_contested"; exit 0; }log_entry "RECLAIMED lock_ttl_expired"elif [ -f "$LOCK_DIR/pid" ]; thenLOCK_PID=$(cat "$LOCK_DIR/pid" 2>/dev/null || echo 0)@@ -339,7 +349,7 @@ CALLER_PID=$(gstack_harness_pid "$PPID")# Stale lock — mv aside atomically (see reclaim note above), re-acquiremv "$LOCK_DIR" "$LOCK_DIR.reap.$$" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; }rm -rf "$LOCK_DIR.reap.$$" 2>/dev/null- mkdir "$LOCK_DIR" 2>/dev/null || { log_entry "SKIP lock_contested"; exit 0; }+ gstack_lock_take "$LOCK_DIR" pid "$MYPID" || { log_entry "SKIP lock_contested"; exit 0; }else# Live holder — or an empty/non-numeric pidfile inside the TTL# window (the -gt test fails on garbage, landing here by design).@@ -347,19 +357,12 @@ CALLER_PID=$(gstack_harness_pid "$PPID")exit 0fielse- # Missing pidfile inside the TTL window: just-acquired (mkdir→echo race).+ # Missing pidfile inside the TTL window: just-acquired (mkdir→pid race).log_entry "SKIP locked_no_pid"exit 0fifi- # Write the HOLDER's PID for stale lock detection (see #2613 note above;- # macOS ships bash 3.2 with no BASHPID — the sh child's $PPID IS this- # subshell, so the fallback is exact there). MYPID is captured once at- # write time so the trap below can prove ownership before removing.- MYPID="${BASHPID:-$(sh -c 'echo $PPID')}"- echo "$MYPID" > "$LOCK_DIR/pid" 2>/dev/null-# In-flight heartbeat: the step-boundary touches below only fire AFTER the# pull / setup return, so a legitimately-slow step (cold clone, huge setup)# older than the TTL got reclaimed while ALIVE. This background loopdiff --git a/bin/gstack-settings-hook b/bin/gstack-settings-hookindex f7005384c..bf63cd84e 100755--- a/bin/gstack-settings-hook+++ b/bin/gstack-settings-hook@@ -47,8 +47,10 @@# treated as an owned legacy stray.## Mutation safety:-# - every mutation runs under a mkdir lock (<settings>.lock/) with an owner-# token; release is ownership-checked; stale locks (>30s) are taken over+# - every mutation runs under a lock directory (<settings>.lock/) whose owner+# token file is created with O_EXCL (gstack_lock_take, bin/gstack-lock.sh;+# mkdir's exit status is not a lock on Ubuntu 26.04's uutils mkdir);+# release is ownership-checked; stale locks (>30s) are taken over# via atomic rename. On lock give-up the mutation is SKIPPED with a warning# (the next setup retries — the system is convergent).# - parse failure fails CLOSED: a corrupt settings.json is never overwritten@@ -353,18 +355,18 @@ _acquire_lock() {local stale_after_s=30 # lock older than this belongs to a crashed holderlocal poll_ms=50 # retry cadence; sleep below derives from thistoken="$$-$RANDOM$RANDOM"+ . "$(cd "$(dirname "$0")" && pwd)/gstack-lock.sh" 2>/dev/null || { echo "gstack-settings-hook: $(dirname "$0")/gstack-lock.sh is missing -- skipping this mutation, exit 5 (fix: reinstall with ./setup)" >&2; return 1; }while :; do- if mkdir "$_LOCK_DIR" 2>/dev/null; then- printf '%s\n' "$token" > "$_LOCK_DIR/owner" 2>/dev/null || true+ if gstack_lock_take "$_LOCK_DIR" owner "$token"; then_LOCK_TOKEN="$token"trap _release_lock EXITtrap 'exit 129' INTtrap 'exit 143' TERMreturn 0fi- # mkdir failed but no lock dir exists: either a holder released between- # our mkdir and this check, or NOT contention (unwritable parent, read-only- # fs, missing directory). Retry mkdir once; a second failure with still no+ # The take failed but no lock dir exists: either a holder released between+ # our take and this check, or NOT contention (unwritable parent, read-only+ # fs, missing directory). Retry the take once; a second failure with still no# lock dir is the environment, and waiting cannot help, so give up loudly# now instead of spinning out the full timeout.if [ ! -e "$_LOCK_DIR" ]; thendiff --git a/bin/gstack-upgrade b/bin/gstack-upgradeindex 6f933b424..a335b0dd5 100755--- a/bin/gstack-upgrade+++ b/bin/gstack-upgrade@@ -251,8 +251,10 @@ if [ -n "${GSTACK_SETUP_LOCK_OWNER:-}" ] && [ "$(cat "$LOCK_DIR/pid" 2>/dev/nullLOCK_HANDED=1elsemkdir -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"+ . "$ROOT/bin/gstack-lock.sh" 2>/dev/null || refuse "$ROOT/bin/gstack-lock.sh is missing" "reinstall with cd $ROOT && ./setup"+ # gstack_lock_take creates the pid file with O_EXCL: mkdir's exit status is+ # not a lock on Ubuntu 26.04's uutils mkdir.+ gstack_lock_take "$LOCK_DIR" pid "$$" || 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"trap '[ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$$" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXITfidiff --git a/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md b/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.mdnew file mode 100644index 000000000..baa8e6560--- /dev/null+++ b/changelog.d/capy-shell-locks-hold-when-mkdir-lies-gst-2247.md@@ -0,0 +1,5 @@+---+important: blocker+---+- **gstack's shell locks hold again on Ubuntu 26.04, where `mkdir` reports success when another process won the race (GST-2247).** Ubuntu 26.04, and GitHub's `ubuntu-latest` from 2026-11-09, ships Rust coreutils (uutils) 0.8.0 as `mkdir`. It exits 0 even when the directory already existed because a racing process just made it, so every `mkdir "$LOCK"` lock in gstack could admit two holders: two updates moving one checkout at once, or two `gstack-config set` calls where one dropped the other's key (a test with eight parallel writers under a uutils-style `mkdir` lost six of the eight keys). Every lock now goes through one helper, `gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the directory, and the holder is whoever creates the lock's pid or owner file with the shell's noclobber redirect, which bash, zsh and dash open `O_CREAT|O_EXCL`, so the kernel admits exactly one. No `flock` (macOS has none). This covers the session-start updater, `gstack-upgrade`, the Capy session pin switch, `gstack-ff-update` (inlined, pinned to the helper by a test, because it must run standalone), setup's dependency-migration and Chromium-install locks, `gstack-browser-ensure`, `gstack-config`, the install registry, the Claude render lock, the developer profile and its takeover lock, `gstack-memorable`, the settings.json hook, the brain-sync drain lock, the Codex model-probe lock and its breaker, the lease directory lock, freeze's state lock and /setup-gbrain's concurrent-run lock. The Claude Code wrapper's copied runtime (`CLAUDE_CODE_RUNTIME_FILES`) and `bin/gstack-render-claude.sh` now carry or source the helper themselves, so a copied runtime and every script that sources the render library still take the lock. Each caller keeps its own waiting, stale-lock recovery, timeout and release. If the owner file is created but can't be fully written (disk full, a quota or a file-size limit), the helper removes it and the directory again and returns 3, so a failed write never leaves a lock that nobody holds. A lock directory that already exists is still never taken, even with no owner file in it, so a lock left by a killed holder waits for the caller's existing stale rule, as before.+- `test/gstack-lock-race.test.ts` runs the old pattern and the helper against a PATH shim that behaves like uutils 0.8.0 `mkdir`, so it runs on any runner image: the old pattern lets two of four racers win, the helper admits exactly one in each of 60 races and never overlaps across take, hold and release loops, and parallel `gstack-config` writers keep every key. `test/mkdir-lock-guard.test.ts` fails when shipped shell, a template, a workflow, a Markdown bash fence or TypeScript that embeds shell decides anything on a non-`-p` `mkdir`'s exit status; it found 26 such sites before this change, 12 more than the first report listed. The /setup-gbrain lock test now expects `mkdir:` on stderr only when the parent cannot be created, because the helper never runs `mkdir` on a path that already exists; no other assertion, threshold or timeout changed.diff --git a/docs/capy-install.md b/docs/capy-install.mdindex 9c6e40e5a..df3aeaac0 100644--- a/docs/capy-install.md+++ b/docs/capy-install.md@@ -254,9 +254,11 @@ by rename, prune) and reclaim (reread, then delete only the record judgedstale) run under one lock in the lease directory, a `.lock` directory whose`owner` file names its holder's pid and start identity, so a renewal is neverdeleted and a live lease never disappears from a concurrent scan. The lock is a-directory because `mkdir` is atomic on every host, while Git Bash on Windows-cannot `ln -s` to a target that does not exist (#3330). A taker publishes a-claim before its `mkdir` and renames it in as the owner after, so an ownerless+directory taken with `gstack_lock_take` (`bin/gstack-lock.sh`), which creates+the `owner` file with O_EXCL, because `mkdir`'s exit status is no lock on+Ubuntu 26.04's uutils `mkdir` and Git Bash on Windows cannot `ln -s` to a+target that does not exist (#3330). A taker publishes a claim before its+`mkdir` and removes it only after its owner file is written, so an ownerlesslock is broken only once no claimant lives and the lock is at least 2 s oldand unchanged while checked, which keeps a taker between its two steps safe.A claim that records no start identity is abandoned after 2 minutes, so adiff --git a/docs/troubleshooting.md b/docs/troubleshooting.mdindex 84064e69a..49b423b6f 100644--- a/docs/troubleshooting.md+++ b/docs/troubleshooting.md@@ -1882,6 +1882,36 @@ A `tracked-by-project` or `version-reverted` cause has its own section:listed changes, check out the default branch, move local commits to anotherbranch), then re-run `bin/gstack-upgrade`. A reinstall that failed after thefast-forward is completed by the next run (`reinstall pending from <version>`).+For `another gstack updater holds <state root>/.setup-lock (pid <n>)`, wait+for that update to finish. If no gstack update is running (`kill -0 <n>`+fails, or the pid reads `unknown` because the holder was killed before it+wrote one), remove the lock with `rm -rf <state root>/.setup-lock` and+re-run. See [how gstack's shell locks work](#shell-locks).++<a id="shell-locks"></a>+### Two gstack updates, setups or config writes ran at once (Ubuntu 26.04, uutils `mkdir`)++**Meaning.** gstack's shell locks (the updater's `.setup-lock`, the config+lock `.config-yaml.lock`, the install registry, the developer profile,+settings.json, the Chromium install, the brain-sync drain, freeze and the+lease directory) are lock directories. Older gstack held one when+`mkdir <lock>` succeeded. Rust coreutils (uutils) 0.8.0, the `mkdir` on+Ubuntu 26.04 and on GitHub's `ubuntu-latest` from 2026-11-09, reports success+even when another process created the directory first, so two racing callers+could both hold the lock: two updates moving one checkout, or two+`gstack-config set` calls where one write dropped the other's key. GNU and+BSD `mkdir` never did this.++**Fix.** Upgrade gstack (`/gstack-upgrade`). Every lock is now taken by+`gstack_lock_take` in `bin/gstack-lock.sh`: `mkdir` only makes the+directory, and the holder is whoever creates its `pid` (or `owner`) file+with the shell's noclobber redirect, which opens it `O_CREAT|O_EXCL`, so+exactly one caller wins whatever `mkdir` reports. Waiting, stale-lock+recovery and release are unchanged. A lock directory with no owner file+inside, left by a process killed while taking it, still counts as held until+the caller's own stale-lock rule clears it; when nothing is running, remove it+with `rm -rf <lock>`. Re-set any config key you set during a concurrent write+on 26.04 (`gstack-config get <key>` shows what stuck).<a id="upgrade-busy"></a>### `gstack-upgrade: live gstack sessions hold this installation: pid <p> (<age>m), ...; nothing was changed; fix: ... (UPGRADE_BUSY)` / `gstack-upgrade: a shared harness (capy-server, pid <p>) holds a lease <n>m old; ... (UPGRADE_BUSY)`diff --git a/freeze/bin/freeze-state.sh b/freeze/bin/freeze-state.shindex ad61b80cd..98582fa11 100755--- a/freeze/bin/freeze-state.sh+++ b/freeze/bin/freeze-state.sh@@ -15,7 +15,8 @@ mutex="$STATE_DIR/.freeze-mutation.lock"action="${1:-}"case "$action" in acquire|set|release|clear) ;; *) echo 'Usage: freeze-state.sh acquire|set DIRECTORY | release OWNER | clear' >&2; exit 2 ;; esac-if ! mkdir "$mutex" 2>/dev/null; then+. "$_here/../../bin/gstack-lock.sh" 2>/dev/null || { echo "FREEZE_ERROR: $_here/../../bin/gstack-lock.sh is missing. No boundary changed. Fix: reinstall with ./setup or /gstack-upgrade." >&2; exit 1; }+if ! gstack_lock_take "$mutex" pid "$$"; thenecho 'FREEZE_BUSY: another writer or an interrupted mutation owns the state lock. Retry after it finishes; if abandoned, inspect it with the user before recovery. No boundary changed.' >&2exit 1fi@@ -23,7 +24,7 @@ temp=""finish() {local rc=$?[ -z "$temp" ] || rm -f -- "$temp"- rmdir "$mutex"+ rm -rf -- "$mutex"exit "$rc"}trap finish EXITdiff --git a/lib/claude-code-migration.ts b/lib/claude-code-migration.tsindex 3dd45f229..31c7da30f 100644--- a/lib/claude-code-migration.ts+++ b/lib/claude-code-migration.ts@@ -9,7 +9,7 @@ const OLD = 'gstack-claude';const NEXT = 'gstack-claude-code';const BANNER = '<!-- AUTO-GENERATED from';export const CLAUDE_CODE_RUNTIME_FILES = [- 'bin/gstack-claude-code', 'bin/gstack-models', 'bin/gstack-config', 'bin/gstack-state-root.sh',+ 'bin/gstack-claude-code', 'bin/gstack-models', 'bin/gstack-config', 'bin/gstack-lock.sh', 'bin/gstack-state-root.sh','lib/claude-code.ts', 'lib/claude-code-windows-job.ts', 'lib/claude-bin.ts','lib/outside-review-result.ts', 'lib/gate-outcomes.ts', 'lib/outside-consent.ts', 'lib/state-root.ts','lib/model-catalog.ts', 'lib/model-policy.ts', 'lib/model-policy-cli.ts', 'lib/model-policy-notice.ts', 'lib/agent-model.ts',diff --git a/lib/docs-only.ts b/lib/docs-only.tsindex a93b75bd2..accaabedd 100644--- a/lib/docs-only.ts+++ b/lib/docs-only.ts@@ -45,7 +45,7 @@ const builtIn = (p: string) => ALLOW.some(r => r.test(p));export const DOCS_READER_TESTS: readonly { tree: RegExp; tests: readonly string[] }[] = [{ tree: /^docs\//, tests: ['test/docs-config-keys.test.ts'] },{ tree: /^(?:docs\/|README\.md$)/, tests: ['test/no-stale-gstack-brain-refs.test.ts'] },- { tree: /./, tests: ['test/bun-entry-isolation.test.ts', 'test/gitattributes-eol.test.ts', 'test/ci-paid-coordination.test.ts', 'test/review-packets-removed.test.ts', 'test/state-root-ratchet.test.ts', 'test/codex-web-search-flag.test.ts'] },+ { tree: /./, tests: ['test/bun-entry-isolation.test.ts', 'test/gitattributes-eol.test.ts', 'test/ci-paid-coordination.test.ts', 'test/review-packets-removed.test.ts', 'test/state-root-ratchet.test.ts', 'test/codex-web-search-flag.test.ts', 'test/mkdir-lock-guard.test.ts'] },];/** Repo-wide listers that never read an allowlisted doc, with the reason. */export const DOCS_READER_EXEMPT: Readonly<Record<string, string>> = {diff --git a/setup b/setupindex f47cfec69..af032fd94 100755--- a/setup+++ b/setup@@ -343,6 +343,7 @@ gstack_state_root_select; GSTACK_STATE_ROOT="$_gstack_sr_root". "$SOURCE_GSTACK_DIR/bin/gstack-skill-name.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-skill-name.sh is missing. fix: reinstall from a fresh clone" >&2; exit 1; }. "$SOURCE_GSTACK_DIR/bin/gstack-claude-root.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-claude-root.sh is missing. fix: reinstall from a fresh clone" >&2; exit 1; }. "$SOURCE_GSTACK_DIR/bin/gstack-install-registry.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-install-registry.sh is missing. fix: reinstall from a fresh clone (docs/ADDING_A_HOST.md)" >&2; exit 1; }+. "$SOURCE_GSTACK_DIR/bin/gstack-lock.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-lock.sh is missing. fix: reinstall from a fresh clone" >&2; exit 1; }. "$SOURCE_GSTACK_DIR/bin/gstack-render-claude.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-render-claude.sh is missing. fix: reinstall from a fresh clone" >&2; exit 1; }. "$SOURCE_GSTACK_DIR/bin/gstack-host-renders.sh" || { echo "$0: $SOURCE_GSTACK_DIR/bin/gstack-host-renders.sh is missing. fix: reinstall from a fresh clone" >&2; exit 1; }SETUP_VERSION="$(cat "$SOURCE_GSTACK_DIR/VERSION" 2>/dev/null || echo unknown)"@@ -1842,19 +1843,20 @@ _deps_verified() {}# Checkout-local migration lock: a live holder means skip; a dead or missing-# holder (killed setup) is reclaimed.+# holder (killed setup) is reclaimed. gstack_lock_take (bin/gstack-lock.sh)+# creates the pid file with O_EXCL: mkdir's exit status is not a lock on+# Ubuntu 26.04's uutils mkdir._deps_lock() {local lock="node_modules.gstack-migrate.lock" holder- if ! mkdir "$lock" 2>/dev/null; then+ if ! gstack_lock_take "$lock" pid "$$"; thenholder="$(cat "$lock/pid" 2>/dev/null || true)"case "$holder" in''|*[!0-9]*|0) [ -z "$(find "$lock" -maxdepth 0 -mmin +5 2>/dev/null)" ] && [ -z "$holder" ] && return 1 ;;*) kill -0 "$holder" 2>/dev/null && return 1 ;;esacrm -rf "$lock"- mkdir "$lock" 2>/dev/null || return 1+ gstack_lock_take "$lock" pid "$$" || return 1fi- echo "$$" > "$lock/pid"}_deps_unlock() { rm -rf node_modules.gstack-migrate.lock; }@@ -2424,15 +2426,17 @@ elif ! ensure_playwright_browser; then_clear_playwright_quarantine_PW_LOCK="${TMPDIR:-/tmp}/gstack-playwright-install.lock"# Stale-lock self-heal: a SIGKILL'd prior setup leaves the lock dir behind- # forever (mkdir mutexes have no owner). If the recorded holder PID is dead,- # reclaim instead of telling the user to rmdir by hand.+ # forever. If the recorded holder PID is dead, reclaim instead of telling the+ # user to remove it by hand. The take is gstack_lock_take (bin/gstack-lock.sh),+ # which creates the pid file with O_EXCL: mkdir's exit status is not a lock+ # on Ubuntu 26.04's uutils mkdir.if [ -d "$_PW_LOCK" ]; then_PW_STALE=0; _PW_HOLDER=0_PW_LOCK_OLD=""[ -n "$(find "$_PW_LOCK" -maxdepth 0 -mmin +$(( _PW_INSTALL_TIMEOUT / 60 + 1 )) 2>/dev/null)" ] && _PW_LOCK_OLD=1if [ ! -f "$_PW_LOCK/pid" ]; then- # No holder recorded (killed between mkdir and echo, or mid-write by a- # live setup): nothing to probe, so only age can prove abandonment.+ # No holder recorded (killed between mkdir and the pid write, or+ # mid-write by a live setup): nothing to probe, so only age can prove abandonment.[ -n "$_PW_LOCK_OLD" ] && _PW_STALE=1else_PW_HOLDER=$(cat "$_PW_LOCK/pid" 2>/dev/null || true)@@ -2461,7 +2465,7 @@ elif ! ensure_playwright_browser; thenif { [ "$_PW_MOVED_PID" -gt 0 ] && [ "$_PW_MOVED_PID" != "$_PW_HOLDER" ] && kill -0 "$_PW_MOVED_PID" 2>/dev/null; } \|| { [ ! -f "$_PW_LOCK.stale.$$/pid" ] && [ -z "$_PW_LOCK_OLD" ]; }; then# A new live holder, or a fresh lock whose holder has not written its- # pid yet (mkdir done, echo pending): not ours to reclaim.+ # pid yet (mkdir done, pid write pending): not ours to reclaim.mv "$_PW_LOCK.stale.$$" "$_PW_LOCK" 2>/dev/null || trueelserm -rf "$_PW_LOCK.stale.$$" 2>/dev/null || true@@ -2469,8 +2473,7 @@ elif ! ensure_playwright_browser; thenfififi- if mkdir "$_PW_LOCK" 2>/dev/null; then- echo "$$" > "$_PW_LOCK/pid" 2>/dev/null || true+ if gstack_lock_take "$_PW_LOCK" pid "$$"; then# Chain the earlier cleanup_copied_bun EXIT trap: `trap ... EXIT` REPLACES# the previous handler, so the lock trap must run both or any run taking# this path leaves .tmp-bun-bin behind.diff --git a/setup-gbrain/SKILL.md b/setup-gbrain/SKILL.mdindex 1d3c9563d..0ab160dff 100644--- a/setup-gbrain/SKILL.md+++ b/setup-gbrain/SKILL.md@@ -801,9 +801,9 @@ invocation.ours.- **STOP points are hard.** Gbrain doctor not healthy, installer PATH shadow,migrate timeout, smoke test failure — each is a STOP. Do not paper over.-- **Concurrent-run lock.** At skill start, create the parent before acquiring- the lock atomically. Keep mkdir's error output; missing parents and filesystem- failures are not evidence of a competing run:+- **Concurrent-run lock.** Create the parent, then take the lock with+ `gstack_lock_take` (O_EXCL; mkdir's status is no lock). A missing parent+ is not a competing run:```bashGSTACK_STATE_ROOT=$(~/.claude/skills/gstack/bin/gstack-paths --get GSTACK_STATE_ROOT); : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"@@ -811,7 +811,8 @@ invocation.echo "ERROR: Cannot create setup-gbrain lock parent $GSTACK_STATE_ROOT." >&2exit 1fi- if ! mkdir "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; then+ . ~/.claude/skills/gstack/bin/gstack-lock.sh || exit 1+ if ! gstack_lock_take "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; thenif [ -d "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d ]; thenecho "Another /setup-gbrain instance is running. Wait for it, or remove $GSTACK_STATE_ROOT/.setup-gbrain.lock.d only if you are sure it is stale." >&2else@@ -821,6 +822,6 @@ invocation.fi```- Release the acquired lock on normal exit AND in the SIGINT trap.+ Release it (`rm -rf`, not rmdir) on normal exit AND in the SIGINT trap.- **CLAUDE.md is the audit trail.** Always update it in Step 8 after asuccessful setup.diff --git a/setup-gbrain/SKILL.md.tmpl b/setup-gbrain/SKILL.md.tmplindex 6301aac2e..fe3d76127 100644--- a/setup-gbrain/SKILL.md.tmpl+++ b/setup-gbrain/SKILL.md.tmpl@@ -714,9 +714,9 @@ invocation.ours.- **STOP points are hard.** Gbrain doctor not healthy, installer PATH shadow,migrate timeout, smoke test failure — each is a STOP. Do not paper over.-- **Concurrent-run lock.** At skill start, create the parent before acquiring- the lock atomically. Keep mkdir's error output; missing parents and filesystem- failures are not evidence of a competing run:+- **Concurrent-run lock.** Create the parent, then take the lock with+ `gstack_lock_take` (O_EXCL; mkdir's status is no lock). A missing parent+ is not a competing run:```bashGSTACK_STATE_ROOT=$(~/.claude/skills/gstack/bin/gstack-paths --get GSTACK_STATE_ROOT); : "${GSTACK_STATE_ROOT:?gstack-paths failed; reinstall with ./setup or /gstack-upgrade}"@@ -724,7 +724,8 @@ invocation.echo "ERROR: Cannot create setup-gbrain lock parent $GSTACK_STATE_ROOT." >&2exit 1fi- if ! mkdir "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; then+ . ~/.claude/skills/gstack/bin/gstack-lock.sh || exit 1+ if ! gstack_lock_take "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d; thenif [ -d "$GSTACK_STATE_ROOT"/.setup-gbrain.lock.d ]; thenecho "Another /setup-gbrain instance is running. Wait for it, or remove $GSTACK_STATE_ROOT/.setup-gbrain.lock.d only if you are sure it is stale." >&2else@@ -734,6 +735,6 @@ invocation.fi```- Release the acquired lock on normal exit AND in the SIGINT trap.+ Release it (`rm -rf`, not rmdir) on normal exit AND in the SIGINT trap.- **CLAUDE.md is the audit trail.** Always update it in Step 8 after asuccessful setup.diff --git a/test/capy-skill-wrapper.test.ts b/test/capy-skill-wrapper.test.tsindex 2f4e31031..212bb1e3d 100644--- a/test/capy-skill-wrapper.test.ts+++ b/test/capy-skill-wrapper.test.ts@@ -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.diff --git a/test/codex-probe-cache.test.ts b/test/codex-probe-cache.test.tsindex 981fde6dd..51fb7b768 100644--- a/test/codex-probe-cache.test.ts+++ b/test/codex-probe-cache.test.ts@@ -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" ]; thenrm -f "$RACE_ONCE" "$RACE_LOCK/owner"rmdir "$RACE_LOCK"- exit 1fi-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');diff --git a/test/freeze-owned-lifecycle.test.ts b/test/freeze-owned-lifecycle.test.tsindex 4d35ad1a0..4118fa035 100644--- a/test/freeze-owned-lifecycle.test.ts+++ b/test/freeze-owned-lifecycle.test.ts@@ -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 });diff --git a/test/gen-skill-docs.test.ts b/test/gen-skill-docs.test.tsindex 4fe1639e1..bb3792e04 100644--- a/test/gen-skill-docs.test.ts+++ b/test/gen-skill-docs.test.ts@@ -2061,7 +2061,7 @@ describe('office-hours closing reads the builder profile before logging the sessconst 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);}diff --git a/test/gstack-browser-ensure.test.ts b/test/gstack-browser-ensure.test.tsindex 4e4d9a71c..5fbd5b3b6 100644--- a/test/gstack-browser-ensure.test.ts+++ b/test/gstack-browser-ensure.test.ts@@ -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");',diff --git a/test/gstack-ff-update.test.ts b/test/gstack-ff-update.test.tsindex 85f5b8650..2bc218064 100644--- a/test/gstack-ff-update.test.ts+++ b/test/gstack-ff-update.test.ts@@ -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');diff --git a/test/gstack-lease.test.ts b/test/gstack-lease.test.tsindex 1b57554b5..cf86ed56d 100644--- a/test/gstack-lease.test.ts+++ b/test/gstack-lease.test.ts@@ -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');diff --git a/test/gstack-lock-race.test.ts b/test/gstack-lock-race.test.tsnew file mode 100644index 000000000..f3df34ea9--- /dev/null+++ b/test/gstack-lock-race.test.ts@@ -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');+ });+});diff --git a/test/gstack-settings-hook-symlink.test.ts b/test/gstack-settings-hook-symlink.test.tsindex 07f229b35..4c99fd199 100644--- a/test/gstack-settings-hook-symlink.test.ts+++ b/test/gstack-settings-hook-symlink.test.ts@@ -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 = '';diff --git a/test/gstack-upgrade-bin.test.ts b/test/gstack-upgrade-bin.test.tsindex 6cd24a154..fe1d98c49 100644--- a/test/gstack-upgrade-bin.test.ts+++ b/test/gstack-upgrade-bin.test.ts@@ -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',];diff --git a/test/helpers/ship-measure-seeded-fixture.ts b/test/helpers/ship-measure-seeded-fixture.tsindex b9703bec8..6902e0a01 100644--- a/test/helpers/ship-measure-seeded-fixture.ts+++ b/test/helpers/ship-measure-seeded-fixture.ts@@ -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:-}" incase "$id" in ${SEEDED_CASE}|${STABLE_CASE}) ;; *) echo "unknown case: $id (cases: ${SEEDED_CASE}, ${STABLE_CASE})" >&2; exit 2 ;; esacif [ -n "\${GSTACK_SHIP_MEASURE_DIR:-}" ]; then slots="$(dirname "$GSTACK_SHIP_MEASURE_DIR")/slots"; else slots="$here/.evals/slots"; fimkdir -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)); doneout=$(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"diff --git a/test/mkdir-lock-guard.test.ts b/test/mkdir-lock-guard.test.tsnew file mode 100644index 000000000..ca8ce35e2--- /dev/null+++ b/test/mkdir-lock-guard.test.ts@@ -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: [] });+ });+});diff --git a/test/plan-mode-preamble-render.test.ts b/test/plan-mode-preamble-render.test.tsindex 101926721..8964de729 100644--- a/test/plan-mode-preamble-render.test.ts+++ b/test/plan-mode-preamble-render.test.ts@@ -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() {diff --git a/test/relink-disabled-router.test.ts b/test/relink-disabled-router.test.tsindex 4268c9a6a..c1dfc24e1 100644--- a/test/relink-disabled-router.test.ts+++ b/test/relink-disabled-router.test.ts@@ -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;diff --git a/test/relink.test.ts b/test/relink.test.tsindex b054cd274..bb1e72057 100644--- a/test/relink.test.ts+++ b/test/relink.test.ts@@ -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'));diff --git a/test/session-update-autostash.test.ts b/test/session-update-autostash.test.tsindex d5a0cff24..bcb7713e4 100644--- a/test/session-update-autostash.test.ts+++ b/test/session-update-autostash.test.ts@@ -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 anddiff --git a/test/session-update-hook-hold.test.ts b/test/session-update-hook-hold.test.tsindex a22ebda94..3710d323a 100644--- a/test/session-update-hook-hold.test.ts+++ b/test/session-update-hook-hold.test.ts@@ -172,7 +172,7 @@ describe.skipIf(process.platform === 'win32')('gstack-session-update: the incomifunction 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 });diff --git a/test/setup-claude-code-migration.test.ts b/test/setup-claude-code-migration.test.tsindex 85ebe5e9f..9e0e54c09 100644--- a/test/setup-claude-code-migration.test.ts+++ b/test/setup-claude-code-migration.test.ts@@ -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);diff --git a/test/setup-gbrain-fixture.test.ts b/test/setup-gbrain-fixture.test.tsindex 1165cfc80..22002d028 100644--- a/test/setup-gbrain-fixture.test.ts+++ b/test/setup-gbrain-fixture.test.ts@@ -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') {diff --git a/test/setup-playwright-best-effort.test.ts b/test/setup-playwright-best-effort.test.tsindex 22bf15a19..c65e016c0 100644--- a/test/setup-playwright-best-effort.test.ts+++ b/test/setup-playwright-best-effort.test.ts@@ -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'}'`,diff --git a/test/setup-production-deps.test.ts b/test/setup-production-deps.test.tsindex 38b3e4d10..13c8b8589 100644--- a/test/setup-production-deps.test.ts+++ b/test/setup-production-deps.test.ts@@ -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). */diff --git a/test/setup-skill-hooks-gate.test.ts b/test/setup-skill-hooks-gate.test.tsindex 243d2d0b2..ec9def6af 100644--- a/test/setup-skill-hooks-gate.test.ts+++ b/test/setup-skill-hooks-gate.test.ts@@ -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-');diff --git a/test/team-mode.test.ts b/test/team-mode.test.tsindex 4bca76887..40c35b612 100644--- a/test/team-mode.test.ts+++ b/test/team-mode.test.ts@@ -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',diff --git a/test/uninstall.test.ts b/test/uninstall.test.tsindex aba334014..5f6772f11 100644--- a/test/uninstall.test.ts+++ b/test/uninstall.test.ts@@ -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 leconst 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 ouconst 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-updateconst 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.minstallRoot = 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);}diff --git a/test/update-channel.test.ts b/test/update-channel.test.tsindex 23c789b4b..47d0baecd 100644--- a/test/update-channel.test.ts+++ b/test/update-channel.test.ts@@ -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 stableconst 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 });