# Runtime, session and AgentCore

What the runtime does and what AgentCore does; conversations, runs and Stop; models and providers; the vault, security and operations.

The runtime is the `soot serve` process. It accepts work, keeps conversations durable, calls AgentCore (from `github.com/2found/2ai`) to run the agent, and publishes the result. The runtime is a thin host. The model loop, retry, compaction, goals, plans and subagents live in the shared library. Soot handles what belongs to a project: configuration, credentials, durable conversation data, access control, granted tools and the process lifecycle. The sections below explain that split and its consequences: Stop, no automatic replay, the vault, and security.

## Overall model

```text
  HTTP event / conversation message / schedule
              │
              ▼
   authentication, scope, durable admission (dedup by request ID, conversations.db)
              │
              ▼
   host worker (up to `workers`) → AgentCore: model → tool → model …
              │                          (retry, fallback, compaction, goal, jobs)
              ▼
   effect receipt + separate checkpoint + public result + SSE
```

There is only one path: no separate worker for cases, no second task dispatcher, no second loop around an event. Work enters a Soot first (`event → Soot → tool`); cases and tickets are passive records and are never a required entry point.

## Who owns what

| Owned by 2ai / AgentCore | Owned by Soot (host) |
| --- | --- |
| Model loop, decoding tool arguments | Configuration: Soot definition, deployment, pack, `~/.soot/config.json` |
| Retry on transient errors, fallback between models | Provider list, models, API keys and logins (vault) |
| Compaction and summaries | Durable conversations, runs, public history, `conversations.db` |
| Memory behavior (recall, consolidation worker) | Memory scope (who may read/write) and the Bolt store that holds it |
| Goal, plan, todo, finish guard | Stop, effect fence, publication |
| Background jobs and subagents | Permission to call tools, per-operation grants, credential resolution, redaction |
| Skills (advertising, `read_skill`) | API authentication, tenant/user/Soot scope |
| Sandbox for files, shell, HTTP | Process lifecycle: serve, supervisor, reload |

Soot does not add a loop, compactor, reviewer or job manager next to AgentCore. New agent behavior is changed in 2ai and then the version in `go.mod` is bumped (currently `v0.2.5`). Project-specific behavior is built from configuration, skills and tools in packs, without touching the binary.

`internal/core/agents` assembles exactly one `preset.Full` configuration for every run. Runs inside a conversation also enable `ask`: the question is published as a normal message, and the next message resumes from the native checkpoint. Advisor is off by default.

## Concepts

- Conversation: a sequence of exchanges belonging to a `tenant/user/Soot`. Every read path and Stop checks scope; knowing an ID grants no access.
- Run: one processing turn, `queued → running → completed | failed | stopped`, or `waiting_input` when `ask` needs a person to answer. FIFO within each conversation; across conversations it follows the durable global submission order. Admission is idempotent by request ID.
- Native session: AgentCore's transcript, summary, plan, goal and loaded tool set. It is separate state, saved through checkpoints, and never exposed through the public API. Compaction only replaces what is sent to the model; the public history and the original transcript stay intact.
- Effect: an action on the outside world (file write, shell, pack operation, workspace write), with a receipt in the journal and a resource fence.
- Checkpoint: the latest resumable state of a run, in that run's own slot.

## Storage: conversations.db

`conversations.db` is SQLite (WAL, `synchronous(FULL)`, a single writer) opened by `internal/core/sqlstore`. It holds messages, runs, events, AgentCore's separate state, effect receipts and Stop records. The same data directory also has `traces.db`, `monitoring.db`, `workspace.db` and the memory store. Only one runtime process opens the store (held by `runtime.lock`); the CLI and Nest go through HTTP. Each commit is one fsync, so the number of commits per run is a cost to keep low. Progress events are batched over a few hundred ms, while messages, receipts, checkpoints and run state are always their own commits, and no event reaches a client before it is durable.

Back up with `soot backup` (consistent while running) and restore with `soot restore` (while stopped); do not copy a DB file that is being written.

## Stop, effect fence and no automatic replay

These are the most important invariants of the runtime.

Stop is written durably before cancellation. From that moment no new tool starts, and late replies and results are blocked; file writes and store writes check Stop inside the transaction that records the intent. Stop does not undo effects that already happened.

Before running, the host claims the effect in the journal, then records the result. A command cancelled midway, or a runtime that dies while running, leaves an `unknown` receipt, which keeps the fence on that exact resource across restarts. An `unknown` effect is never rerun automatically. A person with the `control` permission can view the receipt metadata and can record a resolution (checked, confirming the effect will not be undone) to allow a new intention; a resolution does not execute or replay anything.

A run interrupted while running is marked `failed` when the store is reopened. A `queued` run continues after a restart. Jobs and subagents from the earlier turn are not rebuilt. A provider error, timeout or Stop also does not retry the whole run: it continues only when the user sends another message or presses Retry.

After each model turn finishes, the runtime writes the resumable state into the run's own slot (rate-limited and size-capped; Stop blocks the write). When a run ends without an answer, that state becomes the conversation's resume point, unless a mutation with an unclear outcome remains. The resume point only takes effect the next time the user sends a message.

The deliberate exception is `execution.continue_on_limit: true`: when a run hits the turn/tool ceiling, the worker saves a checkpoint and puts the same run ID back in the queue with a fresh allowance. Only the turn/tool allowance is reissued; `run_timeout`, the goal budget, Stop and fences stay as they were, and one original run gets at most 8 slices (`continuation_limit`). It is off by default.

## Jobs, subagents and background work

AgentCore coordinates; Soot only grants permission and holds the boundary.

- Background jobs: only long-running tools accept `async: true`. A job lives within the turn and is cancelled when the turn ends, on Stop, or when the runtime shuts down.
- Every background job goes through one `job` tool whose `op` is `list`, `status`, `wait`, `cancel`, `send` (a message to a running sub-agent) or `keep`.
- `job` op `keep` lets a job live on after the reply turn, only in conversations run by the workspace itself (Nest, schedules, events), not for website visitors, the SDK or evals. It lives only in memory (`internal/core/agents/kept.go`), so a restart loses it; when it finishes, the host queues an internal turn carrying the result, with at most three such turns chained.
- Durable work (schedules, retries, cron) belongs to `internal/feature/jobs`, see [workspace.md](https://trysoot.com/docs/workspace/index.md).
- Subagents: `spawn_subagent` creates a child; `execution` limits depth and fan-out. A self-fork inherits the parent's tools and credential bindings, and each effect still goes through the root run's authorization, Stop and journal. A teammate runs with its own permissions, but Stop can still cut it off and the caller's allowlist never widens. See [agents.md](https://trysoot.com/docs/agents/index.md).

## Tools, concurrency and durable effects

A pack's tool is an executable with fixed argv. The model's input goes only to stdin, in the `soot/v1` envelope (`contract/contract.go`), and never into argv or environment variables. External tools do not receive provider configuration, history or database handles.

Calls to the same effect resource go one at a time: a later call waits within the tool timeout, costs no extra model turn, and the durable claim still checks ownership, Stop and any earlier `unknown` effect. Different resources run in parallel. A reviewed operation can narrow the resource with `resource_fields`, only when the backend guarantees consistency itself (for example the data pool, see [data.md](https://trysoot.com/docs/data/index.md)).

The ceilings on turns, tool calls, tokens and time are `execution` configuration (`soot schema deployment`). A token budget is an estimate and not a monetary guarantee: set the real limit at the provider. Results from external tools (host shell, `http_request`, `web_fetch`) are wrapped in an `<external_content>` frame so untrusted content cannot pass as an instruction.

## Models, providers and tiers

The host holds providers and API keys; the Soot picks the model. A new Soot declares no `model`; it inherits the runtime's configuration and overrides only what differs.

```text
~/.soot/config.json        providers, default model, tiers, fallback, retry, compact_at
~/.soot/credentials.json   vault: OAuth credentials after `soot login`
```

`SOOT_HOME` changes this directory. The configuration is per OS user running the process, not per workspace folder owner, so several workspaces of one user share it; a deployment can point `ai.file` at a different file. Packs contain no model or provider; a Soot definition only chooses a provider ID that the host declares. Schema: `soot schema ai`.

A tier is a name for a model configuration: `lite`, `flash`, `pro`, `max` (language) and `tts`, `search`, `imagen`. The default tier is `pro` (`config.DefaultTier`): a Soot that sets no tier runs at Pro, a new host has only one model set at Pro, and other tiers are added as needed. Nest displays Lite, Flash, Pro, Max; for Claude these correspond to Haiku, Sonnet, Opus, Fable. The order in which a model is chosen: the Soot's override, then the Soot's tier, then the host's default model.

Clients do not hardcode model IDs because the list changes every few weeks: the runtime picks the newest release of a model family from the account's real list (`config.ResolvePreset`, `internal/core/config/tier_presets.go`), and Nest only displays it.

Retry and fallback have exactly one loop, AgentCore's, around each model request; there is no second loop around the whole event.

- Transient errors (rate limit, 5xx, network) retry with jittered backoff. A key error or exhausted quota goes straight to the declared fallback, never to the demo.
- The rung that succeeds is kept for the whole run. All runs of a Soot share one `ai.FallbackLadder` for the same model chain, so later runs do not probe the primary model again once it is dead; evals use their own ladder to measure from the primary model.
- A partially emitted stream, a cancelled request or an unclear result is not replayed. Tools that already ran stay in the transcript. When the chain is exhausted, the run records the safe error `agent_run_failed` and does not expose the provider's body.

Compaction starts at the Soot's `compact_at`, else the host's, else the `SOOT_COMPACT_AT` environment variable, else 300000 tokens. It never passes the size at which a model of the chain starts billing more (Claude Haiku 5.5: 100000; GPT-5/6: 272000; Gemini Pro, Grok 4.20+: 200000), and comes earlier still if the smallest window in the model chain is smaller; the summary uses the `lite` tier when the host declares it. `soot check --show --secrets` prints the resolved models and demands a key for every selected provider, fallbacks included; if a key is missing it stops before opening state.

Each rung is sent an effort its model serves: the chosen level when the model has it, else the strongest level below it, else its weakest (GPT-5.5 `max` becomes `xhigh`, DeepSeek V4 `medium` becomes `low`, Grok 4.20 takes no level). A model outside the table gets the chosen level as is. `model_options.efforts` lists only the levels at least one model of the run serves, and `GET /v1/settings/models/{provider}` returns `efforts` per model so Settings › AI offers only the levels that model has.

The window, price step and effort levels of each model family are 2ai's tables (`ai.ContextWindowFor`, `ai.LongContextThresholdFor`, `ai.ReasoningEffortsFor`), used only where the provider's own model list says nothing; a value the provider reports always wins. 2ai's `model-catalog` skill updates them, and a 2ai pin bump brings them in; 2agent keeps no table of its own.

## Memory and model-costing background work

Automatic memory consolidation runs in a shared 2ai `ConsolidationWorker` with its own queue and deadline; it does not hold an agent slot or slow publication, and a failure leaves the evidence on disk. Memory scope belongs to the host ([data.md](https://trysoot.com/docs/data/index.md)). Background cost is traced separately from the main run.

## Credentials, vault and redaction

Credentials belong to the host, are granted per Soot and operation, resolved right before exec, and masked before the journal is written. Soot installs no global resolver over text the model writes (replies, memory, delegation).

```text
pack.json        needs:       "I need credential NAME (from: …) and env X"
deployment.json  grants.packs: "this Soot/pack is granted NAME, env [HOME]"
vault (host)     the real value, mode 0600
operation exec   resolve credential → tool env → redact output
```

- `needs` and `grants.packs`: a pack only declares what it reads from the machine and contains no values; the host grants them with `soot add`, `soot grant` or Nest. A need that is not granted blocks only the operation that reads it. Installing a pack grants nothing.
- Vault: provider OAuth credentials are in `credentials.json` (0600, directory 0700), written under a file lock across processes; login and server must use the same OS account and `SOOT_HOME`. Tool credentials are stored separately per Soot. The 2ai `credential` package is the in-memory secret store and the `{{cred:NAME}}` syntax; the on-disk store is `internal/core/credentials`.
- <a id="kho-khóa"></a>Kho khóa (Nest › Cài đặt › Kho khóa) is one list of every key the workspace holds or is missing: each Soot's tool keys, keys for connecting to another server, keys of AI services and chat bots (viewed there, entered under AI and Kênh), and non-secret configuration values. Each row says what the key is for, who uses it, whether it is set, when it was set and when it was last used; you can add, replace, check and delete. What this vault commits to, and the code that backs it: - Each key is its own file (0600) in a directory only the account running Soot can read (0700), written atomically. Without a master key, keys sit in plain text as before; with a master key, every key is encrypted on disk (see "Encryption at rest (master key)" just below). `GET /v1/settings/tool-credentials` returns `protection.private` (whether the directory really is 0700), `protection.encrypted` (`true` when a usable master key exists and no key is left in plain text) and the fields added in the section below, so Nest says only what the server reports. - Nest cannot read a value back. Each key returns its state, `set_at` (the file's modification time), `last_used_at` (the last time a tool read it, written at most once a minute to a side file `<key>.used`, removed when a new value is set or the key is deleted) and `fingerprint` (the first 6 hex characters of a SHA-256 with its own prefix, only to tell two keys apart). - A key is read only when the tool that needs it runs; it goes into the tool's environment, not into the conversation, and is masked in the journal (the Redaction item). - Every add, replace or delete is written to `<data_dir>/vault-audit.jsonl` (who, what, which key, when; never a value). Each row of `GET /v1/settings/tool-credentials` has `change` (the last change), and `GET /v1/settings/tool-credentials/history?soot=&name=` returns the last 20 changes at most. Not available yet: an expiry date for a key pasted by hand. - A pack can declare `needs.credentials.NAME.check` as the name of one of its own read-only tools (`validateNeeds` rejects a name that does not exist, code `invalid_credential_check`); the runtime returns it as `check` (an operation id) and Nest shows a "Kiểm tra" ("Check") button that calls that tool through `POST /v1/tools/call`. A key that declares no `check` has no button, and Nest keeps no table of any project's keys.
- **Encryption at rest (master key).** The `internal/core/seal` package encrypts each key with AES-256-GCM under a 32-byte master key that the operator keeps separately. - **What is encrypted.** A Soot's tool keys (`tool-credentials/<soot>/<NAME>`), keys for connecting to another server (`tool-credentials/_remote/<id>`), keys of tools a Soot or team wrote itself (`written-tool-credentials/<soot|team>/<id>/<NAME>`; the `<NAME>.hosts` file beside it holds only allowed addresses, so it stays plain text), the provider login vault (`credentials.json`), the chat bot token vault (`<data_dir>/channels/credentials.json`), the operator's OAuth clients (`oauth-clients/<provider>.json`) and the MAC key of the idempotency mechanism (`credential-effects/v1/mac-key`). Each ciphertext is bound to its kind, owner and name (AAD): copying a file to another name or another Soot does not open it. - **What is not encrypted.** `env` values in `deployment.json` (not secrets), tokens and keys stored only as hashes, the `.used` and `.sign-in` marker files (they hold no secrets), and the Nest-side connection store of admin keys on the user's machine (outside the runtime's scope). The server status returns a count of keys by kind (`protection.kinds`), so you can see where plain text remains. - **Format.** One line, `soot-seal:v1:<key id>:<base64url(nonce||ciphertext)>`. The `key id` is the first 6 bytes of a SHA-256 of the master key with its own prefix, only to tell which key encrypted it, without revealing it. The AES subkey is derived with HKDF-SHA256 (standard library), with a random 12-byte nonce. - **Where the master key lives.** The variable `SOOT_MASTER_KEY` (value `soot-mk1-…`) or `SOOT_MASTER_KEY_FILE` (a path to a 0600 file), set in the service's env file (main VM: `/etc/soot-lohi/soot.env`). On a Mac, if neither is set, the runtime reads the file `soot/master.key` in the user's configuration directory (`~/Library/Application Support/soot/master.key`), outside `~/.soot`. The master key must **never** sit in the directory it protects (the credentials, data or workspace directory): the runtime refuses that location (`inside_data_folder`), and so does `soot vault init --file`. The key source sits behind a small interface (`seal.KeySource`); adding Keychain or Secret Manager later means adding one file and changing nothing else. - **Turning it on.** On the server: `soot vault init` prints one line, `SOOT_MASTER_KEY=…` (it writes nothing anywhere), to paste into the service's env file, or `soot vault init --file /path/to/master.key` (or `--default-file` on a Mac) writes the key to a 0600 file. Restart Soot: when `serve` runs, every plain-text key is encrypted file by file (atomically, keeping its set time, safe to rerun if interrupted midway) and each file is recorded as `sealed` in the change log. Keys written after the master key exists are all encrypted. `soot vault status` shows the state without printing a key. - **Lost or wrong master key.** Soot keeps running. An encrypted value reports "locked" (`locked`), a tool that needs it fails with a clear error and reveals nothing, and the check and fingerprint of that key are empty. Soot does not overwrite: while any encrypted key cannot be opened, every add or replace of a key is refused (HTTP 409 `vault_locked`; `vault_key_invalid` when a master key is set but unusable); only deleting still works. Set the right master key again and restart, and everything opens again. - **Backup.** Keep a copy of the master key somewhere other than the data (the owner's password vault). **Losing the master key loses every stored key**; there is no recovery, only entering each key again. Back up `<data_dir>/vault-audit.jsonl` too. - **What it blocks and what it does not.** It blocks reading keys from a copy of the directory, a backup, a disk image, or a single leaked file. It does not block someone who has already got into the account running Soot (who can read both the master key in the process environment and the env file), or someone with root on the server. The change log is append-only through the API but not tamper-proof: whoever can write to `data_dir` can edit it. - **Server status.** `protection.state` is `off` (no master key), `on`, `mixed` (a master key exists but some keys are still plain text), `locked` (there are encrypted keys that cannot be opened; `lock_reason`: `no_key`, `wrong_key`, `key_invalid`) or `key_invalid` (`key_problem`: `malformed`, `unreadable`, `inside_data_folder`), with `key_source` (`kind`, `via`), `key_id`, `counts`, `kinds`, `recorded`. Each key row also has `sealed` and `locked`. - **Other callers.** `seal.Seal/Open` and `seal.WriteFile/ReadFile` accept any (scope, owner, name, value), so a new store (for example owner-bound keys of a self-written tool) only needs one call each way, and uses `operations.StoreWritable` to refuse a plain-text write into a store that already holds encrypted files.
- Redaction masks before the journal, including encoded forms of a secret (JSON, URL, base64) and every host environment variable the tool inherits through `needs.env`.
- Telemetry and logs contain only identifiers, enums and counts, through an allowlist (`internal/core/agents/telemetry_attributes.go`); prompts and tool results never leave the process.
- Principal token: every tool call in a conversation on a channel that knows the user carries a short-lived signed token that the model can neither see nor choose (principal-token).

Do not commit keys, tokens, the vault, `.env` or the runtime's databases.

## Security model

A workspace is not a sandbox. The workspace directory, file permissions, API scopes and hashed keys do not isolate a tool from the operating system or protect secrets from the same UID, root or process memory.

- Shell on the host is an explicit grant. `bash` runs under the same UID as the runtime: it can read the connection store, call the `soot` CLI, edit `deployment.json`, and get past Lead's approval gate. Do not grant it to a Soot that handles untrusted content.
- The `execution.sandbox` backend `docker` runs each command in a single-use container: only the workspace is mounted, root is read-only, the host environment is not inherited, and there is no network by default. If Docker fails, the command fails; it never runs on the host instead. File tools and pack operations still run on the host.
- Prompt injection is a real risk. The boundary is the permission granted, not a "do not do X" sentence in the prompt; only removing the grant removes the tool.
- Public web uses the same AgentCore but is a separate credential boundary, assigned only to Soots with no shell or privileged tools.

The API credential types are not interchangeable: operator (Nest, CLI); the `conversation_clients` token (a project's backend); the fixed-user key from `soot auth issue` (one end user); the member key `conversations:read_team` (view teammates' work, read-only); the publishable `spk_…` and visitor `svs_…` (websites). A valid key calling an operator-only route gets 403; an unknown or revoked token gets 401. Client side: [surfaces.md](https://trysoot.com/docs/surfaces/index.md).

## Each runtime does its own work

The target shape: one workspace, n Nests, m runtimes (laptops and VMs) working together.

```text
   workspace
      ├── Nest A  ┐
      ├── Nest B  ├──(HTTP, with the user's permissions)──┐
      └── Nest C  ┘                                       ▼
                                                runtime 1 (laptop)
                                                runtime 2 (VM) … m
```

- A runtime on a laptop is treated exactly like a runtime on a server: same contract, obligations and admission. All Nests are equal; permissions are decided per user, not per machine.
- A Nest does not do a runtime's work: it does not run schedules, check-ins, sync or tools on its behalf, and does not point `--config` at another runtime.
- A runtime does not do another runtime's work. If something cannot run (missing interpreter, pack, grant, credential), fix that runtime instead of moving the work elsewhere.
- The only exception is a request from the user themselves through Lead ([agents.md](https://trysoot.com/docs/agents/index.md)).
- Sending work to a team on another runtime asks that runtime to do it, it does not do the work for it: the work runs on the team's runtime, under the limits and budget there (sections below).

### Starting a piece of work sends it

Every start of work assigned to a Soot or a team (the Bắt đầu button in Nest, `POST /v1/workspace/tasks/{id}/start`, MCP `task_start`, `soot tasks start`, op `start` from Lead or a team's Đầu mối) takes the same path as `send` (plans/work-mail.md):

- The work gets one mail, its sender is whoever pressed start (or the Soot that called `start`), and the reply returns to them: a card on the work for a person, a note in the thread for a Soot. Starting again runs again under the same mail, one reply per run.
- The same limits as `send` apply. A start the limits would hold is refused with that code (`mail_loop`; a team without a Đầu mối still answers "no Đầu mối"), and the work stays as it is for a person.
- Work assigned to a team on another runtime is sent there. Work that ran on another runtime and already has its reply cannot be started again from here: send it as new work.
- A person pressing Bắt đầu on a held mail (`inbox_hold`, `mail_rate_limited`, `mail_loop`, a send to another runtime that was refused) opens that mail: the work runs and the reply goes to the original sender. A Soot cannot open a mail held for `mail_loop`.
- Schedule fires, jobs and a mail the host retries once its team has a Đầu mối still take the old path.

The reply of a mail:

- A run that stops to ask a person (`report_blocker`) replies `needs_person` and the mail stays open. Once the person answers in the work's thread, the next run finishes the work and the real reply returns to the sender. If the blocker is marked handled (or the thread has moved to other work), the mail replies `failed` with reason `run_blocked` instead of waiting forever.
- The reply is written with the mail in one write. If the note cannot enter the sender's thread (the thread is full of pending work), the host retries every 2 seconds, doubling up to 5 minutes, at most 20 times, and it lands once. When the tries run out or the thread is gone, the work gets a `mail_reply_undelivered` line.
- `budget_tokens` counts weighted tokens (like the team and Soot budgets, and like `tokens` in the reply), not raw tokens.
- When a Soot's daily budget is spent, the reply is `blocked`, `daily_tokens_exhausted`, whether the run was refused at the start or stopped midway.

### Sending work to another runtime

A `remote {runtime, group}` group takes work like a team here (`send`, [workspace.md](https://trysoot.com/docs/workspace/index.md)). The two runtimes speak `team-mail.v1` (contracts/team-mail.md); the side that has `remotes.<id>.url` makes every call, in both directions, because a server usually cannot call a Mac.

- The called side issues a peer key named exactly the id it gave the caller, with the reserved item `mail`: `soot auth issue --peer a --groups growth --contract-items mail`. Without `mail` for that team: `403 mail_not_granted`.
- The caller records a mirror and sends `POST /v1/teams/{team}/mail`. If it cannot reach the other side, the mirror stays at `delivery: pending` and is sent again every 30 seconds, doubling up to 10 minutes, with the same `request_id`, so the other side has one piece of work. If it is refused outright (no permission, no such team, an older runtime without `team-mail.v1` answers `mail_unsupported`), the work stops with that code and a `mail_undelivered` card appears at once.
- The caller reads `GET /v1/teams/mail/outbox`: the state and `reply` of the work it sent, and work the other side sent to its teams. It then reports the state of that work (`POST /v1/teams/mail/report`). It reads every minute while work is open and slows to every 10 minutes when idle; `POST /v1/workspace/mail/sync` reads at once.
- A side that cannot call (a Mac behind NAT) declares `remotes.<id>: {"pull_only": true}`, and the other side's team is a `remote` group as usual; work it sends waits in the outbox to be read.
- `url` is https only, or http to a loopback address (two runtimes on one machine).
- `remotes.<id>.name` (optional, at most 80 bytes, no leading or trailing space, no control characters) is the name people read: a Cần bạn card says "Máy chủ <name>", `/v1/workspace` returns it in `remote_names` beside `remote_urls`, and Nest calls that server by this name before it is connected to it. Routing, keys and payloads still use the id.

Work from another runtime never carries a person's permissions: it always passes the limits, its input is framed as outside content, and a `project` the receiving runtime does not know is dropped. The limits do not trust the mail's body:

- The daily bound counts by the sending runtime (`peer:<id>`), whatever team the mail names. After an upgrade, mail recorded under the old key is not counted for the first 24 hours.
- A mail's `hops` is at least one more than the highest hop count of the mail this runtime has open on that runtime, even if the body says less. Unrelated work that arrives while a chain is open is also counted as the chain's next step; a held mail is for a person to decide.

### Moving a team to another runtime

A team runs on exactly one runtime; to run it elsewhere you move the whole team, and there is no "home" runtime. Nest: Đội Soot › team › ⋯ › Chuyển sang máy chủ khác…; CLI: `soot teams move <team> --to <connection> [--from <connection>] [--dry-run]`. It needs Admin on both runtimes (capability `team-move.v1` in `GET /v1/runtime`).

1. The old runtime packs the team (`POST /v1/settings/teams/{id}/export`): Soot definitions, the team, data permissions, collaboration limits, schedules; the tables, tasks, recurring tasks, goals, files and memory of the team and of each Soot; the people with access to the team, with their person ids and approval rights. One `tar.gz`, each part with its SHA-256.
2. The new runtime takes the bundle by its SHA-256 (`PUT /v1/settings/teams/imports/{sha}`) and returns a preview: what moves, what stays (chat history, keys), and what blocks, with how to fix it (a clashing id, a missing pack or tier, an operation or check address the new runtime has not declared, a Soot still in another team or acting as Lead, a team with a channel, website, route or repo source, a new runtime config edited by hand and not yet reviewed, in which case it refuses every save).
3. Data arrives with its original ids (`POST …/imports/{sha}/data`). Each part has a completion mark; running it again adds no copies, and an item with the same id but different content is `import_conflict`.
4. `team.import` saves the team into the new runtime's settings; the preview moves to `saved`. Nest (or the CLI) calls `config.activate`; the new runtime turns the team on at its next idle moment, after running work, and the preview moves to `done`. Saved but not turned on is not yet `done`.
5. Only then does the old runtime run `team.retire` with `moved_to {runtime, import}`, then `config.activate`: the team's Soots are archived, recurring tasks stop and the team leaves the settings. No data is deleted.

The bundle is a snapshot at packing time: what the team writes on the old runtime after that stays there (the preview says so). A move interrupted midway is resumed by running the same command again, or with Tiếp tục in Nest: the same bundle is reused and parts already imported are not imported twice. The new runtime keeps the bundle for one day; after that a fully imported bundle keeps only the small part needed to confirm it, and a bundle with nothing imported is deleted.

Keys and connection passwords never leave the runtime: the preview lists each key to enter again on the new runtime. Members keep their person ids and permissions; each of their devices reconnects once with a `soot pair --for <key>` link (Nest prepares it in the last step). Code: `internal/core/teammove`, `internal/core/workspace/portable.go`, `internal/core/management/actions_team_move.go`.

## Local process lifecycle and operations

`soot serve` is one runtime serving every Soot of a deployment. On a personal machine, the user's supervisor (`cmd/soot/service.go`, `soot service run`) only keeps the process alive and never sends or replays work: `soot spawn` registers the workspace and starts it in the background, and `soot run` wakes it. Each deployment runs as `serve --watch --stop-file …`, a failed child is retried with backoff, and the supervisor reuses an external runtime without taking ownership of it. A file lock (`internal/core/hostio`) serializes startup. A graceful stop uses a marker file or `SIGTERM`; stopping a workspace lasts until an explicit start/run.

Reload goes through a single path. `--watch` or `SIGHUP` validates the new configuration and loads it when the runtime is idle; a bad fix is rejected and the old runtime keeps running. A save from Nest goes through activation with drain (block new admission, wait for running work), so chat and memory are not lost. Changing the listener, state dir, provider, credential or removing a Soot needs a deliberate restart. A restart serves the activated revision, not the contents of the file. Configuration state with a generation and journal is kept by `internal/core/configstate`.

Long-running operation has several parts:

- Monitoring (`/v1/monitoring/*`) is a passive operational projection for operators only: safe IDs, estimated cost, no prompts, tool arguments or credentials. `/healthz` and `/readyz` speak only for Soot itself; health checks of other services live in packs, not in the core. Traces can be exported over OTLP through the same allowlist. `/v1/monitoring/metrics` takes `group_by` as one dimension (`total`, `agent`, `status`, `provider`, `model`, `category`) or up to three different dimensions separated by commas (`status,agent,model`, without `agent=`): each series then carries `group` as its dimension, each dimension is counted and limited as a separate read, but the whole read costs one turn in the metrics read limit (2 turns a minute per key). Kết quả › Chi phí ("Results › Cost") reads the chart, the per-Soot card and the per-model card with one such read.
- Configuration release: a Soot is config. The author runs `soot release` to produce an artifact, the target machine runs `soot update` to stage it, and the runtime applies it by itself when idle (block admission, apply with a journal that can roll back). Running work is not cancelled; a merge against a baseline keeps the user's own changes. The artifact contains no credentials, DB or deployment. Updating the binary is a separate matter (`internal/feature/selfupdate`).
- Reproducible Linux runtime package (`deploy/runtime`): a static executable, BusyBox, Node.js, a pinned TLS bundle; no credentials or state.
- On a VM, the supervisor runs as a systemd unit (`deploy/soot.service`, `SOOT_SERVICE_NEST=off`). 2server handles server lifecycle and rollout; Soot handles the runtime, config and state. A source refresh does not activate by itself.

Performance: an idle runtime uses close to 0 CPU even with `--watch`; Nest open all day on a laptop must stay light; message admission and polled GETs have a p95 under one second. Signals: the `http_route_stats` log every 60 seconds, pprof on loopback only (`SOOT_PPROF`), the `scripts/perf` and `desktop/qa/perf` harnesses; measure before fixing. Known traps: Cloudflare returns 403 for a script's default User-Agent; SQLite commits are expensive, so count commits per operation and not statements; WKWebView does not report `hidden` when the window is behind others; Nest's idle CPU is the number of React commits times the number of rows. Work inbox (Hộp việc): usable within 1 s with 2,000 conversations; a thread shows the newest message within 300 ms at any length; scrolling and streaming at 60 fps; every keystroke under 50 ms; idle sends almost no requests; heap after GC stays flat. Measure on the production build (`vite preview`), not the dev server. Traps: the runtime does not gzip on loopback, so lab bytes are uncompressed bytes (send `X-Forwarded-For` to measure gzip bytes, about 6-12 % of the raw bytes); `vite preview` is HTTP/1.1 (6 sockets per host, SSE holds a socket), so the request wave in the lab looks worse than under HTTP/2 while the serial depth is right; each run reopens the whole transcript in 2ai (BG-4), so seeding a long thread gets slower. Log: 2026-11-14 work-inbox, lab, Problem (long threads and typing) → `.babysit/perf-audit/2026-11-14-work-inbox/`; after the fix (lab, same day, `verify.md`): opening a 500-message thread 855 → 118-126 ms (Chromium) and 837 → 242 ms (WebKit), a 4,373-message thread shows the newest message after 174-182 ms (Chromium) and 274 ms (WebKit, where it never showed before); every keystroke ≤ 32 ms; DOM 44.6k → 6.2k nodes; idle 39 → 4-10 requests a minute; boot reads neither `/messages` nor `/events` before the Work inbox is usable; a new need appears within one `attention` tick. Pinned by `desktop/qa/perf/lane` (the cases `thread-*`, `boot-usable`, `idle-minute`, `need-wake`, `attention-get`, `runs-read`). First connection to a remote server (round 3, 2026-11-14): Nest gathers GETs asked at the same time into one `GET /v1/reads` (at most 24 reads, each read going through exactly the same handler and permissions as a direct call; `work-reads` §4), and `GET /v1/runtime` is also the probe for address, key and API. Lab RTT 210 ms (Chromium): the Work inbox is usable after 1,954-1,986 → 530-566 ms, the serial chain 6-7 → 2 steps, 32-33 → 4-5 requests before usable. The event history (`/events`) no longer repeats message content: `message.completed` carries only `message_id`, the answer's delta is deleted when the answer is saved; only the stream still carries message content (`work-reads` §5). Log: `.babysit/perf-audit/2026-11-14-work-inbox/round3-runtime.md`. Extension screens (from packs and written by a Soot): Nest opens a frame only when it is near the screen, at most 4 frames at a time and 8 live frames in each place, reusing a session that is still valid; every open and call goes through one queue per server (6 jobs at a time, waiting on `Retry-After` when busy); the kit is one shared, immutable copy; a frame out of view reads no data; the runtime budget is in `nest-extensions` §3. Re-measured 2026-11-14 (WebKit, lab, production build; before = snapshot 9e35fc9e, after = tip; median and range of 5 runs, load recorded beside it in `.babysit/perf-audit/2026-11-14-system/verify/report.md`): with 40 screens on the Work inbox, the inbox is usable after 1,171 → 429 ms, opens 40 → 3 sessions and 240 → 16 requests, the kit loads 80 → 2 times, WebContent 337 → 234 MB, returning to the Work inbox opens 40 → 0 sessions, switching light/dark theme 34 → 8 ms. The 21st screen costs about +3.6 ms and adds no request or frame until you scroll near it. Not met: 40 screens are still 1.87 times slower than 0 screens (goal 1.2). Every night `cd desktop && pnpm perf:lane` (`desktop/qa/perf/lane/`) counts these numbers and fails when one passes its threshold; timings are only recorded, not blocking.

## Repository independence

The `2found/2agent` repository holds the Soot project and the `soot` CLI, as one Go module of the same name. Shared foundations are pinned by version in `go.mod`: `github.com/2found/2ai` (currently `v0.4.1`) handles AI, AgentCore, telemetry, credentials, sandbox and JSON primitives; Soot handles the host and project data.

- New source, assets, templates and docs do not depend on a neighboring checkout; shared code needs a versioned dependency or an installed copy in the repo.
- Do not commit a local `replace` or `go.work` (parallel development with 2ai uses an uncommitted local workspace). When a dependency changes, build and test from an independent checkout; a private dependency needs `GOPRIVATE=github.com/2found/*`.
- Desktop uses `@tofound/ui` from npm. Shared packs live in [Soot Forge](https://github.com/2found/soot-forge); `contrib/` holds the SDK and examples.

## Where it lives in the code

| Part | Path |
| --- | --- |
| Serve, reload, supervisor | `cmd/soot/main.go`, `cmd/soot/service.go` |
| Lifecycle, event admission, schedules (trace, job and monitoring stores through interfaces) | `internal/core/runtime/`, `internal/core/ledger/` |
| Run queue, Stop, checkpoint, effects | `internal/core/conversation/` |
| AgentCore (one configuration), composition root | `internal/core/agents/compose.go`, `internal/compose/app/` |
| SQLite store | `internal/core/sqlstore/` |
| Operations, grants, journal; providers, vault | `internal/core/operations/`, `internal/core/toolrun/`, `internal/core/providers/`, `internal/core/credentials/` |
| Models, tiers; saved configuration, activation, release | `internal/core/config/`, `internal/core/configstate/` |
| HTTP, authentication | `internal/core/transport/httpapi/` |
| Core and feature boundary | `docs/contracts/core-layering/layers.json`, `internal/compose/app/layering_test.go` |

Transport only parses, authenticates and calls services; `internal/core/domain` depends on no HTTP, OS, provider or storage; the core does not import `contrib/`. The architecture tests in `internal/compose/app/` keep these boundaries.
