# user-onboarding / v0.3 — operating a4sx (install → automations → fleets → environments)

**Audience:** the **operator/developer** who runs a4sx and builds automations on
it. (This is the *human* guide. A *landing agent* gets a machine brief at `GET /orient`;
the full spec catalog is `GET /specs`.) On a hosted a4sx workspace the platform is already
running: §1 (install), §2 (first-run bootstrap) and the host-fleet commands in §8 describe
running the platform itself, which a workspace user does not do.

**New in v0.3:** the first-run bootstrap tokens are no longer printed to the log; each is
written once to a `0600` file in the collector's data dir and the log shows only its path and
fingerprint (§2). Everything else is unchanged from v0.2.

**The paradigm, in one line:** you build automations by **first onboarding live data
from your systems into a4sx, then growing skills on top of that live data** — and
the platform *enforces* that order (§11). This guide walks the whole operator journey:

> install → first admin token → bring your own model → onboard a data source → secrets
> → how skills work → make skills persistent (shims) → manage fleets → environments.

---

## 0. The shape of the system

- **The collector** (this service) is the always-up control plane + **live event
  substrate**. Everything is an event on a queryable stream (`GET /events`). It's the
  source of truth; it's k8s-hosted and survives everything around it.
- **Satellites** — connectors, **shims** (skill runners), the improvement loops,
  OAuth **holders** — are *ephemeral* processes that emit into / read from the stream.
  They're declared as **fleet-specs** and a **reconciler** keeps them alive.
- **Tenants** partition the collector by hostname (each an isolated factory);
  **environments** isolate workspaces *within* a tenant.

---

## 1. Install & run

**The collector**:

| how | command |
|---|---|
| local (dev) | `docker compose up --build` |
| bare python | `pip install . && python -m collector` |
| kubernetes | apply `manifests/deployment.yaml` (PVC at `/data`, probes on `/healthz`) |

Key env vars (`collector/config.py`):

| var | meaning |
|---|---|
| `DATA_DIR` (`/data`) | persistent state (events.jsonl, sqlite, registries, `_global/`, `tenants/`) |
| `HOST` / `PORT` | listen addr/port |
| `AGENT_MDX_VAULT_MASTER_KEY` | secret-vault KEK — **set this** to use secrets (else vault stays sealed) |
| `POLARIS_BREAKGLASS_ADMIN` | emergency root admin (env-sourced; the ultimate recovery credential) |
| `GH_APP_ID` / `GH_APP_INSTALLATION_ID` / `GH_APP_PRIVATE_KEY_B64` | GitHub App creds (private skill-bundle / manifest repos) |
| `SKILL_BUNDLE_REPO_URL` | git repo holding skill bodies (served at `/agent-skills/*`) |
| `PRIMARY_HOSTNAMES` / `TENANCY_STRICT` | multi-tenancy: default-tenant hostnames / reject unknown hosts |

**The host fleet** — the satellites run on a docker
host driven by a reconciler. Bring it up idempotently:
```bash
POLARIS_URL=https://<collector> host/fleet-up.sh                   # start/recover all
host/fleet-up.sh status                                            # just report
host/install-tripwire.sh                                           # systemd auto-recovery
```
**✅ checkpoint:** `curl https://<collector>/healthz` → `{"ok":true,…}`.

---

## 2. Your first admin token

On **first run** the collector mints one admin token and writes it **once** to a `0600`
file in its data dir (only the hash is stored). The log shows the path and a fingerprint,
never the token:
```
a4sx collector — first-run admin bootstrap
Token written to: /data/bootstrap-tenant-admin.token  (mode 0600)
Fingerprint (sha256, first 12 hex): 3f9c0d1e2a4b
```
A **separate global-admin** token is bootstrapped the same way into
`bootstrap-global-admin.token` (for tenancy — §3). Read each file once, store the token
in a password manager, then delete the file. From a container (the file is root-owned, `0600`):
`docker exec <collector> cat /data/bootstrap-tenant-admin.token`, then `docker exec <collector> rm …`.

```bash
export ADMIN=ge_admin_…
curl -H "Authorization: Bearer $ADMIN" https://<collector>/orient    # get oriented
```

### Tenancy (optional, multi-org)
A **global admin** carves the collector into isolated tenants by hostname:
```bash
# infra first: provision DNS/TLS/ingress for the new hostname, THEN:
curl -X POST https://<collector>/tenants -H "Authorization: Bearer $GLOBAL_ADMIN" \
  -d '{"id":"acme","hostnames":["acme.<domain>"]}'            # → a one-time tenant admin
curl -X POST https://<collector>/tenants/acme/admin-tokens -H "Authorization: Bearer $GLOBAL_ADMIN"
```
Only a global admin (or break-glass) mints global admins; a global admin mints tenant
admins; **tenant admins are just tenant admins**. A token is scoped to its tenant's
hostname. (Deep dive: `multi-tenancy`.) If you're single-org, just use the default tenant.

---

## 3. Bring your own model / subscription

Agents run on an **LLM subscription you own** (Claude team/enterprise, ChatGPT/Codex,
…), wired as an **OAuth holder**: a long-lived container whose credentials live in a
**named docker volume** (so they survive `docker rm`).

1. Create the holder + authenticate the account once (interactive login writes creds
   into the volume):
   ```bash
   docker run -d --name claude-holder --restart unless-stopped \
     -v claude-home:<agent-home>/.claude  <agent-image>  sleep infinity
   docker exec -it claude-holder claude login          # (or `codex login` for OpenAI)
   ```
2. Declare it as a fleet-spec so the reconciler keeps it healthy + its **token fresh**:
   ```yaml
   - kind: oauth_holder
     name: claude-holder
     image: <agent-image>
     volumes: ["claude-home:<agent-home>/.claude"]
     token_path: <agent-home>/.claude/.credentials.json
     token_fresh_min_h: 1            # exercise when < 1h to expiry
     exercise: "claude -p ok --max-turns 1"
   ```
   The reconciler reads the token's `expiresAt`; if it's near expiry and refreshable it
   runs the `exercise` to refresh, else it escalates `agent.needs_human` for a re-login.
3. Shims/loops consume the holder's account (via the account pool the shim is configured
   with). Multiple accounts/seats can back one pool for throughput.

(Exact holder/pool/account wiring + recipes:
`specs/fleet-spec`.) **✅ checkpoint:** `python3 -m reconciler.fleet_status` shows the
holder `ok · token Nh · refresh✓`.

---

## 4. Onboard your first external data source  *(do this before building skills)*

Get a third-party system's signal flowing in as events. Pick what fits:

- **Config-driven webhook** (no code): store the inbound secret in the vault (§5), then
  ```bash
  curl -X POST https://<host>/webhook-adapters -H "Authorization: Bearer $ADMIN" -d '{
    "adapter_id":"github","station":"intake","auth":{"type":"bearer","secret_name":"gh-wh"},
    "rules":[{"id":"pr","when":"…","emit":{ …event mapping… }}]}'           # spec: webhook-adapter
  # → point the third party's webhook at  https://<host>/webhooks/github
  ```
- **A producer you emit from:** register a repo + station, register/approve the producer,
  mint its emit token, emit:
  ```bash
  curl -X POST https://<host>/repositories -H "Authorization: Bearer $ADMIN" -d '{"owner":"acme","repo":"app","mainline_branch":"main"}'
  curl -X POST https://<host>/stations     -H "Authorization: Bearer $ADMIN" -d '{"name":"intake","description":"data in"}'
  curl -X POST https://<host>/producers/register -H "Authorization: Bearer $ADMIN" -d '{"name":"pr-feed","kind":"gh-action","requested_stations":["intake"],"contact":"you@co"}'
  curl -X POST https://<host>/producers/<id>/approve -H "Authorization: Bearer $ADMIN" -d '{"approved_stations":["intake"]}'
  curl -X POST https://<host>/producers/<id>/tokens  -H "Authorization: Bearer $ADMIN"     # → EMIT token
  curl -X POST https://<host>/events -H "Authorization: Bearer $EMIT" -d '{ …envelope… }'  # shape: GET /orient + the envelope spec
  ```
  (Register the repo — events whose `subject.repository` is unregistered are quarantined.)
- **A connector** (GitHub/AzDO/Jira poller/pusher): a satellite that reads the third
  party and emits; its creds are vault secrets; it runs as a fleet-spec (§9).
- Optionally `POST /normalizers` to map/enrich raw shapes into clean event types.

**✅ checkpoint — live data:** `curl -H "Authorization: Bearer $READ" "https://<host>/events?station=intake"`.
*Don't build skills until real events show up.*

---

## 5. Secret management (the vault)

a4sx ships an in-collector, **per-tenant** encrypted vault. Credentials never leave
it as plaintext, and they're **referenced by name** (never embedded in specs/events).

- Model: a shared operator **master KEK** (`AGENT_MDX_VAULT_MASTER_KEY` / `POST
  /vault/unseal`) wraps each tenant's own **DEK**; secret values are DEK-encrypted and
  ride the tenant's event stream. A tenant's DEK can't decrypt another's.
- Use it:
  ```bash
  curl -X POST https://<host>/secrets/gh-wh   -H "Authorization: Bearer $ADMIN" -d '{"value":"…"}'   # store
  curl -X POST https://<host>/vault/grants    -H "Authorization: Bearer $ADMIN" -d '{"producer_id":"<id>","name":"gh-wh"}'  # grant a shim read
  curl       https://<host>/vault/status      -H "Authorization: Bearer $READ"                       # posture (never values)
  # the granted producer reads its value:  GET /secrets/gh-wh  (the only value-returning route, audited)
  ```
- Host-side connectors that the reconciler runs resolve **secret-refs by name** to host
  files at run time (the collector stores only the ref). Deep dive: `secret-vault`.

---

## 6. How skills work

A **skill** is a versioned bundle (a `SKILL.md` entry point + optional helper files)
identified by `skill_id` + `version` + `content_hash`. The collector **serves** skill
bodies from a git-backed bundle repo (`SKILL_BUNDLE_REPO_URL`):

```bash
GET /agent-skills/{skill_id}/versions                  # version history
GET /agent-skills/{skill_id}/{version}                 # manifest (file list)
GET /agent-skills/{skill_id}/{version}/SKILL.md        # the body the agent reads
POST /skill-projection/{skill_id}/publish              # publish a new version (admin)
```

Publishing takes `{files: [{path, content | content_b64}], bump?: "major"|"minor"|"patch",
message?}` and answers `201 {version, …}`, or `422` (error code `bundle_invalid`, the failed
checks in `error.details.checks`) when the bundle fails validation. *(Erratum: earlier revisions
of this page listed `PATCH /agent-skills/{skill_id}`, a route that never existed — it answered
405. The publish route has always been the one above.)*

A runner pins a version, pulls `SKILL.md` (+ helpers), runs it, and hot-reloads when a
`manifest.updated` broadcast says the bundle changed. Authoring patterns (polls→triggers,
composability, avoiding duplication): `specs/skill-design`; bundle mechanics: `specs/skill-bundle`.

---

## 7. Make skills persistent — shims

A one-off skill run ends when it ends. To make a skill **always-on**, run it behind a
**shim**: a small daemon that connects the skill to the live stream and runs it on every
matching event.

What a shim does (`specs/shim`):
1. Boots from its **manifest** (`POLARIS_BOOTSTRAP_URL` = `…/agents/<name>/manifest`)
   using `POLARIS_TOKEN` (its emit token).
2. Registers its **triggers** as subscriptions and opens a long-lived **SSE** stream.
3. On each **delta** (a matching event) it **invokes the skill** (`claude -p <SKILL.md>`
   with the delta on stdin, or in-process), then persists its **cursor** so a restart
   resumes where it left off.

Run it as a fleet-spec so it stays up (§9):
```yaml
- kind: container
  name: cve-triage-shim
  image: <agent-image>
  env: { POLARIS_BOOTSTRAP_URL: "https://<host>/agents/cve-triage-shim/manifest" }
  secret_refs: [{ env_key: POLARIS_TOKEN, name: cve-triage-shim-token }]
  desired: running
```
**✅ checkpoint:** the shim emits `shim.connected`; new matching events now trigger the
skill automatically. *That's a persistent automation: live data → skill, hands-off.*

For **agentic** automations that *improve themselves*, register an **improvement-loop**
(`POST /loops`) over a registered **fitness** (`POST /fitness`) and the env model (§10);
the loop reads the live stream, builds, and **opens PRs** (never self-applies). Deep
dives: `improvement-loop`, `goal-runner`.

---

## 8. Managing fleets

Your satellites (shims, holders, connectors, loops) are a **fleet** kept in a desired
state by a **reconciler** (OBSERVE → DIFF → ACT → EMIT, every ~60s; allowlist-only, never
bulk/destructive; escalates `agent.needs_human` instead of crash-looping).

> **Changing a self-operating service in the fleet? Instruct its operator — don't reach in.** File a ticket
> to the operator (or a peer request) with the change you want; it reasons, deploys health-gated, and pushes
> the change through its governed path (review-branch → merge). Hand-editing a service's container or
> `docker run`-ing a replacement bypasses governance and desyncs it from its repo-of-record. The
> **fleet-conductor** is the operator-pattern + onboarding contact — ask it what owns a thing. (Full norm:
> orientation spec §7.)

Two ways to declare the desired state:
- **Collector registry** (the live authority): `POST /fleet/specs` (admin or `fleet-write`),
  `GET /fleet/specs`, `DELETE …`. The reconciler reads it and converges.
- **Git manifest**: edit by PR; the
  reconciler hot-reloads (`MANIFEST_REPO`/`MANIFEST_REF`).

Resource **kinds**: `container` (single), `pool` (N replicas, shard-aware), `oauth_holder`
(creds + token freshness), `account` (metadata), `producer` (heartbeat SLA), `observe_only`
(k8s-hosted — alert, never act). Reconciler gates (cautious-by-default):
`RECONCILE_DRY_RUN=1` (observe-only), `RECONCILE_ALLOW_RECREATE`, `RECONCILE_ALLOW_CREATE`,
`RECONCILE_META` (the meta layer that ensures one reconciler per tenant), `POLARIS_TENANT`.

Operate it:
```bash
python3 -m reconciler.fleet_status            # live status (ok / drift / converged)
host/fleet-up.sh                              # idempotent bring-up/recovery
```
Multi-tenant: each tenant runs its **own** scoped reconciler (container names namespaced
`<tenant>-…`, secrets resolved per-tenant); the default reconciler is the meta layer that
ensures one per tenant. Deep dives: `fleet-spec`, `fleet-reconciler`, `docs/fleet-runbook.md`.

---

## 9. Environments

Within a tenant, an **environment** is an isolated workspace (a set of stations). Envs
are isolated **by default**; sharing is an explicit **trust edge**.

```bash
curl -X POST https://<host>/environments -H "Authorization: Bearer $ADMIN" -d '{"id":"bond-portfolio","reads_from":["market-data"]}'
curl -X POST https://<host>/stations     -H "Authorization: Bearer $ADMIN" -d '{"name":"strategy","description":"…","environment":"bond-portfolio"}'
curl -X POST https://<host>/environments/bond-portfolio/trust -H "Authorization: Bearer $ADMIN" -d '{"reads_from":["market-data"]}'
```
A token scoped to an env sees only its own stations ∪ those it `reads_from` (a `GET
/events?station=…` outside that set is `403`). Pre-existing stations belong to the
`default_environment` (`software-factory`) — zero change until you create a second env.

**The environment model** turns an env's event stream into a **queryable domain model**
(the "warehouse" your loops build on): declare entity types + how events fold into them,
then query.
```bash
curl -X POST https://<host>/model/<env>/schema -H "Authorization: Bearer $ADMIN" -d '{ …entities + folds… }'  # spec: environment-model
curl       https://<host>/model/<env>/entities/<type>  -H "Authorization: Bearer $READ"   # the projection
curl       https://<host>/model/<env>/graph            -H "Authorization: Bearer $READ"   # the process graph
```

---

## 10. The whole journey on one page

1. **Install** the collector (§1) + bring up the host fleet (`fleet-up.sh`).
2. Capture the **first admin token** (§2); (optional) carve **tenants**.
3. **Bring your model** — an OAuth holder for your LLM subscription (§3).
4. **Onboard a data source** → confirm events at `GET /events` (§4). *Always first.*
5. Put credentials in the **vault** (§5).
6. Author/publish a **skill** (§6); make it persistent behind a **shim** (§7).
7. Keep it alive as a **fleet** (§8); isolate work in **environments** (§9).
8. Grow agentic automations: env model + fitness + loop → PRs you review/merge.

---

## 11. The guardrail that enforces the paradigm: `at_target`

A loop cannot declare its objective "done" unless the objective is bound to a registered
**fitness**, that **fitness signal is present in the environment** and passing, and the
loop reports satisfied — else `409` with the blockers. This is *anti-hollow-completion*:
no "done" without live, grounded evidence. It's *why you onboard data before building
skills* — there's nothing to develop against, or verify, until real data flows.

---

## 12. Go deeper (`GET /specs/<name>/latest`)

`orientation` (the agent brief) · `agent-onboarding` · `multi-tenancy` · `secret-vault` ·
`webhook-adapter` · `normalizer` · `skill-bundle` · `skill-design` · `shim` ·
`fleet-spec` · `fleet-reconciler` · `environment-model` · `improvement-loop` ·
`goal-runner`.

> **Gotchas:** tokens are tenant-scoped (work only on their tenant's host) · secrets are
> refs, never embedded · **onboard data before building skills** (the `at_target` gate) ·
> agents *propose* (PRs), humans/`fleet-write` ratify · trust runtime state (`/events`,
> `fleet_status`), not a spec's status header.
