install / plugin_publish.js

"use strict";
// plugin_tool.js's Hub command (docs\build\PUBLISH_REPORT.md, HUBPLAN_REPORT.md), plain CommonJS, Node built-ins only:
//   publish-stage --out <dir> --name <hub name> --description "<text>" [--revision <n>] [--src <plugin folder>]
//                 [--repo <repository>] [--words <file>]
//     A CLEAN copy of the plugin for `lms push` (run from <dir>): manifest.json (this plugin's owner, the given name,
//     the revision: --revision, else the source manifest's), package.json (the name, the description, the runtime
//     dependency only), package-lock.json (runtime only), tsconfig.json, launcher.js, bootstrap.js, README.md (the
//     page the Hub renders; 2026-11-11: revision 2 had none), install\*.js,
//     src\*.ts with src\baked.ts holding NO path and NO plan, only HUB_FILES: the SHA-256 of every installer file of
//     the repository (bootstrap.js's FILE_RULES, the same digests stage-first bakes), the digest of the copy's
//     bootstrap.js, the install args ["--real", "--yes"], max_per_day 3 and the revision. Digests are not secrets and
//     name no place: the published plugin's main() derives every path from its own folder and the user profile
//     (src\hub.ts). Nothing else: no tests, no node_modules, no stage marker, no state, no logs. Then the RELEASE SCAN
//     reads every file of the copy; on any hit the copy is deleted again and nothing else is written (exit 3). Clean:
//     PUBLISH_CHECK.txt BESIDE the copy (<dir>\..\PUBLISH_CHECK.txt, not pushed) lists every file with its size and
//     SHA-256 and says "scan: clean".
//     Exit 0 ok, 2 usage, 3 the scan failed, 4 failed (--out holds something else, the words file is missing, the
//     repository is not complete), 5 refused under MSI_CHAT_TEST (--out outside MSI_CHAT_TEST_ROOT).
// The scan, per line (the rule and the place are printed, the matched text only by its first characters):
//   secret-hex     32+ hex characters in a row (the HUB_FILES line of src\baked.ts excepted: 64-hex digests by design)
//   secret-base64  40+ base64 / url-safe characters in a row, at least 24 of them letters or digits, not plain hex
//                  (package-lock.json's "integrity" npm digests excepted)
//   secret-word    token / secret / password / api key followed by a quoted literal
//   url            a link: an http(s), ws(s), lmstudio or msichat scheme followed by a colon and two slashes
//                  (package-lock.json may name the npm registry and github.com)
//   ipv4           any IPv4 address except 127.0.0.1
//   host           any host name under one of the private domains (the words file)
//   email          an e-mail address
//   owner          one of the private words: the owner's Windows user name, his folders, his names (the words file;
//                  manifest.json and package.json may hold the Hub owner in their "owner" field, nothing else may)
//   drive-path     a Windows drive path (<letter>:\...) anywhere: the plugin ships no path of any PC
//   old-name       README.md only (what a buyer reads on the Hub page): the old product name, "MSI" as a word in
//                  capitals or "MSI chat" in any case (identifiers such as msi-chat or MSI_CHAT_* are not a hit)
//   html           README.md only: an HTML tag (the Hub page renders plain Markdown; LM Studio's docs name no HTML)
// README.md may name the plugin's Hub id <owner>/<name> (the manifest's owner and the published name: `lms get` needs
// it); any other mention of the owner is still a hit there.
// The Hub split (2026-11-11, docs\build\LINUX_REPORT.md): the source folder's publish.json (not shipped) names its
// default Hub name (locus-win, locus-linux) and its flavor. "win" (this folder; also when there is no publish.json):
// the files above. "linux" (..\lmstudio-plugin-linux): manifest, package, lock, tsconfig, bootstrap.js, README.md and
// src\*.ts only; src\baked.ts holds HUB_FILES alone, made from THAT plugin's bootstrap.js (its FILE_RULES: main\*.py
// and *.sh, server-python\*.py, web\page.html); the repository must hold main\install.sh. "mac"
// (..\lmstudio-plugin-mac, locus-mac, docs\build\MAC_REPORT.md): the same shape and rules as "linux".
// The buyer's copy (2026-11-14, docs\build\PC_INSTALL_REPORT.md; Windows only): `--buyer-pins <pins file>`
// (lmstudio-plugin\payload-pins.json, not shipped) adds payload.js and payload\program-<16 hex>.zip (the installer
// files above plus lmstudio-plugin\manifest.json, install\plugin_payload.js) and bakes HUB_FILES.payload: the Python and
// newt pins (URL, SHA-256, size; payload.js's rules; newt's must be install.cmd's pin), the program zip's digest and
// size, payload.js's digest. The scan then excepts, on the HUB_FILES line only, the two official download URLs (under
// MSI_CHAT_TEST also the test's plain-http 127.0.0.1 server); the zip is not read as text but entry by entry: exactly
// the buyer's files (the owner's own files left out, review H2), no key block, no key-shaped secret literal, none of
// the owner's private details (lmstudio-plugin\payload-private.json, not shipped; exit 3 otherwise).
// The private words live OUTSIDE the plugin, in <repository>\tools\publish-private-words.json ({"hosts": [...],
// "words": [...]}, literal, case-insensitive, a backslash matching one or two): this file is shipped and must scan
// clean itself. Without the words file no copy is made.
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");

const CHECK_FILE = "PUBLISH_CHECK.txt";
const FIXED_FILES = Object.freeze(["manifest.json", "package.json", "package-lock.json", "tsconfig.json", "launcher.js", "bootstrap.js",
  "README.md"]);
const NAME_RE = /^[a-z0-9][a-z0-9-]{0,63}$/;
const MAX_DESCRIPTION = 300;
const MAX_HITS_SHOWN = 30;
const HUB_INSTALL_ARGS = Object.freeze(["--real", "--yes"]);
const HUB_MAX_PER_DAY = 3;

// The repository's src\baked.ts, byte for byte: nothing staged, not a Hub copy.
const EMPTY_BAKED = [
  "// The absolute path of MSI chat's settings.json, written here by `install\\plugin_tool.js stage`.",
  "// The plugin runs with only LM Studio's environment (no APPDATA), so the path is baked in at staging.",
  "// Empty (the repository copy) means \"not staged\": main() returns at once.",
  "export const SETTINGS_PATH: string = \"\";",
  "// The plugin-first plan (JSON text), written here by `install\\plugin_tool.js stage-first` (main\\install.cmd",
  "// /plugin-first): where Locus goes, the repository and python, the digests of bootstrap.js and of every installer file,",
  "// the environment of the install. Empty (the repository copy, and every stage made by `stage`) means \"no plugin-first\":",
  "// main() only starts an installed Locus, as before.",
  "export const BOOTSTRAP_PLAN: string = \"\";",
  "// The Hub copy's digests (JSON text), written here by `install\\plugin_tool.js publish-stage`: the SHA-256 of every",
  "// installer file and of bootstrap.js, the install args, max_per_day, the revision; no path of any PC. With them (and",
  "// nothing else baked) main() derives the install plan from its own folder and the user profile (src\\hub.ts). Empty",
  "// (the repository copy, every stage) means \"not a Hub copy\".",
  "export const HUB_FILES: string = \"\";",
  "",
].join("\n");

const RULES = Object.freeze({
  hex: /[0-9a-f]{32,}/gi,
  base64: /[A-Za-z0-9+/_-]{40,}={0,2}/g,
  word: /\b(?:token|secret|password|passwd|api[ _-]?key)\b\s*[:=]\s*["'`][^"'`]{6,}/gi,
  url: /\b(?:https?|wss?|lmstudio|msichat):\/\/\S*/gi,
  ipv4: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g,
  email: /[A-Za-z0-9._%+-]+@[A-Za-z0-9-]+(?:\.[A-Za-z0-9-]+)*\.[A-Za-z]{2,}/g,
  drive: /\b[A-Za-z]:\\{1,2}/g,
  oldWord: /\bMSI\b/g,
  oldName: /\bmsi chat\b/gi,
  html: /<\/?[A-Za-z][A-Za-z0-9-]*(?:\s[^<>]*)?>|<!--/g,
});

function escapeRe(text) {
  return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
}

// A private word as a pattern: literal, case-insensitive; a backslash in it matches one or two (escaped sources).
function wordRegex(word) {
  return new RegExp(escapeRe(word).replace(/\\\\/g, "\\\\{1,2}"), "gi");
}

function hostRegex(host) {
  return new RegExp("(?:[a-z0-9-]+\\.)*" + escapeRe(host) + "\\b", "gi");
}

// A buyer payload's pinned download URL: python.org's embeddable runtime or newt's GitHub release asset (payload.js's own
// patterns); under MSI_CHAT_TEST also the test's own plain-http server on 127.0.0.1.
function pinnedUrl(url) {
  let rules;
  try {
    rules = require(path.join(__dirname, "..", "payload.js"));
  } catch (err) {
    return false;
  }
  if (Object.values(rules.OFFICIAL).some((re) => re.test(url))) return true;
  return process.env.MSI_CHAT_TEST === "1" && rules.LOOPBACK_URL.test(url);
}

let cachedWords = null;

// {hosts, words} from the words file (the repository's by default). Throws a plain Error when unusable.
function loadWords(file) {
  if (file === undefined && cachedWords !== null) return cachedWords;
  const where = file === undefined ? path.join(__dirname, "..", "..", "tools", "publish-private-words.json") : file;
  let raw;
  try {
    raw = JSON.parse(fs.readFileSync(where, "utf8"));
  } catch (err) {
    throw new Error("the private words file cannot be read: " + where);
  }
  const list = (key) => (Array.isArray(raw[key]) ? raw[key].filter((w) => typeof w === "string" && w.length >= 3) : []);
  const words = { hosts: list("hosts"), words: list("words") };
  if (words.hosts.length + words.words.length === 0) throw new Error("the private words file holds no words: " + where);
  if (file === undefined) cachedWords = words;
  return words;
}

// The hits in one text: [{rule, line, sample}] (sample = the first 4 characters of the match and "...").
// hubId: "<owner>/<name>", the one mention of the owner README.md may hold.
function scanText(text, rel, words = loadWords(), hubId = "") {
  const file = String(rel).replace(/\\/g, "/").split("/").pop().toLowerCase();
  const hits = [];
  text.split(/\r?\n/).forEach((raw, index) => {
    let line = raw;
    if (file === "package-lock.json") {
      // npm's own: the integrity digests, the registry addresses ("resolved") and the github funding links ("url")
      line = line.replace(/"integrity":\s*"sha(?:1|256|512)-[A-Za-z0-9+/=]+"/g, "\"integrity\": \"\"")
        .replace(/"(resolved|url)":\s*"https:\/\/(?:registry\.npmjs\.org|github\.com)\/[^"\s]*"/g, "\"$1\": \"\"");
    }
    if (file === "manifest.json" || file === "package.json") {
      line = line.replace(/"owner":\s*"[A-Za-z0-9._-]+"/g, "\"owner\": \"\"");
    }
    if (file === "readme.md" && hubId) {
      line = line.split(hubId).join("");             // `lms get <owner>/<name>`: the plugin's public Hub id
    }
    if (file === "baked.ts" && /^export const HUB_FILES: string = "/.test(line)) {
      // the Hub digests: 64-hex values inside the baked JSON text; the buyer payload's download URLs when they are the
      // official ones (payload.js OFFICIAL; the test's loopback under MSI_CHAT_TEST). Nothing else on that line.
      line = line.replace(/\\"[0-9a-f]{64}\\"/g, "\\\"\\\"");
      line = line.replace(/\\"(https?:\/\/[^"\\\s]+)\\"/g, (m, url) => (pinnedUrl(url) ? "\\\"\\\"" : m));
    }
    const add = (rule, match) => hits.push({ rule, line: index + 1, sample: match.slice(0, 4) + "..." });
    const each = (re, fn) => { for (const m of line.match(re) || []) fn(m); };
    each(RULES.hex, (m) => add("secret-hex", m));
    // plain hex is the hex rule's; a run of dashes or slashes (a comment rule) holds too few letters and digits
    each(RULES.base64, (m) => { if (!/^[0-9a-f]+$/i.test(m) && (m.match(/[A-Za-z0-9]/g) || []).length >= 24) add("secret-base64", m); });
    each(RULES.word, (m) => add("secret-word", m));
    each(RULES.url, (m) => add("url", m));
    each(RULES.ipv4, (m) => { if (m !== "127.0.0.1") add("ipv4", m); });
    for (const host of words.hosts) each(hostRegex(host), (m) => add("host", m));
    each(RULES.email, (m) => add("email", m));
    for (const word of words.words) each(wordRegex(word), (m) => add("owner", m));
    each(RULES.drive, (m) => add("drive-path", m));
    if (file === "readme.md") {                      // what a buyer reads on the Hub page (2026-11-11)
      each(RULES.oldWord, (m) => add("old-name", m));
      each(RULES.oldName, (m) => add("old-name", m));
      each(RULES.html, (m) => add("html", m));
    }
  });
  return hits;
}

// Every file under `dir`, relative with "/", sorted; links are refused.
function walk(dir, rel = "") {
  const out = [];
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
    const here = rel === "" ? entry.name : rel + "/" + entry.name;
    if (entry.isSymbolicLink()) throw new Error("a link in the copy: " + here);
    if (entry.isDirectory()) out.push(...walk(path.join(dir, entry.name), here));
    else out.push(here);
  }
  return out.sort();
}

// The HUB_FILES text: the repository's installer digests (bootstrap.js collectFiles: the same rules as stage-first), the
// copy's bootstrap.js digest, the install args, max_per_day, the revision.
function hubFilesText(boot, repo, copiedBootstrap, revision, sha256File, payload = null) {
  const collected = boot.collectFiles(repo);
  if (collected.problems.length > 0) throw new Error("the repository is not complete: " + collected.problems.join("; "));
  return JSON.stringify({ schema: 1, revision, bootstrap_sha256: sha256File(copiedBootstrap), files: collected.files,
    install_args: [...HUB_INSTALL_ARGS], max_per_day: HUB_MAX_PER_DAY, ...(payload === null ? {} : { payload }) });
}

// The buyer payload's place in a copy (docs\build\PC_INSTALL_REPORT.md): payload.js and payload\program-<id>.zip.
const BUYER_MODULE = "payload.js";
const PROGRAM_REL = /^payload\/program-[0-9a-f]{16}\.zip$/;

// The source's flavor (publish.json beside its manifest; "win" without one).
function flavorOf(src) {
  let raw = {};
  try {
    raw = JSON.parse(fs.readFileSync(path.join(src, "publish.json"), "utf8"));
  } catch (err) {
    raw = {};
  }
  const hubName = typeof raw.hub_name === "string" && NAME_RE.test(raw.hub_name) ? raw.hub_name : undefined;
  if (raw.flavor === "linux" || raw.flavor === "mac") {
    return { name: raw.flavor, hubName, copied: ["tsconfig.json", "bootstrap.js", "README.md"], dirs: [["src", ".ts"]], repoMarker: ["main", "install.sh"] };
  }
  return { name: "win", hubName, copied: ["tsconfig.json", "launcher.js", "bootstrap.js", "README.md"], dirs: [["install", ".js"], ["src", ".ts"]],
    repoMarker: ["main", "install.cmd"] };
}

// The Linux copy's src\baked.ts: HUB_FILES alone (no path, no plan).
function linuxBakedSource(hubText) {
  return "// Written by publish-stage: no path of any machine, the Hub digests only.\n" +
    "export const HUB_FILES: string = " + JSON.stringify(hubText) + ";\n";
}

module.exports = function publishCommands(tool) {
  const { ToolError, EXIT, PLUGIN_ROOT, OWNER, absPath, guard, canonical, readManifest, refuseLink, refuseSource, isInside, renameRetry,
    runtimePackage, runtimeLock, writeJson, sha256File, bakedSource } = tool;
  const boot = require(path.join(PLUGIN_ROOT, "bootstrap.js"));
  const payloadTool = require("./plugin_payload.js");

  function copyFile(src, dir, rel) {
    const from = path.join(src, ...rel.split("/"));
    if (!fs.existsSync(from) || fs.lstatSync(from).isSymbolicLink() || !fs.statSync(from).isFile()) {
      throw new ToolError(EXIT.FAILED, "--src has no plain file " + rel);
    }
    fs.mkdirSync(path.dirname(path.join(dir, ...rel.split("/"))), { recursive: true });
    fs.copyFileSync(from, path.join(dir, ...rel.split("/")));
  }

  // The plain files of <src>\<sub> with the extension, as "sub/name" (links and folders are left out).
  function plainFiles(src, sub, ext) {
    const dir = path.join(src, sub);
    if (!fs.existsSync(dir)) return [];
    return fs.readdirSync(dir, { withFileTypes: true })
      .filter((e) => e.isFile() && !e.isSymbolicLink() && e.name.toLowerCase().endsWith(ext))
      .map((e) => sub + "/" + e.name).sort();
  }

  // The buyer payload in the fresh copy: payload.js beside bootstrap.js, the program zip in payload\. Returns
  // {payload (the HUB_FILES object), program (the zip's facts)}.
  function writeBuyerPayload(src, dir, repo, pins) {
    copyFile(src, dir, BUYER_MODULE);
    const program = payloadTool.buildProgramZip(repo, boot);
    fs.mkdirSync(path.join(dir, "payload"), { recursive: true });
    fs.writeFileSync(path.join(dir, "payload", program.file), program.buffer);
    return { payload: payloadTool.payloadObject(pins, program, sha256File(path.join(dir, BUYER_MODULE))), program };
  }

  // Writes the copy into `dir` (fresh). Returns the relative file list and the number of installer files hashed.
  function writeCopy(src, dir, manifest, name, description, revision, repo, flavor = flavorOf(src), pins = null) {
    fs.mkdirSync(dir, { recursive: true });
    writeJson(path.join(dir, "manifest.json"), { type: manifest.type, runner: manifest.runner, owner: manifest.owner, name, revision });
    const pkg = JSON.parse(fs.readFileSync(path.join(src, "package.json"), "utf8"));
    const lock = JSON.parse(fs.readFileSync(path.join(src, "package-lock.json"), "utf8"));
    const renamed = Object.assign({}, pkg, { name });
    writeJson(path.join(dir, "package.json"), Object.assign({}, runtimePackage(renamed), { description }));
    writeJson(path.join(dir, "package-lock.json"), runtimeLock(lock, renamed));
    const copied = [...flavor.copied, ...flavor.dirs.flatMap(([sub, ext]) => plainFiles(src, sub, ext))];
    for (const rel of copied) copyFile(src, dir, rel);
    fs.mkdirSync(path.join(dir, "src"), { recursive: true });
    const posix = flavor.name !== "win";                       // linux and mac: HUB_FILES alone, that plugin's rules
    const rules = posix ? require(path.join(src, "bootstrap.js")) : boot;   // that plugin's own FILE_RULES
    const buyer = pins === null ? null : writeBuyerPayload(src, dir, repo, pins);
    const hub = hubFilesText(rules, repo, path.join(dir, "bootstrap.js"), revision, sha256File, buyer === null ? null : buyer.payload);
    fs.writeFileSync(path.join(dir, "src", "baked.ts"), posix ? linuxBakedSource(hub) : bakedSource("", "", hub), "utf8");
    return { files: walk(dir), hashed: Object.keys(JSON.parse(hub).files).length, buyer };
  }

  // An earlier publish copy of this plugin: our owner's manifest and nothing but shipped files (an older copy may still
  // hold PUBLISH_CHECK.txt inside).
  function isPublishCopy(dir) {
    const manifest = readManifest(dir);
    if (manifest === null || typeof manifest !== "object" || manifest.type !== "plugin" || manifest.owner !== OWNER) return false;
    try {
      return walk(dir).every((rel) => FIXED_FILES.includes(rel) || rel === CHECK_FILE || /^install\/[^/]+\.js$/.test(rel) || /^src\/[^/]+\.ts$/.test(rel) ||
        rel === BUYER_MODULE || PROGRAM_REL.test(rel));
    } catch (err) {
      return false;
    }
  }

  // Every text file of the copy by the rules; the program zip (binary) is read entry by entry instead (scanProgram).
  function scanCopy(dir, words, hubId) {
    const problems = [];
    for (const rel of walk(dir)) {
      if (PROGRAM_REL.test(rel)) continue;
      for (const hit of scanText(fs.readFileSync(path.join(dir, ...rel.split("/")), "utf8"), rel, words, hubId)) {
        problems.push({ rel, ...hit });
      }
    }
    return problems;
  }

  // The carried program: its file list and no key or secret literal in any entry; the private words it names, counted.
  function scanProgram(dir, buyer, repo, rules) {
    if (buyer === null) return { problems: [], rules: 0 };
    const rel = "payload/" + buyer.program.file;
    const result = payloadTool.scanProgramZip(fs.readFileSync(path.join(dir, ...rel.split("/"))), require(path.join(dir, BUYER_MODULE)),
      payloadTool.programFiles(repo, boot).rels, rules);
    return { problems: [...result.secrets.map((t) => ({ rel, kind: "secret", text: t })), ...result.private.map((t) => ({ rel, kind: "private", text: t }))],
      rules: rules.length };
  }

  function checkText(files, dir, name, revision, hashed, buyer = null, ruleCount = 0) {
    const lines = ["Locus plugin publish copy (plugin_tool.js publish-stage)", "name: " + name, "revision: " + revision,
      "made: " + new Date().toISOString(), "files: " + files.length, "installer files in HUB_FILES: " + hashed, ""];
    for (const rel of files) {
      const file = path.join(dir, ...rel.split("/"));
      lines.push(String(fs.statSync(file).size).padStart(8) + "  " + sha256File(file) + "  " + rel);
    }
    lines.push("", "scan: clean (" + files.length + " files; rules: secret-hex, secret-base64, secret-word, url, ipv4, host, email, owner, drive-path, " +
      "old-name, html)", "");
    if (buyer !== null) {
      const p = buyer.payload;
      for (const part of ["python", "newt"]) {
        lines.push("buyer payload: " + part + " " + p[part].version + " " + p[part].sha256 + " " + p[part].size + " (" + new URL(p[part].url).hostname + ")");
      }
      lines.push("buyer payload: program " + buyer.program.count + " files, scanned for keys and secret literals: none");
      lines.push("buyer payload: the owner's details (payload-private.json, " + ruleCount + " rules): none",
        "buyer payload: the owner's own files left out: " + payloadTool.OWNER_ONLY.join(", "), "");
    }
    return lines.join("\n");
  }

  function revisionArg(opts, manifest) {
    if (opts.revision === undefined) return Number.isInteger(manifest.revision) && manifest.revision >= 1 ? manifest.revision : 1;
    const value = Number(opts.revision);
    if (!/^[0-9]{1,3}$/.test(String(opts.revision)) || !Number.isInteger(value) || value < 1) {
      throw new ToolError(EXIT.USAGE, "--revision needs a whole number 1-999");
    }
    return value;
  }

  function textArg(opts, key, max) {
    const value = opts[key];
    if (typeof value !== "string" || value.length === 0 || value.length > max || /[\u0000-\u001f\u007f]/.test(value)) {
      throw new ToolError(EXIT.USAGE, "--" + key + " needs plain text of 1-" + max + " characters");
    }
    return value;
  }

  async function cmdPublishStage(opts) {
    const out = absPath(opts, "out");
    guard("--out", out);
    const src = opts.src === undefined ? PLUGIN_ROOT : absPath(opts, "src");
    const flavor = flavorOf(src);
    const name = opts.name === undefined && flavor.hubName !== undefined ? flavor.hubName : textArg(opts, "name", 64);
    if (!NAME_RE.test(name)) throw new ToolError(EXIT.USAGE, "--name must be a plain lowercase name (a-z, 0-9, -)");
    const description = textArg(opts, "description", MAX_DESCRIPTION);
    let words;
    try {
      words = loadWords(opts.words === undefined ? undefined : absPath(opts, "words"));
    } catch (err) {
      throw new ToolError(EXIT.FAILED, err.message);
    }
    for (const [label, text] of [["--name", name], ["--description", description]]) {
      const hits = scanText(text, label, words);
      if (hits.length > 0) throw new ToolError(EXIT.USAGE, label + " holds something the copy may not ship (" + hits[0].rule + ")");
    }
    const manifest = readManifest(src);
    if (manifest === null || typeof manifest !== "object" || manifest.type !== "plugin" || manifest.runner !== "node" ||
        typeof manifest.owner !== "string" || manifest.owner === "") {
      throw new ToolError(EXIT.FAILED, "--src is not a plugin folder (no manifest.json with type, runner and owner)");
    }
    const revision = revisionArg(opts, manifest);
    // the installer files whose digests are baked: this tool's own repository by default (the copy's code runs them)
    const repo = opts.repo === undefined ? path.resolve(PLUGIN_ROOT, "..") : absPath(opts, "repo");
    if (!fs.existsSync(path.join(repo, ...flavor.repoMarker))) {
      throw new ToolError(EXIT.FAILED, "--repo holds no " + flavor.repoMarker.join("\\") + ": " + repo);
    }
    let pins = null;
    let privateRules = [];
    if (opts["buyer-pins"] !== undefined) {           // the buyer payload (docs\build\PC_INSTALL_REPORT.md)
      if (flavor.name !== "win") throw new ToolError(EXIT.USAGE, "--buyer-pins: the buyer payload is built for Windows only so far");
      try {
        const installCmd = fs.readFileSync(path.join(repo, "main", "install.cmd"), "utf8");
        pins = payloadTool.readPins(absPath(opts, "buyer-pins"), require(path.join(src, BUYER_MODULE)),
          { testMode: process.env.MSI_CHAT_TEST === "1", installCmdText: installCmd });
        privateRules = payloadTool.loadPrivateRules(path.join(src, "payload-private.json"));   // review H2: no build without it
      } catch (err) {
        if (err instanceof ToolError) throw err;
        throw new ToolError(EXIT.FAILED, "--buyer-pins: " + err.message);
      }
    }
    refuseSource(out);
    if (isInside(src, out) || isInside(out, src)) throw new ToolError(EXIT.USAGE, "--out and --src must not hold each other");
    if (fs.existsSync(out)) {
      refuseLink(out);
      if (fs.readdirSync(out).length > 0 && !isPublishCopy(out)) {
        throw new ToolError(EXIT.FAILED, "--out exists and is not empty or an earlier publish copy: " + out);
      }
    }
    const fresh = out + ".new";
    if (fs.existsSync(fresh)) {
      refuseLink(fresh);
      fs.rmSync(fresh, { recursive: true, force: true, maxRetries: 3 });
    }
    let files;
    let hashed;
    let buyer;
    let ruleCount = 0;
    try {
      try {
        ({ files, hashed, buyer } = writeCopy(src, fresh, manifest, name, description, revision, repo, flavor, pins));
      } catch (err) {
        if (err instanceof ToolError) throw err;
        throw new ToolError(EXIT.FAILED, err.message);
      }
      const problems = scanCopy(fresh, words, manifest.owner + "/" + name);
      const program = scanProgram(fresh, buyer, repo, privateRules);
      ruleCount = program.rules;
      if (problems.length + program.problems.length > 0) {
        for (const p of problems.slice(0, MAX_HITS_SHOWN)) {
          process.stderr.write("scan: " + p.rule + " in " + path.join(fresh, ...p.rel.split("/")) + ":" + p.line + " (" + p.sample + ")\n");
        }
        if (problems.length > MAX_HITS_SHOWN) process.stderr.write("scan: ... " + (problems.length - MAX_HITS_SHOWN) + " more\n");
        for (const p of program.problems) process.stderr.write("scan: " + p.kind + " in " + p.rel + ": " + p.text + "\n");
        throw new ToolError(EXIT.CHECK, "the release scan found " + (problems.length + program.problems.length) + " hit(s): nothing published, the copy deleted");
      }
    } catch (err) {
      fs.rmSync(fresh, { recursive: true, force: true, maxRetries: 3 });
      throw err;
    }
    if (fs.existsSync(out)) fs.rmSync(out, { recursive: true, force: true, maxRetries: 3 });
    fs.mkdirSync(path.dirname(out), { recursive: true });
    renameRetry(fresh, out);
    const check = path.join(path.dirname(out), CHECK_FILE);         // beside the copy: lms push uploads the folder as it is
    fs.writeFileSync(check, checkText(files, out, name, revision, hashed, buyer, ruleCount), "utf8");
    const buyerLine = buyer === null ? "" : "buyer payload: Python " + buyer.payload.python.version + ", newt " + buyer.payload.newt.version +
      ", the program (" + buyer.program.count + " files) in payload\\" + buyer.program.file + "\n";
    process.stdout.write("publish copy " + out + " (" + files.length + " files, revision " + revision + ", " + hashed +
      " installer files in HUB_FILES, scan: clean; " + check + " written)\n" + buyerLine +
      "from that folder: lms push -y --description " + JSON.stringify(description) + "\n");
    void canonical;
    return EXIT.OK;
  }

  return { "publish-stage": cmdPublishStage };
};

module.exports.EMPTY_BAKED = EMPTY_BAKED;
module.exports.scanText = scanText;
module.exports.loadWords = loadWords;
module.exports.CHECK_FILE = CHECK_FILE;
module.exports.FIXED_FILES = FIXED_FILES;