# publish.mjs

> Publish an account folder to Streamliner through the signed publishing routes — a DRY RUN unless --yes.

Publish an account folder to Streamliner through the signed publishing routes — a DRY RUN unless --yes.

Raw file: https://streamliner.work/agents/skill/scripts/publish.mjs

```js
#!/usr/bin/env node
// Publish an account folder to Streamliner through the signed publishing routes — a DRY RUN unless --yes.
// Node 20+, no dependencies. The same protocol as the repo's scripts/publish-config.mjs (config-schema §8d): one
// publishing path, Local changes → (Staging →) Live.
//
//   node publish.mjs <folder> --host <https://api host> --key <server-key.jwk> [--key-id <id>] [--account <id>]
//                    [--baseline <folder>] [--title <text>] [--live] [--json] [--yes]
//   node publish.mjs <folder> --host <…> --key <…> --promote [--yes]      Staging → Live, whole
//   node publish.mjs [<folder>] --host <…> --key <…> [--account <id>] --restore <n> [--live] --publisher-key <jwk> [--yes]
//   node publish.mjs [<folder>] --host <…> --key <…> [--account <id>] --merge-hotfix [<n>] [--settle staging|hotfix]
//                    --publisher-key <jwk> [--yes]
//
//   <folder>     the account folder (tenant.json, agents/, templates/, forms/, private/…, manifest.json signed by
//                sign-config.mjs at the version this prints: the organization's next revision). The account id
//                defaults to tenant.json `id`.
//   --key        an Ed25519 private JWK whose public half is one of the account's server keys with a config scope.
//                Read from the path, never printed. Ask the owner for a scoped, expiring key; never an employee login.
//   --baseline   a local copy of what is published now, for a field-level diff of the JSON files (the server only
//                reports hashes, so without it the diff is per file).
//   --live       while the organization's Staging is on: a HOTFIX straight to Live (every member gets it now; Staging
//                gets it once merged: --merge-hotfix, or in the app). Only when the owner asks for a hotfix.
//   --promote    promote Staging to Live, whole.
//   --restore <n>   a new revision with revision n's content: onto Staging while it is on (else Live; --live = onto
//                Live with Staging on, which then waits for its merge into Staging like a hotfix). Keys never come back
//                (enrolment.json, server keys, nextKeys stay). Reads the revision from the back end, not the folder.
//   --merge-hotfix [<n>]   merge a hotfix waiting for Staging (the oldest, or revision n) into Staging, per field as the
//                app does. A field changed on both sides keeps Staging's value and the hotfix keeps waiting, unless the
//                owner chose --settle staging (keep Staging's) or --settle hotfix (take the hotfix's).
//   --publisher-key   (--restore, --merge-hotfix) one of the organization's publisher keys (Ed25519 private JWK; the
//                sign-config.mjs key): both make a new manifest, signed here at the next revision. Never printed.
//   --yes        actually write. Without it the back end checks everything (`?dryRun=1`) and writes nothing.
//                ONLY pass --yes after the account owner has seen the dry run and said yes in so many words.
//
// Where it lands: Staging off (the default) → Live; Staging on → Staging, and Live moves only by --promote (or a
// --live hotfix). Prints paths, counts and a readable diff; never file contents of private/ files, keys or tokens.
import { readFileSync, existsSync, readdirSync, statSync } from "node:fs";
import { join, relative, sep } from "node:path";
import { createHash, createPrivateKey, randomBytes, sign } from "node:crypto";
import { restoreOrMerge } from "./restore-merge.mjs";

const argv = process.argv.slice(2);
const opt = (n) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined; };
const flag = (n) => argv.includes(`--${n}`);
const VALUED = new Set(["--host", "--key", "--key-id", "--account", "--baseline", "--title", "--restore", "--settle", "--publisher-key", "--publisher-key-id"]);
const dir = argv.find((a, i) => !a.startsWith("--") && !VALUED.has(argv[i - 1]) && !(argv[i - 1] === "--merge-hotfix" && /^\d+$/.test(a)));
const die = (m, c = 1) => { console.error(`publish: ${m}`); process.exit(c); };
const restoreN = flag("restore") ? (opt("restore") ?? "") : undefined, mergeHotfix = flag("merge-hotfix"), settle = opt("settle");
const history = restoreN !== undefined || mergeHotfix;   // a restore or a hotfix's merge: the folder is optional
if ((history ? !(dir && existsSync(join(dir, "tenant.json"))) && !opt("account") : !dir || !existsSync(join(dir, "tenant.json"))) || !opt("host") || !opt("key"))
  die("usage: node publish.mjs <folder> --host <base url> --key <server-key.jwk> [--key-id id] [--account id] [--baseline folder] [--title text] [--live | --promote] [--json] [--yes]\n" +
    "       node publish.mjs [<folder>] --host <base url> --key <server-key.jwk> [--account id] --restore <n> [--live] --publisher-key <jwk> [--json] [--yes]\n" +
    "       node publish.mjs [<folder>] --host <base url> --key <server-key.jwk> [--account id] --merge-hotfix [<n>] [--settle staging|hotfix] --publisher-key <jwk> [--json] [--yes]", 2);
if (restoreN !== undefined && !/^[1-9]\d{0,8}$/.test(restoreN)) die("--restore <revision number>", 2);
if ([flag("promote"), restoreN !== undefined, mergeHotfix].filter(Boolean).length > 1) die("one of --promote, --restore, --merge-hotfix", 2);
if (settle !== undefined && (!mergeHotfix || !["staging", "hotfix"].includes(settle))) die("--settle staging|hotfix goes with --merge-hotfix", 2);
if (mergeHotfix && flag("live")) die("--merge-hotfix always lands on Staging (--live doesn't apply)", 2);
const base = opt("host").replace(/\/$/, "");
if (/^http:\/\//.test(base) && !/^http:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|$)/.test(base)) die("refusing http:// to a non-local host; use https://", 2);
const yes = flag("yes"), asJSON = flag("json"), wantLive = flag("live"), promote = flag("promote"), title = opt("title");
if (wantLive && promote) die("--live or --promote, not both", 2);
const tenantJSON = dir && existsSync(join(dir, "tenant.json")) ? JSON.parse(readFileSync(join(dir, "tenant.json"), "utf8")) : {};
const account = opt("account") || tenantJSON.id;
if (!/^[a-z0-9-]{3,40}$/.test(account || "")) die(`bad account id ${account}`);
if (tenantJSON.id && tenantJSON.id !== account) die(`tenant.json id is ${tenantJSON.id}, not ${account}`);
const again = `node publish.mjs ${dir ? `${dir} ` : ""}--host ${base} --key ${opt("key")}${dir ? "" : ` --account ${account}`}`;

const CONFIG_PATH = /^(?:tenant\.json|enrolment\.json|manifest\.json|(?:agents|templates|forms)\/[A-Za-z0-9_-][A-Za-z0-9._-]{0,79}\.json|assets\/[a-f0-9]{16,64}\.(?:png|jpe?g|pdf)|demo\/(?:backend\.js|agent\.js|fixtures\.json|tour\.json)|private\/tenant\.json|private\/(?:agents|connections)\/[A-Za-z0-9_-][A-Za-z0-9._@-]{0,79}\.json|private\/briefs\/[a-z0-9][a-z0-9-]{1,47}\.md)$/;
const deviceVisible = (p) => !p.startsWith("private/") && p !== "manifest.json" && p !== "enrolment.json";
const sha = (b) => createHash("sha256").update(b).digest("hex");
const canonical = (v) => v === null || typeof v !== "object" ? JSON.stringify(v)
  : Array.isArray(v) ? "[" + v.map(canonical).join(",") + "]"
  : "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canonical(v[k])).join(",") + "}";
const walk = (d) => readdirSync(d).flatMap((n) => { const p = join(d, n); return statSync(p).isDirectory() ? walk(p) : n.startsWith(".") ? [] : [p]; });
const readFolder = (d) => new Map(walk(d).map((f) => [relative(d, f).split(sep).join("/"), readFileSync(f)]));

// ── the server key (never printed) ──
if (!existsSync(opt("key"))) die("no such key file");
const jwk = JSON.parse(readFileSync(opt("key"), "utf8"));
if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.d) die("the server key must be an Ed25519 private JWK");
const privateKey = createPrivateKey({ key: { kty: "OKP", crv: "Ed25519", d: jwk.d, x: jwk.x }, format: "jwk" });
const local = dir && existsSync(join(dir, "tenant.json")) ? readFolder(dir) : new Map();
const ptLocal = local.has("private/tenant.json") ? JSON.parse(local.get("private/tenant.json")) : null;
const keyId = opt("key-id") || jwk.kid || (ptLocal?.serverKeys || []).find((k) => k.publicKey === jwk.x)?.id;
if (!keyId) die("which key? --key-id <id> (the id the account knows this server key by)");

/// streamline.admin.v1|<account>|<METHOD>|<path?query>|<sha256hex(body)>|<unix seconds>|<nonce>
async function signed(method, path, body) {
  const bytes = body == null ? Buffer.alloc(0) : Buffer.from(JSON.stringify(body));
  const ts = String(Math.floor(Date.now() / 1000)), nonce = randomBytes(18).toString("base64url");
  const signature = sign(null, Buffer.from(`streamline.admin.v1|${account}|${method}|${path}|${sha(bytes)}|${ts}|${nonce}`), privateKey).toString("base64url");
  let res;
  try { res = await fetch(base + path, { method, body: method === "GET" ? undefined : bytes, headers: { "Content-Type": "application/json", "X-Streamline-Key": keyId, "X-Streamline-Timestamp": ts, "X-Streamline-Nonce": nonce, "X-Streamline-Signature": signature } }); }
  catch (e) { die(`can't reach ${base}: ${e.cause?.code || e.message}`); }
  const raw = Buffer.from(await res.arrayBuffer());
  let j = {}; try { j = JSON.parse(raw.toString("utf8")); } catch {}
  return { status: res.status, ok: res.ok, j, raw };
}
const refusal = (r) => [`${r.status} ${r.j.error || "error"}: ${r.j.message || ""}`,
  ...(r.j.problems || []).slice(1).map((p) => `  also ${p.code}: ${p.message}`),
  ...(r.j.problems || []).flatMap((p) => [...(p.missing || []).map((x) => `  missing ${x}`), ...(p.mismatched || []).map((x) => `  mismatched ${x}`)])].join("\n");
const behindSays = (r, where) => `${where} moved to revision ${r.j.current ?? "?"} while this ran: someone pushed meanwhile. Pull first: read what changed (the owner sees it in the app's History tab) into the folder, re-sign at the new next revision, and run the dry run again.`;
const help401 = (r) => (r.status === 401 ? "\n(is this key listed in the account's private/tenant.json serverKeys? has it expired?)" : r.status === 403 ? "\n(the key lacks a config scope)" : "");

// ── --restore <n> / --merge-hotfix [<n>]: a new manifest signed with the publisher key (restore-merge.mjs) ──
if (history) {
  if (!opt("publisher-key")) die("--publisher-key <the organization's publisher JWK> is required: a restore or a hotfix's merge makes a new manifest, signed at the next revision", 2);
  const mergeN = mergeHotfix && /^\d+$/.test(opt("merge-hotfix") || "") ? Number(opt("merge-hotfix")) : undefined;
  process.exit(await restoreOrMerge({
    op: mergeHotfix ? "merge" : "restore", tenant: account, base, signed, yes, json: asJSON, writeIdPrefix: "skill", again,
    revision: mergeHotfix ? mergeN : Number(restoreN), live: wantLive, settle,
    publisherKeyFile: opt("publisher-key"), publisherKeyId: opt("publisher-key-id"), publisherKeyArg: opt("publisher-key"),
  }));
}

// ── the environments (config-schema §8d) ──
const E = `/v1/admin/${account}`;
const envR = await signed("GET", `${E}/env`);
if (!envR.ok) die(`reading the environments: ${refusal(envR)}${help401(envR)}`);
const envs = envR.j, stagingOn = !!envs.staging?.on, next = envs.nextRevision;

if (promote) {
  if (!stagingOn) die("Staging is off for this organization: a push already lands on Live; there is nothing to promote.");
  const rev = envs.staging.revision;
  if (rev === envs.live.revision) { console.log(`${account} on ${base}: Live is already Staging's revision ${rev}; nothing to promote`); process.exit(0); }
  const r = await signed("POST", `${E}/env/live/promote${yes ? "" : "?dryRun=1"}`, { revision: rev });
  if (!r.ok) {
    if (r.j.error === "hotfix_not_merged") die(`Live has a hotfix Staging hasn't merged yet: merge it first (${again} --publisher-key <jwk> --merge-hotfix, a dry run, or in the app: Library → Publish → Waiting for Staging), then promote.`);
    if (r.j.error === "live_ahead") die(`Live (revision ${r.j.live}) is above Staging (${r.j.staging}): promote chosen items from the app (Library → Publish → Promote…).`);
    if (r.j.error === "behind") die(behindSays(r, "Staging"));
    die(`promote refused:\n${refusal(r)}`);
  }
  if (asJSON) { console.log(JSON.stringify({ account, host: base, dryRun: !yes, promoted: rev, from: envs.live.revision, worker: r.j }, null, 2)); process.exit(0); }
  console.log(`${yes ? "PROMOTED" : "DRY RUN — nothing was written"}: ${account} on ${base}, Staging's revision ${rev} → Live (Live was ${envs.live.revision})`);
  for (const p of r.j.put || []) console.log(`  ~ ${p}`);
  for (const p of r.j.deleted || []) console.log(`  - ${p}`);
  if (!yes) console.log(`\nShow this to the account owner. Promote only after they say yes: ${again} --promote --yes`);
  process.exit(0);
}

const hotfix = stagingOn && wantLive, target = stagingOn && !wantLive ? "staging" : "live";
const current = target === "staging" ? envs.staging.revision : envs.live.revision, first = target === "live" && current == null;
const q = target === "staging" ? "?env=staging" : "", where = hotfix ? "Live (a hotfix)" : target === "staging" ? "Staging" : "Live";
if (wantLive && !stagingOn) console.error("note: Staging is off for this organization, so a push lands on Live anyway (--live changes nothing)");

// ── the folder and its manifest ──
const odd = [...local.keys()].filter((p) => !CONFIG_PATH.test(p));
if (odd.length) die(`not config paths (move them out of the folder): ${odd.join(", ")}`);
if (!local.has("manifest.json")) die(`no manifest.json: sign first (sign-config.mjs --version ${next})`);
const manifest = JSON.parse(local.get("manifest.json"));
const listed = (manifest.files || []).map((f) => f.path).sort().join("\n");
const want = [...local.keys()].filter(deviceVisible).sort().join("\n");
const stale = (manifest.files || []).filter((f) => !local.has(f.path) || sha(local.get(f.path)) !== f.sha256);
if (listed !== want || stale.length) die(`the manifest is stale (a file changed since signing): run sign-config.mjs --version ${next} again`);
if (ptLocal && !(ptLocal.serverKeys || []).some((k) => k.id === keyId && k.publicKey === jwk.x && !k.disabled))
  console.error(`warning: private/tenant.json in this folder does not list ${keyId}; pushing it would remove that key (the back end refuses a push that locks the account out)`);

// ── what the target holds ──
const idx = await signed("GET", `${E}/config${q}`);
if (!idx.ok) die(`reading ${where}'s index: ${refusal(idx)}${help401(idx)}`);
const remote = new Map((idx.j.files || []).map((f) => [f.path, f]));
const added = [...local.keys()].filter((p) => p !== "manifest.json" && !remote.has(p)).sort();
const changed = [...local.keys()].filter((p) => p !== "manifest.json" && remote.has(p) && remote.get(p).sha256 !== sha(local.get(p))).sort();
const gone = [...remote.keys()].filter((p) => p !== "manifest.json" && !local.has(p)).sort();
if (!added.length && !changed.length && !gone.length && remote.has("manifest.json")) {
  console.log(`${account} on ${base}: ${where} is already up to date (revision ${current})`);
  process.exit(0);
}
// A push's manifest carries the organization's next revision exactly (an organization's very first may be above it).
if (first ? manifest.version < next : manifest.version !== next)
  die(`the manifest's version is ${manifest.version}; this push needs ${first ? `at least ${next}` : `exactly ${next}`}, the organization's next revision: run sign-config.mjs --version ${next}, then this again`);

// ── the items (config-schema §8d *Items*): what the owner recognizes, never files ──
const itemsOf = (path, before, after) => {
  let m;
  if ((m = /^(?:private\/)?agents\/(.+)\.json$/.exec(path))) return [`streamline:${m[1]}`];
  if ((m = /^private\/briefs\/(.+)\.md$/.exec(path))) return [`brief:${m[1]}`];
  if ((m = /^templates\/(.+)\.json$/.exec(path))) return [`template:${m[1]}`];
  if ((m = /^forms\/(.+)\.json$/.exec(path))) return [`form:${m[1]}`];
  if ((m = /^assets\/(.+)$/.exec(path))) return [`asset:${m[1]}`];
  if ((m = /^private\/connections\/(.+)\.json$/.exec(path))) return [`connection:${m[1]}`];
  if (path === "private/tenant.json") return ["policy"];
  if (path !== "tenant.json") return ["organization"];
  let a, b; try { a = JSON.parse(before); b = JSON.parse(after); } catch { return ["organization"]; }
  if (!a || !b || typeof a !== "object" || typeof b !== "object") return ["organization"];
  const out = new Set();
  for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) {
    if (k === "kinds" || canonical(a[k]) === canonical(b[k])) continue;
    out.add(k === "theme" || k === "themes" ? "theme" : "organization");
  }
  if (canonical(a.kinds) !== canonical(b.kinds)) {
    const ka = new Set(Array.isArray(a.kinds) ? a.kinds : []), kb = new Set(Array.isArray(b.kinds) ? b.kinds : []);
    const moved = [...kb].filter((k) => !ka.has(k)).concat([...ka].filter((k) => !kb.has(k)));
    if (moved.length) for (const k of moved) out.add(`streamline:${k}`); else out.add("organization");
  }
  return [...out];
};
const items = new Set();
for (const p of [...added, ...changed, ...gone]) {
  const before = p === "tenant.json" && remote.has(p) ? (await signed("GET", `${E}/config/tenant.json${q}`)).raw : null;
  for (const i of itemsOf(p, before, local.get(p) || null)) items.add(i);
}

// ── the readable diff (field level when a baseline folder is given) ──
const baseline = opt("baseline") && existsSync(opt("baseline")) ? readFolder(opt("baseline")) : null;
function jsonDiff(a, b, path = "", out = []) {
  if (out.length > 40) return out;
  if (typeof a !== typeof b || Array.isArray(a) !== Array.isArray(b) || a === null || b === null || typeof a !== "object") {
    if (JSON.stringify(a) !== JSON.stringify(b)) out.push(a === undefined ? `+ ${path || "/"}` : b === undefined ? `- ${path || "/"}` : `~ ${path || "/"}`);
    return out;
  }
  if (Array.isArray(a)) {
    const named = (x) => x && typeof x === "object" && (x.name || x.id);
    if (a.every(named) && b.every(named)) {
      const am = new Map(a.map((x) => [named(x), x])), bm = new Map(b.map((x) => [named(x), x]));
      for (const [k, v] of bm) jsonDiff(am.get(k), v, `${path}/${k}`, out);
      for (const k of am.keys()) if (!bm.has(k)) out.push(`- ${path}/${k}`);
      return out;
    }
    for (let i = 0; i < Math.max(a.length, b.length); i++) jsonDiff(a[i], b[i], `${path}/${i}`, out);
    return out;
  }
  for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) jsonDiff(a[k], b[k], `${path}/${k}`, out);
  return out;
}
const details = {};
for (const p of changed) {
  if (!baseline?.has(p) || !p.endsWith(".json")) continue;
  try { details[p] = jsonDiff(JSON.parse(baseline.get(p)), JSON.parse(local.get(p))); } catch {}
}
function summary(p) {   // one line saying what a new or changed streamline does, from the files themselves
  try {
    const j = JSON.parse(local.get(p));
    if (/^private\/agents\//.test(p)) {
      const tools = (j.mcp || []).flatMap((s) => (s.tools || []).map((t) => `${t.name}${t.confirm ? " (confirm)" : t.readOnly ? " (read)" : ""}`));
      return `model ${j.model?.id || "?"}; tools: ${tools.join(", ") || "none"}`;
    }
    if (/^agents\//.test(p)) return `"${j.name}" for roles ${(j.roles || []).join(", ")}`;
  } catch {}
  return "";
}

// ── one write ──
const body = { baseRevision: current ?? null, ...(title ? { title: String(title).slice(0, 120) } : {}), items: [...items].sort(),
  files: Object.fromEntries([...added, ...changed, "manifest.json"].map((p) => [p, local.get(p).toString("base64")])), delete: gone };
body.writeId = `skill-${sha(JSON.stringify(body)).slice(0, 32)}`;
if (Buffer.byteLength(JSON.stringify(body)) > 30 * 1024 * 1024) die("this push is over 30 MB; push large assets in a smaller change first (one write is at most 32 MB)");
const route = hotfix ? "env/live/hotfix" : `env/${target}/push`;
const r = await signed("POST", `${E}/${route}${yes ? "" : "?dryRun=1"}`, body);
if (!r.ok) {
  if (r.j.error === "behind") die(behindSays(r, target === "staging" ? "Staging" : "Live"));
  if (r.j.error === "stale_revision") die(`the manifest must carry revision ${r.j.next}: run sign-config.mjs --version ${r.j.next}, then the dry run again`);
  if (r.j.error === "staging_on" || r.j.error === "staging_off") die(`${r.j.message} (Staging was switched while this ran: run the dry run again)`);
  die(`${yes ? (hotfix ? "hotfix" : "push") : "dry run"} refused:\n${refusal(r)}`);
}
const w = hotfix ? r.j.live : r.j;

if (asJSON) {
  console.log(JSON.stringify({ account, host: base, dryRun: !yes, environment: target, hotfix, revision: w.revision, from: current ?? null, stagingOn, items: body.items, key: keyId, added, changed, deleted: gone, fieldChanges: details, worker: r.j }, null, 2));
  process.exit(0);
}
console.log(`${yes ? (hotfix ? "HOTFIXED" : "PUSHED") : "DRY RUN — nothing was written"}: ${account} on ${base} → ${where}, revision ${current ?? "none"} → ${w.revision} (key ${keyId})`);
console.log(`  items: ${body.items.join(", ") || "none"}`);
for (const p of added) console.log(`  + ${p}${summary(p) ? `   ${summary(p)}` : ""}`);
for (const p of changed) {
  console.log(`  ~ ${p}${summary(p) ? `   ${summary(p)}` : ""}`);
  for (const line of (details[p] || []).slice(0, 25)) console.log(`      ${line}`);
}
for (const p of gone) console.log(`  - ${p}`);
console.log(`  ${added.length} added, ${changed.length} changed, ${gone.length} deleted; the manifest goes last`);
if (hotfix) console.log("\nWARNING: a hotfix reaches every member now, ahead of what Staging holds. Staging gets it only once it is merged (--merge-hotfix with the publisher key, a dry run first; or in the app: Library → Publish → Waiting for Staging); a promotion waits until then.");
if (target === "staging") console.log(`\nThis lands on Staging, not Live: members don't get it until it is promoted (${again} --promote, a dry run first). Use --live only for a hotfix the owner asked for.`);
if (!yes) console.log(`\nShow this to the account owner. Push only after they say yes: rerun with --yes.`);

```
