Skip to content

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
41.7 KB
Raw Blame
/**
 * The shared land lock (crew/lib/ship-queue-land-lock.ts, #3599): `land` and `train land` take the same
 * refs/notes/gstack-land lock, so a standalone land and a train slot can never both publish onto one main.
 * Module cases run against a bare origin and two clones (the race, the read states, owner kinds, the
 * --break-lock rules); command cases drive bin/gstack-ship-queue against the train fixture and its gh
 * shims (both directions, the train-scoped between phase, refusal and resume, the freeze-owned lock and the
 * repair train's takeover).
 */
import { afterEach, describe, expect, test } from 'bun:test';
import * as fs from 'node:fs';
import * as path from 'node:path';
import { EXIT } from '../../lib/headless-artifacts';
import { spawn, spawnSync } from 'node:child_process';
import * as os from 'node:os';
import { acquireLandLock, DIRECT_LOCK_TTL_MS, judgeOwner, LAND_LOCK_REF, readLock, thisProcess, writeLock, type LandLock, type LockOwner, type LockProcess } from '../lib/ship-queue-land-lock';
import { bunIsolationArgs } from '../../lib/bun-isolation';
import { BASE_POLICY, cleanup, makeFixtureRepo, type FixtureRepo } from '../../test/helpers/restamp-fixture';
import { flakyGit } from '../../test/helpers/flaky-git';
import { coordinatorClone } from '../../test/helpers/ship-queue-fixture';
import {
  GREEN_GATE, TRAIN_POLICY, fragmentPr, nonceOf, queue, repoKey, trainFixture, trainJson, wrapLand, type TrainFixture,
} from '../../test/helpers/ship-queue-train-fixture';

const repos: FixtureRepo[] = [];
const fixtures: TrainFixture[] = [];
afterEach(() => {
  while (repos.length) cleanup(repos.pop()!);
  while (fixtures.length) cleanup(fixtures.pop()!.repo);
});

const T0 = Date.parse('2026-10-31T12:00:00Z');
const at = (min: number) => () => new Date(T0 + min * 60_000);

/** Run fn with the fixture's git identity in process.env (the lock writes commits in-process). */
function withRepoEnv<T>(repo: FixtureRepo, fn: () => T): T {
  const saved = Object.fromEntries(Object.keys(repo.env).map(k => [k, process.env[k]]));
  Object.assign(process.env, repo.env);
  try { return fn(); } finally {
    for (const [k, v] of Object.entries(saved)) { if (v === undefined) delete process.env[k]; else process.env[k] = v; }
  }
}
function bareRepo(): FixtureRepo { const r = makeFixtureRepo({ policy: BASE_POLICY, prefix: 'gstack-land-lock-' }); repos.push(r); return r; }
const standalone = (pr: string): LockOwner => ({ pr });
const slotOf = (train: string, slot: number, pr: string): LockOwner => ({ train, slot, pr });
function take(root: string, owner: LockOwner, o: { journal?: string; now?: () => Date; breakLock?: boolean; breakTrainLock?: boolean; liveTrain?: (nonce: string) => boolean; phase?: LandLock['phase'] } = {}) {
  return acquireLandLock({
    root, holder: 'test:1', owner, journal: o.journal ?? ('train' in owner && owner.train ? `train/${owner.train}/slot-${owner.slot}` : `land/${owner.pr}`),
    phase: () => o.phase ?? 'stamping', now: o.now ?? at(0), breakLock: o.breakLock, breakTrainLock: o.breakTrainLock, liveTrain: o.liveTrain,
  });
}
const failureOf = (r: ReturnType<typeof take>) => ('failure' in r ? r.failure : null);

describe('the lock module', () => {
  test('two writers racing the same lock sha leave one winner', () => {
    const repo = bareRepo();
    const other = coordinatorClone(repo);
    withRepoEnv(repo, () => {
      const lock = (pr: string): LandLock => ({ pr, holder: `h${pr}`, started_at: new Date(T0).toISOString(), phase: 'stamping', journal: `land/${pr}` });
      expect(readLock(repo.work).state).toBe('absent');
      const first = writeLock(repo.work, '', lock('1'));
      const second = writeLock(other, '', lock('2'));
      expect([first.ok, second.ok]).toEqual([true, false]);
      const seen = readLock(other);
      expect(seen.state === 'held' && seen.lock.pr).toBe('1');
      const a = writeLock(repo.work, seen.sha, lock('3'));
      const b = writeLock(other, seen.sha, lock('4'));
      expect([a.ok, b.ok]).toEqual([true, false]);
      const final = readLock(other);
      expect(final.state === 'held' && final.lock.pr).toBe('3');
    });
  }, 60_000);

  test('absent, released, held and unreadable are distinct; an unreadable lock refuses, and --break-lock replaces it', () => {
    const repo = bareRepo();
    withRepoEnv(repo, () => {
      const root = repo.work;
      expect(readLock(root)).toMatchObject({ state: 'absent' });
      const got = take(root, standalone('5'));
      expect(failureOf(got)).toBeNull();
      expect(readLock(root)).toMatchObject({ state: 'held', lock: { pr: '5', phase: 'stamping' } });
      if ('held' in got) expect(got.held.release()).toBe(true);
      expect(readLock(root)).toMatchObject({ state: 'released' });
      const junk = repo.git('commit-tree', '4b825dc642cb6eb9a060e54bf8d69288fbee4904', '-m', 'not a lock');
      repo.git('push', '-q', '-f', 'origin', `${junk}:${LAND_LOCK_REF}`);
      expect(readLock(root)).toMatchObject({ state: 'unreadable' });
      const refused = take(root, standalone('6'));
      expect(failureOf(refused)).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(failureOf(refused)!.message).toContain('cannot be read');
      const broke = take(root, standalone('6'), { breakLock: true });
      expect(failureOf(broke)).toBeNull();
      expect(broke.lines.join('\n')).toContain(`LOCK: broke an unreadable lock at ${junk.slice(0, 12)}`);
      expect(readLock(root)).toMatchObject({ state: 'held', lock: { pr: '6' } });
    });
  }, 60_000);

  test('ownership compares the owner kind and journal: the same PR across commands and across trains refuses; a resume of the same journal and a sequential acquisition succeed', () => {
    const repo = bareRepo();
    withRepoEnv(repo, () => {
      const root = repo.work;
      const mine = take(root, standalone('7'), { phase: 'waiting' });
      expect(failureOf(mine)).toBeNull();
      const asSlot = take(root, slotOf('trainA', 1, '7'));
      expect(failureOf(asSlot)).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(failureOf(asSlot)!.message).toMatch(/^#7 holds the land lock \(test:1, phase waiting, since /);
      const resumed = take(root, standalone('7'), { now: at(3) });
      expect(failureOf(resumed)).toBeNull();
      expect(readLock(root)).toMatchObject({ state: 'held', lock: { pr: '7', started_at: new Date(T0).toISOString() } });
      if ('held' in resumed) resumed.held.release();

      const trainA = take(root, slotOf('trainA', 1, '7'), { phase: 'pushing' });
      expect(failureOf(trainA)).toBeNull();
      expect(readLock(root)).toMatchObject({ state: 'held', lock: { train: 'trainA', slot: 1, pr: '7' } });
      const trainB = take(root, slotOf('trainB', 1, '7'));
      expect(failureOf(trainB)!.message).toMatch(/^train trainA slot 1 \(#7\) holds the land lock/);
      expect(failureOf(take(root, standalone('7')))!.message).toMatch(/^train trainA slot 1 \(#7\) holds the land lock/);
      expect(failureOf(take(root, slotOf('trainA', 2, '8')))!.message).toMatch(/^train trainA slot 1 \(#7\) holds the land lock/);
      const same = take(root, slotOf('trainA', 1, '7'));
      expect(failureOf(same)).toBeNull();
      if ('held' in same) same.held.release();
      expect(failureOf(take(root, standalone('8')))).toBeNull();
    });
  }, 60_000);

  test('GST-1344: a push origin applied but answered with an HTTP 502 counts as written; a push that never landed reports the lock unchanged; an unreadable origin says so instead', () => {
    const repo = bareRepo();
    const g = flakyGit(repo.root);
    withRepoEnv({ ...repo, env: { ...repo.env, ...g.env } }, () => {
      const root = repo.work;
      const lock: LandLock = { pr: '11', holder: 'h11', started_at: new Date(T0).toISOString(), phase: 'stamping', journal: 'land/11' };
      g.pushLandsThenFails(1);
      const w = writeLock(root, '', lock);
      expect(w.ok).toBe(true);
      expect(repo.git('rev-parse', LAND_LOCK_REF)).toBe(w.sha);
      expect(repo.git('--git-dir', repo.origin, 'rev-parse', LAND_LOCK_REF)).toBe(w.sha);

      g.reset();
      const got = take(root, standalone('11'), { journal: 'land/11' });
      expect(failureOf(got)).toBeNull();
      if (!('held' in got)) return;
      g.pushFails(1);
      expect(got.held.set('waiting')).toMatchObject({ code: 'QUEUE_NOT_READY', message: expect.stringContaining('the lock there is unchanged') });
      g.pushFails(1);
      g.lsRemoteFails(2);
      g.fetchFails(true);
      expect(got.held.set('waiting')).toMatchObject({ code: 'QUEUE_NOT_READY', message: expect.stringContaining('could not be read') });
      g.reset();
      expect(got.held.release()).toBe(true);
      expect(readLock(root)).toMatchObject({ state: 'released' });
    });
  }, 60_000);

  test('GST-1344: a phase change rejected because origin holds a newer lock from this same run adopts that sha and retries once; the same journal under another holder is not adopted', () => {
    const repo = bareRepo();
    withRepoEnv(repo, () => {
      const root = repo.work;
      const got = take(root, standalone('12'), { journal: 'land/12' });
      if (!('held' in got)) throw new Error('lock not taken');
      const ahead = (holder: string) => {
        const r = readLock(root);
        const w = writeLock(root, r.sha, { ...got.held.lock, holder, phase: 'waiting' });
        expect(w.ok).toBe(true);
        repo.git('update-ref', LAND_LOCK_REF, r.sha);
        return w.sha;
      };
      const mine = ahead('test:1');
      expect(got.held.set('pushing')).toBeNull();
      const after = readLock(root);
      expect(after).toMatchObject({ state: 'held', lock: { phase: 'pushing' } });
      expect(repo.git('rev-parse', `${after.sha}^`)).toBe(mine);

      const theirs = ahead('other:2');
      expect(got.held.set('merging')).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(repo.git('--git-dir', repo.origin, 'rev-parse', LAND_LOCK_REF)).toBe(theirs);
    });
  }, 60_000);

  test('--break-lock prints the holder, refuses a live train run\'s lock without --break-train-lock, and keeps the staleness, mid-push, between and freeze rules', () => {
    const repo = bareRepo();
    withRepoEnv(repo, () => {
      const root = repo.work;
      const hold = (owner: LockOwner, phase: LandLock['phase']) => {
        const r = readLock(root);
        if (r.state === 'held') writeLock(root, r.sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
        expect(failureOf(take(root, owner, { phase }))).toBeNull();
      };
      hold(slotOf('trainA', 2, '9'), 'waiting');
      const live = take(root, standalone('3'), { breakLock: true, now: at(1) });
      expect(failureOf(live)).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(failureOf(live)!.message).toContain('--break-train-lock');
      expect(live.lines).toContain(`LOCK_HOLDER: train trainA slot 2 (#9) holder=test:1 phase=waiting since=${new Date(T0).toISOString()}`);
      const ended = take(root, standalone('3'), { breakLock: true, now: at(1), liveTrain: () => false });
      expect(failureOf(ended)).toBeNull();
      expect(ended.lines).toContain("LOCK: broke train trainA slot 2 (#9)'s lock (test:1, phase waiting)");

      hold(slotOf('trainA', 2, '9'), 'waiting');
      const forced = take(root, standalone('3'), { breakLock: true, breakTrainLock: true, now: at(1) });
      expect(failureOf(forced)).toBeNull();

      hold(slotOf('trainA', 1, '9'), 'between');
      const young = take(root, standalone('3'), { breakLock: true, breakTrainLock: true, now: at(1) });
      expect(failureOf(young)!.message).toMatch(/train trainA slot 1 \(#9\) is between slots \(60 s ago\); --break-lock refused/);
      expect(failureOf(take(root, standalone('3'), { breakLock: true, breakTrainLock: true, now: at(11) }))).toBeNull();

      hold(slotOf('trainA', 1, '9'), 'pushing');
      expect(failureOf(take(root, standalone('3'), { breakLock: true, breakTrainLock: true, now: at(1) }))!.message).toMatch(/train trainA slot 1 \(#9\)'s holder is mid-push \(60 s ago\); --break-lock refused/);

      hold(slotOf('trainA', 1, '9'), 'freeze');
      const frozen = take(root, standalone('3'), { breakLock: true, breakTrainLock: true, now: at(60) });
      expect(failureOf(frozen)).toMatchObject({ code: 'QUEUE_TRAIN_FROZEN' });
      expect(failureOf(take(root, slotOf('trainB', 1, '4'), { breakLock: true, breakTrainLock: true, now: at(60) }))).toMatchObject({ code: 'QUEUE_TRAIN_FROZEN' });

      hold(standalone('5'), 'waiting');
      const plain = take(root, standalone('3'), { breakLock: true, now: at(1) });
      expect(plain.lines).toContain(`LOCK_HOLDER: #5 holder=test:1 phase=waiting since=${new Date(T0).toISOString()}`);
      expect(plain.lines).toContain("LOCK: broke #5's lock (test:1, phase waiting)");
    });
  }, 60_000);
});

/** A real process as a lock records it: its group and kernel start time, with this machine's boot id and pid namespace. */
function procOf(pid: number, self: LockProcess, boot = self.boot): LockProcess {
  const stat = fs.readFileSync(`/proc/${pid}/stat`, 'utf8');
  const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
  return { boot, pidns: self.pidns, pid, pgid: Number(f[2]), start: Number(f[19]), mark: `mark-${pid}-${Date.now()}` };
}
/** A detached shell running script; resolves once /proc shows it leading its own process group. */
async function group(script: string) {
  const child = spawn('sh', ['-c', script], { detached: true, stdio: 'ignore' });
  const exited = new Promise<void>(resolve => child.on('exit', () => resolve()));
  const leads = () => { try { const s = fs.readFileSync(`/proc/${child.pid}/stat`, 'utf8'); return Number(s.slice(s.lastIndexOf(')') + 2).split(' ')[2]) === child.pid; } catch { return false; } };
  while (!leads()) await Bun.sleep(5);
  return { pid: child.pid!, exited, kill: () => { try { process.kill(-child.pid!, 'SIGKILL'); } catch { /* gone */ } } };
}

describe.skipIf(process.platform !== 'linux')('a direct land\'s lock cannot go stale (process-scoped locks)', () => {
  const pin = (n: string) => `land-pin:${n.repeat(40)}`;
  const marksDirs: string[] = [];
  afterEach(() => { while (marksDirs.length) fs.rmSync(marksDirs.pop()!, { recursive: true, force: true }); });
  const newMarks = () => { const d = fs.mkdtempSync(path.join(os.tmpdir(), 'gstack-land-marks-')); marksDirs.push(d); return d; };
  const takeDirect = (root: string, pr: string, o: { proc: LockProcess | null; marks: string; now?: () => Date; breakLock?: boolean; journal?: string; releasesHold?: boolean }) => acquireLandLock({
    root, holder: `cox.local:${o.proc?.pid ?? 1}`, owner: { pr }, journal: o.journal ?? pin(pr.slice(-1)), now: o.now ?? at(0), phase: () => 'merging', breakLock: o.breakLock, releasesHold: o.releasesHold,
    processScoped: { ttlMs: DIRECT_LOCK_TTL_MS, proc: o.proc, marks: o.marks },
  });

  test('a lock whose land process has exited is taken over without --break-lock, and the takeover is logged in the output and in the new lock', async () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const marks = newMarks();
    const dead = await group('sleep 30');
    const proc = procOf(dead.pid, self);
    dead.kill();
    await dead.exited;
    withRepoEnv(repo, () => {
      expect(failureOf(takeDirect(repo.work, '4670', { proc, marks }))).toBeNull();
      expect(readLock(repo.work)).toMatchObject({ state: 'held', lock: { pr: '4670', proc: { pid: dead.pid }, expires_at: new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString() } });
      const judged = readLock(repo.work).sha;
      const next = takeDirect(repo.work, '4671', { proc: { ...self, mark: 'next' }, marks, now: at(1) });
      expect(failureOf(next)).toBeNull();
      expect(next.lines.join('\n')).toMatch(new RegExp(`^LOCK_TAKEOVER: #4670's land lock \\(holder cox.local:${dead.pid}, phase merging, since .*\\): its land \\(process ${dead.pid}\\) and every process it started have exited$`, 'm'));
      const now = readLock(repo.work);
      expect(now).toMatchObject({ state: 'held', lock: { pr: '4671', took_over: { pr: '4670', sha: judged, holder: `cox.local:${dead.pid}` } } });
      expect(repo.git('log', '-1', '--format=%s', LAND_LOCK_REF)).toContain('(took over #4670: its land');
    });
  }, 60_000);

  test('a lock whose land is still running is refused, --break-lock included, even when the land\'s first process exited and left a child running', async () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const marks = newMarks();
    const live = await group('sleep 60');
    const parent = await group('sleep 60 & sleep 0.5; exit 0');
    try {
      const parentProc = procOf(parent.pid, self);
      await parent.exited;
      withRepoEnv(repo, () => {
        expect(failureOf(takeDirect(repo.work, '4670', { proc: procOf(live.pid, self), marks }))).toBeNull();
        for (const breakLock of [false, true]) {
          const refused = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'b' }, marks, now: at(500), breakLock }));
          expect(refused).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
          expect(refused!.message).toContain(`#4670's land is still running: process ${live.pid} of its land`);
          expect(refused!.fix).toContain(`stop process ${live.pid}`);
        }
        live.kill();
        writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
        expect(failureOf(takeDirect(repo.work, '4672', { proc: parentProc, marks }))).toBeNull();
        const orphaned = failureOf(takeDirect(repo.work, '4673', { proc: { ...self, mark: 'c' }, marks, now: at(1) }));
        expect(orphaned!.message).toMatch(/#4672's land is still running: process \d+ of its land/);
        expect(orphaned!.message).not.toContain(`process ${parent.pid} of`);
      });
    } finally { live.kill(); parent.kill(); }
  }, 60_000);

  test('a lock from another machine is refused until it expires, naming the expiry and the fix, then taken over; one this machine wrote before it restarted is taken over at once', () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const marks = newMarks();
    withRepoEnv(repo, () => {
      const elsewhere: LockProcess = { ...self, boot: 'another-boot', pid: 1640, pgid: 1640, start: 1, mark: 'elsewhere' };
      expect(failureOf(takeDirect(repo.work, '4670', { proc: elsewhere, marks: newMarks() }))).toBeNull();
      const early = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'x' }, marks, now: at(89) }));
      expect(early).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(early!.message).toContain('its land ran on another machine, so this one cannot check whether it still runs');
      expect(early!.fix).toContain(`the lock expires at ${new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString()} (in 1 min)`);
      expect(early!.fix).toContain('--break-lock');
      const expired = takeDirect(repo.work, '4671', { proc: { ...self, mark: 'y' }, marks, now: at(90) });
      expect(failureOf(expired)).toBeNull();
      expect(expired.lines.join('\n')).toContain(`LOCK_TAKEOVER: #4670's land lock (holder cox.local:1640, phase merging, since ${new Date(T0).toISOString()}): it expired at ${new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString()}`);

      const before: LockProcess = { ...self, boot: 'before-restart', pid: 1639, pgid: 1639, start: 1, mark: 'restarted' };
      writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
      expect(failureOf(takeDirect(repo.work, '4672', { proc: before, marks }))).toBeNull();
      expect(fs.existsSync(path.join(marks, 'restarted.json'))).toBe(true);
      const rebooted = takeDirect(repo.work, '4673', { proc: { ...self, mark: 'z' }, marks, now: at(1) });
      expect(failureOf(rebooted)).toBeNull();
      expect(rebooted.lines.join('\n')).toContain('this machine wrote it before it last restarted, so its land is gone');
      expect(fs.existsSync(path.join(marks, 'restarted.json'))).toBe(false);
    });
  }, 60_000);

  test('a lock from an older gstack (no process, no expiry) expires 90 minutes after its last phase; a deliberate hold refuses even after it expires', () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const marks = newMarks();
    withRepoEnv(repo, () => {
      const old: LandLock = { pr: '4670', holder: 'cox.local:74326', started_at: new Date(T0).toISOString(), phase_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('4') };
      writeLock(repo.work, readLock(repo.work).sha, old);
      expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'p' }, marks, now: at(30) }))!.message).toContain('it records no land process (an older gstack wrote it)');
      expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'q' }, marks, now: at(91) }))).toBeNull();

      const holder: LockProcess = { ...self, boot: 'held-boot', pid: 77, pgid: 77, start: 1, mark: 'held' };
      writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
      const tampered = takeDirect(repo.work, '4672', { proc: holder, marks });
      if (!('held' in tampered)) throw new Error('lock not taken');
      tampered.held.hold('land.merged_checks changed this checkout\'s git directory while landing #4672');
      const refused = failureOf(takeDirect(repo.work, '4673', { proc: { ...self, mark: 'r' }, marks, now: at(500) }));
      expect(refused!.message).toContain('its land left it held on purpose: land.merged_checks changed');
      expect(refused!.fix).toContain(`gstack-ship-queue land --pr 4672 --pin ${'2'.repeat(40)}`);
    });
  }, 60_000);

  test('a hold set while land.merged_checks run keeps a dead land\'s lock refused; cleared, the lock is taken over', async () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const marks = newMarks();
    const dead = await group('sleep 30');
    const proc = procOf(dead.pid, self);
    dead.kill();
    await dead.exited;
    withRepoEnv(repo, () => {
      const got = takeDirect(repo.work, '4670', { proc, marks });
      if (!('held' in got)) throw new Error('lock not taken');
      expect(got.held.hold('land.merged_checks were running when it stopped')).toBe(true);
      const refused = failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'h1' }, marks, now: at(1) }));
      expect(refused!.message).toContain('its land left it held on purpose: land.merged_checks were running when it stopped');
      expect(refused!.fix).toContain('or pass --break-lock');
      const retry = failureOf(takeDirect(repo.work, '4670', { proc: { ...self, mark: 'h0' }, marks, now: at(1) }));
      expect(retry!.message).toBe("#4670's earlier land left the lock held on purpose: land.merged_checks were running when it stopped");
      expect(failureOf(takeDirect(repo.work, '4670', { proc: { ...self, mark: 'h0' }, marks, now: at(1), releasesHold: true }))).toBeNull();
      writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });

      const again = takeDirect(repo.work, '4672', { proc, marks });
      if (!('held' in again)) throw new Error('lock not taken');
      expect(again.held.hold('land.merged_checks were running when it stopped')).toBe(true);
      expect(again.held.hold(null)).toBe(true);
      expect(failureOf(takeDirect(repo.work, '4671', { proc: { ...self, mark: 'h2' }, marks, now: at(1) }))).toBeNull();

      const unwritable = path.join(marks, 'not-a-dir');
      fs.writeFileSync(unwritable, '');
      writeLock(repo.work, readLock(repo.work).sha, { released: true, by: 'test', at: new Date(T0).toISOString() });
      const blind = takeDirect(repo.work, '4673', { proc: { ...self, mark: 'h3' }, marks: unwritable });
      if (!('held' in blind)) throw new Error('lock not taken');
      expect(blind.held.hold('land.merged_checks were running when it stopped')).toBe(false);
    });
  }, 60_000);

  test('a mark file proves a restart only for this machine and a different boot: another pid namespace or another machine\'s mark is unknown', () => {
    const self = thisProcess()!;
    const marks = newMarks();
    const lock = (proc: LockProcess): LandLock => ({ pr: '4670', holder: 'cox.local:9', started_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('4'), proc });
    const otherNs: LockProcess = { ...self, pidns: 'pid:[1]', pid: 9, pgid: 9, start: 1, mark: 'ns' };
    const machine = `${os.hostname()}/${(() => { try { return fs.readFileSync('/etc/machine-id', 'utf8').trim(); } catch { return ''; } })()}`;
    fs.writeFileSync(path.join(marks, 'ns.json'), JSON.stringify({ machine, boot: self.boot }));
    expect(judgeOwner(lock(otherNs), self, marks).state).toBe('unknown');
    const heldElsewhere: LockProcess = { ...self, boot: 'their-boot', pid: 9, pgid: 9, start: 1, mark: 'held-elsewhere' };
    fs.writeFileSync(path.join(marks, 'held-elsewhere.json'), JSON.stringify({ machine: 'another-host/another-id', boot: 'their-boot', hold: 'land.merged_checks were running when it stopped' }));
    expect(judgeOwner(lock(heldElsewhere), self, marks).state).toBe('unknown');
    const otherMachine: LockProcess = { ...self, boot: 'their-boot', pid: 9, pgid: 9, start: 1, mark: 'theirs' };
    fs.writeFileSync(path.join(marks, 'theirs.json'), JSON.stringify({ machine: 'another-host/another-id', boot: 'their-boot' }));
    expect(judgeOwner(lock(otherMachine), self, marks).state).toBe('unknown');
  });

  test('a rerun in the dead holder\'s own process group is not refused because of its own siblings (a | cat beside it)', () => {
    const dir = newMarks();
    const judge = path.join(dir, 'judge.ts');
    fs.writeFileSync(judge, `import * as fs from 'node:fs';
import { judgeOwner, thisProcess } from ${JSON.stringify(path.resolve(import.meta.dir, '../lib/ship-queue-land-lock.ts'))};
const self = thisProcess()!;
const stat = fs.readFileSync(process.argv[2]!, 'utf8');
const f = stat.slice(stat.lastIndexOf(')') + 2).split(' ');
const proc = { ...self, pid: Number(stat.split(' ')[0]), pgid: Number(f[2]), start: Number(f[19]), mark: 'none' };
console.log(judgeOwner({ pr: '1', holder: 'h', started_at: '', phase: 'merging', journal: 'land-pin:1', proc }, self, process.argv[3]!).state);
`);
    const bun = [process.execPath, ...bunIsolationArgs()].map(a => `'${a}'`).join(' ');
    const script = `sleep 0.5 & cat /proc/$!/stat > '${dir}/holder.stat'; wait; ${bun} '${judge}' '${dir}/holder.stat' '${dir}' | cat`;
    const r = spawnSync('setsid', ['sh', '-c', script], { encoding: 'utf8', timeout: 30_000 });
    expect(r.stdout.trim(), r.stderr).toBe('gone');
  }, 60_000);

  test('a stalled takeover never replaces a newer owner\'s lock, and a taken-over land can neither move nor release the lock it lost', async () => {
    const self = thisProcess()!;
    const repo = bareRepo();
    const other = coordinatorClone(repo);
    const marks = newMarks();
    const dead = await group('sleep 30');
    const deadProc = procOf(dead.pid, self);
    dead.kill();
    await dead.exited;
    withRepoEnv(repo, () => {
      const lost = takeDirect(repo.work, '4670', { proc: deadProc, marks });
      if (!('held' in lost)) throw new Error('lock not taken');
      let fresh = '';
      const stalled = takeDirect(repo.work, '4671', {
        proc: { ...self, mark: 'stalled' }, marks,
        now: () => {
          if (!fresh) {
            const seen = readLock(other);
            const w = writeLock(other, seen.sha, { pr: '4672', holder: 'fresh:1', started_at: new Date(T0).toISOString(), phase: 'merging', journal: pin('7'), proc: { ...self, mark: 'fresh' }, expires_at: new Date(T0 + DIRECT_LOCK_TTL_MS).toISOString() });
            expect(w.ok).toBe(true);
            fresh = w.sha;
          }
          return new Date(T0 + 60_000);
        },
      });
      expect(failureOf(stalled)).toMatchObject({ code: 'QUEUE_LAND_LOCKED', message: 'the land lock moved under this run (another lander took it)' });
      expect(repo.git('--git-dir', repo.origin, 'rev-parse', LAND_LOCK_REF)).toBe(fresh);
      expect(lost.held.set('merging')).toMatchObject({ code: 'QUEUE_LAND_LOCKED' });
      expect(lost.held.release()).toBe(false);
      expect(readLock(repo.work)).toMatchObject({ state: 'held', lock: { pr: '4672', holder: 'fresh:1' } });
    });
  }, 60_000);
});

const POLICY = { ...TRAIN_POLICY, release_tool: null, release_outputs: [], changelog_fragments: { dir: 'changelog.d' }, min_gstack_version: '1.91.336.0' };
function stampedTrain(prs = ['1', '2']) {
  const fx = trainFixture(POLICY, 'gstack-land-lock-'); fixtures.push(fx); wrapLand(fx);
  const heads = prs.map(pr => fragmentPr(fx, pr));
  fx.write(d => { d.rules['evals.yml'] = GREEN_GATE; });
  const nonce = nonceOf(queue(fx, ['train', 'build', '--prs', prs.map((pr, i) => `${pr}@${heads[i]}`).join(',')]).out);
  expect(queue(fx, ['train', 'verdict', '--train', nonce]).status).toBe(EXIT.ok);
  return { fx, heads, nonce };
}
const trainLand = (fx: TrainFixture, nonce: string, pr: string, extra: string[] = []) => queue(fx, ['train', 'land', '--train', nonce, '--pr', pr, '--no-wait', ...extra]);
const land = (fx: TrainFixture, pr: string, extra: string[] = []) => queue(fx, ['land', '--pr', pr, '--no-wait', '--allow-repo-commands', ...extra]);
const originRev = (fx: TrainFixture, ref: string) => fx.repo.git('--git-dir', fx.repo.origin, 'rev-parse', '--verify', '-q', ref);
/** The lock as origin holds it: the parsed lock.json, or null when origin has no lock ref. */
function originLock(fx: TrainFixture): any {
  const sha = (() => { try { return originRev(fx, LAND_LOCK_REF); } catch { return ''; } })();
  return sha ? JSON.parse(fx.repo.git('--git-dir', fx.repo.origin, 'show', `${sha}:lock.json`)) : null;
}
const freezeFile = (fx: TrainFixture) => path.join(fx.state, 'ship-queue', 'freeze');

describe('land and train land share the lock', () => {
  test('a train slot holding the lock refuses a standalone land (no takeover, no freeze; --break-lock names the train and wants --break-train-lock); the train keeps it between slots and releases it after the last', () => {
    const { fx, heads, nonce } = stampedTrain();
    const pin3 = fragmentPr(fx, '3');
    const pushed = trainLand(fx, nonce, '1');
    expect(pushed.out, pushed.err).toMatch(/^PUSHED: [0-9a-f]{40}/m);
    expect(originLock(fx)).toMatchObject({ train: nonce, slot: 1, pr: '1', phase: 'waiting' });
    const lockSha = originRev(fx, LAND_LOCK_REF);

    const blocked = land(fx, '3');
    expect(blocked.status).toBe(EXIT.refused);
    expect(blocked.err).toMatch(new RegExp(`train ${nonce} slot 1 \\(#1\\) holds the land lock .*phase waiting.*\\(QUEUE_LAND_LOCKED\\)`));
    const broke = land(fx, '3', ['--break-lock']);
    expect(broke.status).toBe(EXIT.refused);
    expect(broke.err).toContain('--break-train-lock');
    expect(broke.out).toMatch(new RegExp(`^LOCK_HOLDER: train ${nonce} slot 1 \\(#1\\) holder=\\S+ phase=waiting since=`, 'm'));
    expect(originRev(fx, LAND_LOCK_REF)).toBe(lockSha);
    expect(originRev(fx, 'refs/heads/pr-3')).toBe(pin3);
    expect(fs.existsSync(freezeFile(fx))).toBe(false);

    const merged = trainLand(fx, nonce, '1');
    expect(merged.status, merged.err).toBe(EXIT.ok);
    expect(originLock(fx)).toMatchObject({ train: nonce, slot: 1, pr: '1', phase: 'between' });
    expect(land(fx, '3').err).toMatch(new RegExp(`train ${nonce} slot 1 \\(#1\\) holds the land lock .*phase between.*\\(QUEUE_LAND_LOCKED\\)`));
    expect(originRev(fx, 'refs/heads/pr-3')).toBe(pin3);

    const second = trainLand(fx, nonce, '2');
    expect(second.out, second.err).toMatch(/^LOCK: train \S+ slot 2 takes over its train's between-slots lock/m);
    expect(originLock(fx)).toMatchObject({ train: nonce, slot: 2, pr: '2', phase: 'waiting' });
    expect(trainLand(fx, nonce, '2').status).toBe(EXIT.ok);
    expect(originLock(fx)).toMatchObject({ released: true });
    expect(trainJson(fx, nonce).state).toBe('merged');
    expect(land(fx, '3').out).toMatch(/^PUSHED: [0-9a-f]{40}/m);
    void heads;
  }, 300_000);

  // fails_when=settleLock releases the lock on a refusal partway through a train, so one transient gh or fetch failure on slot 2 lets a standalone land publish onto S1 and the rerun freezes the queue (red team, PR #3737 pass 1); why_new=the test above refuses slot 1 only, before anything merged; seam=the fixture's gh pr view; no_claim=the freeze itself
  test('a refusal partway through a train (slot 1 merged, slot 2 cannot read its PR) keeps the lock between slots, so a standalone land still refuses', () => {
    const { fx, nonce } = stampedTrain();
    fragmentPr(fx, '3');
    trainLand(fx, nonce, '1');
    expect(trainLand(fx, nonce, '1').status).toBe(EXIT.ok);
    const row = fx.read().prs['2'];
    fx.write(d => { delete d.prs['2']; });
    const refused = trainLand(fx, nonce, '2');
    expect(refused.err).toContain('(QUEUE_PROOF_MISSING)');
    expect(refused.out).toMatch(/^LOCK: between /m);
    expect(originLock(fx)).toMatchObject({ train: nonce, phase: 'between' });
    expect(land(fx, '3').err).toMatch(/holds the land lock .*phase between.*\(QUEUE_LAND_LOCKED\)/);
    fx.write(d => { d.prs['2'] = row; });
    expect(trainLand(fx, nonce, '2').out).toMatch(/^PUSHED: [0-9a-f]{40}/m);
  }, 300_000);

  /** Another train's lock, written to origin as that train's run would have left it. */
  function seedLock(fx: TrainFixture, lock: Partial<LandLock> & { train: string; phase: LandLock['phase'] }): void {
    withRepoEnv(fx.repo, () => {
      const cur = readLock(fx.repo.work);
      expect(writeLock(fx.repo.work, cur.sha, { pr: '9', slot: 1, holder: 'old:1', started_at: '2026-10-31T12:00:00.000Z', phase_at: '2026-10-31T12:00:00.000Z', journal: `train/${lock.train}/slot-1`, ...lock } as LandLock).ok).toBe(true);
    });
  }
  /** A freeze record for this repository, cleared at `cleared`, written to the state root as the clearing verify leaves it. */
  function clearedFreeze(fx: TrainFixture, train: string, cleared: string): void {
    const file = path.join(freezeFile(fx), `${repoKey(fx)}.json`);
    fs.mkdirSync(path.dirname(file), { recursive: true });
    fs.writeFileSync(file, JSON.stringify({ schema: 1, kind: 'freeze', repo_key: repoKey(fx), train, merged: ['9'], unmerged: [], main: { sha: '0'.repeat(40), tree: '0'.repeat(40) }, reason: 'test', backstop: null, repair: null, created_at: '2026-10-31T11:00:00.000Z', cleared_at: cleared, cleared_by: 'test', updated_at: cleared }));
  }

  // fails_when=trainTakeover reads "no active freeze record here" as "the freeze is cleared", so a train whose notes fetch failed, or whose freezer never pushed the record, takes the freeze lock and lands onto a frozen main (red team, PR #3737 pass 2); why_new=the freeze test above only exercises the admitted repair train's takeover; seam=a lock and a freeze record written straight to origin and the state root; no_claim=how the record went missing
  test('another train\'s freeze lock is taken over only on a freeze record cleared after the lock: no record, or one cleared before it, refuses', () => {
    const { fx, nonce } = stampedTrain(['1']);
    const old = 'gate.train-old';
    seedLock(fx, { train: old, phase: 'freeze' });
    const noRecord = trainLand(fx, nonce, '1');
    expect(noRecord.status).toBe(EXIT.refused);
    expect(noRecord.err).toMatch(/train gate\.train-old slot 1 \(#9\) holds the land lock .*phase freeze.*\(QUEUE_LAND_LOCKED\)/);
    expect(noRecord.out).not.toMatch(/^PUSHED:/m);
    expect(originLock(fx)).toMatchObject({ train: old, phase: 'freeze' });

    clearedFreeze(fx, old, '2026-10-31T11:30:00.000Z');
    expect(trainLand(fx, nonce, '1').err).toContain('(QUEUE_LAND_LOCKED)');
    clearedFreeze(fx, old, '2026-10-31T12:30:00.000Z');
    const taken = trainLand(fx, nonce, '1');
    expect(taken.out, taken.err).toContain(`LOCK: train ${nonce} takes over train ${old} slot 1 (#9)'s freeze lock; that freeze was cleared at 2026-10-31T12:30:00.000Z`);
    expect(taken.out).toMatch(/^PUSHED: [0-9a-f]{40}/m);
  }, 300_000);

  // fails_when=a freeze lock whose release failed after its freeze cleared refuses every standalone land for good, or a lock ref deleted on origin still reads held from this clone's cached copy (adversarial review, PR #3737 Step 11); why_new=the tests above take the freeze lock over only from train land; seam=a lock and a freeze record written straight to origin and the state root; no_claim=why the release failed
  test('a standalone land takes over a freeze lock once a fetched freeze record shows it cleared after the lock, and a lock deleted on origin reads as absent', () => {
    const { fx } = stampedTrain(['1']);
    fragmentPr(fx, '3');
    seedLock(fx, { train: 'gate.train-old', phase: 'freeze' });
    const frozen = land(fx, '3');
    expect(frozen.status).toBe(EXIT.refused);
    expect(frozen.err).toMatch(/train gate\.train-old slot 1 \(#9\) holds the land lock .*phase freeze.*\(QUEUE_LAND_LOCKED\)/);
    clearedFreeze(fx, 'gate.train-old', '2026-10-31T12:30:00.000Z');
    const taken = land(fx, '3');
    expect(taken.out, taken.err).toContain("LOCK: taking over train gate.train-old slot 1 (#9)'s freeze lock; that freeze was cleared at 2026-10-31T12:30:00.000Z");
    expect(taken.out).toMatch(/^PUSHED: [0-9a-f]{40}/m);

    const { fx: other } = stampedTrain(['1']);
    fragmentPr(other, '3');
    seedLock(other, { train: 'gate.train-old', phase: 'waiting' });
    expect(land(other, '3').err).toContain('(QUEUE_LAND_LOCKED)');
    other.repo.git('--git-dir', other.repo.origin, 'update-ref', '-d', LAND_LOCK_REF);
    expect(land(other, '3').out).toMatch(/^PUSHED: [0-9a-f]{40}/m);
  }, 300_000);

  // fails_when=trainTakeover treats a live train as terminal (two landers publish onto one main) or never takes over a finished train's lock (a stale lock blocks every later train); why_new=no other test seats a foreign train's lock; seam=a second train record written into the state root; no_claim=how that train ended
  test('another train\'s lock is taken over once that train\'s record is terminal, and refused while it is still merging', () => {
    const { fx, nonce } = stampedTrain(['1']);
    const other = `${nonce}-other`;
    const put = (state: string) => {
      const dir = path.join(fx.state, 'ship-queue', 'trains', other);
      fs.mkdirSync(dir, { recursive: true });
      fs.writeFileSync(path.join(dir, 'train.json'), JSON.stringify({ ...trainJson(fx, nonce), nonce: other, state }));
    };
    put('merging');
    seedLock(fx, { train: other, phase: 'waiting' });
    expect(trainLand(fx, nonce, '1').err).toMatch(/holds the land lock .*phase waiting.*\(QUEUE_LAND_LOCKED\)/);
    put('merged');
    const taken = trainLand(fx, nonce, '1');
    expect(taken.out, taken.err).toContain(`takes over train ${other} slot 1 (#9)'s lock; that train is merged`);
    expect(taken.out).toMatch(/^PUSHED: [0-9a-f]{40}/m);
  }, 300_000);

  test('a standalone land holding the lock refuses train land; a refusal before any push releases the train\'s lock', () => {
    const { fx, heads, nonce } = stampedTrain();
    fragmentPr(fx, '3');
    expect(land(fx, '3').out).toMatch(/^PUSHED: /m);
    const blocked = trainLand(fx, nonce, '1');
    expect(blocked.status).toBe(EXIT.refused);
    expect(blocked.err).toMatch(/#3 holds the land lock .*phase waiting.*\(QUEUE_LAND_LOCKED\)/);
    expect(blocked.out).not.toMatch(/^PUSHED:/m);
    expect(originRev(fx, 'refs/heads/pr-1')).toBe(heads[0]);

    expect(land(fx, '3').out).toContain('LOCK: released');
    const stale = trainLand(fx, nonce, '1');
    expect(stale.err).toMatch(/nothing of train \S+ merged, so the queue is not frozen.*\(QUEUE_TRAIN_TREE_MISMATCH\)/);
    expect(originLock(fx)).toMatchObject({ released: true });
  }, 300_000);

  test('after a push the train keeps its lock through a failed wait and a resume takes it back', () => {
    const { fx, nonce } = stampedTrain(['1']);
    const stamp = /^PUSHED: ([0-9a-f]{40})/m.exec(trainLand(fx, nonce, '1').out)![1]!;
    fx.write(d => { d.ci[stamp] = [{ name: 'free-tests', status: 'completed', conclusion: 'failure' }] as any; });
    const red = trainLand(fx, nonce, '1');
    expect(red.status).not.toBe(EXIT.ok);
    expect(originLock(fx)).toMatchObject({ train: nonce, slot: 1, pr: '1', phase: 'waiting' });
    fx.write(d => { delete d.ci[stamp]; });
    const resumed = trainLand(fx, nonce, '1');
    expect(resumed.status, resumed.err).toBe(EXIT.ok);
    expect(originLock(fx)).toMatchObject({ released: true });
  }, 300_000);

  test('a stop that freezes leaves the lock in a freeze phase that --break-lock never breaks; only the admitted repair train takes it over, and it is released once the freeze clears', () => {
    const { fx, nonce } = stampedTrain();
    trainLand(fx, nonce, '1');
    expect(trainLand(fx, nonce, '1').status).toBe(EXIT.ok);
    trainLand(fx, nonce, '2');
    fx.write(d => { (d as any).outsideOnMerge = true; });
    const drift = trainLand(fx, nonce, '2');
    expect(drift.err).toContain('(QUEUE_TRAIN_TREE_MISMATCH)');
    expect(drift.out).toMatch(/^QUEUE_TRAIN_FROZEN: /m);
    expect(originLock(fx)).toMatchObject({ train: nonce, phase: 'freeze' });
    const lockSha = originRev(fx, LAND_LOCK_REF);

    fragmentPr(fx, '3');
    const refused = land(fx, '3', ['--break-lock', '--break-train-lock']);
    expect(refused.status).toBe(EXIT.refused);
    expect(refused.err).toContain('(QUEUE_TRAIN_FROZEN)');
    expect(originRev(fx, LAND_LOCK_REF)).toBe(lockSha);

    const h4 = fragmentPr(fx, '4');
    const repair = queue(fx, ['train', 'build', '--repair', '--prs', `4@${h4}`]);
    expect(repair.status, repair.err).toBe(EXIT.ok);
    const rn = nonceOf(repair.out);
    expect(queue(fx, ['train', 'verdict', '--train', rn]).status).toBe(EXIT.ok);
    const taken = trainLand(fx, rn, '4');
    expect(taken.out, taken.err).toMatch(new RegExp(`^LOCK: repair train ${rn} takes over the freeze lock of train ${nonce}`, 'm'));
    expect(originLock(fx)).toMatchObject({ train: rn, slot: 1, pr: '4', phase: 'freeze' });
    expect(land(fx, '3', ['--break-lock', '--break-train-lock']).err).toContain('(QUEUE_TRAIN_FROZEN)');
    const cleared = trainLand(fx, rn, '4');
    expect(cleared.status, cleared.err).toBe(EXIT.ok);
    expect(cleared.out).toMatch(/^FREEZE: cleared /m);
    expect(originLock(fx)).toMatchObject({ released: true });
  }, 600_000);
});