bootstrap.js

"use strict";
// Locus plugin-first bootstrap (docs\build\PLUGINFIRST_REPORT.md). Plain CommonJS, Node built-ins only, run with
// LM Studio's node.exe. The plugin's main() finds Locus not installed and an install ticket for its stage, checks this
// file's SHA-256 against the one baked into the plugin, writes the baked plan to <run_dir>\state\bootstrap-plan.json
// and runs:
//   <node.exe> bootstrap.js detach --plan <plan file> --plan-sha256 <hex> --ppid <LM Studio's pid>
// "detach" is the launcher's trick (M0): it starts "run" DETACHED and hidden and exits on the child's "spawn" event,
// so LM Studio's tree kill of the plugin no longer reaches the long work. "run":
//   1. takes <state>\bootstrap.lock (pid + start time; stale when the pid is gone or it is older than 45 min);
//   2. records the attempt in the ticket <state>\bootstrap.json;
//   3. verifies this file and every installer file of the repository against the digests baked at staging (no file
//      missing, changed or added);
//   4. runs main\install.cmd /from-plugin <the staged install args> (doctor, msi-chat install: the address, the
//      automatic tunnel site setup when its two files exist, the settings check, autostart on); MSI_CHAT_ALLOW_REAL=1 is
//      set only in install.cmd's own environment and only for a real plan (never under MSI_CHAT_TEST);
//   5. checks the installed release: the verifier on C: (msi_verify.py --check) and every manifest line against the
//      staged digests; only then the ticket says "done";
//   6. with the release's CLI: start, site-ready, pair --first-only --page-only (the QR page for the first phone;
//      exit 10 = a phone is already paired).
// Everything goes to <logs>\bootstrap.log (child output as it is: it never holds a secret; this file logs names, never
// values). <logs>\bootstrap-status.html says where it stands; it is opened in the browser when the install failed or
// needs the owner (never under MSI_CHAT_TEST).
// Exit codes: detach 0 started, 2 spawn error, 3 bad plan, 4 nothing after 8 s, 5 refused; run 0 installed, 3 bad
// plan, 4 failed, 5 refused (no ticket for this stage, or a changed bootstrap.js), 6 another bootstrap holds the lock.
const crypto = require("node:crypto");
const childProcess = require("node:child_process");
const fs = require("node:fs");
const path = require("node:path");

const EXIT = Object.freeze({ OK: 0, USAGE: 2, SPAWN_ERROR: 2, BAD_PLAN: 3, FAILED: 4, TIMEOUT: 4, REFUSED: 5, BUSY: 6 });
const TICKET_FILE = "bootstrap.json";
const LOCK_FILE = "bootstrap.lock";
const PLAN_FILE = "bootstrap-plan.json";
const LOG_FILE = "bootstrap.log";
const STDIO_LOG = "bootstrap_stdio.log";
const STATUS_FILE = "bootstrap-status.html";
const LOCK_MAX_AGE_MS = 45 * 60000;
const LOCK_GRACE_MS = 60000;
const RUN_LIMIT_MS = 30 * 60000;
const INSTALL_TIMEOUT_MS = 20 * 60000;
const STEP_TIMEOUT_MS = 3 * 60000;
const SPAWN_TIMEOUT_MS = 8000;
const MAX_PLAN_BYTES = 200000;
const ATTEMPTS_KEPT = 20;
const ALREADY_PAIRED = 10;

// The test guard (contract rules 4 and 5): a test plan (env.MSI_CHAT_TEST = "1") must carry MSI_CHAT_TEST_ROOT, the
// test's sandbox (one absolute folder, or several separated by ";"); its run folder, plugins root, lms and newt must
// lie under it. python and node may be real binaries anywhere. This file names no place of any PC.
const TEST_ROOT_NAME = "MSI_CHAT_TEST_ROOT";
const GUARDED_ENV_NAMES = Object.freeze(["MSI_CHAT_RUN_DIR", "MSI_CHAT_PLUGINS_ROOT", "MSI_CHAT_LMS", "MSI_CHAT_NEWT_EXE", "MSI_CHAT_PLUGIN_DIR"]);

// The repository files the install runs or copies into the release (repo-relative, '/' separated). Staging hashes
// every file these rules match; the bootstrap refuses a missing, changed or added one.
const FILE_RULES = Object.freeze([
  { dir: "main", match: (n) => /\.(py|cmd|ps1)$/i.test(n) },
  { dir: "server-python", match: (n) => /\.py$/i.test(n) },
  { dir: "web", match: (n) => n.toLowerCase() === "page.html" },
  { dir: "tools", match: (n) => /_(token|secret)_read\.py$/i.test(n) },     // the two sealed-file readers
  { dir: "lmstudio-plugin", match: (n) => ["bootstrap.js", "launcher.js", "package.json"].includes(n.toLowerCase()) },
  { dir: "lmstudio-plugin/install", match: (n) => /\.js$/i.test(n) },
  { dir: "lmstudio-plugin/src", match: (n) => /\.ts$/i.test(n) },
]);
const REQUIRED_FILES = Object.freeze(["main/install.cmd", "main/msi_chat_cli.py", "main/msi_verify.py", "main/msi_install.py",
  "lmstudio-plugin/bootstrap.js", "lmstudio-plugin/launcher.js", "lmstudio-plugin/install/plugin_tool.js"]);

const BASE_ENV_NAMES = Object.freeze(["SystemRoot", "windir", "SystemDrive", "ComSpec", "PATHEXT", "PATH", "TEMP", "TMP",
  "USERPROFILE", "HOMEDRIVE", "HOMEPATH", "APPDATA", "LOCALAPPDATA", "PYTHONDONTWRITEBYTECODE"]);
// MSI_CHAT_PLUGIN_DIR (optional; the Hub plan): the plugin folder that installs Locus, recorded as plugin.installed_dir.
const INSTALL_ENV_NAMES = Object.freeze(["MSI_CHAT_PYTHON", "MSI_CHAT_NODE", "MSI_CHAT_LMS", "MSI_CHAT_RUN_DIR",
  "MSI_CHAT_PLUGINS_ROOT", "MSI_CHAT_NEWT_EXE", "MSI_CHAT_PLUGIN_DIR"]);
const OPTIONAL_ENV_NAMES = Object.freeze(["MSI_CHAT_PLUGIN_DIR"]);
const REQUIRED_ENV_NAMES = Object.freeze(["SystemRoot", "ComSpec", "PATH", "TEMP", "USERPROFILE"]
  .concat(INSTALL_ENV_NAMES.filter((n) => !OPTIONAL_ENV_NAMES.includes(n))));
const TEST_ENV_NAME = /^MSI_CHAT_TEST(_[A-Z0-9_]+)?$|^MSI_CHAT_NEWT_SHA256$/;
const LONG_TOKEN = /[A-Za-z0-9_-]{40,}/;
const SECRET_SHAPE = /[A-Za-z0-9_-]{32,}/g;
const HEX64 = /^[0-9a-f]{64}$/;
const STAGE_ID = /^[0-9a-f]{32}$/;
const REL_PATH = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/;
const VALUE_FLAGS = Object.freeze(["--version", "--data-dir", "--uploads-dir", "--secrets-dir", "--engine-port", "--admin-port",
  "--pair-port", "--lmstudio-home", "--lmstudio-api", "--mode"]);
// The buyer's plan (docs\build\PC_INSTALL_REPORT.md): payload.js, beside this file, downloads and lays down Python, newt
// and the carried program under buyer.root (<profile>\AppData\Local\Locus) before the install; it is loaded only from
// bytes whose SHA-256 is the plan's payload.module_sha256.
const PAYLOAD_MODULE = "payload.js";
const BUYER_REL = "\\AppData\\Local\\Locus";
const PROGRAM_FILE = /^program-([0-9a-f]{16})\.zip$/;
const BARE_FLAGS = Object.freeze(["--real", "--yes"]);
const ARG_VALUE = /^[A-Za-z0-9 :\\._-]{1,260}$/;

function isPlainObject(v) {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

// Same rules as src\settings.ts isAbsWinPath (no "..", ".", empty part, trailing dot or space, stream, wildcard).
function isAbsWinPath(v) {
  if (typeof v !== "string" || v.length < 3 || v.length > 1024) return false;
  if (!/^[A-Za-z]:[\\/]/.test(v)) return false;
  if (/[\u0000-\u001f\u007f"<>|?*%]/.test(v)) return false;
  if (v.indexOf(":", 2) !== -1) return false;
  const parts = v.split(/[\\/]/).slice(1);
  return parts.every((part, i) => (part === "" ? i === parts.length - 1 : part !== "." && part !== ".." && !/[. ]$/.test(part)));
}

function norm(p) {
  return String(p).replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
}

function hasShortName(p) {
  return /(^|\\)[^\\]*~\d/.test(norm(p));
}

function splitRoots(value) {
  return value.split(";").filter((part) => part !== "");
}

// Same rules as src\settings.ts testRootProblem / isUnderTestRoot / testPathProblem (the tests hold both to one table).
function testRootProblem(value) {
  if (typeof value !== "string" || splitRoots(value).length === 0) return TEST_ROOT_NAME + " is missing (set it to the test's sandbox folder)";
  for (const root of splitRoots(value)) {
    if (!isAbsWinPath(root)) return TEST_ROOT_NAME + " holds a path that is not an absolute Windows path";
    if (norm(root).length <= 2) return TEST_ROOT_NAME + " must name a folder, not a whole drive";
    if (hasShortName(root)) return TEST_ROOT_NAME + " holds an 8.3 short name";
  }
  return null;
}

function isUnderTestRoot(p, rootValue) {
  if (testRootProblem(rootValue) !== null || hasShortName(p)) return false;
  const n = norm(p);
  return splitRoots(rootValue).some((root) => n === norm(root) || n.startsWith(norm(root) + "\\"));
}

function testPathProblem(name, p, rootValue) {
  if (typeof p === "string" && hasShortName(p)) return "refused under MSI_CHAT_TEST: " + name + " holds an 8.3 short name";
  if (typeof p !== "string" || !isUnderTestRoot(p, rootValue)) return "refused under MSI_CHAT_TEST: " + name + " is outside " + TEST_ROOT_NAME;
  return null;
}

function lookup(env, name) {
  const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());
  return key === undefined ? undefined : env[key];
}

function sha256Text(text) {
  return crypto.createHash("sha256").update(Buffer.from(text, "utf8")).digest("hex");
}

function sha256File(file, fsApi = fs) {
  const hash = crypto.createHash("sha256");
  const fd = fsApi.openSync(file, "r");
  try {
    const buf = Buffer.alloc(1 << 20);
    let n;
    while ((n = fsApi.readSync(fd, buf, 0, buf.length, null)) > 0) hash.update(buf.subarray(0, n));
  } finally {
    fsApi.closeSync(fd);
  }
  return hash.digest("hex");
}

// --- the plan ---------------------------------------------------------------------------------------------------

// Same rules as src\bootstrap.ts planEnvProblem (the tests hold both to one table).
function planEnvProblem(env, testMode, runDir, python, exists = fs.existsSync) {
  if (!isPlainObject(env)) return "env: not an object";
  const seen = new Set();
  for (const name of Object.keys(env)) {
    if (seen.has(name.toLowerCase())) return "env: a name appears twice (" + name + ")";
    seen.add(name.toLowerCase());
    if (/^LMS_/i.test(name)) return "env: LMS_* names are refused (" + name + ")";
    const isTestName = TEST_ENV_NAME.test(name);
    if (isTestName && !testMode) return "env: " + name + " is a test switch, refused outside MSI_CHAT_TEST";
    if (!isTestName && !BASE_ENV_NAMES.includes(name) && !INSTALL_ENV_NAMES.includes(name)) {
      return "env: " + name + " is not a name the install may get";
    }
    const value = env[name];
    if (typeof value !== "string" || value.length > 8192 || value.includes("\u0000")) return "env: " + name + " is not a plain string";
    if (!isTestName && LONG_TOKEN.test(value)) return "env: " + name + " holds a token-like value";
  }
  for (const name of REQUIRED_ENV_NAMES) {
    const value = lookup(env, name);
    if (typeof value !== "string" || value === "") return "env: " + name + " is missing";
  }
  if (testMode && env.MSI_CHAT_TEST !== "1") return "env: MSI_CHAT_TEST must be 1 under the test";
  const systemRoot = lookup(env, "SystemRoot");
  if (!isAbsWinPath(systemRoot) || !exists(systemRoot.replace(/[\\/]+$/, "") + "\\System32")) {
    return "env: SystemRoot does not hold System32";
  }
  if (norm(lookup(env, "MSI_CHAT_RUN_DIR")) !== norm(runDir)) return "env: MSI_CHAT_RUN_DIR is not the plan's run dir";
  if (norm(lookup(env, "MSI_CHAT_PYTHON")) !== norm(python)) return "env: MSI_CHAT_PYTHON is not the plan's python";
  if (testMode) {
    const root = lookup(env, TEST_ROOT_NAME);
    const rootProblem = testRootProblem(root);
    if (rootProblem !== null) return "refused under MSI_CHAT_TEST: " + rootProblem;
    for (const name of GUARDED_ENV_NAMES) {
      if (OPTIONAL_ENV_NAMES.includes(name) && lookup(env, name) === undefined) continue;
      const problem = testPathProblem(name, lookup(env, name), root);
      if (problem !== null) return problem;
    }
  }
  return null;
}

function installArgsProblem(args, real) {
  if (!Array.isArray(args) || args.length > 40) return "install_args: not a list";
  let sawReal = false;
  for (let i = 0; i < args.length; i += 1) {
    const arg = args[i];
    if (BARE_FLAGS.includes(arg)) {
      sawReal = sawReal || arg === "--real";
      continue;
    }
    if (VALUE_FLAGS.includes(arg)) {
      const value = args[i + 1];
      if (typeof value !== "string" || !ARG_VALUE.test(value) || /^[-/]/.test(value)) return "install_args: " + arg + " needs a plain value";
      i += 1;
      continue;
    }
    return "install_args: " + JSON.stringify(arg) + " is not accepted";
  }
  if (sawReal !== real) return real ? "install_args: a real plan needs --real" : "install_args: --real in a test plan";
  return null;
}

function filesProblem(files) {
  if (!isPlainObject(files) || Object.keys(files).length === 0 || Object.keys(files).length > 2000) return "files: not a list of digests";
  for (const [rel, digest] of Object.entries(files)) {
    if (!REL_PATH.test(rel) || rel.split("/").some((p) => p === "." || p === "..")) return "files: a bad path " + JSON.stringify(rel);
    if (typeof digest !== "string" || !HEX64.test(digest)) return "files: a bad digest for " + rel;
  }
  return null;
}

// A buyer's plan (payload + buyer.root): every place of the install is the one its root gives (src\hub.ts and
// payload.js layoutOf hold the same table), the root is <USERPROFILE>\AppData\Local\Locus, and the install is --mode buyer.
// null when fine, or when the plan is not a buyer's.
function buyerPlanProblem(raw, testMode) {
  if (raw.payload === undefined && raw.buyer === undefined) return null;
  const buyer = raw.buyer;
  const profile = lookup(raw.env || {}, "USERPROFILE");
  if (!isPlainObject(buyer) || !isAbsWinPath(buyer.root) || typeof profile !== "string" ||
      norm(buyer.root) !== norm(profile.replace(/[\\/]+$/, "") + BUYER_REL)) {
    return "buyer.root is not <USERPROFILE>\\AppData\\Local\\Locus";
  }
  const payload = raw.payload;
  const program = isPlainObject(payload) && isPlainObject(payload.program) && typeof payload.program.file === "string" ?
    PROGRAM_FILE.exec(payload.program.file) : null;
  if (!isPlainObject(payload) || typeof payload.module_sha256 !== "string" || !HEX64.test(payload.module_sha256) || program === null ||
      !isPlainObject(payload.newt)) {
    return "payload: not the buyer payload (module_sha256, program.file, newt)";
  }
  const root = buyer.root.replace(/[\\/]+$/, "");
  const newtName = testMode && payload.newt.name === "newt.py" ? "newt.py" : "newt.exe";
  // a user folder with a space: Python in the space-free root <ProgramData>\Locus\u<id> (src\hub.ts spaceFreeRoot)
  let pyBase = root;
  if (/\s/.test(root)) {
    const programData = testMode ? lookup(raw.env, "MSI_CHAT_TEST_PROGRAMDATA") : String(lookup(raw.env, "SystemRoot") || "").slice(0, 2) + "\\ProgramData";
    const expected = typeof programData === "string" && isAbsWinPath(programData) ? spaceFreeRoot(profile, programData) : null;
    if (expected === null || typeof buyer.space_free !== "string" || norm(buyer.space_free) !== norm(expected) || /\s/.test(buyer.space_free)) {
      return "buyer.space_free is not this user's space-free root";
    }
    pyBase = buyer.space_free;
  } else if (buyer.space_free !== undefined) {
    return "buyer.space_free is only for a user folder with a space";
  }
  if (norm(raw.repo) !== norm(root + "\\program\\" + program[1])) return "repo is not the buyer's program folder";
  if (norm(raw.run_dir) !== norm(root + "\\run")) return "run_dir is not the buyer's run folder";
  if (norm(raw.python) !== norm(pyBase + "\\python\\python.exe")) return "python is not the buyer's runtime";
  if (norm(lookup(raw.env, "MSI_CHAT_NEWT_EXE")) !== norm(root + "\\newt\\" + newtName)) return "env: MSI_CHAT_NEWT_EXE is not the buyer's newt";
  const sorted = (o) => JSON.stringify(Object.entries(isPlainObject(o) ? o : {}).sort());
  if (!isPlainObject(payload.program.files) || sorted(raw.files) !== sorted(payload.program.files)) {
    return "files: a buyer's plan verifies exactly the payload's program files";
  }
  const args = Array.isArray(raw.install_args) ? raw.install_args : [];
  const modes = args.map((a, i) => (a === "--mode" ? args[i + 1] : null)).filter((m) => m !== null);
  if (modes.length !== 1 || modes[0] !== "buyer") return "install_args: a buyer's plan installs with --mode buyer, once";
  return null;
}

// Same as payload.js spaceFreeRoot and src\hub.ts spaceFreeRoot (one table in the tests).
function spaceFreeRoot(profile, programData) {
  const id = crypto.createHash("sha256").update(String(profile).replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase(), "utf8").digest("hex");
  return String(programData).replace(/[\\/]+$/, "") + "\\Locus\\u" + id.slice(0, 16);
}

// Checks a parsed plan. Returns {ok: true, plan} or {ok: false, reason}. Never throws.
function checkPlan(raw, options = {}) {
  const fail = (reason) => ({ ok: false, reason: "plugin-first plan: " + reason });
  try {
    if (!isPlainObject(raw)) return fail("not a JSON object");
    if (raw.schema !== 1) return fail("schema is not 1");
    if (typeof raw.stage_id !== "string" || !STAGE_ID.test(raw.stage_id)) return fail("stage_id is not 32 hex characters");
    for (const field of ["repo", "run_dir", "python", "node"]) {
      if (!isAbsWinPath(raw[field])) return fail(field + " is not an absolute path");
    }
    if (!/(^|\\)python\.exe$/i.test(raw.python) || raw.python.includes(" ")) return fail("python must be a python.exe path without spaces");
    const boot = raw.bootstrap;
    if (!isPlainObject(boot) || !isAbsWinPath(boot.path) || !/(^|\\)bootstrap\.js$/i.test(boot.path)) return fail("bootstrap.path is not a bootstrap.js path");
    if (typeof boot.sha256 !== "string" || !HEX64.test(boot.sha256)) return fail("bootstrap.sha256 is not 64 hex characters");
    if (!Number.isInteger(raw.max_per_day) || raw.max_per_day < 1 || raw.max_per_day > 10) return fail("max_per_day is not 1-10");
    if (typeof raw.real !== "boolean") return fail("real is not true or false");
    const testMode = options.testMode === true || (isPlainObject(raw.env) && raw.env.MSI_CHAT_TEST === "1");
    if (raw.real === testMode) return fail(testMode ? "a real plan under MSI_CHAT_TEST" : "a plan that is not real outside MSI_CHAT_TEST");
    const runDir = raw.run_dir.replace(/[\\/]+$/, "");
    const problem = planEnvProblem(raw.env, testMode, runDir, raw.python, options.exists || fs.existsSync) ||
      (testMode ? testPathProblem("run_dir", runDir, lookup(raw.env, TEST_ROOT_NAME)) : null) ||
      filesProblem(raw.files) || installArgsProblem(raw.install_args, raw.real) || buyerPlanProblem(raw, testMode);
    if (problem) return fail(problem);
    return { ok: true, plan: Object.freeze(Object.assign({}, raw, { run_dir: runDir, testMode })) };
  } catch (err) {
    return fail("unreadable (" + (err && err.name) + ")");
  }
}

// --- the installer files ---------------------------------------------------------------------------------------

// {files: {rel: sha256}, problems: [...]} for every file the rules match (links are refused, never followed).
function collectFiles(repo, fsApi = fs) {
  const files = {};
  const problems = [];
  for (const rule of FILE_RULES) {
    const dir = path.win32.join(repo, ...rule.dir.split("/"));
    let entries = [];
    try {
      entries = fsApi.readdirSync(dir, { withFileTypes: true });
    } catch (err) {
      continue;
    }
    for (const entry of entries) {
      if (!rule.match(entry.name)) continue;
      const rel = rule.dir + "/" + entry.name;
      if (entry.isSymbolicLink()) {
        problems.push("a link or junction: " + rel);
      } else if (entry.isFile()) {
        files[rel] = sha256File(path.win32.join(dir, entry.name), fsApi);
      }
    }
  }
  for (const rel of REQUIRED_FILES) {
    if (!(rel in files)) problems.push("missing: " + rel);
  }
  return { files, problems };
}

// Problems ([] = the repository is what was staged): a missing, changed or added installer file.
function verifyFiles(repo, expected, fsApi = fs) {
  const now = collectFiles(repo, fsApi);
  const problems = now.problems.filter((p) => !p.startsWith("missing: "));
  for (const [rel, digest] of Object.entries(expected)) {
    if (!(rel in now.files)) problems.push("missing: " + rel);
    else if (now.files[rel] !== digest) problems.push("changed: " + rel);
  }
  for (const rel of Object.keys(now.files)) {
    if (!(rel in expected)) problems.push("added: " + rel);
  }
  return problems.sort();
}

// The repository file a release file came from (msi_install.lay_down_release), null for newt (pinned by install.cmd
// and the CLI), undefined for a file no staged repository gives.
function repoPathOf(rel) {
  if (/^bin\/newt\.(exe|py)$/i.test(rel)) return null;
  if (/^(main|server-python|tools)\/[^/]+$/.test(rel) || rel === "web/page.html") return rel;
  if (rel === "plugin/launcher.js") return "lmstudio-plugin/launcher.js";
  return undefined;
}

// Every line of the release's MANIFEST.sha256 must be a staged file with the staged digest.
function releaseProblems(releaseDir, planFiles, fsApi = fs) {
  let text;
  try {
    text = fsApi.readFileSync(path.win32.join(releaseDir, "MANIFEST.sha256"), "utf8");
  } catch (err) {
    return ["the release has no MANIFEST.sha256"];
  }
  const problems = [];
  let lines = 0;
  for (const line of text.split("\n")) {
    if (line === "") continue;
    lines += 1;
    const m = /^([0-9a-f]{64}) {2}(.+)$/.exec(line);
    if (!m) {
      problems.push("a malformed manifest line");
      continue;
    }
    const from = repoPathOf(m[2]);
    if (from === null) continue;
    if (from === undefined) problems.push(m[2] + " is not a file of the staged repository");
    else if (!(from in planFiles)) problems.push(m[2] + " was not in the repository when the plugin was staged");
    else if (planFiles[from] !== m[1]) problems.push(m[2] + " differs from the staged repository");
  }
  if (lines === 0) problems.push("the release manifest is empty");
  return problems;
}

// --- the lock and the ticket -----------------------------------------------------------------------------------

function readText(fsApi, file) {
  try {
    return fsApi.readFileSync(file, "utf8");
  } catch (err) {
    return null;
  }
}

function mtimeOf(fsApi, file) {
  try {
    return fsApi.statSync(file).mtimeMs;
  } catch (err) {
    return null;
  }
}

function isAlive(pid) {
  try {
    process.kill(pid, 0);
    return true;
  } catch (err) {
    return err.code === "EPERM";
  }
}

// Same rules as src\bootstrap.ts lockState (the tests hold both to one table).
function lockState(text, mtimeMs, nowMs, alive) {
  if (text === null) return { state: "none", pid: null, started: null };
  let raw = null;
  try {
    raw = JSON.parse(text);
  } catch (err) {
    raw = null;
  }
  const pid = isPlainObject(raw) && Number.isInteger(raw.pid) ? raw.pid : null;
  const started = isPlainObject(raw) && typeof raw.started === "string" ? raw.started : null;
  const startedMs = started === null ? NaN : Date.parse(started);
  if (pid === null || pid <= 0 || Number.isNaN(startedMs)) {
    const young = mtimeMs !== null && nowMs - mtimeMs < LOCK_GRACE_MS;
    return { state: young ? "fresh" : "stale", pid, started };
  }
  if (!alive(pid) || nowMs - startedMs > LOCK_MAX_AGE_MS || startedMs - nowMs > LOCK_GRACE_MS) return { state: "stale", pid, started };
  return { state: "fresh", pid, started };
}

// Creates the lock exclusively. A stale lock is removed only when it is still the one judged stale, then taken.
function acquireLock(stateDir, info, deps) {
  const file = path.win32.join(stateDir, LOCK_FILE);
  const text = JSON.stringify({ schema: 1, pid: info.pid, started: info.started, stage_id: info.stageId, ppid: info.ppid });
  let view = { state: "fresh", pid: null, started: null };
  for (let round = 0; round < 2; round += 1) {
    try {
      const fd = deps.fs.openSync(file, "wx");
      try {
        deps.fs.writeSync(fd, text);
      } finally {
        deps.fs.closeSync(fd);
      }
      return { ok: true, text };
    } catch (err) {
      if (err.code !== "EEXIST") throw err;
    }
    const seen = readText(deps.fs, file);
    view = lockState(seen, mtimeOf(deps.fs, file), deps.now().getTime(), deps.alive);
    if (view.state !== "stale" || round > 0 || readText(deps.fs, file) !== seen) break;
    try {
      deps.fs.unlinkSync(file);
    } catch (err) {
      if (err.code !== "ENOENT") break;
    }
  }
  return { ok: false, view };
}

function releaseLock(stateDir, text, fsApi = fs) {
  const file = path.win32.join(stateDir, LOCK_FILE);
  if (readText(fsApi, file) === text) {
    try {
      fsApi.unlinkSync(file);
    } catch (err) {
      // already gone
    }
  }
}

function writeJsonAtomic(fsApi, file, value) {
  const tmp = file + "." + process.pid + ".tmp";
  fsApi.writeFileSync(tmp, JSON.stringify(value, null, 1) + "\n", "utf8");
  for (let i = 0; ; i += 1) {
    try {
      fsApi.renameSync(tmp, file);
      return;
    } catch (err) {
      if (i >= 10 || (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES")) throw err;
      Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 100);
    }
  }
}

function readJson(fsApi, file) {
  const text = readText(fsApi, file);
  if (text === null) return null;
  try {
    const value = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
    return isPlainObject(value) ? value : null;
  } catch (err) {
    return null;
  }
}

// --- reasons, the log and the status page ------------------------------------------------------------------------

// A reason for the ticket, plugin.jsonl and the status page: one line, at most 400 characters, and anything shaped
// like a key or token (32+ characters of [A-Za-z0-9_-]) replaced. The CLI never prints secrets; this is a second net.
function sanitizeReason(text) {
  return String(text || "").replace(/[\r\n\t]+/g, " ").replace(SECRET_SHAPE, "[...]").replace(/\s{2,}/g, " ").trim().slice(0, 400);
}

// The most telling line of a step's output: the last "[fail]" line, else the last "locus ..." error (an older CLI's
// "msi-chat ..." too), else the last non-empty line.
function telltale(output) {
  const lines = String(output || "").split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
  const pick = [...lines].reverse().find((l) => /^\[fail\]/.test(l) && !/the step above ended/.test(l)) ||
    [...lines].reverse().find((l) => /^(?:locus|msi-chat) [a-z-]+: /.test(l) || /^Locus: /.test(l) || /cannot reach|refused|failed/i.test(l)) ||
    lines[lines.length - 1] || "";
  return sanitizeReason(pick);
}

function makeLog(fsApi, file, now) {
  const write = (text) => {
    try {
      fsApi.appendFileSync(file, text);
    } catch (err) {
      // the log must never stop the install
    }
  };
  const log = (line) => write("[" + now().toISOString() + "] bootstrap: " + line + "\n");
  log.raw = write;
  return log;
}

function escapeHtml(text) {
  return String(text).replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]);
}

function statusHtml(view) {
  const items = view.lines.map((l) => "<li>" + escapeHtml(l) + "</li>").join("\n");
  return "<!DOCTYPE html>\n<html lang=\"en\"><head><meta charset=\"utf-8\"><title>Locus: " + escapeHtml(view.title) +
    "</title>\n<style>body{font-family:system-ui,sans-serif;max-width:46rem;margin:2rem auto;padding:0 1rem;line-height:1.45}" +
    "h1{font-size:1.4rem}.s{padding:.6rem .8rem;border-radius:.4rem;background:" + (view.ok ? "#e7f6ea" : "#fdecea") +
    "}code{background:#f2f2f2;padding:0 .2rem}</style></head>\n<body><h1>Locus: " + escapeHtml(view.title) + "</h1>\n" +
    "<p class=\"s\">" + escapeHtml(view.summary) + "</p>\n<ul>\n" + items + "\n</ul>\n<p>Updated " + escapeHtml(view.at) +
    ". This page is not refreshed by itself: open it again for news.</p></body></html>\n";
}

// The Windows folder of this process (the plan's env, under which "run" was started): never a path written here.
function systemRoot(env) {
  const root = lookup(env || {}, "SystemRoot") || lookup(process.env, "SystemRoot");
  return typeof root === "string" && root !== "" ? root : null;
}

function openPage(file, testMode, log) {
  if (testMode) {
    log("(MSI_CHAT_TEST: no browser opened) " + file);
    return;
  }
  const root = systemRoot();
  if (root === null) {
    log("the status page could not be opened: no SystemRoot");
    return;
  }
  try {
    childProcess.spawn(path.win32.join(root, "explorer.exe"), [file], { detached: true, stdio: "ignore" }).unref();
  } catch (err) {
    log("the status page could not be opened: " + (err && err.code));
  }
}

// --- the steps ----------------------------------------------------------------------------------------------------

function killTree(pid, env) {
  const root = systemRoot(env);
  if (!pid || root === null) return;
  childProcess.spawnSync(path.win32.join(root, "System32", "taskkill.exe"), ["/pid", String(pid), "/T", "/F"],
    { stdio: "ignore", windowsHide: true, timeout: 15000 });
}

// Runs one child (hidden, stdin NUL), its output appended to the log as it comes. Resolves {code, output, timedOut}.
function runStep(command, args, options, timeoutMs, log) {
  return new Promise((resolve) => {
    let output = "";
    let done = false;
    let exitCode = null;
    let timer = null;
    const finish = (extra) => {
      if (done) return;
      done = true;
      clearTimeout(timer);
      resolve(Object.assign({ code: exitCode, output }, extra || {}));
    };
    let child;
    try {
      child = childProcess.spawn(command, args, Object.assign({}, options, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true }));
    } catch (err) {
      finish({ code: null, error: String((err && err.code) || "spawn error") });
      return;
    }
    const take = (d) => {
      const s = String(d);
      log.raw(s);
      if (output.length < 1000000) output += s;
    };
    child.stdout.on("data", take);
    child.stderr.on("data", take);
    child.once("error", (err) => finish({ code: null, error: String((err && err.code) || "spawn error") }));
    child.once("exit", (code) => {
      exitCode = code;
      setTimeout(() => finish(), 1500);        // a grandchild holding the pipe must not hold the bootstrap
    });
    child.once("close", () => finish());
    timer = setTimeout(() => {
      killTree(child.pid, options.env || {});
      finish({ code: null, timedOut: true });
    }, timeoutMs);
  });
}

function codeText(r) {
  if (r.timedOut) return "no end in time (stopped)";
  if (r.error) return "a start error (" + r.error + ")";
  return "exit code " + r.code;
}

function quoteArg(arg) {
  return arg.includes(" ") ? "\"" + arg + "\"" : arg;
}

// cmd.exe /d /s /c ""<repo>\main\install.cmd" /from-plugin <args>"  (the args were checked: no quote, % or & inside)
function installCommand(plan) {
  const script = path.win32.join(plan.repo, "main", "install.cmd");
  const line = "/d /s /c \"\"" + script + "\" /from-plugin" + plan.install_args.map((a) => " " + quoteArg(a)).join("") + "\"";
  return { command: lookup(plan.env, "ComSpec"), args: [line] };
}

function installEnv(plan) {
  const env = Object.assign({}, plan.env);
  if (plan.real === true && plan.testMode !== true && env.MSI_CHAT_TEST === undefined) env.MSI_CHAT_ALLOW_REAL = "1";
  return env;
}

function settingsProblem(settings, plan) {
  if (!settings) return "settings.json was not written";
  if (norm(settings.run_dir) !== norm(plan.run_dir)) return "settings.json names another run folder";
  if (norm(settings.python) !== norm(plan.python)) return "settings.json names another python";
  if (!isAbsWinPath(settings.secrets_dir) || norm(settings.keepalive) !== norm(path.win32.join(settings.secrets_dir, "msi_verify.py"))) {
    return "settings.json's keepalive is not the verifier on C:";
  }
  if (typeof settings.version !== "string" || !/^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/.test(settings.version)) return "settings.json has no version";
  return null;
}

// payload.js from the plugin's folder, compiled from the very bytes whose SHA-256 is the plan's payload.module_sha256.
function loadPayloadModule(plan, fsApi = fs) {
  const file = path.win32.join(path.win32.dirname(plan.bootstrap.path), PAYLOAD_MODULE);
  let bytes;
  try {
    bytes = fsApi.readFileSync(file);
  } catch (err) {
    return { ok: false, reason: "the plugin's payload.js cannot be read: install the plugin again from LM Studio" };
  }
  if (crypto.createHash("sha256").update(bytes).digest("hex") !== plan.payload.module_sha256) {
    return { ok: false, reason: "payload.js differs from the digest baked into this plugin: install the plugin again from LM Studio" };
  }
  const Module = require("node:module");
  const mod = new Module(file, module);
  mod.filename = file;
  mod.paths = [];
  mod._compile(bytes.toString("utf8"), file);
  return { ok: true, mod: mod.exports };
}

// The buyer's payload laid down (payload.js layDown), or why not. The loaded module stays in ctx for the uninstaller.
async function layPayload(ctx) {
  const loaded = loadPayloadModule(ctx.plan, ctx.deps.fs);
  if (!loaded.ok) return { ok: false, step: "verify", reason: loaded.reason };
  ctx.payloadModule = loaded.mod;
  ctx.stopLocus = () => stopForUpdate(ctx);
  return loaded.mod.layDown(ctx);
}

// Review M4: an update lays a new Python or newt down over an installed Locus: it is stopped first, through its own
// release's CLI (start brings it back after the install). Nothing installed yet: nothing to stop.
async function stopForUpdate(ctx) {
  const { plan, deps, log } = ctx;
  const settingsPath = path.win32.join(plan.run_dir, "settings.json");
  const settings = readJson(deps.fs, settingsPath);
  if (!settings || typeof settings.python !== "string" || !deps.fs.existsSync(settings.python)) return { ok: true };
  const cli = path.win32.join(plan.run_dir, "releases", String(settings.version), "main", "msi_chat_cli.py");
  if (!deps.fs.existsSync(cli)) return { ok: true };
  log("update: stopping Locus to lay the new runtime down");
  const r = await deps.runStep(settings.python, ["-I", "-B", "-X", "utf8", cli, "--settings", settingsPath, "stop", "--now"],
    { env: Object.assign({}, plan.env), cwd: plan.run_dir }, STEP_TIMEOUT_MS, log);
  if (r.code === 0 || r.code === 1) return { ok: true };
  return { ok: false, step: "update", reason: "Locus could not be stopped for the update (" + codeText(r) + "): " + telltale(r.output) };
}

async function installSteps(ctx) {
  const { plan, deps, log } = ctx;
  if (sha256File(deps.selfPath, deps.fs) !== plan.bootstrap.sha256) return { ok: false, step: "verify", reason: "bootstrap.js differs from the staged one" };
  if (plan.payload !== undefined) {
    const laid = await deps.layPayload(ctx);
    if (!laid.ok) return { ok: false, step: laid.step || "download", reason: laid.reason };
    log("payload: Python, newt and the Locus program are laid down under " + plan.buyer.root);
  }
  const problems = verifyFiles(plan.repo, plan.files, deps.fs);
  if (problems.length > 0) {
    return { ok: false, step: "verify", reason: "the repository's installer files are not the staged ones (" +
      problems.slice(0, 4).join("; ") + (problems.length > 4 ? "; ..." : "") + "): " +
      (plan.payload !== undefined ? "install the plugin again from LM Studio" : "stage again with main\\install.cmd /plugin-first") };
  }
  log("verify: " + Object.keys(plan.files).length + " installer files match the staged digests");
  const cmd = installCommand(plan);
  const env = installEnv(plan);
  log("install: install.cmd /from-plugin " + plan.install_args.join(" ") + " (environment names: " + Object.keys(env).sort().join(", ") + ")");
  const inst = await deps.runStep(cmd.command, cmd.args, { env, cwd: plan.run_dir, windowsVerbatimArguments: true }, INSTALL_TIMEOUT_MS, log);
  if (inst.code !== 0) return { ok: false, step: "install", reason: "install.cmd ended with " + codeText(inst) + ": " + telltale(inst.output) };
  const settingsPath = path.win32.join(plan.run_dir, "settings.json");
  const settings = readJson(deps.fs, settingsPath);
  const bad = settingsProblem(settings, plan);
  if (bad) return { ok: false, step: "release", reason: bad };
  const check = await deps.runStep(settings.python, ["-I", "-B", "-X", "utf8", settings.keepalive, "--check", "--settings", settingsPath],
    { env: Object.assign({}, plan.env), cwd: plan.run_dir }, STEP_TIMEOUT_MS, log);
  if (check.code !== 0) return { ok: false, step: "release", reason: "the verifier on C: refused the installed release (" + codeText(check) + "): " + telltale(check.output) };
  const release = path.win32.join(plan.run_dir, "releases", settings.version);
  const differs = releaseProblems(release, plan.files, deps.fs);
  if (differs.length > 0) return { ok: false, step: "release", reason: "the installed release is not the staged repository (" + differs.slice(0, 4).join("; ") + ")" };
  log("release: " + settings.version + " verified, and every file is the staged one");
  if (ctx.payloadModule && typeof ctx.payloadModule.writeUninstaller === "function") {
    try {
      log("the buyer's uninstaller: " + ctx.payloadModule.writeUninstaller(ctx, { release, settingsPath }));
    } catch (err) {
      log("the buyer's uninstaller was not written (" + ((err && (err.code || err.message)) || "error") + ")");
    }
    try {          // review M4: what this install was laid down from (the next main() compares it with its own payload)
      log("installed from: " + ctx.payloadModule.writeInstalledPayload(ctx));
    } catch (err) {
      log("the installed payload was not recorded (" + ((err && (err.code || err.message)) || "error") + ")");
    }
  }
  return { ok: true, settings, settingsPath, release };
}

// A buyer's install that has no address yet: the QR page shows the activation QR (msi_buyer, api.md 5.1.1).
function buyerWaiting(settings) {
  return isPlainObject(settings) && settings.mode === "buyer" && !settings.public_host;
}

// The QR page's address as the CLI printed it when it opened the page, else 127.0.0.1:<port> (a browser takes both).
function pageUrl(settings, output = "") {
  const printed = /\bhttp:\/\/127\.0\.0\.1:[0-9]{1,5}\/[A-Za-z0-9/_-]*/.exec(String(output));
  if (printed !== null) return printed[0];
  const port = isPlainObject(settings.pair_page) && Number.isInteger(settings.pair_page.port) && settings.pair_page.port > 0 ?
    settings.pair_page.port : 8765;
  return "127.0.0.1:" + port;
}

// start, site-ready, pair --first-only --page-only through the release's own CLI. {ok, step, text}
async function afterInstall(ctx, done) {
  const { plan, deps, log } = ctx;
  const cliPath = path.win32.join(done.release, "main", "msi_chat_cli.py");
  const cli = (args) => deps.runStep(done.settings.python, ["-I", "-B", "-X", "utf8", cliPath, "--settings", done.settingsPath].concat(args),
    { env: Object.assign({}, plan.env), cwd: plan.run_dir }, STEP_TIMEOUT_MS, log);
  const start = await cli(["start", "--wait", "40"]);
  if (start.code !== 0) {
    return { ok: false, step: "start", text: "Locus is installed but did not start (" + codeText(start) + ": " + telltale(start.output) +
      "). It starts at the next LM Studio start, or run locus start." };
  }
  const ready = await cli(["site-ready"]);
  if (ready.code !== 0 && buyerWaiting(done.settings)) {
    // a buyer's PC before its activation: the QR page shows the activation QR (it moves to the pairing QR once activated)
    const page = await cli(["pair", "--first-only", "--page-only"]);
    const url = pageUrl(done.settings, page.output);
    if (page.code === 0) {
      return { ok: true, step: "activate", text: "Locus is installed and running; the activation page " + url + " is open: scan its QR with " +
        "the Locus app (Activate a PC), then confirm the code on this PC." };
    }
    return { ok: false, step: "activate", text: "Locus is installed and running, but the activation page was not opened (" + telltale(page.output) +
      "). Open " + url + " in a browser and scan its QR with the Locus app (Activate a PC)." };
  }
  if (ready.code !== 0) {
    return { ok: false, step: "site-ready", text: "Locus is installed and running, but a phone cannot reach it yet (" + telltale(ready.output) +
      "). With the two sealed tunnel files beside the secrets folder (locus provision-site names them): set " +
      "MSI_CHAT_ALLOW_REAL=1, then locus provision-site --real. Then pair with the \"Locus - Pair a phone\" shortcut." };
  }
  const pair = await cli(["pair", "--first-only", "--page-only"]);
  if (pair.code === 0) return { ok: true, step: "pair", text: "Locus is installed and running; the QR page is open for the first phone." };
  if (pair.code === ALREADY_PAIRED) return { ok: true, step: "pair", text: "Locus is installed and running; a phone is already paired." };
  return { ok: false, step: "pair", text: "Locus is installed and running, but the QR page was not opened (" + telltale(pair.output) +
    "). Pair with the \"Locus - Pair a phone\" shortcut." };
}

// --- run and detach -----------------------------------------------------------------------------------------------

function parseArgs(argv) {
  const opts = {};
  for (let i = 0; i < argv.length; i += 2) {
    if (!/^--(plan|plan-sha256|ppid)$/.test(argv[i]) || i + 1 >= argv.length) return null;
    opts[argv[i].slice(2)] = argv[i + 1];
  }
  return opts.plan && opts["plan-sha256"] && opts.ppid ? opts : null;
}

// Reads the plan file main() wrote, checks its digest (given by main() on the command line) and the plan itself.
function loadPlan(opts, deps) {
  if (!opts || !isAbsWinPath(opts.plan) || !HEX64.test(opts["plan-sha256"]) || !/^[0-9]{1,10}$/.test(opts.ppid)) {
    return { ok: false, reason: "usage: bootstrap.js <detach|run> --plan <file> --plan-sha256 <hex> --ppid <pid>" };
  }
  const text = readText(deps.fs, opts.plan);
  if (text === null || text.length > MAX_PLAN_BYTES) return { ok: false, reason: "the plan file cannot be read" };
  if (sha256Text(text) !== opts["plan-sha256"]) return { ok: false, reason: "the plan file is not the one main() wrote" };
  let raw;
  try {
    raw = JSON.parse(text);
  } catch (err) {
    return { ok: false, reason: "the plan file is not JSON" };
  }
  const checked = checkPlan(raw, { exists: deps.fs.existsSync });
  if (!checked.ok) return checked;
  if (norm(opts.plan) !== norm(path.win32.join(checked.plan.run_dir, "state", PLAN_FILE))) return { ok: false, reason: "the plan file is not in its run folder" };
  return { ok: true, plan: checked.plan, ppid: Number(opts.ppid), text };
}

function recordAttempt(fsApi, file, change) {
  const ticket = readJson(fsApi, file) || {};
  const attempts = Array.isArray(ticket.attempts) ? ticket.attempts.slice() : [];
  if (attempts.length > 0) attempts[attempts.length - 1] = Object.assign({}, attempts[attempts.length - 1], change.attempt || {});
  writeJsonAtomic(fsApi, file, Object.assign({}, ticket, change.ticket || {}, { attempts }));
}

function writeStatus(ctx, view) {
  const file = path.win32.join(ctx.plan.run_dir, "logs", STATUS_FILE);
  try {
    ctx.deps.fs.writeFileSync(file, statusHtml(Object.assign({ at: ctx.deps.now().toISOString() }, view)), "utf8");
  } catch (err) {
    ctx.log("the status page could not be written: " + (err && err.code));
  }
  return file;
}

function nextTry(plan) {
  return "It tries again at the next LM Studio start (at most " + plan.max_per_day + " times a day). Or, after a fix, run " +
    "main\\install.cmd /plugin-first again.";
}

async function runBootstrap(argv, overrides) {
  const deps = Object.assign({ fs, now: () => new Date(), pid: process.pid, alive: isAlive, runStep, selfPath: __filename,
    openPage, layPayload }, overrides || {});
  const loaded = loadPlan(parseArgs(argv), deps);
  if (!loaded.ok) {
    process.stderr.write("bootstrap: " + loaded.reason + "\n");
    return EXIT.BAD_PLAN;
  }
  const plan = loaded.plan;
  const stateDir = path.win32.join(plan.run_dir, "state");
  const logsDir = path.win32.join(plan.run_dir, "logs");
  deps.fs.mkdirSync(stateDir, { recursive: true });
  deps.fs.mkdirSync(logsDir, { recursive: true });
  const log = makeLog(deps.fs, path.win32.join(logsDir, LOG_FILE), deps.now);
  const ctx = { plan, deps, log };
  const lock = acquireLock(stateDir, { pid: deps.pid, started: deps.now().toISOString(), stageId: plan.stage_id, ppid: loaded.ppid }, deps);
  if (!lock.ok) {
    log("another bootstrap holds the lock (pid " + lock.view.pid + ", since " + lock.view.started + "): nothing done");
    return EXIT.BUSY;
  }
  const ticketFile = path.win32.join(stateDir, TICKET_FILE);
  try {
    const ticket = readJson(deps.fs, ticketFile);
    if (!ticket || ticket.schema !== 1 || ticket.stage_id !== plan.stage_id) {
      log("no install ticket for this stage (forgotten by uninstall, or a newer stage): nothing done");
      return EXIT.REFUSED;
    }
    if (ticket.state === "done") {
      log("this stage already installed Locus: nothing done");
      return EXIT.OK;
    }
    const attempts = (Array.isArray(ticket.attempts) ? ticket.attempts : []).concat([{ at: deps.now().toISOString(), ppid: loaded.ppid,
      pid: deps.pid, result: null, step: null, reason: null }]).slice(-ATTEMPTS_KEPT);
    writeJsonAtomic(deps.fs, ticketFile, Object.assign({}, ticket, { state: "running", attempts }));
    log("attempt " + attempts.length + " for stage " + plan.stage_id.slice(0, 8) + " (LM Studio pid " + loaded.ppid + ", " +
      (plan.real ? "real" : "MSI_CHAT_TEST") + ")");
    writeStatus(ctx, { ok: true, title: "installing itself", summary: "Locus is installing itself (started " + attempts[attempts.length - 1].at + ").",
      lines: ["Log: " + path.win32.join(logsDir, LOG_FILE)] });
    let outcome;
    try {
      outcome = await installSteps(ctx);
    } catch (err) {
      outcome = { ok: false, step: "bootstrap", reason: "unexpected " + ((err && (err.code || err.name)) || "error") };
    }
    if (!outcome.ok) {
      const reason = sanitizeReason(outcome.reason);
      recordAttempt(deps.fs, ticketFile, { ticket: { state: "failed" }, attempt: { result: "failed", step: outcome.step, reason } });
      log("FAILED at " + outcome.step + ": " + reason);
      const page = writeStatus(ctx, { ok: false, title: "the install did not finish", summary: "Locus could not install itself: at " +
        outcome.step + ": " + reason, lines: [nextTry(plan), "Log: " + path.win32.join(logsDir, LOG_FILE)] });
      deps.openPage(page, plan.testMode, log);
      return EXIT.FAILED;
    }
    recordAttempt(deps.fs, ticketFile, { ticket: { state: "done", done: deps.now().toISOString() }, attempt: { result: "done" } });
    log("installed: the ticket says done");
    let after;
    try {
      after = await afterInstall(ctx, outcome);
    } catch (err) {
      after = { ok: false, step: "start", text: "Locus is installed; starting it failed unexpectedly: run locus start" };
    }
    const text = sanitizeReason(after.text);
    recordAttempt(deps.fs, ticketFile, { ticket: { note: text } });
    log((after.ok ? "done: " : "installed, but at " + after.step + ": ") + text);
    const lines = ["Another phone later: the \"Locus - Pair a phone\" shortcut.", "Log: " + path.win32.join(logsDir, LOG_FILE)];
    if (plan.payload !== undefined) lines.push("To remove Locus from this PC: " + path.win32.join(plan.buyer.root, "uninstall.cmd"));
    const page = writeStatus(ctx, { ok: after.ok, title: after.ok ? "installed" : "installed, one step left", summary: text, lines });
    if (!after.ok) deps.openPage(page, plan.testMode, log);
    return EXIT.OK;
  } finally {
    releaseLock(stateDir, lock.text, deps.fs);
  }
}

// The launcher's trick: start "run" detached and hidden, exit on its "spawn" event.
function detach(argv, overrides) {
  const deps = Object.assign({ fs, spawn: childProcess.spawn, timeoutMs: SPAWN_TIMEOUT_MS, execPath: process.execPath,
    selfPath: __filename }, overrides || {});
  const opts = parseArgs(argv);
  const loaded = loadPlan(opts, deps);
  if (!loaded.ok) return Promise.resolve(EXIT.BAD_PLAN);
  if (sha256File(deps.selfPath, deps.fs) !== loaded.plan.bootstrap.sha256) return Promise.resolve(EXIT.REFUSED);
  const logsDir = path.win32.join(loaded.plan.run_dir, "logs");
  return new Promise((resolve) => {
    let out = null;
    let done = false;
    const finish = (code) => {
      if (done) return;
      done = true;
      clearTimeout(timer);
      if (out !== null) {
        try { deps.fs.closeSync(out); } catch (err) { /* already closed */ }
      }
      resolve(code);
    };
    const timer = setTimeout(() => finish(EXIT.TIMEOUT), deps.timeoutMs);
    try {
      deps.fs.mkdirSync(logsDir, { recursive: true });
      out = deps.fs.openSync(path.win32.join(logsDir, STDIO_LOG), "a");
      const child = deps.spawn(deps.execPath, [deps.selfPath, "run", "--plan", opts.plan, "--plan-sha256", opts["plan-sha256"], "--ppid", opts.ppid], {
        detached: true, windowsHide: true, stdio: ["ignore", out, out], env: Object.assign({}, loaded.plan.env), cwd: loaded.plan.run_dir,
      });
      child.once("error", () => finish(EXIT.SPAWN_ERROR));
      child.once("spawn", () => {
        child.unref();
        finish(EXIT.OK);
      });
    } catch (err) {
      finish(EXIT.SPAWN_ERROR);
    }
  });
}

async function main(argv) {
  if (argv[0] === "detach") return detach(argv.slice(1));
  if (argv[0] === "run") {
    setTimeout(() => {
      process.stderr.write("bootstrap: over " + RUN_LIMIT_MS / 60000 + " minutes: stopping\n");
      process.exit(EXIT.FAILED);
    }, RUN_LIMIT_MS).unref();
    return runBootstrap(argv.slice(1));
  }
  process.stderr.write("usage: bootstrap.js <detach|run> --plan <file> --plan-sha256 <hex> --ppid <pid>\n");
  return EXIT.USAGE;
}

module.exports = {
  EXIT, FILE_RULES, REQUIRED_FILES, TICKET_FILE, LOCK_FILE, PLAN_FILE, LOG_FILE, STDIO_LOG, STATUS_FILE, LOCK_MAX_AGE_MS,
  LOCK_GRACE_MS, BASE_ENV_NAMES, INSTALL_ENV_NAMES, GUARDED_ENV_NAMES, TEST_ROOT_NAME, VALUE_FLAGS, BARE_FLAGS, ARG_VALUE,
  isAbsWinPath, testRootProblem, isUnderTestRoot, testPathProblem, sha256Text,
  sha256File, planEnvProblem, installArgsProblem, checkPlan, collectFiles, verifyFiles, releaseProblems, repoPathOf, lockState,
  acquireLock, releaseLock, readJson, writeJsonAtomic, sanitizeReason, telltale, statusHtml, installCommand, installEnv,
  runBootstrap, detach, main, buyerPlanProblem, loadPayloadModule, buyerWaiting, pageUrl, spaceFreeRoot, stopForUpdate, PAYLOAD_MODULE,
};

if (require.main === module) {
  main(process.argv.slice(2)).then((code) => process.exit(code));
}