import { PaperTools } from './paper-tools.ts';
import { isNoteGroup } from '../note-groups.ts';
import { isCommitMessageLanguage, type CommitMessageLanguage } from '../commit.ts';
import { noteAlternativeRange, NOTE_ALTERNATIVE_RANGES, validRoutes, taskFinished, type InFlightMark } from '../shared.ts';
import Fastify from 'fastify';
import compress from '@fastify/compress';
import { registerImportUpload } from './import-upload.ts';
import { listFolders, nearestFolder } from './folders.ts';
import { isLocalRequest } from './security.ts';
import { chooseFolder, closeFolderPicker } from './folder-picker.ts';
import rateLimit from '@fastify/rate-limit';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { createHash, randomUUID } from 'node:crypto';
import { registerFrontend } from './frontend.ts';
import type { Store } from './store.ts';
import type { TaskNoteContext, Workspace } from './workspace.ts';
import { WriterAgent } from './writer/agent.ts';
import { AGENT_TURN, reviewClient, retryReviewRead, allowedReviewRoute, rewriteReviewHtml, rewriteReviewJson, confirmedReviewResponse, annotateReviewState, taskRoute } from './review.ts';
import { fullPaperPdf, nextPaperPass, paperBuildPdf, paperPassPdf, retainedPaperBuild, retainedPaperPdf } from './pdf.ts';
import { withNotePages } from './note-pages.ts';
import { type ChangeAction, Changes } from './changes.ts';
import { bibliography, confirmEntry } from './references.ts';
import { type Manuscripts, gitAbortMerge, gitCommit, gitDiff, gitDiscard, gitFinishMerge, gitIgnore, gitRemote, gitStage, gitStatus, gitSync } from './manuscript.ts';
import { gitHistory, gitVersion, gitVersionDiff, gitRestoreVersion } from './git-history.ts';
import { locateSource, placeSource, readFile, saveSource } from './manuscript-source.ts';
import { captureAnchor, resolveAnchors, isSourceAnchor } from './manuscript-anchors.ts';
import { gitOverview } from './git-overview.ts';
import { findSkill, listedSkill, loadSkills } from './skills.ts';
import { registerSkillRoutes } from './skill-routes.ts';
import { type Listener, equals, guard } from './access.ts';
import { isTaskReviewNote, isAgentId, isMarkKind, PRESET_QUICK_NOTES, QUICK_NOTE_LIMIT, type AgentId, type Annotation, type NoteSummary, type QuickNote, type SourceFile, type Task } from '../shared.ts';
import type { SourceFileRead } from '../../engine/src/types.ts';
import { parseGroupInstructions } from '../note-groups.ts';
import { noteOptionContext, noteOptionsKey } from './note-options.ts';
import { taskNoteResults } from './note-results.ts';
import type { Updates } from './updates.ts';
import { Diagnostics } from './diagnostics.ts';
import { attachmentIds } from './attachments.ts';
import { MAX_ATTACHMENT_BYTES, MAX_ATTACHMENTS } from '../shared.ts';
import { PaperImports, openFolder } from './imports.ts';
import { checkDocument, chooseDocument, noteDocumentFilter, repositoryFiles } from './repository-files.ts';
import { PaperCreations } from './create-paper.ts';
import { Universe } from './universe.ts';
import { DATA, pageViewDir } from './paths.ts';
import { registerAiReviewRoutes } from './ai-review-routes.ts';
import { detectLatex, detectPhitex } from './latex-installation.ts';
import { readCompiler, writeCompiler } from '../../engine/src/core/config.ts';
import { systemRequirements } from './system-requirements.ts';
import { findExecutable } from '../../bin/agent-paths.mjs';
import { OverleafService } from './overleaf/service.ts';
import { registerOverleafRoutes } from './overleaf/routes.ts';

const importsByWorkspace = new WeakMap<Workspace, PaperImports>();
const overleafByWorkspace = new WeakMap<Workspace, OverleafService>();
const creationsByWorkspace = new WeakMap<Workspace, PaperCreations>();
function commitMessageLanguage(value: unknown): CommitMessageLanguage {
  if (value === undefined) return 'auto';
  if (!isCommitMessageLanguage(value)) throw new Error('Choose a supported commit message language.');
  return value;
}
// A review write's reply does not wait for the task's summary to be read
// again: that runs right after it, once at a time per task, and once more
// for writes that arrive meanwhile. The review page's reads of the task wait
// for it, so its next poll shows what the reply used to. The workspace does
// not wait, since one slow engine would hold every paper's state: the
// summary's update announces itself through the event stream.
const settling = new WeakMap<Workspace, Map<string, { done: Promise<void>; again: boolean }>>();
function settle(workspace: Workspace, taskId: string) {
  let tasks = settling.get(workspace);
  if (!tasks) settling.set(workspace, tasks = new Map());
  const running = tasks.get(taskId);
  if (running) { running.again = true; return; }
  const entry = { done: Promise.resolve(), again: false };
  entry.done = (async () => {
    try { do { entry.again = false; await workspace.refresh(taskId); } while (entry.again); }
    finally { tasks.delete(taskId); }
  })().catch(() => undefined);
  tasks.set(taskId, entry);
}
async function settled(workspace: Workspace, taskId: string) {
  await settling.get(workspace)?.get(taskId)?.done;
}

// Git writes to one repository run one at a time; each returns the new status.
// Concurrent requests from browser tabs share the same queue.
export function gitQueue() {
  const queue = new Map<string, Promise<unknown>>();
  return function serialGit<T>(projectId: string, work: () => Promise<T>) {
    const run = (queue.get(projectId) || Promise.resolve()).catch(() => {}).then(work);
    queue.set(projectId, run);
    return run.finally(() => { if (queue.get(projectId) === run) queue.delete(projectId); });
  };
}

// Quick notes as one person saved them: up to eight, each with a unique id.
// A preset may keep only its id; one added in settings needs a name for the
// wheel and an instruction for the agent.
// Where a comment on the task's PDF reader was: a page, its lines, and the
// review round's, manuscript preview's or build's PDF it was made on.
function notePaper(value: unknown, rounds: number): NonNullable<NoteSummary['paper']> {
  const paper = value as Record<string, unknown> | null, invalid = () => new Error('Invalid note location.');
  if (!paper || typeof paper !== 'object' || !Number.isSafeInteger(paper.page) || (paper.page as number) < 0 || !Array.isArray(paper.rects) || !paper.rects.length || paper.rects.length > 200) throw invalid();
  const rects = paper.rects.map(rect => {
    if (!Array.isArray(rect) || rect.length !== 4 || !rect.every(v => typeof v === 'number' && v >= 0 && v <= 1) || rect[2] < rect[0] || rect[3] < rect[1]) throw invalid();
    return rect as [number, number, number, number];
  });
  if (paper.round !== undefined && (!Number.isSafeInteger(paper.round) || (paper.round as number) < 1 || (paper.round as number) > rounds)) throw invalid();
  if (paper.key !== undefined && (typeof paper.key !== 'string' || !/^[0-9a-f]{16,64}$/.test(paper.key))) throw invalid();
  if (paper.build !== undefined && (typeof paper.build !== 'string' || !/^[0-9a-f]{32}$/.test(paper.build))) throw invalid();
  return { page: paper.page as number, rects, ...(paper.round ? { round: paper.round as number } : paper.key ? { key: paper.key as string } : paper.build ? { build: paper.build as string } : {}) };
}
function readQuickNotes(value: unknown): QuickNote[] {
  const invalid = () => new Error('Invalid quick notes.');
  if (!Array.isArray(value) || !value.length || value.length > QUICK_NOTE_LIMIT) throw invalid();
  const ids = new Set<string>();
  return value.map(entry => {
    const { id, label, instruction, icon } = (entry && typeof entry === 'object' ? entry : {}) as Record<string, unknown>;
    if (typeof id !== 'string' || !/^[a-z0-9-]{1,40}$/.test(id) || ids.has(id)) throw invalid();
    ids.add(id);
    const text = (field: unknown, max?: number) => {
      if (field === undefined) return undefined;
      const clean = typeof field === 'string' ? field.trim() : '';
      if (!clean || (max !== undefined && clean.length > max)) throw invalid();
      return clean;
    };
    const name = text(label, 40)?.replace(/[·\s]+/g, ' '), said = text(instruction);
    if ((!name || !said) && !PRESET_QUICK_NOTES.includes(id)) throw invalid();
    if (icon !== undefined && (typeof icon !== 'string' || !/^[a-zA-Z]{1,40}$/.test(icon))) throw invalid();
    return { id, ...(name ? { label: name } : {}), ...(said ? { instruction: said } : {}), ...(icon ? { icon } : {}) };
  });
}

export interface AppOptions {
  universe?: Universe;
  listener: Listener; store: Store; workspace: Workspace; manuscripts: Manuscripts; changes?: Changes;
  csrf: string; serialGit: ReturnType<typeof gitQueue>; dist: string | null; version: string;
  connectReview?: typeof reviewClient;
  updates?: Updates; updateInstance?: string;
  desktopInstance?: string;
  prepareDemo?: () => Promise<void>;
  diagnostics?: Diagnostics;
  latexInstallation?: typeof detectLatex;
  phitexVersion?: typeof detectPhitex;
  systemRequirements?: typeof systemRequirements;
  overleaf?: OverleafService;
}

// Serve the local workspace, including authenticated personal Tailscale access.
export async function buildApp(options: AppOptions) {
  const { listener, store, workspace, manuscripts, serialGit } = options, connectReview = options.connectReview || reviewClient;
  const changes = options.changes || new Changes(fs.mkdtempSync(path.join(os.tmpdir(), 'papilot-changes-')));
  const diagnostics = options.diagnostics || new Diagnostics();
  let imports = importsByWorkspace.get(workspace);
  if (!imports) { imports = new PaperImports(manuscripts, DATA, root => Boolean(workspace.projectByPath(root))); importsByWorkspace.set(workspace, imports); }
  // Papers linked to Overleaf projects sync while the server runs. Files
  // Overleaf changes reach an open manuscript view at once.
  let overleaf = options.overleaf ?? overleafByWorkspace.get(workspace), ownsOverleaf = false;
  if (!overleaf) {
    const service = overleaf = new OverleafService(path.join(DATA, 'overleaf'), store, () => manuscripts.emit('change'));
    overleafByWorkspace.set(workspace, service);
    const paperImports = imports;
    imports.overleaf = { download: (url, root) => service.download(url, root), finish: (link, register) => service.finishImport(link, register), discard: link => service.discard(link) };
    service.start(link => paperImports.holdsLink(link));
    ownsOverleaf = true;
  }
  let creations = creationsByWorkspace.get(workspace);
  let universe = options.universe;
  if (!universe) try { universe = new Universe(); } catch { /* An invalid PAPILOT_UNIVERSE_URL leaves only the blank paper. */ }
  if (!creations) { creations = new PaperCreations(DATA, universe); creationsByWorkspace.set(workspace, creations); }
  workspace.importsBusy = () => imports!.busy || creations!.busy;
  // Whether rounds list what each edit changes elsewhere, such as the uses of
  // a macro: the choice in Settings, off by default, since finding
  // which combination reproduces a change needs additional compilations.
  // Task rounds and the manuscript's Changes both follow it.
  const indirectChanges = () => store.preference<boolean>('indirect-changes') === true;
  workspace.indirectChanges = changes.indirectChanges = indirectChanges;
  // An AI review resumed after a restart compiles its copy here too.
  // A task's document as the store has it now: a running turn may have
  // started before the paper first switched documents and stamped it.
  const taskDocument = (task: Task) => store.findTask(task.id)?.document ?? task.document;
  workspace.prepareReview = (task, worktree) => manuscripts.captureReview(store.project(task.projectId).path, worktree, task.id, task.document);
  workspace.sourcePages = (task, file, lines) => manuscripts.sourcePages(task.projectId, file, lines, taskDocument(task));
  workspace.paperBuild = task => manuscripts.paperBuild(task.projectId, taskDocument(task));
  const paperTools = new PaperTools(store, manuscripts, id => workspace.annotationSending(id));
  workspace.paperTools = async (...args) => {
    const result = await paperTools.call(...args);
    if (['annotation_create', 'annotation_update', 'annotation_delete', 'annotation_restore'].includes(args[1])) manuscripts.emit('change');
    return result;
  };
  const app = Fastify({ logger: false, bodyLimit: Number.MAX_SAFE_INTEGER });
  if (ownsOverleaf) app.addHook('onClose', async () => { await overleaf.stop(); });
  const buildSettingsChanged = (projectId: string) => changes.buildSettingsChanged(projectId);
  manuscripts.on('build-settings', buildSettingsChanged);
  app.addHook('onClose', async () => { manuscripts.off('build-settings', buildSettingsChanged); });
  guard(app, { listener, csrf: options.csrf });
  const updateRequests = new WeakMap<object, () => void>();
  app.addHook('onRequest', async (request, reply) => {
    if (!options.updates || !/^\/(api|review)\//.test(request.url) || /^\/api\/(?:updates(?:\/|$)|health(?:\?|$)|events(?:\?|$)|state(?:\?|$))/.test(request.url)) return;
    if (options.updates.restarting) return reply.code(503).header('Retry-After', '3').send({ error: 'Papilot is restarting after an update. Please wait a moment.' });
    const release = options.updates.enter(); updateRequests.set(request, release); reply.raw.once('close', release);
  });
  app.addHook('onResponse', async request => { updateRequests.get(request)?.(); });
  const projectRequests = new WeakMap<object, () => void>();
  app.addHook('preHandler', async request => {
    const resource = request.routeOptions.config.resource, params = request.params as Record<string, string>;
    if (!resource) return;
    const id = 'project' in resource ? (resource.from === 'body' ? request.body as Record<string, string> : params)?.[resource.project]
      : 'task' in resource ? store.taskProject(params[resource.task])
      : store.taskProject(workspace.requests.get(params[resource.request])?.taskId || '');
    if (id) projectRequests.set(request, workspace.enterProjectRequest(id));
  });
  app.addHook('onSend', async (request, _reply, payload) => { projectRequests.get(request)?.(); return payload; });
  const refreshManuscript = (projectId: string) => {
    try {
      const project = store.project(projectId);
      void manuscripts.refresh(project.id, project.path).catch(() => undefined);
    } catch { /* The paper is gone. */ }
  };
  // Refresh when a Git action or a decision on the paper's own uncommitted
  // changes can have changed its files. A task changes them when it is
  // applied, or, for one that writes accepted changes directly, once its
  // last pending change is decided ('decided' below).
  const WRITES = /^\/api\/projects\/:id\/git\/|^\/review\/:projectId\/api\/changes\/(?:decide|undo)$/;
  app.addHook('onResponse', async (request, reply) => {
    if (request.method !== 'POST' || reply.statusCode >= 400 || !WRITES.test(request.routeOptions.url || '')) return;
    const params = (request.params || {}) as Record<string, string>;
    refreshManuscript(params.projectId ?? params.id);
  });
  app.addHook('onError', async request => { projectRequests.get(request)?.(); });
  await app.register(compress);
  app.setErrorHandler((error, _request, reply) => { reply.code((error as any).statusCode || 400).send({ error: (error as Error).message }); });
  registerSkillRoutes(app, store);
  registerAiReviewRoutes(app, store, manuscripts);
  const project = (param = 'id') => ({ config: { resource: { project: param } } }), task = { config: { resource: { task: 'id' } } };
  registerOverleafRoutes(app, overleaf, () => project(), request => isLocalRequest(request.headers, listener.port));
  app.addContentTypeParser('application/octet-stream', { parseAs: 'buffer' }, (_request, body, done) => done(null, body));
  app.post<{ Params: { id: string } }>('/api/projects/:id/attachments', { ...project(), bodyLimit: MAX_ATTACHMENT_BYTES }, async request => {
    if (!Buffer.isBuffer(request.body)) throw new Error('Upload a file as binary data.');
    const header = request.headers['x-papilot-filename'];
    if (typeof header !== 'string') throw new Error('Choose a file with a valid name.');
    let name: string;
    try { name = decodeURIComponent(header); } catch { throw new Error('Choose a file with a valid name.'); }
    return workspace.attachments.upload(request.params.id, name, request.body);
  });
  app.get<{ Params: { id: string; attachment: string } }>('/api/projects/:id/attachments/:attachment', project(), (request, reply) => {
    const file = workspace.attachments.get(request.params.id, request.params.attachment);
    const disposition = file.mime.startsWith('image/') ? 'inline' : 'attachment';
    return reply.type(file.mime).header('Content-Disposition', `${disposition}; filename="attachment"; filename*=UTF-8''${encodeURIComponent(file.name).replace(/'/g, '%27')}`)
      .header('Content-Security-Policy', "default-src 'none'; sandbox").send(fs.createReadStream(workspace.attachments.path(file)));
  });
  app.post<{ Params: { id: string; attachment: string } }>('/api/projects/:id/attachments/:attachment/discard', project(), request => {
    workspace.attachments.discard(request.params.id, request.params.attachment);
    return { ok: true };
  });
  // The manuscript's own notes: on the PDF of the root document it compiles,
  // not sent to a task, and not an AI review's suggestions.
  // A note on another document waits for it while the paper can compile it
  // again, as the file menu offers it: a root document, or one compiled
  // before, even while it lacks \documentclass of its own. One on a main file
  // since renamed or removed moves to the current document.
  async function paperNoteFilter(id: string, includeSent = false) {
    const root = store.project(id).path, inDocument = await noteDocumentFilter(root, await manuscripts.document(id, root));
    return (note: Annotation) => (includeSent || !note.taskId) && !isTaskReviewNote(note) && inDocument(note);
  }
  async function paperNotes(id: string) { return store.annotations(id).filter(await paperNoteFilter(id)); }
  async function manuscript(id: string, rebuild = false) {
    await options.prepareDemo?.();
    const root = store.project(id).path, state = await manuscripts.state(id, root, rebuild);
    const paperNote = await paperNoteFilter(id), notes = store.annotations(id).filter(paperNote);
    const placed = await manuscripts.reanchor(id, root, notes).catch(() => notes);
    for (let index = 0; index < notes.length; index++) {
      const next = placed[index], previous = notes[index];
      if (next.key === previous.key || next.key !== state.build.key) continue;
      const current = store.annotation(id, previous.id);
      // A comment edit, deletion, or task submission may have happened while
      // PDF positions were being checked. Never restore or overwrite that work.
      if (current.deletedAt !== undefined || current.taskId || workspace.annotationSending(current.id) || current.key !== previous.key) continue;
      const document = manuscripts.documentOf(id, next.key);
      store.saveAnnotation({ ...current, ...(document ? { document } : {}), key: next.key, page: next.page, rect: next.rect, rects: next.rects, source: next.source });
    }
    const annotations = store.annotations(id).filter(paperNote);
    // A cold section lookup must not hold up notes or their source locations.
    // Ready assignments return immediately; pending ones arrive on the next poll.
    const scope = state.build.key ? await Promise.race([
      manuscripts.noteSections(id, state.build.key, annotations).catch(() => null),
      new Promise<null>(resolve => setImmediate(resolve, null)),
    ]) : null;
    const onPaper = await paperNoteFilter(id, true);
    const inFlightTask = (note: Annotation) => {
      const task = note.taskId ? store.findTask(note.taskId) : undefined;
      return task?.projectId === id && task.status !== 'deleting' && !taskFinished(task) ? task : undefined;
    };
    const sent = store.annotations(id).filter(note => onPaper(note) && inFlightTask(note));
    // Reuse confirmed placements, without rewriting the task's source snapshot.
    // Recheck after the lookup: delivery or deletion may have finished meanwhile.
    const positions = await manuscripts.reanchor(id, root, sent).catch(() => sent);
    const inFlightMarks: InFlightMark[] = positions.flatMap(note => {
      const current = store.annotation(id, note.id), task = inFlightTask(current);
      return current.deletedAt === undefined && task && current.taskId === note.taskId
        ? [{ note, taskId: task.id, title: task.title, status: task.status, ...(task.status === 'building' && task.review?.ready ? { ready: true as const } : {}) }] : [];
    });
    return { ...state, annotations, inFlightMarks, ...(scope ? { noteSections: scope.sections, unplacedSectionNotes: scope.unplaced } : {}) };
  }

  app.get('/api/health', () => ({ ok: true, name: 'Papilot', version: options.version, ...(options.desktopInstance ? { desktopInstance: options.desktopInstance } : {}), ...(options.updateInstance ? { updateInstance: options.updateInstance } : {}) }));
  app.get('/api/runtime/requirements', () => (options.systemRequirements || systemRequirements)());
  // Detection starts host processes. All tabs and personal remote connections
  // share one budget and one in-flight probe; polling other routes is unaffected.
  await app.register(async latex => {
    await latex.register(rateLimit, { max: 5, timeWindow: 10000, keyGenerator: () => 'latex-installation' });
    let probe: ReturnType<typeof detectLatex> | undefined;
    latex.get('/api/runtime/latex', () => {
      probe ??= (options.latexInstallation || detectLatex)().finally(() => { probe = undefined; });
      return probe;
    });
    // The experimental PhiTeX compiler, for every paper on this host.
    let phitex: ReturnType<typeof detectPhitex> | undefined;
    const compiler = async () => ({ compiler: readCompiler(), phitex: await (phitex ??= (options.phitexVersion || detectPhitex)().finally(() => { phitex = undefined; })) });
    latex.get('/api/runtime/compiler', compiler);
    latex.post('/api/runtime/compiler', request => {
      const choice = (request.body as { compiler?: unknown } | null)?.compiler;
      if (choice !== 'latexmk' && choice !== 'phitex') throw new Error('Choose latexmk or PhiTeX.');
      writeCompiler(choice);
      return compiler();
    });
  });
  app.post('/api/diagnostics', request => {
    const projectId = (request.body as { projectId?: unknown } | null)?.projectId;
    if (projectId !== undefined && (typeof projectId !== 'string' || !projectId || projectId.length > 64)) throw new Error('Select a valid paper to check.');
    const repo = projectId ? store.project(projectId).path : undefined;
    return diagnostics.check(repo, listener.port);
  });
  if (options.updates) {
    app.get('/api/updates', () => options.updates!.snapshot());
    app.post('/api/updates/check', () => options.updates!.check());
    app.post('/api/updates/channel', request => options.updates!.setChannel((request.body as any)?.channel));
    app.post('/api/updates/install', request => options.updates!.install((request.body as any)?.version));
  }
  app.get('/api/state', async (request, reply) => {
    await options.prepareDemo?.();
    // Check the backend environment (Linux when using WSL), again on each poll
    // so installing Git unlocks version management without a page reload.
    const body = JSON.stringify({ ...workspace.snapshot(), gitAvailable: Boolean(findExecutable('git')), overleaf: overleaf.state(), csrf: options.csrf });
    // The app polls every second or two and most polls find nothing new: those
    // get an empty 304 instead of every task again to download and parse.
    const tag = `"${createHash('sha1').update(body).digest('base64url')}"`;
    reply.header('ETag', tag);
    if (request.headers['if-none-match']?.replace(/^W\//, '') === tag) return reply.code(304).send();
    return reply.type('application/json; charset=utf-8').send(body);
  });
  // Quick notes for the magic pen. None saved means the presets.
  app.get('/api/quick-notes', () => ({ quickNotes: store.preference<QuickNote[]>('quick-notes') || null }));
  app.post('/api/quick-notes', request => {
    const value = (request.body as any)?.quickNotes;
    const quickNotes = value === null ? undefined : readQuickNotes(value);
    store.savePreference('quick-notes', quickNotes);
    return { quickNotes: quickNotes || null };
  });
  app.get('/api/collaboration', () => workspace.collaborationSettings());
  app.post('/api/collaboration', (request, reply) => {
    const { enabled, routes } = (request.body as any) || {};
    if (enabled === undefined && routes === undefined) return reply.code(400).send({ error: 'Send enabled or routes.' });
    if (enabled !== undefined && typeof enabled !== 'boolean') return reply.code(400).send({ error: 'Send enabled as true or false.' });
    if (routes !== undefined && !validRoutes(routes)) return reply.code(400).send({ error: 'Choose a supported worker for each collaboration role.' });
    if (routes !== undefined) workspace.setCollaborationRoutes(routes);
    if (enabled !== undefined) workspace.setCollaborationEnabled(enabled);
    return workspace.collaborationSettings();
  });
  app.get('/api/indirect-changes', () => ({ indirectChanges: indirectChanges() }));
  const alternativePreferences = () => ({ noteAlternatives: store.preference<boolean>('note-alternatives') === true, noteAlternativeRange: noteAlternativeRange(store.preference('note-alternative-range')) });
  app.get('/api/note-alternatives', alternativePreferences);
  app.post('/api/note-alternatives', (request, reply) => {
    const value = (request.body as any)?.noteAlternatives;
    const range = (request.body as any)?.noteAlternativeRange;
    if (typeof value !== 'boolean') return reply.code(400).send({ error: 'Send noteAlternatives as true or false.' });
    if (range !== undefined && (typeof range !== 'string' || !Object.hasOwn(NOTE_ALTERNATIVE_RANGES, range))) return reply.code(400).send({ error: 'Send noteAlternativeRange as few, balanced or many.' });
    store.transaction(() => {
      store.savePreference('note-alternatives', value);
      if (range !== undefined) store.savePreference('note-alternative-range', range);
    });
    return alternativePreferences();
  });
  app.post('/api/indirect-changes', (request, reply) => {
    const value = (request.body as any)?.indirectChanges;
    if (typeof value !== 'boolean') return reply.code(400).send({ error: 'Send indirectChanges as true or false.' });
    store.savePreference('indirect-changes', value || undefined);
    return { indirectChanges: value };
  });
  app.get('/api/events', (request, reply) => {
    reply.hijack();
    reply.raw.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache, no-transform', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
    reply.raw.write('event: change\ndata: {}\n\n');
    let timer: NodeJS.Timeout | undefined;
    const change = () => { timer ??= setTimeout(() => { timer = undefined; reply.raw.write('event: change\ndata: {}\n\n'); }, 400); };
    // A manuscript build started or finished: the open PDF view reloads now
    // instead of at its next poll. The event names no paper.
    let paperTimer: NodeJS.Timeout | undefined;
    const paper = () => { paperTimer ??= setTimeout(() => { paperTimer = undefined; reply.raw.write('event: manuscript\ndata: {}\n\n'); }, 100); };
    // Coauthors' cursors on Overleaf come with the event, as they move.
    let presenceTimer: NodeJS.Timeout | undefined;
    const sendPresence = () => { presenceTimer = undefined; reply.raw.write(`event: presence\ndata: ${JSON.stringify(overleaf.cursors())}\n\n`); };
    const presence = () => { presenceTimer ??= setTimeout(sendPresence, 100); };
    sendPresence();
    workspace.on('change', change);
    overleaf.on('change', change);
    overleaf.on('presence', presence);
    manuscripts.on('change', paper);
    const heartbeat = setInterval(() => reply.raw.write(': heartbeat\n\n'), 15000);
    reply.raw.on('close', () => {
      clearInterval(heartbeat); if (timer) clearTimeout(timer); if (paperTimer) clearTimeout(paperTimer); if (presenceTimer) clearTimeout(presenceTimer); workspace.off('change', change); overleaf.off('change', change); overleaf.off('presence', presence); manuscripts.off('change', paper);
    });
  });
  app.post('/api/reconnect', async request => { await workspace.connect(); return workspace.snapshot().runtime; });
  // Papilot Writer's model providers: subscription sign-ins and API keys.
  const writer = async () => {
    const runtime = workspace.agents.papilot as WriterAgent;
    if (!(runtime instanceof WriterAgent)) throw Object.assign(new Error('Papilot Writer is not available.'), { statusCode: 404 });
    await runtime.preload();
    return runtime.credentials!;
  };
  app.get('/api/writer/auth', async () => (await writer()).status());
  app.post('/api/writer/keys', async request => { const body = (request.body || {}) as any, credentials = await writer(); credentials.setKey(string(body.provider, 'Provider', 64), string(body.key, 'API key', 4096)); return credentials.status(); });
  app.post<{ Params: { provider: string } }>('/api/writer/providers/:provider/remove', async request => { const credentials = await writer(); credentials.remove(request.params.provider); return credentials.status(); });
  app.post('/api/writer/logins', async request => {
    const body = (request.body || {}) as any, credentials = await writer();
    const enterprise = typeof body.enterprise === 'string' ? body.enterprise.trim().slice(0, 200) : '';
    return { id: credentials.login(string(body.provider, 'Provider', 64), enterprise), ...credentials.status() };
  });
  app.post<{ Params: { id: string } }>('/api/writer/logins/:id/code', async request => { const credentials = await writer(); credentials.input(request.params.id, string((request.body as any)?.code, 'Code', 4096)); return credentials.status(); });
  app.post<{ Params: { id: string } }>('/api/writer/logins/:id/cancel', async request => { const credentials = await writer(); credentials.cancel(request.params.id); return credentials.status(); });
  app.post<{ Params: { agent: string } }>('/api/runtime/:agent/usage', async (request, reply) => {
    const id = request.params.agent;
    if (!isAgentId(id)) return reply.code(400).send({ error: 'Unknown agent.' });
    const runtime = workspace.runtimes[id];
    if (!runtime.connected || !runtime.authenticated) return { usage: null };
    await workspace.readUsage(id);
    return { usage: runtime.usage };
  });
  // Codex names reasoning efforts with short lowercase words (low, medium, xhigh).
  const agent = (value: unknown): AgentId => isAgentId(value) ? value : 'codex';
  const effort = (value: unknown) => typeof value === 'string' && /^[a-z]{1,16}$/.test(value) ? value : undefined;
  const string = (value: unknown, name: string, max?: number) => { if (typeof value !== 'string' || !value.trim()) throw new Error(`${name} is required.`); if (max !== undefined && value.length > max) throw new Error(`${name} is required and must be no longer than ${max} characters.`); return value.trim(); };
  const commitModelSettings = (b: Record<string, unknown>) => {
    if (b.model !== undefined && (typeof b.model !== 'string' || b.model.length > 200)) throw new Error('Invalid model.');
    if (b.effort !== undefined && b.effort !== '' && !effort(b.effort)) throw new Error('Invalid reasoning effort.');
    return { model: b.model as string | undefined, effort: b.effort as string | undefined, serviceTier: b.serviceTier === undefined ? undefined : string(b.serviceTier, 'Service tier', 64) };
  };
  app.get('/api/projects/create-defaults', () => creations!.defaults());
  app.get('/api/universe', async () => {
    if (!universe) return { templates: [], error: 'Templates are not available here.' };
    try { return { templates: await universe.templates() }; }
    catch (error) { return { templates: [], error: (error as Error).message }; }
  });
  app.post('/api/projects/create', request => creations!.create((request.body || {}) as any, (root, name) => workspace.addProject(root, name)));
  app.post('/api/projects/open', request => openFolder((request.body || {}) as any, root => workspace.projectByPath(root), (root, name) => workspace.addProject(root, name)));
  registerImportUpload(app, imports);
  app.post('/api/folders', request => listFolders((request.body || {}) as any));
  // The system picker appears on this computer's screen, so only a browser here may open it.
  app.post<{ Body: { path?: unknown; title?: unknown } }>('/api/folders/choose', async (request, reply) => {
    if (!isLocalRequest(request.headers, listener.port)) return { unavailable: true };
    const body = request.body || {}, title = typeof body.title === 'string' && body.title.trim() ? body.title.trim().slice(0, 200) : 'Choose a folder';
    const start = await nearestFolder(body.path), controller = new AbortController();
    const closed = () => { if (!reply.raw.writableFinished) controller.abort(); };
    reply.raw.on('close', closed);
    try { return await chooseFolder(title, start, controller.signal); }
    finally { reply.raw.off('close', closed); }
  });
  // A waiting picker request would otherwise hold shutdown open.
  app.addHook('preClose', async () => closeFolderPicker());
  // Legacy base64 clients still buffer JSON; browser file uploads use the streaming route above.
  app.post('/api/imports', { bodyLimit: 90 * 1024 * 1024 }, request => imports!.create((request.body || {}) as any));
  app.get<{ Params: { id: string } }>('/api/imports/:id', request => imports!.get(request.params.id));
  app.post<{ Params: { id: string } }>('/api/imports/:id/build', request => imports!.build(request.params.id, (request.body || {}) as any));
  app.post<{ Params: { id: string } }>('/api/imports/:id/repair', request => imports!.build(request.params.id, (request.body || {}) as any, (root, error) => workspace.repairImport(root, error, { agent: agent((request.body as any)?.agent) })));
  app.post<{ Params: { id: string } }>('/api/imports/:id/finish', request => imports!.finish(request.params.id, (root, name) => workspace.addProject(root, name)));
  app.post<{ Params: { id: string } }>('/api/projects/:id/rename', project(), request => workspace.renameProject(request.params.id, string((request.body as any).name, 'Paper name', 120)));
  const paperIdle = (id: string) => { if (manuscripts.busyForProject(id) || changes.busyForProject(id)) throw Object.assign(new Error('Wait for this paper’s PDF build to finish before changing its path or removing it.'), { statusCode: 409 }); };
  const forgetPaper = (id: string) => { manuscripts.forgetProject(id); changes.forgetProject(id); };
  app.post<{ Params: { id: string } }>('/api/projects/:id/path', async request => {
    const id = request.params.id, body = request.body as any;
    const result = await workspace.changeProjectPath(id, string(body?.path, 'Repository path', 4000), () => paperIdle(id), body?.name === undefined ? undefined : string(body.name, 'Paper name', 120));
    forgetPaper(id); overleaf.moved(id); return result;
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/remove', request => {
    const id = request.params.id, result = workspace.removeProject(id, () => paperIdle(id));
    forgetPaper(id); overleaf.removed(id); return result;
  });
  // A skill's name: what the author typed after "/".
  const skillName = (value: unknown) => typeof value === 'string' && /^[a-z0-9][a-z0-9-]{0,47}$/.test(value) ? value : undefined;
  // Text the author may leave empty when a skill or review feedback says enough.
  const optional = (value: unknown, name: string, max?: number) => value === undefined || value === '' ? '' : string(value, name, max);
  // Each new note's source lookup while it runs, by note ID.
  const locating = new Map<string, Promise<void>>();
  app.get<{ Params: { id: string } }>('/api/projects/:id/skills', project(), request => ({ skills: loadSkills(store.project(request.params.id).path).map(listedSkill) }));
  app.post('/api/tasks', { config: { resource: { project: 'projectId', from: 'body' } } }, async request => {
    const b = request.body as any, skill = skillName(b.skill), attachments = attachmentIds(b.attachments);
    if (b.annotations !== undefined && (!Array.isArray(b.annotations) || b.annotations.some((id: unknown) => typeof id !== 'string' || !id || id.length > 64))) throw new Error('Select valid PDF notes for this task.');
    const annotations: string[] | undefined = b.annotations, groupInstructions = parseGroupInstructions(b.groupInstructions);
    // A note written seconds ago may still be finding its source.
    if (annotations?.length) await Promise.all(annotations.map(note => locating.get(note)));
    const id = string(b.id, 'Task ID', 64), projectId = string(b.projectId, 'Paper ID', 64);
    // A skill submission uses the same task endpoint and retry identity as
    // editing. A retry returns the task, preparing it again if that failed.
    const existing = store.findTask(id);
    if (existing) { if (existing.projectId !== projectId) throw new Error('Invalid task ID.'); return workspace.retryTask(existing.id); }
    // AI review compiles the task's own copy of the manuscript, so it does not wait for the preview.
    const reviewing = Boolean(skill && findSkill(store.project(projectId).path, skill).output === 'annotations');
    // Derive context on the host from the PDF/source snapshot; clients only
    // submit note IDs. Preserve each mark's own build, including older marks.
    const selectedNotes = store.annotations(projectId).filter(note => annotations?.includes(note.id));
    const noteContexts: Record<string, TaskNoteContext> = {};
    for (const key of new Set(selectedNotes.map(note => note.key))) {
      const scope = await manuscripts.noteSections(projectId, key, selectedNotes.filter(note => note.key === key)).catch(() => null);
      if (scope) for (const note of selectedNotes.filter(note => note.key === key)) {
        const context = scope.contexts[note.id];
        if (context) noteContexts[note.id] = { note, context };
      }
    }
    return workspace.createTask({ id, projectId, noteContexts, ...(reviewing ? { prepareReview: (worktree: string, document?: string) => manuscripts.captureReview(store.project(projectId).path, worktree, id, document) } : {}), title: string(b.title, 'Task title', 120), permissions: b.permissions, instructions: skill || annotations?.length || attachments.length ? optional(b.instructions, 'Instructions') : string(b.instructions, 'Instructions'), skill, annotations, groupInstructions, attachments, agent: agent(b.agent), model: typeof b.model === 'string' ? b.model : undefined, effort: effort(b.effort), serviceTier: b.serviceTier === undefined ? undefined : string(b.serviceTier, 'Service tier', 64) });
  });
  // Retry for a task whose preparation failed; it answers at once as well.
  app.post<{ Params: { id: string } }>('/api/tasks/:id/prepare', task, request => workspace.retryTask(request.params.id));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/restart', task, request => {
    const body = (request.body || {}) as any;
    if (!isAgentId(body.agent)) throw new Error('Choose a valid destination agent.');
    for (const key of ['model', 'effort', 'serviceTier']) if (body[key] !== undefined && typeof body[key] !== 'string') throw new Error('Choose valid destination model settings.');
    return workspace.restartTask(request.params.id, { id: string(body.id, 'Task ID', 64), agent: body.agent,
      model: typeof body.model === 'string' ? body.model : undefined, effort: typeof body.effort === 'string' ? body.effort : undefined,
      serviceTier: typeof body.serviceTier === 'string' ? body.serviceTier : undefined, permissions: body.permissions, stop: body.stop === true, draftAttachments: attachmentIds(body.draftAttachments) });
  });
  app.get<{ Params: { id: string }; Querystring: { since?: string } }>('/api/tasks/:id/items', task, request => { store.task(request.params.id); return store.itemsSince(request.params.id, typeof request.query.since === 'string' ? request.query.since : undefined); });
  app.get<{ Params: { id: string } }>('/api/tasks/:id/note-results', task, async request => {
    const task = store.task(request.params.id), client = await connectReview(store.project(task.projectId).path);
    return { notes: await taskNoteResults(task, store.items(task.id), store.runs().filter(run => run.taskId === task.id), client) };
  });
  // A task's file in the editor beside its review. The review engine reads
  // it from the task's worktree and reviews a save in a new round; a save
  // waits like any review action that writes the task's files. The editor
  // works on \n line breaks, so a CRLF file shows no changes in its text.
  const taskSource = (read: SourceFileRead): SourceFile => ({ file: read.file, revision: read.revision, text: read.text, base: read.base, round: read.round, before: read.before, reviewed: read.reviewed && !read.text.includes('\r'), reverted: read.reverted, passage: [0, 0], focus: [0, 0], drifted: false });
  app.get<{ Params: { id: string }; Querystring: { file?: string } }>('/api/tasks/:id/source', task, async request => {
    const current = store.task(request.params.id), file = string(request.query.file, 'Source file', 1024);
    return retryReviewRead(connectReview, store.project(current.projectId).path, async client =>
      taskSource(await client.get<SourceFileRead>(`${taskRoute(current.name)}/source/file?file=${encodeURIComponent(file)}`)));
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/source', { ...task, bodyLimit: 8 * 1024 * 1024 }, async request => {
    const current = store.task(request.params.id), project = store.project(current.projectId), b = (request.body || {}) as any;
    const client = await connectReview(project.path), route = `${taskRoute(current.name)}/source/file`;
    const input = { id: string(b.id, 'Source edit ID', 80), round: b.round, file: string(b.file, 'Source file', 1024), revision: b.revision, text: b.text };
    const value = await workspace.reviewWrite(current.id, true, async () => {
      const response = await fetch(client.url + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Review-Token': client.token }, body: JSON.stringify(input), signal: AbortSignal.timeout(120000) });
      const value = await response.json() as { error?: string; source?: SourceFileRead };
      if (!confirmedReviewResponse(response.status, value, current.name)) throw new Error('The source edit could not be confirmed. Check task status before retrying.');
      return value;
    }, { route, body: input });
    if (value.error || !value.source) throw Object.assign(new Error(value.error || 'The source edit could not be confirmed. Check task status before retrying.'), { statusCode: 409 });
    store.updateTask(current.id, { error: null });
    settle(workspace, current.id);
    // The review continues from this state, as after an edit made in it.
    const { source, ...state } = value;
    return { source: taskSource(source), state: annotateReviewState(rewriteReviewJson(state, `/review/${project.id}`), store.tasks().filter(item => item.projectId === project.id)) };
  });
  app.get<{ Params: { id: string }; Querystring: { key: string } }>('/api/tasks/:id/note-options', task, async request => {
    const project = store.project(store.task(request.params.id).projectId);
    return retryReviewRead(connectReview, project.path, async client =>
      (await noteOptionContext(store, store.task(request.params.id), string(request.query.key, 'Note key', 200), client)).options);
  });
  app.get<{ Params: { id: string }; Querystring: { key: string; round: string; option: string; retry?: string; comparison?: string; background?: string } }>('/api/tasks/:id/note-options/preview', task, async request => {
    const project = store.project(store.task(request.params.id).projectId);
    return retryReviewRead(connectReview, project.path, async client => {
      const current = store.task(request.params.id);
      const context = await noteOptionContext(store, current, string(request.query.key, 'Note key', 200), client);
      if (context.options.round !== Number(request.query.round)) throw new Error('The review changed. Reload the options.');
      if (request.query.comparison && request.query.comparison !== context.options.comparisonKey) throw new Error('The review changed. Reload the options.');
      if (request.query.option === context.options.selected && (!context.rejected.length || context.options.locked)) return rewriteReviewJson(context.detail, `/review/${current.projectId}`);
      if (context.options.locked) throw new Error(context.options.locked);
      const option = context.options.options.find(option => option.id === request.query.option);
      if (!option) throw new Error('This option is no longer available.');
      if (option.previewError && request.query.retry !== '1') throw new Error(option.previewError);
      const detail = await client.post(`${taskRoute(current.name)}/source/options/preview`, { id: option.id, round: context.options.round, edits: option.edits, rejected: context.rejected, background: request.query.background === '1' }, 1850000);
      if (option.previewError) {
        delete option.previewError;
        store.savePreference(noteOptionsKey(current.id, context.options.key, context.options.round), context.options);
      }
      return rewriteReviewJson(detail, `/review/${current.projectId}`);
    });
  });
  app.post<{ Params: { id: string }; Body: { key: string; round: number; option?: string; id?: string; accept?: boolean; reject?: boolean } }>('/api/tasks/:id/note-options', task, async request => {
    const current = store.task(request.params.id), client = await connectReview(store.project(current.projectId).path), body = request.body;
    const context = await noteOptionContext(store, current, string(body.key, 'Note key', 200), client);
    if (context.options.round !== body.round) throw new Error('The review changed. Reload the options.');
    if ((body.reject !== undefined && typeof body.reject !== 'boolean') || (body.accept !== undefined && typeof body.accept !== 'boolean') || (body.accept && body.reject)) throw new Error('Invalid review action.');
    // A confirmed decision may have lost its HTTP response. Let the journal
    // verify an exact replay even though the note is now reviewed; it rejects
    // new IDs, changed actions and undone decisions without touching source.
    const decision = body.reject || (body.accept && body.option === context.options.selected);
    if (context.options.locked && !(decision && context.options.locked === 'This note includes a reviewed change. Undo that decision before replacing it.')) throw new Error(context.options.locked);
    if (body.option) {
      const option = context.options.options.find(option => option.id === body.option);
      if (!option) throw new Error('This option is no longer available.');
      // Reject the note's published edits directly, even if an uncommitted
      // alternative is being previewed. No candidate build or feedback draft.
      if (body.reject || option.id === context.options.selected) {
        if (!body.accept && !body.reject) return context.options;
        const route = `${taskRoute(current.name)}/decide`, input = { id: string(body.id, 'Review action ID', 80), round: body.round, changes: option.edits.map(edit => edit.unit), action: body.reject ? 'reject' : 'accept' };
        const result = await workspace.reviewWrite(current.id, true, async () => {
          const response = await fetch(client.url + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Review-Token': client.token }, body: JSON.stringify(input), signal: AbortSignal.timeout(120000) });
          const value = await response.json() as { error?: string };
          if (!confirmedReviewResponse(response.status, value, current.name)) throw new Error('The review action could not be confirmed. Check task status before retrying.');
          return value;
        }, { route, body: input });
        if (result.error) throw new Error(result.error);
        await workspace.refresh(current.id);
        return (await noteOptionContext(store, store.task(current.id), body.key, client)).options;
      }
      const route = `${taskRoute(current.name)}/source/options`, input = { id: string(body.id, 'Option request ID', 80), round: body.round, edits: option.edits, ...(body.accept ? { accept: true } : {}) };
      // Keep the annotation's original association before the engine starts
      // its build, including when the save response is interrupted.
      for (const run of store.runs().filter(run => run.taskId === current.id && run.reviewRound === body.round)) {
        const origins = context.notes.filter(note => note.itemId === run.id && note.changes.length && !run.noteRounds?.[note.index]);
        if (origins.length) store.saveRun({ ...run, noteRounds: { ...run.noteRounds, ...Object.fromEntries(origins.map(note => [note.index, body.round])) } });
      }
      const value = await workspace.reviewWrite(current.id, true, async () => {
        const response = await fetch(client.url + route, { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Review-Token': client.token }, body: JSON.stringify(input), signal: AbortSignal.timeout(120000) });
        const value = await response.json() as { error?: string };
        if (!confirmedReviewResponse(response.status, value, current.name)) throw new Error('The option save could not be confirmed. Check task status before retrying.');
        return value;
      }, { route, body: input });
      if (value.error) throw new Error(value.error);
      return { building: true };
    }
    throw new Error('Select an existing option.');
  });
  // Once every change of a task is decided, compile in the background what
  // applying it will write, so the manuscript's PDF is ready or on its way
  // when the author saves it. Individual decisions start no build.
  const predict = (taskId: string) => {
    const current = store.task(taskId), project = store.project(current.projectId);
    if (!current.deferred || current.mode === 'review' || current.delivery?.pending || current.status === 'deleting' || (current.review?.counts.pending ?? 0) > 0) return;
    void (async () => {
      const client = await connectReview(project.path);
      // What applying writes: the accepted text merged with the files on
      // disk as the application merges them, or nothing while it would conflict.
      const preview = await client.get<{ files: Record<string, string | null> | null }>(`${taskRoute(current.name)}/preview`);
      if (preview.files) await manuscripts.predict(project.id, project.path, Object.fromEntries(Object.entries(preview.files).map(([file, data]) => [file, data === null ? null : Buffer.from(data, 'base64')])));
    })().catch(() => undefined);
  };
  // A task's final selection: predict what applying it writes.
  const decided = (taskId: string) => { if (store.findTask(taskId)) predict(taskId); };
  workspace.on('decided', decided);
  app.addHook('onClose', async () => { workspace.off('decided', decided); });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/predict', task, request => {
    predict(store.task(request.params.id).id);
    return { ok: true };
  });
  // Where a note on the task's PDF of its decisions is in the task's files.
  app.post<{ Params: { id: string } }>('/api/tasks/:id/locate', task, async request => {
    const current = store.task(request.params.id), project = store.project(current.projectId), b = request.body as any;
    const isRect = (value: unknown): value is [number, number, number, number] => Array.isArray(value) && value.length === 4 && value.every(v => typeof v === 'number' && v >= 0 && v <= 1) && value[2] >= value[0] && value[3] >= value[1];
    const page = Number(b?.page);
    if (!isRect(b?.rect) || !Number.isSafeInteger(page) || page < 0 || !current.worktree) throw new Error('Mark text on a page first.');
    const rects = Array.isArray(b.rects) ? b.rects.filter(isRect).slice(0, 200) : [];
    const located = await manuscripts.locateBuild(project.path, string(b.key, 'PDF key', 32), page, b.rect, rects, typeof b.quote === 'string' ? b.quote.slice(0, 20000) : '', current.worktree, current.document);
    return { source: located?.source ? { file: located.source.file, lines: located.source.lines } : null };
  });
  app.get<{ Params: { id: string }; Querystring: { round?: string; version?: string; download?: string; retained?: string; metadata?: string; build?: string } }>('/api/tasks/:id/pdf', task, async (request, reply) => {
    const task = store.task(request.params.id), project = store.project(task.projectId);
    const round = request.query.round === undefined ? task.review?.round : Number(request.query.round);
    const side = request.query.version || 'after';
    if (!round || !Number.isSafeInteger(round) || round < 1 || (side !== 'before' && side !== 'after')) return reply.code(400).send({ error: 'Select an existing review round and either the before or after PDF.' });
    if (request.query.metadata === '1') {
      if (request.query.retained !== '1' || side !== 'after' || request.query.build !== undefined) return reply.code(400).send({ error: 'Select an existing review round and either the before or after PDF.' });
      const { key, errors } = await retainedPaperBuild(connectReview, project.path, task.name, round);
      return reply.header('Cache-Control', 'no-store').send({ url: `/api/tasks/${encodeURIComponent(task.id)}/pdf?round=${round}&build=${key}`, ...(errors?.length ? { errors } : {}) });
    }
    const pdf = request.query.build !== undefined
      ? await paperBuildPdf(connectReview, project.path, task.name, round, request.query.build, side)
      : request.query.retained === '1' && side === 'after'
      ? await retainedPaperPdf(connectReview, project.path, task.name, round)
      : await fullPaperPdf(connectReview, project.path, task.name, round, side);
    const filename = `papilot-${task.name}-r${round}-${side}.pdf`;
    return reply.type('application/pdf').header('Content-Disposition', `${request.query.download === '1' ? 'attachment' : 'inline'}; filename="${filename}"`).sendFile(path.basename(pdf), path.dirname(pdf), { cacheControl: false });
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/messages', task, async request => {
    const b = request.body as any, task = store.task(request.params.id), feedback = b.feedback === true, name = skillName(b.skill);
    const attachments = attachmentIds(b.attachments);
    if (feedback && attachments.length) throw new Error('Send attachments with a message, separately from review feedback.');
    const skill = name ? findSkill(store.project(task.projectId).path, name) : undefined;
    let reviewNotes: NoteSummary[] | undefined;
    if (b.notes !== undefined) {
      if (!Array.isArray(b.notes) || !b.notes.length || feedback) throw new Error('Select valid review notes.');
      reviewNotes = b.notes.map((note: any) => {
        if (!note || typeof note !== 'object') throw new Error('Select valid review notes.');
        if (note.group !== undefined && !isNoteGroup(note.group)) throw new Error('Invalid annotation group.');
        if (note.kind !== undefined && !isMarkKind(note.kind)) throw new Error('Invalid kind of mark.');
        // Review marks carry the same actions and quick-note labels as manuscript annotations.
        const stamp = note.stamp === undefined ? '' : string(note.stamp, 'Quick note name', 40).replace(/[·\n]/g, ' ').trim();
        const comment = note.group || note.kind === 'delete' ? optional(note.comment, 'Note') : string(note.comment, 'Note');
        const anchor = note.anchor;
        if (anchor && (!Array.isArray(anchor.sources) || (anchor.round !== undefined && (!Number.isSafeInteger(anchor.round) || anchor.round < 1 || anchor.round > (task.review?.round || 0))))) throw new Error('Invalid note location.');
        const sources = anchor?.sources.map((source: any) => {
          if (!source || !Array.isArray(source.lines) || source.lines.length !== 2 || !source.lines.every((line: unknown) => Number.isSafeInteger(line) && Number(line) >= 1) || source.lines[1] < source.lines[0]) throw new Error('Invalid note location.');
          return { file: string(source.file, 'Source file', 4096), lines: source.lines as [number, number] };
        });
        const paper = note.paper === undefined ? undefined : notePaper(note.paper, task.review?.round || 0);
        return { ...(paper ? { paper } : {}), ...(note.id ? { id: string(note.id, 'Note ID', 100) } : {}), where: string(note.where, 'Note location'), quote: optional(note.quote, 'PDF text'), comment, ...(note.group ? { group: note.group } : {}), ...(note.kind ? { kind: note.kind } : {}), ...(stamp ? { stamp } : {}), ...(anchor ? { anchor: { sources, ...(anchor.round ? { round: anchor.round } : {}) } } : {}) };
      });
    }
    const text = feedback || skill || reviewNotes || attachments.length ? optional(b.text, 'Revision instructions') : string(b.text, 'Revision instructions');
    // A comment on the task's PDF brings its page as an image, and its source lines.
    if (reviewNotes?.some(note => note.paper)) {
      const project = store.project(task.projectId);
      const pages = await withNotePages(reviewNotes, {
        pdf: async paper => paper.round ? retainedPaperPdf(connectReview, project.path, task.name, paper.round) : paper.key ? manuscripts.compiled(task.projectId, paper.key).pdf : paper.build ? manuscripts.buildPdf(project.path, paper.build) : null,
        locate: async (paper, quote) => {
          if (!paper.key || !task.worktree) return null;
          const rect: [number, number, number, number] = [Math.min(...paper.rects.map(r => r[0])), Math.min(...paper.rects.map(r => r[1])), Math.max(...paper.rects.map(r => r[2])), Math.max(...paper.rects.map(r => r[3]))];
          const located = await manuscripts.locateShown(task.projectId, paper.key, paper.page, rect, paper.rects, quote, task.worktree);
          return located?.source ? { file: located.source.file, lines: located.source.lines } : null;
        },
        render: (pdf, page, rects) => manuscripts.notePage(pdf, page, rects),
        attach: async (name, png) => (await workspace.attachments.upload(task.projectId, name, png)).id,
      }, MAX_ATTACHMENTS - attachments.length);
      reviewNotes = pages.notes; attachments.push(...pages.attachments);
    }
    return workspace.enqueue(task.id, text, string(b.requestKey, 'Request ID', 100), true, { skill, feedback, reviewNotes, attachments });
  });
  // Applying writes the manuscript only once its delivery is complete: not
  // for a confirmation, a merge suggestion, a pending delivery or a branch.
  const delivered = (delivery: Task['delivery']) => Boolean(delivery && !delivery.pending && delivery.mode !== 'branch');
  app.post<{ Params: { id: string } }>('/api/tasks/:id/apply', task, async request => {
    const task = store.task(request.params.id), b = (request.body || {}) as any;
    if (b.mode !== undefined && b.mode !== 'workspace' && b.mode !== 'commit') throw new Error('Invalid save action.');
    const result = await serialGit(task.projectId, () => workspace.applyTask(task.id, b.keepCurrent === true, b.mode === 'commit' ? { message: string(b.message, 'Commit message', 5000), ...(b.confirmation ? { confirmation: string(b.confirmation, 'Commit confirmation', 100) } : {}) } : undefined));
    if (delivered(result.delivery)) refreshManuscript(task.projectId);
    return result;
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/commit-message', task, request => {
    const task = store.task(request.params.id), b = (request.body || {}) as Record<string, unknown>;
    if (b.agent !== undefined && !isAgentId(b.agent)) throw new Error('Invalid agent.');
    const settings = commitModelSettings({ ...(b.agent === undefined ? { model: task.model || undefined, effort: task.effort || undefined, serviceTier: task.serviceTier } : {}), ...b });
    return workspace.commitMessage(task.projectId, task.review?.files || [], { taskId: task.id, agent: b.agent === undefined ? task.agent : agent(b.agent), ...settings, fresh: b.fresh === true, language: commitMessageLanguage(b.language) });
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/permissions', task, request => workspace.updateTaskPermissions(request.params.id, (request.body as any)?.permissions));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/model', task, request => {
    const b = (request.body || {}) as Record<string, unknown>;
    if (Object.keys(b).some(key => !['model', 'effort', 'serviceTier'].includes(key))) throw new Error('Only the model and its settings can be changed.');
    if (b.model !== undefined && (typeof b.model !== 'string' || b.model.length > 200)) throw new Error('Invalid model.');
    if (b.effort !== undefined && b.effort !== '' && !effort(b.effort)) throw new Error('Invalid reasoning effort.');
    return workspace.updateTaskModel(request.params.id, { ...(b.model !== undefined ? { model: b.model as string } : {}), ...(b.effort !== undefined ? { effort: b.effort as string } : {}), ...(b.serviceTier !== undefined ? { serviceTier: string(b.serviceTier, 'Service tier', 64) } : {}) });
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/rename', task, request => workspace.renameTask(request.params.id, string((request.body as any).title, 'Task title', 120)));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/title', task, request => workspace.requestTaskTitle(request.params.id));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/archive', task, request => workspace.archiveTask(request.params.id, (request.body as any)?.archived, (request.body as any)?.finished === true));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/interrupt', task, request => workspace.interrupt(request.params.id).then(() => ({ ok: true })));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/workers/stop', task, request => { workspace.stopWorker(request.params.id, string((request.body as any)?.item, 'Worker')); return { ok: true }; });
  // Deleting a task that is already gone succeeds, so a lost response can be retried; a hidden one answers the same.
  // A page an agent looked at, as the chat shows it with that tool call.
  app.get<{ Params: { id: string; file: string } }>('/api/tasks/:id/pages/:file', task, (request, reply) => {
    const dir = pageViewDir(store.task(request.params.id).id), file = request.params.file;
    if (!/^[\w-]{1,100}-\d\.png$/.test(file) || !fs.existsSync(path.join(dir, file))) return reply.code(404).send({ error: 'This page is no longer available.' });
    return reply.type('image/png').header('Cache-Control', 'private, max-age=31536000, immutable').sendFile(file, dir, { cacheControl: false });
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/delete', { config: { resource: { task: 'id' } } }, request => {
    if ((request.body as any)?.confirm !== true) throw new Error('Confirm permanent task deletion before continuing.');
    return workspace.deleteTask(request.params.id);
  });
  app.post<{ Params: { id: string } }>('/api/tasks/:id/reconcile', task, request => workspace.reconcile(request.params.id));
  app.post<{ Params: { id: string } }>('/api/tasks/:id/publish', task, request => {
    const task = store.task(request.params.id); if (task.preparation || ['running', 'waiting_input', 'building'].includes(task.status)) throw new Error('This task is busy. Wait for it to finish or pause it first.');
    void workspace.publish(task.id); return { ok: true };
  });
  // The manuscript preview compiles each paper's working tree and reports its Git status.
  app.get<{ Params: { id: string } }>('/api/projects/:id/manuscript', project(), request => manuscript(request.params.id));
  app.get<{ Params: { id: string } }>('/api/projects/:id/git', project(), request => gitStatus(store.project(request.params.id).path));
  // The paper's bibliography: every entry, its problems and its online check.
  app.get<{ Params: { id: string }; Querystring: { check?: string; retry?: string } }>('/api/projects/:id/references', project(), request =>
    bibliography(store.project(request.params.id).path, request.query.check === '1', request.query.retry === '1'));
  app.post<{ Params: { id: string } }>('/api/projects/:id/references/confirm', project(), request => {
    const b = request.body as any;
    if (typeof b?.id !== 'string' || typeof b?.confirmed !== 'boolean') throw new Error('Choose an entry to confirm.');
    return confirmEntry(store.project(request.params.id).path, b.id, b.confirmed);
  });
  app.get<{ Params: { id: string } }>('/api/projects/:id/git/overview', project(), request => gitOverview(store.project(request.params.id).path, store.tasks().filter(task => task.projectId === request.params.id)));
  app.get<{ Params: { id: string }; Querystring: { before?: string } }>('/api/projects/:id/git/history', project(), request => gitHistory(store.project(request.params.id).path, request.query.before));
  app.get<{ Params: { id: string; hash: string } }>('/api/projects/:id/git/history/:hash', project(), request => gitVersion(store.project(request.params.id).path, request.params.hash));
  app.get<{ Params: { id: string; hash: string }; Querystring: { path?: string } }>('/api/projects/:id/git/history/:hash/diff', project(), request => gitVersionDiff(store.project(request.params.id).path, request.params.hash, string(request.query.path, 'File path', 4096)));
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/restore', project(), request => {
    const project = store.project(request.params.id), b = request.body as any;
    const hash = string(b?.hash, 'Version', 64), head = string(b?.head, 'Current version', 64);
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, () => gitRestoreVersion(project.path, hash, head)));
  });
  app.get<{ Params: { id: string }; Querystring: { path?: string; scope?: string } }>('/api/projects/:id/git/diff', project(), request => gitDiff(store.project(request.params.id).path, string(request.query.path, 'File path', 4096), request.query.scope === 'staged' ? 'staged' : request.query.scope === 'unstaged' ? 'unstaged' : 'all'));
  const paths = (value: unknown): string[] => Array.isArray(value) ? value.filter((p: unknown): p is string => typeof p === 'string') : [];
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/commit', project(), request => {
    const project = store.project(request.params.id), b = request.body as any;
    const message = string(b.message, 'Commit message', 5000), chosen = b.staged === true ? null : paths(b.paths);
    let pushError: string | undefined;
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, async () => {
      const commit = await gitCommit(project.path, message, chosen, b.amend === true);
      // The commit stands even when the push fails; the author can push again.
      if (b.push === true) try { await gitRemote(project.path, 'push'); } catch (error) { pushError = (error as Error).message; }
      return { commit, git: await gitStatus(project.path), ...(pushError ? { pushError } : {}) };
    }));
  });
  // The Git panel's checkboxes stage or unstage whole files.
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/stage', project(), request => {
    const project = store.project(request.params.id), b = request.body as any;
    return serialGit(project.id, async () => ({ git: await gitStage(project.path, paths(b.paths), b.stage !== false) }));
  });
  // The Git panel confirms before discarding; this cannot be undone.
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/discard', project(), request => {
    const project = store.project(request.params.id), b = request.body as any;
    return serialGit(project.id, async () => ({ git: await gitDiscard(project.path, paths(b.paths)) }));
  });
  // An agent writes a commit message for the chosen files, or a fresh one
  // instead of the message it already wrote for them; nothing is written.
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/message', project(), request => {
    const b = request.body as any;
    if (b.agent !== undefined && !isAgentId(b.agent)) throw new Error('Invalid agent.');
    return workspace.commitMessage(store.project(request.params.id).id, paths(b.paths), { agent: b.agent === undefined ? undefined : agent(b.agent), ...commitModelSettings(b), fresh: b.fresh === true, staged: b.staged === true, language: commitMessageLanguage(b.language) });
  });
  // A merge in progress is resolved by an agent, committed, or abandoned.
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/resolve', project(), request => {
    const project = store.project(request.params.id), b = request.body as any;
    return serialGit(project.id, () => workspace.resolveConflicts(project.id, { agent: b.agent === undefined ? undefined : agent(b.agent), model: typeof b.model === 'string' ? b.model : undefined }));
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/finish', project(), request => {
    const project = store.project(request.params.id);
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, async () => ({ commit: await gitFinishMerge(project.path), git: await gitStatus(project.path) })));
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/abort', project(), request => {
    const project = store.project(request.params.id);
    return serialGit(project.id, async () => { await gitAbortMerge(project.path); return { git: await gitStatus(project.path) }; });
  });
  // Chosen untracked build files go into .gitignore by kind.
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/ignore', project(), request => {
    const project = store.project(request.params.id);
    return serialGit(project.id, async () => ({ git: await gitIgnore(project.path, paths((request.body as any).paths)) }));
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/git/sync', project(), request => {
    const project = store.project(request.params.id);
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, async () => ({ git: await gitSync(project.path) })));
  });
  app.post<{ Params: { id: string; action: string } }>('/api/projects/:id/git/:action', project(), request => {
    const project = store.project(request.params.id), action = request.params.action;
    if (action !== 'fetch' && action !== 'pull' && action !== 'merge' && action !== 'push') throw Object.assign(new Error('Unknown Git action.'), { statusCode: 404 });
    const work = async () => { await gitRemote(project.path, action); return { git: await gitStatus(project.path) }; };
    // An automatic remote check must not queue local staging/commits behind
    // network waits. Other remote operations can change HEAD or working files.
    return action === 'fetch' ? work() : serialGit(project.id, work);
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/manuscript', project(), request => manuscript(request.params.id, true));
  // The file browser: the repository's files, and the root document the
  // paper compiles, which can be any of its root documents.
  app.get<{ Params: { id: string } }>('/api/projects/:id/files', project(), async request => {
    const project = store.project(request.params.id);
    const document = await manuscripts.document(project.id, project.path);
    return { document: document ?? null, files: await repositoryFiles(project.path, document) };
  });
  // One switch at a time per paper, and not during its other Git work: each
  // reads and writes the settings and the documents compiled before.
  app.post<{ Params: { id: string } }>('/api/projects/:id/document', project(), request => serialGit(request.params.id, async () => {
    const project = store.project(request.params.id), previous = await manuscripts.document(project.id, project.path);
    const main = await checkDocument(project.path, (request.body as { main?: unknown } | null)?.main);
    if (previous && main !== previous) {
      // Notes and tasks from before a paper could compile several documents
      // are on the one it compiled until now; the review engine marks its
      // tasks as it starts. A task prepared later takes the engine's record.
      store.transaction(() => {
        for (const note of store.annotations(project.id, true)) if (!note.document) store.saveAnnotation({ ...note, document: previous });
        for (const task of store.tasks()) if (task.projectId === project.id && !task.document) store.updateTask(task.id, { document: previous });
      });
      if (store.tasks().some(task => task.projectId === project.id)) await connectReview(project.path);
    }
    // The settings may name another document than the PDF shown, or already
    // name this one, edited by hand: either way the PDF shown is not its own.
    if (await chooseDocument(project.path, main) || main !== previous) await manuscripts.documentChanged(project.id, project.path, main);
    return { document: main };
  }));
  const isRect = (value: unknown): value is [number, number, number, number] => Array.isArray(value) && value.length === 4 && value.every(v => typeof v === 'number' && v >= 0 && v <= 1) && value[2] > value[0] && value[3] > value[1];
  app.post<{ Params: { id: string } }>('/api/projects/:id/manuscript/anchors', project(), request => {
    const b = (request.body || {}) as any;
    if (!isRect(b.rect) || !Number.isInteger(b.page) || b.page < 0) throw new Error('Select text or mark a region on the page first.');
    return captureAnchor(manuscripts, store, request.params.id, string(b.key, 'Preview key', 64), b.page, b.rect,
      Array.isArray(b.rects) ? b.rects.filter(isRect).slice(0, 200) : [], typeof b.quote === 'string' ? b.quote.slice(0, 20000) : '');
  });
  app.post<{ Params: { id: string } }>('/api/projects/:id/manuscript/anchors/resolve', project(), request => {
    const b = (request.body || {}) as any;
    if (!Array.isArray(b.anchors) || !b.anchors.every((anchor: any) => anchor && typeof anchor.id === 'string' && isSourceAnchor(anchor.source) && Number.isInteger(anchor.near) && anchor.near >= 0)) throw new Error('Invalid line range.');
    return resolveAnchors(manuscripts, store, request.params.id, string(b.key, 'Preview key', 64), b.anchors);
  });
  // Manual LaTeX edits from the PDF, without an agent: the passage under a
  // click as it is on disk now, any lines of a file, a save of those lines
  // (which compiles the manuscript), and where saved lines were printed.
  // A paper synced with Overleaf also says who wrote what there.
  const authored = <T extends SourceFile>(projectId: string, source: T): T => {
    const authors = overleaf.authors(projectId, source.file, source.text);
    return authors.length ? { ...source, authors } : source;
  };
  app.post<{ Params: { id: string } }>('/api/projects/:id/manuscript/source/locate', project(), async request => {
    const project = store.project(request.params.id), b = (request.body || {}) as any;
    if (!isRect(b.rect)) throw new Error('Click the text whose source you want to edit.');
    const rects = Array.isArray(b.rects) ? b.rects.filter(isRect).slice(0, 200) : [];
    const found = await locateSource(manuscripts, project.id, project.path, string(b.key, 'Preview key', 64), Number(b.page), b.rect, rects, typeof b.quote === 'string' ? b.quote.slice(0, 20000) : '');
    return { ...found, source: found.source ? authored(project.id, found.source) : null };
  });
  app.get<{ Params: { id: string }; Querystring: { file?: string } }>('/api/projects/:id/manuscript/source', project(), async request =>
    authored(request.params.id, await readFile(store.project(request.params.id).path, request.query.file)));
  app.post<{ Params: { id: string } }>('/api/projects/:id/manuscript/source', { ...project(), bodyLimit: 8 * 1024 * 1024 }, request => {
    const project = store.project(request.params.id);
    // Like reverting a change: one Git write at a time, never during a commit.
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, async () => {
      const saved = await saveSource(project.id, project.path, request.body), at = Date.now();
      return { ...saved, source: authored(project.id, saved.source), tree: await manuscripts.written(project.id, project.path), at };
    }));
  });
  app.get<{ Params: { id: string }; Querystring: { key?: string; file?: string; start?: string; end?: string; near?: string } }>('/api/projects/:id/manuscript/source/place', project(), request => {
    const project = store.project(request.params.id), q = request.query;
    return placeSource(manuscripts, project.id, String(q.key || ''), q.file, q.start, q.end, q.near);
  });
  // Notes are not automatically included in prompts. Explicit annotation-management
  // requests can also use the task-scoped paper tools to access manuscript notes.
  app.post<{ Params: { id: string } }>('/api/projects/:id/annotations', project(), async request => {
    const project = store.project(request.params.id), b = request.body as any;
    if (!isRect(b.rect)) throw new Error('Select text or mark a region on the page first.');
    const rects = Array.isArray(b.rects) ? b.rects.filter(isRect) : [];
    if (b.group !== undefined && !isNoteGroup(b.group)) throw new Error('Invalid annotation group.');
    if (b.kind !== undefined && !isMarkKind(b.kind)) throw new Error('Invalid kind of mark.');
    // A quick note's name labels its mark; its comment is the instruction.
    const stamp = b.stamp === undefined ? '' : string(b.stamp, 'Quick note name', 40).replace(/[·\n]/g, ' ').trim();
    // A delete mark may name a replacement; with none, the text simply goes.
    const comment = b.group || b.kind === 'delete' ? optional(b.comment, 'Note') : string(b.comment, 'Note'), key = string(b.key, 'Preview key', 64), page = Number(b.page);
    const selected = typeof b.quote === 'string' ? b.quote : '';
    // The note is saved at once and SyncTeX finds its source afterwards: in a
    // long paper that lookup took seconds, during which the note box spun.
    const located = manuscripts.locate(project.id, key, page, b.rect, rects, selected);
    // A preview that is gone fails at once and is reported; a lookup that
    // takes time is not waited for.
    const settled = await Promise.race([located.then(value => ({ value }), (error: unknown) => ({ error })), new Promise<null>(resolve => setImmediate(() => resolve(null)))]);
    if (settled && 'error' in settled) throw settled.error;
    const document = manuscripts.documentOf(project.id, key);
    const note = store.saveAnnotation({ id: randomUUID(), projectId: project.id, ...(document ? { document } : {}), key, page, rect: b.rect, ...(b.group ? { group: b.group } : {}), ...(b.kind ? { kind: b.kind } : {}), ...(stamp ? { stamp } : {}), ...(rects.length ? { rects } : {}), comment, quote: settled?.value.quote || selected, source: settled?.value.source ?? null, createdAt: Date.now() });
    if (!settled) {
      const lookup = located.then(({ quote, source }) => {
        // Keep what the author changed meanwhile; a note moved to a newer PDF
        // was placed there with its own source.
        const current = store.annotation(project.id, note.id);
        if (current.key === key && !current.taskId) store.saveAnnotation({ ...current, quote: quote || current.quote, source });
      }).catch(() => undefined).finally(() => locating.delete(note.id));
      locating.set(note.id, lookup);
    }
    return note;
  });
  app.post<{ Params: { id: string; note: string } }>('/api/projects/:id/annotations/:note', project(), request => {
    const note = store.annotation(request.params.id, request.params.note);
    if (isTaskReviewNote(note)) throw new Error('Manage this suggestion in its AI review task, or copy it to the manuscript first.');
    if (workspace.annotationSending(note.id)) throw new Error('This note is being sent. Wait for the task to finish creating.');
    if (note.taskId) throw new Error('This note has already been sent.');
    if (note.deletedAt !== undefined) throw new Error('This note has been deleted. Undo the deletion first.');
    const comment = (request.body as any)?.comment;
    return store.saveAnnotation({ ...note, comment: note.group || note.kind === 'delete' ? optional(comment, 'Note') : string(comment, 'Note') });
  });
  app.post<{ Params: { id: string; note: string } }>('/api/projects/:id/annotations/:note/delete', project(), request => {
    const note = store.annotation(request.params.id, request.params.note);
    if (isTaskReviewNote(note)) throw new Error('Manage this suggestion in its AI review task, or copy it to the manuscript first.');
    if (workspace.annotationSending(note.id)) throw new Error('This note is being sent. Wait for the task to finish creating.');
    store.deleteAnnotation(request.params.id, request.params.note); return { ok: true };
  });
  app.post<{ Params: { id: string; note: string } }>('/api/projects/:id/annotations/:note/restore', project(), async request => {
    const note = store.annotation(request.params.id, request.params.note);
    if (isTaskReviewNote(note)) throw new Error('Manage this suggestion in its AI review task, or copy it to the manuscript first.');
    if (workspace.annotationSending(note.id)) throw new Error('This note is being sent. Wait for the task to finish creating.');
    if (note.taskId) throw new Error('This note has already been sent.');
    const { deletedAt: _, ...restored } = note;
    store.saveAnnotation(restored);
    // Return the original order, including any notes added since the deletion.
    return { annotations: await paperNotes(request.params.id) };
  });
  // What the last build reported, placed on its PDF, and the TeX log itself.
  app.get<{ Params: { id: string } }>('/api/projects/:id/manuscript/problems', project(), request => manuscripts.problems(store.project(request.params.id).id));
  app.get<{ Params: { id: string } }>('/api/projects/:id/manuscript/log', project(), (request, reply) => reply.type('text/plain; charset=utf-8').header('Cache-Control', 'no-store').send(manuscripts.log(store.project(request.params.id).id)));
  app.post<{ Params: { id: string }; Body: { failureId?: unknown; agent?: unknown; model?: unknown } }>('/api/projects/:id/manuscript/repair', project(), request => {
    const paper = store.project(request.params.id), body = request.body;
    const selected = body?.agent;
    if (!isAgentId(selected)) throw new Error('Connect the selected agent before diagnosing compilation problems.');
    return manuscripts.repair(paper.id, paper.path, string(body.failureId, 'Compilation failure ID', 64), prompt => workspace.diagnoseLatexBuild(paper.path, prompt, {
      agent: selected, model: typeof body.model === 'string' ? body.model : undefined,
    }));
  });
  // Exact word places for the PDF view's selection layer; immutable per build key.
  app.get<{ Params: { id: string }; Querystring: { key?: string; page?: string } }>('/api/projects/:id/manuscript/words', project(), async (request, reply) => {
    const project = store.project(request.params.id);
    const words = await manuscripts.words(project.id, String(request.query.key || ''), Number(request.query.page));
    return reply.header('Cache-Control', 'private, max-age=31536000, immutable').send(words);
  });
  const pdfName = (name: string, suffix = '') => (name.replace(/[^\w.-]+/g, '-').replace(/^-+|-+$/g, '') || 'manuscript') + suffix + '.pdf';
  app.get<{ Params: { id: string }; Querystring: { key?: string; download?: string } }>('/api/projects/:id/manuscript.pdf', project(), (request, reply) => {
    const project = store.project(request.params.id), pdf = manuscripts.pdf(project.id, String(request.query.key || ''));
    // Each key names one immutable build, so the viewer can cache and range-read it.
    return reply.type('application/pdf').header('Content-Disposition', `${request.query.download === '1' ? 'attachment' : 'inline'}; filename="${pdfName(project.name)}"`).header('Cache-Control', 'private, max-age=31536000, immutable').sendFile(path.basename(pdf), path.dirname(pdf), { cacheControl: false });
  });
  // The same build with the notes on it, as they are now.
  app.get<{ Params: { id: string }; Querystring: { key?: string } }>('/api/projects/:id/manuscript/annotated.pdf', project(), async (request, reply) => {
    const project = store.project(request.params.id), key = String(request.query.key || '');
    const notes = store.annotations(project.id).filter(note => !note.taskId && !isTaskReviewNote(note) && note.key === key)
      // A deletion's card, if any, gives its replacement.
      .map(note => ({ page: note.page, rect: note.rect, rects: note.rects, comment: note.kind === 'delete' && note.comment.trim() ? `→ ${note.comment}` : note.comment, group: note.group, review: Boolean(note.aiReview), author: note.author?.name, ...(note.kind === 'delete' ? { strike: true } : {}) }));
    const pdf = await manuscripts.annotatedPdf(project.id, key, notes);
    return reply.type('application/pdf').header('Content-Disposition', `attachment; filename="${pdfName(project.name, '-annotated')}"`).header('Cache-Control', 'no-store').send(Buffer.from(pdf.buffer, pdf.byteOffset, pdf.byteLength));
  });
  app.post<{ Params: { id: string } }>('/api/requests/:id', { config: { resource: { request: 'id' } } }, request => { workspace.answer(request.params.id, request.body as any); return { ok: true }; });

  // The review viewer also shows a paper's uncommitted changes against its
  // last commit. Papilot answers those routes itself, ahead of the engine's
  // below, and the viewer posts with Papilot's token. Staging writes the
  // index; reverting writes files, so it waits for review actions and commits.
  const changesAccess = { config: { resource: { project: 'projectId' }, csrf: false as const } };
  const changesToken = (request: { headers: Record<string, unknown> }) => {
    if (!equals(String(request.headers['x-review-token'] || ''), options.csrf)) throw Object.assign(new Error('This page has expired. Refresh it and try again.'), { statusCode: 403 });
  };
  const CHANGE_ACTIONS: Record<string, ChangeAction> = { accept: 'stage', unstage: 'unstage', reject: 'revert' };
  app.get<{ Params: { projectId: string }; Querystring: { round?: string } }>('/review/:projectId/api/changes/state', changesAccess, request => {
    const project = store.project(request.params.projectId), round = Number(request.query.round);
    return changes.state(project.id, project.path, options.csrf, Number.isSafeInteger(round) && round > 0 ? round : undefined);
  });
  app.get<{ Params: { projectId: string; number: string } }>('/review/:projectId/api/changes/rounds/:number', changesAccess, request => changes.detail(store.project(request.params.projectId).id, Number(request.params.number)));
  app.get<{ Params: { projectId: string; number: string; unit: string } }>('/review/:projectId/api/changes/rounds/:number/effects/:unit', changesAccess, request =>
    changes.effects(store.project(request.params.projectId).id, Number(request.params.number), request.params.unit));
  app.get<{ Params: { projectId: string; number: string }; Querystring: { check?: string; retry?: string } }>('/review/:projectId/api/changes/rounds/:number/references', changesAccess, request => {
    const project = store.project(request.params.projectId);
    return changes.references(project.id, project.path, Number(request.params.number), request.query.check === '1', request.query.retry === '1');
  });
  app.post<{ Params: { projectId: string; number: string } }>('/review/:projectId/api/changes/rounds/:number/references/confirm', changesAccess, request => {
    changesToken(request);
    const project = store.project(request.params.projectId), b = request.body as any;
    if (typeof b?.id !== 'string' || typeof b?.confirmed !== 'boolean') throw new Error('Choose an entry to confirm.');
    return changes.confirmReference(project.id, project.path, Number(request.params.number), b.id, b.confirmed);
  });
  app.get<{ Params: { projectId: string; number: string } }>('/review/:projectId/changes/pdf/:number', changesAccess, (request, reply) => {
    const pdf = changes.pdf(store.project(request.params.projectId).id, Number(request.params.number));
    return reply.type('application/pdf').sendFile(path.basename(pdf), path.dirname(pdf), { cacheControl: false });
  });
  app.get<{ Params: { projectId: string; number: string; file: string } }>('/review/:projectId/changes/files/:number/:file', changesAccess, (request, reply) => {
    const file = changes.file(store.project(request.params.projectId).id, Number(request.params.number), request.params.file);
    return reply.header('Cache-Control', 'private, max-age=31536000, immutable').type(file.endsWith('.svg') ? 'image/svg+xml' : 'image/png').send(fs.createReadStream(file));
  });
  app.post<{ Params: { projectId: string } }>('/review/:projectId/api/changes/decide', changesAccess, request => {
    changesToken(request);
    const project = store.project(request.params.projectId), b = request.body as any, action = CHANGE_ACTIONS[String(b?.action)];
    if (!action) throw new Error('Choose stage, unstage or revert.');
    const ids = Array.isArray(b.changes) ? b.changes.filter((id: unknown): id is string => typeof id === 'string') : [];
    const act = () => changes.act(project.id, project.path, options.csrf, action, Number(b.round), ids);
    return serialGit(project.id, () => action === 'revert' ? workspace.exclusiveCommit(project.id, act) : act());
  });
  app.post<{ Params: { projectId: string } }>('/review/:projectId/api/changes/undo', changesAccess, request => {
    changesToken(request);
    const project = store.project(request.params.projectId), id = string((request.body as any)?.id, 'Revert ID', 80);
    return serialGit(project.id, () => workspace.exclusiveCommit(project.id, () => changes.undo(project.id, project.path, options.csrf, id)));
  });

  // The complete PDF of a round's new version, for the review's full paper.
  // A round may compile only the changed chapters; this compiles them all once.
  // While it compiles, `passes` names each earlier version that `?pass=`
  // serves: the chapters the round compiled, then each TeX pass of the whole.
  app.get<{ Params: { projectId: string; name: string; round: string }; Querystring: { pass?: string; build?: string } }>('/review/:projectId/pdf/:name/:round', { config: { resource: { project: 'projectId' } } }, async (request, reply) => {
    const project = store.project(request.params.projectId), name = request.params.name, round = Number(request.params.round);
    const pass = request.query.pass === undefined ? null : Number(request.query.pass);
    if (!/^[a-z0-9-]+$/.test(name) || !Number.isSafeInteger(round) || round < 1 || (pass !== null && (!Number.isSafeInteger(pass) || pass < 1 || request.query.build !== undefined))) return reply.code(404).send({ error: 'Review resource not found.' });
    const pdf = request.query.build !== undefined ? await paperBuildPdf(connectReview, project.path, name, round, request.query.build)
      : pass === null ? await fullPaperPdf(connectReview, project.path, name, round, 'after') : await paperPassPdf(connectReview, project.path, name, round, pass);
    return reply.type('application/pdf').sendFile(path.basename(pdf), path.dirname(pdf), { cacheControl: false });
  });
  app.get<{ Params: { projectId: string; name: string; round: string }; Querystring: { after?: string } }>('/review/:projectId/pdf/:name/:round/passes', { config: { resource: { project: 'projectId' } } }, async (request, reply) => {
    const project = store.project(request.params.projectId), name = request.params.name, round = Number(request.params.round), after = Number(request.query.after ?? 0);
    if (!/^[a-z0-9-]+$/.test(name) || !Number.isSafeInteger(round) || round < 1 || !Number.isSafeInteger(after) || after < 0) return reply.code(404).send({ error: 'Review resource not found.' });
    return nextPaperPass(connectReview, project.path, name, round, after);
  });
  app.route<{ Params: { projectId: string; '*': string } }>({
    // The review page posts with the review engine's token rather than Papilot's.
    method: ['GET', 'POST'], url: '/review/:projectId/*', config: { resource: { project: 'projectId' }, csrf: false }, handler: async (request, reply) => {
      const project = store.project(request.params.projectId);
      const route = '/' + request.params['*'];
      if (route.includes('..') || !allowedReviewRoute(route, request.method)) return reply.code(404).send({ error: 'Review resource not found.' });
      const client = await connectReview(project.path);
      if (request.method === 'POST') {
        if (!equals(String(request.headers['x-review-token'] || ''), client.token)) return reply.code(403).send({ error: 'This review page has expired. Refresh it and try again.' });
      }
      const reviewTask = request.method === 'POST' ? store.tasks().find(t => t.projectId === project.id && t.name === route.split('/')[3]) : undefined;
      const writesFiles = /\/source(?:\/options)?$/.test(route) || route.endsWith('/undo') || (route.endsWith('/decide') && (request.body as any)?.action !== 'comment');
      if (request.method === 'POST' && writesFiles) string((request.body as any)?.id, 'Review action ID', 80);
      // The next poll waits for the summary a write is still reading.
      if (request.method === 'GET' && /^\/api\/tasks\/[a-z0-9-]+\/state$/.test(route)) {
        const task = store.tasks().find(t => t.projectId === project.id && t.name === route.split('/')[3]);
        if (task) await settled(workspace, task.id);
      }
      // Accepting leaves the task's worktree alone, and so does undoing an
      // accept or a comment: these go ahead while the agent edits it. Undoing
      // an accept of an earlier round publishes a round of the worktree, so
      // it waits like rejecting.
      // A reject waits for the turn to end in the engine, and so does
      // undoing one still waiting.
      const besideAgent = Boolean(reviewTask?.deferred && AGENT_TURN.includes(reviewTask.status)) && (route.endsWith('/decide')
        ? ['accept', 'reject'].includes((request.body as any)?.action)
        : route.endsWith('/undo') && await client.get<{ undo?: { id: string; kind: string; republish?: boolean; queued?: boolean } | null }>(`${taskRoute(reviewTask!.name)}/state`)
          .then(state => state.undo?.id === (request.body as any)?.id && (state.undo?.kind !== 'reject' || Boolean(state.undo?.queued)) && !state.undo?.republish, () => false));
      if (besideAgent && route.endsWith('/decide') && (request.body as any)?.action === 'reject') (request.body as any).queue = true;
      let settles: string | undefined;
      const forward = async () => {
        const search = new URL(request.url, 'http://localhost').search;
        const response = await fetch(client.url + route + search, {
          method: request.method, headers: { 'Content-Type': 'application/json', 'X-Review-Token': client.token },
          ...(request.method === 'POST' ? { body: JSON.stringify(request.body) } : {}),
          signal: AbortSignal.timeout(120000), redirect: 'error',
        });
        reply.code(response.status);
        const type = response.headers.get('content-type') || 'application/octet-stream';
        const prefix = `/review/${project.id}`;
        if (type.includes('application/json')) {
          const value = await response.json();
          if (reviewTask && writesFiles && !confirmedReviewResponse(response.status, value, reviewTask.name)) throw new Error('The review engine could not confirm this action. Select Check status before continuing.');
          if (!response.ok && request.method === 'POST' && (value as any).error) {
            const task = store.tasks().find(t => t.projectId === project.id && t.name === route.split('/')[3]);
            if (task) store.updateTask(task.id, { error: 'Review action failed: ' + (value as any).error });
          }
          // Saying what the page shows changes nothing about the task.
          if (response.ok && request.method === 'POST' && !route.endsWith('/references/confirm') && !route.endsWith('/look')) {
            const task = store.tasks().find(t => t.projectId === project.id && t.name === route.split('/')[3]);
            if (task) {
              store.updateTask(task.id, { error: null });
              settles = task.id;
            }
          }
          // A round's new version as one complete PDF, which Papilot compiles,
          // lets the review show the changes in the whole paper.
          const round = request.method === 'GET' && response.ok ? /^\/api\/tasks\/([a-z0-9-]+)\/rounds\/(\d+)$/.exec(route) : null;
          if (round) Object.assign(value as object, { pdf: `${prefix}/pdf/${round[1]}/${round[2]}`, passes: `${prefix}/pdf/${round[1]}/${round[2]}/passes` });
          return rewriteReviewJson(value, prefix);
        }
        if (reviewTask && writesFiles) throw new Error('The review engine returned an unexpected response. Select Check status before continuing.');
        reply.type(type);
        if (type.includes('text/html')) return rewriteReviewHtml(await response.text(), prefix);
        const cache = response.headers.get('cache-control'); if (cache && (route.startsWith('/files/') || route.startsWith('/applied/'))) reply.header('Cache-Control', cache);
        if (route.startsWith('/assets/')) reply.header('Cache-Control', 'private, max-age=31536000, immutable');
        return Buffer.from(await response.arrayBuffer());
      };
      if (request.method === 'POST' && !reviewTask) throw new Error('This review task does not belong to this workspace.');
      let result: unknown;
      try { result = await (reviewTask ? workspace.reviewWrite(reviewTask.id, writesFiles, forward, writesFiles ? { route, body: request.body as Record<string, unknown> } : undefined, besideAgent) : forward()); }
      finally { if (settles) settle(workspace, settles); }
      return annotateReviewState(result, store.tasks().filter(task => task.projectId === project.id));
    },
  });

  if (options.dist) await registerFrontend(app, options.dist);
  else app.get('/', (_request, reply) => reply.type('text/plain').send('Papilot: run npm run build, then restart the server.'));
  return app;
}
