--- name: paperfit description: Diagnose and repair LaTeX paper layout through PaperFit's structured visual closed loop over rendered pages, source-grounded repairs, and visual verification. Use for overflowing figures or tables, float placement, readability, and submission page budgets. --- # PaperFit Execute PaperFit's structured vision-in-the-loop workflow in the current multimodal Codex, Claude Code, or Cursor session. PaperFit organizes visual diagnosis, source-grounded constrained repair, and checklist-based verification; the host model executes this workflow using PaperFit's domain knowledge and tools. Actual rendered-page feedback is required for layout repair and acceptance. An auxiliary vision API or separate agent may supplement this feedback; their absence does not make visual inspection optional. ## Required visual closed loop 1. **Sense:** Compile and render the current manuscript, then actually inspect every physical page to establish the whole-document baseline. Diagnose visible defects using the PaperFit taxonomy and locate their source objects. Verify source/log measurements and auxiliary diagnoses against the pages. If the input cannot render, first restore compilation without claiming a visual repair; enter this visual loop as soon as current pages are available. 2. **Act:** Form a coherent repair candidate grounded in the diagnosis. A candidate is a reviewable source state after one related edit or a batch of related edits, not necessarily a fully repaired manuscript. Preserve a source/assets/PDF checkpoint, apply those changes under the content and template constraints, and state which defects the candidate addresses. Complete this planned batch before its visual verification; intermediate trial builds may help isolate risky edits. 3. **Verify:** Recompile and rerender each changed candidate, then actually inspect every physical page of its current PDF before retaining it or choosing the next repair. Check document-wide flow and visible content on every page at a readable scale; inspect target objects, shifted floats and suspected regressions in detail at useful zoom. Full-page coverage does not require identical inspection depth everywhere. Compare with the checkpoint, distinguishing resolved defects, unchanged pre-existing defects, new or worsened defects, and uncertain findings. Use the visual result to retain progress, revise or roll back; a clean build, page-count match or empty detector report cannot substitute for this step. Missing or unreadable pages leave verification incomplete; inspecting only changed pages does not satisfy this loop. 4. **Record and continue:** Retain a concise per-candidate record under `.paperfit/reports/` of the candidate/checkpoint identity, complete page set and page images actually inspected, diagnosed defects, source changes, visual observations, preservation/page checks, decision and remaining repair queue. Use `keep_and_continue` for verified intermediate progress and reserve `done` for final completion; these describe host decisions, not additional CLI statuses. Do not fabricate page views. Iterate while defects or requested constraints remain unmet within the actual task budget; report incomplete verification honestly. Group related intermediate edits into one candidate; this loop does not require a full API call after every keystroke or waiting until every manuscript defect has been repaired. Whole-document inspection checks the consequences of the current candidate; it is not a zero-defect requirement for every round. A post-hoc evaluator score alone is not evidence that vision participated in repair. If no available model or image tool can inspect the current pages, report the visual-verification gap and do not claim a completed PaperFit visual repair. ## Host authority and useful checks The user's request defines the host's editing authority. For an authorized repair, use normal host tools on any relevant source, included file, local style/class, or project configuration within that scope. The host may reorganize related files, combine changes, or use a repair not listed in PaperFit. Tool support and taxonomy categories are not a permission ceiling. Do not ask the user to reauthorize routine related edits, and do not require a separate acknowledgement for every finding. Treat rules, repair plans and auxiliary visual findings as evidence and advice. Resolve uncertainty by inspecting the source and pages; correct or reject a mistaken diagnosis. Record the reason for consequential decisions, not a ritual response to every suggestion. `human_review`, `approval_required` and unsupported-operation messages describe the optional batch route: the current host should investigate and continue an independently anchored native repair. They do not inherently mean waiting for another human or abandoning the task. Request clarification only when necessary user intent or authority is genuinely missing. Group related edits into a coherent candidate, then compile and inspect its effects. Do not run every tool or regenerate every review after each intermediate keystroke. Ordinary native edits do not need typed-batch approval. Formal source/layout review records are used when seeking acceptance through a supported guarded route; their actual binding requirements still apply. Preserve scientific content, comply with the user's template requirements, and keep source/build/page evidence truthful. A final candidate needs a fresh successful build and inspection of every physical page; uncertainty or an unmet objective cannot be reported as `DONE`. ## Establish the input and objective Find the actual root `.tex` by its `\documentclass` and includes; do not assume `main.tex` or a bundled sample. Preserve author edits and identify the native template and compiler. A page objective applies only when requested: distinguish an upper bound from exact equality and body, reference and appendix scope. Readability, complete visible content, template compliance and the requested pages are joint objectives from the beginning. Use `paperfit --help` for installed tools. If absent, read `packageRoot` from `.paperfit/install-manifest.json` or `$HOME/.paperfit/install-manifest.json`, then use `node "/bin/paperfit.js"` from the paper directory. For a plugin without a receipt, check for `bin/paperfit.js` two directories above this skill. Compatibility bundles may need the installed CLI or source checkout. `paperfit root` locates bundled scripts and docs; they are not in the user's paper. ## Read evidence and question the advice Run `paperfit check-visual --main ""` to compile, render and collect evidence. Preserve the original engine with `--engine xelatex`, `--engine lualatex` or `PAPERFIT_TEX_ENGINE` when needed; an explicit setting overrides a root `% !TeX program = ...` comment, otherwise the fallback is pdfLaTeX. Run `paperfit run scripts/host_context.py --main "" --output .paperfit/reports/host_context.json` for compact findings and exact source anchors. Read the returned artifact paths and open actual page images with the host image tool. Treat each recommendation as a hypothesis: **请你看看这是否是对的**. Check its source object, label, current page and evidence; decide whether to accept, adapt or reject it. Explain the reason when a suggestion is consequential or uncertain. Figure 1 and Table 1 are different objects. A proposed operation being executable does not establish that it improves the paper. Neither a VLM recommendation nor an empty detector report determines correctness. Keep compact structured defect records in the existing reports: a stable defect identifier and A-E category, current page/region, object label or other identity, actual source file/line when resolved, severity, and supporting visual/source/log evidence. Preserve an unresolved anchor as unknown rather than guessing. Mark defects resolved only after the newly rendered pages confirm the repair. The host may correct a category or reject a false finding; record consequential changes without forcing every observation into an executable tool route. Use `pdf_layout_profile` for extracted type sizes, extents and short terminal-line candidates, and `pdf_visibility` for painted text beyond physical page bounds. Inspect actual cells, labels, formulas and paragraph endings before deciding. These tools do not prove scientific equivalence, internal overlap or universal minimum type sizes. Unknown source/PDF binding permits observation but cannot certify a current-source result. If using an external build, run `paperfit isolated-build --main "" --root "" --build-dir "" --engine `. Pass the same `--build-dir` to host context and page-fit. Relative includes resolve at the main file's directory; use `--working-directory project_root` when that is the paper's actual lookup. Keep reports under `.paperfit/reports/` or outside the live and copied source; ordinary `data/` files remain scientific inputs. See `docs/HOST_NATIVE_WORKFLOW.md` for binding and review details. ## Plan and repair with the host Diagnose whole-paper flow before spending attempts on isolated symptoms. Check compilation damage, native-template overrides, large explicit gaps, restrictive float queues, unreadable objects and the last page together. Restore a confirmed broken template setting early rather than compensating for it throughout the paper. Use `paperfit page-fit --main "" --target-pages N --page-policy exact --page-budget-scope with_appendix --output .paperfit/reports/page_fit_01.json` to obtain source opportunities as soon as a page objective is known; a planning report can be useful before the PDF is usable. A current compiled PDF is still necessary for accepting an achieved target. Choose coherent edits based on the actual cause and their interactions. The intervention families in `docs/PAGE_FIT_TOOLBOX.md` are a menu, not a mandatory sequence or one-family-per-attempt limit. The host may combine related placement, wrapping and spacing repairs when it can explain and verify the change. Under a real resource budget, leave room for whole-paper page fitting and final inspection. Restore an executable state first when needed, then prioritize blocking overflow, unreadable or hidden content, broken native-template settings and global flow problems using the current evidence. Plan page count and readability together from the start. Prefer native widths, wrapping, equation breaks and float placement over compensating for an incorrect template with repeated spacing tweaks. A repair plan states which defect it addresses, the affected objects and expected layout tradeoff; it is a hypothesis to test, not a promised page saving. If a trial fails or has no useful effect, change the diagnosis or intervention rather than repeating unchanged checks. Related changes may still be combined within one coherent candidate. - Images: respect `\linewidth` in the real single- or double-column context, aspect ratio and label readability. - Tables: prefer available width, column definitions, wrapping or span over shrinking type. Preserve ordered cells, units, notes, captions and labels. Inspect existing wrappers rather than removing them wholesale. - Floats: choose placement, source anchor or span from the venue and actual queue. A float-only page or several objects on one page can be legitimate. Use barriers only for a demonstrated boundary problem; inspect downstream pages. - Equations: break at actual operators with native alignment, preserving operands, signs, labels and order. Check the resulting printed size and equation number; source size commands alone are insufficient. - Paragraph tails: confirm the actual paragraph and preserve its words during local reflow. Keep a paragraph-setting group active through its paragraph end and check adjacent pages. - References: inspect template/package compatibility before type reduction. For example, redundant `natbib` can override IEEEtran bibliography behavior; preserve citation order and `.bbl` entries while restoring the intended style. Read only the relevant bundled specialist skill (`float-optimizer`, `overflow-repair` or `consistency-polisher`). These are domain advice; custom roles and typed-runtime execution are optional. A normal authorized repair can use host editing tools. Analysis requests stop at evidence and recommendations. An optional guarded batch is `paperfit fix-layout --main "" --apply --max-rounds 3`; without `--apply` it produces a plan. These switches authorize that tool's bounded automation, not all host editing. An unsupported family or unresolved automated anchor does not prohibit an independently anchored host repair. A batch limit is not completion of the user's goal. B1 placement and B2 resizing remain distinct typed operations; using the batch's document-wide B1/endmatter exceptions requires independent host evidence as described in `docs/HOST_NATIVE_WORKFLOW.md`. ## Verify, recover and deliver Preserve source/assets/PDF checkpoints before changing them. Review all changed files as one coherent candidate, including includes and styles. For supported TeX comparisons, use `paperfit run scripts/content_integrity_check.py diff "" "" --output .paperfit/reports/content_diff_01.json` when it helps establish preservation; use distinct paths. Do not repeat unchanged checks after each intermediate edit. Read science, ordinary-prose, layout-policy and action-required channels; also inspect changes that the parser cannot cover. Layout permission does not authorize changing claims, data, citations, assets, captions or body prose, hiding content, adding filler or reducing native body type contrary to the template. Correct or restore confirmed damage or forbidden operations. A protected-token difference can mean automated preservation is unproved rather than proven loss. Preserve the raw report and eligible pending candidate; independently compare exact source objects and compile/render for observation when permitted. Use `scripts/source_review.py` or `scripts/layout_policy.py` for supported hash-bound review. Pending evidence cannot be `DONE`. The word-based semantic hash alone is insufficient; dynamic macros and equivalent structural rewrites need independent content and current-PDF review. Graphic crops/page selections also need source-asset review even if the filename is unchanged. See `docs/HOST_NATIVE_WORKFLOW.md` only when that review is needed. Recompile and rerender each coherent candidate with the original engine. Complete the required visual closed loop by opening every current physical page and comparing target objects and global flow with useful checkpoints before retaining that candidate. Inspect every final physical page after the last source change. Actual current-page evidence takes priority over unsupported critique. The host's multimodal page inspection supplies the required visual feedback; auxiliary API vision may add evidence but does not replace this full-document candidate-level requirement. Apply an explicit candidate acceptance checklist: current source/PDF/page evidence, successful compile and complete rendering, preserved scientific payload and ordinary prose within the authorized scope, native-template compliance, full-page visual inspection, residual/new defect assessment, and the requested page objective. A candidate may be retained as an intermediate checkpoint while an objective remains unmet, but it is not final success. Compare with both its predecessor and a useful verified checkpoint. Do not silently lose previously achieved constraints; record any intermediate tradeoff and continue repairing it. Confirmed content loss, hiding or template violations require correction or recovery. Parser uncertainty calls for retained evidence and independent host review, not an invented PASS. This checklist is required for host judgment; formal typed reviews remain required only when using their guarded route. Decide intermediate retention separately from final completion: - **Keep and continue:** Retain verified improvements when content/template checks pass and the candidate introduces no confirmed regression, even if another intended repair had no effect or some original defects/page objectives remain unmet. Carry those residual defects forward. For example, two fixed tables and an unchanged pre-existing equation overflow are useful progress, not grounds for discarding both table repairs. - **Revise or selectively recover:** If one edit introduces a confirmed problem, first correct or revert that edit while preserving independent verified improvements. Keep source diffs/checkpoints sufficient to identify the edits. Account for interacting changes; do not assume independence. After any correction or partial revert, rebuild, rerender and inspect all pages of the resulting combined candidate before retaining it. If reliable separation is impossible or validation still fails, restore the smallest safe checkpoint, which may be the whole current batch; preserve earlier verified rounds. - **Complete:** Report final completion only with current full-page evidence and all applicable preservation, template, readability and requested page constraints satisfied. An unchanged or newly discovered pre-existing defect does not by itself prove that the current edit regressed; investigate its identity and severity rather than rejecting progress from a raw finding count. The optional batch executor's measured acceptance and rollback rules still apply to that route. It can retain some candidates and stop for host follow-up without marking the task complete; its trial-compile acceptance does not establish full-page visual verification. Continue the authorized native workflow from the retained state when further repair is needed. If a patch or helper fails, inspect which bytes changed and correct or restore the partial edit before continuing. A preparation failure with unchanged source is a tool failure, not a new layout candidate; do not silently count it as measured progress. A declared experimental budget can count reservations differently: keep its original accounting and report the distinction. Repeating a failed check without a new candidate or new evidence does not advance repair. Keep useful candidates rather than assuming the latest is best. `paperfit run scripts/candidate_compare.py --before-pdf --after-pdf --target-pages N --page-policy at_most --output .paperfit/reports/candidate_compare_01.json` measures identities, page-distance changes, type observations and painted-text bounds; it does not rank overall quality or select a winner. Use `exact` only for an equality objective. A readability improvement that adds a page needs further flow repair; a page saved by unreadable labels is a regression. Neither an exact count nor a clean detector finishes a visibly poor paper. After the final source edit, run fresh diagnostics and inspect all final page images. Deliver the matching final PDF with a concise account of improvements, preserved content, remaining defects and any unmet target or inspection limitation. Do not label a one-page miss as success. Continue within the user's actual scope and budget; a runtime `DONE` applies only to its checked artifact.