@mushi-mushi/cli 0.40.2 → 0.40.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,4 +1,9 @@
1
1
  #!/usr/bin/env node
2
+ import {
3
+ ENTRY_CANDIDATES,
4
+ MUSHI_MARKER_START,
5
+ injectSnippet
6
+ } from "./chunk-ZDAN3RYF.js";
2
7
  import {
3
8
  CLI_KEY_LABEL,
4
9
  CLI_KEY_SCOPES,
@@ -12,6 +17,7 @@ import {
12
17
  buildMcpServerBlock,
13
18
  buildMcpServerName,
14
19
  describeUnsafeSdkKey,
20
+ editorKeyCommand,
15
21
  fetchIngestSetup,
16
22
  isMcpClient,
17
23
  printKeyExportHint,
@@ -22,7 +28,7 @@ import {
22
28
  sanitizeEndpoint,
23
29
  sanitizeProjectId,
24
30
  writeMcpServerEntry
25
- } from "./chunk-IKBJJKZX.js";
31
+ } from "./chunk-BKSEVNJH.js";
26
32
  import {
27
33
  FRAMEWORKS,
28
34
  FRAMEWORK_IDS,
@@ -53,7 +59,7 @@ import {
53
59
  registerUxCommands,
54
60
  registerWorkCommands,
55
61
  validateWorkerConfig
56
- } from "./chunk-2WDMI34E.js";
62
+ } from "./chunk-AUWZX4P3.js";
57
63
  import {
58
64
  CONFIG_PATH,
59
65
  MushiCliError,
@@ -73,6 +79,7 @@ import {
73
79
  openInBrowser,
74
80
  outputIsJson,
75
81
  pad,
82
+ peekConfig,
76
83
  printAndExit,
77
84
  printResult,
78
85
  probeEndpointHealth,
@@ -92,11 +99,11 @@ import {
92
99
  tryLoadKeyFromKeychain,
93
100
  trySaveKeyToKeychain,
94
101
  trySaveWorkerKey
95
- } from "./chunk-ASM3AHHH.js";
102
+ } from "./chunk-C6JKAD3Z.js";
96
103
  import {
97
104
  MUSHI_CLI_VERSION,
98
105
  MUSHI_MCP_PIN_SPEC
99
- } from "./chunk-VDC2434D.js";
106
+ } from "./chunk-MEQSUWI4.js";
100
107
  import {
101
108
  CLOUD_API_ENDPOINT,
102
109
  CLOUD_MCP_OAUTH_URL,
@@ -529,7 +536,8 @@ function chooseProjectNonInteractive(projects, preferredName) {
529
536
  }
530
537
  async function runLogin(opts = {}) {
531
538
  const { CLOUD_API_ENDPOINT: CLOUD_API_ENDPOINT2, resolveCloudEndpoint: resolveCloudEndpoint2 } = await import("./endpoint-MJATXOXM.js");
532
- const endpoint = opts.endpoint ? resolveCloudEndpoint2(opts.endpoint) : CLOUD_API_ENDPOINT2;
539
+ const saved = loadConfig().endpoint;
540
+ const endpoint = opts.endpoint ? resolveCloudEndpoint2(opts.endpoint) : saved ? resolveCloudEndpoint2(saved) : CLOUD_API_ENDPOINT2;
533
541
  const consoleBase = await resolveConsoleUrl();
534
542
  let apiKey = opts.apiKey;
535
543
  let projectId2 = opts.projectId;
@@ -615,7 +623,7 @@ error: Could not start login session: ${err instanceof Error ? err.message : Str
615
623
  if (process.stdin.isTTY) {
616
624
  const { createInterface } = await import("readline");
617
625
  const rl = createInterface({ input: process.stdin, output: process.stdout });
618
- const ask = (q2) => new Promise((resolve11) => rl.question(q2, (a) => resolve11(a.trim())));
626
+ const ask = (q2) => new Promise((resolve12) => rl.question(q2, (a) => resolve12(a.trim())));
619
627
  choice = await resolveProjectChoice(projectsList, ask);
620
628
  rl.close();
621
629
  } else {
@@ -975,9 +983,9 @@ async function checkCliAuthPath(config, doFetch = globalThis.fetch) {
975
983
  async function checkSdkInstall(cwd) {
976
984
  try {
977
985
  const { readFile: readFile3 } = await import("fs/promises");
978
- const { join: join14, resolve: resolve11 } = await import("path");
979
- const root = resolve11(cwd);
980
- const pkgPath = join14(root, "package.json");
986
+ const { join: join15, resolve: resolve12 } = await import("path");
987
+ const root = resolve12(cwd);
988
+ const pkgPath = join15(root, "package.json");
981
989
  const pkg = JSON.parse(await readFile3(pkgPath, "utf8"));
982
990
  const deps2 = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
983
991
  const sdks = [
@@ -1188,9 +1196,9 @@ async function checkHostAppWiring(cwd) {
1188
1196
  const checks = [];
1189
1197
  try {
1190
1198
  const { readFile: readFile3, access } = await import("fs/promises");
1191
- const { join: join14, resolve: resolve11 } = await import("path");
1192
- const root = resolve11(cwd);
1193
- const pkgPath = join14(root, "package.json");
1199
+ const { join: join15, resolve: resolve12 } = await import("path");
1200
+ const root = resolve12(cwd);
1201
+ const pkgPath = join15(root, "package.json");
1194
1202
  const pkg = JSON.parse(await readFile3(pkgPath, "utf8"));
1195
1203
  const deps2 = { ...pkg.dependencies ?? {}, ...pkg.devDependencies ?? {} };
1196
1204
  const isCapHybrid = Boolean(deps2["@capacitor/core"] && deps2["react"]);
@@ -1198,7 +1206,7 @@ async function checkHostAppWiring(cwd) {
1198
1206
  let envContent = "";
1199
1207
  for (const f of envCandidates) {
1200
1208
  try {
1201
- envContent = await readFile3(join14(root, f), "utf8");
1209
+ envContent = await readFile3(join15(root, f), "utf8");
1202
1210
  break;
1203
1211
  } catch {
1204
1212
  }
@@ -1213,9 +1221,9 @@ async function checkHostAppWiring(cwd) {
1213
1221
  detail: hasProjectId && hasApiKey ? "VITE_/MUSHI_ project id + API key found" : "Run `mushi connect --write-env` or add VITE_MUSHI_PROJECT_ID + VITE_MUSHI_API_KEY"
1214
1222
  });
1215
1223
  let mcpFound = null;
1216
- for (const rel of [".mcp.json", join14(".cursor", "mcp.json")]) {
1224
+ for (const rel of [".mcp.json", join15(".cursor", "mcp.json")]) {
1217
1225
  try {
1218
- await access(join14(root, rel));
1226
+ await access(join15(root, rel));
1219
1227
  mcpFound = rel;
1220
1228
  break;
1221
1229
  } catch {
@@ -1259,7 +1267,7 @@ var HASH_ROUTER_PATTERNS = [
1259
1267
  var HASH_TEMPLATE_PATTERN = /['"`]\/?#\//;
1260
1268
  async function scanDirForPattern(dir, patterns, maxDepth = 6, maxFiles = 2e3) {
1261
1269
  const { readdir: readdir2, readFile: readFile3 } = await import("fs/promises");
1262
- const { join: join14 } = await import("path");
1270
+ const { join: join15 } = await import("path");
1263
1271
  let count = 0;
1264
1272
  async function walk2(d, depth) {
1265
1273
  if (depth > maxDepth || count > maxFiles) return null;
@@ -1271,7 +1279,7 @@ async function scanDirForPattern(dir, patterns, maxDepth = 6, maxFiles = 2e3) {
1271
1279
  }
1272
1280
  for (const e of entries) {
1273
1281
  if (e.name.startsWith(".") || e.name === "node_modules" || e.name === "dist") continue;
1274
- const full = join14(d, e.name);
1282
+ const full = join15(d, e.name);
1275
1283
  if (e.isDirectory()) {
1276
1284
  const found = await walk2(full, depth + 1);
1277
1285
  if (found) return found;
@@ -1286,12 +1294,12 @@ async function scanDirForPattern(dir, patterns, maxDepth = 6, maxFiles = 2e3) {
1286
1294
  }
1287
1295
  return null;
1288
1296
  }
1289
- const { resolve: resolve11 } = await import("path");
1297
+ const { resolve: resolve12 } = await import("path");
1290
1298
  for (const sub of ["src", "app", "pages", "lib", "components"]) {
1291
- const found = await walk2(join14(resolve11(dir), sub), 0);
1299
+ const found = await walk2(join15(resolve12(dir), sub), 0);
1292
1300
  if (found) return found;
1293
1301
  }
1294
- return walk2(resolve11(dir), 0);
1302
+ return walk2(resolve12(dir), 0);
1295
1303
  }
1296
1304
  async function checkHashRouterCapture(cwd) {
1297
1305
  const hashFile = await scanDirForPattern(cwd, HASH_ROUTER_PATTERNS);
@@ -1324,13 +1332,13 @@ function normalizeProjectPath(path) {
1324
1332
  }
1325
1333
  async function collectMcpSources(root, home) {
1326
1334
  const { readFile: readFile3 } = await import("fs/promises");
1327
- const { join: join14 } = await import("path");
1335
+ const { join: join15 } = await import("path");
1328
1336
  const sources = [];
1329
1337
  const invalid = [];
1330
1338
  const plainFiles = [
1331
- { path: join14(root, ".mcp.json"), claudeCode: true },
1332
- { path: join14(root, ".cursor", "mcp.json"), claudeCode: false },
1333
- { path: join14(home, ".cursor", "mcp.json"), claudeCode: false }
1339
+ { path: join15(root, ".mcp.json"), claudeCode: true },
1340
+ { path: join15(root, ".cursor", "mcp.json"), claudeCode: false },
1341
+ { path: join15(home, ".cursor", "mcp.json"), claudeCode: false }
1334
1342
  ];
1335
1343
  for (const file of plainFiles) {
1336
1344
  let raw;
@@ -1347,7 +1355,7 @@ async function collectMcpSources(root, home) {
1347
1355
  invalid.push(file.path);
1348
1356
  }
1349
1357
  }
1350
- const claudeJsonPath = join14(home, ".claude.json");
1358
+ const claudeJsonPath = join15(home, ".claude.json");
1351
1359
  try {
1352
1360
  const parsed = JSON.parse(await readFile3(claudeJsonPath, "utf8"));
1353
1361
  if (isJsonObject(parsed)) {
@@ -1418,9 +1426,9 @@ function assessMushiEntry(source, name, entry, cliKeySaved) {
1418
1426
  }
1419
1427
  async function checkMcpConfig(config, cwd, doFetch = globalThis.fetch, home) {
1420
1428
  const checks = [];
1421
- const { resolve: resolve11 } = await import("path");
1429
+ const { resolve: resolve12 } = await import("path");
1422
1430
  const { homedir: homedir2 } = await import("os");
1423
- const root = resolve11(cwd);
1431
+ const root = resolve12(cwd);
1424
1432
  const { sources, invalid } = await collectMcpSources(root, home ?? homedir2());
1425
1433
  if (invalid.length > 0) {
1426
1434
  checks.push({
@@ -1544,12 +1552,12 @@ async function checkOnboardingStatus(config, _consoleBase, cwd, doFetch = global
1544
1552
  }
1545
1553
  try {
1546
1554
  const { readFile: readFile3 } = await import("fs/promises");
1547
- const { join: join14, resolve: resolve11 } = await import("path");
1548
- const root = resolve11(cwd);
1555
+ const { join: join15, resolve: resolve12 } = await import("path");
1556
+ const root = resolve12(cwd);
1549
1557
  let envContent = "";
1550
1558
  for (const f of [".env.local", ".env"]) {
1551
1559
  try {
1552
- envContent = await readFile3(join14(root, f), "utf8");
1560
+ envContent = await readFile3(join15(root, f), "utf8");
1553
1561
  break;
1554
1562
  } catch {
1555
1563
  }
@@ -1615,7 +1623,7 @@ async function checkOnboardingStatus(config, _consoleBase, cwd, doFetch = global
1615
1623
  }
1616
1624
  async function checkVersionDrift(cwd, doFetch) {
1617
1625
  const checks = [];
1618
- const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version-42UVFP3L.js");
1626
+ const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version-F3M2GCMT.js");
1619
1627
  if (MUSHI_CLI_VERSION2 === "0.0.0-dev") return checks;
1620
1628
  const parse2 = (v) => {
1621
1629
  const m = v.replace(/^[~^]/, "").match(/^(\d+)\.(\d+)\.(\d+)/);
@@ -1645,8 +1653,8 @@ async function checkVersionDrift(cwd, doFetch) {
1645
1653
  }
1646
1654
  try {
1647
1655
  const { readFile: readFile3 } = await import("fs/promises");
1648
- const { join: join14 } = await import("path");
1649
- const pkg = JSON.parse(await readFile3(join14(cwd, "package.json"), "utf8"));
1656
+ const { join: join15 } = await import("path");
1657
+ const pkg = JSON.parse(await readFile3(join15(cwd, "package.json"), "utf8"));
1650
1658
  const deps2 = { ...pkg.dependencies, ...pkg.devDependencies };
1651
1659
  const candidates = Object.entries(deps2).filter(([name, spec]) => isMushiSdkPackage(name) && !isLauncherOnly(name, spec)).filter(([, v]) => /^[~^]?\d/.test(v));
1652
1660
  const drifted = (await Promise.all(
@@ -1772,7 +1780,7 @@ async function runDoctor(config, options = {}) {
1772
1780
  }
1773
1781
  if (sdkCheck) checks.push(sdkCheck);
1774
1782
  if (sdkCheck?.ok && !sdkCheck.warn) {
1775
- const { findSdkImport } = await import("./snippet-inject-ETGBPDYB.js");
1783
+ const { findSdkImport } = await import("./snippet-inject-BQO5I2RN.js");
1776
1784
  const imported = await findSdkImport(options.cwd ?? process.cwd());
1777
1785
  checks.push(
1778
1786
  imported ? { name: "SDK init snippet wired", ok: true, detail: `Found SDK usage in ${imported.file}` } : {
@@ -1864,6 +1872,11 @@ ${failed.length} check${failed.length === 1 ? "" : "s"} failed.`);
1864
1872
 
1865
1873
  // src/init.ts
1866
1874
  var NATIVE_FRAMEWORK_IDS = /* @__PURE__ */ new Set(["expo", "react-native", "capacitor"]);
1875
+ var CLI_FRESHNESS_SOURCE = {
1876
+ packageName: "@mushi-mushi/cli",
1877
+ version: MUSHI_CLI_VERSION,
1878
+ upgradeCommand: "mushi upgrade --self"
1879
+ };
1867
1880
  var ENV_FILES = [".env.local", ".env"];
1868
1881
  function isInteractive() {
1869
1882
  return Boolean(process.stdin.isTTY && process.stdout.isTTY);
@@ -1876,10 +1889,14 @@ async function runInit(options = {}) {
1876
1889
  await runInitAudit(cwd);
1877
1890
  return;
1878
1891
  }
1892
+ if (options.dryRun) {
1893
+ await runInitDryRun(cwd, options);
1894
+ return;
1895
+ }
1879
1896
  ensureInteractiveOrBailOut(options);
1880
1897
  if (!isInteractive()) options = { ...options, yes: true };
1881
1898
  p.intro("Mushi setup");
1882
- await printFreshnessHint();
1899
+ await printFreshnessHint(options.freshness);
1883
1900
  warnIfWorkspaceRoot(cwd);
1884
1901
  const pkg = readPackageJson(cwd);
1885
1902
  maybeSuggestAudit(pkg);
@@ -1930,10 +1947,13 @@ async function runInit(options = {}) {
1930
1947
  }
1931
1948
  persistCliConfig(credentials, endpoint);
1932
1949
  emitWizardFunnelEvent(credentials, endpoint, "wizard_env_written", { framework: framework.id });
1950
+ await ensureEditorKey(credentials, options, endpoint);
1933
1951
  const enableRewards = await maybeEnableRewards(options);
1934
- await maybeInjectSnippet(cwd, framework, options);
1935
- printNextSteps(framework, consoleBase, enableRewards);
1952
+ const snippet = await maybeInjectSnippet(cwd, framework, options);
1953
+ printNextSteps(framework, consoleBase, enableRewards, snippet);
1936
1954
  await maybeSendTestReport(credentials, { ...options, endpoint, consoleBase });
1955
+ p.note(sampleBugSnippet(framework.id), "Send a sample bug from your app:");
1956
+ p.log.info("No code change: `npx mushi-mushi test` sends one from this terminal.");
1937
1957
  await maybeOfferConnect(credentials, options, consoleBase);
1938
1958
  p.outro("Setup complete.");
1939
1959
  }
@@ -2404,7 +2424,7 @@ async function installPackages(pm, packages, cwd) {
2404
2424
  function runCommand(pm, packages, cwd) {
2405
2425
  const verb = pm === "npm" ? "install" : "add";
2406
2426
  const command = process.platform === "win32" ? `${pm}.cmd` : pm;
2407
- return new Promise((resolve11, reject) => {
2427
+ return new Promise((resolve12, reject) => {
2408
2428
  const child = spawn(command, [verb, ...packages], {
2409
2429
  stdio: "inherit",
2410
2430
  shell: false,
@@ -2413,7 +2433,7 @@ function runCommand(pm, packages, cwd) {
2413
2433
  });
2414
2434
  child.on("error", reject);
2415
2435
  child.on("exit", (code) => {
2416
- if (code === 0) resolve11();
2436
+ if (code === 0) resolve12();
2417
2437
  else reject(new Error(`${pm} exited with code ${code ?? "null"}`));
2418
2438
  });
2419
2439
  });
@@ -2530,33 +2550,67 @@ function emitWizardFunnelEvent(credentials, endpoint, event, metadata = {}) {
2530
2550
  }).catch(() => {
2531
2551
  });
2532
2552
  }
2533
- async function maybeInjectSnippet(cwd, framework, options) {
2534
- if (options.yes || !process.stdin.isTTY) return;
2535
- const { ENTRY_CANDIDATES, injectSnippet, MUSHI_MARKER_START } = await import("./snippet-inject-ETGBPDYB.js");
2536
- const candidates = ENTRY_CANDIDATES[framework.id];
2537
- if (!candidates) return;
2538
- const { readFile: readFile3, writeFile: writeFile3 } = await import("fs/promises");
2539
- const nodePath2 = await import("path");
2553
+ function snippetTarget(framework) {
2554
+ const comment = framework.snippet().split("\n").map((l) => l.trim()).find((l) => l.startsWith("//"));
2555
+ const text2 = comment?.replace(/^\/\/\s*/, "").trim();
2556
+ return text2 && text2.length > 0 ? text2 : "your app entry file";
2557
+ }
2558
+ async function planSnippetInjection(cwd, framework) {
2559
+ const candidates = ENTRY_CANDIDATES[framework.id] ?? [];
2560
+ const { readFile: readFile3 } = await import("fs/promises");
2540
2561
  for (const rel of candidates) {
2541
- const abs = nodePath2.join(cwd, rel);
2562
+ const abs = join2(cwd, rel);
2542
2563
  let source;
2543
2564
  try {
2544
2565
  source = await readFile3(abs, "utf8");
2545
2566
  } catch {
2546
2567
  continue;
2547
2568
  }
2548
- const alreadyInjected = source.includes(MUSHI_MARKER_START);
2549
- const confirmed = await p.confirm({
2550
- message: alreadyInjected ? `Refresh the Mushi init block in ${rel}?` : `Add the Mushi init snippet to ${rel}? (wrapped in markers; re-runs update in place)`
2551
- });
2552
- if (p.isCancel(confirmed) || !confirmed) return;
2553
- await writeFile3(abs, injectSnippet(source, framework.snippet()), "utf8");
2554
- p.log.success(`${alreadyInjected ? "Updated" : "Added"} Mushi init block in ${rel}`);
2555
- return;
2569
+ const next = injectSnippet(source, framework.snippet());
2570
+ return {
2571
+ kind: "inject",
2572
+ file: rel,
2573
+ abs,
2574
+ next,
2575
+ alreadyInjected: source.includes(MUSHI_MARKER_START),
2576
+ unchanged: next === source
2577
+ };
2556
2578
  }
2579
+ return { kind: "manual", target: snippetTarget(framework) };
2557
2580
  }
2558
- function printNextSteps(framework, consoleBase, enableRewards = false) {
2559
- p.note(framework.snippet(), "Add this to your app:");
2581
+ async function applySnippetPlan(plan, opts) {
2582
+ if (plan.kind === "manual") return plan;
2583
+ if (plan.unchanged) {
2584
+ p.log.info(`The Mushi Mushi init block in ${plan.file} is already up to date.`);
2585
+ return { kind: "written", file: plan.file };
2586
+ }
2587
+ if (!opts.yes) {
2588
+ const ok = await opts.confirm(
2589
+ plan.alreadyInjected ? `Refresh the Mushi Mushi init block in ${plan.file}?` : `Add the Mushi Mushi init snippet to ${plan.file}? (wrapped in markers; re-runs update in place)`
2590
+ );
2591
+ if (!ok) return { kind: "manual", target: plan.file };
2592
+ }
2593
+ const { writeFile: writeFile3 } = await import("fs/promises");
2594
+ await writeFile3(plan.abs, plan.next, "utf8");
2595
+ p.log.success(`${plan.alreadyInjected ? "Updated" : "Added"} the Mushi Mushi init block in ${plan.file}`);
2596
+ return { kind: "written", file: plan.file };
2597
+ }
2598
+ async function maybeInjectSnippet(cwd, framework, options) {
2599
+ const plan = await planSnippetInjection(cwd, framework);
2600
+ const outcome = await applySnippetPlan(plan, {
2601
+ yes: Boolean(options.yes) || !isInteractive(),
2602
+ confirm: async (message) => {
2603
+ const answer = await p.confirm({ message });
2604
+ return !p.isCancel(answer) && Boolean(answer);
2605
+ }
2606
+ });
2607
+ if (outcome.kind === "manual" && (options.yes || !isInteractive())) {
2608
+ p.log.info(`One edit left: paste the "Add this to your app" snippet below (${outcome.target}).`);
2609
+ }
2610
+ return outcome;
2611
+ }
2612
+ function printNextSteps(framework, consoleBase, enableRewards = false, snippet = { kind: "manual", target: snippetTarget(framework) }) {
2613
+ p.note(framework.snippet(), snippet.kind === "written" ? `Added to ${snippet.file}:` : "Add this to your app:");
2560
2614
  if (enableRewards) {
2561
2615
  const badgeSnippet = framework.id === "react" ? `// Add to your user menu or profile UI:
2562
2616
  import { MushiRewardsBadge } from 'mushi-mushi/react';
@@ -2571,7 +2625,7 @@ import { MushiRewardsBadge } from 'mushi-mushi/react';
2571
2625
  }
2572
2626
  p.note(
2573
2627
  [
2574
- " [ ] 1. Paste the init snippet above into your app entry file",
2628
+ snippet.kind === "written" ? ` [x] 1. Init snippet added to ${snippet.file}` : ` [ ] 1. Paste the init snippet above (${snippet.target})`,
2575
2629
  " [ ] 2. Start your dev server",
2576
2630
  " [ ] 3. Wire your editor: npx mushi-mushi setup --ide cursor (or --ide claude)",
2577
2631
  ` [ ] 4. Open the Test it tab to send a test report: ${consoleUrl(consoleBase, "/onboarding?tab=verify")}`
@@ -2588,7 +2642,7 @@ async function maybeOfferConnect(credentials, options, _consoleBase) {
2588
2642
  if (p.isCancel(answer) || !answer) return;
2589
2643
  const endpoint = resolveCloudEndpoint(options.endpoint);
2590
2644
  try {
2591
- const { runConnect: runConnect2 } = await import("./connect-H52HI4HK.js");
2645
+ const { runConnect: runConnect2 } = await import("./connect-NQHKFL2H.js");
2592
2646
  const saved = loadConfig();
2593
2647
  const result = await runConnect2(
2594
2648
  {
@@ -2692,12 +2746,185 @@ async function maybeSendTestReport(credentials, options) {
2692
2746
  clearTimeout(timer);
2693
2747
  }
2694
2748
  }
2695
- async function printFreshnessHint() {
2696
- const result = await checkFreshness("mushi-mushi", MUSHI_CLI_VERSION);
2697
- if (!result || !result.isOutdated) return;
2698
- p.log.info(
2699
- `A newer version of mushi-mushi is available: ${result.current} \u2192 ${result.latest}. Run \`npx mushi-mushi@latest\` to get the freshest wizard.`
2749
+ async function freshnessHint(source, check = checkFreshness) {
2750
+ if (!source.version || source.version === "0.0.0-dev") return null;
2751
+ const result = await check(source.packageName, source.version);
2752
+ if (!result || !result.isOutdated) return null;
2753
+ return `A newer version of ${source.packageName} is available: ${result.current} \u2192 ${result.latest}. Run \`${source.upgradeCommand}\` to get the newest wizard.`;
2754
+ }
2755
+ async function printFreshnessHint(source = CLI_FRESHNESS_SOURCE) {
2756
+ const hint = await freshnessHint(source);
2757
+ if (hint) p.log.info(hint);
2758
+ }
2759
+ function needsEditorKey(saved, credentials) {
2760
+ if (credentials.cliKey) return false;
2761
+ return !saved.apiKey || saved.apiKey === credentials.sdkKey;
2762
+ }
2763
+ async function ensureEditorKey(credentials, options, endpoint) {
2764
+ const saved = loadConfig();
2765
+ if (!needsEditorKey(saved, credentials)) return;
2766
+ const command = editorKeyCommand(credentials.projectId);
2767
+ const why = "Your editor's MCP server needs a key that can read reports; the app's key can only send them.";
2768
+ if (options.yes || !isInteractive()) {
2769
+ p.log.info(`${why} To get one, run: ${command}`);
2770
+ return;
2771
+ }
2772
+ const answer = await p.confirm({
2773
+ message: `${why} Approve one more browser sign-in to make it now?`,
2774
+ initialValue: true
2775
+ });
2776
+ if (p.isCancel(answer) || !answer) {
2777
+ p.log.info(`Later: ${command}`);
2778
+ return;
2779
+ }
2780
+ const key = await mintEditorKey(endpoint, credentials.projectId);
2781
+ if (!key) {
2782
+ p.log.warn(`No editor key was made. Run it yourself: ${command}`);
2783
+ return;
2784
+ }
2785
+ saveConfig({ ...loadConfig(), apiKey: key });
2786
+ trySaveKeyToKeychain(key, resolveProfileName());
2787
+ credentials.cliKey = key;
2788
+ p.log.success("Editor key saved to the CLI config (report:write + mcp:read). Restart your editor to use it.");
2789
+ }
2790
+ async function mintEditorKey(endpoint, projectId2) {
2791
+ let session;
2792
+ try {
2793
+ session = await startDeviceAuth(endpoint, ensureClientId());
2794
+ } catch (err) {
2795
+ p.log.warn(err instanceof Error ? err.message : String(err));
2796
+ return null;
2797
+ }
2798
+ try {
2799
+ await openInBrowser(session.verification_uri);
2800
+ } catch {
2801
+ }
2802
+ printAuthBanner(session.user_code, session.verification_uri);
2803
+ const spin = p.spinner();
2804
+ spin.start("Waiting for you to approve in the browser\u2026");
2805
+ try {
2806
+ const cliToken = await waitForCliToken(endpoint, session);
2807
+ const key = await mintProjectKey(endpoint, cliToken, projectId2, {
2808
+ scopes: CLI_KEY_SCOPES,
2809
+ label: CLI_KEY_LABEL
2810
+ });
2811
+ spin.stop("Approved.");
2812
+ return key;
2813
+ } catch (err) {
2814
+ spin.stop("Browser sign-in didn't complete.");
2815
+ p.log.warn(err instanceof Error ? err.message : String(err));
2816
+ return null;
2817
+ }
2818
+ }
2819
+ var WEB_SAMPLE_BUG = `// In any click handler (every web adapter shares this one SDK instance):
2820
+ import { Mushi } from 'mushi-mushi'
2821
+
2822
+ Mushi.getInstance()?.captureException(new Error('Sample bug from Mushi Mushi setup'))`;
2823
+ var NODE_SAMPLE_BUG = `// Anywhere in your server code, e.g. a test route:
2824
+ import { mushi } from './instrument'
2825
+
2826
+ await mushi.captureException(new Error('Sample bug from Mushi Mushi setup'))`;
2827
+ var NATIVE_SAMPLE_BUG = `// In any component inside <MushiProvider>, e.g. a button's onPress:
2828
+ import { useMushi } from '@mushi-mushi/react-native'
2829
+
2830
+ const mushi = useMushi()
2831
+ mushi.submitReport({ description: 'Sample bug from Mushi Mushi setup', category: 'bug' })`;
2832
+ var CAPACITOR_SAMPLE_BUG = `// Anywhere after Mushi.configure(...):
2833
+ import { Mushi } from '@mushi-mushi/capacitor'
2834
+
2835
+ await Mushi.report({ description: 'Sample bug from Mushi Mushi setup', category: 'bug' })`;
2836
+ var SAMPLE_BUG_SNIPPETS = {
2837
+ next: WEB_SAMPLE_BUG,
2838
+ react: WEB_SAMPLE_BUG,
2839
+ cra: WEB_SAMPLE_BUG,
2840
+ remix: WEB_SAMPLE_BUG,
2841
+ astro: WEB_SAMPLE_BUG,
2842
+ solid: WEB_SAMPLE_BUG,
2843
+ vue: WEB_SAMPLE_BUG,
2844
+ nuxt: WEB_SAMPLE_BUG,
2845
+ svelte: WEB_SAMPLE_BUG,
2846
+ sveltekit: WEB_SAMPLE_BUG,
2847
+ angular: WEB_SAMPLE_BUG,
2848
+ vanilla: WEB_SAMPLE_BUG,
2849
+ expo: NATIVE_SAMPLE_BUG,
2850
+ "react-native": NATIVE_SAMPLE_BUG,
2851
+ capacitor: CAPACITOR_SAMPLE_BUG,
2852
+ express: NODE_SAMPLE_BUG,
2853
+ fastify: NODE_SAMPLE_BUG,
2854
+ hono: NODE_SAMPLE_BUG
2855
+ };
2856
+ function sampleBugSnippet(framework) {
2857
+ return SAMPLE_BUG_SNIPPETS[framework];
2858
+ }
2859
+ function planInitDryRun(input) {
2860
+ const { framework, options } = input;
2861
+ const lines = [];
2862
+ if (!input.hasPackageJson) {
2863
+ lines.push("No package.json here: a real run stops (or asks first). Run from your app folder, or pass --cwd.");
2864
+ }
2865
+ lines.push(
2866
+ `Framework: ${framework.label}${input.frameworkSource === "flag" ? " (from --framework)" : " (detected)"}`
2700
2867
  );
2868
+ if (options.projectId && options.apiKey) {
2869
+ lines.push("Credentials: use --project-id and --api-key (checked first: the key must be ingest-only).");
2870
+ } else if (input.saved.projectId && input.saved.hasKey) {
2871
+ lines.push(
2872
+ `Credentials: reuse your saved sign-in (project ${input.saved.projectId.slice(0, 8)}\u2026), or open a browser sign-in if those keys no longer work.`
2873
+ );
2874
+ } else {
2875
+ lines.push(
2876
+ "Credentials: open a browser sign-in. You approve once; it picks or creates the project and makes two keys: an ingest-only key for the app and a read key for your editor's MCP server."
2877
+ );
2878
+ }
2879
+ const packages = framework.needsWebPackage ? [framework.packageName, "mushi-mushi"] : [framework.packageName];
2880
+ const command = installCommand(input.pm, packages);
2881
+ lines.push(options.skipInstall ? `Install: skipped (--skip-install); you run \`${command}\`` : `Install: ${command}`);
2882
+ const envFile = ENV_FILES.find((f) => existsSync2(join2(input.cwd, f))) ?? ENV_FILES[0];
2883
+ const names = envVarsToWrite("<key>", "<id>", framework, input.endpoint).split("\n").map((l) => l.split("=")[0]).filter(Boolean);
2884
+ let existingEnv = "";
2885
+ try {
2886
+ existingEnv = readFileSync2(join2(input.cwd, envFile), "utf-8");
2887
+ } catch {
2888
+ existingEnv = "";
2889
+ }
2890
+ lines.push(
2891
+ existingEnv.includes("MUSHI_PROJECT_ID") ? `Env: update the MUSHI_* lines in ${envFile} (${names.join(", ")})${options.yes ? "" : ", after asking"}` : `Env: add ${names.join(", ")} to ${envFile}`
2892
+ );
2893
+ lines.push("CLI config: save the keys to your private CLI config, outside the repo.");
2894
+ if (input.snippet.kind === "inject") {
2895
+ lines.push(
2896
+ input.snippet.unchanged ? `Snippet: ${input.snippet.file} already has the init block; no change.` : `Snippet: ${input.snippet.alreadyInjected ? "refresh" : "add"} the init block in ${input.snippet.file}` + (options.yes ? "" : ", after asking")
2897
+ );
2898
+ } else {
2899
+ lines.push(`Snippet: not edited automatically; you paste it in (${input.snippet.target}).`);
2900
+ }
2901
+ if (options.sendTestReport !== false) lines.push("Test report: send one test report to check the pipeline.");
2902
+ lines.push("Sample bug: print the one call that sends a bug from your own app.");
2903
+ return lines;
2904
+ }
2905
+ async function runInitDryRun(cwd, options) {
2906
+ p.intro("Mushi Mushi setup (dry run)");
2907
+ await printFreshnessHint(options.freshness);
2908
+ warnIfWorkspaceRoot(cwd);
2909
+ const pkg = readPackageJson(cwd);
2910
+ const framework = options.framework ? FRAMEWORKS[options.framework] : detectFramework(cwd, pkg);
2911
+ const config = peekConfig();
2912
+ const endpoint = resolveCloudEndpoint(
2913
+ firstEndpoint(options.endpoint, process.env.MUSHI_API_ENDPOINT, config.endpoint)
2914
+ );
2915
+ const lines = planInitDryRun({
2916
+ cwd,
2917
+ framework,
2918
+ frameworkSource: options.framework ? "flag" : "detected",
2919
+ pm: detectPackageManager(cwd),
2920
+ hasPackageJson: Boolean(pkg),
2921
+ endpoint,
2922
+ options,
2923
+ saved: { projectId: config.projectId, hasKey: Boolean(config.apiKey) },
2924
+ snippet: await planSnippetInjection(cwd, framework)
2925
+ });
2926
+ p.note(lines.map((l) => `\u2022 ${l}`).join("\n"), "A real run would:");
2927
+ p.outro("Dry run: nothing was changed. Run again without --dry-run to set up.");
2701
2928
  }
2702
2929
  function warnIfWorkspaceRoot(cwd) {
2703
2930
  let hint;
@@ -2886,7 +3113,7 @@ function runMigrate(opts = {}) {
2886
3113
 
2887
3114
  // src/commands/account.ts
2888
3115
  function registerAccountCommands(program2) {
2889
- program2.command("init").description("Set up the Mushi Mushi SDK in this project (auto-detects framework)").option("--project-id <id>", "Skip the prompt \u2014 pass UUID from the Projects page").option("--api-key <key>", "Skip the prompt \u2014 pass the API key (CI only)").option("--framework <id>", "Force a framework (next, react, vue, nuxt, svelte, sveltekit, angular, expo, react-native, capacitor, vanilla)").option("--skip-install", "Print the install command instead of running it").option("-y, --yes", "Accept detected framework without prompting").option("--cwd <path>", "Run the wizard in a different directory").option("--endpoint <url>", "Override the Mushi API endpoint (self-hosted)").option("--skip-test-report", 'Skip the end-of-wizard "send a test report" prompt').option("--audit", "Audit an existing install (doctor checks) instead of running the wizard").action(async (opts) => {
3116
+ program2.command("init").description("Set up the Mushi Mushi SDK in this project (auto-detects framework)").option("--project-id <id>", "Skip the prompt \u2014 pass UUID from the Projects page").option("--api-key <key>", "Skip the prompt \u2014 pass the API key (CI only)").option("--framework <id>", "Force a framework (next, react, vue, nuxt, svelte, sveltekit, angular, expo, react-native, capacitor, vanilla)").option("--skip-install", "Print the install command instead of running it").option("-y, --yes", "Accept detected framework without prompting").option("--cwd <path>", "Run the wizard in a different directory").option("--endpoint <url>", "Override the Mushi API endpoint (self-hosted)").option("--skip-test-report", 'Skip the end-of-wizard "send a test report" prompt').option("--audit", "Audit an existing install (doctor checks) instead of running the wizard").option("--dry-run", "Print what the wizard would install and write, then stop (changes nothing)").action(async (opts) => {
2890
3117
  await runInit({
2891
3118
  projectId: opts.projectId,
2892
3119
  apiKey: opts.apiKey,
@@ -2896,7 +3123,8 @@ function registerAccountCommands(program2) {
2896
3123
  cwd: opts.cwd,
2897
3124
  endpoint: opts.endpoint,
2898
3125
  sendTestReport: opts.skipTestReport ? false : void 0,
2899
- audit: opts.audit
3126
+ audit: opts.audit,
3127
+ dryRun: opts.dryRun
2900
3128
  });
2901
3129
  });
2902
3130
  program2.command("migrate").description("Suggest the most relevant Mushi Mushi migration guide based on your package.json").option("--cwd <path>", "Run from a different directory").option("--json", "Machine-readable JSON output").action((opts) => {
@@ -3627,11 +3855,11 @@ async function findMapFiles(dir) {
3627
3855
  return results;
3628
3856
  }
3629
3857
  function fileHash(path) {
3630
- return new Promise((resolve11, reject) => {
3858
+ return new Promise((resolve12, reject) => {
3631
3859
  const hash = createHash("sha256");
3632
3860
  const stream = createReadStream(path);
3633
3861
  stream.on("data", (chunk) => hash.update(chunk));
3634
- stream.on("end", () => resolve11(hash.digest("hex")));
3862
+ stream.on("end", () => resolve12(hash.digest("hex")));
3635
3863
  stream.on("error", reject);
3636
3864
  });
3637
3865
  }
@@ -4018,7 +4246,7 @@ error: Could not start browser sign-in: ${err instanceof Error ? err.message : S
4018
4246
  const projectsList = await listProjects(endpoint, cliToken);
4019
4247
  const { createInterface } = await import("readline");
4020
4248
  const rl = createInterface({ input: process.stdin, output: process.stdout });
4021
- const ask = (q2) => new Promise((resolve11) => rl.question(q2, (a) => resolve11(a.trim())));
4249
+ const ask = (q2) => new Promise((resolve12) => rl.question(q2, (a) => resolve12(a.trim())));
4022
4250
  let chosen;
4023
4251
  let projectId2;
4024
4252
  let projectName;
@@ -4447,11 +4675,16 @@ If you are not signed in yet, setup runs browser sign-in first, then writes the
4447
4675
  const { createInterface } = await import("readline");
4448
4676
  const rl = createInterface({ input: process.stdin, output: process.stdout });
4449
4677
  const answer = await new Promise(
4450
- (resolve11) => rl.question(" Upgrade this key now via browser sign-in? [Y/n] ", (a) => resolve11(a.trim().toLowerCase()))
4678
+ (resolve12) => rl.question(" Upgrade this key now via browser sign-in? [Y/n] ", (a) => resolve12(a.trim().toLowerCase()))
4451
4679
  );
4452
4680
  rl.close();
4453
4681
  if (answer === "" || answer === "y" || answer === "yes") {
4454
- await runLogin({ endpoint: opts.endpoint, upgradeScope: true, suppressPostLoginBanner: true });
4682
+ await runLogin({
4683
+ endpoint: opts.endpoint,
4684
+ projectId: config.projectId,
4685
+ upgradeScope: true,
4686
+ suppressPostLoginBanner: true
4687
+ });
4455
4688
  const fresh = loadConfig();
4456
4689
  if (fresh.apiKey && target.format === "mcp-json" && !allProjectsList) {
4457
4690
  await writeEntry(
@@ -4487,8 +4720,12 @@ If you are not signed in yet, setup runs browser sign-in first, then writes the
4487
4720
  }
4488
4721
  }
4489
4722
  if (!upgraded && !canPrompt) {
4490
- console.log(" To upgrade this key, run:\n");
4491
- console.log(" mushi login --upgrade-scope\n");
4723
+ console.log(" To get a key that can read reports, run (approve in the browser):\n");
4724
+ console.log(` ${editorKeyCommand(config.projectId)}
4725
+ `);
4726
+ console.log(
4727
+ inlineKey ? " Then re-run this setup command to write the new key, and restart " + ideLabel + ".\n" : " Then restart " + ideLabel + ".\n"
4728
+ );
4492
4729
  }
4493
4730
  } else {
4494
4731
  console.log(`\u26A0 Key probe returned HTTP ${probeRes.status} \u2014 check your credentials.`);
@@ -6991,239 +7228,600 @@ Examples:
6991
7228
 
6992
7229
  // src/commands/selfhost.ts
6993
7230
  import { spawnSync } from "child_process";
6994
- import { randomBytes } from "crypto";
6995
- function hasSupabaseCli() {
7231
+ import { createHmac, randomBytes } from "crypto";
7232
+ import { existsSync as existsSync3, mkdtempSync, readFileSync as readFileSync3, rmSync, writeFileSync as writeFileSync2 } from "fs";
7233
+ import { tmpdir } from "os";
7234
+ import { dirname as dirname2, join as join5, resolve as resolve3 } from "path";
7235
+ import { pathToFileURL } from "url";
7236
+ function supabaseCliVersion() {
6996
7237
  try {
6997
7238
  const r = spawnSync("supabase", ["--version"], { encoding: "utf8", timeout: 5e3 });
6998
- return r.status === 0;
7239
+ return r.status === 0 ? (r.stdout ?? "").trim() : null;
6999
7240
  } catch {
7000
- return false;
7241
+ return null;
7001
7242
  }
7002
7243
  }
7244
+ function supabaseCliMajor(version) {
7245
+ const m = /(\d+)\.\d+\.\d+/.exec(version ?? "");
7246
+ return m ? Number(m[1]) : void 0;
7247
+ }
7248
+ function linkedTargetFlag(cliMajor) {
7249
+ return cliMajor !== void 0 && cliMajor < 3 ? "--linked" : "--remote";
7250
+ }
7003
7251
  function selfhostStepCommand(step) {
7004
- return `supabase ${step.args.join(" ")}${step.mayFail ? " || true" : ""}`;
7252
+ return `supabase ${step.args.join(" ")}`;
7005
7253
  }
7006
- function runSupabase(args, opts) {
7007
- process.stdout.write(` \u203A ${opts.label} \u2026 `);
7008
- const r = spawnSync("supabase", args, {
7009
- cwd: opts.cwd,
7010
- encoding: "utf8",
7011
- timeout: 3e5,
7012
- stdio: ["ignore", "pipe", "pipe"]
7013
- });
7014
- if (r.error || r.status !== 0) {
7015
- process.stdout.write("\u2717\n");
7016
- const stderr = (r.stderr ?? "").trim();
7017
- return {
7018
- ok: false,
7019
- stdout: r.stdout ?? "",
7020
- stderr: stderr || r.error?.message || `exited with ${r.status ?? r.signal}`
7021
- };
7254
+ function redact2(text2, secrets) {
7255
+ let out = text2;
7256
+ for (const s of secrets) if (s) out = out.split(s).join("<redacted>");
7257
+ return out;
7258
+ }
7259
+ function runSupabase(step, opts) {
7260
+ process.stdout.write(` \u203A ${step.label} \u2026 `);
7261
+ for (const f of step.files ?? []) writeFileSync2(f.path, f.content, { mode: 384 });
7262
+ try {
7263
+ const r = spawnSync("supabase", step.args, {
7264
+ cwd: opts.cwd,
7265
+ encoding: "utf8",
7266
+ timeout: 9e5,
7267
+ stdio: ["ignore", "pipe", "pipe"],
7268
+ // The operator already confirmed (prompt or --yes): CLI 3.x reads consent
7269
+ // for hosted changes from SUPABASE_YES in the process environment.
7270
+ env: { ...process.env, SUPABASE_YES: "1" }
7271
+ });
7272
+ if (r.error || r.status !== 0) {
7273
+ process.stdout.write("\u2717\n");
7274
+ const stderr = redact2((r.stderr ?? "").trim() || (r.stdout ?? "").trim(), opts.secrets);
7275
+ return { ok: false, stderr: stderr || r.error?.message || `exited with ${r.status ?? r.signal}` };
7276
+ }
7277
+ process.stdout.write("\u2713\n");
7278
+ return { ok: true, stderr: "" };
7279
+ } finally {
7280
+ for (const f of step.files ?? []) rmSync(f.path, { force: true });
7022
7281
  }
7023
- process.stdout.write("\u2713\n");
7024
- return { ok: true, stdout: r.stdout, stderr: "" };
7025
7282
  }
7026
- var REQUIRED_FUNCTIONS = [
7027
- "api",
7028
- "fast-filter",
7029
- "classify-report",
7030
- "mcp",
7031
- "fix-worker",
7032
- "webhooks-github-indexer"
7033
- ];
7034
- function buildSelfhostSteps(opts, printOnly, internalToken) {
7283
+ var KEY_RE = /^[A-Za-z0-9_-]+$/;
7284
+ var SECRET_RE = /^[A-Za-z0-9_-]{32,}$/;
7285
+ var PLAIN_URL_RE = /^[A-Za-z0-9:/._~-]+$/;
7286
+ function isPlainHttpUrl(value) {
7287
+ try {
7288
+ const u = new URL(value);
7289
+ return (u.protocol === "https:" || u.protocol === "http:") && PLAIN_URL_RE.test(value);
7290
+ } catch {
7291
+ return false;
7292
+ }
7293
+ }
7294
+ function llmProviderOfKey(key) {
7295
+ return key.startsWith("sk-ant-") ? "anthropic" : "openai";
7296
+ }
7297
+ function buildRuntimeConfigSql(supabaseUrl, internalToken) {
7298
+ const q2 = (s) => `'${s.replace(/'/g, "''")}'`;
7299
+ return [
7300
+ "-- Written by `mushi selfhost up`: point pg_cron jobs at this project, not Mushi Mushi Cloud.",
7301
+ "insert into public.mushi_runtime_config (key, value) values",
7302
+ ` ('supabase_url', ${q2(supabaseUrl)}),`,
7303
+ ` ('service_role_key', ${q2(internalToken)}),`,
7304
+ ` ('internal_caller_token', ${q2(internalToken)})`,
7305
+ "on conflict (key) do update set value = excluded.value, updated_at = now();",
7306
+ "",
7307
+ "-- Private, service-role only (same row as 20260416000000_phase0_initial_schema.sql).",
7308
+ "insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)",
7309
+ "values ('screenshots', 'screenshots', false, 5242880, array['image/jpeg', 'image/png', 'image/webp'])",
7310
+ "on conflict (id) do nothing;",
7311
+ "",
7312
+ SELFHOST_PLAN_SQL
7313
+ ].join("\n");
7314
+ }
7315
+ var SELFHOST_PLAN_SQL = [
7316
+ "-- Self-hosted: no billing, so no Mushi Mushi Cloud plan limits on any plan.",
7317
+ "update public.pricing_plans set",
7318
+ " included_diagnoses_per_month = null,",
7319
+ " max_projects = null,",
7320
+ " seat_limit = null,",
7321
+ " retention_days = greatest(coalesce(retention_days, 0), 3650),",
7322
+ ` feature_flags = coalesce(feature_flags, '{}'::jsonb) || '{"byok": true, "sso": true, "plugins": true, "intelligence_reports": true, "audit_log": true, "self_hosted": true, "teams": true}'::jsonb`,
7323
+ "where true;",
7324
+ ""
7325
+ ].join("\n");
7326
+ var CLOUD_PROJECT_REF = "dxptnwrhwsqckaftyymj";
7327
+ var SELF_HOST_DOCS = "https://kensaur.us/mushi-mushi/docs/self-hosting";
7328
+ function buildSelfhostSteps(input, printOnly, internalToken, tmpDir) {
7035
7329
  const steps = [];
7036
- if (opts.projectRef && !/^[a-z0-9-]+$/i.test(opts.projectRef)) {
7037
- return { ok: false, error: `--project-ref must be alphanumeric (got: ${opts.projectRef}).` };
7330
+ const target = linkedTargetFlag(input.cliMajor);
7331
+ if (input.projectRef && !/^[a-z0-9-]+$/i.test(input.projectRef)) {
7332
+ return { ok: false, error: `--project-ref must be alphanumeric (got: ${input.projectRef}).` };
7038
7333
  }
7039
- if (opts.projectRef) {
7040
- steps.push({
7041
- label: `link to Supabase project ${opts.projectRef}`,
7042
- args: ["link", "--project-ref", opts.projectRef],
7043
- critical: true
7044
- });
7334
+ if (input.projectRef === CLOUD_PROJECT_REF || input.supabaseUrl.includes(CLOUD_PROJECT_REF)) {
7335
+ return {
7336
+ ok: false,
7337
+ error: "That is the Mushi Mushi Cloud project. selfhost up deploys to your own Supabase project."
7338
+ };
7045
7339
  }
7046
- steps.push({
7047
- label: "apply database migrations",
7048
- args: ["db", "push"],
7049
- critical: true
7050
- });
7051
- if (opts.anthropicKey && printOnly) {
7052
- steps.push({
7053
- label: "set ANTHROPIC_API_KEY secret",
7054
- args: ["secrets", "set", "ANTHROPIC_API_KEY=sk-ant-..."]
7055
- });
7056
- } else if (opts.anthropicKey) {
7057
- if (!/^[A-Za-z0-9_-]+$/.test(opts.anthropicKey)) {
7340
+ if (!printOnly && !isPlainHttpUrl(input.supabaseUrl)) {
7341
+ return { ok: false, error: `--supabase-url must be a plain http(s) URL (got: ${input.supabaseUrl}).` };
7342
+ }
7343
+ for (const [flag, key] of [
7344
+ ["--anthropic-key", input.anthropicKey],
7345
+ ["--openai-key", input.openaiKey]
7346
+ ]) {
7347
+ if (key && !KEY_RE.test(key)) {
7058
7348
  return {
7059
7349
  ok: false,
7060
- error: "--anthropic-key does not look like an API key (letters, digits, - and _ only).\n Set it manually instead: supabase secrets set ANTHROPIC_API_KEY=<your key>"
7350
+ error: `${flag} does not look like an API key (letters, digits, - and _ only).`
7061
7351
  };
7062
7352
  }
7063
- steps.push({
7064
- label: "set ANTHROPIC_API_KEY secret",
7065
- args: ["secrets", "set", `ANTHROPIC_API_KEY=${opts.anthropicKey}`]
7066
- });
7067
- } else if (printOnly) {
7068
- steps.push({
7069
- label: "set ANTHROPIC_API_KEY secret",
7070
- args: ["secrets", "set", "ANTHROPIC_API_KEY=sk-ant-..."]
7071
- });
7072
7353
  }
7073
- if (opts.adminBaseUrl) {
7074
- let adminUrlOk = false;
7075
- try {
7076
- const u = new URL(opts.adminBaseUrl);
7077
- adminUrlOk = (u.protocol === "https:" || u.protocol === "http:") && /^[A-Za-z0-9:/._~-]+$/.test(opts.adminBaseUrl);
7078
- } catch {
7079
- adminUrlOk = false;
7080
- }
7081
- if (!adminUrlOk) {
7082
- return { ok: false, error: `--admin-base-url must be a plain http(s) URL (got: ${opts.adminBaseUrl}).` };
7083
- }
7354
+ if (input.consoleUrl && !isPlainHttpUrl(input.consoleUrl)) {
7355
+ return { ok: false, error: `--console-url must be a plain http(s) URL (got: ${input.consoleUrl}).` };
7356
+ }
7357
+ if (!printOnly && !SECRET_RE.test(internalToken)) {
7358
+ return {
7359
+ ok: false,
7360
+ error: "MUSHI_INTERNAL_CALLER_SECRET must be at least 32 characters of letters, digits, - and _."
7361
+ };
7362
+ }
7363
+ if (input.projectRef) {
7084
7364
  steps.push({
7085
- label: "set ADMIN_BASE_URL secret",
7086
- args: ["secrets", "set", `ADMIN_BASE_URL=${opts.adminBaseUrl}`]
7365
+ label: `link to Supabase project ${input.projectRef}`,
7366
+ args: ["link", "--project-ref", input.projectRef],
7367
+ critical: true
7087
7368
  });
7088
7369
  }
7089
- steps.push({
7090
- label: "set MUSHI_INTERNAL_CALLER_SECRET (recovery cron auth)",
7091
- args: [
7092
- "secrets",
7093
- "set",
7094
- `MUSHI_INTERNAL_CALLER_SECRET=${printOnly ? "<openssl rand -hex 32>" : internalToken}`
7095
- ]
7096
- });
7097
- if (!opts.skipDeploy) {
7098
- for (const fn of REQUIRED_FUNCTIONS) {
7099
- steps.push({
7100
- label: `deploy edge function: ${fn}`,
7101
- args: ["functions", "deploy", fn, "--no-verify-jwt"]
7102
- });
7103
- }
7370
+ steps.push({ label: "apply database migrations", args: ["db", "push", target], critical: true });
7371
+ const token = printOnly ? "<YOUR_INTERNAL_CALLER_SECRET>" : internalToken;
7372
+ const secretLines = [`MUSHI_INTERNAL_CALLER_SECRET=${token}`, "MUSHI_INSTANCE_MODE=self-hosted"];
7373
+ if (input.anthropicKey) secretLines.push(`ANTHROPIC_API_KEY=${printOnly ? "sk-ant-..." : input.anthropicKey}`);
7374
+ if (input.openaiKey) secretLines.push(`OPENAI_API_KEY=${printOnly ? "sk-..." : input.openaiKey}`);
7375
+ if (input.consoleUrl) {
7376
+ secretLines.push(`ADMIN_BASE_URL=${input.consoleUrl}`);
7377
+ secretLines.push(`MUSHI_ADMIN_ORIGIN_ALLOWLIST=${new URL(input.consoleUrl).origin}`);
7104
7378
  }
7379
+ const secretsFile = join5(tmpDir, "mushi-secrets.env");
7105
7380
  steps.push({
7106
- label: "create screenshots storage bucket",
7107
- args: ["storage", "create", "screenshots", "--public"],
7108
- mayFail: true
7381
+ label: `set function secrets (${secretLines.map((l) => l.split("=")[0]).join(", ")})`,
7382
+ args: ["secrets", "set", "--env-file", secretsFile],
7383
+ critical: true,
7384
+ files: [{ path: secretsFile, content: `${secretLines.join("\n")}
7385
+ ` }]
7109
7386
  });
7387
+ const sqlFile = join5(tmpDir, "mushi-runtime-config.sql");
7388
+ steps.push({
7389
+ label: "point cron jobs at this project (mushi_runtime_config) + screenshots bucket",
7390
+ args: ["db", "query", target, "--file", sqlFile],
7391
+ critical: true,
7392
+ files: [{ path: sqlFile, content: buildRuntimeConfigSql(input.supabaseUrl, token) }]
7393
+ });
7394
+ if (!input.skipDeploy) {
7395
+ steps.push({ label: "deploy every edge function", args: ["functions", "deploy"], stampDeployInfo: true });
7396
+ }
7110
7397
  return { ok: true, steps };
7111
7398
  }
7399
+ function selfhostConfigPatch(existing, endpoint, consoleUrl2) {
7400
+ if (existing.apiKey && existing.endpoint !== endpoint) return null;
7401
+ return consoleUrl2 ? { endpoint, consoleUrl: consoleUrl2 } : { endpoint };
7402
+ }
7403
+ var DEPLOY_INFO_PATH = join5("packages", "server", "supabase", "functions", "_shared", "deploy-info.ts");
7404
+ async function loadDeployStamper(root) {
7405
+ const script = join5(root, "scripts", "deploy-edge-function.mjs");
7406
+ if (!existsSync3(script)) return null;
7407
+ try {
7408
+ const mod = await import(pathToFileURL(script).href);
7409
+ return typeof mod.deployInfoSource === "function" && typeof mod.resolveDeploySha === "function" ? mod : null;
7410
+ } catch {
7411
+ return null;
7412
+ }
7413
+ }
7414
+ function stampDeployInfo(root, stamper, now = /* @__PURE__ */ new Date()) {
7415
+ const file = join5(root, DEPLOY_INFO_PATH);
7416
+ let original;
7417
+ try {
7418
+ original = readFileSync3(file, "utf8");
7419
+ } catch {
7420
+ return null;
7421
+ }
7422
+ const sha = stamper.resolveDeploySha(root);
7423
+ writeFileSync2(file, stamper.deployInfoSource(sha, now.toISOString()));
7424
+ let restored = false;
7425
+ return {
7426
+ sha,
7427
+ restore: () => {
7428
+ if (restored) return;
7429
+ restored = true;
7430
+ writeFileSync2(file, original);
7431
+ }
7432
+ };
7433
+ }
7434
+ function runStamped(step, root, stamper, run) {
7435
+ const stamp = step.stampDeployInfo && stamper ? stampDeployInfo(root, stamper) : null;
7436
+ if (!stamp) return run();
7437
+ const onSignal = () => {
7438
+ stamp.restore();
7439
+ process.exit(130);
7440
+ };
7441
+ process.once("SIGINT", onSignal);
7442
+ process.once("exit", stamp.restore);
7443
+ try {
7444
+ return run();
7445
+ } finally {
7446
+ stamp.restore();
7447
+ process.removeListener("SIGINT", onSignal);
7448
+ process.removeListener("exit", stamp.restore);
7449
+ }
7450
+ }
7451
+ function readLinkedRef(supabaseDir) {
7452
+ try {
7453
+ const ref = readFileSync3(join5(supabaseDir, ".temp", "project-ref"), "utf8").trim();
7454
+ return /^[a-z0-9-]+$/i.test(ref) ? ref : void 0;
7455
+ } catch {
7456
+ return void 0;
7457
+ }
7458
+ }
7459
+ function isInteractive2() {
7460
+ return !!(process.stdin.isTTY && process.stdout.isTTY);
7461
+ }
7462
+ async function resolveLlmKeys(opts, printOnly) {
7463
+ const fromEnv = (name) => {
7464
+ const v = process.env[name]?.trim();
7465
+ if (v && !printOnly) console.log(` Using ${name} from your shell.`);
7466
+ return v || void 0;
7467
+ };
7468
+ const anthropicKey = opts.anthropicKey || fromEnv("ANTHROPIC_API_KEY");
7469
+ const openaiKey = opts.openaiKey || fromEnv("OPENAI_API_KEY");
7470
+ if (anthropicKey || openaiKey || printOnly || !isInteractive2()) return { anthropicKey, openaiKey };
7471
+ const p5 = await import("@clack/prompts");
7472
+ const pasted = await p5.password({
7473
+ message: "Paste an Anthropic (sk-ant-\u2026) or OpenAI (sk-\u2026) API key, or press Enter to skip"
7474
+ });
7475
+ if (p5.isCancel(pasted)) process.exit(1);
7476
+ const key = (pasted ?? "").trim();
7477
+ if (!key) return {};
7478
+ return llmProviderOfKey(key) === "anthropic" ? { anthropicKey: key } : { openaiKey: key };
7479
+ }
7480
+ function printNoLlmNote() {
7481
+ console.log(" No LLM key set. Reports are still ingested, stored and shown in the console,");
7482
+ console.log(" and get a rule-based category and severity. Without a key there is no");
7483
+ console.log(" plain-English diagnosis, no fix drafts and no duplicate detection.");
7484
+ console.log(" Add one later: supabase secrets set ANTHROPIC_API_KEY=\u2026 (or OPENAI_API_KEY=\u2026),");
7485
+ console.log(" or per app in the console under Settings \u2192 AI keys.");
7486
+ }
7112
7487
  async function runSelfhostUp(opts) {
7113
- const supabaseDir = opts.cwd ? `${opts.cwd}/packages/server/supabase` : "packages/server/supabase";
7114
- const printOnly = !!(opts.printCommands || !hasSupabaseCli());
7115
- if (printOnly) {
7116
- console.log("");
7117
- console.log("supabase CLI not found (or --print-commands was passed).");
7118
- console.log("Run the following commands manually:\n");
7119
- } else {
7120
- console.log("");
7121
- console.log("mushi selfhost up \u2014 deploying self-hosted Mushi Mushi\n");
7488
+ const root = resolve3(opts.cwd ?? ".");
7489
+ const serverDir = join5(root, "packages", "server");
7490
+ const supabaseDir = join5(serverDir, "supabase");
7491
+ const cliVersion = supabaseCliVersion();
7492
+ const printOnly = !!(opts.printCommands || !cliVersion);
7493
+ const consoleUrl2 = opts.consoleUrl || opts.adminBaseUrl;
7494
+ if (!printOnly && !existsSync3(join5(supabaseDir, "config.toml"))) {
7495
+ process.stderr.write(
7496
+ `\u2717 ${supabaseDir} has no config.toml. Run this from a clone of the mushi-mushi repo, or pass --cwd <repo root>.
7497
+ `
7498
+ );
7499
+ process.exit(1);
7122
7500
  }
7123
- const built = buildSelfhostSteps(opts, printOnly, randomBytes(32).toString("hex"));
7124
- if (!built.ok) {
7125
- process.stderr.write(`\u2717 ${built.error}
7126
- `);
7501
+ const linkedRef = readLinkedRef(supabaseDir);
7502
+ const ref = opts.projectRef || linkedRef;
7503
+ if (!printOnly && ref === CLOUD_PROJECT_REF) {
7504
+ process.stderr.write(
7505
+ "\u2717 This checkout is linked to the Mushi Mushi Cloud project. Pass --project-ref <your ref> to link your own.\n"
7506
+ );
7127
7507
  process.exit(1);
7128
7508
  }
7129
- let aborted = false;
7130
- for (const step of built.steps) {
7131
- if (printOnly) {
7132
- console.log(`# ${step.label}`);
7133
- console.log(` $ ${selfhostStepCommand(step)}`);
7134
- console.log("");
7135
- } else {
7136
- const result = runSupabase(step.args, { label: step.label, cwd: supabaseDir });
7137
- if (!result.ok && step.mayFail) {
7138
- process.stdout.write(` (fine if it already exists) ${result.stderr.split("\n")[0]}
7139
- `);
7140
- } else if (!result.ok) {
7141
- if (result.stderr) {
7142
- process.stderr.write(` ${result.stderr.split("\n")[0]}
7509
+ const projectRef = opts.projectRef ?? (printOnly && !linkedRef ? "your-project-ref" : void 0);
7510
+ const supabaseUrl = opts.supabaseUrl?.replace(/\/+$/, "") || (ref ? `https://${ref}.supabase.co` : void 0);
7511
+ if (!supabaseUrl && !printOnly) {
7512
+ process.stderr.write(
7513
+ "\u2717 Unknown Supabase project. Pass --project-ref <ref> (or --supabase-url <url> for a custom domain).\n"
7514
+ );
7515
+ process.exit(1);
7516
+ }
7517
+ const resolvedUrl = supabaseUrl ?? "https://<your-ref>.supabase.co";
7518
+ let endpoint = (opts.endpoint || `${resolvedUrl}/functions/v1/api`).replace(/\/+$/, "");
7519
+ if (!printOnly) {
7520
+ try {
7521
+ endpoint = assertEndpoint(endpoint);
7522
+ } catch (err) {
7523
+ process.stderr.write(`\u2717 ${err instanceof Error ? err.message : String(err)}
7143
7524
  `);
7144
- }
7145
- if (step.critical) {
7146
- process.stderr.write(
7147
- `
7148
- \u2717 Critical step failed \u2014 resolve the error above and re-run.
7149
- `
7150
- );
7151
- process.exit(1);
7152
- }
7153
- aborted = true;
7154
- }
7525
+ process.exit(1);
7155
7526
  }
7156
7527
  }
7157
- const endpoint = opts.endpoint || loadConfig().endpoint;
7158
- if (endpoint) {
7528
+ console.log("");
7529
+ if (printOnly) {
7530
+ console.log(cliVersion ? "--print-commands: nothing is run." : "supabase CLI not found.");
7531
+ console.log(`Run these from ${serverDir} (Supabase CLI 3.x; for 2.x use --linked instead of --remote):
7532
+ `);
7533
+ } else {
7534
+ console.log(`mushi selfhost up \u2014 deploying Mushi Mushi to ${resolvedUrl}
7535
+ `);
7536
+ }
7537
+ const llm = await resolveLlmKeys(opts, printOnly);
7538
+ const envToken = process.env["MUSHI_INTERNAL_CALLER_SECRET"]?.trim();
7539
+ const internalToken = envToken || randomBytes(32).toString("hex");
7540
+ const tmpDir = printOnly ? "." : mkdtempSync(join5(tmpdir(), "mushi-selfhost-"));
7541
+ try {
7542
+ const built = buildSelfhostSteps(
7543
+ {
7544
+ projectRef,
7545
+ supabaseUrl: resolvedUrl,
7546
+ ...llm,
7547
+ consoleUrl: consoleUrl2,
7548
+ skipDeploy: opts.skipDeploy,
7549
+ cliMajor: supabaseCliMajor(cliVersion)
7550
+ },
7551
+ printOnly,
7552
+ internalToken,
7553
+ printOnly ? "." : tmpDir
7554
+ );
7555
+ if (!built.ok) {
7556
+ process.stderr.write(`\u2717 ${built.error}
7557
+ `);
7558
+ process.exit(1);
7559
+ }
7159
7560
  if (printOnly) {
7160
- console.log("# seed mushi_runtime_config via API");
7161
- console.log(
7162
- `# mushi login --endpoint ${endpoint} --api-key <key> --project-id <pid>`
7163
- );
7164
- console.log(
7165
- `# then: supabase sql --file <(echo "INSERT INTO public.mushi_runtime_config(key,value)`
7166
- );
7167
- console.log(
7168
- `# VALUES ('internal_caller_token','<token>') ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value,updated_at=now()")`
7169
- );
7561
+ console.log("# generate one secret and use it in BOTH files below");
7562
+ console.log(" $ openssl rand -hex 32");
7170
7563
  console.log("");
7171
- } else if (!aborted) {
7172
- process.stdout.write(` \u203A POST /v1/admin/bootstrap \u2026 `);
7173
- try {
7174
- const config = loadConfig();
7175
- if (config.apiKey) {
7176
- await apiCall("/admin/bootstrap", config, { method: "POST" });
7177
- process.stdout.write("\u2713\n");
7178
- } else {
7179
- process.stdout.write("skipped (not logged in)\n");
7564
+ for (const step of built.steps) {
7565
+ console.log(`# ${step.label}`);
7566
+ for (const f of step.files ?? []) {
7567
+ console.log(` $ cat > ${f.path} <<'EOF'`);
7568
+ for (const line of f.content.trimEnd().split("\n")) console.log(` ${line}`);
7569
+ console.log(" EOF");
7180
7570
  }
7181
- } catch {
7182
- process.stdout.write("warn (non-critical)\n");
7571
+ const cleanup = (step.files ?? []).map((f) => f.path).join(" ");
7572
+ console.log(` $ ${selfhostStepCommand(step)}${cleanup ? ` && rm ${cleanup}` : ""}`);
7573
+ console.log("");
7574
+ }
7575
+ if (!llm.anthropicKey && !llm.openaiKey) {
7576
+ console.log("# LLM key (optional): add ANTHROPIC_API_KEY=\u2026 or OPENAI_API_KEY=\u2026 to mushi-secrets.env");
7577
+ console.log("");
7578
+ }
7579
+ if (!opts.skipDeploy) {
7580
+ console.log("# A plain `supabase functions deploy` leaves _shared/deploy-info.ts unstamped, so");
7581
+ console.log('# /health reports version "dev". `mushi selfhost up` stamps the commit for you.');
7582
+ console.log("");
7583
+ }
7584
+ console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
7585
+ console.log("Then point the CLI at it and check it:");
7586
+ console.log(` mushi config endpoint ${endpoint}`);
7587
+ if (consoleUrl2) console.log(` mushi config consoleUrl ${consoleUrl2}`);
7588
+ console.log(` curl ${endpoint}/health`);
7589
+ console.log(` mushi login --endpoint ${endpoint}`);
7590
+ console.log(" mushi selfhost doctor");
7591
+ return;
7592
+ }
7593
+ if (!opts.yes) {
7594
+ if (!isInteractive2()) {
7595
+ process.stderr.write(
7596
+ "\u2717 selfhost up changes your Supabase project (migrations, secrets, functions). Pass --yes to confirm in a non-interactive shell.\n"
7597
+ );
7598
+ process.exit(1);
7183
7599
  }
7600
+ const p5 = await import("@clack/prompts");
7601
+ const ok = await p5.confirm({
7602
+ message: `Push migrations, set secrets${opts.skipDeploy ? "" : " and deploy every edge function"} on ${resolvedUrl}?`
7603
+ });
7604
+ if (p5.isCancel(ok) || !ok) process.exit(1);
7184
7605
  }
7185
- }
7186
- if (printOnly) {
7187
- console.log("\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500\u2500");
7188
- console.log("Once commands above are done, run:");
7189
- console.log(" mushi selfhost doctor --endpoint <your-endpoint>");
7190
- return;
7191
- }
7192
- if (!aborted && endpoint) {
7606
+ if (envToken) console.log(" Using MUSHI_INTERNAL_CALLER_SECRET from your shell.");
7607
+ if (!llm.anthropicKey && !llm.openaiKey) printNoLlmNote();
7193
7608
  console.log("");
7194
- console.log("Running proof step\u2026");
7609
+ const secrets = [internalToken, llm.anthropicKey ?? "", llm.openaiKey ?? ""];
7610
+ const stamper = built.steps.some((s) => s.stampDeployInfo) ? await loadDeployStamper(root) : null;
7611
+ if (!stamper && !opts.skipDeploy) {
7612
+ console.log(' This clone cannot stamp the deploy (no scripts/deploy-edge-function.mjs helpers): /health will report "dev".');
7613
+ }
7614
+ let failed = false;
7615
+ for (const step of built.steps) {
7616
+ const result = runStamped(step, root, stamper, () => runSupabase(step, { cwd: serverDir, secrets }));
7617
+ if (result.ok) continue;
7618
+ process.stderr.write(` ${result.stderr.split("\n").slice(0, 3).join("\n ")}
7619
+ `);
7620
+ if (step.critical) {
7621
+ process.stderr.write("\n\u2717 Critical step failed: resolve the error above and re-run `mushi selfhost up`.\n");
7622
+ process.exit(1);
7623
+ }
7624
+ failed = true;
7625
+ }
7626
+ const config = loadConfig();
7627
+ const patch = selfhostConfigPatch(config, endpoint, consoleUrl2);
7628
+ if (patch) {
7629
+ saveConfig({ ...config, ...patch });
7630
+ console.log(` \u203A saved endpoint${patch.consoleUrl ? " + consoleUrl" : ""} to ${CONFIG_PATH} \u2713`);
7631
+ } else {
7632
+ console.log(` \u203A ${CONFIG_PATH} holds a key for ${config.endpoint}; left unchanged. Switch with:`);
7633
+ console.log(` mushi config endpoint ${endpoint}`);
7634
+ if (consoleUrl2) console.log(` mushi config consoleUrl ${consoleUrl2}`);
7635
+ }
7636
+ console.log("");
7637
+ console.log("Proof step\u2026");
7195
7638
  const probe = await probeEndpointHealth(endpoint).catch(() => null);
7196
7639
  if (!probe?.ok) {
7197
- console.log(" WARN /health did not return 200 \u2014 check function logs.");
7640
+ console.log(` WARN ${endpoint}/health did not return 200: check the function logs.`);
7198
7641
  } else {
7199
7642
  console.log(` OK /health ${probe.status} ${probe.latencyMs}ms`);
7200
7643
  }
7201
- }
7202
- console.log("");
7203
- if (aborted) {
7204
- console.log(
7205
- "Some non-critical steps failed \u2014 check stderr above, then re-run or fix manually."
7206
- );
7207
- console.log("Run `mushi selfhost doctor` once the endpoint is reachable.");
7208
- process.exit(2);
7209
- } else {
7644
+ const health = await serverHealthCheck(endpoint, fetch);
7645
+ for (const line of formatSelfhostCheck(health)) console.log(` ${line}`);
7646
+ console.log("");
7647
+ if (failed) {
7648
+ console.log("Some steps failed (see above). Fix them and re-run, or deploy the rest by hand.");
7649
+ process.exit(2);
7650
+ }
7210
7651
  console.log("\u2713 selfhost up complete.");
7211
7652
  console.log("");
7212
7653
  console.log("Next steps:");
7213
- console.log(
7214
- " 1. mushi login --endpoint https://<ref>.supabase.co/functions/v1/api"
7215
- );
7216
- console.log(" 2. mushi selfhost doctor");
7217
- console.log(" 3. mushi init (in your app repo)");
7654
+ if (!consoleUrl2) {
7655
+ console.log(` 0. Serve the admin console (${SELF_HOST_DOCS}/admin-spa), then:`);
7656
+ console.log(" mushi config consoleUrl <console url>");
7657
+ console.log(" Without it, `mushi login` opens the Mushi Mushi Cloud console.");
7658
+ }
7659
+ console.log(" 1. Sign up in your console (the first account owns the instance).");
7660
+ console.log(` 2. mushi login --endpoint ${endpoint}`);
7661
+ console.log(" 3. mushi selfhost doctor");
7662
+ console.log(" 4. mushi init (in your app repo)");
7663
+ } finally {
7664
+ if (!printOnly) rmSync(tmpDir, { recursive: true, force: true });
7665
+ }
7666
+ }
7667
+ var b64url = (buf) => Buffer.from(buf).toString("base64url");
7668
+ function mintSupabaseJwt(role, jwtSecret, nowSec) {
7669
+ const header = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
7670
+ const payload = b64url(
7671
+ JSON.stringify({ role, iss: "supabase", iat: nowSec, exp: nowSec + 5 * 365 * 24 * 3600 })
7672
+ );
7673
+ const sig = createHmac("sha256", jwtSecret).update(`${header}.${payload}`).digest("base64url");
7674
+ return `${header}.${payload}.${sig}`;
7675
+ }
7676
+ function buildComposeEnv(rand, nowSec, publicUrl = "http://localhost") {
7677
+ const jwtSecret = rand(32);
7678
+ return [
7679
+ "# Generated by `mushi selfhost secrets`. Keep this file private; never commit it.",
7680
+ `# Public address of the stack (Caddy serves the console and the API here).`,
7681
+ `MUSHI_PUBLIC_URL=${publicUrl}`,
7682
+ `MUSHI_SITE_ADDRESS=${publicUrl}`,
7683
+ "",
7684
+ "# Required: generated, do not edit by hand (the JWTs below are signed with JWT_SECRET).",
7685
+ `POSTGRES_PASSWORD=${rand(24)}`,
7686
+ `JWT_SECRET=${jwtSecret}`,
7687
+ `SUPABASE_ANON_KEY=${mintSupabaseJwt("anon", jwtSecret, nowSec)}`,
7688
+ `SUPABASE_SERVICE_ROLE_KEY=${mintSupabaseJwt("service_role", jwtSecret, nowSec)}`,
7689
+ `MUSHI_INTERNAL_CALLER_SECRET=${rand(32)}`,
7690
+ "",
7691
+ "# Optional: one LLM key turns on the plain-English diagnosis and fix drafts.",
7692
+ "# Either provider works. Leave both empty for rule-based triage only.",
7693
+ "ANTHROPIC_API_KEY=",
7694
+ "OPENAI_API_KEY=",
7695
+ ""
7696
+ ].join("\n");
7697
+ }
7698
+ function runSelfhostSecrets(opts) {
7699
+ const out = resolve3(opts.out);
7700
+ if (opts.publicUrl && !isPlainHttpUrl(opts.publicUrl)) {
7701
+ process.stderr.write(`\u2717 --public-url must be a plain http(s) URL (got: ${opts.publicUrl}).
7702
+ `);
7703
+ process.exit(1);
7704
+ }
7705
+ if (!existsSync3(dirname2(out))) {
7706
+ process.stderr.write(`\u2717 ${dirname2(out)} does not exist.
7707
+ `);
7708
+ process.exit(1);
7709
+ }
7710
+ const body = buildComposeEnv(
7711
+ (n) => randomBytes(n).toString("hex"),
7712
+ Math.floor(Date.now() / 1e3),
7713
+ opts.publicUrl?.replace(/\/+$/, "")
7714
+ );
7715
+ try {
7716
+ writeFileSync2(out, body, { mode: 384, flag: opts.force ? "w" : "wx" });
7717
+ } catch (err) {
7718
+ if (err.code === "EEXIST") {
7719
+ process.stderr.write(`\u2717 ${out} already exists. Pass --force to replace it (this rotates every secret).
7720
+ `);
7721
+ process.exit(1);
7722
+ }
7723
+ throw err;
7724
+ }
7725
+ console.log(`\u2713 Wrote ${out} (mode 600).`);
7726
+ console.log(" Generated: POSTGRES_PASSWORD, JWT_SECRET, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY,");
7727
+ console.log(" MUSHI_INTERNAL_CALLER_SECRET");
7728
+ console.log(" Optional: ANTHROPIC_API_KEY or OPENAI_API_KEY (edit the file)");
7729
+ }
7730
+ function selfhostDoctorExitCode(checks) {
7731
+ if (checks.some((c) => c.status === "fail")) return 1;
7732
+ if (checks.some((c) => c.status === "warn")) return 2;
7733
+ return 0;
7734
+ }
7735
+ function isCloudEndpoint(endpoint) {
7736
+ return endpoint.includes(CLOUD_PROJECT_REF) || /^https:\/\/kensaur\.us\//.test(endpoint);
7737
+ }
7738
+ var HOSTED_CONSOLE = "https://kensaur.us/mushi-mushi/admin";
7739
+ async function consoleCheck(consoleUrl2, endpoint, doFetch) {
7740
+ if (isCloudEndpoint(endpoint)) return null;
7741
+ const base = { name: "console_reachable", label: "Console answers" };
7742
+ const url = consoleUrl2?.trim().replace(/\/+$/, "");
7743
+ if (!url) {
7744
+ return {
7745
+ ...base,
7746
+ status: "info",
7747
+ summary: "No console address saved, so `mushi login` opens Mushi Mushi Cloud.",
7748
+ hint: "mushi config consoleUrl <your console url>"
7749
+ };
7750
+ }
7751
+ if (url.startsWith(HOSTED_CONSOLE)) {
7752
+ return {
7753
+ ...base,
7754
+ status: "warn",
7755
+ summary: "The saved console is Mushi Mushi Cloud\u2019s, but the API is yours: `mushi login` would sign you in on Cloud.",
7756
+ hint: "mushi config consoleUrl <your console url>"
7757
+ };
7758
+ }
7759
+ try {
7760
+ const res = await doFetch(url, { signal: AbortSignal.timeout(8e3), redirect: "follow" });
7761
+ const type = res.headers.get("content-type") ?? "";
7762
+ if (res.ok && type.includes("text/html")) return { ...base, status: "pass", summary: `${url} answers (HTTP ${res.status}).` };
7763
+ return {
7764
+ ...base,
7765
+ status: "warn",
7766
+ summary: `${url} returned HTTP ${res.status}${type ? ` (${type.split(";")[0]})` : ""}, not the console page.`,
7767
+ hint: `Serve apps/admin/dist there with an index.html fallback (${SELF_HOST_DOCS}/admin-spa).`
7768
+ };
7769
+ } catch (err) {
7770
+ return {
7771
+ ...base,
7772
+ status: "warn",
7773
+ summary: `${url} did not answer: ${err instanceof Error ? err.message : String(err)}.`,
7774
+ hint: `Check the console is served at that address (${SELF_HOST_DOCS}/admin-spa).`
7775
+ };
7776
+ }
7777
+ }
7778
+ async function serverHealthCheck(endpoint, doFetch) {
7779
+ const base = { name: "server_deploy", label: "Server deploy" };
7780
+ try {
7781
+ const res = await doFetch(`${endpoint.replace(/\/+$/, "")}/health`, { signal: AbortSignal.timeout(8e3) });
7782
+ if (!res.ok) {
7783
+ return { ...base, status: "fail", summary: `/health returned HTTP ${res.status}.`, hint: "Check the `api` function deployed and its logs." };
7784
+ }
7785
+ const body = await res.json().catch(() => ({}));
7786
+ const version = typeof body.version === "string" ? body.version : null;
7787
+ if (body.mode === "hosted" && !isCloudEndpoint(endpoint)) {
7788
+ return {
7789
+ ...base,
7790
+ status: "warn",
7791
+ summary: "The server says it is Mushi Mushi Cloud, so the console labels this instance wrongly.",
7792
+ hint: "supabase secrets set MUSHI_INSTANCE_MODE=self-hosted (selfhost up sets it)."
7793
+ };
7794
+ }
7795
+ if (!version || version === "dev" || version === "unknown") {
7796
+ return {
7797
+ ...base,
7798
+ status: "info",
7799
+ summary: 'The deploy is not stamped with a commit (/health says "dev"), so you cannot tell which code runs.',
7800
+ hint: "Supabase: re-run `npx mushi-mushi selfhost up`; it stamps the commit. Compose builds are unstamped; compare the image with `git log -1`."
7801
+ };
7802
+ }
7803
+ return { ...base, status: "pass", summary: `Running commit ${version.slice(0, 7)}.` };
7804
+ } catch (err) {
7805
+ return {
7806
+ ...base,
7807
+ status: "fail",
7808
+ summary: `/health did not answer: ${err instanceof Error ? err.message : String(err)}.`,
7809
+ hint: `Check that ${endpoint} is deployed and reachable.`
7810
+ };
7218
7811
  }
7219
7812
  }
7813
+ var TAG = { pass: "OK ", info: "INFO", warn: "WARN", fail: "FAIL" };
7814
+ function formatSelfhostCheck(check) {
7815
+ const title = `${check.label ?? check.name}${check.appName ? ` (${check.appName})` : ""}`;
7816
+ const lines = [`${TAG[check.status]} ${title}: ${check.summary}`];
7817
+ if (check.hint && check.status !== "pass") lines.push(` \u2192 ${check.hint}`);
7818
+ return lines;
7819
+ }
7220
7820
  async function runSelfhostDoctor(opts) {
7221
7821
  const config = loadConfig();
7222
- const endpoint = opts.endpoint || config.endpoint;
7822
+ const endpoint = (opts.endpoint || config.endpoint)?.replace(/\/+$/, "");
7223
7823
  if (!endpoint) {
7224
- process.stderr.write(
7225
- "error: endpoint required \u2014 pass --endpoint or run `mushi login` first.\n"
7226
- );
7824
+ process.stderr.write("error: endpoint required \u2014 pass --endpoint or run `mushi login` first.\n");
7227
7825
  process.exit(1);
7228
7826
  }
7229
7827
  let serverChecks = [];
@@ -7239,9 +7837,10 @@ async function runSelfhostDoctor(opts) {
7239
7837
  serverChecks = [
7240
7838
  {
7241
7839
  name: "server_doctor",
7840
+ label: "Server doctor",
7242
7841
  status: "fail",
7243
7842
  summary: `/v1/admin/doctor returned HTTP ${res.status}`,
7244
- hint: "401 \u2192 check API key scope (needs mcp:read or admin); 403 \u2192 key not owner of this project"
7843
+ hint: res.status === 401 || res.status === 403 ? `Sign the CLI in to this server: mushi login --endpoint ${endpoint} (the key needs mcp:read).` : "Check the `api` function logs."
7245
7844
  }
7246
7845
  ];
7247
7846
  }
@@ -7249,78 +7848,68 @@ async function runSelfhostDoctor(opts) {
7249
7848
  serverChecks = [
7250
7849
  {
7251
7850
  name: "server_doctor",
7851
+ label: "Server doctor",
7252
7852
  status: "fail",
7253
7853
  summary: `unreachable: ${err instanceof Error ? err.message : String(err)}`,
7254
7854
  hint: `Check that ${endpoint} is deployed and reachable.`
7255
7855
  }
7256
7856
  ];
7257
7857
  }
7858
+ const [health, consoleLine] = await Promise.all([
7859
+ serverHealthCheck(endpoint, fetch),
7860
+ consoleCheck(opts.consoleUrl || config.consoleUrl, endpoint, fetch)
7861
+ ]);
7862
+ const checks = [health, ...consoleLine ? [consoleLine] : [], ...serverChecks];
7863
+ const code = selfhostDoctorExitCode(checks);
7258
7864
  if (opts.json) {
7259
- const overallStatus = serverChecks.some((c) => c.status === "fail") ? "fail" : serverChecks.some((c) => c.status === "warn") ? "warn" : "pass";
7260
- console.log(JSON.stringify({ status: overallStatus, checks: serverChecks }, null, 2));
7865
+ console.log(JSON.stringify({ status: code === 1 ? "fail" : code === 2 ? "warn" : "pass", checks }, null, 2));
7261
7866
  } else {
7262
- for (const check of serverChecks) {
7263
- const tag = check.status === "pass" ? "OK " : check.status === "warn" ? "WARN" : "FAIL";
7264
- console.log(`${tag} ${check.name} ${check.summary}`);
7265
- if (check.hint && check.status !== "pass") {
7266
- console.log(` \u2192 Fix: ${check.hint}`);
7267
- }
7867
+ const rank = { fail: 0, warn: 1, info: 2, pass: 3 };
7868
+ for (const check of [...checks].sort((a, b) => rank[a.status] - rank[b.status])) {
7869
+ for (const line of formatSelfhostCheck(check)) console.log(line);
7268
7870
  }
7269
7871
  }
7270
- const hasFailure = serverChecks.some((c) => c.status === "fail");
7271
- const hasWarn = serverChecks.some((c) => c.status === "warn");
7272
- if (hasFailure) process.exit(1);
7273
- if (hasWarn) process.exit(2);
7872
+ if (code !== 0) process.exit(code);
7274
7873
  }
7275
7874
  function registerSelfhostCommands(program2) {
7276
7875
  const selfhost = program2.command("selfhost").description("Self-hosted deployment tools");
7277
- selfhost.command("up").description(
7278
- "Bootstrap a self-hosted Mushi Mushi deployment on a Supabase project"
7279
- ).option(
7280
- "--project-ref <ref>",
7281
- "Supabase project ref (runs `supabase link` first)"
7282
- ).option(
7283
- "--anthropic-key <key>",
7284
- "Anthropic API key to set as a Supabase function secret"
7285
- ).option(
7286
- "--admin-base-url <url>",
7287
- "Base URL of your deployed admin console (e.g. https://your-domain.example.com/admin)"
7288
- ).option(
7289
- "--endpoint <url>",
7290
- `Mushi API endpoint to use for the proof step (default: from ${CONFIG_PATH})`
7291
- ).option(
7292
- "--skip-deploy",
7293
- "Skip function deploys (run db push + secrets only)"
7294
- ).option(
7295
- "--print-commands",
7296
- "Print the supabase CLI commands instead of running them (non-interactive / CI)"
7297
- ).option("--cwd <path>", "Root of the mushi-mushi repo checkout").addHelpText(
7876
+ selfhost.command("up").description("Deploy Mushi Mushi to your own Supabase project (run from a clone of the repo)").option("--project-ref <ref>", "Supabase project ref (runs `supabase link` first)").option("--supabase-url <url>", "Project URL when it is not https://<ref>.supabase.co (custom domain)").option("--anthropic-key <key>", "Anthropic API key (default: $ANTHROPIC_API_KEY, else asked)").option("--openai-key <key>", "OpenAI API key (default: $OPENAI_API_KEY); either provider works").option("--console-url <url>", "Where your admin console is served (sets ADMIN_BASE_URL and the CLI consoleUrl)").option("--admin-base-url <url>", "Deprecated alias of --console-url").option("--endpoint <url>", "API endpoint (default: <supabase url>/functions/v1/api)").option("--skip-deploy", "Skip function deploys (migrations, secrets and runtime config only)").option("--print-commands", "Print the supabase CLI commands instead of running them").option("--yes", "Confirm the changes to the Supabase project without a prompt (CI)").option("--cwd <path>", "Root of the mushi-mushi repo checkout (default: current directory)").addHelpText(
7298
7877
  "after",
7299
7878
  `
7300
7879
  Examples:
7301
- mushi selfhost up --project-ref abcxyzabcxyz
7302
- mushi selfhost up --print-commands # copy-paste mode for CI
7303
- mushi selfhost up --skip-deploy # re-run secrets/migrations only
7304
-
7305
- Requires the Supabase CLI (https://supabase.com/docs/guides/cli).
7306
- If not installed, pass --print-commands to get the exact commands.
7880
+ mushi selfhost up --project-ref abcdefghijklmnopqrst
7881
+ mushi selfhost up --project-ref abcdefghijklmnopqrst --console-url https://mushi.example.com
7882
+ mushi selfhost up --print-commands # copy-paste mode
7883
+ mushi selfhost up --skip-deploy --yes # re-run migrations, secrets and runtime config
7884
+
7885
+ Requires the Supabase CLI (https://supabase.com/docs/guides/cli), logged in
7886
+ (\`supabase login\` or SUPABASE_ACCESS_TOKEN). Set SUPABASE_DB_PASSWORD if your
7887
+ CLI asks for the database password. MUSHI_INTERNAL_CALLER_SECRET in the shell
7888
+ is reused instead of generating a new one.`
7889
+ ).action(async (opts) => {
7890
+ await runSelfhostUp(opts);
7891
+ });
7892
+ selfhost.command("secrets").description("Write a .env with fresh secrets for deploy/docker-compose.yml").option("--out <path>", "File to write", "deploy/.env").option("--public-url <url>", "Public address of the stack (default: http://localhost)").option("--force", "Replace an existing file (rotates every secret)").addHelpText(
7893
+ "after",
7894
+ `
7895
+ Generates POSTGRES_PASSWORD, JWT_SECRET, MUSHI_INTERNAL_CALLER_SECRET, and the
7896
+ anon / service_role JWTs signed with JWT_SECRET. Values are never printed.
7307
7897
 
7308
- After "up" completes:
7309
- mushi selfhost doctor --endpoint https://<ref>.supabase.co/functions/v1/api`
7310
- ).action(
7311
- async (opts) => {
7312
- await runSelfhostUp(opts);
7313
- }
7314
- );
7898
+ Examples:
7899
+ npx mushi-mushi selfhost secrets
7900
+ npx mushi-mushi selfhost secrets --public-url https://mushi.example.com`
7901
+ ).action((opts) => {
7902
+ runSelfhostSecrets(opts);
7903
+ });
7315
7904
  selfhost.command("doctor").description(
7316
7905
  "Check the health of a self-hosted deployment (calls GET /v1/admin/doctor)"
7317
7906
  ).option(
7318
7907
  "--endpoint <url>",
7319
7908
  `Mushi API endpoint (default: from ${CONFIG_PATH})`
7320
- ).option("--json", "Machine-readable JSON output").addHelpText(
7909
+ ).option("--console-url <url>", "Console address to check (default: consoleUrl from the CLI config)").option("--json", "Machine-readable JSON output").addHelpText(
7321
7910
  "after",
7322
7911
  `
7323
- Exit codes: 0 all pass \xB7 2 warnings only \xB7 1 any hard failure
7912
+ Exit codes: 0 healthy (INFO lines are optional extras) \xB7 2 warnings only \xB7 1 any hard failure
7324
7913
 
7325
7914
  Examples:
7326
7915
  mushi selfhost doctor
@@ -7365,11 +7954,11 @@ function registerProfileCommands(program2) {
7365
7954
 
7366
7955
  // src/commands/radar.ts
7367
7956
  import { execFileSync } from "child_process";
7368
- import { resolve as resolve4 } from "path";
7957
+ import { resolve as resolve5 } from "path";
7369
7958
 
7370
7959
  // src/radar/scan.ts
7371
- import { readdirSync as readdirSync2, readFileSync as readFileSync3, statSync as statSync2 } from "fs";
7372
- import { isAbsolute, join as join5, relative as relative2, resolve as resolve3, sep } from "path";
7960
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
7961
+ import { isAbsolute, join as join6, relative as relative2, resolve as resolve4, sep } from "path";
7373
7962
 
7374
7963
  // src/radar/repo-scan-core.ts
7375
7964
  var REPO_SCAN_PATHS = [
@@ -7517,7 +8106,7 @@ function listRepoFiles(root, limit = MAX_FILES) {
7517
8106
  return;
7518
8107
  }
7519
8108
  if (e.isSymbolicLink()) continue;
7520
- const full = join5(dir, e.name);
8109
+ const full = join6(dir, e.name);
7521
8110
  if (e.isDirectory()) {
7522
8111
  if (!SKIP_DIRS.has(e.name)) walk2(full);
7523
8112
  } else if (e.isFile()) {
@@ -7554,7 +8143,7 @@ function findBundleRoots(root) {
7554
8143
  }
7555
8144
  for (const e of entries) {
7556
8145
  if (!e.isDirectory() || e.isSymbolicLink()) continue;
7557
- const full = join5(dir, e.name);
8146
+ const full = join6(dir, e.name);
7558
8147
  const rel = relative2(root, full).split(sep).join("/");
7559
8148
  if (BUNDLE_DIR_NAMES.has(e.name)) {
7560
8149
  roots.push(rel);
@@ -7564,7 +8153,7 @@ function findBundleRoots(root) {
7564
8153
  if (clientParts) {
7565
8154
  for (const part of clientParts) {
7566
8155
  try {
7567
- if (statSync2(join5(full, part)).isDirectory()) roots.push(`${rel}/${part}`);
8156
+ if (statSync2(join6(full, part)).isDirectory()) roots.push(`${rel}/${part}`);
7568
8157
  } catch {
7569
8158
  }
7570
8159
  }
@@ -7592,7 +8181,7 @@ function isClientSafeMatch(m) {
7592
8181
  function bundleRootsFromFlags(root, dirs) {
7593
8182
  const roots = [];
7594
8183
  for (const d of dirs) {
7595
- const full = resolve3(root, d);
8184
+ const full = resolve4(root, d);
7596
8185
  const rel = relative2(root, full);
7597
8186
  if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) throw new Error(`--bundle-dir ${d} must be a folder inside ${root}`);
7598
8187
  if (!statSync2(full).isDirectory()) throw new Error(`--bundle-dir ${d} is not a folder`);
@@ -7600,7 +8189,7 @@ function bundleRootsFromFlags(root, dirs) {
7600
8189
  }
7601
8190
  return [...new Set(roots)].sort();
7602
8191
  }
7603
- function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), bundleDirs) {
8192
+ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync4(p5, "utf8"), bundleDirs) {
7604
8193
  const roots = bundleDirs && bundleDirs.length > 0 ? bundleRootsFromFlags(root, bundleDirs) : findBundleRoots(root);
7605
8194
  const out = { roots, scannedFiles: 0, truncated: false, unreadable: 0, findings: [] };
7606
8195
  const walk2 = (dir) => {
@@ -7618,7 +8207,7 @@ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), b
7618
8207
  return;
7619
8208
  }
7620
8209
  if (e.isSymbolicLink()) continue;
7621
- const full = join5(dir, e.name);
8210
+ const full = join6(dir, e.name);
7622
8211
  if (e.isDirectory()) {
7623
8212
  if (!BUNDLE_SKIP_DIRS.has(e.name)) walk2(full);
7624
8213
  continue;
@@ -7642,17 +8231,17 @@ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), b
7642
8231
  }
7643
8232
  }
7644
8233
  };
7645
- for (const r of roots) walk2(join5(root, r));
8234
+ for (const r of roots) walk2(join6(root, r));
7646
8235
  return out;
7647
8236
  }
7648
- function scanLocalRepo(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), opts = {}) {
8237
+ function scanLocalRepo(root, readFile3 = (p5) => readFileSync4(p5, "utf8"), opts = {}) {
7649
8238
  const { files, truncated, unreadable: unreadableDirs } = listRepoFiles(root);
7650
8239
  let unreadable = unreadableDirs;
7651
8240
  const findings = [];
7652
8241
  const configFiles = {};
7653
8242
  let scannedFiles = 0;
7654
8243
  for (const rel of files) {
7655
- const full = join5(root, rel);
8244
+ const full = join6(root, rel);
7656
8245
  let size = 0;
7657
8246
  try {
7658
8247
  size = statSync2(full).size;
@@ -7742,7 +8331,7 @@ Add one step to your existing CI job, after the build step (no new job needed):
7742
8331
  - run: npx mushi-mushi radar scan --push
7743
8332
  env:
7744
8333
  MUSHI_API_KEY: \${{ secrets.MUSHI_INGEST_KEY }}`).action(async (opts) => {
7745
- const root = resolve4(opts.dir);
8334
+ const root = resolve5(opts.dir);
7746
8335
  let scan;
7747
8336
  try {
7748
8337
  scan = scanLocalRepo(root, void 0, { bundleDirs: opts.bundleDir });
@@ -7807,13 +8396,13 @@ Add one step to your existing CI job, after the build step (no new job needed):
7807
8396
 
7808
8397
  // src/commands/recipe.ts
7809
8398
  import { execFileSync as execFileSync3 } from "child_process";
7810
- import { writeFileSync as writeFileSync3 } from "fs";
7811
- import { join as join7, resolve as resolve5 } from "path";
8399
+ import { writeFileSync as writeFileSync4 } from "fs";
8400
+ import { join as join8, resolve as resolve6 } from "path";
7812
8401
 
7813
8402
  // src/recipe/local.ts
7814
8403
  import { execFileSync as execFileSync2 } from "child_process";
7815
- import { existsSync as existsSync3, readdirSync as readdirSync3, readFileSync as readFileSync4, statSync as statSync3 } from "fs";
7816
- import { join as join6, relative as relative3, sep as sep2 } from "path";
8404
+ import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
8405
+ import { join as join7, relative as relative3, sep as sep2 } from "path";
7817
8406
 
7818
8407
  // src/recipe/engine/design-color.ts
7819
8408
  var clamp01 = (n) => Math.min(1, Math.max(0, n));
@@ -8949,7 +9538,7 @@ function readScanTokens(manifest, treePaths, readFile3) {
8949
9538
  }
8950
9539
 
8951
9540
  // src/file-io.ts
8952
- import { closeSync, fstatSync, openSync, readSync, writeFileSync as writeFileSync2 } from "fs";
9541
+ import { closeSync, fstatSync, openSync, readSync, writeFileSync as writeFileSync3 } from "fs";
8953
9542
  var CHUNK_BYTES = 64 * 1024;
8954
9543
  function readTextFileCapped(path, maxBytes) {
8955
9544
  let fd;
@@ -8985,7 +9574,7 @@ function writeUserOutputFile(path, text2, opts) {
8985
9574
  throw new MushiCliError("E_API_ERROR", `The server sent more than ${Math.round(opts.maxBytes / (1024 * 1024))} MB, so nothing was written.`);
8986
9575
  }
8987
9576
  try {
8988
- writeFileSync2(path, text2, { encoding: "utf8", mode: opts.mode ?? 420 });
9577
+ writeFileSync3(path, text2, { encoding: "utf8", mode: opts.mode ?? 420 });
8989
9578
  } catch (err) {
8990
9579
  throw new MushiCliError("E_FILE_PERMISSION", `Could not write ${path}`, "pick a path you can write to", err);
8991
9580
  }
@@ -9131,7 +9720,7 @@ function walk(root, limit = 2e4) {
9131
9720
  for (const e of entries) {
9132
9721
  if (out.length >= limit) return;
9133
9722
  if (e.isSymbolicLink()) continue;
9134
- const full = join6(dir, e.name);
9723
+ const full = join7(dir, e.name);
9135
9724
  if (e.isDirectory()) {
9136
9725
  if (!SKIP.has(e.name)) go(full);
9137
9726
  } else if (e.isFile()) out.push(relative3(root, full).split(sep2).join("/"));
@@ -9151,7 +9740,7 @@ function listRepoFiles2(root) {
9151
9740
  const entries = [];
9152
9741
  for (const p5 of paths) {
9153
9742
  try {
9154
- const st = statSync3(join6(root, p5));
9743
+ const st = statSync3(join7(root, p5));
9155
9744
  if (st.isFile()) entries.push({ path: p5, size: st.size });
9156
9745
  } catch {
9157
9746
  }
@@ -9160,7 +9749,7 @@ function listRepoFiles2(root) {
9160
9749
  }
9161
9750
  function readJson(path) {
9162
9751
  try {
9163
- return JSON.parse(readFileSync4(path, "utf8"));
9752
+ return JSON.parse(readFileSync5(path, "utf8"));
9164
9753
  } catch {
9165
9754
  return null;
9166
9755
  }
@@ -9197,7 +9786,7 @@ var DEPLOY_STEPS = [
9197
9786
  ];
9198
9787
  var WRITES_FILE = /\b(writeFileSync|writeFile|createWriteStream|outputFileSync|outputFile|outputJsonSync|outputJson|writeJsonSync|writeJson|writeTextFile|write_text)\b/;
9199
9788
  function readCapped(root, path) {
9200
- const f = readTextFileCapped(join6(root, path), MAX_READ_BYTES);
9789
+ const f = readTextFileCapped(join7(root, path), MAX_READ_BYTES);
9201
9790
  return f.kind === "file" ? f.text : null;
9202
9791
  }
9203
9792
  function workspacePatterns(root, pkg) {
@@ -9260,7 +9849,7 @@ function starterManifest(root) {
9260
9849
  const tracked = listRepoFiles2(root).map((e) => e.path);
9261
9850
  const files = tracked.length ? tracked : walk(root);
9262
9851
  const fileSet = new Set(files);
9263
- const pkg = readJson(join6(root, "package.json"));
9852
+ const pkg = readJson(join7(root, "package.json"));
9264
9853
  const deps2 = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
9265
9854
  const rootScripts = Object.entries(pkg?.scripts ?? {}).filter((e) => typeof e[1] === "string");
9266
9855
  const native = files.some((f) => /^capacitor\.config\.(ts|js|json)$/.test(f)) || "expo" in deps2 || "react-native" in deps2 || files.some((f) => f.startsWith("android/") || f.startsWith("ios/"));
@@ -9314,7 +9903,7 @@ function starterManifest(root) {
9314
9903
  }))
9315
9904
  };
9316
9905
  }
9317
- const envExample = ENV_EXAMPLES.find((p5) => existsSync3(join6(root, p5)));
9906
+ const envExample = ENV_EXAMPLES.find((p5) => existsSync4(join7(root, p5)));
9318
9907
  if (envExample) manifest.env = { environments: ["production"], required: [], example: envExample };
9319
9908
  const sourceDirs = tokens.filter((t) => t.role === "source").map((t) => `${t.path.split("/").slice(0, -1).join("/") || "."}/**`);
9320
9909
  manifest.change = { allowPaths: [MANIFEST, ...new Set(sourceDirs)] };
@@ -9330,13 +9919,13 @@ function localReader(root) {
9330
9919
  return (path, maxBytes) => {
9331
9920
  const safe = normalizeRepoPath(path);
9332
9921
  if (!safe) return { kind: "absent" };
9333
- return readTextFileCapped(join6(root, safe), maxBytes);
9922
+ return readTextFileCapped(join7(root, safe), maxBytes);
9334
9923
  };
9335
9924
  }
9336
9925
  function checkRecipe(root) {
9337
9926
  const issues = [];
9338
9927
  const files = {};
9339
- const path = join6(root, MANIFEST);
9928
+ const path = join7(root, MANIFEST);
9340
9929
  const fail = (message) => ({ ok: false, manifest: null, issues: [...issues, { severity: "error", message, path: MANIFEST }], tokenCount: 0, findings: [], design: null, files });
9341
9930
  const manifestRead = readTextFileCapped(path, MAX_MANIFEST_BYTES);
9342
9931
  if (manifestRead.kind === "absent") return fail(`No ${MANIFEST} at the repo root. Run \`mushi recipe init\` to write one.`);
@@ -9518,10 +10107,10 @@ function headBranch(dir) {
9518
10107
  function registerRecipeCommands(program2) {
9519
10108
  const recipe = program2.command("recipe").description("Your app's recipe: design tokens, routes, CI, deploy and env, so a fix uses your own system");
9520
10109
  recipe.command("init").description(`Write a starter ${MANIFEST} from what this repo shows`).option("--dir <path>", "Repo root", ".").option("--force", `Overwrite an existing ${MANIFEST}`).action((opts) => {
9521
- const root = resolve5(opts.dir);
9522
- const target = join7(root, MANIFEST);
10110
+ const root = resolve6(opts.dir);
10111
+ const target = join8(root, MANIFEST);
9523
10112
  try {
9524
- writeFileSync3(target, `${JSON.stringify(starterManifest(root), null, 2)}
10113
+ writeFileSync4(target, `${JSON.stringify(starterManifest(root), null, 2)}
9525
10114
  `, { flag: opts.force ? "w" : "wx" });
9526
10115
  } catch (err) {
9527
10116
  if (err.code !== "EEXIST") throw err;
@@ -9533,7 +10122,7 @@ function registerRecipeCommands(program2) {
9533
10122
  console.log(`Wrote ${MANIFEST}. Check the guesses, then run \`mushi recipe check\`.`);
9534
10123
  });
9535
10124
  recipe.command("check").description(`Validate ${MANIFEST} and its token files, and score how far the code is from your design system (the same rules Mushi's scan uses)`).option("--dir <path>", "Repo root", ".").option("--push", "Send the recipe and the scan to Mushi (one extra step in your existing CI job); fails when the score is above the project's limit").option("--max-score <n>", "Also fail when the deviance score (0\u2013100) is above n, without asking Mushi").option("--json", "Machine-readable JSON output").action(async (opts) => {
9536
- const root = resolve5(opts.dir);
10125
+ const root = resolve6(opts.dir);
9537
10126
  const maxScore = opts.maxScore === void 0 ? null : Number(opts.maxScore);
9538
10127
  if (maxScore !== null && (!Number.isInteger(maxScore) || maxScore < 0 || maxScore > 100)) {
9539
10128
  process.stderr.write("error: --max-score must be a whole number from 0 to 100.\n");
@@ -9628,28 +10217,28 @@ function registerRecipeCommands(program2) {
9628
10217
  }
9629
10218
 
9630
10219
  // src/commands/store.ts
9631
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
9632
- import { join as join9, resolve as resolve6 } from "path";
10220
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
10221
+ import { join as join10, resolve as resolve7 } from "path";
9633
10222
 
9634
10223
  // src/store/pull.ts
9635
10224
  import { createSign, sign as cryptoSign } from "crypto";
9636
- import { mkdirSync, writeFileSync as writeFileSync4 } from "fs";
9637
- import { dirname as dirname2, join as join8 } from "path";
9638
- function b64url(buf) {
10225
+ import { mkdirSync, writeFileSync as writeFileSync5 } from "fs";
10226
+ import { dirname as dirname3, join as join9 } from "path";
10227
+ function b64url2(buf) {
9639
10228
  return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
9640
10229
  }
9641
10230
  function ascJwt(keyId, issuerId, privateKeyPem, nowSec) {
9642
- const head = b64url(JSON.stringify({ alg: "ES256", kid: keyId, typ: "JWT" }));
9643
- const body = b64url(JSON.stringify({ iss: issuerId, iat: nowSec, exp: nowSec + 1200, aud: "appstoreconnect-v1" }));
10231
+ const head = b64url2(JSON.stringify({ alg: "ES256", kid: keyId, typ: "JWT" }));
10232
+ const body = b64url2(JSON.stringify({ iss: issuerId, iat: nowSec, exp: nowSec + 1200, aud: "appstoreconnect-v1" }));
9644
10233
  const sig = cryptoSign("sha256", Buffer.from(`${head}.${body}`), { key: privateKeyPem, dsaEncoding: "ieee-p1363" });
9645
- return `${head}.${body}.${b64url(sig)}`;
10234
+ return `${head}.${body}.${b64url2(sig)}`;
9646
10235
  }
9647
10236
  function googleAssertion(clientEmail, privateKeyPem, nowSec) {
9648
- const head = b64url(JSON.stringify({ alg: "RS256", typ: "JWT" }));
9649
- const body = b64url(JSON.stringify({ iss: clientEmail, scope: "https://www.googleapis.com/auth/androidpublisher", aud: "https://oauth2.googleapis.com/token", iat: nowSec, exp: nowSec + 3600 }));
10237
+ const head = b64url2(JSON.stringify({ alg: "RS256", typ: "JWT" }));
10238
+ const body = b64url2(JSON.stringify({ iss: clientEmail, scope: "https://www.googleapis.com/auth/androidpublisher", aud: "https://oauth2.googleapis.com/token", iat: nowSec, exp: nowSec + 3600 }));
9650
10239
  const signer = createSign("RSA-SHA256");
9651
10240
  signer.update(`${head}.${body}`);
9652
- return `${head}.${body}.${b64url(signer.sign(privateKeyPem))}`;
10241
+ return `${head}.${body}.${b64url2(signer.sign(privateKeyPem))}`;
9653
10242
  }
9654
10243
  async function json(fetchImpl, url, init) {
9655
10244
  const res = await fetchImpl(url, init);
@@ -9708,9 +10297,9 @@ function writeListing(root, listingDir, files) {
9708
10297
  const written = [];
9709
10298
  for (const [rel, text2] of Object.entries(files)) {
9710
10299
  if (rel.includes("..")) continue;
9711
- const path = join8(root, listingDir, rel);
9712
- mkdirSync(dirname2(path), { recursive: true });
9713
- writeFileSync4(path, text2.endsWith("\n") ? text2 : `${text2}
10300
+ const path = join9(root, listingDir, rel);
10301
+ mkdirSync(dirname3(path), { recursive: true });
10302
+ writeFileSync5(path, text2.endsWith("\n") ? text2 : `${text2}
9714
10303
  `);
9715
10304
  written.push(`${listingDir}/${rel}`);
9716
10305
  }
@@ -9733,10 +10322,10 @@ function renderStoreReviews(d) {
9733
10322
  return lines;
9734
10323
  }
9735
10324
  function readManifestStore(root) {
9736
- const path = join9(root, "mushi.recipe.json");
9737
- if (!existsSync4(path)) return null;
10325
+ const path = join10(root, "mushi.recipe.json");
10326
+ if (!existsSync5(path)) return null;
9738
10327
  try {
9739
- const m = JSON.parse(readFileSync5(path, "utf8"));
10328
+ const m = JSON.parse(readFileSync6(path, "utf8"));
9740
10329
  return {
9741
10330
  listingDir: (m.store?.listingDir ?? "fastlane/metadata").replace(/\/+$/, ""),
9742
10331
  appleId: m.store?.ios?.appleId ?? null,
@@ -9754,7 +10343,7 @@ Mushi never holds a key that can publish. After this, change the listing in
9754
10343
  the repo; your own CI (fastlane deliver / supply, or EAS) publishes it.
9755
10344
  Reads store.listingDir, store.ios.appleId and store.android.package from
9756
10345
  mushi.recipe.json.`).action(async (opts) => {
9757
- const root = resolve6(opts.dir);
10346
+ const root = resolve7(opts.dir);
9758
10347
  const cfg = readManifestStore(root);
9759
10348
  if (!cfg) {
9760
10349
  process.stderr.write("error: no readable mushi.recipe.json. Run `mushi recipe init` first.\n");
@@ -9768,7 +10357,7 @@ mushi.recipe.json.`).action(async (opts) => {
9768
10357
  const keyPath = opts.ascKeyPath ?? process.env.MUSHI_ASC_KEY_PATH;
9769
10358
  if (cfg.appleId && keyId && issuerId && keyPath) {
9770
10359
  try {
9771
- const ios = await pullAppStore(fetch, cfg.appleId, { keyId, issuerId, privateKey: readFileSync5(keyPath, "utf8") }, now);
10360
+ const ios = await pullAppStore(fetch, cfg.appleId, { keyId, issuerId, privateKey: readFileSync6(keyPath, "utf8") }, now);
9772
10361
  if (!Object.keys(ios).some((k) => k.endsWith("/description.txt"))) console.log("App Store: no version is live yet, so only the app name, subtitle and privacy link were pulled.");
9773
10362
  Object.assign(files, ios);
9774
10363
  } catch (err) {
@@ -9782,7 +10371,7 @@ mushi.recipe.json.`).action(async (opts) => {
9782
10371
  const playPath = opts.playKeyPath ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
9783
10372
  if (cfg.androidPackage && playPath) {
9784
10373
  try {
9785
- Object.assign(files, await pullPlay(fetch, cfg.androidPackage, JSON.parse(readFileSync5(playPath, "utf8")), now));
10374
+ Object.assign(files, await pullPlay(fetch, cfg.androidPackage, JSON.parse(readFileSync6(playPath, "utf8")), now));
9786
10375
  } catch (err) {
9787
10376
  process.stderr.write(`Google Play: ${err.message}
9788
10377
  `);
@@ -10426,7 +11015,7 @@ function recordingBody(opts) {
10426
11015
  }
10427
11016
 
10428
11017
  // src/commands/releases.ts
10429
- import { readFileSync as readFileSync6 } from "fs";
11018
+ import { readFileSync as readFileSync7 } from "fs";
10430
11019
  var DRAFT_TIMEOUT_MS = 12e4;
10431
11020
  var PUBLISH_TIMEOUT_MS = 6e4;
10432
11021
  function renderReleaseList(rows, total) {
@@ -10462,7 +11051,7 @@ function renderCalendar(data) {
10462
11051
  function readBody(path) {
10463
11052
  if (!path) return void 0;
10464
11053
  try {
10465
- return readFileSync6(path, "utf8");
11054
+ return readFileSync7(path, "utf8");
10466
11055
  } catch (err) {
10467
11056
  throw new MushiCliError("E_FILE_NOT_FOUND", `Could not read ${path}`, "pass a Markdown file you can read", err);
10468
11057
  }
@@ -11326,7 +11915,7 @@ var STATUS_LABEL = {
11326
11915
  pending: "queued"
11327
11916
  };
11328
11917
  var RUN_ID_RE = /^[0-9]{8}-[0-9]{6}-[a-z0-9]{4}$/;
11329
- var KEY_RE = /^[a-z0-9][a-z0-9-]{0,79}$/;
11918
+ var KEY_RE2 = /^[a-z0-9][a-z0-9-]{0,79}$/;
11330
11919
  function projectId() {
11331
11920
  const config = requireConfig({ needsProject: true });
11332
11921
  return { config, pid: encodeURIComponent(config.projectId) };
@@ -11378,7 +11967,7 @@ function registerUxRunsCommands(program2) {
11378
11967
  }
11379
11968
  });
11380
11969
  runs.command("file <runId> <screen>").description("File one screen of a run as a bug (source ux_loop; no AI call)").option("--json", "Machine-readable JSON output").action(async (runId, screen, opts) => {
11381
- if (!KEY_RE.test(screen)) throw new MushiCliError("E_INVALID_INPUT", `"${screen}" is not a screen key (see \`mushi ux-runs show ${runId}\` --json).`);
11970
+ if (!KEY_RE2.test(screen)) throw new MushiCliError("E_INVALID_INPUT", `"${screen}" is not a screen key (see \`mushi ux-runs show ${runId}\` --json).`);
11382
11971
  const { config, pid } = projectId();
11383
11972
  const result = await apiCall(
11384
11973
  `/v1/admin/projects/${pid}/ux-runs/${requireRunId(runId)}/surfaces/${screen}/report`,
@@ -11396,9 +11985,9 @@ function registerUxRunsCommands(program2) {
11396
11985
 
11397
11986
  // src/commands/runner.ts
11398
11987
  import { spawnSync as spawnSync3 } from "child_process";
11399
- import { accessSync, chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync5, fchownSync, fstatSync as fstatSync2, ftruncateSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync7, realpathSync, writeFileSync as writeFileSync5, writeSync } from "fs";
11988
+ import { accessSync, chmodSync, closeSync as closeSync2, constants as fsConstants, existsSync as existsSync6, fchownSync, fstatSync as fstatSync2, ftruncateSync, mkdirSync as mkdirSync2, openSync as openSync2, readFileSync as readFileSync8, realpathSync, writeFileSync as writeFileSync6, writeSync } from "fs";
11400
11989
  import { arch as nodeArch, userInfo } from "os";
11401
- import { dirname as dirname3, join as join10, resolve as resolve7 } from "path";
11990
+ import { dirname as dirname4, join as join11, resolve as resolve8 } from "path";
11402
11991
  import * as p3 from "@clack/prompts";
11403
11992
 
11404
11993
  // src/runner/hooks.ts
@@ -12781,7 +13370,7 @@ function readIfPresent(path) {
12781
13370
  throw err;
12782
13371
  }
12783
13372
  try {
12784
- return readFileSync7(fd, "utf8");
13373
+ return readFileSync8(fd, "utf8");
12785
13374
  } finally {
12786
13375
  closeSync2(fd);
12787
13376
  }
@@ -12806,7 +13395,7 @@ var deps = {
12806
13395
  host: nodeHostIO,
12807
13396
  gh: nodeGh,
12808
13397
  runStep: defaultRunStep,
12809
- systemdRunning: () => existsSync5("/run/systemd/system"),
13398
+ systemdRunning: () => existsSync6("/run/systemd/system"),
12810
13399
  ghAuthText: () => ghAuthStatus().text
12811
13400
  };
12812
13401
  function githubTokenForBill() {
@@ -12827,8 +13416,8 @@ function readRunnerKeyForHeartbeat(keyFile) {
12827
13416
  if (fromEnv) return fromEnv;
12828
13417
  const credDir = process.env["CREDENTIALS_DIRECTORY"];
12829
13418
  const paths = [
12830
- ...credDir ? [join10(credDir, RUNNER_KEY_CREDENTIAL)] : [],
12831
- keyFile ? resolve7(keyFile) : RUNNER_KEY_PATH
13419
+ ...credDir ? [join11(credDir, RUNNER_KEY_CREDENTIAL)] : [],
13420
+ keyFile ? resolve8(keyFile) : RUNNER_KEY_PATH
12832
13421
  ];
12833
13422
  for (const path of paths) {
12834
13423
  const key = deps.host.readFile(path)?.trim();
@@ -12881,7 +13470,7 @@ function heartbeatCommand() {
12881
13470
  if (entry && !entry.includes("/_npx/") && entry.endsWith(".js")) {
12882
13471
  return [process.execPath, entry, "runner", "heartbeat", "--once"];
12883
13472
  }
12884
- return [join10(dirname3(process.execPath), "npx"), "-y", `@mushi-mushi/cli@${MUSHI_CLI_VERSION}`, "runner", "heartbeat", "--once"];
13473
+ return [join11(dirname4(process.execPath), "npx"), "-y", `@mushi-mushi/cli@${MUSHI_CLI_VERSION}`, "runner", "heartbeat", "--once"];
12885
13474
  }
12886
13475
  function safeRealpath(path) {
12887
13476
  try {
@@ -13196,19 +13785,19 @@ The key comes from MUSHI_RUNNER_KEY, or a new one is created with your CLI key
13196
13785
  (needs mcp:write). It is saved in <dir>/${HOOKS_DIR_NAME}/key with mode 0600,
13197
13786
  never in the scripts, and never printed.
13198
13787
  GitHub docs: https://docs.github.com/en/actions/how-tos/manage-runners/self-hosted-runners/run-scripts`).action(async (opts) => {
13199
- const dir = resolve7(opts.dir);
13200
- if (!existsSync5(join10(dir, "config.sh")) && !existsSync5(join10(dir, "run.sh"))) {
13788
+ const dir = resolve8(opts.dir);
13789
+ if (!existsSync6(join11(dir, "config.sh")) && !existsSync6(join11(dir, "run.sh"))) {
13201
13790
  throw new MushiCliError("E_INVALID_INPUT", `${dir} does not look like a runner folder (no config.sh or run.sh).`);
13202
13791
  }
13203
13792
  const config = loadConfig();
13204
13793
  const endpoint = config.endpoint ?? CLOUD_API_ENDPOINT;
13205
13794
  const hostId = hostIdOrThrow();
13206
- const hooksDir = join10(dir, HOOKS_DIR_NAME);
13795
+ const hooksDir = join11(dir, HOOKS_DIR_NAME);
13207
13796
  const files = {
13208
- started: join10(hooksDir, "job-started.sh"),
13209
- completed: join10(hooksDir, "job-completed.sh")
13797
+ started: join11(hooksDir, "job-started.sh"),
13798
+ completed: join11(hooksDir, "job-completed.sh")
13210
13799
  };
13211
- const envPath = join10(dir, ".env");
13800
+ const envPath = join11(dir, ".env");
13212
13801
  const envBefore = readIfPresent(envPath);
13213
13802
  const merged = mergeRunnerEnv(envBefore, files, opts.force);
13214
13803
  if (merged.conflicts.length) {
@@ -13217,7 +13806,7 @@ GitHub docs: https://docs.github.com/en/actions/how-tos/manage-runners/self-host
13217
13806
  throw new MushiCliError("E_INVALID_INPUT", "The runner's .env already sets a job hook.", "chain it from the Mushi hook yourself, or pass --force to replace it");
13218
13807
  }
13219
13808
  if (opts.dryRun) {
13220
- console.log(`Would write ${files.started} and ${files.completed} (mode 0755), and ${join10(hooksDir, "key")} (mode 0600, a runner:write key, not shown).`);
13809
+ console.log(`Would write ${files.started} and ${files.completed} (mode 0755), and ${join11(hooksDir, "key")} (mode 0600, a runner:write key, not shown).`);
13221
13810
  const added = (merged.text ?? "").split("\n").filter((l) => l && !envBefore.split(/\r?\n/).includes(l));
13222
13811
  console.log(added.length ? `Would add to ${envPath}:
13223
13812
  ${added.map((l) => ` ${l}`).join("\n")}` : `${envPath} already has the hooks.`);
@@ -13229,16 +13818,16 @@ ${added.map((l) => ` ${l}`).join("\n")}` : `${envPath} already has the hooks.`)
13229
13818
  });
13230
13819
  mkdirSync2(hooksDir, { recursive: true, mode: 493 });
13231
13820
  for (const phase of ["started", "completed"]) {
13232
- writeFileSync5(files[phase], hookScript({ phase, endpoint, hostId }), { mode: 493 });
13821
+ writeFileSync6(files[phase], hookScript({ phase, endpoint, hostId }), { mode: 493 });
13233
13822
  }
13234
- const keyPath = join10(hooksDir, "key");
13235
- writeFileSync5(keyPath, `${runnerKey}
13823
+ const keyPath = join11(hooksDir, "key");
13824
+ writeFileSync6(keyPath, `${runnerKey}
13236
13825
  `, { mode: 384 });
13237
13826
  console.log(source === "env" ? "Using the runner key from MUSHI_RUNNER_KEY." : "Created a runner key (runner:write: it can only report runner health).");
13238
13827
  if (merged.text) {
13239
13828
  const fd = openSync2(envPath, fsConstants.O_RDWR | fsConstants.O_CREAT | (fsConstants.O_NOFOLLOW ?? 0), 420);
13240
13829
  try {
13241
- const now = mergeRunnerEnv(readFileSync7(fd, "utf8"), files, opts.force);
13830
+ const now = mergeRunnerEnv(readFileSync8(fd, "utf8"), files, opts.force);
13242
13831
  if (now.conflicts.length) throw new MushiCliError("E_INVALID_INPUT", "The runner's .env changed and now sets a job hook.", "run the command again");
13243
13832
  if (now.text) {
13244
13833
  ftruncateSync(fd, 0);
@@ -13269,19 +13858,19 @@ runner. Creating one needs a CLI key with mcp:write (mushi login --upgrade-scope
13269
13858
  ${RUNNER_KEY_PATH} is root-only; the heartbeat timer gets it from systemd.`).action(async (opts) => {
13270
13859
  const config = requireConfig();
13271
13860
  const key = await mintRunnerKeyOnly(config, opts.project, opts.label);
13272
- const out = resolve7(opts.out);
13273
- const dir = dirname3(out);
13861
+ const out = resolve8(opts.out);
13862
+ const dir = dirname4(out);
13274
13863
  const writable = (() => {
13275
13864
  try {
13276
- accessSync(existsSync5(dir) ? dir : dirname3(dir), fsConstants.W_OK);
13277
- return existsSync5(dir) || process.getuid?.() === 0;
13865
+ accessSync(existsSync6(dir) ? dir : dirname4(dir), fsConstants.W_OK);
13866
+ return existsSync6(dir) || process.getuid?.() === 0;
13278
13867
  } catch {
13279
13868
  return false;
13280
13869
  }
13281
13870
  })();
13282
13871
  if (writable) {
13283
13872
  mkdirSync2(dir, { recursive: true, mode: 448 });
13284
- writeFileSync5(out, `${key}
13873
+ writeFileSync6(out, `${key}
13285
13874
  `, { mode: 384 });
13286
13875
  chmodSync(out, 384);
13287
13876
  } else {
@@ -13505,8 +14094,8 @@ async function fixAll(config, opts) {
13505
14094
  }
13506
14095
 
13507
14096
  // src/commands/verify.ts
13508
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
13509
- import { dirname as dirname4, resolve as resolve8 } from "path";
14097
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync7 } from "fs";
14098
+ import { dirname as dirname5, resolve as resolve9 } from "path";
13510
14099
  var WORKFLOW_MAX_BYTES = 64 * 1024;
13511
14100
  var WORKFLOW_SHAPE = /uses:\s*kensaurus\/mushi-mushi\/\.github\/actions\/fix-verify@/;
13512
14101
  var VERIFY_WORKFLOW_PATH = ".github/workflows/mushi-verify.yml";
@@ -13532,13 +14121,13 @@ Verified merge. Docs: https://kensaur.us/mushi-mushi/docs/admin/verified-merge`)
13532
14121
  if (text2.length > WORKFLOW_MAX_BYTES || !WORKFLOW_SHAPE.test(text2) || text2.includes("\0")) {
13533
14122
  throw new MushiCliError("E_API_ERROR", "The server sent something that is not the Mushi verify workflow.", "Copy it from the console instead: Settings \u2192 Fixes \u2192 Verified merge.");
13534
14123
  }
13535
- const out = opts.out ? resolve8(opts.out) : null;
14124
+ const out = opts.out ? resolve9(opts.out) : null;
13536
14125
  if (out && !/\.ya?ml$/i.test(out)) {
13537
14126
  throw new MushiCliError("E_INVALID_INPUT", `--out must be a .yml or .yaml file: ${out}`, "For example: --out .github/workflows/mushi-verify.yml");
13538
14127
  }
13539
14128
  if (out) {
13540
- mkdirSync3(dirname4(out), { recursive: true });
13541
- writeFileSync6(out, text2);
14129
+ mkdirSync3(dirname5(out), { recursive: true });
14130
+ writeFileSync7(out, text2);
13542
14131
  }
13543
14132
  if (outputIsJson(opts.json)) {
13544
14133
  console.log(JSON.stringify({ ok: true, projectId: projectId2, yaml: text2, ...out ? { path: out } : {} }, null, 2));
@@ -13555,9 +14144,9 @@ Verified merge. Docs: https://kensaur.us/mushi-mushi/docs/admin/verified-merge`)
13555
14144
 
13556
14145
  // src/commands/worker.ts
13557
14146
  import { execFileSync as execFileSync4, spawnSync as spawnSync4 } from "child_process";
13558
- import { chmodSync as chmodSync2, existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync8, realpathSync as realpathSync2, rmSync, writeFileSync as writeFileSync7 } from "fs";
14147
+ import { chmodSync as chmodSync2, existsSync as existsSync7, mkdirSync as mkdirSync4, readFileSync as readFileSync9, realpathSync as realpathSync2, rmSync as rmSync2, writeFileSync as writeFileSync8 } from "fs";
13559
14148
  import { homedir, hostname } from "os";
13560
- import { dirname as dirname5, join as join12, resolve as resolve9 } from "path";
14149
+ import { dirname as dirname6, join as join13, resolve as resolve10 } from "path";
13561
14150
  import * as p4 from "@clack/prompts";
13562
14151
 
13563
14152
  // src/worker/flags-view.ts
@@ -13607,7 +14196,7 @@ function flagLines(flags) {
13607
14196
  }
13608
14197
 
13609
14198
  // src/worker/install.ts
13610
- import { join as join11 } from "path";
14199
+ import { join as join12 } from "path";
13611
14200
  var UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
13612
14201
  function parseLanesConf(text2, cloneRoot) {
13613
14202
  const lanes = [];
@@ -13626,7 +14215,7 @@ function parseLanesConf(text2, cloneRoot) {
13626
14215
  else if (mode === "queue" || mode === "fix") initial.mode = "fix";
13627
14216
  else if (mode === "off") Object.assign(initial, { mode: "fix", paused: true });
13628
14217
  else throw new MushiCliError("E_INVALID_INPUT", `lanes.conf line ${i + 1}: mode "${mode}" is not fix, followups, conflicts, audit, skill, queue or off.`);
13629
- lanes.push({ name, projectId: projectId2.toLowerCase(), repoDir: join11(cloneRoot, clone), initial });
14218
+ lanes.push({ name, projectId: projectId2.toLowerCase(), repoDir: join12(cloneRoot, clone), initial });
13630
14219
  }
13631
14220
  if (lanes.length === 0) throw new MushiCliError("E_INVALID_INPUT", "lanes.conf lists no lanes.");
13632
14221
  return lanes;
@@ -13664,7 +14253,7 @@ function windowsTaskArgs(o) {
13664
14253
  }
13665
14254
 
13666
14255
  // src/commands/worker.ts
13667
- var UNIT_PATH = join12(process.env["XDG_CONFIG_HOME"] || join12(homedir(), ".config"), "systemd", "user", SYSTEMD_UNIT_NAME);
14256
+ var UNIT_PATH = join13(process.env["XDG_CONFIG_HOME"] || join13(homedir(), ".config"), "systemd", "user", SYSTEMD_UNIT_NAME);
13668
14257
  function laneDone(l) {
13669
14258
  if (l.config.mode === "conflicts") return l.counts7d.merges ?? 0;
13670
14259
  if (l.config.mode === "audit") return l.counts7d.filed ?? 0;
@@ -13680,19 +14269,19 @@ function cliPath() {
13680
14269
  try {
13681
14270
  return realpathSync2(argv1);
13682
14271
  } catch {
13683
- return resolve9(argv1);
14272
+ return resolve10(argv1);
13684
14273
  }
13685
14274
  }
13686
14275
  function lanesFromOptions(opts) {
13687
14276
  if (opts.lanesConf) {
13688
- const root = resolve9(opts.cloneRoot ?? join12(homedir(), ".cache", "mushi-work"));
13689
- return parseLanesConf(readFileSync8(resolve9(opts.lanesConf), "utf8"), root);
14277
+ const root = resolve10(opts.cloneRoot ?? join13(homedir(), ".cache", "mushi-work"));
14278
+ return parseLanesConf(readFileSync9(resolve10(opts.lanesConf), "utf8"), root);
13690
14279
  }
13691
14280
  if (!opts.lane || !opts.project || !opts.repoDir) {
13692
14281
  throw new MushiCliError("E_INVALID_INPUT", "Name one lane (--lane, --project, --repo-dir) or import --lanes-conf.", "mushi worker install --lane my-app --project <app id> --repo-dir ~/src/my-app");
13693
14282
  }
13694
14283
  if (opts.model && !MODEL_RE.test(opts.model)) throw new MushiCliError("E_INVALID_INPUT", `--model "${opts.model}" is not a model id.`);
13695
- return [{ name: opts.lane, projectId: requireUuid(opts.project, "--project"), repoDir: resolve9(opts.repoDir), ...opts.model ? { initial: { model: opts.model } } : {} }];
14284
+ return [{ name: opts.lane, projectId: requireUuid(opts.project, "--project"), repoDir: resolve10(opts.repoDir), ...opts.model ? { initial: { model: opts.model } } : {} }];
13696
14285
  }
13697
14286
  function printLanes(cfg) {
13698
14287
  for (const l of cfg.lanes) {
@@ -13702,7 +14291,7 @@ function printLanes(cfg) {
13702
14291
  }
13703
14292
  function registerWorkerCommands(program2) {
13704
14293
  const worker = program2.command("worker").description("Set up and read the local worker (`mushi work --daemon`): lanes, key and service");
13705
- worker.command("install").description("Write the lanes file, store a worker key (worker:run) and the service that runs `mushi work --daemon`; prints everything and asks first").option("--lanes-conf <path>", "Import lane-v4's lanes.conf (name profile clone projectId model mode)").option("--clone-root <dir>", "With --lanes-conf: the folder that holds the clones", join12(homedir(), ".cache", "mushi-work")).option("--lane <name>", "One lane: its name").option("--project <id>", "One lane: its app id").option("--repo-dir <path>", "One lane: the clone it works in").option("--model <id>", "One lane: its model when it first registers (the console can change it)").option("--stop-at <time>", "Every lane stops taking reports at this time when it first registers (ISO, e.g. 2026-10-31T14:59:00Z); change it in the console later").option("--cursor-account <email>", "Spend only this Cursor account: a CLI signed in as anyone else counts as signed out").option("--agent <name>", "The coding agent every lane runs: cursor (default) or claude (Claude Code, signed in with claude auth login)").option("--endpoint <url>", "API endpoint (default: the CLI login's)").option("--key-stdin", "Read a worker key made in the console (Workers tab) from stdin instead of creating one").option("--no-service", "Write the lanes file and key only").option("--yes", "Do not ask before writing").option("--dry-run", "Print what would be written; write nothing").action(async (opts) => {
14294
+ worker.command("install").description("Write the lanes file, store a worker key (worker:run) and the service that runs `mushi work --daemon`; prints everything and asks first").option("--lanes-conf <path>", "Import lane-v4's lanes.conf (name profile clone projectId model mode)").option("--clone-root <dir>", "With --lanes-conf: the folder that holds the clones", join13(homedir(), ".cache", "mushi-work")).option("--lane <name>", "One lane: its name").option("--project <id>", "One lane: its app id").option("--repo-dir <path>", "One lane: the clone it works in").option("--model <id>", "One lane: its model when it first registers (the console can change it)").option("--stop-at <time>", "Every lane stops taking reports at this time when it first registers (ISO, e.g. 2026-10-31T14:59:00Z); change it in the console later").option("--cursor-account <email>", "Spend only this Cursor account: a CLI signed in as anyone else counts as signed out").option("--agent <name>", "The coding agent every lane runs: cursor (default) or claude (Claude Code, signed in with claude auth login)").option("--endpoint <url>", "API endpoint (default: the CLI login's)").option("--key-stdin", "Read a worker key made in the console (Workers tab) from stdin instead of creating one").option("--no-service", "Write the lanes file and key only").option("--yes", "Do not ask before writing").option("--dry-run", "Print what would be written; write nothing").action(async (opts) => {
13706
14295
  const cli = loadConfig();
13707
14296
  const endpoint = opts.endpoint ?? process.env["MUSHI_API_ENDPOINT"] ?? cli.endpoint;
13708
14297
  let stopAt = null;
@@ -13766,22 +14355,22 @@ Service: not automated on ${platform}; run \`mushi work --daemon\` under your se
13766
14355
  key = res.data.key;
13767
14356
  }
13768
14357
  assertWorkerKey(key, cli.apiKey);
13769
- mkdirSync4(dirname5(WORKER_CONFIG_PATH), { recursive: true });
13770
- writeFileSync7(WORKER_CONFIG_PATH, `${JSON.stringify(cfg, null, 2)}
14358
+ mkdirSync4(dirname6(WORKER_CONFIG_PATH), { recursive: true });
14359
+ writeFileSync8(WORKER_CONFIG_PATH, `${JSON.stringify(cfg, null, 2)}
13771
14360
  `, { mode: 384 });
13772
14361
  if (trySaveWorkerKey(key)) {
13773
- if (existsSync6(WORKER_KEY_PATH)) rmSync(WORKER_KEY_PATH);
14362
+ if (existsSync7(WORKER_KEY_PATH)) rmSync2(WORKER_KEY_PATH);
13774
14363
  console.log("Saved the worker key in the OS keychain.");
13775
14364
  } else {
13776
- writeFileSync7(WORKER_KEY_PATH, `${key}
14365
+ writeFileSync8(WORKER_KEY_PATH, `${key}
13777
14366
  `, { mode: 384 });
13778
14367
  chmodSync2(WORKER_KEY_PATH, 384);
13779
14368
  console.log(`Saved the worker key in ${WORKER_KEY_PATH} (mode 0600).`);
13780
14369
  }
13781
14370
  console.log(`Wrote ${WORKER_CONFIG_PATH}.`);
13782
14371
  if (service?.kind === "systemd") {
13783
- mkdirSync4(dirname5(UNIT_PATH), { recursive: true });
13784
- writeFileSync7(UNIT_PATH, service.unit);
14372
+ mkdirSync4(dirname6(UNIT_PATH), { recursive: true });
14373
+ writeFileSync8(UNIT_PATH, service.unit);
13785
14374
  const reload = spawnSync4("systemctl", ["--user", "daemon-reload"], { stdio: "inherit" });
13786
14375
  const enable = reload.status === 0 ? spawnSync4("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT_NAME], { stdio: "inherit" }) : reload;
13787
14376
  console.log(enable.status === 0 ? `Started ${SYSTEMD_UNIT_NAME}. Logs: journalctl --user -u ${SYSTEMD_UNIT_NAME} -f` : `Wrote ${UNIT_PATH}; start it with: systemctl --user enable --now ${SYSTEMD_UNIT_NAME}`);
@@ -13880,7 +14469,7 @@ ${"lane".padEnd(16)} ${"app".padEnd(16)} ${"mode".padEnd(10)} ${"state".padEnd(1
13880
14469
  console.log("No worker key on this machine.");
13881
14470
  }
13882
14471
  tryDeleteWorkerKey();
13883
- if (existsSync6(WORKER_KEY_PATH)) rmSync(WORKER_KEY_PATH);
14472
+ if (existsSync7(WORKER_KEY_PATH)) rmSync2(WORKER_KEY_PATH);
13884
14473
  if (process.platform === "linux") spawnSync4("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT_NAME], { stdio: "inherit" });
13885
14474
  if (process.platform === "win32") spawnSync4("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
13886
14475
  console.log(`Removed the key from this machine. The lanes file (${WORKER_CONFIG_PATH}) is kept; delete it if you do not need it.`);
@@ -13888,8 +14477,8 @@ ${"lane".padEnd(16)} ${"app".padEnd(16)} ${"mode".padEnd(10)} ${"state".padEnd(1
13888
14477
  }
13889
14478
 
13890
14479
  // src/template.ts
13891
- import { cpSync, existsSync as existsSync7, renameSync } from "fs";
13892
- import { join as join13, resolve as resolve10 } from "path";
14480
+ import { cpSync, existsSync as existsSync8, renameSync } from "fs";
14481
+ import { join as join14, resolve as resolve11 } from "path";
13893
14482
  import { fileURLToPath } from "url";
13894
14483
  var TEMPLATE_IDS = ["vue", "svelte", "node"];
13895
14484
 
@@ -13912,6 +14501,8 @@ Flags (forwarded to the wizard):
13912
14501
  --skip-install print the install command instead of running it
13913
14502
  --skip-test-report don't offer to send a test report at the end
13914
14503
  --audit health-check an existing install (doctor checks) instead of re-running the wizard
14504
+ --dry-run print what the wizard would install and write, then stop (changes nothing,
14505
+ no sign-in)
13915
14506
  --cwd <path> run in a different directory
13916
14507
  --endpoint <url> override the Mushi API endpoint (self-hosted)
13917
14508
  -y, --yes take the defaults: detected framework, saved credentials, browser sign-in