Skip to content

armgit / mso

Public Imported from GitHub
0

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

refactor(gateway): make lifecycle provider agnostic

Rahman592f365049eb
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 712bb464..d9ebb127 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -54,6 +54,10 @@ under `~/.mso/` plus the independent state directories owned by managed applicat
Window layout and several shell preferences are browser-local or synchronized through the
existing preference store.
+### Gateway lifecycle boundary
+
+**MSO Gateway is deployment-agnostic, supervisor-agnostic, and provider-agnostic by design.** The core classifies local/public/provider/process health plus ownership and supervisor independently; provider-specific launch details remain adapters. A verified public route with no MSO-owned provider process is `external-running`, not `stopped`, and external processes are never auto-adopted or mutated. Cloudflare remains the current managed/default adapter rather than a core architecture assumption. See [`docs/GATEWAY.md`](./GATEWAY.md) for state semantics, provider capabilities, systemd/s6/container/Kubernetes examples and the foreground-supervision decision.
+
## 2. Repository layout
```text
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 40c1214d..8b3d3470 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -15,6 +15,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
- `installer` build node-pty reliably on Codespaces
- `managed-apps` support Hermes without systemd
+**Changed**
+
+- `gateway` make lifecycle provider agnostic
+
**Docs**
- `comparison` refresh product audit
diff --git a/docs/GATEWAY.md b/docs/GATEWAY.md
new file mode 100644
index 00000000..74d2cde6
--- /dev/null
+++ b/docs/GATEWAY.md
@@ -0,0 +1,333 @@
+# MSO Gateway architecture and operations
+
+> **MSO Gateway is deployment-agnostic, supervisor-agnostic, and provider-agnostic by design.**
+
+The gateway core describes health, identity, ownership and lifecycle state. Cloudflare, Tailscale,
+ngrok, a reverse proxy, direct HTTPS, systemd, s6, Docker, Kubernetes and similar technologies are
+provider/supervisor/deployment choices rather than assumptions in the core state machine.
+
+## Architecture boundary
+
+```text
+MSO Gateway Core
+ ↓
+Provider Adapter
+ ↓
+Process Supervisor / Runtime
+ ↓
+Deployment Environment
+```
+
+The current managed public adapter is Cloudflare. It remains the default for `mso gateway start`
+and keeps the existing Quick Tunnel and named-tunnel safety contract, but Cloudflare-specific binary,
+config and launch details stay behind the provider boundary.
+
+Conceptually the core can support:
+
+```text
+ ┌─ Cloudflare Tunnel
+ ├─ Tailscale
+Gateway Core ─────├─ ngrok
+ ├─ reverse proxy
+ ├─ direct HTTPS gateway
+ └─ future provider
+```
+
+and the lifecycle can be hosted by:
+
+```text
+ ┌─ systemd
+ ├─ s6
+Gateway lifecycle ───────├─ Docker / Compose
+ ├─ Kubernetes
+ ├─ external supervisor
+ └─ foreground/manual
+```
+
+Adding another managed provider should implement the provider adapter/capability contract rather than
+add provider-name branches throughout the core.
+
+## State model
+
+`mso gateway status --json` exposes the provider-neutral state model. Human status preserves the legacy
+`gateway: running` line for healthy running states and adds the precise state/dimensions.
+
+| State | Meaning |
+|---|---|
+| `managed-running` | MSO proves ownership of its provider process and local/public identities match. |
+| `external-running` | No MSO-owned provider process exists, but the configured public origin returns the exact selected local MSO identity. |
+| `degraded` | A provider/public route exists or is recorded, but local/public/provider health is not fully healthy. |
+| `recovering` | MSO has durable managed lifecycle evidence but the recorded provider process is stale/missing and needs safe reconciliation. |
+| `stopped` | No owned provider is active and no verified external public route is responding. |
+| `unknown` | State is unsafe/corrupt or cannot be classified safely. |
+
+The dimensions are independent:
+
+```text
+localHealth
+publicHealth
+providerHealth
+processHealth
+ownership
+supervisor
+```
+
+Example managed state:
+
+```json
+{
+ "state": "managed-running",
+ "ownership": "mso",
+ "provider": "cloudflare",
+ "supervisor": "mso-lifecycle",
+ "localHealth": "healthy",
+ "publicHealth": "healthy",
+ "providerHealth": "healthy",
+ "processHealth": "alive"
+}
+```
+
+Example external state:
+
+```json
+{
+ "state": "external-running",
+ "ownership": "external",
+ "provider": "custom",
+ "supervisor": "external",
+ "localHealth": "healthy",
+ "publicHealth": "healthy",
+ "processHealth": "external"
+}
+```
+
+`provider` is dynamic. `custom` means the public route is verified but MSO does not have enough safe
+evidence to name the provider. MSO does not guess provider ownership from a hostname or process name.
+
+## Public health and deployment identity
+
+Process existence is not public readiness. MSO probes the configured public origin at:
+
+```text
+https://<public-origin>/api/health
+```
+
+It validates the MSO health contract and compares the public health identity with the selected local
+runtime. Identity includes `version`, `buildId`, optional `buildSha`, and `runtimeInstanceId`.
+
+Therefore:
+
+```text
+local healthy
+public HTTP healthy
+public identity != local identity
+```
+
+is an `identity-mismatch` and produces a degraded state, not a healthy gateway. This catches a valid
+hostname that is routing to a different MSO deployment.
+
+Status and doctor are observational. A failed probe does not itself restart a provider. Existing managed
+reconciliation remains bounded by proven MSO ownership; external gateways are report-only. This avoids
+turning transient edge/DNS failures into restart storms.
+
+## Provider adapter capabilities
+
+The gateway provider boundary reports capabilities instead of making the core branch on provider names.
+The current capability vocabulary includes:
+
+```text
+publicHealthProbe
+managedProcess
+namedEndpoint
+externalDetection
+restart
+reconnect
+credentialsRequired
+dnsRouting
+```
+
+Cloudflare currently reports managed-process/restart/reconnect support. A generic external/custom route
+reports public-health/external-detection capability but no managed-process/restart authority.
+
+The managed adapter contract is intentionally small: parse/validate start intent, start/reconcile through
+its provider implementation, inspect health/state through the generic core, and expose capabilities.
+This is additive to the existing shell architecture; it is not a new heavyweight plugin framework.
+
+## Managed versus external gateway
+
+### Managed gateway
+
+MSO records and verifies process identity before mutation. Existing protections remain authoritative:
+
+- PID plus kernel process start ticks;
+- executable identity;
+- command-line identity where stable;
+- runtime instance identity for Next;
+- owner-private atomic lifecycle state;
+- held-child launch handshake;
+- checkout/update locks and recovery markers.
+
+`mso gateway stop` terminates only identities proven to be owned by MSO.
+
+### External/unmanaged gateway
+
+When no MSO-owned provider exists but `OS_PUBLIC_ORIGIN` returns the exact local MSO health identity,
+status reports `external-running` and `ownership: external`.
+
+For external processes MSO may:
+
+```text
+detect yes
+inspect yes
+health check yes
+stop no
+restart no
+auto-adopt no
+```
+
+`mso gateway stop` never searches for and kills external tunnel/reverse-proxy processes. There is no
+automatic adoption mechanism. Any future adoption feature must be an explicit, separately verified action.
+
+An implicit `mso gateway start` refuses to create a duplicate connector when a verified external route is
+already present. An explicit named-provider start remains an operator-directed action and retains its
+existing provider validation contract.
+
+## `mso gateway status`
+
+Human-readable status includes the precise state plus provider/ownership/supervisor and health dimensions:
+
+```text
+gateway: running
+state: external-running
+provider: custom
+ownership: external
+supervisor: external
+process-health: external
+local-health: healthy
+public-health: healthy
+provider-health: healthy
+public: https://mso.example.com
+local: http://127.0.0.1:4005
+```
+
+Use structured output for automation:
+
+```bash
+mso gateway status --json
+```
+
+Exit status is `0` for `managed-running` / `external-running`, `1` for `stopped`, and `2` for degraded,
+recovering or other non-healthy classified states.
+
+## `mso gateway doctor`
+
+Doctor is read-only. It checks independent dimensions rather than treating Cloudflare availability as the
+gateway definition:
+
+- selected local MSO health identity;
+- raw application binding/exposure safety;
+- configured stable public origin;
+- public health contract and identity match;
+- lifecycle state and ownership;
+- process/provider health classification;
+- supervisor context;
+- provider-specific diagnostics only when relevant.
+
+The Cloudflare adapter diagnostic never downloads or installs a binary during doctor. Managed installation
+remains an explicit `mso gateway install` or managed-start concern.
+
+A public route may be healthy while doctor separately reports an unsafe local bind. For example, a working
+reverse proxy does not make `0.0.0.0:4005` safe; the application should normally remain loopback-only.
+
+## Supervisor and deployment model
+
+The core does not require systemd. Application lifecycle, gateway lifecycle, provider lifecycle and host
+lifecycle are separate.
+
+### Normal VPS / bare metal
+
+```text
+systemd (or another host supervisor)
+ → MSO runtime on loopback
+chosen gateway provider / reverse proxy
+ → public HTTPS origin
+```
+
+The standard installer may use systemd when it is actually available, but the gateway state machine does
+not derive health/ownership from systemd.
+
+### Container / Docker Compose
+
+```text
+container lifecycle
+ → MSO foreground runtime on loopback/container-private interface
+external or sidecar gateway/reverse proxy
+ → public origin
+```
+
+Use the container restart policy/orchestrator as the supervisor. MSO can inspect a configured external
+public route without claiming its process.
+
+### s6 / external supervisor
+
+```text
+s6
+ → MSO runtime
+ → selected gateway/reverse-proxy lifecycle
+```
+
+The supervisor owns its processes; MSO reports `external-running` when the public identity is valid.
+
+### Kubernetes
+
+```text
+Pod/container lifecycle
+ → MSO runtime
+Service/Ingress/Gateway implementation
+ → configured public origin
+```
+
+Kubernetes owns restart/reconciliation. MSO observes the public identity and does not attempt to kill or
+adopt ingress/controller processes.
+
+### WSL / sandbox / remote development
+
+`mso web` continues to support the already-built loopback fallback without requiring systemd. The managed
+Cloudflare adapter remains available where its binary/process contract is supported, while an externally
+provided route is classified independently.
+
+## Why there is no new `mso gateway supervise` command yet
+
+This refactor does not add a second process-supervision implementation merely for abstraction. Existing
+MSO-managed Cloudflare lifecycle stays intact, and systemd/s6/container/Kubernetes/reverse-proxy deployments
+are represented safely as externally supervised routes. That is enough to make core health/state portable
+without duplicating supervisor semantics.
+
+A future foreground `gateway supervise` should be added only when a managed provider needs one common
+signal-aware foreground contract across supervisors. If added, it must use the same provider adapter,
+ownership proof, deterministic exit codes and structured health model; it must not daemonize or assume a
+specific init system.
+
+## Operational examples
+
+Cloudflare remains the current managed/default provider:
+
+```bash
+mso gateway start
+mso gateway status
+mso gateway status --json
+mso gateway doctor
+mso gateway stop
+```
+
+For a named Cloudflare endpoint:
+
+```bash
+mso gateway domain set https://mso.example.com
+mso gateway start --config ~/.cloudflared/config.yml --tunnel <name-or-uuid>
+```
+
+For Tailscale, nginx/Caddy/Traefik, Kubernetes Ingress/Gateway, PaaS routing or another external provider,
+keep MSO on its private/loopback binding where topology permits, set the stable `OS_PUBLIC_ORIGIN`, and let
+the external supervisor/provider own its process lifecycle. `mso gateway status --json` will report the
+route as external only after the public identity matches the selected local MSO runtime.
diff --git a/docs/INSTALL.md b/docs/INSTALL.md
index cdef4527..260b120b 100644
--- a/docs/INSTALL.md
+++ b/docs/INSTALL.md
@@ -218,6 +218,8 @@ failed phase. Re-running the same one-liner is the supported recovery path.
## 2. Network exposure
+Gateway architecture, provider capabilities, external ownership, state semantics and non-systemd/container/Kubernetes examples are documented in [`GATEWAY.md`](./GATEWAY.md).
+
The installer binds `127.0.0.1` by default. This is intentional: an authenticated MSO Owner
session can execute host commands, and delegated roles still expose private server data.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 7445cb7c..3a9c5849 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,7 @@
+## 2026-09-17 — Gateway core becomes deployment/provider/supervisor agnostic
+
+Refactored the gateway reliability boundary without removing the existing Cloudflare lifecycle or process-ownership protections. The new read-only classifier separates local, public, provider and process health from ownership/supervisor state and reports `managed-running`, `external-running`, `degraded`, `recovering`, `stopped` or `unknown`. A configured public origin is healthy only when its structured MSO health identity matches the selected local runtime, including `buildSha` when present; this fixes the real case where a healthy externally supervised public route was previously displayed as stopped. Added `mso gateway status --json`, capability-based provider metadata, external duplicate-start protection, and provider-neutral non-mutating doctor diagnostics. Cloudflare remains the current managed/default adapter; external reverse proxies/tunnels are detected but never adopted, stopped or restarted. Existing PID/start-ticks/executable/argv/runtime-instance, atomic private state, update locks and recovery markers remain authoritative. No generic `gateway supervise` daemon was added because the current external-supervisor model already covers systemd/s6/container/Kubernetes/PaaS ownership without duplicating supervisor semantics. Added provider-neutral regression coverage and a dedicated `docs/GATEWAY.md` architecture/operations reference.
+
## 2026-09-17 — GitHub reference audit and optional app-binding compatibility
diff --git a/docs/README.md b/docs/README.md
index f2871f70..e79565d6 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -21,6 +21,7 @@ evidence and review freshness. The repository quality gate runs both automatical
|---|---|
| [`../README.md`](../README.md) | Product overview and quickstart |
| [`ARCHITECTURE.md`](./ARCHITECTURE.md) | Current runtime, shell, role, host, Agent/Local Agent/subagent, MCP and deployment architecture |
+| [`GATEWAY.md`](./GATEWAY.md) | Provider-neutral gateway state, health, ownership, supervisor and deployment contract |
| [`COGNITIVE-RUNTIME.md`](./COGNITIVE-RUNTIME.md) | Provider-neutral MCP/session/context/tool-routing runtime and benchmark contract |
| [`RASMIC.md`](./RASMIC.md) | Risk-aware orchestration, repo-local memory/evidence, collision detection and recipe/script promotion |
| [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes |
diff --git a/docs/TROUBLESHOOTING.md b/docs/TROUBLESHOOTING.md
index c9441625..c110f0b1 100644
--- a/docs/TROUBLESHOOTING.md
+++ b/docs/TROUBLESHOOTING.md
@@ -109,6 +109,18 @@ Next from a partially-mutated build. Let the update finish, then rerun the same
`mso deploy` uses the same runtime-quiesce lifecycle and requires the active service to belong to the
checkout invoking the command.
+### `mso gateway status` says `external-running`
+
+This is a healthy, intentional state when `OS_PUBLIC_ORIGIN` reaches the exact same MSO health identity as the selected local runtime but MSO has no owned provider-process record. A reverse proxy, Tailscale, Kubernetes ingress, PaaS router, s6-managed tunnel, or another external supervisor may own that lifecycle. MSO inspects the route but will not stop, restart, or automatically adopt the external process. Use `mso gateway status --json` for the separate ownership/provider/process/local/public dimensions. See [Gateway architecture](./GATEWAY.md).
+
+### `mso gateway status` says `degraded`
+
+A running process is not sufficient proof of public readiness. Check `publicHealth`, `localHealth`, `processHealth`, and `ownership` in `mso gateway status --json`. `identity-mismatch` means the public health endpoint is a valid MSO deployment but not the selected local instance; fix routing rather than restarting blindly. Doctor/status do not mutate providers. An external gateway is report-only; managed recovery remains limited to processes whose ownership identity MSO can prove.
+
+### Public MSO works, but `mso gateway doctor` reports an unsafe local bind
+
+These are independent dimensions. A working public reverse proxy/tunnel does not make `0.0.0.0:<port>` safe. The normal deployment keeps the raw MSO app on loopback/private scope and publishes it through the chosen HTTPS provider. Fix the runtime/service bind separately; do not suppress the doctor finding merely because public health is green.
+
### `mso gateway start` cannot install or verify cloudflared
Current MSO installs a reviewed `cloudflared` release automatically into `~/.mso/tools` on first
diff --git a/scripts/lib/gateway-config.sh b/scripts/lib/gateway-config.sh
index e72bbb1d..5ef7ffe0 100644
--- a/scripts/lib/gateway-config.sh
+++ b/scripts/lib/gateway-config.sh
@@ -97,27 +97,54 @@ CFG
}
gateway_cmd_doctor() {
- local fails=0 origin
+ local fails=0 observed rc state provider public_health local_health ownership public
gateway_info "mso gateway doctor"
- gateway_health_ok && gateway_info " ok verified MSO runtime $LOCAL_URL" \
- || gateway_info " -- no verified MSO runtime (mso web can start the built loopback fallback)"
- if MSO_GATEWAY_NO_AUTO_INSTALL=1 gateway_resolve_cloudflared >/dev/null 2>&1; then
- gateway_info " ok $("$CLOUDFLARED" --version 2>/dev/null | head -1) (pinned/explicit)"
- else gateway_info " FAIL cloudflared unavailable — run: mso gateway install"; fails=$((fails+1)); fi
+ if observed="$(gateway_observe_state)"; then rc=0; else rc=$?; fi
+ if [ "$rc" != 0 ]; then
+ gateway_info " FAIL gateway state is unsafe/corrupt"
+ fails=$((fails+1))
+ fi
+ local_health="$(jq -r '.localHealth // "unknown"' <<<"$observed")"
+ if [ "$local_health" = healthy ]; then gateway_info " ok verified MSO runtime (local) $LOCAL_URL"
+ else gateway_info " warn no verified MSO runtime at $LOCAL_URL (local)"; fi
+
if gateway_port_exposure_state; then
- gateway_info " FAIL raw MSO port has a non-loopback listener — reconfigure it to 127.0.0.1 before public tunneling"; fails=$((fails+1))
+ gateway_info " FAIL local binding security: raw MSO port has a non-loopback listener"
+ fails=$((fails+1))
else
rc=$?
- if [ "$rc" = 1 ]; then gateway_info " ok raw MSO port has no non-loopback listener"
- else gateway_info " FAIL cannot verify kernel listener exposure"; fails=$((fails+1)); fi
+ if [ "$rc" = 1 ]; then gateway_info " ok local binding security: raw MSO port has no non-loopback listener"
+ else gateway_info " FAIL local binding security: cannot verify kernel listener exposure"; fails=$((fails+1)); fi
fi
gateway_info " ok gateway upstream policy is loopback-only"
- origin="$(gateway_env_origin 2>/dev/null || true)"
- [ -n "$origin" ] && gateway_info " ok stable public origin: $origin" || gateway_info " -- no stable public origin (temporary mode available)"
- local active_rc
- if gateway_active_state >/dev/null; then gateway_info " ok public gateway running"
- else active_rc=$?; if [ "$active_rc" = 1 ]; then gateway_info " -- public gateway stopped"
- else gateway_info " FAIL gateway state is unsafe/corrupt"; fails=$((fails+1)); fi; fi
+
+ public="$(jq -r '.public // empty' <<<"$observed")"
+ public_health="$(jq -r '.publicHealth // "unknown"' <<<"$observed")"
+ if [ -n "$public" ]; then gateway_info " info configured public origin: $public"
+ else gateway_info " info no configured stable public origin"; fi
+ case "$public_health" in
+ healthy) gateway_info " ok public MSO identity matches local runtime" ;;
+ identity-mismatch) gateway_info " FAIL public route reaches a different MSO identity"; fails=$((fails+1)) ;;
+ failing) gateway_info " FAIL public route unreachable"; fails=$((fails+1)) ;;
+ invalid) gateway_info " FAIL public route does not return the MSO health contract"; fails=$((fails+1)) ;;
+ unverified) gateway_info " warn public MSO responder exists but local identity is unavailable for comparison" ;;
+ not-configured) gateway_info " info public health not configured" ;;
+ *) gateway_info " warn public health is unknown" ;;
+ esac
+
+ state="$(jq -r '.state // "unknown"' <<<"$observed")"
+ ownership="$(jq -r '.ownership // "unknown"' <<<"$observed")"
+ case "$state" in
+ managed-running) gateway_info " ok gateway lifecycle managed by MSO" ;;
+ external-running) gateway_info " warn gateway lifecycle managed externally; MSO will not stop/restart/adopt it" ;;
+ degraded) gateway_info " FAIL gateway is degraded (ownership: $ownership)"; fails=$((fails+1)) ;;
+ recovering) gateway_info " warn recorded MSO-owned provider process is stale/recovering; no mutation performed" ;;
+ stopped) gateway_info " info no verified public gateway is running" ;;
+ *) gateway_info " FAIL gateway lifecycle state is unknown"; fails=$((fails+1)) ;;
+ esac
+ gateway_info " info supervisor: $(jq -r '.supervisor // "unknown"' <<<"$observed")"
+ provider="$(jq -r '.provider // "custom"' <<<"$observed")"
+ gateway_provider_doctor_readonly "$provider"
return "$fails"
}
@@ -125,18 +152,31 @@ gateway_cmd_web_resolve_locked() {
local mode="$1" state rc
case "$mode" in
public|auto)
+ # Existing MSO-owned lifecycle remains authoritative and is checked first.
+ # This preserves lock/race behavior without adding public probes to the hot path.
if state="$(gateway_active_state)"; then
- # The lifecycle decision and reconciliation share the SAME exclusive lock.
- # Only the checkout-wide runtime lock nests inside it while Next may start.
gateway_with_runtime_shared gateway_reconcile_active_tunnel "$state" >/dev/null
state="$(gateway_active_state)" || gateway_fail "public gateway stopped during reconciliation"
jq -r .url <<<"$state"
return 0
else rc=$?; fi
[ "$rc" = 1 ] || return "$rc"
+
if [ "$mode" = public ]; then
+ local observed observed_state external_url
+ observed="$(gateway_observe_state 2>/dev/null || true)"
+ observed_state="$(jq -r '.state // empty' <<<"$observed" 2>/dev/null || true)"
+ if [ "$observed_state" = external-running ]; then
+ external_url="$(jq -r '.public // empty' <<<"$observed")"
+ [ -n "$external_url" ] || gateway_fail "external gateway has no valid public origin"
+ printf '%s\n' "$external_url"
+ return 0
+ fi
gateway_fail "public gateway is not running; run: mso gateway start"
fi
+
+ # Auto mode deliberately stays local unless MSO itself owns the public
+ # lifecycle. Merely configuring an external origin does not change defaults.
gateway_with_runtime_shared gateway_cmd_local_start_locked >/dev/null
printf '%s\n' "$LOCAL_URL"
;;
diff --git a/scripts/lib/gateway-health.sh b/scripts/lib/gateway-health.sh
index 42a90c98..f5338e50 100755
--- a/scripts/lib/gateway-health.sh
+++ b/scripts/lib/gateway-health.sh
@@ -5,7 +5,7 @@ gateway_health_body_ok() {
local body="$1" expected_instance="${2-}"
[ -n "$body" ] || return 1
jq -e --arg version "$GATEWAY_EXPECTED_VERSION" --arg instance "$expected_instance" '
- type == "object" and .status == "ok" and .version == $version and
+ type == "object" and .status == "ok" and (.service == null or .service == "mso") and .version == $version and
(.buildId | type == "string") and (.buildId | length > 0) and has("runtimeInstanceId") and
(if $instance == "" then true else .runtimeInstanceId == $instance end)
' <<<"$body" >/dev/null 2>&1
@@ -14,7 +14,7 @@ gateway_health_body_ok() {
gateway_health_identity_from_body() {
local body="$1" expected_instance="${2-}"
gateway_health_body_ok "$body" "$expected_instance" || return 1
- jq -c '{version,buildId,runtimeInstanceId}' <<<"$body"
+ jq -c '{version,buildId,buildSha:(.buildSha // null),runtimeInstanceId}' <<<"$body"
}
gateway_fetch_health_body() {
diff --git a/scripts/lib/gateway-provider.sh b/scripts/lib/gateway-provider.sh
new file mode 100644
index 00000000..2ef77f83
--- /dev/null
+++ b/scripts/lib/gateway-provider.sh
@@ -0,0 +1,108 @@
+#!/usr/bin/env bash
+# Provider-neutral gateway adapter boundary. Core lifecycle/state code calls this
+# file; provider-specific Cloudflare implementation remains in gateway-tool.sh and
+# gateway-tunnel.sh. New providers should implement the same small contract rather
+# than branching provider names through the core.
+
+gateway_provider_family() {
+ case "${1:-}" in
+ cloudflare|cloudflare-quick|cloudflare-named) printf '%s\n' cloudflare ;;
+ local) printf '%s\n' local ;;
+ custom|external|'') printf '%s\n' custom ;;
+ *) printf '%s\n' "$1" ;;
+ esac
+}
+
+gateway_provider_capabilities_json() {
+ local provider
+ provider="$(gateway_provider_family "${1:-custom}")"
+ case "$provider" in
+ cloudflare)
+ jq -nc '{publicHealthProbe:true,managedProcess:true,namedEndpoint:true,externalDetection:true,restart:true,reconnect:true,credentialsRequired:true,dnsRouting:true}'
+ ;;
+ local)
+ jq -nc '{publicHealthProbe:false,managedProcess:false,namedEndpoint:false,externalDetection:false,restart:false,reconnect:false,credentialsRequired:false,dnsRouting:false}'
+ ;;
+ *)
+ jq -nc '{publicHealthProbe:true,managedProcess:false,namedEndpoint:true,externalDetection:true,restart:false,reconnect:false,credentialsRequired:false,dnsRouting:false}'
+ ;;
+ esac
+}
+
+gateway_provider_default() { printf '%s\n' cloudflare; }
+
+gateway_provider_parse_start_args() {
+ GATEWAY_SELECTED_PROVIDER="$(gateway_provider_default)"
+ # Backward-compatible Cloudflare adapter arguments remain the current default.
+ gateway_parse_start_args "$@"
+}
+
+gateway_provider_start_locked() {
+ local active observed state ownership provider rc
+ provider="${GATEWAY_SELECTED_PROVIDER:-$(gateway_provider_default)}"
+
+ # Preserve the established managed lifecycle/race path without adding a public
+ # probe before every start. The adapter itself handles active reconciliation and
+ # explicit named-start semantics under the same lifecycle lock.
+ if active="$(gateway_active_state)"; then
+ case "$(gateway_provider_family "$provider")" in
+ cloudflare) gateway_cmd_start_locked ;;
+ *) gateway_fail "provider '$provider' is not implemented for managed start yet" ;;
+ esac
+ return $?
+ else
+ rc=$?
+ fi
+ [ "$rc" = 1 ] || return "$rc"
+
+ # Explicit named-provider starts are deliberate operator actions. They continue
+ # through the existing provider validator rather than being inferred as an
+ # ownership takeover from public-route observation.
+ if [ -n "${GATEWAY_CONFIG:-}${GATEWAY_TUNNEL:-}" ]; then
+ case "$(gateway_provider_family "$provider")" in
+ cloudflare) gateway_cmd_start_locked ;;
+ *) gateway_fail "provider '$provider' is not implemented for managed start yet" ;;
+ esac
+ return $?
+ fi
+
+ # Only an implicit/default start needs external-route duplicate prevention.
+ # Observation is read-only: a detected external route is never adopted/mutated.
+ observed="$(gateway_observe_state)" || return $?
+ state="$(jq -r .state <<<"$observed")"
+ ownership="$(jq -r .ownership <<<"$observed")"
+ if [ "$ownership" = external ] && { [ "$state" = external-running ] || [ "$state" = degraded ]; }; then
+ gateway_fail "configured public gateway is externally managed; refusing to create a duplicate connector from an implicit start"
+ fi
+
+ case "$(gateway_provider_family "$provider")" in
+ cloudflare) gateway_cmd_start_locked ;;
+ *) gateway_fail "provider '$provider' is not implemented for managed start yet" ;;
+ esac
+}
+
+gateway_provider_doctor_readonly() {
+ local provider="$(gateway_provider_family "${1:-custom}")"
+ case "$provider" in
+ cloudflare)
+ # Explicitly disable the resolver's install path: doctor is observational.
+ if MSO_GATEWAY_NO_AUTO_INSTALL=1 gateway_resolve_cloudflared >/dev/null 2>&1; then
+ gateway_info " ok provider cloudflare: $("$CLOUDFLARED" --version 2>/dev/null | head -1)"
+ else
+ gateway_info " warn provider cloudflare: managed binary unavailable (doctor did not install it)"
+ fi
+ ;;
+ local) gateway_info " info provider local: no public provider process" ;;
+ *) gateway_info " info provider $provider: externally/custom managed; MSO will inspect but not mutate it" ;;
+ esac
+}
+
+gateway_provider_supervisor() {
+ local ownership="$1" explicit="${MSO_GATEWAY_SUPERVISOR:-}"
+ if [ -n "$explicit" ]; then printf '%s\n' "$explicit"; return 0; fi
+ case "$ownership" in
+ mso) printf '%s\n' mso-lifecycle ;;
+ external) printf '%s\n' external ;;
+ *) printf '%s\n' unknown ;;
+ esac
+}
diff --git a/scripts/lib/gateway-reconcile.sh b/scripts/lib/gateway-reconcile.sh
index 49d8ae0f..f1ea9753 100755
--- a/scripts/lib/gateway-reconcile.sh
+++ b/scripts/lib/gateway-reconcile.sh
@@ -34,7 +34,13 @@ gateway_reconcile_active_tunnel() {
gateway_fail "recovered runtime is healthy but gateway state could not be persisted"
fi
GATEWAY_PENDING_CLEANUP=0
- gateway_cmd_status
+ # Reconciliation has already passed the provider readiness/identity gate above.
+ # `status` is an observational classifier and may intentionally report degraded
+ # when an operator disabled a public probe, so it must not redefine start success.
+ gateway_info "gateway reconciled"
+ gateway_info "public: $public"
+ gateway_info "local: $LOCAL_URL"
+ return 0
}
gateway_reconcile_runtime_rollback() {
diff --git a/scripts/lib/gateway-runtime.sh b/scripts/lib/gateway-runtime.sh
index 4ec5cdf9..8bc89c31 100644
--- a/scripts/lib/gateway-runtime.sh
+++ b/scripts/lib/gateway-runtime.sh
@@ -192,29 +192,49 @@ gateway_cmd_stop_locked() {
}
gateway_cmd_status() {
- local state mode rc
- if state="$(gateway_active_state)"; then
- mode="$(jq -r .mode <<<"$state")"
- gateway_info "gateway: running"
- gateway_info "mode: $mode"
- gateway_info "provider: $(jq -r .provider <<<"$state")"
- gateway_info "public: $(jq -r .url <<<"$state")"
- gateway_info "local: $(jq -r .localUrl <<<"$state")"
- [ "$mode" != temporary ] || gateway_info "note: Quick Tunnel is preview-only; live Terminal SSE is not supported"
- return 0
+ local json=0 observed rc state legacy mode
+ while [ $# -gt 0 ]; do
+ case "$1" in
+ --json) json=1 ;;
+ *) gateway_fail "usage: mso gateway status [--json]" ;;
+ esac
+ shift
+ done
+ if observed="$(gateway_observe_state)"; then rc=0; else rc=$?; fi
+ if [ "$json" = 1 ]; then
+ printf '%s\n' "$observed"
else
- rc=$?
+ state="$(jq -r .state <<<"$observed")"
+ legacy="$(jq -r .legacyState <<<"$observed")"
+ if [ "$legacy" = running ]; then gateway_info "gateway: running"
+ else gateway_info "gateway: $legacy"; fi
+ gateway_info "state: $state"
+ gateway_info "provider: $(jq -r .provider <<<"$observed")"
+ gateway_info "ownership: $(jq -r .ownership <<<"$observed")"
+ gateway_info "supervisor: $(jq -r .supervisor <<<"$observed")"
+ gateway_info "process-health: $(jq -r .processHealth <<<"$observed")"
+ gateway_info "local-health: $(jq -r .localHealth <<<"$observed")"
+ gateway_info "public-health: $(jq -r .publicHealth <<<"$observed")"
+ gateway_info "provider-health: $(jq -r .providerHealth <<<"$observed")"
+ gateway_info "public: $(jq -r '.public // "--"' <<<"$observed")"
+ gateway_info "local: $(jq -r .local <<<"$observed")"
+ mode="$(jq -r '.mode // empty' <<<"$observed")"
+ [ -z "$mode" ] || gateway_info "mode: $mode"
+ [ "$mode" != temporary ] || gateway_info "note: Quick Tunnel is preview-only; live Terminal SSE is not supported"
fi
- [ "$rc" = 1 ] || return "$rc"
- gateway_info "gateway: stopped"
- gateway_info "local: $LOCAL_URL"
- gateway_health_ok && gateway_info "runtime: healthy MSO (loopback)" || gateway_info "runtime: not a verified MSO endpoint"
- return 1
+ [ "$rc" = 0 ] || return "$rc"
+ state="$(jq -r .state <<<"$observed")"
+ gateway_status_exit_code "$state"
}
gateway_cmd_url() {
- local state rc
- if state="$(gateway_active_state)"; then jq -r .url <<<"$state"; return 0; else rc=$?; fi
- [ "$rc" = 1 ] || return "$rc"
- gateway_fail "gateway is not running; run: mso gateway start"
+ local observed state public rc
+ if observed="$(gateway_observe_state)"; then rc=0; else rc=$?; fi
+ [ "$rc" = 0 ] || return "$rc"
+ state="$(jq -r .state <<<"$observed")"
+ public="$(jq -r '.public // empty' <<<"$observed")"
+ case "$state" in
+ managed-running|external-running) [ -n "$public" ] && { printf '%s\n' "$public"; return 0; } ;;
+ esac
+ gateway_fail "gateway has no healthy public route; run: mso gateway status"
}
diff --git a/scripts/lib/gateway-state.sh b/scripts/lib/gateway-state.sh
new file mode 100644
index 00000000..e0caeed5
--- /dev/null
+++ b/scripts/lib/gateway-state.sh
@@ -0,0 +1,109 @@
+#!/usr/bin/env bash
+# Read-only gateway observation/classification. This layer never starts, stops,
+# adopts, restarts, or rewrites a provider process.
+
+gateway_configured_public_origin() {
+ local candidate="${OS_PUBLIC_ORIGIN:-}"
+ [ -n "$candidate" ] || return 1
+ gateway_validate_public_origin "$candidate" 2>/dev/null
+}
+
+gateway_public_observation() {
+ local public="$1" local_identity="$2" body actual health=unknown
+ [ -n "$public" ] || { jq -nc '{health:"not-configured",identity:null,responder:false}'; return 0; }
+ body="$(gateway_fetch_health_body "$public" 2>/dev/null || true)"
+ [ -n "$body" ] || { jq -nc '{health:"failing",identity:null,responder:false}'; return 0; }
+ actual="$(gateway_health_identity_from_body "$body" 2>/dev/null || true)"
+ if [ -z "$actual" ]; then
+ jq -nc '{health:"invalid",identity:null,responder:true}'
+ return 0
+ fi
+ if [ -z "$local_identity" ]; then
+ health=unverified
+ elif [ "$(jq -cS . <<<"$actual")" = "$(jq -cS . <<<"$local_identity")" ]; then
+ health=healthy
+ else
+ health=identity-mismatch
+ fi
+ jq -nc --arg health "$health" --argjson identity "$actual" '{health:$health,identity:$identity,responder:true}'
+}
+
+gateway_observe_state() {
+ local stored rc tunnel raw_provider provider mode public configured local_identity local_health
+ local process_health ownership supervisor public_obs public_health provider_health state capabilities managed_recorded runtime_owned
+ if stored="$(gateway_state_read)"; then :; else
+ rc=$?
+ jq -nc --arg local "$LOCAL_URL" '{state:"unknown",legacyState:"unknown",ownership:"unknown",provider:"unknown",providerDetail:null,supervisor:"unknown",local:$local,public:null,localHealth:"unknown",publicHealth:"unknown",providerHealth:"unknown",processHealth:"unknown",capabilities:{},stateError:"unsafe-or-corrupt"}'
+ return "$rc"
+ fi
+
+ local_identity="$(gateway_health_url_identity "$LOCAL_URL" 2>/dev/null || true)"
+ if [ -n "$local_identity" ]; then local_health=healthy; else local_health=unhealthy; fi
+
+ tunnel="$(jq -c '.tunnelIdentity // null' <<<"$stored")"
+ raw_provider="$(jq -r '.provider // empty' <<<"$stored")"
+ mode="$(jq -r '.mode // empty' <<<"$stored")"
+ public="$(gateway_validate_public_origin "$(jq -r '.url // empty' <<<"$stored")" 2>/dev/null || true)"
+ configured="$(gateway_configured_public_origin 2>/dev/null || true)"
+ [ -n "$public" ] || public="$configured"
+
+ runtime_owned="$(jq -r '.runtimeOwned // false' <<<"$stored")"
+ managed_recorded=false
+ if [ "$tunnel" != null ]; then managed_recorded=true
+ elif [ -n "$raw_provider" ] && [ "$raw_provider" != local ] && [ "$mode" != local ] && [ "$runtime_owned" = true ]; then managed_recorded=true
+ fi
+ if [ "$managed_recorded" = true ]; then
+ ownership=mso
+ provider="$(gateway_provider_family "${raw_provider:-cloudflare}")"
+ if [ "$tunnel" != null ] && gateway_identity_matches_retry "$tunnel" 2; then process_health=alive; else process_health=stale; fi
+ else
+ ownership=none
+ provider="$(gateway_provider_family "${raw_provider:-custom}")"
+ process_health=not-applicable
+ fi
+
+ public_obs="$(gateway_public_observation "$public" "$local_identity")"
+ public_health="$(jq -r .health <<<"$public_obs")"
+
+ if [ "$ownership" = mso ]; then
+ if [ "$process_health" = alive ] && [ "$local_health" = healthy ] && [ "$public_health" = healthy ]; then
+ state=managed-running; provider_health=healthy
+ elif [ "$process_health" = stale ]; then
+ state=recovering; provider_health=stale
+ else
+ state=degraded; provider_health=degraded
+ fi
+ elif [ "$(jq -r .responder <<<"$public_obs")" = true ]; then
+ ownership=external
+ process_health=external
+ provider="$(gateway_provider_family "${raw_provider:-custom}")"
+ if [ "$local_health" = healthy ] && [ "$public_health" = healthy ]; then
+ state=external-running; provider_health=healthy
+ else
+ state=degraded; provider_health=degraded
+ fi
+ else
+ state=stopped; provider_health=unknown
+ fi
+
+ supervisor="$(gateway_provider_supervisor "$ownership")"
+ capabilities="$(gateway_provider_capabilities_json "$provider")"
+ jq -nc \
+ --arg state "$state" \
+ --arg legacyState "$([ "$state" = managed-running ] || [ "$state" = external-running ] && printf running || { [ "$state" = stopped ] && printf stopped || printf "$state"; })" \
+ --arg ownership "$ownership" --arg provider "$provider" --arg providerDetail "${raw_provider:-}" \
+ --arg supervisor "$supervisor" --arg local "$LOCAL_URL" --arg public "$public" --arg mode "$mode" \
+ --arg localHealth "$local_health" --arg publicHealth "$public_health" \
+ --arg providerHealth "$provider_health" --arg processHealth "$process_health" \
+ --argjson capabilities "$capabilities" --argjson localIdentity "${local_identity:-null}" \
+ --argjson publicIdentity "$(jq -c '.identity' <<<"$public_obs")" \
+ '{state:$state,legacyState:$legacyState,ownership:$ownership,provider:$provider,providerDetail:(if $providerDetail=="" then null else $providerDetail end),supervisor:$supervisor,mode:(if $mode=="" then null else $mode end),local:$local,public:(if $public=="" then null else $public end),localHealth:$localHealth,publicHealth:$publicHealth,providerHealth:$providerHealth,processHealth:$processHealth,capabilities:$capabilities,localIdentity:$localIdentity,publicIdentity:$publicIdentity}'
+}
+
+gateway_status_exit_code() {
+ case "$1" in
+ managed-running|external-running) return 0 ;;
+ stopped) return 1 ;;
+ *) return 2 ;;
+ esac
+}
diff --git a/scripts/mso-gateway b/scripts/mso-gateway
index a7ffa352..c3e40bdc 100755
--- a/scripts/mso-gateway
+++ b/scripts/mso-gateway
@@ -1,6 +1,6 @@
#!/usr/bin/env bash
-# MSO local/public gateway dispatcher. Public access is always an outbound HTTPS
-# tunnel; the Next application itself remains on a validated loopback origin.
+# MSO local/public gateway dispatcher. Gateway core is provider/supervisor/deployment
+# neutral; the application upstream remains a validated loopback origin.
set -euo pipefail
umask 077
@@ -62,8 +62,12 @@ GATEWAY_LOCK_FD=''
# shellcheck source=scripts/lib/gateway-network.sh
. "$ROOT/scripts/lib/gateway-network.sh"
+# Cloudflare is the current managed-provider adapter; generic core calls it through
+# gateway-provider.sh rather than treating it as an architecture boundary.
# shellcheck source=scripts/lib/gateway-tool.sh
. "$ROOT/scripts/lib/gateway-tool.sh"
+# shellcheck source=scripts/lib/gateway-provider.sh
+. "$ROOT/scripts/lib/gateway-provider.sh"
# shellcheck source=scripts/lib/gateway-lock.sh
. "$ROOT/scripts/lib/gateway-lock.sh"
# shellcheck source=scripts/lib/runtime-exclusion.sh
@@ -74,6 +78,8 @@ GATEWAY_LOCK_FD=''
. "$ROOT/scripts/lib/gateway-recovery.sh"
# shellcheck source=scripts/lib/gateway-runtime.sh
. "$ROOT/scripts/lib/gateway-runtime.sh"
+# shellcheck source=scripts/lib/gateway-state.sh
+. "$ROOT/scripts/lib/gateway-state.sh"
# shellcheck source=scripts/lib/gateway-pending.sh
. "$ROOT/scripts/lib/gateway-pending.sh"
# shellcheck source=scripts/lib/gateway-tunnel.sh
@@ -98,9 +104,9 @@ gateway_stop_serialized() {
}
case "${1:-status}" in
- start) gateway_parse_start_args "$@"; gateway_with_lock gateway_with_runtime_shared gateway_cmd_start_locked ;;
+ start) gateway_provider_parse_start_args "$@"; gateway_with_lock gateway_with_runtime_shared gateway_provider_start_locked ;;
stop) gateway_stop_serialized ;;
- status) gateway_cmd_status ;;
+ status) shift || true; gateway_cmd_status "$@" ;;
url) gateway_cmd_url ;;
doctor) gateway_cmd_doctor ;;
install) gateway_cmd_install_tool ;;
@@ -109,5 +115,5 @@ case "${1:-status}" in
local-start) gateway_with_lock gateway_with_runtime_shared gateway_cmd_local_start_locked ;; # internal: onboard/web/update fallback
runtime-assert-update-safe) gateway_with_lock gateway_cmd_runtime_assert_update_safe_locked ;; # internal: read-only offline-build preflight
runtime-stop) gateway_with_lock gateway_cmd_runtime_stop_locked ;; # internal: quiesce owned runtime before offline build
- *) gateway_fail "usage: mso gateway start|stop|status|url|doctor|install|domain ..." ;;
+ *) gateway_fail "usage: mso gateway start|stop|status [--json]|url|doctor|install|domain ..." ;;
esac
diff --git a/scripts/mso-gateway-recovery.test.ts b/scripts/mso-gateway-recovery.test.ts
index ed28ecea..c5a48c74 100644
--- a/scripts/mso-gateway-recovery.test.ts
+++ b/scripts/mso-gateway-recovery.test.ts
@@ -70,7 +70,7 @@ exec node -e 'require(process.argv[1] + ".cjs")' "$0" "$@"
run(["stop"], f.env);
for (let i = 0; i < 50 && spawned.some(alive); i++) await new Promise((r) => setTimeout(r, 20));
expect(spawned.filter(alive)).toEqual([]);
- });
+ }, 10_000);
it("preserves owned runtime identity when only the old tunnel died", async () => {
const f = fixture();
diff --git a/scripts/mso-gateway-state.test.ts b/scripts/mso-gateway-state.test.ts
new file mode 100644
index 00000000..2ca3c7ab
--- /dev/null
+++ b/scripts/mso-gateway-state.test.ts
@@ -0,0 +1,99 @@
+import { spawnSync } from "node:child_process";
+import fs from "node:fs";
+import { describe, expect, it } from "vitest";
+import { GATEWAY, VERSION, fixture, readState, runGateway as run } from "./mso-gateway-test-fixture";
+
+function health(buildId = "fixture") {
+ return `{"status":"ok","service":"mso","buildId":"${buildId}","buildSha":"sha-${buildId}","runtimeInstanceId":"fixture","version":"${VERSION}"}`;
+}
+
+function jsonStatus(env: NodeJS.ProcessEnv) {
+ const out = spawnSync(GATEWAY, ["status", "--json"], { encoding: "utf8", env });
+ return { status: out.status, stderr: out.stderr, value: JSON.parse(out.stdout) as Record<string, unknown> };
+}
+
+describe("gateway provider-neutral state model", () => {
+ it("classifies an MSO-owned healthy provider as managed-running", () => {
+ const f = fixture();
+ run(["start"], f.baseEnv);
+ const observed = jsonStatus(f.baseEnv);
+ expect(observed.status).toBe(0);
+ expect(observed.value.state).toBe("managed-running");
+ expect(observed.value.ownership).toBe("mso");
+ expect(observed.value.provider).toBe("cloudflare");
+ expect(observed.value.processHealth).toBe("alive");
+ expect(observed.value.publicHealth).toBe("healthy");
+ expect((observed.value.capabilities as Record<string, unknown>).managedProcess).toBe(true);
+ run(["stop"], f.baseEnv);
+ });
+
+ it("classifies an alive owned provider with a failed public route as degraded without restarting it", () => {
+ const f = fixture();
+ run(["start"], f.baseEnv);
+ const owned = readState(f.state).value.tunnelIdentity.pid;
+ fs.writeFileSync(f.curl, `#!/bin/sh\ncase "$*" in\n *127.0.0.1:4005/api/health*) printf '%s\\n' '${health()}' ;;\n *trycloudflare.com/api/health*) exit 6 ;;\n *) printf '%s\\n' '${health()}' ;;\nesac\n`, { mode: 0o700 });
+ const observed = jsonStatus(f.baseEnv);
+ expect(observed.status).toBe(2);
+ expect(observed.value.state).toBe("degraded");
+ expect(observed.value.ownership).toBe("mso");
+ expect(observed.value.processHealth).toBe("alive");
+ expect(observed.value.publicHealth).toBe("failing");
+ expect(() => process.kill(owned, 0)).not.toThrow();
+ run(["stop"], f.baseEnv);
+ });
+
+ it("detects a healthy configured route with no MSO ownership as external-running and leaves it external on stop", () => {
+ const f = fixture();
+ fs.writeFileSync(f.curl, `#!/bin/sh\nprintf '%s\\n' '${health()}'\n`, { mode: 0o700 });
+ const env = { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://external.example.test" };
+ const observed = jsonStatus(env);
+ expect(observed.status).toBe(0);
+ expect(observed.value.state).toBe("external-running");
+ expect(observed.value.ownership).toBe("external");
+ expect(observed.value.provider).toBe("custom");
+ expect(observed.value.publicHealth).toBe("healthy");
+ expect((observed.value.capabilities as Record<string, unknown>).managedProcess).toBe(false);
+
+ run(["stop"], env);
+ const after = jsonStatus(env);
+ expect(after.value.state).toBe("external-running");
+ expect(after.value.ownership).toBe("external");
+ });
+
+ it("treats a public MSO identity mismatch as degraded external rather than healthy", () => {
+ const f = fixture();
+ fs.writeFileSync(f.curl, `#!/bin/sh\ncase "$*" in\n *127.0.0.1:4005/api/health*) printf '%s\\n' '${health("selected")}' ;;\n *external.example.test/api/health*) printf '%s\\n' '${health("other")}' ;;\n *) printf '%s\\n' '${health("selected")}' ;;\nesac\n`, { mode: 0o700 });
+ const env = { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://external.example.test" };
+ const observed = jsonStatus(env);
+ expect(observed.status).toBe(2);
+ expect(observed.value.state).toBe("degraded");
+ expect(observed.value.ownership).toBe("external");
+ expect(observed.value.publicHealth).toBe("identity-mismatch");
+ });
+
+ it("reports stale recorded ownership as recovering without mutating the process model", async () => {
+ const f = fixture();
+ run(["start"], f.baseEnv);
+ const pid = readState(f.state).value.tunnelIdentity.pid;
+ process.kill(pid, "SIGTERM");
+ for (let i = 0; i < 100; i++) {
+ try { process.kill(pid, 0); } catch { break; }
+ await new Promise((resolve) => setTimeout(resolve, 10));
+ }
+ const observed = jsonStatus(f.baseEnv);
+ expect(observed.status).toBe(2);
+ expect(observed.value.state).toBe("recovering");
+ expect(observed.value.ownership).toBe("mso");
+ expect(observed.value.processHealth).toBe("stale");
+ });
+
+ it("refuses a duplicate managed start when a verified external route already exists", () => {
+ const f = fixture();
+ fs.writeFileSync(f.curl, `#!/bin/sh\nprintf '%s\\n' '${health()}'\n`, { mode: 0o700 });
+ const env = { ...f.baseEnv, OS_PUBLIC_ORIGIN: "https://external.example.test" };
+ const out = spawnSync(GATEWAY, ["start"], { encoding: "utf8", env });
+ expect(out.status).not.toBe(0);
+ expect(out.stderr).toContain("externally managed");
+ expect(out.stderr).toContain("refusing to create a duplicate");
+ });
+});