Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

54.1 KB
Raw Blame
import { it, expect, vi, beforeEach, afterEach } from 'vitest';
// Git/filesystem are synthetic in this suite; real durable admission has its own boundary tests.
vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublication: (_repo, work) => work() }));
import { basename, join } from 'node:path';
import {
  APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_SNAPSHOT_MAX_BYTES, QUALITY_SNAPSHOT_BRANCH,
  readAppQualitySnapshotFile, readStoredQualitySnapshot, publishAppQualitySnapshot,
  migrateAppQualitySnapshot, __resetQualitySnapshotPublishState,
} from './appQualitySnapshotFile.js';
import {
  APP_QUALITY_LEGACY_SNAPSHOT_FILENAME, qualityFileFromWireSnapshot,
} from './appQualitySnapshotFormat.js';

const app = { id: 'example-id', repoPath: '/repo/example-app' };
const worktreePath = '/tmp/portos-quality-test';
const prUrl = 'https://github.com/example/app/pull/42';
const snapshot = (count = 1) => ({
  schemaVersion: 1,
  repository: 'a'.repeat(64),
  measurements: Array.from({ length: count }, (_, index) => ({
    measurementId: String(index).padStart(64, 'b'),
    assessedAt: '2026-09-10T10:00:00Z',
    report: { version: 1, category: 'security', score: 82, worstSeverity: 5,
      coverage: 'broad', confidence: 'high', scannedFiles: 12, totalFiles: 12 },
  })),
});
const serialized = body => `${JSON.stringify(body, null, 2)}\n`;
const canonical = () => qualityFileFromWireSnapshot(snapshot());
const missingShow = { exitCode: 1, stdout: '', stderr: 'exists' };
const gitDouble = (overrides = {}) => ({
  isRepo: vi.fn(async () => true),
  getRemote: vi.fn(async () => ({ origin: { fetch: '[email protected]:example/app.git' } })),
  fetchOrigin: vi.fn(async () => true),
  getDefaultBranch: vi.fn(async () => 'main'),
  execGit: vi.fn(async (args) => {
    if (args[0] === 'show' || args[0] === 'rev-parse') {
      return missingShow;
    }
    return { exitCode: 0, stdout: '', stderr: '' };
  }),
  stageFiles: vi.fn(async () => true),
  unstageFiles: vi.fn(async () => true),
  commit: vi.fn(async () => ({ hash: 'abc1234', message: 'commit' })),
  createPR: vi.fn(async () => ({ success: true, url: prUrl, cli: 'gh' })),
  mergePR: vi.fn(async () => ({ success: true })),
  parsePullRequestUrl: vi.fn(() => ({ number: 42, host: 'github.com', owner: 'example', repo: 'app' })),
  ...overrides,
});
const testDeps = (overrides = {}) => ({
  git: gitDouble(),
  writeFile: vi.fn(async () => true),
  buildQualitySnapshot: vi.fn(async () => snapshot()),
  mkdtemp: vi.fn(async () => worktreePath),
  rm: vi.fn(async () => {}),
  addWorktree: vi.fn(async () => true),
  queuePendingMerge: vi.fn(async () => true),
  checkSnapshotPublicationOwnership: vi.fn(async () => ({ admitted: true })),
  // Admission itself is pinned in appQualitySnapshotAdmission.test.js.
  getOriginInfo: vi.fn(async () => ({ host: 'github.com', fullName: 'example/app' })),
  withMergeAdmission: vi.fn(async (_origin, work) => ({ admitted: true, result: await work() })),
  probePrForBranch: vi.fn(async () => ({ prState: null, prUrl: null, prNumber: null, readable: true })),
  ...overrides,
});

let log;
beforeEach(() => {
  __resetQualitySnapshotPublishState();
  log = vi.spyOn(console, 'log').mockImplementation(() => {});
});
afterEach(() => log.mockRestore());

// Uniquely pins the opt-in snapshot file contract: numeric-only content and the
// skips that must never touch the app's live checkout or its git index.
it('reads a committed snapshot and answers null for every unusable file', async () => {
  const read = body => readAppQualitySnapshotFile('/repo/example-app', { readFile: async () => body });
  expect(await read(JSON.stringify(snapshot()))).toEqual(snapshot());
  expect(await read('not json')).toBeNull();
  expect(await read('[1,2]')).toBeNull();
  expect(await read('"a string"')).toBeNull();
  expect(await read(' '.repeat(APP_QUALITY_SNAPSHOT_MAX_BYTES + 1))).toBeNull();
  expect(await readAppQualitySnapshotFile('', { readFile: async () => '{}' })).toBeNull();
  expect(await readAppQualitySnapshotFile('/repo/example-app', { readFile: async () => { throw Object.assign(new Error('missing'), { code: 'ENOENT' }); } })).toBeNull();
  expect(APP_QUALITY_SNAPSHOT_FILENAME).toBe('.quality.json');
  expect(QUALITY_SNAPSHOT_BRANCH).toBe('portos/quality-snapshot');
});

it('lands a changed snapshot from a detached worktree so the PR branch stays attachable', async () => {
  const deps = testDeps();
  expect(await publishAppQualitySnapshot(app, deps)).toEqual({
    published: true, hash: 'abc1234', path: '.quality.json',
    prUrl, prNumber: 42, merged: true, queuedMerge: false,
  });
  const [path, body] = deps.writeFile.mock.calls[0];
  expect(path).toBe(join(worktreePath, '.quality.json'));
  expect(body).toBe(canonical());
  expect(JSON.parse(body)).toMatchObject({
    schemaVersion: 2,
    reportVersion: 1,
    categories: ['security'],
    measurements: [['2026-09-10', 0, 82, 5, 0, 2, 12, 12]],
  });
  expect(body.endsWith('\n')).toBe(true);
  expect(body).not.toMatch(/measurementId|Users|summary|app_id|agent-|github/);
  expect(deps.buildQualitySnapshot).toHaveBeenCalledWith(app, 30, deps);
  expect(deps.addWorktree).toHaveBeenCalledWith(
    ['worktree', 'add', '--detach', worktreePath, 'origin/main'],
    '/repo/example-app',
  );
  expect(deps.git.stageFiles).toHaveBeenCalledWith(worktreePath, ['.quality.json']);
  expect(deps.git.commit).toHaveBeenCalledWith(worktreePath,
    'chore: publish PortOS quality snapshot (1 measurements)', { paths: ['.quality.json'] });
  expect(deps.git.execGit).toHaveBeenCalledWith(
    ['push', '--force-with-lease=refs/heads/portos/quality-snapshot:', 'origin', 'HEAD:refs/heads/portos/quality-snapshot'], worktreePath);
  expect(deps.git.createPR).toHaveBeenCalledWith(worktreePath, expect.objectContaining({
    title: 'chore: publish quality snapshot',
    base: 'main',
    head: 'portos/quality-snapshot',
  }));
  expect(deps.git.createPR.mock.calls[0][1].body).toContain('No code review required');
  expect(deps.git.createPR.mock.calls[0][1].body).toContain('structural guards and merge policy still apply');
  expect(deps.git.mergePR).toHaveBeenCalledWith('/repo/example-app', 42, expect.objectContaining({
    forgeAccount: null,
  }));
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(log).toHaveBeenCalledWith(`📊 Published quality snapshot for app example-id: 1 measurements → abc1234 (${prUrl})`);
  expect(deps.git.execGit).toHaveBeenCalledWith(
    ['worktree', 'remove', '--force', worktreePath], '/repo/example-app', { ignoreExitCode: true });

  const unchanged = testDeps();
  expect(await publishAppQualitySnapshot(app, unchanged)).toEqual({
    published: false, reason: 'no-changes', path: '.quality.json',
  });
  expect(unchanged.writeFile).not.toHaveBeenCalled();
  expect(unchanged.addWorktree).not.toHaveBeenCalled();
  expect(unchanged.git.createPR).not.toHaveBeenCalled();
});

it('skips when origin already has the snapshot and does not write the live checkout', async () => {
  const body = canonical();
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).startsWith('origin/main:')
        ? { exitCode: 0, stdout: body, stderr: '' }
        : missingShow),
    }),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toEqual({
    published: false, reason: 'no-changes', path: '.quality.json',
  });
  expect(deps.writeFile).not.toHaveBeenCalled();
  expect(deps.addWorktree).not.toHaveBeenCalled();
  expect(deps.git.stageFiles).not.toHaveBeenCalled();
});

it('merges an already-open snapshot PR whose branch already has the same bytes without waiting for CI', async () => {
  const body = canonical();
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async (args) => args[0] === 'ls-tree' ? { exitCode: 0, stdout: '' } : args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
        ? { exitCode: 0, stdout: body, stderr: '' }
        : missingShow),
    }),
    probePrForBranch: vi.fn(async () => ({
      prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,
    })),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, prUrl, prNumber: 42, merged: true, queuedMerge: false,
  });
  expect(deps.writeFile).not.toHaveBeenCalled();
  expect(deps.addWorktree).not.toHaveBeenCalled();
  expect(deps.git.mergePR).toHaveBeenCalledWith('/repo/example-app', 42, expect.objectContaining({
    forgeAccount: null,
  }));
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
});

it('falls back to the merge-on-green queue when branch protection refuses the immediate merge', async () => {
  const body = canonical();
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async (args) => args[0] === 'ls-tree' ? { exitCode: 0, stdout: '' } : args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
        ? { exitCode: 0, stdout: body, stderr: '' }
        : missingShow),
      mergePR: vi.fn(async () => ({ success: false, error: 'required status checks' })),
    }),
    probePrForBranch: vi.fn(async () => ({
      prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,
    })),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, prUrl, prNumber: 42, merged: false, queuedMerge: true,
  });
  expect(deps.queuePendingMerge).toHaveBeenCalledWith('example-id', expect.objectContaining({ prNumber: 42 }));
});

it('never overwrites an existing snapshot with an empty or unreachable one', async () => {
  const empty = testDeps({ buildQualitySnapshot: async () => snapshot(0) });
  expect(await publishAppQualitySnapshot(app, empty)).toEqual({ published: false, reason: 'no-evidence', path: '.quality.json' });
  expect(empty.writeFile).not.toHaveBeenCalled();

  const missing = testDeps({ buildQualitySnapshot: async () => null });
  expect((await publishAppQualitySnapshot(app, missing)).reason).toBe('no-evidence');

  const notRepo = testDeps({ git: { ...gitDouble(), isRepo: async () => false } });
  expect(await publishAppQualitySnapshot(app, notRepo)).toEqual({ published: false, reason: 'not-a-repo', path: '.quality.json' });
  expect(notRepo.buildQualitySnapshot).not.toHaveBeenCalled();

  const noPath = testDeps();
  expect(await publishAppQualitySnapshot({ id: 'example-id' }, noPath)).toEqual({ published: false, reason: 'no-repo-path', path: '.quality.json' });
  expect(await publishAppQualitySnapshot(null, noPath)).toMatchObject({ reason: 'no-repo-path' });
  expect(noPath.git.isRepo).not.toHaveBeenCalled();
  expect(log).toHaveBeenCalledWith('📊 Quality snapshot skipped for app example-id: not-a-repo');

  const noRemote = testDeps({ git: { ...gitDouble(), getRemote: async () => ({}) } });
  expect(await publishAppQualitySnapshot(app, noRemote)).toEqual({ published: false, reason: 'no-remote', path: '.quality.json' });
  expect(noRemote.git.fetchOrigin).not.toHaveBeenCalled();
});

it('serializes concurrent publishes for one checkout so the second sees the first one\'s bytes', async () => {
  const calls = [];
  let releaseCommit;
  const held = new Promise(resolve => { releaseCommit = resolve; });
  const deps = testDeps({
    git: gitDouble({
      commit: async () => { calls.push('commit-start'); await held; calls.push('commit-end'); return { hash: 'abc1234' }; },
    }),
    addWorktree: async () => { calls.push('worktree'); return true; },
    writeFile: async () => { calls.push('write'); },
  });
  const first = publishAppQualitySnapshot(app, deps);
  const second = publishAppQualitySnapshot(app, deps);
  releaseCommit();
  expect(await first).toMatchObject({ published: true, hash: 'abc1234', prUrl });
  expect(await second).toMatchObject({ published: false, reason: 'no-changes' });
  expect(calls).toEqual(['worktree', 'write', 'commit-start', 'commit-end']);
});

it('unstages the file and rethrows when the commit fails, so no stray path sits in the worktree index', async () => {
  const deps = testDeps({ git: gitDouble({ commit: vi.fn(async () => { throw new Error('index.lock exists'); }) }) });
  await expect(publishAppQualitySnapshot(app, deps)).rejects.toThrow('index.lock exists');
  expect(deps.git.unstageFiles).toHaveBeenCalledWith(worktreePath, ['.quality.json']);
  expect(deps.git.createPR).not.toHaveBeenCalled();

  const next = testDeps();
  expect(await publishAppQualitySnapshot(app, next)).toMatchObject({ published: true, prUrl });
});

it('force-with-lease updates an existing snapshot branch rather than committing on the live checkout', async () => {
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async (args) => {
        if (args[0] === 'show') return missingShow;
        if (args[0] === 'rev-parse' && args.at(-1) === `refs/remotes/origin/${QUALITY_SNAPSHOT_BRANCH}`) {
          return { exitCode: 0, stdout: 'aa'.repeat(20), stderr: '' };
        }
        return { exitCode: 0, stdout: '', stderr: '' };
      }),
    }),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, prUrl });
  expect(deps.git.execGit).toHaveBeenCalledWith([
    'push',
    `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${'aa'.repeat(20)}`,
    'origin',
    `HEAD:refs/heads/${QUALITY_SNAPSHOT_BRANCH}`,
  ], worktreePath);
  expect(deps.writeFile.mock.calls[0][0]).toBe(join(worktreePath, '.quality.json'));
});

it('refreshes refs and rebuilds a detached worktree once after a stale lease', async () => {
  let remoteSha = 'aa'.repeat(20);
  let pushes = 0;
  const git = gitDouble({
    fetchOrigin: vi.fn(async () => { if (pushes) remoteSha = 'bb'.repeat(20); }),
    execGit: vi.fn(async (args) => {
      if (args[0] === 'show') return missingShow;
      if (args[0] === 'rev-parse') return { exitCode: 0, stdout: remoteSha, stderr: '' };
      if (args[0] === 'push' && ++pushes === 1) throw new Error('! [rejected] (stale info)');
      return { exitCode: 0, stdout: '', stderr: '' };
    }),
  });
  const deps = testDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, prUrl });
  expect(git.fetchOrigin).toHaveBeenCalledTimes(2);
  expect(git.fetchOrigin).toHaveBeenLastCalledWith(app.repoPath, { prune: true });
  expect(deps.probePrForBranch).toHaveBeenCalledWith(app.repoPath, QUALITY_SNAPSHOT_BRANCH);
  expect(deps.addWorktree).toHaveBeenCalledTimes(2);
  expect(deps.addWorktree).toHaveBeenLastCalledWith(
    ['worktree', 'add', '--detach', worktreePath, 'origin/main'], app.repoPath,
  );
  expect(git.execGit.mock.calls.filter(([args]) => args[0] === 'push').map(([args]) => args[1])).toEqual([
    `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${'aa'.repeat(20)}`,
    `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${'bb'.repeat(20)}`,
  ]);
  expect(deps.writeFile.mock.calls.every(([path]) => path === join(worktreePath, '.quality.json'))).toBe(true);
  expect(git.createPR).toHaveBeenCalledTimes(1);
});

it.each(['future', 'malformed'])('refuses a %s snapshot found after a stale lease', async kind => {
  let fetches = 0;
  const body = kind === 'future'
    ? JSON.stringify({ schemaVersion: 3, repository: 'a'.repeat(64) })
    : '{invalid json';
  const git = gitDouble({
    fetchOrigin: vi.fn(async () => { fetches++; }),
    execGit: vi.fn(async (args) => {
      if (args[0] === 'show') {
        return fetches > 1 && String(args[1]).includes(`${QUALITY_SNAPSHOT_BRANCH}:`)
          ? { exitCode: 0, stdout: body, stderr: '' }
          : missingShow;
      }
      if (args[0] === 'rev-parse') return { exitCode: 0, stdout: 'aa'.repeat(20), stderr: '' };
      if (args[0] === 'push') throw new Error('! [rejected] (stale info)');
      return { exitCode: 0, stdout: '', stderr: '' };
    }),
  });
  const deps = testDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toEqual({
    published: false, reason: 'unsupported-format', path: '.quality.json',
  });
  expect(git.fetchOrigin).toHaveBeenCalledTimes(2);
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
  expect(git.createPR).not.toHaveBeenCalled();
  expect(deps.writeFile.mock.calls.every(([path]) => path === join(worktreePath, '.quality.json'))).toBe(true);
});

it('leaves a second stale lease rejection visible and retryable', async () => {
  let remoteSha = 'aa'.repeat(20);
  const git = gitDouble({
    fetchOrigin: vi.fn(async () => { remoteSha = remoteSha === 'aa'.repeat(20) ? 'bb'.repeat(20) : 'cc'.repeat(20); }),
    execGit: vi.fn(async (args) => {
      if (args[0] === 'show') return missingShow;
      if (args[0] === 'rev-parse') return { exitCode: 0, stdout: remoteSha, stderr: '' };
      if (args[0] === 'push') throw new Error('! [rejected] (stale info)');
      return { exitCode: 0, stdout: '', stderr: '' };
    }),
  });
  const deps = testDeps({ git });
  await expect(publishAppQualitySnapshot(app, deps)).rejects.toThrow('stale info');
  expect(git.execGit.mock.calls.filter(([args]) => args[0] === 'push')).toHaveLength(2);
  expect(deps.addWorktree).toHaveBeenCalledTimes(2);
  expect(git.createPR).not.toHaveBeenCalled();
  // A failed publish cannot poison the in-process queue or mark these bytes as landed.
  await expect(publishAppQualitySnapshot(app, deps)).rejects.toThrow('stale info');
  expect(deps.addWorktree).toHaveBeenCalledTimes(4);
});

it('does not retry a stale lease when the refreshed PR state cannot be read', async () => {
  const git = gitDouble({
    execGit: vi.fn(async (args) => {
      if (args[0] === 'show') return missingShow;
      if (args[0] === 'rev-parse') return { exitCode: 0, stdout: 'aa'.repeat(20), stderr: '' };
      if (args[0] === 'push') throw new Error('! [rejected] (stale info)');
      return { exitCode: 0, stdout: '', stderr: '' };
    }),
  });
  const deps = testDeps({
    git,
    probePrForBranch: vi.fn().mockResolvedValueOnce({ readable: true, prState: null }).mockResolvedValueOnce({ readable: true, prState: null }).mockResolvedValue({ readable: false }),
  });
  await expect(publishAppQualitySnapshot(app, deps)).rejects.toThrow('publish PR state unavailable');
  expect(deps.probePrForBranch).toHaveBeenCalledWith(app.repoPath, QUALITY_SNAPSHOT_BRANCH);
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
  expect(git.createPR).not.toHaveBeenCalled();
});

it('adopts an already-open PR when createPR reports a conflict and merges it immediately', async () => {
  const deps = testDeps({
    git: gitDouble({
      createPR: vi.fn(async () => ({ success: false, error: 'a pull request already exists' })),
    }),
    probePrForBranch: vi.fn(async () => ({
      prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh', readable: true,
    })),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, prUrl, prNumber: 42, merged: true, queuedMerge: false,
  });
  expect(deps.git.mergePR).toHaveBeenCalled();
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
});

it('merges a GitLab MR immediately instead of arming pipeline auto-merge', async () => {
  const execGlab = vi.fn(async () => '');
  const deps = testDeps({
    git: gitDouble({
      createPR: vi.fn(async () => ({ success: true, url: 'https://gitlab.com/example/app/-/merge_requests/7', cli: 'glab' })),
      parsePullRequestUrl: vi.fn(() => ({ number: 7, host: 'gitlab.com', owner: 'example', repo: 'app' })),
    }),
    execGlab,
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, prNumber: 7, merged: true, queuedMerge: false,
  });
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(execGlab).toHaveBeenCalledWith(
    ['mr', 'merge', '7', '--yes', '--when-pipeline-succeeds=false'],
    '/repo/example-app', undefined, { rejectOnError: true },
  );
});

it('falls back to GitLab auto-merge when the immediate merge is refused', async () => {
  const execGlab = vi.fn()
    .mockRejectedValueOnce(new Error('pipeline must succeed'))
    .mockResolvedValueOnce('');
  const deps = testDeps({
    git: gitDouble({
      createPR: vi.fn(async () => ({ success: true, url: 'https://gitlab.com/example/app/-/merge_requests/7', cli: 'glab' })),
      parsePullRequestUrl: vi.fn(() => ({ number: 7, host: 'gitlab.com', owner: 'example', repo: 'app' })),
    }),
    execGlab,
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, prNumber: 7, merged: false, queuedMerge: true,
  });
  expect(execGlab).toHaveBeenCalledWith(
    ['mr', 'merge', '7', '--yes', '--when-pipeline-succeeds=false'],
    '/repo/example-app', undefined, { rejectOnError: true },
  );
  expect(execGlab).toHaveBeenCalledWith(
    ['mr', 'merge', '7', '--yes', '--auto-merge'],
    '/repo/example-app', undefined, { rejectOnError: true },
  );
});

const showFiles = files => vi.fn(async (args) => {
  if (args[0] !== 'show') return missingShow;
  const spec = String(args[1]);
  const name = spec.slice(spec.lastIndexOf(':') + 1);
  return Object.hasOwn(files, name)
    ? { exitCode: 0, stdout: files[name], stderr: '' }
    : missingShow;
});

it('rewrites a v1 snapshot to canonical v2 and leaves a semantically identical v2 untouched', async () => {
  const upgrade = testDeps({ git: gitDouble({ execGit: showFiles({ '.quality.json': serialized(snapshot()) }) }) });
  expect(await publishAppQualitySnapshot(app, upgrade)).toMatchObject({ published: true, prUrl });
  expect(upgrade.writeFile.mock.calls[0][1]).toBe(canonical());
  expect(upgrade.writeFile.mock.calls[0][0]).toBe(join(worktreePath, '.quality.json'));

  __resetQualitySnapshotPublishState();
  const compact = JSON.stringify(JSON.parse(canonical()));
  const identical = testDeps({ git: gitDouble({ execGit: showFiles({ '.quality.json': compact }) }) });
  expect(await publishAppQualitySnapshot(app, identical)).toEqual({
    published: false, reason: 'no-changes', path: '.quality.json',
  });
  expect(identical.writeFile).not.toHaveBeenCalled();
  expect(identical.addWorktree).not.toHaveBeenCalled();
});

it('does not replace a future snapshot already on the publish branch', async () => {
  const future = JSON.stringify({ schemaVersion: 3, repository: 'a'.repeat(64) });
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async (args) => {
        if (args[0] === 'show' && String(args[1]).includes(`${QUALITY_SNAPSHOT_BRANCH}:`)) {
          return { exitCode: 0, stdout: future, stderr: '' };
        }
        return missingShow;
      }),
    }),
  });
  expect(await publishAppQualitySnapshot(app, deps)).toEqual({
    published: false, reason: 'unsupported-format', path: '.quality.json',
  });
  expect(deps.writeFile).not.toHaveBeenCalled();
  expect(deps.addWorktree).not.toHaveBeenCalled();
});

it('leaves a future, unrecognized, or unreadable snapshot in place', async () => {
  const future = testDeps({
    git: gitDouble({ execGit: showFiles({ '.quality.json': JSON.stringify({ schemaVersion: 3, repository: 'a'.repeat(64) }) }) }),
  });
  expect(await publishAppQualitySnapshot(app, future)).toEqual({
    published: false, reason: 'unsupported-format', path: '.quality.json',
  });
  expect(future.writeFile).not.toHaveBeenCalled();

  const tsv = testDeps({
    git: gitDouble({ execGit: showFiles({ '.quality.json': 'category\tscore\nsecurity\t80\n' }) }),
  });
  expect((await publishAppQualitySnapshot(app, tsv)).reason).toBe('unsupported-format');
  expect(tsv.writeFile).not.toHaveBeenCalled();

  const unreadable = testDeps({
    git: gitDouble({ execGit: vi.fn(async (args) => {
      if (args[0] === 'show') throw new Error('git output exceeded maxBuffer');
      return { exitCode: 0, stdout: '', stderr: '' };
    }) }),
  });
  expect((await publishAppQualitySnapshot(app, unreadable)).reason).toBe('unsupported-format');
  expect(unreadable.writeFile).not.toHaveBeenCalled();
  expect(log).toHaveBeenCalledWith('📊 Quality snapshot left untouched for app example-id: future');

  // Readable, but rewriting it canonically would drop the newer install's rows.
  const newer = testDeps({
    git: gitDouble({ execGit: showFiles({ '.quality.json': JSON.stringify({
      schemaVersion: 2, repository: 'a'.repeat(64), reportVersion: 1,
      categories: ['security', 'example-future-lens'],
      coverage: ['broad', 'partial', 'unavailable', 'not-applicable'], confidence: ['low', 'medium', 'high'],
      measurements: [['2026-09-20T00:00:00.000Z', 1, 50, 3, 0, 2, 10, 10]],
    }) }) }),
  });
  expect((await publishAppQualitySnapshot(app, newer)).reason).toBe('unsupported-format');
  expect(newer.writeFile).not.toHaveBeenCalled();
});

it('migrates a legacy file to v2 without inventing measurements or writing the live checkout', async () => {
  const legacyBody = serialized(snapshot());
  const deps = testDeps({
    git: gitDouble({ execGit: showFiles({ [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: legacyBody }) }),
    buildQualitySnapshot: vi.fn(async () => snapshot(3)),
  });
  expect(await migrateAppQualitySnapshot(app, deps)).toMatchObject({ published: true, prUrl, hash: 'abc1234' });
  expect(deps.buildQualitySnapshot).not.toHaveBeenCalled();
  const [path, body] = deps.writeFile.mock.calls[0];
  expect(path).toBe(join(worktreePath, '.quality.json'));
  expect(path.startsWith(app.repoPath)).toBe(false);
  expect(JSON.parse(body).measurements).toEqual([['2026-09-10', 0, 82, 5, 0, 2, 12, 12]]);
  expect(deps.git.execGit).toHaveBeenCalledWith(
    ['rm', '-f', '--', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME], worktreePath);
  expect(deps.git.commit).toHaveBeenCalledWith(worktreePath,
    'chore: migrate quality snapshot to schema v2 (1 measurements)',
    { paths: ['.quality.json', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME] });

  __resetQualitySnapshotPublishState();
  const again = testDeps({
    git: gitDouble({ execGit: showFiles({ '.quality.json': body }) }),
    buildQualitySnapshot: vi.fn(async () => { throw new Error('database must stay unread'); }),
  });
  expect(await migrateAppQualitySnapshot(app, again)).toEqual({
    published: false, reason: 'no-changes', path: '.quality.json',
  });
  expect(again.writeFile).not.toHaveBeenCalled();
  expect(again.addWorktree).not.toHaveBeenCalled();
});

it('reads v1, v2, and the legacy filename without falling past a canonical file', async () => {
  const v1 = serialized(snapshot());
  const v2 = canonical();
  const read = files => readStoredQualitySnapshot('/repo/example-app', {
    readFile: async path => {
      const name = basename(path);
      if (!Object.hasOwn(files, name)) throw Object.assign(new Error('missing'), { code: 'ENOENT' });
      return files[name];
    },
  });
  expect(APP_QUALITY_LEGACY_SNAPSHOT_FILENAME).toBe('quality-snapshot.json');
  expect((await read({ '.quality.json': v1 })).status).toBe('v1');
  expect((await read({ '.quality.json': v2 })).status).toBe('v2');
  expect((await read({ [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 })).filename).toBe(APP_QUALITY_LEGACY_SNAPSHOT_FILENAME);
  const both = await read({ '.quality.json': v2, [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 });
  expect(both.filename).toBe('.quality.json');
  expect(both.status).toBe('v2');
  expect((await read({ '.quality.json': 'not-json', [APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]: v1 })).status).toBe('unrecognized');
  expect((await read({ '.quality.json': ' '.repeat(APP_QUALITY_SNAPSHOT_MAX_BYTES + 1) })).status).toBe('oversize');
  const unreadable = await readStoredQualitySnapshot('/repo/example-app', {
    readFile: async path => {
      if (basename(path) === '.quality.json') throw Object.assign(new Error('denied'), { code: 'EACCES' });
      return v1;
    },
  });
  expect(unreadable.status).toBe('unreadable');
  expect(unreadable.filename).toBe('.quality.json');
});

it('serializes worktree cleanup, retries a failed Git removal, and reports stale metadata without failing publication', async () => {
  const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
  const order = [];
  let removals = 0;
  const run = async ({ retrySucceeds, listingFails = false }) => {
    removals = 0;
    order.length = 0;
    __resetQualitySnapshotPublishState();
    const base = gitDouble().execGit;
    const deps = testDeps({
      rm: vi.fn(async () => { order.push('rm'); }),
      git: gitDouble({ execGit: vi.fn(async (args, cwd, opts) => {
        if (args[0] === 'worktree' && args[1] === 'remove') {
          order.push('remove');
          removals += 1;
          if (removals === 1) return { exitCode: 128, stdout: '', stderr: `fatal: '${worktreePath}' is locked` };
          if (!retrySucceeds) throw new Error(`cannot remove ${worktreePath}`);
          return { exitCode: 0, stdout: '', stderr: '' };
        }
        if (args[0] === 'worktree' && args[1] === 'list') {
          if (listingFails) return { exitCode: 128, stdout: '', stderr: 'Git listing failed' };
          const stale = retrySucceeds ? '' : `worktree /private${worktreePath}\ndetached\n\n`;
          return { exitCode: 0, stdout: `worktree /repo/example-app\nbranch refs/heads/main\n\n${stale}worktree /repo/other\n`, stderr: '' };
        }
        return base(args, cwd, opts);
      }) }),
    });
    return publishAppQualitySnapshot(app, deps);
  };

  const ok = await run({ retrySucceeds: true });
  expect(ok.published).toBe(true);
  expect(order).toEqual(['remove', 'rm', 'remove']);
  expect(warn).not.toHaveBeenCalled();

  const stale = await run({ retrySucceeds: false });
  expect(stale.published).toBe(true);
  expect(warn).toHaveBeenCalledTimes(1);
  const message = warn.mock.calls[0][0];
  expect(message).toContain('registration remains');
  expect(message).toContain('<snapshot-worktree>');
  expect(message).not.toContain(worktreePath);
  warn.mockClear();
  expect((await run({ retrySucceeds: false, listingFails: true })).published).toBe(true);
  expect(warn).toHaveBeenCalledWith(expect.stringContaining('registration verification unavailable'));
  warn.mockRestore();
});

// Unique regression: a rebuild from only the evidence reachable right now (peers
// offline) used to overwrite the published file and delete every other row.
it('keeps rows already on the default branch when fresh evidence covers less', async () => {
  const existing = snapshot();
  existing.measurements[0].report.category = 'privacy';
  existing.measurements[0].assessedAt = '2026-09-20T10:00:00Z';
  const body = qualityFileFromWireSnapshot(existing);
  const git = gitDouble({
    execGit: vi.fn(async (args) => (args[0] === 'show' && String(args[1]).startsWith('origin/main:')
      ? { exitCode: 0, stdout: body, stderr: '' }
      : args[0] === 'show' || args[0] === 'rev-parse' ? missingShow : { exitCode: 0, stdout: '', stderr: '' })),
  });
  const writeFile = vi.fn(async () => true);
  const result = await publishAppQualitySnapshot(app, testDeps({ git, writeFile, now: Date.parse('2026-10-02T00:00:00Z') }));
  expect(result.published).toBe(true);
  const written = JSON.parse(writeFile.mock.calls[0][1]);
  expect(written.categories).toEqual(['privacy', 'security']);
  expect(written.measurements).toHaveLength(2);
});

it.each(['open-branch', 'lease-branch', 'lease-default'])('preserves another install’s rows during %s publication', async location => {
  const peer = snapshot();
  peer.measurements[0].report.category = 'privacy';
  const peerBody = qualityFileFromWireSnapshot(peer);
  let pushes = 0;
  let fetches = 0;
  const git = gitDouble({
    fetchOrigin: vi.fn(async () => { fetches++; }),
    execGit: vi.fn(async args => {
      if (args[0] === 'show') {
        const branch = String(args[1]).includes(`${QUALITY_SNAPSHOT_BRANCH}:`);
        const hasPeer = location === 'open-branch' ? branch
          : fetches > 1 && (location === 'lease-branch' ? branch : !branch);
        return hasPeer ? { exitCode: 0, stdout: peerBody, stderr: '' } : missingShow;
      }
      if (args[0] === 'rev-parse') return { exitCode: 0, stdout: (fetches > 1 ? 'bb' : 'aa').repeat(20), stderr: '' };
      if (args[0] === 'push' && ++pushes === 1 && location !== 'open-branch') throw new Error('! [rejected] (stale info)');
      return { exitCode: 0, stdout: '', stderr: '' };
    }),
  });
  const deps = testDeps({ git, now: Date.parse('2026-09-20T00:00:00Z') });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
  const written = JSON.parse(deps.writeFile.mock.calls.at(-1)[1]);
  expect(written.categories).toEqual(['privacy', 'security']);
  expect(written.measurements).toHaveLength(2);
});

it('keeps the publication window and fresh same-day evidence when coalescing an open branch', async () => {
  const peer = snapshot(3);
  peer.measurements[0].report.score = 99;
  peer.measurements[1].report.category = 'privacy';
  peer.measurements[2].report.category = 'documentation';
  peer.measurements[2].assessedAt = '2026-08-01T10:00:00Z';
  const git = gitDouble({ execGit: vi.fn(async args => {
    if (args[0] === 'show' && String(args[1]).includes(`${QUALITY_SNAPSHOT_BRANCH}:`)) {
      return { exitCode: 0, stdout: qualityFileFromWireSnapshot(peer), stderr: '' };
    }
    return args[0] === 'show' || args[0] === 'rev-parse' ? missingShow : { exitCode: 0, stdout: '', stderr: '' };
  }) });
  const deps = testDeps({ git, now: Date.parse('2026-09-20T00:00:00Z') });
  await publishAppQualitySnapshot(app, deps);
  const written = JSON.parse(deps.writeFile.mock.calls[0][1]);
  expect(written.categories).toEqual(['privacy', 'security']);
  expect(written.measurements.find(row => row[1] === 1)[2]).toBe(82);
});

it('preserves open-branch history during explicit format migration without applying the publication window', async () => {
  const peer = snapshot();
  peer.measurements[0].report.category = 'privacy';
  peer.measurements[0].assessedAt = '2025-01-01T10:00:00Z';
  const git = gitDouble({ execGit: vi.fn(async args => {
    if (args[0] === 'show') return { exitCode: 0, stderr: '', stdout: String(args[1]).includes(`${QUALITY_SNAPSHOT_BRANCH}:`)
      ? qualityFileFromWireSnapshot(peer) : serialized(snapshot()) };
    return args[0] === 'rev-parse' ? missingShow : { exitCode: 0, stdout: '', stderr: '' };
  }) });
  const deps = testDeps({ git });
  await migrateAppQualitySnapshot(app, deps);
  const written = JSON.parse(deps.writeFile.mock.calls[0][1]);
  expect(written.categories).toEqual(['privacy', 'security']);
  expect(written.measurements).toHaveLength(2);
});

// #11324: exported publication workflow with the real read-only ownership
// boundary. Only persisted state, worktrees and forge/git I/O are synthetic.
const ownedPublicationDeps = ({ agents = {}, trusted = true, worktrees = [], ...overrides } = {}) => {
  const ownership = { agents, trusted, worktrees };
  const deps = testDeps({
    checkSnapshotPublicationOwnership: async input => {
      const { checkSnapshotPublicationOwnership } = await import('./cosClaimOwnership.js');
      const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');
      return checkSnapshotPublicationOwnership(input, {
        readAgentsStateForSafetyCheck: async () => ({ trusted: ownership.trusted, agents: ownership.agents }),
        readCompletionHold: policy => readBranchCompletionHold({ ...policy, tip: 'a'.repeat(40) }, {
          readPolicies: async () => Object.values(ownership.agents),
        }),
        getAppById: async () => app,
        listWorktrees: async () => ownership.worktrees,
        getActiveAgentIds: () => [],
      });
    },
    probePrForBranch: vi.fn(async () => ({ readable: true, prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh' })),
    ...overrides,
  });
  return { deps, ownership };
};
const reviewOwner = status => ({
  id: 'reviewer', status,
  metadata: { reviewLoopMergeTarget: { url: prUrl, branch: QUALITY_SNAPSHOT_BRANCH } },
});
const branchGit = (changes = '.quality.json\0') => gitDouble({
  execGit: vi.fn(async args => {
    if (args[0] === 'show') return missingShow;
    if (args[0] === 'rev-parse') return { exitCode: 0, stdout: 'aa'.repeat(20) };
    if (args[0] === 'diff') return { exitCode: 0, stdout: changes };
    return { exitCode: 0, stdout: '' };
  }),
});
const expectNoPublication = deps => {
  expect(deps.git.execGit.mock.calls.filter(([args]) => args[0] === 'push')).toEqual([]);
  expect(deps.git.createPR).not.toHaveBeenCalled();
  expect(deps.git.mergePR).not.toHaveBeenCalled();
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
};

it('retains deferred measurements through active and paused review, then publishes when the review completes', async () => {
  const { deps, ownership } = ownedPublicationDeps({ agents: { reviewer: reviewOwner('running') }, git: branchGit() });
  const original = structuredClone(ownership.agents);
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: false, deferredPublication: true, reason: 'review-owner-active',
  });
  expect(ownership.agents).toEqual(original);
  ownership.agents.reviewer.status = 'paused';
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'review-owner-active' });
  expectNoPublication(deps);
  expect(deps.addWorktree).not.toHaveBeenCalled();

  ownership.agents.reviewer.status = 'completed';
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, merged: true });
  expect(deps.buildQualitySnapshot).toHaveBeenCalledTimes(3);
  expect(deps.writeFile).toHaveBeenCalledWith(join(worktreePath, '.quality.json'), canonical());
});

it('rechecks ownership before pushing and retries an unchanged body after a late owner releases it', async () => {
  const { deps, ownership } = ownedPublicationDeps({ git: branchGit() });
  deps.git.commit.mockImplementationOnce(async () => {
    ownership.agents.reviewer = reviewOwner('running');
    return { hash: 'abc1234' };
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'review-owner-active', deferredPublication: true });
  expectNoPublication(deps);
  expect(deps.rm).toHaveBeenCalledWith(worktreePath, { recursive: true, force: true });
  ownership.agents = {};
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
  expect(deps.git.commit).toHaveBeenCalledTimes(2);
});

it('keeps completed review delivery from overriding its registered completion policy', async () => {
  const reviewer = reviewOwner('completed');
  reviewer.metadata = { ...reviewer.metadata, sourceWorkspace: app.repoPath,
    worktreeBranch: QUALITY_SNAPSHOT_BRANCH, prCompletionPolicy: 'review-then-merge' };
  const { deps } = ownedPublicationDeps({ agents: { reviewer }, git: branchGit() });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: false, deferredPublication: true, reason: 'pr-completion-review-required',
  });
  expectNoPublication(deps);
});

it('applies a saved handoff only to the exact current PR when the snapshot branch is reused', async () => {
  const agent = { id: 'prior', status: 'completed', metadata: {
    sourceWorkspace: app.repoPath, branchCompletionPolicy: {
      branch: QUALITY_SNAPSHOT_BRANCH, prUrl, completion: 'leave-open', tip: null,
    },
  } };
  const { deps } = ownedPublicationDeps({ agents: { prior: agent }, git: branchGit() });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: false, deferredPublication: true, reason: 'pr-completion-human-handoff',
  });
  expectNoPublication(deps);
  deps.probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN', prUrl: 'https://github.com/example/app/pull/43', prNumber: 43, cli: 'gh' });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, merged: true });
});

it('preserves a live review checkout even when no PR owner target was registered', async () => {
  const holder = { path: '/tmp/agent-reviewer', branch: `refs/heads/${QUALITY_SNAPSHOT_BRANCH}` };
  const { deps, ownership } = ownedPublicationDeps({
    worktrees: [holder], agents: { reviewer: { id: 'reviewer', status: 'running', metadata: { workspacePath: holder.path } } },
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: false, deferredPublication: true });
  expectNoPublication(deps);
  expect(ownership.worktrees).toEqual([holder]);
  expect(deps.rm).not.toHaveBeenCalled();
});

it.each([
  { trusted: false, agents: {} },
  { trusted: true, agents: null },
  { trusted: true, agents: { broken: 'unreadable' } },
])('fails closed on unreadable ownership %#', async input => {
  const { deps } = ownedPublicationDeps(input);
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'ownership-unreadable', deferredPublication: true });
  expectNoPublication(deps);
});

it('defers an unreadable forge or rejected ownership lookup without marking the body delivered', async () => {
  const deps = testDeps({ probePrForBranch: vi.fn().mockRejectedValueOnce(new Error('forge offline')).mockResolvedValue({ readable: true, prState: null }) });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'publish-pr-unreadable' });
  deps.checkSnapshotPublicationOwnership.mockRejectedValueOnce(new Error('state read failed'));
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'ownership-unreadable' });
  expectNoPublication(deps);
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
});

it('preserves foreign review code without a local owner, including when snapshot bytes already match', async () => {
  const git = branchGit('.quality.json\0server/reviewFix.js\0');
  const originalExec = git.execGit.getMockImplementation();
  git.execGit.mockImplementation(args => args[0] === 'show' && args[1].includes(QUALITY_SNAPSHOT_BRANCH)
    ? Promise.resolve({ exitCode: 0, stdout: canonical() }) : originalExec(args));
  const { deps } = ownedPublicationDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'non-snapshot-changes', deferredPublication: true });
  expectNoPublication(deps);
  expect(deps.addWorktree).not.toHaveBeenCalled();
});

it('does not discard foreign review code discovered during a stale-lease retry', async () => {
  let pushes = 0;
  const git = branchGit();
  const originalExec = git.execGit.getMockImplementation();
  git.execGit.mockImplementation(async args => {
    if (args[0] === 'push') { pushes++; throw new Error('! [rejected] (stale info)'); }
    if (args[0] === 'diff' && pushes) return { exitCode: 0, stdout: '.quality.json\0server/reviewFix.js\0' };
    return originalExec(args);
  });
  const { deps } = ownedPublicationDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'non-snapshot-changes', deferredPublication: true });
  expect(pushes).toBe(1);
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
  expect(git.createPR).not.toHaveBeenCalled();
});

it('defers unreadable branch contents rather than treating a failed inspection as an empty diff', async () => {
  const git = branchGit();
  const originalExec = git.execGit.getMockImplementation();
  git.execGit.mockImplementation(args => args[0] === 'diff'
    ? Promise.resolve({ exitCode: 128, stdout: '' }) : originalExec(args));
  const deps = testDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'publish-branch-unreadable', deferredPublication: true });
  expectNoPublication(deps);
});

it('re-inspects a ref moved by another fetch during preparation instead of leasing its unchecked head', async () => {
  let moved = false;
  const git = branchGit();
  const originalExec = git.execGit.getMockImplementation();
  git.commit.mockImplementation(async () => { moved = true; return { hash: 'abc1234' }; });
  git.execGit.mockImplementation(args => args[0] === 'rev-parse' && moved
    ? Promise.resolve({ exitCode: 0, stdout: 'bb'.repeat(20) }) : originalExec(args));
  const deps = testDeps({ git });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
  expect(deps.addWorktree).toHaveBeenCalledTimes(2);
  const pushes = git.execGit.mock.calls.filter(([args]) => args[0] === 'push');
  expect(pushes).toEqual([[[
    'push', `--force-with-lease=refs/heads/${QUALITY_SNAPSHOT_BRANCH}:${'bb'.repeat(20)}`,
    'origin', `HEAD:refs/heads/${QUALITY_SNAPSHOT_BRANCH}`,
  ], worktreePath]]);
});

it('applies the same ownership protection to explicit snapshot migrations', async () => {
  const git = branchGit();
  const originalExec = git.execGit.getMockImplementation();
  git.execGit.mockImplementation(args => args[0] === 'show' && args[1] === 'origin/main:.quality.json'
    ? Promise.resolve({ exitCode: 0, stdout: serialized(snapshot()) }) : originalExec(args));
  const { deps, ownership } = ownedPublicationDeps({ git, agents: { reviewer: reviewOwner('running') } });
  expect(await migrateAppQualitySnapshot(app, deps)).toMatchObject({ reason: 'review-owner-active', deferredPublication: true });
  expectNoPublication(deps);
  ownership.agents = {};
  expect(await migrateAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
});

const guardedPublication = (reused = false) => {
  const head = 'a'.repeat(40);
  const base = 'b'.repeat(40);
  const live = { head, base, state: 'OPEN', manifest: { scripts: { 'pregate:merged': 'node scripts/pregate.js --guards-only' } } };
  const events = [];
  const trees = [];
  const evidence = new Map();
  const deps = testDeps({
    git: gitDouble({
      execGit: vi.fn(async args => {
        if (args[0] === 'ls-tree') return { exitCode: 0, stdout: 'package.json\n' };
        if (args[0] === 'show') {
          if (args[1].endsWith(':package.json')) return { exitCode: 0, stdout: JSON.stringify(live.manifest) };
          return reused && args[1] === `origin/${QUALITY_SNAPSHOT_BRANCH}:.quality.json`
            ? { exitCode: 0, stdout: canonical() } : missingShow;
        }
        if (args[0] === 'rev-parse') {
          if (args[3] === `refs/remotes/origin/${QUALITY_SNAPSHOT_BRANCH}`) {
            return reused ? { exitCode: 0, stdout: head } : missingShow;
          }
          return { exitCode: 0, stdout: args[2] === 'origin/main^{commit}' ? base : head };
        }
        if (args[0] === 'diff') return { exitCode: 0, stdout: '.quality.json\0' };
        if (args[0] === 'ls-remote') return { exitCode: 0, stdout: `${live.base}\trefs/heads/main\n` };
        return { exitCode: 0, stdout: '' };
      }),
      commit: vi.fn(async () => ({ hash: head })),
      mergePR: vi.fn(async () => { events.push('merge'); return { success: true }; }),
    }),
    probePrForBranch: vi.fn(async () => reused
      ? { readable: true, prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh' }
      : { readable: true, prState: null }),
    resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh', env: { EXAMPLE_FORGE_ACCOUNT: 'selected' } })),
    execGh: vi.fn(async () => JSON.stringify({
      state: live.state, isDraft: false, isCrossRepository: false, headRefOid: live.head,
      headRefName: QUALITY_SNAPSHOT_BRANCH, baseRefName: 'main',
    })),
    addWorktree: vi.fn(async () => { trees.push({ path: worktreePath, head, detached: true }); }),
    linkWorktreeDependencies: vi.fn(async () => {}),
    writeMergeEvidence: vi.fn(async (path, record) => { evidence.set(path, structuredClone(record)); }),
    readMergeEvidence: vi.fn(async path => {
      if (!evidence.has(path)) throw Object.assign(new Error('absent'), { code: 'ENOENT' });
      return JSON.stringify(evidence.get(path));
    }),
    listSnapshotMergeWorktrees: vi.fn(async () => [...trees]),
    retireSnapshotMergeCheckouts: vi.fn(async () => { trees.length = 0; evidence.clear(); return []; }),
    execSnapshotMergeGuards: vi.fn(async () => { events.push('guards'); return { stdout: 'guards passed', stderr: '' }; }),
    withMergeAdmission: vi.fn(async (_origin, work) => {
      events.push('admission');
      return { admitted: true, result: await work() };
    }),
  });
  return { deps, live, events, head, base, evidence, trees };
};

// These publisher-boundary regressions uniquely cover exact input validation
// and recovery across both temporary-checkout owners (new and reused PRs).
it.each([false, true])('validates the snapshot before admission and pins the head (reused: %s)', async reused => {
  const { deps, events, head, base } = guardedPublication(reused);
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, merged: true, queuedMerge: false });
  expect(events).toEqual(['guards', 'admission', 'merge']);
  expect(deps.execSnapshotMergeGuards).toHaveBeenCalledWith(process.execPath,
    [join(worktreePath, 'scripts', 'pregate.js'), '--guards-only', '--merged-with', base],
    expect.objectContaining({ cwd: worktreePath, env: expect.objectContaining({ PORTOS_TEST_MEMO: 'off' }) }));
  expect(deps.git.mergePR).toHaveBeenCalledWith(app.repoPath, 42, { forgeAccount: null, expectedHeadSha: head });
  expect(deps.resolveForgeForRepo).toHaveBeenCalledWith(app.repoPath, { forgeAccount: null });
  expect(deps.execGh).toHaveBeenCalledWith(expect.any(Array), undefined,
    { cwd: app.repoPath, env: { EXAMPLE_FORGE_ACCOUNT: 'selected' } });
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(deps.retireSnapshotMergeCheckouts).toHaveBeenCalledTimes(1);
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
  expect(deps.addWorktree.mock.calls[0][0]).toEqual(
    ['worktree', 'add', '--detach', worktreePath, reused ? head : 'origin/main']);
  expect(deps.writeMergeEvidence).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({
    headSha: head, baseSha: base, status: 'passed', stdout: 'guards passed',
  }));
});

it.each([false, true])('retains failed guard evidence without admission or a queue bypass (reused: %s)', async reused => {
  const { deps, head, base } = guardedPublication(reused);
  deps.execSnapshotMergeGuards.mockRejectedValue(Object.assign(new Error('guards failed'), { stdout: 'hostControlRoutes.test.js failed' }));
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, merged: false, queuedMerge: false, deferredMerge: true,
    mergeGuard: { headSha: head, baseSha: base, worktreePath, reason: 'snapshot-merge-guards-failed' },
  });
  expect(deps.withMergeAdmission).not.toHaveBeenCalled();
  expect(deps.git.mergePR).not.toHaveBeenCalled();
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(deps.rm).not.toHaveBeenCalled();
  expect(deps.git.execGit.mock.calls.some(([args]) => args[0] === 'worktree' && args[1] === 'remove')).toBe(false);
  expect(deps.writeMergeEvidence).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({
    status: 'deferred', stdout: 'hostControlRoutes.test.js failed',
  }));
});

it.each(['head', 'base', 'unreadable'])('refuses a %s race inside admission and retains the validated checkout', async race => {
  const { deps, live } = guardedPublication(true);
  deps.execSnapshotMergeGuards.mockImplementation(async () => {
    if (race === 'unreadable') deps.execGh.mockResolvedValueOnce('not-json');
    else live[race] = 'c'.repeat(40);
    return { stdout: 'guards passed', stderr: '' };
  });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true, mergeGuard: { worktreePath } });
  expect(deps.withMergeAdmission).toHaveBeenCalledTimes(1);
  expect(deps.git.mergePR).not.toHaveBeenCalled();
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(deps.rm).not.toHaveBeenCalled();
});

it('refuses a PR that moved away from the new publication before validation', async () => {
  const { deps, live } = guardedPublication();
  live.head = 'c'.repeat(40);
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    published: true, merged: false, deferredMerge: true, mergeGuard: { reason: 'snapshot-merge-head-changed' },
  });
  expect(deps.execSnapshotMergeGuards).not.toHaveBeenCalled();
  expect(deps.withMergeAdmission).not.toHaveBeenCalled();
  expect(deps.rm).not.toHaveBeenCalled();
});

it.each(['admission', 'merge'])('keeps guarded %s refusals retryable without queuing an unvalidated later merge', async refused => {
  const { deps } = guardedPublication(true);
  if (refused === 'admission') deps.withMergeAdmission.mockResolvedValue({ admitted: false, reason: 'active-owner' });
  else deps.git.mergePR.mockResolvedValue({ success: false, error: 'required checks pending' });
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true, queuedMerge: false });
  expect(deps.queuePendingMerge).not.toHaveBeenCalled();
  expect(deps.rm).not.toHaveBeenCalled();
  deps.withMergeAdmission.mockImplementation(async (_origin, work) => ({ admitted: true, result: await work() }));
  deps.git.mergePR.mockResolvedValue({ success: true });
  __resetQualitySnapshotPublishState();
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: true });
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
});

it('preserves a retained checkout that acquired a lock before retry', async () => {
  const { deps, trees } = guardedPublication(true);
  deps.execSnapshotMergeGuards.mockRejectedValue(new Error('guard refused'));
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ deferredMerge: true });
  trees[0].locked = true;
  __resetQualitySnapshotPublishState();
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    merged: false, deferredMerge: true, mergeGuard: { reason: 'retained-snapshot-checkout-changed' },
  });
  expect(deps.addWorktree).toHaveBeenCalledTimes(1);
  expect(deps.retireSnapshotMergeCheckouts).not.toHaveBeenCalled();
  expect(deps.git.mergePR).not.toHaveBeenCalled();
});

it('leaves a guard-capable GitLab MR open instead of falling through to an unpinned merge', async () => {
  const { deps } = guardedPublication(true);
  deps.probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN', prUrl, prNumber: 42, cli: 'glab' });
  deps.execGlab = vi.fn();
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    merged: false, deferredMerge: true, queuedMerge: false, mergeGuard: { reason: 'unsupported-merge-guard-forge' },
  });
  expect(deps.execGlab).not.toHaveBeenCalled();
  expect(deps.withMergeAdmission).not.toHaveBeenCalled();
});

it('keeps generic manifest behavior but refuses an unreadable or unsupported guard contract', async () => {
  const { deps, live } = guardedPublication(true);
  live.manifest = { scripts: { pregate: 'a generic app command' } };
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: true });
  expect(deps.execSnapshotMergeGuards).not.toHaveBeenCalled();
  __resetQualitySnapshotPublishState();
  live.manifest = { scripts: { 'pregate:merged': 'another command' } };
  deps.git.mergePR.mockClear();
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true });
  expect(deps.git.mergePR).not.toHaveBeenCalled();
  live.manifest = null;
  expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
    merged: false, deferredMerge: true, mergeGuard: { reason: 'merge-guard-manifest-unreadable' },
  });
});