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.

feat: add safe local maintenance and visual README

Rahmanba63cec51a9c
diff --git a/CLAUDE.md b/CLAUDE.md
index 67816b18..ba45c6e6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -52,7 +52,7 @@ is the WHY; CHANGELOG is the WHAT, and it is what Settings → About renders as
**Comparison is generated policy, not hand-written marketing.** Edit only
`docs/comparison-data.json`, then run `node scripts/gen-comparison.mjs`. The generator owns the
-README block and `docs/COMPARISON.md`, requires an existing repo evidence path for each MSO cell,
+short README reference and full `docs/COMPARISON.md`, requires an existing repo evidence path for each MSO cell,
restricts competitor sources to reviewed official hosts, requires the SEO-readable words `Strong`,
`Partial`, and `Not offered` rather than icon-only status legends, and expires review after 90 days.
Do not raise a rating because a feature is planned; implementation evidence must land first.
diff --git a/README.md b/README.md
index cf6ef769..8319ba70 100644
--- a/README.md
+++ b/README.md
@@ -1,577 +1,97 @@
<h1 align="center">Manef Shell OS</h1>
-<p align="center"><strong>Your Linux server. One private workspace.</strong></p>
-<p align="center">A real terminal, files, system health, and an AI assistant — from your phone or desktop.</p>
+<p align="center"><strong>Your server. A workspace, not another dashboard.</strong></p>
+<p align="center">Terminal · files · AI · system health — from a browser or CLI.</p>
+<p align="center"><a href="./docs/INSTALL.md">Install</a> · <a href="./docs/CLI.md">CLI</a> · <a href="./docs/README.md">Docs</a> · <a href="./SECURITY.md">Security</a></p>
-<p align="center">
- <a href="#install">Install</a> ·
- <a href="./docs/media/demo.gif">Watch the demo</a> ·
- <a href="./docs/README.md">Documentation</a> ·
- <a href="./SECURITY.md">Security</a>
-</p>
+![MSO desktop and mobile workspace](./docs/media/mso-hero.webp)
-<p align="center">
- <a href="https://github.com/rahmanef63/mso/actions/workflows/ci.yml"><img alt="CI status" src="https://github.com/rahmanef63/mso/actions/workflows/ci.yml/badge.svg" /></a>
- <a href="https://github.com/rahmanef63/mso/actions/workflows/security-core.yml"><img alt="Security checks" src="https://github.com/rahmanef63/mso/actions/workflows/security-core.yml/badge.svg" /></a>
- <img alt="App version" src="https://img.shields.io/github/package-json/v/rahmanef63/mso?label=app" />
- <img alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue" />
- <img alt="Public Alpha — Developer Preview" src="https://img.shields.io/badge/status-Public_Alpha-orange" />
-</p>
+## One workspace
-![MSO browser workspace on desktop and mobile](./docs/media/mso-hero.webp)
+| Operate | Create | Automate |
+|---|---|---|
+| PTY terminal · files · system health | Code · image/video tools · browser | Alfa assistant · trusted skills · optional MCP |
+| Exact-allowlist service controls | Desktop windows · mobile layouts | Approvals · durable sessions · local memory |
-**MSO is a self-hosted visual shell for a Linux server you own.** It runs as a normal,
-non-root Node process, without a required database or separate agent service. The browser,
-CLI, and optional MCP interface use the same guarded host capabilities.
+## In your terminal
-> **Public Alpha / Developer Preview.** An Owner session or exec-scoped agent can execute
-> commands as the service user. Use a dedicated non-root account and a VPN or tightly protected
-> HTTPS proxy. MSO is not an operating system, a multi-tenant security boundary, or a certified security product.
-
-## What you can do
-
-| Workspace | What it provides |
-|---|---|
-| **Operate your server** | Interactive PTY terminal, CPU/memory/disk metrics, service inventory and exact-allowlist lifecycle actions. |
-| **Work with files** | Browse, edit, upload, search, preview and organize files inside configured filesystem roots. |
-| **Work with AI** | Alfa browser cockpit, terminal agent, durable sessions, trusted skills, explicit mutation approvals and optional MCP access. |
-| **Use one responsive shell** | Desktop windows and mobile-first surfaces, media tools, a separate-origin browser and optional managed-app integrations. |
-
-<details>
-<summary><strong>Feature details and scoped benchmark evidence</strong></summary>
-
-**Control** — terminal, files, services, package visibility, and system health for the server you own.
-
-- **Open a real terminal** — interactive PTY support for tools like `vim`, `top`, and `ssh`.
-- **Manage files** — browse, upload, search, preview, rename, move, copy, zip, and delete within configured filesystem roots.
-- **Inspect system health** — view live CPU, memory, disk, network, process, and uptime signals.
-- **Operate services safely** — inventory system and user `systemd` units, read bounded journal output, and expose start/stop/restart only for exact owner-configured allowlist entries.
-- **See pending package updates** — read the package manager’s existing local cache without refreshing repositories or applying an upgrade.
-- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update` (`mso update run` remains a compatibility alias). The CLI update path is Git-based and still works when the web runtime is down.
-- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain or split-origin host as the in-shell dashboard; its Docker port is loopback-only unless public exposure is explicitly enabled. See [docs/MANAGED-APPS.md](./docs/MANAGED-APPS.md).
-
-**Work** — code/text editor, browser, and media tools in the same workspace.
-
-- **Edit project files** — open text/code files from the file manager without context switching.
-- **Preview almost anything** — images (including HEIC/TIFF), audio, video, PDFs, plain text, Markdown, CSV/TSV and HTML, with ← → paging through the folder. Formats no browser can render (Office, iWork, archives, installers) say so and offer the download instead of a blank frame. HTML renders in a fully sandboxed frame, never as a document on MSO's own origin.
-- **Keep admin context together** — move between terminal, files, metrics, services, package updates, and browser views.
-- **Delegate by device** — approve a browser as Viewer, Operator, or Owner. Roles are rechecked on every request; they are an MSO application boundary, not Linux accounts or enterprise SSO.
-
-**Extend** — Alfa AI, modular slices, and custom apps.
-
-- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
-- **Use Alfa Cockpit** — the in-browser assistant now surfaces selected high-value MSO runtime context at the point of execution: active provider/model, searchable project context, trusted host Skills, typed-memory status, native agent sessions, same-principal local-agent presence, pending approvals, and one Activity & Runs timeline. The Cockpit intentionally does **not** claim full CLI parity; credentials/server wiring stay in Settings and dangerous actions still use Alfa's existing approval cards. The same read-model is scriptable as `mso cockpit [project]` / `mso cockpit search <query>`, so the UI does not own a parallel project/session/memory implementation.
-- **Run saved Automations for real** — browser-local automation recipes now re-enter Alfa's normal tool loop instead of only narrating their steps. Reads execute through the existing host bindings; write/exec steps keep the same per-call human approval gate. Playbook starter prompts also appear as bounded quick actions in an empty chat.
-- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](./docs/INFRASTRUCTURE-PROVIDERS.md).
-- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — MSO exposes one generic OAuth MCP server. ChatGPT gets a source-generated compact static profile with complete title/safety/security metadata, resource-bound OAuth + rotating refresh tokens, while other MCP clients can use the full catalog. Exact current counts and hashes live in [the generated MCP catalog](./docs/generated/MCP-CATALOG.md) so this README does not freeze a stale scanner count. Project-owned MCP tool names never enter the global list: discover/call them dynamically through the generic `project_mcp_tools` / `project_mcp_call` seam. See the [ChatGPT custom MCP guide](./docs/CHATGPT-PLUGIN.md) and [MCP reference](./docs/MCP.md).
-- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. For ChatGPT/MCP sessions, `local_agent_inbox(wait_ms=...)` temporarily turns the foreground MCP call into that live receiver for up to 20 seconds, enabling direct two-way session messaging without a worker, DB, webhook, or broker. See [Local Agents](./docs/LOCAL-AGENTS.md).
-- **Spawn focused same-session subagents** — `/spawn` and `agent_subagent_run` create bounded foreground workers with isolated context, explicit delegated scope, turn/timeout caps, no recursive spawn, and final-result-only return. They are not Local Agent peers and do not run autonomously after the parent call returns. See [Subagents](./docs/SUBAGENTS.md).
-- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](./docs/A2A.md).
-- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, uses the RASMIC catalog-first router to select a small per-turn capability pack without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, learns only verified workflow recipes, gates repeated procedures through Tool Forge, and batches/filter/aggregates independent reads through `read_pipeline` before raw data reaches the model. Executable Tool Forge candidates require the explicitly provisioned local Forge sandbox and fail closed when that image is absent. `bun run bench:cognitive`, `bun run bench:memory:calibration`, `bun run bench:memory:lifecycle`, `bun run bench:memory:retrieval-calibration`, `bun run bench:pipeline`, isolated scratch-fixture `bun run bench:corpus`, deterministic repeated `bun run bench:corpus:repeat`, and observation-only `bun run bench:cache-calibration` guard routing, memory correction/privacy/retention semantics, frozen-session behavior, retrieval evidence gates, correctness, policy compliance, repeat coverage/spread, latency, context savings, cache telemetry, and proof-gated normalized provider usage.
-- **Make orchestration risk-aware and self-improving** — [RASMIC](./docs/RASMIC.md) classifies task risk/contention, retrieves compact repo-local memory, records manual user tests and Evidence Receipts, detects path/shared-resource collisions before merge conflicts, and promotes repeated safe routes from observed traces → recipes → tested bounded scripts.
-- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
-- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
-
-### Cognitive Runtime evidence boundary
-
-The public Cognitive Runtime claim baseline was revalidated on **2026-09-04** against source/main/origin and the deployed build at `1d65a6a`. Current deterministic gates at that SHA report **100% required-tool routing recall**, **96.6% average active-schema reduction**, **8/8 typed-memory fixtures**, **6/6 P9 correction/privacy calibration scenarios at 200 corrections**, and **8/8 P10 lifecycle scenarios**. The P10 retrieval gate is intentionally mixed: lexical retrieval is **4/6**, the existing local semantic candidate is **3/6**, and the bounded two-hop relationship fixture is **3/3**; therefore MSO does **not** claim that vector or graph memory is universally unnecessary.
-
-The strongest currently revalidated MSO↔Hermes comparison is the exact P7+P8 **five-run, nine-scenario, matched `openai-codex/gpt-5.6-terra` corpus**: both agents are **5/5 perfect full runs**. On those exact runs, MSO observed **74.7% fewer normalized tokens/attempt**, **12.8% lower mean average latency**, and **34.1% lower mean per-run p50**. These are corpus-specific observations, **not** a claim that MSO is universally faster, smarter, cheaper, or more reliable. Cost is not ranked; cache-hit frequency is not ranked; OpenClaw is not ranked without an equivalent provider/model path. Older P4/P5 numeric tables remain historical release notes and are not the current public benchmark baseline because this audit could not independently revalidate the exact raw artifacts behind those specific numbers. See [Cognitive Runtime → Evidence status and claim boundaries](./docs/COGNITIVE-RUNTIME.md#evidence-status-and-claim-boundaries) and the versioned [claim-audit evidence manifest](./docs/evidence/cognitive-runtime-claim-audit-2026-09-04.json).
-
-</details>
-
-## Install
-
-Run on your Linux server as your **normal user, not root**. Review the
-[bootstrap](./scripts/install.sh) and [installation guide](./docs/INSTALL.md) before executing:
-
-```bash
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
-```
-
-The bootstrap verifies the downloaded installer core before running it. The guided setup
-handles credentials through hidden prompts; never paste secrets into chat or command arguments.
-The default bind is **127.0.0.1**. Keep the raw application port private.
-
-```bash
-mso doctor # verify the installation
-mso web # open the browser workspace
-mso # open the terminal agent
-mso update # update an existing installation safely
-```
-
-Already installed but missing `mso update`? Re-run the official installer. It preserves
-`.env.local` and `~/.mso`, detects the existing service checkout, and refuses dirty/diverged source.
-An agent can follow the same repository-owned installation contract; no parallel setup is needed.
-
-<details>
-<summary><strong>Full setup: onboarding, WSL, providers, tunnels and installer options</strong></summary>
-
-### Install or update with an AI agent
-
-If your AI agent can open this repository and run commands on your server, your request can be as
-short as:
-
-```text
-Install or update MSO from this repo: https://github.com/rahmanef63/mso
-```
-
-The repository carries the rest of the contract. The agent should use MSO's official installer/update
-paths rather than reconstructing setup commands by hand, preserve an existing `.env.local` and
-`~/.mso`, update the checkout already owned by `mso.service` instead of creating a second clone, and
-finish with `mso doctor`. For a current install it may use `mso update` (the same lifecycle exposed by
-Settings → About). If the installed build is old enough that `mso update` or the About updater does not
-exist yet, the universal upgrade/recovery path is simply to re-run the current one-line installer below.
-Only credentials or choices that cannot be inferred should come back to the user; provider secrets must
-stay in hidden/STDIN onboarding prompts rather than command arguments or chat logs.
-
-Run one command on the Linux server as your normal user, **not root**:
+![Actual MSO CLI terminal capture](./docs/media/mso-cli.webp)
```bash
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
-```
-
-That URL is now a **small bootstrap, not the 30 KB installer body**. It downloads
-`scripts/install-core.sh` to a private temporary file, retries transient transfers, requires
-the complete EOF marker, verifies the committed SHA-256 and `bash -n`, and only then executes
-the core. This prevents a truncated `curl | bash` response from stopping after a few preflight
-lines while incorrectly returning success. The command stays the same; the execution boundary is safer.
-
-A fresh install now finishes with a **guided terminal onboarding** when a controlling
-terminal is available. The public bootstrap itself arrives on stdin, so the verified core
-still opens `/dev/tty` for prompts instead of depending on pipeline stdin.
-The flow lets you choose:
-
-- **Alfa AI provider** — OpenAI ChatGPT/Codex device OAuth, or an API-key provider such
- as Anthropic, OpenAI Platform, OpenRouter, Google, Groq, xAI, DeepSeek or Mistral;
-- **Alfa response preset** — normal, Caveman or Ponytail;
-- optional **Hermes / OpenClaw / 9Router** installation (their provider settings remain separate
- from Alfa's credentials);
-- optional **Dokploy** plus **Cloudflare or Hostinger** infrastructure connection. Provider secrets
- are entered with hidden prompts and stay server-side;
-- reviewed **installable skills** such as Ponytail, Caveman and the MSO-safe RTK wrapper.
-
-Immediately after checkout, the installer installs and validates the CLI **before dependency
-installation, the production build, or systemd setup**. It always creates `~/.local/bin/mso`;
-when the invoking shell already has `/usr/local/bin` on `PATH`, it also installs a guarded
-`/usr/local/bin/mso` launcher (using sudo when needed). That order matters on WSL: even if a
-subsequent Bun/Next build fails, `mso -h` remains available for diagnosis and a safe rerun.
-The production build invokes Next's installed Node entrypoint directly instead of resolving
-`next` through Bun's `.bin` remapper, avoiding Bun 1.3.x's intermittent WSL `bin metadata file`
-corruption path.
-
-A child `curl | bash` process cannot modify its parent shell's `PATH`. The installer therefore
-checks the **original invoking PATH** after creating the launchers and explicitly reports whether
-`mso -h` will work immediately. If neither launcher is already reachable from that PATH, the
-install still succeeds, persists `~/.local/bin` in the normal shell profile, and prints the exact
-`export PATH=...` command for the current shell instead of falsely claiming success.
-
-If the environment has no controlling TTY (CI/cloud-init), the installer never blocks. It
-prints the resume command instead:
-
-```bash
-mso onboard
-```
-
-For an intentionally non-interactive install, use safe minimal defaults. `-y` does **not**
-auto-connect external accounts, install large managed apps, or silently add community
-skills:
-
-```bash
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- -y
-```
-
-Already installed? Use the least surprising path:
-
-- **Current MSO:** `mso update`, or Settings → About → Update.
-- **Older/legacy MSO where that updater is missing or broken:** re-run the same one-line installer.
- It discovers an existing `mso.service` WorkingDirectory before choosing a default directory, updates
- that checkout in place, preserves `.env.local` + `~/.mso`, and does not repeat onboarding unless
- `--onboard` is requested.
-- **Recovery:** re-running the installer is also the supported way to repair installer/runtime wiring;
- it refuses dirty/diverged source instead of resetting user work.
-
-After installation, the installer prints whether the current shell can already resolve `mso`.
-On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immediately:
-
-```bash
-mso # interactive MSO setup/operations agent
-mso -h
-mso models # configure AI provider/API/OAuth connections (does not switch model)
-mso model # arrow-key model picker from connected providers
-mso --continue # resume the latest durable MSO Agent session
-mso doctor
-mso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed
-mso provider list # Dokploy/Cloudflare/Hostinger status (secrets masked)
-mso web # open local UI; starts the built loopback runtime if no service is active
-mso update # fetch/verify/build safely; does not require :4005 to be alive
-mso skills available # reviewed installable skill list
-mso skills install ponytail caveman rtk -y
-```
-
-Interactive model/provider menus use a native picker: **↑/↓** moves, typing filters, **Enter**
-selects, and **Esc** cancels. No provider/model number has to be memorized. `/session` and bare
-`/resume` open one recent-session picker directly: newest modified session first, short `@name`
-as the primary label, with the longer human session title and compact `modified …` metadata. Durable session IDs stay hidden in the normal
-picker UI but remain accepted by scriptable `--resume`/`/resume` queries. `/new [title]` persists the
-current session and switches the same terminal to a fresh durable session. `/restart` is a soft Agent
-process replacement: it persists the current session, closes the composer, then reloads the latest CLI
-and Agent modules against that exact same durable session id. Repeated restarts keep a constant process
-depth. It does **not** restart the MSO service or VPS; updated code plus the latest dynamic
-skill/tool/plugin catalog are picked up without abandoning the conversation. Live same-host sessions require no
-manual refresh path: `/agents` discovers them automatically, `@milo <prompt>` dispatches a correlated request only when `milo` is active,
-`/message <agent> <text>` sends notify-only data, `/delegate <agent> <task>` sends a correlated local task before
-remote-A2A fallback, and `/inbox` shows the current session's native agent mailbox. Correlated replies relay as a
-durable synthetic assistant response; notify-only events remain passive peer events. `/spawn` is a separate foreground
-same-session subagent primitive with isolated context and final-result-only return.
-In the Agent slash palette, executable skills carry lifecycle markers so their state is visible before and after use:
-`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).
-The interactive transcript is sectioned by full-width `Assistant`, `Agent work`, `Local agent`, and `Error`
-dividers. The composer stays in its own bottom `Input · @name` area: the short session handle is the input
-identity (`@milo ›`), while permission is shown separately in the bottom footer as `mode ask|auto|yolo`.
-Tab on an empty prompt cycles that footer in place without adding scrollback. MSO defaults to `ask`; use
-`mso --yolo` or `mso -yolo` when you explicitly want write+exec calls auto-approved for that Agent
-process. YOLO still computes and sends the canonical exact-payload approval digest; it only skips the
-interactive compact approval prompt. `/permission` opens the same arrow-key style selector; `auto-write`
-approves writes but still asks before exec. Permission mode is process-local and is not persisted into a
-resumed session. Recoverable HTTP/API failures render a bounded `Error` section instead of silently
-ending the interaction. If a write/exec delivery is uncertain, MSO stops that turn and never retries the
-mutation automatically; if an earlier mutation completed, the error section says so and instructs the
-user/client to continue from that result rather than repeat it. Terminal controls follow familiar agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, and
-interrupts an active model/tool turn; **Ctrl+D** deletes the character to the right or exits on an
-empty prompt; **Ctrl+L** clears/repaints; **Ctrl+W** deletes the previous word; **↑/↓** or
-**Ctrl+P/N** browse prompt history, including durable user prompts restored by `--continue`/`/resume`. Long drafts wrap dynamically to terminal width/height; **↑/↓** move between visual wrapped rows before falling through to history navigation;
-**Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one character, **Ctrl+U/K** delete to the
-start/end of the line, and **Alt+B/F** or **Ctrl+←/→** move by word. `/quit` is an alias for `/exit`.
-An interrupted turn is removed from durable conversation
-history so `--continue` never resumes a half-turn. Server-side jobs that were already created retain
-their own bounded job/cancel lifecycle.
-
-If it explicitly says the current shell cannot see the user launcher yet, run the one-line
-`export PATH="$HOME/.local/bin:$PATH"` it prints; new shells use the persisted profile entry.
-
-**WSL2:** the CLI is supported even when systemd is not active. In that case the installer now
-finishes the CLI instead of failing in `systemctl`, but it skips `mso.service`. `mso onboard` and
-`mso web` can start the already-built production runtime detached on `127.0.0.1` and track ownership
-under private state; `mso update` can update/verify/build without a running API and safely inventories, quiesces and restores every gateway-owned fallback runtime for that checkout instead of rebuilding `.next` underneath any of them. For the full
-background service, enable systemd in `/etc/wsl.conf`, exit all WSL sessions from Windows, reopen
-the distro, then re-run the installer with `--onboard`.
-
-`Caveman`/`Ponytail` appear in two intentionally different places. **Response presets**
-(`mso config style caveman|ponytail`) are lightweight Alfa output policies. The market
-entries are full `SKILL.md` packages installed into the trusted operator root
-`~/.mso/skills`. Selecting a preset does not secretly install a skill, and installing a
-skill does not rewrite the global response preset.
-
-The curated `rtk` skill is an MSO-safe wrapper: it teaches agents to use RTK when the
-binary is already present, but it does **not** run an unpinned remote installer, modify
-shell profiles, or enable global hooks. Installing the RTK binary is a separate explicit
-system change.
-
-MSO binds **`127.0.0.1` by default**, so nothing is published directly to your network.
-On a laptop/WSL install, the supported public-preview path keeps that invariant and creates an
-**outbound HTTPS tunnel** instead of opening port 4005 to the LAN/Internet:
-
-```bash
-mso gateway doctor
-mso gateway start # temporary HTTPS URL; installs MSO's pinned cloudflared on first use
-mso web # opens the active public URL, or loopback when no gateway is running
-mso gateway status
-mso gateway stop
+mso # terminal agent
+mso doctor # installation checks
+mso web # browser workspace
+mso update # guarded update from main
```
-Temporary mode uses a Cloudflare Quick Tunnel and does **not** change `OS_PUBLIC_ORIGIN`, the
-MSO bind address, router/NAT rules, or the Windows firewall. The normal password + approved-device
-gate, live device roles, Secure/HttpOnly/SameSite cookie, same-origin mutation gate, CSP and login
-rate limits remain in front of the host APIs. Gateway state/logs live under an owner-only
-checkout+loopback-origin namespace below `~/.mso/private/gateway`, so two clones/ports cannot control
-each other's tunnel. `stop` validates process identity before terminating anything. On first use, MSO downloads the reviewed `cloudflared` release pinned in
-`security/gateway-artifacts.env` into user-local `~/.mso/tools`, verifies its SHA-256 before first
-execution and again before every reuse, and passes `--no-autoupdate`. No root package install,
-mutable `latest`, or `curl | sh` is involved. Use `mso gateway install` to prefetch it explicitly.
-
-Quick Tunnels are a **preview/testing** surface, not the permanent deployment path. Cloudflare
-documents a 200-concurrent-request limit and no Server-Sent Events support; MSO's live Terminal
-uses SSE, so that stream can be unavailable in temporary mode. Files, Settings and ordinary UI/API
-requests still use the normal authenticated HTTPS surface. For full-time/full-feature access, use a
-named tunnel/custom domain or another production HTTPS reverse proxy.
+[Command reference](./docs/CLI.md) · [Recorded browser demo](./docs/media/demo.gif)
-For a stable domain, keep MSO on loopback and make the public origin explicit:
-
-```bash
-mso gateway domain set https://mso.example.com
-# create/configure the named Cloudflare Tunnel using the example printed above, then:
-mso gateway start --config ~/.cloudflared/config.yml --tunnel mso
+## How it fits together
-mso web
-```
-
-If another gateway is already active, stop it first with `mso gateway stop`. MSO refuses to silently ignore explicit named-tunnel arguments or switch tunnel modes underneath an active endpoint.
-
-
-`mso gateway domain set` updates `OS_PUBLIC_ORIGIN` atomically and prints a loopback-only ingress
-example. Named mode accepts only a dedicated two-rule config (`your hostname → MSO loopback`, then
-`http_status:404`) and a private owner-owned credentials file. It does not put tunnel tokens on a
-command line. A permanent Cloudflare deployment can then add Cloudflare Access/WAF policy in front
-of MSO. If you prefer an
-SSH-only connection instead, use:
-
-```bash
-ssh -N -L 4005:127.0.0.1:4005 you@your-server
+```mermaid
+flowchart LR
+ Browser --> Guard["Authentication + scope + approval"]
+ CLI --> Guard
+ MCP["Optional MCP"] --> Guard
+ Guard --> MSO["MSO · Node / Next.js"]
+ MSO --> Host["Files · PTY · services"]
+ MSO --> State["Local state"]
+ MSO -. optional .-> Model["Your model provider"]
```
-The local tunnel is not just hygiene. The session cookie is `Secure`; ordinary plain-HTTP public IP
-addresses drop it. Bind wider only when the network/firewall design explicitly requires it.
+One self-hosted application. No required database or separate agent service.
+[Architecture](./docs/ARCHITECTURE.md) · [Detailed workspace guide](./docs/reference/WORKSPACE-GUIDE.md)
-Useful installer controls:
+## Install or update MSO from this repo
-| Control | What it is for |
-|---|---|
-| `--dir PATH` | Explicit install directory. Normally omit it so an existing service checkout is detected automatically. |
-| `--ref REF` | Development/testing ref. Normal installs and self-update use `main`. |
-| `--port N` | Local MSO port; default `4005`. |
-| `--bind ADDR` | Listen address; default `127.0.0.1`. Do not use `0.0.0.0` unless your firewall/TLS design explicitly requires it. |
-| `--no-service` | Build only; do not install the systemd service. |
-| `--onboard` | Run guided onboarding even while upgrading an existing install. |
-| `--no-onboard` | Install/update without starting onboarding. |
-| `-y`, `--yes` | Safe non-interactive defaults; does not connect accounts or install optional apps/skills. |
-| `--uninstall` | Remove the systemd unit and MSO CLI links while keeping code and `~/.mso`. |
-| `-h`, `--help` | Print the installer contract without changing the host. |
-
-Equivalent public environment overrides are `MSO_DIR`, `MSO_REF`, `MSO_PORT`, `MSO_BIND`, and
-`MSO_REPO`. Command-line flags are clearer for people; environment overrides are useful to automation.
+Run as your **normal Linux user, not root**. Review [scripts/install.sh](./scripts/install.sh) before executing:
```bash
-# force onboarding even while updating an existing install
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --onboard
-
-# update/build without onboarding
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --no-onboard
-
-# explicit non-default location/port (only when you intentionally need them)
-curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --dir "$HOME/mso" --port 4005
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
```
-There is also a no-login install guide at **<https://mso.rahmanef.com/install>**. **Browser
-sign-in requires HTTPS**, except when you access MSO through a loopback URL such as
-`http://localhost:4005`. Do not pair/approve a browser on plain `http://<server-ip>:4005`:
-the session cookie is `Secure`, so the browser cannot keep the login there. Full production setup,
-TLS/VPN notes, filesystem roots, update/rollback and onboarding details live in
-[docs/INSTALL.md](./docs/INSTALL.md).
-
-</details>
+Default application bind: **127.0.0.1**. Use a VPN or protected HTTPS proxy for remote access.
+[Full installation, WSL and recovery guide](./docs/INSTALL.md)
-## How it works
+## Reset or remove
```mermaid
flowchart LR
- USER["Browser / CLI / MCP client"] --> AUTH["Authentication + role / scope"]
- AUTH --> MSO["MSO · Next.js / Node"]
- MSO --> HOST["Guarded host capabilities"]
- HOST --> FILES["Files · PTY · metrics · services"]
- MSO --> AI["Optional model provider"]
- MSO --> APPS["Optional managed apps · separate runtimes"]
-```
-
-Core persistence is local. Optional model-provider calls send the selected context off-host;
-**BYOK does not mean the data stays on your server**. Files and model output are untrusted input,
-not permission to execute a command. See [architecture](./docs/ARCHITECTURE.md) and
-[the AI/tool contract](./frontend/slices/assistant/CONTRACT.md).
-
-## CLI
-
-```bash
-mso -h # discover commands
-mso stats # inspect system health
-mso ls ~/projects # browse a configured filesystem root
-mso model # select a connected model
-mso --continue # resume the latest durable agent session
-```
-
-<details>
-<summary><strong>More CLI examples and integration notes</strong></summary>
-
-The browser UI is one frontend, not the product. The installer puts `mso` on your
-`PATH`, and it reaches the same API — every endpoint has a named verb, and `mso api`
-covers anything without one.
-
-```bash
-mso # interactive setup/operations agent with MSO ASCII terminal UI
-mso -h # grouped command list; `mso <command> --help` per command
-mso models # configure AI provider/API/OAuth connections
-mso model # arrow-key model picker / switch active model
-mso --continue # resume the latest MSO Agent session
-mso --resume "@milo" # resume by @name; index/id/title queries remain supported
-mso doctor # includes HTTPS/login-origin diagnosis
-mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
-mso onboard # guided AI/app/infrastructure/skill setup
-mso provider list # masked Dokploy/Cloudflare/Hostinger state
-mso provider set cloudflare # hidden credential prompts + live verification
-mso skills available # curated installable skills
-mso skills install ponytail caveman rtk -y
-mso device pending # who typed the password and is waiting
-mso device approve <id> "my phone" --role viewer
-mso ls ~/projects # files; `raw` for binaries, `zip`/`upload` for transfers
-mso exec "df -h" # host shell
-mso stats # cpu / mem / disk
-mso units # system + user systemd inventory
-mso unit logs user mso.service
-mso packages # cached updates; never applies them
-mso camoufox start # power the anti-detection browser
-mso mapp logs hermes # managed apps (hermes, openclaw, 9router)
-mso term open # interactive PTY
-mso service restart # systemd
-mso api GET /api/v1/sys/stats # escape hatch — any endpoint
-eval "$(mso completion bash)" # tab completion
+ Preview["Preview owned paths"] --> Review["Review + stop runtime"]
+ Review --> Confirm["Confirm exact plan token"]
+ Confirm --> Reset["Reset → private recovery archive"]
+ Confirm --> Remove["Uninstall → optional data/code purge"]
```
-Full command reference: [docs/CLI.md](./docs/CLI.md) (generated from `mso --help`).
-
-Global options: `--base <url>` to target another instance, `--env <file>` to pick a
-different secrets file. Device and service commands work even while the service is
-down. If you use [Claude Code](https://claude.com/claude-code), the installer also
-links every committed official skill in `claude-skills/` into `~/.claude/skills/`. Create a consistent workflow skill with `bun run skill:new -- --help` and validate the catalog with `bun run skill:check`.
-
-</details>
-
-## Security warning
-
-**The terminal and exec-scoped tools are not sandboxes.** Device roles narrow API access,
-but every role shares one deployment and the same underlying Unix service account.
-MCP is disabled unless explicitly enabled. Approve only trusted devices and tokens; keep
-filesystem write roots narrow and read the exact command on every approval card.
-The one-shot exec guard refuses unresolved shell expansion in recursive-delete targets;
-this is a conservative accident guard, not proof that arbitrary shell scripts are safe.
-
-Security checks are evidence at a particular revision, not a guarantee. The project has
-**not had an independent third-party security audit**. Read the [security policy](./SECURITY.md)
-and [repeatable assurance process](./docs/SECURITY-ASSURANCE.md) before exposing an instance.
-
-<details>
-<summary><strong>Full trust boundaries, provider data handling and operational controls</strong></summary>
-
-An authenticated **Owner** session can read allowed files and run commands as the Unix user that owns the process. Viewer and Operator devices are server-gated to narrower surfaces, but all roles still share one MSO deployment and one underlying Unix account.
+| Preview command — no changes yet | Scope |
+|---|---|
+| `mso reset` | Server preferences and provider configuration |
+| `mso reset --scope all` | Factory reset of known MSO state and local configuration |
+| `mso uninstall` | Remove owned service/CLI links; keep data and source |
+| `mso uninstall --purge --remove-code` | Also remove known data and a clean standalone clone |
-- Run as a dedicated non-root user.
-- Prefer Tailscale or a VPN; otherwise use HTTPS plus a strict firewall or allowlist.
-- Use a strong `OS_SESSION_SECRET` and a strong `OS_LOGIN_PASSWORD`.
-- Approve only trusted devices; use Viewer by default, Operator only for bounded operational work, and Owner only where full host authority is intended. Device approval is an allowlist, not standards-based MFA or a named-user directory.
-- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.
-- Service inventory is read-only by default. Lifecycle buttons require Operator/Owner **and** an exact `OS_SERVICE_CONTROL_UNITS` entry; wildcards are rejected. Package visibility reads only the existing local cache and never upgrades the host.
-- Never commit `.env.local`, API keys, or data from `~/.mso`. Infrastructure provider tokens live in `~/.mso/private/infra-providers.json` with owner-only permissions; the agent receives only credential-free tool schemas and masked provider state.
-- Dokploy/Cloudflare/Hostinger automation is intentionally bounded. Cloudflare changes one exact record and never bulk-writes a zone; proxying defaults off. Hostinger updates one exact name/type RR-set with `overwrite:true`; unrelated zone rows are never sent in the mutation payload, while ambiguity/conflicts are still refused and writes require approval.
-- Managed-app dashboards are not embedded by default. 9Router is loopback-only by default; a direct public-IP bind requires `NINE_ROUTER_EXPOSE_PUBLIC=1`, while a configured application hostname remains its preferred in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.
-- Camoufox/noVNC is also never served on the cockpit origin. It uses the reserved split-origin host such as `camoufox.mso.example.com`; the legacy `/camoufox-vnc/*` path is permanently closed.
-- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands according to the daemon's own trust model.
-- With a model provider configured, Alfa is a tool-calling agent, not a plain chatbot. Its complete current catalog and human-approval contract are generated from `frontend/slices/assistant/host-tools/*` and documented in `frontend/slices/assistant/CONTRACT.md`; avoid copying a tool count into overview docs because the catalog changes independently of MCP.
-- Everything Alfa reads — file contents, command output, process lists — is sent to your model provider, and is re-sent on every following turn of the same run. BYOK means you own the key, not that the data stays on the box.
-- Choosing an Alfa Cockpit project adds a **bounded metadata snapshot** to each turn (project/path, branch/tree state, HEAD, knowledge availability, and recent project-memory topic titles). It does not inject raw project knowledge or raw repo-memory bodies. Cockpit also masks non-`normal` typed-memory keys/values as `Private memory`; selecting a project is context, never mutation permission.
-- Treat any file Alfa reads as untrusted input. The approval card is the only thing between text hidden inside a file and an `exec.run`. Read the command on the card, not Alfa's summary of it.
-- Agents and Skills group tools for your own convenience. They are not a permission boundary: every agent can call every tool.
-- `exec.run` is not sandboxed. Its cwd is bounded to your write roots, but the command itself runs in your login shell as the service user. The destructive-command denylist is a short accident tripwire, not a guard.
-- The MCP server is off unless `OS_MCP_ENABLED=1`. When on, a bearer token is a standing credential with whatever scope you granted it: at `exec` it runs any command on the box as you, and every call and result goes to the client's provider. The consent screen preselects the server ceiling (`exec` by default), so lower it before Allow when a client needs less; cap all tokens with `OS_MCP_MAX_SCOPE`, and treat anything the model reads as untrusted — scope is what stops a prompt-injected file talking it into a write. See [docs/MCP.md](./docs/MCP.md).
-- MSO has not had a third-party security audit.
+Apply requires `--apply --confirm <preview-token>` from an independent local/SSH terminal.
+Browser reset is separate in **Settings → About**. Unknown files and other projects are retained.
+[Scopes, backups, safeguards and recovery](./docs/MAINTENANCE.md)
-More detail: [SECURITY.md](./SECURITY.md), [docs/FAQ.md](./docs/FAQ.md) and [docs/INSTALL.md](./docs/INSTALL.md).
+## Safety first
-</details>
+**Public Alpha / Developer Preview.** An Owner or exec-scoped agent can execute commands as the
+service user. MSO is **not a shell sandbox or multi-tenant security boundary**. Provider calls may
+send selected context off-host. Keep credentials private and review approvals.
+[Security policy](./SECURITY.md) · [Verification and known limits](./docs/SECURITY-ASSURANCE.md)
-## Development
+<!-- comparison:start -->
+[Product comparison, evidence and limitations](docs/COMPARISON.md) · reviewed 2026-08-29.
+<!-- comparison:end -->
-The reference runtime is **Node 22** (`.nvmrc`); use **Bun** for dependency installation and
-`bun.lock` for reproducibility. Run local development only on a trusted machine.
+## Develop
```bash
bun install --frozen-lockfile
-cp .env.example .env.local # configure local credentials; never commit this file
-bun run dev
-```
-
-```bash
-bun run verify # typecheck, lint, coverage, architecture/docs, local audit
-bun run test:features # separate test process for each area; reports coverage gaps
-bun run audit:strict # unavailable/malformed dependency evidence fails closed
-bash scripts/verify-build.sh # compile committed HEAD out-of-tree, not over a live build
+bun run verify
+bun run test:features
+bun run audit:strict
```
-`bun run test` uses Vitest. **Do not substitute `bun test`**, which uses a different runner.
-The ordinary local audit can explicitly skip an unavailable registry; it is not security proof.
-Use the strict audit and the [security lanes](./docs/SECURITY-ASSURANCE.md) for release assurance.
-
-**Version contracts are independent:** `package.json` owns the app version, `bin/mso`
-owns CLI compatibility, and `lib/mcp/toolset.ts` owns MCP server/toolset compatibility.
-`mso --version` labels app, CLI and Git build; the updater uses the exact Git build as release authority.
-A documentation/security-maintenance change does not invent a new MCP tool contract.
-
-## Comparison
-
-<details>
-<summary><strong>Product scope comparison — methodology and limitations included</strong></summary>
-
-<!-- comparison:start -->
-**Positioning:** MSO is designed as a mobile-first, AI-native private Linux workspace for an owner or small trusted team. It does not claim to replace specialist products at their strongest specialty.
-
-Strong = a first-class product strength · Partial = available with scope limitations · Not offered = not a core product surface
-
-| Product | Best fit | Browser workspace | Linux host administration | Application delivery | Monitoring and observability | Roles and delegation | Built-in AI and MCP |
-|---|---|:---:|:---:|:---:|:---:|:---:|:---:|
-| **MSO** | Mobile-first private Linux workspace | Strong | Partial | Partial | Partial | Partial | Strong |
-| **Cockpit** | Deep graphical Linux administration | Partial | Strong | Partial | Partial | Strong | Not offered |
-| **Coolify** | Self-hosted Git/PaaS delivery | Partial | Partial | Strong | Partial | Strong | Not offered |
-| **Portainer** | Container and stack operations | Partial | Partial | Strong | Partial | Partial | Not offered |
-| **Netdata** | High-resolution observability and RCA | Partial | Not offered | Not offered | Strong | Partial | Partial |
-| **Tailscale SSH** | Identity-aware private remote access | Not offered | Partial | Not offered | Not offered | Strong | Not offered |
-| **File Browser** | Focused web file management | Partial | Not offered | Not offered | Not offered | Partial | Not offered |
-| **ttyd** | Small, focused web terminal | Partial | Not offered | Not offered | Not offered | Partial | Not offered |
-| **CasaOS** | Friendly personal-cloud home server | Partial | Partial | Partial | Partial | Not offered | Not offered |
-| **Runtipi** | Curated one-click self-hosted apps | Partial | Not offered | Strong | Partial | Not offered | Not offered |
-
-Reviewed against official product documentation on **2026-08-29**. Ratings describe product scope, not benchmark scores. See [methodology, evidence, and per-cell notes](docs/COMPARISON.md) and the [execution roadmap](docs/COMPETITIVE-ROADMAP.md).
-<!-- comparison:end -->
-
-</details>
-
-## Tested platforms
-
-<details>
-<summary><strong>Linux / WSL deployment support and untested platforms</strong></summary>
-
-Not yet formally tested across a full distro matrix.
-
-Tested:
-
-- Ubuntu 22.04
-- Ubuntu 24.04
-
-Supported deployment shapes:
-
-- WSL2 Ubuntu: CLI/install path works without systemd; the background service requires systemd enabled in WSL
-- Debian 12 and other systemd-based Linux distributions with Node.js 20.9+ and build tools
-
-Not currently supported:
-
-- Windows host
-- macOS host
-- Automatic service install on non-systemd hosts
-- Root deployment
-
-</details>
-
-## Documentation
-
-| Start here | Reference |
-|---|---|
-| Install, update, recover | [Installation](./docs/INSTALL.md) · [Troubleshooting](./docs/TROUBLESHOOTING.md) |
-| Use the CLI or connect MCP | [Generated CLI reference](./docs/CLI.md) · [MCP](./docs/MCP.md) · [ChatGPT integration](./docs/CHATGPT-PLUGIN.md) |
-| Understand the runtime | [Architecture](./docs/ARCHITECTURE.md) · [Cognitive Runtime](./docs/COGNITIVE-RUNTIME.md) |
-| Contribute or review security | [Contributing](./CONTRIBUTING.md) · [Development](./docs/DEVELOPMENT.md) · [Security](./SECURITY.md) |
-| Browse everything | [Documentation map](./docs/README.md) · [Changelog](./docs/CHANGELOG.md) |
-
-The [maintainer's instance](https://mso.rahmanef.com) requires authentication; it is **not a public demo**.
-The [recorded demo](./docs/media/demo.gif) is available without access to a real server.
-A separate mock-only demo must keep `NEXT_PUBLIC_OS_DEMO=1` at build time and bind to loopback
-unless its owner explicitly publishes it; never enable demo mode on an owner deployment.
-
-## Status and license
-
-**Public Alpha / Developer Preview** — expect rough edges and breaking changes.
-MIT licensed; see [LICENSE](./LICENSE).
+Use Node 22 and Bun >=1.2.15 with native audit support. [Contributing](./CONTRIBUTING.md) ·
+[Development](./docs/DEVELOPMENT.md) · [Changelog](./docs/CHANGELOG.md) · [MIT license](./LICENSE)
diff --git a/bin/mso b/bin/mso
index 1861f40c..c65e9a2d 100755
--- a/bin/mso
+++ b/bin/mso
@@ -93,6 +93,9 @@
# deploy Rebuild active service with runtime quiesce/restore
# update [--rebuild] Update from origin/main safely; works even when the web runtime is down
#
+# reset [--scope config|all] Preview local factory reset; explicit token required to apply
+# uninstall [--purge] [--remove-code] Preview owned installation removal
+#
# Escape hatches
# crud * Generic resource CRUD, incl. editor documents
# api * Call ANY endpoint directly
@@ -129,7 +132,7 @@
# Docs: https://github.com/rahmanef63/mso
set -euo pipefail
-VERSION="1.12.1"
+VERSION="1.13.0"
ROOT="$(cd "$(dirname "$(readlink -f "$0")")/.." && pwd)"
die() { echo "mso: $*" >&2; exit 1; }
@@ -149,6 +152,14 @@ while [ $# -gt 0 ]; do
esac
done
+# Dispatch local maintenance before sourcing credentials or creating a cookie jar.
+case "${1-}" in
+ reset|uninstall)
+ [ -z "$BASE_OVERRIDE$ENV_OVERRIDE${MSO_BASE:-}${OS_BASE:-}${MSO_ENV:-}${OS_ENV:-}" ] \
+ || die "maintenance is local-only; omit --base/--env and run over SSH on the intended host"
+ exec node "$ROOT/scripts/mso-maintenance.mjs" "$@" ;;
+esac
+
B="${BASE_OVERRIDE:-${MSO_BASE:-${OS_BASE:-http://127.0.0.1:4005}}}"
ENVF="${ENV_OVERRIDE:-${MSO_ENV:-${OS_ENV:-$ROOT/.env.local}}}"
# shellcheck disable=SC1090
diff --git a/docs/CLI.md b/docs/CLI.md
index 5b665090..c7480886 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -133,6 +133,9 @@ Commands:
deploy Rebuild active service with runtime quiesce/restore
update [--rebuild] Update from origin/main safely; works even when the web runtime is down
+ reset [--scope config|all] Preview local factory reset; explicit token required to apply
+ uninstall [--purge] [--remove-code] Preview owned installation removal
+
Escape hatches
crud * Generic resource CRUD, incl. editor documents
api * Call ANY endpoint directly
diff --git a/docs/DEVELOPMENT.md b/docs/DEVELOPMENT.md
index 9255472e..85b4bbc0 100644
--- a/docs/DEVELOPMENT.md
+++ b/docs/DEVELOPMENT.md
@@ -54,7 +54,7 @@ uses Git's shared hook path rather than assuming `.git` is a directory.
`docs/comparison-data.json` is the only hand-edited comparison source. It records criterion
definitions, per-product notes, official source URLs, and repository evidence for every MSO rating.
-Do not hand-edit the generated README table or `docs/COMPARISON.md`. After an implementation or
+Do not hand-edit the generated README comparison reference or `docs/COMPARISON.md`. After an implementation or
source review:
```bash
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index 002fa2d3..3f548fa3 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -638,3 +638,7 @@ After install/update:
7. if managed-app origins changed, sign in again and test each explicit app hostname;
8. test Viewer/Operator/Owner route behaviour on separate devices when authorization changed;
9. if Service Center changed, prove inventory, bounded logs, allowlist refusal/action and cache-only package visibility.
+
+## Reset and clean uninstall
+
+Use `mso reset` or `mso uninstall` for local, preview-first maintenance. Optional `--scope all`, `--purge` and `--remove-code` have distinct scopes and need an exact-plan confirmation. Read [maintenance and recovery](./MAINTENANCE.md) before applying. The legacy installer `--uninstall` keeps code and state; it is not a full purge. Bun >=1.2.15 is required for native dependency auditing.
diff --git a/docs/MAINTENANCE.md b/docs/MAINTENANCE.md
new file mode 100644
index 00000000..6886a43b
--- /dev/null
+++ b/docs/MAINTENANCE.md
@@ -0,0 +1,115 @@
+# Reset and uninstall
+
+MSO has separate controls for browser data, server configuration, and installation removal.
+None of the server maintenance commands performs a write by default. Run them as the normal
+installation owner on Linux, from an independent local/SSH terminal—not inside the MSO web terminal.
+
+## Choose a scope
+
+| Action | Removes from active use | Preserves |
+|---|---|---|
+| Settings → About → Appearance only | This browser's appearance cache | Identity, drafts, server data |
+| Settings → About → All MSO browser data | MSO layouts, Playbooks, drafts and owned local storage | Device approval, unrelated browser storage, server files |
+| `mso reset` | Managed server preferences and model/infrastructure configuration | Authentication, history, `.env.local`, source, external apps |
+| `mso reset --scope all` | Known MSO configuration, identity/token stores, memory, sessions/history, `.env.local` | Source, unknown files, other projects and external providers |
+| `mso uninstall` | Verified service registrations and CLI/skill symlinks belonging to this checkout | Source, all server data, browser storage |
+| `mso uninstall --purge` | Above plus known MSO state and reset archives | Source, unknown files, external/shared resources |
+| `mso uninstall --purge --remove-code` | Above plus a verified clean standalone clone | Other projects and resources not owned by the installation |
+
+Browser appearance and Quicklinks can be restored from the server on the next sign-in.
+Use the server configuration reset too when clearing those synchronized preferences.
+Export a browser backup in Settings → Backup before clearing local drafts: the server reset
+archive does not contain browser-only data.
+
+## Preview first
+
+```bash
+mso reset
+mso reset --scope all --json
+mso uninstall
+mso uninstall --purge --remove-code
+```
+
+The preview lists exact archive/removal targets, retained paths and blockers. It does not source
+`.env.local`, create an authentication cookie, stop a process, or mutate a service.
+`--base` and `--env` are rejected for these local commands so a remote URL cannot silently cause
+maintenance on the wrong machine. A custom service name can be selected with `--service name.service`.
+
+## Apply the reviewed plan
+
+Stop MSO and its owned fallback/gateway runtimes first, through an independent SSH terminal.
+For a standard systemd installation, the main service is `mso.service`; the optional browser
+service is the user unit `camoufox-vnc.service`. Stop only the units/tunnels belonging to this
+installation. Do not stop another project's services to make a check pass.
+
+Run the preview again after stopping the runtime. Copy the exact token it prints, then repeat
+**the same scope/options** with both flags:
+
+```bash
+mso reset --apply --confirm <token-from-current-preview>
+```
+
+The placeholder is not a usable token. A changed file, scope or unit changes the plan token;
+inspect a fresh preview rather than reusing an old confirmation. `--yes` is intentionally unsupported.
+
+Apply checks ownership, symlinks, target identity and offline runtime state, then coordinates
+with the checkout's existing runtime-exclusion lock. It refuses when started inside the live MSO
+service. It does not silently stop production or approve its own destructive action.
+
+## Reset recovery archive
+
+Reset **moves**, rather than destroys, selected data into an owner-only archive:
+
+```text
+~/.mso/maintenance-backups/<unique-id>/
+├── manifest.json # original paths and reviewed scope; mode 0600
+└── files/ # preserved data; private parent directories
+ ├── .mso/...
+ └── <checkout>/.env.local # only for --scope all
+```
+
+Archive directories are `0700`. They can contain valid credentials and private conversations;
+do not commit, upload, email, or publish them. A reset does not revoke provider credentials.
+`uninstall --purge` permanently deletes these archives along with the selected known state.
+File deletion is not a guarantee of secure erasure from SSDs, snapshots or third-party backups.
+
+To recover, keep MSO stopped, inspect `manifest.json`, and move only the intended archived items
+back to their recorded locations after verifying that those destinations are absent. Do not
+blindly overwrite new configuration. For a full reset without restoration, re-run the official
+installer to create new local authentication configuration, then onboard and pair devices again.
+
+An interruption is reported as a failure, with the count of completed steps and recovery path.
+The operation does not claim transaction-wide rollback; completed archive moves remain recoverable.
+
+## Clean uninstall boundaries
+
+Source removal is refused for a dirty checkout, a linked worktree, a clone with additional
+worktrees, or unrecognized ignored files. This prevents a cleanup command from deleting unpushed
+work, sibling projects or files that Git does not describe. Preserve those items independently
+before requesting source removal. No force option bypasses these checks.
+
+Only verified symlinks into this checkout and verified service files are removed. A third-party
+command named `mso`, a manually installed skill, or a service belonging to another checkout is
+retained. If service removal requires elevated permission, the operation uses noninteractive
+`sudo` for the exact system operation and fails when permission is unavailable.
+
+Unrecognized `.mso` entries—including old worktrees, operator artifacts and coordination state—are
+retained and reported, not recursively swept away. Empty parent directories or lock metadata may
+remain. Review the retained list before calling the host completely cleaned.
+
+These are intentionally **not** removed: other projects, shared Node/Bun/system packages,
+external managed applications and their data, SC/CR/provider stores, cloud deployments,
+DNS/TLS configuration, browser profiles/cookies, and browser-local storage on other devices.
+Remove or revoke external resources separately through their owning tools.
+
+Configured or inherited custom storage overrides block automatic reset/purge. Their values are
+not printed and their targets are not traversed. Reconcile those paths manually; the command
+never claims a customized installation was completely reset while quietly leaving a secret store behind.
+
+## Verification
+
+`bun run test -- scripts/maintenance.test.ts` exercises isolated synthetic homes only, including
+preview immutability, stale confirmation, identity/symlink checks, private archives, normal uninstall,
+explicit purge, clean standalone source removal and failure-before-data-removal on service errors.
+Browser ownership is tested separately in `frontend/slices/os-settings/lib/browser-reset.test.ts`.
+The maintenance feature is not tested by resetting or uninstalling the maintainer's production host.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 26d7b821..57e2d762 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,4 +1,5 @@
# mso — Progress Log
+- **Visual README + local maintenance (2026-09-05):** README reduced from 575 to 97 lines with two Mermaid diagrams and an actual CLI PTY capture; longer valid material moved to the workspace reference. App 0.2.3 / CLI 1.13.0 adds preview-first reset and uninstall with exact-plan confirmation, private reset archives, stopped-runtime checks, existing runtime-exclusion coordination, symlink/ownership checks and explicit purge/standalone-source options. Unknown .mso entries/worktrees, other projects, shared dependencies and browser profiles are retained. Settings separates browser reset from copyable server maintenance previews; the device identity is preserved. Synthetic fixture tests exercise reset, clean-clone uninstall and failure paths; production was not reset or uninstalled. PR38 review fixes include complete glob escaping and a Bun >=1.2.15 native-audit prerequisite, enforced by the installer with refreshed bootstrap checksum.
- **Previously hidden exec/discovery test gaps closed (2026-09-05):** the remaining expected-failure shell-expansion case is now a real passing refusal test. Recursive deletion with unresolved shell expansion is conservatively refused; literal reviewed targets remain subject to normal approvals, and the matcher is explicitly not a shell parser or sandbox. Added eight predicate-only expansion fixtures without executing destructive commands. Registered the previously omitted root machine-protocol proxy test in normal Vitest/coverage and added an inventory regression contract. Per-area runs now use isolated exact-include configurations and verify the exact returned file set, preventing substring matches from counting unrelated nested proxy tests twice. Earlier per-area totals from this audit are superseded by the exact-selection rerun.
- **Compiler-enforced unused-code cleanup (2026-09-05):** resolved 49 unused import/local/parameter diagnostics across the shell, assistant, media, host, MCP and test modules. Calls with intentional side effects remain intact; positional callback placeholders are explicitly named. TypeScript `noUnusedLocals` and `noUnusedParameters` now make the ordinary typecheck/CI reject regressions. This is compiler-proven unused-symbol cleanup, not a claim that every exported symbol, runtime-discovered asset or optional integration is removable.
- **Public-sharing security and maintenance audit (2026-09-05):** app `0.2.2` keeps the independently versioned CLI/MCP contracts unchanged. Release and assurance dependency audits now fail closed on unavailable, malformed or incomplete evidence; local developer skips are explicitly labelled, registry diagnostics do not expose raw URLs, and skipped optional scanners cannot produce an unconditional assurance PASS. Removed the dormant Convex deploy tail, fixed shared Git-hook installation and out-of-tree dependency copying for linked worktrees, and added functional regression tests. README now leads with a readable install/features/security overview and collapsible reference detail, preserving generated comparison evidence and public-alpha limits. `test:features` runs each test area in a separate process and distinguishes PASS/PARTIAL/SKIPPED/FAIL. The Forge Docker sandbox and synthetic credential-path fixture activate previously skipped security checks without using real secrets; CI now provisions the same bounded fixtures. Onboarding tests derive the app version from `package.json`; the browser suite follows the actual Activity & Runs UI, checks infrastructure deep-links, and never echoes session-cookie diagnostics. Full-history scanning now requests merge diffs explicitly in CI and the assurance runner; independent scanner outputs remain private; no genuine historical secret was identified by the configured scan, so shared history was not rewritten. Live-service deployment and remote CI status require separate exact-revision evidence and are not inferred from local tests.
diff --git a/docs/README.md b/docs/README.md
index 142baa89..485f59f5 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -80,3 +80,7 @@ These files are copy/script drafts, not technical authority:
When a current-reference doc and one of these drafts disagree, update the draft or follow
the current-reference doc.
+
+## Reset and removal
+
+[Maintenance, factory reset and clean uninstall](./MAINTENANCE.md) · [Extended workspace reference](./reference/WORKSPACE-GUIDE.md)
diff --git a/docs/media/mso-cli.webp b/docs/media/mso-cli.webp
new file mode 100644
index 00000000..473e447c
Binary files /dev/null and b/docs/media/mso-cli.webp differ
diff --git a/docs/reference/WORKSPACE-GUIDE.md b/docs/reference/WORKSPACE-GUIDE.md
new file mode 100644
index 00000000..ad697539
--- /dev/null
+++ b/docs/reference/WORKSPACE-GUIDE.md
@@ -0,0 +1,562 @@
+# Workspace reference
+
+Detailed usage and installation context moved from the main README. For the short overview, see [README](../../README.md).
+
+<h1 align="center">Manef Shell OS</h1>
+<p align="center"><strong>Your Linux server. One private workspace.</strong></p>
+<p align="center">A real terminal, files, system health, and an AI assistant — from your phone or desktop.</p>
+
+<p align="center">
+ <a href="#install">Install</a> ·
+ <a href="../media/demo.gif">Watch the demo</a> ·
+ <a href="../README.md">Documentation</a> ·
+ <a href="../../SECURITY.md">Security</a>
+</p>
+
+<p align="center">
+ <a href="https://github.com/rahmanef63/mso/actions/workflows/ci.yml"><img alt="CI status" src="https://github.com/rahmanef63/mso/actions/workflows/ci.yml/badge.svg" /></a>
+ <a href="https://github.com/rahmanef63/mso/actions/workflows/security-core.yml"><img alt="Security checks" src="https://github.com/rahmanef63/mso/actions/workflows/security-core.yml/badge.svg" /></a>
+ <img alt="App version" src="https://img.shields.io/github/package-json/v/rahmanef63/mso?label=app" />
+ <img alt="MIT license" src="https://img.shields.io/badge/license-MIT-blue" />
+ <img alt="Public Alpha — Developer Preview" src="https://img.shields.io/badge/status-Public_Alpha-orange" />
+</p>
+
+![MSO browser workspace on desktop and mobile](../media/mso-hero.webp)
+
+**MSO is a self-hosted visual shell for a Linux server you own.** It runs as a normal,
+non-root Node process, without a required database or separate agent service. The browser,
+CLI, and optional MCP interface use the same guarded host capabilities.
+
+> **Public Alpha / Developer Preview.** An Owner session or exec-scoped agent can execute
+> commands as the service user. Use a dedicated non-root account and a VPN or tightly protected
+> HTTPS proxy. MSO is not an operating system, a multi-tenant security boundary, or a certified security product.
+
+## What you can do
+
+| Workspace | What it provides |
+|---|---|
+| **Operate your server** | Interactive PTY terminal, CPU/memory/disk metrics, service inventory and exact-allowlist lifecycle actions. |
+| **Work with files** | Browse, edit, upload, search, preview and organize files inside configured filesystem roots. |
+| **Work with AI** | Alfa browser cockpit, terminal agent, durable sessions, trusted skills, explicit mutation approvals and optional MCP access. |
+| **Use one responsive shell** | Desktop windows and mobile-first surfaces, media tools, a separate-origin browser and optional managed-app integrations. |
+
+<details>
+<summary><strong>Feature details and scoped benchmark evidence</strong></summary>
+
+**Control** — terminal, files, services, package visibility, and system health for the server you own.
+
+- **Open a real terminal** — interactive PTY support for tools like `vim`, `top`, and `ssh`.
+- **Manage files** — browse, upload, search, preview, rename, move, copy, zip, and delete within configured filesystem roots.
+- **Inspect system health** — view live CPU, memory, disk, network, process, and uptime signals.
+- **Operate services safely** — inventory system and user `systemd` units, read bounded journal output, and expose start/stop/restart only for exact owner-configured allowlist entries.
+- **See pending package updates** — read the package manager’s existing local cache without refreshing repositories or applying an upgrade.
+- **Update itself** — Settings → About shows what is on `origin/main`, lists the incoming commits, and runs the whole deploy (pull → verify the build out-of-tree → build → restart) from a button. The verification runs first on purpose: a commit that does not compile becomes a refusal, not an outage. The updater runs in the owner's systemd user manager and does not require passwordless sudo. Same thing from a shell: `mso update` (`mso update run` remains a compatibility alias). The CLI update path is Git-based and still works when the web runtime is down.
+- **Manage other apps on the box** — detect, start/stop/restart, health, version, logs, and state backups for separate applications you already run (Hermes, OpenClaw, 9Router), driven through their own systemd/Docker/CLI contracts. 9Router uses its configured application domain or split-origin host as the in-shell dashboard; its Docker port is loopback-only unless public exposure is explicitly enabled. See [docs/MANAGED-APPS.md](../MANAGED-APPS.md).
+
+**Work** — code/text editor, browser, and media tools in the same workspace.
+
+- **Edit project files** — open text/code files from the file manager without context switching.
+- **Preview almost anything** — images (including HEIC/TIFF), audio, video, PDFs, plain text, Markdown, CSV/TSV and HTML, with ← → paging through the folder. Formats no browser can render (Office, iWork, archives, installers) say so and offer the download instead of a blank frame. HTML renders in a fully sandboxed frame, never as a document on MSO's own origin.
+- **Keep admin context together** — move between terminal, files, metrics, services, package updates, and browser views.
+- **Delegate by device** — approve a browser as Viewer, Operator, or Owner. Roles are rechecked on every request; they are an MSO application boundary, not Linux accounts or enterprise SSO.
+
+**Extend** — Alfa AI, modular slices, and custom apps.
+
+- **Use BYOK AI** — Alfa and the terminal MSO Agent use credentials stored on your server, not committed to the repo. Bare `mso` opens the interactive setup/operations agent. `mso models` manages AI provider/API/OAuth connections; `mso model` only selects the active model from providers that are already connected.
+- **Use Alfa Cockpit** — the in-browser assistant now surfaces selected high-value MSO runtime context at the point of execution: active provider/model, searchable project context, trusted host Skills, typed-memory status, native agent sessions, same-principal local-agent presence, pending approvals, and one Activity & Runs timeline. The Cockpit intentionally does **not** claim full CLI parity; credentials/server wiring stay in Settings and dangerous actions still use Alfa's existing approval cards. The same read-model is scriptable as `mso cockpit [project]` / `mso cockpit search <query>`, so the UI does not own a parallel project/session/memory implementation.
+- **Run saved Automations for real** — browser-local automation recipes now re-enter Alfa's normal tool loop instead of only narrating their steps. Reads execute through the existing host bindings; write/exec steps keep the same per-call human approval gate. Playbook starter prompts also appear as bounded quick actions in an empty chat.
+- **Automate deployment providers without handing tokens to the model** — Dokploy and Cloudflare are built-in feature apps; `mso provider` also supports Hostinger DNS. Secrets stay in owner-only MSO state while bounded provider tools perform live checks and approved deployment/DNS operations. See [docs/INFRASTRUCTURE-PROVIDERS.md](../INFRASTRUCTURE-PROVIDERS.md).
+- **Drive the box from ChatGPT, Codex, Claude Code, Cursor, Gemini CLI or VS Code** — MSO exposes one generic OAuth MCP server. ChatGPT gets a source-generated compact static profile with complete title/safety/security metadata, resource-bound OAuth + rotating refresh tokens, while other MCP clients can use the full catalog. Exact current counts and hashes live in [the generated MCP catalog](../generated/MCP-CATALOG.md) so this README does not freeze a stale scanner count. Project-owned MCP tool names never enter the global list: discover/call them dynamically through the generic `project_mcp_tools` / `project_mcp_call` seam. See the [ChatGPT custom MCP guide](../CHATGPT-PLUGIN.md) and [MCP reference](../MCP.md).
+- **Message live local sessions by a short name** — every durable same-principal MSO session gets a unique familiar handle such as `@milo`, `@luna`, or `@nara`, independent from its longer auto-generated session title. `/rename <name>` changes that handle, while `/title <text>` changes the session description. `@milo …` resolves only agents with a current lease **and** a live receiver subscription, then creates an explicitly correlated request; replies relay deterministically into the originating conversation while notify-only events remain passive. Presence lease (`idle`/`busy`/`offline`) and receiver subscription (`consumerConnected`) are reported separately so an idle-but-unsubscribed target is diagnosable. For ChatGPT/MCP sessions, `local_agent_inbox(wait_ms=...)` temporarily turns the foreground MCP call into that live receiver for up to 20 seconds, enabling direct two-way session messaging without a worker, DB, webhook, or broker. See [Local Agents](../LOCAL-AGENTS.md).
+- **Spawn focused same-session subagents** — `/spawn` and `agent_subagent_run` create bounded foreground workers with isolated context, explicit delegated scope, turn/timeout caps, no recursive spawn, and final-result-only return. They are not Local Agent peers and do not run autonomously after the parent call returns. See [Subagents](../SUBAGENTS.md).
+- **Delegate between remote agents with standard A2A v1** — register public HTTPS peers, attach private API-key/Bearer/OAuth access-token profiles, stream remote tasks over SSE, or expose MSO's authenticated inbound Agent Card when a public HTTPS origin is configured. Inbound credentials are owner-minted `read | write | exec` capabilities and run in a memory-isolated task context. See [A2A](../A2A.md).
+- **Keep agents efficient independently of the model provider** — the MCP-first [Cognitive Runtime](../COGNITIVE-RUNTIME.md) isolates conversations from OAuth identity, budgets model context/tool output, uses the RASMIC catalog-first router to select a small per-turn capability pack without weakening scopes, compacts durable sessions with sanitized 30-day backup archives, learns only verified workflow recipes, gates repeated procedures through Tool Forge, and batches/filter/aggregates independent reads through `read_pipeline` before raw data reaches the model. Executable Tool Forge candidates require the explicitly provisioned local Forge sandbox and fail closed when that image is absent. `bun run bench:cognitive`, `bun run bench:memory:calibration`, `bun run bench:memory:lifecycle`, `bun run bench:memory:retrieval-calibration`, `bun run bench:pipeline`, isolated scratch-fixture `bun run bench:corpus`, deterministic repeated `bun run bench:corpus:repeat`, and observation-only `bun run bench:cache-calibration` guard routing, memory correction/privacy/retention semantics, frozen-session behavior, retrieval evidence gates, correctness, policy compliance, repeat coverage/spread, latency, context savings, cache telemetry, and proof-gated normalized provider usage.
+- **Make orchestration risk-aware and self-improving** — [RASMIC](../RASMIC.md) classifies task risk/contention, retrieves compact repo-local memory, records manual user tests and Evidence Receipts, detects path/shared-resource collisions before merge conflicts, and promotes repeated safe routes from observed traces → recipes → tested bounded scripts.
+- **Add app slices** — features are modular under `frontend/slices/<slug>/`.
+- **Personalize the interface** — macOS, Windows, iOS, and Android shell layouts are UI preferences, not the core product.
+
+### Cognitive Runtime evidence boundary
+
+The public Cognitive Runtime claim baseline was revalidated on **2026-09-04** against source/main/origin and the deployed build at `1d65a6a`. Current deterministic gates at that SHA report **100% required-tool routing recall**, **96.6% average active-schema reduction**, **8/8 typed-memory fixtures**, **6/6 P9 correction/privacy calibration scenarios at 200 corrections**, and **8/8 P10 lifecycle scenarios**. The P10 retrieval gate is intentionally mixed: lexical retrieval is **4/6**, the existing local semantic candidate is **3/6**, and the bounded two-hop relationship fixture is **3/3**; therefore MSO does **not** claim that vector or graph memory is universally unnecessary.
+
+The strongest currently revalidated MSO↔Hermes comparison is the exact P7+P8 **five-run, nine-scenario, matched `openai-codex/gpt-5.6-terra` corpus**: both agents are **5/5 perfect full runs**. On those exact runs, MSO observed **74.7% fewer normalized tokens/attempt**, **12.8% lower mean average latency**, and **34.1% lower mean per-run p50**. These are corpus-specific observations, **not** a claim that MSO is universally faster, smarter, cheaper, or more reliable. Cost is not ranked; cache-hit frequency is not ranked; OpenClaw is not ranked without an equivalent provider/model path. Older P4/P5 numeric tables remain historical release notes and are not the current public benchmark baseline because this audit could not independently revalidate the exact raw artifacts behind those specific numbers. See [Cognitive Runtime → Evidence status and claim boundaries](../COGNITIVE-RUNTIME.md#evidence-status-and-claim-boundaries) and the versioned [claim-audit evidence manifest](../evidence/cognitive-runtime-claim-audit-2026-09-04.json).
+
+</details>
+
+## Install
+
+Run on your Linux server as your **normal user, not root**. Review the
+[bootstrap](../../scripts/install.sh) and [installation guide](../INSTALL.md) before executing:
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
+```
+
+The bootstrap verifies the downloaded installer core before running it. The guided setup
+handles credentials through hidden prompts; never paste secrets into chat or command arguments.
+The default bind is **127.0.0.1**. Keep the raw application port private.
+
+```bash
+mso doctor # verify the installation
+mso web # open the browser workspace
+mso # open the terminal agent
+mso update # update an existing installation safely
+```
+
+Already installed but missing `mso update`? Re-run the official installer. It preserves
+`.env.local` and `~/.mso`, detects the existing service checkout, and refuses dirty/diverged source.
+An agent can follow the same repository-owned installation contract; no parallel setup is needed.
+
+<details>
+<summary><strong>Full setup: onboarding, WSL, providers, tunnels and installer options</strong></summary>
+
+### Install or update with an AI agent
+
+If your AI agent can open this repository and run commands on your server, your request can be as
+short as:
+
+```text
+Install or update MSO from this repo: https://github.com/rahmanef63/mso
+```
+
+The repository carries the rest of the contract. The agent should use MSO's official installer/update
+paths rather than reconstructing setup commands by hand, preserve an existing `.env.local` and
+`~/.mso`, update the checkout already owned by `mso.service` instead of creating a second clone, and
+finish with `mso doctor`. For a current install it may use `mso update` (the same lifecycle exposed by
+Settings → About). If the installed build is old enough that `mso update` or the About updater does not
+exist yet, the universal upgrade/recovery path is simply to re-run the current one-line installer below.
+Only credentials or choices that cannot be inferred should come back to the user; provider secrets must
+stay in hidden/STDIN onboarding prompts rather than command arguments or chat logs.
+
+Run one command on the Linux server as your normal user, **not root**:
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash
+```
+
+That URL is now a **small bootstrap, not the 30 KB installer body**. It downloads
+`scripts/install-core.sh` to a private temporary file, retries transient transfers, requires
+the complete EOF marker, verifies the committed SHA-256 and `bash -n`, and only then executes
+the core. This prevents a truncated `curl | bash` response from stopping after a few preflight
+lines while incorrectly returning success. The command stays the same; the execution boundary is safer.
+
+A fresh install now finishes with a **guided terminal onboarding** when a controlling
+terminal is available. The public bootstrap itself arrives on stdin, so the verified core
+still opens `/dev/tty` for prompts instead of depending on pipeline stdin.
+The flow lets you choose:
+
+- **Alfa AI provider** — OpenAI ChatGPT/Codex device OAuth, or an API-key provider such
+ as Anthropic, OpenAI Platform, OpenRouter, Google, Groq, xAI, DeepSeek or Mistral;
+- **Alfa response preset** — normal, Caveman or Ponytail;
+- optional **Hermes / OpenClaw / 9Router** installation (their provider settings remain separate
+ from Alfa's credentials);
+- optional **Dokploy** plus **Cloudflare or Hostinger** infrastructure connection. Provider secrets
+ are entered with hidden prompts and stay server-side;
+- reviewed **installable skills** such as Ponytail, Caveman and the MSO-safe RTK wrapper.
+
+Immediately after checkout, the installer installs and validates the CLI **before dependency
+installation, the production build, or systemd setup**. It always creates `~/.local/bin/mso`;
+when the invoking shell already has `/usr/local/bin` on `PATH`, it also installs a guarded
+`/usr/local/bin/mso` launcher (using sudo when needed). That order matters on WSL: even if a
+subsequent Bun/Next build fails, `mso -h` remains available for diagnosis and a safe rerun.
+The production build invokes Next's installed Node entrypoint directly instead of resolving
+`next` through Bun's `.bin` remapper, avoiding Bun 1.3.x's intermittent WSL `bin metadata file`
+corruption path.
+
+A child `curl | bash` process cannot modify its parent shell's `PATH`. The installer therefore
+checks the **original invoking PATH** after creating the launchers and explicitly reports whether
+`mso -h` will work immediately. If neither launcher is already reachable from that PATH, the
+install still succeeds, persists `~/.local/bin` in the normal shell profile, and prints the exact
+`export PATH=...` command for the current shell instead of falsely claiming success.
+
+If the environment has no controlling TTY (CI/cloud-init), the installer never blocks. It
+prints the resume command instead:
+
+```bash
+mso onboard
+```
+
+For an intentionally non-interactive install, use safe minimal defaults. `-y` does **not**
+auto-connect external accounts, install large managed apps, or silently add community
+skills:
+
+```bash
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- -y
+```
+
+Already installed? Use the least surprising path:
+
+- **Current MSO:** `mso update`, or Settings → About → Update.
+- **Older/legacy MSO where that updater is missing or broken:** re-run the same one-line installer.
+ It discovers an existing `mso.service` WorkingDirectory before choosing a default directory, updates
+ that checkout in place, preserves `.env.local` + `~/.mso`, and does not repeat onboarding unless
+ `--onboard` is requested.
+- **Recovery:** re-running the installer is also the supported way to repair installer/runtime wiring;
+ it refuses dirty/diverged source instead of resetting user work.
+
+After installation, the installer prints whether the current shell can already resolve `mso`.
+On the normal Ubuntu/WSL PATH (which includes `/usr/local/bin`) these work immediately:
+
+```bash
+mso # interactive MSO setup/operations agent
+mso -h
+mso models # configure AI provider/API/OAuth connections (does not switch model)
+mso model # arrow-key model picker from connected providers
+mso --continue # resume the latest durable MSO Agent session
+mso doctor
+mso onboard # run/re-run guided setup; starts the built loopback runtime on WSL when needed
+mso provider list # Dokploy/Cloudflare/Hostinger status (secrets masked)
+mso web # open local UI; starts the built loopback runtime if no service is active
+mso update # fetch/verify/build safely; does not require :4005 to be alive
+mso skills available # reviewed installable skill list
+mso skills install ponytail caveman rtk -y
+```
+
+Interactive model/provider menus use a native picker: **↑/↓** moves, typing filters, **Enter**
+selects, and **Esc** cancels. No provider/model number has to be memorized. `/session` and bare
+`/resume` open one recent-session picker directly: newest modified session first, short `@name`
+as the primary label, with the longer human session title and compact `modified …` metadata. Durable session IDs stay hidden in the normal
+picker UI but remain accepted by scriptable `--resume`/`/resume` queries. `/new [title]` persists the
+current session and switches the same terminal to a fresh durable session. `/restart` is a soft Agent
+process replacement: it persists the current session, closes the composer, then reloads the latest CLI
+and Agent modules against that exact same durable session id. Repeated restarts keep a constant process
+depth. It does **not** restart the MSO service or VPS; updated code plus the latest dynamic
+skill/tool/plugin catalog are picked up without abandoning the conversation. Live same-host sessions require no
+manual refresh path: `/agents` discovers them automatically, `@milo <prompt>` dispatches a correlated request only when `milo` is active,
+`/message <agent> <text>` sends notify-only data, `/delegate <agent> <task>` sends a correlated local task before
+remote-A2A fallback, and `/inbox` shows the current session's native agent mailbox. Correlated replies relay as a
+durable synthetic assistant response; notify-only events remain passive peer events. `/spawn` is a separate foreground
+same-session subagent primitive with isolated context and final-result-only return.
+In the Agent slash palette, executable skills carry lifecycle markers so their state is visible before and after use:
+`◇ ready` → `◆ queued` (selected for the next message) → `✓ invoked` (actually sent with a model turn).
+The interactive transcript is sectioned by full-width `Assistant`, `Agent work`, `Local agent`, and `Error`
+dividers. The composer stays in its own bottom `Input · @name` area: the short session handle is the input
+identity (`@milo ›`), while permission is shown separately in the bottom footer as `mode ask|auto|yolo`.
+Tab on an empty prompt cycles that footer in place without adding scrollback. MSO defaults to `ask`; use
+`mso --yolo` or `mso -yolo` when you explicitly want write+exec calls auto-approved for that Agent
+process. YOLO still computes and sends the canonical exact-payload approval digest; it only skips the
+interactive compact approval prompt. `/permission` opens the same arrow-key style selector; `auto-write`
+approves writes but still asks before exec. Permission mode is process-local and is not persisted into a
+resumed session. Recoverable HTTP/API failures render a bounded `Error` section instead of silently
+ending the interaction. If a write/exec delivery is uncertain, MSO stops that turn and never retries the
+mutation automatically; if an earlier mutation completed, the error section says so and instructs the
+user/client to continue from that result rather than repeat it. Terminal controls follow familiar agent/shell conventions: **Ctrl+C** clears a non-empty draft, exits from an empty idle prompt, and
+interrupts an active model/tool turn; **Ctrl+D** deletes the character to the right or exits on an
+empty prompt; **Ctrl+L** clears/repaints; **Ctrl+W** deletes the previous word; **↑/↓** or
+**Ctrl+P/N** browse prompt history, including durable user prompts restored by `--continue`/`/resume`. Long drafts wrap dynamically to terminal width/height; **↑/↓** move between visual wrapped rows before falling through to history navigation;
+**Ctrl+A/E** and **Ctrl+B/F** move to line boundaries or one character, **Ctrl+U/K** delete to the
+start/end of the line, and **Alt+B/F** or **Ctrl+←/→** move by word. `/quit` is an alias for `/exit`.
+An interrupted turn is removed from durable conversation
+history so `--continue` never resumes a half-turn. Server-side jobs that were already created retain
+their own bounded job/cancel lifecycle.
+
+If it explicitly says the current shell cannot see the user launcher yet, run the one-line
+`export PATH="$HOME/.local/bin:$PATH"` it prints; new shells use the persisted profile entry.
+
+**WSL2:** the CLI is supported even when systemd is not active. In that case the installer now
+finishes the CLI instead of failing in `systemctl`, but it skips `mso.service`. `mso onboard` and
+`mso web` can start the already-built production runtime detached on `127.0.0.1` and track ownership
+under private state; `mso update` can update/verify/build without a running API and safely inventories, quiesces and restores every gateway-owned fallback runtime for that checkout instead of rebuilding `.next` underneath any of them. For the full
+background service, enable systemd in `/etc/wsl.conf`, exit all WSL sessions from Windows, reopen
+the distro, then re-run the installer with `--onboard`.
+
+`Caveman`/`Ponytail` appear in two intentionally different places. **Response presets**
+(`mso config style caveman|ponytail`) are lightweight Alfa output policies. The market
+entries are full `SKILL.md` packages installed into the trusted operator root
+`~/.mso/skills`. Selecting a preset does not secretly install a skill, and installing a
+skill does not rewrite the global response preset.
+
+The curated `rtk` skill is an MSO-safe wrapper: it teaches agents to use RTK when the
+binary is already present, but it does **not** run an unpinned remote installer, modify
+shell profiles, or enable global hooks. Installing the RTK binary is a separate explicit
+system change.
+
+MSO binds **`127.0.0.1` by default**, so nothing is published directly to your network.
+On a laptop/WSL install, the supported public-preview path keeps that invariant and creates an
+**outbound HTTPS tunnel** instead of opening port 4005 to the LAN/Internet:
+
+```bash
+mso gateway doctor
+mso gateway start # temporary HTTPS URL; installs MSO's pinned cloudflared on first use
+mso web # opens the active public URL, or loopback when no gateway is running
+mso gateway status
+mso gateway stop
+```
+
+Temporary mode uses a Cloudflare Quick Tunnel and does **not** change `OS_PUBLIC_ORIGIN`, the
+MSO bind address, router/NAT rules, or the Windows firewall. The normal password + approved-device
+gate, live device roles, Secure/HttpOnly/SameSite cookie, same-origin mutation gate, CSP and login
+rate limits remain in front of the host APIs. Gateway state/logs live under an owner-only
+checkout+loopback-origin namespace below `~/.mso/private/gateway`, so two clones/ports cannot control
+each other's tunnel. `stop` validates process identity before terminating anything. On first use, MSO downloads the reviewed `cloudflared` release pinned in
+`security/gateway-artifacts.env` into user-local `~/.mso/tools`, verifies its SHA-256 before first
+execution and again before every reuse, and passes `--no-autoupdate`. No root package install,
+mutable `latest`, or `curl | sh` is involved. Use `mso gateway install` to prefetch it explicitly.
+
+Quick Tunnels are a **preview/testing** surface, not the permanent deployment path. Cloudflare
+documents a 200-concurrent-request limit and no Server-Sent Events support; MSO's live Terminal
+uses SSE, so that stream can be unavailable in temporary mode. Files, Settings and ordinary UI/API
+requests still use the normal authenticated HTTPS surface. For full-time/full-feature access, use a
+named tunnel/custom domain or another production HTTPS reverse proxy.
+
+For a stable domain, keep MSO on loopback and make the public origin explicit:
+
+```bash
+mso gateway domain set https://mso.example.com
+# create/configure the named Cloudflare Tunnel using the example printed above, then:
+mso gateway start --config ~/.cloudflared/config.yml --tunnel mso
+
+mso web
+```
+
+If another gateway is already active, stop it first with `mso gateway stop`. MSO refuses to silently ignore explicit named-tunnel arguments or switch tunnel modes underneath an active endpoint.
+
+
+`mso gateway domain set` updates `OS_PUBLIC_ORIGIN` atomically and prints a loopback-only ingress
+example. Named mode accepts only a dedicated two-rule config (`your hostname → MSO loopback`, then
+`http_status:404`) and a private owner-owned credentials file. It does not put tunnel tokens on a
+command line. A permanent Cloudflare deployment can then add Cloudflare Access/WAF policy in front
+of MSO. If you prefer an
+SSH-only connection instead, use:
+
+```bash
+ssh -N -L 4005:127.0.0.1:4005 you@your-server
+```
+
+The local tunnel is not just hygiene. The session cookie is `Secure`; ordinary plain-HTTP public IP
+addresses drop it. Bind wider only when the network/firewall design explicitly requires it.
+
+Useful installer controls:
+
+| Control | What it is for |
+|---|---|
+| `--dir PATH` | Explicit install directory. Normally omit it so an existing service checkout is detected automatically. |
+| `--ref REF` | Development/testing ref. Normal installs and self-update use `main`. |
+| `--port N` | Local MSO port; default `4005`. |
+| `--bind ADDR` | Listen address; default `127.0.0.1`. Do not use `0.0.0.0` unless your firewall/TLS design explicitly requires it. |
+| `--no-service` | Build only; do not install the systemd service. |
+| `--onboard` | Run guided onboarding even while upgrading an existing install. |
+| `--no-onboard` | Install/update without starting onboarding. |
+| `-y`, `--yes` | Safe non-interactive defaults; does not connect accounts or install optional apps/skills. |
+| `--uninstall` | Remove the systemd unit and MSO CLI links while keeping code and `~/.mso`. |
+| `-h`, `--help` | Print the installer contract without changing the host. |
+
+Equivalent public environment overrides are `MSO_DIR`, `MSO_REF`, `MSO_PORT`, `MSO_BIND`, and
+`MSO_REPO`. Command-line flags are clearer for people; environment overrides are useful to automation.
+
+```bash
+# force onboarding even while updating an existing install
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --onboard
+
+# update/build without onboarding
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --no-onboard
+
+# explicit non-default location/port (only when you intentionally need them)
+curl -fsSL https://raw.githubusercontent.com/rahmanef63/mso/main/scripts/install.sh | bash -s -- --dir "$HOME/mso" --port 4005
+```
+
+There is also a no-login install guide at **<https://mso.rahmanef.com/install>**. **Browser
+sign-in requires HTTPS**, except when you access MSO through a loopback URL such as
+`http://localhost:4005`. Do not pair/approve a browser on plain `http://<server-ip>:4005`:
+the session cookie is `Secure`, so the browser cannot keep the login there. Full production setup,
+TLS/VPN notes, filesystem roots, update/rollback and onboarding details live in
+[docs/INSTALL.md](../INSTALL.md).
+
+</details>
+
+## How it works
+
+```mermaid
+flowchart LR
+ USER["Browser / CLI / MCP client"] --> AUTH["Authentication + role / scope"]
+ AUTH --> MSO["MSO · Next.js / Node"]
+ MSO --> HOST["Guarded host capabilities"]
+ HOST --> FILES["Files · PTY · metrics · services"]
+ MSO --> AI["Optional model provider"]
+ MSO --> APPS["Optional managed apps · separate runtimes"]
+```
+
+Core persistence is local. Optional model-provider calls send the selected context off-host;
+**BYOK does not mean the data stays on your server**. Files and model output are untrusted input,
+not permission to execute a command. See [architecture](../ARCHITECTURE.md) and
+[the AI/tool contract](../../frontend/slices/assistant/CONTRACT.md).
+
+## CLI
+
+```bash
+mso -h # discover commands
+mso stats # inspect system health
+mso ls ~/projects # browse a configured filesystem root
+mso model # select a connected model
+mso --continue # resume the latest durable agent session
+```
+
+<details>
+<summary><strong>More CLI examples and integration notes</strong></summary>
+
+The browser UI is one frontend, not the product. The installer puts `mso` on your
+`PATH`, and it reaches the same API — every endpoint has a named verb, and `mso api`
+covers anything without one.
+
+```bash
+mso # interactive setup/operations agent with MSO ASCII terminal UI
+mso -h # grouped command list; `mso <command> --help` per command
+mso models # configure AI provider/API/OAuth connections
+mso model # arrow-key model picker / switch active model
+mso --continue # resume the latest MSO Agent session
+mso --resume "@milo" # resume by @name; index/id/title queries remain supported
+mso doctor # includes HTTPS/login-origin diagnosis
+mso doctor --fix # safe local repairs; never changes DNS/TLS/firewall/credentials
+mso onboard # guided AI/app/infrastructure/skill setup
+mso provider list # masked Dokploy/Cloudflare/Hostinger state
+mso provider set cloudflare # hidden credential prompts + live verification
+mso skills available # curated installable skills
+mso skills install ponytail caveman rtk -y
+mso device pending # who typed the password and is waiting
+mso device approve <id> "my phone" --role viewer
+mso ls ~/projects # files; `raw` for binaries, `zip`/`upload` for transfers
+mso exec "df -h" # host shell
+mso stats # cpu / mem / disk
+mso units # system + user systemd inventory
+mso unit logs user mso.service
+mso packages # cached updates; never applies them
+mso camoufox start # power the anti-detection browser
+mso mapp logs hermes # managed apps (hermes, openclaw, 9router)
+mso term open # interactive PTY
+mso service restart # systemd
+mso api GET /api/v1/sys/stats # escape hatch — any endpoint
+eval "$(mso completion bash)" # tab completion
+```
+
+Full command reference: [docs/CLI.md](../CLI.md) (generated from `mso --help`).
+
+Global options: `--base <url>` to target another instance, `--env <file>` to pick a
+different secrets file. Device and service commands work even while the service is
+down. If you use [Claude Code](https://claude.com/claude-code), the installer also
+links every committed official skill in `claude-skills/` into `~/.claude/skills/`. Create a consistent workflow skill with `bun run skill:new -- --help` and validate the catalog with `bun run skill:check`.
+
+</details>
+
+## Security warning
+
+**The terminal and exec-scoped tools are not sandboxes.** Device roles narrow API access,
+but every role shares one deployment and the same underlying Unix service account.
+MCP is disabled unless explicitly enabled. Approve only trusted devices and tokens; keep
+filesystem write roots narrow and read the exact command on every approval card.
+The one-shot exec guard refuses unresolved shell expansion in recursive-delete targets;
+this is a conservative accident guard, not proof that arbitrary shell scripts are safe.
+
+Security checks are evidence at a particular revision, not a guarantee. The project has
+**not had an independent third-party security audit**. Read the [security policy](../../SECURITY.md)
+and [repeatable assurance process](../SECURITY-ASSURANCE.md) before exposing an instance.
+
+<details>
+<summary><strong>Full trust boundaries, provider data handling and operational controls</strong></summary>
+
+An authenticated **Owner** session can read allowed files and run commands as the Unix user that owns the process. Viewer and Operator devices are server-gated to narrower surfaces, but all roles still share one MSO deployment and one underlying Unix account.
+
+- Run as a dedicated non-root user.
+- Prefer Tailscale or a VPN; otherwise use HTTPS plus a strict firewall or allowlist.
+- Use a strong `OS_SESSION_SECRET` and a strong `OS_LOGIN_PASSWORD`.
+- Approve only trusted devices; use Viewer by default, Operator only for bounded operational work, and Owner only where full host authority is intended. Device approval is an allowlist, not standards-based MFA or a named-user directory.
+- Keep write roots narrow with `OS_FS_WRITE_ROOTS`.
+- Service inventory is read-only by default. Lifecycle buttons require Operator/Owner **and** an exact `OS_SERVICE_CONTROL_UNITS` entry; wildcards are rejected. Package visibility reads only the existing local cache and never upgrades the host.
+- Never commit `.env.local`, API keys, or data from `~/.mso`. Infrastructure provider tokens live in `~/.mso/private/infra-providers.json` with owner-only permissions; the agent receives only credential-free tool schemas and masked provider state.
+- Dokploy/Cloudflare/Hostinger automation is intentionally bounded. Cloudflare changes one exact record and never bulk-writes a zone; proxying defaults off. Hostinger updates one exact name/type RR-set with `overwrite:true`; unrelated zone rows are never sent in the mutation payload, while ambiguity/conflicts are still refused and writes require approval.
+- Managed-app dashboards are not embedded by default. 9Router is loopback-only by default; a direct public-IP bind requires `NINE_ROUTER_EXPOSE_PUBLIC=1`, while a configured application hostname remains its preferred in-shell UI. Give each vendor UI a separate explicit hostname such as `hermes.mso.example.com`; there is no supported same-origin iframe mode.
+- Camoufox/noVNC is also never served on the cockpit origin. It uses the reserved split-origin host such as `camoufox.mso.example.com`; the legacy `/camoufox-vnc/*` path is permanently closed.
+- That boundary is browser-only: a plugin installed into Hermes or OpenClaw runs inside that daemon and can run host commands according to the daemon's own trust model.
+- With a model provider configured, Alfa is a tool-calling agent, not a plain chatbot. Its complete current catalog and human-approval contract are generated from `frontend/slices/assistant/host-tools/*` and documented in `frontend/slices/assistant/CONTRACT.md`; avoid copying a tool count into overview docs because the catalog changes independently of MCP.
+- Everything Alfa reads — file contents, command output, process lists — is sent to your model provider, and is re-sent on every following turn of the same run. BYOK means you own the key, not that the data stays on the box.
+- Choosing an Alfa Cockpit project adds a **bounded metadata snapshot** to each turn (project/path, branch/tree state, HEAD, knowledge availability, and recent project-memory topic titles). It does not inject raw project knowledge or raw repo-memory bodies. Cockpit also masks non-`normal` typed-memory keys/values as `Private memory`; selecting a project is context, never mutation permission.
+- Treat any file Alfa reads as untrusted input. The approval card is the only thing between text hidden inside a file and an `exec.run`. Read the command on the card, not Alfa's summary of it.
+- Agents and Skills group tools for your own convenience. They are not a permission boundary: every agent can call every tool.
+- `exec.run` is not sandboxed. Its cwd is bounded to your write roots, but the command itself runs in your login shell as the service user. The destructive-command denylist is a short accident tripwire, not a guard.
+- The MCP server is off unless `OS_MCP_ENABLED=1`. When on, a bearer token is a standing credential with whatever scope you granted it: at `exec` it runs any command on the box as you, and every call and result goes to the client's provider. The consent screen preselects the server ceiling (`exec` by default), so lower it before Allow when a client needs less; cap all tokens with `OS_MCP_MAX_SCOPE`, and treat anything the model reads as untrusted — scope is what stops a prompt-injected file talking it into a write. See [docs/MCP.md](../MCP.md).
+- MSO has not had a third-party security audit.
+
+More detail: [SECURITY.md](../../SECURITY.md), [docs/FAQ.md](../FAQ.md) and [docs/INSTALL.md](../INSTALL.md).
+
+</details>
+
+## Development
+
+The reference runtime is **Node 22** (`.nvmrc`); use **Bun** for dependency installation and
+`bun.lock` for reproducibility. Run local development only on a trusted machine.
+
+```bash
+bun install --frozen-lockfile
+cp .env.example .env.local # configure local credentials; never commit this file
+bun run dev
+```
+
+```bash
+bun run verify # typecheck, lint, coverage, architecture/docs, local audit
+bun run test:features # separate test process for each area; reports coverage gaps
+bun run audit:strict # unavailable/malformed dependency evidence fails closed
+bash scripts/verify-build.sh # compile committed HEAD out-of-tree, not over a live build
+```
+
+`bun run test` uses Vitest. **Do not substitute `bun test`**, which uses a different runner.
+The ordinary local audit can explicitly skip an unavailable registry; it is not security proof.
+Use the strict audit and the [security lanes](../SECURITY-ASSURANCE.md) for release assurance.
+
+**Version contracts are independent:** `package.json` owns the app version, `bin/mso`
+owns CLI compatibility, and `lib/mcp/toolset.ts` owns MCP server/toolset compatibility.
+`mso --version` labels app, CLI and Git build; the updater uses the exact Git build as release authority.
+A documentation/security-maintenance change does not invent a new MCP tool contract.
+
+## Comparison
+
+<details>
+<summary><strong>Product scope comparison — methodology and limitations included</strong></summary>
+
+See [the generated product comparison](../COMPARISON.md).
+
+</details>
+
+## Tested platforms
+
+<details>
+<summary><strong>Linux / WSL deployment support and untested platforms</strong></summary>
+
+Not yet formally tested across a full distro matrix.
+
+Tested:
+
+- Ubuntu 22.04
+- Ubuntu 24.04
+
+Supported deployment shapes:
+
+- WSL2 Ubuntu: CLI/install path works without systemd; the background service requires systemd enabled in WSL
+- Debian 12 and other systemd-based Linux distributions with Node.js 20.9+ and build tools
+
+Not currently supported:
+
+- Windows host
+- macOS host
+- Automatic service install on non-systemd hosts
+- Root deployment
+
+</details>
+
+## Documentation
+
+| Start here | Reference |
+|---|---|
+| Install, update, recover | [Installation](../INSTALL.md) · [Troubleshooting](../TROUBLESHOOTING.md) |
+| Use the CLI or connect MCP | [Generated CLI reference](../CLI.md) · [MCP](../MCP.md) · [ChatGPT integration](../CHATGPT-PLUGIN.md) |
+| Understand the runtime | [Architecture](../ARCHITECTURE.md) · [Cognitive Runtime](../COGNITIVE-RUNTIME.md) |
+| Contribute or review security | [Contributing](../../CONTRIBUTING.md) · [Development](../DEVELOPMENT.md) · [Security](../../SECURITY.md) |
+| Browse everything | [Documentation map](../README.md) · [Changelog](../CHANGELOG.md) |
+
+The [maintainer's instance](https://mso.rahmanef.com) requires authentication; it is **not a public demo**.
+The [recorded demo](../media/demo.gif) is available without access to a real server.
+A separate mock-only demo must keep `NEXT_PUBLIC_OS_DEMO=1` at build time and bind to loopback
+unless its owner explicitly publishes it; never enable demo mode on an owner deployment.
+
+## Status and license
+
+**Public Alpha / Developer Preview** — expect rough edges and breaking changes.
+MIT licensed; see [LICENSE](../../LICENSE).
diff --git a/frontend/slices/os-settings/components/about-section.tsx b/frontend/slices/os-settings/components/about-section.tsx
index 1167ea39..f1f7965b 100644
--- a/frontend/slices/os-settings/components/about-section.tsx
+++ b/frontend/slices/os-settings/components/about-section.tsx
@@ -1,9 +1,7 @@
"use client";
import { useEffect, useState } from "react";
-import { Info, RotateCcw } from "lucide-react";
-import { Button } from "@/components/ui/button";
-import { FormDrawer } from "@/features/appshell";
+import { Info } from "lucide-react";
import { useOsApi, type SysStats, type FsUsage } from "@/features/appshell";
import { fmtGiB, fmtUptime } from "@/lib/os-api/format";
import { useAppearance, effectiveServerTarget } from "@/lib/appearance";
@@ -12,31 +10,18 @@ import { SettingsSection, SettingsValueRow, SettingsActionRow } from "@/features
import { MsoMark } from "@/components/shared/mso-mark";
import { WhatsNew } from "./whats-new";
import { UpdateSection } from "./update-section";
+import { MaintenanceSection } from "./maintenance-section";
import pkg from "../../../../package.json";
import { openOnboarding } from "@/features/auth";
const APP_NAME = "Manef Shell OS";
const APP_TAGLINE = "Browser-based visual shell";
-// Wipes appearance + device identity, then reloads fresh. Storage keys keep the
-// historical "mso" prefix (changing them would orphan existing device ids).
-function performReset() {
- try {
- localStorage.removeItem("mso:tweaks");
- localStorage.removeItem("mso.device.id");
- localStorage.removeItem("mso:demo-fs");
- } catch {
- /* private mode / quota */
- }
- window.location.reload();
-}
-
export function AboutSection() {
const api = useOsApi();
const { tweaks } = useAppearance();
const [stats, setStats] = useState<SysStats | null>(null);
const [usage, setUsage] = useState<FsUsage | null>(null);
- const [confirmReset, setConfirmReset] = useState(false);
// Stats are MOCK when the active target is mock/demo — flag it so About never
// presents invented machine specs as the real host (VPS-essence honesty).
@@ -98,44 +83,10 @@ export function AboutSection() {
<WhatsNew />
- <SettingsSection icon={<RotateCcw />} title="Reset">
- <SettingsActionRow
- label="Open onboarding"
- icon={<Info />}
- onClick={openOnboarding}
- />
- <SettingsActionRow
- label="Reset MSO"
- tone="destructive"
- icon={<RotateCcw />}
- onClick={() => setConfirmReset(true)}
- />
+ <SettingsSection icon={<Info />} title="Setup">
+ <SettingsActionRow label="Open onboarding" icon={<Info />} onClick={openOnboarding} />
</SettingsSection>
-
- <FormDrawer open={confirmReset} onOpenChange={setConfirmReset} size="sm">
- <FormDrawer.Header>
- <FormDrawer.Title>Reset MSO?</FormDrawer.Title>
- <FormDrawer.Description>
- Clears appearance + device identity, then reloads. Your files on disk are untouched.
- </FormDrawer.Description>
- </FormDrawer.Header>
- <FormDrawer.Footer>
- <Button type="button" variant="ghost" onClick={() => setConfirmReset(false)}>
- Cancel
- </Button>
- <Button
- type="button"
- variant="destructive"
- onClick={() => {
- setConfirmReset(false);
- performReset();
- }}
- >
- <RotateCcw className="size-4" />
- Reset
- </Button>
- </FormDrawer.Footer>
- </FormDrawer>
+ <MaintenanceSection />
</div>
);
}
diff --git a/frontend/slices/os-settings/components/maintenance-section.tsx b/frontend/slices/os-settings/components/maintenance-section.tsx
new file mode 100644
index 00000000..396153d0
--- /dev/null
+++ b/frontend/slices/os-settings/components/maintenance-section.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { useState } from "react";
+import { Copy, RotateCcw, TerminalSquare } from "lucide-react";
+import { Button } from "@/components/ui/button";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { FormDrawer } from "@/features/appshell";
+import { SettingsSection, SettingsBlock } from "@/features/shell-settings";
+import { browserResetKeys, resetBrowserState, type BrowserResetScope } from "../lib/browser-reset";
+
+const COMMANDS = [
+ ["Reset server configuration", "mso reset"],
+ ["Factory reset server state", "mso reset --scope all"],
+ ["Uninstall, keep server data", "mso uninstall"],
+ ["Uninstall and purge owned data/code", "mso uninstall --purge --remove-code"],
+] as const;
+
+export function MaintenanceSection() {
+ const [scope, setScope] = useState<BrowserResetScope>("appearance");
+ const [pending, setPending] = useState<string[] | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [copied, setCopied] = useState<string | null>(null);
+ const preview = () => {
+ try { setError(null); setPending(browserResetKeys(localStorage, scope)); }
+ catch { setError("Browser storage is unavailable. Nothing was reset."); }
+ };
+ const apply = () => {
+ try { resetBrowserState(localStorage, scope); window.location.reload(); }
+ catch { setError("The browser reset did not complete. Review your browser storage permissions."); setPending(null); }
+ };
+ const copy = async (command: string) => {
+ try { await navigator.clipboard.writeText(command); setCopied(command); }
+ catch { setError("Copy failed. Select the command text and copy it manually."); }
+ };
+ return (
+ <>
+ <SettingsSection icon={<RotateCcw />} title="Reset this browser" footnote="Keeps device approval and server files. Server-synced appearance and Quicklinks can return after signing in; use server configuration reset to clear those too.">
+ <SettingsBlock>
+ <div className="flex flex-col gap-3 sm:flex-row sm:items-center">
+ <Select value={scope} onValueChange={(value) => setScope(value as BrowserResetScope)}>
+ <SelectTrigger className="min-h-11 flex-1" aria-label="Browser reset scope"><SelectValue /></SelectTrigger>
+ <SelectContent>
+ <SelectItem value="appearance">Appearance only</SelectItem>
+ <SelectItem value="browser">All MSO browser data</SelectItem>
+ </SelectContent>
+ </Select>
+ <Button variant="outline" className="min-h-11" onClick={preview}>Preview reset</Button>
+ </div>
+ <p className="mt-3 text-xs text-muted-foreground">Export a browser backup in Settings → Backup before clearing Playbooks, layouts or drafts.</p>
+ {error && <p role="alert" className="mt-2 text-xs text-destructive-text">{error}</p>}
+ </SettingsBlock>
+ </SettingsSection>
+ <SettingsSection icon={<TerminalSquare />} title="Server reset & uninstall" footnote="Run on the server through an independent SSH/local terminal. These commands only preview changes. Applying requires the current preview token and stopped MSO runtimes; it is not available through a browser button.">
+ <SettingsBlock>
+ <div className="space-y-3">
+ {COMMANDS.map(([label, command]) => (
+ <div key={command} className="min-w-0">
+ <p className="mb-1 text-xs font-medium">{label}</p>
+ <div className="flex items-start gap-2 rounded-lg border border-border bg-secondary/30 p-2">
+ <code className="min-w-0 flex-1 select-text break-words text-xs leading-6">{command}</code>
+ <Button variant="ghost" size="icon" className="size-11 shrink-0" aria-label={`Copy ${label.toLowerCase()}`} onClick={() => void copy(command)}><Copy className="size-4" /></Button>
+ </div>
+ </div>
+ ))}
+ </div>
+ <p role="status" className="mt-2 text-xs text-muted-foreground">{copied ? "Preview command copied. No server action was executed." : "Reset creates a private recovery archive. Purge permanently removes known MSO data, including reset archives."}</p>
+ <p className="mt-2 text-xs text-muted-foreground">Other projects, shared dependencies, DNS/TLS, external apps and browser profiles stay untouched. Unknown files and linked worktrees are preserved and reported.</p>
+ </SettingsBlock>
+ </SettingsSection>
+ <FormDrawer open={pending !== null} onOpenChange={(open) => { if (!open) setPending(null); }} size="sm">
+ <FormDrawer.Header>
+ <FormDrawer.Title>Reset {scope === "appearance" ? "browser appearance" : "MSO browser data"}?</FormDrawer.Title>
+ <FormDrawer.Description>{pending?.length ?? 0} local storage entries will be removed. Device identity and server data remain. Unsaved local drafts cannot be recovered without a backup.</FormDrawer.Description>
+ </FormDrawer.Header>
+ <FormDrawer.Footer>
+ <Button variant="ghost" onClick={() => setPending(null)}>Cancel</Button>
+ <Button variant="destructive" disabled={!pending?.length} onClick={apply}>Reset this browser</Button>
+ </FormDrawer.Footer>
+ </FormDrawer>
+ </>
+ );
+}
diff --git a/frontend/slices/os-settings/lib/browser-reset.test.ts b/frontend/slices/os-settings/lib/browser-reset.test.ts
new file mode 100644
index 00000000..89861c4c
--- /dev/null
+++ b/frontend/slices/os-settings/lib/browser-reset.test.ts
@@ -0,0 +1,23 @@
+import { describe, expect, it } from "vitest";
+import { browserResetKeys, resetBrowserState } from "./browser-reset";
+
+function storage(): Storage {
+ const values = new Map<string, string>([
+ ["mso:tweaks", "appearance"], ["mso.device.id", "approved-device"], ["sv:dock", "layout"],
+ ["alfa.playbooks", "playbooks"], ["reel.draft", "draft"], ["mso:demo-fs", "sample"], ["other-app", "keep"],
+ ]);
+ return { get length() { return values.size; }, key: (i) => [...values.keys()][i] ?? null,
+ getItem: (key) => values.get(key) ?? null, setItem: (key, value) => { values.set(key, value); },
+ removeItem: (key) => { values.delete(key); }, clear: () => values.clear() };
+}
+describe("browser reset ownership", () => {
+ it("previews without changing data", () => { const s = storage(); expect(browserResetKeys(s, "browser")).toHaveLength(5); expect(s.length).toBe(7); });
+ it("appearance-only preserves drafts and device approval", () => {
+ const s = storage(); expect(resetBrowserState(s, "appearance")).toBe(1);
+ expect(s.getItem("reel.draft")).toBe("draft"); expect(s.getItem("mso.device.id")).toBe("approved-device");
+ });
+ it("removes every owned entry without skipping shifting indices", () => {
+ const s = storage(); expect(resetBrowserState(s, "browser")).toBe(5);
+ expect(s.length).toBe(2); expect(s.getItem("mso.device.id")).toBe("approved-device"); expect(s.getItem("other-app")).toBe("keep");
+ });
+});
diff --git a/frontend/slices/os-settings/lib/browser-reset.ts b/frontend/slices/os-settings/lib/browser-reset.ts
new file mode 100644
index 00000000..9778ce18
--- /dev/null
+++ b/frontend/slices/os-settings/lib/browser-reset.ts
@@ -0,0 +1,20 @@
+import { MSO_LOCAL_STATE } from "@/features/appshell";
+
+export type BrowserResetScope = "appearance" | "browser";
+
+/** Snapshot before removal: Storage keys shift after each mutation. Identity is retained. */
+export function browserResetKeys(storage: Storage, scope: BrowserResetScope): string[] {
+ const keys: string[] = [];
+ for (let i = 0; i < storage.length; i++) {
+ const key = storage.key(i);
+ if (!key || key === "mso.device.id") continue;
+ const owned = MSO_LOCAL_STATE.prefixes.some((prefix) => key.startsWith(prefix)) || MSO_LOCAL_STATE.extra.includes(key);
+ if (scope === "appearance" ? key === "mso:tweaks" : owned) keys.push(key);
+ }
+ return keys;
+}
+export function resetBrowserState(storage: Storage, scope: BrowserResetScope): number {
+ const keys = browserResetKeys(storage, scope);
+ for (const key of keys) storage.removeItem(key);
+ return keys.length;
+}
diff --git a/lib/install-docs-contract.test.ts b/lib/install-docs-contract.test.ts
index 727af83c..8c9e0a19 100644
--- a/lib/install-docs-contract.test.ts
+++ b/lib/install-docs-contract.test.ts
@@ -24,14 +24,14 @@ function publicEnv() {
}
describe("installer documentation contract", () => {
- it("keeps every public installer flag and env override in README + INSTALL.md", () => {
+ it("keeps full installer options in INSTALL.md and the overview linked", () => {
expect(publicFlags().length).toBeGreaterThan(5);
expect(publicEnv().length).toBeGreaterThan(3);
for (const token of [...publicFlags(), ...publicEnv()]) {
- expect(README, `README missing ${token}`).toContain(token);
expect(INSTALL, `INSTALL.md missing ${token}`).toContain(token);
}
- expect(README).toContain("Useful installer controls");
+ expect(README).toContain("./docs/INSTALL.md");
+ expect(README.split("\n").length).toBeLessThanOrEqual(120);
});
it("documents one AI-agent path and the legacy-upgrade bridge", () => {
diff --git a/package.json b/package.json
index 838387f9..7be2af34 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "mso",
- "version": "0.2.2",
+ "version": "0.2.3",
"private": true,
"engines": {
"node": ">=20.9"
@@ -40,7 +40,8 @@
"bench:cache-calibration": "bun scripts/bench-agent-cache.mjs",
"mcp:catalog": "node scripts/gen-mcp-catalog.mjs",
"audit:strict": "node scripts/audit.mjs --strict",
- "test:features": "node scripts/test-features.mjs"
+ "test:features": "node scripts/test-features.mjs",
+ "screenshot:cli": "node scripts/capture-cli.mjs"
},
"dependencies": {
"@anthropic-ai/sdk": "^0.120.0",
diff --git a/scripts/audit.mjs b/scripts/audit.mjs
index 7424b0c1..37eeaa87 100644
--- a/scripts/audit.mjs
+++ b/scripts/audit.mjs
@@ -18,6 +18,13 @@ function unavailable(reason) {
process.exit(STRICT ? 2 : 0);
}
+// Old Bun resolves unknown commands as package scripts; avoid recursively invoking this audit.
+const versionProbe = spawnSync("bun", ["--version"], { encoding: "utf8", timeout: 5000 });
+const version = /^(\d+)\.(\d+)\.(\d+)/.exec((versionProbe.stdout ?? "").trim());
+const nativeAudit = version && (Number(version[1]) > 1 || Number(version[1]) === 1
+ && (Number(version[2]) > 2 || Number(version[2]) === 2 && Number(version[3]) >= 15));
+if (versionProbe.status !== 0 || !nativeAudit) unavailable("Bun >=1.2.15 with the native audit command is required; update Bun first");
+
const res = spawnSync("bun", ["audit", "--json"], {
encoding: "utf8", timeout: AUDIT_TIMEOUT_MS, killSignal: "SIGTERM",
});
diff --git a/scripts/audit.test.ts b/scripts/audit.test.ts
index 266cc46e..aa70d60d 100644
--- a/scripts/audit.test.ts
+++ b/scripts/audit.test.ts
@@ -6,18 +6,22 @@ import { afterEach, describe, expect, it } from "vitest";
const roots: string[] = [];
afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); });
-function audit(report: string, code = 0, strict = true) {
+function audit(report: string, code = 0, strict = true, version = "1.3.14") {
const root = mkdtempSync(path.join(tmpdir(), "mso-audit-contract-"));
chmodSync(root, 0o700); roots.push(root);
const bin = path.join(root, "bin"); mkdirSync(bin);
- writeFileSync(path.join(bin, "bun"), `#!${process.execPath}\nprocess.stdout.write(process.env.FIXTURE_REPORT ?? '');\nprocess.stderr.write('private-registry-diagnostic');\nprocess.exit(Number(process.env.FIXTURE_EXIT));\n`, { mode: 0o700 });
+ writeFileSync(path.join(bin, "bun"), `#!${process.execPath}\nif(process.argv[2]==='--version'){console.log(process.env.FIXTURE_BUN_VERSION);process.exit(0)}\nprocess.stdout.write(process.env.FIXTURE_REPORT ?? '');\nprocess.stderr.write('private-registry-diagnostic');\nprocess.exit(Number(process.env.FIXTURE_EXIT));\n`, { mode: 0o700 });
return spawnSync(process.execPath, [path.join(process.cwd(), "scripts/audit.mjs"), ...(strict ? ["--strict"] : [])], {
encoding: "utf8", env: { ...process.env, PATH: `${bin}:${process.env.PATH}`,
- FIXTURE_REPORT: report, FIXTURE_EXIT: String(code) }, timeout: 10_000,
+ FIXTURE_BUN_VERSION: version, FIXTURE_REPORT: report, FIXTURE_EXIT: String(code) }, timeout: 10_000,
});
}
describe("dependency audit evidence boundary", () => {
+ it("refuses Bun without native audit before any recursive script resolution", () => {
+ const result = audit("{}", 0, true, "1.2.14");
+ expect(result.status).toBe(2); expect(result.stderr).toContain("Bun >=1.2.15");
+ });
it("accepts a successful empty advisory report", () => {
const result = audit("{}"); expect(result.status).toBe(0); expect(result.stdout).toContain("(strict)");
});
diff --git a/scripts/capture-cli.mjs b/scripts/capture-cli.mjs
new file mode 100644
index 00000000..c968ca1a
--- /dev/null
+++ b/scripts/capture-cli.mjs
@@ -0,0 +1,53 @@
+#!/usr/bin/env node
+// Capture the real CLI in a PTY, then render those bytes with xterm. No provider/account is used.
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { createRequire } from "node:module";
+import { fileURLToPath } from "node:url";
+
+const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
+const require = createRequire(import.meta.url);
+const pty = require("node-pty");
+const { chromium } = require(path.join(root, "os-browser/node_modules/playwright"));
+const sharp = require("sharp");
+const temporaryHome = fs.mkdtempSync(path.join(os.tmpdir(), "mso-cli-capture-"));
+const env = { ...process.env, HOME: temporaryHome, TERM: "xterm-256color" };
+for (const key of Object.keys(env)) if (/^(?:MSO_|OS_|GH_|GITHUB_|OPENAI_|ANTHROPIC_|BUN_|NODE_OPTIONS)/.test(key)) delete env[key];
+let browser;
+try {
+ const output = await new Promise((resolve, reject) => {
+ const child = pty.spawn("/bin/bash", [path.join(root, "bin/mso"), "reset", "--help"], {
+ name: "xterm-256color", cols: 112, rows: 30, cwd: root, env,
+ });
+ let text = "";
+ const timer = setTimeout(() => { child.kill(); reject(new Error("CLI capture timed out")); }, 10000);
+ child.onData((value) => { text += value; });
+ child.onExit(({ exitCode }) => {
+ clearTimeout(timer);
+ if (exitCode !== 0) reject(new Error("CLI capture failed")); else resolve(text);
+ });
+ });
+ if (!String(output).includes("PREVIEW ONLY")) throw new Error("Expected maintenance CLI output was not captured");
+ browser = await chromium.launch({ headless: true });
+ const page = await browser.newPage({ viewport: { width: 1160, height: 810 }, deviceScaleFactor: 1.5 });
+ await page.setContent(`<!doctype html><html><head><meta charset="utf-8"></head><body><main id="capture"><header><span class="dots">● ● ●</span><span>Manef Shell OS · terminal</span><span class="badge">ACTUAL CLI OUTPUT</span></header><div class="command">$ mso reset --help</div><div id="terminal"></div><footer>Preview first. Apply only with explicit confirmation.</footer></main></body></html>`);
+ await page.addStyleTag({ path: path.join(path.dirname(require.resolve("@xterm/xterm")), "../css/xterm.css") });
+ await page.addStyleTag({ content: `*{box-sizing:border-box}body{margin:0;padding:24px;background:#f4f4f7;font-family:Arial,sans-serif}main{background:#1b1b20;border:1px solid #363640;border-radius:16px;overflow:hidden;padding:0 24px 18px;color:#f2f2f5}header{height:62px;display:flex;gap:20px;align-items:center;border-bottom:1px solid #363640;font-size:13px;color:#c5c5ce}.dots{letter-spacing:5px;color:#92929d}.badge{margin-left:auto;letter-spacing:1px;font-size:10px}.command{padding:20px 0 14px;font:600 15px monospace;color:#83afff}footer{border-top:1px solid #363640;padding-top:14px;color:#aaaab8;font-size:12px}#terminal{padding-bottom:12px}` });
+ await page.addScriptTag({ path: require.resolve("@xterm/xterm") });
+ await page.evaluate(async (text) => {
+ const terminal = new window.Terminal({ cols: 112, rows: 29, fontSize: 14, lineHeight: 1.2, fontFamily: "monospace", convertEol: true, cursorBlink: false,
+ theme: { background: "#1b1b20", foreground: "#f2f2f5", cursor: "#83afff" } });
+ terminal.open(document.getElementById("terminal"));
+ await new Promise((resolve) => terminal.write(text, resolve));
+ terminal.scrollToTop();
+ }, String(output));
+ await page.evaluate(() => document.fonts.ready);
+ const image = await page.locator("#capture").screenshot({ type: "png" });
+ const target = path.join(root, "docs/media/mso-cli.webp");
+ await sharp(image).webp({ lossless: true }).toFile(target);
+ console.log(`Captured real CLI output: ${path.relative(root, target)} (${fs.statSync(target).size} bytes)`);
+} finally {
+ if (browser) await browser.close();
+ fs.rmSync(temporaryHome, { recursive: true, force: true });
+}
diff --git a/scripts/cli/commands-admin.sh b/scripts/cli/commands-admin.sh
index 69bef4ec..ee1a13a5 100755
--- a/scripts/cli/commands-admin.sh
+++ b/scripts/cli/commands-admin.sh
@@ -5,6 +5,7 @@
mso_cmd_admin() {
local cmd="$1"; shift || true
case "$cmd" in
+ reset|uninstall) exec node "$ROOT/scripts/mso-maintenance.mjs" "$cmd" "$@" ;;
# ── devices (local file, works even when the service is down) ────────────
# Both shapes work: `mso devices` reads as a noun, `mso device list` matches the
# subcommand-group habit every other area here uses (mapp/term/camoufox/service).
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 83c17f24..b7e96532 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -32,6 +32,8 @@ U_term="term open [cwd] [cols] [rows]|input <id> <text>|resize <id> <cols> <rows
U_device="device list|pending|approve <id> [label] [--role viewer|operator|owner]|role <id> <role>|revoke <id>|revoke all --yes"
U_service="service status|start|stop|restart|logs [n]"
U_unit="unit logs <system|user> <unit> [limit]|start|stop|restart <system|user> <unit>"
+U_reset="reset [--scope config|all] [--json] [--apply --confirm <preview-token>]"
+U_uninstall="uninstall [--purge] [--remove-code] [--service name.service] [--json] [--apply --confirm <preview-token>]"
U_update="update [--rebuild] | status | log"
U_cockpit="cockpit [project] | cockpit show [project] | cockpit search <query…>"
U_threads="threads list|show <id>|save <json>|rm <id>"
@@ -89,7 +91,7 @@ mso_cli_main() {
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
- devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|crud|api|completion)
+ devices|device|approve|revoke|oauth|mcp|audit|whoami|login|logout|service|build|deploy|update|reset|uninstall|crud|api|completion)
mso_cmd_admin "$cmd" "$@" ;;
help|-h|--help) usage; exit 0 ;;
*) mso_cli_unknown "$cmd" ;;
diff --git a/scripts/gen-comparison.mjs b/scripts/gen-comparison.mjs
index 17acea2f..07b51765 100755
--- a/scripts/gen-comparison.mjs
+++ b/scripts/gen-comparison.mjs
@@ -69,17 +69,7 @@ const tableRule = `|---|---|${data.criteria.map(() => ":---:").join("|")}|`;
const tableRows = data.products.map((product) =>
`| **${escape(product.name)}** | ${escape(product.bestFor)} | ${data.criteria.map((criterion) => ratingLabel(product.ratings[criterion.id].value)).join(" | ")} |`
);
-const compact = [
- `**Positioning:** ${data.positioning}`,
- "",
- `Strong = a first-class product strength · Partial = available with scope limitations · Not offered = not a core product surface`,
- "",
- tableHeader,
- tableRule,
- ...tableRows,
- "",
- `Reviewed against official product documentation on **${data.reviewedAt}**. Ratings describe product scope, not benchmark scores. See [methodology, evidence, and per-cell notes](docs/COMPARISON.md) and the [execution roadmap](docs/COMPETITIVE-ROADMAP.md).`,
-].join("\n");
+const compact = `[Product comparison, evidence and limitations](docs/COMPARISON.md) · reviewed ${data.reviewedAt}.`;
const start = "<!-- comparison:start -->";
const end = "<!-- comparison:end -->";
diff --git a/scripts/install-core.sh b/scripts/install-core.sh
index 5793bca3..d4cc78a8 100755
--- a/scripts/install-core.sh
+++ b/scripts/install-core.sh
@@ -251,7 +251,11 @@ ensure_node() {
# (see the unit's ExecStart below) because node-pty's binding is built against
# node's ABI and the whole /api/v1 surface imports it.
ensure_bun() {
- command -v bun >/dev/null 2>&1 && { info "bun $(bun -v) ok"; return; }
+ if command -v bun >/dev/null 2>&1; then
+ bun -v | awk -F. '{exit !(($1+0)>1 || (($1+0)==1 && (($2+0)>2 || (($2+0)==2 && ($3+0)>=15))))}' \
+ || die "Bun >=1.2.15 is required for native dependency auditing; upgrade Bun and rerun the installer."
+ info "bun $(bun -v) ok"; return
+ fi
command -v sha256sum >/dev/null 2>&1 || die "sha256sum is required to verify the Bun bootstrap."
info "installing Bun from a pinned, verified bootstrap…"
local bootstrap actual url
diff --git a/scripts/install.sh b/scripts/install.sh
index eba1204a..721a8184 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="31a50e9b8306c5c4f056cc9b351627b8368ef437440c6154bc2544b235908d7b"
+CORE_SHA256="ac481aff3e31bbe829ab9238ff209ba92b96234127756df2b6b021222c304899"
CORE_EOF='# MSO_INSTALLER_CORE_EOF'
TMP_INSTALLER=''
diff --git a/scripts/lib/maintenance-apply.mjs b/scripts/lib/maintenance-apply.mjs
new file mode 100644
index 00000000..a067206a
--- /dev/null
+++ b/scripts/lib/maintenance-apply.mjs
@@ -0,0 +1,110 @@
+import fs from "node:fs";
+import path from "node:path";
+import { randomUUID } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { confirmationFor, maintenancePlan } from "./maintenance-plan.mjs";
+import { ensurePrivateDirectory, inside, revalidate, snapshot, statOrNull } from "./maintenance-paths.mjs";
+
+const run = (command, args) => spawnSync(command, args, { encoding: "utf8", timeout: 15000, maxBuffer: 65536 });
+export function prepareMaintenance(context, options) {
+ const plan = { ...maintenancePlan(context, options), services: [] };
+ for (const [manager, dir] of [["system", context.systemUnitDir ?? "/etc/systemd/system"], ["user", path.join(context.home, ".config/systemd/user")]]) {
+ for (const name of [options.service, "camoufox-vnc.service"]) {
+ const file = path.join(dir, name), stat = statOrNull(file);
+ if (!stat) continue;
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 65536) { plan.blockers.push(`Unverified service unit: ${name}`); continue; }
+ const text = fs.readFileSync(file, "utf8");
+ const workingDir = /^WorkingDirectory=(.*)$/m.exec(text)?.[1];
+ const start = /^ExecStart=(.*)$/m.exec(text)?.[1] ?? "";
+ const owns = workingDir === context.repo || (name === "camoufox-vnc.service" && start.startsWith(`${context.repo}/scripts/camoufox-vnc-service`));
+ if (!owns) { plan.retained.push({ path: file, reason: "Service belongs to another installation" }); continue; }
+ try {
+ const entry = snapshot(dir, file, { privileged: manager === "system" });
+ plan.services.push({ name, manager });
+ if (options.action === "uninstall") plan.targets.push({ ...entry, category: "service", name, manager });
+ } catch (error) { plan.blockers.push(error.message); }
+ }
+ }
+ return { ...plan, confirmation: confirmationFor(plan) };
+}
+export function assertOffline(plan) {
+ const cgroup = fs.readFileSync("/proc/self/cgroup", "utf8");
+ if (/(?:mso|mso-demo)\.service/.test(cgroup)) throw new Error("Run maintenance from an independent SSH/local terminal, not the MSO service");
+ for (const unit of [...plan.services, { name: "mso-self-update.service", manager: "user" }]) {
+ const result = run("systemctl", [...(unit.manager === "user" ? ["--user"] : []), "is-active", unit.name]);
+ const state = result.stdout?.trim();
+ if (["active", "activating", "reloading", "deactivating"].includes(state)) throw new Error(`Stop ${unit.manager} ${unit.name} before applying maintenance`);
+ if (plan.services.includes(unit) && !["inactive", "failed", "unknown"].includes(state)) throw new Error(`Cannot verify offline state for ${unit.name}`);
+ }
+ for (const pid of fs.readdirSync("/proc").filter((name) => /^\d+$/.test(name))) {
+ try {
+ const comm = fs.readFileSync(`/proc/${pid}/comm`, "utf8");
+ if (!/next-server/.test(comm)) continue;
+ const cwd = fs.readlinkSync(`/proc/${pid}/cwd`);
+ if (JSON.parse(fs.readFileSync(path.join(cwd, "package.json"), "utf8")).name === "mso") throw new Error(`MSO runtime ${pid} is still running; stop it first`);
+ } catch (error) { if (error.message.startsWith("MSO runtime")) throw error; }
+ }
+}
+function systemAction(command, args, privileged) {
+ const result = privileged && process.getuid() !== 0 ? run("sudo", ["-n", command, ...args]) : run(command, args);
+ if (result.status !== 0) throw new Error(`Maintenance system operation failed: ${command}; no success is assumed`);
+}
+export function applyMaintenance(context, options, plan, dependencies = {}) {
+ if (!options.apply) return { applied: false, plan };
+ if (process.getuid() === 0) throw new Error("Run as the normal installation owner, not root");
+ if (plan.blockers.length) throw new Error(`Resolve preview blockers first: ${plan.blockers.join("; ")}`);
+ if (options.confirm !== plan.confirmation) throw new Error("Explicit --confirm must match the current preview token");
+ const checkOffline = dependencies.assertOffline ?? assertOffline;
+ const privileged = dependencies.systemAction ?? systemAction;
+ checkOffline(plan);
+ for (const entry of plan.targets) revalidate(entry);
+ const lock = path.join(context.home, ".mso-maintenance.lock");
+ try { fs.mkdirSync(lock, { mode: 0o700 }); } catch { throw new Error("Maintenance lock exists; inspect any interrupted operation before retrying"); }
+ let backup = null;
+ const completed = [];
+ try {
+ // Check again under the owner-local lock; never mutate an actively served tree.
+ checkOffline(plan);
+ if (plan.action === "reset" && plan.targets.length) {
+ const base = path.join(context.home, ".mso/maintenance-backups");
+ ensurePrivateDirectory(context.home, base);
+ backup = path.join(base, randomUUID());
+ fs.mkdirSync(backup, { mode: 0o700 });
+ fs.writeFileSync(path.join(backup, "manifest.json"), JSON.stringify({ version: 1, createdAt: new Date().toISOString(), plan }, null, 2), { mode: 0o600 });
+ for (const entry of plan.targets) {
+ revalidate(entry);
+ const dest = path.join(backup, "files", path.relative(context.home, entry.path));
+ ensurePrivateDirectory(backup, path.dirname(dest));
+ fs.renameSync(entry.path, dest);
+ completed.push(entry.path);
+ }
+ } else if (plan.action === "uninstall") {
+ // Remove verified service registrations before any code/state. Failure aborts.
+ for (const entry of plan.targets.filter((entry) => entry.category === "service")) {
+ revalidate(entry);
+ privileged("systemctl", [...(entry.manager === "user" ? ["--user"] : []), "disable", entry.name], entry.privileged);
+ if (entry.privileged) privileged("rm", ["--", entry.path], true); else fs.unlinkSync(entry.path);
+ privileged("systemctl", [...(entry.manager === "user" ? ["--user"] : []), "daemon-reload"], entry.privileged);
+ if (statOrNull(entry.path)) throw new Error(`Service unit remains: ${entry.name}`);
+ completed.push(entry.path);
+ }
+ const code = plan.targets.find((entry) => entry.category === "code");
+ for (const entry of plan.targets.filter((entry) => entry.category !== "service" && entry.category !== "code")) {
+ revalidate(entry);
+ if (entry.privileged) privileged("rm", ["--", entry.path], true);
+ else fs.rmSync(entry.path, { recursive: entry.kind === "directory", force: false });
+ completed.push(entry.path);
+ }
+ if (code) {
+ // Earlier removal of .env.local changes directory mtime, but not identity.
+ const now = snapshot(code.root, code.path);
+ if (!now || now.dev !== code.dev || now.ino !== code.ino) throw new Error("Installation identity changed");
+ if (!inside(context.home, code.path)) throw new Error("Invalid installation target");
+ fs.rmSync(code.path, { recursive: true, force: false }); completed.push(code.path);
+ }
+ }
+ return { applied: true, action: plan.action, backup, completed, retained: plan.retained };
+ } catch (error) {
+ throw new Error(`${error.message}. Completed ${completed.length} step(s).${backup ? ` Recovery files: ${backup}` : ""}`);
+ } finally { fs.rmdirSync(lock); }
+}
diff --git a/scripts/lib/maintenance-paths.mjs b/scripts/lib/maintenance-paths.mjs
new file mode 100644
index 00000000..a0d351f0
--- /dev/null
+++ b/scripts/lib/maintenance-paths.mjs
@@ -0,0 +1,53 @@
+// Local-owner maintenance only. Never follow an external target while removing MSO state.
+import fs from "node:fs";
+import path from "node:path";
+
+export function inside(root, target) {
+ const relative = path.relative(root, target);
+ return relative !== "" && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
+}
+export function statOrNull(target) {
+ try { return fs.lstatSync(target); } catch (error) { if (error.code === "ENOENT") return null; throw error; }
+}
+export function safeParents(root, target) {
+ if (!inside(root, target)) throw new Error("Maintenance target is outside its ownership root");
+ const rootStat = statOrNull(root);
+ if (!rootStat?.isDirectory() || rootStat.isSymbolicLink() || fs.realpathSync(root) !== root || (rootStat.mode & 0o022)) throw new Error(`Unsafe ownership root: ${root}`);
+ let current = root;
+ for (const part of path.relative(root, path.dirname(target)).split(path.sep).filter(Boolean)) {
+ current = path.join(current, part);
+ const stat = statOrNull(current);
+ if (!stat) break;
+ if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error(`Unsafe parent: ${current}`);
+ if (stat.mode & 0o022) throw new Error(`Writable-by-others parent: ${current}`);
+ }
+}
+export function snapshot(root, target, { symlink = false, privileged = false } = {}) {
+ safeParents(root, target);
+ const stat = statOrNull(target);
+ if (!stat) return null;
+ if (stat.isSymbolicLink() && !symlink) throw new Error(`Refusing symlink state: ${target}`);
+ if (!stat.isFile() && !stat.isDirectory() && !stat.isSymbolicLink()) throw new Error(`Unsupported entry: ${target}`);
+ if (!privileged && stat.uid !== process.getuid()) throw new Error(`Not owned by the current user: ${target}`);
+ if (!stat.isSymbolicLink() && (stat.mode & 0o022)) throw new Error(`Writable-by-others target: ${target}`);
+ return { path: target, root, dev: stat.dev, ino: stat.ino, mode: stat.mode, size: stat.size, mtimeMs: stat.mtimeMs,
+ kind: stat.isSymbolicLink() ? "symlink" : stat.isDirectory() ? "directory" : "file", privileged };
+}
+export function revalidate(entry) {
+ const now = snapshot(entry.root, entry.path, { symlink: entry.kind === "symlink", privileged: entry.privileged });
+ if (!now || ["dev", "ino", "mode", "size", "mtimeMs"].some((key) => now[key] !== entry[key])) throw new Error(`Target changed since preview: ${entry.path}`);
+}
+export function ensurePrivateDirectory(root, target) {
+ safeParents(root, path.join(target, ".check"));
+ const stat = statOrNull(target);
+ if (stat && (!stat.isDirectory() || stat.isSymbolicLink() || stat.uid !== process.getuid() || (stat.mode & 0o077))) throw new Error(`Expected owner-only directory: ${target}`);
+ fs.mkdirSync(target, { recursive: true, mode: 0o700 });
+}
+export function ownedLink(root, target, repo) {
+ const stat = statOrNull(target);
+ if (!stat?.isSymbolicLink()) return null;
+ safeParents(root, target);
+ const linkTarget = path.resolve(path.dirname(target), fs.readlinkSync(target));
+ if (!inside(repo, linkTarget)) return null;
+ return snapshot(root, target, { symlink: true, privileged: stat.uid !== process.getuid() });
+}
diff --git a/scripts/lib/maintenance-plan.mjs b/scripts/lib/maintenance-plan.mjs
new file mode 100644
index 00000000..73084460
--- /dev/null
+++ b/scripts/lib/maintenance-plan.mjs
@@ -0,0 +1,96 @@
+import fs from "node:fs";
+import path from "node:path";
+import { createHash } from "node:crypto";
+import { spawnSync } from "node:child_process";
+import { inside, ownedLink, snapshot, statOrNull } from "./maintenance-paths.mjs";
+
+export const CONFIG_ENTRIES = ["prefs.json", "config.json", "private/infra-providers.json"];
+export const ALL_ENTRIES = [...CONFIG_ENTRIES, "auth-devices.json", "mcp.json", "cli.device.id", "memory.json",
+ "agent-memory", "agent-sessions", "agent-session-archive", "project-agent-tasks", "threads", "skill-memory.json",
+ "audit.log", "temp-shares", "private/cli", "private/gateway", "private/update-state", "private/a2a-inbound-tokens.json",
+ "private/a2a-credentials.json", "private/a2a-local-auth.json", "private/a2a-agents.json", "private/a2a-tasks.json",
+ "private/local-agent-messages.json", "private/local-agent-presence.json"];
+const STORE_OVERRIDES = /^(?:OS_.*(?:STORE|DIR|PATH|LOG)|MSO_(?:PRIVATE_STATE_DIR|DEVICE_FILE|JAR|UPDATE_STATE_DIR|GATEWAY_STATE_DIR))$/;
+export function parseMaintenanceArgs(args) {
+ const options = { action: args[0], scope: "config", purge: false, removeCode: false, apply: false, json: false, confirm: "", service: "mso.service" };
+ if (!["reset", "uninstall"].includes(options.action)) throw new Error("Expected reset or uninstall");
+ const seen = new Set();
+ for (let i = 1; i < args.length; i++) {
+ const arg = args[i];
+ if (seen.has(arg)) throw new Error(`Repeated option: ${arg}`); seen.add(arg);
+ if (["--help", "-h"].includes(arg)) { options.help = true; continue; }
+ if (["--apply", "--json", "--purge", "--remove-code"].includes(arg)) {
+ options[{ "--apply": "apply", "--json": "json", "--purge": "purge", "--remove-code": "removeCode" }[arg]] = true; continue;
+ }
+ if (["--scope", "--confirm", "--service"].includes(arg) && args[i + 1] && !args[i + 1].startsWith("--")) {
+ options[arg.slice(2)] = args[++i]; continue;
+ }
+ throw new Error(`Unknown or incomplete option: ${arg}`);
+ }
+ if (!["config", "all"].includes(options.scope)) throw new Error("Scope must be config or all");
+ if (!/^[a-zA-Z0-9][a-zA-Z0-9_.@-]{0,100}\.service$/.test(options.service)) throw new Error("Invalid systemd service name");
+ if (options.action === "reset" && (options.purge || options.removeCode)) throw new Error("Purge/remove-code are uninstall-only");
+ if (options.action === "uninstall" && seen.has("--scope")) throw new Error("Uninstall uses --purge, not --scope");
+ return options;
+}
+export function maintenancePlan(context, options) {
+ const { home, repo } = context;
+ if (!path.isAbsolute(home) || fs.realpathSync(home) !== home || home === path.parse(home).root || fs.statSync(home).uid !== process.getuid()) throw new Error("Invalid canonical home");
+ if (!inside(home, repo) || fs.realpathSync(repo) !== repo) throw new Error("Installation must be a real directory beneath home");
+ if (JSON.parse(fs.readFileSync(path.join(repo, "package.json"), "utf8")).name !== "mso"
+ || !statOrNull(path.join(repo, "bin/mso")) || !statOrNull(path.join(repo, "scripts/install-core.sh"))) throw new Error("Not an MSO installation");
+ const targets = [], retained = [], blockers = [];
+ const add = (root, target, kind = "state", config) => {
+ try { const entry = snapshot(root, target, config); if (entry) targets.push({ ...entry, category: kind }); }
+ catch (error) { blockers.push(error.message); }
+ };
+ const state = path.join(home, ".mso");
+ const selected = options.action === "reset" ? options.scope === "all" ? ALL_ENTRIES : CONFIG_ENTRIES : options.purge ? [...ALL_ENTRIES, "maintenance-backups"] : [];
+ for (const relative of selected) add(home, path.join(state, relative));
+ const all = options.scope === "all" && options.action === "reset" || options.purge;
+ if (all) add(home, path.join(repo, ".env.local"));
+ // Custom stores are never guessed, traversed, or silently advertised as reset.
+ const envFile = path.join(repo, ".env.local"), envStat = statOrNull(envFile);
+ if (envStat?.isSymbolicLink()) blockers.push("Local configuration is a symlink; review it manually");
+ if (selected.length && envStat?.isFile()) {
+ if (envStat.size > 1024 * 1024) blockers.push("Local configuration is unexpectedly large");
+ else for (const line of fs.readFileSync(envFile, "utf8").split(/\r?\n/)) {
+ const match = /^\s*(?:export\s+)?([A-Z][A-Z0-9_]*)\s*=\s*(.*)$/.exec(line);
+ if (match && STORE_OVERRIDES.test(match[1]) && match[2].trim() && !/^(?:""|'')$/.test(match[2].trim())) blockers.push(`Custom storage override ${match[1]} requires manual reconciliation`);
+ }
+ }
+ for (const [key, value] of Object.entries(context.env ?? {})) if (value && STORE_OVERRIDES.test(key) && selected.length) blockers.push(`Inherited storage override ${key} requires manual reconciliation`);
+ if (statOrNull(state)?.isDirectory() && !statOrNull(state)?.isSymbolicLink()) {
+ const selectedRoots = new Set(selected.map((name) => name.split("/")[0]));
+ for (const name of fs.readdirSync(state)) if (!selectedRoots.has(name)) retained.push({ path: path.join(state, name), reason: "Outside the selected reset scope" });
+ retained.push({ path: path.join(state, "private"), reason: "Unrecognized private entries are preserved" });
+ }
+ if (options.action === "uninstall") {
+ for (const dir of [path.join(home, ".local/bin"), context.systemBinDir ?? "/usr/local/bin"]) {
+ try { const link = ownedLink(dir, path.join(dir, "mso"), repo); if (link) targets.push({ ...link, category: "launcher" }); }
+ catch (error) { blockers.push(error.message); }
+ }
+ const skills = path.join(home, ".claude/skills");
+ if (statOrNull(skills)?.isDirectory() && !statOrNull(skills)?.isSymbolicLink()) for (const name of fs.readdirSync(skills)) {
+ try { const link = ownedLink(home, path.join(skills, name), path.join(repo, "claude-skills")); if (link) targets.push({ ...link, category: "skill-link" }); }
+ catch (error) { blockers.push(error.message); }
+ }
+ }
+ if (options.removeCode) {
+ if (!statOrNull(path.join(repo, ".git"))?.isDirectory()) blockers.push("Code removal requires a standalone Git clone, not a linked worktree");
+ const git = (args) => spawnSync("git", ["-C", repo, ...args], { encoding: "utf8", timeout: 10000, maxBuffer: 1024 * 1024 });
+ const dirty = git(["status", "--porcelain", "--untracked-files=all"]), trees = git(["worktree", "list", "--porcelain"]);
+ if (dirty.status !== 0 || dirty.stdout.trim()) blockers.push("Code removal refuses a dirty/unverified checkout");
+ if (trees.status !== 0 || (trees.stdout.match(/^worktree /gm) ?? []).length !== 1) blockers.push("Code removal refuses shared linked worktrees");
+ const ignored = git(["ls-files", "--others", "--ignored", "--exclude-standard", "--directory"]);
+ if (ignored.status !== 0 || ignored.stdout.split("\n").filter(Boolean).some((name) => !/^(?:node_modules\/|\.next\/|coverage\/|\.env\.local$|tsconfig\.tsbuildinfo$)/.test(name))) blockers.push("Unrecognized ignored files must be preserved before code removal");
+ if (!options.purge) blockers.push("--remove-code also requires --purge because the checkout may contain local configuration");
+ add(home, repo, "code");
+ } else retained.push({ path: repo, reason: "Source code retained; --remove-code is explicit" });
+ retained.push({ path: "Other projects, shared runtimes, external providers, DNS/TLS and browser profiles", reason: "Never owned by this uninstall" });
+ return { version: 1, action: options.action, scope: options.scope, purge: options.purge, removeCode: options.removeCode,
+ service: options.service, repo, home, targets, retained, blockers: [...new Set(blockers)] };
+}
+export function confirmationFor(plan) {
+ return `${plan.action.toUpperCase()}:${createHash("sha256").update(JSON.stringify(plan)).digest("hex").slice(0, 16)}`;
+}
diff --git a/scripts/maintenance-lock.sh b/scripts/maintenance-lock.sh
new file mode 100644
index 00000000..3da59d4c
--- /dev/null
+++ b/scripts/maintenance-lock.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Only the local maintenance entrypoint calls this after validating its preview token.
+set -euo pipefail
+ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+# shellcheck source=lib/private-state.sh
+source "$ROOT/scripts/lib/private-state.sh"
+# shellcheck source=lib/runtime-exclusion.sh
+source "$ROOT/scripts/lib/runtime-exclusion.sh"
+runtime_exclusion_acquire exclusive 0 || { echo 'mso maintenance: runtime/update lock is busy; no maintenance applied' >&2; exit 1; }
+trap runtime_exclusion_release EXIT
+MSO_MAINTENANCE_LOCKED=1 node "$ROOT/scripts/mso-maintenance.mjs" "$@"
diff --git a/scripts/maintenance.test.ts b/scripts/maintenance.test.ts
new file mode 100644
index 00000000..fdec8b0c
--- /dev/null
+++ b/scripts/maintenance.test.ts
@@ -0,0 +1,153 @@
+import fs from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import { spawnSync } from "node:child_process";
+import { afterEach, describe, expect, it } from "vitest";
+import { parseMaintenanceArgs } from "./lib/maintenance-plan.mjs";
+import { prepareMaintenance, applyMaintenance } from "./lib/maintenance-apply.mjs";
+import { inside } from "./lib/maintenance-paths.mjs";
+
+const fixtures: string[] = [];
+afterEach(() => { for (const dir of fixtures.splice(0)) fs.rmSync(dir, { recursive: true, force: true }); });
+function fixture() {
+ const home = fs.mkdtempSync(path.join(os.tmpdir(), "mso-maintenance-test-")); fixtures.push(home);
+ const repo = path.join(home, "mso");
+ const put = (name: string, text = "fixture") => {
+ const target = path.join(home, name); fs.mkdirSync(path.dirname(target), { recursive: true, mode: 0o700 });
+ fs.writeFileSync(target, text, { mode: 0o600 }); return target;
+ };
+ put("mso/package.json", '{"name":"mso"}'); put("mso/bin/mso"); put("mso/scripts/install-core.sh");
+ const context = { home, repo, env: {}, systemUnitDir: path.join(home, "units"), systemBinDir: path.join(home, "bin") };
+ const plan = (...args: string[]) => {
+ const options = parseMaintenanceArgs(args); return { options, value: prepareMaintenance(context, options) };
+ };
+ const apply = (...args: string[]) => {
+ const { options, value } = plan(...args);
+ return applyMaintenance(context, { ...options, apply: true, confirm: value.confirmation }, value, { assertOffline: () => undefined });
+ };
+ return { home, repo, context, put, plan, apply };
+}
+
+describe("maintenance preview and argument boundary", () => {
+ it("does not create state, locks or backups during preview", () => {
+ const f = fixture(), { options, value } = f.plan("reset");
+ expect(applyMaintenance(f.context, options, value).applied).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".mso"))).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".mso-maintenance.lock"))).toBe(false);
+ });
+ it.each([["reset", "--yes"], ["reset", "--scope", "everything"], ["reset", "--scope"], ["reset", "--purge"], ["uninstall", "--scope", "all"], ["uninstall", "--service", "../x"], ["reset", "--json", "--json"]])("refuses invalid option set %j", (...args) => {
+ expect(() => parseMaintenanceArgs(args)).toThrow();
+ });
+ it("requires the current preview token", () => {
+ const f = fixture(); f.put(".mso/prefs.json"); const { options, value } = f.plan("reset");
+ expect(() => applyMaintenance(f.context, { ...options, apply: true, confirm: "wrong" }, value)).toThrow(/confirm/);
+ expect(fs.existsSync(path.join(f.home, ".mso/prefs.json"))).toBe(true);
+ });
+ it("refuses a target replaced after preview", () => {
+ const f = fixture(), file = f.put(".mso/prefs.json"); const { options, value } = f.plan("reset");
+ fs.renameSync(file, file + ".old"); fs.writeFileSync(file, "replacement", { mode: 0o600 });
+ expect(() => applyMaintenance(f.context, { ...options, apply: true, confirm: value.confirmation }, value, { assertOffline: () => undefined })).toThrow(/changed since preview/);
+ });
+ it("refuses active-runtime application before changing any data", () => {
+ const f = fixture(), file = f.put(".mso/prefs.json"); const { options, value } = f.plan("reset");
+ expect(() => applyMaintenance(f.context, { ...options, apply: true, confirm: value.confirmation }, value, { assertOffline: () => { throw new Error("runtime active"); } })).toThrow(/runtime active/);
+ expect(fs.readFileSync(file, "utf8")).toBe("fixture");
+ });
+ it("rejects remote targeting and avoids sourcing an env file", () => {
+ const f = fixture(); const marker = path.join(f.home, "sourced"); f.put("danger.env", `touch '${marker}'\n`);
+ const run = spawnSync("bash", [path.join(process.cwd(), "bin/mso"), "--env", path.join(f.home, "danger.env"), "reset", "--help"], { encoding: "utf8", env: { ...process.env, HOME: f.home } });
+ expect(run.status).not.toBe(0); expect(run.stderr).toContain("local-only"); expect(fs.existsSync(marker)).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".mso"))).toBe(false);
+ });
+});
+
+describe("maintenance ownership and preservation", () => {
+ it("rejects a symlinked state directory", () => {
+ const f = fixture(); fs.symlinkSync(f.repo, path.join(f.home, ".mso"));
+ expect(f.plan("reset").value.blockers.join(" ")).toMatch(/Unsafe parent/);
+ });
+ it("rejects a symlinked configuration target", () => {
+ const f = fixture(); const external = f.put("other/data"); f.put(".mso/keep");
+ fs.symlinkSync(external, path.join(f.home, ".mso/config.json"));
+ expect(f.plan("reset").value.blockers.join(" ")).toMatch(/symlink/);
+ });
+ it("rejects a symlinked launcher parent without touching its destination", () => {
+ const f = fixture(); f.put("elsewhere/keep"); fs.mkdirSync(path.join(f.home, ".local"), { mode: 0o700 });
+ fs.symlinkSync(path.join(f.home, "elsewhere"), path.join(f.home, ".local/bin"));
+ fs.symlinkSync(path.join(f.repo, "bin/mso"), path.join(f.home, "elsewhere/mso"));
+ expect(f.plan("uninstall").value.blockers.join(" ")).toMatch(/Unsafe ownership root/);
+ });
+ it("blocks custom paths without returning secret values", () => {
+ const f = fixture(); f.put("mso/.env.local", "OS_CONFIG_STORE=/outside/private-location\nOS_LOGIN_PASSWORD=do-not-print\n");
+ const p = f.plan("reset", "--scope", "all").value;
+ expect(p.blockers.join(" ")).toContain("OS_CONFIG_STORE");
+ expect(JSON.stringify(p)).not.toContain("do-not-print"); expect(JSON.stringify(p)).not.toContain("private-location");
+ });
+ it("archives config privately while preserving authentication and install configuration", () => {
+ const f = fixture(); f.put(".mso/config.json", "model-config"); f.put(".mso/prefs.json"); f.put(".mso/auth-devices.json"); f.put("mso/.env.local", "# fixture\n");
+ const result = f.apply("reset"); expect(result.applied).toBe(true);
+ expect(fs.existsSync(path.join(f.home, ".mso/config.json"))).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".mso/auth-devices.json"))).toBe(true);
+ expect(fs.existsSync(path.join(f.repo, ".env.local"))).toBe(true);
+ const backup = result.backup!; expect(fs.statSync(backup).mode & 0o777).toBe(0o700);
+ expect(fs.readFileSync(path.join(backup, "files/.mso/config.json"), "utf8")).toBe("model-config");
+ expect(fs.statSync(path.join(backup, "manifest.json")).mode & 0o777).toBe(0o600);
+ });
+ it("full reset archives identity/history but preserves unknown projects and browser profiles", () => {
+ const f = fixture(); f.put(".mso/auth-devices.json"); f.put(".mso/threads/one.yaml"); f.put("mso/.env.local", "# fixture\n");
+ const saved = f.put(".mso/worktrees/private-project/keep"); const browser = f.put(".local/share/camoufox/keep");
+ const result = f.apply("reset", "--scope", "all"); expect(result.applied).toBe(true);
+ expect(fs.existsSync(path.join(f.repo, ".env.local"))).toBe(false);
+ expect(fs.existsSync(saved)).toBe(true); expect(fs.existsSync(browser)).toBe(true);
+ });
+ it("normal uninstall only removes links pointing into this installation", () => {
+ const f = fixture(); f.put(".mso/config.json"); f.put(".local/bin/other");
+ fs.symlinkSync(path.join(f.repo, "bin/mso"), path.join(f.home, ".local/bin/mso"));
+ f.put(".claude/skills/other/SKILL.md"); fs.symlinkSync(path.join(f.repo, "claude-skills/mso"), path.join(f.home, ".claude/skills/mso"));
+ f.apply("uninstall"); expect(fs.existsSync(path.join(f.home, ".local/bin/mso"))).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".local/bin/other"))).toBe(true);
+ expect(fs.existsSync(path.join(f.home, ".mso/config.json"))).toBe(true);
+ expect(fs.existsSync(f.repo)).toBe(true);
+ });
+ it("purge deletes known state and reset archives, not unknown worktrees", () => {
+ const f = fixture(); f.put(".mso/config.json"); f.put(".mso/maintenance-backups/test/data"); const kept = f.put(".mso/worktrees/keep");
+ f.apply("uninstall", "--purge"); expect(fs.existsSync(path.join(f.home, ".mso/config.json"))).toBe(false);
+ expect(fs.existsSync(path.join(f.home, ".mso/maintenance-backups"))).toBe(false); expect(fs.existsSync(kept)).toBe(true);
+ });
+ it("refuses removing code from a linked or unverified checkout", () => {
+ const f = fixture(); f.put("mso/.git", "gitdir: elsewhere");
+ expect(f.plan("uninstall", "--purge", "--remove-code").value.blockers.join(" ")).toMatch(/standalone|unverified/);
+ });
+ it("requires explicit purge when removing source code", () => {
+ const f = fixture(); expect(f.plan("uninstall", "--remove-code").value.blockers.join(" ")).toContain("--purge");
+ });
+ it("does not confuse sibling prefix paths with descendants", () => {
+ expect(inside("/home/owner/mso", "/home/owner/mso-backup")).toBe(false);
+ expect(inside("/home/owner/mso", "/home/owner/mso")).toBe(false);
+ });
+ it("removes a clean standalone clone only with explicit purge and code options", () => {
+ const f = fixture(); f.put("mso/.gitignore", ".env.local\nnode_modules/\n");
+ const git = (...args: string[]) => {
+ const result = spawnSync("git", args, { cwd: f.repo, encoding: "utf8" });
+ expect(result.status, result.stderr).toBe(0);
+ };
+ git("init", "-q"); git("add", ".");
+ git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "fixture");
+ f.put("mso/.env.local", "# synthetic config\n"); f.put(".mso/config.json");
+ const kept = f.put("other-project/keep");
+ const preview = f.plan("uninstall", "--purge", "--remove-code");
+ expect(preview.value.blockers).toEqual([]);
+ f.apply("uninstall", "--purge", "--remove-code");
+ expect(fs.existsSync(f.repo)).toBe(false); expect(fs.existsSync(kept)).toBe(true);
+ });
+ it("keeps state when verified service removal fails", () => {
+ const f = fixture(); const state = f.put(".mso/config.json");
+ f.put("units/mso.service", `[Service]\nWorkingDirectory=${f.repo}\n`);
+ const { options, value } = f.plan("uninstall", "--purge");
+ expect(() => applyMaintenance(f.context, { ...options, apply: true, confirm: value.confirmation }, value, {
+ assertOffline: () => undefined, systemAction: () => { throw new Error("service operation refused"); },
+ })).toThrow(/service operation refused/);
+ expect(fs.existsSync(state)).toBe(true);
+ });
+
+});
diff --git a/scripts/mso-maintenance.mjs b/scripts/mso-maintenance.mjs
new file mode 100644
index 00000000..2aaccc53
--- /dev/null
+++ b/scripts/mso-maintenance.mjs
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+// Deliberately local CLI, not an HTTP/MCP destructive endpoint.
+import os from "node:os";
+import { spawnSync } from "node:child_process";
+import path from "node:path";
+import { fileURLToPath } from "node:url";
+import { parseMaintenanceArgs } from "./lib/maintenance-plan.mjs";
+import { prepareMaintenance, applyMaintenance, assertOffline } from "./lib/maintenance-apply.mjs";
+
+const HELP = `MSO maintenance — local installation only
+
+ mso reset [--scope config|all] [--json]
+ mso uninstall [--purge] [--remove-code] [--service name.service] [--json]
+
+Every command is PREVIEW ONLY unless --apply and --confirm <preview-token> are both present.
+
+ reset Archive managed preferences + model/infrastructure configuration.
+ reset --scope all Also archive MSO identities, sessions, history, memory and .env.local.
+ uninstall Remove only this installation's service registrations and CLI/skill links.
+ --purge Permanently delete known MSO state and reset backups; no recovery copy.
+ --remove-code Also remove a clean standalone clone; requires --purge.
+
+Stop MSO and its fallback/gateway runtimes from an independent SSH terminal first.
+Apply refuses active/unknown runtimes, unsafe paths, custom storage overrides, and stale tokens.
+Unknown files, worktrees, other projects, external apps, shared Node/Bun, DNS/TLS and browser
+profiles are never erased. Review retained paths; manual external cleanup can still be needed.
+See docs/MAINTENANCE.md for scope, recovery, and full uninstall instructions.
+`;
+try {
+ const options = parseMaintenanceArgs(process.argv.slice(2));
+ if (options.help) { process.stdout.write(HELP); process.exit(0); }
+ const context = { home: os.homedir(), repo: path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), env: process.env };
+ const plan = prepareMaintenance(context, options);
+ if (options.apply && process.env.MSO_MAINTENANCE_LOCKED !== "1") {
+ if (plan.blockers.length || options.confirm !== plan.confirmation) throw new Error("Resolve preview blockers and supply the exact current confirmation token first");
+ assertOffline(plan);
+ const child = spawnSync("bash", [path.join(context.repo, "scripts/maintenance-lock.sh"), ...process.argv.slice(2)], { stdio: "inherit" });
+ process.exit(child.status ?? 1);
+ }
+ const result = applyMaintenance(context, options, plan);
+ if (!result.applied && plan.blockers.length) process.exitCode = 2;
+ if (options.json) console.log(JSON.stringify(result, null, 2));
+ else if (!result.applied) {
+ console.log(`MSO ${plan.action} · PREVIEW ONLY\nInstallation: ${plan.repo}\nScope: ${plan.action === "reset" ? plan.scope : plan.purge ? "uninstall + purge" : "uninstall, keep data"}\n`);
+ for (const entry of plan.targets) console.log(` ${plan.action === "reset" ? "ARCHIVE" : "REMOVE "} ${entry.path}`);
+ if (!plan.targets.length) console.log(" No matching owned targets.");
+ console.log("\nRetained:"); for (const entry of plan.retained) console.log(` KEEP ${entry.path}`);
+ if (plan.blockers.length) { console.log("\nBlocked:"); for (const reason of plan.blockers) console.log(` ${reason}`); }
+ else console.log(`\nAfter stopping the runtime, repeat the same options with:\n --apply --confirm ${plan.confirmation}`);
+ console.log("\nNo files, credentials, services or processes were changed.");
+ if (plan.blockers.length) process.exitCode = 2;
+ } else {
+ console.log(`MSO ${plan.action}: completed ${result.completed.length} owned changes.`);
+ if (result.backup) console.log(`Private recovery archive: ${result.backup}`);
+ console.log("Review retained paths before calling the host fully cleaned.");
+ }
+} catch (error) { console.error(`mso maintenance: ${error.message}`); process.exitCode = 1; }
diff --git a/scripts/test-features.mjs b/scripts/test-features.mjs
index 4b870b5d..75cbed61 100644
--- a/scripts/test-features.mjs
+++ b/scripts/test-features.mjs
@@ -54,7 +54,7 @@ for (const [name, files] of [...groups].sort(([a], [b]) => a.localeCompare(b)))
const configFile = join(outputDir, `${basename}.config.mts`);
// CLI filters match substrings, even with absolute paths. Override include
// instead, then independently verify the exact result-file inventory below.
- const exactIncludes = files.map((file) => file.replace(/[?*{}\[\]]/g, "\\$&"));
+ const exactIncludes = files.map((file) => file.replace(/[\\?*{}\[\]]/g, "\\$&"));
writeFileSync(configFile,
`import base from ${JSON.stringify(join(root, "vitest.config.mts"))};\nexport default {...base, test: {...base.test, include: ${JSON.stringify(exactIncludes)}}};\n`,
{ mode: 0o600 });