src / bootstrap.ts

// Locus plugin-first install, main()'s side (docs\build\PLUGINFIRST_REPORT.md). Pure rules, no I/O:
// - the plan baked into src\baked.ts by `install\plugin_tool.js stage-first` (where Locus goes, which python and
//   repository, the bootstrap.js digest, the environment of the install);
// - the ticket <run_dir>\state\bootstrap.json (made at staging: "this plugin may install Locus once"; written by the
//   bootstrap afterwards: running / failed / done, one attempt per try) and the lock <run_dir>\state\bootstrap.lock
//   (made by the bootstrap itself while it runs: pid + start time);
// - the decision: today's start path, start the bootstrap, or nothing (with the reason).
// bootstrap.js (CommonJS, the detached installer) holds the same rules; tests\plugin_first_rules.test.mjs holds both
// to one table. Erasable TypeScript only.
import { TEST_ROOT_NAME, isAbsWinPath, testPathProblem, testRootProblem } from "./settings.ts";

export const PLAN_SCHEMA = 1;
export const TICKET_FILE = "bootstrap.json";
export const LOCK_FILE = "bootstrap.lock";
export const PLAN_FILE = "bootstrap-plan.json";
export const LOCK_MAX_AGE_MS = 45 * 60_000;   // the bootstrap stops itself after 30 min: an older lock is stale
export const LOCK_GRACE_MS = 60_000;          // an unreadable lock younger than this is a writer between open and write
export const DEFAULT_MAX_PER_DAY = 3;
export const MAX_PLAN_BYTES = 200_000;

// The environment of the install (never process.env): the launch_env names of contract 3.1, the paths install.cmd
// reads, and under MSI_CHAT_TEST only the test switches. MSI_CHAT_ALLOW_REAL is never baked: the bootstrap adds it to
// install.cmd's own environment only for a real plan.
export const BASE_ENV_NAMES: readonly string[] = [
  "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.
export const INSTALL_ENV_NAMES: readonly string[] = [
  "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: readonly string[] = ["MSI_CHAT_PLUGIN_DIR"];
const REQUIRED_ENV_NAMES: readonly string[] = ["SystemRoot", "ComSpec", "PATH", "TEMP", "USERPROFILE",
  ...INSTALL_ENV_NAMES.filter((n) => !OPTIONAL_ENV_NAMES.includes(n))];
// Under MSI_CHAT_TEST these places of the install must lie under MSI_CHAT_TEST_ROOT (the run folder, LM Studio's
// plugin root and CLI, newt, the plugin folder: what a test must never write to or start for real); python and node
// may be real binaries.
const GUARDED_ENV_NAMES: readonly string[] = ["MSI_CHAT_RUN_DIR", "MSI_CHAT_PLUGINS_ROOT", "MSI_CHAT_LMS", "MSI_CHAT_NEWT_EXE", "MSI_CHAT_PLUGIN_DIR"];
const TEST_ENV_NAME = /^MSI_CHAT_TEST(_[A-Z0-9_]+)?$|^MSI_CHAT_NEWT_SHA256$/;
const LONG_TOKEN = /[A-Za-z0-9_-]{40,}/;
const HEX64 = /^[0-9a-f]{64}$/;
const STAGE_ID = /^[0-9a-f]{32}$/;

export interface Plan {
  readonly stageId: string;
  readonly runDir: string;
  readonly stateDir: string;
  readonly logsDir: string;
  readonly python: string;
  readonly bootstrapPath: string;
  readonly bootstrapSha256: string;
  readonly env: Readonly<Record<string, string>>;
  readonly maxPerDay: number;
  readonly real: boolean;
  readonly testMode: boolean;
  readonly text: string;
}

export type PlanResult = { readonly ok: true; readonly plan: Plan } | { readonly ok: false; readonly reason: string };

type Json = Record<string, unknown>;

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

function samePath(a: string, b: string): boolean {
  const n = (p: string): string => p.replace(/\//g, "\\").replace(/\\+$/, "").toLowerCase();
  return n(a) === n(b);
}

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

// null when the install environment is acceptable. `exists` is only used for SystemRoot\System32 (M0: a wrong
// SystemRoot crashed Node).
export function planEnvProblem(env: unknown, testMode: boolean, runDir: string, python: string,
  exists: (p: string) => boolean = () => true): string | null {
  if (!isObject(env)) return "env: not an object";
  const seen = new Set<string>();
  for (const name of Object.keys(env)) {
    const lower = name.toLowerCase();
    if (seen.has(lower)) return "env: a name appears twice (" + name + ")";
    seen.add(lower);
    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") as string;
  if (!isAbsWinPath(systemRoot) || !exists(systemRoot.replace(/[\\/]+$/, "") + "\\System32")) {
    return "env: SystemRoot does not hold System32";
  }
  if (!samePath(lookup(env, "MSI_CHAT_RUN_DIR") as string, runDir)) return "env: MSI_CHAT_RUN_DIR is not the plan's run dir";
  if (!samePath(lookup(env, "MSI_CHAT_PYTHON") as string, 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 as string);
      if (problem !== null) return problem;
    }
  }
  return null;
}

// Parses and checks the baked plan text (the fields main() uses; the bootstrap checks the rest too). Never throws.
export function parsePlan(text: string, options: { readonly testMode?: boolean; readonly exists?: (p: string) => boolean }): PlanResult {
  const fail = (reason: string): PlanResult => ({ ok: false, reason: "plugin-first plan: " + reason });
  if (text.length === 0 || text.length > MAX_PLAN_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 !== PLAN_SCHEMA) return fail("schema is not " + PLAN_SCHEMA);
  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"] as const) {
    if (!isAbsWinPath(raw[field])) return fail(field + " is not an absolute path");
  }
  const python = raw.python as string;
  if (!/(^|\\)python\.exe$/i.test(python) || python.includes(" ")) return fail("python must be a python.exe path without spaces");
  const boot = raw.bootstrap;
  if (!isObject(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");
  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");
  if (typeof raw.real !== "boolean") return fail("real is not true or false");
  const env = raw.env;
  const testMode = options.testMode === true || (isObject(env) && 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 as string).replace(/[\\/]+$/, "");
  const envProblem = planEnvProblem(env, testMode, runDir, python, options.exists);
  if (envProblem !== null) return fail(envProblem);
  if (testMode) {
    // planEnvProblem accepted the root and MSI_CHAT_RUN_DIR (= run_dir by name) under it; said once more for run_dir.
    const runProblem = testPathProblem("run_dir", runDir, lookup(env as Json, TEST_ROOT_NAME) as string);
    if (runProblem !== null) return fail(runProblem);
  }
  return {
    ok: true,
    plan: Object.freeze({
      stageId: raw.stage_id, runDir, stateDir: runDir + "\\state", logsDir: runDir + "\\logs", python,
      bootstrapPath: boot.path, bootstrapSha256: boot.sha256, env: Object.freeze({ ...(env as Record<string, string>) }),
      maxPerDay: max, real: raw.real, testMode, text,
    }),
  };
}

export type TicketState = "pending" | "running" | "failed" | "done";

export interface Attempt {
  readonly at: string;
  readonly ppid: number | null;
  readonly pid: number | null;
  readonly result: "done" | "failed" | null;
  readonly step: string | null;
  readonly reason: string | null;
}

export interface Ticket {
  readonly stageId: string;
  readonly state: TicketState;
  readonly attempts: readonly Attempt[];
  readonly done: string | null;
}

const STATES: readonly string[] = ["pending", "running", "failed", "done"];

function intOrNull(value: unknown): number | null {
  return typeof value === "number" && Number.isInteger(value) ? value : null;
}

function strOrNull(value: unknown): string | null {
  return typeof value === "string" ? value : null;
}

// The ticket of THIS stage, or null (none, unreadable, or another stage's).
export function parseTicket(text: string | null, stageId: string): Ticket | null {
  if (text === null) return null;
  let raw: unknown;
  try {
    raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
  } catch {
    return null;
  }
  if (!isObject(raw) || raw.schema !== 1 || raw.stage_id !== stageId || !STATES.includes(raw.state as string)) return null;
  const attempts = Array.isArray(raw.attempts) ? raw.attempts.filter(isObject).map((a): Attempt => ({
    at: typeof a.at === "string" ? a.at : "", ppid: intOrNull(a.ppid), pid: intOrNull(a.pid),
    result: a.result === "done" || a.result === "failed" ? a.result : null, step: strOrNull(a.step), reason: strOrNull(a.reason),
  })) : [];
  return { stageId, state: raw.state as TicketState, attempts, done: strOrNull(raw.done) };
}

export interface LockView {
  readonly state: "none" | "fresh" | "stale";
  readonly pid: number | null;
  readonly started: string | null;
}

// The lock's stale rules: none = no file; stale = its pid is gone, or it is older than LOCK_MAX_AGE_MS (a reused pid
// or a hung bootstrap), or its start lies in the future, or it is unreadable for longer than LOCK_GRACE_MS.
export function lockState(text: string | null, mtimeMs: number | null, nowMs: number, alive: (pid: number) => boolean): LockView {
  if (text === null) return { state: "none", pid: null, started: null };
  let raw: unknown = null;
  try {
    raw = JSON.parse(text);
  } catch {
    raw = null;
  }
  const pid = isObject(raw) ? intOrNull(raw.pid) : null;
  const started = isObject(raw) ? strOrNull(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 };
}

export function attemptsToday(ticket: Ticket, now: Date): number {
  const day = now.toISOString().slice(0, 10);
  return ticket.attempts.filter((a) => a.at.slice(0, 10) === day).length;
}

// main() asks whether Locus is installed (answering /health; or autostart on, install.json and the release verified:
// the install finished) for every ticket that is not done while no bootstrap runs (F1: a failed or stale ticket never
// blocks an installed Locus and is never run over a running one; a half-made install is installed over), and on a Hub
// install also when there is no ticket (installed or not decides).
export function needsInstalledCheck(ticket: Ticket | null, lock: Pick<LockView, "state">, hub = false): boolean {
  if (lock.state === "fresh") return false;
  return ticket === null ? hub : ticket.state !== "done";
}

export interface Facts {
  readonly ticket: Ticket | null;
  readonly lock: LockView;
  readonly installed: boolean | null;
  readonly ppid: number;
  readonly now: Date;
  readonly maxPerDay: number;
  readonly hub?: boolean;      // a Hub install: no ticket and Locus not installed means "write the ticket, then install"
}

export type BootstrapDecision =
  | { readonly action: "legacy" }
  | { readonly action: "ticket" }
  | { readonly action: "spawn"; readonly attempt: number }
  | { readonly action: "wait"; readonly result: "install-running" | "install-waiting"; readonly reason: string };

function lastReason(ticket: Ticket): string {
  const last = ticket.attempts[ticket.attempts.length - 1];
  if (last === undefined) return "no reason recorded";
  if (last.result === null) return "the last attempt stopped without a result (see bootstrap.log)";
  return (last.step !== null ? "at " + last.step + ": " : "") + (last.reason ?? "no reason recorded");
}

export function decideBootstrap(f: Facts): BootstrapDecision {
  const t = f.ticket;
  if (t !== null && t.state === "done") return { action: "legacy" };
  if (f.lock.state === "fresh") {
    return { action: "wait", result: "install-running",
      reason: "Locus is installing itself (bootstrap pid " + String(f.lock.pid) + ", since " + String(f.lock.started) + ")" };
  }
  if (f.installed === true) return { action: "legacy" };                       // F1: installed, whatever the ticket says
  if (t === null) return f.hub === true && f.installed === false ? { action: "ticket" } : { action: "legacy" };
  if (t.attempts.length === 0) return { action: "spawn", attempt: 1 };
  const why = lastReason(t);
  const today = attemptsToday(t, f.now);
  if (today >= f.maxPerDay) {
    return { action: "wait", result: "install-waiting", reason: "the install failed " + today + " attempts today (at most " +
      f.maxPerDay + " a day): " + why + ". It tries again tomorrow at the next LM Studio start, or run main\\install.cmd " +
      "/plugin-first again" };
  }
  if (t.attempts.some((a) => a.ppid === f.ppid)) {
    return { action: "wait", result: "install-waiting",
      reason: "the install failed in this LM Studio session: " + why + ". It tries again at the next LM Studio start" };
  }
  return { action: "spawn", attempt: t.attempts.length + 1 };
}