src / start.ts

// MSI chat plugin: the first box of the start chain (build contract section 4).
// main() -> startMsiChat(): read the baked settings path; return when there are no valid settings, when
// start_with_lmstudio is not true, when <state_dir>\stopped.flag exists, or when /health already says msi-chat;
// otherwise start launcher.js with this node.exe (detached, hidden, stdio ignored, env = launch_env exactly,
// cwd = run_dir) and wait for it to exit (10 s at most). LM Studio tree-kills the plugin 0.06-0.22 s after
// main() returns (M0), so the launcher must have exited by then: its child is then outside the plugin's tree.
// One JSON line per run goes to <logs_dir>\plugin.jsonl: names of variables only, never values.
// Plugin-first (docs\build\PLUGINFIRST_REPORT.md): when the stage baked a plan (src\baked.ts BOOTSTRAP_PLAN), main()
// first reads the install ticket and lock in <run_dir>\state (src\bootstrap.ts decides): a ticket that still waits
// for its install starts bootstrap.js the launcher's way ("installing"); a running bootstrap or the retry rules give
// "install-running" / "install-waiting" with the reason; a done or absent ticket is today's path below.
// The Hub install (docs\build\HUBPLAN_REPORT.md): with no path and no plan baked but HUB_FILES (the digests made at
// publish time), main() derives the plan from its own folder <home>\extensions\plugins\<owner>\<name> and USERPROFILE
// (src\hub.ts), writes the ticket itself when Locus is not installed, and runs the same plugin-first path. A PC
// without the installer (<home>\msi-chat) gets one line and nothing else. Every run appends a marker line
// {t, event, mode: staged | hub | inert, result} to <plugin folder>\locus-plugin.log (names only).
// The buyer's install (docs\build\PC_INSTALL_REPORT.md): a Hub copy published with the buyer payload (HUB_FILES.payload)
// on a PC WITHOUT the installer repository derives the buyer's plan instead (src\hub.ts, the buyer's part): the place
// <USERPROFILE>\AppData\Local\Locus, the pins, the carried program; the bootstrap downloads and lays it all down. With the
// repository present (the owner's PC) nothing changes.
import { spawn as nodeSpawn, spawnSync as nodeSpawnSync } from "node:child_process";
import type { SpawnOptions, SpawnSyncOptions } from "node:child_process";
import { createHash } from "node:crypto";
import * as nodeFs from "node:fs";
import * as nodeHttp from "node:http";
import { BOOTSTRAP_PLAN, HUB_FILES, SETTINGS_PATH } from "./baked.ts";
import {
  LOCK_FILE, PLAN_FILE, TICKET_FILE, attemptsToday, decideBootstrap, lockState, needsInstalledCheck, parsePlan, parseTicket,
} from "./bootstrap.ts";
import type { Plan } from "./bootstrap.ts";
import {
  PLUGIN_LOG, TEST_HUB_ARGS_NAME, UNINSTALLED_MARKER, buildHubPlan, findPluginFolder, hubEnv, hubMissing, hubPaths, hubShape,
  hubTicketText, parseHubFiles, parseTestHubArgs, pluginFolderCandidates, testOverrides,
} from "./hub.ts";
import type { HubFiles, PluginFolder, PluginPlace } from "./hub.ts";
import {
  BUYER_REL, INSTALLED_FILE, PAYLOAD_MODULE, buildBuyerPlan, buyerLayout, buyerMissing, buyerPaths, buyerRoot, parsePayload, payloadOutdated,
  programDataOf, programFilesMismatch, spaceFreeRoot,
} from "./hub.ts";
import { TEST_ROOT_NAME, isUnderTestRoot, parseSettingsText, testPathProblem, testRootProblem } from "./settings.ts";
import type { PluginSettings } from "./settings.ts";

export type StartResult = "no-settings" | "disabled" | "stopped" | "already-running" | "started" | "error"
  | "installing" | "install-running" | "install-waiting" | "no-installer";
export type Mode = "staged" | "hub" | "inert";

export const LAUNCHER_WAIT_MS = 10_000;
export const HEALTH_TIMEOUT_MS = 1_500;
export const HEALTH_MAX_BYTES = 65_536;

export interface StartFs {
  readFileSync(path: string, encoding: "utf8"): string;
  existsSync(path: string): boolean;
  appendFileSync(path: string, data: string): void;
  mkdirSync(path: string, options: { recursive: true }): unknown;
}

export interface HealthAnswer {
  readonly status: number;
  readonly body: string;
}

export type HealthGet = (host: string, port: number, timeoutMs: number) => Promise<HealthAnswer | null>;

export interface ChildLike {
  readonly pid?: number | undefined;
  once(event: "exit", listener: (code: number | null, signal: string | null) => void): unknown;
  once(event: "error", listener: (err: Error) => void): unknown;
  unref(): void;
  kill?(): boolean;
}

export type SpawnFn = (command: string, args: readonly string[], options: SpawnOptions) => ChildLike;
export type SpawnSyncFn = (command: string, args: readonly string[], options: SpawnSyncOptions) => { readonly status: number | null };

// The plugin-first reads and writes, injectable for tests.
export interface PluginFirstIo {
  readText(path: string): string | null;
  mtimeMs(path: string): number | null;
  writeText(path: string, text: string): void;
  mkdirs(path: string): void;
  sha256(path: string): string | null;
  alive(pid: number): boolean;
}

export interface StartDeps {
  readonly settingsPath?: string;
  readonly fs?: StartFs;
  readonly healthGet?: HealthGet;
  readonly spawn?: SpawnFn;
  readonly nodePath?: string;
  readonly waitMs?: number;
  readonly healthTimeoutMs?: number;
  readonly now?: () => Date;
  readonly env?: Readonly<Record<string, string | undefined>>;
  readonly pid?: number;
  readonly ppid?: number;
  readonly planText?: string;
  readonly hubFilesText?: string;
  readonly candidates?: readonly string[];      // the plugin's own folder candidates (tests); else from the runtime
  readonly pfIo?: PluginFirstIo;
  readonly verifyInstalled?: (settingsPath: string, testMode: boolean) => boolean;
}

export interface LaunchCommand {
  readonly command: string;
  readonly args: readonly string[];
  readonly options: SpawnOptions;
}

// GET /health on <host>:<port> (plain HTTP) with a hard time limit; null on any failure. Never throws.
export function httpHealthGet(host: string, port: number, timeoutMs: number): Promise<HealthAnswer | null> {
  return new Promise((resolve) => {
    let settled = false;
    let timer: ReturnType<typeof setTimeout> | undefined;
    const finish = (answer: HealthAnswer | null): void => {
      if (settled) return;
      settled = true;
      if (timer !== undefined) clearTimeout(timer);
      resolve(answer);
    };
    const req = nodeHttp.get(
      { host, port, path: "/health", agent: false, timeout: timeoutMs, headers: { Accept: "application/json" } },
      (res) => {
        let body = "";
        res.setEncoding("utf8");
        res.on("data", (chunk: string) => {
          body += chunk;
          if (body.length > HEALTH_MAX_BYTES) {
            req.destroy();
            finish(null);
          }
        });
        res.on("end", () => finish({ status: res.statusCode ?? 0, body }));
        res.on("error", () => finish(null));
      },
    );
    timer = setTimeout(() => {
      req.destroy();
      finish(null);
    }, timeoutMs);
    req.on("timeout", () => {
      req.destroy();
      finish(null);
    });
    req.on("error", () => finish(null));
  });
}

// "Already running" (contract 4.1): 200 with JSON whose app is "msi-chat". Anything else is "not ours".
export function isMsiChatHealth(answer: HealthAnswer | null): boolean {
  if (answer === null || answer.status !== 200) return false;
  try {
    const parsed: unknown = JSON.parse(answer.body);
    return typeof parsed === "object" && parsed !== null && (parsed as { app?: unknown }).app === "msi-chat";
  } catch {
    return false;
  }
}

function hasLmsName(env: Readonly<Record<string, string>>): boolean {
  return Object.keys(env).some((name) => /^LMS_/i.test(name));
}

// The launcher's command line (contract section 4): <node.exe> <settings.launcher> <settings path>.
export function launchCommand(settings: PluginSettings, settingsPath: string, nodePath: string): LaunchCommand {
  const env: Record<string, string> = { ...settings.launchEnv };
  if (hasLmsName(env)) throw new Error("launch_env holds an LMS_* name");
  return {
    command: nodePath,
    args: [settings.launcher, settingsPath],
    options: { detached: true, windowsHide: true, stdio: "ignore", env, cwd: settings.runDir },
  };
}

interface LauncherOutcome {
  readonly code?: number | null;
  readonly error?: string;
  readonly timedOut?: boolean;
}

function waitExit(child: ChildLike, waitMs: number): Promise<LauncherOutcome> {
  return new Promise((resolve) => {
    const timer = setTimeout(() => resolve({ timedOut: true }), waitMs);
    child.once("exit", (code) => {
      clearTimeout(timer);
      resolve({ code });
    });
    child.once("error", (err) => {
      clearTimeout(timer);
      resolve({ error: String((err as NodeJS.ErrnoException).code ?? "spawn error") });
    });
  });
}

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

interface Decision {
  readonly result: StartResult;
  readonly logsDir: string | null;
  readonly note: Note;
}

function errorName(err: unknown): string {
  if (err instanceof Error) return String((err as NodeJS.ErrnoException).code ?? err.name);
  return "error";
}

function lookupEnv(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;
}

async function startLauncher(settings: PluginSettings, settingsPath: string, deps: StartDeps): Promise<Decision> {
  const launchEnvNames = Object.keys(settings.launchEnv).sort();
  let child: ChildLike;
  try {
    const cmd = launchCommand(settings, settingsPath, deps.nodePath ?? process.execPath);
    const spawn = deps.spawn ?? (nodeSpawn as unknown as SpawnFn);
    child = spawn(cmd.command, cmd.args, cmd.options);
  } catch (err) {
    return { result: "error", logsDir: settings.logsDir, note: { launchEnvNames, reason: "launch failed " + errorName(err) } };
  }
  const outcome = await waitExit(child, deps.waitMs ?? LAUNCHER_WAIT_MS);
  if (outcome.timedOut) child.kill?.();
  child.unref();
  const note: Note = { launcherPid: child.pid ?? null, launchEnvNames };
  if (outcome.timedOut) return { result: "error", logsDir: settings.logsDir, note: { ...note, reason: "launcher did not exit in time" } };
  if (outcome.error !== undefined) return { result: "error", logsDir: settings.logsDir, note: { ...note, reason: "launcher spawn error " + outcome.error } };
  if (outcome.code !== 0) return { result: "error", logsDir: settings.logsDir, note: { ...note, reason: "launcher exit " + String(outcome.code) } };
  return { result: "started", logsDir: settings.logsDir, note: { ...note, launcherExit: 0 } };
}

// --- plugin-first -------------------------------------------------------------------------------------------------

function nodePluginFirstIo(): PluginFirstIo {
  return {
    readText: (p) => {
      try {
        return nodeFs.readFileSync(p, "utf8");
      } catch {
        return null;
      }
    },
    mtimeMs: (p) => {
      try {
        return nodeFs.statSync(p).mtimeMs;
      } catch {
        return null;
      }
    },
    writeText: (p, text) => nodeFs.writeFileSync(p, text, "utf8"),
    mkdirs: (p) => {
      nodeFs.mkdirSync(p, { recursive: true });
    },
    sha256: (p) => {
      try {
        return createHash("sha256").update(nodeFs.readFileSync(p)).digest("hex");
      } catch {
        return null;
      }
    },
    alive: (pid) => {
      try {
        process.kill(pid, 0);
        return true;
      } catch (err) {
        return (err as NodeJS.ErrnoException).code === "EPERM";
      }
    },
  };
}

// "Installed" for the plugin-first decision: settings.json passes the plugin's checks, its secrets folder still holds
// install.json (an uninstall without /purge keeps settings.json, the release and the verifier, but removes
// install.json: that Locus is uninstalled), AND the verifier on C: (settings.keepalive = <secrets_dir>\msi_verify.py)
// says the release and settings.json are as installed (`msi_verify.py --check`, the checks it makes before every
// start). Never throws.
export function defaultVerifyInstalled(settingsPath: string, testMode: boolean,
  deps: { readonly spawnSync?: SpawnSyncFn; readonly fs?: StartFs; readonly testRoot?: string } = {}): boolean {
  const fs: StartFs = deps.fs ?? (nodeFs as unknown as StartFs);
  try {
    if (!fs.existsSync(settingsPath)) return false;
    const text = fs.readFileSync(settingsPath, "utf8");
    const checked = parseSettingsText(text, { exists: (p) => fs.existsSync(p) }, { testMode, testRoot: deps.testRoot });
    if (!checked.ok || !/(^|\\)msi_verify\.py$/i.test(checked.settings.keepalive)) return false;
    const secretsDir = checked.settings.keepalive.replace(/\\[^\\]+$/, "");
    const raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text) as { secrets_dir?: unknown };
    if (typeof raw.secrets_dir !== "string" || raw.secrets_dir.replace(/[\\/]+$/, "").toLowerCase() !== secretsDir.toLowerCase()) return false;
    if (!fs.existsSync(secretsDir + "\\install.json")) return false;
    const s = checked.settings;
    const run = deps.spawnSync ?? (nodeSpawnSync as unknown as SpawnSyncFn);
    const res = run(s.python, ["-I", "-B", "-X", "utf8", s.keepalive, "--check", "--settings", settingsPath],
      { env: { ...s.launchEnv }, cwd: s.runDir, windowsHide: true, stdio: "ignore", timeout: 20_000 });
    return res.status === 0;
  } catch {
    return false;
  }
}

// "Installed" for the plugin-first decision (F1): a Locus that answers /health on the settings' admin port is installed
// and running, whatever the verifier says (never installed over); otherwise the install must have FINISHED: autostart on
// (start_with_lmstudio true) is install.cmd /from-plugin's last step, so a settings.json without it is a half-made
// install (an attempt that failed after the release was laid down) and is installed over; then the verifier's word
// (defaultVerifyInstalled: install.json and `msi_verify.py --check`). Never throws.
async function installedForDecision(settingsPath: string, testMode: boolean, deps: StartDeps, fs: StartFs, env: Env): Promise<boolean> {
  try {
    if (!fs.existsSync(settingsPath)) return false;
    const checked = parseSettingsText(fs.readFileSync(settingsPath, "utf8"), { exists: (p) => fs.existsSync(p) }, { testMode, testRoot: env[TEST_ROOT_NAME] });
    if (!checked.ok) return false;
    const healthGet = deps.healthGet ?? httpHealthGet;
    if (isMsiChatHealth(await healthGet(checked.settings.adminHost, checked.settings.adminPort, deps.healthTimeoutMs ?? HEALTH_TIMEOUT_MS))) return true;
    if (checked.settings.startWithLmstudio !== true) return false;
    const verify = deps.verifyInstalled ?? ((p, t) => defaultVerifyInstalled(p, t, { fs, testRoot: env[TEST_ROOT_NAME] }));
    return verify(settingsPath, testMode);
  } catch {
    return false;
  }
}

async function spawnBootstrap(plan: Plan, ppid: number, io: PluginFirstIo, deps: StartDeps, note: Note): Promise<Decision> {
  const fail = (reason: string, extra: Note = {}): Decision => ({ result: "error", logsDir: plan.logsDir, note: { ...note, ...extra, reason } });
  if (io.sha256(plan.bootstrapPath) !== plan.bootstrapSha256) {
    return fail("bootstrap.js differs from the digest baked into this plugin: stage it again (main\\install.cmd /plugin-first), or install the plugin again");
  }
  const planFile = plan.stateDir + "\\" + PLAN_FILE;
  const env: Record<string, string> = { ...plan.env };
  if (hasLmsName(env)) return fail("the plan's env holds an LMS_* name");
  let child: ChildLike;
  try {
    io.mkdirs(plan.stateDir);
    io.mkdirs(plan.logsDir);
    io.writeText(planFile, plan.text);
    const sha = createHash("sha256").update(plan.text, "utf8").digest("hex");
    const spawn = deps.spawn ?? (nodeSpawn as unknown as SpawnFn);
    child = spawn(deps.nodePath ?? process.execPath, [plan.bootstrapPath, "detach", "--plan", planFile, "--plan-sha256", sha, "--ppid", String(ppid)],
      { detached: true, windowsHide: true, stdio: "ignore", env, cwd: plan.runDir });
  } catch (err) {
    return fail("the bootstrap could not be started " + errorName(err));
  }
  const outcome = await waitExit(child, deps.waitMs ?? LAUNCHER_WAIT_MS);
  if (outcome.timedOut) child.kill?.();
  child.unref();
  const extra: Note = { bootstrapDetacherPid: child.pid ?? null, bootstrapEnvNames: Object.keys(env).sort() };
  if (outcome.timedOut) return fail("the bootstrap's detacher did not exit in time", extra);
  if (outcome.error !== undefined) return fail("bootstrap spawn error " + outcome.error, extra);
  if (outcome.code !== 0) return fail("the bootstrap's detacher ended with exit " + String(outcome.code), extra);
  return { result: "installing", logsDir: plan.logsDir, note: { ...note, ...extra } };
}

interface PluginFirstOutcome {
  readonly decision: Decision | null;      // null: today's start path, with `note` added to its line
  readonly note: Note;
  readonly logsDir: string | null;
}

interface HubTicket {
  readonly text: string;      // the ticket main() writes when a Hub install finds Locus not installed and no ticket
  readonly outdated?: boolean;  // review M4: a buyer's Locus laid down from another payload: installed over (an update)
}

async function pluginFirst(planText: string, settingsPath: string, deps: StartDeps, fs: StartFs, env: Env,
  hub: HubTicket | null): Promise<PluginFirstOutcome> {
  const parsed = parsePlan(planText, { testMode: env.MSI_CHAT_TEST === "1", exists: (p) => fs.existsSync(p) });
  if (!parsed.ok) return { decision: { result: "error", logsDir: null, note: { reason: parsed.reason } }, note: {}, logsDir: null };
  const plan = parsed.plan;
  const io = deps.pfIo ?? nodePluginFirstIo();
  const now = (deps.now ?? (() => new Date()))();
  const ticketPath = plan.stateDir + "\\" + TICKET_FILE;
  let ticket = parseTicket(io.readText(ticketPath), plan.stageId);
  const lockPath = plan.stateDir + "\\" + LOCK_FILE;
  const lock = lockState(io.readText(lockPath), io.mtimeMs(lockPath), now.getTime(), (pid) => io.alive(pid));
  const ppid = deps.ppid ?? process.ppid;
  const installed: boolean | null = needsInstalledCheck(ticket, lock, hub !== null)
    ? (hub !== null && hub.outdated === true ? false : await installedForDecision(settingsPath, plan.testMode, deps, fs, env))
    : null;
  let decision = decideBootstrap({ ticket, lock, installed, ppid, now, maxPerDay: plan.maxPerDay, hub: hub !== null });
  if (decision.action === "ticket" && hub !== null) {
    try {
      io.mkdirs(plan.stateDir);
      io.mkdirs(plan.logsDir);
      io.writeText(ticketPath, hub.text);
    } catch (err) {
      return { decision: { result: "error", logsDir: plan.logsDir, note: { reason: "the install ticket could not be written " + errorName(err) } }, note: {}, logsDir: plan.logsDir };
    }
    ticket = parseTicket(hub.text, plan.stageId);
    decision = decideBootstrap({ ticket, lock, installed, ppid, now, maxPerDay: plan.maxPerDay, hub: true });
  }
  const note: Note = { pluginFirst: { stage: plan.stageId.slice(0, 8), ticket: ticket === null ? "none" : ticket.state,
    attemptsToday: ticket === null ? 0 : attemptsToday(ticket, now), ...(installed === null ? {} : { installed }) } };
  if (decision.action === "legacy" || decision.action === "ticket") return { decision: null, note, logsDir: plan.logsDir };
  if (decision.action === "wait") {
    return { decision: { result: decision.result, logsDir: plan.logsDir, note: { ...note, reason: decision.reason } }, note, logsDir: plan.logsDir };
  }
  return { decision: await spawnBootstrap(plan, ppid, io, deps, { ...note, attempt: decision.attempt }), note, logsDir: plan.logsDir };
}

// A plan (staged or derived) in front of today's start path.
async function decideWithPlan(planText: string, settingsPath: string, deps: StartDeps, fs: StartFs, env: Env, hub: HubTicket | null): Promise<Decision> {
  const pf = await pluginFirst(planText, settingsPath, deps, fs, env, hub);
  if (pf.decision !== null) return pf.decision;
  const legacy = await decideStart(settingsPath, deps, fs, env);
  return { result: legacy.result, logsDir: legacy.logsDir ?? pf.logsDir, note: { ...legacy.note, ...pf.note } };
}

// --- the Hub install ------------------------------------------------------------------------------------------------

function readManifest(fs: StartFs, dir: string): unknown {
  try {
    const file = dir + "\\manifest.json";
    if (!fs.existsSync(file)) return null;
    const text = fs.readFileSync(file, "utf8");
    return JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
  } catch {
    return null;
  }
}

// The plan derived from the plugin's place and the environment, then the plugin-first path with it.
async function decideHub(hubText: string, place: PluginPlace, deps: StartDeps, fs: StartFs, env: Env): Promise<Decision> {
  const fail = (reason: string): Decision => ({ result: "error", logsDir: null, note: { reason } });
  const testMode = env.MSI_CHAT_TEST === "1";
  if (testMode) {
    const rootProblem = testRootProblem(env[TEST_ROOT_NAME]);
    if (rootProblem !== null) return fail("refused under MSI_CHAT_TEST: " + rootProblem);
    const placeProblem = testPathProblem("the plugin folder", place.pluginDir, env[TEST_ROOT_NAME] as string);
    if (placeProblem !== null) return fail(placeProblem);
  }
  const parsedHub = parseHubFiles(hubText);
  if (!parsedHub.ok) return fail(parsedHub.reason);
  const derived = hubPaths(place, lookupEnv(env, "USERPROFILE"));
  if (derived === null) return fail("USERPROFILE is not a usable folder in the plugin's environment");
  const paths = testOverrides(derived, env, testMode);
  const settingsPath = paths.runDir + "\\settings.json";
  if (fs.existsSync(place.pluginDir + "\\" + UNINSTALLED_MARKER)) {
    // uninstall.cmd left this plugin in LM Studio: it never installs Locus again by itself; an installed Locus still starts
    const legacy = await decideStart(settingsPath, deps, fs, env);
    return { ...legacy, note: { ...legacy.note, uninstalled: true } };
  }
  const missing = hubMissing(paths, (p) => fs.existsSync(p));
  const repoHere = fs.existsSync(paths.repo) && fs.existsSync(paths.repo + "\\main\\install.cmd");
  if (missing !== null && !repoHere && hasPayload(hubText)) return decideBuyer(hubText, parsedHub.hub, place, deps, fs, env, testMode);
  if (missing !== null) return { result: "no-installer", logsDir: null, note: { note: missing } };
  const planEnv = hubEnv(env, paths, testMode);
  if (!planEnv.ok) return fail(planEnv.reason);
  const testArgs = testMode ? parseTestHubArgs(env[TEST_HUB_ARGS_NAME]) : { ok: true as const, args: [] as readonly string[] };
  if (!testArgs.ok) return fail(testArgs.reason);
  const made = (deps.now ?? (() => new Date()))().toISOString();
  const built = buildHubPlan(parsedHub.hub, paths, planEnv.env, testMode, testArgs.args, made);
  if (!built.ok) return fail(built.reason);
  return decideWithPlan(built.text, settingsPath, deps, fs, env, { text: hubTicketText(parsedHub.hub, paths, made) });
}

// --- the buyer's install (src\hub.ts) --------------------------------------------------------------------------------

function payloadOf(hubText: string): unknown {
  try {
    const raw: unknown = JSON.parse(hubText);
    return typeof raw === "object" && raw !== null ? (raw as Record<string, unknown>).payload : undefined;
  } catch {
    return undefined;
  }
}

function hasPayload(hubText: string): boolean {
  return payloadOf(hubText) !== undefined;
}

// A stranger's PC: the buyer's place and plan, checked here without any network (6a: nothing network-bound in main()),
// then the plugin-first path with it. Refusals write nothing but the marker line. A user folder with a space puts Python
// in the space-free root (the review round). An installed Locus laid down from another payload is installed over
// (review M4: the update; the old program is not started meanwhile).
async function decideBuyer(hubText: string, hub: HubFiles, place: PluginPlace, deps: StartDeps, fs: StartFs, env: Env,
  testMode: boolean): Promise<Decision> {
  const fail = (reason: string): Decision => ({ result: "error", logsDir: null, note: { reason } });
  const parsed = parsePayload(payloadOf(hubText), testMode);
  if (!parsed.ok) return fail(parsed.reason);
  const mismatch = programFilesMismatch(parsed.payload, hub);
  if (mismatch !== null) return fail(mismatch);
  const root = buyerRoot(lookupEnv(env, "USERPROFILE"));
  if (!root.ok) return { result: "no-installer", logsDir: null, note: { note: root.note } };
  const profile = root.root.slice(0, -(BUYER_REL.length + 1));
  let spaceFree: string | null = null;
  if (/\s/.test(root.root)) {
    const programData = programDataOf(env, testMode);
    if (programData === null) return { result: "no-installer", logsDir: null, note: { note: "Locus: ProgramData is not known in the plugin's environment: nothing done" } };
    spaceFree = spaceFreeRoot(profile, programData);
  }
  const layout = buyerLayout(root.root, parsed.payload, testMode, spaceFree);
  const node = place.home + "\\.internal\\utils\\node.exe";
  const missing = buyerMissing(place, node, parsed.payload, (p) => fs.existsSync(p));
  if (missing !== null) return { result: "no-installer", logsDir: null, note: { note: missing } };
  const io = deps.pfIo ?? nodePluginFirstIo();
  if (io.sha256(place.pluginDir + "\\" + PAYLOAD_MODULE) !== parsed.payload.module_sha256) {
    return fail("payload.js differs from the digest baked into this plugin: install the plugin again from LM Studio");
  }
  const planEnv = hubEnv(env, buyerPaths(place, layout, node), testMode, profile);
  if (!planEnv.ok) return fail(planEnv.reason);
  const testArgs = testMode ? parseTestHubArgs(env[TEST_HUB_ARGS_NAME]) : { ok: true as const, args: [] as readonly string[] };
  if (!testArgs.ok) return fail(testArgs.reason);
  const made = (deps.now ?? (() => new Date()))().toISOString();
  const built = buildBuyerPlan(hub, parsed.payload, place, layout, node, planEnv.env, testMode, testArgs.args, made);
  if (!built.ok) return fail(built.reason);
  const ticket = hubTicketText(hub, buyerPaths(place, layout, node), made);
  const settingsPath = layout.runDir + "\\settings.json";
  const outdated = fs.existsSync(settingsPath) && payloadOutdated(io.readText(layout.root + "\\" + INSTALLED_FILE), parsed.payload);
  return decideWithPlan(built.text, settingsPath, deps, fs, env, { text: ticket, outdated });
}

// --- today's start path -------------------------------------------------------------------------------------------

async function decideStart(settingsPath: string, deps: StartDeps, fs: StartFs, env: Env): Promise<Decision> {
  if (settingsPath === "") return { result: "no-settings", logsDir: null, note: { reason: "not staged" } };
  const testMode = env.MSI_CHAT_TEST === "1";
  if (testMode) {
    // The plugin's own test switch needs its own root; the settings file must lie under it before it is even read.
    const rootProblem = testRootProblem(env[TEST_ROOT_NAME]);
    if (rootProblem !== null) return { result: "error", logsDir: null, note: { reason: "refused under MSI_CHAT_TEST: " + rootProblem } };
    const fileProblem = testPathProblem("the settings file", settingsPath, env[TEST_ROOT_NAME] as string);
    if (fileProblem !== null) return { result: "error", logsDir: null, note: { reason: fileProblem } };
  }
  if (!fs.existsSync(settingsPath)) return { result: "no-settings", logsDir: null, note: { reason: "no settings file" } };
  let text: string;
  try {
    text = fs.readFileSync(settingsPath, "utf8");
  } catch (err) {
    return { result: "no-settings", logsDir: null, note: { reason: "settings unreadable " + errorName(err) } };
  }
  const checked = parseSettingsText(text, { exists: (p) => fs.existsSync(p) }, { testMode, testRoot: env[TEST_ROOT_NAME] });
  if (!checked.ok) {
    return { result: checked.refused ? "error" : "no-settings", logsDir: checked.logsDir, note: { reason: checked.reason } };
  }
  const settings = checked.settings;
  if (settings.startWithLmstudio !== true) return { result: "disabled", logsDir: settings.logsDir, note: {} };
  if (fs.existsSync(settings.stateDir + "\\stopped.flag")) return { result: "stopped", logsDir: settings.logsDir, note: {} };
  const healthGet = deps.healthGet ?? httpHealthGet;
  const answer = await healthGet(settings.adminHost, settings.adminPort, deps.healthTimeoutMs ?? HEALTH_TIMEOUT_MS);
  if (isMsiChatHealth(answer)) return { result: "already-running", logsDir: settings.logsDir, note: {} };
  return startLauncher(settings, settingsPath, deps);
}

function writeLog(fs: StartFs, logsDir: string | null, line: Note): void {
  if (logsDir === null) return;
  try {
    fs.mkdirSync(logsDir, { recursive: true });
    fs.appendFileSync(logsDir + "\\plugin.jsonl", JSON.stringify(line) + "\n");
  } catch {
    // Logging must never make main() fail.
  }
}

// The test switch that guards the plugin's OWN folder (where the marker line goes): the plugin's environment, or the
// process's (a test process runs the start code from the repository: its plugin folder is never written to).
function ownFolderGuard(env: Env): { readonly testMode: boolean; readonly root: string | undefined } {
  if (env.MSI_CHAT_TEST === "1") return { testMode: true, root: env[TEST_ROOT_NAME] };
  if (process.env.MSI_CHAT_TEST === "1") return { testMode: true, root: process.env[TEST_ROOT_NAME] };
  return { testMode: false, root: undefined };
}

// The marker line of this run, in the plugin's own folder (<plugin>\locus-plugin.log): a Hub install proves main() ran.
// Only an INSTALLED plugin's folder (<home>\extensions\plugins\<owner>\<name>, the Hub's and lms dev -i's shape) gets
// it, never the source folder the tests run from; under MSI_CHAT_TEST only one under the test's root.
function writeMarker(fs: StartFs, place: PluginPlace | null, env: Env, line: Note): void {
  if (place === null) return;
  const guard = ownFolderGuard(env);
  if (guard.testMode && (typeof guard.root !== "string" || !isUnderTestRoot(place.pluginDir, guard.root))) return;
  try {
    fs.appendFileSync(place.pluginDir + "\\" + PLUGIN_LOG, JSON.stringify(line) + "\n");
  } catch {
    // never makes main() fail
  }
}

// The folders main() looks at for its own place. Under MSI_CHAT_TEST only folders under the test's root are even
// looked at (a refused run reads nothing outside it); an unusable root means no place at all.
function candidatesFor(deps: StartDeps, env: Env): readonly string[] {
  const all = deps.candidates ?? pluginFolderCandidates(import.meta.url, process.argv[1], process.cwd());
  const guard = ownFolderGuard(env);
  if (!guard.testMode) return all;
  if (typeof guard.root !== "string" || testRootProblem(guard.root) !== null) return [];
  return all.filter((c) => isUnderTestRoot(c, guard.root as string));
}

// What this copy of the plugin is: staged (a settings path or a plan baked in), hub (the digests baked in and the
// folder is a Hub install's), inert (the repository copy, or a Hub copy in a folder of another shape).
function modeOf(planText: string, settingsPath: string, hubText: string, place: PluginPlace | null): Mode {
  if (planText !== "" || settingsPath !== "") return "staged";
  if (hubText !== "" && place !== null) return "hub";
  return "inert";
}

// The plugin's whole job. Never throws; always resolves to one of the StartResult values.
export async function startMsiChat(deps: StartDeps = {}): Promise<StartResult> {
  const fs: StartFs = deps.fs ?? (nodeFs as unknown as StartFs);
  const env = deps.env ?? process.env;
  const now = (deps.now ?? (() => new Date()))().toISOString();
  const pid = deps.pid ?? process.pid;
  const ppid = deps.ppid ?? process.ppid;
  const base: Note = { t: now, event: "main", pid, ppid, envNames: Object.keys(env).sort() };
  const planText = deps.planText ?? BOOTSTRAP_PLAN;
  const settingsPath = deps.settingsPath ?? SETTINGS_PATH;
  const hubText = deps.hubFilesText ?? HUB_FILES;
  let folder: PluginFolder | null = null;
  let place: PluginPlace | null = null;
  let decision: Decision;
  // The plugin's own test switch needs its own root before anything is read or looked for.
  const rootProblem = env.MSI_CHAT_TEST === "1" ? testRootProblem(env[TEST_ROOT_NAME]) : null;
  if (rootProblem === null) {
    try {
      folder = findPluginFolder(candidatesFor(deps, env), (dir) => readManifest(fs, dir));
      place = hubShape(folder);
    } catch {
      folder = null;
      place = null;
    }
  }
  const mode = modeOf(planText, settingsPath, hubText, place);
  try {
    if (rootProblem !== null) decision = { result: "error", logsDir: null, note: { reason: "refused under MSI_CHAT_TEST: " + rootProblem } };
    else if (mode === "hub" && place !== null) decision = await decideHub(hubText, place, deps, fs, env);
    else if (planText !== "") decision = await decideWithPlan(planText, settingsPath, deps, fs, env, null);
    else decision = await decideStart(settingsPath, deps, fs, env);
  } catch (err) {
    decision = { result: "error", logsDir: null, note: { reason: "unexpected " + errorName(err) } };
  }
  writeLog(fs, decision.logsDir, { ...base, result: decision.result, ...decision.note });
  const extra: Note = hubText !== "" && mode === "inert" ? { reason: "not a Hub install folder (extensions\\plugins\\<owner>\\<name>)" } : {};
  const marker: Note = { t: now, event: "main", mode, result: decision.result, pid, ppid, ...extra };
  for (const key of ["reason", "note", "uninstalled", "attempt"] as const) {
    if (decision.note[key] !== undefined) marker[key] = decision.note[key];
  }
  writeMarker(fs, place, env, marker);
  return decision.result;
}