Files
gstack/test/gstack-slug-parity.test.ts
T
f30b7b788a v1.91.13.0 fix: severe bug wave (autoplan guard, land-and-deploy CI gate, project identity, gbrain, review gates) (#3013)
* fix(land-and-deploy): never merge over red, pending or missing CI (#2995)

/land-and-deploy gated only on required checks, so a repo with none
(every GitHub Free private repo, any repo without branch protection)
skipped the CI wait and could merge over red CI. The verdict now comes
from bin/gstack-ci-gate, a tested helper bound to the head SHA: all
checks by default, cancel/unknown buckets fail, NO_CHECKS needs explicit
per-head approval, and both merge commands (including --auto) run only
after a PASS for the same SHA they pin with --match-head-commit.

Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>

* fix(slug): give nested-group projects their own state bucket and verify checkpoint identity (#3003, #2901)

gstack-slug kept only the last two remote path segments, so
customer-a/product/repo and customer-b/product/repo shared one bucket
and /context-restore could present another project's checkpoint.

- One canonical-remote rule (bash + TS, golden vectors) used by all six
  resolvers: lowercased host, no userinfo/port/.git, Azure DevOps and
  Bitbucket Server normalized. 3+ segment remotes get
  <last-two>-<16 hex>; two-segment remotes (all of GitHub) are unchanged.
- Versioned sticky cache (v2:) keeps cache hits git-free.
- context-save stamps the credential-free remote and root;
  context-restore only treats this project's checkpoints as latest,
  reports foreign/unverified ones first, and treats a different root
  with the same remote (Conductor handoff) as information.
- gstack-slug --adopt-legacy copies only files the user confirms.
- question-preference-hook reads the same versioned cache, so never-ask
  preferences fire; unknown identity asks instead of auto-deciding.

* fix(gbrain): brain context loads, managed sync works, memory sync stops duplicating (#2883, #2985, #2922)

- brain-context-load called 'gbrain list_pages' (an MCP tool name), so
  every skill's brain context was 0 bytes. It now uses 'gbrain list'
  with gbrain's real filter flags, and prints one line when queries fail.
- The code-stage sync always passes --no-pull (managed gbrain >= 0.51
  refuses without it); a gbrain that rejects the flag fails with an
  upgrade message and is never retried without it. stderr is streamed
  with a bounded tail and quoted in failure summaries.
- /sync-gbrain gains --sources (and GSTACK_MEMORY_INGEST_SOURCES); by
  default it skips types already synced through a federated curated
  source, so curated pages stop being re-duplicated.

Co-authored-by: Vitor Cepeda Lopes <vitor@vitorcepedalopes.com>
Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>

* fix(codex,cso): clean Codex reviews stop failing; semgrep and trivy SARIF results import (#2769, #3011)

- Codex review gate is PASS / FAIL / UNVERIFIED. Untagged output (what
  a clean 'codex review --base' prints) is UNVERIFIED, not FAIL, and
  never a false PASS; P2/P3-only output passes.
- import-sarif resolves semgrep's undeclared %SRCROOT% and trivy's
  ROOTPATH (including git-URL targets) through explicit, captured
  mappings; declared bases must sit inside the source root or the
  run's checkout, URIs are percent-decoded, and rejected results are
  counted with rule, base and path instead of silently dropped.

* fix: version strings are not IPs, failed update checks are not 'up to date', private security reporting (#2856, #2786, #2984)

- The pre-push redact hook exempts a root VERSION file that is only a
  version string and the version token in CHANGELOG release headings;
  the engine allowlist is untouched.
- gstack-update-check caches an unreadable remote as CHECK_FAILED with
  a short TTL instead of UP_TO_DATE; /gstack-upgrade never reports
  'latest' after a failed check.
- SECURITY.md points reporters at GitHub private vulnerability
  reporting.
- pr-title-sync (pull_request_target, write token) pins actions/checkout
  to a reviewed SHA.

* fix(autoplan): publication guard accepts real Claude Code journals (#3007, #3009, #2968, #2977, #2986, #3006)

The guard required a session journal to start with a user message, but
Claude Code starts it with SessionStart hook attachments (and a forked
compacted session starts with a compact_boundary), so every phase was
denied for anyone with a SessionStart hook. Windows path spellings
(C:/, /c/, drive case) were rejected too.

- Reader accepts the captured startup, compact, clear and fork shapes
  (claude 2.1.284 fixture), computes root uniqueness over every
  candidate, and returns typed reason codes instead of one string.
- Hard denials (competing root, foreign cwd, sidechain, agent, cycle,
  malformed, identity) say what happened and how to run the reviews by
  hand; unflushed journals still retry.
- A well-formed, stable journal whose root shape is unrecognized now
  warns ('phase publication was NOT verified') and continues, without
  overriding Claude Code's own permission check; no bypass switch.
- Windows paths fold before validation, so '..' is still rejected.
- Periodic drift canary runs the reader on fresh journals from the
  pinned claude.

Co-authored-by: Charles M Berg <77517285+CharlesBerg85@users.noreply.github.com>
Co-authored-by: laurenbdaniels-coder <264343335+laurenbdaniels-coder@users.noreply.github.com>
Co-authored-by: Jordan Mayer <176445995+maydaycyber@users.noreply.github.com>
Co-authored-by: elmesery-dev <elmesery.dev@gmail.com>

* v1.91.13.0: severe bug fix wave release notes, stale gbrain verbs in docs

* test: seed the versioned slug cache in the memory-injection deny case (#2901)

The preference hook now resolves the project bucket from gstack-slug's
v2 slug-cache entry instead of basename(cwd); this fixture still wrote
preferences under the basename bucket without the entry the skill
preamble always writes first.

* fix: full-suite follow-ups for the fix wave

- gstack-slug's --help heredoc is over 512B, so it gets the BASH_COMPAT=50
  pipe-deadlock guard like the other bins.
- Refresh the codex/factory ship goldens for the plan-gates slug change.
- The periodic lane gains the autoplan journal drift canary (107 paid
  files); raise the eval-slices cap to 25 so every slice still starts
  at once until its recorded duration lets the planner pack it.

* fix(plan-eng-review): clearer Step 0 sequencing, write routes and section outputs

The workflow judge scored plan-eng-review's instructions at
actionability 3.67 (bar 4) on text unchanged from main. Resolve the
ambiguities it named together, without changing any gate or output:
Step 0 names the Read's order and keeps one STOP; the pending-call,
read-only, forbidden-write and failed-save rules become one Write
routes block; header/label limits and grid checks are concrete;
Performance gets a checklist; each section has a stated output shape;
Lake Score is defined. Same total length (parity cap).

---------

Co-authored-by: harshitgavita-07 <harshit.gavita@gmail.com>
Co-authored-by: Vitor Cepeda Lopes <vitor@vitorcepedalopes.com>
Co-authored-by: Charles M Berg <77517285+CharlesBerg85@users.noreply.github.com>
Co-authored-by: laurenbdaniels-coder <264343335+laurenbdaniels-coder@users.noreply.github.com>
Co-authored-by: Jordan Mayer <176445995+maydaycyber@users.noreply.github.com>
Co-authored-by: elmesery-dev <elmesery.dev@gmail.com>
2026-10-02 11:11:00 -07:00

377 lines
19 KiB
TypeScript

/**
* 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<string, string | undefined> {
// 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<string> {
return spawnSync('bash', [SLUG_SCRIPT], {
cwd,
env: baseEnv(tmpHome),
encoding: 'utf8',
timeout: 10_000,
});
}
function runRemoteSlug(cwd: string, tmpHome: string): SpawnSyncReturns<string> {
return spawnSync('bash', [REMOTE_SLUG_SCRIPT], {
cwd,
env: baseEnv(tmpHome),
encoding: 'utf8',
timeout: 10_000,
});
}
function slugOf(r: SpawnSyncReturns<string>): 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('v2:garrytan-gstack');
});
test('hostile origin `url = ..` cannot become a ".." slug — basename fallback holds', () => {
// git accepts `..` as a remote URL; the sed parse passes it through
// unchanged, so unguarded it becomes SLUG=".." — filing state one level
// ABOVE ~/.gstack/projects/ (confined to ~/.gstack, but still traversal).
// The dot-only guard rejects it and the basename fallback anchors identity.
const repo = makeRepo(path.join(fixtures, 'dotty'), '..');
const r = runSlug(repo, tmpHome);
expect(r.status).toBe(0);
expect(slugOf(r)).toBe('dotty');
// The cache must hold the healed value, never the dot slug.
const cacheFile = path.join(tmpHome, '.gstack', 'slug-cache', encodedCacheKey(repo));
expect(fs.readFileSync(cacheFile, 'utf8').trim()).toBe('v2:dotty');
});
test('package.json wrapper root (no .git): sticky basename slug is PRESERVED — heal is stray-repo-shape only', () => {
// Legit #2212 shape: a monorepo wrapper anchored by package.json used
// gstack before an inner dir grew a remote-bearing repo. The degraded-
// ancestor heal must NOT fire here — it is restricted to marker roots
// anchored by a .git entry whose origin does NOT resolve (the live-bug
// stray-repo shape).
const wrapper = path.join(fixtures, 'wrapperproj');
fs.mkdirSync(wrapper, { recursive: true });
fs.writeFileSync(path.join(wrapper, 'package.json'), '{"name":"wrapper"}\n');
const inner = makeRepo(path.join(wrapper, 'apps', 'web'), 'https://github.com/acme/web.git');
const cacheDir = path.join(tmpHome, '.gstack', 'slug-cache');
fs.mkdirSync(cacheDir, { recursive: true });
const cacheFile = path.join(cacheDir, encodedCacheKey(inner));
fs.writeFileSync(cacheFile, 'wrapperproj');
const r = runSlug(inner, tmpHome);
expect(r.status).toBe(0);
expect(slugOf(r)).toBe('wrapperproj'); // NOT healed to acme-web
expect(fs.readFileSync(cacheFile, 'utf8').trim()).toBe('v2:wrapperproj');
});
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('v2:stickyproj');
});
// ── Nested-group remotes (#3003) ─────────────────────────────────────────
const VECTORS: Array<{ url: string; slug: string }> = JSON.parse(
fs.readFileSync(path.join(ROOT, 'test', 'fixtures', 'remote-identity-vectors.json'), 'utf8'),
);
const vectorSlug = (url: string): string => VECTORS.find((v) => v.url === url)!.slug;
test('2/3/4-segment ssh+https remotes: both bins agree with the golden vectors', () => {
const urls = [
'https://github.com/garrytan/gstack.git',
'git@github.com:garrytan/gstack.git',
'https://gitlab.com/customer-a/product/repo.git',
'git@gitlab.com:customer-a/product/repo.git',
'ssh://git@gitlab.com:2222/customer-a/product/repo.git',
'https://gitlab.com/customer-b/product/repo.git',
'git@gitlab.example.com:group/sub/team/repo.git',
'https://gitlab.example.com/group/sub/team/repo',
];
urls.forEach((url, i) => {
const repo = makeRepo(path.join(fixtures, `nested-${i}`), url);
expectParity(repo, tmpHome, vectorSlug(url));
});
// Same nested repo over ssh, https and ssh:// with a port → one bucket;
// a sibling group's repo with the same last two segments → a different one.
expect(vectorSlug('git@gitlab.com:customer-a/product/repo.git'))
.toBe(vectorSlug('ssh://git@gitlab.com:2222/customer-a/product/repo.git'));
expect(vectorSlug('https://gitlab.com/customer-b/product/repo.git'))
.not.toBe(vectorSlug('https://gitlab.com/customer-a/product/repo.git'));
});
test('pre-populated unversioned cache of a nested repo moves once, prints one notice, then stays git-free', () => {
const repo = makeRepo(path.join(fixtures, 'nested-cached'), 'git@gitlab.com:customer-a/product/repo.git');
const cacheDir = path.join(tmpHome, '.gstack', 'slug-cache');
fs.mkdirSync(cacheDir, { recursive: true });
const cacheFile = path.join(cacheDir, encodedCacheKey(repo));
fs.writeFileSync(cacheFile, 'product-repo'); // pre-#3003 sticky value
fs.mkdirSync(path.join(tmpHome, '.gstack', 'projects', 'product-repo', 'checkpoints'), { recursive: true });
const first = runSlug(repo, tmpHome);
expect(first.status).toBe(0);
expect(slugOf(first)).toBe('product-repo-5eca1fe041984543');
expect(fs.readFileSync(cacheFile, 'utf8')).toBe('v2:product-repo-5eca1fe041984543');
expect(first.stderr).toContain(
'gstack now files this project under projects/product-repo-5eca1fe041984543; earlier data is still in projects/product-repo',
);
// The old bucket is left in place, never moved or deleted.
expect(fs.existsSync(path.join(tmpHome, '.gstack', 'projects', 'product-repo', 'checkpoints'))).toBe(true);
// Second resolve: a v2 cache hit — no notice and no remote lookup.
const shimDir = path.join(fixtures, 'git-shim');
fs.mkdirSync(shimDir, { recursive: true });
const realGit = spawnSync('bash', ['-c', 'command -v git'], { encoding: 'utf8', timeout: 10_000 }).stdout.trim();
const log = path.join(fixtures, 'git-calls.log');
fs.writeFileSync(path.join(shimDir, 'git'), `#!/usr/bin/env bash\necho "$*" >> "${log}"\nexec "${realGit}" "$@"\n`, { mode: 0o755 });
const second = spawnSync('bash', [SLUG_SCRIPT], {
cwd: repo,
env: { ...baseEnv(tmpHome), PATH: `${shimDir}:${process.env.PATH}` },
encoding: 'utf8',
timeout: 10_000,
});
expect(slugOf(second)).toBe('product-repo-5eca1fe041984543');
expect(second.stderr).toBe('');
const calls = fs.existsSync(log) ? fs.readFileSync(log, 'utf8') : '';
expect(calls).not.toContain('remote get-url');
});
test('unversioned sticky identity of a nested repo that is NOT the old last-two slug is kept (#2212)', () => {
const repo = makeRepo(path.join(fixtures, 'stickynested'), 'https://gitlab.com/customer-a/product/repo.git');
const cacheDir = path.join(tmpHome, '.gstack', 'slug-cache');
fs.mkdirSync(cacheDir, { recursive: true });
const cacheFile = path.join(cacheDir, encodedCacheKey(repo));
fs.writeFileSync(cacheFile, 'stickynested');
const r = runSlug(repo, tmpHome);
expect(slugOf(r)).toBe('stickynested');
expect(fs.readFileSync(cacheFile, 'utf8')).toBe('v2:stickynested');
expect(r.stderr).toBe('');
});
test('--identity prints the canonical remote without credentials, and nothing on disk holds them', () => {
const user = 'ci-bot';
const secret = ['sentinel', 'tok', '81274'].join('-');
const repo = makeRepo(path.join(fixtures, 'creds'), `https://${user}:${secret}@GitLab.com:8443/customer-a/product/repo.git`);
const r = spawnSync('bash', [SLUG_SCRIPT, '--identity'], { cwd: repo, env: baseEnv(tmpHome), encoding: 'utf8', timeout: 10_000 });
expect(r.status).toBe(0);
expect(r.stdout).toContain('PROJECT_REMOTE=gitlab.com/customer-a/product/repo\n');
expect(r.stdout).toContain('SLUG=product-repo-5eca1fe041984543\n');
expect(r.stdout).toContain('LEGACY_SLUG=product-repo\n');
expect(r.stdout + r.stderr).not.toContain(secret);
const stateFiles = spawnSync('grep', ['-rl', secret, path.join(tmpHome, '.gstack')], { encoding: 'utf8', timeout: 10_000 });
expect(stateFiles.stdout).toBe('');
});
test('GSTACK_PROJECT_SLUG of "." or ".." is ignored instead of escaping projects/', () => {
const repo = makeRepo(path.join(fixtures, 'pinned'), 'https://github.com/acme/pinned.git');
for (const pin of ['.', '..', '/..']) {
const r = spawnSync('bash', [SLUG_SCRIPT], {
cwd: repo,
env: { ...baseEnv(tmpHome), GSTACK_PROJECT_SLUG: pin },
encoding: 'utf8',
timeout: 10_000,
});
expect(slugOf(r)).toBe('acme-pinned');
}
});
});