diff --git a/bin/gstack-slug b/bin/gstack-slug index 924454722..fb164a69b 100755 --- a/bin/gstack-slug +++ b/bin/gstack-slug @@ -13,11 +13,30 @@ # Without this walk-up, running gstack-slug from a subdir whose only # "marker" is a deploy artifact silently resolves to the subdir's basename, # misfiling all session state under a phantom slug. (2026-05-25 bug fix.) -# 2. If the resolved project root has a git remote, derive the slug from it. +# 2. Derive the slug from the canonical git remote: the OUTERMOST ancestor +# that is an actual git repo (`.git` directory, or `.git` FILE for +# worktrees/submodules) with an `origin` remote wins. The slug is +# `owner-repo`, parsed EXACTLY like browse/bin/remote-slug so the two +# bins can never disagree on a canonical-remote repo. Marker-only +# ancestors that are NOT remote-bearing repos (a stray empty ~/.git, +# a stray package.json in $HOME) still anchor the basename FALLBACK, +# but they can no longer shadow a real remote. (2026-08-17 bug fix: +# a stray empty ~/.git made the walk-up pick $HOME as project root; +# $HOME has no origin, so EVERY repo under it degraded to +# SLUG= — one shared bucket for all projects.) # 3. Otherwise use the basename of the resolved project root. # 4. If no project root was found anywhere on the chain, fall back to the # basename of $(pwd) (preserves prior behavior for plain folders). # +# MIGRATION NOTE (2026-08-17): sessions run BEFORE the remote-first fix above, +# in repos below a stray marker-bearing ancestor, filed their session state +# (decisions / timeline / ceo-plans / learnings) under the DEGRADED slug — +# ~/.gstack/projects// (e.g. `garrytan`) instead of the +# canonical ~/.gstack/projects//. The slug cache self-heals on the +# next invocation (see 1b), but already-written store data does NOT move. +# Whether/how to merge those stores is tracked in TODOS.md — do not add data +# migration code here. +# # Caching is self-healing: a cache entry for the literal pwd that differs from # the freshly-computed slug gets opportunistically rewritten (single-shot, key- # local — never sweeps other entries). This lets pre-existing poisoned caches @@ -112,6 +131,32 @@ _outermost_project_root() { fi } +# 1a. Outermost REMOTE-BEARING repo root: walk the same ancestor chain and +# track the outermost dir that has a `.git` entry (directory for normal +# clones, FILE for git-worktrees/submodules — `git -C` resolves a +# worktree's remote through its main clone) AND whose `origin` remote +# resolves. This is the canonical-identity walk: a marker-only ancestor +# with no resolvable origin (stray empty ~/.git, stray package.json) +# cannot win here, so it cannot hijack remote-derived identity the way +# it can hijack the marker walk above. Nested-repo semantics preserved: +# an inner repo under an outer canonical-remote repo still resolves to +# the OUTER repo's remote (outermost wins), same as before. +# Note: git spawns only at `.git`-bearing ancestors — typically one. +_outermost_remote_repo() { + local dir="$1" + local outermost="" parent="" depth=0 + while [[ -n "$dir" && "$dir" != "/" && $depth -lt 64 ]]; do + if [[ -e "$dir/.git" ]] && git -C "$dir" remote get-url origin >/dev/null 2>&1; then + outermost="$dir" + fi + parent=$(dirname "$dir") + [[ "$parent" == "$dir" ]] && break # dirname fixed point (C:/, ., //srv) + dir="$parent" + depth=$((depth + 1)) + done + printf '%s' "$outermost" +} + # Only compute the project root if we don't already have a slug (env override # took precedence). The walk is cheap (~10 stats on the deepest realistic cwd). PROJECT_ROOT="" @@ -119,34 +164,65 @@ if [[ -z "$SLUG" ]]; then PROJECT_ROOT=$(_outermost_project_root "$PROJECT_DIR") fi +# Lazy, memoized remote discovery. Needed on exactly two paths: fresh +# resolution (no usable cache) and the degraded-ancestor heal check below. +# Gating it keeps ordinary cache hits git-spawn-free. +REMOTE_ROOT="" +REMOTE_URL="" +_REMOTE_RESOLVED=0 +_resolve_remote() { + if [[ "$_REMOTE_RESOLVED" -eq 1 ]]; then return 0; fi + _REMOTE_RESOLVED=1 + REMOTE_ROOT=$(_outermost_remote_repo "$PROJECT_DIR") + if [[ -n "$REMOTE_ROOT" ]]; then + REMOTE_URL=$(git -C "$REMOTE_ROOT" remote get-url origin 2>/dev/null) || REMOTE_URL="" + fi + return 0 +} + # 1b. Cached identity is STICKY (#2212): a project that used gstack before it # adopted a git remote keeps its pre-origin slug — recomputing from the # remote here would rename the project mid-life and orphan everything -# under ~/.gstack/projects//. The ONE exception is the provable -# old-bug shape (#1125): the pre-walk-up resolver cached basename(pwd) -# for a SUBDIRECTORY of the real project — if the cached value equals this -# pwd's basename while the walk-up says pwd is NOT the project root, the -# cache came from that bug, not from legitimate identity; fall through and -# recompute so it heals. +# under ~/.gstack/projects//. TWO provable bug shapes are exempt +# and fall through to recompute (self-heal): +# - Old-bug shape (#1125): the pre-walk-up resolver cached basename(pwd) +# for a SUBDIRECTORY of the real project — cached == pwd basename while +# the walk-up says pwd is NOT the project root. +# - Degraded-ancestor shape (2026-08-17): the pre-remote-first resolver +# cached basename(PROJECT_ROOT) for a marker-only ancestor (stray +# ~/.git) that is NOT the remote-bearing repo — cached == the marker +# root's basename while a remote-bearing repo BELOW it exists. Legit +# #2212 stickiness is safe: there the repo that adopted the remote IS +# the marker root (REMOTE_ROOT == PROJECT_ROOT), so the heal never fires. if [[ -z "$SLUG" && -f "$CACHE_FILE" ]]; then _CACHED=$(cat "$CACHE_FILE" 2>/dev/null | tr -cd 'a-zA-Z0-9._-') if [[ -n "$_CACHED" ]]; then _PWD_BASE=$(basename "$PROJECT_DIR" | tr -cd 'a-zA-Z0-9._-') + _ROOT_BASE="" + if [[ -n "$PROJECT_ROOT" ]]; then + _ROOT_BASE=$(basename "$PROJECT_ROOT" | tr -cd 'a-zA-Z0-9._-') + fi if [[ "$_CACHED" == "$_PWD_BASE" && -n "$PROJECT_ROOT" && "$PROJECT_ROOT" != "$PROJECT_DIR" ]]; then : # old-bug shape — recompute below and self-heal the cache + elif [[ -n "$PROJECT_ROOT" && "$_CACHED" == "$_ROOT_BASE" ]] \ + && { _resolve_remote; [[ -n "$REMOTE_URL" && "$REMOTE_ROOT" != "$PROJECT_ROOT" ]]; }; then + : # degraded-ancestor shape — recompute below and self-heal the cache else SLUG="$_CACHED" fi fi fi -# 2. If we found a project root and it has a git remote, derive slug from the -# remote URL (existing logic — kept verbatim, just rooted at PROJECT_ROOT -# instead of $PWD so a subdir without its own remote inherits the parent's). -if [[ -z "$SLUG" && -n "$PROJECT_ROOT" ]]; then - REMOTE_URL=$(git -C "$PROJECT_ROOT" remote get-url origin 2>/dev/null) || REMOTE_URL="" +# 2. Canonical remote-derived slug. Sourced from the outermost remote-bearing +# repo (see 1a) — NOT from PROJECT_ROOT, which may be a marker-only +# ancestor with no remote. Parse kept byte-identical to +# browse/bin/remote-slug (strip trailing .git, then owner/repo → owner-repo) +# so the two bins agree on every canonical-remote repo, worktrees included. +# Parity pinned by test/gstack-slug-parity.test.ts. +if [[ -z "$SLUG" ]]; then + _resolve_remote if [[ -n "$REMOTE_URL" ]]; then - RAW_SLUG=$(printf '%s' "$REMOTE_URL" | sed 's|.*[:/]\([^/]*/[^/]*\)\.git$|\1|;s|.*[:/]\([^/]*/[^/]*\)$|\1|' | tr '/' '-') + RAW_SLUG=$(printf '%s' "${REMOTE_URL%.git}" | sed -E 's#.*[:/]([^/]+)/([^/]+)$#\1-\2#') SLUG=$(printf '%s' "$RAW_SLUG" | tr -cd 'a-zA-Z0-9._-') fi fi diff --git a/test/gstack-slug-parity.test.ts b/test/gstack-slug-parity.test.ts new file mode 100644 index 000000000..5e1ce5d36 --- /dev/null +++ b/test/gstack-slug-parity.test.ts @@ -0,0 +1,236 @@ +/** + * bin/gstack-slug ↔ browse/bin/remote-slug parity. + * + * The bug this pins (2026-08-17, observed live in a Conductor worktree of + * garrytan/gstack): a stray marker-bearing ancestor above the repo — an empty + * `~/.git` directory that is not even a valid git repo — captured + * gstack-slug's "outermost strong marker" walk-up as the project root. That + * ancestor has no `origin` remote, so the resolver silently degraded to + * `basename($HOME)` and emitted `SLUG=garrytan`, while remote-slug (which + * asks git for the containing repo's remote) correctly said + * `garrytan-gstack`. Every store keyed on the slug (decisions, timeline, + * ceo-plans, learnings) filed into ~/.gstack/projects/garrytan/ — one bucket + * shared by every repo under $HOME. + * + * The fix makes the canonical remote authoritative: gstack-slug now walks the + * ancestor chain for the OUTERMOST dir with a `.git` entry (dir for normal + * clones, FILE for git-worktrees) whose `origin` remote resolves, and derives + * `owner-repo` with the exact same parse remote-slug uses. Marker-only + * ancestors that are not remote-bearing repos can still anchor the basename + * FALLBACK, but they can no longer shadow a real remote. + * + * Contracts pinned here: + * - Parity: for any repo (plain clone or git-worktree) whose slug derivation + * reaches a canonical remote, gstack-slug's SLUG equals remote-slug's + * output — including under a stray-marker home. + * - Walk-up preserved: a nested inner repo under an outer canonical-remote + * repo resolves to the OUTER repo's owner-repo (outermost wins), matching + * remote-slug run at the outer root. + * - Fallback preserved: a no-remote repo still resolves to its basename. + * - Cache self-heal: a pre-fix degraded cache entry (== the bogus marker + * root's basename) is rewritten to the canonical slug; legit #2212 sticky + * identity (repo that adopted a remote after first use) is NOT healed. + * + * Test pattern mirrors test/gstack-slug-cwd-walk-up.test.ts: per-test + * tmpHome, spawnSync against the real bash scripts, fixtures on disk. + */ +import { describe, test, expect, beforeEach, afterEach } from 'bun:test'; +import { spawnSync, type SpawnSyncReturns } from 'child_process'; +import * as fs from 'fs'; +import * as path from 'path'; +import * as os from 'os'; + +const ROOT = path.resolve(import.meta.dir, '..'); +const SLUG_SCRIPT = path.join(ROOT, 'bin', 'gstack-slug'); +const REMOTE_SLUG_SCRIPT = path.join(ROOT, 'browse', 'bin', 'remote-slug'); + +function baseEnv(tmpHome: string): Record { + // Drop any ambient override: a sibling test leaking GSTACK_PROJECT_SLUG in + // a shared-process shard would flip runs into override mode. + const { GSTACK_PROJECT_SLUG: _drop, ...ambient } = process.env; + return { ...ambient, HOME: tmpHome, GSTACK_HOME: path.join(tmpHome, '.gstack') }; +} + +function runSlug(cwd: string, tmpHome: string): SpawnSyncReturns { + return spawnSync('bash', [SLUG_SCRIPT], { + cwd, + env: baseEnv(tmpHome), + encoding: 'utf8', + timeout: 10_000, + }); +} + +function runRemoteSlug(cwd: string, tmpHome: string): SpawnSyncReturns { + return spawnSync('bash', [REMOTE_SLUG_SCRIPT], { + cwd, + env: baseEnv(tmpHome), + encoding: 'utf8', + timeout: 10_000, + }); +} + +function slugOf(r: SpawnSyncReturns): string { + const m = r.stdout.match(/^SLUG=([^\n]*)$/m); + return m ? m[1]! : ''; +} + +function git(args: string[], opts: { cwd?: string } = {}): void { + const r = spawnSync('git', args, { encoding: 'utf8', timeout: 10_000, ...opts }); + if (r.status !== 0) { + throw new Error(`git ${args.join(' ')} failed: ${r.stderr}`); + } +} + +/** git init -b main + optional origin remote. Returns the repo path. */ +function makeRepo(dir: string, originUrl?: string): string { + fs.mkdirSync(dir, { recursive: true }); + git(['init', '-q', '-b', 'main', dir]); + if (originUrl) git(['-C', dir, 'remote', 'add', 'origin', originUrl]); + return dir; +} + +function encodedCacheKey(absPath: string): string { + return absPath.replace(/\//g, '_'); +} + +/** Assert both scripts succeed in `cwd` and emit the same slug. */ +function expectParity(cwd: string, tmpHome: string, expected: string): void { + const gstack = runSlug(cwd, tmpHome); + const remote = runRemoteSlug(cwd, tmpHome); + expect(gstack.status).toBe(0); + expect(remote.status).toBe(0); + const remoteOut = remote.stdout.trim(); + expect(slugOf(gstack)).toBe(expected); + expect(remoteOut).toBe(expected); + expect(slugOf(gstack)).toBe(remoteOut); +} + +describe('gstack-slug ↔ remote-slug parity', () => { + let tmpHome: string; + let fixtures: string; + + beforeEach(() => { + // realpathSync: macOS tmpdir is a symlink (/var -> /private/var); the + // scripts key their cache and walk on the resolved cwd. + tmpHome = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'slug-parity-home-'))); + fixtures = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'slug-parity-fix-'))); + }); + + afterEach(() => { + try { fs.rmSync(tmpHome, { recursive: true, force: true }); } catch {} + try { fs.rmSync(fixtures, { recursive: true, force: true }); } catch {} + }); + + test('plain clone, https remote WITH .git suffix — identical owner-repo slug', () => { + const repo = makeRepo(path.join(fixtures, 'proj'), 'https://github.com/acme/widgets.git'); + expectParity(repo, tmpHome, 'acme-widgets'); + }); + + test('plain clone, https remote WITHOUT .git suffix (live-bug URL shape) — identical slug', () => { + const repo = makeRepo(path.join(fixtures, 'proj'), 'https://github.com/garrytan/gstack'); + expectParity(repo, tmpHome, 'garrytan-gstack'); + }); + + test('plain clone, scp-like ssh remote — identical owner-repo slug', () => { + const repo = makeRepo(path.join(fixtures, 'proj'), 'git@github.com:acme/widgets.git'); + expectParity(repo, tmpHome, 'acme-widgets'); + }); + + test('git-worktree of a clone (.git FILE, the Conductor shape) — identical slug', () => { + const main = makeRepo(path.join(fixtures, 'main-clone'), 'https://github.com/garrytan/gstack'); + git(['-C', main, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init']); + const wt = path.join(fixtures, 'wt'); + git(['-C', main, 'worktree', 'add', '-q', wt, '-b', 'feature-branch']); + // Sanity: worktree roots carry a .git FILE, not a directory. + expect(fs.statSync(path.join(wt, '.git')).isFile()).toBe(true); + expectParity(wt, tmpHome, 'garrytan-gstack'); + }); + + test('LIVE BUG SHAPE: stray empty .git on an ancestor "home" no longer degrades the slug', () => { + // The exact 2026-08-17 reproduction: an ancestor dir with an empty .git + // (not a valid repo, no origin) above a canonical-remote worktree. + const strayHome = path.join(fixtures, 'strayhome'); + fs.mkdirSync(path.join(strayHome, '.git'), { recursive: true }); // empty — invalid repo + const main = makeRepo( + path.join(strayHome, 'conductor', 'workspaces', 'gstack', 'main-clone'), + 'https://github.com/garrytan/gstack', + ); + git(['-C', main, '-c', 'user.email=t@t', '-c', 'user.name=t', 'commit', '-q', '--allow-empty', '-m', 'init']); + const wt = path.join(strayHome, 'conductor', 'workspaces', 'gstack', 'beirut-v4'); + git(['-C', main, 'worktree', 'add', '-q', wt, '-b', 'gstack-fix-wave']); + + // Both the plain clone and the worktree must resolve to owner-repo — the + // pre-fix resolver emitted `strayhome` (the marker root's basename) here. + expectParity(main, tmpHome, 'garrytan-gstack'); + expectParity(wt, tmpHome, 'garrytan-gstack'); + expect(slugOf(runSlug(wt, tmpHome))).not.toBe('strayhome'); + }); + + test('walk-up preserved: nested inner repo (no remote) resolves to the OUTER repo slug', () => { + const outer = makeRepo(path.join(fixtures, 'outer'), 'git@github.com:acme/outer.git'); + const inner = makeRepo(path.join(outer, 'vendor', 'inner')); + + const gstack = runSlug(inner, tmpHome); + expect(gstack.status).toBe(0); + // Outermost remote-bearing repo wins — same answer as remote-slug asked + // at the outer root. (remote-slug asked from INSIDE the inner repo can't + // see past the inner .git — its remote derivation does not succeed there, + // so the parity clause doesn't apply; the walk-up contract does.) + expect(slugOf(gstack)).toBe('acme-outer'); + expect(runRemoteSlug(outer, tmpHome).stdout.trim()).toBe('acme-outer'); + }); + + test('walk-up preserved: nested inner repo WITH its own remote still resolves to the OUTER repo slug', () => { + const outer = makeRepo(path.join(fixtures, 'outer'), 'git@github.com:acme/outer.git'); + const inner = makeRepo(path.join(outer, 'vendor', 'inner'), 'git@github.com:acme/inner.git'); + + const gstack = runSlug(inner, tmpHome); + expect(gstack.status).toBe(0); + // Outermost wins — unchanged from the pre-fix walk-up semantics. + expect(slugOf(gstack)).toBe('acme-outer'); + }); + + test('fallback unchanged: no-remote repo resolves to its basename (and remote-slug agrees)', () => { + const repo = makeRepo(path.join(fixtures, 'lonely')); + const gstack = runSlug(repo, tmpHome); + expect(gstack.status).toBe(0); + expect(slugOf(gstack)).toBe('lonely'); + // remote-slug's own no-remote fallback is basename(toplevel) — parity + // holds incidentally on this shape too. + expect(runRemoteSlug(repo, tmpHome).stdout.trim()).toBe('lonely'); + }); + + test('cache self-heal: a pre-fix degraded cache entry is rewritten to the canonical slug', () => { + const strayHome = path.join(fixtures, 'strayhome'); + fs.mkdirSync(path.join(strayHome, '.git'), { recursive: true }); + const repo = makeRepo(path.join(strayHome, 'git', 'proj'), 'https://github.com/garrytan/gstack'); + + // Pre-seed the cache with the pre-fix degraded value: the bogus marker + // root's basename (what the old resolver computed and cached). + const cacheDir = path.join(tmpHome, '.gstack', 'slug-cache'); + fs.mkdirSync(cacheDir, { recursive: true }); + const cacheFile = path.join(cacheDir, encodedCacheKey(repo)); + fs.writeFileSync(cacheFile, 'strayhome'); + + const gstack = runSlug(repo, tmpHome); + expect(gstack.status).toBe(0); + expect(slugOf(gstack)).toBe('garrytan-gstack'); + // The cache file itself must have been overwritten (self-healing). + expect(fs.readFileSync(cacheFile, 'utf8').trim()).toBe('garrytan-gstack'); + }); + + test('sticky identity preserved (#2212): repo that adopted a remote after first use is NOT healed', () => { + // Legit sticky shape: the repo itself is the marker root (REMOTE_ROOT == + // PROJECT_ROOT) and its cached identity is its pre-origin basename slug. + const repo = makeRepo(path.join(fixtures, 'stickyproj'), 'https://github.com/x/y.git'); + const cacheDir = path.join(tmpHome, '.gstack', 'slug-cache'); + fs.mkdirSync(cacheDir, { recursive: true }); + const cacheFile = path.join(cacheDir, encodedCacheKey(repo)); + fs.writeFileSync(cacheFile, 'stickyproj'); + + const gstack = runSlug(repo, tmpHome); + expect(gstack.status).toBe(0); + expect(slugOf(gstack)).toBe('stickyproj'); + expect(fs.readFileSync(cacheFile, 'utf8').trim()).toBe('stickyproj'); + }); +});