fix: adversarial round — the P0 finalize fail-safe and 12 hardened findings

Three adversarial passes (Claude fresh-context, Codex chaos, Codex structured
with P1 gate) on the full wave diff. Multi-source findings, all fixed:

- P0: finalize_queue is now explicit-delete-only — a record is unlinked ONLY
  when classification proves it staged or dropped; a classifier crash, a
  missing class file, or a malformed pulled .brain-privacy-map.json (which
  previously nuked the whole snapshotted queue, remotely triggerable) now
  retains everything, warns, and re-drains next run. load_privacy_map treats
  corrupt maps as retain-all, never as empty.
- next-version cannot silently drop a live claim: unreadable advertised refs
  get a targeted --depth=1 fetch + retry; still-unreadable claims surface as
  UNKNOWN warnings instead of duplicate-version silence.
- session-update lock: ownership-checked EXIT trap (a TTL-reclaimed holder
  can no longer delete the new holder's lock) + a 5-min background heartbeat
  so a legitimately-slow pull/setup is never reclaimed while alive.
- ensure-event collapses ALL same-(event,source) duplicates to one canonical
  entry; unique per-process tmp path; setup call sites surface (not swallow)
  the hardened refusals.
- memory-ingest: --limit counts only policy-permitted pages (denied records
  no longer starve permitted ones); --probe applies the same policy filter as
  --bulk (skipped_policy_* fields on the report).
- version-bump repair accepts a genuine literal 0.0.0.0 VERSION file.
- slug heal restricted to the stray-.git shape — package.json-anchored
  wrapper roots keep their legit sticky identity (#2212 preserved).
- brain-sync: idle fast path sees leftover .migrating records; unparseable
  spool records quarantine instead of warning forever; migration comment
  stops overclaiming the transition-window race.
- CDP throttling justifications document override persistence (callers own
  restoration), pinned in the allowlist test.

Deferred with record: deny retroactivity for already-ingested pages (P2 TODO,
same semantics as the code-import gate); legacy-migration tail race
(transition-window, requires pre-spool writers).

288 pass / 0 fail across the 10 touched suites.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-08-17 14:13:50 -07:00
co-authored by Claude Fable 5
parent b7d44c45b4
commit fd0dbdeea2
20 changed files with 789 additions and 99 deletions
+29
View File
@@ -326,6 +326,35 @@ describe("walk-up parity with bin/gstack-slug (outermost project root)", () => {
expect(fs.readFileSync(cacheFile, "utf-8")).toBe("garrytan-gstack");
});
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 — it is restricted to marker roots anchored
// by a .git entry whose origin does NOT resolve (the live-bug shape).
const wrapper = path.join(tmp, "wrapperproj");
const inner = path.join(wrapper, "apps", "web");
fs.mkdirSync(inner, { recursive: true });
fs.writeFileSync(path.join(wrapper, "package.json"), '{"name":"wrapper"}\n');
spawnSync("git", ["init", "-q", inner]);
spawnSync("git", ["-C", inner, "remote", "add", "origin", "https://github.com/acme/web.git"]);
const cacheDir = path.join(nativeHome(), "slug-cache");
fs.mkdirSync(cacheDir, { recursive: true });
const cacheFile = path.join(cacheDir, toMsysPath(inner).replace(/\//g, "_"));
fs.writeFileSync(cacheFile, "wrapperproj"); // legit sticky identity
expect(slugFromEnvironment(nativeHome(), inner)).toBe("wrapperproj"); // NOT healed to acme-web
expect(fs.readFileSync(cacheFile, "utf-8")).toBe("wrapperproj");
// The bash implementation agrees on the same fixture (own home, seeded cache).
if (HAS_BASH) {
const bashCacheDir = path.join(tmp, "bash-home", ".gstack", "slug-cache");
fs.mkdirSync(bashCacheDir, { recursive: true });
fs.writeFileSync(path.join(bashCacheDir, toMsysPath(inner).replace(/\//g, "_")), "wrapperproj");
expect(bashSlug(inner)).toBe("wrapperproj");
}
});
test("sticky identity preserved (#2212): a remote adopted AT the marker root is NOT healed", () => {
// Legit sticky shape: the repo that adopted the remote IS the marker root
// (remote root == project root), so the degraded-ancestor heal must not
+83 -8
View File
@@ -553,15 +553,20 @@ describe('#2549 queue integrity', () => {
expect(detail.dropped.missing).toContain('projects/p/learnings.jsonl');
});
test('an unparseable legacy queue line migrates as-is and is preserved, never destroyed', () => {
test('an unparseable legacy queue line migrates as-is and is quarantined, never destroyed', () => {
// The line lands in the legacy single-file queue (pre-spool writer);
// migration converts it verbatim to a spool record, and the drain keeps
// what it cannot parse.
// migration converts it verbatim to a spool record, and the drain moves
// what it cannot parse into quarantine (never deletes it, and never
// leaves it re-warning at every boundary).
initWithMode('full');
fs.appendFileSync(path.join(tmpHome, '.brain-queue.jsonl'), 'not json at all\n');
const r = run(['gstack-brain-sync', '--once']);
expect(r.status).toBe(0);
expect(spoolText()).toContain('not json at all');
const qDir = path.join(spoolDir(), 'quarantine');
expect(fs.existsSync(qDir)).toBe(true);
const qFiles = fs.readdirSync(qDir);
expect(qFiles.length).toBe(1);
expect(fs.readFileSync(path.join(qDir, qFiles[0]), 'utf-8')).toContain('not json at all');
});
test('finalize: a synced record leaves the spool while a held sibling survives the same drain', () => {
@@ -841,7 +846,7 @@ describe('C12 spool queue', () => {
expect(spoolText()).not.toContain('learnings.jsonl');
});
test('an unparseable spool record is kept and warned about; the drain continues', () => {
test('an unparseable spool record is quarantined with a warning; the drain continues', () => {
initWithMode('full');
fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","ts":"2026-01-01T00:00:00Z"}\n');
@@ -850,10 +855,13 @@ describe('C12 spool queue', () => {
const r = run(['gstack-brain-sync', '--once']);
expect(r.status).toBe(0);
expect(r.stderr).toContain('unparseable');
// The good sibling synced; the unreadable record was never destroyed.
// The good sibling synced; the unreadable record was never destroyed
// it moved to quarantine so it stops re-warning at every boundary.
expect(remoteLog()).toMatch(/sync: 1 file/);
expect(spoolFiles()).toEqual([badFile]);
expect(spoolText()).toContain('this is not json');
expect(spoolFiles()).toEqual([]);
const qPath = path.join(spoolDir(), 'quarantine', badFile);
expect(fs.existsSync(qPath)).toBe(true);
expect(fs.readFileSync(qPath, 'utf-8')).toContain('this is not json');
});
test('--status queue_depth counts spool records plus unmigrated legacy lines', () => {
@@ -867,6 +875,73 @@ describe('C12 spool queue', () => {
expect(supplemental.queue_depth).toBe(3);
});
test('G1: a malformed pulled privacy map (["bad"]) holds the queue — warns, deletes NOTHING, next run re-drains', () => {
// Remotely triggerable kill vector: the privacy map arrives via the
// artifacts-repo pull. A non-dict entry used to raise mid-classification
// AFTER the snapshot manifest was written, and the old finalize polarity
// ("delete unless retained") then unlinked EVERY snapshotted record.
initWithMode('full');
fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","ts":"2026-01-01T00:00:00Z"}\n');
run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
const seeded = spoolFiles();
expect(seeded.length).toBe(1);
fs.writeFileSync(path.join(tmpHome, '.brain-privacy-map.json'), '["bad"]');
const r = run(['gstack-brain-sync', '--once']);
expect(r.status).toBe(0);
expect(r.stderr).toContain('privacy map');
// Zero records deleted; nothing pushed.
expect(spoolFiles()).toEqual(seeded);
expect(remoteLog()).not.toMatch(/sync:/);
// Fix the map: the surviving queue re-drains and syncs.
fs.writeFileSync(path.join(tmpHome, '.brain-privacy-map.json'), '[]');
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(spoolFiles().length).toBe(0);
expect(remoteLog()).toMatch(/sync: 1 file/);
});
test('G1: a classifier that dies AFTER the snapshot write consumes nothing (call-site exit check + explicit-delete finalize)', () => {
// A dict entry with a non-string pattern passes the shape filter but
// raises inside fnmatch DURING classification — the post-manifest crash
// window (same shape as ENOSPC/OOM mid-run). The call site must see the
// nonzero exit, warn, skip finalize, and leave everything queued.
initWithMode('full');
fs.mkdirSync(path.join(tmpHome, 'projects', 'p'), { recursive: true });
fs.writeFileSync(path.join(tmpHome, 'projects/p/learnings.jsonl'), '{"skill":"x","ts":"2026-01-01T00:00:00Z"}\n');
run(['gstack-brain-enqueue', 'projects/p/learnings.jsonl']);
const seeded = spoolFiles();
expect(seeded.length).toBe(1);
fs.writeFileSync(path.join(tmpHome, '.brain-privacy-map.json'), '[{"pattern": 123}]');
const r = run(['gstack-brain-sync', '--once']);
expect(r.status).toBe(0);
expect(r.stderr).toContain('classification failed');
expect(spoolFiles()).toEqual(seeded); // zero records deleted
expect(remoteLog()).not.toMatch(/sync:/);
const status = JSON.parse(fs.readFileSync(path.join(tmpHome, '.brain-sync-status.json'), 'utf-8'));
expect(status.status).toBe('error');
expect(status.message).toContain('queue preserved');
// Fix the map: the surviving queue re-drains and syncs.
fs.writeFileSync(path.join(tmpHome, '.brain-privacy-map.json'), '[]');
expect(run(['gstack-brain-sync', '--once']).status).toBe(0);
expect(spoolFiles().length).toBe(0);
expect(remoteLog()).toMatch(/sync: 1 file/);
});
test('G1: finalize is explicit-delete-only and the fast path is .migrating-aware (static pins)', () => {
const src = fs.readFileSync(path.join(BIN, 'gstack-brain-sync'), 'utf-8');
// The compute call site checks the python exit status before finalizing.
expect(src).toMatch(/if ! compute_paths_to_stage /);
// finalize_queue takes the staged-paths file and deletes only staged dropped.
expect(src).toContain('deletable = staged | dropped');
expect(src).toContain('if p not in deletable:');
// The empty fast path also treats a leftover .migrating file as non-idle.
expect(src).toMatch(/spool_has_records && \[ ! -s "\$QUEUE" \] && \[ ! -s "\$QUEUE\.migrating" \]/);
});
test('--drop-queue keeps the --yes gate and counts spool + legacy entries', () => {
initWithMode('full');
seedSpool('{"file":"projects/p/a.jsonl","ts":"t"}');
+84 -1
View File
@@ -300,9 +300,16 @@ describe("internal: parseTranscriptJsonl + buildTranscriptPage shape", () => {
describe("gstack-memory-ingest --limit", () => {
it("respects --limit by stopping after N writes (mocked via --probe shortcut)", () => {
const r = runScript(["--probe", "--limit", "1"]);
// Hermetic home: against the operator's real HOME this walked the whole
// transcript corpus (and, post policy-parity, batch-checked its real
// policy store), making a pure arg-parsing assertion slow and flaky.
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
mkdirSync(gstackHome, { recursive: true });
const r = runScript(["--probe", "--limit", "1"], { HOME: home, GSTACK_HOME: gstackHome });
// --limit doesn't apply to probe but argument should parse without error
expect(r.exitCode).toBe(0);
rmSync(home, { recursive: true, force: true });
});
it("rejects --limit 0 with exit 1", () => {
@@ -1201,6 +1208,82 @@ describe("#2392: transcript ingest honors per-remote trust policy", () => {
rmSync(home, { recursive: true, force: true });
});
it("(f) probe policy parity: a denied remote's transcript lands in skipped_policy_deny, not new_count", () => {
// --probe used to count policy-denied transcripts as ingestible (it only
// applied attribution), so its numbers overstated what --bulk would write.
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
mkdirSync(gstackHome, { recursive: true });
const denyCwd = makeRepoWithRemote(home, "denied", "https://github.com/denyme/denied.git");
writeSessionForRepo(home, "work-denied", "denysess1", denyCwd);
setPolicy(gstackHome, "https://github.com/denyme/denied.git", "deny");
const r = runScript(["--probe"], { HOME: home, GSTACK_HOME: gstackHome });
expect(r.exitCode).toBe(0);
expect(r.stdout).toContain("Total files in window: 0");
expect(r.stdout).toMatch(/New \(never ingested\):\s+0/);
expect(r.stdout).toMatch(/Skipped \(policy deny\):\s+1/);
expect(r.stdout).not.toMatch(/Skipped \(policy read-only\)/);
rmSync(home, { recursive: true, force: true });
});
it("(g) probe policy parity: a read-only remote's transcript lands in skipped_policy_readonly", () => {
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
mkdirSync(gstackHome, { recursive: true });
const roCwd = makeRepoWithRemote(home, "readonly", "https://github.com/roorg/rorepo.git");
writeSessionForRepo(home, "work-readonly", "rosess1", roCwd);
setPolicy(gstackHome, "https://github.com/roorg/rorepo.git", "read-only");
const r = runScript(["--probe"], { HOME: home, GSTACK_HOME: gstackHome });
expect(r.exitCode).toBe(0);
expect(r.stdout).toContain("Total files in window: 0");
expect(r.stdout).toMatch(/Skipped \(policy read-only\):\s+1/);
rmSync(home, { recursive: true, force: true });
});
it("(h) --limit counts policy-PERMITTED pages only: a denied-first corpus still writes the allowed page", () => {
// Walk order is deterministic here: Claude Code projects are walked
// BEFORE Codex sessions (walkAllSources), so the DENIED transcript is
// prepared first. Pre-fix, --limit 1 was applied to the unfiltered
// prepared array — the denied record consumed the limit and the permitted
// one starved (written: 0).
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
mkdirSync(gstackHome, { recursive: true });
const { binDir } = installFakeGbrain(home);
const denyCwd = makeRepoWithRemote(home, "denied", "https://github.com/denyme/denied.git");
writeSessionForRepo(home, "work-denied", "denysess1", denyCwd); // Claude Code: walked first
const okCwd = makeRepoWithRemote(home, "allowed", "https://github.com/okorg/okrepo.git");
const today = new Date();
const ymd = `${today.getFullYear()}-${String(today.getMonth() + 1).padStart(2, "0")}-${String(today.getDate()).padStart(2, "0")}`;
writeCodexSession(
home, ymd,
`{"type":"session_meta","payload":{"id":"oksess-codex","cwd":"${okCwd.replace(/\\/g, "\\\\")}"},"timestamp":"${today.toISOString()}"}\n`,
);
setPolicy(gstackHome, "https://github.com/denyme/denied.git", "deny");
const r = runScript(["--bulk", "--quiet", "--limit", "1"], {
HOME: home,
GSTACK_HOME: gstackHome,
PATH: `${binDir}:${process.env.PATH || ""}`,
});
expect(r.exitCode).toBe(0);
expect(r.stdout).toMatch(/written:\s+1/);
expect(r.stdout).toMatch(/skipped \(policy deny\):\s+1/);
// The page that landed is the PERMITTED one (the Codex session), not
// whichever record happened to be walked first.
const sessions = stateSessions(gstackHome);
expect(sessions.length).toBe(1);
expect(sessions[0]).toContain("rollout-");
rmSync(home, { recursive: true, force: true });
});
it("artifacts are never policy-filtered, even when their project's remote is denied", () => {
const home = makeTestHome();
const gstackHome = join(home, ".gstack");
+96
View File
@@ -662,6 +662,102 @@ describe("fetchGitClaimed — non-mutating live remote query (ls-remote first)",
});
});
describe("fetchGitClaimed — unfetched live claims (G2: ls-remote advertises SHAs without objects)", () => {
// `git ls-remote` lists a branch's tip sha without transferring objects, so
// a branch pushed AFTER the last local fetch has no local object and both
// VERSION reads fail. The old `continue` silently dropped that LIVE claim —
// the exact duplicate-allocation this fallback exists to prevent.
function git(cwd: string, ...args: string[]) {
return Bun.spawnSync(["git", "-c", "user.email=t@t", "-c", "user.name=t", ...args], { cwd });
}
function cloneFixture(): { root: string; origin: string; clone: string } {
const root = mkdtempSync(join(tmpdir(), "nextver-unfetched-"));
const origin = join(root, "origin");
mkdirSync(origin);
git(origin, "init", "-q", "-b", "main");
writeFileSync(join(origin, "VERSION"), "0.1.66.0\n");
git(origin, "add", "-A");
git(origin, "commit", "-qm", "v0.1.66.0 chore: base");
const clone = join(root, "clone");
git(root, "clone", "-q", origin, clone);
return { root, origin, clone };
}
test("a claim branch pushed after the last local fetch is read via a targeted fetch", () => {
const { root, origin, clone } = cloneFixture();
const cwd = process.cwd();
try {
// The claim lands on origin AFTER the clone — its objects are absent
// locally, so `git show <sha>:VERSION` and the remote-tracking read
// both fail until the targeted fetch runs.
git(origin, "checkout", "-q", "-b", "late-claim");
writeFileSync(join(origin, "VERSION"), "0.1.70.0\n");
git(origin, "add", "-A");
git(origin, "commit", "-qm", "v0.1.70.0 feat: late claim");
git(origin, "checkout", "-q", "main");
process.chdir(clone);
const warnings: string[] = [];
const claims = fetchGitClaimed("main", "VERSION", warnings);
expect(claims.map((c) => c.version)).toContain("0.1.70.0");
expect(warnings.join(" ")).not.toContain("UNKNOWN claim");
} finally {
process.chdir(cwd);
rmSync(root, { recursive: true, force: true });
}
});
test("a claim STILL unreadable after the fetch surfaces as an UNKNOWN-claim warning, never silence", () => {
const { root, origin, clone } = cloneFixture();
const cwd = process.cwd();
try {
// A ref origin advertises but cannot serve: dangling sha written
// straight into refs/. ls-remote lists it; every local read fails, the
// targeted fetch fails ("not our ref"), and the object never appears.
writeFileSync(
join(origin, ".git", "refs", "heads", "ghost"),
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\n",
);
process.chdir(clone);
const warnings: string[] = [];
const claims = fetchGitClaimed("main", "VERSION", warnings);
expect(claims.map((c) => c.branch)).not.toContain("origin/ghost");
const joined = warnings.join(" ");
expect(joined).toContain("origin/ghost");
expect(joined).toContain("UNKNOWN claim");
} finally {
process.chdir(cwd);
rmSync(root, { recursive: true, force: true });
}
});
test("a live branch that simply carries no VERSION file is not a claim and not an UNKNOWN warning", () => {
const { root, origin, clone } = cloneFixture();
const cwd = process.cwd();
try {
// Branch exists BEFORE the clone (objects local), VERSION deleted on it:
// the read fails because the PATH is absent, not the object. Old
// semantics (skip quietly) must hold — no phantom UNKNOWN noise.
git(origin, "checkout", "-q", "-b", "docs-only");
git(origin, "rm", "-q", "VERSION");
git(origin, "commit", "-qm", "docs: no version file");
git(origin, "checkout", "-q", "main");
git(clone, "fetch", "-q", "origin");
process.chdir(clone);
const warnings: string[] = [];
const claims = fetchGitClaimed("main", "VERSION", warnings);
expect(claims.map((c) => c.branch)).not.toContain("origin/docs-only");
expect(warnings.join(" ")).not.toContain("docs-only");
} finally {
process.chdir(cwd);
rmSync(root, { recursive: true, force: true });
}
});
});
describe("width pinned on failed base read (3-digit repos)", () => {
// readBaseVersion used to return a literal "0.0.0.0" when origin/<base> was
// unreadable — a 4-digit string, which flipped versionWidth() to 4 and
@@ -219,6 +219,77 @@ describe('add-event', () => {
});
});
// ----------------------------------------------------------------------
// ensure-event: duplicate (event, source) collapse
// ----------------------------------------------------------------------
describe('ensure-event collapses duplicate (event, source) entries', () => {
test('two same-source entries from the old matcher-keyed dedup collapse to ONE updated entry', () => {
// Pre-existing installs can carry two entries with the same
// (event, _gstack_source) — the old dedup keyed on the matcher too, so a
// matcher change pushed a second registration. `.find()` updated only the
// first and left the stale twin running forever.
const { spawnSync } = require('child_process');
fs.writeFileSync(settingsFile, JSON.stringify({
hooks: {
PostToolUse: [
{ _gstack_source: 'plan-tune-cathedral', matcher: 'OldMatcherA', hooks: [{ type: 'command', command: '/old-a', timeout: 5 }] },
{ matcher: 'Bash', hooks: [{ type: 'command', command: '/user-own-hook' }] },
{ _gstack_source: 'plan-tune-cathedral', matcher: 'OldMatcherB', hooks: [{ type: 'command', command: '/old-b', timeout: 5 }] },
],
},
}, null, 2));
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'PostToolUse',
'--matcher', 'NewMatcher',
'--command', '/canonical',
'--source', 'plan-tune-cathedral',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
expect(r.status).toBe(0);
// The collapse is reported on stderr, never silent.
expect(r.stderr).toContain('collapsed 1 duplicate');
const s = settings();
const mine = s.hooks.PostToolUse.filter((e: any) => e._gstack_source === 'plan-tune-cathedral');
expect(mine).toHaveLength(1); // ONE canonical entry — the stale twin is gone
expect(mine[0].matcher).toBe('NewMatcher');
expect(mine[0].hooks[0].command).toBe('/canonical');
// Unrelated user hook untouched.
const bash = s.hooks.PostToolUse.find((e: any) => e.matcher === 'Bash');
expect(bash.hooks[0].command).toBe('/user-own-hook');
expect(s.hooks.PostToolUse).toHaveLength(2);
});
test('no duplicates → no collapse message, single entry updated as before', () => {
const { spawnSync } = require('child_process');
fs.writeFileSync(settingsFile, JSON.stringify({
hooks: {
PostToolUse: [
{ _gstack_source: 'plan-tune-cathedral', matcher: 'OldMatcher', hooks: [{ type: 'command', command: '/old', timeout: 5 }] },
],
},
}, null, 2));
const r = spawnSync('bash', [
SETTINGS_HOOK, 'ensure-event',
'--event', 'PostToolUse',
'--matcher', 'NewMatcher',
'--command', '/new',
'--source', 'plan-tune-cathedral',
'--timeout', '5',
], { env: { ...process.env, GSTACK_SETTINGS_FILE: settingsFile }, encoding: 'utf-8', timeout: 15_000 });
expect(r.status).toBe(0);
expect(r.stderr).not.toContain('collapsed');
const s = settings();
expect(s.hooks.PostToolUse).toHaveLength(1);
expect(s.hooks.PostToolUse[0].hooks[0].command).toBe('/new');
});
});
// ----------------------------------------------------------------------
// remove-source
// ----------------------------------------------------------------------
+22
View File
@@ -233,6 +233,28 @@ describe('gstack-slug ↔ remote-slug parity', () => {
expect(fs.readFileSync(cacheFile, 'utf8').trim()).toBe('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('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.
+28
View File
@@ -651,6 +651,34 @@ describe('#2600: repair must not write fabricated 0.0.0.0 when VERSION is missin
expect(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version).toBe('0.5.0');
});
test('repair proceeds when VERSION genuinely reads 0.0.0.0 (a real file, not the sentinel)', () => {
// current === DEFAULT is ambiguous: it is BOTH the missing/unparseable
// sentinel AND a legitimate literal "0.0.0.0" in a brand-new repo. The
// guard now disambiguates on the raw bytes — a real 0.0.0.0 repairs
// package.json to the npm-valid 0.0.0.
const dir = makeDir();
fs.writeFileSync(path.join(dir, 'VERSION'), '0.0.0.0\n');
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '0.5.0' }, null, 2) + '\n');
const out = execFileSync('bun', [BIN, 'repair'], { cwd: dir }).toString();
const result = JSON.parse(out);
expect(result.repaired).toBe('0.0.0.0');
expect(result.packageJsonVersion).toBe('0.0.0');
expect(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version).toBe('0.0.0');
});
test('repair still rejects whitespace-only VERSION content (sentinel path, not a real version)', () => {
const dir = makeDir();
fs.writeFileSync(path.join(dir, 'VERSION'), ' \n\n');
fs.writeFileSync(path.join(dir, 'package.json'), JSON.stringify({ name: 'x', version: '0.5.0' }, null, 2) + '\n');
let code = 0;
try { execFileSync('bun', [BIN, 'repair'], { cwd: dir, stdio: 'pipe' }); }
catch (e: any) { code = e.status; }
expect(code).toBe(2);
expect(JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf-8')).version).toBe('0.5.0');
});
test('repair reproduces the exact issue scenario: VERSION in root, package.json in app/ (#2600)', () => {
// The exact layout from the issue: VERSION at repo root, package.json in app/
// Running repair from app/ cwd with no VERSION there used to write 0.0.0.0 into app/package.json.
+28 -2
View File
@@ -245,10 +245,36 @@ describe('gstack-session-update lock identity + TTL (#2613)', () => {
const src = fs.readFileSync(SCRIPT, 'utf8');
const mvAside = src.match(/mv "\$LOCK_DIR" "\$LOCK_DIR\.reap\.\$\$" 2>\/dev\/null \|\| \{ log_entry "SKIP lock_contested"; exit 0; \}/g) || [];
expect(mvAside.length).toBe(2); // TTL branch + dead-PID branch
// The only rm -rf of the live lock dir is the holder's EXIT trap.
// The only rm -rf of the live lock dir is the holder's EXIT trap — and
// even that one is ownership-checked (see the static pin below).
const bareRms = src.match(/rm -rf "\$LOCK_DIR"(?!\.)/g) || [];
expect(bareRms.length).toBe(1);
expect(src).toContain(`trap 'rm -rf "$LOCK_DIR" 2>/dev/null' EXIT`);
expect(src).toContain(
`trap 'kill "$HB_PID" 2>/dev/null; [ "$(cat "$LOCK_DIR/pid" 2>/dev/null)" = "$MYPID" ] && rm -rf "$LOCK_DIR" 2>/dev/null' EXIT`,
);
});
test('EXIT trap is ownership-checked and a heartbeat runs during pull/setup (static pins)', () => {
const src = fs.readFileSync(SCRIPT, 'utf8');
// (a) After a TTL reclaim by another updater, $LOCK_DIR belongs to the
// NEW holder — the old holder's trap must remove the lock ONLY while the
// pidfile still contains ITS pid (MYPID captured at write time).
const trapLine = src.split('\n').find((l) => l.includes("trap '") && l.includes('rm -rf "$LOCK_DIR"'));
expect(trapLine).toBeDefined();
expect(trapLine!).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"');
// (b) In-flight heartbeat: the step-boundary touches only fire AFTER the
// pull / setup return, so a legitimately-slow step past the 30-min TTL
// got reclaimed while ALIVE. The loop re-checks ownership each beat and
// exits instead of touching a reclaimed holder's pidfile.
expect(src).toMatch(
/while :; do sleep 300; \[ "\$\(cat "\$LOCK_DIR\/pid" 2>\/dev\/null\)" = "\$MYPID" \] \|\| exit 0; touch "\$LOCK_DIR\/pid" 2>\/dev\/null; done/,
);
expect(src).toContain('HB_PID=$!');
// The trap stops the heartbeat so it can never outlive the holder.
expect(trapLine!).toContain('kill "$HB_PID"');
});
test('an expired-TTL lock is reclaimed even when its pid is alive (PID reuse)', async () => {
+14
View File
@@ -237,6 +237,20 @@ describe('timeline-stop-hook wiring', () => {
expect(teardown).toContain('remove-source --source gstack-timeline-stop');
});
test('setup surfaces a settings-hook refusal instead of swallowing it', () => {
// The hardened settings-hook refuses to rewrite a corrupt settings.json
// (exit 1). Both setup call sites (ALREADY_INSTALLED plan-tune re-point,
// timeline ensure-event) must stay non-fatal but PRINT the failure.
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
const warnings = setup.match(/settings hook update failed/g) || [];
expect(warnings.length).toBeGreaterThanOrEqual(2);
// The old swallow patterns are gone (the --no-team remove-source teardown
// legitimately keeps its 2>/dev/null; only the ensure-event registration
// must surface stderr).
expect(setup).not.toContain('_install_plan_tune_hooks >/dev/null 2>&1 || true');
expect(setup).not.toMatch(/ensure-event[\s\S]{0,220}--source gstack-timeline-stop[\s\S]{0,40}2>\/dev\/null/);
});
test('setup routes the Stop hook through ensure-event, not presence-only dedup', () => {
const setup = fs.readFileSync(path.join(ROOT, 'setup'), 'utf-8');
// ensure-event registers when missing AND re-points a stale path in place.