# CLI Contract

The `op-sys` CLI is the local API for the ledger substrate. Humans, skills, wrappers, and generated product surfaces should use this contract instead of reading storage directly.

The bundled installer uses the ordinary hosted `install.sh` entry point and
prints a shell-quoted executable path usable immediately by an existing agent.
After installation, public capability discovery and local ledger inspection need
no cloud account, agent registration, or mandatory skill. See
[installation](/docs/raw/manuals/installation.md#one-command-installation-macos-arm64).

## Rules

Public capability discovery applies across ledger use, contracts, contributions,
retrieval, sharing, access, and recovery. `capabilities list` presents a readable
overview; `--prefix` narrows the operation names. Structured results include usage
guidance and the actual contract schema profile. `capabilities get --name NAME`
exposes an operation's purpose, invocation bindings, input/result/error schemas,
permissions, effects, and retry/concurrency semantics. Discovery is read-only and
does not initialize a local ledger or grant access.

`contracts validate --payload-schema @schema.json` checks proposed rules and
examples without publishing, changing admission, or writing test records. Its
structured report distinguishes schema validity from per-example validity;
neither result promises future admission or factual truth. Human authentication
and genuine decisions remain resumable handoffs through the ordinary capabilities.

`records limits` reports protocol ceilings and current service size bounds for
the selected contributor. `records validate --payload @contribution.json` checks
current contract, payload, available attachments and write-size rules without a
write, search preparation, billing reservation or operation identity. Inspect
`valid`: true passes these checks, false reports issues, null leaves service
bounds unknown. The operation exits successfully when it produced a valid report,
including a failed check. Append remains the sole acceptance boundary. Oversized
appends include `limit.name`, decimal `maximum`/`actual`, and `source` in the public
error; JSON request escaping does not change canonical payload size.

- The local ledger is the source of truth.
- Core commands are workflow-neutral.
- Skills and external surfaces define workflow conventions.
- Workers are externally owned commands coordinated through claims, events, comments, and artifacts.
- JSON output is the automation surface; human output is display-only.

Everyday ledger and record commands show human summaries by default. Record lists
label shortened payloads as previews, and reads retain source and coverage warnings.
Use `--output json` for full resource fields and pagination tokens; never parse
the human presentation. Ledger errors include their code and actionable recovery
in both human and structured output. See [the quickstart](/docs/raw/manuals/ledger-quickstart.md).

Record, setup, tool, and MCP commands run independently of worker execution.
Legacy worker and coordination commands select the optional integration; see
[the execution boundary](/docs/raw/manuals/execution-boundary.md).

## Global Flags

- `--state-root <path>`
- `--repo-root <path>`
- `--scope user|project`
- `--actor <id>`
- `--output human|json`

JSON mode emits:

```json
{
  "schema_version": "v1",
  "payload": {}
}
```

## Top-Level Groups

- `init`, `status`, `where`
- `doctor`
- `self`
- `schema`
- `workflow`
- `ledger`
- `records` (consumer-governed logical ledgers and generic local records)
- `approval`
- `worker-type`
- `worker`
- `session`
- `policy`
- `audit`
- `state`
- `trust`
- `cloud`
- `query`

Core does not expose legacy workflow-specific command groups. Workflow-specific experiences should be implemented by skills, wrappers, templates, or product surfaces that call the generic ledger commands.

Cloud is an optional capability of the same CLI. It must not require users to learn a separate `op-sys-cloud` command surface.

## Substrate Config

The core uses `ledgers create/get/list/inspect/configure`, immutable `contracts`
and `records append/get/list/outcome/erase`. Submission enforces the admitted
contract without a strictness opt-out. Unknown explicit selections fail rather
than creating replacement ledgers. See [the core contract](/docs/raw/manuals/ledger-core.md) for
current bindings, acceptance, errors and pagination. Execution events are not
automatically uploaded or converted into records.

The state root also contains local substrate config files such as `policy.json`, `team.json`, and the private `trust/` directory. Policy and team configuration are portable state, not workflow records; trust custody and legacy `keystore.json` are never exported. In schema v11, policy and team settings are canonical versioned SQLite rows; their JSON files are recoverable projections, not editable sources of truth. `team.json` is retained for state-root compatibility and launch context such as local charter notes; it is not a public CLI surface or a workflow/team-management API.

### Public-key trust

```bash
op-sys trust keygen --owner <public-label>
op-sys trust rotate --owner <public-label>
op-sys trust list --local
op-sys trust list --trusted
op-sys trust public export --key <local-id> --out <public-json>
op-sys trust fingerprint [--key <local-id>|--file <public-json>]
op-sys trust add --file <public-json> --expect-fingerprint <confirmed-fingerprint> --label <known-owner>
op-sys trust revoke <fingerprint-or-local-id> --reason <public-reason> [--compromised-at <unix-seconds>]
op-sys trust remove <external-fingerprint>
op-sys trust legacy status
op-sys trust legacy destroy --yes
op-sys trust notary add --file <public-json> --expect-fingerprint <confirmed-fingerprint> --label <authority> --incident-policy op-sys.pre-cutoff-anchor.v1
op-sys trust notary list
op-sys trust notary revoke <fingerprint> --reason <reason> [--compromised-at <unix-seconds>]
op-sys trust notary remove <fingerprint>
```

Mutating trust commands require an initialized local ledger. Fingerprinting
defaults to the active local key; `--key` and `--file` are mutually exclusive.
Listing defaults to local public identities. Public-only commands never create,
repair or migrate the store. Trust add requires exact independent confirmation,
not trust-on-first-use. Rotation preserves history; revoke disables signing
without selecting a fallback. Removing trust does not delete a local seed.
New keys sign for 90 days; legacy recovery custody is inactive for a maximum
30-day window, with explicit deletion and no automatic secret export.
See [trust.md](/docs/raw/manuals/trust.md) for schemas, compromise/backdating limits, custody,
bounded storage and the separate crypto/trust/historical verification facts.

### Atomic mutation contract

One ledger-service mutation commits its primary rows, audit entries, events,
and idempotency receipt together, or rolls them all back. Nested operations,
including every operation in a batch, reuse the outer writer transaction.
Session getters that reconcile state and approval getters that expire pending/approved
approvals also run under this boundary. A failed nested call makes the outer
transaction rollback-only even if its exception is caught.

The SQLite `events` table is the committed local outbox. A successful replay
returns its original result without another audit, event, or approval action;
explicit strict-contract validation still applies. Concurrent callers check
replay keys under the same writer reservation. This does not promise atomicity
for external commands, filesystem artifacts, or remote publication.
Comment/artifact notification events do not derive their own replay key from
the caller's key: primary-row replay already prevents duplicate notifications,
and caller-created event keys cannot suppress their outbox rows.

Lease heartbeat and release require the requested owner and an unexpired
lease in the SQL mutation predicate. `lease_missing`, `lease_expired`, and
`lease_conflict` are expected concurrency outcomes; an old owner cannot renew
or remove a replacement owner's lease. Re-read ownership before deciding
whether another claim attempt is appropriate.

Policy/team canonical updates share their audit/outbox transaction. JSON is
published only after commit; a projection failure does not undo that commit.
Writable startup or the next settings read rebuilds a missing/stale projection
from SQLite without duplicate audit/events. Never restore canonical settings
from a projection. Read-only diagnostics do not repair files.

## Local State Protection

Managed local state is private by default. POSIX directories use `0700` and
sensitive files use `0600`. Windows removes inherited access and applies a
protected DACL granting full control only to the current user and `SYSTEM`.
Symlinks, junctions, reparse points, wrong file kinds, wrong ownership, and an
ACL or mode that cannot be verified fail closed as
`state_permissions_unsecured`.

```bash
op-sys state permissions
op-sys state permissions --repair
```

The default command is read-only. It returns `ok`, `repair_requested`, a
secret-free `paths` array, and `project_state_git_exclude`. Each path item has
only `path`, `expected`, and `ok`; the Git item adds `applicable` and a
value-free `status` code. `--repair`
explicitly repairs the managed-sensitive-path inventory and the project-local
Git exclusion before returning the same shape. Neither form prints file
contents.

Before any other initialized-state command reads local state, the CLI repairs
permission or Git-exclude drift. A command that performed this upgrade repair
adds `state_permissions_repaired: true` to its otherwise unchanged result.
`doctor`, the read-only `state permissions` form, `state verify` and trust
commands never make that automatic repair; trust reads fail closed on unsafe
permissions, while explicit mutations use protected atomic file operations.

Project initialization adds exactly `/.op-sys/` to the effective exclude file
reported by `git -C <repo> rev-parse --git-path info/exclude`. Existing
comments, unrelated rules, newline convention, and permissions are preserved;
tracked `.gitignore` is not edited. A user-scoped state root reports the Git
check as not applicable. Git exclusion is not encryption and does not remove
already committed state from history.

## Schema Discovery

`schema show` returns the full public schema catalog. `schema show --surface <name>` returns one surface contract. Public surfaces are:

- `cli-envelope`
- `worker-runtime`
- `doctor`
- `self`
- `ledger`
- `workflows`
- `ledger-batch`
- `approvals`
- `sessions`
- `policy`
- `audit`
- `state`
- `worker`
- `worker-type`
- `database-schema`

The `database-schema` surface describes the local SQLite inspection and
migration payload. These forms are non-mutating dry runs:

```bash
op-sys schema database
op-sys schema database migrate
```

`op-sys schema database migrate --yes` explicitly executes the displayed
forward-only plan. The result remains under `payload.database`: `dry_run` is
false, `inspection` describes the resulting database, and `migration` is the
startup migration result. Without `--yes`, `dry_run` is true and `migration`
is null. Inspection does not initialize or migrate state. All three forms
require an existing initialized state database; use `op-sys init` to create
new state. In particular, confirmation never converts a missing database into
an implicit initialization.

Ordinary writable service construction for admitted local state does not copy
or scan the whole database. It checks a private, non-exported
`locks/schema-admission.json` against local filesystem identity, current schema
and migration history, with existing permission/restore/locking guards and
WAL-aware SQLite reads. Normal data writes retain admission. Missing, malformed,
old or identity-mismatched records require deep validation; unsafe paths and
changed schema/history fail closed. First opening an existing unadmitted ledger
can therefore still be expensive. Explicit `schema database` diagnostics and
migration/import/restore validation remain deep operations. Routine success
does not certify unread data pages or foreign keys; the admission record is
neither a portable trust artifact nor a backup.

`op-sys init` accepts an absent, zero-byte, or valid empty-v0 database only in
an absent/empty root, or one containing private empty recognized managed
containers and the exact private canonical migration-lock residue left by an
interrupted fresh bootstrap. Root state files, SQLite sidecars, nonempty or
unsafe managed containers, unsafe/noncanonical locks, and unknown top-level
entries are ambiguous initialized-state evidence; initialization rejects them
value-free and without repair.

The inspection object contains `status`, `reason`, `current_version`,
`target_version`, `fingerprint`, `canonical_fingerprint`, `integrity_ok`,
`foreign_keys_ok`, `empty`, `migration_required`, `migration_supported`,
`pending`, `last_applied_migration`, `backup_count`, `newest_backup`,
`backup_inventory_status`, `backup_inventory_reason`, `backup_destination`,
and `recovery`.

The target is schema v10. Only exact v4-v9 structural fingerprints bound by
the checked-in fixture-provenance manifest are migratable. Unsupported v1-v3,
non-empty unversioned state, unknown/corrupt/checksum-divergent state, and
newer versions fail closed. There is no downgrade command. A confirmed or
automatic startup migration first creates a verified private backup below
`<state-root>/backups/schema/` with an adjacent private receipt binding its
SHA-256, size, source version and fingerprint. Inspection counts only fully
revalidated receipt/file pairs; `backup_inventory_status` and
`backup_inventory_reason` expose invalid or unreadable inventory without
echoing file contents. Migration uses the same bounded cross-process and
exclusive SQLite locking. Contention reports `schema_migration_busy`.

Successful retention keeps the three newest recognized backup/receipt pairs
globally plus the newest pair for every source version. Invalid, unreadable,
unrecognized, or receipt-less files are not recovery points and are not pruned
automatically. On a migration or validation failure, stop other writers,
preserve the database and all evidence, and retry only after resolving the
reported reason. Restore only a revalidated backup/receipt pair to a separate
private path; do not overwrite the failed or upgraded database.

Unsupported or non-empty unversioned inputs fail before the automatic backup
stage. With every writer stopped, preserve a private byte-for-byte copy of the
complete state root, including SQLite sidecars and referenced files. An
additional recovery capture may be created outside the state root with:

```bash
op-sys --state-root /path/to/legacy-state state export \
  --out /private/recovery/op-sys-legacy-state.zip --no-sign
```

This is raw preservation, not adoption. `state verify` is expected to reject
the bundle while its database schema remains unsupported or unversioned, and
`state import` must not be used to bypass that result. Inspect a disposable
copy with owner-approved legacy/read-only tooling, inventory every record
family, and manually recreate reviewed records in newly initialized v10 state.
There is no downgrade: an upgraded database must never be opened by an older
binary. The complete operator procedure is in
[Self-Hosting](/docs/raw/manuals/self-hosting.md#schema-upgrades-and-recovery).

A newly created v10 database contains one checksum-bound schema-origin record.
An upgraded v10 database contains a distinct origin bound to its exact accepted
source fingerprint and complete selected route, followed by its applied rows.
Missing, empty, mixed, truncated, transplanted, or malformed v10 history is
invalid. `last_applied_migration` excludes either origin record because an
origin is not an applied migration.

## Diagnostics And Runtime Management

Public diagnostic and runtime commands:

```bash
op-sys doctor
op-sys self version
op-sys self update [--channel <channel>] [--version <version>]
op-sys self uninstall [--dry-run] [--yes]
```

`doctor` returns `{ "ok": true|false, "checks": [] }`. Check items expose `check`, `ok`, `detail`, and `remediation`. It is read-only and includes `state_root_permissions`, `state_file_permissions`, and, for project scope, `project_state_git_exclude`. Its remediation points to `op-sys state permissions --repair`; it never performs that repair itself.

`self version` returns source or managed runtime metadata. `self update`
validates the executing managed-runtime identity before invoking its installer
and returns `{ "updated": true, ... }`. `self uninstall` returns
`scheduled`, `dry_run`, `runtime_root`, `removal_receipt`, a secret-free
`validation` report, and `message`. `removal_receipt` is null when unscheduled.
After scheduling it names a private value-free receipt that is created only if
detached removal fails; the path normally disappears on success. `--dry-run`
performs all target validation that precedes helper creation without creating
a helper or deleting files; `--yes` is required to schedule removal. The
runtime root is derived from the executing launcher, module, and managed
Python layout. `OP_SYS_INSTALL_ROOT` is accepted only when its canonical path
equals that derived root.

Automated uninstall requires agreeing private `install/managed.json`,
`install/source.json`, and per-version installation metadata. Missing or
inconsistent legacy metadata fails closed. Ledger data and the resolved state
root are outside uninstall scope. Install into a fresh prefix and separately
review an ineligible old prefix before any manual removal. Stable safety failures include
`install_root_mismatch`, `install_marker_invalid`, and
`uninstall_target_unsafe`. Windows managed-runtime update/uninstall supports
only unpackaged Python when every participating identity-bearing path is on a
queryable, case-insensitive NTFS namespace. This managed-operation boundary
does not globally restrict ordinary Windows state storage.

## Ledger Rails

Required generic commands:

```bash
op-sys ledger entity create --type <type> --workflow <namespace> --title <title> --data <json>
op-sys ledger entity show --id <entity-id>
op-sys ledger entity list
op-sys ledger entity update --id <entity-id> --data <json>
op-sys ledger entity patch --id <entity-id> --patch <json>

op-sys ledger event append --entity <entity-id> --type <event-type> --payload <json>
op-sys ledger event list --entity <entity-id>

op-sys ledger relation add --from <entity-id> --to <entity-id> --type <relation-type>
op-sys ledger relation list --entity <entity-id>
op-sys ledger relation remove --id <relation-id>

op-sys ledger claim --entity <entity-id> --worker <worker-id>
op-sys ledger release --entity <entity-id> --worker <worker-id>

op-sys ledger comment --entity <entity-id> --body <body>
op-sys ledger artifact attach --entity <entity-id> --path artifacts/<relative-path> --kind <kind>

op-sys ledger batch --operation <json> [--operation <json> ...]
```

`ledger entity patch` applies JSON merge patch semantics to entity `data`: objects merge recursively, `null` removes keys, and other values replace the current value.

`ledger batch` accepts repeated operation objects or one explicit batch envelope:

```bash
op-sys ledger batch \
  --operation '{"op":"entity.create","ref":"incident","type":"incident","workflow":"example.incident","data":{"status":"new"}}' \
  --operation '{"op":"event.append","entity_ref":"incident","type":"incident.created","payload":{}}'
```

```bash
op-sys ledger batch \
  --operation '{"idempotency_key":"open-1","operations":[{"op":"entity.create","ref":"incident","type":"incident","data":{}}]}'
```

Identifier fields in a batch are exact literals: they are not trimmed,
stringified, or implicitly resolved merely because their text matches a ref
name. Use `$name`, `{ "ref": "name" }`, or a dedicated `*_ref` field for an
explicit intra-batch reference. Explicit empty, null, structured, or padded ID
and type values reach the normal field validator and do not fall back to an
alias or default. Invalid and unknown refs use the value-free
`batch_entity_ref_invalid` reason.
Ref declarations and explicit ref lookups trim surrounding whitespace and
remove one leading `$` before applying the opaque-ID grammar. Two declarations
that normalize to the same name (for example `dup`, `" dup "`, and `$dup`)
fail before any operation with `batch_ref_duplicate`; a present declaration
whose value is null, non-string, or empty fails with `batch_ref_invalid` rather
than being treated as omitted. Persisted idempotent receipts are not blindly
trusted: top-level and `batch`-nested `results` must be arrays of object items
whose `result` is an object, `refs` must be objects, all five root/nested views
are required, and the duplicated results/refs views must match exactly. Every
present documented resource slot (`entity`, `event`, `relation`, `comment`,
`artifact`, `claim`, or `lease`, including `claim.lease`) must be an object;
their documented resource IDs and ref names/values are revalidated before
replay. Arbitrary entity data, event payloads, artifact metadata, and other
workflow-owned JSON are not interpreted as refs.

Batch flags:

- `--operation <json>`
- `--precondition <json>`
- `--idempotency-key <key>`
- `--contract <path>`
- `--strict-contract`
- `--approval <approval-id>`

Batch envelopes accept these top-level keys:

- `operations`: required non-empty array when calling the service; the CLI builds it from repeated `--operation` values unless a single explicit envelope is passed
- `preconditions`: optional batch-level array evaluated before operation writes
- `idempotency_key`: optional full-batch replay key; successful receipts are persisted and returned unchanged on replay
- `workflow` or `workflow_namespace`: optional default workflow namespace for operation items
- `workflow_version`: optional default workflow version
- `contract` or `workflow_contract`: optional strict workflow contract object or path
- `strict_contract`: opt into contract enforcement for entity, event, and relation types

Supported batch operation types are:

- `entity.create`: create an entity; accepts `type` or `entity_type`, optional `entity_id`, `ref`, `workflow`, `workflow_namespace`, `workflow_version`, `title`, `body`, and `data`; returns `entity` and additive scalar `entity_id`
- `entity.patch`: apply JSON merge patch to an entity; accepts `entity`, `entity_id`, or `entity_ref`, required `patch`, and optional operation `preconditions`; returns `entity` and additive scalar `entity_id`
- `event.append`: append an event; accepts `entity`, `entity_id`, or `entity_ref`, `type` or `event_type`, optional `payload`, workflow fields, `causal_refs`, and `idempotency_key`; returns `event` and additive scalar `event_id`
- `relation.add`: add a relation; accepts `from`, `from_entity`, `from_entity_id`, or `from_entity_ref`, `to`, `to_entity`, `to_entity_id`, or `to_entity_ref`, `type` or `relation_type`, optional `ref`, workflow fields, and `data`; returns `relation` and additive scalar `relation_id`
- `relation.remove`: remove a relation; accepts `relation`, `id`, `relation_id`, or `relation_ref`; returns `relation`, additive scalar `relation_id`, and `removed: true`
- `comment.add`: add an entity comment; accepts `entity`, `entity_id`, or `entity_ref`, required `body`, optional `kind` and `idempotency_key`; returns `comment` and additive scalar `comment_id`
- `artifact.attach`: attach an artifact; accepts `entity`, `entity_id`, or `entity_ref`, required safe `artifacts/...` path, optional `kind`, `metadata`, and `idempotency_key`; returns `artifact` and additive scalar `artifact_id`
- `claim.acquire`: acquire a claim; accepts `entity`, `entity_id`, or `entity_ref`, `worker` or `worker_id`, and optional `ttl_seconds`; returns `claim` and `lease`
- `claim.release`: release a claim; accepts `entity`, `entity_id`, or `entity_ref`, and `worker` or `worker_id`; returns `claim`, `lease`, and `released: true`

Supported preconditions are valid at the batch level or inside an operation's `preconditions` array:

- `entity.exists`: the target entity must exist
- `entity.type_is`: the target entity type must match `entity_type`
- `entity.data.equals` or `entity.data_equals`: the entity data value at `path` must equal `value` or `equals`
- `entity.data.in` or `entity.data_in`: the entity data value at `path` must be in `values` or `in`
- `claim.absent`: the target entity must have no active claim
- `claim.held_by`: the target entity must be actively claimed by `worker` or `worker_id`

Batch refs are declared with `ref` and consumed with fields such as `entity_ref`, `from_entity_ref`, `to_entity_ref`, and `relation_ref`. Ref values may be plain names or `$name`. Public `refs` resolve to scalar IDs when the operation result exposes one: entity, event, relation, comment, artifact, and claim or lease refs resolve to the relevant ID.

Canonical service target:

```python
ledger_batch(
  actor: str,
  operation: dict,
  approval_id: str | None = None,
  workflow_contract: dict | str | Path | None = None,
  strict_contract: bool | None = None,
)
```

Stable batch output:

```json
{
  "batch": {
    "operation_count": 2,
    "applied_count": 2,
    "idempotency_key": "open-1",
    "idempotent": false,
    "results": [
      {
        "index": 0,
        "op": "entity.create",
        "result": {
          "entity": {},
          "entity_id": "ent_..."
        }
      }
    ],
    "refs": {
      "incident": "ent_..."
    }
  },
  "results": [
    {
      "index": 0,
      "op": "entity.create",
      "result": {
        "entity": {},
        "entity_id": "ent_..."
      }
    }
  ],
  "refs": {
    "incident": "ent_..."
  }
}
```

## Hosted account and connection commands

```bash
op-sys auth login --endpoint <service-url>
# For machine credentials instead, use a separate connection; see cloud-client.md.
op-sys auth status
op-sys workspaces list
op-sys selection update --workspace <workspace-id>
op-sys connections check
op-sys service health
op-sys usage get
op-sys billing get
op-sys service metrics
op-sys service inspect
op-sys auth logout
```

Authentication uses the selected named connection. Setup can create a named
connection explicitly; endpoint changes use `connections` operations. Ledger
selection and remote configuration are separate. Machine login verifies the
candidate before saving private credentials and preserves the previous revision
on failure. Status returns redacted verification metadata.

Use `invitations inspect --invitation "$INVITATION_URL"` to preview a
workspace or ledger offer before signing in. Use the same link with
`invitations accept` when ready to join. Find the full workflows in
[workspace onboarding](/docs/raw/manuals/team-onboarding.md) and [ledger sharing](/docs/raw/manuals/ledger-core.md#invite-a-participant-to-a-ledger).

`connections check` checks configuration, credentials, verification and account-service
access. It does not require a local source or send records. Billing operations
retain their separate administrative authorization.

Use [replicas](/docs/raw/manuals/ledger-replicas.md) for clone/synchronize/status and
[authority transfer](/docs/raw/manuals/ledger-authority.md) to move write authority. Synchronization
is explicit. Local execution mutations remain local; they do not upload events.

The execution-query commands below remain separately available while their final
product disposition is assessed. They do not query core records. For records,
use `records list`, `records state`, `changes feed`, or `records search/feed`
with explicit ledger IDs or an authorized collection.


Query commands share one vocabulary across local and cloud-backed use:

```bash
op-sys query events --scope local
op-sys query sources --scope cloud [--namespace <cloud-namespace>] [--source-id <source-id>] [--ledger <ledger-id>]
op-sys query events --scope cloud --ledger <ledger-id> [--source-id <source-id>] [--namespace <cloud-namespace>] [--payload metadata|full] [--since-at <timestamp>]
op-sys query events --scope all --ledger <ledger-id> [--source-id <source-id>] [--namespace <cloud-namespace>] [--payload metadata|full] [--since-at <timestamp>]
op-sys query event <event-id> --scope cloud [--source-id <source-id>] [--namespace <cloud-namespace>]
op-sys query tail --scope cloud --ledger <ledger-id> [--source-id <source-id>] [--namespace <cloud-namespace>] [--payload metadata|full] [--since-at <timestamp>]
op-sys query context --scope cloud --ledger <ledger-id> [--source-id <source-id>] [--namespace <cloud-namespace>] [--payload metadata|full] [--since-at <timestamp>] --limit 20
op-sys query search <query> --scope cloud [--source-id <source-id>] [--namespace <cloud-namespace>] [--payload metadata|full] [--since-at <timestamp>] --limit 20
```

Supported scopes are `local`, `cloud`, and `all` where a command can return both local and cloud results.

`query context` returns bounded agent/tool context:

```json
{
  "context": {
    "scope": "cloud",
    "events": [],
    "event_count": 0,
    "truncated": false,
    "limit": 20,
    "payload_mode": "metadata",
    "order": "occurred_at_desc",
    "sources": [],
    "filters": {}
  }
}
```

Cloud queries are payload-light by default so agents can use them as organizational memory without wasting context. Use `--payload full` or `query event` only when raw payload details are needed.

`query sources --scope cloud` returns source discovery metadata for agent planning: source ids, ledger labels, namespaces, labels, dimensions, event counts, last sync, top workflows, top entity types, top workers, and `suggested_filters`.

`query search` is the agent-first retrieval path. It returns ranked compact context blocks with `score`, `text_score`, `score_reasons`, a short `summary`, compact event identifiers, `sources`, `suggested_filters`, and `suggested_next_tools`. Cloud follow-ups use `op_sys_cloud_event_get` / `op_sys_cloud_entity_timeline`; local follow-ups use `op_sys_event_get` / `op_sys_events_query` without a Cloud connection.

### Local query pages

Local events/tail return `events`, `next_cursor`, `has_more`, `limit`, `order`,
`filters`, `snapshot_sequence` and bounded `candidate_count`. Context includes
the same page metadata. `--cursor` is filter/order-bound; `--order asc|desc`
defaults to asc for events and desc for tail/context. `--actor`, `--since-at`,
event/entity type/ID and workflow/version filters apply before LIMIT.
`--since` remains an exclusive sequence lower bound. See
[the full local-query contract](/docs/raw/manuals/local-query.md) for literal FTS matching,
ranked pagination, concurrency, text budgets, SQLite support and rebuild.

Agent tool commands expose the same cloud memory surface as the SDK:

```bash
op-sys tools list
op-sys tools call <tool-name> --arguments <json-object>
op-sys mcp config [--server-name <name>] [--client claude|claude-desktop|claude-code|generic]
op-sys mcp doctor [--check] [--usage]
op-sys mcp serve
```

`tools list` returns stable tool names, descriptions, and JSON input schemas. `tools call` returns `{ "tool": { "name": "...", "result": {} } }`.

The list also identifies `protocol: "op-sys.capabilities.v1"`. It is the same
[public catalog](/docs/raw/manuals/public-capabilities.md) used by `OpSys.capabilities` and MCP,
including retained command and SDK operations. Consumers build interfaces over
these capabilities; Cloud web remains account/access/billing/setup only.

`mcp config` emits a secret-free `mcpServers` configuration object with `op-sys mcp serve` and resolved local path environment variables. It must not emit cloud API keys or read/ingest keys. `mcp doctor` verifies the local state root, MCP initialization, tool schemas, cloud configuration, and optionally live cloud access with `--check` or the usage tool with `--usage`.

`mcp serve` runs a stdio MCP server. It must write only newline-delimited JSON-RPC MCP messages to stdout. Supported request methods are `initialize`, `ping`, `tools/list`, and `tools/call`; resources and prompts are not advertised. The MCP tool list is derived from the same `TOOL_CONTRACTS` catalog used by `op-sys tools list`.

Each result item preserves operation order and keeps the resource-keyed payload under `result`:

```json
{
  "index": 0,
  "op": "entity.create",
  "result": {
    "entity": {},
    "entity_id": "ent_..."
  }
}
```

## Approvals

Approvals authorize one exact operation until expiry. Their actor IDs and
votes are cooperative metadata, not authentication. Supply effect-complete
`--operation-json` input using service argument names, without actor/approval
ID. `--actor` binds the intended executor; voting uses the reviewer's own
registered operator/approver ID.

```bash
op-sys approval request \
  --action ledger.artifact.attach \
  --target-type entity \
  --target-id ent_example \
  --reason "Attach reviewed local evidence" \
  --operation-json '{"entity_id":"ent_example","kind":"evidence","path":"artifacts/log.txt"}'

op-sys approval list
op-sys approval show --id <approval-id>
op-sys approval decide --id <approval-id> --decision approve --reason "Reviewed"
op-sys approval revoke --id <approval-id> --reason "No longer needed"
```

Approval payloads are resource-keyed:

```json
{ "approval": {} }
```

Lists return:

```json
{ "approvals": [] }
```

`operation_digest` and `intent` expose the normalized action, actor, ordered
targets, resolved context and per-effect hashes. They omit free-form effect
values; hashes are not encryption. Never use credentials as metadata or
review reasons. State `consumed` adds `consumed_at`, `consumed_by`, and
`consumed_event_id`. Pending/approved rows expire at `expires_at <= now`;
terminal rows cannot be revived. Failed operations roll consumption back and
idempotent replays return their previous result without consuming again.
Legacy digest-less records remain viewable/revocable but require a new request.

Base < team `policy_defaults` < acting worker-type `metadata.policy` governs
permissions, votes, TTL and strictness. Matching explicit deny rules survive
all layers. Operator/approver IDs are explicit canonical team settings;
unknown actor IDs are not operators. Multi-operation batches require distinct
inner `approval_id` values; global approval plus multiple/inner approvals
fails `batch_approval_ambiguous`. See [the complete rules](/docs/raw/manuals/approvals.md) and
[policy example](/docs/examples/approval-policy.json).

Documented approval selector kinds have typed boundaries. `entity`,
`relation`, `worker`, and `session` target IDs use the opaque-ID grammar;
type/kind selectors use the stricter type-name grammar; `entity_type` also
accepts `<workflow-namespace>:<entity-type>` after validating both components;
and `artifact_path` must be a safe relative path under `artifacts/`. The same
contracts apply to documented ID/type/path keys in `payload.context`. Unknown
selector kinds and their payloads remain opaque for forward compatibility.
Before an approval API can expire, create, vote, revoke, or list records, all
approval primary/vote foreign keys and documented selector contexts in every
row—including inactive, revoked, denied, and expired rows—are preflighted.
Known payload/context containers must be objects when present. Errors are
field-specific and do not echo rejected values.

`state import` is an offline state-root replacement operation. Stop every
op-sys process and every other writer that can reach the target state root
before invoking it, and keep them stopped until the command completes. The
same-process active-store refusal is defense in depth only; it is not a
cross-process writer fence, and an approval does not replace this operator
precondition.

Export and import hold `locks/schema-migration.lock` for their operation;
writable SQLite startup and migrations already use this same persistent lock.
Contention returns `schema_migration_busy` after the bounded root-lock wait
(five seconds by default). Governed imports also retain their immediate,
exclusive reservation lock. Import rechecks authorization under both locks;
its initial authorization preflight does not grant the operation. Nested
database startup/inspection in the owning thread borrows the held native
descriptor without reacquiring it; another thread/process cannot borrow it.
Root or lock identity drift fails `schema_lock_unsafe`. Never remove or replace
the persistent lock to clear contention. Existing stores and external SQLite
writers are not stopped by this coordination, so offline import remains required.

Archive members under `governance` or `locks` (including case/Unicode aliases)
fail `bundle_governance_reserved` before target mutation. Local receipts and
the locks protecting them are not portable payloads.

The default policy requires approval for state imports:

```bash
op-sys approval request \
  --action state.import \
  --target-type state \
  --target-id state_root \
  --reason "Import verified bundle" \
  --bundle ./state.zip

op-sys approval decide --id <approval-id> --decision approve
op-sys state import --bundle ./state.zip --approval <approval-id>
```

State permission inspection and repair do not read bundle contents and are
separate from the import approval flow:

```bash
op-sys state permissions
op-sys state permissions --repair
```

`--bundle` is exclusive with `--operation-json` and derives the exact verified
manifest and namespace/version pairs. Workflow flags are optional equality
assertions, not standalone approval input. All imported workflow pairs
participate in permission, vote and TTL decisions. Changing the manifest,
actor or target root fails `approval_scope_mismatch`.

Import requires a database snapshot and retains a private one-shot receipt
under `governance/imports`, which bundles cannot replace or export. Consumption
and audit are prepared with the staged database before publication. Proven
ordinary rollback releases the reservation. A crash may finalize without
re-import only after complete-file verification; uncertain state fails
`approval_import_recovery_required`. Retain evidence and keep writers stopped
for explicit recovery review. A consumed manifest fails `approval_consumed`
even when policy requires zero votes.

Each restore also retains a distinct private rollback directory at
`governance/restores/<random-operation>/`. Its `before/` tree holds the exact
original bytes of files being overwritten and target SQLite sidecars being
removed. `receipt.json` binds their sizes/hashes, expected prepared-file
sizes/hashes, target path/filesystem identity and manifest SHA-256. Absent
targets and sidecars are explicit null entries. This is not a full state-root
backup, nor the imported snapshot's separate migration backup.

Private-file publication rechecks the prior target immediately before
replacement, after the replacement copy is complete. A newly appeared,
disappeared or changed target fails `state_permissions_unsecured`; intervening
bytes are not overwritten by that publication. Hard-linked existing private
output targets are rejected. This check does not provide atomic conditional
replacement against arbitrary nonparticipating writers.

Restore propagates the journal-verified prior target through the final
replacement/removal helpers; rollback similarly binds its known-before/after
byte proof to the target it is about to change. Staged and backup sources are
copied with bounded reads and verified against the expected complete size and
SHA-256 before publication, including same-length content changes. Private
read checks do not reapply permissions after capturing source metadata.
POSIX output retains its creator descriptor through publication or cleanup,
checks the temporary name against that descriptor, and leaves substituted
names untouched. An uncertain temporary file requires review, not blind
deletion. None of these checks relaxes the offline-import precondition.

On Windows, ordinary source reads and directory enumeration hold native
no-reparse parent handles. Regular source readers deny write/delete sharing,
so incompatible open writers cause refusal rather than an unfenced read.
Handle duplicates are binary and noninheritable; the original pin outlives
each reader. SQLite online backup instead holds an identity-only database
pin that permits writes but denies rename/delete. It does not read
the source through a raw file descriptor or checkpoint source WAL. Its native
read-access request enforces sharing; the wrapper never exposes a payload
reader. Directory leases require listing/traversal rights.

Windows private output retains its exclusive creator descriptor and publishes
by handle relative to a checked parent lease. The final parent permits the
OS's child-rename write open only after the temporary file exists; ancestors
stay pinned. An absent target uses native nonreplacement semantics. Rename
accepts only a plain leaf name, subject to Windows' 255 UTF-16-unit component
limit, with no device/stream/traversal interpretation. Pre-rename cleanup and
target removal use checked deletion handles, not pathname unlink. A failed or
uncertain rename retains its private temporary evidence; do not blindly remove
it. Recovery-directory creation also holds parent leases. The filesystem and sharing requirements apply to each path involved in the operation.

Snapshot creation is exclusive: a pre-existing staging database is never
overwritten. The creator descriptor stays open until both SQLite connections
close; Windows uses read/write sharing without DELETE access or sharing.
Permission repair and private-parent creation hold parent/file leases as
appropriate, including final SQLite database/sidecar hardening after connections
close. Private JSON projections and the manifest use the same pinned atomic
output path as other portable files. These changes add no CLI flags or authority
and do not remove the POSIX pathname-stability/offline requirements.

Read-only database inspection rejects symlinked, non-private or changed input
before querying. It retains Windows parent/database pins until the connection
has closed and rechecks the named file afterward. POSIX retains only a parent
descriptor alongside SQLite, avoiding raw database-descriptor lock effects;
its pathname checks are not atomic protection from same-account writers.
New one-shot import receipts retain their exclusive creator through final
verification. Partial creation remains private recovery evidence. Retained
migration-backup copies require expected complete source bytes and an absent
destination through publication; an intervening destination is preserved.
Receipt reads verify protection within their pinned read scope, without repair.

The receipt progresses through `preparing`, `prepared`, `applying` and
`restored`; handled pre-publication failure records `not_applied`, proven
ordinary rollback records `rolled_back`, and failed/uncertain rollback records
`recovery_required`. A process exit can leave an earlier phase. Treat these
as recorded observations and revalidate all bytes before recovery, not as
current-state guarantees or authorization. No new restore is automatically
replayed from these journals. The existing governed one-shot complete-byte
recovery contract remains separate.

Writable store startup, the schema runner, export and a new restore check both
root-wide recovery journals and import reservations. An `applying` or
`recovery_required` journal, or an `applying` or `restored` import reservation,
blocks admission with `bundle_restore_recovery_required`. Startup checks again
under its migration lock before writable setup. Read-only diagnostics remain
available. Historical pre-publication and proven terminal phases do not claim
that current target bytes still match their recorded hashes.

Admission reads only private regular receipt files: at most 1,024 combined
journal/reservation records and 16 MiB aggregate metadata, plus the existing
8 MiB control-file ceiling. These lower-only Python `ArchiveLimits` fields are
`recovery_records` and `recovery_metadata_bytes`; no CLI increase is available.
Immediate directory enumeration is bounded; backup payloads are never walked
or hashed during admission. Missing/unsafe/malformed records, unexpected
registry names (including an abandoned import temporary file), or exceeded
bounds require explicit review without automatic repair or evidence deletion.

Before publication, a governed prepared receipt binds `restore_recovery_id`
to its exact journal. Existing complete-file crash finalization checks this
identity, manifest, root identity and prepared hash inventory, then proves all
target bytes. It may finalize that journal's metadata before consuming the
one-shot receipt; another pending journal/reservation still blocks it. This
does not replay any file replacement. A valid older receipt without a journal
binding remains eligible for its existing full-byte recovery only when no
pending journal needs an inferred association. A missing explicitly linked
journal is never interpreted as the older format.

All original-file copies and the complete prepared plan are written before
the first target payload mutation. Copying applies the same per-file and
aggregate byte ceilings to the old target set (including up to three SQLite
sidecars); the receipt has the control-JSON cap. A target exceeding those
bounds is rejected before replacement even if the incoming ZIP fits.
Prepared files are checked again after staged migration/audit preparation,
including member count, per-file/control size and aggregate expansion.
Rollback validates original-copy hashes, attempts independent files after a
failure, and refuses to erase target bytes matching neither the recorded
before nor after state. Failed rollback reports `bundle_restore_recovery_required`
with the private receipt location. Keep all writers stopped and retain that
directory for explicit review; do not delete it or retry another import to
hide a partial operation. Successful and rolled-back operations also retain
their recovery directories; there is no automatic retention cleanup.

Freshly applied imports return `restore_recovery` with `receipt_path`,
`status`, `backup_files` and `backup_bytes`. This metadata does not authorize
restoration, migration or release. Existing recovered one-shot imports retain
their prior recovery response shape.

New exports use the closed `op-sys.bundle.v2` envelope and its restricted JSON
canonicalization. Default export requires an active signer; it does not generate
a key or quarantine legacy custody. `--no-sign` explicitly sets unsigned policy.
`state import` accepts only `verification_state: "verified_trusted"` by default.
The other states are `valid_untrusted`, `invalid`, `unsigned`, and
`legacy_insecure`; none grants import authority. Unknown keys require the
separate fingerprint-confirmed `trust add` workflow. Required signature removal
fails with `bundle_signature_missing`; editing policy to unsigned does not
clear the default `bundle_unsigned` rejection. Invalid signature inspection
returns structured facts with `valid: false` and exit code 2. Structural
errors use the normal error envelope. `signature_status` is a deprecated,
derived compatibility field, not the admission policy.

Verification reports canonical manifest/signature digests, signer fingerprint,
signed-at, separate mathematical/trust/archival facts, the public trust snapshot,
evaluation time, and `not_online_checked` freshness. Independent explicit notary
proofs can preserve archives across ordinary signer expiry; self-asserted time
cannot clear compromise. See [bundle-v2.md](/docs/raw/manuals/bundle-v2.md) for the exact verification and import policy. Import review additionally binds schema,
admission mode and exact signature into its one-shot approval; pre-v2 approvals
cannot authorize new imports.

Exports omit `keystore.json`, including unsigned exports. Context inspection,
verification and ordinary import reject legacy bundles containing that entry
with `legacy_private_material`. The explicit legacy recovery exception only
hash-checks and discards the exact root entry, never parses or installs it.
Preserve the original privately. The complete normalized `trust/` tree is also
reserved and rejected with `bundle_trust_reserved`. New signatures are Ed25519;
the importer needs explicit public trust, cryptographic validity and valid
signing-time status or an accepted independent archival anchor. V1/HMAC input
is always `legacy_insecure`. `approval request --bundle` and `state import`
accept mutually exclusive `--allow-unsigned` / `--allow-legacy-insecure` with
the same exact non-secret `--override-reason`. Both require an explicitly
approved intent even under zero-vote policy and return untrusted recovery
facts plus a high-severity audit. Invalid signatures and unknown signed v2
keys cannot bypass. The proposed policy caps grant lifetime at six hours
(lower existing policy limits still apply) and closes legacy recovery at
2026-12-22 00:00:00 UTC. See [the full dated policy and command sequence](/docs/raw/manuals/bundle-v2.md#explicit-untrusted-recovery-policy-proposed)
for eligibility, exact binding, retention and unchanged offline writer/rollback
requirements. Owner policy acceptance remains pending.
Export exclusion does not remove sensitive
content a user has independently placed inside ordinary artifacts.

Source collection fails with `bundle_source_unsafe` for symlinks/reparse points,
non-regular files, hard-linked aliases and missing or escaping explicit skill
contract references. The error identifies the path, not its contents. Replace
the source with a contained regular file; no link-following bypass is provided.
Contained parent-relative skill references remain supported after checking each
component. Skill frontmatter is limited to 1 MiB and must remain byte-stable
while read.

Export captures source identity and size before copying, hashes complete bytes
while streaming, and rejects detected source changes before publishing. Known
managed key/database/sidecar identities cannot become workflow payloads through
skill references or filename aliases. Artifact references and generated
governance projections come from the SQLite snapshot; workflow metadata comes
from the staged files, not a second live read. The SQLite online backup pins a
read transaction, includes committed WAL content, and checks logical page size
before copying. Its source read transaction ends when backup completes, before
private-copy validation and compaction; the source identity protections and
lifecycle guard remain active. A source-close failure aborts export. Only the
private backup is normalized to standalone rollback-journal mode; export does
not checkpoint or change the live journal mode.

The private snapshot must pass full `integrity_check(1)`, foreign-key validation
and the shared provenance/schema inspection before compaction or publication.
Unknown/corrupt layouts and invalid migration history are rejected, not repaired
by export. A supported legacy snapshot remains portable without migration;
migration still occurs only in the verified import path. Archive database
verification uses the same full integrity gate before semantic validation.

Archive input uses one bounded reader for context, verification, approval
review and restore. It accepts regular-file stored/DEFLATE ZIP members,
including consistent ZIP64 headers and signed/unsigned data descriptors.
Member names must be exact, unique and portable: no traversal, backslashes,
control/format characters, directory entries, file/directory conflicts,
Windows aliases or Unicode-normalized/case-fold collisions. Encrypted,
unsupported, overlapping, CRC-invalid or undeclared members are rejected.
Unknown or link-bearing extra fields are unsupported; only consistent ZIP64,
timestamp, inert UID/GID and identical Unicode-name metadata is accepted.
Permissions, ownership and timestamps are never restored from ZIP metadata.

`state export`, `state verify`, `state import` and `approval request --bundle`
accept the following lower-only limits. Defaults equal compiled maxima; values
must be positive integers. Byte units are binary (MiB = 1,048,576 bytes).

| Option | Default / compiled maximum |
| --- | --- |
| `--max-archive-bytes` | 17,179,869,184 (16 GiB) |
| `--max-entries` | 8,192, including `manifest.json` |
| `--max-entry-bytes` | 34,359,738,368 (32 GiB expanded) |
| `--max-total-bytes` | 68,719,476,736 (64 GiB expanded) |
| `--max-filename-bytes` | 1,024 (encoded name and UTF-8) |
| `--max-path-depth` | 16 components |
| `--max-compression-ratio` | 200 expanded bytes per compressed byte |

Additional compiled input ceilings are 8 MiB per JSON/control entry, 16 MiB
central directory, 4 KiB extra fields per header and 4 KiB per comment.
Export reserves up to 28 additional central-directory bytes per member for
ZIP64 sizes/offsets when selected byte ceilings permit ZIP64. A tightly lowered
central-byte budget can therefore be refused conservatively before copying,
even if the final compressed members would not have needed every reserved byte.
Export shares the member, name, size and control ceilings. Its source inventory
is capped at 65,536 visited nodes across the state/repository/skill collectors
(including directories and scanned but unselected names). Artifact-reference
queries also cap returned rows at 65,536 and path bytes at the filename limit.
SQLite backup, validation and private-copy compaction share a 3,600-second cooperative deadline,
checked between backup steps and SQLite VM work; this is not a deadline for
blocked operating-system I/O or the whole export. These two export limits have
no CLI switches; Python `ArchiveLimits` callers may only lower them.

Each read-only database inspection additionally permits at most 4,096 schema
objects (`database_objects`), 32,000,000 aggregate physical-table rows
(`database_rows`, including SQLite metadata and FTS shadow-table rows), and
3,600 cooperative seconds (`database_seconds`). These are compiled, lower-only
Python limits without new CLI flags. Duplicate rows count before workflow
deduplication. SQLite values/encoded rows and generated SQL are also bounded by
the 8 MiB `control_bytes` ceiling (values/rows additionally respect `entry_bytes`).
An independent lower-only `database_schema_bytes` ceiling of 8 MiB admits
aggregate schema fingerprint input before shared validators materialize it.
Its conservative estimate is three framing bytes plus, for every `sqlite_master`
object, 20 framing/null bytes and six times the total UTF-8 byte lengths of
`type`, `name`, `tbl_name` and `sql`. Null fields contribute zero input bytes.
This reserves JSON escaping and includes internal objects, so a literal schema
smaller than 8 MiB can still be rejected. It does not change fingerprint bytes
or migration checksums. SQLite's initial native schema loading precedes this
check and is not protected by a process-wide memory quota.
Inspection uses `mode=ro`, `query_only`, `trusted_schema=OFF` and a read transaction;
the deadline covers each connection, not all inspections or blocked OS I/O.
Workflow contexts and their combined operation output must fit the control-byte
budget. Metadata scans stream rows instead of materializing entire result sets.
Recovery hashes stop at the captured file length plus one detection byte and
respect selected per-file, aggregate and entry-count limits; they cannot wait
indefinitely for a growing file to reach EOF.

Byte, row and time limits do not establish an entity-count capacity guarantee.
History, audit/events, search indexes and artifacts all consume capacity.
Use the documented limits when sizing storage and recovery operations.

Refused databases require review and a supported export/recovery path.
Do not increase limits locally, repair schemas or migrate live data to bypass
a failed inspection.

Compressed input and expanded output are streamed in chunks of at most 64 KiB;
actual lengths, CRCs and SHA-256 digests must agree. Archive records cannot be
prefixed, padded, split or followed by extra data. `bundle_limit_exceeded`
identifies the exceeded limit; `bundle_limit_invalid` rejects an attempted
increase or disabled limit. Python callers can supply a lower `ArchiveLimits`
to export and input APIs; no unbounded switch exists. Re-export oversized/high-ratio
legacy content within the profile or obtain review of a new bounded format;
do not raise limits locally. These input limits do not constitute approval of
production use. Export bounds collection and staged copies, hashes ordinary
source files in at most 1 MiB chunks, and bounds ZIP writes before bytes reach
disk. It checks the completed ZIP against this same profile before atomic
publication; a rejected export leaves an existing output file unchanged.
These checks do not semantically approve an exported database or replace
verification, migration prerequisites or independent recovery evidence.

Structural bundle and import admission failures use JSON error envelopes.
Signature inspection instead retains structured `invalid` facts with exit 2.
Import reasons distinguish `bundle_signature_missing`, `bundle_signature_invalid`,
`bundle_signer_untrusted`, `bundle_unsigned`, `bundle_legacy_insecure`, and specific
anchor/time failures; the old aggregate `bundle_signature_unverified` is no
longer used. The low-level kernel `import_bundle()` is internal/test-only and
refuses unguided use; even its test-only entry retains signature admission.
The CLI and `OpSys.state.import_bundle()` always use governed one-shot import.
This does not authorize any production rollout.

## Opaque identifiers and managed paths

Resource IDs and relational ID references use one public opaque grammar:
ASCII, 1–128 characters, beginning with an ASCII alphanumeric character and
continuing with ASCII alphanumerics, `_`, `-`, or `.`. The whole values `.` and
`..` are invalid, as are `/`, `\`, NUL, whitespace, control/format characters,
absolute paths, drive/UNC forms, option-like leading dashes, and non-ASCII
confusables. Worker, entity, event, and relation types plus comment and
artifact kinds use a stricter lowercase, letter-first, 1–64-character subset;
workflow namespaces retain their documented lowercase dotted grammar.

Creation, foreign-key writes, and operational mutations reject invalid values
with a field-specific reason such as `entity_id_invalid`, `worker_id_invalid`,
`session_id_invalid`, `approval_id_invalid`, `event_type_invalid`,
`relation_type_invalid`, `comment_kind_invalid`, `artifact_kind_invalid`, or
`worker_type_invalid`.
Bundle verification rejects an invalid stored ID or foreign-key reference with
`bundle_identifier_invalid` and reports only its table and field, never the
value. Existing unsafe local IDs remain available to state export and
non-operational recovery inspection, but `doctor` reports them and operational
mutation/launch refuses them with a field-specific reason or
`unsafe_runtime_identifier`; they require a separately audited relational
remap or export/recreation rather than silent rewriting.

Isolation directories, worktree targets, and Git run branches use a hash plus
a generated run token. Automatic session logs use a random run token. The
original IDs are metadata, not path components. Recursive cleanup requires a
canonical direct managed child and a matching per-run marker. Pre-existing
unmarked directories are not automatically deleted.

## Sessions

Sessions track externally launched or supervised worker processes. They are public CLI records, separate from claims.

```bash
op-sys session create \
  --worker incident-agent \
  --command './incident-worker' \
  --log-path .op-sys/logs/incident-agent.log \
  --execution '{"entity_id":"ent_...","runtime":"codex"}'

op-sys session show --id <session-id>
op-sys session list --worker incident-agent
op-sys session running --id <session-id> --pid 12345
op-sys session completed --id <session-id> --exit-code 0
op-sys session failed --id <session-id> --exit-code 1 --error "worker failed"
op-sys session stop --id <session-id>
op-sys session stop --id <unmanaged-session-id> --record-only
op-sys session restart --id <session-id> --log-path .op-sys/logs/restart.log
```

Singular session commands return `{ "session": {} }`; list returns `{ "sessions": [] }`.

Normal `stop` coordinates with the owning controller, verifies the exact process
tree's exit, then atomically records/audits/emits stopped. Missing or reused
identity and unconfirmed exit return `session_process_unverified`, without a
termination claim. `--exit-code`, if supplied, must match the native exit receipt.
The bounded wait occurs outside SQLite's writer transaction; a timed-out request
can still be processed later. An already-completed normal run remains terminal.

`--record-only` is unsafe record recovery, not process termination: it sends no
stop request and uses distinct `session.stop_record_only` audit and
`session.stopped_record_only` event names. It cannot authorize restart or cleanup.
`restart` requires a terminal record plus verified tree-exit evidence and creates
a new pending session without the old process binding. Manual `completed`/`failed`
records remain supported, but a managed process cannot acquire terminal status
without exit proof. See [stop/recovery semantics](/docs/raw/manuals/worker-runtime-contract.md#stop-recovery-and-restart).

Session `process_state` (also exposed as `lifecycle_state`) is `live`, `exited`,
`unverified` or `identity_reused`. A missing process identity never becomes
verified merely because `pid_alive` is false or the row's `terminal` flag is true.
`execution.entity_id` and `execution.worker_id` are exact opaque IDs;
`execution.entity_type`, `execution.worker_type`, and `launch.worker_type` use
the stricter type-name grammar. The same rules apply to the duplicated
`metadata.execution` object and to `launch.match.entity_ids` /
`launch.match.entity_types`. Manual/public session input cannot persist
non-empty `execution.isolation` or claim the managed worker-session launch
marker. Both are accepted at creation only through the private built-in launch
manager registration capability; copying the marker into public input never
grants provenance. Read-only store/export recovery of older records remains
available, while operational session APIs fail closed before PID inspection or
lifecycle mutation.

## Workflow Skill Contracts

Workflow skill contracts are advisory metadata discovered from:

- `<state-root>/workflows.json`
- `<state-root>/workflows/*.json`
- `<repo>/op-sys.workflows.json`
- `<repo>/.op-sys-workflows.json`
- `<repo>/.op-sys-workflows/*.json`
- `<repo>/.agents/skills/*/SKILL.md` frontmatter key `op_sys_workflow_contract`
- `<repo>/.codex/skills/*/SKILL.md` frontmatter key `op_sys_workflow_contract`
- `<repo>/skills/*/SKILL.md` frontmatter key `op_sys_workflow_contract`

Commands:

```bash
op-sys workflow list
op-sys workflow show --workflow example.incident --version v1
op-sys workflow validate --file ./workflow.json
```

The worker runtime exposes this metadata under `workflow.skill_contract`, with optional derived `workflow.instructions` and `workflow.metadata` fields when the contract provides worker-facing guidance. Skill contracts are not plugins. Unknown valid entities and events remain acceptable unless strict validation or policy explicitly rejects them.

Contract files use the same strict workflow contract shape accepted by service-level validation. Supported top-level fields are:

- `schema_version`: must be `op-sys.workflow-contract.v1`
- `namespace`: lowercase dotted workflow namespace such as `example.workflow`
- `version`: non-empty workflow version
- `title`, `description`, `instructions`, `worker_instructions`: optional human or worker-facing text
- `metadata`: optional workflow-owned JSON object
- `entity_types`, `event_types`, `relation_types`: mappings keyed by workflow type name
- `recommended_commands`: optional canonical CLI command names such as `ledger entity create`
- `view_conventions`, `worker_result_conventions`: optional string arrays for external surfaces and workers

Type contracts support:

- `entity_types.<type>.required_data_fields`: list of required keys in entity `data`
- `entity_types.<type>.data_schema`: compact JSON-schema subset for entity `data`
- `event_types.<type>.entity_types`: list of entity types the event applies to
- `event_types.<type>.payload_schema`: compact JSON-schema subset for event `payload`
- `relation_types.<type>.from_entity_types`: allowed source entity types
- `relation_types.<type>.to_entity_types`: allowed target entity types

The compact JSON-schema subset supports `type`, `properties`, `required`, `items`, `additionalProperties`, `enum`, `minimum`, `maximum`, `minItems`, `maxItems`, `minLength`, `maxLength`, and annotation keys `$id`, `$schema`, `title`, `description`, `default`, and `examples`. Supported JSON types are `object`, `array`, `string`, `number`, `integer`, `boolean`, and `null`.

The type sections are mappings; empty objects keep the consumer story simple, while `data_schema`, `payload_schema`, and relation bindings can be added when strict validation is needed:

```json
{
  "schema_version": "op-sys.workflow-contract.v1",
  "namespace": "example.workflow",
  "version": "v1",
  "entity_types": {
    "example_entity": {}
  },
  "event_types": {
    "example_entity.created": { "entity_types": ["example_entity"] }
  },
  "relation_types": {
    "related_to": {}
  }
}
```

Workflow namespaces must use lowercase dotted segments such as `example.incident`. Entity, event, and relation type identifiers follow the ledger command rules: lowercase, start with a letter, and then use lowercase letters, digits, `_`, `.`, or `-`.

## Workers

Workers are identities for externally owned commands:

```bash
op-sys worker create \
  --id incident-agent \
  --type incident-responder \
  --mode autonomous \
  --command './incident-worker' \
  --match-entity-type incident \
  --match-workflow example.incident
```

Workers should read the runtime payload and write workflow-neutral results: events, comments, artifacts, and release instructions. See [worker-runtime-contract.md](/docs/raw/manuals/worker-runtime-contract.md).

Worker environments are allowlisted and bounded. Declare additions with `env`;
credential-like names require `metadata.worker.execution.secret_env` and are
never taken from ambient credentials. Secret values are literal and managed
launch/session/envelope/result serialization is redacted. `schema show --surface
worker-runtime` reports the exact base names and byte/count limits. See the
[environment contract](/docs/raw/manuals/worker-runtime-contract.md#environment) for error reasons
and compatibility changes. Avoid supplying secrets in command-line arguments.

Worker run reports include a private `log_path` and machine-readable `reason`.
`worker_output_limit_exceeded` means the result was withheld and tree shutdown
was attempted; it is not a successful truncated result. Failed tree/pipe
verification retains isolation for recovery. Configure byte budgets at
`metadata.worker.execution.output_limits`; `schema show --surface worker-runtime`
lists exact defaults and ceilings.

Copy/worktree/branch isolation constrains change application and cleanup; it
does not sandbox the worker process at the operating-system boundary.

See [Cloud client safety](/docs/raw/manuals/cloud-client.md) for the precise capability/credential
input, generation recovery, retention, environment and compatibility contracts.
See [MCP lifecycle](/docs/raw/manuals/agent-mcp.md#protocol-and-lifecycle) for initialization,
protocol versions, transport limits and error semantics.

### Shared consumer-defined ledgers

`ledgers create`, `ledgers inspect`, `records append` and `records list` use the
ledger operations through the selected local or hosted connection. Inspect the
[guide to how ledgers work](/docs/raw/manuals/ledger-core.md) and the command's `--help` for current inputs.

Use `ledgers clone` for an authorized local copy, `ledgers sync` for
explicit bounded reconciliation, and `ledgers status` for progress. A remote
remembers a destination; configuring it does not upload records. See
[replicas](/docs/raw/manuals/ledger-replicas.md) and [connections](/docs/raw/manuals/client-connections.md).

`authority transfer` and `authority resume` perform a fenced handoff while
retaining accepted history and retry outcomes. [Authority transfer](/docs/raw/manuals/ledger-authority.md)
describes destination administration and resumption. [Portable archives](/docs/raw/manuals/ledger-portability.md)
use `ledgers export` and `ledgers import`; imported history does not gain authority.

State rules are ledger configuration: use `ledgers update`, ordinary
`records append`, and `records state`; there is no public views namespace.
`groups` manages authorization and `collections` saves ledger selections for
`records search/feed`. [Surrounding capabilities](/docs/raw/manuals/ledger-surrounding.md)
covers their permissions, conditional acceptance and retrieval bounds. [Files](/docs/raw/manuals/ledger-files.md)
use `files` operations and same-ledger attachments. No record enrollment, adoption
or legacy synchronization commands remain.

## Named client connections

CLI, SDK and MCP share named connections, per-ledger remotes and explicit client
selection. See [client connections](/docs/raw/manuals/client-connections.md) for setup, precedence, identity
association and direct HTTP integration. Endpoint changes require fresh authentication.

See [how ledgers work](/docs/raw/manuals/ledger-core.md) for the common local/hosted ledger operations, governed contracts, permissions and append outcome recovery.

File uploads accept paths or streams up to 1 GiB and checkpoint acknowledged
progress. `files download --output-file` streams into an adjacent temporary file
and publishes it only after size and SHA-256 verification. Local files require
no AWS setup. See [files](/docs/raw/manuals/ledger-files.md) for storage, access and backup behavior.
