# mirror.mjs

> Put a personal streamline or brief straight into the Streamliner app on this Mac, through its folder of files (Files on this Mac: the mirror).

Put a personal streamline or brief straight into the Streamliner app on this Mac, through its folder of files (Files on this Mac: the mirror).

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

```js
#!/usr/bin/env node
// Put a personal streamline or brief straight into the Streamliner app on this Mac, through its folder of files (Files
// on this Mac: the mirror). Node 20+, no dependencies. Never prints a key or token, and never writes one.
//
//   node mirror.mjs find   [--mirror <dir>] [--json]
//   node mirror.mjs status [--mirror <dir>] [--json]
//   node mirror.mjs put <file.streamline.json | brief.md> [--mirror <dir>] [--id <id>] [--wait <s>] [--dev] [--json] [--yes]
//   node mirror.mjs put <file> --place <organization folder> --path <file in its layout> [--yes]   (owners and admins)
//   node mirror.mjs push <organization folder> [--note "<what changed>"] [--wait <s>] [--json]
//   node mirror.mjs tool <personal | organization folder> <tool> ['<json args>'] [--wait <s>] [--json]
//   node mirror.mjs tools [<place>] [--json]
//
// find     Where the mirror is: --mirror <dir>, else $STREAMLINER_MIRROR, else ~/Streamliner, else a short search of the
//          home folder (4 levels, skipping Library, node_modules and .git) for .streamliner/mirror.json. Run from a mirror's
//          own copy (`<mirror>/.streamliner/skill/scripts/mirror.mjs`) or from inside a mirror, that mirror comes first. A folder counts
//          only when that file says { "app": "Streamliner", "format": 1 }. Prints the folder, when the app last wrote it,
//          whether the app is running, and the personal streamlines and briefs in it.
// status   What the app says in .streamliner/review.json: edits waiting for the person's tap, edits not applied, and
//          what was applied lately, in plain words.
// put      Checks the file (check.mjs: the same rules the app's checker runs; and the app's secret rules), then, with
//          --yes, writes it into personal/ atomically (a temporary file in the same folder, then a rename) and waits
//          (default 10 s) for the app's answer: applied; waiting for the person's tap (a new streamline always waits);
//          not applied, in the app's words; or the app isn't running, so it applies at the next launch. An existing id is
//          an edit: a short diff is printed first. Without --yes it is a dry run that writes nothing.
//
// put --place  An organization's folder (docs/plans/mirror-organizations.md): the whole setup as the person's Mac runs it in
//          Local. For owners and admins (mirror.json's places): the same level rules and checks as the app; the file
//          becomes one of their Local changes (widening waits for their tap).
//          A streamline's private file (private/agents/<id>.json) carries its toll-free block (`tollfree`, #192) like
//          every other private field: put it whole, and the diff names each toll-free field that changes.
// push     Asks the app to open the Push sheet for an organization, the note as its title. The person taps Push (and the
//          device key asks for them); the answer says pushed (to Staging or Live, at which revision), canceled or refused.
// tool     Runs one of the Concierge's tools through the app (the same code, permissions and taps): reads and Local-change
//          writes at once, a confirm tool after the person's tap on a card. Prints the app's answer.
// tools    What each place may call (.streamliner/tools.json, written by the app).
//
// Never writes status.json, settings, .streamliner/ (except a request), CHANGES.md, manifest.json or a .server.json.
// Never approves anything: the tap in the app is the person's (law 5).
//
// Exit 0 done (or a clean dry run), 1 refused or not applied, 2 usage, 3 no mirror found.
// Tests: STREAMLINER_APP_RUNNING=1|0 stands in for `pgrep -x Streamline` (scripts/skillmirrorcheck.mjs).

import { readFileSync, writeFileSync, existsSync, readdirSync, statSync, renameSync, mkdirSync, rmSync, mkdtempSync } from "node:fs";
import { join, dirname, basename, resolve } from "node:path";
import { homedir, tmpdir } from "node:os";
import { fileURLToPath } from "node:url";
import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";

const HERE = dirname(fileURLToPath(import.meta.url));
const argv = process.argv.slice(2);
const cmd = argv[0];
const VALUED = new Set(["--mirror", "--wait", "--id", "--place", "--path", "--note", "--args"]);
const opt = (n) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined; };
const flag = (n) => argv.includes(`--${n}`);
const positional = argv.slice(1).filter((a, i, all) => !a.startsWith("--") && !VALUED.has(all[i - 1]));
const asJSON = flag("json");

// The app's own secret rules (runtime/configcheck.js SECRET_PATTERNS and SECRET_KEYS; skillmirrorcheck keeps them equal).
const SECRET_PATTERNS = [
  [/sk-ant-[A-Za-z0-9_-]{8,}/, "an Anthropic API key"], [/\bsk-(proj-)?[A-Za-z0-9_-]{20,}/, "an OpenAI-style API key"],
  [/\bgsk_[A-Za-z0-9]{10,}/, "a Groq API key"], [/\bAKIA[0-9A-Z]{16}\b/, "an AWS access key"],
  [/-----BEGIN [A-Z ]*PRIVATE KEY/, "a private key"], [/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/, "a JWT (a bearer token)"],
  [/\bgh[pousr]_[A-Za-z0-9]{30,}/, "a GitHub token"], [/\bxox[abprs]-[A-Za-z0-9-]{10,}/, "a Slack token"],
];
const SECRET_KEYS = /^(api[_-]?key|apikey|secret|client[_-]?secret|private[_-]?key|password|passwd|access[_-]?token|refresh[_-]?token|bearer)$/i;
const STREAMLINE_ID = /^[a-z0-9_]{2,32}$/;          // PersonalStore.validId (and never "concierge")
const BRIEF_ID = /^[a-z0-9][a-z0-9-]{1,47}$/;        // config-schema §4.7
const BRIEF_MAX = 20000;
const SCHEMA = "streamline.personal/1";

const out = (s) => { if (!asJSON) console.log(s); };
const fail = (code, text, extra = {}) => {
  if (asJSON) console.log(JSON.stringify({ ok: false, error: text, ...extra }, null, 2));
  else console.error(text);
  process.exit(code);
};
const readJSON = (p) => { try { return JSON.parse(readFileSync(p, "utf8")); } catch { return null; } };
/// Mirror.hash: the first 12 bytes of SHA-256, as hex.
const appHash = (buf) => createHash("sha256").update(buf).digest("hex").slice(0, 24);

/// Secret findings in a JSON value or a text: [{ path, message }] (the app quarantines a file on any).
function secrets(value, text) {
  const found = [];
  if (value === undefined) {
    String(text).split("\n").forEach((line, i) => { for (const [re, what] of SECRET_PATTERNS) if (re.test(line)) found.push({ path: `line ${i + 1}`, message: `looks like ${what}` }); });
    return found;
  }
  const visit = (v, ptr, key) => {
    if (typeof v === "string") {
      for (const [re, what] of SECRET_PATTERNS) if (re.test(v)) { found.push({ path: ptr, message: `looks like ${what}` }); return; }
      if (key && SECRET_KEYS.test(key) && v.trim() && !/^\s*\{\{[^}]*\}\}\s*$/.test(v)) found.push({ path: ptr, message: `"${key}" holds a literal value` });
    } else if (Array.isArray(v)) v.forEach((x, i) => visit(x, `${ptr}/${i}`));
    else if (v && typeof v === "object") for (const [k, x] of Object.entries(v)) visit(x, `${ptr}/${k.replace(/~/g, "~0").replace(/\//g, "~1")}`, k);
  };
  visit(value, "");
  return found;
}

// ── find ──

/// Why `dir` is not a mirror (null: it is one).
function notAMirror(dir) {
  const f = join(dir, ".streamliner/mirror.json");
  if (!existsSync(f)) return `${dir} has no .streamliner/mirror.json`;
  const m = readJSON(f);
  if (!m) return `${f} isn't valid JSON`;
  if (m.app !== "Streamliner" || m.format !== 1) return `${f} isn't a Streamliner mirror (app "${m.app}", format ${m.format})`;
  return null;
}

function search(home) {
  const skip = new Set(["Library", "node_modules", ".git", ".Trash"]);
  const queue = [[home, 0]];
  while (queue.length) {
    const [d, depth] = queue.shift();
    if (existsSync(join(d, ".streamliner/mirror.json")) && !notAMirror(d)) return d;
    if (depth >= 4) continue;
    let names = [];
    try { names = readdirSync(d, { withFileTypes: true }); } catch { continue; }
    for (const e of names) if (e.isDirectory() && !skip.has(e.name) && !e.name.startsWith(".")) queue.push([join(d, e.name), depth + 1]);
  }
  return null;
}

/// { dir, via } or { dir: null, problems }.
function findMirror() {
  const problems = [];
  const explicit = opt("mirror");
  if (explicit) {
    const d = resolve(explicit), why = notAMirror(d);
    return why ? { dir: null, problems: [why], explicit: true } : { dir: d, via: "--mirror" };
  }
  const env = process.env.STREAMLINER_MIRROR;
  if (env) {
    const d = resolve(env), why = notAMirror(d);
    if (!why) return { dir: d, via: "$STREAMLINER_MIRROR" };
    problems.push(`$STREAMLINER_MIRROR: ${why}`);
  }
  // The mirror this copy of the script came with (`.streamliner/skill/scripts/`), then the folder Claude runs in.
  const own = resolve(HERE, "../../..");
  if (!notAMirror(own)) return { dir: own, via: "the folder this script came with" };
  for (let d = resolve(process.cwd()); ; d = dirname(d)) {
    if (!notAMirror(d)) return { dir: d, via: "the current folder" };
    if (dirname(d) === d) break;
  }
  const home = homedir();
  const usual = join(home, "Streamliner");
  if (!notAMirror(usual)) return { dir: usual, via: "~/Streamliner" };
  const found = search(home);
  if (found) return { dir: found, via: "a search of the home folder" };
  return { dir: null, problems };
}

function appRunning() {
  const forced = process.env.STREAMLINER_APP_RUNNING;
  if (forced === "1" || forced === "0") return forced === "1";
  const r = spawnSync("pgrep", ["-x", "Streamline"], { encoding: "utf8" });
  return r.status === 0;
}

const HOW_TO_TURN_ON = "Turn it on in Streamliner on this Mac: the Library's Files tab → Keep as Files on This Mac… (or the offer on the app's first run). "
  + "Without it, give the person the file to import (Files, AirDrop).";

function mirrorOrExit() {
  const f = findMirror();
  if (!f.dir) fail(3, (f.explicit ? f.problems[0] : "No Streamliner mirror found on this Mac." + (f.problems.length ? ` (${f.problems.join("; ")})` : "")) + " " + HOW_TO_TURN_ON, { found: false });
  return f;
}

function personalIds(dir) {
  const p = join(dir, "personal");
  const ls = (d) => { try { return readdirSync(d); } catch { return []; } };
  return {
    streamlines: ls(p).filter((n) => n.endsWith(".streamline.json") && !n.startsWith(".")).map((n) => n.slice(0, -".streamline.json".length)).sort(),
    briefs: ls(join(p, "briefs")).filter((n) => n.endsWith(".md") && !n.startsWith(".")).map((n) => n.slice(0, -3)).sort(),
  };
}

function cmdFind() {
  const f = mirrorOrExit();
  const m = readJSON(join(f.dir, ".streamliner/mirror.json"));
  const running = appRunning();
  const ids = personalIds(f.dir);
  const places = (m.places || []).map((p) => ({ id: p.id, access: p.access, folder: p.folder, ...(p.name ? { name: p.name } : {}) }));
  if (asJSON) { console.log(JSON.stringify({ ok: true, found: true, mirror: f.dir, via: f.via, lastSync: m.lastSync ?? null, appRunning: running, places, personal: ids }, null, 2)); return; }
  out(`Mirror: ${f.dir} (found via ${f.via})`);
  out(`Last written by the app: ${m.lastSync ?? "unknown"}`);
  out(`The app is ${running ? "running: edits apply within a second or two" : "not running: edits apply at its next launch"}.`);
  out(`Personal streamlines: ${ids.streamlines.join(", ") || "none"}`);
  out(`Personal briefs: ${ids.briefs.join(", ") || "none"}`);
}

// ── status ──

function review(dir) { return readJSON(join(dir, ".streamliner/review.json")) || { pending: [], notices: [] }; }

function cmdStatus() {
  const f = mirrorOrExit();
  const r = review(f.dir);
  const running = appRunning();
  const pending = r.pending || [], notices = r.notices || [];
  if (asJSON) { console.log(JSON.stringify({ ok: true, mirror: f.dir, appRunning: running, pending, notices }, null, 2)); return; }
  out(`Mirror: ${f.dir} · the app is ${running ? "running" : "not running"}`);
  if (!pending.length && !notices.some((n) => n.tone === "warning")) out("Nothing is waiting: every file is what the app has.");
  for (const p of pending) {
    out(`Waiting for the person's tap: ${p.name} (${p.path})${p.removal ? ", a removal" : ""}. They approve it on the card in Streamliner.`);
    for (const why of p.reasons || []) out(`  - ${why}`);
  }
  for (const n of notices.filter((n) => n.tone === "warning")) out(`Not applied: ${n.text}`);
  for (const n of notices.filter((n) => n.tone !== "warning")) out(`Lately: ${n.text}`);
  for (const p of orgPlaces(f.dir)) {
    out(`\n${p.name || p.folder} (${p.folder}, ${p.access}): ${(p.localChanges || []).length} Local change${(p.localChanges || []).length === 1 ? "" : "s"}${(p.conflicts || []).length ? `, ${(p.conflicts || []).length} in conflict` : ""}.`);
    for (const c of p.localChanges || []) out(`  - ${c}`);
    for (const c of p.conflicts || []) out(`  - conflict: ${c} (the organization's copy is beside it as .server.json; delete that to keep yours)`);
    if (p.lastPush) out(`  Last push: r${p.lastPush.revision} to ${p.lastPush.environment === "staging" ? "Staging" : "Live"} (${p.lastPush.at}).`);
  }
}

/// The organization places in mirror.json (owners and admins), with what the app says about each.
function orgPlaces(dir) {
  const m = readJSON(join(dir, ".streamliner/mirror.json")) || {};
  return (m.places || []).filter((p) => p.id !== "personal").map((p) => ({ ...p, folder: String(p.folder || "").replace(/\/$/, "") }));
}

// ── requests: push, tool, tools ──

/// Writes a request for the app and waits for its answer (`.streamliner/answers/<id>.json`), which it prints and deletes.
async function request(dir, id, body, waitSeconds) {
  const reqDir = join(dir, ".streamliner/requests"), ansFile = join(dir, ".streamliner/answers", `${id}.json`);
  mkdirSync(reqDir, { recursive: true });
  rmSync(ansFile, { force: true });
  const tmp = join(reqDir, `.${id}.${process.pid}.tmp`);
  writeFileSync(tmp, JSON.stringify({ ...body, at: new Date().toISOString() }, null, 2) + "\n");
  renameSync(tmp, join(reqDir, `${id}.json`));
  const end = Date.now() + waitSeconds * 1000;
  while (Date.now() < end) {
    const a = readJSON(ansFile);
    if (a) { rmSync(ansFile, { force: true }); return a; }
    await new Promise((r) => setTimeout(r, 250));
  }
  return { status: "no_answer", text: `No answer from the app within ${waitSeconds} s. The request stays in .streamliner/requests/ until the app reads it; run this again to wait.` };
}

function report(a) {
  if (asJSON) { console.log(JSON.stringify({ ok: !["refused", "failed", "no_answer"].includes(a.status), ...a }, null, 2)); }
  else {
    out(a.text || a.status);
    if (a.result !== undefined && a.status !== "pushed") out(typeof a.result === "string" ? a.result : JSON.stringify(a.result, null, 2));
  }
  process.exit(["refused", "failed", "no_answer"].includes(a.status) ? 1 : 0);
}

async function cmdPush() {
  const folder = (positional[0] || "").replace(/\/$/, "");
  if (!folder) fail(2, "usage: node mirror.mjs push <organization folder> [--note \"<what changed>\"] [--wait <s>] [--json]");
  const f = mirrorOrExit();
  const place = orgPlaces(f.dir).find((p) => p.folder === folder);
  if (!place) fail(1, `"${folder}" isn't an organization folder in ${f.dir}. mirror.mjs status lists them.`);
  if (!appRunning()) fail(1, "The app isn't running: open Streamliner on this Mac, then ask again. A push is always the person's tap in the app.");
  if (!asJSON) out(`Asked Streamliner to open the Push sheet for ${place.name || folder}. The person reviews it and taps Push; waiting for their answer…`);
  report(await request(f.dir, `push-${folder.replace(/[^A-Za-z0-9_-]/g, "_")}`, { place: folder, note: opt("note") || "" }, Number(opt("wait") ?? 180)));
}

async function cmdTool() {
  const [place, tool, argText] = positional;
  if (!place || !tool) fail(2, "usage: node mirror.mjs tool <personal | organization folder> <tool> ['<json args>'] [--wait <s>] [--json]");
  let args = {};
  if (argText) { try { args = JSON.parse(argText); } catch (e) { fail(2, `The arguments aren't JSON: ${e.message}`); } }
  const f = mirrorOrExit();
  if (!appRunning()) fail(1, "The app isn't running: open Streamliner on this Mac, then ask again.");
  const catalog = readJSON(join(f.dir, ".streamliner/tools.json"));
  const spec = (catalog?.places?.[place] || []).find((t) => t.name === tool);
  if (catalog && !spec) fail(1, catalog.excluded?.[tool] || `${tool} isn't a tool you may call in ${place}. node mirror.mjs tools ${place} lists them.`);
  if (spec?.gate === "confirm" && !asJSON) out(`${tool} waits for the person's tap on a card in Streamliner, as in the Concierge.`);
  const id = `tool-${Date.now().toString(36)}${Math.random().toString(36).slice(2, 6)}`;
  report(await request(f.dir, id, { place, tool, args }, Number(opt("wait") ?? (spec?.gate === "confirm" ? 180 : 30))));
}

function cmdTools() {
  const f = mirrorOrExit();
  const catalog = readJSON(join(f.dir, ".streamliner/tools.json"));
  if (!catalog) fail(1, "The app hasn't written .streamliner/tools.json yet (an older build, or the app hasn't run since the mirror was turned on).");
  const only = positional[0];
  if (asJSON) { console.log(JSON.stringify(only ? { place: only, tools: catalog.places?.[only] || [] } : catalog, null, 2)); return; }
  for (const [place, list] of Object.entries(catalog.places || {})) {
    if (only && place !== only) continue;
    out(`${place}:`);
    for (const t of list) out(`  ${t.name}${t.gate === "confirm" ? " (waits for a tap)" : t.gate === "write" ? " (writes Local changes or drafts)" : ""}: ${t.title || ""}`);
  }
  if (!only) for (const [t, why] of Object.entries(catalog.excluded || {})) out(`not from files: ${t}: ${why}`);
}

// ── put ──

function short(v) {
  const s = v === undefined ? "(none)" : typeof v === "string" ? JSON.stringify(v) : JSON.stringify(v);
  return s.length > 70 ? s.slice(0, 67) + "…" : s;
}

/// Top-level keys that differ, as lines: + added, - removed, ~ changed.
function diffLines(before, after) {
  const lines = [];
  for (const k of [...new Set([...Object.keys(before || {}), ...Object.keys(after || {})])].sort()) {
    const a = before?.[k], b = after?.[k];
    if (JSON.stringify(a) === JSON.stringify(b)) continue;
    if (a === undefined) lines.push(`+ ${k}: ${short(b)}`);
    else if (b === undefined) lines.push(`- ${k}`);
    else lines.push(`~ ${k}: ${short(a)} → ${short(b)}`);
  }
  return lines;
}

/// [tollfree] #192: a streamline's private file carries its `tollfree` block like any other private field (the app, the
/// Concierge and admin.mjs change the same block); the diff names each of its fields, since one line can't show them.
function nestedDiff(a, b, at) {
  const obj = (v) => v && typeof v === "object" && !Array.isArray(v);
  if (obj(a) && obj(b)) return [...new Set([...Object.keys(a), ...Object.keys(b)])].sort().flatMap((k) => nestedDiff(a[k], b[k], `${at}.${k}`));
  if (JSON.stringify(a) === JSON.stringify(b)) return [];
  return [a === undefined ? `+ ${at}: ${short(b)}` : b === undefined ? `- ${at}` : `~ ${at}: ${short(a)} → ${short(b)}`];
}
function tollfreeDiff(diff, before, after) {
  if (JSON.stringify(before?.tollfree) === JSON.stringify(after?.tollfree)) return diff;
  const lines = [...diff.filter((l) => !/^[+~-] tollfree(:|$)/.test(l)), ...nestedDiff(before?.tollfree, after?.tollfree, "tollfree")];
  const t = after?.tollfree;
  if (t?.enabled && t?.embed?.origins === "any") lines.push("  (any website can put this chat on its pages, and the organization's key pays for it)");
  return lines;
}

function textDiff(before, after) {
  const a = String(before).split("\n"), b = String(after).split("\n");
  const sa = new Set(a), sb = new Set(b);
  return [...b.filter((l) => !sa.has(l) && l.trim()).slice(0, 6).map((l) => `+ ${l.slice(0, 80)}`),
          ...a.filter((l) => !sb.has(l) && l.trim()).slice(0, 6).map((l) => `- ${l.slice(0, 80)}`)];
}

/// The skill's own check (check.mjs) of one personal file, as JSON.
function runCheck(file) {
  const r = spawnSync(process.execPath, [join(HERE, "check.mjs"), file, "--json", ...(flag("dev") ? ["--dev"] : [])], { encoding: "utf8" });
  try { return JSON.parse(r.stdout); } catch { return { ok: false, errors: [{ path: "", message: (r.stderr || r.stdout || "the check didn't answer").trim().split("\n").pop() }] }; }
}

// An organization folder's files a person may edit there (MirrorOrgRules.editable).
const ORG_PATH = /^(tenant\.json|private\/tenant\.json|(agents|templates|forms|private\/agents|private\/connections)\/[^/]+\.json|private\/briefs\/[^/]+\.md)$/;

/// What one level may change (ConciergeOrgRules.refusal): the app refuses the same, in the same words.
function levelRefusal(access, org, rel, before, after) {
  const possessive = /s$/i.test(org) ? `${org}'` : `${org}'s`;
  if (rel === "private/tenant.json") {
    if (access !== "owner") return `Only an owner changes ${possessive} policies (daily limits, networks, link sharing, how long records are kept).`;
    const b = before ? JSON.parse(before) : {}, a = JSON.parse(after);
    const changed = ["serverKeys", "access", "users"].filter((k) => JSON.stringify(b[k] ?? null) !== JSON.stringify(a[k] ?? null));
    return changed.length ? `Server keys, access levels and the directory's people (${changed.join(", ")}) aren't changed from files: keys are the organization's own, and people are changed in People.` : null;
  }
  if (access === "owner") return null;
  const owners = `Admins publish streamlines, briefs, templates and forms. Changing ${possessive} brand or sign-in needs an owner.`;
  if (rel === "tenant.json") {
    const canon = (v) => v === null || typeof v !== "object" ? JSON.stringify(v) : Array.isArray(v) ? `[${v.map(canon).join(",")}]`
      : `{${Object.keys(v).sort().map((k) => JSON.stringify(k) + ":" + canon(v[k])).join(",")}}`;
    const strip = (t) => { const o = JSON.parse(t || "{}"); delete o.kinds; return canon(o); };
    return strip(before) === strip(after) ? null : owners;
  }
  if (rel.startsWith("private/connections/") || rel === "enrolment.json") return owners;
  return null;
}

/// An organization place from mirror.json, for owners and admins.
function orgPlace(dir, folder) {
  const m = readJSON(join(dir, ".streamliner/mirror.json")) || {};
  const p = (m.places || []).find((x) => x.folder === `${folder}/` || x.folder === folder);
  if (!p) fail(1, `"${folder}" isn't an organization folder in ${dir} (mirror.json's places: ${(m.places || []).map((x) => x.folder).join(", ") || "none"}).`);
  if (p.id === "personal") return null;
  if (!["owner", "admin"].includes(p.access)) fail(1, `${p.name || folder}: only owners and admins change an organization's files.`);
  return p;
}

/// The skill's check over an organization folder, with and without the file: only the problems the file brings count.
function orgCheck(dir, folder, rel, bytes) {
  const tmp = mkdtempSync(join(tmpdir(), "mirror-org-"));
  try {
    const copy = (from, to) => { for (const n of readdirSync(from, { withFileTypes: true })) { if (n.name.startsWith(".") && n.name !== ".") continue; const a = join(from, n.name), b = join(to, n.name); if (n.isDirectory()) { mkdirSync(b, { recursive: true }); copy(a, b); } else writeFileSync(b, readFileSync(a)); } };
    const before = join(tmp, "before"), after = join(tmp, "after");
    mkdirSync(before, { recursive: true }); mkdirSync(after, { recursive: true });
    copy(join(dir, folder), before); copy(join(dir, folder), after);
    mkdirSync(dirname(join(after, rel)), { recursive: true });
    writeFileSync(join(after, rel), bytes);
    const key = (e) => `${e.file}|${e.path}|${e.code || e.message}`;
    const b = new Set((runCheck(before).errors || []).map(key));
    const a = runCheck(after);
    return { errors: (a.errors || []).filter((e) => !b.has(key(e))), warnings: a.warnings || [] };
  } finally { rmSync(tmp, { recursive: true, force: true }); }
}

/// What the person's file becomes in the mirror: { rel, bytes, value?, kind, id, problems }.
function prepare(src, dir) {
  const problems = [];
  const text = readFileSync(src, "utf8");
  const placeName = opt("place");
  if (placeName && placeName !== "personal") {
    const place = orgPlace(dir, placeName.replace(/\/$/, ""));
    if (place) {
      const folder = place.folder.replace(/\/$/, "");
      const rel = opt("path") || "";
      if (!ORG_PATH.test(rel)) fail(2, `Pass --path <file in the organization's layout>: tenant.json, agents/<id>.json, private/agents/<id>.json, private/briefs/<id>.md, templates/<id>.json, forms/<id>.json (never manifest.json, enrolment.json, CHANGES.md or a .server.json).`);
      let value;
      if (rel.endsWith(".json")) { try { value = JSON.parse(text); } catch (e) { fail(1, `${src} isn't valid JSON: ${e.message}`); } }
      for (const s of value === undefined ? secrets(undefined, text) : secrets(value)) problems.push(`${s.path || "/"}: ${s.message}. Never put a key in a file: remove it, and rotate that key where it came from`);
      const target = join(dir, folder, rel);
      const before = existsSync(target) ? readFileSync(target, "utf8") : null;
      if (!problems.length) { try { const why = levelRefusal(place.access, place.name || folder, rel, before, text); if (why) problems.push(why); } catch (e) { problems.push(`${rel}: ${e.message}`); } }
      return { kind: "organization", org: place, folder, id: rel, rel: `${folder}/${rel}`, inner: rel, bytes: Buffer.from(text), value, text, problems };
    }
  }
  if (src.endsWith(".md")) {
    const id = opt("id") || basename(src).replace(/\.md$/, "");
    if (!BRIEF_ID.test(id)) problems.push(`"${id}" isn't a brief id (2-48 of a-z, 0-9 and -); pass --id`);
    if (text.length > BRIEF_MAX) problems.push(`the brief is ${text.length} characters; the limit is ${BRIEF_MAX}`);
    for (const s of secrets(undefined, text)) problems.push(`${s.path}: ${s.message}. Never put a key in a file: remove it, and rotate that key where it came from`);
    return { kind: "brief", id, rel: `personal/briefs/${id}.md`, bytes: Buffer.from(text), text, problems };
  }
  if (!src.endsWith(".json")) fail(2, "put takes a *.streamline.json (a personal streamline) or a brief's .md file.");
  let value;
  try { value = JSON.parse(text); } catch (e) { fail(1, `${src} isn't valid JSON: ${e.message}`); }
  if (!value || typeof value !== "object" || Array.isArray(value)) fail(1, `${src} isn't a streamline (a JSON object).`);
  if (value.schema && value.schema !== SCHEMA) problems.push(`schema is "${value.schema}"; a personal streamline is ${SCHEMA}`);
  const fromName = basename(src).replace(/\.streamline\.json$|\.json$/, "");
  const id = opt("id") || value.id || (STREAMLINE_ID.test(fromName) ? fromName : String(value.name || "").toLowerCase().replace(/[^a-z0-9]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 32));
  if (!STREAMLINE_ID.test(id) || id === "concierge") problems.push(`"${id}" isn't a streamline id ([a-z0-9_]{2,32}, not "concierge"); pass --id`);
  // The mirror's shape is the import file's (config-schema §10.1) with id and schema always present: Mirror.handle adds both.
  const norm = { schema: SCHEMA, id, ...value };
  norm.schema = SCHEMA; norm.id = id;
  for (const s of secrets(norm)) problems.push(`${s.path || "/"}: ${s.message}. Never put a key in a file: remove it, and rotate that key where it came from`);
  const bytes = Buffer.from(JSON.stringify(norm, null, 2) + "\n");
  return { kind: "streamline", id, rel: `personal/${id}.streamline.json`, bytes, value: norm, problems };
}

/// One poll's verdict, or null to keep waiting. `final` at the deadline: read what is there.
function verdict(dir, rel, before, final) {
  const reviewText = (() => { try { return readFileSync(join(dir, ".streamliner/review.json"), "utf8"); } catch { return ""; } })();
  const changed = reviewText !== before.review;
  const r = (() => { try { return JSON.parse(reviewText); } catch { return { pending: [], notices: [] }; } })();
  const about = (x) => x.path === rel || (x.paths || []).includes(rel);
  const pend = (r.pending || []).find(about);
  if (pend && (changed || final)) return { outcome: "waiting", name: pend.name, reasons: pend.reasons || [], removal: !!pend.removal };
  const note = [...(r.notices || [])].reverse().find(about);
  if (note && changed) return note.tone === "warning" ? { outcome: "not_applied", text: note.text } : { outcome: "applied", text: note.text };
  // The app's record: it rewrote mirror.json with the file as it is now (an edit equal to what it had leaves no notice).
  const m = readJSON(join(dir, ".streamliner/mirror.json"));
  let disk = null;
  try { disk = readFileSync(join(dir, rel)); } catch {}
  if (m && disk && m.lastSync !== before.lastSync && m.files?.[rel] === appHash(disk)) return { outcome: "applied", text: "The app has it." };
  // An organization's folder: the export record (OrgFiles, full sha256) catching up with the file means it was staged.
  const slash = rel.indexOf("/"), folder = rel.slice(0, slash), inner = rel.slice(slash + 1);
  const rec = folder !== "personal" ? readJSON(join(dir, `.streamliner/exports/${folder}.json`)) : null;
  if (rec && disk && rec.files?.[inner] === createHash("sha256").update(disk).digest("hex") && before.record !== rec.files?.[inner]) return { outcome: "applied", text: "Added to Local changes." };
  if (final && note) return note.tone === "warning" ? { outcome: "not_applied", text: note.text } : { outcome: "applied", text: note.text };
  return null;
}

async function cmdPut() {
  const src = positional[0];
  if (!src || !existsSync(src) || !statSync(src).isFile()) fail(2, "usage: node mirror.mjs put <file.streamline.json | brief.md> [--mirror <dir>] [--id <id>] [--wait <s>] [--dev] [--json] [--yes]");
  const f = mirrorOrExit();
  const p = prepare(src, f.dir);
  // personal/'s streamlines and briefs, or an organization's account layout (owners and admins): never status.json,
  // settings, .streamliner/, CHANGES.md, manifest.json or a .server.json.
  if (p.kind !== "organization" && !/^personal\/([a-z0-9_]{2,32}\.streamline\.json|briefs\/[a-z0-9][a-z0-9-]{1,47}\.md)$/.test(p.rel)) p.problems.push(`${p.rel} isn't a personal streamline or brief path`);
  // The skill's check (the app's checker's rules) on the file as it will land.
  let check = { ok: true, errors: [], warnings: [] };
  if (p.kind === "streamline" && !p.problems.length) {
    const tmp = mkdtempSync(join(tmpdir(), "mirror-put-"));
    try { const t = join(tmp, `${p.id}.streamline.json`); writeFileSync(t, p.bytes); check = runCheck(t); }
    finally { rmSync(tmp, { recursive: true, force: true }); }
    for (const e of check.errors || []) p.problems.push(`${e.path ? e.path + ": " : ""}${e.message}${e.fix ? ` (fix: ${e.fix})` : ""}`);
  }
  if (p.kind === "organization" && !p.problems.length) {
    check = orgCheck(f.dir, p.folder, p.inner, p.bytes);
    for (const e of check.errors) p.problems.push(`${e.file ? e.file + " " : ""}${e.path ? e.path + ": " : ""}${e.message}${e.fix ? ` (fix: ${e.fix})` : ""}`);
  }
  const target = join(f.dir, p.rel);
  const exists = existsSync(target);
  const current = exists ? readFileSync(target) : null;
  const asJSONFile = p.value !== undefined;
  let diff = !exists ? [] : asJSONFile ? diffLines(readJSON(target), p.value) : textDiff(current.toString("utf8"), p.text);
  if (exists && asJSONFile && p.kind === "organization" && /^private\/agents\//.test(p.inner)) diff = tollfreeDiff(diff, readJSON(target), p.value);
  const same = exists && (Buffer.compare(current, p.bytes) === 0 || (asJSONFile && JSON.stringify(readJSON(target)) === JSON.stringify(p.value)));
  const running = appRunning();
  // A refused file's diff is left out: it may quote the very value refused (a key pasted into a field).
  const base = { mirror: f.dir, path: p.rel, kind: p.kind, id: p.id, edit: exists, diff: p.problems.length ? [] : diff, warnings: (check.warnings || []).map((w) => `${w.path ? w.path + ": " : ""}${w.message}`) };

  if (p.problems.length) {
    if (asJSON) console.log(JSON.stringify({ ok: false, outcome: "refused", problems: p.problems, ...base }, null, 2));
    else { console.error(`Not written: ${p.rel} would not be applied.`); for (const x of p.problems) console.error(`  - ${x}`); }
    process.exit(1);
  }
  if (same) {
    if (asJSON) console.log(JSON.stringify({ ok: true, outcome: "unchanged", ...base }, null, 2));
    else out(`${p.rel} already holds exactly this: nothing to do.`);
    return;
  }
  if (!flag("yes")) {
    const waits = (p.kind === "streamline" && !exists) || (p.kind === "organization" && !exists && /^agents\//.test(p.inner));
    if (asJSON) { console.log(JSON.stringify({ ok: true, outcome: "dry_run", waitsForTap: waits, appRunning: running, ...base }, null, 2)); return; }
    out(`DRY RUN: nothing was written.`);
    out(`${exists ? "Edit" : "New"} ${p.kind === "organization" ? `file in ${p.org.name || p.folder} (it becomes one of your Local changes)` : p.kind}: ${p.rel} in ${f.dir}`);
    for (const l of diff) out(`  ${l}`);
    for (const w of base.warnings) out(`  warning: ${w}`);
    out(waits ? "A new streamline waits for the person's tap on a card in Streamliner." : "The app applies it at once unless it widens access (a new server, fewer taps, a new image host), which waits for a tap.");
    if (!running) out("The app isn't running: it applies the file at its next launch.");
    out("Show the person this, and on their yes run the same command with --yes.");
    return;
  }

  // The write: a hidden temporary file in the same folder (the app's watcher skips dotfiles), then one rename.
  const before = { review: (() => { try { return readFileSync(join(f.dir, ".streamliner/review.json"), "utf8"); } catch { return ""; } })(),
                   lastSync: readJSON(join(f.dir, ".streamliner/mirror.json"))?.lastSync,
                   record: p.kind === "organization" ? readJSON(join(f.dir, `.streamliner/exports/${p.folder}.json`))?.files?.[p.inner] : undefined };
  mkdirSync(dirname(target), { recursive: true });
  const tmp = join(dirname(target), `.${basename(target)}.${process.pid}.tmp`);
  writeFileSync(tmp, p.bytes);
  renameSync(tmp, target);

  let v = null;
  if (!running) v = { outcome: "app_not_running", text: "The app isn't running: it applies the file at its next launch (a new streamline then waits for the person's tap)." };
  else {
    const wait = Math.max(0, Number(opt("wait") ?? 10)) * 1000, end = Date.now() + wait;
    while (!(v = verdict(f.dir, p.rel, before, false)) && Date.now() < end) await new Promise((r) => setTimeout(r, 200));
    v = v || verdict(f.dir, p.rel, before, true) || { outcome: "no_answer", text: `No answer from the app within ${wait / 1000} s. Run: node mirror.mjs status` };
  }
  const ok = v.outcome !== "not_applied";
  if (asJSON) { console.log(JSON.stringify({ ok, written: true, ...v, ...base }, null, 2)); process.exit(ok ? 0 : 1); }
  out(`Wrote ${p.rel}.`);
  switch (v.outcome) {
    case "applied": out(`Applied: ${v.text}`); break;
    case "waiting": out(`Waiting for the person's tap: approve it on the card in Streamliner (${v.name}).`); for (const r of v.reasons) out(`  - ${r}`); break;
    case "not_applied": out(`Not applied: ${v.text}`); break;
    default: out(v.text);
  }
  process.exit(ok ? 0 : 1);
}

switch (cmd) {
  case "find": cmdFind(); break;
  case "status": cmdStatus(); break;
  case "put": await cmdPut(); break;
  case "push": await cmdPush(); break;
  case "tool": await cmdTool(); break;
  case "tools": cmdTools(); break;
  default:
    console.error("usage: node mirror.mjs find | status | put <file> | push <folder> | tool <place> <tool> [args] | tools [<place>]  [--mirror <dir>] [--yes] [--json]");
    process.exit(2);
}

```
