> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monolex.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture

> The MonoSurf 0.11.3 architecture: shared facade, exact-port ownership, fail-closed cookie hydration, bound page evidence, profiles, site plugins, trust gates, and native-UI handoff.

# Architecture

MonoSurf separates browser ownership, page automation, reusable site
contracts, and safety checks so each result says which layer produced it.

*Verified against `monosurf 0.11.3`, OpenCLIs build
`2026-07-19-222928`.*

## System Map

```text theme={null}
AI or human
    ↓
entry point
    ├── standalone monosurf CLI
    └── embedded kernel-cli websurf namespace
    ↓
shared lib-monosurf facade
    ├── canonical help and embedded docs
    ├── profile TUI
    └── compatibility frontend contract
    ↓
shared lib-monosurf-core engine
    ├── profile and browser lifecycle
    ├── direct browse and external-CDP attach
    ├── site-plugin dispatch and batch control
    └── grants, doctor, self-tests, planning, and routing
    ↓
session ownership
    ├── ephemeral browser owned by MonoSurf
    ├── persistent managed profile owned by MonoSurf
    └── external CDP endpoint owned by another app
    ↓
Rust-native CDP connection
    ├── DOM and JavaScript
    ├── screenshots and responsive viewport
    ├── console and HTTP health
    ├── feed collection
    └── page network response stream
    ↓
structured output, files, evidence, and shell exit status
```

The normal page-control path is Rust-native and connects directly through CDP.
Standalone `monosurf` and `kernel-cli websurf` are frontends over the same
facade and core, so they share help, docs, the profile TUI, the profile
registry, plugins, grants, and browser state. Kernel CLI links this stack
in-process; it does not spawn the standalone CLI. The engine can use Chromium
installed by Chrome, Playwright, Puppeteer, or a headless-shell distribution
without turning those packages into the control layer.

## Four Architecture Planes

| Plane                | Owns                                                                                                    | Contract                                                        |
| -------------------- | ------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------- |
| Connection           | Browser discovery, managed profile launch, CDP-listener ownership proof, external attach, CDP readiness | Establish one page session or fail clearly.                     |
| Identity             | Named profiles, persistent default, account label, engine pin, live cookie jar                          | Preserve the intended browser identity across close and reboot. |
| Page work            | Navigation, wait/expect, extraction, evaluation, screenshots, console, network, collection              | Produce the requested web result and a scriptable exit code.    |
| Trust and operations | TLS, grants, plugin integrity/signatures, doctor safety classes, self-tests                             | Keep high-power or destructive behavior explicit.               |

## Session Ownership

Ownership determines what happens at the end of a command:

| Session type     | Created by                     | Closed by                   | Login persistence                |
| ---------------- | ------------------------------ | --------------------------- | -------------------------------- |
| Ephemeral browse | MonoSurf                       | MonoSurf                    | Deliberately discarded           |
| Managed profile  | MonoSurf profile manager       | `stop`, a person, or the OS | Retained in the profile          |
| External CDP     | Another application or browser | External owner              | Determined by the external owner |

This boundary prevents an attach command from accidentally terminating an
Electron app or browser it did not launch.

For managed profiles, MonoSurf 0.11.3 proves listener ownership from the
process command line's exact `--user-data-dir` argument. New profiles skip
active unregistered ports and keep the exact chosen port through launch proof
and cleanup. A foreign listener blocks `start` and profile-backed connection;
`stop` signals only a listener proven to belong to that profile. Temporarily
unknown OS metadata is retried for a bounded interval, then fails closed.
Explicit `browse --cdp-url <endpoint>` is the separate, intentional foreign-
attach path and never transfers lifecycle ownership to MonoSurf.

## Identity and Profile State

```text theme={null}
profile registry and default pointer
              ↓ choose
named browser profile
              ├── live site session
              ├── browser-managed encrypted cookies
              └── pinned browser kind and signing identity
```

Bookkeeping and login state are intentionally different. `doctor --fix` can
remove stale process records or temporary debris without deleting a managed
profile. `profile rm` and `doctor --prune` are the explicit destructive
boundaries.

## Login Snapshot Boundary

MonoSurf can hold session evidence in two encrypted owners:

| Owner                                    | Purpose                                                                                           | Priority at runtime                                                     |
| ---------------------------------------- | ------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------- |
| Managed Chromium profile                 | The live browser session, including current cookies and site storage                              | First; live state wins.                                                 |
| OpenCLIs vault or legacy secure fallback | Snapshot saved by `login` or an explicit bridge Sync click, used to bootstrap an empty cookie jar | Used only when no live cookie is available and the grant allows access. |

This design keeps server-rotated tokens current while retaining a protected
bootstrap path. It does not claim that a grant erases browser state; grants
authorize site-command access to the protected capability.

Bridge import is cookie-only. The batch hydration runs before navigation,
validates every cookie scope, supplies an explicit HTTP(S) origin, preserves
domain/path/HttpOnly/Secure/SameSite/expiry, and fails the command on any CDP
error. It never clones localStorage, IndexedDB, service workers, passwords, a
Chrome profile, or the Chrome process. Full Agent Browser state uses the
separate same-profile managed-login path.

## Direct Browse Data Flow

```text theme={null}
browse URL + requested evidence
          ↓
resolve ephemeral / managed / external session
          ↓
configure viewport, console, and network listeners
          ↓
navigate under strict TLS
          ↓
wait or assert selector state
          ↓
text / extract / eval / collect + optional screenshot and diagnostics
          ↓
write output atomically or stream JSONL
          ↓
return exit status and apply the session ownership rule
```

Network listeners start before navigation so the main document and early
subresources are not missed. Collection emits items incrementally, while
single-shot outputs use an atomic replace.

## Site Plugin Data Flow

```text theme={null}
domain + command + arguments
          ↓
resolve installed plugin and its declared intent
          ↓
validate domain and plugin integrity
          ↓
check read or write grant
          ↓
connect to profile and prefer the live session
          ↓
hydrate from protected snapshot only when the live jar is empty
          ↓
navigate → wait → actions → extract → format
```

Plugin commands remain data-defined, but they execute inside a logged-in page.
Local checksums block unsigned or changed local code until it is reviewed and
re-signed. Official pulls add server signature verification before replacement.

## Trust Gates

| Gate                     | Protects against                                                                                    | Failure behavior                                                                                         |
| ------------------------ | --------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------- |
| Strict TLS               | Invalid page certificates                                                                           | Navigation is refused unless testing explicitly uses `--insecure`.                                       |
| Domain validation        | A plugin masquerading as another site                                                               | Plugin load is refused.                                                                                  |
| Local integrity          | Unsigned or modified plugin actions                                                                 | Execution is blocked until review and signing.                                                           |
| Official pull signature  | Tampered registry payload                                                                           | The downloaded plugin is refused before it reaches the installed set.                                    |
| Read/write grant         | Unbounded access to authenticated site actions                                                      | The site command stops before protected session use.                                                     |
| Engine pin               | A different browser identity silently opening an old profile                                        | Launch fails unless the user accepts the change.                                                         |
| Managed-port ownership   | A foreign browser/service being adopted, driven, or killed because it occupies a profile's CDP port | Foreign listeners block connect; stop signals only a verified owner.                                     |
| Cookie hydration         | Malformed scope, partial CDP import, or silent overwrite of a live session                          | Only an empty jar is eligible; explicit-origin batch import fails on any invalid item or CDP error.      |
| Navigation postcondition | A click being reported as success without its expected page effect                                  | Exact-control ambiguity, URL drift, missing/covered target, toast mismatch, or timeout returns non-zero. |
| Confirmation gate        | Accidental profile deletion                                                                         | Destructive commands confirm or require `--yes`.                                                         |

## Operational Evidence

MonoSurf exposes health and regression checks as part of the architecture:

| Surface                              | Evidence                                                                              |
| ------------------------------------ | ------------------------------------------------------------------------------------- |
| `doctor --json`                      | Read-only registry, profile-directory, process-record, and temp-state reconciliation. |
| `selftest typing`                    | Page input and Unicode behavior.                                                      |
| `selftest leak`                      | Ephemeral child-browser and temporary-profile cleanup.                                |
| `selftest collect`                   | Complete incremental collection and visible stall reason.                             |
| `--console`, `--net`, `--expect`     | Page-runtime errors, HTTP failures, and selector-level smoke assertions.              |
| `postcondition navigation` / `toast` | One real CDP click plus bound URL/history/viewport/target/header or toast proof.      |

## Companion Boundary

```text theme={null}
static public resource ──▶ MonoFetch
interactive web page  ───▶ MonoSurf / kernel-cli websurf
native desktop/UI     ───▶ Kernel CLI OS commands
snapshot/token vault  ───▶ OpenCLIs Vault
passkey/WebAuthn      ───▶ MonoPass
same-profile browser ───▶ Monolex Agent Browser
searchable knowledge ───▶ Monomento
```

The shared web engine ends at the CDP-visible page. [Kernel CLI](/kernel-cli)
owns browser chrome, native dialogs, permission prompts, accessibility, input,
windows, and other desktop applications. Embedding the engine gives one binary
two clearly owned surfaces; it does not make AX/OCR and CDP one blended driver.
The standalone 0.11.3 artifact and Kernel CLI 0.26.11 both expose the same
facade/engine contract, collision-safe ownership, cookie hydration, and
postcondition surfaces. Their executables are not byte-identical; independently
published artifacts share behavior and state without collapsing release
identity. Cookie bridge installation additionally depends on the shared
`~/.niia/bin/monolex-native-host` staged by Monolex desktop; neither standalone
CLI archive bundles it. See [OpenCLIs Vault](/ai-clis/openclis-vault),
[MonoPass](/ai-clis/monopass), and the [Monolex CLI Agent Browser
surface](/ai-clis/monolex-cli) for the adjacent ownership boundaries.

## Release Proof Layers

Keep these facts separate when validating a MonoSurf release:

1. Source and embedded docs describe intended behavior.
2. OpenCLIs CDN `latest.json` names version 0.11.3 and build
   `2026-07-19-222928`; immutable `meta.json` owns platform hashes.
3. The OpenCLIs API owns description, docs links, AI use, and wrapper guidance.
4. The installed path proves which artifact runs.
5. `monosurf version` proves the binary version.
6. `doctor`, self-tests, and a real browse command prove the current runtime.

<CardGroup cols={2}>
  <Card title="How It Works" icon="gears" href="/monosurf/how-it-works">
    Follow session selection, login-state resolution, page work, and cleanup.
  </Card>

  <Card title="Usage and Command Reference" icon="terminal" href="/monosurf/usage">
    Run the supported command families and option groups.
  </Card>

  <Card title="Auth Gate" icon="shield-halved" href="/monosurf/auth-gate">
    Understand grants, live sessions, snapshots, and revocation.
  </Card>

  <Card title="Kernel CLI Reference" icon="microchip" href="/kernel-cli/reference">
    Continue the workflow outside the browser page.
  </Card>
</CardGroup>
