# restore-merge.mjs

> Restore a revision, and merge a waiting hotfix into Staging, from a terminal (config-schema §8d; §8b *Clients*).

Restore a revision, and merge a waiting hotfix into Staging, from a terminal (config-schema §8d; §8b *Clients*).

Raw file: https://streamliner.work/agents/skill/scripts/restore-merge.mjs

```js
// Restore a revision, and merge a waiting hotfix into Staging, from a terminal (config-schema §8d; §8b *Clients*).
// Node 20+, no dependencies. ONE SOURCE: edited here, in scripts/; the skill ships the same bytes as
// skills/building-streamlines/scripts/restore-merge.mjs (scripts/sync-skill.mjs). Not run on its own: the repo's
// scripts/publish-config.mjs (`--restore <n>`, `--merge-hotfix [<n>]`) and the skill's scripts/publish.mjs import it.
//
// Both writes make a NEW revision whose manifest must be signed, so the caller holds two keys: the account's server key
// (scope `config`; it signs the requests) and one of the organization's publisher keys (enrolment.json; it signs the
// manifest, at exactly the organization's next revision, as sign-tenant.mjs / sign-config.mjs do). The app does the same
// with an approved device key (Publishing/Core/PublishingWrites.swift: `restore`, `mergeHotfix`), and this file follows
// it step for step:
//
//   restore   revision n's files onto Staging (Staging on) or Live (Staging off, or --live): the changed ones by
//             reference to the stored file, the ones n lacks deleted (an item's file only), never the keys:
//             enrolment.json and the manifest stay the target's, private/tenant.json keeps the target's serverKeys.
//             POST /v1/admin/<t>/revisions/<n>/restore { env, baseRevision, files, delete, writeId }
//   merge     a hotfix waiting for Staging (env.staging.hotfixPending): per file, three ways (runtime/setup.js
//             mergeFile, the app's merge): Live before the hotfix (base), the hotfix (theirs), Staging now (mine). A
//             field changed on both sides keeps Staging's value and is listed, so the hotfix still waits, unless
//             `settle` says whose value wins ("staging" | "hotfix"; the app's conflict sheet, all at once).
//             POST /v1/admin/<t>/env/staging/merge { hotfix, baseRevision, files, delete, conflicts, writeId }
//
// A dry run unless `yes` (`?dryRun=1`: the Worker checks everything, the manifest included, and writes nothing; nothing
// is written locally either way). Prints what changes in plain words first (paths, items and JSON pointers, never a
// value or a file's contents), refusals in the Worker's words. Never prints a key.
import { readFileSync, existsSync } from "node:fs";
import { join, dirname } from "node:path";
import { fileURLToPath } from "node:url";
import { createHash, createPrivateKey, sign } from "node:crypto";
import vm from "node:vm";

const HERE = dirname(fileURLToPath(import.meta.url));
const sha = (b) => createHash("sha256").update(b).digest("hex");
export const jcs = (v) => v === null || typeof v !== "object" ? JSON.stringify(v)
  : Array.isArray(v) ? "[" + v.map(jcs).join(",") + "]"
  : "{" + Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + jcs(v[k])).join(",") + "}";
const deviceVisible = (p) => !p.startsWith("private/") && p !== "manifest.json" && p !== "enrolment.json";
const parse = (b) => { if (b == null) return undefined; try { return JSON.parse(Buffer.isBuffer(b) ? b.toString("utf8") : b); } catch { return undefined; } };
const same = (a, b) => (a == null && b == null) || (a != null && b != null && Buffer.compare(a, b) === 0);
const text = (b) => (b == null ? null : b.toString("utf8"));
const pretty = (v) => JSON.stringify(v, null, 2) + "\n";

/// The item a path belongs to (the app's PublishItemID(path:)); null = no item (demo/…, manifest, enrolment).
export function itemOf(path) {
  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 = /^private\/connections\/([^/]+)\.json$/.exec(path))) return `connection:${m[1]}`;
  if ((m = /^assets\/(.+)$/.exec(path))) return `asset:${m[1]}`;
  if (path === "private/tenant.json") return "policy";
  if (path === "tenant.json") return "organization";
  return null;
}

/// The JSON pointers that differ between two values (objects per key, arrays and scalars whole): words, never values.
function pointers(a, b, ptr = "", out = []) {
  const obj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
  if (out.length > 30) return out;
  if (obj(a) && obj(b)) { for (const k of new Set([...Object.keys(a), ...Object.keys(b)])) pointers(a[k], b[k], `${ptr}/${String(k).replace(/~/g, "~0").replace(/\//g, "~1")}`, out); return out; }
  if (jcs(a ?? null) !== jcs(b ?? null) || (a === undefined) !== (b === undefined)) out.push(`${a === undefined ? "+" : b === undefined ? "-" : "~"} ${ptr || "/"}`);
  return out;
}

/// runtime/setup.js (the app's merge, a classic script): beside the repo's scripts/, in the packaged skill's vendor/, or
/// from the skill folder inside the repo.
function loadSetup() {
  const at = [join(HERE, "../runtime/setup.js"), join(HERE, "vendor/runtime/setup.js"), join(HERE, "../../../runtime/setup.js")].find((p) => existsSync(p));
  if (!at) throw new Error("runtime/setup.js (the three-way merge) isn't next to this script: use the packaged skill, or run it from the repo");
  const ctx = {};
  vm.runInNewContext(readFileSync(at, "utf8"), ctx, { filename: "setup.js" });
  return ctx.StreamlineSetup;
}

/// Set (or, value undefined, remove) one RFC 6901 pointer in a JSON value.
function setPointer(doc, ptr, value) {
  const keys = ptr.split("/").slice(1).map((k) => k.replace(/~1/g, "/").replace(/~0/g, "~"));
  if (!keys.length) return value;
  let o = doc;
  for (const k of keys.slice(0, -1)) { if (o[k] === null || typeof o[k] !== "object") o[k] = {}; o = o[k]; }
  const last = keys[keys.length - 1];
  if (value === undefined) { if (Array.isArray(o)) o.splice(Number(last), 1); else delete o[last]; } else o[last] = value;
  return doc;
}

/// A manifest over every device-visible file of the resulting tree, the target's settings kept (minApp, refresh,
/// nextKeys), at `version`, signed with the publisher key (Ed25519 over its JCS bytes without `signature`).
export function signManifest({ tenant, entries, version, like, jwk, keyId }) {
  const files = [...entries.keys()].filter(deviceVisible).sort().map((path) => ({ path, sha256: entries.get(path).sha256, bytes: entries.get(path).bytes }));
  const unsigned = {
    schema: "streamline.config/1", tenant, version, published: new Date().toISOString().replace(/\.\d{3}Z$/, "Z"),
    ...(like?.minApp ? { minApp: like.minApp } : {}), ...(like?.refresh ? { refresh: like.refresh } : {}), ...(like?.nextKeys ? { nextKeys: like.nextKeys } : {}),
    files,
  };
  const key = createPrivateKey({ key: { kty: "OKP", crv: "Ed25519", d: jwk.d, x: jwk.x }, format: "jwk" });
  return Buffer.from(pretty({ ...unsigned, signature: { alg: "Ed25519", keyId, sig: sign(null, Buffer.from(jcs(unsigned)), key).toString("base64url") } }));
}

export const refusalWords = (r) => [`${r.status} ${r.j.error || "error"}: ${r.j.message || ""}`.trim(),
  ...(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");

class Refused extends Error {}

/// Run a restore or a hotfix's merge. `o`: { op: "restore" | "merge", tenant, base, signed(method, path, body) → { status,
/// ok, j, raw }, publisherKeyFile, publisherKeyId?, revision? (restore: required; merge: which hotfix, else the oldest
/// waiting), live? (restore onto Live while Staging is on), settle? ("staging" | "hotfix"), yes, json, writeIdPrefix,
/// again (the command line to repeat, for the words), publisherKeyArg? (the
/// --publisher-key path given, repeated in those words; a path, never the key) }. → exit code (0 done or nothing to do, 1 refused).
export async function restoreOrMerge(o) {
  const out = [], say = (s = "") => { if (!o.json) console.log(s); else out.push(s); };
  try { return await run(o, say); }
  catch (e) { if (e instanceof Refused) { console.error(`${o.op === "restore" ? "restore" : "merge"}: ${e.message}`); return 1; } throw e; }
}

async function run(o, say) {
  const refuse = (m) => { throw new Refused(m); };
  o = { ...o, again: `${o.again}${o.publisherKeyArg ? ` --publisher-key ${o.publisherKeyArg}` : ""}` };
  const E = `/v1/admin/${o.tenant}`, dry = !o.yes;
  const get = async (path, what) => { const r = await o.signed("GET", path); if (!r.ok) refuse(`reading ${what}: ${refusalWords(r)}`); return r; };

  // ── the publisher key (never printed) ──
  if (!o.publisherKeyFile || !existsSync(o.publisherKeyFile)) refuse(`no publisher key at ${o.publisherKeyFile || "(none given)"}: a restore and a hotfix's merge make a new manifest, signed with one of the organization's publisher keys (--publisher-key <jwk>)`);
  const jwk = JSON.parse(readFileSync(o.publisherKeyFile, "utf8"));
  if (jwk.kty !== "OKP" || jwk.crv !== "Ed25519" || !jwk.d) refuse("the publisher key must be an Ed25519 private JWK");

  const envR = await get(`${E}/env`, "the environments");
  const envs = envR.j, stagingOn = !!envs.staging?.on;

  // ── where it lands, and what is there now ──
  let target, hot = null, pending = null;
  if (o.op === "restore") {
    target = stagingOn && !o.live ? "staging" : "live";
    if (o.live && !stagingOn) say("note: Staging is off for this organization, so a restore lands on Live anyway (--live changes nothing)");
  } else {
    if (!stagingOn) refuse("Staging is off for this organization: there is no hotfix to merge into it.");
    const waiting = envs.staging.hotfixPending || [];
    if (!waiting.length) { say(`${o.tenant} on ${o.base}: no hotfix is waiting for its merge into Staging; nothing to do`); return 0; }
    hot = o.revision ?? Math.min(...waiting.map((h) => h.revision));
    pending = waiting.find((h) => h.revision === hot);
    if (!pending) refuse(`revision ${hot} isn't a hotfix waiting for its merge (waiting: ${waiting.map((h) => h.revision).join(", ")})`);
    target = "staging";
  }
  const q = target === "staging" ? "?env=staging" : "", where = target === "staging" ? "Staging" : "Live";
  const baseRevision = target === "staging" ? envs.staging.revision : envs.live.revision;
  if (baseRevision == null) refuse(`${where} has no revision yet: push first`);
  const idxR = await get(`${E}/config${q}`, `${where}'s index`);
  const current = new Map((idxR.j.files || []).map((f) => [f.path, f]));
  const readTarget = async (p) => (current.has(p) ? (await get(`${E}/config/${p}${q}`, `${where}'s ${p}`)).raw : null);
  const readRev = async (n, p) => (await get(`${E}/revisions/${n}/files/${p}`, `revision ${n}'s ${p}`)).raw;
  const like = parse(await readTarget("manifest.json")) || {};
  const enrol = parse(await readTarget("enrolment.json")) || {};
  const keyId = o.publisherKeyId || jwk.kid && [...(enrol.keys || []), ...(like.nextKeys || [])].find((k) => k.keyId === jwk.kid && k.pub === jwk.x)?.keyId
    || [...(enrol.keys || []), ...(like.nextKeys || [])].find((k) => k.pub === jwk.x)?.keyId;
  if (!keyId) refuse(`that key isn't one of ${o.tenant}'s publisher keys (${where}'s enrolment.json or the manifest's nextKeys): the Worker would refuse the manifest. Use the organization's publisher key, or --publisher-key-id <id> if you know it is listed`);

  // entries: the resulting tree's hashes (what the manifest lists); files: what the write sends; changes: the words
  const entries = new Map([...current].filter(([p]) => p !== "manifest.json").map(([p, f]) => [p, { sha256: f.sha256, bytes: f.bytes }]));
  const files = {}, del = [], changes = [], conflicts = [];
  const put = (p, bytes) => { files[p] = bytes.toString("base64"); entries.set(p, { sha256: sha(bytes), bytes: bytes.length }); };
  const describe = (p, before, after) => {
    const change = before == null ? "added" : after == null ? "removed" : "changed";
    const row = { path: p, item: itemOf(p), change };
    if (change === "changed" && p.endsWith(".json")) { const a = parse(before), b = parse(after); if (a !== undefined && b !== undefined) row.fields = pointers(a, b); }
    changes.push(row);
  };
  let title;

  if (o.op === "restore") {
    const n = o.revision;
    const old = (await get(`${E}/revisions/${n}`, `revision ${n}`)).j;
    title = `restore revision ${n} (${old.environment}, ${old.kind}${old.title ? ` "${old.title}"` : ""}) onto ${where}`;
    const keep = new Set(["manifest.json", "enrolment.json"]);
    for (const [p, f] of Object.entries(old.files || {}).sort(([a], [b]) => a.localeCompare(b))) {
      if (keep.has(p)) continue;
      if (p === "private/tenant.json") {
        // Never resurrect keys: the policy as it was, with the target's server keys.
        const then = parse(await readRev(n, p)), nowB = await readTarget(p), now = parse(nowB);
        if (!then || typeof then !== "object") continue;
        if (now && "serverKeys" in now) then.serverKeys = now.serverKeys; else delete then.serverKeys;
        if (now && jcs(then) === jcs(now)) continue;
        const b = Buffer.from(pretty(then));
        put(p, b); describe(p, nowB, b);
        continue;
      }
      if (current.get(p)?.sha256 === f.sha256) continue;
      const thenB = await readRev(n, p), nowB = await readTarget(p);
      // The same JSON written another way (key order, spacing) stays as it is.
      if (nowB && p.endsWith(".json") && parse(nowB) !== undefined && jcs(parse(nowB)) === jcs(parse(thenB))) continue;
      files[p] = { ref: f.sha256 }; entries.set(p, { sha256: f.sha256, bytes: f.bytes });
      describe(p, nowB, thenB);
    }
    for (const p of [...current.keys()].sort()) {
      if (keep.has(p) || (old.files || {})[p] || !itemOf(p)) continue;
      del.push(p); entries.delete(p); changes.push({ path: p, item: itemOf(p), change: "removed" });
    }
    if (!changes.length) { say(`${o.tenant} on ${o.base}: ${where} (revision ${baseRevision}) already holds revision ${n}'s content; nothing to restore`); return 0; }
  } else {
    const S = loadSetup();
    const fix = (await get(`${E}/revisions/${hot}`, `the hotfix (revision ${hot})`)).j;
    const before = fix.parent != null ? (await get(`${E}/revisions/${fix.parent}`, `revision ${fix.parent}`)).j : null;
    title = `merge hotfix revision ${hot}${fix.title ? ` "${fix.title}"` : ""} (waiting: ${pending.reason}) into Staging`;
    const skip = new Set(["manifest.json", "enrolment.json"]);
    const paths = [...new Set([...Object.keys(fix.files || {}), ...Object.keys(before?.files || {})])].filter((p) => !skip.has(p) && fix.files?.[p]?.sha256 !== before?.files?.[p]?.sha256).sort();
    for (const p of paths) {
      const old = before?.files?.[p] ? await readRev(before.revision, p) : null;
      const neu = fix.files?.[p] ? await readRev(hot, p) : null;
      const cur = await readTarget(p);
      let result;   // Buffer, or null = no file
      if (!(p.endsWith(".json") || p.endsWith(".md"))) {
        // A binary file: the hotfix's unless Staging changed it too.
        if (same(cur, old) || same(cur, neu)) result = neu;
        else if (o.settle === "hotfix") result = neu;
        else { result = cur; if (o.settle !== "staging") conflicts.push({ path: p, pointer: "" }); }
      } else {
        const r = S.mergeFile(p, text(old), text(neu), text(cur));
        let t = r.merged !== undefined ? r.merged : r.text;
        for (const f of r.fields || []) {
          if (o.settle === "staging") continue;   // `merged` already keeps Staging's value on each field
          if (o.settle !== "hotfix") { conflicts.push({ path: p, pointer: f.pointer }); continue; }
          if (f.pointer === "") t = typeof f.theirs === "string" || f.theirs === undefined ? (f.theirs ?? null) : pretty(f.theirs);
          else t = pretty(setPointer(parse(t) ?? {}, f.pointer, f.theirs));
        }
        result = t == null ? null : Buffer.from(t);
      }
      if (result != null) { if (!same(result, cur)) { put(p, result); describe(p, cur, result); } }
      else if (cur != null) { del.push(p); entries.delete(p); changes.push({ path: p, item: itemOf(p), change: "removed" }); }
    }
  }

  // ── the words, before anything is sent ──
  say(`${o.tenant} on ${o.base}: ${dry ? "DRY RUN" : "about to"} ${title}`);
  say(`  ${where} is at revision ${baseRevision}; the new revision is ${envs.nextRevision}, its manifest signed with publisher key ${keyId}`);
  for (const c of changes) {
    say(`  ${c.change === "added" ? "+" : c.change === "removed" ? "-" : "~"} ${c.path}${c.item ? `  (${c.item})` : ""}`);
    for (const f of (c.fields || []).slice(0, 20)) say(`      ${f}`);
  }
  if (!changes.length) say(`  no file changes${conflicts.length ? "" : " (the write records the merge, so the hotfix stops waiting)"}`);
  for (const c of conflicts) say(`  ! ${c.path} ${c.pointer || "(the whole file)"}: changed on both Live (the hotfix) and Staging; Staging's kept`);
  if (o.op === "restore") say("  kept as they are: enrolment.json, the server keys in private/tenant.json and the manifest's nextKeys (a restore never brings keys back)");

  // ── one write (re-signed once at the Worker's next revision if someone wrote meanwhile) ──
  const stable = { op: o.op, n: o.revision ?? hot, baseRevision, files: Object.fromEntries(Object.entries(files).map(([p, v]) => [p, typeof v === "string" ? sha(Buffer.from(v, "base64")) : v.ref])), del, conflicts };
  const writeId = `${o.writeIdPrefix || "cli"}-${o.op}-${sha(JSON.stringify(stable)).slice(0, 24)}`;
  let version = envs.nextRevision, r;
  for (let attempt = 0; attempt < 2; attempt++) {
    const body = o.op === "restore"
      ? { env: target, baseRevision, files: { ...files, "manifest.json": signManifest({ tenant: o.tenant, entries, version, like, jwk, keyId }).toString("base64") }, delete: del, writeId }
      : { hotfix: hot, baseRevision, files: { ...files, "manifest.json": signManifest({ tenant: o.tenant, entries, version, like, jwk, keyId }).toString("base64") }, delete: del, conflicts, writeId };
    const route = o.op === "restore" ? `${E}/revisions/${o.revision}/restore` : `${E}/env/staging/merge`;
    r = await o.signed("POST", `${route}${dry ? "?dryRun=1" : ""}`, body);
    if (r.status === 409 && r.j.error === "stale_revision" && Number.isInteger(r.j.next) && r.j.next !== version) { version = r.j.next; continue; }
    break;
  }
  if (!r.ok) {
    const hint = {
      behind: `${where} moved to revision ${r.j.current ?? "?"} while this ran: someone wrote meanwhile. Run it again (it reads ${where} again).`,
      not_pending: "that hotfix isn't waiting any more (someone merged it meanwhile): check with `admin.mjs … env status`.",
      keys_changed: "a restore never brings keys back; this client keeps them, so the target's keys changed while it ran: run it again.",
      bad_manifest_signature: "the publisher key isn't the organization's: ask the owner which key signs its manifests.",
      staging_off: "Staging was turned off while this ran: run it again.",
    }[r.j.error];
    refuse(`${dry ? "dry run" : o.op} refused by the Worker:\n${refusalWords(r)}${hint ? `\n${hint}` : ""}`);
  }
  if (o.json) { console.log(JSON.stringify({ account: o.tenant, host: o.base, op: o.op, dryRun: dry, environment: target, revision: r.j.revision, from: baseRevision, ...(o.op === "restore" ? { restoreOf: o.revision } : { hotfix: hot }), changes, conflicts, publisherKey: keyId, worker: r.j }, null, 2)); return 0; }
  say(`${dry ? "DRY RUN ok, nothing written — would make" : "made"} revision ${r.j.revision} on ${where}: ${(r.j.put || []).length} written, ${(r.j.deleted || []).length} deleted`);
  if (o.op === "restore" && target === "live" && stagingOn) say(`\nwarning: Live now has a change Staging lacks, like a hotfix: it waits for its merge into Staging (${o.again} --merge-hotfix${dry ? "" : ` ${r.j.revision}`}), and a whole promotion waits until then.`);
  if (o.op === "restore" && target === "staging" && !dry) say(`\nOn Staging, not Live. Promote it when it has been tried: ${o.again} --promote (a dry run), then --promote --yes`);
  if (o.op === "merge" && conflicts.length) say(`\n${conflicts.length} field${conflicts.length === 1 ? "" : "s"} changed on both sides ${dry ? "would keep" : "kept"} Staging's value, so the hotfix ${dry ? "would still wait" : "still waits"}. Settle them: ${o.again} --merge-hotfix ${hot} --settle staging (keep Staging's) or --settle hotfix (take the hotfix's), or field by field in the app (Library → Publish → Waiting for Staging).`);
  else if (o.op === "merge" && !dry) say(`\nThe hotfix is in Staging and no longer waits: Staging can be promoted again.`);
  if (dry) say(`\nNothing was written. To ${o.op === "restore" ? "restore" : "merge"}: ${o.again} ${o.op === "restore" ? `--restore ${o.revision}${o.live ? " --live" : ""}` : `--merge-hotfix ${hot}${o.settle ? ` --settle ${o.settle}` : ""}`} --yes`);
  return 0;
}

```
