import type { NoteSections } from './note-sections.ts';
import type { ReviewSnapshot } from './ai-review.ts';
import { markedPage } from './note-pages.ts';
import type { Project as BuildProject } from '../../engine/src/core/config.ts';
import type { BuildInfo } from '../../engine/src/types.ts';
import { ReviewSnapshots } from './review-snapshot.ts';
import { execFile } from 'node:child_process';
import { createHash, randomUUID } from 'node:crypto';
import { EventEmitter } from 'node:events';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { promisify } from 'node:util';
import { pathToFileURL } from 'node:url';
import { ENGINE, ROOT } from './paths.ts';
import { stateDir } from './state.ts';
import type { Annotation, BuildProblem, BuildProgress, BuildRepairResult, GitDiffScope, GitFile, GitStatus, ManuscriptBuild, ManuscriptProblems } from '../shared.ts';
import { ignorePattern } from '../commit.ts';
import { PdfReader } from './pdf-reader.ts';
import { annotatePdf, type ExportNote } from './annotated-pdf.ts';
import { collectProblems, countProblems, locateProblems, scrubLog, sortProblems, syncView, type StoredProblem } from './build-problems.ts';
import { parseLatexRepair } from './latex-repair.ts';
// Where a note comes from in the source, worked out in the PDF reader's worker.
export { anchor, followLines, parseSynctex, settleLines, sourceExcerpt, type Anchor } from './note-location.ts';

type Rect = [number, number, number, number];

const exec = promisify(execFile);
async function git(root: string, args: string[], env: NodeJS.ProcessEnv = {}) {
  return (await exec('git', args, { cwd: root, timeout: 30_000, env: { ...process.env, ...env }, maxBuffer: 64 * 1024 * 1024 })).stdout;
}

// Porcelain v2 keeps paths with spaces intact under -z and reports branch,
// upstream and ahead/behind counts without a second command.
export function parseStatus(output: string, numstat: string): Omit<GitStatus, 'head'> {
  const lines = new Map<string, [number, number]>();
  const stats = numstat.split('\0');
  for (let i = 0; i < stats.length; i++) {
    const [added, deleted, file] = stats[i].split('\t');
    if (!added) continue;
    // A rename lists an empty path followed by the old and new paths.
    const target = file || (i += 2, stats[i]);
    if (target && added !== '-') lines.set(target, [Number(added), Number(deleted)]);
  }
  const status: Omit<GitStatus, 'head'> = { branch: null, upstream: null, ahead: 0, behind: 0, files: [] };
  const fields = output.split('\0');
  for (let i = 0; i < fields.length; i++) {
    const field = fields[i];
    if (field.startsWith('# branch.head ')) status.branch = field.slice(14) === '(detached)' ? null : field.slice(14);
    else if (field.startsWith('# branch.upstream ')) status.upstream = field.slice(18);
    else if (field.startsWith('# branch.ab ')) { const [ahead, behind] = field.slice(12).split(' '); status.ahead = Number(ahead); status.behind = -Number(behind); }
    else if (field.startsWith('? ')) status.files.push({ path: field.slice(2), status: '?', staged: false, unstaged: true });
    else if (/^[12u] /.test(field)) {
      const parts = field.split(' '), xy = parts[1], kind = field[0];
      const file = parts.slice(kind === '1' ? 8 : kind === '2' ? 9 : 10).join(' ');
      // A rename or copy is followed by its original path.
      const from = kind === '2' ? fields[++i] : undefined;
      const code = kind === 'u' ? 'U' : xy[1] !== '.' ? xy[1] : xy[0];
      // X is the index against HEAD, Y the working tree against the index. The
      // staged list shows X where it differs, such as a new file edited again.
      status.files.push({ path: file, status: code, staged: xy[0] !== '.', unstaged: xy[1] !== '.', lines: lines.get(file), ...(from ? { from } : {}), ...(xy[0] !== '.' && xy[0] !== code ? { index: xy[0] } : {}) });
    }
  }
  return status;
}

export async function gitStatus(root: string): Promise<GitStatus> {
  const [status, numstat, head, remotes] = await Promise.all([
    git(root, ['status', '--porcelain=v2', '--branch', '-z', '--untracked-files=all'], { GIT_OPTIONAL_LOCKS: '0' }),
    git(root, ['diff', '--numstat', '-z', 'HEAD']).catch(() => ''),
    git(root, ['log', '-1', '--format=%h%x00%s%x00%ct']).catch(() => ''),
    git(root, ['remote']).catch(() => ''),
  ]);
  const [hash, subject, time] = head.trim().split('\0');
  const parsed = parseStatus(status, numstat), dir = gitDir(root);
  // Incoming decorations describe the remote side since the common ancestor,
  // not HEAD versus upstream (which would also include local-only commits).
  // Read cached tracking refs only; fetching remains an explicit operation.
  if (parsed.upstream && parsed.behind > 0 && parsed.files.length) {
    const changes = (await git(root, ['diff', '--name-status', '-z', '--find-renames', 'HEAD...@{upstream}', '--']).catch(() => '')).split('\0');
    const incoming = new Map<string, string>();
    for (let i = 0; i + 1 < changes.length;) {
      const status = changes[i++][0], file = changes[i++];
      if (!status || !file) continue;
      incoming.set(file, status);
      if (status === 'R' || status === 'C') { const destination = changes[i++]; if (destination) incoming.set(destination, status); }
    }
    for (const file of parsed.files) {
      const status = incoming.get(file.path) || (file.from && incoming.get(file.from));
      if (status) file.incoming = status;
    }
  }
  // A merge in progress names the files whose conflict markers remain.
  const mergeHead = dir && readText(path.join(dir, 'MERGE_HEAD')).trim();
  const merging = mergeHead && dir
    ? { head: mergeHead, message: readText(path.join(dir, 'MERGE_MSG')).split('\n')[0] || 'Merge', conflicts: parsed.files.filter(file => file.status === 'U' && conflictMarkers(root, file.path)).map(file => file.path) }
    : null;
  return { ...parsed, head: hash ? { hash, subject, date: Number(time) * 1000 } : null, remote: Boolean(remotes.trim()), merging };
}
const readText = (file: string) => { try { return fs.readFileSync(file, 'utf8'); } catch { return ''; } };
// The repository's Git directory: .git, or where a .git file points.
function gitDir(root: string) {
  try {
    const dot = path.join(root, '.git');
    return fs.statSync(dot).isFile() ? path.resolve(root, readText(dot).replace(/^gitdir:\s*/, '').trim()) : dot;
  } catch { return null; }
}
// Cheap evidence that Git's own state moved: the index, HEAD, the current
// branch, a fetch or a merge. Each changes when a commit, stage, checkout,
// fetch or merge happens, from Papilot or from a terminal.
export function gitStamp(root: string) {
  const dir = gitDir(root);
  if (!dir) return '';
  const common = path.resolve(dir, readText(path.join(dir, 'commondir')).trim() || '.');
  const branch = readText(path.join(dir, 'HEAD')).match(/^ref: (refs\/\S+)/)?.[1];
  // FETCH_HEAD belongs to the worktree that fetched, so a linked worktree checks
  // its own and the main one's.
  return [path.join(dir, 'index'), path.join(dir, 'HEAD'), path.join(dir, 'MERGE_HEAD'), path.join(dir, 'FETCH_HEAD'), common !== dir && path.join(common, 'FETCH_HEAD'), path.join(common, 'packed-refs'), branch && path.join(common, branch)]
    .map(file => { try { const stat = file && fs.statSync(file); return stat ? `${stat.mtimeMs}:${stat.size}` : '-'; } catch { return '-'; } }).join('|');
}
export function mergeInProgress(root: string) {
  const dir = gitDir(root);
  return Boolean(dir && fs.existsSync(path.join(dir, 'MERGE_HEAD')));
}
export const conflictMarkers = (root: string, file: string) => /^(?:<{7}|>{7})(?: |$)/m.test(readText(path.join(root, file)));

// Paths from the browser are matched against the changed files, and Git reads
// them literally, so a name cannot act as a pathspec pattern.
const literal = { GIT_LITERAL_PATHSPECS: '1' };
const DIFF_LIMIT = 400_000;

// One changed file's diff against HEAD; an untracked file shows as all new.
export async function gitDiff(root: string, file: string, scope: GitDiffScope = 'all') {
  const entry = (await gitStatus(root)).files.find(item => item.path === file);
  if (!entry || (scope === 'staged' && !entry.staged) || (scope === 'unstaged' && !entry.unstaged)) throw Object.assign(new Error('That file has no uncommitted changes.'), { statusCode: 404 });
  const diff = await fileDiff(root, entry, scope);
  return { path: file, diff: diff.slice(0, DIFF_LIMIT), truncated: diff.length > DIFF_LIMIT };
}
// A file's diff against HEAD, or with staged, what its index holds.
function fileDiff(root: string, entry: GitFile, scope: GitDiffScope = 'all') {
  const names = ['--', ...(entry.from ? [entry.from] : []), entry.path];
  // An unmerged index has multiple stages, not a single staged version.
  // Compare the working file with HEAD so conflict markers and both sides
  // reach the two-column viewer as an ordinary diff, rather than diff --cc.
  if (entry.status === 'U') return git(root, ['diff', '--no-color', '--no-ext-diff', '--no-textconv', 'HEAD', ...names], literal);
  if (scope === 'staged') return git(root, ['diff', '--cached', '--no-color', '--find-renames', ...names], literal);
  return entry.status === '?'
    // `git diff --no-index` exits with 1 when the files differ.
    ? exec('git', ['diff', '--no-index', '--no-color', '--', '/dev/null', entry.path], { cwd: root, maxBuffer: 64 * 1024 * 1024 }).then(r => r.stdout, (e: { stdout?: string }) => e.stdout || '')
    : git(root, ['diff', '--no-color', '--find-renames', ...(scope === 'all' ? ['HEAD'] : []), ...names], literal);
}

// What a commit message is written from: the chosen files' diffs, or what is
// staged in them, and the
// repository's recent commit subjects, whose style and language the message follows.
export async function commitChanges(root: string, paths: string[], staged = false) {
  const files = (await gitStatus(root)).files.filter(item => paths.includes(item.path) && (!staged || item.staged));
  if (!files.length) throw new Error(staged ? 'Stage at least one change.' : 'Select at least one changed file.');
  let patch = '';
  for (const file of files) patch += await fileDiff(root, file, staged ? 'staged' : 'all');
  return { files, patch, recent: await recentCommitSubjects(root) };
}

export async function recentCommitSubjects(root: string) {
  return (await git(root, ['log', '-8', '--format=%s']).catch(() => '')).split('\n').filter(Boolean);
}

// Adds the patterns for the chosen untracked build files to the repository's
// .gitignore, one per kind of file and each only once, so they leave the list
// of changes. The .gitignore is then a change to commit like any other.
export async function gitIgnore(root: string, paths: string[]) {
  const patterns = [...new Set((await gitStatus(root)).files.filter(item => item.status === '?' && paths.includes(item.path)).map(item => ignorePattern(item.path)).filter((pattern): pattern is string => Boolean(pattern)))];
  if (!patterns.length) throw new Error('None of the chosen files is build output that can be ignored.');
  const file = path.join(root, '.gitignore');
  const current = fs.existsSync(file) ? fs.readFileSync(file, 'utf8') : '';
  const present = new Set(current.split(/\r?\n/).map(line => line.trim()));
  const missing = patterns.filter(pattern => !present.has(pattern) && !present.has('/' + pattern));
  if (missing.length) fs.writeFileSync(file, `${current}${current && !current.endsWith('\n') ? '\n' : ''}${current.trim() ? '\n' : ''}# Build output\n${missing.join('\n')}\n`);
  return gitStatus(root);
}

// Stage or unstage whole files, as the Git panel's checkboxes do. A rename
// moves with both of its paths.
export async function gitStage(root: string, paths: string[], stage: boolean) {
  const status = await gitStatus(root), files = status.files.filter(item => paths.includes(item.path));
  if (status.merging) throw new Error('Finish or abort the merge before staging other changes.');
  if (!files.length) throw new Error('Select at least one changed file.');
  const names = [...new Set(files.flatMap(item => item.from ? [item.from, item.path] : [item.path]))];
  if (stage) await gitAction(root, ['add', '-A', '--', ...names]);
  else await gitAction(root, status.head ? ['reset', '-q', 'HEAD', '--', ...names] : ['rm', '-r', '-q', '--cached', '--ignore-unmatch', '--', ...names]);
  return gitStatus(root);
}

// Discard what the Changes list shows for these files, as an editor's source
// control does: a tracked file returns to its staged version, or the last
// commit, and an untracked file is deleted. Staged changes stay.
export async function gitDiscard(root: string, paths: string[]) {
  const status = await gitStatus(root);
  if (status.merging) throw new Error('Finish or abort the merge before discarding changes.');
  const files = status.files.filter(item => paths.includes(item.path) && item.unstaged);
  if (!files.length) throw new Error('Select at least one changed file.');
  const tracked = files.filter(item => item.status !== '?').map(item => item.path);
  if (tracked.length) await gitAction(root, ['-c', 'core.autocrlf=false', 'checkout', '--', ...tracked]);
  for (const item of files.filter(item => item.status === '?')) {
    const file = path.resolve(root, item.path);
    if (!file.startsWith(root + path.sep)) throw new Error('Invalid file path.');
    fs.rmSync(file, { force: true });
  }
  return gitStatus(root);
}

// Commit what is staged, or with paths, exactly those files as they are on
// disk; changes staged for other files then stay staged and out of the commit.
export async function gitCommit(root: string, message: string, paths: string[] | null, amend = false) {
  const status = await gitStatus(root);
  if (status.merging) throw new Error('Finish or abort the merge before committing other changes.');
  if (amend && !status.head) throw new Error('There is no commit to amend.');
  const options = amend ? ['--amend'] : [];
  if (!paths) {
    if (!status.files.some(item => item.staged)) throw new Error('Stage at least one change to commit.');
    await gitAction(root, ['commit', ...options, '-m', message]);
    return (await git(root, ['rev-parse', '--short', 'HEAD'])).trim();
  }
  const files = status.files.filter(item => paths.includes(item.path));
  if (!files.length) throw new Error('Select at least one changed file to commit.');
  if (files.some(item => item.status === 'U')) throw new Error('Resolve the merge conflicts in the selected files before committing.');
  // A rename is already staged, so only its new path is added; the commit
  // names the old path too, so the removal is part of it.
  await gitAction(root, ['add', '-A', '--', ...files.map(item => item.path)]);
  await gitAction(root, ['commit', ...options, '--only', '-m', message, '--', ...new Set(files.flatMap(item => item.from ? [item.from, item.path] : [item.path]))]);
  return (await git(root, ['rev-parse', '--short', 'HEAD'])).trim();
}

// Fetch, fast-forward pull and push use the host's Git credentials. Nothing
// may prompt, so a missing credential fails instead of hanging.
const fetching = new Map<string, Promise<unknown>>();
export async function gitRemote(root: string, action: 'fetch' | 'pull' | 'merge' | 'push') {
  const status = await gitStatus(root);
  if (!status.remote) throw new Error('This repository has no remote.');
  if (status.merging && action !== 'fetch') throw new Error('Finish or abort the merge first.');
  if (action === 'fetch') {
    // Fetch updates objects and remote refs, not the index or working files.
    // Share an in-flight fetch across panels/listeners without locking edits.
    const key = fs.realpathSync(root);
    let pending = fetching.get(key);
    if (!pending) {
      pending = gitAction(root, ['fetch', '--prune'], 120_000).finally(() => { if (fetching.get(key) === pending) fetching.delete(key); });
      fetching.set(key, pending);
    }
    await pending;
  }
  else if (action === 'pull' || action === 'merge') {
    if (!status.upstream) throw new Error('This branch does not track a remote branch yet.');
    // Pull only fast-forwards. Merge also joins a branch that has diverged
    // from its upstream; conflicts leave the merge in progress to resolve.
    // A host's merge.autoStash setting must not hide the author's pending edits.
    if (action === 'pull') await gitAction(root, ['-c', 'core.autocrlf=false', 'pull', '--ff-only', '--no-autostash'], 120_000);
    else await gitAction(root, ['-c', 'core.autocrlf=false', 'pull', '--no-rebase', '--ff', '--no-edit', '--no-autostash'], 120_000).catch(error => { if (!mergeInProgress(root)) throw error; });
  } else if (status.upstream) await gitAction(root, ['push'], 120_000);
  else {
    if (!status.branch) throw new Error('Check out a branch before pushing.');
    const remotes = (await git(root, ['remote'])).split('\n').filter(Boolean);
    await gitAction(root, ['push', '-u', remotes.includes('origin') ? 'origin' : remotes[0], status.branch], 120_000);
  }
}

// Sync committed history only. Fetch before deciding how to integrate the
// upstream; Git protects local edits, and conflicts stop before any push.
// Do not stash, reset or create a commit from the user's pending edits.
export async function gitSync(root: string): Promise<GitStatus> {
  const initial = await gitStatus(root);
  if (!initial.branch) throw new Error('Check out a branch before syncing.');
  if (initial.merging) throw new Error('Finish or abort the merge first.');
  await gitRemote(root, 'fetch');
  let status = await gitStatus(root);
  if (status.upstream && status.behind > 0) {
    await gitRemote(root, status.ahead > 0 ? 'merge' : 'pull');
    status = await gitStatus(root);
    if (status.merging) return status;
  }
  // A newly cloned empty remote may have a configured upstream but no ref
  // (and therefore no ahead count). Push also creates that first remote ref.
  await gitRemote(root, 'push');
  return gitStatus(root);
}

// A merge in progress ends with its commit once no conflict markers remain,
// or is abandoned, restoring the files as they were before it.
export async function gitFinishMerge(root: string) {
  const status = await gitStatus(root);
  if (!status.merging) throw new Error('No merge is in progress.');
  if (status.merging.conflicts.length) throw new Error(`Resolve the conflicts in ${status.merging.conflicts.join(', ')} first.`);
  const resolved = status.files.filter(item => item.status === 'U').map(item => item.path);
  if (resolved.length) await gitAction(root, ['add', '-A', '--', ...resolved]);
  await gitAction(root, ['commit', '--no-edit']);
  return (await git(root, ['rev-parse', '--short', 'HEAD'])).trim();
}
export async function gitAbortMerge(root: string) {
  if (!mergeInProgress(root)) throw new Error('No merge is in progress.');
  await gitAction(root, ['-c', 'core.autocrlf=false', 'merge', '--abort']);
}
// What an agent needs to resolve a merge's conflicts: the files with markers
// and the commits on each side.
export async function mergeConflicts(root: string) {
  const status = await gitStatus(root);
  if (!status.merging) throw new Error('No merge is in progress.');
  const subjects = async (range: string) => (await git(root, ['log', '-12', '--format=%s', range]).catch(() => '')).split('\n').filter(Boolean);
  return { files: status.merging.conflicts, branch: status.branch || 'HEAD', upstream: status.upstream || 'the remote branch', ours: await subjects('MERGE_HEAD..HEAD'), theirs: await subjects('HEAD..MERGE_HEAD') };
}

// Git's own message, without the usage noise, becomes the error the user sees.
async function gitAction(root: string, args: string[], timeout = 60_000) {
  try { return (await exec('git', args, { cwd: root, timeout, env: { ...process.env, ...literal, GIT_TERMINAL_PROMPT: '0' }, maxBuffer: 64 * 1024 * 1024 })).stdout; }
  catch (error) {
    const e = error as { stderr?: string; stdout?: string; killed?: boolean; message: string };
    const detail = (e.stderr || e.stdout || '').split('\n').map(line => line.trim()).filter(line => line && !/^(hint|To |From ):?/.test(line)).slice(-4).join(' ');
    throw new Error(e.killed ? `git ${args[0]} timed out.` : detail || e.message);
  }
}

// The preview shows the manuscript as it is on disk, including accepted but
// uncommitted review changes. A private index records it as a Git tree
// without touching the real index, branches or files. It starts from the
// previous snapshot's index, or the repository's, so Git rehashes only files
// whose size or modification time changed.
export async function workingTree(root: string) {
  const dir = gitDir(root), saved = dir && path.join(await stateDir(dir), 'working-index');
  const folder = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'papilot-index-')), index = path.join(folder, 'index'), env = { GIT_INDEX_FILE: index };
  const snapshot = async (seed: string | null | undefined) => {
    if (!seed || !await copyIndex(seed, index)) { await fs.promises.rm(index, { force: true }); await git(root, ['read-tree', 'HEAD'], env).catch(() => git(root, ['read-tree', '--empty'], env)); }
    await git(root, ['add', '-A'], env);
    return (await git(root, ['write-tree'], env)).trim();
  };
  try {
    let tree: string;
    try { tree = await snapshot(saved && fs.existsSync(saved) ? saved : dir && path.join(dir, 'index')); }
    catch { tree = await snapshot(null); }
    if (saved) {
      const temporary = `${saved}.${randomUUID()}.tmp`;
      try {
        await fs.promises.mkdir(path.dirname(saved), { recursive: true });
        if (await copyIndex(index, temporary)) await fs.promises.rename(temporary, saved);
      } catch { /* The next snapshot rehashes more files. */ }
      finally { await fs.promises.rm(temporary, { force: true }); }
    }
    return tree;
  } finally { await fs.promises.rm(folder, { recursive: true, force: true }); }
}
// Copies an index and keeps its modification time, which Git compares with
// each file's to catch edits made in the instant the index was written.
async function copyIndex(from: string, to: string) {
  try {
    const stat = await fs.promises.stat(from);
    await fs.promises.copyFile(from, to);
    await fs.promises.utimes(to, stat.atime, stat.mtime);
    return true;
  } catch { return false; }
}


// Each page's size in points. A long paper takes tens of milliseconds, so
// the event loop answers other requests every few pages.
async function pageSizes(mupdf: any, pdf: string) {
  const document = mupdf.Document.openDocument(await fs.promises.readFile(pdf), 'application/pdf'), pages: [number, number][] = [];
  try {
    for (let i = 0; i < document.countPages(); i++) {
      if (i && i % 32 === 0) await new Promise(resolve => setImmediate(resolve));
      const page = document.loadPage(i);
      try { const [x0, y0, x1, y1] = page.getBounds(); pages.push([Math.round(x1 - x0), Math.round(y1 - y0)]); }
      finally { page.destroy(); }
    }
  } finally { document.destroy(); }
  return pages;
}

async function engine() {
  const [{ Builder, BuildError, reprioritize }, { Repo, gitBinary }, config, { mupdf, PdfDocument, containsCenter, walkText }] = await Promise.all([
    import(pathToFileURL(path.join(ENGINE, 'src/core/build.ts')).href) as Promise<typeof import('../../engine/src/core/build.ts')>,
    import(pathToFileURL(path.join(ENGINE, 'src/core/git.ts')).href) as Promise<typeof import('../../engine/src/core/git.ts')>,
    import(pathToFileURL(path.join(ENGINE, 'src/core/config.ts')).href) as Promise<typeof import('../../engine/src/core/config.ts')>,
    import(pathToFileURL(path.join(ENGINE, 'src/render/pdf.ts')).href),
  ]);
  return { config, loadProject: config.loadProject, Builder, BuildError, reprioritize, Repo, gitBinary, mupdf, PdfDocument, containsCenter, walkText };
}

// Every word on a page with its exact place, for the PDF view's selection
// layer: [text, left, baseline, font size, width, ends a line], in points from
// the page's top left. pdf.js lays a whole line out in a stand-in font and
// drifts from the printed words mid-line; per-word runs cannot drift.
export async function pdfWords(pdf: string, page: number) {
  const { PdfDocument, walkText } = await engine();
  const document = new PdfDocument(pdf);
  try {
    if (!Number.isInteger(page) || page < 0 || page >= document.length) throw Object.assign(new Error('That page is not part of the manuscript.'), { statusCode: 400 });
    const raw = document.raw.loadPage(page), [x0, y0, x1, y1] = raw.getBounds();
    const words: { text: string; left: number; right: number; baseline: number; size: number; eol: boolean }[] = [];
    let word: (typeof words)[number] | null = null;
    const text = raw.toStructuredText('preserve-whitespace');
    walkText(text, {
      beginLine: () => { word = null; },
      onChar: (c: string, origin: [number, number], _font: unknown, size: number, quad: number[]) => {
        if (/\s/u.test(c)) { word = null; return; }
        const left = Math.min(quad[0], quad[2], quad[4], quad[6]) - x0, right = Math.max(quad[0], quad[2], quad[4], quad[6]) - x0;
        if (!word) { word = { text: '', left, right, baseline: origin[1] - y0, size, eol: false }; words.push(word); }
        word.text += c; word.right = Math.max(word.right, right);
      },
      endLine: () => { if (words.length) words[words.length - 1].eol = true; },
    });
    text.destroy(); raw.destroy();
    const round = (value: number) => Math.round(value * 100) / 100;
    return { width: round(x1 - x0), height: round(y1 - y0), words: words.map(w => [w.text, round(w.left), round(w.baseline), round(w.size), round(w.right - w.left), w.eol ? 1 : 0] as [string, number, number, number, number, number]) };
  } finally { document.close(); }
}

function unexplainedErrors(details: string[], problems: StoredProblem[]) {
  const plain = (text: string) => text.replace(/\s+/g, ' ').trim();
  return details.filter(line => line.trim() && !/==> Fatal error occurred|^Emergency stop/.test(line) && !problems.some(problem => plain(line).includes(plain(problem.message).replace(/^[^:]+:\d+: /, ''))));
}

// `problems` come from the last finished build. They are placed on the PDF
// named `problemsKey`; a failed build has no PDF of its own to place them on.
interface Build {
  tree: string; status: ManuscriptBuild['status']; key?: string; pdf?: string; root?: string; sourceDir?: string; pages?: [number, number][]; builtAt?: number; error?: string; progress?: BuildProgress;
  problems?: StoredProblem[]; problemsKey?: string; log?: string; logFolder?: string; previewOnly?: () => boolean;
  failureId?: string; failedProject?: BuildProject;
  // Stops the compilation when the paper compiles another document instead.
  stop?: AbortController;
}



export class Manuscripts extends EventEmitter {
  private reviewSnapshots = new ReviewSnapshots();
  // Notes are located and placed on PDFs off the event loop.
  private pdfReader = new PdfReader();
  private builds = new Map<string, Build>();
  private repairs = new WeakMap<Build, Promise<BuildRepairResult>>();
  // When each paper's view last asked for its manuscript: the build of a
  // manuscript on screen compiles in the foreground, others behind it.
  private viewed = new Map<string, number>();
  private oldPdfs = new Map<string, string | null>();
  // Every PDF the view may still be showing, by paper and key: each pass and
  // each finished build. The author marks the pages on screen, which a newer
  // pass may already have replaced; reading words, locating and exporting on
  // those pages must still work. Builds keep their folders (and SyncTeX) until
  // the cache is pruned days later.
  private shown = new Map<string, { pdf: string; root?: string; sourceDir?: string; document?: string }>();
  // The root document each paper compiles, as its latest build found it.
  private documents = new Map<string, string>();
  // Each paper's working tree, where located lines are followed to.
  private roots = new Map<string, string>();
  private placements = new Map<string, (Pick<Annotation, 'key' | 'page' | 'rect' | 'rects' | 'source'>) | null>();
  // Placed problems per problem list; a rebuild in progress shares its predecessor's list.
  private located = new WeakMap<StoredProblem[], Promise<BuildProblem[]>>();
  // Papers whose working tree changed while their manuscript compiled: they
  // compile again as soon as that build ends.
  private stale = new Set<string>();
  // One working-tree snapshot per paper at a time; a request made meanwhile
  // waits for the next one, which sees every edit made before it was asked.
  private snapshots = new Map<string, { current: Promise<string>; next?: Promise<string> }>();
  // Per paper, the speculative build that is running and the one wanted next.
  // The manuscript as applying a task would write it, compiling: a newer
  // prediction cancels it.
  private speculation = new Map<string, AbortController>();
  // Every open event stream listens for builds.
  constructor() { super(); this.setMaxListeners(0); }
  /** Stops every compiler this process started, also paused ones, so that
   *  nothing keeps running after Papilot quits. */
  async stop() {
    const stopping = Promise.all([this.reviewSnapshots.stop(), this.pdfReader.stop()]);
    const { stopAll } = await import(pathToFileURL(path.join(ENGINE, 'src/core/process.ts')).href);
    stopAll();
    await stopping;
  }
  /** Loads the PDF engine and reads Papilot's example paper with it once,
   *  before the server answers requests: compiling its WebAssembly and
   *  setting up color conversion take a few hundred milliseconds the first
   *  time, which would otherwise hold up the first PDF someone opens. */
  async warm() {
    try {
      const { PdfDocument, gitBinary } = await engine(), sample = path.join(ROOT, 'examples/papilot-paper/preview/main.pdf');
      gitBinary();
      if (!fs.existsSync(sample)) return;
      const document = new PdfDocument(sample);
      try { document.page(0); } finally { document.close(); }
    } catch { /* The first build pays for it instead. */ }
  }
  get busyForUpdate() { return this.reviewSnapshots.busy || [...this.builds.values()].some(build => build.status === 'building'); }
  busyForProject(id: string) { return this.builds.get(id)?.status === 'building'; }
  forgetProject(id: string) { this.builds.get(id)?.stop?.abort(); this.builds.delete(id); this.documents.delete(id); this.stale.delete(id); this.speculation.get(id)?.abort(); this.speculation.delete(id); }

  // The caller verifies the example's source tree. An edit or explicit rebuild
  // uses Builder; the original PDF can be read before TeX is installed.
  async seedPreview(projectId: string, root: string, tree: string, pdf: string, previewOnly?: () => boolean) {
    const { mupdf } = await engine(), key = await this.rememberPreview(root, tree, pdf), pages = await pageSizes(mupdf, pdf);
    this.builds.set(projectId, { tree, status: 'ready', key, pdf, root, sourceDir: '', pages, previewOnly,
      builtAt: (await fs.promises.stat(pdf)).mtimeMs, problems: [], problemsKey: key });
    // Not remembered with the builds: once released, edited sources must not
    // be paired with the bundled preview.
    this.roots.set(projectId, root);
  }

  private remember(projectId: string, key: string, pdf: string, root?: string, sourceDir?: string, document?: string) {
    const id = `${projectId}:${key}`;
    this.shown.delete(id);
    this.shown.set(id, { pdf, root, sourceDir, document });
    if (this.shown.size > 200) this.shown.delete(this.shown.keys().next().value!);
  }

  private shownBuild(projectId: string, key: string) {
    const build = this.builds.get(projectId);
    if (build?.pdf && build.key === key) return { pdf: build.pdf, root: build.root, sourceDir: build.sourceDir };
    const shown = key ? this.shown.get(`${projectId}:${key}`) : undefined;
    return shown && fs.existsSync(shown.pdf) ? shown : null;
  }

  // Demo previews live outside the compiler cache. Register their persisted
  // identities on every startup so notes from before Git installation can
  // still be placed, even after the app has restarted or the paper was edited.
  async rememberPreview(root: string, tree: string, pdf: string) {
    const key = createHash('sha256').update(tree).update(await fs.promises.readFile(pdf)).digest('hex').slice(0, 16);
    this.oldPdfs.set(`${root}:${key}`, pdf);
    return key;
  }

  // Keep the original PDF addressable while notes move from the read-only
  // demo to its first Git-backed preview.
  releasePreview(projectId: string) {
    const build = this.builds.get(projectId);
    if (!build?.previewOnly) return;
    if (build.root && build.key && build.pdf) this.oldPdfs.set(`${build.root}:${build.key}`, build.pdf);
    this.builds.delete(projectId);
  }

  // The working tree as a Git tree. Requests made while a snapshot runs share
  // the next one, which starts when it ends and so sees every edit made
  // before they asked.
  private snapshot(root: string): Promise<string> {
    const entry = this.snapshots.get(root);
    if (entry) return entry.next ??= entry.current.then(() => undefined, () => undefined).then(() => this.takeSnapshot(root));
    return this.takeSnapshot(root);
  }
  private takeSnapshot(root: string) {
    const current = workingTree(root);
    this.snapshots.set(root, { current });
    void current.then(() => undefined, () => undefined).then(() => {
      const entry = this.snapshots.get(root);
      if (entry?.current === current && !entry.next) this.snapshots.delete(root);
    });
    return current;
  }

  // The view polls every second and a half while a build runs; Git's status
  // costs a walk of the working tree, which competes with TeX, so it is
  // read again at most every few seconds then, and after Papilot's own writes.
  // Between builds the view polls every five seconds to notice other editors:
  // the status is read again when the working tree or Git's own state moved,
  // and at least every half minute for what neither shows, such as a push
  // from a terminal changing how far the branch is ahead.
  private statuses = new Map<string, { at: number; value: Promise<GitStatus>; tree?: string; stamp?: string }>();
  private gitStatus(root: string, building: boolean, tree?: string) {
    const cached = this.statuses.get(root), age = cached ? Date.now() - cached.at : Infinity, stamp = building ? undefined : gitStamp(root);
    if (cached && (building ? age < 5000 : tree !== undefined && cached.tree === tree && cached.stamp === stamp && age < 30000)) return cached.value;
    const value = gitStatus(root);
    this.statuses.set(root, { at: Date.now(), value, tree, stamp });
    value.catch(() => { if (this.statuses.get(root)?.value === value) this.statuses.delete(root); });
    return value;
  }

  async state(projectId: string, root: string, rebuild = false): Promise<{ git: GitStatus; build: ManuscriptBuild }> {
    const current = this.builds.get(projectId), building = current?.status === 'building';
    this.viewed.set(projectId, Date.now());
    if (building) void engine().then(({ reprioritize }) => reprioritize()).catch(() => undefined);
    if (current?.previewOnly) {
      const matches = current.previewOnly();
      const error = rebuild || !matches ? 'Install Git to compile changes to the example paper.' : undefined;
      return { git: { branch: null, upstream: null, ahead: 0, behind: 0, files: [], head: null },
        build: { status: error ? 'failed' : 'ready', key: current.key, pages: current.pages, builtAt: current.builtAt, current: matches, error } };
    }
    // Polling an in-flight build needs its status, not another source snapshot.
    // Once it finishes, the next read checks for edits made during compilation.
    // The snapshot comes first so an unchanged tree can reuse the last status.
    const tree = building ? current.tree : await this.snapshot(root), status = await this.gitStatus(root, building, building ? undefined : tree);
    let build = this.builds.get(projectId);
    if (!build || (build.status !== 'building' && (build.tree !== tree || rebuild))) build = this.start(projectId, root, tree, build, rebuild);
    const { status: state, key, pages, builtAt, error, failureId } = build, document = key ? this.documentOf(projectId, key) : undefined;
    return { git: status, build: { status: state, key, ...(document ? { document } : {}), pages, builtAt, error, failureId, tree: build.tree, current: build.tree === tree && state === 'ready', problems: build.problems && countProblems(build.problems), ...(state === 'building' && build.progress ? { progress: build.progress } : {}) } };
  }

  /** Compiles the working tree if it changed, without waiting for anyone to
   *  look: after a commit, an applied task or a Git action, the PDF is on its
   *  way before the manuscript is opened. */
  async refresh(projectId: string, root: string) {
    this.statuses.delete(root);
    if (this.builds.get(projectId)?.status === 'building') { this.stale.add(projectId); return; }
    const tree = await this.snapshot(root), build = this.builds.get(projectId);
    if (build?.status === 'building') { if (build.tree !== tree) this.stale.add(projectId); return; }
    if (!build || build.tree !== tree) this.start(projectId, root, tree, build);
  }

  /** After Papilot itself wrote into the working tree: the tree it is now,
   *  compiling at once or as soon as the build in progress ends. The caller
   *  recognizes the build of its write by this tree. */
  async written(projectId: string, root: string) {
    this.statuses.delete(root);
    const tree = await this.snapshot(root), build = this.builds.get(projectId);
    if (build?.status === 'building') { if (build.tree !== tree) this.stale.add(projectId); }
    else if (!build || build.tree !== tree) this.start(projectId, root, tree, build);
    return tree;
  }

  /** Compiles in the background what the manuscript will be once the given
   *  files are written into the working tree, such as a reviewed task that is
   *  about to be applied. When that happens, the build of the working tree is
   *  the same build, so its PDF is ready or already on its way. A build
   *  someone waits for always runs first. */
  async predict(projectId: string, root: string, files: Record<string, Buffer | null>) {
    const previous = this.speculation.get(projectId), stop = new AbortController();
    this.speculation.set(projectId, stop);
    // The prediction it replaces stops once this one waits for its own build,
    // unless both need the same.
    const replace = () => previous?.abort();
    try {
      const { Builder, Repo, loadProject } = await engine(), repo = new Repo(root);
      const tree = await this.snapshot(root), predicted = await repo.treeWithAsync(tree, files);
      if (predicted === tree || stop.signal.aborted) return replace();
      await new Builder(loadProject(root), repo).build(predicted, ['full'], null, { priority: 'background', signal: stop.signal, onKey: replace });
    } catch {
      /* A build that fails here fails again, and is reported, when it is needed. */
      replace();
    } finally {
      if (this.speculation.get(projectId) === stop) this.speculation.delete(projectId);
    }
  }

  /** The root document the paper compiles, or undefined when it has none
   *  that compiles, such as a folder with several and none chosen. */
  async document(projectId: string, root: string) {
    const known = this.documents.get(projectId);
    if (known) return known;
    try { return (await engine()).loadProject(root).main as string; } catch { return undefined; }
  }
  /** The root document whose PDF `key` is, when this process knows it: a
   *  note can only be made on such a PDF, which is never guessed. */
  documentOf(projectId: string, key: string) {
    return this.shown.get(`${projectId}:${key}`)?.document;
  }
  /** The paper compiles another of its root documents now. The PDF on screen
   *  is not an earlier version of that one, so it does not stay while the
   *  new document compiles. */
  async documentChanged(projectId: string, root: string, document: string) {
    const tree = await this.snapshot(root), previous = this.builds.get(projectId);
    if (previous?.key && previous.pdf) this.oldPdfs.set(`${root}:${previous.key}`, previous.pdf);
    previous?.stop?.abort();
    // A speculative build of the document no longer compiled is not wanted either.
    this.speculation.get(projectId)?.abort(); this.speculation.delete(projectId);
    this.builds.delete(projectId);
    this.documents.set(projectId, document);
    this.emit('build-settings', projectId);
    this.start(projectId, root, tree);
  }

  // Keep the previous pages visible while a newer working tree compiles.
  private start(projectId: string, root: string, tree: string, previous?: Build, force = false, tested?: { project: BuildProject; result: BuildInfo; pages: [number, number][] }) {
    if (previous?.key && previous.pdf) this.oldPdfs.set(`${root}:${previous.key}`, previous.pdf);
    const build: Build = { tree, status: 'building', stop: new AbortController(), key: previous?.key, pdf: previous?.pdf, root: previous?.root, sourceDir: previous?.sourceDir, pages: previous?.pages, builtAt: previous?.builtAt, problems: previous?.problems, problemsKey: previous?.problemsKey, log: previous?.log, logFolder: previous?.logFolder };
    this.builds.set(projectId, build);
    this.roots.set(projectId, root);
    this.stale.delete(projectId);
    this.emit('change', projectId);
    void (async () => {
      let project: BuildProject | undefined;
      try {
        const { Builder, Repo, loadProject, mupdf } = await engine();
        project = tested?.project ?? loadProject(root);
        if (this.builds.get(projectId) === build) this.documents.set(projectId, project.main);
        const startedAt = Date.now();
        const sizes = (pdf: string) => pageSizes(mupdf, pdf);
        // A pass that latexmk follows with more work already shows the edit;
        // its pages replace the previous PDF while references settle.
        const pass = async (preview: { pdf: string; root: string }) => {
          if (this.builds.get(projectId) !== build || build.status !== 'building') return;
          const pages = await sizes(preview.pdf), key = createHash('sha256').update(preview.pdf).digest('hex').slice(0, 16);
          if (this.builds.get(projectId) !== build || build.status !== 'building') return;
          this.oldPdfs.set(`${root}:${key}`, preview.pdf);
          this.remember(projectId, key, preview.pdf, preview.root, project!.source_dir || '', project!.main);
          Object.assign(build, { key, pdf: preview.pdf, root: preview.root, sourceDir: project!.source_dir || '', pages, builtAt: Date.now() });
          this.emit('change', projectId);
        };
        const result = tested?.result ?? await new Builder(project, new Repo(root)).build(tree, ['full'], null, { force, signal: build.stop!.signal, priority: () => Date.now() - (this.viewed.get(projectId) ?? 0) < 15000 ? 'foreground' : 'normal', pass: (preview: { pdf: string; root: string }) => void pass(preview).catch(() => undefined), progress: (progress: Omit<BuildProgress, 'startedAt'>) => { if (this.builds.get(projectId) === build) build.progress = { ...progress, startedAt }; } });
        const pages = tested?.pages ?? await sizes(result.pdf);
        const key = createHash('sha256').update(result.key + result.pdf).digest('hex').slice(0, 16);
        this.remember(projectId, key, result.pdf, result.root, project!.source_dir || '', project!.main);
        if (this.builds.get(projectId) !== build) return;
        const log = String(result.pdf).replace(/\.pdf$/, '.log');
        let problems: StoredProblem[] = [];
        try { problems = collectProblems(await fs.promises.readFile(log), { cwd: result.cwd, root: result.root, sourceDir: project!.source_dir || '', outDir: path.dirname(result.pdf) }); } catch { /* A build without a readable log reports no problems. */ }
        problems.push(...unexplainedErrors(result.errors || [], problems).map((message): StoredProblem => ({ kind: 'error', severity: 'error', message: scrubLog(message, path.dirname(result.root)) })));
        Object.assign(build, { status: 'ready', key, pdf: result.pdf, root: result.root, sourceDir: project!.source_dir || '', pages, builtAt: Date.now(), error: undefined, problems, problemsKey: key, log: fs.existsSync(log) ? log : undefined, logFolder: path.dirname(result.root) });
        // Place the problems now, so the list is ready when someone opens it.
        if (problems.length) void this.problems(projectId).catch(() => undefined);
      } catch (error) {
        if (this.builds.get(projectId) !== build) return;
        const detail = error as { message?: string; details?: string[]; log?: string };
        const message = [detail.message, ...(detail.details || [])].filter(Boolean).join('\n') || 'The manuscript could not be compiled.';
        // The engine keeps latexmk's transcript and the TeX log of a failed
        // build; its sources are gone, so files resolve in the working tree.
        let problems: StoredProblem[] = [];
        if (detail.log && project) try {
          const kept = await fs.promises.readFile(detail.log), marker = Buffer.from('\n\n--- TeX log ---\n'), at = kept.indexOf(marker);
          // TeX stopped in its first pass, before references resolve, so only
          // the errors of a failed run mean anything.
          if (at >= 0) problems = collectProblems(kept.subarray(at + marker.length), { cwd: path.join(root, project.doc_dir || '.'), root: path.join(root, project.source_dir || '.'), sourceDir: project.source_dir || '' })
            .filter(problem => problem.severity === 'error').map(({ source: _source, ...problem }) => problem);
        } catch { /* Fall back to the compiler's own message below. */ }
        // BibTeX, Biber, latexmk and helper programs fail outside the TeX log;
        // whatever the compiler said that the parsed errors do not cover stays.
        const unexplained = unexplainedErrors(detail.details || [], problems);
        const logFolder = detail.log && project ? path.join(project.state, 'cache/builds', path.basename(detail.log, '.log')) : undefined;
        if (!problems.length || unexplained.length) problems.push({ kind: 'error', severity: 'error', message: scrubLog([...(problems.length ? [] : [detail.message || 'The manuscript could not be compiled.']), ...unexplained].join('\n'), logFolder) });
        // The previous PDF stays on screen, and so do its warnings and places;
        // a pass of this build that was shown went with its folder.
        Object.assign(build, { key: previous?.key, pdf: previous?.pdf, root: previous?.root, sourceDir: previous?.sourceDir, pages: previous?.pages, builtAt: previous?.builtAt });
        const shown = build.problemsKey && build.problemsKey === build.key ? (build.problems || []).filter(problem => problem.severity !== 'error') : [];
        Object.assign(build, { status: 'failed', failureId: randomUUID(), failedProject: project, error: message, problems: [...problems, ...shown], problemsKey: shown.length ? build.problemsKey : undefined, log: detail.log && fs.existsSync(detail.log) ? detail.log : undefined, logFolder });
      }
      this.emit('change', projectId);
      // Edits made while this build ran are compiled next, right away.
      if (this.stale.delete(projectId)) void this.refresh(projectId, root).catch(() => undefined);
    })();
    return build;
  }

  // Old annotations keep their saved content. Only their proven PDF position
  // changes; ambiguous or missing content stays on the earlier version.
  async reanchor(projectId: string, root: string, notes: Annotation[]): Promise<Annotation[]> {
    // The pages on screen, including a pass of a build still running.
    const build = this.builds.get(projectId);
    if (!build?.pdf || !build.key || !notes.some(note => note.key !== build.key)) return notes;
    // Every poll asks again; placements already checked need no PDF opened.
    const cacheKey = (note: Annotation) => JSON.stringify([projectId, build.key, note.key, note.page, note.rect, note.rects, note.quote]);
    if (notes.every(note => note.key === build.key || this.placements.has(cacheKey(note))))
      return notes.map(note => { const placement = note.key === build.key ? null : this.placements.get(cacheKey(note)); return placement ? { ...note, ...placement } : note; });
    // Placing reads every page of a long PDF between other requests; a poll
    // that arrives meanwhile shares the work instead of repeating it.
    const batch = JSON.stringify([projectId, build.key, notes.map(note => cacheKey(note))]);
    let placing = this.reanchoring.get(batch);
    if (!placing) {
      placing = this.place(projectId, root, notes, build.pdf, build.key, cacheKey);
      this.reanchoring.set(batch, placing);
      void placing.then(() => undefined, () => undefined).then(() => this.reanchoring.delete(batch));
    }
    return placing;
  }
  private reanchoring = new Map<string, Promise<Annotation[]>>();
  private async place(projectId: string, root: string, notes: Annotation[], pdfFile: string, buildKey: string, cacheKey: (note: Annotation) => string): Promise<Annotation[]> {
    // Each note to place, with the earlier PDF it was written on.
    const wanted = new Map<string, { note: Annotation; previous: string | null }>();
    for (const note of notes) {
      const key = cacheKey(note);
      if (note.key === buildKey || this.placements.has(key) || wanted.has(key)) continue;
      wanted.set(key, { note, previous: await this.cachedPdf(root, note.key).catch(() => null) });
    }
    const readable = [...wanted.values()].filter((entry): entry is { note: Annotation; previous: string } => entry.previous !== null);
    const matches = await this.pdfReader.place(pdfFile, readable), found = new Map(readable.map((entry, index) => [entry.note, matches[index]]));
    for (const [key, { note }] of wanted) {
      let placement: Pick<Annotation, 'key' | 'page' | 'rect' | 'rects' | 'source'> | null = null;
      const match = found.get(note);
      if (match) try {
        const { source } = await this.locate(projectId, buildKey, match.page, match.rect, match.rects, note.quote);
        placement = { ...match, key: buildKey, source };
      } catch { /* Keep the annotation intact when its position cannot be verified. */ }
      this.placements.set(key, placement);
    }
    const output = notes.map(note => {
      const placement = note.key === buildKey ? null : this.placements.get(cacheKey(note));
      return placement ? { ...note, ...placement } : note;
    });
    if (this.placements.size > 2000) this.placements.clear();
    if (this.oldPdfs.size > 500) this.oldPdfs.clear();
    return this.builds.get(projectId)?.key === buildKey ? output : notes;
  }

  // Every problem of the last finished build, placed on its PDF when there is
  // one. Placing runs SyncTeX per problem, once per build.
  async problems(projectId: string): Promise<ManuscriptProblems> {
    const build = this.builds.get(projectId);
    if (!build?.problems) return { status: build?.status || 'building', problems: [], log: Boolean(build?.log) };
    const { problems, problemsKey: key, pdf, failureId } = build;
    if (!key || key !== build.key || !pdf) return { status: build.status, failureId, problems: sortProblems(problems.map(({ source: _source, occurrence: _occurrence, ...problem }) => problem)), log: Boolean(build.log) };
    let placed = this.located.get(problems);
    if (!placed) {
      placed = (async () => {
        const { PdfDocument } = await engine();
        // Most problems need only a page's size; its text, which takes up to
        // a hundred milliseconds to read on a busy page, is read when a
        // missing reference or citation is searched for on it.
        const document = new PdfDocument(pdf), pages = new Map<number, { destroy(): void; getBounds(): number[]; search(needle: string, options: object): number[][][] }>();
        try {
          return sortProblems(await locateProblems(problems, pdf, page => {
            if (!Number.isInteger(page) || page < 0 || page >= document.length) return null;
            if (!pages.has(page)) pages.set(page, document.raw.loadPage(page));
            const raw = pages.get(page)!, bounds = raw.getBounds();
            return {
              bounds, width: bounds[2] - bounds[0], height: bounds[3] - bounds[1],
              search: (needle: string) => raw.search(needle, {}).flat().map(q => [Math.min(q[0], q[2], q[4], q[6]), Math.min(q[1], q[3], q[5], q[7]), Math.max(q[0], q[2], q[4], q[6]), Math.max(q[1], q[3], q[5], q[7])]),
            };
          }));
        } finally { for (const page of pages.values()) page.destroy(); document.close(); }
      })();
      placed.catch(() => this.located.delete(problems));
      this.located.set(problems, placed);
    }
    return { status: build.status, key, failureId, problems: await placed, log: Boolean(build.log) };
  }

  log(projectId: string) {
    const build = this.builds.get(projectId);
    if (!build?.log || !fs.existsSync(build.log)) throw Object.assign(new Error('There is no compilation log yet.'), { statusCode: 404 });
    return scrubLog(fs.readFileSync(build.log, 'utf8'), build.logFolder);
  }

  repair(projectId: string, root: string, failureId: string, diagnose: (prompt: string) => Promise<string>): Promise<BuildRepairResult> {
    const failed = this.builds.get(projectId);
    const stale = () => Object.assign(new Error('The manuscript build changed. Check the latest compilation problems.'), { statusCode: 409 });
    if (failed?.status !== 'failed' || failed.failureId !== failureId) throw stale();
    const { tree, failedProject: project } = failed;
    const pending = this.repairs.get(failed);
    if (pending) return pending;
    const checkCurrent = async () => {
      if (this.builds.get(projectId) !== failed || await this.snapshot(root) !== tree || this.builds.get(projectId) !== failed) throw stale();
    };
    const repair = (async (): Promise<BuildRepairResult> => {
      const { Builder, BuildError, Repo, config, mupdf } = await engine();
      const { ENGINES, loadBuildDocuments, loadProject, readBuildOverrides, readSettings, saveBuildOverrides, signature } = config;
      const { which } = await import(pathToFileURL(path.join(ENGINE, 'src/core/process.ts')).href) as typeof import('../../engine/src/core/process.ts');
      const repo = new Repo(root), defaults = readSettings(root), saved = readBuildOverrides(root, defaults);
      let documents: ReturnType<typeof loadBuildDocuments> | undefined = project;
      if (!documents) try { documents = loadBuildDocuments(root, defaults, saved.ignoreLatexmkrc); }
      catch { /* An unresolved main document still permits diagnosis and advice. */ }
      const checkSettings = () => {
        if (JSON.stringify(readSettings(root)) !== JSON.stringify(defaults) || JSON.stringify(readBuildOverrides(root)) !== JSON.stringify(saved)) throw stale();
      };
      const entries = (await repo.entriesAsync(tree)).filter(entry => entry.mode.startsWith('100'));
      const candidates = entries.filter(entry => /\.tex$/i.test(entry.file)).map(entry => entry.file).slice(0, 80);
      const errors = (failed.problems || []).filter(problem => problem.severity === 'error');
      const focus = new Set([documents?.main, ...errors.map(problem => problem.file)]);
      const small = new Set(entries.filter(entry => entry.size <= 100_000 && /\.(tex|sty|cls|bib)$/i.test(entry.file)).map(entry => entry.file));
      const files = [...focus].filter((file): file is string => Boolean(file && small.has(file))).slice(0, 6);
      const blobs = await repo.blobsAsync(tree, files);
      const excerpts = files.map(file => {
        const lines = blobs[file]?.toString('utf8').split('\n') || [];
        const line = errors.find(problem => problem.file === file && problem.line)?.line ?? 1;
        const start = Math.max(0, line - 5);
        return { file, line: start + 1, text: lines.slice(start, start + 14).join('\n').slice(0, 1600) };
      });
      const { main, latexmkrc } = documents || {}, { engine: compiler, source_dir } = project || {};
      const prompt = JSON.stringify({ platform: process.platform, installedEngines: ENGINES.filter(name => which(name)), latexmkInstalled: Boolean(which('latexmk')),
        settings: { main, engine: compiler, source_dir, latexmkrc, ...saved }, candidates, excerpts, error: scrubLog(failed.error || '', failed.logFolder).slice(0, 12000) });
      await checkCurrent();
      const { kind, summary, settings } = parseLatexRepair(await diagnose(prompt));
      await checkCurrent();
      if (!settings) return { kind, summary };
      checkSettings();
      const next = { ...saved, ...settings }, candidate = loadProject(root, next);
      if (!entries.some(entry => entry.file === candidate.main)) throw new Error('Choose an existing TeX main file.');
      if (candidate.latexmkrc && (!documents || candidate.latexmkrc !== documents.latexmkrc || candidate.doc_dir !== documents.doc_dir))
        throw new Error('The proposed settings would enable a different latexmkrc.');
      if (project && signature(project) === signature(candidate)) return { kind: 'advice', summary };
      let result: BuildInfo;
      try { result = await new Builder(candidate, repo).build(tree, ['full'], null, { force: true, priority: 'foreground' }); }
      catch (error) {
        if (!(error instanceof BuildError)) throw error;
        return { kind: 'advice', summary: `${summary}\n\n${scrubLog([error.message, ...error.details].join('\n'))}` };
      }
      const pages = await pageSizes(mupdf, result.pdf);
      if (!pages.length) throw new Error('The manuscript could not be compiled.');
      await checkCurrent();
      checkSettings();
      if (signature(loadProject(root, next)) !== signature(candidate)) throw stale();
      saveBuildOverrides(root, next);
      this.emit('build-settings', projectId);
      this.start(projectId, root, tree, failed, false, { project: candidate, result, pages });
      return { kind, summary };
    })().finally(() => this.repairs.delete(failed));
    this.repairs.set(failed, repair);
    return repair;
  }

  // Compile the task's frozen source tree, then retain its PDF outside the build cache.
  // A preview build of the same tree is shared, not repeated.
  async captureReview(root: string, worktree: string, taskId: string, document?: string): Promise<ReviewSnapshot> {
    const { Builder, BuildError, Repo, config } = await engine();
    // The task's root document, as the engine compiles it.
    const tree = await workingTree(worktree), project = config.projectFor(root, document);
    let result;
    try { result = await new Builder(project, new Repo(root)).build(tree, ['full']); }
    catch (error) { throw error instanceof BuildError ? new Error('The manuscript could not be compiled for AI review. Fix the errors shown in the manuscript preview, then try again.') : error; }
    const snapshot = await this.reviewSnapshot(project.state, result);
    // The task does not exist yet, so a PDF kept by an earlier failed attempt is replaced.
    return { ...snapshot, ...(result.errors?.length ? { errors: result.errors } : {}), pdf: await this.preserveReviewPdf(root, taskId, result.pdf, true) };
  }

  private async reviewPdfPath(root: string, taskId: string) {
    const { loadProject } = await engine();
    return path.join(loadProject(root).state, 'ai-reviews', createHash('sha256').update(taskId).digest('hex'), 'review.pdf');
  }

  async savedReviewPdf(root: string, taskId: string): Promise<string | null> {
    const pdf = await this.reviewPdfPath(root, taskId);
    return fs.existsSync(pdf) ? pdf : null;
  }

  private reviewCopies = new Map<string, Promise<string>>();
  async preserveReviewPdf(root: string, taskId: string, source: string, replace = false) {
    const pdf = await this.reviewPdfPath(root, taskId), folder = path.dirname(pdf);
    // Async copies must still publish in order: a retry retains the original,
    // and an earlier recovery cannot overwrite a later explicit replacement.
    const copying = (this.reviewCopies.get(pdf) || Promise.resolve()).catch(() => undefined).then(async () => {
      await fs.promises.mkdir(folder, { recursive: true });
      if (replace || !fs.existsSync(pdf)) {
        const temporary = path.join(folder, `review-${randomUUID()}.tmp`);
        try { await fs.promises.copyFile(source, temporary); await fs.promises.rename(temporary, pdf); }
        finally { await fs.promises.rm(temporary, { force: true }); }
      }
      return pdf;
    });
    this.reviewCopies.set(pdf, copying);
    try { return await copying; }
    finally { if (this.reviewCopies.get(pdf) === copying) this.reviewCopies.delete(pdf); }
  }

  async cachedPdf(root: string, key: string): Promise<string | null> {
    const lookup = `${root}:${key}`;
    if (this.oldPdfs.has(lookup)) return this.oldPdfs.get(lookup)!;
    const { loadProject } = await engine();
    const cache = path.join(loadProject(root).state, 'cache/builds');
    let found: string | null = null;
    const entries = await fs.promises.readdir(cache, { withFileTypes: true }).catch(() => []);
    for (let at = 0; at < entries.length && !found; at += 32)
      await Promise.all(entries.slice(at, at + 32).map(async entry => {
        if (!entry.isDirectory() || entry.name.endsWith('.lock')) return;
        try {
          const folder = path.join(cache, entry.name), saved = JSON.parse(await fs.promises.readFile(path.join(folder, 'result.json'), 'utf8'));
          if (typeof saved.pdf !== 'string' || createHash('sha256').update(saved.key + saved.pdf).digest('hex').slice(0, 16) !== key) return;
          // A build from before the state folder moved names its PDF by the
          // former path, which the link left there keeps valid.
          const inside = (file: string, base: string) => path.resolve(file).startsWith(path.resolve(base) + path.sep);
          if (!inside(saved.pdf, folder) && !inside(await fs.promises.realpath(saved.pdf).catch(() => ''), await fs.promises.realpath(folder))) return;
          if (fs.existsSync(saved.pdf)) found = saved.pdf;
        } catch { /* Incomplete builds have no usable PDF. */ }
      }));
    this.oldPdfs.set(lookup, found); return found;
  }

  async placeReviewNote(projectId: string, root: string, note: Annotation, pdf: string): Promise<Annotation> {
    const state = await this.state(projectId, root);
    if (!state.build.current || !state.build.key) throw new Error('Wait for the current manuscript PDF to finish compiling, then copy the suggestion again.');
    const key = state.build.key, [match] = await this.pdfReader.place(this.pdf(projectId, key), [{ note, previous: pdf }]);
    if (!match) throw new Error('This passage could not be located reliably in the current manuscript. The suggestion remains in the review task.');
    const { source } = await this.locate(projectId, key, match.page, match.rect, match.rects, note.quote);
    const latest = await this.state(projectId, root);
    if (!latest.build.current || latest.build.key !== key) throw new Error('The manuscript changed while copying this suggestion. Try again.');
    return { ...note, ...match, key, source };
  }

  snapshotPdf(pdf: string, key?: string): Promise<ReviewSnapshot> {
    return this.reviewSnapshots.run(pdf, key);
  }

  // Reading the lines of every page takes tens of seconds on a long paper. A
  // build's PDF never changes, so another review of the same build, also after
  // a restart, reuses the lines kept beside the review PDFs.
  private reviewLines = new Map<string, Promise<ReviewSnapshot>>();
  private reviewSnapshot(state: string, build: { key: string; pdf: string }) {
    const id = createHash('sha256').update(build.key + build.pdf).digest('hex').slice(0, 24);
    const cached = this.reviewLines.get(id);
    if (cached) return cached;
    const folder = path.join(state, 'ai-reviews', 'snapshots'), file = path.join(folder, id + '.json');
    const pending = (async () => {
      try {
        const saved = JSON.parse(await fs.promises.readFile(file, 'utf8')) as ReviewSnapshot;
        if (typeof saved?.key === 'string' && Array.isArray(saved.lines) && saved.lines.length) return saved;
      } catch { /* Not read before, or unreadable: read the PDF again. */ }
      const snapshot = await this.snapshotPdf(build.pdf);
      try {
        await fs.promises.mkdir(folder, { recursive: true });
        const temporary = path.join(folder, `${id}-${randomUUID()}.tmp`);
        await fs.promises.writeFile(temporary, JSON.stringify(snapshot));
        await fs.promises.rename(temporary, file);
        // Only recent builds are reviewed again; keep the newest few.
        const saved = await Promise.all((await fs.promises.readdir(folder)).filter(name => name.endsWith('.json'))
          .map(async name => ({ name, at: (await fs.promises.stat(path.join(folder, name)).catch(() => null))?.mtimeMs ?? 0 })));
        for (const old of saved.sort((a, b) => b.at - a.at).slice(8)) await fs.promises.rm(path.join(folder, old.name), { force: true });
      } catch { /* The lines are still returned; the next review reads the PDF again. */ }
      return snapshot;
    })();
    this.reviewLines.set(id, pending);
    pending.catch(() => { if (this.reviewLines.get(id) === pending) this.reviewLines.delete(id); });
    if (this.reviewLines.size > 2) this.reviewLines.delete(this.reviewLines.keys().next().value!);
    return pending;
  }

  /** The PDF pages, counted from 1, where lines of a paper file printed in the
   *  manuscript's latest build, or null without one. A task's text differs
   *  from it only where the task edited, so this places most of what it reads. */
  /** The paper's latest compiled build, which Papilot Writer maps the paper from. */
  // A task's agent reads the manuscript's PDF only while it is of the task's document.
  paperBuild(projectId: string, document?: string) {
    const build = this.builds.get(projectId);
    if (!build?.pdf || !build.root || !fs.existsSync(build.pdf) || (document && this.documentOf(projectId, build.key!) !== document)) return null;
    return { pdf: build.pdf, root: build.root, sourceDir: build.sourceDir || '', builtAt: build.builtAt, pages: build.pages?.length };
  }
  async sourcePages(projectId: string, file: string, lines: number[], document?: string): Promise<number[] | null> {
    const build = this.builds.get(projectId);
    if (!build?.pdf || !fs.existsSync(build.pdf) || (document && this.documentOf(projectId, build.key!) !== document)) return null;
    const relative = path.posix.relative(build.sourceDir || '', file.split(path.sep).join('/'));
    if (relative.startsWith('..')) return [];
    const input = path.join(build.root || path.dirname(build.pdf), relative), pages = new Set<number>();
    // A blank or preamble line prints nothing; the next few lines stand in for it.
    await Promise.all(lines.slice(0, 12).map(async line => {
      for (let next = line; next < line + 4; next++) {
        const boxes = await syncView(build.pdf!, input, next);
        if (boxes.length) { for (const box of boxes) pages.add(box.page + 1); return; }
      }
    }));
    return [...pages].sort((a, b) => a - b);
  }
  pdf(projectId: string, key: string) {
    const shown = this.shownBuild(projectId, key);
    if (!shown) throw Object.assign(new Error('This manuscript preview is out of date. Refresh it and try again.'), { statusCode: 404 });
    return shown.pdf;
  }

  /** The PDF named `key` and the folder its sources were compiled in, which
   *  holds `sourceDir` of the repository: the PDF shown now, or one shown
   *  shortly before whose files are still there. */
  compiled(projectId: string, key: string) {
    const pdf = this.pdf(projectId, key), shown = this.shownBuild(projectId, key)!;
    return { pdf, root: shown.root || path.dirname(pdf), sourceDir: shown.sourceDir || '' };
  }

  async noteSections(projectId: string, key: string, notes: Annotation[]): Promise<NoteSections> {
    return this.pdfReader.sections(this.compiled(projectId, key), key, notes);
  }

  /** A page of a PDF as a PNG, with a commented passage marked on it. */
  async notePage(pdf: string, page: number, rects: Rect[]) {
    const { mupdf } = await engine();
    return markedPage(mupdf, pdf, page, rects);
  }
  // The PDF with the paper's notes drawn on it, to share with people outside Papilot.
  async annotatedPdf(projectId: string, key: string, notes: ExportNote[]) {
    const pdf = this.pdf(projectId, key), { mupdf } = await engine();
    return annotatePdf(mupdf, fs.readFileSync(pdf), notes);
  }

  // A note keeps the text under the marked region and its LaTeX source, so it
  // stays meaningful after the manuscript changes and the preview recompiles.
  // A text selection arrives as one rectangle per line plus the selected text;
  // a marked region arrives as one rectangle.
  // Word places for the PDF view's selection layer, cached per build and page.
  private wordCache = new Map<string, Awaited<ReturnType<typeof pdfWords>>>();
  async words(projectId: string, key: string, page: number) {
    const cacheKey = `${projectId}:${key}:${page}`, cached = this.wordCache.get(cacheKey);
    if (cached) return cached;
    const result = await pdfWords(this.pdf(projectId, key), page);
    if (this.wordCache.size > 200) this.wordCache.delete(this.wordCache.keys().next().value!);
    this.wordCache.set(cacheKey, result);
    return result;
  }

  // The pages may be those of an earlier pass or build than the latest: the
  // place is found in the PDF that was marked, then followed to the file as it
  // is now.
  /** The PDF of a build in the paper's build cache, or null once it is gone. */
  async buildPdf(root: string, key: string) {
    const { loadProject } = await engine(), project = loadProject(root);
    try {
      const info = JSON.parse(await fs.promises.readFile(path.join(project.state, 'cache/builds', key, 'result.json'), 'utf8'));
      return typeof info.pdf === 'string' && fs.existsSync(info.pdf) ? info.pdf as string : null;
    } catch { return null; }
  }
  /** Where a mark on a manuscript preview PDF is, followed into `working`'s files. */
  async locateShown(projectId: string, key: string, page: number, rect: Rect, rects: Rect[], selected: string, working: string) {
    const { pdf, root, sourceDir } = this.compiled(projectId, key);
    return this.pdfReader.locate({ pdf, page, rect, rects, selected, root, sourceDir, working });
  }
  async locate(projectId: string, key: string, page: number, rect: Rect, rects: Rect[] = [], selected = '') {
    const pdf = this.pdf(projectId, key), build = this.shownBuild(projectId, key)!;
    const located = await this.pdfReader.locate({ pdf, page, rect, rects, selected, root: build.root, sourceDir: build.sourceDir, working: this.roots.get(projectId) });
    if (!located) throw Object.assign(new Error('That page is not part of the manuscript.'), { statusCode: 400 });
    return located;
  }

}
