Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

284 KB
Raw Blame
import { execFile, execFileSync } from 'node:child_process';
import {
  appendFileSync,
  chmodSync,
  existsSync,
  lstatSync,
  mkdirSync,
  mkdtempSync,
  readFileSync,
  rmSync,
  symlinkSync,
  writeFileSync,
} from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { promisify } from 'node:util';
import { LOCAL_DIR, type SyncMode, SyncStatusSchema } from '@inkeep/open-knowledge-core';
import simpleGit from 'simple-git';
import { afterEach, beforeEach, describe, expect, onTestFinished, test, vi } from 'vitest';
import { configureTestGitRepository } from '../../../test-support/configure-git-fixture.test-helper.ts';
import { type Conflict, ConflictAuthority } from './conflict-authority.ts';
import { createContentFilter } from './content-filter.ts';
import { classifyGitError } from './error-classification.ts';
import type { GitHandle } from './git-handle.ts';
import { listNames } from './git-paths.ts';
import type {
  CheckPushPermissionOptions,
  DetectGhAccountsFn,
  DetectGhFn,
  PushPermission,
} from './github-permissions.ts';
import { getLogger } from './logger.ts';
import { createSyncCredentialConfigResolver } from './share/git-context.ts';
import { declareGitHubHosts, useIsolatedHome } from './share/git-host-declarations.test-helper.ts';
import type { CredentialUrlMatchReader } from './share/github-account.ts';
import {
  CONTENTION_WARN_THRESHOLD,
  classifyFastForwardRefusal,
  isFetchDisprovableFailure,
  SyncEngine,
  type SyncState,
} from './sync-engine.ts';

const execFileAsync = promisify(execFile);
const JITTER_SAMPLES = [
  { draw: 0, edge: 'min' },
  { draw: 1 / 2, edge: 'mid' },
  { draw: 1 - Number.EPSILON, edge: 'max' },
] as const;

function jitterBand(seconds: number) {
  return {
    min: Math.round(seconds * 0.85 * 1000),
    mid: seconds * 1000,
    max: Math.round(seconds * 1.15 * 1000),
  };
}

const stubContentFilter = {
  isExcluded: (_path: string) => false,
  isDirExcluded: (_path: string) => false,
};

interface CapturedLog {
  data: Record<string, unknown>;
  msg: string;
  level: 'info' | 'warn';
}
function captureSyncLogs(name = 'sync-engine'): { entries: CapturedLog[]; restore: () => void } {
  const entries: CapturedLog[] = [];
  const logger = getLogger(name);
  const record =
    (level: CapturedLog['level']) =>
    (data: unknown, msg?: string): void => {
      entries.push({ data: (data ?? {}) as Record<string, unknown>, msg: msg ?? '', level });
    };
  const infoSpy = vi.spyOn(logger, 'info').mockImplementation(record('info') as never);
  const warnSpy = vi.spyOn(logger, 'warn').mockImplementation(record('warn') as never);
  return {
    entries,
    restore: () => {
      infoSpy.mockRestore();
      warnSpy.mockRestore();
    },
  };
}

let tmpDir = '';
let projectDir = '';
let contentDir = '';
let okDir = '';

beforeEach(() => {
  tmpDir = mkdtempSync(join(tmpdir(), 'sync-engine-test-'));
  projectDir = join(tmpDir, 'project');
  contentDir = join(tmpDir, 'content');
  okDir = join(projectDir, '.ok', LOCAL_DIR);
  mkdirSync(projectDir, { recursive: true });
  mkdirSync(okDir, { recursive: true });
});

afterEach(() => {
  rmSync(tmpDir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
});

let authority: ConflictAuthority;

function newAuthority(): ConflictAuthority {
  authority = new ConflictAuthority({
    projectDir,
    contentDir: projectDir,
    io: {
      gitRaw: (args) => simpleGit(projectDir).raw(args),
      writeProjectFileUntracked: (absPath, bytes) => writeFileSync(absPath, bytes, 'utf-8'),
      unlinkProjectFileUndeclared: (absPath) => rmSync(absPath, { force: true }),
      deleteResolvedContent: (_docName, absPath) => rmSync(absPath, { force: true }),
      applyResolvedContent: async (_docName, absPath, bytes) => {
        writeFileSync(absPath, bytes, 'utf-8');
      },
    },
  });
  return authority;
}

function workingTreeConflicts(): Array<Extract<Conflict, { kind: 'working-tree' }>> {
  return authority.list().filter((c) => c.kind === 'working-tree');
}

function makeEngine(
  opts: { syncEnabled?: boolean; mode?: SyncMode; onStateChange?: (s: SyncState) => void } = {},
) {
  return new SyncEngine({
    conflicts: newAuthority(),
    projectDir,
    contentDir,
    contentFilter: stubContentFilter,
    syncEnabled: opts.syncEnabled,
    mode: opts.mode,
    onStateChange: opts.onStateChange,
  });
}

async function initGitWithOrigin(originUrl = 'https://github.com/inkeep/open-knowledge.git') {
  const git = simpleGit(projectDir);
  await git.init(['--initial-branch=main']);
  configureTestGitRepository(projectDir);
  await git.raw('config', 'user.name', 'Test');
  await git.raw('config', 'user.email', '[email protected]');
  writeFileSync(join(projectDir, 'README.md'), 'seed\n', 'utf-8');
  await git.add('.');
  await git.commit('seed');
  await git.addRemote('origin', originUrl);
  return git;
}

interface FakeProbeRecorder {
  calls: number;
  next: PushPermission[];
  opts: CheckPushPermissionOptions[];
  fn: (opts: CheckPushPermissionOptions) => Promise<PushPermission>;
}

function fakeProbe(...sequence: Array<PushPermission>) {
  const rec: FakeProbeRecorder = {
    calls: 0,
    next: [...sequence],
    opts: [],
    fn: async (opts) => {
      rec.calls++;
      rec.opts.push(opts);
      return rec.next.shift() ?? { kind: 'unknown', error: 'network' };
    },
  };
  return rec;
}

function makeProbeEngine(opts: {
  syncEnabled?: boolean;
  mode?: SyncMode;
  fakeProbe: FakeProbeRecorder['fn'];
  detectGhAccounts?: DetectGhAccountsFn;
  _readCredentialUrlMatch?: CredentialUrlMatchReader;
  cc1Broadcaster?: ConstructorParameters<typeof SyncEngine>[0]['cc1Broadcaster'];
}) {
  return new SyncEngine({
    conflicts: newAuthority(),
    projectDir,
    contentDir,
    contentFilter: stubContentFilter,
    syncEnabled: opts.syncEnabled,
    mode: opts.mode,
    checkPushPermissionFn: opts.fakeProbe,
    detectGhAccounts: opts.detectGhAccounts,
    _readCredentialUrlMatch: opts._readCredentialUrlMatch,
    cc1Broadcaster: opts.cc1Broadcaster,
  });
}

async function waitForPushPermissionResolved(engine: SyncEngine, timeoutMs = 1000): Promise<void> {
  const deadline = Date.now() + timeoutMs;
  while (engine.getStatus().pushPermission === undefined) {
    if (Date.now() > deadline) {
      throw new Error(`push-permission probe did not resolve within ${timeoutMs}ms`);
    }
    await new Promise((r) => setTimeout(r, 5));
  }
}

describe('SyncEngine initial state', () => {
  test('starts in dormant state', () => {
    const engine = makeEngine();
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('stays dormant when syncEnabled is explicitly false', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().state).toBe('dormant');
  });
});

describe('SyncEngine stop()', () => {
  test('transitions from dormant to dormant without error', () => {
    const engine = makeEngine();
    engine.stop();
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('onStateChange is NOT called when stop() is a no-op (already dormant)', () => {
    const calls: SyncState[] = [];
    const engine = makeEngine({ onStateChange: (s) => calls.push(s) });
    engine.stop();
    expect(calls).toEqual([]);
  });
});

describe('SyncEngine destroy()', () => {
  test('is safe to call when never started', async () => {
    const engine = makeEngine();
    await expect(engine.destroy()).resolves.toBeUndefined();
    expect(engine.getStatus().state).toBe('dormant');
  });
});

describe('SyncEngine state persistence round-trip', () => {
  const statePath = () => join(okDir, 'sync-state.json');

  test('saveStateNow via destroy() writes sync-state.json', async () => {
    const engine = makeEngine();
    await engine.destroy();
    expect(existsSync(statePath())).toBe(true);
  });

  test('sync-state.json does not persist the config-owned enabled preference', async () => {
    const engine = makeEngine({ syncEnabled: true });
    await engine.destroy();
    const persisted = JSON.parse(readFileSync(statePath(), 'utf-8')) as Record<string, unknown>;
    expect(persisted.syncEnabled).toBeUndefined();
  });

  test('restores consecutiveFailures from disk on start()', async () => {
    const persisted = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 4,
      inflightConflicts: [],
    };
    writeFileSync(statePath(), JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(4);
  });

  test('ignores legacy syncEnabled from sync-state.json', async () => {
    const persisted = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 0,
      inflightConflicts: [],
      syncEnabled: true,
    };
    writeFileSync(statePath(), JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().syncEnabled).toBe(false);
  });

  test('a legacy inflightConflicts array does not resurrect cleared conflicts', async () => {
    const persisted = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 0,
      inflightConflicts: ['docs/a.md', 'docs/b.md'],
    };
    writeFileSync(statePath(), JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().conflictCount).toBe(0);
    expect(authority.count()).toBe(0);
  });

  test('the persisted sync state no longer carries a conflict list', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    authority.raise({ kind: 'merge-native', file: 'docs/a.md' });
    await engine.destroy();

    const written = JSON.parse(readFileSync(statePath(), 'utf-8')) as Record<string, unknown>;
    expect(written.inflightConflicts).toBeUndefined();
  });

  test('only conflicts with markers on disk count as sync conflicts and hold the push', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    authority.raise({
      kind: 'reconcile',
      file: 'docs/a.md',
      reason: 'merged-with-markers',
      stages: { base: 'B', ours: 'O', theirs: 'T' },
    });

    expect(authority.count()).toBe(1);
    expect(engine.getStatus().conflictCount).toBe(0);
    expect(engine.getStatus().state).not.toBe('conflict');

    authority.raise({
      kind: 'reconcile',
      file: 'docs/c.md',
      reason: 'disk-markers',
      stages: { base: 'B', ours: 'O', theirs: '<<<<<<< a\nT\n=======\nU\n>>>>>>> b\n' },
    });
    expect(engine.getStatus().conflictCount).toBe(1);

    authority.raise({ kind: 'working-tree', file: 'docs/b.md', theirsSha: 'sha' });
    expect(engine.getStatus().conflictCount).toBe(2);
  });

  async function setupRealMergeConflict(files: string[]): Promise<void> {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    for (const f of files) {
      const dir = join(projectDir, f, '..');
      mkdirSync(dir, { recursive: true });
      writeFileSync(join(projectDir, f), 'base\n', 'utf-8');
    }
    await git.add('.');
    await git.commit('base');
    await git.checkoutLocalBranch('feature');
    for (const f of files) writeFileSync(join(projectDir, f), 'feature\n', 'utf-8');
    await git.add('.');
    await git.commit('feature changes');
    await git.checkout('main');
    for (const f of files) writeFileSync(join(projectDir, f), 'main\n', 'utf-8');
    await git.add('.');
    await git.commit('main changes');
    try {
      await git.merge(['feature']);
    } catch {}
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
  }

  test('state is "conflict" (not "idle") when restarting mid-merge with tracked conflicts', async () => {
    const files = ['docs/a.md', 'docs/b.md'];
    await setupRealMergeConflict(files);

    writeFileSync(
      join(okDir, 'conflicts.json'),
      JSON.stringify({
        version: 1,
        branch: 'main',
        conflicts: files.map((f) => ({ file: f, detectedAt: '2026-04-17T00:00:00.000Z' })),
      }),
      'utf-8',
    );
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        inflightConflicts: files,
      }),
      'utf-8',
    );

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      const status = engine.getStatus();
      expect(status.conflictCount).toBe(2);
      expect(status.state).toBe('conflict');
    } finally {
      await engine.destroy();
    }
  });

  test('clears stale conflicts.json when MERGE_HEAD is gone (user resolved externally)', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);

    writeFileSync(
      join(okDir, 'conflicts.json'),
      JSON.stringify({
        version: 1,
        branch: 'main',
        conflicts: [{ file: 'test.md', detectedAt: '2026-04-17T00:00:00.000Z' }],
      }),
      'utf-8',
    );
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        inflightConflicts: ['test.md'],
      }),
      'utf-8',
    );

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      const status = engine.getStatus();
      expect(status.conflictCount).toBe(0);
      expect(status.state).not.toBe('conflict');
    } finally {
      await engine.destroy();
    }
  });

  test('reconciles partial external resolve against git unmerged index', async () => {
    const files = ['docs/a.md', 'docs/b.md'];
    await setupRealMergeConflict(files);

    const git = simpleGit(projectDir);
    await git.raw(['checkout', '--theirs', '--', 'docs/a.md']);
    await git.raw(['add', '--', 'docs/a.md']);

    writeFileSync(
      join(okDir, 'conflicts.json'),
      JSON.stringify({
        version: 1,
        branch: 'main',
        conflicts: files.map((f) => ({ file: f, detectedAt: '2026-04-17T00:00:00.000Z' })),
      }),
      'utf-8',
    );
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        inflightConflicts: files,
      }),
      'utf-8',
    );

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      const status = engine.getStatus();
      expect(status.conflictCount).toBe(1);
      expect(status.state).toBe('conflict');
      const conflicts = authority.list().map((c) => c.file);
      expect(conflicts).toEqual(['docs/b.md']);
    } finally {
      await engine.destroy();
    }
  });

  test('state transitions out of "conflict" once the last conflict is resolved', async () => {
    const conflictedFile = 'a.md';
    await setupRealMergeConflict([conflictedFile]);

    writeFileSync(
      join(okDir, 'conflicts.json'),
      JSON.stringify({
        version: 1,
        branch: 'main',
        conflicts: [{ file: conflictedFile, detectedAt: '2026-04-17T00:00:00.000Z' }],
      }),
      'utf-8',
    );
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        inflightConflicts: [conflictedFile],
      }),
      'utf-8',
    );

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      expect(engine.getStatus().state).toBe('conflict');

      await authority.resolve(conflictedFile, 'mine');
      const after = engine.getStatus();
      expect(after.conflictCount).toBe(0);
      expect(after.state).not.toBe('conflict');
    } finally {
      await engine.destroy();
    }
  });

  test('names an unrecognized persisted pause reason before dropping it', async () => {
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        pausedReason: 'reason-from-a-newer-build',
        inflightConflicts: [],
      }),
      'utf-8',
    );

    const logs = captureSyncLogs();
    const engine = makeEngine({ syncEnabled: false });
    try {
      await engine.start();
      expect(engine.getStatus().pausedReason).toBeUndefined();

      const dropped = logs.entries.filter(
        (e) => e.level === 'warn' && e.data.event === 'paused-reason-unrecognized',
      );
      expect(dropped).toHaveLength(1);
      expect(dropped[0]?.data).toMatchObject({ pausedReason: 'reason-from-a-newer-build' });
    } finally {
      logs.restore();
      await engine.destroy();
    }
  });

  test('a recognized persisted pause reason is restored without a diagnostic', async () => {
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        pausedReason: 'detached-head',
        inflightConflicts: [],
      }),
      'utf-8',
    );

    const logs = captureSyncLogs();
    const engine = makeEngine({ syncEnabled: false });
    try {
      await engine.start();
      expect(engine.getStatus().pausedReason).toBe('detached-head');
      expect(
        logs.entries.filter((e) => e.data.event === 'paused-reason-unrecognized'),
      ).toHaveLength(0);
    } finally {
      logs.restore();
      await engine.destroy();
    }
  });

  test('ignores state files with unknown version', async () => {
    const persisted = { version: 99, consecutiveFailures: 9999, inflightConflicts: [] };
    writeFileSync(statePath(), JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
  });

  test('tolerates missing state file gracefully', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await expect(engine.start()).resolves.toBeUndefined();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
  });

  test('tolerates corrupt state file gracefully', async () => {
    writeFileSync(statePath(), 'not-json', 'utf-8');
    const engine = makeEngine({ syncEnabled: false });
    await expect(engine.start()).resolves.toBeUndefined();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
  });
});

describe('SyncEngine ConflictStore admission (content-only)', () => {
  async function setupDivergence(remoteAction: 'modify' | 'delete'): Promise<void> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, '.mcp.json'), '{"a":1}\n', 'utf-8');
    writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');
    await sister.add('.');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');

    if (remoteAction === 'modify') {
      writeFileSync(join(sisterDir, '.mcp.json'), '{"a":99}\n', 'utf-8');
      await sister.add('.mcp.json');
      await sister.commit('modify mcp on remote');
    } else {
      await sister.rm('.mcp.json');
      await sister.commit('delete mcp on remote');
    }
    await sister.push('origin', 'main');

    writeFileSync(join(projectDir, '.mcp.json'), '{"a":2}\n', 'utf-8');
    await project.add('.mcp.json');
    await project.commit('modify mcp locally');
  }

  function makeEngineForConflict() {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
    });
  }

  test('modify/modify on .mcp.json auto-resolves cleanly, no ConflictStore entry', async () => {
    await setupDivergence('modify');

    const engine = makeEngineForConflict();
    try {
      await engine.start();
      await engine.pullOnce('sync');

      const status = engine.getStatus();
      expect(status.conflictCount).toBe(0);
      expect(status.state).toBe('idle');
      expect(status.pausedReason).toBeUndefined();

      const mergeHeadPath = join(projectDir, '.git', 'MERGE_HEAD');
      expect(existsSync(mergeHeadPath)).toBe(false);

      const conflictsJsonPath = join(okDir, 'conflicts.json');
      if (existsSync(conflictsJsonPath)) {
        const parsed = JSON.parse(readFileSync(conflictsJsonPath, 'utf-8')) as {
          conflicts?: Array<{ file: string }>;
        };
        expect(parsed.conflicts ?? []).toEqual([]);
      }
    } finally {
      await engine.destroy();
    }
  });

  test('a commit failure after auto-resolving a non-content conflict reports error, not success', async () => {
    await setupDivergence('modify');
    const hookPath = join(projectDir, '.git', 'hooks', 'pre-commit');
    writeFileSync(hookPath, '#!/bin/sh\nexit 1\n', { mode: 0o755 });
    chmodSync(hookPath, 0o755);

    const engine = makeEngineForConflict();
    try {
      await engine.start();
      const outcome = await engine.pullOnce('sync');

      expect(outcome).toBe('error');
      const status = engine.getStatus();
      expect(status.lastPullOutcome).toBe('error');
      expect(status.pullError ?? '').not.toBe('');
      expect(status.state).toBe('idle');
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
    } finally {
      await engine.destroy();
    }
  });

  test('modify/delete on .mcp.json aborts the merge and pauses without ConflictStore entry', async () => {
    await setupDivergence('delete');

    const engine = makeEngineForConflict();
    try {
      await engine.start();
      await engine.pullOnce('sync');

      const status = engine.getStatus();
      expect(status.conflictCount).toBe(0);
      expect(status.state).toBe('idle');
      expect(status.pausedReason).toBe('non-content-merge-failure');
      expect(status.pullError ?? '').toContain('.mcp.json');
      expect(status.pullError ?? '').toContain('git rm <file>');
      expect(status.pullError ?? '').toContain('git checkout');

      const mergeHeadPath = join(projectDir, '.git', 'MERGE_HEAD');
      expect(existsSync(mergeHeadPath)).toBe(false);

      const conflictsJsonPath = join(okDir, 'conflicts.json');
      if (existsSync(conflictsJsonPath)) {
        const parsed = JSON.parse(readFileSync(conflictsJsonPath, 'utf-8')) as {
          conflicts?: Array<{ file: string }>;
        };
        expect(parsed.conflicts ?? []).toEqual([]);
      }
    } finally {
      await engine.destroy();
    }
  });

  test('trigger() clears non-content-merge-failure pausedReason so retry can re-attempt', async () => {
    await setupDivergence('delete');

    const engine = makeEngineForConflict();
    try {
      await engine.start();
      await engine.pullOnce('sync');
      expect(engine.getStatus().pausedReason).toBe('non-content-merge-failure');

      const projectGit = simpleGit(projectDir);
      await projectGit.rm('.mcp.json');
      await projectGit.commit('resolve modify/delete locally');

      await engine.trigger('sync');
      const status = engine.getStatus();
      expect(status.pausedReason).toBeUndefined();
      expect(status.conflictCount).toBe(0);
      expect(status.state).toBe('idle');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine tracked MCP overlap preparation', () => {
  test('matching newer local and incoming launchers do not pause full sync', async () => {
    const bareDir = join(tmpDir, 'mcp-overlap.git');
    const sisterDir = join(tmpDir, 'mcp-overlap-sister');
    mkdirSync(bareDir, { recursive: true });
    mkdirSync(sisterDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const v1 = JSON.stringify({
      mcpServers: {
        other: { command: 'keep-me' },
        'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', '# ok-mcp-v1\nexit 127'] },
      },
    });
    const v2 = v1.replace('# ok-mcp-v1', '# ok-mcp-v2');
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, '.mcp.json'), `${v1}\n`, 'utf-8');
    await sister.add('.mcp.json');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    appendFileSync(join(projectDir, '.git', 'info', 'exclude'), '\n.ok/\n', 'utf-8');

    writeFileSync(join(sisterDir, '.mcp.json'), `${v2}\n`, 'utf-8');
    await sister.add('.mcp.json');
    await sister.commit('incoming v2');
    await sister.push('origin', 'main');

    writeFileSync(join(projectDir, '.mcp.json'), `${v2}\n`, 'utf-8');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: {
        ...stubContentFilter,
        isExcluded: (path: string) => path === '.mcp.json',
      },
      syncEnabled: true,
    });
    try {
      await engine.start();
      const outcome = await engine.pullOnce();
      expect(outcome).toBe('succeeded');
      expect(engine.getStatus().pausedReason).toBeUndefined();
      expect(readFileSync(join(projectDir, '.mcp.json'), 'utf-8')).toBe(`${v2}\n`);
      expect((await simpleGit(projectDir).status()).isClean()).toBe(true);
    } finally {
      await engine.destroy();
    }
  });

  test('full sync keeps a locally newer launcher reconciled as overlay (no interim commit)', async () => {
    const bareDir = join(tmpDir, 'mcp-newer-overlap.git');
    const sisterDir = join(tmpDir, 'mcp-newer-overlap-sister');
    mkdirSync(bareDir, { recursive: true });
    mkdirSync(sisterDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const config = (marker: string, theme: string) =>
      `${JSON.stringify({
        theme,
        mcpServers: {
          other: { command: 'keep-me' },
          'open-knowledge': {
            command: '/bin/sh',
            args: ['-l', '-c', `${marker}\nexit 127`],
          },
        },
      })}\n`;
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v1', 'base'), 'utf8');
    await sister.add('.mcp.json');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v2', 'incoming'), 'utf8');
    await sister.add('.mcp.json');
    await sister.commit('incoming launcher');
    await sister.push('origin', 'main');
    writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99', 'base'), 'utf8');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: {
        ...stubContentFilter,
        isExcluded: (path: string) => path === '.mcp.json',
      },
      syncEnabled: true,
    });
    try {
      await engine.start();
      expect(await engine.pullOnce()).toBe('succeeded');

      const project = simpleGit(projectDir);
      const raw = readFileSync(join(projectDir, '.mcp.json'), 'utf8');
      expect(raw).not.toContain('<<<<<<<');
      expect(JSON.parse(raw)).toEqual(JSON.parse(config('# ok-mcp-v99', 'incoming')));
      expect((await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim()).toBe('');
      expect((await project.log({ maxCount: 1 })).latest?.message).toBe('incoming launcher');
      expect((await project.raw(['stash', 'list'])).trim()).toBe('');
    } finally {
      await engine.destroy();
    }
  });

  test('full sync persists a newer winner in an entry-only generated commit', async () => {
    const project = simpleGit(projectDir);
    await project.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');
    const entry = (marker: string) => ({
      command: '/bin/sh',
      args: ['-l', '-c', `${marker}\nexit 127`],
    });
    const config = (marker: string) =>
      `${JSON.stringify({
        theme: 'keep',
        mcpServers: {
          other: { command: 'keep-me' },
          'open-knowledge': entry(marker),
        },
      })}\n`;
    writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v2'), 'utf8');
    await project.add('.mcp.json');
    await project.commit('base');
    writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
    });
    await (
      engine as unknown as {
        persistReconciledMcpEntries: (
          entries: Array<{ path: string; raw: string; winnerEntry: Record<string, unknown> }>,
        ) => Promise<void>;
      }
    ).persistReconciledMcpEntries([
      {
        path: '.mcp.json',
        raw: config('# ok-mcp-v99'),
        winnerEntry: entry('# ok-mcp-v99'),
      },
    ]);

    expect((await project.log({ maxCount: 1 })).latest?.message).toBe(
      'Update OpenKnowledge MCP launcher',
    );
    expect(await project.show(['--format=', '--name-only', 'HEAD'])).toBe('.mcp.json\n');
    expect(JSON.parse(readFileSync(join(projectDir, '.mcp.json'), 'utf8'))).toEqual(
      JSON.parse(config('# ok-mcp-v99')),
    );
    expect((await project.status()).files).toEqual([]);
    const committed = JSON.parse(await project.show(['HEAD:.mcp.json'])) as {
      theme: string;
      mcpServers: Record<string, unknown>;
    };
    expect(committed.theme).toBe('keep');
    expect(committed.mcpServers.other).toEqual({ command: 'keep-me' });
  });

  test('push retry persists a locally newer launcher after a non-fast-forward rejection', async () => {
    const bareDir = join(tmpDir, 'mcp-push-retry.git');
    const sisterDir = join(tmpDir, 'mcp-push-retry-sister');
    mkdirSync(bareDir, { recursive: true });
    mkdirSync(sisterDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const config = (marker: string) =>
      `${JSON.stringify({
        mcpServers: {
          other: { command: 'keep-me' },
          'open-knowledge': {
            command: '/bin/sh',
            args: ['-l', '-c', `${marker}\nexit 127`],
          },
        },
      })}\n`;
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, '.gitignore'), '/.ok/*\n', 'utf8');
    writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v1'), 'utf8');
    writeFileSync(join(sisterDir, 'shared.md'), 'base\n', 'utf8');
    await sister.add(['.gitignore', '.mcp.json', 'shared.md']);
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    await simpleGit(projectDir).raw(['config', 'user.name', '']);
    await simpleGit(projectDir).raw(['config', 'user.email', '']);

    writeFileSync(join(sisterDir, '.mcp.json'), config('# ok-mcp-v2'), 'utf8');
    await sister.add('.mcp.json');
    await sister.commit('incoming launcher');
    await sister.push('origin', 'main');

    writeFileSync(join(projectDir, '.mcp.json'), config('# ok-mcp-v99'), 'utf8');
    writeFileSync(join(projectDir, 'local.md'), 'local content\n', 'utf8');
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: {
        ...stubContentFilter,
        isExcluded: (path: string) => path === '.mcp.json',
      },
      syncEnabled: true,
      pullIntervalSeconds: 99999,
      pushIntervalSeconds: 99999,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      const project = simpleGit(projectDir);
      const raw = readFileSync(join(projectDir, '.mcp.json'), 'utf8');
      expect(raw).not.toContain('<<<<<<<');
      expect(JSON.parse(raw)).toEqual(JSON.parse(config('# ok-mcp-v99')));
      expect((await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim()).toBe('');
      const status = await project.status();
      expect(status.files.filter((file) => file.path !== '.mcp.json')).toEqual([]);
      expect(status.files.find((file) => file.path === '.mcp.json')?.index ?? ' ').toBe(' ');
      expect((await project.raw(['stash', 'list'])).trim()).toBe('');
      expect(JSON.parse(await bare.show(['main:.mcp.json']))).toEqual(
        JSON.parse(config('# ok-mcp-v99')),
      );
      expect(await bare.show(['main:local.md'])).toBe('local content\n');
      expect((await project.log({ maxCount: 1 })).latest?.message).toBe(
        'Update OpenKnowledge MCP launcher',
      );
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine delete/modify dirty content conflicts', () => {
  async function setupRemoteModifyLocalDelete(): Promise<void> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');
    await sister.add('foo.md');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push(['--set-upstream', 'origin', 'main']);
    await bare.raw(['symbolic-ref', 'HEAD', 'refs/heads/main']);

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir, ['--branch', 'main']);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');

    writeFileSync(join(sisterDir, 'foo.md'), 'remote edit\n', 'utf-8');
    await sister.add('foo.md');
    await sister.commit('remote modify');
    await sister.push('origin', 'main');

    rmSync(join(projectDir, 'foo.md'), { force: true });
  }

  async function setupRemoteDeleteLocalModify(): Promise<void> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');
    await sister.add('foo.md');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push(['--set-upstream', 'origin', 'main']);
    await bare.raw(['symbolic-ref', 'HEAD', 'refs/heads/main']);

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir, ['--branch', 'main']);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');

    await sister.rm('foo.md');
    await sister.commit('remote delete');
    await sister.push('origin', 'main');

    writeFileSync(join(projectDir, 'foo.md'), 'local edit\n', 'utf-8');
  }

  function makeProjectRootEngine(
    opts: { onContentConflictsDetected?: (files: string[]) => void } = {},
  ) {
    const conflicts = newAuthority();
    const detected = opts.onContentConflictsDetected;
    if (detected !== undefined) {
      conflicts.subscribe((change) => {
        if (change.type === 'raised') detected([change.conflict.file]);
      });
    }
    return new SyncEngine({
      conflicts,
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      pullIntervalSeconds: 99999,
      pushIntervalSeconds: 99999,
    });
  }

  test('surfaces a conflict when remote modifies a file deleted locally', async () => {
    await setupRemoteModifyLocalDelete();

    const engine = makeProjectRootEngine();
    try {
      await engine.start();
      await engine.trigger('sync');

      const status = engine.getStatus();
      expect(status.state).toBe('conflict');
      expect(status.conflictCount).toBe(1);
      expect(status.pausedReason).toBeUndefined();
      expect(authority.list().map((c) => c.file)).toEqual(['foo.md']);
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);

      const project = simpleGit(projectDir);
      const unmerged = (await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim();
      expect(unmerged).toBe('foo.md');

      const log = await project.raw(['log', '--oneline', '--max-count=5']);
      expect(log).not.toContain('Auto-save: interim before merge');
    } finally {
      await engine.destroy();
    }
  });

  test('notifies loaded-doc callback when remote deletes a file modified locally', async () => {
    await setupRemoteDeleteLocalModify();

    const notified: string[][] = [];
    const engine = makeProjectRootEngine({
      onContentConflictsDetected: (files) => {
        notified.push([...files]);
      },
    });
    try {
      await engine.start();
      await engine.trigger('sync');

      const status = engine.getStatus();
      expect(status.state).toBe('conflict');
      expect(status.conflictCount).toBe(1);
      expect(authority.list().map((c) => c.file)).toEqual(['foo.md']);
      expect(notified).toEqual([['foo.md']]);

      const project = simpleGit(projectDir);
      const unmerged = (await project.raw(['diff', '--name-only', '--diff-filter=U'])).trim();
      expect(unmerged).toBe('foo.md');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine non-ASCII filename conflicts', () => {
  const fileName = 'hyvää yötä.md';

  async function setupRemoteModifyLocalDeleteNonAscii(): Promise<void> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, fileName), 'base\n', 'utf-8');
    await sister.add([fileName]);
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push(['--set-upstream', 'origin', 'main']);
    await bare.raw(['symbolic-ref', 'HEAD', 'refs/heads/main']);

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir, ['--branch', 'main']);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');

    writeFileSync(join(sisterDir, fileName), 'remote edit\n', 'utf-8');
    await sister.add([fileName]);
    await sister.commit('remote modify');
    await sister.push('origin', 'main');

    rmSync(join(projectDir, fileName), { force: true });
  }

  test('surfaces a content conflict with the real UTF-8 path', async () => {
    await setupRemoteModifyLocalDeleteNonAscii();

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      pullIntervalSeconds: 99999,
      pushIntervalSeconds: 99999,
    });
    try {
      await engine.start();
      await engine.trigger('sync');

      const status = engine.getStatus();
      expect(status.state).toBe('conflict');
      expect(status.conflictCount).toBe(1);
      expect(status.pausedReason).toBeUndefined();
      expect(authority.list().map((c) => c.file)).toEqual([fileName]);
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine getStatus()', () => {
  test('returns all required fields in dormant state', () => {
    const engine = makeEngine();
    const status = engine.getStatus();
    expect(status).toHaveProperty('state', 'dormant');
    expect(status).toHaveProperty('lastSyncUtc', null);
    expect(status).toHaveProperty('lastFetchUtc', null);
    expect(status).toHaveProperty('lastPushedSha', null);
    expect(status).toHaveProperty('ahead', 0);
    expect(status).toHaveProperty('behind', 0);
    expect(status).toHaveProperty('consecutiveFailures', 0);
    expect(status).toHaveProperty('conflictCount', 0);
    expect(status).toHaveProperty('hasRemote', false);
  });
});

describe('SyncEngine push gating — scheduled vs explicit', () => {
  async function projectWithUnpushedCommit() {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# seed\n');
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    const originBefore = (await git.revparse(['origin/main'])).trim();

    writeFileSync(join(projectDir, 'README.md'), '# seed\n\nlocal edit\n');
    await git.add('.');
    await git.commit('local commit not pushed');
    const localHead = (await git.revparse(['HEAD'])).trim();

    return { git, localHead, originBefore };
  }

  test.each(['off', 'follow'] as const)(
    "%s never pushes on the engine's own initiative",
    async (mode) => {
      const { git, originBefore } = await projectWithUnpushedCommit();
      const engine = makeEngine({ mode });
      await engine.refreshRemote();
      try {
        await (engine as unknown as { runPushCycle: () => Promise<void> }).runPushCycle();

        expect((await git.revparse(['origin/main'])).trim()).toBe(originBefore);
        expect(engine.getStatus().lastPushedSha).toBeNull();
      } finally {
        await engine.destroy();
      }
    },
  );

  test.each(['off', 'follow'] as const)(
    '%s pushes when the user explicitly asks, without arming a loop',
    async (mode) => {
      const { git, localHead } = await projectWithUnpushedCommit();
      const engine = makeEngine({ mode });
      await engine.refreshRemote();
      try {
        await engine.pushOnce();

        expect((await git.revparse(['origin/main'])).trim()).toBe(localHead);
        expect(engine.getStatus().lastPushedSha).toBe(localHead);
        expect(engine.getStatus().syncMode).toBe(mode);
      } finally {
        await engine.destroy();
      }
    },
  );

  test('refuses when there is no remote to push to', async () => {
    const engine = makeEngine({ mode: 'off' });
    const states: SyncState[] = [];
    engine.onStateChange = (s) => states.push(s);

    await engine.pushOnce();

    expect(states).not.toContain('pushing');
  });
});

describe('SyncEngine lastRunUtc — "Updated N ago"', () => {
  async function currentProject() {
    const bare = join(tmpDir, 'bare.git');
    mkdirSync(bare, { recursive: true });
    await simpleGit(bare).init(true);
    configureTestGitRepository(bare);
    await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'doc.md'), 'v1\n');
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', bare);
    await git.push(['--set-upstream', 'origin', 'main']);
    return git;
  }

  test('a pull that finds nothing new still counts as a run', async () => {
    await currentProject();
    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      const before = engine.getStatus();
      expect(before.lastRunUtc).toBeNull();

      await engine.pullOnce();

      const after = engine.getStatus();
      expect(after.lastRunUtc).not.toBeNull();
      expect(after.lastSyncUtc).toBe(before.lastSyncUtc);
    } finally {
      await engine.destroy();
    }
  });

  test('an explicit push counts as a run', async () => {
    await currentProject();
    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      await engine.pushOnce();
      expect(engine.getStatus().lastRunUtc).not.toBeNull();
    } finally {
      await engine.destroy();
    }
  });

  test('the panel-open fetch does NOT count as a run', async () => {
    await currentProject();
    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      expect(await engine.fetchOnly()).toBe(true);
      expect(engine.getStatus().lastRunUtc).toBeNull();
    } finally {
      await engine.destroy();
    }
  });

  test('a push cycle that exits without landing does not stamp a run', async () => {
    await currentProject();
    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      (engine as unknown as { doPushCycle: () => Promise<void> }).doPushCycle = async () => {};
      await engine.pushOnce();
      expect(engine.getStatus().lastRunUtc).toBeNull();
    } finally {
      await engine.destroy();
    }
  });

  test('a failed op does not stamp a run', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'doc.md'), 'v1\n');
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', join(tmpDir, 'nope.git'));

    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      await engine.fetchOnly();
      expect(engine.getStatus().lastRunUtc).toBeNull();
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine unified pull — B1 in every mode', () => {
  async function projectWithSister() {
    const bare = join(tmpDir, 'bare.git');
    mkdirSync(bare, { recursive: true });
    await simpleGit(bare).init(true);
    configureTestGitRepository(bare);
    await simpleGit(bare).raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(
      join(projectDir, 'doc.md'),
      'TOP\n\n\n\n\n\n\n\n\n\nMIDDLE\n\n\n\n\n\n\n\n\n\nBOTTOM\n',
    );
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', bare);
    await git.push(['--set-upstream', 'origin', 'main']);

    const sisterDir = join(tmpDir, 'sister');
    await simpleGit(tmpDir).clone(bare, sisterDir);
    configureTestGitRepository(sisterDir);
    const sister = simpleGit(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    return { git, sister, sisterDir };
  }

  function makeRootContentEngine(mode: SyncMode) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode,
    });
  }

  test('a full-mode pull never authors a commit from the dirty tree (FR-1)', async () => {
    const { git, sister, sisterDir } = await projectWithSister();
    writeFileSync(join(sisterDir, 'other.md'), 'teammate\n');
    await sister.add('.');
    await sister.commit('teammate adds other.md');
    await sister.push();

    writeFileSync(join(projectDir, 'doc.md'), 'TOP-mine\n');

    const engine = makeRootContentEngine('full');
    await engine.refreshRemote();
    try {
      expect(await engine.pullOnce()).toBe('succeeded');

      const log = await git.log();
      expect(log.all.some((c) => c.message === 'Auto-save: interim before merge')).toBe(false);
      expect(log.latest?.message).toBe('teammate adds other.md');
      expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('TOP-mine\n');
      expect(readFileSync(join(projectDir, 'other.md'), 'utf-8')).toBe('teammate\n');
    } finally {
      await engine.destroy();
    }
  });

  test('full-mode separated edits to one file auto-combine without a conflict (FR-2)', async () => {
    const { sister, sisterDir } = await projectWithSister();
    const seeded = readFileSync(join(sisterDir, 'doc.md'), 'utf-8');
    writeFileSync(join(sisterDir, 'doc.md'), seeded.replace('TOP', 'TOP-THEIRS'));
    await sister.add('.');
    await sister.commit('teammate edits top');
    await sister.push();

    const local = readFileSync(join(projectDir, 'doc.md'), 'utf-8');
    writeFileSync(join(projectDir, 'doc.md'), local.replace('BOTTOM', 'BOTTOM-MINE'));

    const engine = makeRootContentEngine('full');
    await engine.refreshRemote();
    try {
      expect(await engine.pullOnce()).toBe('succeeded');

      const merged = readFileSync(join(projectDir, 'doc.md'), 'utf-8');
      expect(merged).toContain('TOP-THEIRS');
      expect(merged).toContain('BOTTOM-MINE');
      expect(engine.getStatus().conflictCount).toBe(0);
    } finally {
      await engine.destroy();
    }
  });

  test.each(['off', 'follow', 'full'] as const)(
    'diverged committed history: Pull refuses, Pull-and-Push merges — mode %s (FR-5)',
    async (mode) => {
      const { git, sister, sisterDir } = await projectWithSister();
      writeFileSync(join(sisterDir, 'theirs.md'), 'theirs\n');
      await sister.add('.');
      await sister.commit('teammate commit');
      await sister.push();

      writeFileSync(join(projectDir, 'mine.md'), 'mine\n');
      await git.add('.');
      await git.commit('local commit');

      const engine = makeRootContentEngine(mode);
      await engine.refreshRemote();
      try {
        expect(await engine.pullOnce()).toBe('refused');
        expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');

        await engine.pullOnce('sync');

        expect(engine.getStatus().pausedReason).toBeUndefined();
        expect(existsSync(join(projectDir, 'theirs.md'))).toBe(true);
        expect(existsSync(join(projectDir, 'mine.md'))).toBe(true);
      } finally {
        await engine.destroy();
      }
    },
  );

  test.each(['off', 'follow', 'full'] as const)(
    'the Sync verb keeps the classic commit+merge machinery — mode %s',
    async (mode) => {
      const { git, sister, sisterDir } = await projectWithSister();
      const seeded = readFileSync(join(sisterDir, 'doc.md'), 'utf-8');
      writeFileSync(join(sisterDir, 'doc.md'), seeded.replace('TOP', 'TOP-THEIRS'));
      await sister.add('.');
      await sister.commit('teammate edits top');
      await sister.push();

      const local = readFileSync(join(projectDir, 'doc.md'), 'utf-8');
      writeFileSync(join(projectDir, 'doc.md'), local.replace('BOTTOM', 'BOTTOM-MINE'));

      const engine = makeRootContentEngine(mode);
      await engine.refreshRemote();
      try {
        expect(await engine.pullOnce('sync')).toBe('succeeded');

        const merged = readFileSync(join(projectDir, 'doc.md'), 'utf-8');
        expect(merged).toContain('TOP-THEIRS');
        expect(merged).toContain('BOTTOM-MINE');
        const log = await git.log();
        expect(log.all.some((c) => c.message === 'Auto-save: interim before merge')).toBe(true);
      } finally {
        await engine.destroy();
      }
    },
  );

  test('follow mode keeps a local artifact edit that origin also changed (the phantom-offline fix)', async () => {
    const { sister, sisterDir } = await projectWithSister();
    mkdirSync(join(sisterDir, '.ok'), { recursive: true });
    writeFileSync(join(sisterDir, '.ok', 'config.yml'), 'shared: remote\n');
    await sister.add(['.ok/config.yml']);
    await sister.commit('teammate edits config');
    await sister.push();

    mkdirSync(join(projectDir, '.ok'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'shared: local\n');

    const engine = makeRootContentEngine('follow');
    try {
      await engine.start();
      await vi.waitFor(
        () => {
          expect(engine.getStatus().behind).toBe(0);
        },
        { timeout: 10_000, interval: 100 },
      );

      const status = engine.getStatus();
      expect(status.state).not.toBe('offline');
      expect(status.pullError).toBeUndefined();
      expect(readFileSync(join(projectDir, '.ok', 'config.yml'), 'utf-8')).toBe('shared: local\n');
    } finally {
      await engine.destroy();
    }
  });

  test('pending ledger conflicts gate the push cycle', async () => {
    const { sister, sisterDir } = await projectWithSister();
    const seeded = readFileSync(join(sisterDir, 'doc.md'), 'utf-8');
    writeFileSync(join(sisterDir, 'doc.md'), seeded.replace('MIDDLE', 'MIDDLE-THEIRS'));
    await sister.add('.');
    await sister.commit('teammate edits middle');
    await sister.push();

    const local = readFileSync(join(projectDir, 'doc.md'), 'utf-8');
    writeFileSync(join(projectDir, 'doc.md'), local.replace('MIDDLE', 'MIDDLE-MINE'));

    const engine = makeRootContentEngine('full');
    await engine.refreshRemote();
    try {
      await engine.pullOnce();
      expect(engine.getStatus().conflictCount).toBe(1);

      const states: SyncState[] = [];
      engine.onStateChange = (st) => states.push(st);
      await engine.pushOnce();
      expect(states).not.toContain('pushing');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine fetchOnly() — the read-only op', () => {
  test('refreshes tracking refs and counts without touching the working tree', async () => {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'doc.md'), 'v1\n');
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    const localHead = (await git.revparse(['HEAD'])).trim();

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.clone(bareDir, sisterDir);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'doc.md'), 'v1\nv2\n');
    await sister.add('.');
    await sister.commit('sister edit');
    await sister.push();

    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      expect(await engine.fetchOnly()).toBe(true);

      expect(engine.getStatus().behind).toBe(1);
      expect((await git.revparse(['HEAD'])).trim()).toBe(localHead);
      expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('v1\n');
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
    } finally {
      await engine.destroy();
    }
  });

  test('a failed fetch stays quiet — no error surfaced, no pause', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'doc.md'), 'v1\n');
    await git.add('.');
    await git.commit('seed');
    await git.addRemote('origin', join(tmpDir, 'does-not-exist.git'));

    const engine = makeEngine({ mode: 'off' });
    await engine.refreshRemote();
    try {
      expect(await engine.fetchOnly()).toBe(false);

      const status = engine.getStatus();
      expect(status.pullError).toBeUndefined();
      expect(status.pullErrorCode).toBeUndefined();
      expect(status.pausedReason).toBeUndefined();
      expect(status.state).not.toBe('auth-error');
    } finally {
      await engine.destroy();
    }
  });

  test('declines without a remote rather than shelling out', async () => {
    const engine = makeEngine({ mode: 'off' });
    expect(await engine.fetchOnly()).toBe(false);
  });
});

describe('SyncEngine no-remote detection', () => {
  test('stays dormant if project dir has no git remote (no .git/)', async () => {
    const engine = makeEngine();
    await engine.start();
    expect(engine.getStatus().state).toBe('dormant');
    expect(engine.getStatus().hasRemote).toBe(false);
  });
});

describe('SyncEngine refreshRemote()', () => {
  test('is a no-op when hasRemote is already true', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);
    await git.addRemote('origin', 'https://example.invalid/repo.git');

    const states: SyncState[] = [];
    const engine = makeEngine({ syncEnabled: false, onStateChange: (s) => states.push(s) });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(true);
    expect(engine.getStatus().state).toBe('disabled');

    const callsBefore = states.length;
    await engine.refreshRemote();
    expect(states.length).toBe(callsBefore);
    expect(engine.getStatus().hasRemote).toBe(true);
  });

  test('detects a newly-added remote and transitions dormant → disabled (syncEnabled=false)', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);

    const states: SyncState[] = [];
    const engine = makeEngine({ syncEnabled: false, onStateChange: (s) => states.push(s) });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(false);
    expect(engine.getStatus().state).toBe('dormant');

    await git.addRemote('origin', 'https://example.invalid/repo.git');

    await engine.refreshRemote();

    expect(engine.getStatus().hasRemote).toBe(true);
    expect(engine.getStatus().state).toBe('disabled');
    expect(states).toContain('disabled');
  });

  test('detects a newly-added remote and transitions dormant → idle (syncEnabled=true)', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);

    const states: SyncState[] = [];
    const engine = makeEngine({ syncEnabled: true, onStateChange: (s) => states.push(s) });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(false);
    expect(engine.getStatus().state).toBe('dormant');

    await git.addRemote('origin', 'https://example.invalid/repo.git');

    await engine.refreshRemote();

    expect(engine.getStatus().hasRemote).toBe(true);
    expect(engine.getStatus().state).toBe('idle');
    expect(states).toContain('idle');

    engine.stop();
  });

  test('stays dormant when no remote was added since boot', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(false);

    await engine.refreshRemote();

    expect(engine.getStatus().hasRemote).toBe(false);
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('tolerates missing .git/ without throwing', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    await expect(engine.refreshRemote()).resolves.toBeUndefined();
    expect(engine.getStatus().hasRemote).toBe(false);
  });
});

describe('SyncEngine setEnabled() — unconditional remote re-probe', () => {
  test('setEnabled(true) demotes to dormant when remote was removed since boot', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);
    await git.addRemote('origin', 'https://example.invalid/repo.git');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(true);
    expect(engine.getStatus().state).toBe('disabled');

    await git.removeRemote('origin');

    await engine.setEnabled(true);

    expect(engine.getStatus().hasRemote).toBe(false);
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('setEnabled(true) transitions dormant → idle when remote was added since boot', async () => {
    const git = simpleGit(projectDir);
    await git.init();
    configureTestGitRepository(projectDir);

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().hasRemote).toBe(false);
    expect(engine.getStatus().state).toBe('dormant');

    await git.addRemote('origin', 'https://example.invalid/repo.git');

    await engine.setEnabled(true);

    expect(engine.getStatus().hasRemote).toBe(true);
    expect(engine.getStatus().state).toBe('idle');

    engine.stop();
  });
});

describe('SyncEngine updateCurrentBranch()', () => {
  test('transitions to disabled when branch is null (detached HEAD)', () => {
    const states: SyncState[] = [];
    const engine = makeEngine({ onStateChange: (s) => states.push(s) });
    engine.updateCurrentBranch(null);
    expect(engine.getStatus().state).toBe('dormant');
    expect(states).toEqual([]);
  });
});

describe('SyncEngine backoff thresholds via persisted state', () => {
  const statePath = () => join(okDir, 'sync-state.json');

  function persistState(overrides: Record<string, unknown>) {
    const base = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 0,
      inflightConflicts: [],
    };
    writeFileSync(statePath(), JSON.stringify({ ...base, ...overrides }), 'utf-8');
  }

  test('consecutiveFailures=0 is restored and stays in default interval range', async () => {
    persistState({ consecutiveFailures: 0 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
  });

  test('consecutiveFailures=3 is restored (5 min backoff threshold)', async () => {
    persistState({ consecutiveFailures: 3 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(3);
  });

  test('consecutiveFailures=5 is restored (15 min backoff threshold)', async () => {
    persistState({ consecutiveFailures: 5 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(5);
  });

  test('consecutiveFailures=8 is restored (60 min backoff threshold)', async () => {
    persistState({ consecutiveFailures: 8 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(8);
  });

  test('trigger() resets consecutiveFailures to 0', async () => {
    persistState({ consecutiveFailures: 5 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(5);
    await engine.trigger();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
  });

  test('consecutivePushFailures is restored independently of the pull leg', async () => {
    persistState({ consecutiveFailures: 2, consecutivePushFailures: 6 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(2);
    expect(engine.getStatus().consecutivePushFailures).toBe(6);
  });

  test('a state file predating the push leg restores it as 0', async () => {
    persistState({ consecutiveFailures: 4 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().consecutiveFailures).toBe(4);
    expect(engine.getStatus().consecutivePushFailures).toBe(0);
  });

  test('the connectivity latch survives a restart, so the release stays available', async () => {
    persistState({ consecutivePushFailures: 4, pushStreakIsConnectivity: true });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    const internals = engine as unknown as { pushStreakIsConnectivity: boolean };
    expect(engine.getStatus().consecutivePushFailures).toBe(4);
    expect(internals.pushStreakIsConnectivity).toBe(true);
  });

  test('the latch round-trips through saveStateNow, not just through a hand-written file', async () => {
    const writer = makeEngine({ syncEnabled: false });
    await writer.start();
    const internals = writer as unknown as {
      consecutivePushFailures: number;
      pushStreakIsConnectivity: boolean;
      saveStateNow(): void;
    };
    internals.consecutivePushFailures = 3;
    internals.pushStreakIsConnectivity = true;
    internals.saveStateNow();
    await writer.stop();

    const reader = makeEngine({ syncEnabled: false });
    await reader.start();
    expect({
      streak: reader.getStatus().consecutivePushFailures,
      latch: (reader as unknown as { pushStreakIsConnectivity: boolean }).pushStreakIsConnectivity,
    }).toEqual({ streak: 3, latch: true });
    await reader.stop();
  });

  test('a state file predating the latch restores it as not-dischargeable', async () => {
    persistState({ consecutivePushFailures: 6 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    const internals = engine as unknown as { pushStreakIsConnectivity: boolean };
    expect(engine.getStatus().consecutivePushFailures).toBe(6);
    expect(internals.pushStreakIsConnectivity).toBe(false);
  });

  test('trigger() resets both legs', async () => {
    persistState({ consecutiveFailures: 5, consecutivePushFailures: 7 });
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    await engine.trigger();
    expect(engine.getStatus().consecutiveFailures).toBe(0);
    expect(engine.getStatus().consecutivePushFailures).toBe(0);
  });
});

describe('SyncEngine pull-only cadence', () => {
  test.each(JITTER_SAMPLES)(
    'a follower with no credentials pulls at the configured interval (draw $draw)',
    ({ draw, edge }) => {
      const random = vi.spyOn(Math, 'random').mockReturnValue(draw);
      onTestFinished(() => random.mockRestore());
      const engine = new SyncEngine({
        conflicts: newAuthority(),
        projectDir,
        contentDir,
        contentFilter: stubContentFilter,
        mode: 'follow',
        pullIntervalSeconds: 30,
        pushIntervalSeconds: 99999,
      });
      const internals = engine as unknown as { effectivePullDelayMs(): number };
      expect(internals.effectivePullDelayMs()).toBe(jitterBand(30)[edge]);
    },
  );
});

describe('SyncEngine lastRunUtc survives a restart', () => {
  test('a restored engine reports the run stamp its legs restored', async () => {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
    });
    const internals = engine as unknown as {
      lastPullOkUtc: string | null;
      lastPushOkUtc: string | null;
      saveStateNow(): void;
    };
    try {
      internals.lastPullOkUtc = '2026-08-24T10:00:00.000Z';
      internals.lastPushOkUtc = '2026-08-24T09:00:00.000Z';
      expect(engine.getStatus().lastRunUtc).toBe('2026-08-24T10:00:00.000Z');
      internals.saveStateNow();
    } finally {
      await engine.destroy();
    }

    const restored = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
    });
    try {
      await restored.start();
      const status = restored.getStatus();
      expect(status.lastPullOkUtc).toBe('2026-08-24T10:00:00.000Z');
      expect(status.lastRunUtc).toBe('2026-08-24T10:00:00.000Z');
    } finally {
      await restored.destroy();
    }
  });
});

describe('SyncEngine unborn-HEAD guard', () => {
  async function initRepoWithOrigin(withCommit: boolean) {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    const bareDir = join(tmpDir, 'unborn-bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    await git.addRemote('origin', bareDir);
    if (withCommit) {
      writeFileSync(join(projectDir, 'README.md'), 'seed\n', 'utf-8');
      await git.add('.');
      await git.commit('seed');
    }
  }

  function makeEngine() {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'off',
    });
    (engine as unknown as { hasRemote: boolean }).hasRemote = true;
    return engine;
  }

  test('pullOnce refuses on an unborn HEAD even with a remote configured', async () => {
    await initRepoWithOrigin(false);
    const engine = makeEngine();
    try {
      expect(await engine.pullOnce()).toBe('refused');
    } finally {
      await engine.destroy();
    }
  });

  test('a repo with one commit is no longer unborn and gets past the guard', async () => {
    await initRepoWithOrigin(true);
    const engine = makeEngine();
    try {
      expect(await engine.pullOnce()).not.toBe('refused');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine one-shot push guards', () => {
  type PushInternals = {
    cycleInFlight: 'pull' | 'push' | null;
    conflictCount: number;
    state: string;
    hasRemote: boolean;
    doPushCycle(retriesLeft?: number): Promise<void>;
    runOneShotPush(): Promise<void>;
  };

  function makeOneShotEngine(mode: SyncMode = 'follow') {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode,
    });
    const internals = engine as unknown as PushInternals;
    internals.hasRemote = true;
    internals.state = 'idle';
    const cycles: number[] = [];
    internals.doPushCycle = async (retriesLeft = 0) => {
      cycles.push(retriesLeft);
    };
    return { engine, internals, cycles };
  }

  test('refuses while a pull is in flight rather than racing it', async () => {
    const { engine, internals, cycles } = makeOneShotEngine();
    try {
      internals.cycleInFlight = 'pull';
      await engine.pushOnce();
      expect(cycles).toEqual([]);
    } finally {
      await engine.destroy();
    }
  });

  test('refuses while conflicts hold the tree', async () => {
    const { engine, cycles } = makeOneShotEngine();
    try {
      authority.raise({ kind: 'merge-native', file: 'a.md' });
      await engine.pushOnce();
      expect(cycles).toEqual([]);
    } finally {
      await engine.destroy();
    }
  });

  test('refuses while parked on an auth error', async () => {
    const { engine, internals, cycles } = makeOneShotEngine();
    try {
      internals.state = 'auth-error';
      await engine.pushOnce();
      expect(cycles).toEqual([]);
    } finally {
      await engine.destroy();
    }
  });

  test('pushes when nothing blocks it — the control', async () => {
    const { engine, cycles } = makeOneShotEngine();
    try {
      await engine.pushOnce();
      expect(cycles).toHaveLength(1);
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine push chain survives a B1 conflict', () => {
  type ChainInternals = {
    schedulePush(overrideDelayMs?: number): void;
    pushTimer: ReturnType<typeof setTimeout> | null;
    conflictCount: number;
    runPushCycle(): Promise<void>;
  };

  test('a push tick with ledger conflicts re-arms the chain instead of ending it', async () => {
    const conflicts = newAuthority();
    conflicts.raise({ kind: 'merge-native', file: 'a.md' });
    const engine = new SyncEngine({
      conflicts,
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
      detectGh: () => ({ available: true, token: 'gh-token' }),
    });
    const internals = engine as unknown as ChainInternals;
    const rearms: Array<number | undefined> = [];
    internals.schedulePush = (d?: number) => {
      rearms.push(d);
    };
    (internals as unknown as { state: string }).state = 'idle';

    await internals.runPushCycle();

    expect(rearms).toHaveLength(1);
  });

  test('an emptied ledger restarts both legs even though B1 left the state idle', async () => {
    const conflicts = newAuthority();
    conflicts.raise({ kind: 'merge-native', file: 'a.md' });
    const engine = new SyncEngine({
      conflicts,
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
    });
    const internals = engine as unknown as ChainInternals & {
      state: string;
      subscribeToConflicts(): void;
      schedulePull(overrideDelayMs?: number): void;
    };
    const pushRearms: Array<number | undefined> = [];
    const pullRearms: Array<number | undefined> = [];
    internals.schedulePush = (d?: number) => {
      pushRearms.push(d);
    };
    internals.schedulePull = (d?: number) => {
      pullRearms.push(d);
    };
    internals.subscribeToConflicts();
    internals.state = 'conflict';

    await conflicts.pruneMergeNativeAgainstGit();

    expect(pushRearms).toHaveLength(1);
    expect(pullRearms).toHaveLength(1);
  });
});

describe('SyncEngine enable schedules both legs immediately', () => {
  type EnableInternals = {
    schedulePull(overrideDelayMs?: number): void;
    schedulePush(overrideDelayMs?: number): void;
    probeRemote(): Promise<boolean>;
    probePushPermissionInternal(reason: string): Promise<void>;
  };

  test('enabling full sync schedules the push at 0, not a full interval out', async () => {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'off',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 3600,
      detectGh: () => ({ available: true, token: 'gh-token' }),
    });
    const internals = engine as unknown as EnableInternals;
    internals.probeRemote = async () => true;
    internals.probePushPermissionInternal = async () => {};
    const pullDelays: Array<number | undefined> = [];
    const pushDelays: Array<number | undefined> = [];
    internals.schedulePull = (d?: number) => {
      pullDelays.push(d);
    };
    internals.schedulePush = (d?: number) => {
      pushDelays.push(d);
    };

    await engine.setMode('full');

    expect(pullDelays).toEqual([0]);
    expect(pushDelays).toEqual([0]);
  });
});

describe('SyncEngine setIntervals()', () => {
  type IntervalInternals = {
    effectivePullDelayMs(): number;
    pullIntervalSeconds: number;
    pushIntervalSeconds: number;
    pullTimer: ReturnType<typeof setTimeout> | null;
    pushTimer: ReturnType<typeof setTimeout> | null;
    schedulePull(overrideDelayMs?: number): void;
  };

  function makeIntervalEngine(mode: SyncMode) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode,
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
      detectGh: () => ({ available: true, token: 'gh-token' }),
    });
  }

  test('a new pull interval changes the delay the engine would schedule', async () => {
    const engine = makeIntervalEngine('follow');
    const internals = engine as unknown as IntervalInternals;
    engine.setIntervals(900, 60);
    const delayMs = internals.effectivePullDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(900).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(900).max);
  });

  test('pull and push move independently', () => {
    const engine = makeIntervalEngine('full');
    const internals = engine as unknown as IntervalInternals;
    engine.setIntervals(30, 3600);
    expect(internals.pullIntervalSeconds).toBe(30);
    expect(internals.pushIntervalSeconds).toBe(3600);
  });

  test('a same-value call does not re-arm the timers', () => {
    const engine = makeIntervalEngine('follow');
    const internals = engine as unknown as IntervalInternals;
    internals.schedulePull();
    try {
      const pullTimerBefore = internals.pullTimer;
      expect(pullTimerBefore).not.toBeNull();
      engine.setIntervals(30, 60);
      expect(internals.pullTimer).toBe(pullTimerBefore);
    } finally {
      engine.stop();
    }
  });

  test('a changed interval re-arms an armed timer rather than waiting it out', () => {
    const engine = makeIntervalEngine('follow');
    const internals = engine as unknown as IntervalInternals;
    internals.schedulePull();
    try {
      const pullTimerBefore = internals.pullTimer;
      engine.setIntervals(3600, 60);
      expect(internals.pullTimer).not.toBe(pullTimerBefore);
      expect(internals.pullTimer).not.toBeNull();
    } finally {
      engine.stop();
    }
  });

  test('an unarmed timer stays unarmed — a cadence change must not start a loop', () => {
    const engine = makeIntervalEngine('off');
    const internals = engine as unknown as IntervalInternals;
    expect(internals.pullTimer).toBeNull();
    engine.setIntervals(300, 300);
    expect(internals.pullTimer).toBeNull();
    expect(internals.pushTimer).toBeNull();
  });

  test('a longer configured interval is honored for a follower', async () => {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
    });
    const internals = engine as unknown as IntervalInternals;
    engine.setIntervals(3600, 60);
    const delayMs = internals.effectivePullDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(3600).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(3600).max);
  });
});

describe('SyncEngine contention warn threshold', () => {
  test('escalates to warn only once the run reaches the threshold', async () => {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
    });
    const internals = engine as unknown as {
      consecutiveContentions: number;
      logContention(): void;
    };
    const cap = captureSyncLogs();
    try {
      for (let i = 0; i < CONTENTION_WARN_THRESHOLD + 1; i++) {
        internals.consecutiveContentions = i + 1;
        internals.logContention();
      }
      const levels = cap.entries
        .filter((e) => /contention|contended/i.test(e.msg))
        .map((e) => e.level);
      expect(levels.slice(0, CONTENTION_WARN_THRESHOLD - 1)).toEqual(
        Array(CONTENTION_WARN_THRESHOLD - 1).fill('info'),
      );
      expect(levels.slice(CONTENTION_WARN_THRESHOLD - 1)).toEqual(['warn', 'warn']);
    } finally {
      cap.restore();
      await engine.stop();
    }
  });
});

describe('SyncEngine runPushCycle ownership guard', () => {
  type GuardInternals = {
    cycleInFlight: 'pull' | 'push' | null;
    pushTimer: NodeJS.Timeout | null;
    state: SyncState;
    doPushCycle(retriesLeft?: number): Promise<void>;
    runPushCycle(): Promise<void>;
  };

  function makeGuardEngine() {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
    });
    const internals = engine as unknown as GuardInternals;
    internals.state = 'idle';
    internals.cycleInFlight = 'pull';
    const cycles: number[] = [];
    internals.doPushCycle = async (retriesLeft = 0) => {
      cycles.push(retriesLeft);
    };
    return { engine, internals, cycles };
  }

  test('a pull in flight defers the push without running a cycle', async () => {
    const { engine, internals, cycles } = makeGuardEngine();
    await internals.runPushCycle();
    expect(cycles).toEqual([]);
    await engine.stop();
  });

  test('the timer path re-arms, and a press does not clobber a live timer', async () => {
    const timer = makeGuardEngine();
    timer.internals.pushTimer = null;
    await timer.internals.runPushCycle();
    expect(timer.cycles).toEqual([]);
    expect(timer.internals.pushTimer).not.toBeNull();
    await timer.engine.stop();

    const press = makeGuardEngine();
    const armed = setTimeout(() => {}, 60_000);
    press.internals.pushTimer = armed;
    await press.internals.runPushCycle();
    expect(press.cycles).toEqual([]);
    expect(press.internals.pushTimer).toBe(armed);
    clearTimeout(armed);
    await press.engine.stop();
  });
});

describe('SyncEngine push-streak cause tracking', () => {
  type CauseInternals = {
    bumpFailureCount(op: 'push' | 'pull', connectivityClass?: boolean): void;
    consecutivePushFailures: number;
    pushStreakIsConnectivity: boolean;
  };

  function makeEngineForCause() {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds: 60,
      detectGh: () => ({ available: true, token: 'gh-token' }),
    }) as unknown as CauseInternals;
  }

  test('a streak of pure connectivity failures stays dischargeable', () => {
    const e = makeEngineForCause();
    e.bumpFailureCount('push', true);
    e.bumpFailureCount('push', true);
    expect(e.consecutivePushFailures).toBe(2);
    expect(e.pushStreakIsConnectivity).toBe(true);
  });

  test('one non-connectivity failure latches the streak undischargeable', () => {
    const e = makeEngineForCause();
    e.bumpFailureCount('push', true);
    e.bumpFailureCount('push', false);
    e.bumpFailureCount('push', true);
    expect(e.consecutivePushFailures).toBe(3);
    expect(e.pushStreakIsConnectivity).toBe(false);
  });

  test('the cause defaults to non-connectivity when the caller does not classify', () => {
    const e = makeEngineForCause();
    e.bumpFailureCount('push');
    expect(e.pushStreakIsConnectivity).toBe(false);
  });

  test('the predicate is driven by real classifier output, not a hand-passed flag', () => {
    const cases: Array<[string, string, boolean]> = [
      ['fatal: unable to access: Could not resolve host: github.com', 'network/dns', true],
      [
        'fatal: unable to access: Failed to connect to github.com port 443: Connection refused',
        'network/connection-refused',
        true,
      ],
      [
        'fatal: unable to access: Operation timed out after 30001 milliseconds',
        'network/timeout',
        true,
      ],
      [
        'fatal: unable to access: Failed to connect: Network is unreachable',
        'network/unknown-network',
        true,
      ],
      ['fatal: Temporary failure in name resolution', 'network/unknown-network', true],
      [
        'error: RPC failed; HTTP 429 curl 22 The requested URL returned error: 429',
        'network/429',
        false,
      ],
      [
        'error: RPC failed; HTTP 503 curl 22 The requested URL returned error: 503',
        'network/5xx',
        false,
      ],
      [
        '! [remote rejected] main -> main (protected branch hook declined)',
        'semantic/protected-branch',
        false,
      ],
      ['error: could not write to index file: No space left on device', 'local/disk-full', false],
    ];
    for (const [stderr, expectedClass, expected] of cases) {
      const classified = classifyGitError(new Error(stderr));
      expect({
        stderr,
        classified: `${classified.class}/${classified.subclass}`,
        disprovable: isFetchDisprovableFailure(classified),
      }).toEqual({ stderr, classified: expectedClass, disprovable: expected });
    }
  });

  test('a rate-limited or 5xx push streak is NOT dischargeable by a fetch', () => {
    for (const subclass of ['429', '5xx'] as const) {
      const e = makeEngineForCause();
      const classified = { class: 'network' as const, subclass, retryable: true as const };
      e.bumpFailureCount('push', isFetchDisprovableFailure(classified));
      expect(e.pushStreakIsConnectivity).toBe(false);
    }
  });

  test('a pull failure never touches the push cause flag', () => {
    const e = makeEngineForCause();
    e.bumpFailureCount('push', true);
    e.bumpFailureCount('pull');
    expect(e.consecutivePushFailures).toBe(1);
    expect(e.pushStreakIsConnectivity).toBe(true);
  });
});

describe('SyncEngine effectivePushDelayMs floors on the configured interval', () => {
  type PushDelayInternals = {
    effectivePushDelayMs(): number;
    consecutivePushFailures: number;
  };

  function makePushEngine(pushIntervalSeconds: number) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      pullIntervalSeconds: 30,
      pushIntervalSeconds,
      detectGh: () => ({ available: true, token: 'gh-token' }),
    });
  }

  test.each(
    [60, 180].flatMap((intervalSeconds) =>
      JITTER_SAMPLES.map((sample) => ({ intervalSeconds, ...sample })),
    ),
  )(
    'with no streak, delay stays in the configured push band ($intervalSeconds s, draw $draw)',
    ({ intervalSeconds, draw, edge }) => {
      const random = vi.spyOn(Math, 'random').mockReturnValue(draw);
      onTestFinished(() => random.mockRestore());
      const engine = makePushEngine(intervalSeconds);
      const internals = engine as unknown as PushDelayInternals;
      expect(internals.consecutivePushFailures).toBe(0);
      const delayMs = internals.effectivePushDelayMs();
      expect(delayMs).toBe(jitterBand(intervalSeconds)[edge]);
    },
  );

  test('with streak=3 (5-min backoff) and a short interval, backoff wins', () => {
    const engine = makePushEngine(60);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = 3;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(300).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(300).max);
  });

  test.each([
    [5, 900],
    [8, 3600],
  ])('streak=%i climbs to the %i-second tier', (streak, tierSeconds) => {
    const engine = makePushEngine(60);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = streak;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(tierSeconds).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(tierSeconds).max);
  });

  test('with streak=3 (5-min backoff) and a long interval, interval wins', () => {
    const engine = makePushEngine(900);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = 3;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(900).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(900).max);
  });

  test('with streak=5 (15-min backoff) and a short interval, backoff wins', () => {
    const engine = makePushEngine(60);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = 5;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(900).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(900).max);
  });

  test('with streak=5 (15-min backoff) and an interval already longer, interval wins', () => {
    const engine = makePushEngine(3600);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = 5;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(3600).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(3600).max);
  });

  test('with streak=8 (60-min backoff) and a short interval, backoff wins', () => {
    const engine = makePushEngine(60);
    const internals = engine as unknown as PushDelayInternals;
    internals.consecutivePushFailures = 8;
    const delayMs = internals.effectivePushDelayMs();
    expect(delayMs).toBeGreaterThanOrEqual(jitterBand(3600).min);
    expect(delayMs).toBeLessThanOrEqual(jitterBand(3600).max);
  });
});

describe('SyncEngine lifecycle edge cases', () => {
  test('double start() is idempotent (second call is no-op)', async () => {
    const states: SyncState[] = [];
    const engine = makeEngine({ syncEnabled: false, onStateChange: (s) => states.push(s) });
    await engine.start();
    await engine.start();
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('stop() after destroy() is idempotent', async () => {
    const engine = makeEngine();
    await engine.destroy();
    engine.stop();
    expect(engine.getStatus().state).toBe('dormant');
  });

  test('destroy() calls saveStateNow() and writes file', async () => {
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    await engine.destroy();
    expect(existsSync(join(okDir, 'sync-state.json'))).toBe(true);
  });

  test('pausedReason is persisted through destroy + restore', async () => {
    const statePath = join(okDir, 'sync-state.json');
    const persisted = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 0,
      pausedReason: 'detached-head',
      inflightConflicts: [],
    };
    writeFileSync(statePath, JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().pausedReason).toBe('detached-head');
  });

  test('loadState drops no-push-permission from legacy state files (defense-in-depth)', async () => {
    const statePath = join(okDir, 'sync-state.json');
    const persisted = {
      version: 1,
      lastSyncUtc: null,
      lastFetchUtc: null,
      lastPushedSha: null,
      consecutiveFailures: 0,
      pausedReason: 'no-push-permission',
      inflightConflicts: [],
    };
    writeFileSync(statePath, JSON.stringify(persisted), 'utf-8');

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().pausedReason).toBeUndefined();
  });

  test('saveStateNow does not persist no-push-permission when set in-memory by the probe', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pausedReason).toBe('no-push-permission');

    await engine.destroy();

    const statePath = join(okDir, 'sync-state.json');
    const reloaded = JSON.parse(readFileSync(statePath, 'utf-8')) as { pausedReason?: string };
    expect(reloaded.pausedReason).toBeUndefined();
  });
});

describe('SyncEngine push cycle pushes existing commits when local is ahead of origin', () => {
  test('pushes existing HEAD when local is ahead of origin and tree is clean', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    writeFileSync(join(projectDir, 'README.md'), '# Test\n\nlocal change\n');
    await git.add('.');
    await git.commit('local commit not yet pushed');

    const headBefore = (await git.revparse(['HEAD'])).trim();
    const remoteBefore = (await git.revparse(['origin/main'])).trim();
    expect(headBefore).not.toBe(remoteBefore);

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      await engine.trigger('push');

      const remoteAfter = (await git.revparse(['origin/main'])).trim();
      expect(remoteAfter).toBe(headBefore);
      expect(engine.getStatus().lastPushedSha).toBe(headBefore);
    } finally {
      await engine.destroy();
    }
  });

  test('records lastSyncUtc when HEAD already matches origin and tree is clean', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    const head = (await git.revparse(['HEAD'])).trim();
    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.lastPushedSha).toBe(head);
      expect(status.lastSyncUtc).not.toBeNull();
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine push cycle with non-ASCII filenames', () => {
  const fileName = 'hyvää yötä.md';

  test('commits and pushes the deletion of a file with a non-ASCII name', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    writeFileSync(join(projectDir, fileName), 'sisältö\n');
    await git.add('.');
    await git.commit('add non-ascii file');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    rmSync(join(projectDir, fileName));

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('README.md');
      expect(headPaths).not.toContain(fileName);

      const subject = (await git.raw(['log', '--format=%s', '--max-count=1'])).trim();
      expect(subject).toContain(fileName);

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine push cycle vs gitignored content (precedent #55 at the staging boundary)', () => {
  const templatePath = join('trips', '.ok', 'templates', 'article.md');
  const templateRel = 'trips/.ok/templates/article.md';

  async function initRepoWithBareRemote() {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    return git;
  }

  function makePushEngine() {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
    });
  }

  test('skips untracked ignored paths instead of failing the whole push cycle', async () => {
    const git = await initRepoWithBareRemote();
    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');

    mkdirSync(join(projectDir, 'trips', '.ok', 'templates'), { recursive: true });
    writeFileSync(join(projectDir, templatePath), '# Template\n');
    writeFileSync(join(projectDir, 'note.md'), 'new note\n');

    const engine = makePushEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();
      expect(status.consecutiveFailures).toBe(0);

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('note.md');
      expect(headPaths).not.toContain(templateRel);

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test('skips files inside an ignored nested repository instead of failing the whole push cycle', async () => {
    const git = await initRepoWithBareRemote();
    writeFileSync(join(projectDir, '.gitignore'), '/child/\n');
    await git.add('.gitignore');
    await git.commit('ignore child');
    await git.push(['origin', 'main']);

    const childDir = join(projectDir, 'child');
    mkdirSync(childDir);
    const child = simpleGit(childDir);
    await child.init(['--initial-branch=main']);
    await child.raw('config', 'user.name', 'Test');
    await child.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(childDir, 'AGENTS.md'), '# Child\n');
    await child.add('AGENTS.md');
    await child.commit('child');
    writeFileSync(join(projectDir, 'root-note.md'), 'edited\n');

    const engine = makePushEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();
      expect(status.consecutiveFailures).toBe(0);

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('root-note.md');
      expect(headPaths.filter((p) => p.startsWith('child/'))).toEqual([]);

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test('keeps syncing edits to a tracked file that an ignore rule also matches', async () => {
    const git = await initRepoWithBareRemote();
    mkdirSync(join(projectDir, 'trips', '.ok', 'templates'), { recursive: true });
    writeFileSync(join(projectDir, templatePath), '# Template v1\n');
    await git.add('.');
    await git.commit('add template while shared');
    await git.push(['origin', 'main']);

    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
    writeFileSync(join(projectDir, templatePath), '# Template v2\n');

    const engine = makePushEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain(templateRel);
      const blob = await git.raw(['show', `HEAD:${templateRel}`]);
      expect(blob).toBe('# Template v2\n');

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine push cycle stages shareable .ok artifacts (sync scope)', () => {
  async function initSharedRepoWithBareRemote() {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    return { git, bareDir };
  }

  function makeShareableEngine(mode?: SyncMode) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: createContentFilter({ projectDir, contentDir: projectDir }),
      ...(mode ? { mode } : { syncEnabled: true }),
    });
  }

  async function cloneAsTeammate(bareDir: string) {
    const sisterDir = join(tmpDir, 'sister');
    await simpleGit(tmpDir).clone(bareDir, sisterDir);
    configureTestGitRepository(sisterDir);
    const sister = simpleGit(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    return { sister, sisterDir };
  }

  test('stages and pushes every shareable artifact class in a shared full-mode project', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
    mkdirSync(join(projectDir, '.ok', 'templates'), { recursive: true });
    mkdirSync(join(projectDir, 'docs', '.ok', 'templates'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');
    writeFileSync(join(projectDir, '.ok', '.gitignore'), 'local/\nworktrees/\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
    writeFileSync(join(projectDir, '.ok', 'templates', 'meeting.md'), '# Meeting\n');
    writeFileSync(join(projectDir, 'docs', '.ok', 'templates', 'article.md'), '# Article\n');
    writeFileSync(join(projectDir, 'docs', '.ok', 'frontmatter.yml'), 'icon: book\n');
    writeFileSync(join(projectDir, 'docs', 'guide.md'), '# Guide\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();
      expect(status.consecutiveFailures).toBe(0);

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      for (const path of [
        '.ok/config.yml',
        '.ok/.gitignore',
        '.ok/schemas/frontmatter.json',
        '.ok/templates/meeting.md',
        'docs/.ok/templates/article.md',
        'docs/.ok/frontmatter.yml',
        'docs/guide.md',
      ]) {
        expect(headPaths).toContain(path);
      }

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test('stages, updates, and deletes files in a doc-relative attachment folder without a sibling doc', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, 'assets'), { recursive: true });
    writeFileSync(join(projectDir, 'assets', 'diagram.png'), 'attachment-v1');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: createContentFilter({
        projectDir,
        contentDir: projectDir,
        attachmentFolderPath: './assets',
      }),
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');
      expect(await git.raw(['show', 'HEAD:assets/diagram.png'])).toBe('attachment-v1');

      writeFileSync(join(projectDir, 'assets', 'diagram.png'), 'attachment-v2');
      await engine.trigger('push');
      expect(await git.raw(['show', 'HEAD:assets/diagram.png'])).toBe('attachment-v2');

      rmSync(join(projectDir, 'assets', 'diagram.png'));
      await engine.trigger('push');
      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).not.toContain('assets/diagram.png');
      expect((await git.revparse(['origin/main'])).trim()).toBe(
        (await git.revparse(['HEAD'])).trim(),
      );
    } finally {
      await engine.destroy();
    }
  });

  test('stages files in a fixed attachment folder with no markdown document anywhere in the tree', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    rmSync(join(projectDir, 'README.md'));
    mkdirSync(join(projectDir, 'assets'), { recursive: true });
    writeFileSync(join(projectDir, 'assets', 'diagram.png'), 'attachment-doc-less');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: createContentFilter({
        projectDir,
        contentDir: projectDir,
        attachmentFolderPath: 'assets',
      }),
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      expect(engine.getStatus().pushError).toBeUndefined();
      expect(await git.raw(['show', 'HEAD:assets/diagram.png'])).toBe('attachment-doc-less');
      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).not.toContain('README.md');
      expect((await git.revparse(['origin/main'])).trim()).toBe(
        (await git.revparse(['HEAD'])).trim(),
      );
    } finally {
      await engine.destroy();
    }
  });

  test('a live attachment-folder change freezes the old tracked folder and syncs the new one', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, 'assets'), { recursive: true });
    mkdirSync(join(projectDir, 'media'), { recursive: true });
    writeFileSync(join(projectDir, 'assets', 'old.png'), 'old-v1');

    const contentFilter = createContentFilter({
      projectDir,
      contentDir: projectDir,
      attachmentFolderPath: 'assets',
    });
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter,
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      contentFilter.setAttachmentFolderPath('media');
      writeFileSync(join(projectDir, 'assets', 'old.png'), 'old-v2-local');
      writeFileSync(join(projectDir, 'media', 'new.png'), 'new-v1');
      await engine.trigger('push');

      expect(await git.raw(['show', 'HEAD:assets/old.png'])).toBe('old-v1');
      expect(await git.raw(['show', 'HEAD:media/new.png'])).toBe('new-v1');
      expect(readFileSync(join(projectDir, 'assets', 'old.png'), 'utf-8')).toBe('old-v2-local');
    } finally {
      await engine.destroy();
    }
  });

  test('local-only .ok sharing does not block a configured attachment folder', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
    mkdirSync(join(projectDir, '.ok'), { recursive: true });
    mkdirSync(join(projectDir, 'assets'), { recursive: true });
    writeFileSync(
      join(projectDir, '.ok', 'config.yml'),
      'content:\n  attachmentFolderPath: assets\n',
    );
    writeFileSync(join(projectDir, 'assets', 'shared.png'), 'attachment');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: createContentFilter({
        projectDir,
        contentDir: projectDir,
        attachmentFolderPath: 'assets',
      }),
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('assets/shared.png');
      expect(headPaths).not.toContain('.ok/config.yml');
    } finally {
      await engine.destroy();
    }
  });

  test('tracks the deletion of a shareable artifact and keeps the surviving ones', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
    await git.add(['.ok/config.yml', '.ok/schemas/frontmatter.json']);
    await git.commit('add shareable artifacts');
    await git.push(['origin', 'main']);

    rmSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'));

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      expect(engine.getStatus().pushError).toBeUndefined();
      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).not.toContain('.ok/schemas/frontmatter.json');
      expect(headPaths).toContain('.ok/config.yml');

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test.runIf(process.getuid?.() !== 0)(
    'fails closed on an unreadable tracked schema when content and project roots match',
    async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
      await git.add(['.ok/schemas/frontmatter.json']);
      await git.commit('track project schema');
      await git.push(['origin', 'main']);
      const headBefore = (await git.revparse(['HEAD'])).trim();
      const remoteBefore = (await git.revparse(['origin/main'])).trim();

      writeFileSync(join(projectDir, 'note.md'), '# Must stay local\n');

      const engine = makeShareableEngine();
      const cap = captureSyncLogs();
      try {
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
        await engine.start();
        await engine.trigger('push');

        const status = engine.getStatus();
        expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');
        expect(status.consecutivePushFailures).toBeGreaterThan(0);
        expect(status.consecutiveFailures).toBe(0);
        const detail = cap.entries.find(
          (entry) => entry.msg === '[sync] push cycle: staging error detail',
        );
        expect(detail?.data.err).toBeInstanceOf(Error);
        expect((detail?.data.err as Error | undefined)?.cause).toMatchObject({
          code: expect.stringMatching(/^(?:EACCES|EPERM)$/),
        });
        expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);
        expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);
        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).toContain('.ok/schemas/frontmatter.json');
        expect(headPaths).not.toContain('note.md');
        expect(existsSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'))).toBe(true);
      } finally {
        cap.restore();
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o755);
        await engine.destroy();
      }
    },
  );

  test.runIf(process.getuid?.() !== 0)(
    'names a nested unreadable template subtree and commits no partial snapshot',
    async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'docs', '.ok', 'templates'), { recursive: true });
      writeFileSync(join(projectDir, 'docs', '.ok', 'templates', 'article.md'), '# Template\n');
      await git.add(['docs/.ok/templates/article.md']);
      await git.commit('track folder template');
      await git.push(['origin', 'main']);
      const headBefore = (await git.revparse(['HEAD'])).trim();
      const remoteBefore = (await git.revparse(['origin/main'])).trim();

      writeFileSync(join(projectDir, 'note.md'), '# Must stay local\n');

      const engine = makeShareableEngine();
      try {
        chmodSync(join(projectDir, 'docs', '.ok', 'templates'), 0o311);
        await engine.start();
        await engine.trigger('push');

        const status = engine.getStatus();
        expect(status.pushError).toContain(
          'Shareable .ok subtree "docs/.ok/templates" could not be fully enumerated',
        );
        expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);
        expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);
        expect(await git.raw(['show', 'HEAD:docs/.ok/templates/article.md'])).toBe('# Template\n');
        expect(await git.raw(['ls-tree', '-r', '--name-only', 'HEAD'])).not.toContain('note.md');
      } finally {
        chmodSync(join(projectDir, 'docs', '.ok', 'templates'), 0o755);
        await engine.destroy();
      }
    },
  );

  test('never stages .ok local state, worktrees, or legacy root state files', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, '.ok', 'worktrees', 'wt1'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');
    writeFileSync(join(projectDir, '.ok', 'local', 'principal.json'), '{}\n');
    writeFileSync(join(projectDir, '.ok', 'worktrees', 'wt1', 'scratch.md'), '# Scratch\n');
    writeFileSync(join(projectDir, '.ok', 'state.json'), '{}\n');
    writeFileSync(join(projectDir, '.ok', 'server.lock'), '{}\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      expect(engine.getStatus().pushError).toBeUndefined();
      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('.ok/config.yml');
      expect(
        headPaths.filter((p) => p.startsWith('.ok/local/') || p.startsWith('.ok/worktrees/')),
      ).toEqual([]);
      expect(headPaths).not.toContain('.ok/state.json');
      expect(headPaths).not.toContain('.ok/server.lock');
    } finally {
      await engine.destroy();
    }
  });

  test.runIf(process.getuid?.() !== 0)(
    'a one-shot push reports a staging failure instead of rejecting',
    async () => {
      const { bareDir } = await initSharedRepoWithBareRemote();

      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{}\n');

      const engine = makeShareableEngine('off');
      const internal = engine as unknown as {
        commitDirtyContentFilesToHead: (handle: unknown, op: 'push' | 'pull') => Promise<void>;
      };
      const commitDirty = internal.commitDirtyContentFilesToHead.bind(engine);
      internal.commitDirtyContentFilesToHead = async (handle, op) => {
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
        await commitDirty(handle, op);
      };

      try {
        await engine.start();

        const { sister, sisterDir } = await cloneAsTeammate(bareDir);
        writeFileSync(join(sisterDir, 'remote.md'), '# Remote\n');
        await sister.add(['remote.md']);
        await sister.commit('advance remote');
        await sister.push(['origin', 'main']);
        writeFileSync(join(projectDir, 'local.md'), '# Local\n');

        await expect(engine.pushOnce()).resolves.toBeUndefined();

        const status = engine.getStatus();
        expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');
        expect(status.pullError).toBeUndefined();
      } finally {
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o755);
        await engine.destroy();
      }
    },
  );

  test.runIf(process.getuid?.() !== 0)(
    'reports retry staging failures as push errors',
    async () => {
      const { bareDir } = await initSharedRepoWithBareRemote();
      const { sister, sisterDir } = await cloneAsTeammate(bareDir);
      writeFileSync(join(sisterDir, 'remote.md'), '# Remote\n');
      await sister.add(['remote.md']);
      await sister.commit('advance remote');
      await sister.push(['origin', 'main']);

      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{}\n');
      writeFileSync(join(projectDir, 'local.md'), '# Local\n');
      const engine = makeShareableEngine();
      const internal = engine as unknown as {
        commitDirtyContentFilesToHead: (handle: unknown, op: 'push' | 'pull') => Promise<void>;
      };
      const commitDirty = internal.commitDirtyContentFilesToHead.bind(engine);
      internal.commitDirtyContentFilesToHead = async (handle, op) => {
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
        await commitDirty(handle, op);
      };

      try {
        await engine.start();
        await engine.trigger('push');

        const status = engine.getStatus();
        expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');
        expect(status.pullError).toBeUndefined();
      } finally {
        chmodSync(join(projectDir, '.ok', 'schemas'), 0o755);
        await engine.destroy();
      }
    },
  );

  test('refuses a secret-suffixed file inside an admitted .ok directory', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'api.key'), 'secret\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      expect(engine.getStatus().pushError).toBeUndefined();
      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('.ok/schemas/frontmatter.json');
      expect(headPaths).not.toContain('.ok/schemas/api.key');
    } finally {
      await engine.destroy();
    }
  });

  test('local-only projects keep every artifact class unstaged without failing the cycle', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
    mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
    mkdirSync(join(projectDir, 'docs', '.ok', 'templates'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
    writeFileSync(join(projectDir, 'docs', '.ok', 'templates', 'article.md'), '# Article\n');
    writeFileSync(join(projectDir, 'note.md'), 'new note\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();
      expect(status.consecutiveFailures).toBe(0);

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('note.md');
      expect(headPaths.filter((p) => p.includes('.ok/'))).toEqual([]);

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test('local-only projects freeze a tracked artifact: no edit sync, no spurious deletion', async () => {
    const { git } = await initSharedRepoWithBareRemote();
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');
    await git.add(['.ok/config.yml']);
    await git.commit('add config while shared');
    await git.push(['origin', 'main']);

    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: follow\n');
    writeFileSync(join(projectDir, 'note.md'), 'new note\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('push');

      const status = engine.getStatus();
      expect(status.pushError).toBeUndefined();

      const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
      expect(headPaths).toContain('note.md');
      expect(headPaths).toContain('.ok/config.yml');
      const blob = await git.raw(['show', 'HEAD:.ok/config.yml']);
      expect(blob).toBe('sync:\n  mode: full\n');

      const remoteHead = (await git.revparse(['origin/main'])).trim();
      expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
    } finally {
      await engine.destroy();
    }
  });

  test('follow-mode pull fast-forwards shareable artifacts into the working tree', async () => {
    const { git, bareDir } = await initSharedRepoWithBareRemote();
    const { sister, sisterDir } = await cloneAsTeammate(bareDir);
    mkdirSync(join(sisterDir, '.ok', 'schemas'), { recursive: true });
    writeFileSync(join(sisterDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
    await sister.add(['.ok/schemas/frontmatter.json']);
    await sister.commit('teammate adds schema');
    await sister.push(['origin', 'main']);

    const engine = makeShareableEngine('follow');
    try {
      await engine.start();
      await engine.trigger('pull');

      expect(existsSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'))).toBe(true);
      expect((await git.revparse(['HEAD'])).trim()).toBe(
        (await git.revparse(['origin/main'])).trim(),
      );
    } finally {
      await engine.destroy();
    }
  });

  test('pull keeps local shareable-artifact edits as overlay without committing them', async () => {
    const { git, bareDir } = await initSharedRepoWithBareRemote();
    const { sister, sisterDir } = await cloneAsTeammate(bareDir);
    writeFileSync(join(sisterDir, 'from-teammate.md'), '# Teammate\n');
    await sister.add(['from-teammate.md']);
    await sister.commit('teammate note');
    await sister.push(['origin', 'main']);

    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'sync:\n  mode: full\n');

    const engine = makeShareableEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const status = engine.getStatus();
      expect(status.conflictCount).toBe(0);
      expect(status.pausedReason).toBeUndefined();
      expect(status.state).toBe('idle');
      expect(existsSync(join(projectDir, 'from-teammate.md'))).toBe(true);

      expect(readFileSync(join(projectDir, '.ok', 'config.yml'), 'utf-8')).toBe(
        'sync:\n  mode: full\n',
      );
      const lastMessage = (await git.log({ maxCount: 1 })).latest?.message;
      expect(lastMessage).toBe('teammate note');
      const log = await git.log();
      expect(log.all.some((c) => c.message === 'Auto-save: interim before merge')).toBe(false);
    } finally {
      await engine.destroy();
    }
  });

  test('keeps local artifact edits and pins template conflicts without merging', async () => {
    const { git, bareDir } = await initSharedRepoWithBareRemote();
    mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
    mkdirSync(join(projectDir, '.ok', 'templates'), { recursive: true });
    mkdirSync(join(projectDir, 'docs', '.ok', 'templates'), { recursive: true });
    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'shared: base\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'lint.json'), '{"a":1}\n');
    writeFileSync(join(projectDir, '.ok', 'templates', 'project.md'), '# Base project\n');
    writeFileSync(join(projectDir, 'docs', '.ok', 'templates', 'folder.md'), '# Base folder\n');
    await git.add([
      '.ok/config.yml',
      '.ok/schemas/lint.json',
      '.ok/templates/project.md',
      'docs/.ok/templates/folder.md',
    ]);
    await git.commit('add shareable artifacts');
    await git.push(['origin', 'main']);

    const { sister, sisterDir } = await cloneAsTeammate(bareDir);
    writeFileSync(join(sisterDir, '.ok', 'config.yml'), 'shared: remote\n');
    writeFileSync(join(sisterDir, '.ok', 'schemas', 'lint.json'), '{"a":99}\n');
    writeFileSync(join(sisterDir, '.ok', 'templates', 'project.md'), '# Remote project\n');
    writeFileSync(join(sisterDir, 'docs', '.ok', 'templates', 'folder.md'), '# Remote folder\n');
    await sister.add([
      '.ok/config.yml',
      '.ok/schemas/lint.json',
      '.ok/templates/project.md',
      'docs/.ok/templates/folder.md',
    ]);
    await sister.commit('teammate edits config and schema');
    await sister.push(['origin', 'main']);

    writeFileSync(join(projectDir, '.ok', 'config.yml'), 'shared: local\n');
    writeFileSync(join(projectDir, '.ok', 'schemas', 'lint.json'), '{"a":2}\n');
    writeFileSync(join(projectDir, '.ok', 'templates', 'project.md'), '# Local project\n');
    writeFileSync(join(projectDir, 'docs', '.ok', 'templates', 'folder.md'), '# Local folder\n');

    const engine = makeShareableEngine();
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.trigger('pull');

      const status = engine.getStatus();
      expect(status.state).toBe('idle');
      expect(status.pausedReason).toBeUndefined();
      expect(status.conflictCount).toBe(2);
      const conflicts = authority.list();
      expect(conflicts.map((conflict) => conflict.file).sort()).toEqual([
        '.ok/templates/project.md',
        'docs/.ok/templates/folder.md',
      ]);
      expect(workingTreeConflicts()).toHaveLength(conflicts.length);
      expect(workingTreeConflicts().every((c) => c.theirsSha.length > 0)).toBe(true);
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);

      expect(readFileSync(join(projectDir, '.ok', 'config.yml'), 'utf-8')).toBe('shared: local\n');
      expect(readFileSync(join(projectDir, '.ok', 'schemas', 'lint.json'), 'utf-8')).toBe(
        '{"a":2}\n',
      );
      expect(readFileSync(join(projectDir, '.ok', 'templates', 'project.md'), 'utf-8')).toBe(
        '# Local project\n',
      );

      expect((await git.log({ maxCount: 1 })).latest?.message).toBe(
        'teammate edits config and schema',
      );
      const overwriteWarnings = cap.entries.filter((e) =>
        e.msg.includes('local project config edits were overwritten'),
      );
      expect(overwriteWarnings).toEqual([]);
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  describe('with content.dir as a subfolder (project-root shareable set)', () => {
    function makeSubfolderEngine(attachmentFolderPath?: string) {
      const contentDir = join(projectDir, 'content');
      return new SyncEngine({
        conflicts: newAuthority(),
        projectDir,
        contentDir,
        contentFilter: createContentFilter({
          projectDir,
          contentDir,
          ...(attachmentFolderPath ? { attachmentFolderPath } : {}),
        }),
        syncEnabled: true,
      });
    }

    test('configured attachment folders stay content-relative when content.dir is a subfolder', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content', 'assets'), { recursive: true });
      writeFileSync(join(projectDir, 'content', 'assets', 'diagram.png'), 'attachment');

      const engine = makeSubfolderEngine('assets');
      try {
        await engine.start();
        await engine.trigger('push');

        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).toContain('content/assets/diagram.png');
        expect(headPaths).not.toContain('assets/diagram.png');
      } finally {
        await engine.destroy();
      }
    });

    test('stages the project-root shareable set alongside subfolder content', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content', 'docs', '.ok'), { recursive: true });
      mkdirSync(join(projectDir, 'content', 'guides', '.ok'), { recursive: true });
      mkdirSync(join(projectDir, 'content', '.ok', 'schemas'), { recursive: true });
      mkdirSync(join(projectDir, 'content', '.ok', 'templates'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'templates'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'config.yml'), 'content:\n  dir: content\n');
      writeFileSync(join(projectDir, '.ok', '.gitignore'), 'local/\nworktrees/\n');
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
      writeFileSync(join(projectDir, '.ok', 'templates', 'meeting.md'), '# Meeting\n');
      writeFileSync(join(projectDir, 'content', '.ok', 'config.yml'), 'wrong: root\n');
      writeFileSync(join(projectDir, 'content', '.ok', '.gitignore'), 'local/\n');
      writeFileSync(join(projectDir, 'content', '.ok', 'schemas', 'nested.json'), '{}\n');
      writeFileSync(join(projectDir, 'content', '.ok', 'templates', 'daily.md'), '# Daily\n');
      writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');
      writeFileSync(join(projectDir, 'content', 'docs', '.ok', 'config.yml'), 'not: project\n');
      writeFileSync(join(projectDir, 'content', 'docs', '.ok', 'frontmatter.yml'), 'icon: book\n');
      writeFileSync(join(projectDir, 'content', 'guides', '.ok', 'frontmatter.yml'), 'icon: map\n');

      const engine = makeSubfolderEngine();
      try {
        await engine.start();
        await engine.trigger('push');

        const status = engine.getStatus();
        expect(status.pushError).toBeUndefined();
        expect(status.consecutiveFailures).toBe(0);

        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        for (const path of [
          '.ok/config.yml',
          '.ok/.gitignore',
          '.ok/schemas/frontmatter.json',
          '.ok/templates/meeting.md',
          'content/.ok/templates/daily.md',
          'content/note.md',
          'content/guides/.ok/frontmatter.yml',
        ]) {
          expect(headPaths).toContain(path);
        }
        expect(headPaths).not.toContain('content/.ok/config.yml');
        expect(headPaths).not.toContain('content/.ok/.gitignore');
        expect(headPaths).not.toContain('content/.ok/schemas/nested.json');
        expect(headPaths).not.toContain('content/docs/.ok/config.yml');
        expect(headPaths).not.toContain('content/docs/.ok/frontmatter.yml');

        const remoteHead = (await git.revparse(['origin/main'])).trim();
        expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
      } finally {
        await engine.destroy();
      }
    });

    test('tracks deletion of a project-root artifact and keeps the survivors', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'config.yml'), 'content:\n  dir: content\n');
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
      writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');
      await git.add(['.ok/config.yml', '.ok/schemas/frontmatter.json', 'content/note.md']);
      await git.commit('add shareable artifacts');
      await git.push(['origin', 'main']);

      rmSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'));

      const engine = makeSubfolderEngine();
      try {
        await engine.start();
        await engine.trigger('push');

        expect(engine.getStatus().pushError).toBeUndefined();
        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).not.toContain('.ok/schemas/frontmatter.json');
        expect(headPaths).toContain('.ok/config.yml');
        expect(headPaths).toContain('content/note.md');

        const remoteHead = (await git.revparse(['origin/main'])).trim();
        expect(remoteHead).toBe((await git.revparse(['HEAD'])).trim());
      } finally {
        await engine.destroy();
      }
    });

    test('folder artifacts outside contentDir and outside the root .ok stay frozen', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content'), { recursive: true });
      mkdirSync(join(projectDir, 'docs', '.ok'), { recursive: true });
      writeFileSync(join(projectDir, 'docs', '.ok', 'frontmatter.yml'), 'icon: book\n');
      await git.add(['docs/.ok/frontmatter.yml']);
      await git.commit('folder metadata outside the content walk');
      await git.push(['origin', 'main']);

      mkdirSync(join(projectDir, 'docs2', '.ok'), { recursive: true });
      writeFileSync(join(projectDir, 'docs2', '.ok', 'frontmatter.yml'), 'icon: rocket\n');
      writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');

      const engine = makeSubfolderEngine();
      try {
        await engine.start();
        await engine.trigger('push');

        expect(engine.getStatus().pushError).toBeUndefined();
        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).toContain('docs/.ok/frontmatter.yml');
        expect(headPaths).not.toContain('docs2/.ok/frontmatter.yml');
        expect(headPaths).toContain('content/note.md');
      } finally {
        await engine.destroy();
      }
    });

    test('the second walk still refuses local state, legacy files, and secrets', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'worktrees', 'wt1'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'schemas', 'lint.json'), '{"type":"object"}\n');
      writeFileSync(join(projectDir, '.ok', 'schemas', 'api.key'), 'secret\n');
      writeFileSync(join(projectDir, '.ok', 'local', 'principal.json'), '{}\n');
      writeFileSync(join(projectDir, '.ok', 'worktrees', 'wt1', 'scratch.md'), '# Scratch\n');
      writeFileSync(join(projectDir, '.ok', 'state.json'), '{}\n');
      writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');

      const engine = makeSubfolderEngine();
      try {
        await engine.start();
        await engine.trigger('push');

        expect(engine.getStatus().pushError).toBeUndefined();
        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).toContain('.ok/schemas/lint.json');
        expect(headPaths).toContain('content/note.md');
        for (const path of headPaths) {
          expect(path).not.toMatch(/^\.ok\/(local|worktrees)\//);
        }
        expect(headPaths).not.toContain('.ok/schemas/api.key');
        expect(headPaths).not.toContain('.ok/state.json');
      } finally {
        await engine.destroy();
      }
    });

    test('local-only subfolder projects keep the project-root set unstaged without errors', async () => {
      const { git } = await initSharedRepoWithBareRemote();
      mkdirSync(join(projectDir, 'content'), { recursive: true });
      mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
      writeFileSync(join(projectDir, '.ok', 'config.yml'), 'content:\n  dir: content\n');
      writeFileSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'), '{"type":"object"}\n');
      writeFileSync(join(projectDir, 'content', 'note.md'), '# Note\n');
      writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');

      const engine = makeSubfolderEngine();
      try {
        await engine.start();
        await engine.trigger('push');

        const status = engine.getStatus();
        expect(status.pushError).toBeUndefined();
        expect(status.consecutiveFailures).toBe(0);
        const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
        expect(headPaths).toContain('content/note.md');
        expect(headPaths.filter((p) => p.startsWith('.ok/'))).toEqual([]);
      } finally {
        await engine.destroy();
      }
    });

    test.runIf(process.getuid?.() !== 0)(
      'fails closed when a tracked project-root .ok is unreadable',
      async () => {
        const { git } = await initSharedRepoWithBareRemote();
        mkdirSync(join(projectDir, 'content'), { recursive: true });
        writeFileSync(join(projectDir, '.ok', 'config.yml'), 'content:\n  dir: content\n');
        mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
        await git.add(['.ok/config.yml']);
        await git.commit('track project config');
        await git.push(['origin', 'main']);
        const headBefore = (await git.revparse(['HEAD'])).trim();
        const remoteBefore = (await git.revparse(['origin/main'])).trim();

        writeFileSync(join(projectDir, 'content', 'note.md'), '# Must stay local\n');

        const engine = makeSubfolderEngine();
        try {
          chmodSync(join(projectDir, '.ok'), 0o311);
          await engine.start();
          await engine.trigger('push');

          const status = engine.getStatus();
          expect(status.pushError).toContain('Shareable .ok subtree ".ok"');
          expect(status.consecutivePushFailures).toBeGreaterThan(0);
          expect(status.consecutiveFailures).toBe(0);
          expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);
          expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);
          const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
          expect(headPaths).toContain('.ok/config.yml');
          expect(headPaths).not.toContain('content/note.md');
          expect(existsSync(join(projectDir, '.ok', 'config.yml'))).toBe(true);
        } finally {
          chmodSync(join(projectDir, '.ok'), 0o755);
          await engine.destroy();
        }
      },
    );

    test.runIf(process.getuid?.() !== 0)(
      'fails closed when a tracked project-root schema directory is unreadable',
      async () => {
        const { git } = await initSharedRepoWithBareRemote();
        mkdirSync(join(projectDir, 'content'), { recursive: true });
        mkdirSync(join(projectDir, '.ok', 'schemas'), { recursive: true });
        mkdirSync(join(projectDir, '.ok', 'local'), { recursive: true });
        writeFileSync(
          join(projectDir, '.ok', 'schemas', 'frontmatter.json'),
          '{"type":"object"}\n',
        );
        await git.add(['.ok/schemas/frontmatter.json']);
        await git.commit('track project schema');
        await git.push(['origin', 'main']);
        const headBefore = (await git.revparse(['HEAD'])).trim();
        const remoteBefore = (await git.revparse(['origin/main'])).trim();

        writeFileSync(join(projectDir, 'content', 'note.md'), '# Must stay local\n');

        const engine = makeSubfolderEngine();
        try {
          chmodSync(join(projectDir, '.ok', 'schemas'), 0o311);
          await engine.start();
          await engine.trigger('push');

          const status = engine.getStatus();
          expect(status.pushError).toContain('Shareable .ok subtree ".ok/schemas"');
          expect(status.consecutivePushFailures).toBeGreaterThan(0);
          expect(status.consecutiveFailures).toBe(0);
          expect((await git.revparse(['HEAD'])).trim()).toBe(headBefore);
          expect((await git.revparse(['origin/main'])).trim()).toBe(remoteBefore);
          const headPaths = await listNames(git, ['ls-tree', '-r', '--name-only', 'HEAD']);
          expect(headPaths).toContain('.ok/schemas/frontmatter.json');
          expect(headPaths).not.toContain('content/note.md');
          expect(existsSync(join(projectDir, '.ok', 'schemas', 'frontmatter.json'))).toBe(true);
        } finally {
          chmodSync(join(projectDir, '.ok', 'schemas'), 0o755);
          await engine.destroy();
        }
      },
    );
  });
});

describe('SyncEngine per-operation error isolation', () => {
  test('a successful fetch does not clear a standing push error', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    await git.raw('config', 'remote.origin.pushurl', join(tmpDir, 'nonexistent-bare.git'));

    writeFileSync(join(projectDir, 'README.md'), '# Test\n\nlocal change\n');
    await git.add('.');
    await git.commit('local commit');

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();
      await engine.trigger('sync');

      const status = engine.getStatus();
      expect(status.pushError ?? '').not.toBe('');
      expect(status.lastFetchUtc).not.toBeNull();
      expect(status.pullError).toBeUndefined();
    } finally {
      await engine.destroy();
    }
  });

  test('a successful push does not clear a standing pull error', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    await git.raw('config', 'remote.origin.url', join(tmpDir, 'nonexistent-bare.git'));
    await git.raw('config', 'remote.origin.pushurl', bareDir);

    writeFileSync(join(projectDir, 'README.md'), '# Test\n\nlocal change\n');
    await git.add('.');
    await git.commit('local commit');
    const head = (await git.revparse(['HEAD'])).trim();

    const engine = makeEngine({ syncEnabled: true });
    try {
      await engine.start();

      await engine.trigger('pull');
      const afterPull = engine.getStatus();
      expect(afterPull.pullError ?? '').not.toBe('');
      expect(afterPull.pushError).toBeUndefined();

      await engine.trigger('push');
      const afterPush = engine.getStatus();
      const remoteAfter = (await simpleGit(bareDir).revparse(['main'])).trim();
      expect(remoteAfter).toBe(head);
      expect(afterPush.lastPushedSha).toBe(head);
      expect(afterPush.pullError ?? '').not.toBe('');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine push-permission probe', () => {
  const home = useIsolatedHome();

  test('keeps host classification from construction until a new engine starts', async () => {
    await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
    const path = join(home(), '.ok', 'global.yml');
    declareGitHubHosts(home(), 'ghes.acme.test');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    writeFileSync(path, 'git:\n  hosts: {}\n');
    try {
      await engine.start();
      await waitForPushPermissionResolved(engine);
      expect(probe.calls).toBe(1);
      expect(engine.getStatus().remote?.webUrl).toBe(
        'https://ghes.acme.test/inkeep/open-knowledge',
      );
      const restartedProbe = fakeProbe({ kind: 'allowed' });
      const restarted = makeProbeEngine({ syncEnabled: false, fakeProbe: restartedProbe.fn });
      try {
        await restarted.start();
        await waitForPushPermissionResolved(restarted);
        expect(restartedProbe.calls).toBe(0);
        expect(restarted.getStatus().remote?.webUrl).toBeNull();
      } finally {
        await restarted.destroy();
      }
    } finally {
      await engine.destroy();
    }
  });
  test('does NOT run when there is no remote', async () => {
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    expect(probe.calls).toBe(0);
    expect(engine.getStatus().pushPermission).toBeUndefined();
  });

  test('does NOT run for a non-github origin (gitlab, self-hosted) — emits unknown', async () => {
    await initGitWithOrigin('https://gitlab.com/foo/bar.git');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await new Promise((r) => setTimeout(r, 10));
    expect(probe.calls).toBe(0);
    expect(engine.getStatus().pushPermission).toEqual({ checkStatus: 'unknown' });
  });

  test('records `allowed` after start() against a github origin', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(probe.calls).toBe(1);
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'allowed',
    });
  });

  test('probes a DECLARED GitHub Enterprise origin against the enterprise host', async () => {
    await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
    declareGitHubHosts(home(), 'ghes.acme.test');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(probe.calls).toBe(1);
    expect(probe.opts[0]).toMatchObject({
      owner: 'inkeep',
      repo: 'open-knowledge',
      host: 'ghes.acme.test',
    });
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'allowed',
    });
  });

  test('does NOT probe or park an UNDECLARED self-hosted https origin in full mode', async () => {
    await initGitWithOrigin('https://git.example.internal/team/kb.git');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ mode: 'full', fakeProbe: probe.fn });
    try {
      await engine.start();
      await new Promise((r) => setTimeout(r, 10));
      const status = engine.getStatus();
      expect(probe.calls).toBe(0);
      expect(status.pushPermission).toEqual({ checkStatus: 'unknown' });
      expect(status.pausedReason).not.toBe('no-push-permission');
      expect(status.state).not.toBe('disabled');
    } finally {
      await engine.destroy();
    }
  });

  test('threads the origin-declared account and the accounts listing into the probe', async () => {
    await initGitWithOrigin('https://[email protected]/inkeep/open-knowledge.git');
    const probe = fakeProbe({ kind: 'allowed' });
    const accountsFn: DetectGhAccountsFn = () => [{ login: 'alice', active: true }];
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      detectGhAccounts: accountsFn,
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(probe.opts[0]?.account).toMatchObject({ login: 'alice', source: 'remote-url' });
    expect(probe.opts[0]?.detectGhAccounts).toBe(accountsFn);
  });

  test('a re-probe that changes only the resolved identity still broadcasts', async () => {
    await initGitWithOrigin();
    const signal = vi.fn();
    const probe = fakeProbe(
      { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
      { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'bob' },
    );
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      cc1Broadcaster: { signal },
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const before = signal.mock.calls.length;

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(signal.mock.calls.length).toBeGreaterThan(before);
    expect(signal.mock.calls.at(-1)?.[0]).toBe('sync-status');
    await engine.destroy();
  });

  test('a re-probe that changes only the declared-miss login still broadcasts', async () => {
    await initGitWithOrigin();
    const signal = vi.fn();
    const probe = fakeProbe(
      {
        kind: 'denied',
        reason: 'private-no-access',
        resolvedLogin: 'bob',
        declaredLogin: 'alice',
        declaredSource: 'remote-url',
      },
      {
        kind: 'denied',
        reason: 'private-no-access',
        resolvedLogin: 'bob',
        declaredLogin: 'carol',
        declaredSource: 'remote-url',
      },
    );
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      cc1Broadcaster: { signal },
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const before = signal.mock.calls.length;

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(signal.mock.calls.length).toBeGreaterThan(before);
    await engine.destroy();
  });

  test('a re-probe that changes only the declaration mechanism still broadcasts', async () => {
    await initGitWithOrigin();
    const signal = vi.fn();
    const probe = fakeProbe(
      {
        kind: 'denied',
        reason: 'private-no-access',
        resolvedLogin: 'bob',
        declaredLogin: 'alice',
        declaredSource: 'remote-url',
      },
      {
        kind: 'denied',
        reason: 'private-no-access',
        resolvedLogin: 'bob',
        declaredLogin: 'alice',
        declaredSource: 'credential-config',
      },
    );
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      cc1Broadcaster: { signal },
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const before = signal.mock.calls.length;

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(signal.mock.calls.length).toBeGreaterThan(before);
    await engine.destroy();
  });

  test('a re-probe with an identical outcome does not re-broadcast', async () => {
    await initGitWithOrigin();
    const signal = vi.fn();
    const probe = fakeProbe(
      { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
      { kind: 'denied', reason: 'private-no-access', resolvedLogin: 'alice' },
    );
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      cc1Broadcaster: { signal },
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const before = signal.mock.calls.length;

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(signal.mock.calls.length).toBe(before);
    await engine.destroy();
  });

  test('a denied probe leaves the repository-not-found park intact', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'private-no-access' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-not-found-as-identity';

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    const status = engine.getStatus();
    expect(status.pausedReason).toBe('auth-error');
    expect(status.state).toBe('auth-error');
    expect(status.pushErrorCode).toBe('auth-not-found-as-identity');
    await engine.destroy();
  });

  test('a denied probe DOES demote a non-masquerade auth park', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-403';

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(engine.getStatus().pausedReason).toBe('no-push-permission');
    await engine.destroy();
  });

  test('the not-found park survives a denied probe even after an offline transition', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'allowed' }, { kind: 'denied', reason: 'private-no-access' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const internal = engine as unknown as InternalState;
    internal.state = 'offline';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-not-found-as-identity';

    await engine.refreshPushPermission();

    expect(probe.calls).toBe(2);
    expect(engine.getStatus().pausedReason).toBe('auth-error');
    await engine.destroy();
  });

  test('an origin with no declared account probes with no login — the owner is never a selector', async () => {
    await initGitWithOrigin('https://github.com/inkeep/open-knowledge.git');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      _readCredentialUrlMatch: () => null,
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(probe.opts[0]?.account?.source).toBe('active');
    expect(probe.opts[0]?.account?.login).toBeUndefined();
  });

  test('a denied probe result carries its identity fields into getStatus()', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({
      kind: 'denied',
      reason: 'private-no-access',
      resolvedLogin: 'bob',
      declaredLogin: 'alice',
      declaredSource: 'remote-url',
    });
    const engine = makeProbeEngine({
      syncEnabled: false,
      fakeProbe: probe.fn,
      _readCredentialUrlMatch: () => null,
    });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'denied',
      deniedReason: 'private-no-access',
      resolvedLogin: 'bob',
      declaredLogin: 'alice',
      declaredSource: 'remote-url',
    });
  });

  test('records `denied` and pauses in-memory when syncEnabled is true', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const status = engine.getStatus();
    expect(probe.calls).toBe(1);
    expect(status.pushPermission).toEqual({
      checkStatus: 'denied',
      deniedReason: 'no-collaborator',
    });
    expect(status.state).toBe('disabled');
    expect(status.pausedReason).toBe('no-push-permission');
  });

  test('records `denied` but does NOT change state when syncEnabled is false', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const status = engine.getStatus();
    expect(status.pushPermission?.checkStatus).toBe('denied');
    expect(status.pausedReason).not.toBe('no-push-permission');
  });

  test('maps private-no-access denial through to status', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'private-no-access' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'denied',
      deniedReason: 'private-no-access',
    });
  });

  test('maps repo-not-found denial through to status', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'repo-not-found' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'denied',
      deniedReason: 'repo-not-found',
    });
  });

  test('does NOT write autoSync.enabled = false to __local__/project on denied (D6 in-memory invariant)', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const persisted =
      existsSync(join(okDir, 'config.yml')) || existsSync(join(okDir, 'config.json'));
    expect(persisted).toBe(false);
  });

  test('passes the origin transport through to the probe (declared ssh origin)', async () => {
    await initGitWithOrigin('[email protected]:acme/kb.git');
    declareGitHubHosts(home(), 'git.example.com');
    const probe = fakeProbe({ kind: 'unknown', error: 'ssh-unverified' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(probe.opts[0]).toMatchObject({
      owner: 'acme',
      repo: 'kb',
      host: 'git.example.com',
      transport: 'ssh',
    });
  });

  test('ssh-unverified probe result does NOT pause the engine (declared self-hosted forge over SSH)', async () => {
    await initGitWithOrigin('[email protected]:acme/kb.git');
    declareGitHubHosts(home(), 'git.example.com');
    const probe = fakeProbe({ kind: 'unknown', error: 'ssh-unverified' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const status = engine.getStatus();
    expect(status.pushPermission).toEqual({
      checkStatus: 'unknown',
      unknownError: 'ssh-unverified',
    });
    expect(status.state).toBe('idle');
    expect(status.pausedReason).not.toBe('no-push-permission');
  });

  test('records `unknown` without changing state', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'unknown', error: 'network' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const status = engine.getStatus();
    expect(status.pushPermission).toEqual({
      checkStatus: 'unknown',
      unknownError: 'network',
    });
    expect(status.state).toBe('idle');
    expect(status.pausedReason).not.toBe('no-push-permission');
  });

  test('refreshPushPermission re-runs the probe and updates status', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'unknown', error: 'network' }, { kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission?.checkStatus).toBe('unknown');

    const next = await engine.refreshPushPermission();
    expect(next).toEqual({ checkStatus: 'allowed' });
    expect(engine.getStatus().pushPermission?.checkStatus).toBe('allowed');
    expect(probe.calls).toBe(2);
  });

  test('refreshPushPermission resumes idle when a previously-denied user gets push access', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' }, { kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().state).toBe('disabled');
    expect(engine.getStatus().pausedReason).toBe('no-push-permission');

    await engine.refreshPushPermission();
    const status = engine.getStatus();
    expect(status.pushPermission?.checkStatus).toBe('allowed');
    expect(status.state).toBe('idle');
    expect(status.pausedReason).toBeUndefined();
  });

  test('refreshPushPermission emits unknown for non-github origin (does not call probe)', async () => {
    await initGitWithOrigin('https://gitlab.com/foo/bar.git');
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    const result = await engine.refreshPushPermission();
    expect(result).toEqual({ checkStatus: 'unknown' });
    expect(probe.calls).toBe(0);
  });

  test('handles a probe that throws (defense-in-depth)', async () => {
    await initGitWithOrigin();
    const throwingProbe: FakeProbeRecorder['fn'] = async () => {
      throw new Error('injected fake failure');
    };
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: throwingProbe });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission).toEqual({
      checkStatus: 'unknown',
      unknownError: 'network',
    });
  });

  test('pushPermission is omitted from status before the probe resolves', () => {
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    expect(engine.getStatus().pushPermission).toBeUndefined();
  });

  test('FR7: pushPermission is absent during the probe window (cold-start latency)', async () => {
    await initGitWithOrigin();
    let resolveProbe: (p: PushPermission) => void = () => {};
    const slowProbe: FakeProbeRecorder['fn'] = () => {
      const { promise, resolve } = Promise.withResolvers<PushPermission>();
      resolveProbe = resolve;
      return promise;
    };
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: slowProbe });
    await engine.start();
    expect(engine.getStatus().pushPermission).toBeUndefined();
    resolveProbe({ kind: 'allowed' });
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().pushPermission?.checkStatus).toBe('allowed');
  });

  test('FR7: `unknown` (network failure) preserves the absent-or-allowed UI invariant', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'unknown', error: 'network' });
    const engine = makeProbeEngine({ syncEnabled: false, fakeProbe: probe.fn });
    await engine.start();
    await waitForPushPermissionResolved(engine);
    const status = engine.getStatus();
    expect(status.pushPermission?.checkStatus).toBe('unknown');
    expect(status.pushPermission?.checkStatus).not.toBe('denied');
  });

  test('FR7: transitioning idle → fetching during probe window does NOT set no-push-permission pausedReason', async () => {
    await initGitWithOrigin();
    let resolveProbe: (p: PushPermission) => void = () => {};
    const slowProbe: FakeProbeRecorder['fn'] = () => {
      const { promise, resolve } = Promise.withResolvers<PushPermission>();
      resolveProbe = resolve;
      return promise;
    };
    const engine = makeProbeEngine({ syncEnabled: true, fakeProbe: slowProbe });
    await engine.start();
    expect(engine.getStatus().state).toBe('idle');
    expect(engine.getStatus().pausedReason).not.toBe('no-push-permission');
    resolveProbe({ kind: 'allowed' });
    await waitForPushPermissionResolved(engine);
    expect(engine.getStatus().state).toBe('idle');
    expect(engine.getStatus().pausedReason).toBeUndefined();
  });
});

describe('SyncEngine getStatus() with restored state', () => {
  const statePath = () => join(okDir, 'sync-state.json');

  test('lastSyncUtc and lastFetchUtc are restored', async () => {
    const now = new Date().toISOString();
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: now,
        lastFetchUtc: now,
        lastPushedSha: 'abc123',
        consecutiveFailures: 0,
        inflightConflicts: [],
      }),
      'utf-8',
    );

    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    const status = engine.getStatus();
    expect(status.lastSyncUtc).toBe(now);
    expect(status.lastFetchUtc).toBe(now);
    expect(status.lastPushedSha).toBe('abc123');
  });
});

interface InternalState {
  state: SyncState;
  pausedReason?: string;
  pushError?: string;
  pullError?: string;
  pushErrorCode?: string;
  pullErrorCode?: string;
  cycleInFlight: 'pull' | 'push' | null;
  gitHandle: () => unknown;
  handleError: (classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull') => void;
}

describe('SyncEngine auth-error recovery', () => {
  const statePath = () => join(okDir, 'sync-state.json');

  test('does not restore a persisted auth-error pausedReason (re-attempts on restart)', async () => {
    writeFileSync(
      statePath(),
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        inflightConflicts: [],
        pausedReason: 'auth-error',
      }),
      'utf-8',
    );
    const engine = makeEngine({ syncEnabled: false });
    await engine.start();
    expect(engine.getStatus().pausedReason).toBeUndefined();
  });

  test('saveStateNow does not persist auth-error when set in-memory', async () => {
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';

    await engine.destroy();

    const reloaded = JSON.parse(readFileSync(statePath(), 'utf-8')) as { pausedReason?: string };
    expect(reloaded.pausedReason).toBeUndefined();
  });

  test('notifyCredentialsChanged clears auth-error and re-evaluates', async () => {
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushError = 'no credential';
    internal.pullError = 'no credential';
    internal.pushErrorCode = 'auth-no-credential';
    internal.pullErrorCode = 'auth-no-credential';
    expect(engine.getStatus().state).toBe('auth-error');

    await engine.notifyCredentialsChanged();

    const status = engine.getStatus();
    expect(status.state).not.toBe('auth-error');
    expect(status.pausedReason).toBeUndefined();
    expect(status.pushError).toBeUndefined();
    expect(status.pullError).toBeUndefined();
    expect(status.pushErrorCode).toBeUndefined();
    expect(status.pullErrorCode).toBeUndefined();
    expect(status.state).toBe('dormant');
    await engine.destroy();
  });

  test('notifyCredentialsChanged is a no-op when sync is disabled', async () => {
    const engine = makeEngine({ syncEnabled: false });
    (engine as unknown as InternalState).pausedReason = 'auth-error';
    await engine.notifyCredentialsChanged();
    expect(engine.getStatus().pausedReason).toBe('auth-error');
  });

  test('notifyCredentialsChanged rebuilds the credential chain, even when sync is off', async () => {
    const resolved = [
      ['credential.helper=!ok auth git-credential'],
      ['credential.helper=', 'credential.helper=!ok auth git-credential'],
    ];
    let calls = 0;
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: false,
      credentialConfig: resolved[0],
      resolveCredentialConfig: async () => resolved[Math.min(++calls, 1)],
    });
    expect(engine.getCredentialConfig()).toEqual(resolved[0]);

    await engine.notifyCredentialsChanged();

    expect(engine.getCredentialConfig()).toEqual(resolved[1]);
  });

  test.each([
    ['pull', (engine: SyncEngine) => engine.pullOnce()],
    ['push', (engine: SyncEngine) => engine.pushOnce()],
  ] as const)(
    'a token removed outside the server drops the ambient reset from the next %s',
    async (_op, runCycle) => {
      await initGitWithOrigin('https://git.invalid/team/notes.git');
      const storedHosts = new Set(['git.invalid']);
      const resolveCredentialConfig = createSyncCredentialConfigResolver({
        projectDir,
        tokenStore: {
          async get(host: string) {
            return storedHosts.has(host) ? { login: 'alice', token: 'tok' } : null;
          },
        },
        localOpCliArgs: ['open-knowledge'],
        declaredGitHubHosts: new Set(),
      });
      const engine = new SyncEngine({
        conflicts: newAuthority(),
        projectDir,
        contentDir,
        contentFilter: stubContentFilter,
        syncEnabled: false,
        credentialConfig: await resolveCredentialConfig(),
        resolveCredentialConfig,
      });
      const internal = engine as unknown as { hasRemote: boolean; gitHandle: () => GitHandle };
      internal.hasRemote = true;
      const createGitHandle = internal.gitHandle.bind(engine);
      const invocationChains: string[][] = [];
      internal.gitHandle = () => {
        const handle = createGitHandle();
        invocationChains.push(handle.credentialConfig);
        return handle;
      };
      expect(engine.getCredentialConfig()).toContain('credential.helper=');

      storedHosts.delete('git.invalid');
      await runCycle(engine);

      expect(invocationChains.length).toBeGreaterThan(0);
      expect(invocationChains[0]).not.toContain('credential.helper=');
      expect(invocationChains[0]).toHaveLength(1);
      await engine.destroy();
    },
  );

  test('a failed credential chain rebuild keeps the previous chain', async () => {
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: false,
      credentialConfig: ['credential.helper=!ok auth git-credential'],
      resolveCredentialConfig: async () => {
        throw new Error('keychain locked');
      },
    });

    await engine.notifyCredentialsChanged();

    expect(engine.getCredentialConfig()).toEqual(['credential.helper=!ok auth git-credential']);
  });

  test('a push-permission pause left over from a GitHub origin clears once the origin is not GitHub', async () => {
    await initGitWithOrigin('https://gitlab.com/team/notes.git');
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState & { hasRemote: boolean };
    internal.hasRemote = true;
    internal.state = 'disabled';
    internal.pausedReason = 'no-push-permission';

    const result = await engine.refreshPushPermission();

    expect(result).toEqual({ checkStatus: 'unknown' });
    expect(engine.getStatus().pausedReason).toBeUndefined();
    expect(engine.getStatus().state).toBe('idle');
    await engine.destroy();
  });

  test('notifyCredentialsChanged is a no-op when not parked on auth-error', async () => {
    const engine = makeEngine({ syncEnabled: true });
    const before = engine.getStatus().state;
    await engine.notifyCredentialsChanged();
    expect(engine.getStatus().state).toBe(before);
  });

  test('a manual trigger clears the identity-ambiguous not-found park', async () => {
    await simpleGit(projectDir).init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-not-found-as-identity';
    expect(engine.getStatus().state).toBe('auth-error');

    await engine.trigger('sync');

    const status = engine.getStatus();
    expect(status.state).not.toBe('auth-error');
    expect(status.pausedReason).toBeUndefined();
    expect(status.pushErrorCode).toBeUndefined();
    await engine.destroy();
  });

  test('a manual trigger keeps every other auth park parked', async () => {
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-401';

    await engine.trigger('sync');

    expect(engine.getStatus().state).toBe('auth-error');
    expect(engine.getStatus().pausedReason).toBe('auth-error');
    await engine.destroy();
  });

  test('a pull-side not-found park clears on manual trigger too', async () => {
    await simpleGit(projectDir).init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    const engine = makeEngine({ syncEnabled: true });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pullErrorCode = 'auth-not-found-as-identity';

    await engine.trigger('sync');

    const status = engine.getStatus();
    expect(status.state).not.toBe('auth-error');
    expect(status.pausedReason).toBeUndefined();
    expect(status.pullErrorCode).toBeUndefined();
    await engine.destroy();
  });

  test('un-parking via trigger(push) revives the pull loop', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');
    const bareDir = join(tmpDir, 'unpark-bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      pullIntervalSeconds: 0.05,
    });
    const internal = engine as unknown as InternalState;
    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-not-found-as-identity';

    await engine.trigger('push');
    expect(engine.getStatus().state).not.toBe('auth-error');

    const deadline = Date.now() + 5000;
    while (engine.getStatus().lastFetchUtc === null) {
      if (Date.now() > deadline) throw new Error('pull loop never ran after trigger(push)');
      await new Promise((r) => setTimeout(r, 10));
    }
    await engine.destroy();
  });

  test('a manual trigger on the not-found park flushes both identity caches', async () => {
    await initGitWithOrigin();
    const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
    let urlmatchCalls = 0;
    const probe = fakeProbe({ kind: 'allowed' });
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: false,
      detectGh: detect.fn,
      _readCredentialUrlMatch: () => {
        urlmatchCalls++;
        return null;
      },
      checkPushPermissionFn: probe.fn,
    });
    const internal = engine as unknown as InternalState;

    internal.gitHandle();
    const detectAfterPrime = detect.calls();
    const urlmatchAfterPrime = urlmatchCalls;
    expect(detectAfterPrime).toBeGreaterThan(0);
    expect(urlmatchAfterPrime).toBeGreaterThan(0);
    internal.gitHandle();
    expect(detect.calls()).toBe(detectAfterPrime);
    expect(urlmatchCalls).toBe(urlmatchAfterPrime);

    internal.state = 'auth-error';
    internal.pausedReason = 'auth-error';
    internal.pushErrorCode = 'auth-not-found-as-identity';
    await engine.trigger('push');

    internal.gitHandle();
    expect(detect.calls()).toBeGreaterThan(detectAfterPrime);
    expect(urlmatchCalls).toBeGreaterThan(urlmatchAfterPrime);
    await engine.destroy();
  });
});

function recordDetectGh(
  result: ReturnType<DetectGhFn> | ((host?: string, login?: string) => ReturnType<DetectGhFn>),
): {
  fn: DetectGhFn;
  calls: () => number;
  lastHost: () => string | undefined;
  logins: () => Array<string | undefined>;
} {
  let calls = 0;
  let lastHost: string | undefined;
  const logins: Array<string | undefined> = [];
  return {
    fn: (host?: string, options?: { login?: string }) => {
      const login = options?.login;
      calls++;
      lastHost = host;
      logins.push(login);
      return typeof result === 'function' ? result(host, login) : result;
    },
    calls: () => calls,
    lastHost: () => lastHost,
    logins: () => logins,
  };
}

describe('SyncEngine gh-token credential relay', () => {
  const home = useIsolatedHome();

  test('threads the resolved gh token through git handles during a real push cycle', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# Test\n');
    await git.add('.');
    await git.commit('Initial');

    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);

    writeFileSync(join(projectDir, 'README.md'), '# Test\n\nchange\n');
    await git.add('.');
    await git.commit('local commit');

    const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      detectGh: detect.fn,
    });
    try {
      await engine.start();
      await engine.trigger('push');

      expect(detect.calls()).toBeGreaterThan(0);
      expect(detect.lastHost()).toBe('github.com');
    } finally {
      await engine.destroy();
    }
  });

  test('resolves the gh token against a declared GitHub Enterprise origin host', async () => {
    await initGitWithOrigin('https://ghes.acme.test/inkeep/open-knowledge.git');
    declareGitHubHosts(home(), 'ghes.acme.test');
    const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      detectGh: detect.fn,
    });
    try {
      (engine as unknown as { gitHandle: () => unknown }).gitHandle();
      expect(detect.calls()).toBe(1);
      expect(detect.lastHost()).toBe('ghes.acme.test');
    } finally {
      await engine.destroy();
    }
  });

  test('caches the gh token across handles, then re-resolves after an auth error', () => {
    const detect = recordDetectGh({ available: true, token: 'gho_relayed' });
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      detectGh: detect.fn,
    });
    const internal = engine as unknown as InternalState;

    internal.gitHandle();
    internal.gitHandle();
    expect(detect.calls()).toBe(1);

    internal.handleError(
      classifyGitError(
        new Error(
          'fatal: could not read Username for https://github.com: terminal prompts disabled',
        ),
      ),
      'push',
    );
    internal.gitHandle();
    expect(detect.calls()).toBe(2);
  });
});

describe('SyncEngine declared-account resolution', () => {
  function countingUrlMatch(response: string | null): {
    fn: CredentialUrlMatchReader;
    calls: () => number;
  } {
    let calls = 0;
    return {
      fn: () => {
        calls += 1;
        return response;
      },
      calls: () => calls,
    };
  }

  function makeAccountEngine(
    detect: DetectGhFn,
    readUrlMatch: CredentialUrlMatchReader,
    detectGhAccounts?: DetectGhAccountsFn,
  ) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir,
      contentFilter: stubContentFilter,
      syncEnabled: true,
      detectGh: detect,
      detectGhAccounts,
      _readCredentialUrlMatch: readUrlMatch,
    });
  }

  const honorRequested = (_host?: string, login?: string): ReturnType<DetectGhFn> =>
    login
      ? { available: true, token: `gho_${login}`, resolvedLogin: login }
      : { available: true, token: 'gho_active' };

  test('threads the URL-declared account into gh and names it in the relay env', async () => {
    await initGitWithOrigin('https://[email protected]/mona/kb.git');
    const detect = recordDetectGh(honorRequested);
    const urlMatch = countingUrlMatch(null);
    const engine = makeAccountEngine(detect.fn, urlMatch.fn);

    const handle = (engine as unknown as { gitHandle: () => GitHandle }).gitHandle();

    expect(detect.logins()).toEqual(['alice']);
    expect(detect.lastHost()).toBe('github.com');
    expect(handle.env.OK_GH_TOKEN).toBe('gho_alice');
    expect(handle.env.OK_GH_TOKEN_LOGIN).toBe('alice');
    expect(urlMatch.calls()).toBe(0);
  });

  test('an org-owned origin with no declared account resolves exactly as before', async () => {
    await initGitWithOrigin('https://github.com/inkeep/kb.git');
    const detect = recordDetectGh(honorRequested);
    const urlMatch = countingUrlMatch(null);
    const engine = makeAccountEngine(detect.fn, urlMatch.fn);

    const handle = (engine as unknown as { gitHandle: () => GitHandle }).gitHandle();

    expect(detect.logins()).toEqual([undefined]);
    expect(detect.lastHost()).toBe('github.com');
    expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
    expect('OK_GH_TOKEN_LOGIN' in handle.env).toBe(false);
  });

  test('the credential-config lookup runs once per window across many handles', async () => {
    await initGitWithOrigin('https://github.com/inkeep/kb.git');
    const detect = recordDetectGh(honorRequested);
    const urlMatch = countingUrlMatch(null);
    const engine = makeAccountEngine(detect.fn, urlMatch.fn);
    const internal = engine as unknown as { gitHandle: () => GitHandle };

    internal.gitHandle();
    internal.gitHandle();
    internal.gitHandle();

    expect(urlMatch.calls()).toBe(1);
    expect(detect.calls()).toBe(1);
  });

  test('a remote-URL account edit takes effect on the next handle, no restart', async () => {
    const git = await initGitWithOrigin('https://[email protected]/mona/kb.git');
    const detect = recordDetectGh(honorRequested);
    const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
    const internal = engine as unknown as { gitHandle: () => GitHandle };

    expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('alice');
    await git.raw('remote', 'set-url', 'origin', 'https://[email protected]/mona/kb.git');
    expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('bob');
    expect(detect.logins()).toEqual(['alice', 'bob']);
  });

  test('a declared account gh cannot serve warns once per miss and recovers', async () => {
    await initGitWithOrigin('https://[email protected]/mona/kb.git');
    let honor = false;
    const detect = recordDetectGh((_host, login) => {
      if (!login) return { available: true, token: 'gho_active' };
      return honor
        ? { available: true, token: 'gho_alice', resolvedLogin: login }
        : { available: true, token: 'gho_active', fallback: true };
    });
    const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
    const internal = engine as unknown as { gitHandle: () => GitHandle };
    const logs = captureSyncLogs();
    const missWarns = () =>
      logs.entries.filter((e) => e.level === 'warn' && e.msg.includes('declared GitHub account'));

    try {
      const handle = internal.gitHandle();
      internal.gitHandle();
      internal.gitHandle();

      expect(missWarns()).toHaveLength(1);
      expect(missWarns()[0]?.data).toMatchObject({
        host: 'github.com',
        declaredLogin: 'alice',
        declaredSource: 'remote-url',
      });
      expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
      expect('OK_GH_TOKEN_LOGIN' in handle.env).toBe(false);

      honor = true;
      await engine.notifyCredentialsChanged();
      expect(internal.gitHandle().env.OK_GH_TOKEN_LOGIN).toBe('alice');
      expect(missWarns()).toHaveLength(1);

      honor = false;
      await engine.notifyCredentialsChanged();
      internal.gitHandle();
      expect(missWarns()).toHaveLength(2);
    } finally {
      logs.restore();
    }
  });

  test('a declared account with no gh token at all still warns once', async () => {
    await initGitWithOrigin('https://[email protected]/mona/kb.git');
    const detect = recordDetectGh(() => ({ available: false }));
    const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn);
    const internal = engine as unknown as { gitHandle: () => GitHandle };
    const logs = captureSyncLogs();
    const missWarns = () =>
      logs.entries.filter((e) => e.level === 'warn' && e.msg.includes('declared GitHub account'));

    try {
      const handle = internal.gitHandle();
      internal.gitHandle();

      expect(missWarns()).toHaveLength(1);
      expect(missWarns()[0]?.msg).toContain('no gh token');
      expect(missWarns()[0]?.data).toMatchObject({
        host: 'github.com',
        declaredLogin: 'alice',
        declaredSource: 'remote-url',
      });
      expect('OK_GH_TOKEN' in handle.env).toBe(false);
    } finally {
      logs.restore();
    }
  });

  test('the fallback warning names the active account that answered instead', async () => {
    await initGitWithOrigin('https://[email protected]/mona/kb.git');
    const detect = recordDetectGh((_host, login) =>
      login
        ? { available: true, token: 'gho_active', fallback: true }
        : { available: true, token: 'gho_active' },
    );
    const accounts: DetectGhAccountsFn = () => [{ login: 'bob', active: true }];
    const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn, accounts);
    const internal = engine as unknown as { gitHandle: () => GitHandle };
    const logs = captureSyncLogs();

    try {
      internal.gitHandle();
      const warn = logs.entries.find(
        (e) => e.level === 'warn' && e.msg.includes('declared GitHub account'),
      );
      expect(warn?.data).toMatchObject({ declaredLogin: 'alice', resolvedLogin: 'bob' });
    } finally {
      logs.restore();
    }
  });

  test('a throwing accounts listing costs the warning its name, not the handle its token', async () => {
    await initGitWithOrigin('https://[email protected]/mona/kb.git');
    const detect = recordDetectGh((_host, login) =>
      login
        ? { available: true, token: 'gho_active', fallback: true }
        : { available: true, token: 'gho_active' },
    );
    const accounts: DetectGhAccountsFn = () => {
      throw new Error('gh exploded');
    };
    const engine = makeAccountEngine(detect.fn, countingUrlMatch(null).fn, accounts);
    const internal = engine as unknown as { gitHandle: () => GitHandle };
    const logs = captureSyncLogs();

    try {
      const handle = internal.gitHandle();
      expect(handle.env.OK_GH_TOKEN).toBe('gho_active');
      const miss = logs.entries.find(
        (e) => e.level === 'warn' && e.msg.includes('declared GitHub account'),
      );
      expect(miss?.data).toMatchObject({ declaredLogin: 'alice' });
      expect((miss?.data as { resolvedLogin?: string } | undefined)?.resolvedLogin).toBeUndefined();
      const failed = logs.entries.find(
        (e) => e.level === 'warn' && e.msg.includes('detectGhAccounts failed'),
      );
      expect(failed?.data).toMatchObject({ host: 'github.com' });
    } finally {
      logs.restore();
    }
  });
});

describe('SyncEngine sync mode', () => {
  test('constructing with a mode reports it in status', () => {
    expect(makeEngine({ mode: 'follow' }).getStatus().syncMode).toBe('follow');
    expect(makeEngine({ mode: 'full' }).getStatus().syncMode).toBe('full');
    expect(makeEngine({ mode: 'off' }).getStatus().syncMode).toBe('off');
  });

  test('syncEnabled is true for pull and full, false for off', () => {
    expect(makeEngine({ mode: 'follow' }).getStatus().syncEnabled).toBe(true);
    expect(makeEngine({ mode: 'full' }).getStatus().syncEnabled).toBe(true);
    expect(makeEngine({ mode: 'off' }).getStatus().syncEnabled).toBe(false);
  });

  test('legacy syncEnabled option maps to a mode (true→full, else off)', () => {
    expect(makeEngine({ syncEnabled: true }).getStatus().syncMode).toBe('full');
    expect(makeEngine({ syncEnabled: false }).getStatus().syncMode).toBe('off');
    expect(makeEngine({}).getStatus().syncMode).toBe('off');
  });

  test('setEnabled adapter maps to a mode (true→full, false→off)', async () => {
    const engine = makeEngine({ mode: 'off' });
    try {
      await engine.setEnabled(true);
      expect(engine.getStatus().syncMode).toBe('full');
      await engine.setEnabled(false);
      expect(engine.getStatus().syncMode).toBe('off');
    } finally {
      await engine.destroy();
    }
  });

  test('setMode records the new mode', async () => {
    const engine = makeEngine({ mode: 'off' });
    try {
      await engine.setMode('follow');
      expect(engine.getStatus().syncMode).toBe('follow');
    } finally {
      await engine.destroy();
    }
  });

  test('setMode is a no-op on a same-value call', async () => {
    const states: SyncState[] = [];
    const engine = makeEngine({ mode: 'off', onStateChange: (s) => states.push(s) });
    try {
      await engine.setMode('off');
      expect(states).toEqual([]);
      expect(engine.getStatus().syncMode).toBe('off');
    } finally {
      await engine.destroy();
    }
  });

  test('getStatus() output conforms to the wire schema and carries syncMode', () => {
    const parsed = SyncStatusSchema.safeParse(makeEngine({ mode: 'follow' }).getStatus());
    expect(parsed.success).toBe(true);
    expect(parsed.success && parsed.data.syncMode).toBe('follow');
  });
});

describe('SyncEngine pull-only mode', () => {
  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  test('pull cycle fast-forwards the clone to origin tip and updates the working tree', async () => {
    const bareDir = await seedBareOrigin();

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'doc.md'), 'v1\n', 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    writeFileSync(join(sisterDir, 'doc.md'), 'v1\nv2\n', 'utf-8');
    await sister.add('.');
    await sister.commit('advance');
    await sister.push('origin', 'main');
    const originTip = (await sister.revparse(['HEAD'])).trim();

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
    });
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('v1\nv2\n');
      expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
      expect(engine.getStatus().state).toBe('idle');
    } finally {
      await engine.destroy();
    }
  });

  test('never pushes local commits on its own, but honors an explicit push', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'README.md'), '# seed\n');
    await git.add('.');
    await git.commit('seed');

    const bareDir = await seedBareOrigin();
    await git.addRemote('origin', bareDir);
    await git.push(['--set-upstream', 'origin', 'main']);
    const originBefore = (await git.revparse(['origin/main'])).trim();

    writeFileSync(join(projectDir, 'README.md'), '# seed\n\nlocal edit\n');
    await git.add('.');
    await git.commit('local commit not pushed');
    const localHead = (await git.revparse(['HEAD'])).trim();
    expect(localHead).not.toBe(originBefore);

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
    });
    try {
      await engine.start();

      expect((await git.revparse(['origin/main'])).trim()).toBe(originBefore);
      expect(engine.getStatus().lastPushedSha).toBeNull();

      await engine.trigger('push');

      expect((await git.revparse(['origin/main'])).trim()).toBe(localHead);
      expect(engine.getStatus().lastPushedSha).toBe(localHead);
      expect(engine.getStatus().syncMode).toBe('follow');
    } finally {
      await engine.destroy();
    }
  });

  test('a denied push probe keeps the engine pulling (no pause)', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ mode: 'follow', fakeProbe: probe.fn });
    try {
      await engine.start();
      await waitForPushPermissionResolved(engine);
      const status = engine.getStatus();
      expect(status.pushPermission).toEqual({
        checkStatus: 'denied',
        deniedReason: 'no-collaborator',
      });
      expect(status.state).not.toBe('disabled');
      expect(status.pausedReason).not.toBe('no-push-permission');
      expect(status.syncMode).toBe('follow');
    } finally {
      await engine.destroy();
    }
  });

  test('a denied push probe still pauses a full-sync engine (unchanged behavior)', async () => {
    await initGitWithOrigin();
    const probe = fakeProbe({ kind: 'denied', reason: 'no-collaborator' });
    const engine = makeProbeEngine({ mode: 'full', fakeProbe: probe.fn });
    try {
      await engine.start();
      await waitForPushPermissionResolved(engine);
      const status = engine.getStatus();
      expect(status.state).toBe('disabled');
      expect(status.pausedReason).toBe('no-push-permission');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine pull-only B1 fast-forward cycle', () => {
  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  async function cloneBehindOrigin(opts: {
    seed: Record<string, string>;
    advance: Record<string, string | null>;
  }): Promise<{ originTip: string; bareDir: string }> {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    for (const [f, c] of Object.entries(opts.advance)) {
      if (c === null) rmSync(join(sisterDir, f), { force: true });
      else writeFileSync(join(sisterDir, f), c, 'utf-8');
    }
    await sister.raw(['add', '-A']);
    await sister.commit('advance');
    await sister.push('origin', 'main');
    return { originTip: (await sister.revparse(['HEAD'])).trim(), bareDir };
  }

  function makePullEngine(
    opts: {
      onContentConflictsResolved?: (files: string[]) => void;
      onContentConflictsDetected?: (files: string[]) => void;
    } = {},
  ) {
    const conflicts = newAuthority();
    const detected = opts.onContentConflictsDetected;
    const resolved = opts.onContentConflictsResolved;
    conflicts.subscribe((change) => {
      if (change.type === 'raised') detected?.([change.conflict.file]);
      else resolved?.([change.file]);
    });
    return new SyncEngine({
      conflicts,
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
    });
  }

  async function assertNoGitResidue(): Promise<void> {
    expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
    const stashList = await simpleGit(projectDir).raw(['stash', 'list']);
    expect(stashList.trim()).toBe('');
  }

  test('non-overlapping local edit survives the fast-forward', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'A1\n', 'b.md': 'B1\n' },
      advance: { 'b.md': 'B1\nB2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL\n');
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);
      await assertNoGitResidue();
      expect(engine.getStatus().state).toBe('idle');
    } finally {
      await engine.destroy();
    }
  });

  test('a byte-identical overlay converges silently', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'v1\n' },
      advance: { 'a.md': 'v1\nv2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'v1\nv2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('v1\nv2\n');
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('tracked MCP overlay upgrades to the incoming newer launcher without a commit', async () => {
    const mcp = (marker: string) =>
      `${JSON.stringify({
        mcpServers: {
          other: { command: 'keep-me' },
          'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', `${marker}\nexit 127`] },
        },
      })}\n`;
    const { originTip } = await cloneBehindOrigin({
      seed: { '.mcp.json': mcp('# ok-mcp-v1') },
      advance: { '.mcp.json': mcp('# ok-mcp-v2') },
    });
    writeFileSync(join(projectDir, '.mcp.json'), mcp('# ok-mcp-v1'), 'utf8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, '.mcp.json'), 'utf8')).toBe(mcp('# ok-mcp-v2'));
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([]);
      expect(
        (await project.log()).all.filter((commit) => commit.message.includes('MCP launcher')),
      ).toEqual([]);
    } finally {
      await engine.destroy();
    }
  });

  test('tracked MCP overlay preserves a recognized future launcher over incoming v2', async () => {
    const mcp = (marker: string) =>
      `${JSON.stringify({
        mcpServers: {
          other: { command: 'keep-me' },
          'open-knowledge': { command: '/bin/sh', args: ['-l', '-c', `${marker}\nexit 127`] },
        },
      })}\n`;
    const { originTip } = await cloneBehindOrigin({
      seed: { '.mcp.json': mcp('# ok-mcp-v1') },
      advance: { '.mcp.json': mcp('# ok-mcp-v2') },
    });
    writeFileSync(join(projectDir, '.mcp.json'), mcp('# ok-mcp-v99'), 'utf8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, '.mcp.json'), 'utf8')).toBe(mcp('# ok-mcp-v99'));
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual([
        '.mcp.json',
      ]);
    } finally {
      await engine.destroy();
    }
  });

  test('a locally-deleted content file the tip modifies is restored from origin', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'C1\n', 'keep.md': 'K1\n' },
      advance: { 'a.md': 'C1\nC2\n', 'keep.md': 'K1\nK2\n' },
    });
    rmSync(join(projectDir, 'a.md'), { force: true });

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');
      expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');
      expect(authority.list()).toEqual([]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('a locally-deleted NON-content file the tip modifies stays deleted', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'cfg.json': '{"a":1}\n', 'keep.md': 'K1\n' },
      advance: { 'cfg.json': '{"a":2}\n', 'keep.md': 'K1\nK2\n' },
    });
    rmSync(join(projectDir, 'cfg.json'), { force: true });

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(existsSync(join(projectDir, 'cfg.json'))).toBe(false);
      expect(readFileSync(join(projectDir, 'keep.md'), 'utf-8')).toBe('K1\nK2\n');
      expect(authority.list()).toEqual([]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('same-file overlap keeps the local edit while the branch reaches origin tip', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n', 'b.md': 'B1\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n', 'b.md': 'B1\nB2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('checkpoints the overlay before the reset, capturing the pre-reset bytes', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const seen: Array<{ paths: number; bytesAtCheckpoint: string }> = [];
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
      checkpointBeforeOverlayRestore: ({ paths }) => {
        seen.push({ paths, bytesAtCheckpoint: readFileSync(join(projectDir, 'a.md'), 'utf-8') });
      },
    });
    try {
      await engine.start();
      await engine.trigger('pull');

      expect(seen).toHaveLength(1);
      expect(seen[0]?.paths).toBe(1);
      expect(seen[0]?.bytesAtCheckpoint).toBe('LOCAL1\nline2\n');
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('does not checkpoint when the pull has no overlapping edit', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'A1\n', 'b.md': 'B1\n' },
      advance: { 'b.md': 'B1\nB2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');

    let calls = 0;
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
      checkpointBeforeOverlayRestore: () => {
        calls += 1;
      },
    });
    try {
      await engine.start();
      await engine.trigger('pull');

      expect(calls).toBe(0);
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
    } finally {
      await engine.destroy();
    }
  });

  test('a failing overlay checkpoint does not abort the cycle', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'follow',
      checkpointBeforeOverlayRestore: () => {
        throw new Error('shadow unavailable');
      },
    });
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('refuses an incoming symlink that escapes the repo before any overlay write, leaving its target untouched', async () => {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'a.md'), 'A1\n', 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    writeFileSync(join(projectDir, 'a.md'), 'A1\nLOCAL\n', 'utf-8');

    const escapeTarget = join(tmpDir, 'escape-target.txt');
    writeFileSync(escapeTarget, 'PRECIOUS\n', 'utf-8');
    rmSync(join(sisterDir, 'a.md'), { force: true });
    symlinkSync(escapeTarget, join(sisterDir, 'a.md'));
    await sister.raw(['add', '-A']);
    await sister.commit('a.md -> escape');
    await sister.push('origin', 'main');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      expect(readFileSync(escapeTarget, 'utf-8')).toBe('PRECIOUS\n');
      expect(engine.getStatus().lastPullOutcome).toBe('refused');
      expect(engine.getStatus().pausedReason).toBe('unsafe-incoming-symlinks');
    } finally {
      await engine.destroy();
    }
  });

  test('a local symlink in the way of an overlay is replaced by the restore, never written through', async () => {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'a.md'), 'A1\n', 'utf-8');
    mkdirSync(join(sisterDir, 'sub'), { recursive: true });
    writeFileSync(join(sisterDir, 'sub', 'a.md'), 'A1\n', 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    const escapeDir = join(tmpDir, 'escape-dir');
    mkdirSync(escapeDir, { recursive: true });
    const escapeTarget = join(escapeDir, 'a.md');
    writeFileSync(escapeTarget, 'A1\nLOCAL\n', 'utf-8');
    rmSync(join(projectDir, 'sub'), { recursive: true, force: true });
    symlinkSync(escapeDir, join(projectDir, 'sub'));

    writeFileSync(join(sisterDir, 'sub', 'a.md'), 'A1\nREMOTE\n', 'utf-8');
    await sister.add('sub/a.md');
    await sister.commit('remote edit');
    await sister.push('origin', 'main');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      expect(readFileSync(escapeTarget, 'utf-8')).toBe('A1\nLOCAL\n');
      expect(lstatSync(join(projectDir, 'sub')).isSymbolicLink()).toBe(false);
      expect(engine.getStatus().pausedReason).not.toBe('unsafe-incoming-symlinks');
    } finally {
      await engine.destroy();
    }
  });

  test('diverged local history pauses instead of merging', async () => {
    const { bareDir } = await cloneBehindOrigin({
      seed: { 'a.md': 'v1\n' },
      advance: { 'a.md': 'v1\nORIGIN\n' },
    });
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Follower');
    await project.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'a.md'), 'v1\nLOCAL COMMIT\n', 'utf-8');
    await project.add('.');
    await project.commit('local commit ahead');
    const localTip = (await project.revparse(['HEAD'])).trim();

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      expect((await project.revparse(['HEAD'])).trim()).toBe(localTip);
      expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
    expect(bareDir).toContain('bare.git');
  });

  test('different-line edits to the same file auto-combine with no conflict', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'L1\nL2\nL3\n' },
      advance: { 'a.md': 'L1\nL2\nORIGIN3\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nL2\nL3\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nL2\nORIGIN3\n');
      expect(authority.list()).toEqual([]);
      expect(engine.getStatus().state).toBe('idle');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('same-line collision raises a pinned working-tree conflict and never forks', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      await assertNoGitResidue();

      const conflicts = workingTreeConflicts();
      expect(authority.list()).toHaveLength(1);
      expect(conflicts).toHaveLength(1);
      expect(conflicts[0]?.file).toBe('a.md');
      expect(conflicts[0]?.theirsSha).toMatch(/^[0-9a-f]{40}$/);
      expect(conflicts[0]?.baseSha).toMatch(/^[0-9a-f]{40}$/);
      expect(engine.getStatus().state).toBe('idle');
    } finally {
      await engine.destroy();
    }
  });

  test('a non-content overlap keeps the local edit without raising a conflict', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'config.json': '{"a":1}\n' },
      advance: { 'config.json': '{"a":2}\n' },
    });
    writeFileSync(join(projectDir, 'config.json'), '{"a":3}\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'config.json'), 'utf-8')).toBe('{"a":3}\n');
      expect(authority.list()).toEqual([]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('a locally-deleted content file the tip modifies is restored, not conflicted', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { 'a.md': 'C1\n' },
      advance: { 'a.md': 'C1\nC2\n' },
    });
    rmSync(join(projectDir, 'a.md'), { force: true });

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('C1\nC2\n');
      expect(authority.list()).toEqual([]);
      expect(engine.getStatus().state).toBe('idle');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  async function advanceOriginFrom(files: Record<string, string | null>): Promise<string> {
    const sisterDir = join(tmpDir, 'sister');
    const sister = simpleGit(sisterDir);
    for (const [f, c] of Object.entries(files)) {
      if (c === null) rmSync(join(sisterDir, f), { force: true });
      else writeFileSync(join(sisterDir, f), c, 'utf-8');
    }
    await sister.raw(['add', '-A']);
    await sister.commit('advance again');
    await sister.push('origin', 'main');
    return (await sister.revparse(['HEAD'])).trim();
  }

  test('an unresolved collision re-pins theirs to the latest tip on each pull', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      const firstPin = workingTreeConflicts()[0]?.theirsSha;
      expect(firstPin).toMatch(/^[0-9a-f]{40}$/);

      const tip2 = await advanceOriginFrom({ 'a.md': 'ORIGIN1b\nline2\n' });
      await engine.trigger('pull');

      const conflicts = workingTreeConflicts();
      expect(conflicts).toHaveLength(1);
      expect(conflicts[0]?.theirsSha).not.toBe(firstPin);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('a collision auto-dissolves when upstream converges to the local overlay', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      expect(authority.list()).toHaveLength(1);

      const tip2 = await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });
      await engine.trigger('pull');

      expect(authority.list()).toEqual([]);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip2);
      expect(await listNames(simpleGit(projectDir), ['diff-index', '--name-only', 'HEAD'])).toEqual(
        [],
      );
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('notifies the resolved callback when a collision auto-dissolves', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const resolved: string[][] = [];
    const engine = makePullEngine({
      onContentConflictsResolved: (files) => {
        resolved.push([...files]);
      },
    });
    try {
      await engine.start();
      await engine.trigger('pull');
      expect(authority.list()).toHaveLength(1);

      await advanceOriginFrom({ 'a.md': 'LOCAL1\nline2\n' });
      await engine.trigger('pull');

      expect(authority.list()).toEqual([]);
      expect(resolved).toEqual([['a.md']]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('a fast-forward refusal restores the overlay bytes (mineRestore guard)', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');
    const headBefore = (await simpleGit(projectDir).revparse(['HEAD'])).trim();

    const engine = makePullEngine();
    const ffSpy = vi
      .spyOn(engine as unknown as { fastForwardOnly: () => Promise<unknown> }, 'fastForwardOnly')
      .mockResolvedValue({
        ok: false,
        refusal: 'divergence',
        stderr: '',
        exitCode: 128,
        timedOut: false,
      });
    try {
      await engine.start();
      const outcome = await engine.pullOnce();

      expect(ffSpy).toHaveBeenCalled();
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      expect(outcome).toBe('refused');
      expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(headBefore);
    } finally {
      await engine.destroy();
    }
  });

  test('resolving take-theirs writes the tip version and clears the conflict without committing', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();
      expect(authority.list()).toHaveLength(1);

      await authority.resolve('a.md', 'theirs');

      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('ORIGIN1\nline2\n');
      expect(authority.list()).toEqual([]);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('REPRO: content-strategy resolve fires the resolved callback', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const resolved: string[][] = [];
    const engine = makePullEngine({
      onContentConflictsResolved: (files) => {
        resolved.push([...files]);
      },
    });
    try {
      await engine.start();
      await engine.trigger('pull');
      expect(authority.list()).toHaveLength(1);

      await authority.resolve('a.md', 'content', 'MERGED\nline2\n');

      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('MERGED\nline2\n');
      expect(authority.list()).toEqual([]);
      expect(resolved).toEqual([['a.md']]);
    } finally {
      await engine.destroy();
    }
  });

  test('a merge-native resolve also fires the resolved callback', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');
    const git = simpleGit(projectDir);
    await git.raw('config', 'user.name', 'Test');
    await git.raw('config', 'user.email', '[email protected]');
    await git.add('a.md');
    await git.commit('local edit');

    const resolved: string[][] = [];
    const conflicts = newAuthority();
    conflicts.subscribe((change) => {
      if (change.type === 'cleared') resolved.push([change.file]);
    });
    const engine = new SyncEngine({
      conflicts,
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'auto',
    });
    try {
      await engine.start();
      await engine.trigger('sync');
      expect(authority.list()).toHaveLength(1);

      await authority.resolve('a.md', 'content', 'MERGED\nline2\n');

      expect(authority.list()).toEqual([]);
      expect(resolved).toEqual([['a.md']]);
    } finally {
      await engine.destroy();
    }
  });

  test('resolving keep-mine leaves the overlay and clears the conflict without committing', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      const tip = (await simpleGit(projectDir).revparse(['HEAD'])).trim();

      await authority.resolve('a.md', 'mine');

      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('LOCAL1\nline2\n');
      expect(authority.list()).toEqual([]);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(tip);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('a non-content overlap is never auto-committed in pull mode', async () => {
    const { originTip } = await cloneBehindOrigin({
      seed: { '.mcp.json': '{"v":1}\n', 'a.md': 'A1\n' },
      advance: { '.mcp.json': '{"v":2}\n', 'a.md': 'A1\nA2\n' },
    });
    writeFileSync(join(projectDir, '.mcp.json'), '{"v":3}\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, '.mcp.json'), 'utf-8')).toBe('{"v":3}\n');
      expect(authority.list()).toEqual([]);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('reconcileConflictsFromGit leaves working-tree conflicts intact', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'line1\nline2\n' },
      advance: { 'a.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nline2\n', 'utf-8');

    const engine = makePullEngine();
    try {
      await engine.start();
      await engine.trigger('pull');
      expect(authority.list()).toHaveLength(1);

      await authority.pruneMergeNativeAgainstGit();
      expect(authority.list()).toHaveLength(1);
    } finally {
      await engine.destroy();
    }
  });

  test('a persisted working-tree conflict survives boot and keeps the engine idle', async () => {
    await cloneBehindOrigin({
      seed: { 'a.md': 'v1\n' },
      advance: { 'a.md': 'v1\nv2\n' },
    });
    const blob = (await simpleGit(projectDir).raw(['rev-parse', 'HEAD:a.md'])).trim();
    writeFileSync(
      join(okDir, 'conflicts.json'),
      JSON.stringify({
        version: 1,
        branch: 'main',
        conflicts: [
          {
            file: 'a.md',
            detectedAt: new Date().toISOString(),
            variant: 'working-tree',
            theirsSha: blob,
            baseSha: blob,
          },
        ],
      }),
      'utf-8',
    );

    const engine = makePullEngine();
    try {
      await engine.start();
      expect(authority.list().map((c) => c.file)).toEqual(['a.md']);
      expect(engine.getStatus().state).toBe('idle');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine pull-only mode transitions', () => {
  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  async function seedAndClone(seed: Record<string, string>): Promise<{
    seedTip: string;
    bareDir: string;
    sister: ReturnType<typeof simpleGit>;
    sisterDir: string;
  }> {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    for (const [f, c] of Object.entries(seed)) writeFileSync(join(sisterDir, f), c, 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');
    const seedTip = (await sister.revparse(['HEAD'])).trim();

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Follower');
    await project.raw('config', 'user.email', '[email protected]');
    return { seedTip, bareDir, sister, sisterDir };
  }

  async function advanceOrigin(
    sister: ReturnType<typeof simpleGit>,
    sisterDir: string,
    files: Record<string, string | null>,
  ): Promise<string> {
    for (const [f, c] of Object.entries(files)) {
      if (c === null) rmSync(join(sisterDir, f), { force: true });
      else writeFileSync(join(sisterDir, f), c, 'utf-8');
    }
    await sister.raw(['add', '-A']);
    await sister.commit('advance');
    await sister.push('origin', 'main');
    return (await sister.revparse(['HEAD'])).trim();
  }

  async function commitLocal(files: Record<string, string>, msg: string): Promise<string> {
    const project = simpleGit(projectDir);
    for (const [f, c] of Object.entries(files)) writeFileSync(join(projectDir, f), c, 'utf-8');
    await project.add('.');
    await project.commit(msg);
    return (await project.revparse(['HEAD'])).trim();
  }

  function makeEngineMode(
    mode: SyncMode,
    checkpoint?: (ctx: { branch: string; ahead: number }) => void | Promise<void>,
  ) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode,
      pullIntervalSeconds: 99999,
      pushIntervalSeconds: 99999,
      checkpointBeforeStrandedConversion: checkpoint,
    });
  }

  async function waitForHead(sha: string, timeoutMs = 5000): Promise<void> {
    const deadline = Date.now() + timeoutMs;
    const project = simpleGit(projectDir);
    while ((await project.revparse(['HEAD'])).trim() !== sha) {
      if (Date.now() > deadline) throw new Error(`HEAD did not reach ${sha} within ${timeoutMs}ms`);
      await new Promise((r) => setTimeout(r, 20));
    }
  }

  async function assertNoGitResidue(): Promise<void> {
    expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
    const stashList = await simpleGit(projectDir).raw(['stash', 'list']);
    expect(stashList.trim()).toBe('');
  }

  test('a failed stranded-commit conversion surfaces the divergence instead of a clean idle', async () => {
    await seedAndClone({ 'a.md': 'A1\n' });
    await commitLocal({ 'a.md': 'A1\nLOCAL2\n' }, 'local 1');
    await commitLocal({ 'a.md': 'A1\nLOCAL2\nLOCAL3\n' }, 'local 2');
    writeFileSync(join(projectDir, '.git', 'index.lock'), '', 'utf-8');

    const engine = makeEngineMode('full');
    try {
      await engine.setMode('follow');
      expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');
    } finally {
      rmSync(join(projectDir, '.git', 'index.lock'), { force: true });
      await engine.destroy();
    }
  });

  test('full→pull downgrade folds ahead-only commits into an overlay at origin tip', async () => {
    const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });
    await commitLocal({ 'a.md': 'A1\nLOCAL2\n' }, 'local 1');
    const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL2\nLOCAL3\n' }, 'local 2');

    const engine = makeEngineMode('full');
    try {
      await engine.setMode('follow');

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(seedTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL2\nLOCAL3\n');
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);
      expect((await project.raw(['rev-list', '--count', 'origin/main..HEAD'])).trim()).toBe('0');
      expect((await project.revparse(['ORIG_HEAD'])).trim()).toBe(localTip);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('enable-time divergence converts then fast-forwards to origin tip', async () => {
    const { sister, sisterDir } = await seedAndClone({ 'a.md': 'A1\n', 'b.md': 'B1\n' });
    const originTip = await advanceOrigin(sister, sisterDir, { 'b.md': 'B1\nB2\n' });
    await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');

    const engine = makeEngineMode('off');
    try {
      await engine.setMode('follow');
      await waitForHead(originTip);

      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'a.md'), 'utf-8')).toBe('A1\nLOCAL\n');
      expect(readFileSync(join(projectDir, 'b.md'), 'utf-8')).toBe('B1\nB2\n');
      expect(await listNames(project, ['diff-index', '--name-only', 'HEAD'])).toEqual(['a.md']);
      expect((await project.raw(['rev-list', '--count', 'origin/main..HEAD'])).trim()).toBe('0');
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('the checkpoint fires before the branch ref moves', async () => {
    const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });
    const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');

    let checkpointAhead = 0;
    let headAtCheckpoint: string | null = null;
    const engine = makeEngineMode('off', async ({ ahead }) => {
      checkpointAhead = ahead;
      headAtCheckpoint = (await simpleGit(projectDir).revparse(['HEAD'])).trim();
    });
    try {
      await engine.setMode('follow');

      expect(checkpointAhead).toBe(1);
      expect(headAtCheckpoint).toBe(localTip);
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(seedTip);
    } finally {
      await engine.destroy();
    }
  });

  test('off→pull with no ahead commits enables plainly (no conversion)', async () => {
    const { seedTip } = await seedAndClone({ 'a.md': 'A1\n' });

    let checkpointCalled = false;
    const engine = makeEngineMode('off', () => {
      checkpointCalled = true;
    });
    try {
      await engine.setMode('follow');

      expect(checkpointCalled).toBe(false);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(seedTip);
      expect(engine.getStatus().syncMode).toBe('follow');
    } finally {
      await engine.destroy();
    }
  });

  test('off→full keeps ahead commits (full mode pushes them, never converts)', async () => {
    await seedAndClone({ 'a.md': 'A1\n' });
    const localTip = await commitLocal({ 'a.md': 'A1\nLOCAL\n' }, 'local edit');

    let checkpointCalled = false;
    const engine = makeEngineMode('off', () => {
      checkpointCalled = true;
    });
    try {
      await engine.setMode('full');

      expect(checkpointCalled).toBe(false);
      expect((await simpleGit(projectDir).revparse(['HEAD'])).trim()).toBe(localTip);
      await assertNoGitResidue();
    } finally {
      await engine.destroy();
    }
  });

  test('pull→full upgrade pushes the overlay content on the next cycle', async () => {
    const { bareDir } = await seedAndClone({ 'a.md': 'A1\n' });
    writeFileSync(join(projectDir, 'a.md'), 'A1\nOVERLAY\n', 'utf-8');

    const engine = makeEngineMode('follow');
    try {
      await engine.setMode('full');
      await engine.trigger('push');

      const originContent = await simpleGit(bareDir).raw(['show', 'main:a.md']);
      expect(originContent).toBe('A1\nOVERLAY\n');
    } finally {
      await engine.destroy();
    }
  });

  test('probeUnpushedCommitCount reports the stranded count with and without an upstream', async () => {
    await seedAndClone({ 'a.md': 'A1\n' });
    await commitLocal({ 'a.md': 'A1\nL1\n' }, 'local 1');
    await commitLocal({ 'a.md': 'A1\nL1\nL2\n' }, 'local 2');

    const engine = makeEngineMode('off');
    try {
      await engine.refreshRemote();
      expect(await engine.probeUnpushedCommitCount()).toBe(2);

      await simpleGit(projectDir).raw(['branch', '--unset-upstream']);
      expect(await engine.probeUnpushedCommitCount()).toBe(2);
    } finally {
      await engine.destroy();
    }
  });
});

describe('classifyFastForwardRefusal (pinned against real git)', () => {
  async function realFfRefusal(): Promise<{ code: number | null; stderr: string }> {
    try {
      await execFileAsync(
        'git',
        ['-c', 'core.autocrlf=false', 'merge', '--ff-only', 'origin/main'],
        {
          cwd: projectDir,
          env: { ...process.env, LANG: 'C', LC_ALL: 'C' },
        },
      );
      throw new Error('expected fast-forward to refuse');
    } catch (e) {
      const err = e as { code?: number | string; stderr?: string };
      return {
        code: typeof err.code === 'number' ? err.code : null,
        stderr: typeof err.stderr === 'string' ? err.stderr : String(e),
      };
    }
  }

  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  async function cloneBehind(advance: string): Promise<void> {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'a.md'), 'l1\nl2\n', 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');
    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    writeFileSync(join(sisterDir, 'a.md'), advance, 'utf-8');
    await sister.add('.');
    await sister.commit('advance');
    await sister.push('origin', 'main');
    await simpleGit(projectDir).fetch('origin');
  }

  test('an overlapping dirty edit classifies as overlay-overlap', async () => {
    await cloneBehind('ORIGIN1\nl2\n');
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL1\nl2\n', 'utf-8');
    const { code, stderr } = await realFfRefusal();
    expect(code).toBe(1);
    expect(classifyFastForwardRefusal({ exitCode: code, stderr })).toBe('overlay-overlap');
  });

  test('diverged history classifies as divergence', async () => {
    await cloneBehind('ORIGIN1\nl2\n');
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Follower');
    await project.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'a.md'), 'LOCAL_COMMIT\nl2\n', 'utf-8');
    await project.add('.');
    await project.commit('local ahead');
    const { code, stderr } = await realFfRefusal();
    expect(code).toBe(128);
    expect(classifyFastForwardRefusal({ exitCode: code, stderr })).toBe('divergence');
  });
});

describe("SyncEngine one-shot pull (op 'pull')", () => {
  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  async function cloneFromOrigin(opts: {
    seed: Record<string, string>;
    advance?: Record<string, string>;
  }): Promise<{ originTip: string; bareDir: string }> {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    if (opts.advance) {
      for (const [f, c] of Object.entries(opts.advance)) {
        writeFileSync(join(sisterDir, f), c, 'utf-8');
      }
      await sister.add('.');
      await sister.commit('advance');
      await sister.push('origin', 'main');
    }
    return { originTip: (await sister.revparse(['HEAD'])).trim(), bareDir };
  }

  function makeEngineFor(mode: SyncMode) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode,
    });
  }

  async function assertNoGitResidue(): Promise<void> {
    expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
    expect((await simpleGit(projectDir).raw(['stash', 'list'])).trim()).toBe('');
  }

  test('mode off: a one-shot pull fast-forwards without enabling the project', async () => {
    const { originTip, bareDir } = await cloneFromOrigin({
      seed: { 'doc.md': 'v1\n' },
      advance: { 'doc.md': 'v1\nv2\n' },
    });
    const originRefBefore = (await simpleGit(bareDir).revparse(['main'])).trim();

    const engine = makeEngineFor('off');
    try {
      await engine.start();
      expect(engine.getStatus().state).toBe('disabled');

      const outcome = await engine.pullOnce();

      expect(outcome).toBe('succeeded');
      const project = simpleGit(projectDir);
      expect((await project.revparse(['HEAD'])).trim()).toBe(originTip);
      expect(readFileSync(join(projectDir, 'doc.md'), 'utf-8')).toBe('v1\nv2\n');
      const status = engine.getStatus();
      expect(status.syncMode).toBe('off');
      expect(status.state).toBe('disabled');
      expect(status.lastPullOutcome).toBe('succeeded');
      expect(typeof status.lastPullUtc).toBe('string');
      await assertNoGitResidue();
      expect((await simpleGit(bareDir).revparse(['main'])).trim()).toBe(originRefBefore);
    } finally {
      await engine.destroy();
    }
  });

  test('an already-current project reports up-to-date', async () => {
    await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });
    const engine = makeEngineFor('follow');
    try {
      await engine.start();
      const outcome = await engine.pullOnce();
      expect(outcome).toBe('up-to-date');
      expect(typeof engine.getStatus().lastPullUtc).toBe('string');
    } finally {
      await engine.destroy();
    }
  });

  test('a same-line collision reports conflict', async () => {
    await cloneFromOrigin({
      seed: { 'doc.md': 'line1\nline2\n' },
      advance: { 'doc.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'doc.md'), 'LOCAL1\nline2\n', 'utf-8');
    const engine = makeEngineFor('follow');
    try {
      await engine.start();
      const outcome = await engine.pullOnce();
      expect(outcome).toBe('conflict');
      expect(engine.getStatus().conflictCount).toBe(1);
      expect(engine.getStatus().lastPullOutcome).toBe('conflict');
    } finally {
      await engine.destroy();
    }
  });

  test('a concurrent one-shot is refused (single-flight)', async () => {
    await cloneFromOrigin({
      seed: { 'doc.md': 'v1\n' },
      advance: { 'doc.md': 'v1\nv2\n' },
    });
    const engine = makeEngineFor('follow');
    try {
      await engine.start();
      const first = engine.pullOnce();
      const second = await engine.pullOnce();
      expect(second).toBe('refused');
      expect(await first).toBe('succeeded');
    } finally {
      await engine.destroy();
    }
  });

  test('an unreachable remote reports error-class', async () => {
    await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });
    await simpleGit(projectDir).raw(
      'config',
      'remote.origin.url',
      join(tmpDir, 'nonexistent-bare.git'),
    );
    const engine = makeEngineFor('follow');
    try {
      await engine.start();
      const outcome = await engine.pullOnce();
      expect(outcome).toBe('error');
      const status = engine.getStatus();
      expect(status.lastPullOutcome).toBe('error');
      expect(`${status.pullError ?? ''}${status.pullErrorCode ?? ''}`).not.toBe('');
    } finally {
      await engine.destroy();
    }
  });

  test("trigger('pull') records the outcome in status", async () => {
    await cloneFromOrigin({
      seed: { 'doc.md': 'v1\n' },
      advance: { 'doc.md': 'v1\nv2\n' },
    });
    const engine = makeEngineFor('follow');
    try {
      await engine.start();
      await engine.trigger('pull');
      const status = engine.getStatus();
      expect(status.lastPullOutcome).toBe('succeeded');
      expect(typeof status.lastPullUtc).toBe('string');
    } finally {
      await engine.destroy();
    }
  });

  test('lastPullUtc is null before the first pull and set after (change-detection)', async () => {
    await cloneFromOrigin({
      seed: { 'doc.md': 'v1\n' },
      advance: { 'doc.md': 'v1\nv2\n' },
    });
    const engine = makeEngineFor('off');
    try {
      await engine.start();
      expect(engine.getStatus().lastPullUtc).toBeNull();
      expect(engine.getStatus().lastPullOutcome).toBeNull();
      await engine.pullOnce();
      expect(engine.getStatus().lastPullUtc).not.toBeNull();
      expect(engine.getStatus().lastPullOutcome).toBe('succeeded');
    } finally {
      await engine.destroy();
    }
  });

  test('refuses when there is no remote', async () => {
    const git = simpleGit(projectDir);
    await git.init(['--initial-branch=main']);
    configureTestGitRepository(projectDir);
    await git.raw('config', 'user.name', 'Solo');
    await git.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(projectDir, 'doc.md'), 'v1\n', 'utf-8');
    await git.add('.');
    await git.commit('seed');
    const engine = makeEngineFor('off');
    try {
      await engine.start();
      const outcome = await engine.pullOnce();
      expect(outcome).toBe('refused');
      expect(engine.getStatus().lastPullOutcome).toBe('refused');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine telemetry', () => {
  async function seedBareOrigin(): Promise<string> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    await simpleGit(bareDir).init(true);
    configureTestGitRepository(bareDir);
    await simpleGit(bareDir).raw('symbolic-ref', 'HEAD', 'refs/heads/main');
    return bareDir;
  }

  async function cloneFromOrigin(opts: {
    seed: Record<string, string>;
    advance?: Record<string, string>;
  }): Promise<void> {
    const bareDir = await seedBareOrigin();
    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    for (const [f, c] of Object.entries(opts.seed)) writeFileSync(join(sisterDir, f), c, 'utf-8');
    await sister.add('.');
    await sister.commit('seed');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });

    if (opts.advance) {
      for (const [f, c] of Object.entries(opts.advance)) {
        writeFileSync(join(sisterDir, f), c, 'utf-8');
      }
      await sister.add('.');
      await sister.commit('advance');
      await sister.push('origin', 'main');
    }
  }

  function makeEngineFor(mode: SyncMode) {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode,
    });
  }

  test('setMode logs the mode change with its source', async () => {
    await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });
    const engine = makeEngineFor('off');
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.setMode('full', 'committed-default');
      const entry = cap.entries.find((e) => e.msg === '[sync] mode changed');
      expect(entry).toBeDefined();
      expect(entry?.data).toMatchObject({ from: 'off', to: 'full', source: 'committed-default' });
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  test('an unchanged setMode emits no mode-change log', async () => {
    await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' } });
    const engine = makeEngineFor('follow');
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.setMode('follow');
      expect(cap.entries.some((e) => e.msg === '[sync] mode changed')).toBe(false);
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  test('a one-shot pull logs its mode and outcome on success', async () => {
    await cloneFromOrigin({ seed: { 'doc.md': 'v1\n' }, advance: { 'doc.md': 'v1\nv2\n' } });
    const engine = makeEngineFor('off');
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.pullOnce();
      const entry = cap.entries.find((e) => e.msg === '[sync] one-shot pull complete');
      expect(entry).toBeDefined();
      expect(entry?.data).toMatchObject({ mode: 'off', outcome: 'succeeded' });
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  test('a refused one-shot pull still logs the refused outcome', async () => {
    const engine = makeEngineFor('off');
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.pullOnce();
      const entry = cap.entries.find((e) => e.msg === '[sync] one-shot pull complete');
      expect(entry?.data).toMatchObject({ mode: 'off', outcome: 'refused' });
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  test('a B1 pull logs conflict-lifecycle counts and the overlay-stock gauge', async () => {
    await cloneFromOrigin({
      seed: { 'docA.md': 'line1\nline2\n', 'docB.md': 'b1\nb2\nb3\n', 'docC.md': 'c\n' },
      advance: { 'docA.md': 'ORIGIN1\nline2\n', 'docB.md': 'b1\nb2\nORIGIN3\n' },
    });
    writeFileSync(join(projectDir, 'docA.md'), 'LOCAL1\nline2\n', 'utf-8');
    writeFileSync(join(projectDir, 'docB.md'), 'LOCAL1\nb2\nb3\n', 'utf-8');
    writeFileSync(join(projectDir, 'docC.md'), 'c\nlocal-extra\n', 'utf-8');
    const engine = makeEngineFor('follow');
    const cap = captureSyncLogs();
    try {
      await engine.start();
      await engine.pullOnce();
      const entry = cap.entries.find(
        (e) => e.msg === '[sync] pull-only: fast-forwarded to origin tip',
      );
      expect(entry).toBeDefined();
      expect(entry?.data).toMatchObject({
        created: 1,
        autoCombined: 1,
        autoDissolved: 0,
        overlayStock: 3,
      });
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });

  test('resolving a working-tree conflict logs the chosen strategy', async () => {
    await cloneFromOrigin({
      seed: { 'doc.md': 'line1\nline2\n' },
      advance: { 'doc.md': 'ORIGIN1\nline2\n' },
    });
    writeFileSync(join(projectDir, 'doc.md'), 'LOCAL1\nline2\n', 'utf-8');
    const engine = makeEngineFor('follow');
    const cap = captureSyncLogs('conflict-authority');
    try {
      await engine.start();
      await engine.pullOnce();
      expect(engine.getStatus().conflictCount).toBe(1);
      await authority.resolve('doc.md', 'theirs');
      const entry = cap.entries.find((e) => e.msg === '[conflicts] conflict resolved by choice');
      expect(entry).toBeDefined();
      expect(entry?.data).toMatchObject({ choice: 'theirs', kind: 'working-tree' });
    } finally {
      cap.restore();
      await engine.destroy();
    }
  });
});

describe('SyncEngine blocking-change resolution', () => {
  async function setupOverlap(): Promise<void> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'settings.json'), '{"a":1}\n', 'utf-8');
    writeFileSync(join(sisterDir, 'keep.json'), '{"keep":1}\n', 'utf-8');
    writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');
    await sister.add('.');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');

    writeFileSync(join(sisterDir, 'settings.json'), '{"a":99}\n', 'utf-8');
    await sister.add('settings.json');
    await sister.commit('remote edit');
    await sister.push('origin', 'main');

    writeFileSync(join(projectDir, 'settings.json'), '{"a":2}\n', 'utf-8');
  }

  const markdownOnlyFilter = {
    isExcluded: (path: string) => !path.endsWith('.md'),
    isDirExcluded: (_path: string) => false,
  };

  function makeOverlapEngine(mode: SyncMode = 'full') {
    return new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: markdownOnlyFilter,
      mode,
    });
  }

  test('Manual mode publishes the blocking paths too, not just full', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine('off');
    try {
      await engine.start();
      await engine.trigger('sync');

      expect(engine.getStatus().pausedReason).toBe('external-changes-pending');
      expect(engine.getStatus().blockingPaths).toEqual(['settings.json']);
    } finally {
      await engine.destroy();
    }
  });

  test('a pause resolved outside the app is retracted by the next successful pull', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine();
    try {
      await engine.start();
      await engine.pullOnce('sync');
      expect(engine.getStatus().blockingPaths).toEqual(['settings.json']);

      await simpleGit(projectDir).checkout(['--', 'settings.json']);
      await engine.pullOnce('sync');

      expect(engine.getStatus().pausedReason).toBeUndefined();
      expect(engine.getStatus().blockingPaths).toBeUndefined();
    } finally {
      await engine.destroy();
    }
  });

  test('a restored pause does not outlive the paths it needs', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine();
    try {
      await engine.start();
      await engine.pullOnce('sync');
      expect(engine.getStatus().pausedReason).toBe('external-changes-pending');
      await engine.destroy();

      const restored = makeOverlapEngine();
      try {
        await restored.start();
        expect(restored.getStatus().pausedReason).not.toBe('external-changes-pending');
      } finally {
        await restored.destroy();
      }
    } finally {
      await engine.destroy();
    }
  });

  test('pausing on an overlap publishes the blocking paths, and resuming retracts them', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine();
    try {
      await engine.start();
      await engine.pullOnce('sync');

      expect(engine.getStatus().pausedReason).toBe('external-changes-pending');
      expect(engine.getStatus().blockingPaths).toEqual(['settings.json']);
      expect(engine.getBlockingPaths()).toEqual(['settings.json']);

      await engine.commitBlockingPaths();
      expect(engine.getStatus().blockingPaths).toBeUndefined();
      expect(engine.getBlockingPaths()).toEqual([]);
    } finally {
      await engine.destroy();
    }
  });

  test('commit takes exactly the blocking paths and leaves the rest of the tree dirty', async () => {
    await setupOverlap();
    writeFileSync(join(projectDir, 'keep.json'), '{"keep":2}\n', 'utf-8');

    const engine = makeOverlapEngine();
    try {
      await engine.start();
      await engine.pullOnce('sync');
      expect(engine.getBlockingPaths()).toEqual(['settings.json']);

      const sha = await engine.commitBlockingPaths();
      expect(sha).toMatch(/^[0-9a-f]{40}$/);

      const git = simpleGit(projectDir);
      const committed = await git.raw(['show', '--name-only', '--format=', 'HEAD']);
      expect(committed.trim()).toBe('settings.json');
      const status = await git.status();
      expect(status.modified).toContain('keep.json');
    } finally {
      await engine.destroy();
    }
  });

  test('the engine exposes no way to discard the blocking paths', async () => {
    const engine = makeOverlapEngine();
    try {
      expect((engine as unknown as Record<string, unknown>).discardBlockingPaths).toBeUndefined();
    } finally {
      await engine.destroy();
    }
  });

  test('a scoped probe is not fooled by content the user staged by hand', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine();
    try {
      await engine.start();
      await engine.pullOnce('sync');
      expect(engine.getBlockingPaths()).toEqual(['settings.json']);

      const pg = simpleGit(projectDir);
      await pg.checkout(['--', 'settings.json']);
      writeFileSync(join(projectDir, 'keep.json'), '{"staged":"by hand"}\n', 'utf-8');
      await pg.add('keep.json');

      expect(await engine.commitBlockingPaths()).toBeNull();
      const staged = await pg.raw(['diff', '--cached', '--name-only']);
      expect(staged.trim()).toBe('keep.json');
    } finally {
      await engine.destroy();
    }
  });

  test('the display cap does not leak into the action or hide the true set size', () => {
    const engine = makeOverlapEngine();
    const internals = engine as unknown as {
      blockingPaths: string[];
      pausedReason?: string;
    };
    internals.pausedReason = 'external-changes-pending';
    internals.blockingPaths = Array.from({ length: 60 }, (_, i) => `file-${i}.json`);

    expect(engine.getBlockingPaths()).toHaveLength(60);
    expect(engine.getStatus().blockingPaths).toHaveLength(50);
  });

  test('commit declines when nothing is blocking', async () => {
    await setupOverlap();
    const engine = makeOverlapEngine();
    try {
      await engine.start();
      expect(engine.getBlockingPaths()).toEqual([]);
      expect(await engine.commitBlockingPaths()).toBeNull();
      expect(readFileSync(join(projectDir, 'settings.json'), 'utf-8')).toBe('{"a":2}\n');
    } finally {
      await engine.destroy();
    }
  });
});

describe('SyncEngine split-leg backoff, end to end', () => {
  function pushCompeting(sisterDir: string, marker: string): void {
    writeFileSync(join(sisterDir, 'foo.md'), `${marker}\n`, 'utf-8');
    execFileSync('git', ['-C', sisterDir, 'commit', '-am', marker], { stdio: 'pipe' });
    execFileSync('git', ['-C', sisterDir, 'push', 'origin', 'main'], { stdio: 'pipe' });
  }

  async function setupWithSister(): Promise<{ bareDir: string; sisterDir: string }> {
    const bareDir = join(tmpDir, 'bare.git');
    mkdirSync(bareDir, { recursive: true });
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw('symbolic-ref', 'HEAD', 'refs/heads/main');

    const sisterDir = join(tmpDir, 'sister');
    mkdirSync(sisterDir, { recursive: true });
    const sister = simpleGit(sisterDir);
    await sister.init(['--initial-branch=main']);
    configureTestGitRepository(sisterDir);
    await sister.raw('config', 'user.name', 'Sister');
    await sister.raw('config', 'user.email', '[email protected]');
    writeFileSync(join(sisterDir, 'foo.md'), 'base\n', 'utf-8');
    await sister.add('.');
    await sister.commit('base');
    await sister.addRemote('origin', bareDir);
    await sister.push('origin', 'main');

    rmSync(projectDir, { recursive: true, force: true });
    await simpleGit(tmpDir).clone(bareDir, projectDir);
    configureTestGitRepository(projectDir);
    mkdirSync(okDir, { recursive: true });
    const project = simpleGit(projectDir);
    await project.raw('config', 'user.name', 'Project');
    await project.raw('config', 'user.email', '[email protected]');
    return { bareDir, sisterDir };
  }

  test('a real DNS-failure push charges the push leg, and a real fetch discharges it', async () => {
    const { bareDir } = await setupWithSister();
    const project = simpleGit(projectDir);

    await project.remote(['set-url', 'origin', 'http://sync-test.invalid/nope.git']);
    writeFileSync(join(projectDir, 'note.md'), 'local\n', 'utf-8');

    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      syncEnabled: true,
    });
    try {
      await engine.start();
      await engine.trigger('push');
      expect(engine.getStatus().consecutivePushFailures).toBeGreaterThan(0);

      await project.remote(['set-url', 'origin', bareDir]);
      await (engine as unknown as { runPullCycle(): Promise<void> }).runPullCycle();

      expect(engine.getStatus().consecutivePushFailures).toBe(0);
    } finally {
      await engine.stop();
    }
  });

  test('contention releases a connectivity streak and the message it disproved', async () => {
    const { sisterDir } = await setupWithSister();
    writeFileSync(join(projectDir, 'note.md'), 'mine\n', 'utf-8');
    pushCompeting(sisterDir, 'remote-1');

    let raced = false;
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      syncEnabled: true,
      setBatchInProgress: (value: boolean) => {
        if (value || raced) return;
        raced = true;
        pushCompeting(sisterDir, 'remote-2');
      },
    });
    try {
      await engine.start();
      const internals = engine as unknown as {
        consecutivePushFailures: number;
        consecutiveContentions: number;
        pushStreakIsConnectivity: boolean;
        pushError: string | undefined;
        runPushCycle(): Promise<void>;
      };
      internals.consecutivePushFailures = 5;
      internals.pushStreakIsConnectivity = true;
      internals.pushError = 'Connection timed out';

      await internals.runPushCycle();

      expect(raced).toBe(true);
      expect(internals.consecutiveContentions).toBe(1);
      expect(internals.consecutivePushFailures).toBe(0);
      expect(internals.pushStreakIsConnectivity).toBe(false);
      expect(engine.getStatus().pushError).toBeUndefined();
    } finally {
      await engine.stop();
    }
  });

  test('a double non-fast-forward counts as contention, not as backoff', async () => {
    const { sisterDir } = await setupWithSister();

    writeFileSync(join(projectDir, 'note.md'), 'mine\n', 'utf-8');
    pushCompeting(sisterDir, 'remote-1');

    let raced = false;
    const engine = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'full',
      syncEnabled: true,
      setBatchInProgress: (value: boolean) => {
        if (value || raced) return;
        raced = true;
        pushCompeting(sisterDir, 'remote-2');
      },
    });
    try {
      await engine.start();

      const internals = engine as unknown as {
        consecutivePushFailures: number;
        consecutiveContentions: number;
        runPushCycle(): Promise<void>;
      };
      internals.consecutivePushFailures = 4;
      await internals.runPushCycle();

      expect(raced).toBe(true);
      expect(internals.consecutivePushFailures).toBe(4);
      expect(internals.consecutiveContentions).toBe(1);
    } finally {
      await engine.stop();
    }
  });
});

describe('SyncEngine exclusive merge ownership', () => {
  interface CycleInternals {
    state: SyncState;
    hasRemote: boolean;
    pullTimer: NodeJS.Timeout | null;
    pushTimer: NodeJS.Timeout | null;
    conflictCount: number;
    pausedReason?: string;
    pullError?: string;
    pushError?: string;
    gitHandle(): GitHandle;
    saveStateNow(): void;
    commitDirtyContentFilesToHead(handle: GitHandle, op: 'push' | 'pull'): Promise<string | null>;
    doPushCycle(retriesLeft?: number): Promise<void>;
    doPullCycle(invocation: 'explicit' | 'sync'): Promise<'up-to-date'>;
    runPullCycle(): Promise<void>;
    handleError(classified: ReturnType<typeof classifyGitError>, op: 'push' | 'pull'): void;
  }

  async function setup(mode: SyncMode = 'full', signal = vi.fn()) {
    const bareDir = join(tmpDir, 'exclusive.git');
    mkdirSync(bareDir);
    const bare = simpleGit(bareDir);
    await bare.init(true);
    configureTestGitRepository(bareDir);
    await bare.raw(['symbolic-ref', 'HEAD', 'refs/heads/main']);
    const git = await initGitWithOrigin(bareDir);
    writeFileSync(join(projectDir, '.git', 'info', 'exclude'), '.ok/\n');
    await git.push(['--set-upstream', 'origin', 'main']);
    const conflicts = newAuthority();
    const engine = new SyncEngine({
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode,
      cc1Broadcaster: { signal },
      conflicts,
    });
    const internals = engine as unknown as CycleInternals;
    internals.hasRemote = true;
    internals.state = mode === 'off' ? 'disabled' : 'idle';
    return { engine, internals, git, bareDir, conflicts };
  }

  async function diverge(bareDir: string) {
    const sisterDir = join(tmpDir, 'exclusive-sister');
    await simpleGit(tmpDir).clone(bareDir, sisterDir);
    configureTestGitRepository(sisterDir);
    const sister = simpleGit(sisterDir);
    await sister.raw(['config', 'user.name', 'Sister']);
    await sister.raw(['config', 'user.email', '[email protected]']);
    writeFileSync(join(sisterDir, 'README.md'), 'theirs\n');
    await sister.add('README.md');
    await sister.commit('remote edit');
    await sister.push('origin', 'main');
    writeFileSync(join(projectDir, 'README.md'), 'ours\n');
  }

  test.each(['mine', 'theirs'] as const)(
    'a scheduled pull cannot enter a rejected push retry and %s resolves actual side bytes',
    async (strategy) => {
      const { engine, internals, git, bareDir, conflicts } = await setup();
      await diverge(bareDir);
      const enteredRetry = Promise.withResolvers<void>();
      const releaseRetry = Promise.withResolvers<void>();
      const commitDirty = internals.commitDirtyContentFilesToHead.bind(engine);
      let first = true;
      internals.commitDirtyContentFilesToHead = async (handle, op) => {
        if (first) {
          first = false;
          enteredRetry.resolve();
          await releaseRetry.promise;
        }
        return commitDirty(handle, op);
      };
      const push = engine.pushOnce();
      try {
        await enteredRetry.promise;
        const headBeforeMerge = await git.revparse('HEAD');
        await internals.runPullCycle();
        releaseRetry.resolve();
        await push;

        expect(await git.revparse('HEAD')).toBe(headBeforeMerge);
        expect(await git.raw(['show', 'HEAD:README.md'])).toBe('ours\n');
        expect(await git.raw(['show', ':2:README.md'])).toBe('ours\n');
        expect(await git.raw(['show', ':3:README.md'])).toBe('theirs\n');
        expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(true);
        expect(engine.getStatus().state).toBe('conflict');

        await conflicts.resolve('README.md', strategy);
        expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(
          strategy === 'mine' ? 'ours\n' : 'theirs\n',
        );
        expect(await git.raw(['diff', '--name-only', '--diff-filter=U'])).toBe('');
        expect(existsSync(join(projectDir, '.git', 'MERGE_HEAD'))).toBe(false);
      } finally {
        releaseRetry.resolve();
        await push;
        await engine.destroy();
      }
    },
  );

  test('a scheduled pull defers, preserves its timer, and resumes after a push', async () => {
    const { engine, internals } = await setup();
    const entered = Promise.withResolvers<void>();
    const release = Promise.withResolvers<void>();
    internals.doPushCycle = async () => {
      entered.resolve();
      await release.promise;
    };
    const pull = vi.fn(async () => 'up-to-date' as const);
    internals.doPullCycle = pull;
    const push = engine.pushOnce();
    try {
      await entered.promise;
      await internals.runPullCycle();
      expect(pull).not.toHaveBeenCalled();
      expect(internals.pullTimer).not.toBeNull();
      const deferredTimer = internals.pullTimer;
      await internals.runPullCycle();
      expect(internals.pullTimer).toBe(deferredTimer);
      release.resolve();
      await push;
      await internals.runPullCycle();
      expect(pull).toHaveBeenCalledTimes(1);
    } finally {
      release.resolve();
      await push;
      await engine.destroy();
    }
  });

  test('a follow-mode pull holds ownership while it is in flight', async () => {
    const { engine, internals } = await setup('follow');
    const entered = Promise.withResolvers<void>();
    const release = Promise.withResolvers<void>();
    const pull = vi.fn(async () => {
      entered.resolve();
      await release.promise;
      return 'up-to-date' as const;
    });
    const push = vi.fn(async () => {});
    internals.doPullCycle = pull;
    internals.doPushCycle = push;
    const running = internals.runPullCycle();
    try {
      await entered.promise;
      await engine.pushOnce();
      expect(await engine.pullOnce()).toBe('refused');
      expect(push).not.toHaveBeenCalled();
      expect(pull).toHaveBeenCalledTimes(1);
      release.resolve();
      await running;
      await engine.pushOnce();
      expect(push).toHaveBeenCalledTimes(1);
    } finally {
      release.resolve();
      await running;
      await engine.destroy();
    }
  });

  test.each(['autosave', 'interim'] as const)(
    '%s refuses an unmerged real index even without MERGE_HEAD',
    async (writer) => {
      const { engine, internals, git, bareDir } = await setup();
      await diverge(bareDir);
      await git.add('README.md');
      await git.commit('local edit');
      await git.fetch('origin');
      await expect(git.merge(['origin/main'])).rejects.toThrow();
      rmSync(join(projectDir, '.git', 'MERGE_HEAD'));
      const head = await git.revparse('HEAD');
      const stages = await git.raw(['ls-files', '--unmerged']);
      const working = readFileSync(join(projectDir, 'README.md'), 'utf8');
      try {
        if (writer === 'autosave') {
          await internals.doPushCycle();
        } else {
          await expect(
            internals.commitDirtyContentFilesToHead(internals.gitHandle(), 'pull'),
          ).rejects.toThrow('Git operation');
        }
        expect(await git.revparse('HEAD')).toBe(head);
        expect(await git.raw(['ls-files', '--unmerged'])).toBe(stages);
        expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(working);
      } finally {
        await engine.destroy();
      }
    },
  );

  test.each(['MERGE_HEAD', 'CHERRY_PICK_HEAD', 'REVERT_HEAD', 'rebase-merge', 'rebase-apply'])(
    'autosave and interim commits refuse %s with a resolved index',
    async (marker) => {
      const { engine, internals, git } = await setup();
      const head = await git.revparse('HEAD');
      const markerPath = join(projectDir, '.git', marker);
      if (marker.startsWith('rebase-')) mkdirSync(markerPath);
      else writeFileSync(markerPath, head);
      writeFileSync(join(projectDir, 'README.md'), 'resolved but not committed\n');
      const stages = await git.raw(['ls-files', '--stage']);
      try {
        await internals.doPushCycle();
        await expect(
          internals.commitDirtyContentFilesToHead(internals.gitHandle(), 'pull'),
        ).rejects.toThrow('Git operation');
        expect(await git.revparse('HEAD')).toBe(head);
        expect(await git.raw(['ls-files', '--stage'])).toBe(stages);
        expect(existsSync(markerPath)).toBe(true);
        expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe(
          'resolved but not committed\n',
        );
      } finally {
        await engine.destroy();
      }
    },
  );

  test('an unreadable real index refuses autosave without modifying the repository', async () => {
    const { engine, internals, git } = await setup();
    const head = await git.revparse('HEAD');
    const stages = await git.raw(['ls-files', '--stage']);
    writeFileSync(join(projectDir, 'README.md'), 'unsaved content\n');
    const handle = internals.gitHandle();
    const raw = vi.spyOn(handle.git, 'raw').mockRejectedValue(new Error('index unreadable'));
    const gitHandle = vi.spyOn(internals, 'gitHandle').mockReturnValue(handle);
    try {
      await internals.doPushCycle();
      expect(engine.getStatus().pushError).toContain('index unreadable');
      expect(await git.revparse('HEAD')).toBe(head);
      expect(await git.raw(['ls-files', '--stage'])).toBe(stages);
      expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe('unsaved content\n');
    } finally {
      raw.mockRestore();
      gitHandle.mockRestore();
      await engine.destroy();
    }
  });

  test('autosave resumes after an operation ends and preserves authored marker-like text', async () => {
    const { engine, git } = await setup();
    const content = '<<<<<<< example\nours\n=======\ntheirs\n>>>>>>> documentation\n';
    const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
    writeFileSync(markerPath, await git.revparse('HEAD'));
    writeFileSync(join(projectDir, 'README.md'), content);
    try {
      await engine.pushOnce();
      expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
      expect(engine.getStatus().pushError).toBeUndefined();
      rmSync(markerPath);
      await engine.pushOnce();
      expect(engine.getStatus().pushError).toBeUndefined();
      expect(await git.raw(['show', 'HEAD:README.md'])).toBe(content);
      expect(await git.revparse('HEAD')).toBe(await git.revparse('origin/main'));
    } finally {
      await engine.destroy();
    }
  });

  test('an idle refusal immediately broadcasts a retryable pause without replacing other errors', async () => {
    const signal = vi.fn();
    const { engine, internals, git } = await setup('full', signal);
    internals.pullError = 'unrelated pull failure';
    const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
    writeFileSync(markerPath, await git.revparse('HEAD'));
    try {
      await engine.pushOnce();
      expect(signal).toHaveBeenCalledWith('sync-status');
      expect(engine.getStatus()).toMatchObject({
        state: 'idle',
        pausedReason: 'git-operation-in-progress',
        pullError: 'unrelated pull failure',
      });
      expect(engine.getStatus().pushError).toBeUndefined();
      expect(engine.getStatus().pushErrorCode).toBeUndefined();
      expect(internals.pushTimer).not.toBeNull();
    } finally {
      await engine.destroy();
    }
  });

  test.each(['full', 'follow', 'off'] as const)(
    '%s exposes an operation refusal and a no-op push clears it after external recovery',
    async (mode) => {
      const { engine, git } = await setup(mode);
      const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
      const head = await git.revparse('HEAD');
      writeFileSync(markerPath, head);
      try {
        await engine.pushOnce();
        expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
        expect(engine.getStatus().pushError).toBeUndefined();
        await engine.pushOnce();
        expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
        rmSync(markerPath);
        await engine.pushOnce();
        expect(engine.getStatus().pausedReason).toBeUndefined();
        expect(engine.getStatus().pushError).toBeUndefined();
        expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');
        expect(await git.revparse('HEAD')).toBe(head);
      } finally {
        await engine.destroy();
      }
    },
  );

  test.each(['full', 'follow', 'off'] as const)(
    '%s keeps an up-to-date pull paused until Git is ready, then clears the pause',
    async (mode) => {
      const { engine, internals, git } = await setup(mode);
      const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
      writeFileSync(markerPath, await git.revparse('HEAD'));
      internals.pausedReason = 'git-operation-in-progress';
      internals.pushError = 'unrelated push failure';
      try {
        expect(await engine.pullOnce()).toBe('refused');
        expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
        expect(engine.getStatus().pullError).toBeUndefined();
        rmSync(markerPath);
        expect(await engine.pullOnce()).toBe('up-to-date');
        expect(engine.getStatus().pausedReason).toBeUndefined();
        expect(engine.getStatus().pushError).toBe('unrelated push failure');
        expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');
      } finally {
        await engine.destroy();
      }
    },
  );

  test.each(['full', 'off'] as const)(
    '%s preserves a newly discovered pull refusal through one-shot settlement',
    async (mode) => {
      const { engine, git, bareDir } = await setup(mode);
      await diverge(bareDir);
      const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
      const head = await git.revparse('HEAD');
      writeFileSync(markerPath, head);
      try {
        expect(await engine.pullOnce('sync')).toBe('refused');
        expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');
        expect(engine.getStatus().pullError).toBeUndefined();
        expect(engine.getStatus().pullErrorCode).toBeUndefined();
        expect(engine.getStatus().state).toBe(mode === 'off' ? 'disabled' : 'idle');
        expect(await git.revparse('HEAD')).toBe(head);
        expect(existsSync(markerPath)).toBe(true);
        expect(readFileSync(join(projectDir, 'README.md'), 'utf8')).toBe('ours\n');
      } finally {
        await engine.destroy();
      }
    },
  );

  test('the operation pause is neither written to the state file nor restored from it', async () => {
    const { engine, internals, git } = await setup('off');
    const markerPath = join(projectDir, '.git', 'CHERRY_PICK_HEAD');
    const statePath = join(okDir, 'sync-state.json');
    writeFileSync(markerPath, await git.revparse('HEAD'));
    try {
      await engine.pushOnce();
      expect(engine.getStatus().pausedReason).toBe('git-operation-in-progress');

      internals.saveStateNow();
      const persisted = JSON.parse(readFileSync(statePath, 'utf-8')) as { pausedReason?: string };
      expect(persisted.pausedReason).toBeUndefined();
    } finally {
      await engine.destroy();
    }

    rmSync(markerPath);
    writeFileSync(
      statePath,
      JSON.stringify({
        version: 1,
        lastSyncUtc: null,
        lastFetchUtc: null,
        lastPushedSha: null,
        consecutiveFailures: 0,
        pausedReason: 'git-operation-in-progress',
        inflightConflicts: [],
      }),
      'utf-8',
    );

    const restarted = new SyncEngine({
      conflicts: newAuthority(),
      projectDir,
      contentDir: projectDir,
      contentFilter: stubContentFilter,
      mode: 'off',
    });
    try {
      await restarted.start();
      expect(restarted.getStatus().pausedReason).toBeUndefined();
    } finally {
      await restarted.destroy();
    }
  });

  test('a successful safety probe preserves an unrelated pause reason', async () => {
    const { engine, internals } = await setup();
    internals.pausedReason = 'diverged-local-commits';
    try {
      await engine.pushOnce();
      expect(engine.getStatus().pausedReason).toBe('diverged-local-commits');
    } finally {
      await engine.destroy();
    }
  });

  test('an operation refusal preserves tracked-conflict guidance', async () => {
    const { engine, internals, git, conflicts } = await setup();
    internals.state = 'conflict';
    conflicts.raise({ kind: 'merge-native', file: 'README.md' });
    internals.pullError = 'existing conflict guidance';
    internals.pausedReason = 'non-content-merge-failure';
    writeFileSync(join(projectDir, '.git', 'CHERRY_PICK_HEAD'), await git.revparse('HEAD'));
    try {
      await internals.doPushCycle();
      expect(engine.getStatus()).toMatchObject({
        state: 'conflict',
        conflictCount: 1,
        pausedReason: 'non-content-merge-failure',
        pullError: 'existing conflict guidance',
      });
      expect(engine.getStatus().pushError).toBeUndefined();
    } finally {
      await engine.destroy();
    }
  });

  test('a dirty-tree error preserves the conflict state and does not schedule autosave', async () => {
    const { engine, internals, conflicts } = await setup();
    internals.state = 'conflict';
    conflicts.raise({ kind: 'merge-native', file: 'README.md' });
    try {
      internals.handleError(
        classifyGitError(
          new Error('Your local changes to the following files would be overwritten by merge'),
        ),
        'pull',
      );
      expect(engine.getStatus().state).toBe('conflict');
      expect(internals.conflictCount).toBe(1);
      expect(internals.pushTimer).toBeNull();
    } finally {
      await engine.destroy();
    }
  });
});