# Agent Portability: Reference Implementation Architecture

*If we built Agent Portability from scratch, this is what we would build.*

**Status:** Proposed reference architecture for discussion. This document makes concrete design choices from the Agent Portability Requirements; it is not an adopted PAA standard. Requirements remain the source of what must be true. This document describes one coherent implementation that aims to make those requirements real.

## The product in one sentence

A person owns a portable memory bundle containing their agents, work, policies, connections, schedules and recoverable task state; replaceable services operate on that bundle through narrow, authenticated interfaces, while secrets remain encrypted and usable only through an authorization broker.

The goal is not identical model output on every machine. The goal is that moving or replacing a component does not lose the owner's work, identity, decisions or control, and that any unavailable capability is explained before it causes silent failure.

## Design decisions

This design makes the following choices so implementation can begin without pretending every choice is still open.

1. **Your Memory is the durable source of truth.** Services may cache or index data, but anything whose loss changes the owner's work, authority, identity, connections or unfinished obligations is represented in Your Memory and can be reconstructed or restored from it.
2. **Memory is a local, owner-readable folder first.** Durable owner content is stored as ordinary UTF-8 Markdown and files in a documented directory, with small JSON sidecars only for machine-managed state that Markdown cannot safely represent. The folder itself is the source of truth and canonical interchange. The first local implementation uses no database. Search indexes can be built in memory from files; coordination state is stored in versioned JSON with atomic updates and a single-writer lock. If performance later warrants a database cache, it lives outside Memory in app-managed storage, is disposable, and is never required to read, own, back up or move Memory.
3. **The owner has a recovery key.** Secret material is encrypted with a random Memory data key; that key is wrapped by one or more owner-controlled recovery methods (passphrase-derived key, hardware-backed key, or both). The recovery method is never stored inside the bundle. Losing every recovery method means secrets cannot be recovered; the system says so plainly.
4. **Auth is replaceable but privileged.** Auth is the policy enforcement point, not the owner of policy. It reads protected records and authorizes actions. A replacement Auth is trusted by an explicit owner recovery ceremony that rotates its signing key and records the change in the audit history.
5. **No component receives broad raw credentials.** A connection broker executes an approved operation itself, or issues the narrowest short-lived credential the external service supports. Raw refresh tokens are never returned to an agent or model.
6. **Agent packages are declarative and inert until activated.** A package declares identity, files, dependencies, effects, data handling and requested capabilities. Installation inspects and validates content without running it; owner grants are separate records and never arrive inside the package.
7. **Structured operations are portable; implementation code is replaceable.** Runtime engines, schedulers, databases, tool protocols and UI frameworks are adapters. Portable task journals and action receipts define recovery meaning independently of those engines.
8. **Consequential external actions use prepare, authorize, execute, reconcile.** Exactly-once execution cannot be promised across arbitrary external services. The system prevents duplicate logical work where possible and reconciles uncertain outcomes before retrying.
9. **A share is an explicit filtered copy.** It carries selected agent definition and selected owner data, with provenance. It never carries grants, credentials, private data or active schedules by default.
10. **Compatibility is checked continuously.** Installation, updates, model/provider changes, tool-source changes and component replacement all produce a readiness report against the same declared requirements.

## System shape
The implementation is a local desktop product. Rust/Tauri provides the native app shell and manages application lifecycle; React is the owner-facing interface. The app starts and supervises the local agent runtime, keeps its data in the application-managed Memory location, and presents setup, permissions, approvals, connections, tasks, backup, and restore through guided screens.

The logical PAA components remain distinct in their contracts, but the first local implementation does not deploy them as a fleet of services:

- **Your Memory:** Markdown, JSON, ordinary owner files, and encrypted secret envelopes in the app-managed local Memory folder.
- **Gateway:** a local-only API boundary used by the desktop app and authorized local integrations; it is not exposed publicly by default.
- **Auth:** evaluates owner and agent authority and records approvals in protected Memory records.
- **Agent Loop:** the bundled runtime that interprets agent definitions, calls BrainDrive Models and tools, and writes durable progress.
- **Connection broker:** a restricted local capability for using encrypted provider credentials without returning raw tokens to the Agent Loop or model.
- **Adapters:** MCP, model-service and external-service integrations behind the portable capability contracts.

```text
Owner
  |
React UI inside Rust/Tauri desktop app
  | starts, supervises, and authenticates to
Bundled local agent runtime
  |-- Gateway / Auth / Agent Loop
  |-- authorized connection-broker interface
  |-- MCP and other adapters
  |-- Your Memory (app-managed local files)
  |
  +---- BrainDrive Models service (curated model selection)
  +---- owner-approved external services
```

The local runtime binds only to loopback or uses operating-system local IPC, with a per-launch credential so another local process cannot call it anonymously. The Tauri app hides process management and reports health in the UI. Owners do not install Node, Docker, a database, or a separate service.

The model experience is BrainDrive Models: BrainDrive chooses and tests the underlying models; LiteLLM stays internal to that service. Other provider adapters are optional compatibility paths, not the default setup flow.
## Your Memory layout and contract

A reference directory layout:

```text
memory/
  memory.json                  # format version, stable Memory ID, feature profile
  agents/<installation-id>/    # installed definition plus owner customizations
  work/                        # conversations, documents, journals, durable task state
  policies/                    # protected actor, grant, approval and limit records
  connections/                 # protected provider, scope, owner and lifecycle records
  schedules/                   # portable schedule and event-subscription definitions
  audit/                       # append-only signed event records
  exports/                     # optional owner-created export manifests
  indexes/                     # optional derived files; source labels retained
  secret-store/                # encrypted envelopes only; excluded from generic tools
```

Owner-facing durable content is Markdown wherever that remains clear to a person: agent instructions, conversations, notes, task summaries, schedules and policy explanations. Small machine-managed JSON files hold IDs, grants, connection metadata, task execution state, receipts and other records needing strict schemas. Every durable object has a stable ID, schema version, provenance, sharing classification and migration rules; names and paths are not identities. Writers use write-to-temp, fsync and atomic rename, plus lock files for protected records. A crash leaves the old complete file or the new complete file, never a half-written policy. The application validates structured files on read and preserves unknown optional fields.

The Memory folder is already the portable bundle: a person can browse it, copy it, and open its Markdown without the application. A packaged backup adds a manifest, integrity hashes, and optionally a full encryption wrapper. It excludes rebuildable indexes and caches, which are regenerated from their sources. The manifest lists included, omitted and unsupported items and says whether encrypted credentials are present and restorable. Sync services can copy the folder, but the app detects concurrent/conflicting edits and does not claim safe simultaneous multi-device writing.

### Data classes

| Class | Examples | Access and movement |
|---|---|---|
| Shareable | Agent definition, public skills, declared requirements | Eligible for a filtered copy after owner review |
| Private | Conversations, personal files, task journals | Remains with owner; selected items can be shared explicitly |
| Protected | Actor registry, grants, approval rules, connection metadata | Auth-only mutation; carried in owner-controlled backup, never agent-readable |
| Never disclosed | API keys, OAuth refresh tokens, signing keys | Separately encrypted; broker-only use; never in logs, search or shared copies |
| Derived | Embeddings, indexes, caches | Rebuildable; classification and provenance inherited from source |

Mixed-source derived records take the most restrictive source classification. Classification cannot be lowered by an agent. An owner may create a new reviewed derivative or explicit share copy, with lineage and the transformation recorded.

## Agent definition, package and lifecycle

An agent installation consists of a versioned definition plus owner-specific state. The definition is a copy of a publisher's package; local customization is stored as an overlay, not silently written back to the publisher's content.

The minimum manifest contains:

- stable definition ID, publisher ID, version, package format version, integrity digest and provenance;
- purpose, entry-point instructions, skills/resources, and all referenced files;
- required and optional model capabilities, tools, memory scopes, execution features, channels and dependent agents;
- declared external effects, data classes read/written, destinations and retention;
- requested permissions in terms of actions and scopes, never grants;
- optional schedules and triggers, disabled on import;
- compatibility ranges, explicit degraded modes and typed reasons for incompatibility;
- migration and rollback instructions for owner data, if any.

The manifest is validated against a published schema before content is activated. Unknown required fields fail closed; unknown optional fields are preserved on round-trip. References are pinned to versions and integrity digests. A package with executable content is isolated and subject to the same trust and permission checks as any third-party tool.

Lifecycle is explicit: discovered → inspected → installed → ready/limited → active → paused/disabled → removed. Updates repeat inspection and readiness checks, show changes in permissions, effects, data handling and migrations, and preserve a rollback point. Removing an agent revokes its authority and stops new work; owner data and audit records are retained unless the owner separately deletes them.

A shared or imported copy keeps definition and publisher identity, receives a new installation ID and actor identity, and starts with no grants, no connections, and no active schedules. Imported definitions are not promoted to built-in trust.

## Identity and authority

The system distinguishes definition, publisher, installation, actor, session and owner identities. The actor is the security principal for an installed agent. Actor keys may rotate while the actor ID stays stable; rotation is an audited Auth operation.

Policy records live in the protected area of Your Memory. Auth evaluates:

`Actor + Action + Resource + Context → Allow | Deny | Approval required`

Context includes purpose, data classification, destination, current grant, owner/session state, limits, expiry and delegation chain. Unknown conditions deny. A tool or broker independently checks the authorization decision at the point of effect, so prompt text cannot grant authority and a compromised Agent Loop cannot turn a broad prompt into an external action.

Owner administration requires a distinct owner session, not an agent session acting for the owner. The owner can require a hardware key or other step-up proof for policy changes, recovery, connection setup and sharing. The initial policy model uses explicit action/scope grants and a small deterministic evaluator; a more capable policy engine can be substituted behind the same decision interface.

Delegation carries the originating actor and constrained operation through every hop. The effective authority is no greater than the intersection of each actor's authority and the explicit delegation. Re-delegation is denied unless expressly allowed.

For money or other bounded impact, Auth creates a reservation before execution. Reservations count against limits until settled, released, or expired after reconciliation. Concurrent requests cannot each observe the same remaining balance and overrun a limit.

## Connections and secret use

A connection record identifies the provider, account, owner, granted scopes, approved actors/actions, lifecycle, provider-side constraints, redirect or webhook bindings, and last health check. The record contains no usable credential. Secret envelopes hold encrypted token material and metadata needed by the broker.

The broker exposes operations, not a general-purpose token read. An adapter requests a specific operation with actor, resource, destination and idempotency key. Auth authorizes it; the broker executes it or returns a narrow, short-lived token where execution must occur elsewhere. Responses are filtered to the minimum needed by the caller. Logs record decision and outcome metadata, never token values or sensitive payloads.

When a Memory is moved, the owner restores the secret key and the broker checks provider constraints. Some providers bind credentials to a client registration, device, audience or region. In those cases, the readiness report identifies the affected connection and exact reauthorization step; the connection is not silently represented as healthy. Revocation disables local use immediately and asks the provider to revoke remotely where supported.

## Model and tool portability

The model interface is capability-based, not provider-shaped. An agent declares abilities such as text generation, vision, structured output, tool calling and context requirements. A provider adapter reports its supported abilities and relevant limits. The compatibility checker runs on install and whenever model/provider configuration changes. A mismatch either blocks a required function or activates an explicitly declared limited mode; no silent substitution is allowed.

Provider-hosted threads, files and hidden state are not authoritative. Conversation and durable context live in Your Memory; requests to a model are assembled from authorized context for each call. Provider adapters redact and minimize data according to policy, and the owner can inspect which data classes may leave the system.

Tools have stable capability IDs and versioned input/output schemas, plus declared effects, authority, timeout, idempotency and failure behavior. Protocols such as MCP are supported through adapters. A tool being discoverable does not mean it is installed, compatible or authorized. The readiness checker verifies all three independently. Tool failure cannot corrupt durable memory; side effects have receipts or an explicit unknown outcome.

## Execution and durable work

The Agent Loop may use any orchestration framework, but the portable journal defines task meaning. A task record contains task ID, installation/actor/session IDs, goal, status, timestamps, checkpoints, referenced inputs, pending operation, completed step receipts, retry state and required capabilities. Sensitive content is referenced by Memory object ID and access policy rather than copied into a runtime's private state.

Before a consequential external action, the runtime writes an intent record. Auth checks policy and any required owner approval. The adapter executes with an idempotency key when supported and records a receipt. If the process crashes after the service may have acted but before a receipt is committed, the task enters `outcome_unknown`; recovery queries the service or presents the ambiguity to the owner before retry. The system never guesses that the action failed and blindly repeats it.

Checkpoint and journal formats are versioned and engine-neutral. Runtime-specific workflow state can be stored as disposable acceleration data only if the portable journal is sufficient to resume safely or explain why resumption is unavailable. A replaced runtime must inspect in-progress tasks and either resume, safely pause, or report the precise missing capability.

## Scheduling and event triggers
Schedule definitions live in Your Memory and include agent installation, recurrence, time zone, active state, missed-run behavior, concurrency policy, expiry, and required authorization. Store recurrence in an open format such as RFC 5545 RRULE, with explicit timezone identifiers.

For the first local release, the app-managed scheduler runs only while the desktop runtime is available. The UI shows whether the app must remain open, which runs were skipped, and how the missed-run rule applies. Do not promise unattended execution while the computer or app is off. A later release may integrate operating-system background scheduling, with the same schedule definitions and visible battery/availability behavior.

A single local coordinator claims each due occurrence, writes its task and receipt records atomically, and uses idempotency keys for consequential effects where supported. An uncertain external outcome is reconciled before retry. This initial single-user design does not require Temporal or multiple competing schedulers.

Events from local tools can enter through the local Gateway. Remote webhooks cannot reach a private desktop address without a relay; support them only through an explicit owner-enabled hosted relay or a reachable owner-controlled endpoint, and record that dependency in the connection/readiness report. A copied schedule is disabled until the receiving owner enables it.
## Gateway and interaction channels

The Gateway is a stable, versioned API for conversations, approvals, task progress, files and events. Web, desktop, CLI, voice and messaging clients are adapters over the same API and do not own conversation state. A generic conversational client is always available for agents that declare conversation as their presentation.

Agent-specific screens are optional clients. They may improve interaction but cannot contain unique business logic, hidden authority or the only path to owner data. Approvals are explicit Gateway resources; a channel that cannot display an approval leaves it pending until expiry or owner action. No channel may translate an unsupported approval into approval.

The first reference client is a minimal web chat plus a CLI conformance client. Using both against one Memory demonstrates that conversation, actor identity and policy do not depend on a specific frontend.

## Sharing, export and restore

Sharing creates a new, reviewable package. The export process walks selected objects and their dependencies, checks sharing levels and third-party rights, strips private and never-disclosed data, removes owner grants and connection secrets, disables schedules, and records omissions. It preserves publisher provenance and adds a sharer signature where configured. The recipient inspects the package before installation and receives a new installation identity.

A full owner backup is different from a share package. It contains private and protected records and may contain encrypted secret envelopes, but never the recovery key. It is encrypted for the owner's recovery method, integrity checked and accompanied by a manifest. Restore verifies the bundle before activating services, asks the owner to establish/trust Auth, checks secret recoverability and provider connection health, then runs compatibility checks. The old Memory remains untouched until the owner commits to the restored copy.

## Component replacement and readiness

Every component publishes a versioned capability profile and data contract. On replacement, the system compares that profile with each active agent and in-progress task. The owner sees a readiness report grouped into:

- works as before;
- works with a declared limitation;
- requires owner action (for example, reconnection or approval);
- blocked because a required capability or safety guarantee is missing;
- not checked, with the reason.

A replacement Auth must not begin authorizing actions until the owner completes a recovery ceremony. That ceremony verifies the Memory integrity, establishes the new Auth signing identity, records the trust transition, and requires review of policy semantics and outstanding approvals. If the old Auth is available, the owner can approve a signed handoff. If it is unavailable, the owner recovery key plus an out-of-band owner proof authorizes recovery. A compromised old Auth cannot veto recovery, but its audit records are marked as potentially untrusted from the suspected compromise point.

A component cannot claim compatibility solely from its own declaration. Conformance evidence includes independent tests for data preservation, authority boundaries, revocation, ambiguous outcomes, export/restore, second-client operation and component substitution. Claims are tied to the exact implementation version and requirement set.

## Operational qualities

- **Security:** least privilege between components; encrypted transport; secret redaction; isolated execution for untrusted code; fail-closed authorization; dependency and package integrity checks.
- **Durability:** atomic commits for protected records; append-only audit chain with signed checkpoints; tested backup and restore; explicit recovery states.
- **Observability:** owner-readable event history for grants, approvals, connection changes, data exports, component changes and external effects. Logs contain enough to explain decisions without recording secrets or unnecessary private content.
- **Privacy:** purpose-bound context assembly, source labels on derived data, retention controls and deletion propagation to indexes/caches.
- **Interoperability:** published schemas, version negotiation, stable IDs, migration rules and round-trip tests for unknown optional fields.
- **Availability:** components may restart independently. If Auth or the broker is unavailable, new privileged actions stop; read-only work may continue only where its policy permits.

## Concrete implementation blueprint

The architecture needs an actual first implementation to make the boundaries tangible. This section chooses a desktop-first local stack that fits the current Rust/Tauri + React application and its bundled runtime. Portable data formats and service contracts remain independent of those implementation choices.

### Reference stack
| Area | Reference choice | Owner-facing implication |
|---|---|---|
| Desktop shell | Existing Rust/Tauri application | One normal desktop install; shell manages app startup, local runtime lifecycle, native integrations, and updates. |
| User interface | Existing React + TypeScript app inside Tauri | All ordinary setup and Memory management happens in guided screens. |
| Agent runtime | Bundle the existing TypeScript/Node runtime with the desktop distribution | Owner does not install Node or run a server command; runtime version is managed by the app publisher. |
| Local API | Existing Fastify Gateway bound to loopback or local IPC | UI and approved local clients use one versioned boundary; no public endpoint is opened by default. |
| Durable Memory | App-managed local folder with Markdown, JSON, and encrypted files | Human-readable, portable source of truth; app creates and manages its location automatically. |
| Coordination | Atomic file updates, a single-writer lock, and versioned JSON task records | No database installation or visible database file in the first local release. |
| Search | In-memory indexes rebuilt from Memory | Search data is disposable and never the only copy of owner information. |
| Model access | BrainDrive Models through its supported API | BrainDrive selects and tests underlying models; LiteLLM is internal infrastructure, not an owner setting. |
| Model portability | Provider-neutral capability profile and adapter contract | Agents declare capabilities; compatibility is checked when BrainDrive Models changes its model assignment/profile. |
| Tools | Existing MCP integration behind a stable capability/authorization layer | Owners connect or approve tools in the app; MCP itself does not grant authority. |
| Durable execution | PAA-owned task journal and action receipts in Memory | A task can be explained and safely reconciled without relying on a workflow vendor's private history. |
| Local scheduling | Small app-managed scheduler for the first release | Scheduled work runs while the app/runtime is available; paused/missed work is shown clearly. |
| Secret custody | Extend the existing vault using versioned envelope encryption | Owner completes recovery setup in the app; raw credentials remain unavailable to the model and agent. |
| Executable isolation | Declarative agents and trusted MCP tools first; add WASI and OS-native sandboxing before third-party scripts |
| Development | Docker may support local development and integration tests | Docker is not included in installation instructions and is never a prerequisite for owners. |
| Hosted deployment | Separate future target, outside this local reference build | A hosted version may add database/object storage infrastructure while preserving the same Memory export contract. |

The Rust/Tauri shell and React interface reflect the current desktop product. This reference keeps the existing TypeScript runtime bundled behind that app; Rust is not assumed to replace the Agent Loop. Docker remains a development tool. No exact Node patch level or database version is part of the portability contract.
### What “Markdown files” means in practice

The folder should feel like the owner's own filing cabinet, not an opaque application database. For example:

```text
MyMemory/
  memory.md                         # name, overview, recovery/export notes
  agents/<install-id>/AGENT.md      # readable instructions and skills
  conversations/<year>/<id>.md     # readable conversation transcript
  notes/ and documents/             # owner files in their original formats
  tasks/<task-id>/task.md           # goal, summary and human-readable state
  tasks/<task-id>/state.json        # checkpoints and pending action IDs
  policies/<actor-id>.json          # structured grants; edited through the app
  connections/<id>.json             # provider and scope metadata, no token value
  schedules/<id>.json               # recurrence, timezone, enabled state
  audit/events.jsonl                # append-only decision/action metadata
  secrets/<id>.enc                  # encrypted secret envelope, unreadable as plain text
  (no database file in the owner folder)
```

Markdown is the default for content people may want to inspect or edit. JSON is for compact machine-managed records that need exact fields and safe updates; the application presents these as readable settings screens rather than asking owners to hand-edit policy files. Secrets are encrypted binary envelopes, not Markdown. The app offers “Open Memory Folder,” backup, restore and conflict repair in its interface.

Local-first ownership also changes the failure model: the app works offline for local files and local models/tools; external model or service calls require a connection. If the app is closed during a scheduled action, the UI tells the owner which schedules pause. Always-on hosted scheduling is an optional service and must be visible as such.
### What we need to build

This is the product-specific engineering, rather than something an off-the-shelf framework supplies:

- **Portable Memory contract:** record schemas, IDs, classification and provenance metadata, migrations, bundle export/import, integrity manifests, and round-trip compatibility rules.
- **Agent package format:** manifest schema, package layout, signature/provenance fields, dependency resolution, inspection report, import/export filtering and lifecycle state machine.
- **Capability registry:** stable IDs and schemas for models, tools, channels, execution features and their effects; adapters map external protocols into this registry.
- **Readiness engine:** compares an agent's required/optional capabilities against the current implementation profile on install, update and every relevant component/configuration change.
- **Auth and owner presence:** actor registry, owner/agent identity separation, policy evaluator, approval lifecycle, delegation chain, spending reservations, revocation and recovery ceremony.
- **Connection broker:** provider connection lifecycle and health, scoped operations, token refresh, local revocation, provider revoke, and safe reconnection reporting.
- **Portable task journal:** task and step state, intents, approvals, receipts, idempotency keys, unknown outcomes and recovery instructions.
- **Sharing and backup workflows:** distinct filtered share packages and full owner backups, with user review of what leaves and verification before restore.
- **Compatibility/conformance suite:** portable fixtures and journeys that can be run against another implementation without relying on vendor internals.

We adopt infrastructure, protocol libraries and UI frameworks. We do not outsource the ownership semantics, policy meaning, manifest semantics, compatibility report, or recovery protocol; those are the portability product.

### Service and storage topology
The first local build ships as the desktop application plus a bundled, app-managed local runtime. Tauri starts the runtime when needed, checks readiness, passes a per-launch local credential, and stops it cleanly on exit. The runtime contains the Gateway, Auth, Agent Loop, compatibility checker, and initial scheduler as modules with explicit interfaces rather than separately administered services. These are logical security boundaries inside a signed desktop product, not a claim that same-user processes can contain arbitrary hostile code; downloaded executable agents remain unsupported until a real OS sandbox is in place.

The connection broker is a narrow internal boundary. The runtime can request an authorized operation but cannot read raw secret values. Secret decryption is limited to the broker path and protected by the app's owner-unlock/recovery flow. Tool and model calls receive only the context and capability authorized for that operation.

Memory is stored under the application-managed user-data location. The owner can use “Open Memory Folder,” backup, or export, but does not choose or maintain the path during setup. Durable records are Markdown, versioned JSON, ordinary attachments, or encrypted envelopes. The first local implementation has no database; it uses a single writer for protected records and rebuildable in-memory indexes.

The local Gateway is private to the device by default. It does not require a public domain, reverse proxy, Docker, Kubernetes, or PostgreSQL. A webhook source that requires a public callback needs an explicitly enabled relay or hosted endpoint; that is an optional service dependency, not an assumed property of local operation.

A future SaaS edition would be a separate deployment profile. It could use PostgreSQL for transactional multi-user coordination and object storage for blobs, while preserving the same schemas, classifications, and export/restore bundle. Those services are not part of the local user's installation.

### Core API contracts

Publish OpenAPI contracts for the optional local Gateway and JSON Schema for portable objects. These are logical APIs: the desktop UI may use authenticated local IPC/Tauri commands, while compatible external clients can use a loopback-only Gateway when enabled. Never bind the local Gateway to a public interface by default. Initial operations:

- `POST /v1/conversations/{id}/turns` — submit a user turn and stream progress/events.
- `GET /v1/agents/{installationId}/readiness` — return capability status and blockers.
- `POST /v1/agents/import` and `/export` — inspect or create filtered packages.
- `POST /v1/authorizations/evaluate` — Auth decision request; internal, signed caller identity required.
- `POST /v1/approvals/{id}/decision` — owner approval or rejection with step-up proof where configured.
- `POST /v1/actions/prepare` and `/execute` — prepare intent, reserve limits, authorize and commit an external effect.
- `POST /v1/connections/{id}/operations` — broker operation; caller supplies an operation, never a token.
- `GET /v1/tasks/{id}` and `/events` — inspect durable progress and outcome state.
- `POST /v1/memory/exports` and `/restores` — owner backup/restore lifecycle.

Every mutating operation has an idempotency key. APIs return typed states such as `dependency_unavailable`, `approval_required`, `policy_denied`, `outcome_unknown`, and `reauthorization_required`; clients must not collapse them into generic success/failure.

### How the critical workflows work

**Install an agent:** fetch package bytes into quarantine → verify digest/signature if present → validate manifest and references without execution → classify files and data handling → resolve capability profile → produce owner-readable inspection → owner selects grants → create new installation and actor IDs → persist definition and grant records separately → activate only when required capabilities are ready.

**Perform an external action:** Agent Loop writes a durable task step and action intent → Auth evaluates actor/action/resource/context → if needed, Gateway creates an approval resource and pauses → Auth issues a short-lived, single-operation authorization → broker checks it and any limit reservation → broker executes with an idempotency key → receipt and outcome are committed → task journal advances. A crash after external execution but before receipt yields `outcome_unknown`; recovery queries the provider or asks the owner before retry.

**Replace Auth:** stop privileged actions → verify Memory export and audit chain → owner signs a trust transition using a separate owner credential/recovery method → new Auth loads policy fixtures and protected records in read-only mode → run decision conformance cases → activate new Auth key and mark the transition → review pending approvals and active leases. No agent can authorize its own replacement.

**Move Memory:** create an owner backup → verify its manifest → restore through the desktop app into its automatically managed local location → check migrations and encrypted secret recovery → re-establish Auth trust → check BrainDrive Models and external connection status → show the readiness report. The owner confirms the restored Memory before the app switches to it. Reauthorize only providers that require it.

**Share an agent:** select definition and any explicitly chosen shareable examples → dependency closure is calculated → private/protected/never-disclosed records and grants are excluded → schedules are disabled → recipient-specific package is hashed and signed → owner previews included and omitted content → recipient inspects before install and receives fresh installation/actor identities.

### Data and schema implementation details

Use Markdown for readable durable content and JSON Schema for machine-managed records. Validate JSON sidecars at every write and on startup. The files are the source of truth. Build search indexes in memory for the first release; do not add a database dependency to the local product. Large immutable packages can be content-addressed by SHA-256 within the same folder. Add an app-private, rebuildable cache only after measured performance requires it.

Write protected policy, reservations, leases and action receipts as small versioned JSON records with atomic replacement under a single-writer lock. Append audit events as newline-delimited JSON records in a hash-linked log with periodic owner-signed checkpoints. Audit payloads contain identities, decision codes and object references, not full prompts, credentials or external response bodies. The local reference build runs one writer for protected records and serializes writes with a lock. The lock is runtime coordination, not user data. Exported records remain ordinary files.

The initial encrypted secret format uses an envelope per credential: random data-encryption key, authenticated encryption, key identifier, algorithm/version metadata, ciphertext, nonce and authentication tag. The memory key encrypts credential data keys; recovery methods wrap the memory key. Rotation rewraps the memory key where possible and rotates provider credentials when required. The cryptographic format is versioned and independently documented so another implementation can decrypt with the owner's key without calling the original service.

### Delivery and staffing shape

A credible first implementation is a small product team, not one generic “agent platform” sprint. Work streams are: (1) Memory/manifest and migrations, (2) Gateway/client and capability adapters, (3) Auth and owner recovery, (4) broker and provider integrations, (5) durable execution and conformance. They can proceed in sequence around the shared schemas.

The first vertical slice should run through the packaged desktop app: initialize app-managed Memory automatically, install a text-only agent, use BrainDrive Models, call one read-only tool and one approval-gated write tool, store a conversation and task receipt in Memory, then export and restore into a second local profile. Docker and CLI use are not part of the owner journey.

## Build sequence

### 1. Portable bundle and agent manifest

Define the logical Memory bundle, schema/version rules, agent manifest, object IDs, sharing labels and inspection report. Implement import/export and round-trip validation for definitions and owner data. This gives every later subsystem a stable contract.

### 2. Agent loop, model and tool adapters

Build the generic Gateway and Agent Loop against interfaces, a capability-based model adapter, tool registry, and compatibility checker. Keep conversations and task journals in Memory from the first version.

### 3. Auth and protected records

Implement actor identities, grants, policy evaluation, owner presence, approval resources, audit records and protected storage. Add delegation and reservations before enabling consequential tools.

### 4. Connection broker and encrypted secret store

Implement owner recovery-key setup, encrypted envelopes, scoped broker operations, connection health, revocation and redacted audit. Begin with a small number of services and exercise restore to another installation.

### 5. Safe durable execution

Add intent/receipt journal, idempotency and unknown-outcome reconciliation. Only then enable long-running or autonomous tasks that can affect external systems.

### 6. Schedules, events and additional clients

Add leases, fencing, recurrence and missed-run rules, stable event ingress, then CLI and other client adapters. Keep schedules off on copied agents.

### 7. Replacement and conformance

Exercise component substitution and whole-Memory restore. Publish evidence for every requirement and test multiple independent implementations against the same bundle and fixtures.

## Acceptance journeys

The reference implementation is successful when these owner journeys work end to end:

1. Install a declarative agent, inspect its dependencies and requested actions, grant only selected actions, and see a clear limited/blocked report for missing dependencies.
2. BrainDrive changes the underlying model assignment; active agents are checked against the updated capability profile and any incompatibility is reported before the affected capability is used.
3. Replace a tool adapter or Agent Loop while conversations and tasks exist; recover safe tasks and explicitly reconcile uncertain external actions.
4. Connect an external account, replace the Agent Loop, and continue using the connection without exposing its refresh token to the agent or model.
5. Copy an agent to another owner's Memory; preserve definition provenance but transfer no work, grants, keys, connections or enabled schedules.
6. Move a complete Memory to new hardware, restore with the owner's key, re-trust Auth, and distinguish healthy connections from those requiring provider reauthorization.
7. Attach two generic clients to the same Gateway and resume one conversation with identical identity and authority boundaries.
8. Run scheduler recovery and duplicate-occurrence scenarios in conformance fixtures; verify one logical run and safe reconciliation without requiring multiple schedulers in the owner installation.
9. Export selected owner data, inspect exactly what leaves, and verify that derived data and third-party rights are handled according to source classifications.

## Deliberate limits

This architecture does not promise identical model behavior, universal transferability of provider-bound credentials, exactly-once effects from arbitrary third-party services, conflict-free multi-writer file synchronization, or automatic portability of a proprietary agent UI. It requires honest capability reporting and a safe path through each limitation.

The architecture's central rule is simple: define the durable meaning and owner-controlled boundaries in portable records; let implementations choose replaceable machinery to operate on them; and verify the owner journeys across actual component changes.







