Skip to content

armgit / mso

Public Imported from GitHub
0

Browser-based graphical shell and control plane for a Linux server you own — real terminal, file manager, live metrics and BYOK AI in one mobile-first workspace. Next.js 16 · React 19 · node-pty · Tailwind v4 · shadcn/ui. Public alpha, self-hosted.

fix(runtime): prevent live Next build corruption

Rahman541df5f982c9
diff --git a/CLAUDE.md b/CLAUDE.md
index 35558127..a1eddc83 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -217,7 +217,8 @@ to `resources/` (rr) and drive any project from one manifest:
`public/sw.js` is byte-identical across deploys, so the toast never fired). It
caches ONLY icons+manifest, never chunks/HTML.
- **New routes need a clean build.** Adding a new `app/**/route.ts` or page folder
- may not register under incremental Turbopack — `rm -rf .next && bun run build`.
+ may not register under incremental Turbopack. On the live production checkout use
+ `mso deploy`; for verification use `mso build`. Never remove/replace live `.next`.
- **`git add` aborts on a bad pathspec** and stages NOTHING new — after a
`git rm`, don't re-list the removed file in `git add`; prefer `git add -A` and
check `git status --short` before committing (a broken commit shipped once this way).
@@ -225,14 +226,14 @@ to `resources/` (rr) and drive any project from one manifest:
`/home/rahman/.mso/worktrees/mso-demo-runtime`: `git fetch origin -q && git reset --hard
origin/main -q && bun run build && sudo systemctl restart mso-demo.service`.
Mind the cwd — running the sync from the prod dir is a classic slip.
-- **Never `bun run build` in this checkout just to CHECK a change** — it is
- `mso.service`'s WorkingDirectory, and `next build` deletes `distDir` before it
- compiles, so the live site 404s every chunk until a restart. Worse, repeat builds
- rename every chunk and mint a new `BUILD_ID`, so already-served HTML stays broken
- afterwards. Use `bash scripts/verify-build.sh`, which builds a throwaway copy of
- `HEAD` in a temp dir (node_modules is COPIED, not symlinked — Turbopack hard-fails
- on a symlink pointing outside the filesystem root). A real deploy still builds in
- place, which is fine because a restart immediately follows.
+- **`bun run build` is now fail-closed on a live checkout.** The package script
+ acquires the checkout runtime-exclusion lock and refuses before touching `.next`
+ when a Next/MSO runtime is serving that same checkout. Use `mso build` for the
+ out-of-tree compile proof and `mso deploy` for a production rebuild. The reason is
+ fundamental: Next loads manifests at process start while `next build` replaces
+ `.next`; mixing those generations makes already-served HTML point at missing chunks.
+ Raw `next build` is an internal deploy primitive only after the supported lifecycle
+ has quiesced the runtime.
- **The Browser app powers a systemd USER unit**, `camoufox-vnc.service` in
`~/.config/systemd/user/`, whose `ExecStart` points at **`scripts/camoufox-vnc-service`
in THIS repo** (it used to live untracked under `~/.openclaw/workspace/`, so a fresh
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index a622fa5d..cd8a4d7d 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -15,6 +15,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `runtime` prevent live Next build corruption
- `mcp` harden Open in MSO navigation
- `agent` calibrate correction memory semantics
- `agent` compare normalized token proofs per row
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 2670f1d4..da47091c 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -94,13 +94,14 @@ tail -f ~/.mso/self-update.log # success ends with UPDATE OK
A direct manual build-and-replace remains available for recovery, but it bypasses the
release gates and should not be the normal path.
-**Never run `bun run build` inside the running prod checkout just to "verify" a change.**
+**`bun run build` now refuses when a live Next/MSO runtime serves the same checkout.**
`next start` loads the build manifest at boot; overwriting `.next` under the live
process makes the already-served HTML reference chunk hashes that no longer exist on
disk → every JS/CSS chunk 404/500s → **the live site is broken until you restart**.
-To test runtime behaviour without risking prod, use a **separate checkout / a demo
-instance** on a different port — e.g. a build with `NEXT_PUBLIC_OS_DEMO=1` (no login,
+Use `mso build` for the normal out-of-tree compile proof and `mso deploy` for a
+production replacement. To test runtime behaviour without risking prod, use a
+**separate checkout / a demo instance** on a different port — e.g. a build with `NEXT_PUBLIC_OS_DEMO=1` (no login,
no host access, forced mock data), served on `:4006` via its own systemd unit. For a
non-destructive static check, `bun run typecheck && bun run lint` is the cheap gate.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index ee6c2357..9ac7cd9e 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,4 +1,5 @@
# mso — Progress Log
+- **Live-build chunk corruption eliminated (2026-09-03):** a production browser repro proved the shell/Settings crash was not a Settings logic regression: an in-place `next build` in the active service checkout replaced `.next` while the old Next process still served its boot-time manifest, making all 19 root-referenced chunks disappear and one observed JS request return `500 text/plain`. Production was recovered through `mso deploy`; shell + Settings then passed real authenticated Playwright on desktop/mobile with zero failed requests/console errors. `bun run build` is now a fail-closed wrapper that holds the checkout exclusion and refuses a same-checkout live runtime; `mso build` remains the out-of-tree proof and guarded deploy/update lifecycles invoke raw Next only after quiescence. Post-replacement validation now checks every root-referenced JS/CSS asset status+MIME, not one CSS/chunk. The Fresh 3 smoke scratch path moved out of protected `~/.mso`, and recursive `fs_mkdir` now securely supports missing parents while rejecting symlink escapes.
## 2026-09-03 — Cognitive Runtime P10 memory retention & lifecycle
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
index b3fbce99..05ce7338 100644
--- a/docs/TESTING-HANDOFF.md
+++ b/docs/TESTING-HANDOFF.md
@@ -1,4 +1,5 @@
# MSO testing handoff
+- Live-build regression gate: `bun run build` must refuse before `.next` mutation when the same checkout is being served; `mso build` is the safe out-of-tree verification path and `mso deploy` owns production rebuild/replacement. Post-deploy acceptance must verify every JS/CSS asset referenced by root HTML plus authenticated browser rendering of `/settings`; one sampled chunk is not sufficient.
Update this file at the end of every manual or automated test session. Keep it factual; never include tokens, cookies, prompts containing secrets, or hidden transcripts.
diff --git a/docs/integrations/CHATGPT-UI.md b/docs/integrations/CHATGPT-UI.md
index 4da9cd40..bc5aade6 100644
--- a/docs/integrations/CHATGPT-UI.md
+++ b/docs/integrations/CHATGPT-UI.md
@@ -80,7 +80,7 @@ Do not manually click through every model action. Cover the public contract with
| Workflow/UI bridge | Start a read-only workflow for `mso`, press `Refresh`, then `Open in MSO` | progress updates; automatic link opens or the explicit `Open directly` fallback is shown |
| VPS card | Ask for the current VPS status | `vps_status` renders CPU/memory/disk/apps/browser/infra and its refresh works |
| Project/Git | Ask to inspect project `mso`, then show its current diff/history | `project_get` and `project_diff` render the correct project/branch/changes without secrets |
-| Safe filesystem CRUD | Create/read/copy/move/delete a disposable file under `~/.mso/smoke-tests/` | content/hash round-trip succeeds and cleanup leaves no test file |
+| Safe filesystem CRUD | Create/read/copy/move/delete a disposable file under `~/mso-smoke-tests/` | content/hash round-trip succeeds and cleanup leaves no test file |
| Convex | Check database status/tools for a known Convex project such as CareerPack | provider is Convex, project boundary is preserved, no env credential tools appear |
| Project agent | Run `project_agent_run` in `plan_mode=true` for a harmless project inspection | returns a bounded plan/message id without modifying the repo |
| Operator integrations | Check `browser_status` + `infra_providers_list` | read-only state is returned without starting browser/app or exposing provider secrets |
diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.ts
index b581a308..63fa6c4e 100644
--- a/lib/config/env-example.test.ts
+++ b/lib/config/env-example.test.ts
@@ -45,6 +45,7 @@ const NOT_A_KNOB: Record<string, string> = {
E2E_DEVICE: "test harness",
E2E_HEADED: "test harness",
E2E_PREVIEW_DIR: "test harness",
+ MSO_RUNTIME_PROC_ROOT: "test-only fake /proc root for live-runtime ownership tests",
OS_MEDIA_BASE: "scripts/gen-readme-media.mjs only",
OS_MEDIA_DEVICE: "scripts/gen-readme-media.mjs only",
};
diff --git a/lib/host/fs.test.ts b/lib/host/fs.test.ts
index a4d34c8e..d37a6cfe 100644
--- a/lib/host/fs.test.ts
+++ b/lib/host/fs.test.ts
@@ -11,7 +11,7 @@ import {
import os from "node:os";
import path from "node:path";
import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
-import { copy, move, remove, writeFile } from "./fs";
+import { copy, makeDir, move, remove, writeFile } from "./fs";
// Mirrors paths.test.ts setup. Layout:
// base/read/ ← read root
@@ -83,6 +83,24 @@ describe("writeFile (atomic write inside WRITE roots)", () => {
});
});
+describe("makeDir (recursive mkdir inside WRITE roots)", () => {
+ it("creates missing parent directories recursively", async () => {
+ useRoots(readRoot, writeRoot);
+ const target = path.join(writeRoot, "mkdir-parent", "child", "grandchild");
+ await makeDir(target);
+ expect(existsSync(target)).toBe(true);
+ });
+
+ it("rejects a missing descendant below an existing symlink that escapes the write root", async () => {
+ useRoots(readRoot, writeRoot);
+ const outsideDir = path.join(outside, "mkdir-outside"); mkdirSync(outsideDir, { recursive: true });
+ const link = path.join(writeRoot, "mkdir-link");
+ try { symlinkSync(outsideDir, link, "dir"); } catch { /* stable across retries */ }
+ await expect(makeDir(path.join(link, "new", "child"))).rejects.toThrow(/outside writable roots/i);
+ expect(existsSync(path.join(outsideDir, "new"))).toBe(false);
+ });
+});
+
describe("move (rename)", () => {
it("renames a file inside the write root", async () => {
useRoots(readRoot, writeRoot);
diff --git a/lib/host/fs.ts b/lib/host/fs.ts
index 8d023953..b0b2961a 100644
--- a/lib/host/fs.ts
+++ b/lib/host/fs.ts
@@ -15,6 +15,7 @@ import {
isSensitivePath,
resolveReadable,
resolveRoots,
+ safeMkdirPath,
safeWritePath,
} from "./paths";
@@ -79,7 +80,7 @@ export async function writeFile(requested: string, content: string): Promise<voi
}
export async function makeDir(requested: string): Promise<void> {
- const p = await safeWritePath(requested, false);
+ const p = await safeMkdirPath(requested);
await fs.mkdir(p, { recursive: true });
}
diff --git a/lib/host/mkdir-path.test.ts b/lib/host/mkdir-path.test.ts
new file mode 100644
index 00000000..cfc3f2be
--- /dev/null
+++ b/lib/host/mkdir-path.test.ts
@@ -0,0 +1,51 @@
+import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, symlinkSync } from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from "vitest";
+import { makeDir } from "./fs";
+import { safeMkdirPath } from "./paths";
+
+let base = "";
+let writeRoot = "";
+let outside = "";
+
+beforeAll(() => {
+ base = realpathSync(mkdtempSync(path.join(os.tmpdir(), "mso-mkdir-")));
+ writeRoot = path.join(base, "write");
+ outside = path.join(base, "outside");
+ mkdirSync(writeRoot, { recursive: true });
+ mkdirSync(outside, { recursive: true });
+});
+afterAll(() => rmSync(base, { recursive: true, force: true }));
+afterEach(() => vi.unstubAllEnvs());
+
+function useWriteRoot(root = writeRoot) {
+ vi.stubEnv("OS_FS_READ_ROOTS", root);
+ vi.stubEnv("OS_FS_WRITE_ROOTS", root);
+}
+
+describe("recursive mkdir containment", () => {
+ it("creates all missing parents inside a real write root", async () => {
+ useWriteRoot();
+ const target = path.join(writeRoot, "a", "b", "c");
+ await expect(safeMkdirPath(target)).resolves.toBe(target);
+ await makeDir(target);
+ expect(existsSync(target)).toBe(true);
+ });
+
+ it("rejects a missing descendant below an existing symlink escape", async () => {
+ useWriteRoot();
+ const target = path.join(outside, "target");
+ mkdirSync(target, { recursive: true });
+ const link = path.join(writeRoot, "link");
+ symlinkSync(target, link, "dir");
+ await expect(makeDir(path.join(link, "new", "child"))).rejects.toThrow(/outside writable roots/i);
+ expect(existsSync(path.join(target, "new"))).toBe(false);
+ });
+
+ it("keeps the owner .mso state tree blocked", async () => {
+ useWriteRoot(os.homedir());
+ await expect(safeMkdirPath(path.join(os.homedir(), ".mso", "smoke-tests", "x")))
+ .rejects.toThrow(/credential|sensitive/i);
+ });
+});
diff --git a/lib/host/paths.ts b/lib/host/paths.ts
index bdbf0932..dddbf20c 100644
--- a/lib/host/paths.ts
+++ b/lib/host/paths.ts
@@ -349,6 +349,43 @@ export async function resolveReadable(requested: string): Promise<string> {
// WRITE: "/" collapses to home (never the FS root). When !mustExist the parent
// is checked (target doesn't exist yet). Asserts inside a write root.
+/** Resolve a mkdir -p target without requiring its immediate parent to exist.
+ * The deepest existing ancestor is realpath-checked against the write root, so an
+ * existing symlink component cannot redirect newly-created descendants outside the jail. */
+export async function safeMkdirPath(requested: string): Promise<string> {
+ const h = homeDir();
+ let absolute: string;
+ if (!requested || requested === "~" || requested === "/") absolute = h;
+ else if (requested.startsWith("~/")) absolute = path.join(h, requested.slice(2));
+ else absolute = path.resolve(requested);
+ const normalized = path.resolve(absolute);
+ const configured = lexicalRoots(writeRootList());
+
+ for (const root of configured) {
+ const lexicalPrefix = root === path.parse(root).root ? root : root + path.sep;
+ if (normalized !== root && !normalized.startsWith(lexicalPrefix)) continue;
+ const realRoot = await fs.realpath(root).catch(() => path.resolve(root));
+ let ancestor = normalized;
+ while (true) {
+ try {
+ const realAncestor = await fs.realpath(ancestor);
+ if (!isUnderRoot(realAncestor, realRoot)) throw new HostError("Path outside writable roots");
+ break;
+ } catch (error) {
+ if (error instanceof HostError) throw error;
+ const code = (error as NodeJS.ErrnoException).code;
+ if (code !== "ENOENT" && code !== "ENOTDIR") throw error;
+ const parent = path.dirname(ancestor);
+ if (parent === ancestor) throw new HostError("Path outside writable roots");
+ ancestor = parent;
+ }
+ }
+ assertNotCredential(normalized);
+ return normalized;
+ }
+ throw new HostError("Path outside writable roots");
+}
+
export async function safeWritePath(requested: string, mustExist: boolean): Promise<string> {
const h = homeDir();
let absolute: string;
diff --git a/package.json b/package.json
index e103f6c6..cdb76999 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
},
"scripts": {
"dev": "next dev --hostname 0.0.0.0 --port 3000",
- "build": "next build",
+ "build": "bash scripts/build-safe.sh",
"start": "next start",
"lint": "eslint .",
"typecheck": "tsc --noEmit",
diff --git a/scripts/build-safe.sh b/scripts/build-safe.sh
new file mode 100755
index 00000000..45a20e79
--- /dev/null
+++ b/scripts/build-safe.sh
@@ -0,0 +1,42 @@
+#!/usr/bin/env bash
+# Safe default for `bun run build`.
+# A Next production server reads manifests/chunks from .next for its whole life.
+# `next build` starts by deleting/replacing that tree, so running it in the same
+# checkout as a live Next runtime creates a deterministic chunk/manifest outage.
+set -euo pipefail
+
+ROOT="$(git rev-parse --show-toplevel 2>/dev/null || pwd -P)"
+# shellcheck source=scripts/lib/private-state.sh
+. "$ROOT/scripts/lib/private-state.sh"
+# shellcheck source=scripts/lib/runtime-exclusion.sh
+. "$ROOT/scripts/lib/runtime-exclusion.sh"
+
+runtime_exclusion_acquire_exclusive || {
+ echo "mso build: another deploy/update/build owns this checkout; retry after it finishes" >&2
+ exit 75
+}
+trap 'runtime_exclusion_release' EXIT INT TERM
+
+set +e
+LIVE="$(node "$ROOT/scripts/lib/live-runtime.mjs" "$ROOT" 2>/dev/null)"
+LIVE_RC=$?
+set -e
+case "$LIVE_RC" in
+ 0)
+ PID="$(printf '%s' "$LIVE" | node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{try{process.stdout.write(String(JSON.parse(s).pid||"?"))}catch{process.stdout.write("?")}})')"
+ echo "mso build: refusing in-place Next build; live runtime pid $PID is serving this checkout" >&2
+ echo "mso build: use 'mso build' to verify HEAD out-of-tree, or 'mso deploy' for a safe production rebuild" >&2
+ exit 73
+ ;;
+ 1) ;;
+ *)
+ echo "mso build: could not inspect live runtime ownership; refusing to mutate .next" >&2
+ exit 74
+ ;;
+esac
+
+NEXT="$ROOT/node_modules/next/dist/bin/next"
+[ -f "$NEXT" ] || { echo "mso build: Next is not installed; run bun install" >&2; exit 69; }
+cd "$ROOT"
+# Keep the checkout-wide exclusion FD inherited by Node for the entire mutation.
+node "$NEXT" build
diff --git a/scripts/check-served-assets.mjs b/scripts/check-served-assets.mjs
new file mode 100755
index 00000000..9a8fb23a
--- /dev/null
+++ b/scripts/check-served-assets.mjs
@@ -0,0 +1,11 @@
+#!/usr/bin/env node
+import { verifyServedStaticAssets } from "./lib/served-assets.mjs";
+
+const base = process.argv[2] || "http://127.0.0.1:4005";
+try {
+ const result = await verifyServedStaticAssets(base);
+ console.log(`asset graph OK: ${result.assetCount} referenced JS/CSS assets`);
+} catch (error) {
+ console.error(`asset graph FAILED: ${error instanceof Error ? error.message : String(error)}`);
+ process.exit(1);
+}
diff --git a/scripts/e2e/shell.mjs b/scripts/e2e/shell.mjs
index cb30ca83..507b85c9 100644
--- a/scripts/e2e/shell.mjs
+++ b/scripts/e2e/shell.mjs
@@ -176,17 +176,22 @@ async function session(browser, { width, height, label, touch = width < 768, exp
];
for (const slug of nativeSlugs) {
await page.goto(`${BASE}/${slug}`, { waitUntil: "domcontentloaded" });
- await page.waitForTimeout(1200);
+ // Wait for the shell-owned surface before judging its loading state. A fixed sleep
+ // can observe "no spinner" before React mounts, or a transient spinner on cold import.
+ const surfaceReady = width >= 768
+ ? await page.locator("[data-window]").first().waitFor({ state: "attached", timeout: 5_000 }).then(() => true).catch(() => false)
+ : await page.locator('[data-slot="mobile-feature-header"]').first().waitFor({ state: "attached", timeout: 5_000 }).then(() => true).catch(() => false);
+ const contentReady = surfaceReady
+ ? await page.waitForFunction(() => document.querySelectorAll(".animate-spin").length === 0, null, { timeout: 5_000 }).then(() => true).catch(() => false)
+ : false;
// Desktop puts the app in a [data-window]; iOS/Android render it full-screen in
// the shell, with no window chrome at all. Assert the surface-appropriate thing
// rather than a window that is correctly absent on a phone.
check(page.url().endsWith(`/${slug}`), `/${slug} deep-link kept the URL`);
- if (width >= 768) {
- check((await page.locator("[data-window]").count()) > 0, `/${slug} opened a window`);
- }
+ if (width >= 768) check(surfaceReady, `/${slug} opened a window`);
// A spinner that never resolves is the exact failure window-content.tsx used to
// sit in forever when a chunk import rejected.
- check((await page.locator(".animate-spin").count()) === 0, `/${slug} rendered without a stuck spinner`);
+ check(contentReady, `/${slug} rendered without a stuck spinner`);
// Mobile navigation is shell-owned for EVERY feature. Root contract:
// < Home | centered feature title | AI. Feature slices may publish a parent
@@ -230,10 +235,13 @@ async function session(browser, { width, height, label, touch = width < 768, exp
// as an MSO host-network failure. Their own runtime has separate managed-app tests.
for (const slug of ["hermes", "openclaw", "9router"]) {
await page.goto(`${BASE}/${slug}`, { waitUntil: "domcontentloaded" });
- await page.waitForTimeout(1200);
+ const windowReady = width < 768 ? true : await page.locator("[data-window]").first().waitFor({ state: "attached", timeout: 5_000 })
+ .then(() => true).catch(() => false);
+ const managedReady = await page.waitForFunction(() => document.querySelectorAll(".animate-spin").length === 0, null, { timeout: 5_000 })
+ .then(() => true).catch(() => false);
check(page.url().endsWith(`/${slug}`), `/${slug} managed-app deep-link kept the URL`);
- if (width >= 768) check((await page.locator("[data-window]").count()) > 0, `/${slug} managed-app opened a window`);
- check((await page.locator(".animate-spin").count()) === 0, `/${slug} managed-app host rendered without a stuck spinner`);
+ if (width >= 768) check(windowReady, `/${slug} managed-app opened a window`);
+ check(managedReady, `/${slug} managed-app host rendered without a stuck spinner`);
}
await ctx.close();
diff --git a/scripts/e2e/smoke.test.ts b/scripts/e2e/smoke.test.ts
index c6bd04cd..f609ec2f 100644
--- a/scripts/e2e/smoke.test.ts
+++ b/scripts/e2e/smoke.test.ts
@@ -61,23 +61,19 @@ describe.skipIf(skip)(
expect([401, 403]).toContain(res.status);
});
- it.skipIf(skip)("a referenced _next/static chunk serves with correct MIME", async () => {
- // Discover a real chunk URL from the rendered shell so we don't hardcode
- // a hash. The home page is HTML and always references >=1 _next/static
- // chunk. Catches the classic stale-CDN chunk 404 / wrong MIME bug.
+ it.skipIf(skip)("every root-referenced _next/static JS/CSS asset serves with correct MIME", async () => {
const homeRes = await get("/");
expect(homeRes.status).toBe(200);
const html = await homeRes.text();
- const m = html.match(/\/_next\/static\/[^"' )]+\.(?:js|css)/);
- expect(m, "no _next/static chunk found in home HTML").not.toBeNull();
- const chunkPath = m![0];
- const res = await get(chunkPath);
- expect(res.status).toBe(200);
- const ct = res.headers.get("content-type") ?? "";
- const expected = chunkPath.endsWith(".css")
- ? "text/css"
- : "javascript";
- expect(ct.toLowerCase()).toContain(expected);
+ const assets = [...new Set(html.match(/\/_next\/static\/[^"'\s)<>]+\.(?:js|css)(?:\?[^"'\s)<>]*)?/g) ?? [])];
+ expect(assets.length, "no _next/static JS/CSS assets found in home HTML").toBeGreaterThan(0);
+ expect(assets.length).toBeLessThanOrEqual(120);
+ for (const asset of assets) {
+ const res = await get(asset, { method: "HEAD" });
+ expect(res.status, asset).toBe(200);
+ const ct = (res.headers.get("content-type") ?? "").toLowerCase();
+ expect(ct, asset).toContain(asset.split("?", 1)[0].endsWith(".css") ? "text/css" : "javascript");
+ }
});
},
);
diff --git a/scripts/lib/live-runtime.mjs b/scripts/lib/live-runtime.mjs
new file mode 100644
index 00000000..b480d6cc
--- /dev/null
+++ b/scripts/lib/live-runtime.mjs
@@ -0,0 +1,45 @@
+import fs from "node:fs";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+
+function canonical(value) {
+ try { return fs.realpathSync(value); } catch { return path.resolve(value); }
+}
+
+function runtimeCommand(comm, cmdline) {
+ const text = `${comm} ${cmdline}`.replace(/\0/g, " ");
+ return (
+ /\bnext-server\b/i.test(text) ||
+ /node_modules\/next\/dist\/bin\/next\s+start\b/i.test(text) ||
+ /\b(?:npm|bun|pnpm)\s+run\s+start(?:\s|$)/i.test(text) ||
+ /\byarn\s+start(?:\s|$)/i.test(text)
+ );
+}
+
+export function findCheckoutRuntime(root, procRoot = "/proc") {
+ const target = canonical(root);
+ let entries;
+ try { entries = fs.readdirSync(procRoot, { withFileTypes: true }); } catch { return null; }
+
+ for (const entry of entries) {
+ if (!entry.isDirectory() || !/^\d+$/.test(entry.name)) continue;
+ const dir = path.join(procRoot, entry.name);
+ let cwd, comm = "", cmdline = "";
+ try { cwd = canonical(fs.readlinkSync(path.join(dir, "cwd"))); } catch { continue; }
+ if (cwd !== target) continue;
+ try { comm = fs.readFileSync(path.join(dir, "comm"), "utf8").trim(); } catch { /* optional */ }
+ try { cmdline = fs.readFileSync(path.join(dir, "cmdline"), "utf8"); } catch { /* optional */ }
+ if (runtimeCommand(comm, cmdline)) {
+ return { pid: Number(entry.name), comm: comm || "next-runtime" };
+ }
+ }
+ return null;
+}
+
+const invoked = process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
+if (invoked) {
+ const root = process.argv[2] || process.cwd();
+ const hit = findCheckoutRuntime(root, process.env.MSO_RUNTIME_PROC_ROOT || "/proc");
+ if (!hit) process.exit(1);
+ process.stdout.write(`${JSON.stringify(hit)}\n`);
+}
diff --git a/scripts/lib/served-assets.mjs b/scripts/lib/served-assets.mjs
new file mode 100644
index 00000000..c61fb4fe
--- /dev/null
+++ b/scripts/lib/served-assets.mjs
@@ -0,0 +1,43 @@
+const MAX_ASSETS = 120;
+
+export function referencedStaticAssets(html) {
+ const matches = html.match(/\/_next\/static\/[^"'\s)<>]+\.(?:js|css)(?:\?[^"'\s)<>]*)?/g) ?? [];
+ return [...new Set(matches)].slice(0, MAX_ASSETS);
+}
+
+function expectedMime(asset) {
+ return asset.split("?", 1)[0].endsWith(".css") ? "text/css" : "javascript";
+}
+
+async function boundedFetch(url, options = {}) {
+ return fetch(url, { ...options, cache: "no-store", signal: AbortSignal.timeout(8_000) });
+}
+
+export async function verifyServedStaticAssets(baseUrl) {
+ const base = new URL(baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`);
+ const home = await boundedFetch(base);
+ if (!home.ok) throw new Error(`root HTML returned ${home.status}`);
+ const html = await home.text();
+ const assets = referencedStaticAssets(html);
+ if (!assets.length) throw new Error("root HTML references no Next static JS/CSS assets");
+
+ const failures = [];
+ for (const asset of assets) {
+ let response;
+ try {
+ response = await boundedFetch(new URL(asset, base), { method: "HEAD" });
+ } catch (error) {
+ failures.push(`${asset}: ${error instanceof Error ? error.message : String(error)}`);
+ continue;
+ }
+ const contentType = (response.headers.get("content-type") ?? "").toLowerCase();
+ const mime = expectedMime(asset);
+ if (!response.ok || !contentType.includes(mime)) {
+ failures.push(`${asset}: ${response.status} ${contentType || "no-content-type"}`);
+ }
+ }
+ if (failures.length) {
+ throw new Error(`static asset graph mismatch (${failures.length}/${assets.length}): ${failures.slice(0, 8).join("; ")}`);
+ }
+ return { assetCount: assets.length, assets };
+}
diff --git a/scripts/live-runtime.test.ts b/scripts/live-runtime.test.ts
new file mode 100644
index 00000000..e30e5617
--- /dev/null
+++ b/scripts/live-runtime.test.ts
@@ -0,0 +1,58 @@
+import { execFileSync, spawnSync } from "node:child_process";
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+const SCRIPT = path.join(process.cwd(), "scripts/lib/live-runtime.mjs");
+const BUILD = path.join(process.cwd(), "scripts/build-safe.sh");
+const roots: string[] = [];
+
+function fixture(command: string, options: { sameRoot?: boolean; comm?: string } = {}) {
+ const base = fs.mkdtempSync(path.join(os.tmpdir(), "mso-live-runtime-")); roots.push(base);
+ const root = path.join(base, "repo"), other = path.join(base, "other"), proc = path.join(base, "proc"), pid = path.join(proc, "123");
+ fs.mkdirSync(root); fs.mkdirSync(other); fs.mkdirSync(pid, { recursive: true });
+ fs.symlinkSync(options.sameRoot === false ? other : root, path.join(pid, "cwd"));
+ fs.writeFileSync(path.join(pid, "comm"), `${options.comm ?? "node"}\n`);
+ fs.writeFileSync(path.join(pid, "cmdline"), command.replace(/ /g, "\0") + "\0");
+ return { base, root, proc };
+}
+
+afterEach(() => { for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); });
+
+describe("live checkout runtime detector", () => {
+ it("detects Next/npm runtimes only when they serve the exact checkout", () => {
+ const next = fixture("node node_modules/next/dist/bin/next start --port 4005");
+ const found = execFileSync(process.execPath, [SCRIPT, next.root], { env: { ...process.env, MSO_RUNTIME_PROC_ROOT: next.proc }, encoding: "utf8" });
+ expect(JSON.parse(found)).toMatchObject({ pid: 123 });
+
+ const other = fixture("npm run start --hostname 0.0.0.0", { sameRoot: false });
+ expect(spawnSync(process.execPath, [SCRIPT, other.root], { env: { ...process.env, MSO_RUNTIME_PROC_ROOT: other.proc } }).status).toBe(1);
+
+ const build = fixture("node node_modules/next/dist/bin/next build");
+ expect(spawnSync(process.execPath, [SCRIPT, build.root], { env: { ...process.env, MSO_RUNTIME_PROC_ROOT: build.proc } }).status).toBe(1);
+ });
+
+ it("recognizes next-server process titles", () => {
+ const f = fixture("next-server v16.3.2", { comm: "next-server" });
+ expect(spawnSync(process.execPath, [SCRIPT, f.root], { env: { ...process.env, MSO_RUNTIME_PROC_ROOT: f.proc } }).status).toBe(0);
+ });
+
+ it("package build is guarded and refuses before touching a fake live checkout", () => {
+ const pkg = JSON.parse(fs.readFileSync(path.join(process.cwd(), "package.json"), "utf8"));
+ expect(pkg.scripts.build).toBe("bash scripts/build-safe.sh");
+
+ const proc = fs.mkdtempSync(path.join(os.tmpdir(), "mso-build-proc-")); roots.push(proc);
+ const pid = path.join(proc, "456"); fs.mkdirSync(pid);
+ fs.symlinkSync(process.cwd(), path.join(pid, "cwd"));
+ fs.writeFileSync(path.join(pid, "comm"), "next-server\n"); fs.writeFileSync(path.join(pid, "cmdline"), "next-server\0");
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "mso-build-home-")); roots.push(home);
+ const out = spawnSync("bash", [BUILD], {
+ cwd: process.cwd(), encoding: "utf8",
+ env: { ...process.env, HOME: home, MSO_RUNTIME_PROC_ROOT: proc, MSO_RUNTIME_EXCLUSION_DIR: path.join(home, "locks") },
+ });
+ expect(out.status).toBe(73);
+ expect(out.stderr).toContain("refusing in-place Next build");
+ expect(out.stderr).toContain("mso deploy");
+ });
+});
diff --git a/scripts/post-deploy-smoke.sh b/scripts/post-deploy-smoke.sh
index fd753847..f9efb454 100755
--- a/scripts/post-deploy-smoke.sh
+++ b/scripts/post-deploy-smoke.sh
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
-# Post-deploy smoke test. Run AFTER `bun run build && sudo systemctl restart mso.service`.
+# Post-deploy smoke test. Run AFTER the supported MSO deploy/release lifecycle.
# Catches the chunk-MIME drift that has bitten this deploy twice (per CLAUDE.md).
#
# REQUIRES: devDependencies installed on host (vitest lives in devDeps). Run
@@ -10,6 +10,7 @@ set -euo pipefail
BASE_URL="${OS_BASE_URL:-http://localhost:4005}"
echo "Smoke testing ${BASE_URL}..."
+node scripts/check-served-assets.mjs "$BASE_URL"
# Prefer the full vitest smoke suite (4 checks: health, root HTML, chunk MIME,
# asset 200). Falls back to curl if vitest isn't on the deploy box.
diff --git a/scripts/self-update.sh b/scripts/self-update.sh
index c91c643d..75b05ab3 100755
--- a/scripts/self-update.sh
+++ b/scripts/self-update.sh
@@ -98,7 +98,7 @@ else
fi
step "building in place"
-bun run build >/dev/null || die "in-place build failed — check disk space"
+node node_modules/next/dist/bin/next build >/dev/null || die "in-place build failed — check disk space"
step "restarting mso.service (same-user signal; no sudo)"
# mso.service runs as the owner and has Restart=always. Signalling its MainPID is
@@ -151,31 +151,16 @@ done
|| die "mso.service did not return with a new MainPID within ${RESTART_WAIT_SECONDS}s; release state is unverified — inspect the system unit before retrying"
printf 'restarted %s -> %s after %ss\n' "$OLD_PID" "$NEW_PID" "$((RESTART_WAIT_SECONDS - (RESTART_DEADLINE - SECONDS)))"
-# The chunk-mismatch check CLAUDE.md warns about, verified rather than remembered —
-# the same check scripts/ship.sh ends with. `active` only means npm has started, not
-# that Next is already accepting connections, so wait for real HTML before checking
-# its referenced CSS chunk.
-# The user transient unit intentionally does not inherit arbitrary service env.
-# Read the fixed numeric PORT from the installed unit instead; fall back to the
-# installer's default for older or hand-written units.
+# Verify the COMPLETE static asset graph referenced by root HTML. A healthy first
+# stylesheet is insufficient: an in-place build can leave one old JS chunk missing
+# while other assets still serve correctly. The helper is bounded and checks
+# status + MIME for every referenced root JS/CSS asset.
SERVICE_PORT="$(systemctl show -p Environment --value mso.service 2>/dev/null \
| tr ' ' '\n' | sed -n 's/^PORT=//p' | head -1)"
PORT="${PORT:-${SERVICE_PORT:-4005}}"
-HTML=""
-for _ in $(seq 1 30); do
- HTML="$(curl -fsS --max-time 3 "http://127.0.0.1:$PORT/" 2>/dev/null || true)"
- [ -n "$HTML" ] && break
- sleep 1
-done
-CSS=$(printf '%s' "$HTML" | grep -o '/_next/static/[^"]*\.css' | head -1)
-if [ -z "$CSS" ]; then
- die "no CSS reference in the served HTML — recover with: rm -rf .next && bun run build && sudo systemctl restart mso.service"
-fi
-TYPE=$(curl -fsSI --max-time 10 "http://127.0.0.1:$PORT$CSS" | tr -d '\r' | awk -F': ' 'tolower($1)=="content-type"{print $2}')
-case "$TYPE" in
- text/css*) ;;
- *) die "chunk mismatch: $CSS served as '${TYPE:-nothing}'. Recover with: rm -rf .next && bun run build && sudo systemctl restart mso.service" ;;
-esac
+ASSET_BASE="http://127.0.0.1:$PORT"
+node scripts/check-served-assets.mjs "$ASSET_BASE" \
+ || die "served static asset graph is inconsistent after replacement; use the supported MSO deploy/rebuild lifecycle and inspect ~/.mso/self-update.log"
step "inner update stage complete — now at $(git rev-parse --short HEAD)"
printf 'INNER STAGE COMPLETE\n'
diff --git a/scripts/served-assets.test.ts b/scripts/served-assets.test.ts
new file mode 100644
index 00000000..4f3ddbbb
--- /dev/null
+++ b/scripts/served-assets.test.ts
@@ -0,0 +1,37 @@
+import { createServer, type Server } from "node:http";
+import { afterEach, describe, expect, it } from "vitest";
+import { referencedStaticAssets, verifyServedStaticAssets } from "./lib/served-assets.mjs";
+
+let server: Server | undefined;
+afterEach(async () => { if (server) await new Promise<void>((resolve) => server!.close(() => resolve())); server = undefined; });
+
+async function serve(bad = false) {
+ server = createServer((req, res) => {
+ if (req.url === "/") {
+ res.setHeader("content-type", "text/html");
+ res.end('<script src="/_next/static/chunks/a.js"></script><link rel="stylesheet" href="/_next/static/css/b.css"><script src="/_next/static/chunks/a.js"></script>');
+ return;
+ }
+ if (req.url === "/_next/static/chunks/a.js") {
+ res.statusCode = bad ? 500 : 200; res.setHeader("content-type", bad ? "text/plain" : "application/javascript"); res.end(); return;
+ }
+ if (req.url === "/_next/static/css/b.css") { res.setHeader("content-type", "text/css; charset=utf-8"); res.end(); return; }
+ res.statusCode = 404; res.end();
+ });
+ await new Promise<void>((resolve) => server!.listen(0, "127.0.0.1", resolve));
+ const address = server.address(); if (!address || typeof address === "string") throw new Error("missing test port");
+ return `http://127.0.0.1:${address.port}`;
+}
+
+describe("served Next asset graph", () => {
+ it("deduplicates and extracts all referenced JS/CSS assets", () => {
+ expect(referencedStaticAssets('<script src="/_next/static/chunks/a.js"></script><script src="/_next/static/chunks/a.js"></script><link href="/_next/static/css/b.css">'))
+ .toEqual(["/_next/static/chunks/a.js", "/_next/static/css/b.css"]);
+ });
+ it("passes only when every referenced asset is healthy with the right MIME", async () => {
+ const base = await serve(false); await expect(verifyServedStaticAssets(base)).resolves.toMatchObject({ assetCount: 2 });
+ });
+ it("fails on the exact 500 text/plain chunk class that breaks the shell", async () => {
+ const base = await serve(true); await expect(verifyServedStaticAssets(base)).rejects.toThrow(/a\.js: 500 text\/plain/);
+ });
+});