@mushi-mushi/cli 0.40.1 → 0.40.3

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-OVBRQDHI.js";
31
+ } from "./chunk-HNVCLEDF.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-3B7PXCRR.js";
62
+ } from "./chunk-5TO6PSO6.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-QKO42UPX.js";
102
+ } from "./chunk-CGQE3GJK.js";
96
103
  import {
97
104
  MUSHI_CLI_VERSION,
98
105
  MUSHI_MCP_PIN_SPEC
99
- } from "./chunk-KQHEYAEK.js";
106
+ } from "./chunk-ZVNRKEVP.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-T27RO74F.js");
1626
+ const { MUSHI_CLI_VERSION: MUSHI_CLI_VERSION2 } = await import("./version-I4APZBTF.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
+ };
2578
+ }
2579
+ return { kind: "manual", target: snippetTarget(framework) };
2580
+ }
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}).`);
2556
2609
  }
2610
+ return outcome;
2557
2611
  }
2558
- function printNextSteps(framework, consoleBase, enableRewards = false) {
2559
- p.note(framework.snippet(), "Add this to your app:");
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-LCTKRHV7.js");
2645
+ const { runConnect: runConnect2 } = await import("./connect-FNGAJ532.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)"}`
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}`
2700
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;
@@ -2777,7 +3004,7 @@ var MIGRATE_CATALOG = [
2777
3004
  // Sentry gets a bespoke entry, NOT the generic competitor template:
2778
3005
  // the canonical messaging is "standalone OR enrich Sentry" — Mushi adds
2779
3006
  // plain-English diagnosis + paste-ready fixes ALONGSIDE Sentry, never a
2780
- // rip-out pitch (VISION.md drift guard).
3007
+ // rip-out pitch (docs/VISION.md drift guard).
2781
3008
  {
2782
3009
  slug: "sentry-to-mushi",
2783
3010
  title: "Sentry + Mushi (enrich or standalone)",
@@ -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,232 +7228,441 @@ 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
+ function supabaseCliVersion() {
6996
7236
  try {
6997
7237
  const r = spawnSync("supabase", ["--version"], { encoding: "utf8", timeout: 5e3 });
6998
- return r.status === 0;
7238
+ return r.status === 0 ? (r.stdout ?? "").trim() : null;
6999
7239
  } catch {
7000
- return false;
7240
+ return null;
7001
7241
  }
7002
7242
  }
7243
+ function supabaseCliMajor(version) {
7244
+ const m = /(\d+)\.\d+\.\d+/.exec(version ?? "");
7245
+ return m ? Number(m[1]) : void 0;
7246
+ }
7247
+ function linkedTargetFlag(cliMajor) {
7248
+ return cliMajor !== void 0 && cliMajor < 3 ? "--linked" : "--remote";
7249
+ }
7003
7250
  function selfhostStepCommand(step) {
7004
- return `supabase ${step.args.join(" ")}${step.mayFail ? " || true" : ""}`;
7251
+ return `supabase ${step.args.join(" ")}`;
7005
7252
  }
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
- };
7253
+ function redact2(text2, secrets) {
7254
+ let out = text2;
7255
+ for (const s of secrets) if (s) out = out.split(s).join("<redacted>");
7256
+ return out;
7257
+ }
7258
+ function runSupabase(step, opts) {
7259
+ process.stdout.write(` \u203A ${step.label} \u2026 `);
7260
+ for (const f of step.files ?? []) writeFileSync2(f.path, f.content, { mode: 384 });
7261
+ try {
7262
+ const r = spawnSync("supabase", step.args, {
7263
+ cwd: opts.cwd,
7264
+ encoding: "utf8",
7265
+ timeout: 9e5,
7266
+ stdio: ["ignore", "pipe", "pipe"],
7267
+ // The operator already confirmed (prompt or --yes): CLI 3.x reads consent
7268
+ // for hosted changes from SUPABASE_YES in the process environment.
7269
+ env: { ...process.env, SUPABASE_YES: "1" }
7270
+ });
7271
+ if (r.error || r.status !== 0) {
7272
+ process.stdout.write("\u2717\n");
7273
+ const stderr = redact2((r.stderr ?? "").trim() || (r.stdout ?? "").trim(), opts.secrets);
7274
+ return { ok: false, stderr: stderr || r.error?.message || `exited with ${r.status ?? r.signal}` };
7275
+ }
7276
+ process.stdout.write("\u2713\n");
7277
+ return { ok: true, stderr: "" };
7278
+ } finally {
7279
+ for (const f of step.files ?? []) rmSync(f.path, { force: true });
7022
7280
  }
7023
- process.stdout.write("\u2713\n");
7024
- return { ok: true, stdout: r.stdout, stderr: "" };
7025
7281
  }
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) {
7282
+ var KEY_RE = /^[A-Za-z0-9_-]+$/;
7283
+ var SECRET_RE = /^[A-Za-z0-9_-]{32,}$/;
7284
+ var PLAIN_URL_RE = /^[A-Za-z0-9:/._~-]+$/;
7285
+ function isPlainHttpUrl(value) {
7286
+ try {
7287
+ const u = new URL(value);
7288
+ return (u.protocol === "https:" || u.protocol === "http:") && PLAIN_URL_RE.test(value);
7289
+ } catch {
7290
+ return false;
7291
+ }
7292
+ }
7293
+ function llmProviderOfKey(key) {
7294
+ return key.startsWith("sk-ant-") ? "anthropic" : "openai";
7295
+ }
7296
+ function buildRuntimeConfigSql(supabaseUrl, internalToken) {
7297
+ const q2 = (s) => `'${s.replace(/'/g, "''")}'`;
7298
+ return [
7299
+ "-- Written by `mushi selfhost up`: point pg_cron jobs at this project, not Mushi Mushi Cloud.",
7300
+ "insert into public.mushi_runtime_config (key, value) values",
7301
+ ` ('supabase_url', ${q2(supabaseUrl)}),`,
7302
+ ` ('service_role_key', ${q2(internalToken)}),`,
7303
+ ` ('internal_caller_token', ${q2(internalToken)})`,
7304
+ "on conflict (key) do update set value = excluded.value, updated_at = now();",
7305
+ "",
7306
+ "-- Private, service-role only (same row as 20260416000000_phase0_initial_schema.sql).",
7307
+ "insert into storage.buckets (id, name, public, file_size_limit, allowed_mime_types)",
7308
+ "values ('screenshots', 'screenshots', false, 5242880, array['image/jpeg', 'image/png', 'image/webp'])",
7309
+ "on conflict (id) do nothing;",
7310
+ "",
7311
+ SELFHOST_PLAN_SQL
7312
+ ].join("\n");
7313
+ }
7314
+ var SELFHOST_PLAN_SQL = [
7315
+ "-- Self-hosted: no billing, so no Mushi Mushi Cloud plan limits on any plan.",
7316
+ "update public.pricing_plans set",
7317
+ " included_diagnoses_per_month = null,",
7318
+ " max_projects = null,",
7319
+ " seat_limit = null,",
7320
+ " retention_days = greatest(coalesce(retention_days, 0), 3650),",
7321
+ ` feature_flags = coalesce(feature_flags, '{}'::jsonb) || '{"byok": true, "sso": true, "plugins": true, "intelligence_reports": true, "audit_log": true, "self_hosted": true, "teams": true}'::jsonb`,
7322
+ "where true;",
7323
+ ""
7324
+ ].join("\n");
7325
+ var CLOUD_PROJECT_REF = "dxptnwrhwsqckaftyymj";
7326
+ function buildSelfhostSteps(input, printOnly, internalToken, tmpDir) {
7035
7327
  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}).` };
7328
+ const target = linkedTargetFlag(input.cliMajor);
7329
+ if (input.projectRef && !/^[a-z0-9-]+$/i.test(input.projectRef)) {
7330
+ return { ok: false, error: `--project-ref must be alphanumeric (got: ${input.projectRef}).` };
7038
7331
  }
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
- });
7332
+ if (input.projectRef === CLOUD_PROJECT_REF || input.supabaseUrl.includes(CLOUD_PROJECT_REF)) {
7333
+ return {
7334
+ ok: false,
7335
+ error: "That is the Mushi Mushi Cloud project. selfhost up deploys to your own Supabase project."
7336
+ };
7045
7337
  }
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)) {
7338
+ if (!printOnly && !isPlainHttpUrl(input.supabaseUrl)) {
7339
+ return { ok: false, error: `--supabase-url must be a plain http(s) URL (got: ${input.supabaseUrl}).` };
7340
+ }
7341
+ for (const [flag, key] of [
7342
+ ["--anthropic-key", input.anthropicKey],
7343
+ ["--openai-key", input.openaiKey]
7344
+ ]) {
7345
+ if (key && !KEY_RE.test(key)) {
7058
7346
  return {
7059
7347
  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>"
7348
+ error: `${flag} does not look like an API key (letters, digits, - and _ only).`
7061
7349
  };
7062
7350
  }
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
7351
  }
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
- }
7352
+ if (input.consoleUrl && !isPlainHttpUrl(input.consoleUrl)) {
7353
+ return { ok: false, error: `--console-url must be a plain http(s) URL (got: ${input.consoleUrl}).` };
7354
+ }
7355
+ if (!printOnly && !SECRET_RE.test(internalToken)) {
7356
+ return {
7357
+ ok: false,
7358
+ error: "MUSHI_INTERNAL_CALLER_SECRET must be at least 32 characters of letters, digits, - and _."
7359
+ };
7360
+ }
7361
+ if (input.projectRef) {
7084
7362
  steps.push({
7085
- label: "set ADMIN_BASE_URL secret",
7086
- args: ["secrets", "set", `ADMIN_BASE_URL=${opts.adminBaseUrl}`]
7363
+ label: `link to Supabase project ${input.projectRef}`,
7364
+ args: ["link", "--project-ref", input.projectRef],
7365
+ critical: true
7087
7366
  });
7088
7367
  }
7368
+ steps.push({ label: "apply database migrations", args: ["db", "push", target], critical: true });
7369
+ const token = printOnly ? "<YOUR_INTERNAL_CALLER_SECRET>" : internalToken;
7370
+ const secretLines = [`MUSHI_INTERNAL_CALLER_SECRET=${token}`];
7371
+ if (input.anthropicKey) secretLines.push(`ANTHROPIC_API_KEY=${printOnly ? "sk-ant-..." : input.anthropicKey}`);
7372
+ if (input.openaiKey) secretLines.push(`OPENAI_API_KEY=${printOnly ? "sk-..." : input.openaiKey}`);
7373
+ if (input.consoleUrl) secretLines.push(`ADMIN_BASE_URL=${input.consoleUrl}`);
7374
+ const secretsFile = join5(tmpDir, "mushi-secrets.env");
7089
7375
  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
- }
7104
- }
7376
+ label: `set function secrets (${secretLines.map((l) => l.split("=")[0]).join(", ")})`,
7377
+ args: ["secrets", "set", "--env-file", secretsFile],
7378
+ critical: true,
7379
+ files: [{ path: secretsFile, content: `${secretLines.join("\n")}
7380
+ ` }]
7381
+ });
7382
+ const sqlFile = join5(tmpDir, "mushi-runtime-config.sql");
7105
7383
  steps.push({
7106
- label: "create screenshots storage bucket",
7107
- args: ["storage", "create", "screenshots", "--public"],
7108
- mayFail: true
7384
+ label: "point cron jobs at this project (mushi_runtime_config) + screenshots bucket",
7385
+ args: ["db", "query", target, "--file", sqlFile],
7386
+ critical: true,
7387
+ files: [{ path: sqlFile, content: buildRuntimeConfigSql(input.supabaseUrl, token) }]
7109
7388
  });
7389
+ if (!input.skipDeploy) {
7390
+ steps.push({ label: "deploy every edge function", args: ["functions", "deploy"] });
7391
+ }
7110
7392
  return { ok: true, steps };
7111
7393
  }
7394
+ function selfhostConfigPatch(existing, endpoint, consoleUrl2) {
7395
+ if (existing.apiKey && existing.endpoint !== endpoint) return null;
7396
+ return consoleUrl2 ? { endpoint, consoleUrl: consoleUrl2 } : { endpoint };
7397
+ }
7398
+ function readLinkedRef(supabaseDir) {
7399
+ try {
7400
+ const ref = readFileSync3(join5(supabaseDir, ".temp", "project-ref"), "utf8").trim();
7401
+ return /^[a-z0-9-]+$/i.test(ref) ? ref : void 0;
7402
+ } catch {
7403
+ return void 0;
7404
+ }
7405
+ }
7406
+ function isInteractive2() {
7407
+ return !!(process.stdin.isTTY && process.stdout.isTTY);
7408
+ }
7409
+ async function resolveLlmKeys(opts, printOnly) {
7410
+ const fromEnv = (name) => {
7411
+ const v = process.env[name]?.trim();
7412
+ if (v && !printOnly) console.log(` Using ${name} from your shell.`);
7413
+ return v || void 0;
7414
+ };
7415
+ const anthropicKey = opts.anthropicKey || fromEnv("ANTHROPIC_API_KEY");
7416
+ const openaiKey = opts.openaiKey || fromEnv("OPENAI_API_KEY");
7417
+ if (anthropicKey || openaiKey || printOnly || !isInteractive2()) return { anthropicKey, openaiKey };
7418
+ const p5 = await import("@clack/prompts");
7419
+ const pasted = await p5.password({
7420
+ message: "Paste an Anthropic (sk-ant-\u2026) or OpenAI (sk-\u2026) API key, or press Enter to skip"
7421
+ });
7422
+ if (p5.isCancel(pasted)) process.exit(1);
7423
+ const key = (pasted ?? "").trim();
7424
+ if (!key) return {};
7425
+ return llmProviderOfKey(key) === "anthropic" ? { anthropicKey: key } : { openaiKey: key };
7426
+ }
7427
+ function printNoLlmNote() {
7428
+ console.log(" No LLM key set. Reports are still ingested, stored and shown in the console,");
7429
+ console.log(" and get a rule-based category and severity. Without a key there is no");
7430
+ console.log(" plain-English diagnosis, no fix drafts and no duplicate detection.");
7431
+ console.log(" Add one later: supabase secrets set ANTHROPIC_API_KEY=\u2026 (or OPENAI_API_KEY=\u2026),");
7432
+ console.log(" or per project in the console under Settings \u2192 API Keys.");
7433
+ }
7112
7434
  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");
7435
+ const root = resolve3(opts.cwd ?? ".");
7436
+ const serverDir = join5(root, "packages", "server");
7437
+ const supabaseDir = join5(serverDir, "supabase");
7438
+ const cliVersion = supabaseCliVersion();
7439
+ const printOnly = !!(opts.printCommands || !cliVersion);
7440
+ const consoleUrl2 = opts.consoleUrl || opts.adminBaseUrl;
7441
+ if (!printOnly && !existsSync3(join5(supabaseDir, "config.toml"))) {
7442
+ process.stderr.write(
7443
+ `\u2717 ${supabaseDir} has no config.toml. Run this from a clone of the mushi-mushi repo, or pass --cwd <repo root>.
7444
+ `
7445
+ );
7446
+ process.exit(1);
7122
7447
  }
7123
- const built = buildSelfhostSteps(opts, printOnly, randomBytes(32).toString("hex"));
7124
- if (!built.ok) {
7125
- process.stderr.write(`\u2717 ${built.error}
7126
- `);
7448
+ const linkedRef = readLinkedRef(supabaseDir);
7449
+ const ref = opts.projectRef || linkedRef;
7450
+ if (!printOnly && ref === CLOUD_PROJECT_REF) {
7451
+ process.stderr.write(
7452
+ "\u2717 This checkout is linked to the Mushi Mushi Cloud project. Pass --project-ref <your ref> to link your own.\n"
7453
+ );
7127
7454
  process.exit(1);
7128
7455
  }
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]}
7456
+ const projectRef = opts.projectRef ?? (printOnly && !linkedRef ? "your-project-ref" : void 0);
7457
+ const supabaseUrl = opts.supabaseUrl?.replace(/\/+$/, "") || (ref ? `https://${ref}.supabase.co` : void 0);
7458
+ if (!supabaseUrl && !printOnly) {
7459
+ process.stderr.write(
7460
+ "\u2717 Unknown Supabase project. Pass --project-ref <ref> (or --supabase-url <url> for a custom domain).\n"
7461
+ );
7462
+ process.exit(1);
7463
+ }
7464
+ const resolvedUrl = supabaseUrl ?? "https://<your-ref>.supabase.co";
7465
+ let endpoint = (opts.endpoint || `${resolvedUrl}/functions/v1/api`).replace(/\/+$/, "");
7466
+ if (!printOnly) {
7467
+ try {
7468
+ endpoint = assertEndpoint(endpoint);
7469
+ } catch (err) {
7470
+ process.stderr.write(`\u2717 ${err instanceof Error ? err.message : String(err)}
7143
7471
  `);
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
- }
7472
+ process.exit(1);
7155
7473
  }
7156
7474
  }
7157
- const endpoint = opts.endpoint || loadConfig().endpoint;
7158
- if (endpoint) {
7475
+ console.log("");
7476
+ if (printOnly) {
7477
+ console.log(cliVersion ? "--print-commands: nothing is run." : "supabase CLI not found.");
7478
+ console.log(`Run these from ${serverDir} (Supabase CLI 3.x; for 2.x use --linked instead of --remote):
7479
+ `);
7480
+ } else {
7481
+ console.log(`mushi selfhost up \u2014 deploying Mushi Mushi to ${resolvedUrl}
7482
+ `);
7483
+ }
7484
+ const llm = await resolveLlmKeys(opts, printOnly);
7485
+ const envToken = process.env["MUSHI_INTERNAL_CALLER_SECRET"]?.trim();
7486
+ const internalToken = envToken || randomBytes(32).toString("hex");
7487
+ const tmpDir = printOnly ? "." : mkdtempSync(join5(tmpdir(), "mushi-selfhost-"));
7488
+ try {
7489
+ const built = buildSelfhostSteps(
7490
+ {
7491
+ projectRef,
7492
+ supabaseUrl: resolvedUrl,
7493
+ ...llm,
7494
+ consoleUrl: consoleUrl2,
7495
+ skipDeploy: opts.skipDeploy,
7496
+ cliMajor: supabaseCliMajor(cliVersion)
7497
+ },
7498
+ printOnly,
7499
+ internalToken,
7500
+ printOnly ? "." : tmpDir
7501
+ );
7502
+ if (!built.ok) {
7503
+ process.stderr.write(`\u2717 ${built.error}
7504
+ `);
7505
+ process.exit(1);
7506
+ }
7159
7507
  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
- );
7508
+ console.log("# generate one secret and use it in BOTH files below");
7509
+ console.log(" $ openssl rand -hex 32");
7170
7510
  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");
7511
+ for (const step of built.steps) {
7512
+ console.log(`# ${step.label}`);
7513
+ for (const f of step.files ?? []) {
7514
+ console.log(` $ cat > ${f.path} <<'EOF'`);
7515
+ for (const line of f.content.trimEnd().split("\n")) console.log(` ${line}`);
7516
+ console.log(" EOF");
7180
7517
  }
7181
- } catch {
7182
- process.stdout.write("warn (non-critical)\n");
7518
+ const cleanup = (step.files ?? []).map((f) => f.path).join(" ");
7519
+ console.log(` $ ${selfhostStepCommand(step)}${cleanup ? ` && rm ${cleanup}` : ""}`);
7520
+ console.log("");
7183
7521
  }
7522
+ if (!llm.anthropicKey && !llm.openaiKey) {
7523
+ console.log("# LLM key (optional): add ANTHROPIC_API_KEY=\u2026 or OPENAI_API_KEY=\u2026 to mushi-secrets.env");
7524
+ console.log("");
7525
+ }
7526
+ 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");
7527
+ console.log("Then point the CLI at it and check it:");
7528
+ console.log(` mushi config endpoint ${endpoint}`);
7529
+ if (consoleUrl2) console.log(` mushi config consoleUrl ${consoleUrl2}`);
7530
+ console.log(` curl ${endpoint}/health`);
7531
+ console.log(` mushi login --endpoint ${endpoint}`);
7532
+ console.log(" mushi selfhost doctor");
7533
+ return;
7184
7534
  }
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) {
7535
+ if (!opts.yes) {
7536
+ if (!isInteractive2()) {
7537
+ process.stderr.write(
7538
+ "\u2717 selfhost up changes your Supabase project (migrations, secrets, functions). Pass --yes to confirm in a non-interactive shell.\n"
7539
+ );
7540
+ process.exit(1);
7541
+ }
7542
+ const p5 = await import("@clack/prompts");
7543
+ const ok = await p5.confirm({
7544
+ message: `Push migrations, set secrets${opts.skipDeploy ? "" : " and deploy every edge function"} on ${resolvedUrl}?`
7545
+ });
7546
+ if (p5.isCancel(ok) || !ok) process.exit(1);
7547
+ }
7548
+ if (envToken) console.log(" Using MUSHI_INTERNAL_CALLER_SECRET from your shell.");
7549
+ if (!llm.anthropicKey && !llm.openaiKey) printNoLlmNote();
7193
7550
  console.log("");
7194
- console.log("Running proof step\u2026");
7551
+ const secrets = [internalToken, llm.anthropicKey ?? "", llm.openaiKey ?? ""];
7552
+ let failed = false;
7553
+ for (const step of built.steps) {
7554
+ const result = runSupabase(step, { cwd: serverDir, secrets });
7555
+ if (result.ok) continue;
7556
+ process.stderr.write(` ${result.stderr.split("\n").slice(0, 3).join("\n ")}
7557
+ `);
7558
+ if (step.critical) {
7559
+ process.stderr.write("\n\u2717 Critical step failed: resolve the error above and re-run `mushi selfhost up`.\n");
7560
+ process.exit(1);
7561
+ }
7562
+ failed = true;
7563
+ }
7564
+ const config = loadConfig();
7565
+ const patch = selfhostConfigPatch(config, endpoint, consoleUrl2);
7566
+ if (patch) {
7567
+ saveConfig({ ...config, ...patch });
7568
+ console.log(` \u203A saved endpoint${patch.consoleUrl ? " + consoleUrl" : ""} to ${CONFIG_PATH} \u2713`);
7569
+ } else {
7570
+ console.log(` \u203A ${CONFIG_PATH} holds a key for ${config.endpoint}; left unchanged. Switch with:`);
7571
+ console.log(` mushi config endpoint ${endpoint}`);
7572
+ if (consoleUrl2) console.log(` mushi config consoleUrl ${consoleUrl2}`);
7573
+ }
7574
+ console.log("");
7575
+ console.log("Proof step\u2026");
7195
7576
  const probe = await probeEndpointHealth(endpoint).catch(() => null);
7196
7577
  if (!probe?.ok) {
7197
- console.log(" WARN /health did not return 200 \u2014 check function logs.");
7578
+ console.log(` WARN ${endpoint}/health did not return 200: check the function logs.`);
7198
7579
  } else {
7199
7580
  console.log(` OK /health ${probe.status} ${probe.latencyMs}ms`);
7200
7581
  }
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 {
7582
+ console.log("");
7583
+ if (failed) {
7584
+ console.log("Some steps failed (see above). Fix them and re-run, or deploy the rest by hand.");
7585
+ process.exit(2);
7586
+ }
7210
7587
  console.log("\u2713 selfhost up complete.");
7211
7588
  console.log("");
7212
7589
  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)");
7590
+ if (!consoleUrl2) {
7591
+ console.log(" 0. Serve the admin console (docs/SELF_HOSTED.md, step 4), then:");
7592
+ console.log(" mushi config consoleUrl <console url>");
7593
+ console.log(" Without it, `mushi login` opens the Mushi Mushi Cloud console.");
7594
+ }
7595
+ console.log(" 1. Sign up in your console (the first account owns the instance).");
7596
+ console.log(` 2. mushi login --endpoint ${endpoint}`);
7597
+ console.log(" 3. mushi selfhost doctor");
7598
+ console.log(" 4. mushi init (in your app repo)");
7599
+ } finally {
7600
+ if (!printOnly) rmSync(tmpDir, { recursive: true, force: true });
7218
7601
  }
7219
7602
  }
7603
+ var b64url = (buf) => Buffer.from(buf).toString("base64url");
7604
+ function mintSupabaseJwt(role, jwtSecret, nowSec) {
7605
+ const header = b64url(JSON.stringify({ alg: "HS256", typ: "JWT" }));
7606
+ const payload = b64url(
7607
+ JSON.stringify({ role, iss: "supabase", iat: nowSec, exp: nowSec + 5 * 365 * 24 * 3600 })
7608
+ );
7609
+ const sig = createHmac("sha256", jwtSecret).update(`${header}.${payload}`).digest("base64url");
7610
+ return `${header}.${payload}.${sig}`;
7611
+ }
7612
+ function buildComposeEnv(rand, nowSec, publicUrl = "http://localhost") {
7613
+ const jwtSecret = rand(32);
7614
+ return [
7615
+ "# Generated by `mushi selfhost secrets`. Keep this file private; never commit it.",
7616
+ `# Public address of the stack (Caddy serves the console and the API here).`,
7617
+ `MUSHI_PUBLIC_URL=${publicUrl}`,
7618
+ `MUSHI_SITE_ADDRESS=${publicUrl}`,
7619
+ "",
7620
+ "# Required: generated, do not edit by hand (the JWTs below are signed with JWT_SECRET).",
7621
+ `POSTGRES_PASSWORD=${rand(24)}`,
7622
+ `JWT_SECRET=${jwtSecret}`,
7623
+ `SUPABASE_ANON_KEY=${mintSupabaseJwt("anon", jwtSecret, nowSec)}`,
7624
+ `SUPABASE_SERVICE_ROLE_KEY=${mintSupabaseJwt("service_role", jwtSecret, nowSec)}`,
7625
+ `MUSHI_INTERNAL_CALLER_SECRET=${rand(32)}`,
7626
+ "",
7627
+ "# Optional: one LLM key turns on the plain-English diagnosis and fix drafts.",
7628
+ "# Either provider works. Leave both empty for rule-based triage only.",
7629
+ "ANTHROPIC_API_KEY=",
7630
+ "OPENAI_API_KEY=",
7631
+ ""
7632
+ ].join("\n");
7633
+ }
7634
+ function runSelfhostSecrets(opts) {
7635
+ const out = resolve3(opts.out);
7636
+ if (opts.publicUrl && !isPlainHttpUrl(opts.publicUrl)) {
7637
+ process.stderr.write(`\u2717 --public-url must be a plain http(s) URL (got: ${opts.publicUrl}).
7638
+ `);
7639
+ process.exit(1);
7640
+ }
7641
+ if (!existsSync3(dirname2(out))) {
7642
+ process.stderr.write(`\u2717 ${dirname2(out)} does not exist.
7643
+ `);
7644
+ process.exit(1);
7645
+ }
7646
+ const body = buildComposeEnv(
7647
+ (n) => randomBytes(n).toString("hex"),
7648
+ Math.floor(Date.now() / 1e3),
7649
+ opts.publicUrl?.replace(/\/+$/, "")
7650
+ );
7651
+ try {
7652
+ writeFileSync2(out, body, { mode: 384, flag: opts.force ? "w" : "wx" });
7653
+ } catch (err) {
7654
+ if (err.code === "EEXIST") {
7655
+ process.stderr.write(`\u2717 ${out} already exists. Pass --force to replace it (this rotates every secret).
7656
+ `);
7657
+ process.exit(1);
7658
+ }
7659
+ throw err;
7660
+ }
7661
+ console.log(`\u2713 Wrote ${out} (mode 600).`);
7662
+ console.log(" Generated: POSTGRES_PASSWORD, JWT_SECRET, SUPABASE_ANON_KEY, SUPABASE_SERVICE_ROLE_KEY,");
7663
+ console.log(" MUSHI_INTERNAL_CALLER_SECRET");
7664
+ console.log(" Optional: ANTHROPIC_API_KEY or OPENAI_API_KEY (edit the file)");
7665
+ }
7220
7666
  async function runSelfhostDoctor(opts) {
7221
7667
  const config = loadConfig();
7222
7668
  const endpoint = opts.endpoint || config.endpoint;
@@ -7274,44 +7720,34 @@ async function runSelfhostDoctor(opts) {
7274
7720
  }
7275
7721
  function registerSelfhostCommands(program2) {
7276
7722
  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(
7723
+ 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
7724
  "after",
7299
7725
  `
7300
7726
  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.
7727
+ mushi selfhost up --project-ref abcdefghijklmnopqrst
7728
+ mushi selfhost up --project-ref abcdefghijklmnopqrst --console-url https://mushi.example.com
7729
+ mushi selfhost up --print-commands # copy-paste mode
7730
+ mushi selfhost up --skip-deploy --yes # re-run migrations, secrets and runtime config
7731
+
7732
+ Requires the Supabase CLI (https://supabase.com/docs/guides/cli), logged in
7733
+ (\`supabase login\` or SUPABASE_ACCESS_TOKEN). Set SUPABASE_DB_PASSWORD if your
7734
+ CLI asks for the database password. MUSHI_INTERNAL_CALLER_SECRET in the shell
7735
+ is reused instead of generating a new one.`
7736
+ ).action(async (opts) => {
7737
+ await runSelfhostUp(opts);
7738
+ });
7739
+ 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(
7740
+ "after",
7741
+ `
7742
+ Generates POSTGRES_PASSWORD, JWT_SECRET, MUSHI_INTERNAL_CALLER_SECRET, and the
7743
+ anon / service_role JWTs signed with JWT_SECRET. Values are never printed.
7307
7744
 
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
- );
7745
+ Examples:
7746
+ npx mushi-mushi selfhost secrets
7747
+ npx mushi-mushi selfhost secrets --public-url https://mushi.example.com`
7748
+ ).action((opts) => {
7749
+ runSelfhostSecrets(opts);
7750
+ });
7315
7751
  selfhost.command("doctor").description(
7316
7752
  "Check the health of a self-hosted deployment (calls GET /v1/admin/doctor)"
7317
7753
  ).option(
@@ -7365,11 +7801,11 @@ function registerProfileCommands(program2) {
7365
7801
 
7366
7802
  // src/commands/radar.ts
7367
7803
  import { execFileSync } from "child_process";
7368
- import { resolve as resolve4 } from "path";
7804
+ import { resolve as resolve5 } from "path";
7369
7805
 
7370
7806
  // 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";
7807
+ import { readdirSync as readdirSync2, readFileSync as readFileSync4, statSync as statSync2 } from "fs";
7808
+ import { isAbsolute, join as join6, relative as relative2, resolve as resolve4, sep } from "path";
7373
7809
 
7374
7810
  // src/radar/repo-scan-core.ts
7375
7811
  var REPO_SCAN_PATHS = [
@@ -7517,7 +7953,7 @@ function listRepoFiles(root, limit = MAX_FILES) {
7517
7953
  return;
7518
7954
  }
7519
7955
  if (e.isSymbolicLink()) continue;
7520
- const full = join5(dir, e.name);
7956
+ const full = join6(dir, e.name);
7521
7957
  if (e.isDirectory()) {
7522
7958
  if (!SKIP_DIRS.has(e.name)) walk2(full);
7523
7959
  } else if (e.isFile()) {
@@ -7554,7 +7990,7 @@ function findBundleRoots(root) {
7554
7990
  }
7555
7991
  for (const e of entries) {
7556
7992
  if (!e.isDirectory() || e.isSymbolicLink()) continue;
7557
- const full = join5(dir, e.name);
7993
+ const full = join6(dir, e.name);
7558
7994
  const rel = relative2(root, full).split(sep).join("/");
7559
7995
  if (BUNDLE_DIR_NAMES.has(e.name)) {
7560
7996
  roots.push(rel);
@@ -7564,7 +8000,7 @@ function findBundleRoots(root) {
7564
8000
  if (clientParts) {
7565
8001
  for (const part of clientParts) {
7566
8002
  try {
7567
- if (statSync2(join5(full, part)).isDirectory()) roots.push(`${rel}/${part}`);
8003
+ if (statSync2(join6(full, part)).isDirectory()) roots.push(`${rel}/${part}`);
7568
8004
  } catch {
7569
8005
  }
7570
8006
  }
@@ -7592,7 +8028,7 @@ function isClientSafeMatch(m) {
7592
8028
  function bundleRootsFromFlags(root, dirs) {
7593
8029
  const roots = [];
7594
8030
  for (const d of dirs) {
7595
- const full = resolve3(root, d);
8031
+ const full = resolve4(root, d);
7596
8032
  const rel = relative2(root, full);
7597
8033
  if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) throw new Error(`--bundle-dir ${d} must be a folder inside ${root}`);
7598
8034
  if (!statSync2(full).isDirectory()) throw new Error(`--bundle-dir ${d} is not a folder`);
@@ -7600,7 +8036,7 @@ function bundleRootsFromFlags(root, dirs) {
7600
8036
  }
7601
8037
  return [...new Set(roots)].sort();
7602
8038
  }
7603
- function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), bundleDirs) {
8039
+ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync4(p5, "utf8"), bundleDirs) {
7604
8040
  const roots = bundleDirs && bundleDirs.length > 0 ? bundleRootsFromFlags(root, bundleDirs) : findBundleRoots(root);
7605
8041
  const out = { roots, scannedFiles: 0, truncated: false, unreadable: 0, findings: [] };
7606
8042
  const walk2 = (dir) => {
@@ -7618,7 +8054,7 @@ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), b
7618
8054
  return;
7619
8055
  }
7620
8056
  if (e.isSymbolicLink()) continue;
7621
- const full = join5(dir, e.name);
8057
+ const full = join6(dir, e.name);
7622
8058
  if (e.isDirectory()) {
7623
8059
  if (!BUNDLE_SKIP_DIRS.has(e.name)) walk2(full);
7624
8060
  continue;
@@ -7642,17 +8078,17 @@ function scanBuiltBundles(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), b
7642
8078
  }
7643
8079
  }
7644
8080
  };
7645
- for (const r of roots) walk2(join5(root, r));
8081
+ for (const r of roots) walk2(join6(root, r));
7646
8082
  return out;
7647
8083
  }
7648
- function scanLocalRepo(root, readFile3 = (p5) => readFileSync3(p5, "utf8"), opts = {}) {
8084
+ function scanLocalRepo(root, readFile3 = (p5) => readFileSync4(p5, "utf8"), opts = {}) {
7649
8085
  const { files, truncated, unreadable: unreadableDirs } = listRepoFiles(root);
7650
8086
  let unreadable = unreadableDirs;
7651
8087
  const findings = [];
7652
8088
  const configFiles = {};
7653
8089
  let scannedFiles = 0;
7654
8090
  for (const rel of files) {
7655
- const full = join5(root, rel);
8091
+ const full = join6(root, rel);
7656
8092
  let size = 0;
7657
8093
  try {
7658
8094
  size = statSync2(full).size;
@@ -7742,7 +8178,7 @@ Add one step to your existing CI job, after the build step (no new job needed):
7742
8178
  - run: npx mushi-mushi radar scan --push
7743
8179
  env:
7744
8180
  MUSHI_API_KEY: \${{ secrets.MUSHI_INGEST_KEY }}`).action(async (opts) => {
7745
- const root = resolve4(opts.dir);
8181
+ const root = resolve5(opts.dir);
7746
8182
  let scan;
7747
8183
  try {
7748
8184
  scan = scanLocalRepo(root, void 0, { bundleDirs: opts.bundleDir });
@@ -7807,13 +8243,13 @@ Add one step to your existing CI job, after the build step (no new job needed):
7807
8243
 
7808
8244
  // src/commands/recipe.ts
7809
8245
  import { execFileSync as execFileSync3 } from "child_process";
7810
- import { writeFileSync as writeFileSync3 } from "fs";
7811
- import { join as join7, resolve as resolve5 } from "path";
8246
+ import { writeFileSync as writeFileSync4 } from "fs";
8247
+ import { join as join8, resolve as resolve6 } from "path";
7812
8248
 
7813
8249
  // src/recipe/local.ts
7814
8250
  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";
8251
+ import { existsSync as existsSync4, readdirSync as readdirSync3, readFileSync as readFileSync5, statSync as statSync3 } from "fs";
8252
+ import { join as join7, relative as relative3, sep as sep2 } from "path";
7817
8253
 
7818
8254
  // src/recipe/engine/design-color.ts
7819
8255
  var clamp01 = (n) => Math.min(1, Math.max(0, n));
@@ -8949,7 +9385,7 @@ function readScanTokens(manifest, treePaths, readFile3) {
8949
9385
  }
8950
9386
 
8951
9387
  // src/file-io.ts
8952
- import { closeSync, fstatSync, openSync, readSync, writeFileSync as writeFileSync2 } from "fs";
9388
+ import { closeSync, fstatSync, openSync, readSync, writeFileSync as writeFileSync3 } from "fs";
8953
9389
  var CHUNK_BYTES = 64 * 1024;
8954
9390
  function readTextFileCapped(path, maxBytes) {
8955
9391
  let fd;
@@ -8985,7 +9421,7 @@ function writeUserOutputFile(path, text2, opts) {
8985
9421
  throw new MushiCliError("E_API_ERROR", `The server sent more than ${Math.round(opts.maxBytes / (1024 * 1024))} MB, so nothing was written.`);
8986
9422
  }
8987
9423
  try {
8988
- writeFileSync2(path, text2, { encoding: "utf8", mode: opts.mode ?? 420 });
9424
+ writeFileSync3(path, text2, { encoding: "utf8", mode: opts.mode ?? 420 });
8989
9425
  } catch (err) {
8990
9426
  throw new MushiCliError("E_FILE_PERMISSION", `Could not write ${path}`, "pick a path you can write to", err);
8991
9427
  }
@@ -9131,7 +9567,7 @@ function walk(root, limit = 2e4) {
9131
9567
  for (const e of entries) {
9132
9568
  if (out.length >= limit) return;
9133
9569
  if (e.isSymbolicLink()) continue;
9134
- const full = join6(dir, e.name);
9570
+ const full = join7(dir, e.name);
9135
9571
  if (e.isDirectory()) {
9136
9572
  if (!SKIP.has(e.name)) go(full);
9137
9573
  } else if (e.isFile()) out.push(relative3(root, full).split(sep2).join("/"));
@@ -9151,7 +9587,7 @@ function listRepoFiles2(root) {
9151
9587
  const entries = [];
9152
9588
  for (const p5 of paths) {
9153
9589
  try {
9154
- const st = statSync3(join6(root, p5));
9590
+ const st = statSync3(join7(root, p5));
9155
9591
  if (st.isFile()) entries.push({ path: p5, size: st.size });
9156
9592
  } catch {
9157
9593
  }
@@ -9160,7 +9596,7 @@ function listRepoFiles2(root) {
9160
9596
  }
9161
9597
  function readJson(path) {
9162
9598
  try {
9163
- return JSON.parse(readFileSync4(path, "utf8"));
9599
+ return JSON.parse(readFileSync5(path, "utf8"));
9164
9600
  } catch {
9165
9601
  return null;
9166
9602
  }
@@ -9197,7 +9633,7 @@ var DEPLOY_STEPS = [
9197
9633
  ];
9198
9634
  var WRITES_FILE = /\b(writeFileSync|writeFile|createWriteStream|outputFileSync|outputFile|outputJsonSync|outputJson|writeJsonSync|writeJson|writeTextFile|write_text)\b/;
9199
9635
  function readCapped(root, path) {
9200
- const f = readTextFileCapped(join6(root, path), MAX_READ_BYTES);
9636
+ const f = readTextFileCapped(join7(root, path), MAX_READ_BYTES);
9201
9637
  return f.kind === "file" ? f.text : null;
9202
9638
  }
9203
9639
  function workspacePatterns(root, pkg) {
@@ -9260,7 +9696,7 @@ function starterManifest(root) {
9260
9696
  const tracked = listRepoFiles2(root).map((e) => e.path);
9261
9697
  const files = tracked.length ? tracked : walk(root);
9262
9698
  const fileSet = new Set(files);
9263
- const pkg = readJson(join6(root, "package.json"));
9699
+ const pkg = readJson(join7(root, "package.json"));
9264
9700
  const deps2 = { ...pkg?.dependencies ?? {}, ...pkg?.devDependencies ?? {} };
9265
9701
  const rootScripts = Object.entries(pkg?.scripts ?? {}).filter((e) => typeof e[1] === "string");
9266
9702
  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 +9750,7 @@ function starterManifest(root) {
9314
9750
  }))
9315
9751
  };
9316
9752
  }
9317
- const envExample = ENV_EXAMPLES.find((p5) => existsSync3(join6(root, p5)));
9753
+ const envExample = ENV_EXAMPLES.find((p5) => existsSync4(join7(root, p5)));
9318
9754
  if (envExample) manifest.env = { environments: ["production"], required: [], example: envExample };
9319
9755
  const sourceDirs = tokens.filter((t) => t.role === "source").map((t) => `${t.path.split("/").slice(0, -1).join("/") || "."}/**`);
9320
9756
  manifest.change = { allowPaths: [MANIFEST, ...new Set(sourceDirs)] };
@@ -9330,13 +9766,13 @@ function localReader(root) {
9330
9766
  return (path, maxBytes) => {
9331
9767
  const safe = normalizeRepoPath(path);
9332
9768
  if (!safe) return { kind: "absent" };
9333
- return readTextFileCapped(join6(root, safe), maxBytes);
9769
+ return readTextFileCapped(join7(root, safe), maxBytes);
9334
9770
  };
9335
9771
  }
9336
9772
  function checkRecipe(root) {
9337
9773
  const issues = [];
9338
9774
  const files = {};
9339
- const path = join6(root, MANIFEST);
9775
+ const path = join7(root, MANIFEST);
9340
9776
  const fail = (message) => ({ ok: false, manifest: null, issues: [...issues, { severity: "error", message, path: MANIFEST }], tokenCount: 0, findings: [], design: null, files });
9341
9777
  const manifestRead = readTextFileCapped(path, MAX_MANIFEST_BYTES);
9342
9778
  if (manifestRead.kind === "absent") return fail(`No ${MANIFEST} at the repo root. Run \`mushi recipe init\` to write one.`);
@@ -9518,10 +9954,10 @@ function headBranch(dir) {
9518
9954
  function registerRecipeCommands(program2) {
9519
9955
  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
9956
  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);
9957
+ const root = resolve6(opts.dir);
9958
+ const target = join8(root, MANIFEST);
9523
9959
  try {
9524
- writeFileSync3(target, `${JSON.stringify(starterManifest(root), null, 2)}
9960
+ writeFileSync4(target, `${JSON.stringify(starterManifest(root), null, 2)}
9525
9961
  `, { flag: opts.force ? "w" : "wx" });
9526
9962
  } catch (err) {
9527
9963
  if (err.code !== "EEXIST") throw err;
@@ -9533,7 +9969,7 @@ function registerRecipeCommands(program2) {
9533
9969
  console.log(`Wrote ${MANIFEST}. Check the guesses, then run \`mushi recipe check\`.`);
9534
9970
  });
9535
9971
  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);
9972
+ const root = resolve6(opts.dir);
9537
9973
  const maxScore = opts.maxScore === void 0 ? null : Number(opts.maxScore);
9538
9974
  if (maxScore !== null && (!Number.isInteger(maxScore) || maxScore < 0 || maxScore > 100)) {
9539
9975
  process.stderr.write("error: --max-score must be a whole number from 0 to 100.\n");
@@ -9628,28 +10064,28 @@ function registerRecipeCommands(program2) {
9628
10064
  }
9629
10065
 
9630
10066
  // src/commands/store.ts
9631
- import { existsSync as existsSync4, readFileSync as readFileSync5 } from "fs";
9632
- import { join as join9, resolve as resolve6 } from "path";
10067
+ import { existsSync as existsSync5, readFileSync as readFileSync6 } from "fs";
10068
+ import { join as join10, resolve as resolve7 } from "path";
9633
10069
 
9634
10070
  // src/store/pull.ts
9635
10071
  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) {
10072
+ import { mkdirSync, writeFileSync as writeFileSync5 } from "fs";
10073
+ import { dirname as dirname3, join as join9 } from "path";
10074
+ function b64url2(buf) {
9639
10075
  return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
9640
10076
  }
9641
10077
  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" }));
10078
+ const head = b64url2(JSON.stringify({ alg: "ES256", kid: keyId, typ: "JWT" }));
10079
+ const body = b64url2(JSON.stringify({ iss: issuerId, iat: nowSec, exp: nowSec + 1200, aud: "appstoreconnect-v1" }));
9644
10080
  const sig = cryptoSign("sha256", Buffer.from(`${head}.${body}`), { key: privateKeyPem, dsaEncoding: "ieee-p1363" });
9645
- return `${head}.${body}.${b64url(sig)}`;
10081
+ return `${head}.${body}.${b64url2(sig)}`;
9646
10082
  }
9647
10083
  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 }));
10084
+ const head = b64url2(JSON.stringify({ alg: "RS256", typ: "JWT" }));
10085
+ 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
10086
  const signer = createSign("RSA-SHA256");
9651
10087
  signer.update(`${head}.${body}`);
9652
- return `${head}.${body}.${b64url(signer.sign(privateKeyPem))}`;
10088
+ return `${head}.${body}.${b64url2(signer.sign(privateKeyPem))}`;
9653
10089
  }
9654
10090
  async function json(fetchImpl, url, init) {
9655
10091
  const res = await fetchImpl(url, init);
@@ -9708,9 +10144,9 @@ function writeListing(root, listingDir, files) {
9708
10144
  const written = [];
9709
10145
  for (const [rel, text2] of Object.entries(files)) {
9710
10146
  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}
10147
+ const path = join9(root, listingDir, rel);
10148
+ mkdirSync(dirname3(path), { recursive: true });
10149
+ writeFileSync5(path, text2.endsWith("\n") ? text2 : `${text2}
9714
10150
  `);
9715
10151
  written.push(`${listingDir}/${rel}`);
9716
10152
  }
@@ -9733,10 +10169,10 @@ function renderStoreReviews(d) {
9733
10169
  return lines;
9734
10170
  }
9735
10171
  function readManifestStore(root) {
9736
- const path = join9(root, "mushi.recipe.json");
9737
- if (!existsSync4(path)) return null;
10172
+ const path = join10(root, "mushi.recipe.json");
10173
+ if (!existsSync5(path)) return null;
9738
10174
  try {
9739
- const m = JSON.parse(readFileSync5(path, "utf8"));
10175
+ const m = JSON.parse(readFileSync6(path, "utf8"));
9740
10176
  return {
9741
10177
  listingDir: (m.store?.listingDir ?? "fastlane/metadata").replace(/\/+$/, ""),
9742
10178
  appleId: m.store?.ios?.appleId ?? null,
@@ -9754,7 +10190,7 @@ Mushi never holds a key that can publish. After this, change the listing in
9754
10190
  the repo; your own CI (fastlane deliver / supply, or EAS) publishes it.
9755
10191
  Reads store.listingDir, store.ios.appleId and store.android.package from
9756
10192
  mushi.recipe.json.`).action(async (opts) => {
9757
- const root = resolve6(opts.dir);
10193
+ const root = resolve7(opts.dir);
9758
10194
  const cfg = readManifestStore(root);
9759
10195
  if (!cfg) {
9760
10196
  process.stderr.write("error: no readable mushi.recipe.json. Run `mushi recipe init` first.\n");
@@ -9768,7 +10204,7 @@ mushi.recipe.json.`).action(async (opts) => {
9768
10204
  const keyPath = opts.ascKeyPath ?? process.env.MUSHI_ASC_KEY_PATH;
9769
10205
  if (cfg.appleId && keyId && issuerId && keyPath) {
9770
10206
  try {
9771
- const ios = await pullAppStore(fetch, cfg.appleId, { keyId, issuerId, privateKey: readFileSync5(keyPath, "utf8") }, now);
10207
+ const ios = await pullAppStore(fetch, cfg.appleId, { keyId, issuerId, privateKey: readFileSync6(keyPath, "utf8") }, now);
9772
10208
  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
10209
  Object.assign(files, ios);
9774
10210
  } catch (err) {
@@ -9782,7 +10218,7 @@ mushi.recipe.json.`).action(async (opts) => {
9782
10218
  const playPath = opts.playKeyPath ?? process.env.GOOGLE_APPLICATION_CREDENTIALS;
9783
10219
  if (cfg.androidPackage && playPath) {
9784
10220
  try {
9785
- Object.assign(files, await pullPlay(fetch, cfg.androidPackage, JSON.parse(readFileSync5(playPath, "utf8")), now));
10221
+ Object.assign(files, await pullPlay(fetch, cfg.androidPackage, JSON.parse(readFileSync6(playPath, "utf8")), now));
9786
10222
  } catch (err) {
9787
10223
  process.stderr.write(`Google Play: ${err.message}
9788
10224
  `);
@@ -10426,7 +10862,7 @@ function recordingBody(opts) {
10426
10862
  }
10427
10863
 
10428
10864
  // src/commands/releases.ts
10429
- import { readFileSync as readFileSync6 } from "fs";
10865
+ import { readFileSync as readFileSync7 } from "fs";
10430
10866
  var DRAFT_TIMEOUT_MS = 12e4;
10431
10867
  var PUBLISH_TIMEOUT_MS = 6e4;
10432
10868
  function renderReleaseList(rows, total) {
@@ -10462,7 +10898,7 @@ function renderCalendar(data) {
10462
10898
  function readBody(path) {
10463
10899
  if (!path) return void 0;
10464
10900
  try {
10465
- return readFileSync6(path, "utf8");
10901
+ return readFileSync7(path, "utf8");
10466
10902
  } catch (err) {
10467
10903
  throw new MushiCliError("E_FILE_NOT_FOUND", `Could not read ${path}`, "pass a Markdown file you can read", err);
10468
10904
  }
@@ -11326,7 +11762,7 @@ var STATUS_LABEL = {
11326
11762
  pending: "queued"
11327
11763
  };
11328
11764
  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}$/;
11765
+ var KEY_RE2 = /^[a-z0-9][a-z0-9-]{0,79}$/;
11330
11766
  function projectId() {
11331
11767
  const config = requireConfig({ needsProject: true });
11332
11768
  return { config, pid: encodeURIComponent(config.projectId) };
@@ -11378,7 +11814,7 @@ function registerUxRunsCommands(program2) {
11378
11814
  }
11379
11815
  });
11380
11816
  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).`);
11817
+ 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
11818
  const { config, pid } = projectId();
11383
11819
  const result = await apiCall(
11384
11820
  `/v1/admin/projects/${pid}/ux-runs/${requireRunId(runId)}/surfaces/${screen}/report`,
@@ -11396,9 +11832,9 @@ function registerUxRunsCommands(program2) {
11396
11832
 
11397
11833
  // src/commands/runner.ts
11398
11834
  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";
11835
+ 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
11836
  import { arch as nodeArch, userInfo } from "os";
11401
- import { dirname as dirname3, join as join10, resolve as resolve7 } from "path";
11837
+ import { dirname as dirname4, join as join11, resolve as resolve8 } from "path";
11402
11838
  import * as p3 from "@clack/prompts";
11403
11839
 
11404
11840
  // src/runner/hooks.ts
@@ -12781,7 +13217,7 @@ function readIfPresent(path) {
12781
13217
  throw err;
12782
13218
  }
12783
13219
  try {
12784
- return readFileSync7(fd, "utf8");
13220
+ return readFileSync8(fd, "utf8");
12785
13221
  } finally {
12786
13222
  closeSync2(fd);
12787
13223
  }
@@ -12806,7 +13242,7 @@ var deps = {
12806
13242
  host: nodeHostIO,
12807
13243
  gh: nodeGh,
12808
13244
  runStep: defaultRunStep,
12809
- systemdRunning: () => existsSync5("/run/systemd/system"),
13245
+ systemdRunning: () => existsSync6("/run/systemd/system"),
12810
13246
  ghAuthText: () => ghAuthStatus().text
12811
13247
  };
12812
13248
  function githubTokenForBill() {
@@ -12827,8 +13263,8 @@ function readRunnerKeyForHeartbeat(keyFile) {
12827
13263
  if (fromEnv) return fromEnv;
12828
13264
  const credDir = process.env["CREDENTIALS_DIRECTORY"];
12829
13265
  const paths = [
12830
- ...credDir ? [join10(credDir, RUNNER_KEY_CREDENTIAL)] : [],
12831
- keyFile ? resolve7(keyFile) : RUNNER_KEY_PATH
13266
+ ...credDir ? [join11(credDir, RUNNER_KEY_CREDENTIAL)] : [],
13267
+ keyFile ? resolve8(keyFile) : RUNNER_KEY_PATH
12832
13268
  ];
12833
13269
  for (const path of paths) {
12834
13270
  const key = deps.host.readFile(path)?.trim();
@@ -12881,7 +13317,7 @@ function heartbeatCommand() {
12881
13317
  if (entry && !entry.includes("/_npx/") && entry.endsWith(".js")) {
12882
13318
  return [process.execPath, entry, "runner", "heartbeat", "--once"];
12883
13319
  }
12884
- return [join10(dirname3(process.execPath), "npx"), "-y", `@mushi-mushi/cli@${MUSHI_CLI_VERSION}`, "runner", "heartbeat", "--once"];
13320
+ return [join11(dirname4(process.execPath), "npx"), "-y", `@mushi-mushi/cli@${MUSHI_CLI_VERSION}`, "runner", "heartbeat", "--once"];
12885
13321
  }
12886
13322
  function safeRealpath(path) {
12887
13323
  try {
@@ -13196,19 +13632,19 @@ The key comes from MUSHI_RUNNER_KEY, or a new one is created with your CLI key
13196
13632
  (needs mcp:write). It is saved in <dir>/${HOOKS_DIR_NAME}/key with mode 0600,
13197
13633
  never in the scripts, and never printed.
13198
13634
  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"))) {
13635
+ const dir = resolve8(opts.dir);
13636
+ if (!existsSync6(join11(dir, "config.sh")) && !existsSync6(join11(dir, "run.sh"))) {
13201
13637
  throw new MushiCliError("E_INVALID_INPUT", `${dir} does not look like a runner folder (no config.sh or run.sh).`);
13202
13638
  }
13203
13639
  const config = loadConfig();
13204
13640
  const endpoint = config.endpoint ?? CLOUD_API_ENDPOINT;
13205
13641
  const hostId = hostIdOrThrow();
13206
- const hooksDir = join10(dir, HOOKS_DIR_NAME);
13642
+ const hooksDir = join11(dir, HOOKS_DIR_NAME);
13207
13643
  const files = {
13208
- started: join10(hooksDir, "job-started.sh"),
13209
- completed: join10(hooksDir, "job-completed.sh")
13644
+ started: join11(hooksDir, "job-started.sh"),
13645
+ completed: join11(hooksDir, "job-completed.sh")
13210
13646
  };
13211
- const envPath = join10(dir, ".env");
13647
+ const envPath = join11(dir, ".env");
13212
13648
  const envBefore = readIfPresent(envPath);
13213
13649
  const merged = mergeRunnerEnv(envBefore, files, opts.force);
13214
13650
  if (merged.conflicts.length) {
@@ -13217,7 +13653,7 @@ GitHub docs: https://docs.github.com/en/actions/how-tos/manage-runners/self-host
13217
13653
  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
13654
  }
13219
13655
  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).`);
13656
+ console.log(`Would write ${files.started} and ${files.completed} (mode 0755), and ${join11(hooksDir, "key")} (mode 0600, a runner:write key, not shown).`);
13221
13657
  const added = (merged.text ?? "").split("\n").filter((l) => l && !envBefore.split(/\r?\n/).includes(l));
13222
13658
  console.log(added.length ? `Would add to ${envPath}:
13223
13659
  ${added.map((l) => ` ${l}`).join("\n")}` : `${envPath} already has the hooks.`);
@@ -13229,16 +13665,16 @@ ${added.map((l) => ` ${l}`).join("\n")}` : `${envPath} already has the hooks.`)
13229
13665
  });
13230
13666
  mkdirSync2(hooksDir, { recursive: true, mode: 493 });
13231
13667
  for (const phase of ["started", "completed"]) {
13232
- writeFileSync5(files[phase], hookScript({ phase, endpoint, hostId }), { mode: 493 });
13668
+ writeFileSync6(files[phase], hookScript({ phase, endpoint, hostId }), { mode: 493 });
13233
13669
  }
13234
- const keyPath = join10(hooksDir, "key");
13235
- writeFileSync5(keyPath, `${runnerKey}
13670
+ const keyPath = join11(hooksDir, "key");
13671
+ writeFileSync6(keyPath, `${runnerKey}
13236
13672
  `, { mode: 384 });
13237
13673
  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
13674
  if (merged.text) {
13239
13675
  const fd = openSync2(envPath, fsConstants.O_RDWR | fsConstants.O_CREAT | (fsConstants.O_NOFOLLOW ?? 0), 420);
13240
13676
  try {
13241
- const now = mergeRunnerEnv(readFileSync7(fd, "utf8"), files, opts.force);
13677
+ const now = mergeRunnerEnv(readFileSync8(fd, "utf8"), files, opts.force);
13242
13678
  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
13679
  if (now.text) {
13244
13680
  ftruncateSync(fd, 0);
@@ -13269,19 +13705,19 @@ runner. Creating one needs a CLI key with mcp:write (mushi login --upgrade-scope
13269
13705
  ${RUNNER_KEY_PATH} is root-only; the heartbeat timer gets it from systemd.`).action(async (opts) => {
13270
13706
  const config = requireConfig();
13271
13707
  const key = await mintRunnerKeyOnly(config, opts.project, opts.label);
13272
- const out = resolve7(opts.out);
13273
- const dir = dirname3(out);
13708
+ const out = resolve8(opts.out);
13709
+ const dir = dirname4(out);
13274
13710
  const writable = (() => {
13275
13711
  try {
13276
- accessSync(existsSync5(dir) ? dir : dirname3(dir), fsConstants.W_OK);
13277
- return existsSync5(dir) || process.getuid?.() === 0;
13712
+ accessSync(existsSync6(dir) ? dir : dirname4(dir), fsConstants.W_OK);
13713
+ return existsSync6(dir) || process.getuid?.() === 0;
13278
13714
  } catch {
13279
13715
  return false;
13280
13716
  }
13281
13717
  })();
13282
13718
  if (writable) {
13283
13719
  mkdirSync2(dir, { recursive: true, mode: 448 });
13284
- writeFileSync5(out, `${key}
13720
+ writeFileSync6(out, `${key}
13285
13721
  `, { mode: 384 });
13286
13722
  chmodSync(out, 384);
13287
13723
  } else {
@@ -13505,8 +13941,8 @@ async function fixAll(config, opts) {
13505
13941
  }
13506
13942
 
13507
13943
  // src/commands/verify.ts
13508
- import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "fs";
13509
- import { dirname as dirname4, resolve as resolve8 } from "path";
13944
+ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync7 } from "fs";
13945
+ import { dirname as dirname5, resolve as resolve9 } from "path";
13510
13946
  var WORKFLOW_MAX_BYTES = 64 * 1024;
13511
13947
  var WORKFLOW_SHAPE = /uses:\s*kensaurus\/mushi-mushi\/\.github\/actions\/fix-verify@/;
13512
13948
  var VERIFY_WORKFLOW_PATH = ".github/workflows/mushi-verify.yml";
@@ -13532,13 +13968,13 @@ Verified merge. Docs: https://kensaur.us/mushi-mushi/docs/admin/verified-merge`)
13532
13968
  if (text2.length > WORKFLOW_MAX_BYTES || !WORKFLOW_SHAPE.test(text2) || text2.includes("\0")) {
13533
13969
  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
13970
  }
13535
- const out = opts.out ? resolve8(opts.out) : null;
13971
+ const out = opts.out ? resolve9(opts.out) : null;
13536
13972
  if (out && !/\.ya?ml$/i.test(out)) {
13537
13973
  throw new MushiCliError("E_INVALID_INPUT", `--out must be a .yml or .yaml file: ${out}`, "For example: --out .github/workflows/mushi-verify.yml");
13538
13974
  }
13539
13975
  if (out) {
13540
- mkdirSync3(dirname4(out), { recursive: true });
13541
- writeFileSync6(out, text2);
13976
+ mkdirSync3(dirname5(out), { recursive: true });
13977
+ writeFileSync7(out, text2);
13542
13978
  }
13543
13979
  if (outputIsJson(opts.json)) {
13544
13980
  console.log(JSON.stringify({ ok: true, projectId: projectId2, yaml: text2, ...out ? { path: out } : {} }, null, 2));
@@ -13555,9 +13991,9 @@ Verified merge. Docs: https://kensaur.us/mushi-mushi/docs/admin/verified-merge`)
13555
13991
 
13556
13992
  // src/commands/worker.ts
13557
13993
  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";
13994
+ 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
13995
  import { homedir, hostname } from "os";
13560
- import { dirname as dirname5, join as join12, resolve as resolve9 } from "path";
13996
+ import { dirname as dirname6, join as join13, resolve as resolve10 } from "path";
13561
13997
  import * as p4 from "@clack/prompts";
13562
13998
 
13563
13999
  // src/worker/flags-view.ts
@@ -13607,7 +14043,7 @@ function flagLines(flags) {
13607
14043
  }
13608
14044
 
13609
14045
  // src/worker/install.ts
13610
- import { join as join11 } from "path";
14046
+ import { join as join12 } from "path";
13611
14047
  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
14048
  function parseLanesConf(text2, cloneRoot) {
13613
14049
  const lanes = [];
@@ -13626,7 +14062,7 @@ function parseLanesConf(text2, cloneRoot) {
13626
14062
  else if (mode === "queue" || mode === "fix") initial.mode = "fix";
13627
14063
  else if (mode === "off") Object.assign(initial, { mode: "fix", paused: true });
13628
14064
  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 });
14065
+ lanes.push({ name, projectId: projectId2.toLowerCase(), repoDir: join12(cloneRoot, clone), initial });
13630
14066
  }
13631
14067
  if (lanes.length === 0) throw new MushiCliError("E_INVALID_INPUT", "lanes.conf lists no lanes.");
13632
14068
  return lanes;
@@ -13664,7 +14100,7 @@ function windowsTaskArgs(o) {
13664
14100
  }
13665
14101
 
13666
14102
  // src/commands/worker.ts
13667
- var UNIT_PATH = join12(process.env["XDG_CONFIG_HOME"] || join12(homedir(), ".config"), "systemd", "user", SYSTEMD_UNIT_NAME);
14103
+ var UNIT_PATH = join13(process.env["XDG_CONFIG_HOME"] || join13(homedir(), ".config"), "systemd", "user", SYSTEMD_UNIT_NAME);
13668
14104
  function laneDone(l) {
13669
14105
  if (l.config.mode === "conflicts") return l.counts7d.merges ?? 0;
13670
14106
  if (l.config.mode === "audit") return l.counts7d.filed ?? 0;
@@ -13680,19 +14116,19 @@ function cliPath() {
13680
14116
  try {
13681
14117
  return realpathSync2(argv1);
13682
14118
  } catch {
13683
- return resolve9(argv1);
14119
+ return resolve10(argv1);
13684
14120
  }
13685
14121
  }
13686
14122
  function lanesFromOptions(opts) {
13687
14123
  if (opts.lanesConf) {
13688
- const root = resolve9(opts.cloneRoot ?? join12(homedir(), ".cache", "mushi-work"));
13689
- return parseLanesConf(readFileSync8(resolve9(opts.lanesConf), "utf8"), root);
14124
+ const root = resolve10(opts.cloneRoot ?? join13(homedir(), ".cache", "mushi-work"));
14125
+ return parseLanesConf(readFileSync9(resolve10(opts.lanesConf), "utf8"), root);
13690
14126
  }
13691
14127
  if (!opts.lane || !opts.project || !opts.repoDir) {
13692
14128
  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
14129
  }
13694
14130
  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 } } : {} }];
14131
+ return [{ name: opts.lane, projectId: requireUuid(opts.project, "--project"), repoDir: resolve10(opts.repoDir), ...opts.model ? { initial: { model: opts.model } } : {} }];
13696
14132
  }
13697
14133
  function printLanes(cfg) {
13698
14134
  for (const l of cfg.lanes) {
@@ -13702,7 +14138,7 @@ function printLanes(cfg) {
13702
14138
  }
13703
14139
  function registerWorkerCommands(program2) {
13704
14140
  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) => {
14141
+ 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
14142
  const cli = loadConfig();
13707
14143
  const endpoint = opts.endpoint ?? process.env["MUSHI_API_ENDPOINT"] ?? cli.endpoint;
13708
14144
  let stopAt = null;
@@ -13766,22 +14202,22 @@ Service: not automated on ${platform}; run \`mushi work --daemon\` under your se
13766
14202
  key = res.data.key;
13767
14203
  }
13768
14204
  assertWorkerKey(key, cli.apiKey);
13769
- mkdirSync4(dirname5(WORKER_CONFIG_PATH), { recursive: true });
13770
- writeFileSync7(WORKER_CONFIG_PATH, `${JSON.stringify(cfg, null, 2)}
14205
+ mkdirSync4(dirname6(WORKER_CONFIG_PATH), { recursive: true });
14206
+ writeFileSync8(WORKER_CONFIG_PATH, `${JSON.stringify(cfg, null, 2)}
13771
14207
  `, { mode: 384 });
13772
14208
  if (trySaveWorkerKey(key)) {
13773
- if (existsSync6(WORKER_KEY_PATH)) rmSync(WORKER_KEY_PATH);
14209
+ if (existsSync7(WORKER_KEY_PATH)) rmSync2(WORKER_KEY_PATH);
13774
14210
  console.log("Saved the worker key in the OS keychain.");
13775
14211
  } else {
13776
- writeFileSync7(WORKER_KEY_PATH, `${key}
14212
+ writeFileSync8(WORKER_KEY_PATH, `${key}
13777
14213
  `, { mode: 384 });
13778
14214
  chmodSync2(WORKER_KEY_PATH, 384);
13779
14215
  console.log(`Saved the worker key in ${WORKER_KEY_PATH} (mode 0600).`);
13780
14216
  }
13781
14217
  console.log(`Wrote ${WORKER_CONFIG_PATH}.`);
13782
14218
  if (service?.kind === "systemd") {
13783
- mkdirSync4(dirname5(UNIT_PATH), { recursive: true });
13784
- writeFileSync7(UNIT_PATH, service.unit);
14219
+ mkdirSync4(dirname6(UNIT_PATH), { recursive: true });
14220
+ writeFileSync8(UNIT_PATH, service.unit);
13785
14221
  const reload = spawnSync4("systemctl", ["--user", "daemon-reload"], { stdio: "inherit" });
13786
14222
  const enable = reload.status === 0 ? spawnSync4("systemctl", ["--user", "enable", "--now", SYSTEMD_UNIT_NAME], { stdio: "inherit" }) : reload;
13787
14223
  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 +14316,7 @@ ${"lane".padEnd(16)} ${"app".padEnd(16)} ${"mode".padEnd(10)} ${"state".padEnd(1
13880
14316
  console.log("No worker key on this machine.");
13881
14317
  }
13882
14318
  tryDeleteWorkerKey();
13883
- if (existsSync6(WORKER_KEY_PATH)) rmSync(WORKER_KEY_PATH);
14319
+ if (existsSync7(WORKER_KEY_PATH)) rmSync2(WORKER_KEY_PATH);
13884
14320
  if (process.platform === "linux") spawnSync4("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT_NAME], { stdio: "inherit" });
13885
14321
  if (process.platform === "win32") spawnSync4("schtasks", ["/Delete", "/TN", WINDOWS_TASK_NAME, "/F"], { stdio: "inherit" });
13886
14322
  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 +14324,8 @@ ${"lane".padEnd(16)} ${"app".padEnd(16)} ${"mode".padEnd(10)} ${"state".padEnd(1
13888
14324
  }
13889
14325
 
13890
14326
  // src/template.ts
13891
- import { cpSync, existsSync as existsSync7, renameSync } from "fs";
13892
- import { join as join13, resolve as resolve10 } from "path";
14327
+ import { cpSync, existsSync as existsSync8, renameSync } from "fs";
14328
+ import { join as join14, resolve as resolve11 } from "path";
13893
14329
  import { fileURLToPath } from "url";
13894
14330
  var TEMPLATE_IDS = ["vue", "svelte", "node"];
13895
14331
 
@@ -13912,6 +14348,8 @@ Flags (forwarded to the wizard):
13912
14348
  --skip-install print the install command instead of running it
13913
14349
  --skip-test-report don't offer to send a test report at the end
13914
14350
  --audit health-check an existing install (doctor checks) instead of re-running the wizard
14351
+ --dry-run print what the wizard would install and write, then stop (changes nothing,
14352
+ no sign-in)
13915
14353
  --cwd <path> run in a different directory
13916
14354
  --endpoint <url> override the Mushi API endpoint (self-hosted)
13917
14355
  -y, --yes take the defaults: detected framework, saved credentials, browser sign-in