# Command And Output Schema Guidance

Use `op-sys --output json` when integrating with the CLI.

Local query events/tail retain `payload.events` and add `next_cursor`,
`has_more`, `limit`, normalized `order`, effective `filters`,
`snapshot_sequence`, and bounded `candidate_count`. Context carries these
under `payload.context`; search carries ranked `items`, positive `text_score`,
matching-field reasons, `result_count`, cursor and lookahead/budget-based
`truncated` under `payload.search`. Search order is
`score_desc_then_sequence_desc`; ordinary local order is `sequence_asc` or
`sequence_desc`. `candidate_count_is_total=false` on local search explicitly
distinguishes fetched candidates from a total count. See
[local query semantics](/docs/raw/manuals/local-query.md). Cloud checkpoint envelopes remain
independent and there is no combined cross-scope cursor.

## Envelope

Every JSON response uses:

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

The envelope is stable. Payloads may gain additive fields during `0.x`.

## Stable Payload Families

Trust uses `schema show --surface trust` and secret-free payloads:

- `trust keygen|rotate|add|revoke`: `{ "key": { ... } }`
- `trust list`: `{ "keys": [ ... ] }`
- `trust fingerprint`: `{ "algorithm": "Ed25519", "key_id": "...", "fingerprint": "ed25519:sha256:..." }`
- `trust public export`: `{ "public_key": { ... } }` (the same closed public document written to the output)
- `trust remove`: `{ "fingerprint": "...", "removed": true }`
- `trust legacy status|destroy`: `{ "legacy": { ... } }`
- `trust notary add|revoke`: `{ "notary": { "key": <public-document>, "label": "...", "source": "public-key-file", "trusted_at": 0, "incident_policy": "op-sys.pre-cutoff-anchor.v1", "enabled": true, "disabled_at": null } }`
- `trust notary list`: `{ "notaries": [...] }`, including disabled public history; never seeds or automatic trust.
- `trust notary remove`: `{ "fingerprint": "...", "removed": true, "history_retained": true, "disabled_at": 0 }`; removal is permanent for this fingerprint, not history erasure.

Key summaries add `key_id`, `active` and `scope` to the public document;
trusted lists also include `label`, `source` and `trusted_at`. Public JSON
and byte-signature envelope fields are defined in [trust.md](/docs/raw/manuals/trust.md).
Every timestamp is an integer UTC Unix second. Verification primitives expose
`cryptographically_valid`, `trusted`, `signer_status_at_signing` and
`trust_evaluated_at` independently; bundle admission uses structured
`verification_state`, not the deprecated aggregate `signature_status`.
`signature` uses canonical unpadded base64url, not HMAC hex.
No seed or legacy secret appears in these shapes.

Legacy status reports `present`, `insecure`, `active`, `destroyed`, and
`recovery_window_open`; a recorded quarantine also adds `quarantined_at`,
`destroy_after`, `destroyed_at`, and `destruction_pending`. A destruction fence
with a remaining file reports pending, not deleted. Successful destroy returns
`destroyed`, `quarantine_present: false`, and `destroyed_at`. It proves logical
file removal, not erasure of media, memory or backups.

Generic ledger commands return resource-keyed payloads:

- `ledger entity create|show|update|patch`: `{ "entity": { ... } }`
- `ledger entity list`: `{ "entities": [ ... ] }`
- `ledger event append`: `{ "event": { ... } }`
- `ledger event list`: `{ "events": [ ... ] }`
- `ledger relation add|remove`: `{ "relation": { ... } }`
- `ledger relation list`: `{ "relations": [ ... ] }`
- `ledger claim|release`: `{ "claim": { ... } }`
- `ledger comment`: `{ "comment": { ... } }`
- `ledger artifact attach`: `{ "artifact": { ... } }`
- `ledger batch`: `{ "batch": { ... }, "results": [ ... ], "refs": { ... } }`

Approval commands return:

- `approval request|show|decide|revoke`: `{ "approval": { ... } }`
- `approval list`: `{ "approvals": [ ... ] }`

Worker type commands return:

- `worker-type create`: `{ "worker_type": { ... } }`
- `worker-type list`: `{ "worker_types": [ ... ] }`

Worker commands return:

- `worker create|show`: `{ "worker": { ... } }`
- `worker list`: `{ "workers": [ ... ] }`

Default worker create/update/show/list views redact configured secrets. A
redacted display is not a credential-bearing configuration round trip.

Managed launch serialization can include `secret_env`, the explicitly allowed
environment-name list. Corresponding values are `[REDACTED]` in launch/session
records and worker envelopes. Prepared execution values are not a serialized
output contract. `worker-runtime.environment_policy` in schema discovery gives
the base allowlist and count/value/total byte limits. See the
[worker environment contract](/docs/raw/manuals/worker-runtime-contract.md#environment).

Worker execution and resolved launch contracts include `output_limits` with
integer `stdout_bytes`, `stderr_bytes`, `log_bytes`, and `line_bytes` fields.
Managed sessions retain it in both `launch` and `execution`; manually created
or historical execution records may omit it. Schema discovery reports the
defaults and hard bounds at `worker-runtime.output_limits`. See the
[output budget contract](/docs/raw/manuals/worker-runtime-contract.md#output-budget-configuration).

Supervised worker run reports add `reason` (a machine-readable failure reason,
or `null`) and `log_path`. Session-backed runs store the additive version-1
`execution.process` object with exact session/worker bindings, control locator,
native identity and owner identity. It contains no native handles or credentials.
Older/unmanaged sessions can omit this object and do not thereby acquire safe
process-control authority. See the [controller contract](/docs/raw/manuals/worker-runtime-contract.md#controller-logs-and-exit-receipts).

Session commands return:

- `session create|show|running|completed|failed|stop|restart`: `{ "session": { ... } }`
- `session list`: `{ "sessions": [ ... ] }`

Session `process_state` and `lifecycle_state` share the values `live`, `exited`,
`unverified`, and `identity_reused`. `terminal` reflects recorded status only;
`pid_alive` is not process-tree authority. Version-1 `execution.process` contains
`version`, `session_id`, `worker_id`, `control_id`, `identity`, and `owner`.
The native `identity` is a POSIX group (platform, PID/PGID, boot/start identity)
or Windows job (platform, PID, creation identity, random job token); `owner`
contains controller PID/start identity. Unknown versions/fields or mismatched
session/worker/PID bindings fail closed. Older records can omit the object.

Verified stop sets reserved `metadata.record_only_stop=false`, with audit action
`session.stop` and event `session.stopped`. `--record-only` instead sets true and
uses `session.stop_record_only` / `session.stopped_record_only`, without a process
termination claim. `session_process_unverified`, `session_stop_transaction_active`,
`session_stop_provenance_invalid`, and `session_stop_required` use the ordinary
error envelope. See [stop/recovery semantics](/docs/raw/manuals/worker-runtime-contract.md#stop-recovery-and-restart).

Policy commands return:

- `policy show|set`: `{ "policy": { ... } }`

Audit commands return:

- `audit list`: `{ "audits": [ ... ] }`

Workflow skill contract commands return:

- `workflow list`: `{ "workflows": [ ... ] }`
- `workflow show`: `{ "workflow": { ... } }`
- `workflow validate`: `{ "valid": true|false, "results": [ ... ] }`

Doctor commands return:

- `doctor`: `{ "ok": true|false, "checks": [ ... ] }`; checks include the secret-free `persisted_identifiers` result after the state store is readable

Self-management commands return:

- `self version`: runtime metadata, including `installed`, `execution_mode`, `cli_version`, and `reported_at`
- `self update`: `{ "updated": true, ... }`
- `self uninstall`: `{ "scheduled": true|false, "dry_run": true|false, "runtime_root": "...", "removal_receipt": "..."|null, "validation": { "ok": true, "checks": [ ... ] }, "message": "..." }`

Database schema commands return:

- `schema database` and `schema database migrate`: `{ "database": { "dry_run": true, "inspection": { ... }, "migration": null } }`
- `schema database migrate --yes`: `{ "database": { "dry_run": false, "inspection": { ... }, "migration": { ... } } }`

`inspection` 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`. Each `pending` item contains
`migration_id`, `checksum`, `from_version`, and `to_version`.

When present, `migration` contains `status`, `source_version`,
`target_version`, `source_fingerprint`, `target_fingerprint`, `applied`,
`backup`, and `pruned_backups`. `applied` uses the pending-item shape.
`backup` is null when no migration was needed; otherwise it contains `path`,
`receipt_path`, `sha256`, `source_version`, `fingerprint`, and `size`. These
paths are operator metadata, not database contents. Schema validation and lock
failures use the normal error envelope; bounded writer contention uses
`reason: "schema_migration_busy"`.

A routine startup migration result with `status: "current"`, `applied: []`
and `backup: null` means no schema migration was needed. For admitted local
state it follows identity/schema/history checks, not a whole-database integrity
scan; no integrity attestation is implied or added to that payload. Explicit
schema inspection still performs deep checks and reports its actual
`integrity_ok` and `foreign_keys_ok` observations. The private local admission
record is not a public output or portable trust record.

The schema surface supports migrations only from exact provenance-backed
v4-v9 layouts to v10. Unsupported older, non-empty unversioned, unknown,
corrupt, checksum-divergent, and newer layouts return a non-current inspection
or a normal error envelope and are not rewritten. There is no downgrade
payload or command, and an upgraded database must not be opened with an older
binary.

Retention counts only recognized, revalidated backup/receipt pairs. After a
successful migration it keeps the three newest pairs globally plus the newest
pair for each source version; unknown, malformed, orphaned, and unreadable
artifacts are retained for review. If migration fails, preserve the database
and evidence, stop competing writers, and act on `inspection.reason`,
`inspection.recovery`, or the error `reason`; restore a verified pair only to a
separate private path.

For unsupported or unversioned state, no automatic migration backup exists.
After stopping every writer, preserve a private complete state-root copy and,
where export can read the legacy layout, create an additional unsigned raw
capture:

```bash
op-sys --state-root <legacy-root> state export \
  --out <outside-root.zip> --no-sign
```

`state verify` is expected to reject a capture
whose database schema is unsupported or unversioned. Such a capture is not
importable proof of current-schema validity; retain it for owner-approved
inspection and manual recreation as documented in
[Self-Hosting](/docs/raw/manuals/self-hosting.md#schema-upgrades-and-recovery).

Uninstall validation checks expose only stable check names, booleans, and
value-free remediation/detail categories. Installation IDs are never returned.
`--dry-run` never creates or starts a detached remover. A non-dry-run result
still has `scheduled: false` until `--yes` is supplied. For a scheduled
operation, `removal_receipt` identifies a private value-free file created only
on detached failure; it normally disappears with the helper directory after a
successful removal.
Automated eligibility requires agreeing private root, source, and per-version
installation metadata. Missing or inconsistent legacy metadata requires a
fresh managed prefix and separate manual review of the old prefix. Ledger data
and the resolved state root remain outside uninstall scope.

State commands return:

- `state permissions`: `{ "ok": true|false, "repair_requested": false, "paths": [{ "path": "...", "expected": "0600|0700|current_user_and_system_only_acl", "ok": true|false }], "project_state_git_exclude": { "path": "...", "expected": "/.op-sys/", "ok": true|false, "applicable": true|false, "status": "excluded|missing_rule|not_project_scoped|..." } }`
- `state permissions --repair`: the same shape with `repair_requested: true`; values remain path/status metadata only
- `state export`: `{ "manifest": { ... }, "signature": { ... }|null }`
- `state verify`: manifest, database-schema and archive diagnostics, plus `bundle_schema`, `verification_state`, `reason`, `manifest_sha256`, `signature_sha256`, `fingerprint`, `key_id`, `signed_at`, `cryptographically_valid`, `trusted`, `signer_status_at_signing`, `trust_evaluated_at`, `trust_snapshot`, `archival_validity`, and `remediation`. States are `verified_trusted|valid_untrusted|invalid|unsigned|legacy_insecure`. `valid` is false for invalid signatures/proofs (exit 2); an inspectable unsigned/legacy archive is not an import authorization. Structural errors use the normal error envelope.
- `state import`: the same facts, accepted only as `verified_trusted` by default, plus `database_migration`, `restore_recovery` and `import_receipt: { "manifest_sha256": "...", "operation_digest": "...", "status": "consumed", "recovered": false }`. Governed import requires a database snapshot. Explicit approved recovery returns `unsigned` or `legacy_insecure`, never trusted, and additionally `recovery: { "mode": "unsigned|legacy_insecure", "policy": "op-sys.bundle-recovery.v1", "untrusted": true, "override_reason_sha256": "...", "discarded_entries": [{ "path": "keystore.json", "sha256": "..." }], "legacy_cutoff_utc": null, "warning": "HIGH: ..." }`. `discarded_entries` is empty when no key was discarded; legacy recovery reports cutoff `2026-12-22T00:00:00Z`. The warning denies original-provenance authentication. No key bytes or raw override reason appear in these result/audit fields. See [the proposed policy](/docs/raw/manuals/bundle-v2.md#explicit-untrusted-recovery-policy-proposed).

`state export` adds `schema: "op-sys.bundle.v2"`, `signatures` and `anchors`.
Its singular `signature` is an output-only deprecated alias. The ZIP envelope
contains exactly `schema`, `manifest`, `signatures`, `anchors`. Manifest entries
include exact `bytes` as well as `path`/`sha256`. Legacy `signature_status`
is derived as verified (trusted), unsigned (deliberately unsigned v2), or
unverified (all other states); do not use it to authorize import. Public trust
snapshots explicitly say `revocation_freshness: "not_online_checked"`; archival
validity reports independently verified proofs and authority snapshots, not
merely the signer's claimed `signed_at`. See [bundle-v2.md](/docs/raw/manuals/bundle-v2.md).

Freshly applied imports additionally return `restore_recovery`:
`{ "receipt_path": ".../governance/restores/<operation>/receipt.json", "status": "restored", "backup_files": 3, "backup_bytes": 123456 }`.
Counts refer to original overwritten files and removed SQLite sidecars, not
the imported snapshot's migration backup or every file in the state root.
Existing one-shot crash-finalization responses keep their prior shape.
Private rollback receipts use schema `op-sys.restore-recovery.v1`, with
`manifest_sha256`, `target` (path/device/inode), and `files` entries containing
`path`, `before` and `after` (null for absence, otherwise `sha256`/`bytes`).
Their status is `preparing`, `prepared`, `applying`, `restored`, `not_applied`,
`rolled_back` or `recovery_required`; rollback failures include only paths and
error class labels, not payloads. Phases are historical observations, not
current-byte guarantees. Failed rollback uses `bundle_restore_recovery_required`
and identifies the retained private receipt; keep writers stopped for review.

Restore passes its prior target snapshot and expected replacement bytes
through the private I/O helpers; rollback does the same for its known-state
proof. Changed prepared/backup bytes fail before publication, not just during
the final restored-state check. Bounded-copy failures retain the existing
`bundle_source_unsafe`/`bundle_limit_exceeded` diagnostics, while target or
temporary-name safety failures use `state_permissions_unsecured`. If ordinary
rollback cannot prove recovery, `bundle_restore_recovery_required` remains the
outer result. No new response fields or recovery authority are introduced.

Windows handle-based publication/removal keeps those diagnostics. Sharing,
parent, descriptor, private-ACL, or native rename/deletion failures report
`state_permissions_unsecured` unless the enclosing restore reports unproven
recovery. A failed/uncertain rename may leave a private adjacent temporary
file intentionally retained for review. That file is not authority to retry,
delete, replay or finalize an operation.

An existing snapshot-staging destination or a failure to retain its private
creator identity also reports `state_permissions_unsecured`; existing bytes
are not overwritten. Windows database-creator construction failures can leave
a private file in the disposable staging directory. No new response fields,
automatic recovery, or cleanup authority are introduced.

Fresh import-receipt creation uses the same retained-creator checks and refuses
an existing name. A failed write can leave a private partial receipt requiring
review. Read-only SQLite inspection rejects unsafe or changed names with
`bundle_source_unsafe`; native pin failures use `state_permissions_unsecured`.
Retained migration-backup copies preserve absent-target and expected-byte
checks. Enclosing governed-import or restore recovery errors still take
precedence where recovery cannot be proved. No success fields are added.

`bundle_restore_recovery_required` also covers writable startup, schema-runner,
export and new-restore admission when root-wide journals/reservations are
pending, unsafe, malformed, missing or over bounded metadata limits. It does
not disclose receipt payloads or trigger repair/replay.

Store startup rejects a symlink/reparse component in the state-root path first
with `state_permissions_unsecured`, including an absent root below a linked
parent. It does not classify an unsafe root path as interrupted-restore
evidence or create state through that path.

Internal `ArchiveLimits` additionally report `recovery_records: 1024` and
`recovery_metadata_bytes: 16777216`, both lower-only. Read-only diagnostics are
not blocked by this admission check. Governed prepared receipts now include
`restore_recovery_id`; successful exact complete-byte crash finalization may
add `recovery_finalized: true` to its linked `restored` journal. The existing
recovered command response is unchanged; no new approval authority is implied.

`state import` is an offline replacement operation. Every op-sys process and
other writer that can reach the target state root must remain stopped for the
entire command. Its same-process active-store refusal is not a cross-process
writer fence; approval does not enforce or replace this operator precondition.

Export/import now participate in the persistent root schema lock, alongside
migrations and writable startup. Root-lock contention uses
`schema_migration_busy`; detected held-root/lock identity changes use
`schema_lock_unsafe`. No success payload changes are introduced by locking.
Import rejects local `governance` and `locks` archive trees and their normalized
aliases with `bundle_governance_reserved`. These checks do not stop already-open
or unrelated writers, or authorize recovery/publication.

The successful `state verify` shape above applies only when all archive,
database-schema, integrity, and semantic checks pass. Unsupported or
unversioned database schemas instead return the normal error envelope. An
unsigned bundle is not automatically valid or importable; `unsigned` describes
an explicit v2 manifest policy after all other verification gates pass, not
the absence of a stripped required signature.

Verification and import also include `archive`: `archive_bytes`, `entry_count`
(including the manifest), `expanded_bytes`, `legacy_private_material: false`,
and `limits`. The latter records the effective `archive_bytes`, `entries`,
`entry_bytes`, `total_bytes`, `filename_bytes`, `path_depth`,
`compression_ratio`, `control_bytes`, `central_bytes`, `extra_bytes` and
`comment_bytes` ceilings. These are metadata-only diagnostics, not payloads
or a trust assertion. Cap failures use `bundle_limit_exceeded`; invalid or
above-maximum limits use `bundle_limit_invalid`. See the exact ceilings and
lower-only CLI flags in [cli-contract.md](/docs/raw/manuals/cli-contract.md).

`database_schema` is the read-only inspection of the database inside the
verified bundle. A provenance-backed v4-v9 bundle reports
`status: "migration_required"`; verification never migrates or rewrites the
bundle. Governed import runs the shared schema runner on a private staged
copy, prepares consumption/audit there, then publishes the prepared files.
`database_migration` reports `status: "current"` or `"migrated"`; the latter
includes a retained verified backup of the pre-migration imported snapshot,
not a backup of the previous target state. Manifest counts and
`database_schema` describe the original bundle, not the added consumption/audit.
A null `database_schema` applies only to verification of a database-less bundle.

`import_receipt.recovered: true` means a retry verified every prepared target
file and finalized the durable receipt without repeating restore. Partial or
changed state returns `approval_import_recovery_required`; preserve the
receipt and keep writers stopped. Repeated successful import returns
`approval_consumed`. Governance receipts are excluded from portable bundles.

Approval records add nullable `operation_digest`, `intent`, `consumed_at`,
`consumed_by`, and `consumed_event_id`, and state `consumed`. `intent` contains
`schema`, `action`, `actor`, ordered `targets`, resolved `context`, and
`effects` keyed by argument name with `{ "sha256": "..." }` values. Raw
free-form effects are omitted; hashes are not encryption. Schema v12 retains
legacy records with missing intents as non-authorizing. Pending and approved
TTL expiry, current votes, exact digest and one-shot state are checked on use;
failed mutations roll consumption back. Base < team < acting worker-type
policy applies, with explicit matching deny rules retained. Explicit
operator/approver IDs and distinct votes are cooperative metadata, not
authentication. See [the full contract](/docs/raw/manuals/approvals.md) and
[policy example](/docs/examples/approval-policy.json).

`init` retains `state_root`, `bootstrapped_key`, and `team`, and adds
`permissions_hardened` plus the secret-free `project_state_git_exclude`
diagnostic. Doctor adds `state_root_permissions`, `state_file_permissions`, and
the project-only `project_state_git_exclude` check. Permission and doctor
outputs never include state-file contents.

An ordinary initialized-state command that had to repair upgrade-time
permission or project-exclude drift adds
`"state_permissions_repaired": true` to its normal result. This additive field
is absent when no repair was needed and is never added by `doctor`, read-only
`state permissions`, or `state verify`.

Database-schema inspection counts only receipt-backed backups whose current
bytes, SQLite integrity, version, and fingerprint revalidate. It exposes
`backup_inventory_status` (`empty`, `verified`, `invalid`, or `unreadable`)
and a null or stable value-free `backup_inventory_reason`. A migration backup
payload includes `receipt_path` beside its path and hash metadata.

State bundle manifests expose `ledger.substrate_config_paths` for portable substrate config files. This includes `team.json` for compatibility and worker launch context; it does not define a public CLI surface.

`keystore.json` is absent from exported entries and `substrate_config_paths`:
legacy HMAC/private keys remain local. Context, verification and import reject
an archive carrying the legacy keystore with `reason: "legacy_private_material"`
before restoring anything; the diagnostic does not expose key values.
The entire `trust/` tree is likewise non-portable and reserved:
`reason: "bundle_trust_reserved"` rejects such entries before restore.

Unsafe export collection uses `reason: "bundle_source_unsafe"` and a quoted
source path without payload bytes. Source symlink/reparse/non-regular/hard-link
failures, invalid explicit skill references, and oversized or changing skill
frontmatter are rejected. Output targets still cannot replace or alias managed
private files, including the non-exported keystore; those failures retain
`reason: "state_permissions_unsecured"`.

Export applies the same lower-only CLI limits as verify/import. Exceeded
source inventory, byte, control-metadata, ZIP output or cooperative SQLite
snapshot-time bounds use `reason: "bundle_limit_exceeded"` and identify the
limit without payload data; invalid/raised limits use `bundle_limit_invalid`.
The internal export maxima include `source_nodes: 65536` and
`snapshot_seconds: 3600`; the latter covers backup/validation/private compaction, not the
entire export or blocked OS I/O. Detected source identity/size changes use
`bundle_source_unsafe`. Failed export leaves existing output bytes unchanged.

Read-only database inspections expose lower-only limits `database_objects: 4096`,
`database_schema_bytes: 8388608` (conservative aggregate schema fingerprint
input, including JSON escaping/framing, not a native-parser or global RSS cap),
`database_rows: 32000000` (aggregate physical-table rows, including FTS shadow
tables), and `database_seconds: 3600` in the archive-limit description. SQLite
values/rows and workflow context output also honor `control_bytes`. Exceeding
these bounds reports `bundle_limit_exceeded`; raised/disabled limits report
`bundle_limit_invalid`. The time bound is per connection and cooperative.
Full SQLite integrity failure reports `schema_integrity_failed`; foreign-key,
schema and provenance failures retain the shared schema reasons. These gates
run before export publication and archive restore; no automatic repair is
implied. Recovery complete-byte hashes are bounded by the selected archive
limits; a failed recovery proof retains `approval_import_recovery_required`.

On Windows, incompatible ordinary source-file sharing or an unsafe native
source/parent pin also refuses collection without payload diagnostics.
SQLite backup uses a separate metadata-only pin permitting database writers.
Publication detects target appearance/disappearance or identity/size/time/mode
changes during copying and returns `state_permissions_unsecured`; it does not
replace those intervening bytes. Existing hard-linked private-output targets
are rejected. No new success-envelope fields or online-import permission are
introduced by these checks.
The v2 export envelope's manifest metadata refers to
staged payloads and the captured database, not subsequent live source reads.

Structural/read failures use the normal error envelope, including `bundle_invalid`,
`bundle_contract_invalid`, `bundle_signature_missing` and `bundle_size_mismatch`.
Invalid signature inspection returns structured `verification_state: "invalid"`
with exit 2. Import rejects invalid signatures (`bundle_signature_invalid`),
unknown signers (`bundle_signer_untrusted`), unsigned (`bundle_unsigned`) and
v1 (`bundle_legacy_insecure`) input. Archival-policy failures retain their
specific anchor/time reason. These replace the old aggregate
`bundle_signature_unverified` error.

An otherwise readable bundle containing an unsafe stored identifier or
foreign-key identifier is rejected with
`reason: "bundle_identifier_invalid"`. Its detail names only the table and
field. Creation-, reference-, and mutation-time identifier errors are
field-specific (for example `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`), and a persisted/custom-ledger ID rejected at worker launch uses
`unsafe_runtime_identifier`; none of these errors needs to echo the rejected
value.

The persisted check also inspects only schema-owned nested identifier slots:
worker match entity IDs/types, session execution and launch identifiers,
documented approval selector/context identifiers, and documented batch receipt
resource IDs/refs. `team.json` member worker IDs are checked separately by
`doctor` and bundle verification/import. Workflow-owned data/event payloads,
audit snapshots, principal labels, idempotency keys, and unknown approval
selector payloads remain opaque and are never scanned heuristically.

Opaque IDs are 1–128 ASCII characters, begin with an ASCII alphanumeric, and
continue with ASCII alphanumerics, `_`, `-`, or `.`. The complete values `.`
and `..`, path/drive/UNC syntax, leading option syntax, whitespace,
control/format characters, and Unicode confusables are invalid. Hash-and-token
isolation/worktree/branch names and random-token automatic log names are
implementation details; they do not alter the public ID fields in entity,
worker, session, or execution outputs.
Worker, entity, event, and relation types plus comment and artifact kinds use
the schema catalog's stricter lowercase, letter-first, 1–64-character subset
of this grammar.
Manual/public session input that supplies `execution.isolation` or claims the
built-in manager launch marker fails with
`session_isolation_provenance_invalid`. Only the private built-in launch
manager registration capability may persist the marker and its canonical
isolation result.

`schema show` returns machine-readable descriptions for the public contract surfaces. Public surfaces include `cli-envelope`, `worker-runtime`, `doctor`, `self`, `ledger`, `workflows`, `ledger-batch`, `approvals`, `sessions`, `policy`, `audit`, `state`, `trust`, `worker`, `worker-type`, and `database-schema`. `schema show --surface worker-runtime` exposes stable worker environment keys, including `OP_SYS_SESSION_ID` for session-backed launches. `schema show --surface ledger` exposes stable generic ledger record fields for entity, event, relation, claim, comment, artifact, and batch outputs. `schema show --surface ledger-batch` exposes the top-level batch payload, operation envelope keys, supported operation types, supported preconditions, result item fields, ref fields, and resource result keys. `schema show --surface sessions` exposes both singular `{ "session": {} }` and list `{ "sessions": [] }` result shapes. `schema show --surface database-schema` exposes the inspection, forward-plan, backup, recovery, and migration-result fields used by `schema database`.

## Generic Entity

Documented fields:

- `entity_id`
- `entity_type`
- `workflow_namespace`
- `workflow_version`
- `title`
- `body`
- `data`
- `created_by_actor_id`
- `updated_by_actor_id`
- `created_at`
- `updated_at`

`data` is workflow-owned JSON. Core does not assign business meaning to fields such as status, owner, severity, priority, or acceptance.

## Generic Event

Documented fields:

- `sequence`
- `event_id`
- `event_type`
- `actor`
- `entity_type`
- `entity_id`
- `workflow_namespace`
- `workflow_version`
- `payload`
- `causal_refs`
- `idempotency_key`
- `occurred_at`

## Generic Relation

Documented fields:

- `relation_id`
- `from_entity_id`
- `to_entity_id`
- `relation_type`
- `workflow_namespace`
- `data`
- `created_by_actor_id`
- `created_at`

## Generic Claim

Claim acquire output includes lease fields:

- `entity_type`
- `entity_id`
- `owner_worker_id`
- `lease_expires_at`
- `heartbeat_at`
- `created_at`
- `updated_at`
- `lease`
- `workflow_namespace`
- `workflow_version`

Claim release output includes:

- `entity_type`
- `entity_id`
- `worker_id`
- `released`
- `workflow_namespace`
- `workflow_version`

## Generic Comment

Documented fields:

- `comment_id`
- `entity_id`
- `author`
- `kind`
- `body`
- `idempotency_key`
- `created_at`

## Generic Artifact

Documented fields:

- `artifact_id`
- `entity_id`
- `kind`
- `path`
- `metadata`
- `created_by`
- `idempotency_key`
- `created_at`

## Workflow Contract

Workflow files accepted by `workflow validate` use the strict contract shape:

```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": {}
}
```

Supported top-level contract fields are `schema_version`, `namespace`, `version`, `title`, `description`, `instructions`, `worker_instructions`, `metadata`, `entity_types`, `event_types`, `relation_types`, `recommended_commands`, `view_conventions`, and `worker_result_conventions`. `recommended_commands` values use canonical space-separated CLI names, for example `ledger entity create`.

The type sections are mappings. Empty objects are valid; teams add schemas or relation bindings only when they want strict validation. Entity type contracts support `required_data_fields` and `data_schema`. Event type contracts support `entity_types` and `payload_schema`. Relation type contracts support `from_entity_types` and `to_entity_types`.

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

Workflow namespaces use lowercase dotted segments such as `example.workflow`. Entity, event, and relation type names use the same lowercase identifier rules as ledger commands.

Workflow discovery includes standalone workflow JSON files and skill package `SKILL.md` frontmatter that points `op_sys_workflow_contract` at a workflow contract file in the same skill directory.

## Batch

`ledger batch` normalizes repeated `--operation` values into one operation envelope and passes that envelope to:

```python
ledger_batch(actor, operation, approval_id=None, workflow_contract=None, strict_contract=None)
```

Output includes:

- `batch.operation_count`
- `batch.applied_count`
- `batch.idempotency_key`
- `batch.idempotent`
- `batch.results`
- `batch.refs`
- `results`
- `refs`

Supported operation types are:

- `entity.create`
- `entity.patch`
- `event.append`
- `relation.add`
- `relation.remove`
- `comment.add`
- `artifact.attach`
- `claim.acquire`
- `claim.release`

Supported preconditions are:

- `entity.exists`
- `entity.type_is`
- `entity.data.equals` and alias `entity.data_equals`
- `entity.data.in` and alias `entity.data_in`
- `claim.absent`
- `claim.held_by`

Each result item preserves operation order as `{ "index": 0, "op": "entity.create", "result": { ... } }`. The nested `result` object is resource-keyed, for example `{ "entity": { ... }, "entity_id": "ent_..." }`, `{ "event": { ... }, "event_id": "evt_..." }`, or `{ "claim": { ... }, "lease": { ... } }`. Additive scalar IDs are part of the public batch shape for entity, event, relation, comment, and artifact results; relation removal adds `removed: true`, and claim release adds `released: true`.

Batch refs are declared with `ref` and consumed through fields such as `entity_ref`, `from_entity_ref`, `to_entity_ref`, and `relation_ref`. Public `refs` map ref names to scalar IDs when available, including claim and lease refs resolving to the entity ID.

For idempotent replay, the same idempotency key returns the same receipt.
Before returning it, op-sys requires both top-level and `batch`-nested
`results` to be arrays of object items with object `result` records, requires
both `refs` containers to be objects, requires every root/nested view, and
requires duplicated results/refs views to match. Every present known resource
slot (including `claim.lease`) must be an object before op-sys revalidates
documented resource IDs plus ref names/values in both views. Ref declarations normalize
surrounding whitespace and one leading `$`; duplicate normalized names fail
with `batch_ref_duplicate`, while a present null/non-string/empty declaration
fails with `batch_ref_invalid`. Identifier literals retain exact literal
semantics and are never normalized into refs.

## Integration Guidance

Integrations should:

- pass `--state-root` explicitly
- pass `--repo-root` when targeting a project-scoped ledger from outside the repo
- treat IDs as opaque
- parse JSON, not human output
- use `schema show`, `workflow`, `approval`, and `session` commands for discovery and coordination

Integrations should not read or mutate SQLite directly.

## Cloud and MCP additions

Cloud status/configure/connect return configured credential flags, revision and
verified capability metadata, never key values. Replica status and synchronization
use the current [replica contract](/docs/raw/manuals/ledger-replicas.md). Source batch receipts and
public checkpoint reset are no longer supported.

MCP uses JSON-RPC standard boundary errors (`-32700`, `-32600`, `-32601`,
`-32602`, `-32603`) and `-32002` for an unready/closed lifecycle. Tool application
failures are result objects with `isError: true`. See [MCP](/docs/raw/manuals/agent-mcp.md) for
versions and limits and [Cloud safety](/docs/raw/manuals/cloud-client.md) for credential handling.
