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.

refactor: split installer phases and lock release lifecycle

Rahman5eb90c44bcf1
diff --git a/architecture.boundaries.json b/architecture.boundaries.json
index d1ad3e1d..8d8a778f 100644
--- a/architecture.boundaries.json
+++ b/architecture.boundaries.json
@@ -4,7 +4,7 @@
"structuralCycles": 0,
"crossDomainCycles": 0,
"filesOver220": 54,
- "filesOver500": 1,
+ "filesOver500": 0,
"serverFrontendImports": 0,
"appshellSelfBarrelImports": 0,
"nonMcpMcpImports": 0,
diff --git a/lib/install-contract.test.ts b/lib/install-contract.test.ts
index b56f41be..e9e66f56 100644
--- a/lib/install-contract.test.ts
+++ b/lib/install-contract.test.ts
@@ -7,11 +7,16 @@ import { describe, expect, it } from "vitest";
const BOOTSTRAP = path.join(__dirname, "../scripts/install.sh");
const CORE = path.join(__dirname, "../scripts/install-core.sh");
+const PHASES = ["cli.sh", "runtime-build.sh", "service.sh", "finalize.sh"].map((name) =>
+ path.join(__dirname, "../scripts/install", name),
+);
+const installerSource = () => [CORE, ...PHASES].map((file) => fs.readFileSync(file, "utf8")).join("\n");
describe("one-line installer contract", () => {
it("is valid bash and documents onboarding controls", () => {
expect(() => execFileSync("bash", ["-n", BOOTSTRAP])).not.toThrow();
expect(() => execFileSync("bash", ["-n", CORE])).not.toThrow();
+ for (const phase of PHASES) expect(() => execFileSync("bash", ["-n", phase])).not.toThrow();
const help = execFileSync("bash", [CORE, "--help"], { encoding: "utf8" });
expect(help).toContain("--onboard");
expect(help).toContain("--no-onboard");
@@ -95,7 +100,7 @@ describe("one-line installer contract", () => {
});
it("uses the controlling tty after curl|bash and never stdin for onboarding", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
expect(src).toContain("[ -r /dev/tty ] && [ -w /dev/tty ]");
expect(src).toContain('onboard </dev/tty >/dev/tty 2>/dev/tty');
expect(src).toContain('ONBOARD_MODE=auto');
@@ -103,7 +108,7 @@ describe("one-line installer contract", () => {
});
it("installs the CLI before dependencies, build, and service setup and proves it against the invoking PATH", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
expect(src.indexOf("# ---- CLI on PATH")).toBeLessThan(src.indexOf("INSTALL_PHASE=dependencies"));
expect(src.indexOf("# ---- CLI on PATH")).toBeLessThan(src.indexOf("INSTALL_PHASE=build"));
expect(src.indexOf("# ---- CLI on PATH")).toBeLessThan(src.indexOf("# ---- systemd unit ----"));
@@ -125,7 +130,7 @@ describe("one-line installer contract", () => {
});
it("holds the checkout runtime lifecycle across dependency/build and service refresh", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
const begin = src.indexOf("install_runtime_lifecycle_begin");
const deps = src.indexOf("INSTALL_PHASE=dependencies");
const build = src.indexOf('node "$NEXT_BIN" build');
@@ -141,7 +146,7 @@ describe("one-line installer contract", () => {
});
it("bypasses Bun bin remapping for production build and repairs only a missing package payload", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
expect(src).toContain('NEXT_BIN="$DIR/node_modules/next/dist/bin/next"');
expect(src).toContain('node "$NEXT_BIN" build');
expect(src).not.toMatch(/^\s*bun run build\s*$/m);
@@ -151,7 +156,7 @@ describe("one-line installer contract", () => {
});
it("requires systemd as PID 1 before service setup and gates onboarding on verified health", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
expect(src).toContain("systemd_ready()");
expect(src).toContain("/proc/1/comm");
expect(src).toContain('= "systemd"');
@@ -167,7 +172,7 @@ describe("one-line installer contract", () => {
});
it("verifies a commit-pinned Bun bootstrap before execution", () => {
- const src = fs.readFileSync(CORE, "utf8");
+ const src = installerSource();
expect(src).toMatch(/BUN_BOOTSTRAP_COMMIT="[0-9a-f]{40}"/);
expect(src).toMatch(/BUN_BOOTSTRAP_SHA256="[0-9a-f]{64}"/);
expect(src).toContain('raw.githubusercontent.com/oven-sh/bun/$BUN_BOOTSTRAP_COMMIT/src/cli/install.sh');
diff --git a/lib/install-docs-contract.test.ts b/lib/install-docs-contract.test.ts
index 15c0fa0c..727af83c 100644
--- a/lib/install-docs-contract.test.ts
+++ b/lib/install-docs-contract.test.ts
@@ -4,10 +4,13 @@ import path from "node:path";
import { describe, expect, it } from "vitest";
const CORE = path.join(__dirname, "../scripts/install-core.sh");
+const PHASES = ["cli.sh", "runtime-build.sh", "service.sh", "finalize.sh"].map((name) =>
+ path.join(__dirname, "../scripts/install", name),
+);
const README = fs.readFileSync(path.join(__dirname, "../README.md"), "utf8");
const INSTALL = fs.readFileSync(path.join(__dirname, "../docs/INSTALL.md"), "utf8");
const AGENTS = fs.readFileSync(path.join(__dirname, "../AGENTS.md"), "utf8");
-const core = fs.readFileSync(CORE, "utf8");
+const core = [CORE, ...PHASES].map((file) => fs.readFileSync(file, "utf8")).join("\n");
const help = execFileSync("bash", [CORE, "--help"], { encoding: "utf8" });
function publicFlags() {
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index fb7d3790..a05d0b21 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -394,410 +394,15 @@ else
fi
cd "$DIR"
-INSTALL_PHASE=cli
-# ---- CLI on PATH (before deps/build/service so a partial WSL install still gets a CLI) ----
-# The web UI is one frontend; bin/mso reaches the same /api surface from a shell.
-BIN_DIR="${MSO_BIN_DIR:-$HOME/.local/bin}"
-mkdir -p "$BIN_DIR"
-ln -sfn "$DIR/bin/mso" "$BIN_DIR/mso"
-ok "cli → $BIN_DIR/mso"
-
-# A fresh distro/WSL home often omits ~/.local/bin from the current PATH. Persist
-# one small idempotent block for future shells. Default to bash when SHELL is not
-# exported (common in curl|bash/cloud-init); zsh gets its own rc instead.
-path_block() {
- local rc="$1"
- [ -e "$rc" ] || : > "$rc"
- grep -q '^# >>> mso cli >>>$' "$rc" 2>/dev/null && return
- cat >> "$rc" <<'EOF'
-
-# >>> mso cli >>>
-case ":$PATH:" in
- *":$HOME/.local/bin:"*) ;;
- *) export PATH="$HOME/.local/bin:$PATH" ;;
-esac
-# <<< mso cli <<<
-EOF
- info "added ~/.local/bin to PATH in $rc"
-}
-if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
- path_block "$HOME/.profile"
- case "${SHELL:-/bin/bash}" in
- */zsh) path_block "$HOME/.zshrc" ;;
- *) path_block "$HOME/.bashrc" ;;
- esac
-else
- warn "custom MSO_BIN_DIR=$BIN_DIR is not written into shell profiles; add it to PATH yourself"
-fi
-
-# Prove discoverability from the PARENT shell's original PATH. If the user-local
-# directory was already there, nothing else is needed. Otherwise use a guarded
-# launcher in /usr/local/bin (or MSO_SYSTEM_BIN_DIR) only when that directory is
-# already on the invoking PATH. This also makes `--no-service` useful on WSL.
-PARENT_PATH_RESOLVED="$(normalize_parent_path "$PARENT_PATH" "$PARENT_CWD")"
-SYSTEM_BIN_DIR="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}"
-case "$SYSTEM_BIN_DIR" in /*) ;; *) SYSTEM_BIN_DIR="$PARENT_CWD/$SYSTEM_BIN_DIR" ;; esac
-SYSTEM_CLI="$SYSTEM_BIN_DIR/mso"
-TARGET_CLI_REAL="$(readlink -f "$DIR/bin/mso")"
-CLI_IMMEDIATE=0
-parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
-if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
- CLI_IMMEDIATE=1
-elif path_has_dir "$PARENT_PATH_RESOLVED" "$SYSTEM_BIN_DIR"; then
- if link_cli_guarded "$SYSTEM_CLI" "$DIR/bin/mso"; then
- ok "current-PATH cli → $SYSTEM_CLI"
- parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
- if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
- CLI_IMMEDIATE=1
- fi
- else
- warn "could not install $SYSTEM_CLI; the user CLI is still installed at $BIN_DIR/mso"
- fi
-else
- info "$SYSTEM_BIN_DIR is not on the invoking PATH — skipped the extra launcher"
-fi
-
-# Validate the actual launcher independently of PATH. The child installer may use
-# its own exported PATH for onboarding, but that is NOT treated as proof that the
-# parent shell can see the command.
-[ -x "$BIN_DIR/mso" ] || die "CLI launcher target is not executable: $BIN_DIR/mso"
-"$BIN_DIR/mso" -h >/dev/null 2>&1 || die "CLI launcher self-check failed: $BIN_DIR/mso (verify curl/jq/coreutils and rerun)"
-export PATH="$BIN_DIR:$PATH"
-if [ "$CLI_IMMEDIATE" -eq 1 ]; then
- ok "mso -h will resolve immediately after the installer returns ($parent_cli)"
-else
- warn "mso is installed, but this shell's existing PATH cannot see it yet"
- warn "for this shell run: export PATH=\"$BIN_DIR:\$PATH\""
- if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
- info "future shells will load the persisted ~/.local/bin PATH block"
- else
- warn "custom MSO_BIN_DIR is not persisted automatically; add $BIN_DIR to your shell profile"
- fi
-fi
-
-
-INSTALL_PHASE=runtime-safety
-# ---- freeze every runtime that can read this checkout before dependency/build mutation ----
-# The lifecycle remains open through service refresh. A pre-mutation abort restores the
-# known-good service/fallbacks; after mutation starts EXIT preserves recovery intent and
-# never serves the possibly changed tree.
-# shellcheck source=scripts/lib/install-runtime-lifecycle.sh
-. "$DIR/scripts/lib/install-runtime-lifecycle.sh"
-trap install_runtime_lifecycle_cleanup EXIT
-trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM
-install_runtime_lifecycle_begin
-
-INSTALL_PHASE=dependencies
-# ---- deps (compiles node-pty) ----
-info "installing dependencies…"
-install_runtime_lifecycle_mark_mutation_started
-bun install --frozen-lockfile || bun install
-
-INSTALL_PHASE=configuration
-# ---- data dir + secrets (write .env.local only if absent) ----
-mkdir -p "$HOME/.mso" && chmod 700 "$HOME/.mso"
-
-GEN_PW=""
-if [ ! -f .env.local ]; then
- SECRET="$(rand_hex 32)"
- GEN_PW="$(rand_password)"
- ( umask 077
- cat > .env.local <<EOF
-# mso — generated by install.sh. Private; NEVER commit.
-OS_LOGIN_PASSWORD=$GEN_PW
-OS_SESSION_SECRET=$SECRET
-# SESSION_EXPIRY_HOURS=24
-# OS_FS_READ_ROOTS=~:~/projects
-# OS_FS_WRITE_ROOTS=~:~/projects
-# OS_AUDIT_LOG=~/.mso/audit.log
-EOF
- )
- chmod 600 .env.local
- ok "wrote .env.local (login password + session secret generated)"
-else
- info ".env.local exists — left untouched (existing secrets preserved)"
-fi
-
-INSTALL_PHASE=build
-# ---- build ----
-# Do not invoke Next through `bun run build` here. Bun resolves package binaries
-# through node_modules/.bin metadata, and Bun 1.3.x can occasionally leave that
-# metadata unreadable on WSL even when node_modules/next itself is intact. The
-# package entrypoint is ordinary Node.js, so invoke it directly and bypass the
-# remapper entirely. Only force-reinstall when the package payload itself is absent.
-NEXT_BIN="$DIR/node_modules/next/dist/bin/next"
-if [ ! -f "$NEXT_BIN" ]; then
- warn "Next.js package entrypoint is missing after bun install — repairing dependencies once…"
- bun install --force --frozen-lockfile || bun install --force
-fi
-[ -f "$NEXT_BIN" ] || die "Next.js package entrypoint is still missing after dependency repair: $NEXT_BIN"
-info "building (next build via Node entrypoint)…"
-node "$NEXT_BIN" build
-
-INSTALL_PHASE=service
-# ---- systemd unit ----
-if [ "$DO_SERVICE" -eq 1 ] && systemd_ready; then
- SERVICE_ATTEMPTED=1
- # Start via npm (always on PATH, ships with node) to match the proven prod unit;
- # PORT/HOSTNAME are set as env too so `next start` binds correctly regardless.
- NPM_BIN="$(command -v npm)"
- RUNTIME_INSTANCE_ID="$(rand_hex 16)"
- info "installing $SERVICE (needs sudo)…"
- sudo_do tee "/etc/systemd/system/$SERVICE" >/dev/null <<EOF
-[Unit]
-Description=Manef Shell OS — browser-based visual shell for a Linux server
-After=network.target
-
-[Service]
-Type=simple
-User=$(id -un)
-WorkingDirectory=$DIR
-EnvironmentFile=$DIR/.env.local
-Environment=PORT=$PORT
-Environment=HOSTNAME=$BIND
-# Fresh on every installer-driven restart. /api/health echoes this non-secret nonce
-# so readiness proves the HTTP response came from THIS restarted unit, not a stale
-# process that happened to keep answering on the configured port.
-Environment=MSO_RUNTIME_INSTANCE_ID=$RUNTIME_INSTANCE_ID
-# A system unit with User= inherits no login session, so it gets no user-bus
-# address and every \`systemctl --user\` it runs answers "Failed to connect to bus:
-# No medium found". That silently broke the managed-app installs (which create
-# systemd USER units) and made installed apps read as "not installed". Paired with
-# the \`loginctl enable-linger\` below, without which /run/user/<uid> is destroyed
-# at logout.
-#
-# The UID IS WRITTEN OUT, NOT the %U specifier. Do not "tidy" this back to %U — it
-# was tried and it FAILS: with User=example and UID=1000, systemd 255 expanded %U
-# to 0, so the unit got XDG_RUNTIME_DIR=/run/user/0 and every systemctl --user
-# answered "No such file or directory" — the original bug wearing a new message.
-# Specifiers are expanded while the unit is parsed, before the NAME in User= has
-# been resolved to a uid, so %U falls back to the manager's own uid (root).
-Environment=XDG_RUNTIME_DIR=/run/user/$(id -u)
-# systemd would otherwise give this unit only
-# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. Both managed-app CLIs install
-# themselves into ~/.local/bin, so without this \`which hermes\` fails inside the
-# service on a host where it plainly works in a terminal.
-Environment=PATH=$HOME/.local/bin:$HOME/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
-ExecStart=$NPM_BIN run start -- --hostname $BIND --port $PORT
-Restart=always
-RestartSec=5
-KillSignal=SIGTERM
-TimeoutStopSec=20
-MemoryMax=3G
-StandardOutput=journal
-StandardError=journal
-SyslogIdentifier=mso
-
-[Install]
-WantedBy=multi-user.target
-EOF
- # A wildcard bind is not an address you can dial; probe loopback instead.
- HEALTH_HOST="$BIND"
- case "$BIND" in 0.0.0.0|::|"") HEALTH_HOST=127.0.0.1 ;; esac
-
- # Makes /run/user/<uid> — where the user bus lives — exist without a login
- # session and survive logout. The XDG_RUNTIME_DIR above names that directory, so
- # without linger it would point at nothing after the installing shell exits.
- # Idempotent; failure is not fatal, it only means managed-app installs will say
- # so plainly when they preflight the bus.
- sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
- || warn "could not enable linger for $(id -un) — self-update and managed-app user services may stop after logout"
- # `enable-linger` makes the manager persistent, but some minimal images do not
- # start [email protected] until the next login. Start it now so the first update
- # button works immediately, then prove the bus MSO will use actually answers.
- sudo_do systemctl start "user@$(id -u).service" >/dev/null 2>&1 \
- || warn "could not start the per-user systemd manager — self-update may be unavailable"
- if ! XDG_RUNTIME_DIR="/run/user/$(id -u)" systemctl --user show-environment >/dev/null 2>&1; then
- warn "per-user systemd bus is unavailable — self-update and managed-app services will not work until user@$(id -u).service is running"
- fi
-
- sudo_do systemctl daemon-reload
- sudo_do systemctl enable "$SERVICE"
- # restart, NOT `enable --now`. `--now` only *starts*, and a start on a unit
- # that is already running is a no-op — so re-running this installer used to
- # fetch, rebuild and then leave the OLD process serving a .next that had been
- # replaced underneath it. Every chunk 404s and nosniff makes that fatal
- # (docs/TROUBLESHOOTING.md). `restart` starts an inactive unit just as well,
- # so this is also correct on a first install.
- sudo_do systemctl restart "$SERVICE"
- ok "$SERVICE enabled + restarted"
-
- info "waiting for http://$HEALTH_HOST:$PORT/api/health …"
- up=0
- for _ in $(seq 1 30); do
- body="$(curl -fsS --max-time 3 "http://$HEALTH_HOST:$PORT/api/health" 2>/dev/null || true)"
- if [ -n "$body" ]; then
- now_build="$(printf '%s' "$body" | sed -n 's/.*"buildId":"\([^"]*\)".*/\1/p')"
- now_instance="$(printf '%s' "$body" | sed -n 's/.*"runtimeInstanceId":"\([^"]*\)".*/\1/p')"
- # A healthy response is accepted only when it carries the nonce injected into
- # THIS service unit before restart. This remains correct when NEXT_DEPLOYMENT_ID
- # intentionally keeps buildId stable and cannot be satisfied by a stale or
- # unrelated process still listening on the same port.
- if [ "$now_instance" = "$RUNTIME_INSTANCE_ID" ]; then
- up=1; SERVICE_READY=1
- ok "health OK (build ${now_build:-unknown}, runtime instance verified)"
- break
- fi
- fi
- sleep 2
- done
- if [ "$up" -ne 1 ]; then
- # is-active needs no privileges — do not spend a sudo prompt on the sad path.
- if systemctl is-active --quiet "$SERVICE"; then
- warn "service is running but /api/health did not prove the restarted runtime instance — check: journalctl -u mso -e"
- else
- warn "$SERVICE is not running — check: journalctl -u mso -e"
- fi
- fi
-elif [ "$DO_SERVICE" -eq 1 ]; then
- if is_wsl; then
- warn "WSL detected without systemd as PID 1 — service install skipped; the mso CLI is still installed"
- info "for the full service: enable systemd in /etc/wsl.conf, run 'wsl --shutdown' from Windows, reopen WSL, then re-run this installer --onboard"
- else
- warn "systemd is not available as PID 1 — service install skipped; run manually: PORT=$PORT bun run start"
- fi
-fi
-
-INSTALL_PHASE=runtime-restore
-# `.next` and service state are stable. Release the exclusive mutation lock before
-# local-start takes its shared side, then restore every previously-owned fallback
-# using the exact env-file identity persisted with that runtime.
-install_runtime_lifecycle_finish
-trap - EXIT HUP INT TERM
-
-INSTALL_PHASE=integrations
-# ---- optional Claude Code integration ----
-# MSO catalogs $DIR/claude-skills directly, so these symlinks are NOT required by MSO.
-# They only expose the same official playbooks to Claude Code when its home exists.
-SKILL_DIR="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
-if [ -d "$DIR/claude-skills" ] && [ -d "$(dirname "$SKILL_DIR")" ]; then
- mkdir -p "$SKILL_DIR"
- for s in "$DIR"/claude-skills/*/; do
- name="$(basename "$s")"
- if [ -e "$SKILL_DIR/$name" ] && [ ! -L "$SKILL_DIR/$name" ]; then
- warn "skill $name exists and is not a symlink — left alone"
- continue
- fi
- ln -sfn "${s%/}" "$SKILL_DIR/$name"
- done
- # Prune ours that no longer exist. Only symlinks POINTING INTO this repo's
- # claude-skills are touched, so a hand-made or third-party skill is never
- # removed. Without this a deleted skill kept a dangling entry forever and the
- # agent still saw it listed (mso-browser-list did exactly that).
- for l in "$SKILL_DIR"/*; do
- [ -L "$l" ] || continue
- tgt="$(readlink "$l")"
- case "$tgt" in "$DIR/claude-skills/"*) [ -d "$tgt" ] || { rm -f "$l"; info "pruned stale skill $(basename "$l")"; } ;; esac
- done
- ok "skills → $SKILL_DIR (/mso, /mso-camoufox, /mso-apps, /mso-list, …)"
-fi
-
-INSTALL_PHASE=summary
-# ---- next steps ----
-# How to reach it depends on the bind AND on the Secure session cookie: a
-# browser only keeps that cookie over plain http on localhost/127.0.0.1/::1, so
-# any address that is not one of those needs TLS or a tunnel to log in at all.
-WHOAMI="$(id -un)"
-case "$BIND" in
- 127.0.0.1|::1|localhost)
- REACH="tunnel from your own machine:
- ssh -N -L $PORT:127.0.0.1:$PORT $WHOAMI@<this-host>
- then open http://localhost:$PORT
- (or \`tailscale serve $PORT\`, or a TLS reverse proxy → 127.0.0.1:$PORT)" ;;
- 0.0.0.0|::)
- REACH="http://<this-host>:$PORT
- !! bound on EVERY interface. An authenticated session runs commands as
- $WHOAMI — firewall it, or re-run with --bind 127.0.0.1.
- Plain http to an IP also cannot log in: the session cookie is Secure." ;;
- *)
- REACH="http://$BIND:$PORT
- (plain http to a non-loopback address cannot complete a login — the
- session cookie is Secure. Put TLS in front, or tunnel to loopback.)" ;;
-esac
-
-if [ "$SERVICE_READY" -eq 1 ]; then
- OPEN_STATUS="$REACH"
- LOG_STATUS="journalctl -u mso -f"
-elif [ "$DO_SERVICE" -eq 0 ]; then
- OPEN_STATUS="not running (--no-service). Start manually: cd $DIR && PORT=$PORT bun run start"
- LOG_STATUS="no system service installed"
-elif [ "$SERVICE_ATTEMPTED" -eq 1 ]; then
- OPEN_STATUS="service was installed/restarted but did not pass health verification; inspect the journal before opening the UI"
- LOG_STATUS="journalctl -u mso -e"
-elif is_wsl; then
- OPEN_STATUS="not running (WSL systemd is unavailable). Enable systemd or start manually from $DIR"
- LOG_STATUS="no system service installed"
-else
- OPEN_STATUS="systemd is unavailable; start manually from $DIR"
- LOG_STATUS="no system service installed"
-fi
-
-if [ "$FRESH_INSTALL" -eq 1 ]; then
- ok "mso installed at $DIR"
-else
- ok "mso updated at $DIR"
- info "existing .env.local and ~/.mso state preserved"
-fi
-cat <<EOF
-
- Runtime: $OPEN_STATUS
- Env: $DIR/.env.local
-EOF
-[ -n "$GEN_PW" ] && printf ' Password: %s (shown once — save it now; edit OS_LOGIN_PASSWORD in .env.local + service refresh to change)\n' "$GEN_PW"
-if [ "$FRESH_INSTALL" -eq 1 ]; then
-cat <<EOF
-
- Pair your first device after the API is running (device approval is a browser allowlist, not standards-based 2FA):
- 1. FIRST use HTTPS, or an SSH tunnel and http://localhost:$PORT. Do not pair on plain http://<server-ip>:$PORT:
- the Secure session cookie cannot persist there, and changing to an HTTPS hostname creates a different browser device id.
- 2. Enter the password — the browser lands PENDING and shows a device id.
- 3. On this server:
- node $DIR/scripts/approve-device.js --list # see the pending id
- node $DIR/scripts/approve-device.js <deviceId> "my phone" # approve it
- 4. In that SAME browser origin, click "Check again". Approve later devices from Settings → Devices.
-EOF
-fi
-cat <<EOF
-
- Logs: $LOG_STATUS
- Doctor: mso doctor (or: mso doctor --fix for safe local repairs)
- Onboard: mso onboard
- Update: mso update (or Settings → About in the web UI)
- Legacy: re-run the official one-line installer to upgrade/recover an older install
- Uninstall: re-run the installer with --uninstall
- Listen: $BIND:$PORT (change with --bind / MSO_BIND)
- Security: verify from OUTSIDE the box — \`curl -m5 http://<public-ip>:$PORT/api/health\`
- run on your laptop is the only test that proves what is reachable.
- Review ~/.mso/audit.log.
-EOF
-
-INSTALL_PHASE=onboarding
-# A successful fresh install should lead directly into a usable product. curl|bash
-# owns stdin, so interactive setup uses the controlling terminal explicitly.
-RUN_ONBOARD=0
-case "$ONBOARD_MODE" in
- always) RUN_ONBOARD=1 ;;
- never) RUN_ONBOARD=0 ;;
- auto) [ "$FRESH_INSTALL" -eq 1 ] && RUN_ONBOARD=1 ;;
-esac
-if [ "$RUN_ONBOARD" -eq 1 ] && [ "$SERVICE_READY" -eq 1 ]; then
- if [ "$YES" -eq 1 ]; then
- echo
- info "running minimal non-interactive onboarding (-y)…"
- "$BIN_DIR/mso" onboard -y || warn "onboarding did not finish — run: mso doctor --fix ; then: mso onboard"
- elif [ -r /dev/tty ] && [ -w /dev/tty ]; then
- echo
- info "starting guided onboarding…"
- if ! "$BIN_DIR/mso" onboard </dev/tty >/dev/tty 2>/dev/tty; then
- warn "onboarding stopped early — run: mso doctor --fix ; then resume: mso onboard"
- fi
- else
- echo
- warn "no interactive terminal detected — onboarding skipped. Run: mso onboard"
- fi
-elif [ "$RUN_ONBOARD" -eq 1 ]; then
- warn "no verified running MSO API is available for onboarding — start/enable the service, then run 'mso onboard'"
-fi
+# ---- post-checkout phases ----
+# Fresh installs have the requested checkout now, so the rest of the installer is
+# split into bounded repo-owned phases without adding bootstrap downloads.
+for phase in cli runtime-build service finalize; do
+ module="$DIR/scripts/install/$phase.sh"
+ [ -f "$module" ] || die "installer phase missing from checkout: $module"
+ # shellcheck source=/dev/null
+ . "$module"
+done
INSTALL_PHASE=complete
# MSO_INSTALLER_CORE_EOF
diff --git a/scripts/install.sh b/scripts/install.sh
index 75bdcc64..816526ea 100755
--- a/scripts/install.sh
+++ b/scripts/install.sh
@@ -12,7 +12,7 @@ set -Eeuo pipefail
umask 077
CORE_URL="${MSO_INSTALL_CORE_URL:-https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install-core.sh}"
-CORE_SHA256="b769aea7c8b21a34d49222da6d6384ec4ebd917eb5cde97c7b62083e92217c91"
+CORE_SHA256="09fc92677ad4082102f867717aa00774466920320d4958bc94384c69562bcb31"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
TMP_INSTALLER=''
diff --git a/scripts/install/cli.sh b/scripts/install/cli.sh
new file mode 100755
index 00000000..7a11f345
--- /dev/null
+++ b/scripts/install/cli.sh
@@ -0,0 +1,82 @@
+#!/usr/bin/env bash
+# Install/prove the CLI launcher and invoking-shell PATH Sourced by the verified installer core after checkout.
+INSTALL_PHASE=cli
+# ---- CLI on PATH (before deps/build/service so a partial WSL install still gets a CLI) ----
+# The web UI is one frontend; bin/mso reaches the same /api surface from a shell.
+BIN_DIR="${MSO_BIN_DIR:-$HOME/.local/bin}"
+mkdir -p "$BIN_DIR"
+ln -sfn "$DIR/bin/mso" "$BIN_DIR/mso"
+ok "cli → $BIN_DIR/mso"
+
+# A fresh distro/WSL home often omits ~/.local/bin from the current PATH. Persist
+# one small idempotent block for future shells. Default to bash when SHELL is not
+# exported (common in curl|bash/cloud-init); zsh gets its own rc instead.
+path_block() {
+ local rc="$1"
+ [ -e "$rc" ] || : > "$rc"
+ grep -q '^# >>> mso cli >>>$' "$rc" 2>/dev/null && return
+ cat >> "$rc" <<'EOF'
+
+# >>> mso cli >>>
+case ":$PATH:" in
+ *":$HOME/.local/bin:"*) ;;
+ *) export PATH="$HOME/.local/bin:$PATH" ;;
+esac
+# <<< mso cli <<<
+EOF
+ info "added ~/.local/bin to PATH in $rc"
+}
+if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
+ path_block "$HOME/.profile"
+ case "${SHELL:-/bin/bash}" in
+ */zsh) path_block "$HOME/.zshrc" ;;
+ *) path_block "$HOME/.bashrc" ;;
+ esac
+else
+ warn "custom MSO_BIN_DIR=$BIN_DIR is not written into shell profiles; add it to PATH yourself"
+fi
+
+# Prove discoverability from the PARENT shell's original PATH. If the user-local
+# directory was already there, nothing else is needed. Otherwise use a guarded
+# launcher in /usr/local/bin (or MSO_SYSTEM_BIN_DIR) only when that directory is
+# already on the invoking PATH. This also makes `--no-service` useful on WSL.
+PARENT_PATH_RESOLVED="$(normalize_parent_path "$PARENT_PATH" "$PARENT_CWD")"
+SYSTEM_BIN_DIR="${MSO_SYSTEM_BIN_DIR:-/usr/local/bin}"
+case "$SYSTEM_BIN_DIR" in /*) ;; *) SYSTEM_BIN_DIR="$PARENT_CWD/$SYSTEM_BIN_DIR" ;; esac
+SYSTEM_CLI="$SYSTEM_BIN_DIR/mso"
+TARGET_CLI_REAL="$(readlink -f "$DIR/bin/mso")"
+CLI_IMMEDIATE=0
+parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
+if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
+ CLI_IMMEDIATE=1
+elif path_has_dir "$PARENT_PATH_RESOLVED" "$SYSTEM_BIN_DIR"; then
+ if link_cli_guarded "$SYSTEM_CLI" "$DIR/bin/mso"; then
+ ok "current-PATH cli → $SYSTEM_CLI"
+ parent_cli="$(PATH="$PARENT_PATH_RESOLVED" command -v mso 2>/dev/null || true)"
+ if [ -n "$parent_cli" ] && [ "$(readlink -f "$parent_cli" 2>/dev/null || true)" = "$TARGET_CLI_REAL" ]; then
+ CLI_IMMEDIATE=1
+ fi
+ else
+ warn "could not install $SYSTEM_CLI; the user CLI is still installed at $BIN_DIR/mso"
+ fi
+else
+ info "$SYSTEM_BIN_DIR is not on the invoking PATH — skipped the extra launcher"
+fi
+
+# Validate the actual launcher independently of PATH. The child installer may use
+# its own exported PATH for onboarding, but that is NOT treated as proof that the
+# parent shell can see the command.
+[ -x "$BIN_DIR/mso" ] || die "CLI launcher target is not executable: $BIN_DIR/mso"
+"$BIN_DIR/mso" -h >/dev/null 2>&1 || die "CLI launcher self-check failed: $BIN_DIR/mso (verify curl/jq/coreutils and rerun)"
+export PATH="$BIN_DIR:$PATH"
+if [ "$CLI_IMMEDIATE" -eq 1 ]; then
+ ok "mso -h will resolve immediately after the installer returns ($parent_cli)"
+else
+ warn "mso is installed, but this shell's existing PATH cannot see it yet"
+ warn "for this shell run: export PATH=\"$BIN_DIR:\$PATH\""
+ if [ "$BIN_DIR" = "$HOME/.local/bin" ]; then
+ info "future shells will load the persisted ~/.local/bin PATH block"
+ else
+ warn "custom MSO_BIN_DIR is not persisted automatically; add $BIN_DIR to your shell profile"
+ fi
+fi
diff --git a/scripts/install/finalize.sh b/scripts/install/finalize.sh
new file mode 100755
index 00000000..63df1c03
--- /dev/null
+++ b/scripts/install/finalize.sh
@@ -0,0 +1,135 @@
+#!/usr/bin/env bash
+# Integrations, summary, reachability guidance, and onboarding Sourced by the verified installer core after checkout.
+INSTALL_PHASE=integrations
+# ---- optional Claude Code integration ----
+# MSO catalogs $DIR/claude-skills directly, so these symlinks are NOT required by MSO.
+# They only expose the same official playbooks to Claude Code when its home exists.
+SKILL_DIR="${MSO_SKILL_DIR:-$HOME/.claude/skills}"
+if [ -d "$DIR/claude-skills" ] && [ -d "$(dirname "$SKILL_DIR")" ]; then
+ mkdir -p "$SKILL_DIR"
+ for s in "$DIR"/claude-skills/*/; do
+ name="$(basename "$s")"
+ if [ -e "$SKILL_DIR/$name" ] && [ ! -L "$SKILL_DIR/$name" ]; then
+ warn "skill $name exists and is not a symlink — left alone"
+ continue
+ fi
+ ln -sfn "${s%/}" "$SKILL_DIR/$name"
+ done
+ # Prune ours that no longer exist. Only symlinks POINTING INTO this repo's
+ # claude-skills are touched, so a hand-made or third-party skill is never
+ # removed. Without this a deleted skill kept a dangling entry forever and the
+ # agent still saw it listed (mso-browser-list did exactly that).
+ for l in "$SKILL_DIR"/*; do
+ [ -L "$l" ] || continue
+ tgt="$(readlink "$l")"
+ case "$tgt" in "$DIR/claude-skills/"*) [ -d "$tgt" ] || { rm -f "$l"; info "pruned stale skill $(basename "$l")"; } ;; esac
+ done
+ ok "skills → $SKILL_DIR (/mso, /mso-camoufox, /mso-apps, /mso-list, …)"
+fi
+
+INSTALL_PHASE=summary
+# ---- next steps ----
+# How to reach it depends on the bind AND on the Secure session cookie: a
+# browser only keeps that cookie over plain http on localhost/127.0.0.1/::1, so
+# any address that is not one of those needs TLS or a tunnel to log in at all.
+WHOAMI="$(id -un)"
+case "$BIND" in
+ 127.0.0.1|::1|localhost)
+ REACH="tunnel from your own machine:
+ ssh -N -L $PORT:127.0.0.1:$PORT $WHOAMI@<this-host>
+ then open http://localhost:$PORT
+ (or \`tailscale serve $PORT\`, or a TLS reverse proxy → 127.0.0.1:$PORT)" ;;
+ 0.0.0.0|::)
+ REACH="http://<this-host>:$PORT
+ !! bound on EVERY interface. An authenticated session runs commands as
+ $WHOAMI — firewall it, or re-run with --bind 127.0.0.1.
+ Plain http to an IP also cannot log in: the session cookie is Secure." ;;
+ *)
+ REACH="http://$BIND:$PORT
+ (plain http to a non-loopback address cannot complete a login — the
+ session cookie is Secure. Put TLS in front, or tunnel to loopback.)" ;;
+esac
+
+if [ "$SERVICE_READY" -eq 1 ]; then
+ OPEN_STATUS="$REACH"
+ LOG_STATUS="journalctl -u mso -f"
+elif [ "$DO_SERVICE" -eq 0 ]; then
+ OPEN_STATUS="not running (--no-service). Start manually: cd $DIR && PORT=$PORT bun run start"
+ LOG_STATUS="no system service installed"
+elif [ "$SERVICE_ATTEMPTED" -eq 1 ]; then
+ OPEN_STATUS="service was installed/restarted but did not pass health verification; inspect the journal before opening the UI"
+ LOG_STATUS="journalctl -u mso -e"
+elif is_wsl; then
+ OPEN_STATUS="not running (WSL systemd is unavailable). Enable systemd or start manually from $DIR"
+ LOG_STATUS="no system service installed"
+else
+ OPEN_STATUS="systemd is unavailable; start manually from $DIR"
+ LOG_STATUS="no system service installed"
+fi
+
+if [ "$FRESH_INSTALL" -eq 1 ]; then
+ ok "mso installed at $DIR"
+else
+ ok "mso updated at $DIR"
+ info "existing .env.local and ~/.mso state preserved"
+fi
+cat <<EOF
+
+ Runtime: $OPEN_STATUS
+ Env: $DIR/.env.local
+EOF
+[ -n "$GEN_PW" ] && printf ' Password: %s (shown once — save it now; edit OS_LOGIN_PASSWORD in .env.local + service refresh to change)\n' "$GEN_PW"
+if [ "$FRESH_INSTALL" -eq 1 ]; then
+cat <<EOF
+
+ Pair your first device after the API is running (device approval is a browser allowlist, not standards-based 2FA):
+ 1. FIRST use HTTPS, or an SSH tunnel and http://localhost:$PORT. Do not pair on plain http://<server-ip>:$PORT:
+ the Secure session cookie cannot persist there, and changing to an HTTPS hostname creates a different browser device id.
+ 2. Enter the password — the browser lands PENDING and shows a device id.
+ 3. On this server:
+ node $DIR/scripts/approve-device.js --list # see the pending id
+ node $DIR/scripts/approve-device.js <deviceId> "my phone" # approve it
+ 4. In that SAME browser origin, click "Check again". Approve later devices from Settings → Devices.
+EOF
+fi
+cat <<EOF
+
+ Logs: $LOG_STATUS
+ Doctor: mso doctor (or: mso doctor --fix for safe local repairs)
+ Onboard: mso onboard
+ Update: mso update (or Settings → About in the web UI)
+ Legacy: re-run the official one-line installer to upgrade/recover an older install
+ Uninstall: re-run the installer with --uninstall
+ Listen: $BIND:$PORT (change with --bind / MSO_BIND)
+ Security: verify from OUTSIDE the box — \`curl -m5 http://<public-ip>:$PORT/api/health\`
+ run on your laptop is the only test that proves what is reachable.
+ Review ~/.mso/audit.log.
+EOF
+
+INSTALL_PHASE=onboarding
+# A successful fresh install should lead directly into a usable product. curl|bash
+# owns stdin, so interactive setup uses the controlling terminal explicitly.
+RUN_ONBOARD=0
+case "$ONBOARD_MODE" in
+ always) RUN_ONBOARD=1 ;;
+ never) RUN_ONBOARD=0 ;;
+ auto) [ "$FRESH_INSTALL" -eq 1 ] && RUN_ONBOARD=1 ;;
+esac
+if [ "$RUN_ONBOARD" -eq 1 ] && [ "$SERVICE_READY" -eq 1 ]; then
+ if [ "$YES" -eq 1 ]; then
+ echo
+ info "running minimal non-interactive onboarding (-y)…"
+ "$BIN_DIR/mso" onboard -y || warn "onboarding did not finish — run: mso doctor --fix ; then: mso onboard"
+ elif [ -r /dev/tty ] && [ -w /dev/tty ]; then
+ echo
+ info "starting guided onboarding…"
+ if ! "$BIN_DIR/mso" onboard </dev/tty >/dev/tty 2>/dev/tty; then
+ warn "onboarding stopped early — run: mso doctor --fix ; then resume: mso onboard"
+ fi
+ else
+ echo
+ warn "no interactive terminal detected — onboarding skipped. Run: mso onboard"
+ fi
+elif [ "$RUN_ONBOARD" -eq 1 ]; then
+ warn "no verified running MSO API is available for onboarding — start/enable the service, then run 'mso onboard'"
+fi
diff --git a/scripts/install/runtime-build.sh b/scripts/install/runtime-build.sh
new file mode 100755
index 00000000..dda56acb
--- /dev/null
+++ b/scripts/install/runtime-build.sh
@@ -0,0 +1,59 @@
+#!/usr/bin/env bash
+# Quiesce runtime, install dependencies/config, and build Sourced by the verified installer core after checkout.
+INSTALL_PHASE=runtime-safety
+# ---- freeze every runtime that can read this checkout before dependency/build mutation ----
+# The lifecycle remains open through service refresh. A pre-mutation abort restores the
+# known-good service/fallbacks; after mutation starts EXIT preserves recovery intent and
+# never serves the possibly changed tree.
+# shellcheck source=scripts/lib/install-runtime-lifecycle.sh
+. "$DIR/scripts/lib/install-runtime-lifecycle.sh"
+trap install_runtime_lifecycle_cleanup EXIT
+trap 'exit 129' HUP; trap 'exit 130' INT; trap 'exit 143' TERM
+install_runtime_lifecycle_begin
+
+INSTALL_PHASE=dependencies
+# ---- deps (compiles node-pty) ----
+info "installing dependencies…"
+install_runtime_lifecycle_mark_mutation_started
+bun install --frozen-lockfile || bun install
+
+INSTALL_PHASE=configuration
+# ---- data dir + secrets (write .env.local only if absent) ----
+mkdir -p "$HOME/.mso" && chmod 700 "$HOME/.mso"
+
+GEN_PW=""
+if [ ! -f .env.local ]; then
+ SECRET="$(rand_hex 32)"
+ GEN_PW="$(rand_password)"
+ ( umask 077
+ cat > .env.local <<EOF
+# mso — generated by install.sh. Private; NEVER commit.
+OS_LOGIN_PASSWORD=$GEN_PW
+OS_SESSION_SECRET=$SECRET
+# SESSION_EXPIRY_HOURS=24
+# OS_FS_READ_ROOTS=~:~/projects
+# OS_FS_WRITE_ROOTS=~:~/projects
+# OS_AUDIT_LOG=~/.mso/audit.log
+EOF
+ )
+ chmod 600 .env.local
+ ok "wrote .env.local (login password + session secret generated)"
+else
+ info ".env.local exists — left untouched (existing secrets preserved)"
+fi
+
+INSTALL_PHASE=build
+# ---- build ----
+# Do not invoke Next through `bun run build` here. Bun resolves package binaries
+# through node_modules/.bin metadata, and Bun 1.3.x can occasionally leave that
+# metadata unreadable on WSL even when node_modules/next itself is intact. The
+# package entrypoint is ordinary Node.js, so invoke it directly and bypass the
+# remapper entirely. Only force-reinstall when the package payload itself is absent.
+NEXT_BIN="$DIR/node_modules/next/dist/bin/next"
+if [ ! -f "$NEXT_BIN" ]; then
+ warn "Next.js package entrypoint is missing after bun install — repairing dependencies once…"
+ bun install --force --frozen-lockfile || bun install --force
+fi
+[ -f "$NEXT_BIN" ] || die "Next.js package entrypoint is still missing after dependency repair: $NEXT_BIN"
+info "building (next build via Node entrypoint)…"
+node "$NEXT_BIN" build
diff --git a/scripts/install/service.sh b/scripts/install/service.sh
new file mode 100755
index 00000000..681df650
--- /dev/null
+++ b/scripts/install/service.sh
@@ -0,0 +1,132 @@
+#!/usr/bin/env bash
+# Install/restart/verify the systemd service and restore fallbacks Sourced by the verified installer core after checkout.
+INSTALL_PHASE=service
+# ---- systemd unit ----
+if [ "$DO_SERVICE" -eq 1 ] && systemd_ready; then
+ SERVICE_ATTEMPTED=1
+ # Start via npm (always on PATH, ships with node) to match the proven prod unit;
+ # PORT/HOSTNAME are set as env too so `next start` binds correctly regardless.
+ NPM_BIN="$(command -v npm)"
+ RUNTIME_INSTANCE_ID="$(rand_hex 16)"
+ info "installing $SERVICE (needs sudo)…"
+ sudo_do tee "/etc/systemd/system/$SERVICE" >/dev/null <<EOF
+[Unit]
+Description=Manef Shell OS — browser-based visual shell for a Linux server
+After=network.target
+
+[Service]
+Type=simple
+User=$(id -un)
+WorkingDirectory=$DIR
+EnvironmentFile=$DIR/.env.local
+Environment=PORT=$PORT
+Environment=HOSTNAME=$BIND
+# Fresh on every installer-driven restart. /api/health echoes this non-secret nonce
+# so readiness proves the HTTP response came from THIS restarted unit, not a stale
+# process that happened to keep answering on the configured port.
+Environment=MSO_RUNTIME_INSTANCE_ID=$RUNTIME_INSTANCE_ID
+# A system unit with User= inherits no login session, so it gets no user-bus
+# address and every \`systemctl --user\` it runs answers "Failed to connect to bus:
+# No medium found". That silently broke the managed-app installs (which create
+# systemd USER units) and made installed apps read as "not installed". Paired with
+# the \`loginctl enable-linger\` below, without which /run/user/<uid> is destroyed
+# at logout.
+#
+# The UID IS WRITTEN OUT, NOT the %U specifier. Do not "tidy" this back to %U — it
+# was tried and it FAILS: with User=example and UID=1000, systemd 255 expanded %U
+# to 0, so the unit got XDG_RUNTIME_DIR=/run/user/0 and every systemctl --user
+# answered "No such file or directory" — the original bug wearing a new message.
+# Specifiers are expanded while the unit is parsed, before the NAME in User= has
+# been resolved to a uid, so %U falls back to the manager's own uid (root).
+Environment=XDG_RUNTIME_DIR=/run/user/$(id -u)
+# systemd would otherwise give this unit only
+# /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin. Both managed-app CLIs install
+# themselves into ~/.local/bin, so without this \`which hermes\` fails inside the
+# service on a host where it plainly works in a terminal.
+Environment=PATH=$HOME/.local/bin:$HOME/.bun/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
+ExecStart=$NPM_BIN run start -- --hostname $BIND --port $PORT
+Restart=always
+RestartSec=5
+KillSignal=SIGTERM
+TimeoutStopSec=20
+MemoryMax=3G
+StandardOutput=journal
+StandardError=journal
+SyslogIdentifier=mso
+
+[Install]
+WantedBy=multi-user.target
+EOF
+ # A wildcard bind is not an address you can dial; probe loopback instead.
+ HEALTH_HOST="$BIND"
+ case "$BIND" in 0.0.0.0|::|"") HEALTH_HOST=127.0.0.1 ;; esac
+
+ # Makes /run/user/<uid> — where the user bus lives — exist without a login
+ # session and survive logout. The XDG_RUNTIME_DIR above names that directory, so
+ # without linger it would point at nothing after the installing shell exits.
+ # Idempotent; failure is not fatal, it only means managed-app installs will say
+ # so plainly when they preflight the bus.
+ sudo_do loginctl enable-linger "$(id -un)" >/dev/null 2>&1 \
+ || warn "could not enable linger for $(id -un) — self-update and managed-app user services may stop after logout"
+ # `enable-linger` makes the manager persistent, but some minimal images do not
+ # start [email protected] until the next login. Start it now so the first update
+ # button works immediately, then prove the bus MSO will use actually answers.
+ sudo_do systemctl start "user@$(id -u).service" >/dev/null 2>&1 \
+ || warn "could not start the per-user systemd manager — self-update may be unavailable"
+ if ! XDG_RUNTIME_DIR="/run/user/$(id -u)" systemctl --user show-environment >/dev/null 2>&1; then
+ warn "per-user systemd bus is unavailable — self-update and managed-app services will not work until user@$(id -u).service is running"
+ fi
+
+ sudo_do systemctl daemon-reload
+ sudo_do systemctl enable "$SERVICE"
+ # restart, NOT `enable --now`. `--now` only *starts*, and a start on a unit
+ # that is already running is a no-op — so re-running this installer used to
+ # fetch, rebuild and then leave the OLD process serving a .next that had been
+ # replaced underneath it. Every chunk 404s and nosniff makes that fatal
+ # (docs/TROUBLESHOOTING.md). `restart` starts an inactive unit just as well,
+ # so this is also correct on a first install.
+ sudo_do systemctl restart "$SERVICE"
+ ok "$SERVICE enabled + restarted"
+
+ info "waiting for http://$HEALTH_HOST:$PORT/api/health …"
+ up=0
+ for _ in $(seq 1 30); do
+ body="$(curl -fsS --max-time 3 "http://$HEALTH_HOST:$PORT/api/health" 2>/dev/null || true)"
+ if [ -n "$body" ]; then
+ now_build="$(printf '%s' "$body" | sed -n 's/.*"buildId":"\([^"]*\)".*/\1/p')"
+ now_instance="$(printf '%s' "$body" | sed -n 's/.*"runtimeInstanceId":"\([^"]*\)".*/\1/p')"
+ # A healthy response is accepted only when it carries the nonce injected into
+ # THIS service unit before restart. This remains correct when NEXT_DEPLOYMENT_ID
+ # intentionally keeps buildId stable and cannot be satisfied by a stale or
+ # unrelated process still listening on the same port.
+ if [ "$now_instance" = "$RUNTIME_INSTANCE_ID" ]; then
+ up=1; SERVICE_READY=1
+ ok "health OK (build ${now_build:-unknown}, runtime instance verified)"
+ break
+ fi
+ fi
+ sleep 2
+ done
+ if [ "$up" -ne 1 ]; then
+ # is-active needs no privileges — do not spend a sudo prompt on the sad path.
+ if systemctl is-active --quiet "$SERVICE"; then
+ warn "service is running but /api/health did not prove the restarted runtime instance — check: journalctl -u mso -e"
+ else
+ warn "$SERVICE is not running — check: journalctl -u mso -e"
+ fi
+ fi
+elif [ "$DO_SERVICE" -eq 1 ]; then
+ if is_wsl; then
+ warn "WSL detected without systemd as PID 1 — service install skipped; the mso CLI is still installed"
+ info "for the full service: enable systemd in /etc/wsl.conf, run 'wsl --shutdown' from Windows, reopen WSL, then re-run this installer --onboard"
+ else
+ warn "systemd is not available as PID 1 — service install skipped; run manually: PORT=$PORT bun run start"
+ fi
+fi
+
+INSTALL_PHASE=runtime-restore
+# `.next` and service state are stable. Release the exclusive mutation lock before
+# local-start takes its shared side, then restore every previously-owned fallback
+# using the exact env-file identity persisted with that runtime.
+install_runtime_lifecycle_finish
+trap - EXIT HUP INT TERM
diff --git a/scripts/release-lifecycle-contract.test.ts b/scripts/release-lifecycle-contract.test.ts
new file mode 100644
index 00000000..938705f7
--- /dev/null
+++ b/scripts/release-lifecycle-contract.test.ts
@@ -0,0 +1,32 @@
+import fs from "node:fs";
+import path from "node:path";
+import { describe, expect, it } from "vitest";
+
+const ROOT = process.cwd();
+const read = (rel: string) => fs.readFileSync(path.join(ROOT, rel), "utf8");
+
+describe("single MSO release lifecycle authority", () => {
+ it("routes ship, update and CLI deploy through mso-service-update", () => {
+ const ship = read("scripts/ship-handoff.sh");
+ const update = read("scripts/mso-update");
+ const cli = read("scripts/cli/service.sh");
+ expect(ship).toContain('SERVICE_UPDATE="$ROOT/scripts/mso-service-update"');
+ expect(ship).toContain('/bin/bash "$SERVICE_UPDATE" --ship-finalize');
+ expect(update).toContain('/bin/bash "$ROOT/scripts/mso-service-update"');
+ expect(cli).toContain('MSO_SERVICE_UPDATE_BIN:-$ROOT/scripts/mso-service-update');
+ expect(cli).toContain('/bin/bash "$helper" --rebuild-only');
+ });
+
+ it("keeps build/restart inside the shared inner lifecycle and success outside it", () => {
+ const outer = read("scripts/mso-service-update");
+ const inner = read("scripts/self-update.sh");
+ expect(outer).toContain('SELF_UPDATE="$ROOT/scripts/self-update.sh"');
+ expect(outer).toContain('/bin/bash "$SELF_UPDATE" "$@"');
+ expect(inner).toContain("verify-build.sh");
+ expect(inner).toMatch(/restart/i);
+ const restore = outer.indexOf("update_gateway_restore_all");
+ const success = outer.lastIndexOf("UPDATE OK");
+ expect(restore).toBeGreaterThan(0);
+ expect(success).toBeGreaterThan(restore);
+ });
+});