Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -329,6 +329,25 @@ mechcheck terms .
It prints what that document calls things, and ends with the `terminology:`
block ready to paste into your group's configuration.

**Files that are not part of the upload** — a figure script's bytecode cache,
an author block the anonymous copy leaves out — go under `ignore_paths`:

```yaml
# mechcheck.yaml
ignore_paths:
- '**/__pycache__/**'
- authors.tex
```

The patterns read as `.gitignore` reads them: `*` stays inside one directory,
`**/` is any number of directories, a trailing `/` means everything under it,
and a pattern without a `/` matches that file name anywhere. The rules that
walk the project tree leave these files out: file names (`VEN006`), finding
the main document, and the `.bib` search when the document names none. A file
the document itself inputs is still read. A project's list replaces the
default one (`build/**`, `out/**`, `.git/**`, `**/node_modules/**`,
`**/__pycache__/**`), as every list in the file does.

**Where this applies.** `mechcheck.yaml` is now read by every layer — the
command line, the standalone page and the Chrome extension all honour the same
file, so a student who drops a project on the page gets the same answer CI
Expand Down
122 changes: 107 additions & 15 deletions browser/mechcheck.html
Original file line number Diff line number Diff line change
Expand Up @@ -2138,6 +2138,38 @@ <h2>Drop your Overleaf project here</h2>
}
}

// ignore_paths, read as .gitignore reads a pattern (the same as
// mechcheck/config.py): `*` stays inside one directory, `**/` is any number of
// directories (none included), a trailing `/` means everything under it, and a
// pattern without a `/` matches the file name in any directory.
const DEFAULT_IGNORE_PATHS = ["build/**", "out/**", ".git/**", "**/node_modules/**", "**/__pycache__/**"];
function ignoreRegex(pattern) {
let p = String(pattern).trim().replace(/\\/g, "/");
while (p.startsWith("./")) p = p.slice(2);
if (p.endsWith("/")) p += "**";
let out = "";
for (let i = 0; i < p.length;) {
if (p.startsWith("**/", i)) { out += "(?:.*/)?"; i += 3; }
else if (p.startsWith("**", i)) { out += ".*"; i += 2; }
else if (p[i] === "*") { out += "[^/]*"; i += 1; }
else if (p[i] === "?") { out += "[^/]"; i += 1; }
else { out += p[i].replace(/[.*+?^${}()|[\]\\/]/g, "\\$&"); i += 1; }
}
return new RegExp("^(?:" + out + ")$");
}
function pathIgnored(rel, patterns) {
rel = String(rel).replace(/\\/g, "/");
while (rel.startsWith("./")) rel = rel.slice(2);
const name = rel.split("/").pop();
for (const raw of patterns || []) {
const pattern = String(raw).trim();
if (!pattern) continue;
const rx = ignoreRegex(pattern);
if (rx.test(rel) || (!pattern.replace(/\/+$/, "").includes("/") && rx.test(name))) return true;
}
return false;
}

/** A key that must be a list, however the file spelled it. */
function asConfigList(value) {
if (Array.isArray(value)) return value;
Expand Down Expand Up @@ -2205,7 +2237,14 @@ <h2>Drop your Overleaf project here</h2>
this.severityOverrides = isPlainObject(this.file.severity) ? this.file.severity : {};
this.ruleOptions = isPlainObject(this.file.rules) ? this.file.rules : {};
this.terminology = asConfigList(this.file.terminology);
// Files the rules that walk the project leave out (#6); a file the
// document inputs is still read. A project's own list replaces the
// default one, as every list in the file does.
this.ignorePaths = Object.prototype.hasOwnProperty.call(this.file, "ignore_paths")
? asConfigList(this.file.ignore_paths) : DEFAULT_IGNORE_PATHS.slice();
}
/** Is this project-relative path one of the project's ignore_paths? */
ignores(path) { return pathIgnored(path, this.ignorePaths); }
enabled(id) {
if (this.enable.some(p => globMatch(id, p))) return true;
if (this.disable.some(p => globMatch(id, p))) return false;
Expand Down Expand Up @@ -3013,7 +3052,11 @@ <h2>Drop your Overleaf project here</h2>
if (DOUBLE_OK.has(m[1].toLowerCase())) continue;
// "\paragraph{Latency} Latency": a heading and the first word of its
// text, not a slip. A group closes between the two words.
if (text.slice(m.index + m[1].length, m.index + m[0].length - m[1].length).includes("}")) continue;
const between = text.slice(m.index + m[1].length, m.index + m[0].length - m[1].length);
if (between.includes("}")) continue;
// "$a$ and $b$ and $c$": the maths between the two words is masked in
// the prose view, but the reader sees it, so the words are not adjacent (#3).
if (/(?<!\\)\$|\\[(\[]/.test(between)) continue;
ctx.add("STY003", `repeated word: '${m[0].trim()}'`,
{ at: m.index, context: ctx.project.excerpt(m.index),
edit: ctx.editSpan(m.index, m.index + m[0].length, m[1], `${m[0]} -> ${m[1]}`) });
Expand Down Expand Up @@ -3323,6 +3366,15 @@ <h2>Drop your Overleaf project here</h2>
/* ---- BIO: verification against Crossref / OpenAlex / DBLP ---- */
const HARD_MISMATCH = 0.55, SOFT_MISMATCH = 0.80;
const workTitle = w => !w ? "" : (Array.isArray(w.title) ? (w.title[0] || "") : (w.title || ""));
/* The title, and the title joined with its subtitle: Crossref keeps the part
after the colon in a separate `subtitle` field ("DeepMimic" and
"example-guided deep reinforcement learning of ..."), and a bib entry carries
both halves, so compare it with both forms (#5). */
function workTitles(w) {
const title = workTitle(w);
const sub = !w ? "" : (Array.isArray(w.subtitle) ? (w.subtitle[0] || "") : (w.subtitle || ""));
return title && sub ? [title, `${title}: ${sub}`] : [title];
}
function workYear(w) {
for (const k of ["issued","published-print","published-online","created"]) {
const parts = ((w && w[k] && w[k]["date-parts"]) || [[null]])[0];
Expand Down Expand Up @@ -3352,8 +3404,8 @@ <h2>Drop your Overleaf project here</h2>
if (!e.doi || !e.title) continue;
const work = await ctx.crossrefByDoi(e.doi);
if (!work) continue;
const actual = workTitle(work);
const score = similarity(e.title, actual);
let score = -1, actual = "";
for (const t of workTitles(work)) { const s = similarity(e.title, t); if (s > score) { score = s; actual = t; } }
if (score >= SOFT_MISMATCH) continue;
ctx.add("BIO002", `\`${e.key}\`: the DOI resolves to "${cleanLatex(actual).slice(0, 80)}" (similarity ${score.toFixed(2)})`,
{ file: e.file, line: e.lineOf("title"), context: e.title.slice(0, 70),
Expand Down Expand Up @@ -3764,12 +3816,45 @@ <h2>Drop your Overleaf project here</h2>
ctx.add("ACC005", `table with about ${rows} rows has no \\Description`, { at: env.start });
}}});

/* Since PDF 1.5 the catalog can live in a compressed object stream
(/Type /ObjStm, FlateDecode), which is what pdfTeX writes by default and
what LaTeX tagging produces; the raw bytes then never show /Marked true.
Returns the inflated text of every object stream (latin1, byte for byte). */
async function inflateObjectStreams(bytes) {
const text = new TextDecoder("latin1").decode(bytes);
const out = [];
const objstm = /\/Type\s*\/ObjStm/g;
let m;
while ((m = objstm.exec(text)) !== null) {
const kw = /stream\r?\n/g;
kw.lastIndex = objstm.lastIndex;
const s = kw.exec(text);
if (!s || s.index - objstm.lastIndex > 4096) continue;
const start = s.index + s[0].length;
let end = text.indexOf("endstream", start);
if (end < 0) continue;
while (end > start && (text[end - 1] === "\n" || text[end - 1] === "\r")) end--;
out.push(await inflate(bytes.subarray(start, end)));
}
return out.join("\n");
}
async function inflate(bytes) {
if (typeof DecompressionStream === "undefined") return "";
const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate")).getReader();
const chunks = [];
try {
for (;;) { const { done, value } = await reader.read(); if (done) break; chunks.push(value); }
} catch (e) { /* junk after the end of the data, or not deflate: keep what came out */ }
return chunks.map(c => new TextDecoder("latin1").decode(c)).join("");
}

rule({ id:"ACC006", title:"PDF is not tagged", cat:"accessibility", sev:SEV.warn, needsBuild:true,
why:"An untagged PDF has no reading order, so assistive technology cannot navigate it. ASSETS requires an accessible PDF at submission.",
fix:"Compile with a recent acmart, or run the publisher's accessibility pipeline.",
run(ctx){ if (!ctx.pdfBytes) return;
const text = new TextDecoder("latin1").decode(ctx.pdfBytes.slice(0, 4e6));
if (/\/Marked\s*true/.test(text)) return;
// The whole file: the catalog of a large PDF can sit near its end.
const text = new TextDecoder("latin1").decode(ctx.pdfBytes);
if (/\/Marked\s*true/.test(text) || /\/Marked\s*true/.test(ctx.pdfObjects || "")) return;
ctx.add("ACC006", "the compiled PDF does not declare itself as tagged (/MarkInfo /Marked true)",
{ file: ctx.pdfName || "the PDF" });
}});
Expand Down Expand Up @@ -4219,7 +4304,7 @@ <h2>Drop your Overleaf project here</h2>
const base = path.split("/").pop();
// What a compile leaves behind; nobody uploads main.synctex.gz.
if (!base || base.startsWith(".") || BUILD_ARTEFACTS.some(s => base.toLowerCase().endsWith(s))
|| allowed.test(base)) continue;
|| allowed.test(base) || ctx.config.ignores(path)) continue;
ctx.add("VEN006", `\`${path}\` ${base.includes(" ") ? "contains a space" : "contains characters TAPS rejects"}`,
{ file: path, fix: "Rename it: letters, digits, dash and underscore only." });
if (++n > 25) return;
Expand Down Expand Up @@ -5780,6 +5865,13 @@ <h2>Drop your Overleaf project here</h2>
let log = null, pdfBytes = null, pdfName = null;
const logs = new Map(), pdfs = new Map();

// The project's own mechcheck.yaml, unless the caller supplied one (or
// passed null to say "check this as it stands, ignore the file"). Read
// first: its ignore_paths decide which files the main file is chosen from.
const projectConfig = options.projectConfig !== undefined
? options.projectConfig : readProjectConfig(files);
const config = new Config(options, (projectConfig && projectConfig.data) || {});

for (const [path, bytes] of files) {
allFiles.set(path, bytes);
if (/\.(tex|cls|sty)$/i.test(path)) sources.set(path, decodeText(bytes));
Expand All @@ -5791,10 +5883,11 @@ <h2>Drop your Overleaf project here</h2>
// Prefer a file that looks like a real root, but never refuse to check
// something just because the preamble is unusual: fall back to the largest
// .tex file and say so rather than making the user guess what went wrong.
let mainPath = options.main || findMainDocument(sources);
const candidates = new Map([...sources].filter(([p]) => !config.ignores(p)));
let mainPath = options.main || findMainDocument(candidates);
let mainGuessed = false;
if (!mainPath) {
const texFiles = [...sources.entries()].filter(([p]) => /\.tex$/i.test(p));
const texFiles = [...candidates.entries()].filter(([p]) => /\.tex$/i.test(p));
if (!texFiles.length) throw new Error("No .tex file in what you dropped in.");
texFiles.sort((a, b) => b[1].length - a[1].length);
mainPath = texFiles[0][0];
Expand Down Expand Up @@ -5823,18 +5916,17 @@ <h2>Drop your Overleaf project here</h2>
}

const project = new TexProject(sources, mainPath);
// The project's own mechcheck.yaml, unless the caller supplied one (or
// passed null to say "check this as it stands, ignore the file").
const projectConfig = options.projectConfig !== undefined
? options.projectConfig : readProjectConfig(files);
const config = new Config(options, (projectConfig && projectConfig.data) || {});

const bib = [];
for (const [path, bytes] of files) if (/\.bib$/i.test(path)) bib.push(...parseBib(decodeText(bytes), path));
for (const [path, bytes] of files)
if (/\.bib$/i.test(path) && !config.ignores(path)) bib.push(...parseBib(decodeText(bytes), path));
// ACC006 reads the PDF's catalog, which can sit in a compressed object
// stream; the rules are synchronous, so those streams are inflated here (#4).
const pdfObjects = pdfBytes ? await inflateObjectStreams(pdfBytes) : "";

const findings = [];
const ctx = {
project, config, bib, log, pdfBytes, pdfName, allFiles,
project, config, bib, log, pdfBytes, pdfName, pdfObjects, allFiles,
cache: {},
ignoreAcronyms: (options.ignoreAcronyms || [])
.concat(asList(config.option("ABB001", "ignore", [])))
Expand Down
72 changes: 70 additions & 2 deletions browser/test-engine.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import { readFileSync, readdirSync, statSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { fileURLToPath } from "node:url";
import { deflateSync } from "node:zlib";

const here = fileURLToPath(new URL(".", import.meta.url));
const repo = join(here, "..");
Expand All @@ -19,8 +20,8 @@ const script = html.slice(html.indexOf("<script>") + 8, html.lastIndexOf("</scri
const engine = script.slice(0, script.indexOf("/* ===================== 7. Interface"));

const module = await import("data:text/javascript;base64," +
Buffer.from(engine + "\nexport { runChecks, applyFixes, TexProject, parseBib, similarity, findMainDocument, RULES, SEV, collectFiles, readZip, parseYamlSubset, readProjectConfig, VENUES, pFromT, pFromF, pFromChi2, pFromZ, pFromR };").toString("base64"));
const { runChecks, applyFixes, parseBib, similarity, findMainDocument, RULES, SEV,
Buffer.from(engine + "\nexport { runChecks, applyFixes, TexProject, parseBib, similarity, findMainDocument, RULES, SEV, collectFiles, readZip, parseYamlSubset, readProjectConfig, VENUES, pFromT, pFromF, pFromChi2, pFromZ, pFromR, pathIgnored };").toString("base64"));
const { runChecks, applyFixes, parseBib, similarity, findMainDocument, RULES, SEV, pathIgnored,
parseYamlSubset, readProjectConfig, VENUES,
pFromT, pFromF, pFromChi2, pFromZ, pFromR } = module;

Expand Down Expand Up @@ -1224,5 +1225,72 @@ console.log("\nreview fixes, October 2026 (the same cases as tests/test_review_f
}
}

console.log("\nfalse positives, November 2026 (the same cases as tests/test_false_positives.py, #3-#6)");
{
const enc = new TextEncoder();
const project = entries => new Map(Object.entries(entries).map(([k, v]) => [k, typeof v === "string" ? enc.encode(v) : v]));
const doc = body => `\\documentclass{article}\n\\begin{document}\n${body}\n\\end{document}\n`;
const run = async (files, o = {}) => runChecks(files, { profile: "paper", verify: false, maxPerRule: 0, ...o });
const rules = async (files, o) => new Set((await run(files, o)).findings.map(f => f.rule));

// STY003: maths between two words is text the reader sees (#3)
check("STY003 words either side of maths are not a repeat",
!(await rules(project({ "main.tex": doc(String.raw`The intervals were $[0.1, 0.2]$ for one arm, and $[0.3, 0.4]$ and $[0.5, 0.6]$ for the others, and \(x\) and \(y\).`) }))).has("STY003"));
check("STY003 a repeat next to maths is still reported",
(await rules(project({ "main.tex": doc("The value $x$ is the the largest.") }))).has("STY003"));

// ACC006: a catalog in a compressed object stream is still a catalog (#4)
const pdf = (catalog, compressed) => {
if (!compressed) return enc.encode(`%PDF-1.4\n1 0 obj\n${catalog}\nendobj\ntrailer\n<< /Root 1 0 R >>\n%%EOF\n`);
const body = deflateSync(Buffer.from("1 0 " + catalog, "latin1"));
const head = enc.encode(`%PDF-1.7\n2 0 obj\n<< /Type /ObjStm /N 1 /First 4 /Filter /FlateDecode /Length ${body.length} >>\nstream\n`);
const tail = enc.encode("\nendstream\nendobj\n3 0 obj\n<< /Type /XRef /Root 1 0 R >>\nendobj\n%%EOF\n");
return new Uint8Array([...head, ...body, ...tail]);
};
const TAGGED = "<< /Type /Catalog /MarkInfo << /Marked true >> /StructTreeRoot 5 0 R >>";
const UNTAGGED = "<< /Type /Catalog /Pages 4 0 R >>";
const acc = async bytes => (await rules(project({ "main.tex": doc("Hello."), "main.pdf": bytes }))).has("ACC006");
check("ACC006 a tagged PDF with object streams is not reported", !(await acc(pdf(TAGGED, true))));
check("ACC006 a tagged PDF without object streams is not reported", !(await acc(pdf(TAGGED, false))));
check("ACC006 an untagged PDF with object streams is reported", await acc(pdf(UNTAGGED, true)));

// BIO002: Crossref keeps the subtitle in its own field (#5)
{
const record = { title: ["DeepMimic"],
subtitle: ["example-guided deep reinforcement learning of physics-based character skills"] };
const fetchJson = async url => url.startsWith("https://api.crossref.org/works/10.1145") ? { message: record } : null;
const bio = async title => (await run(project({
"main.tex": doc("See \\cite{peng2018}.\n\\bibliography{refs}"),
"refs.bib": `@article{peng2018,\n title = {${title}},\n author = {Peng, Xue Bin},\n year = {2018},\n doi = {10.1145/3197517.3201311}\n}\n`,
}), { verify: true, fetchJson })).findings.some(f => f.rule === "BIO002");
check("BIO002 a title with its Crossref subtitle matches",
!(await bio("{DeepMimic}: Example-Guided Deep Reinforcement Learning of Physics-Based Character Skills")));
check("BIO002 a title without the subtitle still matches", !(await bio("{DeepMimic}")));
check("BIO002 a different work is still reported", await bio("Knitting Patterns of the Nineteenth Century"));
}

// ignore_paths is applied by the rules that walk the tree (#6)
{
const pats = ["**/__pycache__/**", "build/**", "*.cpython-313.pyc", "authors.tex", "figs/raw/"];
check("ignore_paths reads like .gitignore",
pathIgnored("scripts/__pycache__/plot.cpython-313.pyc", pats) && pathIgnored("__pycache__/x.pyc", pats)
&& pathIgnored("build/main.log", pats) && pathIgnored("deep/dir/a.cpython-313.pyc", pats)
&& pathIgnored("authors.tex", pats) && pathIgnored("sub/authors.tex", pats) && pathIgnored("figs/raw/a b.png", pats)
&& !pathIgnored("figs/plot.pdf", pats) && !pathIgnored("mybuild/main.log", pats)
&& !pathIgnored("sections/main.tex", ["*/x/*.tex"]) && pathIgnored("sections/x/a.tex", ["*/x/*.tex"]));
const files = extra => project({ "main.tex": doc("Hello."), "scripts/__pycache__/plot.cpython-313.pyc": "",
"my figure.png": "", ...extra });
const ven = async f => (await run(f, { venue: "chi" })).findings.filter(x => x.rule === "VEN006").map(x => x.file).join();
check("VEN006 the default ignore_paths skip the bytecode cache", (await ven(files({}))) === "my figure.png",
await ven(files({})));
check("VEN006 a project's ignore_paths replace the default list",
(await ven(files({ "mechcheck.yaml": "ignore_paths:\n - 'my figure.png'\n" }))) === "scripts/__pycache__/plot.cpython-313.pyc");
const two = extra => project({ "paper.tex": doc("Hello."), "attic/main.tex": doc("Old."), ...extra });
check("an ignored file is not taken for the main document",
(await run(two({}))).stats.main === "attic/main.tex"
&& (await run(two({ "mechcheck.yaml": "ignore_paths:\n - 'attic/'\n" }))).stats.main === "paper.tex");
}
}

console.log(`\n${passed} passed, ${failed} failed`);
process.exit(failed ? 1 : 0);
Loading
Loading