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

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

// This suite tests the real instances.js implementation — cancel the global
// vitest.setup.js mock so the real getPeers (and all other exports) are used.
// The global mock stubs getPeers → [] to prevent live peer fan-out in tests
// that create records; here we instead mock instances.js's own dependencies
// (fileUtils, asyncMutex, etc.) to make the real code deterministic.
vi.unmock('./instances.js');

// Mock dependencies before importing the module
vi.mock('fs/promises', () => ({
  writeFile: vi.fn().mockResolvedValue(undefined),
  rename: vi.fn().mockResolvedValue(undefined)
}));

vi.mock('../lib/fileUtils.js', async (importOriginal) => ({
  ...(await importOriginal()),
  tryReadFile: vi.fn().mockResolvedValue(null),
  dataPath: (name) => `/mock/data/${name}`,
  readJSONFile: vi.fn(),
  ensureDir: vi.fn().mockResolvedValue(undefined),
  atomicWrite: vi.fn().mockResolvedValue(undefined),
  PATHS: { data: '/mock/data' }
}));

vi.mock('../lib/asyncMutex.js', () => ({
  createMutex: () => (fn) => fn()
}));

vi.mock('dns/promises', () => ({ default: { lookup: vi.fn() } }));
vi.mock('./instanceEvents.js', () => ({
  instanceEvents: {
    emit: vi.fn()
  }
}));

vi.mock('./peerSocketRelay.js', () => ({
  connectToPeer: vi.fn(),
  disconnectFromPeer: vi.fn()
}));

vi.mock('./tailcatPeer.js', () => ({
  stopForwardForPeer: vi.fn().mockResolvedValue(undefined),
  listTailcatForwards: vi.fn().mockResolvedValue([]),
  attachTailcatForwardsToPeers: async (peers) => peers,
  attachTailcatForwardToPeer: async (peer) => peer,
}));

vi.mock('../lib/ports.js', () => ({
  DEFAULT_PEER_PORT: 5555
}));

vi.mock('../lib/tailscale.js', () => ({
  getTailscaleStatus: vi.fn()
}));

// fetch is stubbed per-test in beforeEach and restored in afterEach

import dns from 'dns/promises';
import { stopForwardForPeer } from './tailcatPeer.js';
import { readJSONFile, atomicWrite } from '../lib/fileUtils.js';
import { getTailscaleStatus } from '../lib/tailscale.js';
import { instanceEvents } from './instanceEvents.js';
import { connectToPeer, disconnectFromPeer } from './peerSocketRelay.js';
import { peerBaseUrl } from '../lib/peerUrl.js';
import {
  getPeers,
  getAssignableInstances,
  addPeer,
  peerLogLabel,
  removePeer,
  updatePeer,
  pairPeerSyncSecret,
  acceptPeerSyncSecretFromPeer,
  setPeerSchemaGap,
  probePeer,
  probeAllPeers,
  queryPeer,
  handleAnnounce,
  redactPeerForWire,
  sanitizePeerForClient,
  resolveEffectiveCategories,
  applyReciprocalSync,
  requestReciprocalSync,
  enqueueReciprocalSync,
  DEFAULT_SYNC_CATEGORIES,
  startPolling,
  stopPolling,
  __resetPeersSeenOnlineForTests,
  __resetPeerWakesForTests,
  BACKOFF_TIERS_MS,
  PEER_WAKE_RATE_LIMIT_MS,
  shouldWakePeer,
  wakePeerProbe
} from './instances.js';

describe('instances.js', () => {
  beforeEach(() => {
    vi.clearAllMocks();
    __resetPeersSeenOnlineForTests();
    __resetPeerWakesForTests();
    vi.useFakeTimers();
    vi.stubGlobal('fetch', vi.fn());
    dns.lookup.mockResolvedValue([]);
    readJSONFile.mockResolvedValue({ self: null, peers: [] });
    getTailscaleStatus.mockResolvedValue({ available: true, running: true, state: 'Running', reason: 'running' });
  });

  afterEach(() => {
    stopPolling();
    vi.useRealTimers();
    vi.unstubAllGlobals();
  });

  // --- Self Identity is services/instanceIdentity.test.js (#6836) ---

  // --- Assignable instances (#4520) ---

  describe('getAssignableInstances', () => {
    it('lists self plus every enabled full-sync peer that has advertised an identity', async () => {
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'self-id', name: 'workstation' },
        peers: [
          { id: 'p1', instanceId: 'peer-id', name: 'render-box', address: '192.0.2.10', fullSync: true, enabled: true },
          // Never probed: no federation identity yet, so pinning to it would
          // strand the task unrunnable on every peer.
          { id: 'p2', instanceId: null, name: 'not-yet-connected', address: '192.0.2.11', fullSync: true }
        ]
      });
      expect(await getAssignableInstances()).toEqual([
        { instanceId: 'self-id', name: 'workstation', isSelf: true },
        { instanceId: 'peer-id', name: 'render-box', isSelf: false }
      ]);
    });

    it('omits peers the CoS task sweep never reaches (not full-sync, or disabled)', async () => {
      // peerCosSync only sweeps `fullSync === true && enabled !== false` peers, so
      // pinning to any other peer strands the task: it never leaves this machine,
      // and this machine skips it for being pinned elsewhere.
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'self-id', name: 'workstation' },
        peers: [
          { id: 'p1', instanceId: 'category-sync-peer', name: 'partial', fullSync: false, enabled: true },
          { id: 'p2', instanceId: 'disabled-peer', name: 'paused', fullSync: true, enabled: false },
          { id: 'p3', instanceId: 'legacy-peer', name: 'legacy-no-flag' }
        ]
      });
      expect(await getAssignableInstances()).toEqual([
        { instanceId: 'self-id', name: 'workstation', isSelf: true }
      ]);
    });

    it('is empty before this install has an identity of its own', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      expect(await getAssignableInstances()).toEqual([]);
    });

    it('falls back to a peer address, then its id, when the peer is unnamed', async () => {
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'self-id', name: 'workstation' },
        peers: [
          { id: 'p1', instanceId: 'peer-a', name: '', address: '192.0.2.10', fullSync: true },
          { id: 'p2', instanceId: 'peer-b', name: '', address: '', fullSync: true }
        ]
      });
      const assignable = await getAssignableInstances();
      expect(assignable.map(i => i.name)).toEqual(['workstation', '192.0.2.10', 'peer-b']);
    });
  });

  // --- Peer CRUD ---

  describe('getPeers', () => {
    it('should return peers array', async () => {
      const peers = [{ id: '1', address: '10.0.0.1' }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await getPeers();

      expect(result).toEqual(peers);
    });

    it('should return empty array when no peers', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      const result = await getPeers();

      expect(result).toEqual([]);
    });
  });

  describe('peerLogLabel', () => {
    it('uses anonymous cycle ordinals without exposing peer identity', () => {
      expect(peerLogLabel()).toBe('peer');
      expect(peerLogLabel(0)).toBe('peer 1');
      expect(peerLogLabel(1)).toBe('peer 2');
      expect(peerLogLabel({ name: 'Example Machine', host: 'peer.example', address: '192.0.2.20', instanceId: 'abc123def456' })).toBe('peer');
    });
  });

  describe('addPeer', () => {
    it('persists the tailcat protocol without changing classic peer records', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      const secure = await addPeer({ address: '127.0.0.1', port: 15555, transport: 'tailcat', protocol: 'https' });
      const plain = await addPeer({ address: '127.0.0.1', port: 15556, transport: 'tailcat' });
      const classic = await addPeer({ address: '192.0.2.10', protocol: 'https' });

      expect(secure).toMatchObject({ transport: 'tailcat', protocol: 'https' });
      expect(plain).toMatchObject({ transport: 'tailcat', protocol: 'http' });
      expect(classic).not.toHaveProperty('protocol');
      expect(atomicWrite).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({ peers: [secure, plain, classic] }));
    });

    it('logs and skips the self-announce when instances data becomes unreadable (#12978)', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      const writesBefore = atomicWrite.mock.calls.length;
      // addPeer persists first; only the fire-and-forget announce reads afterwards.
      readJSONFile.mockImplementation(async () => {
        if (atomicWrite.mock.calls.length > writesBefore) throw new Error('EIO: read failed');
        return { self: null, peers: [] };
      });
      const log = vi.spyOn(console, 'log').mockImplementation(() => {});
      const unhandled = vi.fn();
      process.on('unhandledRejection', unhandled);
      try {
        await addPeer({ address: '192.0.2.30' });
        // Suite may run fake timers: flush microtasks instead of sleeping.
        for (let i = 0; i < 20; i++) await Promise.resolve();
        expect(log).toHaveBeenCalledWith(expect.stringContaining('Announce skipped'));
        expect(unhandled).not.toHaveBeenCalled();
      } finally {
        process.off('unhandledRejection', unhandled);
        log.mockRestore();
      }
    });

    it('should add a peer with correct defaults', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.2', name: 'remote-host' });

      expect(peer).toMatchObject({
        id: expect.any(String),
        address: '10.0.0.2',
        port: 5555,
        name: 'remote-host',
        instanceId: null,
        status: 'unknown',
        enabled: true,
        mediaProvider: { enabled: false, audioModels: [] },
        directions: ['outbound']
      });
      expect(peer.addedAt).toBeDefined();
      expect(instanceEvents.emit).toHaveBeenCalledWith('peers:updated', expect.any(Array));
    });

    it('should use address as name when name is not provided', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.3' });

      expect(peer.name).toBe('10.0.0.3');
    });

    it('should accept names like null/undefined/NaN as valid hostnames', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.4', name: 'null' });

      expect(peer.name).toBe('null');
    });

    it('should use custom port when specified', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.5', port: 8080 });

      expect(peer.port).toBe(8080);
    });

    it('should default hostManual to false when no host provided (allow auto-learn)', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.6' });

      expect(peer.host).toBeNull();
      expect(peer.hostManual).toBe(false);
    });

    it('should latch hostManual when host is provided at add time', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.7', host: 'host-delta.example-tailnet.ts.net' });

      expect(peer.host).toBe('host-delta.example-tailnet.ts.net');
      expect(peer.hostManual).toBe(true);
    });

    it('should default auth to null when no credential is provided', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.8' });

      expect(peer.auth).toBeNull();
    });

    it('should store a sanitized credential when provided', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.9', auth: { username: '  alice  ', password: 's3cret' } });

      expect(peer.auth).toEqual({ username: 'alice', password: 's3cret' });
    });

    it('should treat a blank credential as no auth', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.10', auth: { username: '', password: '' } });

      expect(peer.auth).toBeNull();
    });

    it('should store a password-only credential (username defaults to "")', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.11', auth: { password: 'tok3n' } });

      expect(peer.auth).toEqual({ username: '', password: 'tok3n' });
    });

    it('should ignore a username-only payload (no blank-password store)', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));

      const peer = await addPeer({ address: '10.0.0.12', auth: { username: 'alice' } });

      // A username-only payload (e.g. a redacted client peer round-tripped back)
      // must not store a blank-password credential — it's ignored, so a new peer
      // is left with no auth.
      expect(peer.auth).toBeNull();
    });
  });

  describe('removePeer', () => {
    it('should remove existing peer by id', async () => {
      const peers = [
        { id: 'peer-1', name: 'host1', address: '10.0.0.1' },
        { id: 'peer-2', name: 'host2', address: '10.0.0.2' }
      ];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const removed = await removePeer('peer-1');

      expect(removed).toMatchObject({ id: 'peer-1', name: 'host1' });
      expect(stopForwardForPeer).not.toHaveBeenCalled();
      expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');
      expect(instanceEvents.emit).toHaveBeenCalledWith('peers:updated', expect.any(Array));
    });

    it('keeps a tailcat peer recoverable when forward retirement fails, then removes it on retry', async () => {
      const peer = { id: 'tailcat-peer', transport: 'tailcat', address: '127.0.0.1', port: 15555 };
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });
      stopForwardForPeer.mockRejectedValueOnce(new Error('forward metadata write failed'));

      await expect(removePeer(peer.id)).rejects.toThrow('forward metadata write failed');
      expect(peers).toEqual([peer]);
      expect(atomicWrite).not.toHaveBeenCalled();

      await expect(removePeer(peer.id)).resolves.toEqual(peer);
      expect(stopForwardForPeer).toHaveBeenCalledWith(peer.id);
      expect(peers).toEqual([]);
    });

    it('allows transport-owned rollback without re-entering transport cleanup', async () => {
      const peer = { id: 'tailcat-peer', transport: 'tailcat' };
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });

      await expect(removePeer(peer.id, { stopTransport: false })).resolves.toEqual(peer);
      expect(stopForwardForPeer).not.toHaveBeenCalled();
    });

    it('should return null for non-existent peer', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      const removed = await removePeer('non-existent');

      expect(removed).toBeNull();
      expect(disconnectFromPeer).toHaveBeenCalledWith('non-existent');
    });
  });

  it('pairing a legacy peer preserves its outbound relationship', async () => {
    const peer = { id: 'legacy-peer', instanceId: 'peer-a', enabled: true, syncEnabled: false };
    readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });
    await updatePeer('legacy-peer', { syncSecret: 'synthetic-pair-secret-32-characters-long' });
    expect(peer.directions).toEqual(['outbound', 'inbound']);
    expect(peer.syncEnabled).toBe(false);
  });

  describe('redactPeerForWire', () => {
    it('strips credentials and local media-routing state before a peer crosses the wire', () => {
      const peer = {
        id: 'peer-1',
        name: 'host',
        auth: { username: 'a', password: 'b' },
        syncSecret: 'synthetic-pair-secret-32-characters-long',
        mediaProvider: { enabled: true, audioModels: [{ engine: 'example', modelId: 'example' }] },
        mediaProviderStatus: { state: 'ready' },
        status: 'online',
      };
      const redacted = redactPeerForWire(peer);

      expect(redacted).not.toHaveProperty('auth');
      expect(redacted).not.toHaveProperty('syncSecret');
      expect(sanitizePeerForClient(peer)).not.toHaveProperty('syncSecret');
      expect(sanitizePeerForClient(peer).hasSyncSecret).toBe(true);
      expect(redacted).not.toHaveProperty('mediaProvider');
      expect(redacted).not.toHaveProperty('mediaProviderStatus');
      expect(redacted).toMatchObject({ id: 'peer-1', name: 'host', status: 'online' });
      // Does not mutate the original
      expect(peer.auth).toEqual({ username: 'a', password: 'b' });
    });

    it('is a no-op for a peer without auth', () => {
      const peer = { id: 'peer-1', name: 'host' };
      expect(redactPeerForWire(peer)).toBe(peer);
    });
  });

  // handleAnnounce auto-creates an inbound-only peer for ANY host that can reach
  // the port — no approval step, and auth is off by default. A default-ON
  // category must not reach those, or announcing would be enough to get a
  // stranger's numbers pulled into this install's fleet report.
  describe('resolveEffectiveCategories — default-ON scope', () => {
    it('does not default a category on for an unapproved announce peer', () => {
      const announced = { id: 'p1', directions: ['inbound'], syncEnabled: false };
      expect(resolveEffectiveCategories(announced).usage).toBe(false);
    });

    it('does default it on for a peer the user added here', () => {
      expect(resolveEffectiveCategories({ id: 'p1', directions: ['outbound'] }).usage).toBe(true);
      // A legacy record with no directions array stays permissive.
      expect(resolveEffectiveCategories({ id: 'p2' }).usage).toBe(true);
    });

    it('honors an explicit opt-IN on an announce peer — that is a user decision', () => {
      const announced = { id: 'p1', directions: ['inbound'], syncCategories: { usage: true } };
      expect(resolveEffectiveCategories(announced).usage).toBe(true);
    });
  });

  // Video-history rows are the metadata half of Media Collections — one toggle.
  describe('resolveEffectiveCategories — videoHistory folded into mediaCollections', () => {
    it('implies videoHistory whenever mediaCollections is on', () => {
      const peer = { id: 'p1', syncCategories: { mediaCollections: true, videoHistory: false } };
      expect(resolveEffectiveCategories(peer)).toMatchObject({ mediaCollections: true, videoHistory: true });
    });

    it('keeps a legacy videoHistory-only peer syncing, and adds nothing when both are off', () => {
      expect(resolveEffectiveCategories({ id: 'p1', syncCategories: { videoHistory: true } }))
        .toMatchObject({ mediaCollections: false, videoHistory: true });
      expect(resolveEffectiveCategories({ id: 'p2', syncCategories: {} }))
        .toMatchObject({ mediaCollections: false, videoHistory: false });
    });
  });

  describe('sanitizePeerForClient', () => {
    it('never exposes a legacy tailcat capability on either wire surface', () => {
      const peer = { id: 'peer-example', tcAddress: 'tcEXAMPLE' + 'A'.repeat(40) };
      expect(sanitizePeerForClient(peer)).not.toHaveProperty('tcAddress');
      expect(redactPeerForWire(peer)).not.toHaveProperty('tcAddress');
    });

    // The sync path layers DEFAULT_SYNC_CATEGORIES *under* the stored map so a
    // peer record written before a category existed picks up its shipped default
    // with no migration. Shipping the RAW map to the client would render a
    // default-ON category's checkbox off while the server actively syncs it.
    it('resolves the effective category map so the UI matches what actually syncs', () => {
      const sanitized = sanitizePeerForClient({ id: 'p1', syncCategories: { brain: true } });
      expect(sanitized.syncCategories.brain).toBe(true);
      expect(sanitized.syncCategories.usage).toBe(true);   // default-ON, absent from the stored map
      expect(sanitized.syncCategories.goals).toBe(false);
    });

    it('lets an explicit opt-out survive the default merge', () => {
      const sanitized = sanitizePeerForClient({ id: 'p1', syncCategories: { usage: false } });
      expect(sanitized.syncCategories.usage).toBe(false);
    });

    // The UI renders syncEnabled separately, so the payload shows what the user
    // CONFIGURED. Masking here would render every box on a syncEnabled:false peer
    // unchecked, and ticking one would silently reactivate the rest.
    it('shows the configured selection on a peer whose master switch is off', () => {
      const sanitized = sanitizePeerForClient({
        id: 'p1', syncEnabled: false, syncCategories: { brain: true, universe: true },
      });
      expect(sanitized.syncCategories.brain).toBe(true);
      expect(sanitized.syncCategories.universe).toBe(true);
    });

    it('redacts the password to a hasPassword marker but keeps the username', () => {
      const peer = { id: 'peer-1', name: 'host', auth: { username: 'alice', password: 'secret' }, status: 'online' };
      const sanitized = sanitizePeerForClient(peer);

      expect(sanitized.auth).toEqual({ username: 'alice', hasPassword: true });
      expect(sanitized.auth.password).toBeUndefined();
      expect(sanitized).toMatchObject({ id: 'peer-1', status: 'online' });
      // Original (server-side record) keeps the real password
      expect(peer.auth.password).toBe('secret');
    });

    it('leaves a credential-less peer\'s credential alone', () => {
      const peer = { id: 'peer-1', name: 'host', auth: null };
      const sanitized = sanitizePeerForClient(peer);
      expect(sanitized.auth).toBeNull();
      expect(sanitized.id).toBe('peer-1');
    });
  });

  describe('updatePeer', () => {
    it('should update peer name', async () => {
      const peers = [{ id: 'peer-1', name: 'old-name', enabled: true }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { name: 'new-name' });

      expect(result.name).toBe('new-name');
    });

    it('stores the media sync mode and ignores an unknown one', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', name: 'host', enabled: true }] });
      expect((await updatePeer('peer-1', { mediaSyncMode: 'host' })).mediaSyncMode).toBe('host');
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', name: 'host', enabled: true, mediaSyncMode: 'host' }] });
      expect((await updatePeer('peer-1', { mediaSyncMode: 'stream-everything' })).mediaSyncMode).toBe('host');
    });

    it('should update peer enabled state', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { enabled: false });

      expect(result.enabled).toBe(false);
      expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');
    });

    it('should return null for non-existent peer', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      const result = await updatePeer('missing', { name: 'x' });

      expect(result).toBeNull();
    });

    it('should accept names like undefined as valid hostnames', async () => {
      const peers = [{ id: 'peer-1', name: 'good-name', enabled: true }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { name: 'undefined' });

      expect(result.name).toBe('undefined');
    });

    it('should set a credential on a peer', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: null }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { auth: { username: 'bob', password: 'pw' } });

      expect(result.auth).toEqual({ username: 'bob', password: 'pw' });
    });

    it('should clear a credential when auth is null', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { auth: null });

      expect(result.auth).toBeNull();
    });

    it('should ignore a malformed auth value rather than wiping a working credential', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { auth: 'not-an-object' });

      expect(result.auth).toEqual({ username: 'bob', password: 'pw' });
    });

    it('should ignore a username-only payload rather than wiping a working password', async () => {
      // The client only ever receives a redacted peer ({ username, hasPassword }).
      // Round-tripping that shape back into a PATCH sends auth.username with no
      // password — it must not clear the stored secret with a blank password.
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { auth: { username: 'bob' } });

      expect(result.auth).toEqual({ username: 'bob', password: 'pw' });
      expect(disconnectFromPeer).not.toHaveBeenCalled();
    });

    it('should reconnect the relay and re-probe immediately when the credential changes', async () => {
      // Peer is deep in backoff from prior 401s — the new credential must
      // trigger an immediate probe, not wait out nextProbeAt.
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, status: 'offline', consecutiveFailures: 5, nextProbeAt: '2999-01-01T00:00:00Z', auth: { username: 'bob', password: 'old' } }];
      readJSONFile.mockResolvedValue({ self: null, peers });
      fetch.mockRejectedValue(new Error('offline'));

      await updatePeer('peer-1', { auth: { username: 'bob', password: 'new' } });

      // Relay pins the Basic header at connect time, so a credential change
      // must tear it down to reconnect with the new extraHeaders.
      expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');
      // Immediate re-probe fired (bypasses the nextProbeAt backoff gate). The
      // probe is fire-and-forget and now resolves our instanceId (one extra
      // microtask) before fetching sync-status, so wait for the fetch.
      await vi.waitFor(() => expect(fetch).toHaveBeenCalled());
    });

    it('should NOT reconnect or re-probe on a no-op credential write', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, auth: { username: 'bob', password: 'pw' } }];
      readJSONFile.mockResolvedValue({ self: null, peers });
      fetch.mockRejectedValue(new Error('offline'));

      await updatePeer('peer-1', { auth: { username: 'bob', password: 'pw' } });

      expect(disconnectFromPeer).not.toHaveBeenCalled();
      expect(fetch).not.toHaveBeenCalled();
    });

    it('should not disconnect when enabling a peer', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: false }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      await updatePeer('peer-1', { enabled: true });

      expect(disconnectFromPeer).not.toHaveBeenCalled();
    });

    it('stores a disabled remote-media allowlist while preserving future config fields', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', {
        mediaProvider: {
          enabled: false,
          futureField: 'keep',
          audioModels: [{ engine: ' minimax-music3 ', modelId: 'minimax-music3', futureModel: 'keep-too' }],
        },
      });

      expect(result.mediaProvider).toEqual({
        enabled: false,
        futureField: 'keep',
        audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3', futureModel: 'keep-too' }],
        imageModels: [],
        videoModels: [],
      });
      expect(fetch).not.toHaveBeenCalled();
    });

    it('should set a valid DNS host and disconnect the relay so it reconnects via HTTPS', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: null }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { host: 'host-alpha.example-tailnet.ts.net' });

      expect(result.host).toBe('host-alpha.example-tailnet.ts.net');
      expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');
    });

    it('should clear host when empty string is passed', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'old.example.com' }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { host: '' });

      expect(result.host).toBeNull();
    });

    it('should latch hostManual when user explicitly sets host', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: null, hostManual: false }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { host: 'host-delta.example-tailnet.ts.net' });

      expect(result.host).toBe('host-delta.example-tailnet.ts.net');
      expect(result.hostManual).toBe(true);
    });

    it('should latch hostManual when user explicitly clears host (the un-revert bug)', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'host-delta.example-tailnet.ts.net', hostManual: false }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { host: '' });

      expect(result.host).toBeNull();
      expect(result.hostManual).toBe(true);
    });

    it('should ignore invalid host (leave unchanged)', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'good.example.com' }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const result = await updatePeer('peer-1', { host: 'bad!!host' });

      expect(result.host).toBe('good.example.com');
    });

    it('should not disconnect the relay when host is invalid or unchanged', async () => {
      const peers = [{ id: 'peer-1', name: 'host', enabled: true, host: 'same.example.com' }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      await updatePeer('peer-1', { host: 'same.example.com' });
      expect(disconnectFromPeer).not.toHaveBeenCalled();

      await updatePeer('peer-1', { host: 'bad!!host' });
      expect(disconnectFromPeer).not.toHaveBeenCalled();
    });
  });

  // --- Bidirectional sync reciprocation ---

  describe('applyReciprocalSync', () => {
    it('mirrors a peer\'s enabled categories onto our local record for that peer', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: false, goals: false } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { changed, peer } = await applyReciprocalSync('inst-A', { brain: true });

      expect(changed).toBe(true);
      expect(peer.syncCategories.brain).toBe(true);
      expect(peer.syncEnabled).toBe(true); // recomputed from the resulting map
      expect(peer._reciprocalChanged).toBeUndefined(); // no transient marker leaks onto the record
      // And the persisted payload must not carry any transient marker either.
      const written = atomicWrite.mock.calls.at(-1)?.[1];
      expect(written.peers[0]._reciprocalChanged).toBeUndefined();
    });

    it('is a no-op (changed:false) when our record already matches — the echo guard', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { changed } = await applyReciprocalSync('inst-A', { brain: true });

      expect(changed).toBe(false);
    });

    it('echo guard treats absent-vs-false alike: adding goals:false to a partial map is a no-op', async () => {
      // prev is a partial map missing `goals`; incoming sets goals:false, which
      // is already the effective state → must NOT report changed (the baseline
      // is defaulted so `false !== undefined` can't spuriously trip the guard).
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { changed } = await applyReciprocalSync('inst-A', { goals: false });

      expect(changed).toBe(false);
    });

    // `usage` is the one default-ON category. `syncEnabled` is derived from the
    // category map AND gates per-record outbound pushes (peerAllowsOutbound), so
    // a default-ON category must never flip it on by itself — otherwise adding
    // one would silently widen what every existing peer may receive.
    // The client used to compute syncEnabled itself by summing the whole category
    // map — which reads a default-ON category as "something is enabled" and
    // widens the peer's outbound push consent (peerAllowsOutbound). syncEnabled
    // is DERIVED, so a syncCategories edit recomputes it and ignores the value
    // a caller sent alongside.
    it('recomputes syncEnabled from the categories, ignoring a caller-sent value', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true, usage: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const peer = await updatePeer('p1', { syncCategories: { brain: false }, syncEnabled: true });

      expect(peer.syncCategories.usage).toBe(true);
      expect(peer.syncEnabled).toBe(false);
    });

    it('a default-ON category alone does not flip syncEnabled on', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { peer } = await applyReciprocalSync('inst-A', { brain: false, usage: true });

      expect(peer.syncCategories.usage).toBe(true);
      expect(peer.syncEnabled).toBe(false); // no CONTENT category left enabled
    });

    it('applies an all-false map to clear a stale enabled category (the offline-disable recovery path)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { changed, peer } = await applyReciprocalSync('inst-A', { brain: false });

      expect(changed).toBe(true);
      expect(peer.syncCategories.brain).toBe(false);
      expect(peer.syncEnabled).toBe(false); // nothing left enabled
    });

    it('full-mirror is intentional: a peer\'s category:false disables a category we independently enabled (issue #1094)', async () => {
      // Decision (issue #1094): sync categories are a symmetric full mirror, not
      // two strictly-independent per-direction switches. So when a peer announces
      // `{ goals: false }` (e.g. via 'Make mutual' pushing its current set), it
      // DISABLES goals on our record for that peer even though we had enabled it
      // toward them independently. This pins that behavior so a future refactor to
      // enable-only reciprocation can't silently regress 'Make mutual' / the
      // offline-disable recovery path without tripping this test.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true, goals: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { changed, peer } = await applyReciprocalSync('inst-A', { goals: false });

      expect(changed).toBe(true);
      expect(peer.syncCategories.goals).toBe(false); // announced false is authoritative — clobbers our independent enable
      expect(peer.syncCategories.brain).toBe(true);  // omitted keys preserved untouched
      expect(peer.syncEnabled).toBe(true);           // brain still on
    });

    it('returns changed:false for an unknown peer instanceId', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });
      const { changed, peer } = await applyReciprocalSync('nope', { brain: true });
      expect(changed).toBe(false);
      expect(peer).toBeNull();
    });

    it('drops unknown/garbage category keys (only DEFAULT_SYNC_CATEGORIES keys applied)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: false } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });

      const { peer } = await applyReciprocalSync('inst-A', { brain: true, __proto__: true, bogus: true });

      expect(peer.syncCategories.brain).toBe(true);
      expect(peer.syncCategories.bogus).toBeUndefined();
    });

    it('ignores a non-object categories payload', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });
      const { changed } = await applyReciprocalSync('inst-A', 'not-an-object');
      expect(changed).toBe(false);
    });
  });

  describe('requestReciprocalSync', () => {
    it('POSTs our self instanceId + sanitized categories to the peer', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me-id', name: 'me' }, peers: [] });
      const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
      vi.stubGlobal('fetch', fetchMock);

      const result = await requestReciprocalSync(
        { id: 'p1', address: '10.0.0.2', port: 5555, name: 'B' },
        { brain: true, bogus: true }
      );

      expect(result.ok).toBe(true);
      expect(fetchMock).toHaveBeenCalledTimes(1);
      const [url, opts] = fetchMock.mock.calls[0];
      expect(url).toContain('/api/instances/peers/sync-categories');
      const body = JSON.parse(opts.body);
      expect(body.instanceId).toBe('me-id');
      expect(body.syncCategories).toEqual({ brain: true }); // bogus dropped
    });

    it('returns ok:false (not throw) when the peer 404s the endpoint (older version)', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me-id' }, peers: [] });
      vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: false, status: 404 }));

      const result = await requestReciprocalSync(
        { id: 'p1', address: '10.0.0.2', port: 5555, name: 'B' },
        { brain: true }
      );

      expect(result.ok).toBe(false);
      expect(result.reason).toBe('http-404');
    });

    it('returns ok:false when we have no self identity', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      const result = await requestReciprocalSync({ id: 'p1', address: '10.0.0.2', port: 5555 }, { brain: true });
      expect(result.ok).toBe(false);
      expect(result.reason).toBe('no-self-identity');
    });
  });

  describe('enqueueReciprocalSync', () => {
    it('reads the FRESHEST persisted categories at send time (last enqueue wins, not enqueue-time snapshot)', async () => {
      // readJSONFile is re-read on each send; point it at the latest map so the
      // serialized send carries final state regardless of when it was enqueued.
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'me-id' },
        peers: [{ id: 'p1', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true, goals: true } }]
      });
      const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
      vi.stubGlobal('fetch', fetchMock);

      await enqueueReciprocalSync('p1');

      const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
      expect(body.syncCategories).toEqual({ brain: true, goals: true });
    });

    it('serializes per peer so sends leave in enqueue order (no stale-map race)', async () => {
      // Unique peer id so the module-level per-peer tail can't chain onto another
      // test's queue. The second send resolves immediately; the first blocks on
      // resolveFirst. If sends raced, order would be ['second', 'first']; ordered
      // serialization yields ['first', 'second'].
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'me-id' },
        peers: [{ id: 'p-serial', instanceId: 'inst-A', name: 'A', syncCategories: { brain: true } }]
      });
      const order = [];
      let resolveFirst;
      let firstReachedFetch;
      const firstFetchStarted = new Promise(r => { firstReachedFetch = r; });
      const fetchMock = vi.fn()
        .mockImplementationOnce(() => new Promise(r => {
          resolveFirst = () => { order.push('first'); r({ ok: true, status: 200 }); };
          firstReachedFetch();
        }))
        .mockImplementationOnce(async () => { order.push('second'); return { ok: true, status: 200 }; });
      vi.stubGlobal('fetch', fetchMock);

      const p1 = enqueueReciprocalSync('p-serial');
      const p2 = enqueueReciprocalSync('p-serial');
      // The second send resolves immediately; the first blocks until we release
      // it. If the two ran concurrently (unserialized), 'second' would land
      // first. Wait for the first send to signal it reached its (blocked) fetch —
      // a deterministic signal, independent of how many awaits precede fetch —
      // then release it; the recorded order proves serialization.
      await firstFetchStarted;
      resolveFirst();
      await Promise.all([p1, p2]);
      expect(order).toEqual(['first', 'second']);
    });

    it('no-ops cleanly for a peer that lost its instanceId', async () => {
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'me-id' },
        peers: [{ id: 'p-noinst', name: 'A', syncCategories: { brain: true } }] // no instanceId
      });
      vi.stubGlobal('fetch', vi.fn());
      const result = await enqueueReciprocalSync('p-noinst');
      expect(result.ok).toBe(false);
      expect(result.reason).toBe('no-peer-identity');
    });

    it('a full-sync peer reciprocates the ALL-ON category view + the fullSync flag (not its raw all-false map)', async () => {
      // A full-sync peer mirrors everything; its stored syncCategories can be
      // all-false underneath. Sending that raw would tell the peer to DISABLE
      // everything (reciprocal apply is an authoritative overlay). It must send
      // every category on, plus fullSync:true so a new-enough peer adopts mirror
      // mode too.
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'me-id' },
        peers: [{ id: 'p-full', instanceId: 'inst-A', name: 'A', fullSync: true, syncCategories: { brain: false } }]
      });
      const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
      vi.stubGlobal('fetch', fetchMock);

      await enqueueReciprocalSync('p-full');

      const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
      expect(body.fullSync).toBe(true);
      // Every category present and true.
      expect(Object.values(body.syncCategories).every(Boolean)).toBe(true);
      expect(body.syncCategories.brain).toBe(true);
      expect(body.syncCategories.tracks).toBe(true);
    });
  });

  describe('fullSync (full-mirror) peer mode', () => {
    it('addPeer defaults fullSync off when no self default is set', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));
      const peer = await addPeer({ address: '10.0.0.9', name: 'p' });
      expect(peer.fullSync).toBe(false);
    });

    it('addPeer inherits the self-side defaultPeerFullSync for new peers', async () => {
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me', defaultPeerFullSync: true }, peers: [] });
      fetch.mockRejectedValue(new Error('not reachable'));
      const peer = await addPeer({ address: '10.0.0.10', name: 'p' });
      expect(peer.fullSync).toBe(true);
      expect(peer.syncEnabled).toBe(true);
    });

    it('updatePeer enabling fullSync implies syncEnabled on', async () => {
      const peers = [{ id: 'p1', name: 'A', enabled: true, fullSync: false, syncEnabled: false, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const result = await updatePeer('p1', { fullSync: true });
      expect(result.fullSync).toBe(true);
      expect(result.syncEnabled).toBe(true);
    });

    it('updatePeer disabling fullSync recomputes syncEnabled from the preserved category map', async () => {
      // brain was on underneath → still sync-enabled after turning mirror off.
      const onPeer = [{ id: 'p1', name: 'A', enabled: true, fullSync: true, syncEnabled: true, syncCategories: { brain: true } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: onPeer });
      const stillOn = await updatePeer('p1', { fullSync: false });
      expect(stillOn.fullSync).toBe(false);
      expect(stillOn.syncEnabled).toBe(true);

      // empty map → nothing left to sync.
      const emptyPeer = [{ id: 'p2', name: 'B', enabled: true, fullSync: true, syncEnabled: true, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers: emptyPeer });
      const off = await updatePeer('p2', { fullSync: false });
      expect(off.syncEnabled).toBe(false);
    });

    it('applyReciprocalSync adopts fullSync even when the category map is empty', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', fullSync: false, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', {}, { fullSync: true });
      expect(changed).toBe(true);
      expect(peer.fullSync).toBe(true);
      expect(peer.syncEnabled).toBe(true);
    });

    it('adopting full mirror via reciprocation preserves the underlying per-category selection', async () => {
      // The sender includes an all-on compat map alongside fullSync:true. A
      // fullSync-aware receiver must NOT overwrite its own selection with it —
      // otherwise a later disable would leave every category on instead of
      // restoring the user's choice (only brain here).
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', fullSync: false, syncCategories: { brain: true } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const allOn = Object.fromEntries(Object.keys(DEFAULT_SYNC_CATEGORIES).map(k => [k, true]));
      const { changed, peer } = await applyReciprocalSync('inst-A', allOn, { fullSync: true });
      expect(changed).toBe(true);
      expect(peer.fullSync).toBe(true);
      expect(peer.syncCategories.brain).toBe(true);
      expect(peer.syncCategories.universe).toBeFalsy(); // not clobbered to true
    });

    it('applyReciprocalSync drops our mirror when the peer reports fullSync:false (disable reciprocation)', async () => {
      // The peer stopped mirroring us — symmetric with the enable path. The
      // preserved per-category map (brain on) becomes authoritative again.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', fullSync: true, syncEnabled: true, syncCategories: { brain: true } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { brain: true }, { fullSync: false });
      expect(changed).toBe(true);
      expect(peer.fullSync).toBe(false);
      expect(peer.syncEnabled).toBe(true); // brain still on underneath
    });

    it('applyReciprocalSync ignores an absent fullSync field (older peer) — mirror untouched', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', fullSync: true, syncEnabled: true, syncCategories: { brain: true } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      // No fullSync key in opts → undefined → must not clear the mirror.
      const { peer } = await applyReciprocalSync('inst-A', { brain: true });
      expect(peer.fullSync).toBe(true);
    });

    // --- Outbound consent on reciprocation (#1636) ---
    // An `/announce`-created peer record is inbound-only until the user here adds
    // it back. peerAllowsOutbound refuses to push to an inbound-only peer, so a
    // reciprocally-enabled per-record category / fullSync would silently never
    // back-subscribe — leaving the "mirror" one-directional. An explicit
    // reciprocal-sync request IS the peer's consent to receive our pushes, so we
    // adopt `outbound` when (and only when) we turn a per-record kind on.

    it('adopts `outbound` on an inbound-only peer when a per-record category is reciprocally enabled (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], syncCategories: { universe: false } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { universe: true });
      expect(changed).toBe(true);
      expect(peer.syncCategories.universe).toBe(true);
      expect(peer.directions).toContain('outbound'); // backfill/push now unblocked
      expect(peer.directions).toContain('inbound');  // existing direction preserved
    });

    it('adopts `outbound` on an inbound-only peer when fullSync is reciprocally adopted (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], fullSync: false, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', {}, { fullSync: true });
      expect(changed).toBe(true);
      expect(peer.fullSync).toBe(true);
      expect(peer.directions).toContain('outbound');
    });

    it('does NOT add `outbound` when the peer reports fullSync:false — a disable is not consent to push (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], fullSync: true, syncEnabled: true, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', {}, { fullSync: false });
      expect(changed).toBe(true);
      expect(peer.fullSync).toBe(false);
      expect(peer.directions).not.toContain('outbound'); // mirror dropped, not widened
    });

    it('leaves directions untouched when only a snapshot category (no per-record kind) is reciprocated (#1636)', async () => {
      // brain/goals sync via the snapshot path, which does not gate on directions —
      // so there is no backfill to unblock and no reason to widen consent.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], syncCategories: { brain: false } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { brain: true });
      expect(changed).toBe(true);
      expect(peer.syncCategories.brain).toBe(true);
      expect(peer.directions).toEqual(['inbound']); // not widened to outbound
    });

    it('does not duplicate `outbound` when the peer record already pushes — idempotent (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound', 'outbound'], syncCategories: { universe: false } }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { peer } = await applyReciprocalSync('inst-A', { universe: true });
      expect(peer.directions.filter(d => d === 'outbound')).toHaveLength(1);
    });

    it('heals a pre-existing inbound-only record that already adopted fullSync — a re-sent request with no flip still adopts outbound (#1636)', async () => {
      // The population this issue exists to fix: a record that adopted fullSync (or
      // categories) BEFORE the fix landed but stayed inbound-only, so it never
      // back-filled. Nothing flips on a re-sent reciprocal request, so outbound
      // adoption must drive change detection itself or the echo guard returns first.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], fullSync: true, syncEnabled: true, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', {}, { fullSync: true });
      expect(changed).toBe(true);           // NOT echo-guarded — the missing direction is a real change
      expect(peer.fullSync).toBe(true);     // unchanged
      expect(peer.directions).toContain('outbound');
    });

    it('heals a pre-existing inbound-only record with an already-enabled per-record category (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], syncCategories: { universe: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { universe: true });
      expect(changed).toBe(true);
      expect(peer.directions).toContain('outbound');
    });

    it('stays a no-op when a fullSync re-send arrives on a record that already pushes (echo guard intact) (#1636)', async () => {
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound', 'outbound'], fullSync: true, syncEnabled: true, syncCategories: {} }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed } = await applyReciprocalSync('inst-A', {}, { fullSync: true });
      expect(changed).toBe(false); // already outbound + already fullSync → nothing to do
    });

    it('does not adopt outbound (or report changed) for a snapshot-only category that already matches on an inbound-only peer (#1636)', async () => {
      // brain is a snapshot category, not a per-record push kind — it doesn't gate
      // on directions, so there's no backfill to unblock and no consent to widen.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], syncCategories: { brain: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { brain: true });
      expect(changed).toBe(false);
      expect(peer.directions).toEqual(['inbound']);
    });

    it('a snapshot-only reciprocal request does NOT widen outbound just because a per-record category is already enabled locally (#1636)', async () => {
      // Consent is scoped to THIS request: reciprocating `goals` (a snapshot
      // category) must not opportunistically start pushing the locally-enabled
      // `universe` records back — the peer never asked us to mirror universe here.
      const peers = [{ id: 'p1', instanceId: 'inst-A', name: 'A', directions: ['inbound'], syncCategories: { universe: true }, syncEnabled: true }];
      readJSONFile.mockResolvedValue({ self: { instanceId: 'me' }, peers });
      const { changed, peer } = await applyReciprocalSync('inst-A', { goals: true });
      expect(changed).toBe(true);                 // goals (snapshot) was enabled
      expect(peer.syncCategories.goals).toBe(true);
      expect(peer.syncCategories.universe).toBe(true); // preserved
      expect(peer.directions).toEqual(['inbound']);    // NOT widened to outbound
    });

    it('disabling fullSync reciprocates fullSync:false even with an empty category map', async () => {
      // The empty-map case is the one the no-categories send guard used to drop:
      // a just-disabled mirror peer whose underlying syncCategories is empty must
      // STILL POST fullSync:false so the remote learns to drop its mirror.
      readJSONFile.mockResolvedValue({
        self: { instanceId: 'me-id' },
        peers: [{ id: 'p1', instanceId: 'inst-A', name: 'A', enabled: true, fullSync: false, syncCategories: {} }],
      });
      const fetchMock = vi.fn().mockResolvedValue({ ok: true, status: 200 });
      vi.stubGlobal('fetch', fetchMock);
      const result = await enqueueReciprocalSync('p1');
      expect(result.ok).toBe(true);
      expect(fetchMock).toHaveBeenCalledTimes(1);
      const body = JSON.parse(fetchMock.mock.calls.at(-1)[1].body);
      expect(body.fullSync).toBe(false);
      expect(body.syncCategories).toEqual({}); // valid object so the receiver schema parses
    });
    // updateSelf itself (including the defaultPeerFullSync field this block's
    // addPeer tests rely on) is covered by instanceIdentity.test.js (#6836).
  });

  // --- Probing ---

  describe('probePeer', () => {
    const makePeer = (overrides = {}) => ({
      id: 'peer-1',
      address: '10.0.0.1',
      port: 5555,
      name: 'remote',
      status: 'unknown',
      lastSeen: null,
      lastHealth: null,
      lastApps: null,
      remoteSyncSeqs: null,
      enabled: true,
      ...overrides
    });

    it('refuses to probe a DNS host that resolves to loopback or link-local, but probes a tailnet answer', async () => {
      const peer = makePeer({ host: 'rebind.example.com' });
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      for (const address of ['127.0.0.1', '169.254.169.254']) {
        dns.lookup.mockResolvedValueOnce([{ address, family: 4 }]);
        const result = await probePeer(peer);
        expect(result.status).toBe('offline');
        expect(JSON.stringify(result.lastProbe)).toContain('loopback or link-local');
      }

      dns.lookup.mockResolvedValueOnce([{ address: '100.64.0.50', family: 4 }]);
      fetch.mockResolvedValue({ ok: true, json: () => Promise.resolve({ instanceId: 'remote-id' }) });
      const allowed = await probePeer(peer);
      expect(JSON.stringify(allowed.lastProbe)).not.toContain('loopback or link-local');
    });

    it('should mark peer online on successful probe', async () => {
      const peer = makePeer();
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const healthData = { instanceId: 'remote-id', version: '1.0.0', hostname: 'remote-host' };
      const appsData = [{
        id: 'app1', name: 'MyApp', icon: 'package', overallStatus: 'online',
        uiPort: 3000, apiPort: 3001, type: 'express',
      }];

      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(healthData) }) // health
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(appsData) }) // apps
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ seq: 1 }) }); // sync

      const result = await probePeer(peer);

      expect(result.status).toBe('online');
      expect(result.instanceId).toBe('remote-id');
      expect(result.version).toBe('1.0.0');
      expect(result.lastSeen).toBeDefined();
      expect(result.lastApps).toEqual(appsData);
      expect(connectToPeer).toHaveBeenCalledWith(peer);
      expect(fetch).toHaveBeenCalledTimes(3);
      expect(fetch.mock.calls[1][0]).toBe('http://10.0.0.1:5555/api/apps?view=probe');
    });

    it('discovers and persists capacity only for an opted-in media provider peer', async () => {
      const target = makePeer({
        mediaProvider: {
          enabled: true,
          audioModels: [{ engine: 'minimax-music3', modelId: 'minimax-music3' }],
        },
      });
      readJSONFile.mockResolvedValue({ self: null, peers: [target] });
      const providerStatus = {
        wireVersion: 1,
        generatedAt: new Date().toISOString(),
        staleAfterMs: 60_000,
        status: 'ready',
        kinds: ['audio'],
        queue: { totalActive: 0, providerActive: 0, queued: 0, running: 0, maxQueuedJobs: 2, accepting: true },
        capabilities: [{
          kind: 'audio', engine: 'minimax-music3', engineName: 'MiniMax Music 3',
          modelId: 'minimax-music3', modelName: 'MiniMax Music 3', ready: true,
          unavailableReason: null, runtimeReady: true, platformSupported: true,
          cudaRequired: true, cudaState: 'available', minDurationSec: 10,
          maxDurationSec: 300, defaultDurationSec: 60, lyrics: true, autoDuration: false,
        }],
      };
      fetch.mockImplementation(async (url) => {
        if (String(url).endsWith('/api/system/health/details')) {
          return { ok: true, json: async () => ({ instanceId: 'remote-id', version: '1.0.0' }) };
        }
        if (String(url).includes('/api/apps?view=probe')) return { ok: true, json: async () => [] };
        if (String(url).includes('/api/instances/sync-status')) return { ok: true, json: async () => ({}) };
        if (String(url).includes('/api/federation/media/v1/status')) {
          return { ok: true, status: 200, text: async () => JSON.stringify(providerStatus) };
        }
        return { ok: false, status: 404, text: async () => '' };
      });

      const result = await probePeer(target);

      expect(result.mediaProviderStatus).toMatchObject({ state: 'ready', reason: null });
      // Every known kind is requested, not just already-allowlisted ones — a
      // fresh consumer has no visual allowlist, and scoping the question to it
      // is what previously made image/video capabilities undiscoverable (#4348).
      expect(fetch).toHaveBeenCalledWith(
        'http://10.0.0.1:5555/api/federation/media/v1/status?kinds=audio,image,video',
        expect.objectContaining({ signal: expect.any(AbortSignal) }),
      );
    });

    it('should mark peer offline on fetch failure', async () => {
      const peer = makePeer({ lastSeen: '2024-01-01T00:00:00Z', lastHealth: { uptime: 100 } });
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      fetch.mockRejectedValue(new Error('Connection refused'));

      const result = await probePeer(peer);

      expect(result.status).toBe('offline');
      expect(result.lastSeen).toBe('2024-01-01T00:00:00Z');
      expect(result.lastHealth).toEqual({ uptime: 100 });
      expect(result.lastProbe).toMatchObject({ ok: false, class: expect.any(String) });
      expect(result.lastProbe.message).toBeTruthy();
      expect(disconnectFromPeer).toHaveBeenCalledWith('peer-1');
    });

    it('classifies a tailcat loopback refuse as local_refused on lastProbe', async () => {
      const peer = makePeer({
        transport: 'tailcat',
        address: '127.0.0.1',
        port: 15555,
      });
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      const refused = Object.assign(new Error('connect ECONNREFUSED 127.0.0.1:15555'), { code: 'ECONNREFUSED' });
      fetch.mockRejectedValue(refused);

      const result = await probePeer(peer);

      expect(result.status).toBe('offline');
      expect(result.lastProbe).toMatchObject({
        ok: false,
        class: 'local_refused',
      });
      expect(result.lastProbe.message).toMatch(/forward is not listening/i);
    });

    it('persists lastProbe ok + latency on a successful probe', async () => {
      const peer = makePeer();
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id' }) })
        .mockResolvedValueOnce({ ok: false })
        .mockResolvedValueOnce({ ok: false });

      const result = await probePeer(peer);

      expect(result.status).toBe('online');
      expect(result.lastProbe).toMatchObject({ ok: true, class: 'ok', httpStatus: 200 });
      expect(typeof result.lastProbe.latencyMs).toBe('number');
    });

    it('should mark peer offline on non-ok health response', async () => {
      const peer = makePeer();
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      fetch
        .mockResolvedValueOnce({ ok: false, status: 500 }) // health
        .mockResolvedValueOnce(null) // apps (caught)
        .mockResolvedValueOnce(null); // sync (caught)

      const result = await probePeer(peer);

      expect(result.status).toBe('offline');
      expect(result.authRequired).toBe(false);
    });

    it('should set authRequired when the peer responds 401', async () => {
      const peer = makePeer();
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      fetch
        .mockResolvedValueOnce({ ok: false, status: 401 }) // health — auth-gated proxy
        .mockResolvedValueOnce(null)
        .mockResolvedValueOnce(null);

      const result = await probePeer(peer);

      expect(result.status).toBe('offline');
      expect(result.authRequired).toBe(true);
    });

    it('should clear authRequired on a successful probe', async () => {
      const peer = makePeer({ authRequired: true });
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id' }) })
        .mockResolvedValueOnce({ ok: false })
        .mockResolvedValueOnce({ ok: false });

      const result = await probePeer(peer);

      expect(result.status).toBe('online');
      expect(result.authRequired).toBe(false);
    });

    it('latches the receiver confirmation of the pair token, and drops it on an auth failure (#8356)', async () => {
      const peer = makePeer({ syncSecret: 'example-pair-secret-0123456789-abcdef' });
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      const health = (body) => ({ ok: true, json: () => Promise.resolve({ instanceId: 'r-id', ...body }) });

      // An older receiver never answers: the sender keeps presenting Basic.
      fetch.mockResolvedValueOnce(health({})).mockResolvedValueOnce(null).mockResolvedValueOnce(null);
      expect((await probePeer(peer)).peerAuthAccepted).toBe(false);

      fetch.mockResolvedValueOnce(health({ peerAuth: { version: 1, accepted: true } }))
        .mockResolvedValueOnce(null).mockResolvedValueOnce(null);
      expect((await probePeer(peer)).peerAuthAccepted).toBe(true);

      // A timeout keeps the confirmation; a 401 (lost pairing, downgrade) clears it.
      fetch.mockRejectedValueOnce(new Error('timeout')).mockResolvedValueOnce(null).mockResolvedValueOnce(null);
      expect((await probePeer(peer)).peerAuthAccepted).toBe(true);
      fetch.mockResolvedValueOnce({ ok: false, status: 401 }).mockResolvedValueOnce(null).mockResolvedValueOnce(null);
      expect((await probePeer(peer)).peerAuthAccepted).toBe(false);
    });

    it('should auto-update name from hostname when name is an IP', async () => {
      const peer = makePeer({ name: '10.0.0.1' });
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const healthData = { instanceId: 'r-id', hostname: 'proper-hostname' };
      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(healthData) })
        .mockResolvedValueOnce({ ok: false })
        .mockResolvedValueOnce({ ok: false });

      const result = await probePeer(peer);

      expect(result.name).toBe('proper-hostname');
    });

    it('should emit peer:online when transitioning to online', async () => {
      const peer = makePeer({ status: 'offline' });
      const peers = [peer];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const healthData = { instanceId: 'r-id' };
      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(healthData) })
        .mockResolvedValueOnce({ ok: false })
        .mockResolvedValueOnce({ ok: false })
        // announceSelf calls
        .mockRejectedValue(new Error('announce failed'));

      const result = await probePeer(peer);

      expect(result.status).toBe('online');
      expect(instanceEvents.emit).toHaveBeenCalledWith('peer:online', expect.any(Object));
    });

    it('emits peer:online on the first probe after boot for a peer persisted as online, then only on transitions (#11750)', async () => {
      // The persisted status survives a restart, so without the per-process
      // first-sighting rule an edit stranded by the restart is never retried.
      const peer = makePeer({ status: 'online' });
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      const healthData = { instanceId: 'r-id' };
      fetch.mockImplementation(async () => ({ ok: true, json: () => Promise.resolve(healthData) }));
      const onlineEmits = () => instanceEvents.emit.mock.calls.filter(([name]) => name === 'peer:online').length;

      await probePeer(peer);
      expect(onlineEmits()).toBe(1);

      await probePeer(peer);
      expect(onlineEmits()).toBe(1);
    });

    it('should return null if peer is removed during probe', async () => {
      const peer = makePeer({ id: 'removed-peer' });
      // The peer list does NOT contain this peer
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      const healthData = { instanceId: 'r-id' };
      fetch
        .mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(healthData) })
        .mockResolvedValueOnce({ ok: false })
        .mockResolvedValueOnce({ ok: false });

      const result = await probePeer(peer);

      expect(result).toBeNull();
    });
  });

  describe('probeAllPeers', () => {
    it('should skip probing when no enabled peers', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      await probeAllPeers();

      expect(fetch).not.toHaveBeenCalled();
    });

    it('should only probe enabled peers', async () => {
      const peers = [
        { id: 'p1', address: '10.0.0.1', port: 5555, name: 'h1', enabled: true, status: 'unknown' },
        { id: 'p2', address: '10.0.0.2', port: 5555, name: 'h2', enabled: false, status: 'unknown' }
      ];
      readJSONFile.mockResolvedValue({ self: null, peers });

      // Probe will call fetch for enabled peer only
      fetch.mockRejectedValue(new Error('offline'));

      await probeAllPeers();

      // Only 3 fetch calls for p1 (health, apps, sync), not 6
      expect(fetch).toHaveBeenCalledTimes(3);
    });
  });

  // --- Query Proxy ---

  describe('queryPeer', () => {
    it('should proxy request to peer and return data', async () => {
      const peers = [{ id: 'peer-1', address: '10.0.0.1', port: 5555 }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      const mockData = { apps: ['app1'] };
      fetch.mockResolvedValue({ json: () => Promise.resolve(mockData) });

      const result = await queryPeer('peer-1', '/api/apps');

      expect(result).toEqual({ success: true, data: mockData });
      expect(fetch).toHaveBeenCalledWith(
        'http://10.0.0.1:5555/api/apps',
        expect.objectContaining({ signal: expect.any(AbortSignal) })
      );
    });

    it('should return error for non-existent peer', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      const result = await queryPeer('missing', '/api/apps');

      expect(result).toEqual({ error: 'Peer not found' });
      expect(fetch).not.toHaveBeenCalled();
    });

    it('should return error when fetch fails', async () => {
      const peers = [{ id: 'peer-1', address: '10.0.0.1', port: 5555 }];
      readJSONFile.mockResolvedValue({ self: null, peers });

      fetch.mockRejectedValue(new Error('Connection refused'));

      const result = await queryPeer('peer-1', '/api/apps');

      expect(result).toEqual({ error: 'Failed to query peer: Connection refused' });
    });
  });

  describe('queryPeer federation-surface allowlist', () => {
    beforeEach(() => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'peer-1', address: '10.0.0.1', port: 5555 }] });
      fetch.mockResolvedValue({ json: () => Promise.resolve({}) });
    });

    it.each([
      '/api/settings', '/api/commands/execute', '/api/peer-sync/push', '/api/apps/../settings',
      'https://example.test/api/apps', '//example.test/api/apps', '/api/apps/%2e%2e/settings',
      '/api/apps%2fx', 'api/apps', '/api/apps\\..\\settings', '/api/apps#x', '/api/apps\t/x',
      'http://user:[email protected]/api/apps', '/api/settings?next=/api/apps', '/api/brain/sync/../../settings',
    ])('refuses %j before any network call', async (p) => {
      const result = await queryPeer('peer-1', p);
      expect(result).toMatchObject({ status: 400 });
      expect(fetch).not.toHaveBeenCalled();
    });

    it('proxies allowlisted paths and forwards the query on the peer origin', async () => {
      await queryPeer('peer-1', '/api/brain/reconcile/snapshot');
      await queryPeer('peer-1', '/api/apps?x=1&y=/../z');
      expect(fetch.mock.calls.map(c => c[0])).toEqual([
        'http://10.0.0.1:5555/api/brain/reconcile/snapshot',
        'http://10.0.0.1:5555/api/apps?x=1&y=/../z',
      ]);
    });
  });

  // --- Announce (Bidirectional Registration) ---

  it('keeps tailcat routing managed while applying ordinary peer settings', async () => {
    const peer = {
      id: 'tailcat-peer', transport: 'tailcat', address: '127.0.0.1', port: 15555, host: null, protocol: 'https'
    };
    readJSONFile.mockResolvedValue({ self: null, peers: [peer] });

    const updated = await updatePeer(peer.id, {
      address: '192.0.2.10', port: 5555, host: 'peer.example.com', protocol: 'http', name: 'Example peer', enabled: false
    });

    expect(updated).toMatchObject({
      address: '127.0.0.1', port: 15555, host: null, protocol: 'https', name: 'Example peer', enabled: false
    });
  });

  describe('handleAnnounce', () => {
    it('emits peer:online once per process when an announce marks a known peer online (#11750)', async () => {
      const peer = { id: 'peer-local', instanceId: 'peer-a', address: '192.0.2.10', port: 5555,
        name: 'Example peer', status: 'online', directions: ['outbound'] };
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      const onlineEmits = () => instanceEvents.emit.mock.calls.filter(([name]) => name === 'peer:online').length;

      await handleAnnounce({ instanceId: 'peer-a', address: '192.0.2.10', port: 5555 });
      expect(onlineEmits()).toBe(1);

      await handleAnnounce({ instanceId: 'peer-a', address: '192.0.2.10', port: 5555 });
      expect(onlineEmits()).toBe(1);
    });

    it('does not emit peer:online for a forged announce that was not trusted', async () => {
      const peer = { id: 'peer-local', instanceId: 'peer-a', address: '192.0.2.10', port: 5555,
        name: 'Example peer', status: 'online', directions: ['outbound'] };
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      await handleAnnounce({ instanceId: 'peer-a', address: '198.51.100.99', port: 5555 });
      expect(instanceEvents.emit).not.toHaveBeenCalledWith('peer:online', expect.anything());
    });

    it('keeps an admitted peer identity, callback endpoint and consent unchanged after forged discovery', async () => {
      const peer = { id: 'peer-local', instanceId: 'peer-a', address: '192.0.2.10', port: 5555,
        host: 'configured.example.com', directions: ['inbound'], syncSecret: 'synthetic-pair-secret-32-characters-long',
        syncEnabled: false, syncCategories: { universe: false } };
      const before = structuredClone(peer);
      readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });
      await handleAnnounce({ instanceId: 'peer-forged', address: '192.0.2.10', port: 5555, host: 'attacker.example.com' });
      expect(peer).toEqual(before);
      await applyReciprocalSync('peer-a', { universe: true }, { fullSync: true });
      expect(peer).toEqual(before);
    });

    it('ignores host/port/name/status from an announce whose address does not match the stored peer, even without a syncSecret', async () => {
      // instanceId is public (GET /api/system/health, unauthenticated), so a caller
      // that only knows it — but isn't calling from the peer's real address — must
      // not be able to redirect this peer record to a host of their choosing.
      const peer = {
        id: 'peer-local', instanceId: 'peer-a', address: '192.0.2.10', port: 5555,
        host: 'configured.example.com', name: 'configured.example.com', status: 'offline',
        directions: ['outbound']
      };
      const before = structuredClone(peer);
      readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });

      const result = await handleAnnounce({
        instanceId: 'peer-a', address: '198.51.100.99', port: 443,
        host: 'attacker.example.com', name: 'attacker'
      });

      expect(result.created).toBe(false);
      expect(result.peer.host).toBe(before.host);
      expect(result.peer.port).toBe(before.port);
      expect(result.peer.name).toBe(before.name);
      expect(result.peer.status).toBe(before.status);
      expect(result.peer.directions).toEqual(before.directions);
      expect(peerBaseUrl(result.peer)).toBe(peerBaseUrl(before));
    });

    it('preserves the managed tailcat endpoint when the remote announces its own host and port', async () => {
      const existing = {
        id: 'tailcat-peer', address: '127.0.0.1', port: 15555, host: null,
        transport: 'tailcat', instanceId: 'remote-instance', directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '192.0.2.10', port: 5555, host: 'peer.example.com',
        instanceId: 'remote-instance', name: 'Example peer'
      });

      expect(result.created).toBe(false);
      expect(result.peer).toMatchObject({
        address: '127.0.0.1', port: 15555, host: null, transport: 'tailcat', status: 'online'
      });
      expect(result.peer.directions).toEqual(['outbound', 'inbound']);
      expect(atomicWrite).toHaveBeenCalledWith(expect.any(String), expect.objectContaining({ peers: [result.peer] }));
    });

    it.each(['localhost', 'api.localhost', '127.0.0.1', '169.254.169.254'])(
      'stores no host for a new peer announcing %s, and adopts a *.ts.net host', async (badHost) => {
        readJSONFile.mockResolvedValue({ self: null, peers: [] });
        const refused = await handleAnnounce({ address: '192.0.2.10', port: 5555, instanceId: 'bad', host: badHost });
        expect(refused.peer.host).toBeNull();
        readJSONFile.mockResolvedValue({ self: null, peers: [] });
        const ok = await handleAnnounce({ address: '192.0.2.11', port: 5555, instanceId: 'good', host: 'box.example-tailnet.ts.net' });
        expect(ok.peer.host).toBe('box.example-tailnet.ts.net');
      });

    it('should create a new peer from announcement', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      // probePeer will call fetch
      fetch.mockRejectedValue(new Error('offline'));

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'remote-host'
      });

      expect(result.created).toBe(true);
      expect(result.peer).toMatchObject({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'remote-host',
        enabled: true,
        directions: ['inbound']
      });
      // Note: status not asserted — handleAnnounce fires async probePeer which may change it
      expect(instanceEvents.emit).toHaveBeenCalledWith('peers:updated', expect.any(Array));
    });

    it('preserves a tailcat listener when its remote announces a different endpoint', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{
        id: 'peer-tunnel', instanceId: 'remote-example', transport: 'tailcat',
        address: '127.0.0.1', port: 15555, host: null, hostManual: true,
        name: 'Example peer', directions: ['outbound'],
      }] });
      const { peer } = await handleAnnounce({ address: '192.0.2.10', port: 5555,
        instanceId: 'remote-example', host: 'peer.example.com' });
      expect(peer).toMatchObject({ address: '127.0.0.1', port: 15555, host: null });
    });

    it('should update existing peer matched by instanceId but preserve user-set name', async () => {
      const existing = {
        id: 'p1',
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'custom-name',
        status: 'offline',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'remote-hostname'
      });

      expect(result.created).toBe(false);
      expect(result.peer.name).toBe('custom-name'); // user-set name preserved
      expect(result.peer.status).toBe('online');
      expect(result.peer.directions).toContain('inbound');
      expect(result.peer.directions).toContain('outbound');
    });

    it('should auto-update name from announce when current name is an IP', async () => {
      const existing = {
        id: 'p1',
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: '10.0.0.5',
        status: 'offline',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'remote-hostname'
      });

      expect(result.created).toBe(false);
      expect(result.peer.name).toBe('remote-hostname'); // IP auto-updated to hostname
      expect(result.peer.status).toBe('online');
    });

    it('should match existing peer by address+port when instanceId differs', async () => {
      const existing = {
        id: 'p1',
        address: '10.0.0.5',
        port: 5555,
        instanceId: null,
        name: 'host',
        status: 'unknown',
        directions: []
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'new-id',
        name: 'host'
      });

      expect(result.created).toBe(false);
      expect(result.peer.instanceId).toBe('new-id');
      expect(result.peer.directions).toContain('inbound');
    });

    it('should preserve user-set name on announce even with NaN hostname', async () => {
      const existing = {
        id: 'p1',
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote',
        name: 'good-name',
        status: 'offline',
        directions: []
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote',
        name: 'NaN'
      });

      // Name preserved because 'good-name' is not an IP address
      expect(result.peer.name).toBe('good-name');
    });

    it('should not duplicate inbound direction on re-announce', async () => {
      const existing = {
        id: 'p1',
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote',
        name: 'host',
        status: 'online',
        directions: ['inbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '10.0.0.5',
        port: 5555,
        instanceId: 'remote',
        name: 'host'
      });

      const inboundCount = result.peer.directions.filter(d => d === 'inbound').length;
      expect(inboundCount).toBe(1);
    });

    it('should store host on a new peer announced over Tailscale', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('offline'));

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'host-beta.example-tailnet.ts.net'
      });

      expect(result.created).toBe(true);
      expect(result.peer.host).toBe('host-beta.example-tailnet.ts.net');
    });

    it('should learn host on existing peer when previously absent', async () => {
      const existing = {
        id: 'p1',
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: null,
        status: 'offline',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'host-beta.example-tailnet.ts.net'
      });

      expect(result.peer.host).toBe('host-beta.example-tailnet.ts.net');
    });

    it('should not overwrite a user-set host on existing peer', async () => {
      const existing = {
        id: 'p1',
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'manual.example.ts.net',
        status: 'online',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'auto.different.ts.net'
      });

      expect(result.peer.host).toBe('manual.example.ts.net');
    });

    it('should not re-adopt host on cleared peer when hostManual is true', async () => {
      // Reproduces the original "can't undo Tailnet DNS" bug: user cleared
      // peer.host, but the next inbound announce silently re-adopted the DNS
      // name because the only safeguard was "is existing.host empty?".
      const existing = {
        id: 'p1',
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: null,
        hostManual: true,
        status: 'offline',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'host-beta.example-tailnet.ts.net'
      });

      expect(result.peer.host).toBeNull();
      expect(result.peer.hostManual).toBe(true);
    });

    it('should still learn host on a fresh peer when hostManual is unset', async () => {
      // Auto-learn must remain the default for never-touched peers — only
      // explicit user intervention should latch hostManual.
      const existing = {
        id: 'p1',
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: null,
        status: 'offline',
        directions: ['outbound']
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [existing] });

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'host-beta.example-tailnet.ts.net'
      });

      expect(result.peer.host).toBe('host-beta.example-tailnet.ts.net');
    });

    it('should drop invalid host strings via validHost', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      fetch.mockRejectedValue(new Error('offline'));

      const result = await handleAnnounce({
        address: '100.64.0.50',
        port: 5555,
        instanceId: 'remote-instance',
        name: 'null',
        host: 'has spaces and:colons'
      });

      expect(result.peer.host).toBeNull();
    });

    it('probes a paired peer on the top backoff tier immediately when it announces, emits peer:online, and preserves host/port/name (#12621)', async () => {
      const peer = {
        id: 'peer-paired',
        instanceId: 'remote-paired',
        address: '192.0.2.10',
        port: 5555,
        host: null,
        name: 'Stored Box Name',
        status: 'offline',
        consecutiveFailures: 5,
        nextProbeAt: new Date(Date.now() + 3_600_000).toISOString(),
        syncSecret: 'synthetic-pair-secret-32-characters-long',
        enabled: true,
      };
      readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });

      fetch.mockImplementation(async (url) => {
        if (url.includes('/api/system/health/details')) {
          return {
            ok: true,
            status: 200,
            json: async () => ({ instanceId: 'remote-paired', version: '1.7.0' }),
          };
        }
        return { ok: false, status: 404 };
      });

      const onlineEmits = () => instanceEvents.emit.mock.calls.filter(([name]) => name === 'peer:online');

      const result = await handleAnnounce({
        instanceId: 'remote-paired',
        address: '192.0.2.10',
        port: 5555,
        host: 'attacker-host.example.com',
        name: 'Attacker Attempt Name',
      });

      expect(result.created).toBe(false);
      expect(result.peer.host).toBeNull();
      expect(result.peer.port).toBe(5555);
      expect(result.peer.name).toBe('Stored Box Name');
      expect(result.peer.nextProbeAt).toBeNull();

      await vi.waitFor(() => expect(onlineEmits().length).toBe(1));
      expect(onlineEmits()[0][1]).toMatchObject({
        id: 'peer-paired',
        status: 'online',
        host: null,
        port: 5555,
        name: 'Stored Box Name',
        consecutiveFailures: 0,
        nextProbeAt: null,
      });
    });

    it('triggers probe to stored address only when a forged announce with mismatched address arrives (#12621)', async () => {
      const peer = {
        id: 'peer-paired',
        instanceId: 'remote-paired',
        address: '192.0.2.10',
        port: 5555,
        host: null,
        name: 'Stored Box Name',
        status: 'offline',
        consecutiveFailures: 5,
        nextProbeAt: new Date(Date.now() + 3_600_000).toISOString(),
        syncSecret: 'synthetic-pair-secret-32-characters-long',
        enabled: true,
      };
      readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });

      const fetchedUrls = [];
      fetch.mockImplementation(async (url) => {
        fetchedUrls.push(url);
        return { ok: false, status: 500 };
      });

      const result = await handleAnnounce({
        instanceId: 'remote-paired',
        address: '198.51.100.99', // forged IP
        port: 9999,
        host: 'attacker-host.example.com',
        name: 'Attacker Attempt Name',
      });

      expect(result.created).toBe(false);
      expect(result.peer.address).toBe('192.0.2.10');
      expect(result.peer.port).toBe(5555);
      expect(result.peer.host).toBeNull();
      expect(result.peer.name).toBe('Stored Box Name');

      await vi.waitFor(() => expect(fetchedUrls.length).toBeGreaterThan(0));
      for (const url of fetchedUrls) {
        expect(url).not.toContain('198.51.100.99');
        expect(url).not.toContain('9999');
        expect(url).not.toContain('attacker-host.example.com');
        expect(url).toContain('192.0.2.10');
      }
    });

    it('rate-limits announce wakes to at most once per 30 seconds per peer (#12621)', async () => {
      const peer = {
        id: 'peer-paired',
        instanceId: 'remote-paired',
        address: '192.0.2.10',
        port: 5555,
        status: 'offline',
        syncSecret: 'synthetic-pair-secret-32-characters-long',
        enabled: true,
      };
      readJSONFile.mockResolvedValue({ self: { instanceId: 'local-instance' }, peers: [peer] });

      let probeCount = 0;
      fetch.mockImplementation(async (url) => {
        if (url.includes('/api/system/health/details')) probeCount++;
        return { ok: false, status: 500 };
      });

      // First announce wakes the probe
      await handleAnnounce({ instanceId: 'remote-paired', address: '192.0.2.10', port: 5555 });
      await vi.waitFor(() => expect(probeCount).toBe(1));

      // Second announce 5s later does not wake
      vi.advanceTimersByTime(5_000);
      await handleAnnounce({ instanceId: 'remote-paired', address: '192.0.2.10', port: 5555 });
      expect(probeCount).toBe(1);

      // Third announce after 30s interval wakes again
      vi.advanceTimersByTime(26_000); // 31s total
      await handleAnnounce({ instanceId: 'remote-paired', address: '192.0.2.10', port: 5555 });
      await vi.waitFor(() => expect(probeCount).toBe(2));
    });
  });

  describe('probe backoff and wake (#12621)', () => {
    it('pins the tier sequence and caps backoff at 1 hour (#12621)', () => {
      expect(BACKOFF_TIERS_MS).toEqual([
        30_000,
        60_000,
        300_000,
        900_000,
        3_600_000,
      ]);
      expect(BACKOFF_TIERS_MS.at(-1)).toBe(3_600_000);
    });

    it('caps backoff tier at 1h (3_600_000 ms) on repeated consecutive failures', async () => {
      const peer = {
        id: 'peer-failing',
        address: '192.0.2.20',
        port: 5555,
        name: 'Failing peer',
        status: 'offline',
        consecutiveFailures: 10,
        enabled: true,
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });
      fetch.mockRejectedValue(new Error('offline'));

      const updated = await probePeer(peer);
      expect(updated.consecutiveFailures).toBe(11);
      const expectedTime = new Date(Date.now() + 3_600_000).toISOString();
      expect(updated.nextProbeAt).toBe(expectedTime);
    });

    it('wakePeerProbe clears nextProbeAt and fires probePeer rate-limited to once per 30s', async () => {
      const peer = {
        id: 'peer-sleepy',
        address: '192.0.2.30',
        port: 5555,
        name: 'Sleepy peer',
        status: 'offline',
        nextProbeAt: new Date(Date.now() + 3_600_000).toISOString(),
        enabled: true,
      };
      readJSONFile.mockResolvedValue({ self: null, peers: [peer] });

      let probeCalled = 0;
      fetch.mockImplementation(async (url) => {
        if (url.includes('/api/system/health/details')) probeCalled++;
        return { ok: false, status: 500 };
      });

      const first = wakePeerProbe(peer);
      expect(first).toBe(true);
      await vi.waitFor(() => expect(probeCalled).toBe(1));

      // Second call immediately is rate-limited
      const second = wakePeerProbe(peer);
      expect(second).toBe(false);
      expect(probeCalled).toBe(1);

      // After 30s passes, it wakes again
      vi.advanceTimersByTime(PEER_WAKE_RATE_LIMIT_MS);
      const third = wakePeerProbe(peer);
      expect(third).toBe(true);
      await vi.waitFor(() => expect(probeCalled).toBe(2));
    });

    it('wakePeerProbe ignores disabled peers', () => {
      const disabled = { id: 'peer-off', enabled: false };
      expect(wakePeerProbe(disabled)).toBe(false);
    });
  });

  // --- Polling ---

  describe('startPolling / stopPolling', () => {
    let logSpy;

    beforeEach(() => {
      logSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
    });

    afterEach(() => {
      logSpy.mockRestore();
    });

    // startPolling now defers to an async gate (loadData + Tailscale check);
    // flush the resolved-promise chain so the gate reaches beginPolling().
    const flush = async () => { for (let i = 0; i < 8; i++) await Promise.resolve(); };
    const logged = (frag) => logSpy.mock.calls.some(c => String(c[0]).includes(frag));

    it('starts polling immediately with no peers (solo install), without probing Tailscale', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });
      getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });

      startPolling();
      await flush();

      expect(logged('Instance polling started')).toBe(true);
      // No peers → never even asks Tailscale.
      expect(getTailscaleStatus).not.toHaveBeenCalled();
      stopPolling();
    });

    it('starts polling when tailnet peers exist and Tailscale is connected', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
      getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });

      startPolling();
      await flush();

      expect(getTailscaleStatus).toHaveBeenCalled();
      expect(logged('Instance polling started')).toBe(true);
      expect(logged('Peer sync deferred')).toBe(false);
      stopPolling();
    });

    it('probes immediately for a LAN/IP peer even when Tailscale is down (never stranded)', async () => {
      // A peer addressed by a plain LAN IP (no MagicDNS host, not a CGNAT addr)
      // is reachable without Tailscale, so the gate must not defer it.
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'lan', enabled: true, address: '192.168.1.50' }] });
      getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });

      startPolling();
      await flush();

      expect(logged('Instance polling started')).toBe(true);
      expect(logged('Peer sync deferred')).toBe(false);
      // A non-tailnet peer means we don't even need to ask Tailscale.
      expect(getTailscaleStatus).not.toHaveBeenCalled();
      stopPolling();
    });

    it('defers polling when all peers are tailnet-only and Tailscale is down, then starts once it comes up', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
      getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });

      startPolling();
      await flush();

      expect(logged('Peer sync deferred')).toBe(true);
      expect(logged('Instance polling started')).toBe(false);

      // Tailscale connects; the recheck watcher should pick it up and start polling.
      getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });
      await vi.advanceTimersByTimeAsync(60_000);
      await flush();

      expect(logged('Tailscale connected — starting peer sync polling')).toBe(true);
      expect(logged('Instance polling started')).toBe(true);
      stopPolling();
    });

    it('does not start twice', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [] });

      startPolling();
      startPolling(); // second call should be a no-op
      await flush();

      const starts = logSpy.mock.calls.filter(c => String(c[0]).includes('Instance polling started')).length;
      expect(starts).toBe(1);
      stopPolling();
    });

    it('stop clears a pending Tailscale watch so it never starts polling later', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
      getTailscaleStatus.mockResolvedValue({ running: false, state: 'Stopped', reason: 'tailscale-stopped' });

      startPolling();
      await flush();
      expect(logged('Peer sync deferred')).toBe(true);

      stopPolling();
      stopPolling(); // double stop should be safe

      // Even if Tailscale comes up after stop, the (cleared) watcher must not fire.
      getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });
      await vi.advanceTimersByTimeAsync(60_000);
      await flush();

      expect(logged('Instance polling started')).toBe(false);
    });

    it('aborts startup if stopPolling is called during the async gate window', async () => {
      readJSONFile.mockResolvedValue({ self: null, peers: [{ id: 'p1', enabled: true, host: 'p1.tailnet.ts.net' }] });
      getTailscaleStatus.mockResolvedValue({ running: true, state: 'Running', reason: 'running' });

      startPolling();      // kicks off the async gate (loadData → getTailscaleStatus)
      stopPolling();       // lands before the gate resolves — must cancel it
      await flush();

      // The generation bump makes the resolving gate bail before beginPolling().
      expect(logged('Instance polling started')).toBe(false);

      // And a fresh start afterward still works (state wasn't left wedged).
      startPolling();
      await flush();
      expect(logged('Instance polling started')).toBe(true);
      stopPolling();
    });
  });

  describe('automatic peer sync pairing', () => {
    const selfId = '191aaece-a492-41ee-a66d-d4661eadc132';
    const peerId = '9f131a42-3103-4a68-9ad7-5f58d7926c1e';
    const makePeer = (overrides = {}) => ({
      id: 'peer-record', instanceId: peerId, address: '192.0.2.20', port: 5555,
      enabled: true, status: 'online', syncEnabled: true, directions: ['outbound'],
      auth: { username: '', password: 'synthetic-instance-password' },
      ...overrides,
    });

    it('generates one secret, provisions it remotely with Basic auth, then stores it locally', async () => {
      const peer = makePeer();
      readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });
      fetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue({ paired: true }) });

      const updated = await pairPeerSyncSecret(peer.id);
      const pairCall = fetch.mock.calls.find(([url]) => url.endsWith('/api/instances/peers/pair-secret'));
      expect(pairCall).toBeDefined();
      const [, options] = pairCall;
      const headers = Object.fromEntries(Object.entries(options.headers).map(([key, value]) => [key.toLowerCase(), value]));
      const generatedSecret = JSON.parse(options.body).syncSecret;
      expect(generatedSecret).toMatch(/^[A-Za-z0-9_-]{43}$/);
      expect(updated.syncSecret).toBe(generatedSecret);
      expect(peer.syncSecret).toBe(generatedSecret);
      expect(options.redirect).toBe('error');
      expect(headers).toMatchObject({
        authorization: expect.stringMatching(/^Basic /),
        'x-portos-instance-id': expect.any(String),
        'x-portos-peer-auth': '',
      });
    });

    it('reuses an unconfirmed local secret when remote provisioning needs a retry', async () => {
      const secret = 'synthetic-pair-secret-32-characters-long';
      const peer = makePeer({ syncSecret: secret, peerAuthAccepted: false });
      readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });
      fetch.mockResolvedValue({ ok: true, json: vi.fn().mockResolvedValue({ paired: true }) });

      await pairPeerSyncSecret(peer.id);

      const pairCall = fetch.mock.calls.find(([url]) => url.endsWith('/api/instances/peers/pair-secret'));
      expect(JSON.parse(pairCall[1].body).syncSecret).toBe(secret);
    });

    it('does not store a newly generated secret when the peer rejects pairing', async () => {
      const peer = makePeer();
      readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });
      fetch.mockResolvedValue({ ok: false, status: 404, json: vi.fn().mockResolvedValue({}) });

      await expect(pairPeerSyncSecret(peer.id)).rejects.toMatchObject({ code: 'PEER_PAIR_REJECTED' });
      expect(peer).not.toHaveProperty('syncSecret');
    });

    it('accepts a generated secret only for one registered peer and preserves sync consent', async () => {
      const peer = makePeer({ syncEnabled: false, syncCategories: { universe: false } });
      readJSONFile.mockResolvedValue({ self: { instanceId: selfId }, peers: [peer] });
      const accepted = await acceptPeerSyncSecretFromPeer(peerId, 'synthetic-pair-secret-32-characters-long');

      expect(accepted.syncSecret).toBe('synthetic-pair-secret-32-characters-long');
      expect(accepted.directions).toEqual(['outbound', 'inbound']);
      expect(accepted.syncEnabled).toBe(false);
      expect(disconnectFromPeer).toHaveBeenCalledWith(peer.id);
      expect(await acceptPeerSyncSecretFromPeer('unknown-peer', 'synthetic-pair-secret-32-characters-long')).toBeNull();
    });
  });

  describe('setPeerSchemaGap', () => {
    const gap = (n) => ({ detectedAt: '2026-01-01T00:00:00.000Z', ahead: [n], behind: [], senderPortosVersion: '9.9.9' });
    const seed = (schemaGaps) => {
      const peer = { id: 'p1', instanceId: 'remote-1', ...(schemaGaps ? { schemaGaps } : {}) };
      readJSONFile.mockResolvedValue({ self: { instanceId: 'self-id' }, peers: [peer] });
      return peer;
    };

    it('keeps both gaps when two categories are recorded concurrently', async () => {
      const peer = seed();
      await Promise.all([
        setPeerSchemaGap('remote-1', 'universe', gap('universe')),
        setPeerSchemaGap('remote-1', 'pipeline', gap('pipeline'))
      ]);
      expect(Object.keys(peer.schemaGaps).sort()).toEqual(['pipeline', 'universe']);
    });

    it('leaves exactly the recorded category when another is cleared concurrently', async () => {
      const peer = seed({ B: gap('B') });
      await Promise.all([
        setPeerSchemaGap('remote-1', 'A', gap('A')),
        setPeerSchemaGap('remote-1', 'B', null)
      ]);
      expect(Object.keys(peer.schemaGaps)).toEqual(['A']);
    });

    it('removes the schemaGaps key when the last gap clears and ignores unknown peers', async () => {
      const peer = seed({ A: gap('A') });
      await setPeerSchemaGap('remote-1', 'A', null);
      expect(peer).not.toHaveProperty('schemaGaps');
      expect(await setPeerSchemaGap('nobody', 'A', gap('A'))).toBeNull();
    });
  });
});