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

56.0 KB
Raw Blame
import { describe, it, expect, vi, beforeEach } from 'vitest';

// Real admission logic over a serialized synthetic runtime store.
const admissionState = vi.hoisted(() => ({ state: { agents: {}, mergeAdmissions: {} } }));
vi.mock('./cosState.js', async () => {
  const { createFileWriteQueue } = await import('../lib/fileWriteQueue.js');
  return {
    withStateLock: createFileWriteQueue(),
    loadState: async () => admissionState.state,
    saveState: async state => { admissionState.state = state; },
    readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(admissionState.state) }),
  };
});

// ─── mocks (must precede the import under test) ──────────────────────────────

const execGhMock = vi.fn();
const ensureForgeReachableMock = vi.fn(async () => ({ ok: true, status: 'ok', detail: null, remedy: null }));
vi.mock('./github.js', () => ({
  execGh: (...args) => execGhMock(...args),
  ensureForgeReachable: (...args) => ensureForgeReachableMock(...args),
}));

// The per-repo gh credential overlay (#7540). Mocked rather than real so the
// suite asserts what execGh RECEIVED without spawning git/gh probes.
const PINNED_ENV = { GH_TOKEN: 'token-for-other-account' };
const resolveForgeExecOptionsMock = vi.fn(async (repoPath) => ({
  cwd: repoPath || undefined,
  env: PINNED_ENV,
  customEnv: PINNED_ENV,
}));
vi.mock('./forgeExecOptions.js', () => ({
  resolveForgeExecOptions: (...args) => resolveForgeExecOptionsMock(...args),
}));

const screenMock = vi.fn();
const fingerprintMock = vi.fn();
vi.mock('./untrustedContent.js', () => ({
  screenUntrustedContent: (...args) => screenMock(...args),
  getContributionAssessmentFingerprint: (...args) => fingerprintMock(...args),
}));
const prepareGuardMock = vi.fn();
const guardCurrentMock = vi.fn();
vi.mock('./pendingMergeGuard.js', async importOriginal => ({
  summarizeMergeGuardOutput: (await importOriginal()).summarizeMergeGuardOutput,
  preparePendingMergeGuard: (...args) => prepareGuardMock(...args),
  pendingMergeGuardCurrent: (...args) => guardCurrentMock(...args),
}));
const mergePrMock = vi.fn();
vi.mock('./git.js', () => ({
  mergePR: (...args) => mergePrMock(...args),
}));

const addNotificationMock = vi.fn();
vi.mock('./notifications.js', () => ({
  addNotification: (...args) => addNotificationMock(...args),
  NOTIFICATION_TYPES: { AGENT_WARNING: 'agent_warning' },
  PRIORITY_LEVELS: { HIGH: 'high' },
}));

const spawnReviewLoopFollowUpMock = vi.fn();
vi.mock('./agentWorktreeCleanup.js', () => ({
  spawnReviewLoopFollowUp: (...args) => spawnReviewLoopFollowUpMock(...args),
}));

const mockApps = new Map();
vi.mock('./apps.js', () => ({
  getActiveApps: vi.fn(async () => [...mockApps.values()]),
  getAppById: vi.fn(async (id) => mockApps.get(id) || null),
  updateApp: vi.fn(async (id, patch) => {
    const cur = mockApps.get(id) || { id };
    const next = { ...cur, ...patch };
    mockApps.set(id, next);
    return next;
  }),
}));

const tasksById = vi.hoisted(() => new Map());
const recoveryAgents = vi.hoisted(() => ({ value: [] }));
vi.mock('./cosClaimOwnershipState.js', () => ({ readClaimOwnershipAgents: async () => recoveryAgents.value }));
vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: async metadata => ({
  reviewers: metadata.reviewers || [], usernames: metadata.usernames || [], optionalReviewers: [], reviewerMaxRounds: {},
}) }));
vi.mock('./cosTaskStore.js', () => ({
  getTaskById: async (id) => tasksById.get(id) ?? null,
}));

const getOriginInfoMock = vi.fn();
vi.mock('../lib/gitRemote.js', () => ({
  getOriginInfo: (...args) => getOriginInfoMock(...args),
}));

import { __resetForgeNoAccessLog } from '../lib/forgeAccessErrors.js';
import {
  matchesAuthorFilter,
  computePrCheck,
  formatPullRequestsForPrompt,
  readPrWatcherState,
  readPendingMergePrs,
  queuePendingMerge,
  isPendingMergeReady,
  processPendingMergePrs,
  clearPendingMergeAssessmentHolds,
  sweepPendingMergePrs,
  MAX_PENDING_MERGE_TICKS,
  checkPullRequests,
  getSelfLogin,
  __resetSelfLoginCache,
} from './prWatcher.js';

const pr = (number, login, extra = {}) => ({
  number,
  title: `PR ${number}`,
  authorLogin: login,
  url: `https://github.com/o/r/pull/${number}`,
  createdAt: '2026-06-05T00:00:00Z',
  isDraft: false,
  headRefName: `feat/${number}`,
  ...extra,
});

beforeEach(() => {
  execGhMock.mockReset();
  screenMock.mockReset().mockResolvedValue({ ok: true, screening: { safe: true } });
  fingerprintMock.mockReset().mockResolvedValue('policy-1');
  ensureForgeReachableMock.mockReset();
  ensureForgeReachableMock.mockResolvedValue({ ok: true, status: 'ok', detail: null, remedy: null });
  mergePrMock.mockReset();
  prepareGuardMock.mockReset().mockResolvedValue({ ok: true, evidence: null });
  guardCurrentMock.mockReset().mockResolvedValue(true);
  addNotificationMock.mockReset();
  spawnReviewLoopFollowUpMock.mockReset();
  addNotificationMock.mockResolvedValue({ id: 'notification-1' });
  spawnReviewLoopFollowUpMock.mockResolvedValue({ id: 'follow-up-1' });
  getOriginInfoMock.mockReset();
  mockApps.clear();
  tasksById.clear();
  recoveryAgents.value = [];
  __resetSelfLoginCache();
});

describe('matchesAuthorFilter', () => {
  it('any matches everything', () => {
    expect(matchesAuthorFilter(pr(1, 'alice'), 'any', 'bob')).toBe(true);
    expect(matchesAuthorFilter(pr(1, null), 'any', 'bob')).toBe(true);
  });
  it('self matches only the operator login', () => {
    expect(matchesAuthorFilter(pr(1, 'bob'), 'self', 'bob')).toBe(true);
    expect(matchesAuthorFilter(pr(1, 'alice'), 'self', 'bob')).toBe(false);
    expect(matchesAuthorFilter(pr(1, null), 'self', 'bob')).toBe(false);
  });
  it('others matches everyone but the operator', () => {
    expect(matchesAuthorFilter(pr(1, 'alice'), 'others', 'bob')).toBe(true);
    expect(matchesAuthorFilter(pr(1, 'bob'), 'others', 'bob')).toBe(false);
    expect(matchesAuthorFilter(pr(1, null), 'others', 'bob')).toBe(false);
  });
});

describe('computePrCheck', () => {
  it('first run baselines to max open PR and dispatches nothing', () => {
    const r = computePrCheck({ prs: [pr(5, 'a'), pr(8, 'b')], prevLastSeen: null, authorFilter: 'any', selfLogin: null });
    expect(r.firstRun).toBe(true);
    expect(r.newPrs).toEqual([]);
    expect(r.newLastSeen).toBe(8);
  });

  it('first run with no open PRs baselines to 0', () => {
    const r = computePrCheck({ prs: [], prevLastSeen: null, authorFilter: 'any', selfLogin: null });
    expect(r.firstRun).toBe(true);
    expect(r.newLastSeen).toBe(0);
  });

  it('detects only PRs above the high-water mark', () => {
    const r = computePrCheck({ prs: [pr(5, 'a'), pr(8, 'b'), pr(9, 'c')], prevLastSeen: 8, authorFilter: 'any', selfLogin: null });
    expect(r.newPrs.map(p => p.number)).toEqual([9]);
    expect(r.candidateCount).toBe(1);
    expect(r.newLastSeen).toBe(9);
  });

  it('applies the author gate but still advances the mark past gated-out PRs', () => {
    const r = computePrCheck({
      prs: [pr(10, 'bob'), pr(11, 'alice')],
      prevLastSeen: 9, authorFilter: 'others', selfLogin: 'bob'
    });
    // #10 (bob) gated out, #11 (alice) dispatched
    expect(r.newPrs.map(p => p.number)).toEqual([11]);
    expect(r.candidateCount).toBe(2);
    // mark advances past BOTH so the gated-out #10 never re-fires
    expect(r.newLastSeen).toBe(11);
  });

  it('never regresses the mark when open PRs are below it', () => {
    const r = computePrCheck({ prs: [pr(3, 'a')], prevLastSeen: 10, authorFilter: 'any', selfLogin: null });
    expect(r.newPrs).toEqual([]);
    expect(r.newLastSeen).toBe(10);
  });
});

describe('readPrWatcherState', () => {
  it('tolerates missing / malformed state', () => {
    expect(readPrWatcherState(undefined)).toEqual({});
    expect(readPrWatcherState({})).toEqual({});
    expect(readPrWatcherState({ prWatcherState: null })).toEqual({});
    expect(readPrWatcherState({ prWatcherState: [1, 2] })).toEqual({});
    expect(readPrWatcherState({ prWatcherState: { lastSeenPrNumber: 7 } })).toEqual({ lastSeenPrNumber: 7 });
  });
});

const pendingMerge = (overrides = {}) => ({
  prUrl: 'https://github.com/o/r/pull/88',
  prNumber: 88,
  prBranch: 'cos/task-88',
  sourceAgentId: 'agent-88',
  sourceTask: {
    id: 'task-88',
    priority: 'MEDIUM',
    description: 'Automated task',
    metadata: { app: 'app1' }
  },
  ticks: 0,
  ...overrides,
});

const pendingApp = (entries = [pendingMerge()]) => ({
  id: 'app1',
  repoPath: '/repos/app1',
  // Pinned so the merge path proves it carries the account down (#7540) — an
  // owner-match alone picks the wrong account for an org repo.
  forgeAccount: 'other-account',
  pendingMergePrs: entries
});


function installPendingEvidence() {
  const evidence = {
    pr: {
      number: 88, title: 'Fix example', body: 'Closes #101', headRefOid: 'a'.repeat(40),
      author: { login: 'contributor' }, commits: [{ messageHeadline: 'Complete commit', messageBody: '' }],
      state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }],
    },
    issue: { number: 101, state: 'open', title: 'Example requirement', body: 'Preserve private access.', assignees: [] },
    diff: 'diff --git a/example.js b/example.js\n+const safe = true;',
  };
  execGhMock.mockImplementation(async (args) => {
    if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify({ ...evidence.pr, number: Number(args[2]) });
    if (args[0] === 'pr' && args[1] === 'diff') return evidence.diff;
    if (args[0] === 'api' && args.includes('repos/o/r/issues/101')) return JSON.stringify(evidence.issue);
    throw new Error('Unexpected forge read');
  });
  return evidence;
}

describe('merge-only PR watcher', () => {
  beforeEach(() => {
    admissionState.state = { agents: {}, mergeAdmissions: {} };
    getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
  });

  it('queues a valid pending merge once without resetting its elapsed tick budget', async () => {
    mockApps.set('app1', pendingApp([pendingMerge({ ticks: 4 })]));

    const queued = await queuePendingMerge('app1', pendingMerge());

    expect(queued).toBe(true);
    expect(readPendingMergePrs(mockApps.get('app1'))).toHaveLength(1);
    expect(readPendingMergePrs(mockApps.get('app1'))[0].ticks).toBe(4);
  });

  it('recognizes only a clean OPEN PR with completed green checks as merge-ready', () => {
    expect(isPendingMergeReady({
      state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }]
    })).toBe(true);
    expect(isPendingMergeReady({
      state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: []
    })).toBe(false);
    expect(isPendingMergeReady({
      state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ status: 'IN_PROGRESS' }]
    })).toBe(false);
  });

  it('defers a pending merge without consuming retries while a live parent holds admission', async () => {
    const { claimMergeAdmission } = await import('./cosMergeAdmission.js');
    admissionState.state.agents.parent = { id: 'parent', taskId: 'task-parent', startedAt: '2026-01-01', status: 'running',
      metadata: { sourceWorkspace: '/repos/app1', claimPicksOwnBranch: true } };
    const lease = await claimMergeAdmission({ agentId: 'parent', action: 'acquire' });
    expect(lease.admitted).toBe(true);
    const app = pendingApp();
    mockApps.set(app.id, app);
    installPendingEvidence();
    expect(await processPendingMergePrs(app)).toMatchObject({ waiting: 1, merged: 0 });
    expect(mergePrMock).not.toHaveBeenCalled();
    expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(0);
    await claimMergeAdmission({ agentId: 'parent', action: 'release', token: lease.token, outcome: 'leave-open' });
    mergePrMock.mockResolvedValue({ success: true });
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 1 });
  });

  it('merges a green pending PR without spawning a follow-up agent', async () => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    installPendingEvidence();
    mergePrMock.mockResolvedValue({ success: true });

    const result = await processPendingMergePrs(app);

    expect(result).toMatchObject({ ok: true, checked: 1, merged: 1, escalated: 0 });
    expect(mergePrMock).toHaveBeenCalledWith('/repos/app1', 88, { forgeAccount: 'other-account', expectedHeadSha: 'a'.repeat(40) });
    expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();
    expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
    expect(execGhMock).toHaveBeenCalledWith([
      'pr', 'view', '88', '--repo', 'github.com/o/r',
      '--json', 'number,title,body,commits,headRefOid,author,state,isDraft,baseRefName,baseRefOid,mergeable,mergeStateStatus,statusCheckRollup'
    ], undefined, { cwd: '/repos/app1', env: PINNED_ENV, backoffKey: 'github.com/o/r' });
  });

  it.each([
    ['unavailable', { ok: false }],
    ['malformed', {}],
    ['uncertain', { ok: false, screening: { safe: false, layers: { securityModel: 'uncertain' } } }],
    ['incompatible', { ok: false, screening: { safe: false, layers: { securityModel: 'incompatible' } } }],
  ])('retains a ready PR when the contribution assessment is %s', async (_name, response) => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    installPendingEvidence();
    screenMock.mockResolvedValue(response);
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });
    expect(mergePrMock).not.toHaveBeenCalled();
    expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(1);
  });

  describe('a withheld contribution assessment', () => {
    const modelRequired = { ok: false, code: 'untrusted-content-model-required', message: 'No eligible API provider has a default model.' };
    const head = 'a'.repeat(40);
    const handoff = (headSha = head) => ({
      headSha, repository: 'github.com/o/r', agentId: 'agent-88', taskId: 'task-88',
      receiptId: 'receipt-88', prCompletion: 'merge-on-green',
    });
    const armOwner = () => {
      tasksById.set('task-88', { id: 'task-88', status: 'completed', metadata: { prCompletion: 'merge-on-green' } });
    };
    const sweep = async (app) => {
      const logged = vi.spyOn(console, 'error').mockImplementation(() => {});
      try { return { result: await processPendingMergePrs(app), lines: logged.mock.calls.map(call => String(call[0])) }; }
      finally { logged.mockRestore(); }
    };

    it('names the assessment code in the log line, attention, and the deadline notification', async () => {
      const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1, handoff: handoff() })]);
      mockApps.set(app.id, app);
      armOwner();
      installPendingEvidence();
      screenMock.mockResolvedValue(modelRequired);
      const { lines } = await sweep(app);
      const kept = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(lines.some(line => line.includes('Deterministic merge failed for PR #88') && line.includes('untrusted-content-model-required')
        && !line.includes('assessment was unavailable or withheld'))).toBe(true);
      expect(kept.attention).toContain('untrusted-content-model-required');
      expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
        description: expect.stringContaining('untrusted-content-model-required'),
      }));
    });

    it('reports a thrown assessment as security-action-assessment-error without logging the error text', async () => {
      const app = pendingApp();
      mockApps.set(app.id, app);
      installPendingEvidence();
      screenMock.mockRejectedValue(new Error('contribution body must stay out of the log'));
      const warned = vi.spyOn(console, 'warn').mockImplementation(() => {});
      const { lines } = await sweep(app);
      warned.mockRestore();
      expect(lines.some(line => line.includes('security-action-assessment-error'))).toBe(true);
      expect(lines.some(line => line.includes('contribution body must stay out of the log'))).toBe(false);
      expect(warned.mock.calls.some(call => String(call[0]).includes('contribution body must stay out of the log'))).toBe(false);
    });

    it('is not re-assessed, and takes no admission lease, while the head and policy are unchanged', async () => {
      const app = pendingApp([pendingMerge({ handoff: handoff() })]);
      mockApps.set(app.id, app);
      armOwner();
      installPendingEvidence();
      screenMock.mockResolvedValue(modelRequired);
      await sweep(app);
      expect(screenMock).toHaveBeenCalledTimes(1);
      expect(readPendingMergePrs(mockApps.get(app.id))[0].assessmentWithheld).toMatchObject({ headSha: head, policy: 'policy-1' });

      // A live parent holding the lease would defer any entry that asked for it.
      const { claimMergeAdmission } = await import('./cosMergeAdmission.js');
      admissionState.state.agents.parent = { id: 'parent', taskId: 'task-parent', startedAt: '2026-01-01', status: 'running',
        metadata: { sourceWorkspace: '/repos/app1', claimPicksOwnBranch: true } };
      const lease = await claimMergeAdmission({ agentId: 'parent', action: 'acquire' });
      expect(lease.admitted).toBe(true);
      const held = await processPendingMergePrs(mockApps.get(app.id));
      expect(held.waiting || 0).toBe(0);
      expect(screenMock).toHaveBeenCalledTimes(1);
      expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(2);
      await claimMergeAdmission({ agentId: 'parent', action: 'release', token: lease.token, outcome: 'leave-open' });
    });

    it('re-arms a bound entry when the policy is saved again without a fingerprint change', async () => {
      const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1, handoff: handoff() })]);
      mockApps.set(app.id, app);
      armOwner();
      installPendingEvidence();
      screenMock.mockResolvedValue(modelRequired);
      await sweep(app);
      const withheld = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(withheld.assessmentWithheld).toMatchObject({ headSha: head, policy: 'policy-1', code: expect.stringContaining('untrusted-content-model-required') });
      expect(withheld.attention).toContain('untrusted-content-model-required');
      await clearPendingMergeAssessmentHolds();
      const cleared = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(cleared.assessmentWithheld).toBeUndefined();
      expect(cleared.attention).toBeUndefined();
      expect(cleared.handoff.headSha).toBe(head);
      screenMock.mockResolvedValue({ ok: true, screening: { safe: true } });
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });
      expect(screenMock).toHaveBeenCalledTimes(2);
    });

    it('does not persist a hold when a policy save overlaps the assessment', async () => {
      const app = pendingApp([pendingMerge({ handoff: handoff() })]);
      mockApps.set(app.id, app);
      armOwner();
      installPendingEvidence();
      screenMock.mockImplementation(async () => {
        await clearPendingMergeAssessmentHolds();
        return modelRequired;
      });
      await sweep(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0].assessmentWithheld).toBeUndefined();
      screenMock.mockResolvedValue({ ok: true, screening: { safe: true } });
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });
      expect(screenMock).toHaveBeenCalledTimes(2);
    });

    it('keeps an unrelated attention when a policy save clears the assessment hold', async () => {
      const app = pendingApp([pendingMerge({
        handoff: handoff(),
        attention: 'forge-unreadable',
        assessmentWithheld: { headSha: head, code: 'untrusted-content-model-required', policy: 'policy-1', reason: 'untrusted-content-model-required' },
      })]);
      mockApps.set(app.id, app);
      await clearPendingMergeAssessmentHolds();
      const kept = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(kept.assessmentWithheld).toBeUndefined();
      expect(kept.attention).toBe('forge-unreadable');
    });

    it('re-arms a bound entry when the handed-off head moves', async () => {
      const app = pendingApp([pendingMerge({ handoff: handoff() })]);
      mockApps.set(app.id, app);
      armOwner();
      const evidence = installPendingEvidence();
      screenMock.mockResolvedValue(modelRequired);
      await sweep(app);
      const nextHead = 'b'.repeat(40);
      const stored = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(stored.assessmentWithheld.headSha).toBe(head);
      mockApps.set(app.id, { ...mockApps.get(app.id), pendingMergePrs: [{ ...stored, handoff: handoff(nextHead) }] });
      evidence.pr.headRefOid = nextHead;
      screenMock.mockResolvedValue({ ok: true, screening: { safe: true } });
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });
      expect(screenMock).toHaveBeenCalledTimes(2);
    });

    it.each([
      ['a changed policy', () => fingerprintMock.mockResolvedValue('policy-2'), () => {}],
      ['a new head', () => {}, (e) => { e.pr.headRefOid = 'b'.repeat(40); }],
    ])('is assessed again after %s', async (_name, changePolicy, changeEvidence) => {
      const app = pendingApp();
      mockApps.set(app.id, app);
      const evidence = installPendingEvidence();
      screenMock.mockResolvedValue(modelRequired);
      await sweep(app);
      changePolicy();
      changeEvidence(evidence);
      screenMock.mockResolvedValue({ ok: true, screening: { safe: true } });
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });
      expect(screenMock).toHaveBeenCalledTimes(2);
    });

    it('does not cache a transport failure that can heal without a change', async () => {
      const app = pendingApp();
      mockApps.set(app.id, app);
      installPendingEvidence();
      screenMock.mockResolvedValue({ ok: false, code: 'untrusted-content-reasoner-failed' });
      await sweep(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0].assessmentWithheld).toBeUndefined();
    });
  });

  it.each([
    ['head', (e) => { e.pr.headRefOid = 'b'.repeat(40); }],
    ['title', (e) => { e.pr.title = 'Rewritten title'; }],
    ['body', (e) => { e.pr.body = 'Rewritten description'; }],
    ['intent', (e) => { e.issue.body = 'Changed requirement'; }],
    ['CI', (e) => { e.pr.statusCheckRollup = [{ status: 'IN_PROGRESS' }]; }],
  ])('withholds a queued merge when %s changes during inference', async (_name, mutate) => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    const evidence = installPendingEvidence();
    screenMock.mockImplementation(async () => {
      mutate(evidence);
      return { ok: true, screening: { safe: true } };
    });
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });
    expect(mergePrMock).not.toHaveBeenCalled();
    expect(readPendingMergePrs(mockApps.get(app.id))).toHaveLength(1);
  });

  it('screens complete commit tails and linked intent using the owning forge account', async () => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    const evidence = installPendingEvidence();
    evidence.pr.commits[0].messageBody = 'x'.repeat(100_001) + 'TAIL';
    mergePrMock.mockResolvedValue({ success: true });
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 1 });
    expect(screenMock).toHaveBeenCalledWith(expect.objectContaining({
      content: expect.stringContaining('TAIL'),
    }));
    expect(screenMock.mock.calls[0][0].content).toContain('Preserve private access.');
    for (const [, , options] of execGhMock.mock.calls) {
      expect(options).toMatchObject({ cwd: app.repoPath, env: PINNED_ENV });
    }
  });

  it.each(['commits', 'linked issues'])('refuses oversized complete %s before inference', async (surface) => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    const evidence = installPendingEvidence();
    if (surface === 'commits') evidence.pr.commits[0].messageBody = 'x'.repeat(2_000_001);
    else evidence.issue.body = 'x'.repeat(65_537);
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0 });
    expect(screenMock).not.toHaveBeenCalled();
    expect(mergePrMock).not.toHaveBeenCalled();
  });

  it('notifies and retires an unavailable assessment at the queue deadline', async () => {
    const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);
    mockApps.set(app.id, app);
    installPendingEvidence();
    screenMock.mockRejectedValue(new Error('Provider unavailable'));
    expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0, timedOut: 1 });
    expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
      description: expect.stringContaining('security-action-assessment-error'),
    }));
    expect(readPendingMergePrs(mockApps.get(app.id))).toEqual([]);
  });

  it.each([
    ['validation-failed', { state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'FAILURE' }] }],
    ['merge-conflict', { state: 'OPEN', mergeStateStatus: 'DIRTY', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }],
  ])('escalates %s to the existing merge-only follow-up', async (_reason, prView) => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    execGhMock.mockResolvedValueOnce(JSON.stringify(prView));

    const result = await processPendingMergePrs(app);

    expect(result).toMatchObject({ ok: true, escalated: 1, merged: 0 });
    expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({
      prUrl: 'https://github.com/o/r/pull/88',
      prBranch: 'cos/task-88',
      sourceWorkspace: '/repos/app1',
      prCompletion: 'merge-on-green',
      reviewers: []
    }));
    expect(mergePrMock).not.toHaveBeenCalled();
    expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
  });

  it('joins an overlapping sweep of the same app instead of escalating its entry twice', async () => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'FAILURE' }] }));

    const [timer, generator] = await Promise.all([processPendingMergePrs(app), processPendingMergePrs(app)]);

    expect(timer).toBe(generator);
    expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledTimes(1);
  });

  it('retains the receipt while its owner is active and records a blocked retry once across sweeps', async () => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'DIRTY' }));
    spawnReviewLoopFollowUpMock.mockResolvedValueOnce({ id: 'sys-rl-owner', deferred: true });
    expect(await processPendingMergePrs(app)).toMatchObject({ escalated: 0, waiting: 1 });
    expect(readPendingMergePrs(mockApps.get(app.id))).toHaveLength(1);
    spawnReviewLoopFollowUpMock.mockResolvedValueOnce({ id: 'sys-rl-owner', blocked: 'retry budget exhausted' });
    await processPendingMergePrs(mockApps.get(app.id));
    expect(readPendingMergePrs(mockApps.get(app.id))[0].recoveryBlocked).toBe('retry budget exhausted');
    execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }));
    await processPendingMergePrs(mockApps.get(app.id));
    expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledTimes(2);
    expect(addNotificationMock).toHaveBeenCalledTimes(1);
    expect(mergePrMock).not.toHaveBeenCalled();
  });

  it('does not erase a newer receipt when an older recovery settles', async () => {
    const app = pendingApp();
    mockApps.set(app.id, app);
    execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'DIRTY' }));
    spawnReviewLoopFollowUpMock.mockImplementationOnce(async () => {
      await queuePendingMerge(app.id, { ...app.pendingMergePrs[0], handoff: {
        receiptId: 'new-receipt', headSha: 'b'.repeat(40), repository: 'github.com/o/r',
        agentId: 'new-run', prCompletion: 'review-then-merge',
      } });
      return { id: 'sys-rl-owner', resumed: true };
    });
    await processPendingMergePrs(app);
    expect(readPendingMergePrs(mockApps.get(app.id))[0].handoff.receiptId).toBe('new-receipt');
  });

  it('stops polling and notifies after the bounded pending-merge budget', async () => {
    const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);
    mockApps.set(app.id, app);
    execGhMock.mockResolvedValueOnce(JSON.stringify({
      state: 'OPEN', mergeStateStatus: 'BLOCKED', statusCheckRollup: [{ status: 'IN_PROGRESS' }]
    }));

    const result = await processPendingMergePrs(app);

    expect(result).toMatchObject({ ok: true, timedOut: 1 });
    expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
      type: 'agent_warning',
      priority: 'high',
      link: 'https://github.com/o/r/pull/88'
    }));
    expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
  });

  it('ticks an unreadable PR so a permanently-broken entry can time out', async () => {
    // `gh pr view` fails (deleted PR / renamed repo / revoked token). Counting
    // this cycle as an error but NOT as a tick re-queued the entry unchanged
    // forever — MAX_PENDING_MERGE_TICKS never fired and it leaked in apps.json.
    const app = pendingApp([pendingMerge({ ticks: 2 })]);
    mockApps.set(app.id, app);
    execGhMock.mockRejectedValueOnce(new Error('could not resolve to a PullRequest'));

    const result = await processPendingMergePrs(app);

    expect(result).toMatchObject({ ok: true, checked: 0, errors: 1, timedOut: 0 });
    expect(readPendingMergePrs(mockApps.get('app1'))[0].ticks).toBe(3);
  });

  it('times out and notifies once a permanently-unreadable PR exhausts its tick budget', async () => {
    const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);
    mockApps.set(app.id, app);
    execGhMock.mockRejectedValueOnce(new Error('could not resolve to a PullRequest'));

    const result = await processPendingMergePrs(app);

    expect(result).toMatchObject({ ok: true, errors: 1, timedOut: 1 });
    expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
      type: 'agent_warning',
      link: 'https://github.com/o/r/pull/88',
      description: expect.stringContaining('could not be read from the forge'),
    }));
    expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
  });

  describe('merged-tree guard admission', () => {
    const guard = { headSha: 'a'.repeat(40), baseSha: 'b'.repeat(40), baseBranch: 'main', logPath: '/example/guard.log' };
    const handoff = { headSha: guard.headSha, repository: 'github.com/o/r', agentId: 'agent-88', taskId: 'task-88',
      receiptId: 'receipt-88', prCompletion: 'merge-on-green' };
    const setup = () => {
      const app = pendingApp([pendingMerge({ handoff })]);
      mockApps.set(app.id, app);
      tasksById.set('task-88', { id: 'task-88', status: 'completed', metadata: { prCompletion: 'merge-on-green' } });
      const evidence = installPendingEvidence();
      evidence.pr.baseRefName = 'main';
      return { app, evidence };
    };

    const legacy = (snapshot = false) => {
      const { app } = setup();
      app.pendingMergePrs = [pendingMerge(snapshot ? { sourceAgentId: null, prBranch: 'portos/quality-snapshot',
        sourceTask: { id: `quality-snapshot-${app.id}`, description: 'Publish PortOS quality snapshot', metadata: { app: app.id } } } : {})];
      tasksById.get('task-88').metadata.app = app.id;
      prepareGuardMock.mockResolvedValue({ ok: false, reason: 'merged-tree-recovery-required', evidence: { headSha: guard.headSha } });
      return app;
    };

    it.each([false, true])('recovers an unbound producer with a pinned checkout task before any merge (snapshot=%s)', async snapshot => {
      const app = legacy(snapshot);
      expect(await processPendingMergePrs(app)).toMatchObject({ escalated: 1, merged: 0 });
      expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({
        prCompletion: 'merge-on-green', reviewers: [],
        mergeGuardTarget: expect.objectContaining({ headSha: guard.headSha, appId: app.id,
          sourceTaskId: snapshot ? `quality-snapshot-${app.id}` : 'task-88' }),
      }));
      expect(readPendingMergePrs(mockApps.get(app.id))).toEqual([]);
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(admissionState.state.mergeAdmissions).toEqual({});
    });

    it('retains the queue while a completed source still has an active worker', async () => {
      const app = legacy();
      recoveryAgents.value = [{ id: 'agent-88', taskId: 'task-88', status: 'running' }];
      expect(await processPendingMergePrs(app)).toMatchObject({ waiting: 1 });
      expect(readPendingMergePrs(mockApps.get(app.id))).toHaveLength(1);
      expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it('preserves the live source review policy and roster instead of the skinny queued metadata', async () => {
      const app = legacy();
      Object.assign(tasksById.get('task-88').metadata, { prCompletion: 'review-then-merge', reviewers: ['claude'], usernames: ['reviewer'] });
      await processPendingMergePrs(app);
      expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({
        prCompletion: 'review-then-merge', reviewers: ['claude'], usernames: ['reviewer'],
      }));
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it('holds changed human completion policy without dispatching or merging', async () => {
      const app = legacy();
      tasksById.get('task-88').metadata.prCompletion = 'leave-open';
      await processPendingMergePrs(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ recoveryBlocked: 'recovery-owner-policy-held' });
      expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it.each(['throw', 'unpersisted', 'deferred'])('retains queue custody when checkout recovery is %s', async outcome => {
      const app = legacy();
      if (outcome === 'throw') spawnReviewLoopFollowUpMock.mockRejectedValue(new Error('store unavailable'));
      else spawnReviewLoopFollowUpMock.mockResolvedValue(outcome === 'deferred' ? { deferred: true } : null);
      await processPendingMergePrs(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ mergedTreeGuard: { headSha: guard.headSha, reason: 'merged-tree-recovery-required' } });
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it('retains a failing combined-tree receipt and log without taking admission or merging', async () => {
      const { app } = setup();
      prepareGuardMock.mockImplementation(async () => {
        expect(admissionState.state.mergeAdmissions).toEqual({});
        return { ok: false, reason: 'merged-tree-guards-failed', evidence: guard };
      });
      await processPendingMergePrs(app);
      const kept = readPendingMergePrs(mockApps.get(app.id))[0];
      expect(kept).toMatchObject({ handoff, ticks: 0, mergedTreeGuard: { ...guard, reason: 'merged-tree-guards-failed' },
        recoveryBlocked: 'merged-tree-guards-failed' });
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(admissionState.state.mergeAdmissions).toEqual({});
      expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();
      await processPendingMergePrs(mockApps.get(app.id));
      expect(prepareGuardMock).toHaveBeenCalledTimes(1);
      expect(addNotificationMock).toHaveBeenCalledTimes(1);
    });

    it('retains an actionable diagnostic when validation prerequisites throw', async () => {
      const { app } = setup();
      prepareGuardMock.mockRejectedValue(new Error('git fetch failed: repository unavailable'));
      await processPendingMergePrs(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,
        mergedTreeGuard: { reason: 'merged-tree-validation-unavailable', detail: 'git fetch failed: repository unavailable' } });
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(admissionState.state.mergeAdmissions).toEqual({});
    });

    it('notifies once and retains the owner when an unavailable prerequisite exhausts its retry budget', async () => {
      const { app } = setup();
      app.pendingMergePrs[0].ticks = MAX_PENDING_MERGE_TICKS - 1;
      prepareGuardMock.mockRejectedValue(new Error('git fetch failed: repository unavailable'));
      await processPendingMergePrs(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,
        ticks: MAX_PENDING_MERGE_TICKS, attention: 'merged-tree-validation-unavailable' });
      expect(addNotificationMock).toHaveBeenCalledTimes(1);
      await processPendingMergePrs(mockApps.get(app.id));
      expect(addNotificationMock).toHaveBeenCalledTimes(1);
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it('notifies and holds a checkout refusal for repair instead of retrying forever', async () => {
      const { app } = setup();
      prepareGuardMock.mockResolvedValue({ ok: false, reason: 'merged-tree-checkout-unverified' });
      await processPendingMergePrs(app);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff,
        recoveryBlocked: 'merged-tree-checkout-unverified' });
      await processPendingMergePrs(mockApps.get(app.id));
      expect(prepareGuardMock).toHaveBeenCalledTimes(1);
      expect(addNotificationMock).toHaveBeenCalledTimes(1);
      expect(mergePrMock).not.toHaveBeenCalled();
    });

    it('runs the guard outside admission and merges the unchanged reviewed head inside it', async () => {
      const { app } = setup();
      prepareGuardMock.mockImplementation(async () => {
        expect(admissionState.state.mergeAdmissions).toEqual({});
        return { ok: true, evidence: guard };
      });
      guardCurrentMock.mockImplementation(async () => {
        expect(Object.keys(admissionState.state.mergeAdmissions)).toHaveLength(1);
        return true;
      });
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(app)).toMatchObject({ merged: 1 });
      expect(guardCurrentMock).toHaveBeenCalledWith(guard, expect.objectContaining({ headRefOid: guard.headSha }), expect.any(Function));
      expect(mergePrMock).toHaveBeenCalledWith(app.repoPath, 88, { forgeAccount: 'other-account', expectedHeadSha: guard.headSha });
    });

    it('releases admission when the checked base moves and validates again before a later merge', async () => {
      const { app } = setup();
      prepareGuardMock.mockResolvedValue({ ok: true, evidence: guard });
      guardCurrentMock.mockResolvedValueOnce(false).mockResolvedValueOnce(true);
      mergePrMock.mockResolvedValue({ success: true });
      expect(await processPendingMergePrs(app)).toMatchObject({ merged: 0, waiting: 1 });
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ handoff, mergedTreeGuard: guard, ticks: 0 });
      expect(Object.values(admissionState.state.mergeAdmissions).every(lease => lease.status !== 'active')).toBe(true);
      expect(await processPendingMergePrs(mockApps.get(app.id))).toMatchObject({ merged: 1 });
      expect(prepareGuardMock).toHaveBeenCalledTimes(2);
    });

    it('never merges a head changed during guard execution and preserves the receipt for fresh recovery', async () => {
      const { app, evidence } = setup();
      prepareGuardMock.mockImplementation(async () => {
        evidence.pr.headRefOid = 'c'.repeat(40);
        return { ok: true, evidence: guard };
      });
      await processPendingMergePrs(app);
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(readPendingMergePrs(mockApps.get(app.id))[0].handoff).toEqual(handoff);
      await processPendingMergePrs(mockApps.get(app.id));
      expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledWith(expect.objectContaining({ prCompletion: 'merge-on-green' }));
    });
  });

  describe('a bound handoff receipt', () => {
    const boundHandoff = {
      headSha: 'a'.repeat(40), repository: 'github.com/o/r', agentId: 'agent-88', taskId: 'task-88',
      receiptId: 'receipt-88', prCompletion: 'merge-on-green',
    };

    it('stays queued in attention, notified once, when its PR stays unreadable past the budget', async () => {
      const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1, handoff: boundHandoff })]);
      mockApps.set(app.id, app);
      execGhMock.mockRejectedValue(new Error('could not resolve to a PullRequest'));

      expect(await processPendingMergePrs(app)).toMatchObject({ ok: true, checked: 0, errors: 1, timedOut: 1 });
      expect(readPendingMergePrs(mockApps.get(app.id))).toEqual([
        expect.objectContaining({ ticks: MAX_PENDING_MERGE_TICKS, attention: 'forge-unreadable' }),
      ]);
      expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
        description: expect.stringContaining('PortOS retains its pending-merge receipt'),
      }));

      await processPendingMergePrs(mockApps.get(app.id));
      expect(addNotificationMock).toHaveBeenCalledTimes(1);
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ ticks: MAX_PENDING_MERGE_TICKS, attention: 'forge-unreadable' });
    });

    it('is held for its owner, not escalated, when the owning task is no longer running', async () => {
      const app = pendingApp([pendingMerge({ handoff: boundHandoff })]);
      mockApps.set(app.id, app);
      tasksById.set('task-88', { id: 'task-88', status: 'failed', metadata: { prCompletion: 'merge-on-green' } });
      execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'DIRTY', headRefOid: 'a'.repeat(40) }));

      expect(await processPendingMergePrs(app)).toMatchObject({ ok: true, checked: 1, escalated: 0, waiting: 1 });
      expect(spawnReviewLoopFollowUpMock).not.toHaveBeenCalled();
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ recoveryBlocked: 'The coordinating task is failed', ticks: 0 });
      expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
        description: 'PR #88 remains owned by task task-88: The coordinating task is failed.',
      }));
    });

    it('is held for its owner, not merged, when the owning task stops inside merge admission', async () => {
      const app = pendingApp([pendingMerge({ handoff: boundHandoff })]);
      mockApps.set(app.id, app);
      tasksById.set('task-88', { id: 'task-88', status: 'failed', metadata: { prCompletion: 'merge-on-green' } });
      installPendingEvidence();

      expect(await processPendingMergePrs(app)).toMatchObject({ ok: true, checked: 1, merged: 0, waiting: 1 });
      expect(mergePrMock).not.toHaveBeenCalled();
      expect(readPendingMergePrs(mockApps.get(app.id))[0]).toMatchObject({ recoveryBlocked: 'The coordinating task is failed', ticks: 0 });
      expect(addNotificationMock).toHaveBeenCalledWith(expect.objectContaining({
        description: 'PR #88 remains owned by task task-88: The coordinating task is failed.',
      }));
    });
  });
});

describe('sweepPendingMergePrs', () => {
  beforeEach(() => {
    mockApps.clear();
    getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
  });

  // The regression this whole sweep exists for: pending merges used to drain
  // only when the app's `pr-watcher` scheduled task fired, so an install that
  // left that task disabled queued green PRs into a list nothing ever read.
  // The sweep must not consult the task schedule at all.
  it('drains a pending merge for an app with no pr-watcher config', async () => {
    mockApps.set('app1', { ...pendingApp(), name: 'App One', prWatcherState: undefined });
    installPendingEvidence();
    mergePrMock.mockResolvedValue({ success: true });

    const totals = await sweepPendingMergePrs();

    expect(totals).toMatchObject({ checked: 1, merged: 1, failures: 0 });
    expect(readPendingMergePrs(mockApps.get('app1'))).toEqual([]);
  });

  it('skips apps with no queued PRs without resolving their git origin', async () => {
    mockApps.set('app1', { id: 'app1', name: 'App One', repoPath: '/repos/app1' });
    mockApps.set('app2', { id: 'app2', name: 'App Two', repoPath: '/repos/app2', pendingMergePrs: [] });

    const totals = await sweepPendingMergePrs();

    expect(totals).toMatchObject({ checked: 0, merged: 0, failures: 0 });
    expect(getOriginInfoMock).not.toHaveBeenCalled();
    expect(execGhMock).not.toHaveBeenCalled();
  });

  it('counts a failing app and still sweeps the rest', async () => {
    mockApps.set('app1', { ...pendingApp(), name: 'App One' });
    mockApps.set('app2', {
      id: 'app2', name: 'App Two', repoPath: '/repos/app2',
      pendingMergePrs: [pendingMerge({ prNumber: 99, prUrl: 'https://github.com/o/r/pull/99' })]
    });
    // app1 fails the forge check; app2 proceeds and merges.
    ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable' });
    installPendingEvidence();
    mergePrMock.mockResolvedValue({ success: true });

    const totals = await sweepPendingMergePrs();

    expect(totals).toMatchObject({ failures: 1, checked: 1, merged: 1 });
    // The unreachable app keeps its entry for the next tick.
    expect(readPendingMergePrs(mockApps.get('app1'))).toHaveLength(1);
    expect(readPendingMergePrs(mockApps.get('app2'))).toEqual([]);
  });
});

describe('formatPullRequestsForPrompt', () => {
  it('renders a markdown block with numbers, authors and urls', () => {
    const out = formatPullRequestsForPrompt(
      [pr(12, 'alice', { isDraft: true })],
      { repoFullName: 'o/r', defaultBranch: 'main' }
    );
    expect(out).toContain('o/r');
    expect(out).toContain('`main`');
    expect(out).toContain('#12');
    expect(out).toContain('by alice');
    expect(out).toContain('_(draft)_');
    expect(out).toContain('https://github.com/o/r/pull/12');
  });
});

describe('getSelfLogin', () => {
  it('resolves against the given host (via --hostname) and caches per host', async () => {
    execGhMock.mockResolvedValueOnce('bob\n');
    expect(await getSelfLogin('github.com')).toBe('bob');
    expect(await getSelfLogin('github.com')).toBe('bob');
    expect(execGhMock).toHaveBeenCalledTimes(1);
    // --hostname is required: without it `gh api` hits github.com regardless of
    // cwd and would resolve the wrong identity on an enterprise repo.
    expect(execGhMock).toHaveBeenCalledWith(
      ['api', 'user', '--hostname', 'github.com', '--jq', '.login'],
      undefined,
      { backoffKey: 'github.com' }
    );
  });

  it('caches each host independently — a different login per host', async () => {
    execGhMock
      .mockResolvedValueOnce('alice\n')        // github.com
      .mockResolvedValueOnce('alice_corp\n');  // enterprise
    expect(await getSelfLogin('github.com')).toBe('alice');
    expect(await getSelfLogin('github.enterprise.test')).toBe('alice_corp');
    // Both cached — no re-resolve for either host.
    expect(await getSelfLogin('github.com')).toBe('alice');
    expect(await getSelfLogin('github.enterprise.test')).toBe('alice_corp');
    expect(execGhMock).toHaveBeenCalledTimes(2);
  });

  it('isolates scoped viewers on one host from each other and the ambient cache', async () => {
    const first = { cwd: '/example/repo', env: { GH_TOKEN: 'synthetic-token-a' } };
    const second = { cwd: '/example/repo', env: { GH_TOKEN: 'synthetic-token-b' } };
    execGhMock.mockImplementation(async (args, timeout, options) => {
      if (options.env === first.env) return 'example-reviewer-a';
      if (options.env === second.env) return 'example-reviewer-b';
      return 'ambient-viewer';
    });
    expect(await getSelfLogin('github.com')).toBe('ambient-viewer');
    expect(await getSelfLogin('github.com', first)).toBe('example-reviewer-a');
    expect(await getSelfLogin('github.com', second)).toBe('example-reviewer-b');
    execGhMock.mockRejectedValueOnce(new Error('Synthetic scoped account unavailable'));
    expect(await getSelfLogin('github.com', second)).toBeNull();
    expect(await getSelfLogin('github.com', second)).toBe('example-reviewer-b');
    expect(await getSelfLogin('github.com')).toBe('ambient-viewer');
    expect(execGhMock).toHaveBeenCalledTimes(5);
    expect(execGhMock).toHaveBeenCalledWith(
      ['api', 'user', '--hostname', 'github.com', '--jq', '.login'],
      undefined, { ...second, backoffKey: 'github.com' },
    );
  });

  it('returns null with no host and never shells out', async () => {
    expect(await getSelfLogin()).toBe(null);
    expect(await getSelfLogin('')).toBe(null);
    expect(execGhMock).not.toHaveBeenCalled();
  });

  it('returns null when gh fails', async () => {
    execGhMock.mockRejectedValueOnce(new Error('not authed'));
    expect(await getSelfLogin('github.com')).toBe(null);
  });

  it('does not cache a failed lookup — retries on the next call', async () => {
    execGhMock.mockRejectedValueOnce(new Error('keychain locked'));
    expect(await getSelfLogin('github.com')).toBe(null);
    // A transient failure must not wedge the cache: the next call retries.
    execGhMock.mockResolvedValueOnce('bob');
    expect(await getSelfLogin('github.com')).toBe('bob');
    expect(execGhMock).toHaveBeenCalledTimes(2);
  });
});

describe('checkPullRequests trusted maintenance boundary', () => {
  const app = { id: 'app1', repoPath: '/repos/example', prWatcherState: { lastSeenPrNumber: 9 } };
  const rawPr = (number, login, extra = {}) => ({ number, author: { login }, headRefOid: 'a'.repeat(40), updatedAt: '2026-08-01T00:00:00Z', ...extra });
  function forge(prs, { permission = 'write', host = 'github.com' } = {}) {
    getOriginInfoMock.mockResolvedValue({ host, fullName: 'example/project', hasOrigin: true });
    execGhMock.mockImplementation(async args => {
      if (args[0] === 'repo') return 'main';
      if (args[0] === 'pr') return JSON.stringify(prs);
      if (args.at(-1) === 'user') return JSON.stringify({ login: 'operator' });
      const login = args.at(-1).split('/').at(-2);
      return JSON.stringify({ user: { login }, permission: login === 'collaborator' ? permission : 'read' });
    });
  }

  it('routes self and live write collaborators, and legacy any/others never widen maintenance', async () => {
    forge([rawPr(10, 'operator'), rawPr(11, 'collaborator'), rawPr(12, 'external'), rawPr(13, null)]);
    for (const authorFilter of ['any', 'others', 'trusted']) {
      const result = await checkPullRequests(app, { authorFilter });
      expect(result.newPrs.map(pr => pr.number)).toEqual([10, 11]);
      expect(Object.keys(result.activityByPr)).toEqual(['10', '11']);
    }
    expect((await checkPullRequests(app, { authorFilter: 'self' })).newPrs.map(pr => pr.number)).toEqual([10]);
  });

  it('baselines once, converges, and re-dispatches an existing trusted PR after head or CI changes', async () => {
    const prs = [rawPr(3, 'collaborator')];
    forge(prs);
    const baseline = await checkPullRequests({ ...app, prWatcherState: {} });
    expect(baseline).toMatchObject({ firstRun: true, newPrs: [], newLastSeen: 3 });
    const tracked = { ...app, prWatcherState: { lastSeenPrNumber: 3, activityByPr: baseline.activityByPr } };
    expect((await checkPullRequests(tracked)).newPrs).toEqual([]);
    prs[0].headRefOid = 'b'.repeat(40);
    expect((await checkPullRequests(tracked)).newPrs.map(pr => pr.number)).toEqual([3]);
    prs[0].headRefOid = 'a'.repeat(40);
    prs[0].statusCheckRollup = [{ status: 'COMPLETED', conclusion: 'FAILURE' }];
    expect((await checkPullRequests(tracked)).newPrs.map(pr => pr.number)).toEqual([3]);
    const failureSeen = await checkPullRequests(tracked);
    prs[0].statusCheckRollup[0].completedAt = '2026-08-02T00:00:00Z';
    expect((await checkPullRequests({ ...tracked, prWatcherState: { lastSeenPrNumber: 3, activityByPr: failureSeen.activityByPr } })).newPrs.map(pr => pr.number)).toEqual([3]);
  });

  it('runs every gh read with the per-repo credential, honouring the app\'s forgeAccount pin', async () => {
    // #7540: `gh repo view`, `gh pr list` and the collaborator `gh api` probes all
    // used gh's ambient active login, so an app whose repo belongs to another
    // GitHub account 404'd on every tick forever.
    forge([rawPr(10, 'collaborator')]);
    const pinned = { ...app, forgeAccount: 'other-account' };

    expect((await checkPullRequests(pinned)).newPrs).toHaveLength(1);

    expect(resolveForgeExecOptionsMock).toHaveBeenCalledWith('/repos/example', { forgeAccount: 'other-account' });
    // Not just the PR list — the default-branch read and the actor-trust probes
    // are against the same private repo and need the same credential.
    const kinds = new Set(execGhMock.mock.calls.map(([args]) => args[0]));
    expect(kinds).toEqual(new Set(['repo', 'pr', 'api']));
    for (const [, , options] of execGhMock.mock.calls) {
      expect(options).toMatchObject({ cwd: '/repos/example', env: PINNED_ENV });
    }
    expect(ensureForgeReachableMock).toHaveBeenCalledWith('pr-watcher', {
      hostname: 'github.com',
      env: PINNED_ENV,
    });
  });

  it('logs a no-access 404 ONCE per repo instead of once per poll', async () => {
    // #7540: permanent until credentials change, so the watcher must not narrate
    // it every scheduler tick — and must still report the poll as failed.
    __resetForgeNoAccessLog();
    getOriginInfoMock.mockResolvedValue({ host: 'github.com', fullName: 'example/project', hasOrigin: true });
    execGhMock.mockRejectedValue(Object.assign(
      new Error("GraphQL: Could not resolve to a Repository with the name 'example/project'. (repository)"),
      { ghExitCode: 1, ghNoAccess: true }
    ));
    const errors = vi.spyOn(console, 'error').mockImplementation(() => {});

    const first = await checkPullRequests(app);
    const second = await checkPullRequests(app);

    expect(first).toMatchObject({ ok: false, reason: 'default-branch-unresolved' });
    expect(second).toMatchObject({ ok: false, reason: 'default-branch-unresolved' });
    const noAccessLines = errors.mock.calls
      .map(([line]) => String(line))
      .filter((line) => line.includes('not visible to the gh account'));
    expect(noAccessLines).toHaveLength(1);
    expect(noAccessLines[0]).toContain('Forge account');
    errors.mockRestore();
  });

  it('refreshes authority every poll and pins repository and permission queries to the enterprise host', async () => {
    forge([rawPr(10, 'collaborator')], { host: 'github.enterprise.example' });
    expect((await checkPullRequests(app)).newPrs).toHaveLength(1);
    expect(execGhMock.mock.calls.filter(([a]) => a[0] === 'api').every(([a]) => a.includes('github.enterprise.example'))).toBe(true);
    expect(execGhMock.mock.calls.filter(([a]) => a.includes('--repo')).every(([a]) => a.includes('github.enterprise.example/example/project'))).toBe(true);
    expect(execGhMock.mock.calls
      .filter(([a]) => a[0] === 'repo' || (a[0] === 'pr' && a[1] === 'list'))
      .every(([, , options]) => options?.backoffKey === 'github.enterprise.example/example/project')).toBe(true);
    forge([rawPr(10, 'collaborator')], { permission: 'read' });
    expect((await checkPullRequests(app)).newPrs).toEqual([]);
    execGhMock.mockImplementation(async args => args[0] === 'repo' ? 'main' : args[0] === 'pr' ? JSON.stringify([rawPr(10, 'collaborator')]) : Promise.reject(new Error('unavailable')));
    expect((await checkPullRequests(app)).newPrs).toEqual([]);
  });

  it('does not advance state after unsupported forge, unreachable, malformed or truncated input', async () => {
    getOriginInfoMock.mockResolvedValue({ host: 'gitlab.example.com', fullName: 'example/project' });
    expect(await checkPullRequests(app)).toMatchObject({ ok: false, reason: 'not-a-github-repo' });
    forge([]);
    ensureForgeReachableMock.mockResolvedValueOnce({ ok: false, status: 'unreachable' });
    expect(await checkPullRequests(app)).toMatchObject({ ok: false, reason: 'forge-unreachable' });
    execGhMock.mockImplementation(async args => args[0] === 'repo' ? 'main' : '{}');
    expect(await checkPullRequests(app)).toMatchObject({ ok: false, reason: 'pr-list-failed' });
    forge(Array.from({ length: 200 }, (_, i) => rawPr(i + 1, 'operator')));
    expect(await checkPullRequests(app)).toMatchObject({ ok: false, reason: 'too-many-open-prs' });
  });
});