// ============================================================================ // Project : localvm-research // File : web/server.js // Purpose : Research showcase platform — routes and pages (English, light) // Author : Simon-Pierre Boucher // Contact : contact@spboucher.ai // Created : 2026-08-12 // Modified : 2026-08-12 // Platform : macOS / Apple Silicon (arm64) — Node.js (deployed on MacLustr) // License : All rights reserved (research code) // ============================================================================ "use strict"; const fs = require("fs"); const path = require("path"); const express = require("express"); const C = require("./lib/content"); const R = require("./lib/render"); const app = express(); const PORT = process.env.PORT || 8120; app.use("/static", express.static(path.join(__dirname, "public"), { maxAge: "1h" })); app.use(express.urlencoded({ extended: false, limit: "16kb" })); // ---- comments storage (data/ is excluded from deploy rsync — persistent) ---- const DATA_DIR = path.join(__dirname, "data"); const COMMENTS_FILE = path.join(DATA_DIR, "comments.json"); fs.mkdirSync(DATA_DIR, { recursive: true }); function readComments() { try { return JSON.parse(fs.readFileSync(COMMENTS_FILE, "utf8")); } catch { return []; } } function saveComment(entry) { const all = readComments(); all.push(entry); fs.writeFileSync(COMMENTS_FILE, JSON.stringify(all, null, 2)); } const lastPostByIp = new Map(); function page(res, opts) { res.send(R.layout({ ...opts, buildInfo: C.buildInfo() })); } function metaChips(data) { if (!data || !Object.keys(data).length) return ""; const fields = ["document", "author", "created", "modified", "status"]; const chips = fields .filter((f) => data[f]) .map((f) => `${f}${R.esc(data[f])}`) .join(""); return chips ? `
${chips}
` : ""; } // ---------------------------------------------------------------- home app.get("/", (req, res) => { const s = C.stats(); const chart = C.expHChartData(); const log = C.parseLogEntries().slice(-3).reverse(); const phases = [ ["Phase 1 — Literature sweep (§4.1–4.10)", "done", `${s.notes} theme notes · ${s.sources} sources`], ["Phase 2 — State-of-the-art map", C.exists("research/state_of_the_art.md") ? "done" : "pending", "technique taxonomy + overlap analysis"], ["Phase 3 — Research gaps", s.gaps ? "done" : "pending", `${s.gaps} falsifiable approaches (G01–G${String(s.gaps).padStart(2, "0")})`], ["Phase 4 — Candidate ranking", C.exists("research/candidate_ranking.md") ? "done" : "in progress", "10-axis scoring, 3–5 candidates"], ["Phases 5–6 — Framework & micro-experiments", s.experimentsDone ? "in progress" : "pending", `${s.experimentsDone}/${s.experiments} experiments completed`], ["Phase 7 — Candidate prototype", C.exists("experiments/candidate_01/analysis.md") ? "in progress" : "pending", "margin-gated deferred refinement, 1.7B + 32B runs"], ["Phase 11 — Novelty check", C.exists("research/novelty_check.md") ? "done" : "pending", "adversarial prior-art search, 45 sources"], ]; const phaseHtml = phases .map( ([name, st, detail]) => `
  • ${name}${detail}
    ${st}
  • ` ) .join(""); const logHtml = log .map((e) => { const [when, ...rest] = e.title.split(" — "); const excerpt = R.markdownToHtml(e.body.split("\n").slice(0, 6).join("\n"), "research/LOG.md").html; return `

    ${R.esc(rest.join(" — ") || when)}

    ${excerpt}
    `; }) .join(""); const body = `

    Independent systems + ML research · Apple Silicon

    Running LLMs larger than memory
    on a consumer Mac

    Can an existing pretrained model be transformed post-training into an execution representation whose instantaneous working set is dramatically smaller than the full checkpoint — while preserving most of its capabilities? This platform exposes the complete paper trail: hypotheses, notes, code, benchmarks, and raw results.

    total model size ≠ resident size ≠ bytes read per token ≠ parameters required for this token

    ${s.sources}sources reviewed
    ${s.gaps}research gaps identified
    ${s.experimentsDone}/${s.experiments}experiments completed
    ${s.build.commits || "—"}commits

    First result — the SSD substrate is not the bottleneck

    Experiment H measured this Mac's internal NVMe under genuinely cold-cache conditions. Random reads reach the ~13.1 GB/s device ceiling at 1 MiB blocks (QD 8), while 4 KiB single-threaded reads manage only 67 MB/s — a 200× spread that dictates the weight-block layout contract: ≥ 256 KiB blocks at QD ≥ 4. Saturated Metal GPU compute costs < 5%.

    ${R.ssdChartSvg(chart)} Experiment H: hypothesis, method, analysis →

    Research phases

    Latest from the research log

    Full research log →
    ${logHtml}
    `; page(res, { title: "Home", active: "Home", body }); }); // ---------------------------------------------------------------- research index app.get("/research", (req, res) => { const docs = [ ["research/LOG.md", "Research log", "Append-only, auditable record of every question, experiment, result, and decision."], ["research/state_of_the_art.md", "State of the art", "Phase 2 — technique taxonomy across six families with overlap analysis."], ["research/research_gaps.md", "Research gaps", "Phase 3 — falsifiable approaches with kill-numbers, G01–G24."], ["research/candidate_ranking.md", "Candidate ranking", "Phase 4 — 10-axis scoring and selected prototype candidates."], ["research/bibliography.md", "Bibliography", "Every consulted source with URL and access date."], ["research/novelty_check.md", "Novelty check", "Phase 11 — final novelty verification (written last)."], ]; const cards = docs .map(([rel, title, desc]) => { const ok = C.exists(rel); return `

    ${title}

    ${desc}

    ${ok ? "" : 'not yet written'}
    `; }) .join(""); const notes = (C.listDir("research/notes") || []) .filter((f) => f.name.endsWith(".md") && f.name !== "README.md") .map((f) => { const md = C.readMarkdown(f.rel); const sources = md ? (md.content.match(/^- .*http/gm) || []).length : 0; const lines = md ? md.content.split("\n").length : 0; return `

    ${R.esc(f.name.replace(".md", "").replace(/_/g, " "))}

    Phase 1 literature notes — ${lines} lines.

    ${sources} sources
    `; }) .join(""); const body = `

    Research documents

    ${cards}

    Phase 1 literature notes

    ${notes}

    The project charter itself is public: read the full research charter.

    `; page(res, { title: "Research", active: "Research", body }); }); // ---------------------------------------------------------------- markdown viewer app.get(/^\/doc\/(.+)$/, (req, res) => { const rel = req.params[0]; const md = rel.endsWith(".md") ? C.readMarkdown(rel) : null; if (!md) return notFound(res); const crumb = `

    Research / ${R.esc(rel)}

    `; if (rel === "research/LOG.md") { const entries = C.parseLogEntries(); const body = `${crumb} ${R.docHeader({ ...md.data, document: "Research log" }, rel)}

    Append-only, newest first — every question, experiment, result, interpretation, and decision, as required by the charter (§12). ${entries.length} entries.

    ${R.logTimeline(entries, rel)}`; return page(res, { title: "Research log", active: "Research", body }); } const { html, toc } = R.markdownToHtml(md.content, rel); const tocBox = R.tocHtml(toc); const body = `${crumb}${R.docHeader(md.data, rel)}
    ${tocBox}
    ${html}
    `; page(res, { title: md.data.document || rel, active: "Research", body }); }); // ---------------------------------------------------------------- experiments app.get("/experiments", (req, res) => { const exps = C.listExperiments(); const cards = exps .map( (e) => `

    ${R.esc(e.id)}

    ${R.esc(e.purpose)}

    ${e.status} ${e.runs ? `${e.runs} result run${e.runs > 1 ? "s" : ""}` : ""}
    ` ) .join(""); const body = `

    Experiments

    Every experiment carries a registered hypothesis with an explicit falsification criterion (seven-field scientific block), a benchmark implementation, raw results, and an analysis. Negative results are kept.

    ${cards}
    `; page(res, { title: "Experiments", active: "Experiments", body }); }); app.get("/experiments/:id", (req, res) => { const exps = C.listExperiments(); const exp = exps.find((e) => e.id === req.params.id); if (!exp) return notFound(res); const sections = []; for (const [file, title] of [["hypothesis.md", "Hypothesis"], ["analysis.md", "Analysis"], ["README.md", "README"]]) { const md = C.readMarkdown(path.posix.join(exp.rel, file)); if (md && md.content.trim().length > 40) { sections.push(`

    ${title}

    ${metaChips(md.data)}
    ${R.markdownToHtml(md.content, path.posix.join(exp.rel, file)).html}
    `); } } const runs = C.listResultRuns().filter((r) => r.experiment === exp.id || r.experiment.startsWith(exp.id + "_")); const runsHtml = runs.length ? `

    Result runs

    ` : ""; const codeLink = C.exists(path.posix.join(exp.rel, "benchmark.py")) ? `

    View benchmark implementation (benchmark.py) →

    ` : ""; const body = `

    Experiments / ${R.esc(exp.id)}

    ${R.esc(exp.id)}

    ${R.esc(exp.purpose)}

    ${codeLink}${sections.join("")}${runsHtml}`; page(res, { title: exp.id, active: "Experiments", body }); }); // ---------------------------------------------------------------- results app.get("/results", (req, res) => { const runs = C.listResultRuns(); const expIds = C.listExperiments().map((e) => e.id); const rows = runs .map( (r) => { const target = expIds.find((id) => r.experiment === id || r.experiment.startsWith(id + "_")); const expCell = target ? `${r.experiment}` : r.experiment; return `${expCell} ${r.timestamp} ${r.files.map((f) => `${f.name}`).join(" · ")}`; } ) .join(""); const body = `

    Raw results

    Every result is reproducible from commit hash + config + seed + hardware manifest, and each JSON embeds the manifest of the exact machine that produced it.

    ${rows || ''}
    ExperimentRun (UTC)Files
    No result runs yet.
    `; page(res, { title: "Results", active: "Results", body }); }); app.get(/^\/results\/(.+)$/, (req, res) => { const rel = req.params[0].startsWith("results/") ? req.params[0] : "results/" + req.params[0]; const raw = C.readText(rel); if (raw === null) return notFound(res); let bodyContent; if (rel.endsWith(".json")) { const obj = C.readJson(rel); bodyContent = `
    ${R.highlightFile(JSON.stringify(obj, null, 2), "x.json")}
    `; } else { bodyContent = `
    ${R.esc(raw.slice(0, 200000))}
    `; } const body = `

    Results / ${R.esc(rel)}

    ${bodyContent}
    `; page(res, { title: rel, active: "Results", body }); }); // ---------------------------------------------------------------- code browser const CODE_ROOTS = ["src", "tools", "benchmarks", "experiments", "Makefile", "pyproject.toml", "CITATION.cff"]; app.get("/code", (req, res) => { const sections = CODE_ROOTS.map((root) => { if (!C.exists(root)) return ""; const st = C.listDir(root); if (st === null) { return `
  • ${root}
  • `; } const files = C.walk(root, (f) => C.isTextFile(f.rel) && !f.rel.includes("results/")); return `
  • ${root}/
  • `; }).join(""); const body = `

    Code

    Core library (src/localvm/), tooling, benchmark harness, and experiment implementations. Every file carries the project's author header; MLX/Metal is the primary compute path — CUDA is never a core dependency.

    `; page(res, { title: "Code", active: "Code", body }); }); app.get(/^\/file\/(.+)$/, (req, res) => { const rel = req.params[0]; if (!C.isTextFile(rel)) return notFound(res); const raw = C.readText(rel); if (raw === null) return notFound(res); const name = rel.split("/").pop(); const body = `

    Code / ${R.esc(rel)}

    ${R.esc(rel)} ${raw.split("\n").length} lines
    ${R.highlightFile(raw.slice(0, 400000), name)}
    `; page(res, { title: name, active: "Code", body }); }); // ---------------------------------------------------------------- about app.get("/about", (req, res) => { const chart = C.expHChartData(); const m = (chart && chart.manifest) || {}; const chip = m.chip || {}, mem = m.memory || {}, ssd = m.ssd || {}, os = m.os || {}, sw = m.software || {}; const hw = `
    Chip${R.esc(chip.brand || "Apple M5 Max")} — ${chip.cores_performance || 6}P + ${chip.cores_efficiency || 12}E CPU cores, ${chip.gpu_cores || 40} GPU cores
    Unified memory${mem.unified_gb || 48} GB (16 KiB pages)
    Storage${R.esc(ssd.model || "APPLE SSD AP2048Z")} ${R.esc(ssd.size || "2 TB")} — measured ceiling ≈ 13.1 GB/s (iostat-validated)
    OSmacOS ${R.esc(os.version || "27.0")} (${R.esc(os.build || "")})
    StackPython ${R.esc(sw.python || "3.14")}, MLX ${R.esc(sw.mlx || "0.32")}, PyTorch ${R.esc(sw.torch || "2.12")} (MPS), Metal
    `; const body = `

    About this project

    localvm-research is an independent research project by Simon-Pierre Boucher (contact@spboucher.ai) investigating whether pretrained large language models that normally do not fit in a consumer Mac's memory can be transformed — strictly post-training — into execution representations with dramatically smaller instantaneous working sets.

    The methodology is deliberately strict: an append-only research log, registered hypotheses with explicit falsification criteria before any experiment runs, no results reported from uncommitted code, hardware manifests embedded in every result file, and negative results kept and published. The full methodology is codified in the research charter.

    Primary research hardware

    ${hw}

    What would count as a breakthrough

    Failure is an acceptable outcome — the project's charter defines explicit failure criteria, and the log records why an approach died, not just what survived.

    `; page(res, { title: "About", active: "About", body }); }); // ---------------------------------------------------------------- publications app.get("/publications", (req, res) => { const pubs = (C.listDir("docs/publications") || []) .filter((f) => f.name.endsWith(".md")) .map((f) => { const md = C.readMarkdown(f.rel); const abstract = (md.content.split(/## Abstract/i)[1] || "").trim().split("\n\n")[0] || ""; return { rel: f.rel, data: md.data, abstract }; }) .sort((a, b) => String(b.data.created).localeCompare(String(a.data.created))); const cards = pubs.length ? pubs.map((p) => `
    ${R.esc(p.data.number || "report")} ${R.esc(p.data.created || "")} ${R.esc(p.data.status || "draft")}

    ${R.esc(p.data.title || p.rel)}

    ${R.esc(p.data.author || "")}

    ${R.esc(p.abstract.slice(0, 420))}${p.abstract.length > 420 ? "…" : ""}

    Read the full report →
    `).join("") : "

    No publications yet.

    "; const body = `

    Publications

    Official write-ups of the project's results to date — every number traceable to a committed result file with hardware manifest, every figure regenerated from raw data.

    ${cards}
    `; page(res, { title: "Publications", active: "Publications", body }); }); // raw asset serving (figures referenced by publications) app.get(/^\/raw\/(.+)$/, (req, res) => { const rel = req.params[0]; const ext = path.extname(rel).toLowerCase(); const types = { ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg" }; const abs = C.safeResolve(rel); if (!abs || !types[ext] || !require("fs").existsSync(abs)) return notFound(res); res.type(types[ext]).sendFile(abs); }); // ---------------------------------------------------------------- comments app.get("/comments", (req, res) => { const AVATAR_COLORS = ["#2a78d6", "#eb6834", "#1baf7a", "#4a3aa7", "#e87ba4", "#008300"]; const comments = readComments().slice().reverse(); const list = comments.length ? comments.map((c) => { const initial = (c.name || "?").trim()[0].toUpperCase(); const hue = AVATAR_COLORS[[...String(c.name)].reduce((a, ch) => a + ch.charCodeAt(0), 0) % AVATAR_COLORS.length]; return `
    ${R.esc(initial)}
    ${R.esc(c.name)}

    ${R.esc(c.message)}

    `; }).join("") : `
    💬

    No comments yet — be the first to leave one.

    `; const posted = req.query.posted ? `
    Thanks — your comment is posted.
    ` : ""; const err = req.query.err ? `
    ${R.esc(String(req.query.err))}
    ` : ""; const body = `

    Discussion

    Questions, critiques, pointers to prior art we missed, replication reports — all welcome. Comments are public; no account, no tracking.

    ${posted}${err}
    Leave a comment
    Stored on this server only · moderated after the fact

    ${comments.length} comment${comments.length === 1 ? "" : "s"}

    ${list}
    `; page(res, { title: "Comments", active: "Comments", body }); }); app.post("/comments", (req, res) => { const ip = req.headers["x-forwarded-for"] || req.socket.remoteAddress || "?"; const name = String(req.body.name || "").trim().slice(0, 60); const message = String(req.body.message || "").trim().slice(0, 2000); if (String(req.body.website || "").length) return res.redirect("/comments?posted=1"); // honeypot if (!name || message.length < 3) return res.redirect("/comments?err=Name and comment are required."); const last = lastPostByIp.get(ip) || 0; if (Date.now() - last < 30_000) return res.redirect("/comments?err=Please wait a moment between comments."); lastPostByIp.set(ip, Date.now()); saveComment({ name, message, ts: new Date().toISOString() }); res.redirect("/comments?posted=1"); }); // ---------------------------------------------------------------- misc app.get("/health", (req, res) => res.json({ ok: true, app: "localvm-web", author: "Simon-Pierre Boucher" })); function notFound(res) { res.status(404); page(res, { title: "Not found", active: "", body: `

    404

    That page does not exist. Back to home.

    ` }); } app.use((req, res) => notFound(res)); app.listen(PORT, () => console.log(`localvm-web listening on :${PORT}`));