src / hub.ts

// Locus plugin, the Hub install (docs\build\HUBPLAN_REPORT.md). A plugin installed from the LM Studio Hub has no path
// baked in: src\baked.ts holds only HUB_FILES, the digests of the installer files made at publish time. main() then
// derives the whole install plan at run time, with pure functions only (no I/O here; the probes are injected):
// - the plugin's own folder <home>\extensions\plugins\<owner>\<name> (manifest.json beside the code, owner and name
//   equal to the two folder names) gives the LM Studio home, and from it the installer repository <home>\msi-chat,
//   the run folder <home>\msi-chat-run, the plugins root, lms.exe, node.exe, newt.exe;
// - USERPROFILE (the only profile name the plugin's environment has: no APPDATA, no LOCALAPPDATA) gives python.exe;
// - the bootstrap is the plugin's own bootstrap.js, checked against the digest baked beside the files.
// The plan has the shape `stage-first` bakes (src\bootstrap.ts parsePlan, bootstrap.js checkPlan check it), so the
// bootstrap runs exactly as for a staged plugin. Erasable TypeScript only; node:crypto for the stage id alone.
import { createHash } from "node:crypto";
import { TEST_ROOT_NAME, isAbsWinPath } from "./settings.ts";

export const HUB_SCHEMA = 1;
export const PLUGIN_LOG = "locus-plugin.log";                 // the marker line of every main() run, in the plugin's folder
export const UNINSTALLED_MARKER = "locus-uninstalled.json";   // left by uninstall.cmd: this plugin installs nothing by itself
export const PYTHON_REL = "AppData\\Local\\Programs\\Python\\Python312\\python.exe";
export const REPO_NAME = "msi-chat";
export const RUN_NAME = "msi-chat-run";
export const TEST_HUB_ARGS_NAME = "MSI_CHAT_TEST_HUB_ARGS";   // test only: the install args of the test, a JSON list
export const TEST_NEWT_EXE_NAME = "MSI_CHAT_TEST_NEWT_EXE";   // test only: the fake newt (a .py stand-in) instead of <home>\newt\newt.exe
const MAX_HUB_BYTES = 200_000;
const MAX_LEVELS_UP = 2;
const PLAIN_NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;
const HEX64 = /^[0-9a-f]{64}$/;
const REL_PATH = /^[A-Za-z0-9_.-]+(\/[A-Za-z0-9_.-]+)*$/;
// bootstrap.js's install-args rules (the tests hold both to one table).
const VALUE_FLAGS: readonly string[] = ["--version", "--data-dir", "--uploads-dir", "--secrets-dir", "--engine-port", "--admin-port",
  "--pair-port", "--lmstudio-home", "--lmstudio-api", "--mode"];
const BARE_FLAGS: readonly string[] = ["--real", "--yes"];
const ARG_VALUE = /^[A-Za-z0-9 :\\._-]{1,260}$/;
const TEST_ENV_NAME = /^MSI_CHAT_TEST(_[A-Z0-9_]+)?$|^MSI_CHAT_NEWT_SHA256$/;

type Json = Record<string, unknown>;

function isObject(value: unknown): value is Json {
  return typeof value === "object" && value !== null && !Array.isArray(value);
}

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

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

function parentOf(p: string): string | null {
  const n = norm(p);
  const i = n.lastIndexOf("\\");
  return i <= 2 ? null : n.slice(0, i);   // a folder right under the drive has no parent folder (a whole drive is not a place)
}

function baseOf(p: string): string {
  const n = norm(p);
  return n.slice(n.lastIndexOf("\\") + 1);
}

export interface PluginFolder {
  readonly dir: string;        // the folder that holds manifest.json
  readonly manifest: Json;
}

// The plugin's own folder: the first candidate (or one of its parents, at most 2 levels up) that holds a manifest.json
// of a node plugin. `readManifest` returns the parsed manifest.json of a folder, or null.
export function findPluginFolder(candidates: readonly string[], readManifest: (dir: string) => unknown): PluginFolder | null {
  for (const candidate of candidates) {
    if (!isAbsWinPath(candidate) || hasShortName(candidate)) continue;
    let dir: string | null = norm(candidate);
    for (let level = 0; level <= MAX_LEVELS_UP && dir !== null; level += 1) {
      const manifest = readManifest(dir);
      if (isObject(manifest) && manifest.type === "plugin" && manifest.runner === "node") return { dir, manifest };
      dir = parentOf(dir);
    }
  }
  return null;
}

export interface PluginPlace {
  readonly pluginDir: string;
  readonly owner: string;
  readonly name: string;
  readonly home: string;
}

// The Hub shape: <home>\extensions\plugins\<owner>\<name>, the manifest's owner and name being the folder names
// (compared as written: LM Studio makes the folders from the Hub identity). null for any other place.
export function hubShape(folder: PluginFolder | null): PluginPlace | null {
  if (folder === null) return null;
  const { dir, manifest } = folder;
  const owner = manifest.owner;
  const name = manifest.name;
  if (typeof owner !== "string" || typeof name !== "string" || !PLAIN_NAME.test(owner) || !PLAIN_NAME.test(name)) return null;
  const ownerDir = parentOf(dir);
  const pluginsDir = ownerDir === null ? null : parentOf(ownerDir);
  const extensionsDir = pluginsDir === null ? null : parentOf(pluginsDir);
  const home = extensionsDir === null ? null : parentOf(extensionsDir);
  if (ownerDir === null || pluginsDir === null || extensionsDir === null || home === null) return null;
  if (baseOf(dir) !== name || baseOf(ownerDir) !== owner) return null;
  if (baseOf(pluginsDir).toLowerCase() !== "plugins" || baseOf(extensionsDir).toLowerCase() !== "extensions") return null;
  if (norm(home).length <= 2 || !isAbsWinPath(home)) return null;
  return { pluginDir: dir, owner, name, home };
}

export interface HubPaths extends PluginPlace {
  readonly repo: string;
  readonly runDir: string;
  readonly pluginsRoot: string;
  readonly lms: string;
  readonly node: string;
  readonly newt: string;
  readonly python: string;
  readonly bootstrap: string;
}

// Every path of the install from the Hub place and USERPROFILE. null when USERPROFILE is not a usable folder.
export function hubPaths(place: PluginPlace, userProfile: unknown): HubPaths | null {
  if (!isAbsWinPath(userProfile) || hasShortName(userProfile) || norm(userProfile).length <= 2) return null;
  const home = place.home;
  return Object.freeze({
    ...place,
    repo: home + "\\" + REPO_NAME,
    runDir: home + "\\" + RUN_NAME,
    pluginsRoot: home + "\\extensions\\plugins",
    lms: home + "\\bin\\lms.exe",
    node: home + "\\.internal\\utils\\node.exe",
    newt: home + "\\newt\\newt.exe",
    python: norm(userProfile) + "\\" + PYTHON_REL,
    bootstrap: place.pluginDir + "\\bootstrap.js",
  });
}

// The first thing missing for an install, as the one line a stranger's PC gets; null when everything is there.
export function hubMissing(paths: HubPaths, exists: (p: string) => boolean): string | null {
  const gone = (what: string, p: string): string => "Locus: " + what + " is missing (expected " + p + "): nothing done";
  if (!exists(paths.repo) || !exists(paths.repo + "\\main\\install.cmd")) {
    return "Locus: the installer is not on this PC (expected " + paths.repo + "): nothing done";
  }
  if (!exists(paths.lms)) return gone("lms.exe", paths.lms);
  if (!exists(paths.node)) return gone("node.exe", paths.node);
  if (!exists(paths.newt)) return gone("newt.exe", paths.newt);
  if (paths.python.includes(" ")) return "Locus: python.exe's path holds a space (" + paths.python + "): nothing done";
  if (!exists(paths.python)) return gone("python.exe", paths.python);
  if (!exists(paths.bootstrap)) return gone("the plugin's bootstrap.js", paths.bootstrap);
  return null;
}

// The folders main() looks at for its own place: the module's folder (import.meta.url; empty in LM Studio's CommonJS
// bundle), the folder of the script node runs (argv[1], ".lmstudio\production.js" under LM Studio, resolved against
// cwd), and cwd itself (LM Studio starts the plugin in its folder).
export function pluginFolderCandidates(moduleUrl: string | undefined, argv1: string | undefined, cwd: string): string[] {
  const out: string[] = [];
  const add = (p: string | null): void => {
    if (p !== null && isAbsWinPath(p) && !out.includes(p)) out.push(p);
  };
  if (typeof moduleUrl === "string" && /^file:\/\/\//i.test(moduleUrl)) {
    try {
      const file = decodeURIComponent(moduleUrl.slice("file:///".length)).replace(/\//g, "\\");
      add(parentOf(file));
    } catch {
      // not a usable URL
    }
  }
  if (typeof argv1 === "string" && /\.(js|mjs|cjs|ts)$/i.test(argv1)) {
    const script = /^[A-Za-z]:[\\/]/.test(argv1) ? norm(argv1) : norm(cwd) + "\\" + norm(argv1).replace(/^(\.\\)+/, "");
    add(parentOf(script));
  }
  add(isAbsWinPath(cwd) ? norm(cwd) : null);
  return out;
}

// --- HUB_FILES (src\baked.ts) ---------------------------------------------------------------------------------------

export interface HubFiles {
  readonly revision: number;
  readonly bootstrapSha256: string;
  readonly files: Readonly<Record<string, string>>;
  readonly installArgs: readonly string[];
  readonly maxPerDay: number;
  readonly stageId: string;
}

export type HubFilesResult = { readonly ok: true; readonly hub: HubFiles } | { readonly ok: false; readonly reason: string };

// The stage of a Hub revision: the first 32 hex characters of the digest of the baked text (one ticket per revision).
export function hubStageId(text: string): string {
  return createHash("sha256").update(text, "utf8").digest("hex").slice(0, 32);
}

// Same rules as bootstrap.js installArgsProblem (the tests hold both to one table).
export function installArgsProblem(args: unknown, real: boolean): string | null {
  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: unknown = args[i];
    if (typeof arg === "string" && BARE_FLAGS.includes(arg)) {
      sawReal = sawReal || arg === "--real";
      continue;
    }
    if (typeof arg === "string" && VALUE_FLAGS.includes(arg)) {
      const value: unknown = 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;
}

export function parseHubFiles(text: string): HubFilesResult {
  const fail = (reason: string): HubFilesResult => ({ ok: false, reason: "HUB_FILES: " + reason });
  if (text.length === 0 || text.length > MAX_HUB_BYTES) return fail("empty or too large");
  let raw: unknown;
  try {
    raw = JSON.parse(text);
  } catch {
    return fail("not valid JSON");
  }
  if (!isObject(raw)) return fail("not a JSON object");
  if (raw.schema !== HUB_SCHEMA) return fail("schema is not " + HUB_SCHEMA);
  if (typeof raw.revision !== "number" || !Number.isInteger(raw.revision) || raw.revision < 1) return fail("revision is not a whole number");
  if (typeof raw.bootstrap_sha256 !== "string" || !HEX64.test(raw.bootstrap_sha256)) return fail("bootstrap_sha256 is not 64 hex characters");
  const files = raw.files;
  if (!isObject(files) || Object.keys(files).length === 0 || Object.keys(files).length > 2000) return fail("files is 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 fail("a bad path in files " + JSON.stringify(rel));
    if (typeof digest !== "string" || !HEX64.test(digest)) return fail("a bad digest for " + rel);
  }
  const argsProblem = installArgsProblem(raw.install_args, true);
  if (argsProblem !== null) return fail(argsProblem);
  const max = raw.max_per_day;
  if (typeof max !== "number" || !Number.isInteger(max) || max < 1 || max > 10) return fail("max_per_day is not 1-10");
  return {
    ok: true,
    hub: Object.freeze({
      revision: raw.revision, bootstrapSha256: raw.bootstrap_sha256, files: Object.freeze({ ...(files as Record<string, string>) }),
      installArgs: Object.freeze([...(raw.install_args as string[])]), maxPerDay: max, stageId: hubStageId(text),
    }),
  };
}

// MSI_CHAT_TEST_HUB_ARGS (test only): the test's own install args as a JSON list of plain strings.
export function parseTestHubArgs(value: unknown): { readonly ok: true; readonly args: readonly string[] } | { readonly ok: false; readonly reason: string } {
  if (value === undefined || value === "") return { ok: true, args: [] };
  let raw: unknown;
  try {
    raw = typeof value === "string" ? JSON.parse(value) : null;
  } catch {
    raw = null;
  }
  if (!Array.isArray(raw) || !raw.every((a) => typeof a === "string")) return { ok: false, reason: TEST_HUB_ARGS_NAME + ": not a JSON list of strings" };
  const problem = installArgsProblem([...raw, "--yes"], false);
  if (problem !== null) return { ok: false, reason: TEST_HUB_ARGS_NAME + ": " + problem };
  return { ok: true, args: raw as string[] };
}

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

type Env = Readonly<Record<string, string | undefined>>;

function lookup(env: Env, name: string): string | undefined {
  const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());
  const value = key === undefined ? undefined : env[key];
  return typeof value === "string" && value !== "" ? value : undefined;
}

export type HubEnvResult = { readonly ok: true; readonly env: Readonly<Record<string, string>> } | { readonly ok: false; readonly reason: string };

// The install's environment from the plugin's own (M0: the basic Windows names only): the 3.1 launch_env names, the
// Windows ones derived from SystemRoot and USERPROFILE when the plugin's environment lacks them, a short system PATH,
// the paths install.cmd reads, and under MSI_CHAT_TEST the test switches only. Never LMS_*, never MSI_CHAT_ALLOW_REAL.
// `profile`: the buyer's install (below) names USERPROFILE itself (its python is not under the profile's Python312).
export function hubEnv(env: Env, paths: HubPaths, testMode: boolean, profileOf?: string): HubEnvResult {
  const systemRoot = lookup(env, "SystemRoot");
  if (systemRoot === undefined || !isAbsWinPath(systemRoot)) return { ok: false, reason: "SystemRoot is not in the plugin's environment" };
  const root = norm(systemRoot);
  const profile = profileOf ?? paths.python.slice(0, -(PYTHON_REL.length + 1));     // python = <USERPROFILE>\<PYTHON_REL>
  const temp = lookup(env, "TEMP") ?? lookup(env, "TMP") ?? profile + "\\AppData\\Local\\Temp";
  const out: Record<string, string> = {
    SystemRoot: root, windir: lookup(env, "windir") ?? root, SystemDrive: lookup(env, "SystemDrive") ?? root.slice(0, 2),
    ComSpec: root + "\\system32\\cmd.exe", PATHEXT: ".COM;.EXE;.BAT;.CMD",
    PATH: [root + "\\system32", root, root + "\\System32\\Wbem", root + "\\System32\\WindowsPowerShell\\v1.0"].join(";"),
    TEMP: temp, TMP: lookup(env, "TMP") ?? temp, USERPROFILE: profile, HOMEDRIVE: lookup(env, "HOMEDRIVE") ?? profile.slice(0, 2),
    HOMEPATH: lookup(env, "HOMEPATH") ?? profile.slice(2), APPDATA: profile + "\\AppData\\Roaming", LOCALAPPDATA: profile + "\\AppData\\Local",
    PYTHONDONTWRITEBYTECODE: "1",
    MSI_CHAT_PYTHON: paths.python, MSI_CHAT_NODE: paths.node, MSI_CHAT_LMS: paths.lms, MSI_CHAT_RUN_DIR: paths.runDir,
    MSI_CHAT_PLUGINS_ROOT: paths.pluginsRoot, MSI_CHAT_NEWT_EXE: paths.newt, MSI_CHAT_PLUGIN_DIR: paths.pluginDir,
  };
  if (testMode) {
    for (const [name, value] of Object.entries(env)) {
      if (TEST_ENV_NAME.test(name) && typeof value === "string" && value !== "") out[name] = value;
    }
    if (out.MSI_CHAT_TEST !== "1" || lookup(env, TEST_ROOT_NAME) === undefined) return { ok: false, reason: "MSI_CHAT_TEST without " + TEST_ROOT_NAME };
  }
  return { ok: true, env: Object.freeze(out) };
}

// Under MSI_CHAT_TEST the fake newt (a .py stand-in, MSI_CHAT_TEST_NEWT_EXE) replaces <home>\newt\newt.exe: a .exe
// stand-in cannot pass the run-time newt pin. Outside the test nothing changes.
export function testOverrides(paths: HubPaths, env: Env, testMode: boolean): HubPaths {
  const newt = testMode ? lookup(env, TEST_NEWT_EXE_NAME) : undefined;
  if (newt === undefined || !isAbsWinPath(newt)) return paths;
  return Object.freeze({ ...paths, newt: norm(newt) });
}

export type HubPlanResult = { readonly ok: true; readonly text: string } | { readonly ok: false; readonly reason: string };

// The plan text, in the shape of a stage-first plan: a real plan outside MSI_CHAT_TEST (the baked args, --real among
// them), a test plan under it (--real dropped, the test's args added), --lmstudio-home <home> always (the derived home).
export function buildHubPlan(hub: HubFiles, paths: HubPaths, env: Readonly<Record<string, string>>, testMode: boolean,
  testArgs: readonly string[], made: string): HubPlanResult {
  const base = testMode ? hub.installArgs.filter((a) => a !== "--real") : [...hub.installArgs];
  const args = [...base, ...testArgs];
  if (!args.includes("--yes")) args.push("--yes");
  if (!args.includes("--lmstudio-home")) args.push("--lmstudio-home", paths.home);
  const problem = installArgsProblem(args, !testMode);
  if (problem !== null) return { ok: false, reason: "the Hub plan: " + problem };
  const plan = {
    schema: 1, stage_id: hub.stageId, made, repo: paths.repo, run_dir: paths.runDir, python: paths.python, node: paths.node,
    bootstrap: { path: paths.bootstrap, sha256: hub.bootstrapSha256 }, files: hub.files, install_args: args, real: !testMode, env,
    max_per_day: hub.maxPerDay, hub: { owner: paths.owner, name: paths.name, revision: hub.revision },
  };
  return { ok: true, text: JSON.stringify(plan) };
}

// The ticket main() writes itself on a Hub install (the console of stage-first is not there): pending, this revision's stage.
export function hubTicketText(hub: HubFiles, paths: HubPaths, made: string): string {
  return JSON.stringify({ schema: 1, stage_id: hub.stageId, made, state: "pending", attempts: [], done: null, max_per_day: hub.maxPerDay,
    hub: { owner: paths.owner, name: paths.name, revision: hub.revision } }, null, 1) + "\n";
}

// --- the buyer's install on a stranger's PC ----------------------------------------------------------------------------
// docs\build\PC_INSTALL_REPORT.md; design-product.md 6a. A
// Hub copy published with the buyer payload carries in HUB_FILES a `payload` object: the pins of the python.org
// embeddable runtime and of newt (URL, SHA-256, size), the program zip it carries (payload\program-<id>.zip: digest,
// size) and the digest of payload.js (the bootstrap's downloader). When the installer repository is NOT on the PC (a
// buyer's), main() derives the buyer's place, <USERPROFILE>\AppData\Local\Locus, and a plan in the shape the bootstrap
// knows plus `payload` and `buyer.root`; the bootstrap then downloads, checks and lays everything down before it runs
// install.cmd /from-plugin with --mode buyer. Pure functions only (no I/O); payload.js holds the same rules (the tests
// hold both to one table). Erasable TypeScript only.

export const BUYER_REL = "AppData\\Local\\Locus";
export const PAYLOAD_MODULE = "payload.js";
export const PAYLOAD_DIR = "payload";

const MiB = 1024 * 1024;
const CAPS: Readonly<Record<string, number>> = { python: 64 * MiB, newt: 128 * MiB, program: 32 * MiB };
const VERSION = /^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$/;
const PROGRAM_FILE = /^program-([0-9a-f]{16})\.zip$/;
const OFFICIAL: Readonly<Record<string, RegExp>> = {
  python: /^https:\/\/www\.python\.org\/ftp\/python\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/python-\1-embed-amd64\.zip$/,
  newt: /^https:\/\/github\.com\/fosrl\/newt\/releases\/download\/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})\/newt_windows_amd64\.exe$/,
};
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([0-9]{1,5})\/[A-Za-z0-9._~/-]{1,200}$/;
// the installer's argument rule (bootstrap.js ARG_VALUE): the buyer's paths become install args (a space is fine since
// the review round: Python and newt's pin copy then live in the space-free root)
const PROFILE_CHARS = /^[A-Za-z]:[\\/][A-Za-z0-9 \\/._-]*$/;

export interface Pin {
  readonly version?: string;
  readonly url?: string;
  readonly sha256: string;
  readonly size: number;
  readonly file?: string;
  readonly name?: string;
  readonly files?: Readonly<Record<string, string>>;
}

export interface Payload {
  readonly schema: number;
  readonly module_sha256: string;
  readonly python: Pin;
  readonly newt: Pin;
  readonly program: Pin;
}

export type PayloadResult = { readonly ok: true; readonly payload: Payload } | { readonly ok: false; readonly reason: string };

// program.files (payload.js programFilesProblem: the same texts).
function programFilesProblem(files: unknown): string | null {
  if (!isObject(files) || Object.keys(files).length === 0 || Object.keys(files).length > 2000) return "program.files is 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 "program.files: a bad path";
    if (typeof digest !== "string" || !HEX64.test(digest)) return "program.files: a bad digest";
  }
  return null;
}

// Same rules and texts as payload.js pinProblem.
function pinProblem(part: string, pin: unknown, testMode: boolean): string | null {
  if (!isObject(pin)) return part + ": not an object";
  if (typeof pin.sha256 !== "string" || !HEX64.test(pin.sha256)) return part + ".sha256 is not 64 hex characters";
  const cap = CAPS[part] ?? 0;
  if (typeof pin.size !== "number" || !Number.isInteger(pin.size) || pin.size < 1 || pin.size > cap) return part + ".size is not 1-" + cap;
  if (part === "program") {
    const m = typeof pin.file === "string" ? PROGRAM_FILE.exec(pin.file) : null;
    if (m === null || m[1] !== pin.sha256.slice(0, 16)) return "program.file is not program-<the first 16 hex of its digest>.zip";
    if (pin.url !== undefined) return "program.url: the program is carried in the plugin, never downloaded";
    return programFilesProblem(pin.files);
  }
  if (typeof pin.version !== "string" || !VERSION.test(pin.version)) return part + ".version is not x.y.z";
  const pattern = OFFICIAL[part];
  const official = typeof pin.url === "string" && pattern !== undefined ? pattern.exec(pin.url) : null;
  const loopback = testMode && typeof pin.url === "string" && LOOPBACK_URL.test(pin.url);
  if (!loopback && (official === null || official[1] !== pin.version)) return part + ".url is not the official download of " + pin.version;
  if (pin.name !== undefined && !(part === "newt" && testMode && pin.name === "newt.py")) return part + ".name is only for the test's newt stand-in";
  return null;
}

// The `payload` object of HUB_FILES, checked (payload.js payloadProblem: the same texts).
export function parsePayload(raw: unknown, testMode: boolean): PayloadResult {
  if (!isObject(raw) || raw.schema !== 1) return { ok: false, reason: "payload: schema is not 1" };
  if (typeof raw.module_sha256 !== "string" || !HEX64.test(raw.module_sha256)) return { ok: false, reason: "payload: module_sha256 is not 64 hex characters" };
  for (const part of ["python", "newt", "program"]) {
    const problem = pinProblem(part, raw[part], testMode);
    if (problem !== null) return { ok: false, reason: "payload: " + problem };
  }
  return { ok: true, payload: JSON.parse(JSON.stringify(raw)) as Payload };
}

export interface BuyerLayout {
  readonly root: string;
  readonly runDir: string;
  readonly python: string;
  readonly pythonDir: string;
  readonly newtDir: string;
  readonly newt: string;
  readonly programDir: string;
  readonly program: string;
  readonly downloads: string;
  readonly data: string;
  readonly uploads: string;
  readonly secrets: string;
  readonly uninstaller: string;
  readonly spaceFree: string | null;
}

// Every folder of a buyer's install from its root (payload.js layoutOf: one table); the upload area is
// <profile>\Locus-uploads (the engine refuses one in app data; the person finds the files his phones sent there). With a
// space in the user folder, Python lives in the space-free root (newt splits its --updown command at spaces).
export function buyerLayout(root: string, payload: Payload, testMode: boolean, spaceFree: string | null = null): BuyerLayout {
  const programId = (PROGRAM_FILE.exec(payload.program.file ?? "") ?? ["", ""])[1];
  const newtName = testMode && payload.newt.name === "newt.py" ? "newt.py" : "newt.exe";
  const pyBase = spaceFree ?? root;
  return Object.freeze({
    root, runDir: root + "\\run", python: pyBase + "\\python\\python.exe", pythonDir: pyBase + "\\python", newtDir: root + "\\newt",
    newt: root + "\\newt\\" + newtName, programDir: root + "\\program", program: root + "\\program\\" + programId,
    downloads: root + "\\downloads", data: root + "\\data",
    uploads: root.slice(0, -(BUYER_REL.length + 1)) + "\\Locus-uploads", secrets: root + "\\secrets",
    uninstaller: root + "\\uninstall.cmd", spaceFree,
  });
}

// The space-free root of a user folder with a space (payload.js spaceFreeRoot: one table): <ProgramData>\Locus\u<16 hex
// of the profile's path>, made private by the bootstrap before anything is written in it.
export function spaceFreeRoot(profile: string, programData: string): string {
  const id = createHash("sha256").update(profile.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase(), "utf8").digest("hex");
  return programData.replace(/[\\/]+$/, "") + "\\Locus\\u" + id.slice(0, 16);
}

export const TEST_PROGRAMDATA_NAME = "MSI_CHAT_TEST_PROGRAMDATA";   // test only: the sandbox's ProgramData

// ProgramData of this PC: <SystemRoot's drive>\ProgramData; under MSI_CHAT_TEST the test's own folder. null: unknown.
export function programDataOf(env: Readonly<Record<string, string | undefined>>, testMode: boolean): string | null {
  const get = (name: string): string | undefined => {
    const key = Object.keys(env).find((k) => k.toLowerCase() === name.toLowerCase());
    const value = key === undefined ? undefined : env[key];
    return typeof value === "string" && value !== "" ? value : undefined;
  };
  if (testMode) {
    const test = get(TEST_PROGRAMDATA_NAME);
    return test !== undefined && isAbsWinPath(test) && !/\s/.test(test) ? test.replace(/[\\/]+$/, "") : null;
  }
  const root = get("SystemRoot");
  return root !== undefined && isAbsWinPath(root) ? root.slice(0, 2) + "\\ProgramData" : null;
}

export type RootResult = { readonly ok: true; readonly root: string } | { readonly ok: false; readonly note: string };

// <USERPROFILE>\AppData\Local\Locus. The notes name no folder (the marker line holds names only).
export function buyerRoot(userProfile: unknown): RootResult {
  const unusable: RootResult = { ok: false, note: "Locus: USERPROFILE is not a usable folder in the plugin's environment: nothing done" };
  if (!isAbsWinPath(userProfile)) return unusable;
  const profile = (userProfile as string).replace(/\//g, "\\").replace(/\\+$/, "");
  if (profile.length <= 2 || /(^|\\)[^\\]*~\d/.test(profile)) return unusable;
  if (/[\t\r\n]|\s{2}|\s\\|\\\s|\s$/.test(profile)) return unusable;
  if (!PROFILE_CHARS.test(profile)) return { ok: false, note: "Locus: the Windows user folder's name holds a character the installer does not accept yet: nothing done" };
  return { ok: true, root: profile + "\\" + BUYER_REL };
}

// The first file a buyer's install needs that is not there, as the one line of the marker log; null when all are.
export function buyerMissing(place: PluginPlace, node: string, payload: Payload, exists: (p: string) => boolean): string | null {
  if (!exists(node)) return "Locus: LM Studio's node.exe is missing (expected " + node + "): nothing done";
  for (const file of ["bootstrap.js", PAYLOAD_MODULE]) {
    if (!exists(place.pluginDir + "\\" + file)) return "Locus: the plugin's " + file + " is missing: install the plugin again from LM Studio";
  }
  const carried = PAYLOAD_DIR + "\\" + (payload.program.file ?? "");
  if (!exists(place.pluginDir + "\\" + carried)) return "Locus: the Locus program is missing from the plugin (" + carried + "): install the plugin again from LM Studio";
  return null;
}

// The HubPaths-shaped places of a buyer's install (what hubEnv and the plan's env take).
export function buyerPaths(place: PluginPlace, layout: BuyerLayout, node: string): HubPaths {
  return Object.freeze({
    ...place, repo: layout.program, runDir: layout.runDir, pluginsRoot: place.home + "\\extensions\\plugins", lms: place.home + "\\bin\\lms.exe",
    node, newt: layout.newt, python: layout.python, bootstrap: place.pluginDir + "\\bootstrap.js",
  });
}

// The buyer's plan text: the Hub plan's shape (stage, paths, the baked digests, the env) plus `payload` and
// `buyer.root`; the install args --mode buyer and the buyer's folders (--real only in a real plan).
export function buildBuyerPlan(hub: HubFiles, payload: Payload, place: PluginPlace, layout: BuyerLayout, node: string,
  env: Readonly<Record<string, string>>, testMode: boolean, testArgs: readonly string[], made: string): HubPlanResult {
  const args = testMode ? hub.installArgs.filter((a) => a !== "--real") : [...hub.installArgs];
  if (!args.includes("--yes")) args.push("--yes");
  args.push("--mode", "buyer", "--lmstudio-home", place.home, "--data-dir", layout.data, "--uploads-dir", layout.uploads,
    "--secrets-dir", layout.secrets, ...testArgs);
  const problem = installArgsProblem(args, !testMode);
  if (problem !== null) return { ok: false, reason: "the buyer's plan: " + problem };
  const plan = {
    schema: 1, stage_id: hub.stageId, made, repo: layout.program, run_dir: layout.runDir, python: layout.python, node,
    bootstrap: { path: place.pluginDir + "\\bootstrap.js", sha256: hub.bootstrapSha256 }, files: payload.program.files ?? {},
    install_args: args, real: !testMode, env, max_per_day: hub.maxPerDay, hub: { owner: place.owner, name: place.name, revision: hub.revision },
    payload, buyer: layout.spaceFree === null ? { root: layout.root } : { root: layout.root, space_free: layout.spaceFree },
  };
  return { ok: true, text: JSON.stringify(plan) };
}

// The program's files must be installer files of HUB_FILES with the same digests (both are made by one publish).
export function programFilesMismatch(payload: Payload, hub: HubFiles): string | null {
  for (const [rel, digest] of Object.entries(payload.program.files ?? {})) {
    if (hub.files[rel] !== digest) return "payload: program.files differs from HUB_FILES for " + rel;
  }
  return null;
}

// Review M4: the payload an installed Locus was laid down from (<root>\\installed-payload.json, written by the bootstrap
// after a successful install) is not this plugin's: an update. Nothing recorded (an install before the record) counts as
// an update too, once Locus is installed.
export const INSTALLED_FILE = "installed-payload.json";

export function payloadOutdated(recordText: string | null, payload: Payload): boolean {
  if (recordText === null) return true;
  try {
    const raw: unknown = JSON.parse(recordText);
    return !isObject(raw) || raw.python !== payload.python.sha256 || raw.newt !== payload.newt.sha256 || raw.program !== payload.program.sha256;
  } catch {
    return true;
  }
}