# Self-Hosting `op-sys`

Use `op-sys` against this repository by recording repo-scoped work as generic ledger entities.

Portable exports never contain the managed `trust/` tree or legacy `keystore.json`, whether
signed or unsigned. Ordinary inspection/import of old bundles carrying it fails with `legacy_private_material`;
preserve them privately and re-export from the source using a version that
excludes signing keys. The trust tree is rejected with `bundle_trust_reserved`.
New signatures use Ed25519, and importing recipients must explicitly add a
public key using an independently confirmed fingerprint. No bundle can install
keys or trust decisions. New bundles are v2, and only `verified_trusted` imports
are accepted by default. Unsigned exports remain inspectable but cannot be
imported without a separate reason-bound one-shot recovery grant; v1 is always
`legacy_insecure`. Default export requires an existing active signer. Refer to
[bundle-v2.md](/docs/raw/manuals/bundle-v2.md) for notary archival policy and current limits. Ordinary artifacts
can themselves contain sensitive user content.

Use the [explicit recovery procedure and proposed dated policy](/docs/raw/manuals/bundle-v2.md#explicit-untrusted-recovery-policy-proposed)
only against an isolated initialized recipient after appropriate backup and
writer shutdown. `--allow-unsigned` and `--allow-legacy-insecure` are distinct,
must match the approval, and never bypass invalid v2 signatures. Recovery stays
untrusted; legacy key material is discarded without parsing or installation.
The proposal caps grants at six hours and closes legacy recovery at December 22,
2026 00:00 UTC. Preserve original archives privately and reconcile before v2
re-export; re-signing does not authenticate original provenance. Final owner
acceptance and any valuable/live-state authorization remain separate gates.

Use [the public-key exchange procedure](/docs/raw/manuals/trust.md) for `trust public export`,
`trust fingerprint` and `trust add`; do not copy another ledger's private
directory. Upgraded local key mutation quarantines HMAC material inactive for
a fixed 30-day recovery window. The owner must arrange any separately
authorized recovery and run `trust legacy destroy --yes`; expiry alone does
not delete the quarantine. Separately held encrypted/offline key backups,
recipient notification after rotation or compromise, and destruction of
backup copies remain the custodian's responsibilities. The pure-Python
provider is not constant-time, and these keys are not release-signing roots.

Export collection requires regular files below the approved state/repository
roots. Symlinked files or directories (including dangling/empty links), reparse
points, FIFOs and hard-linked file aliases fail with `bundle_source_unsafe` and
the affected path. Replace them with contained regular files before retrying.
An explicit skill workflow-contract reference must exist and remain inside the
repository; contained `../` references are checked component by component.
Skill metadata is read only after those checks, is capped at 1 MiB, and fails
if its identity or complete byte snapshot changes during the read.

Archive input and export are limited to 16 GiB archive bytes, 8,192 regular
members, 32 GiB per expanded member, 64 GiB total expansion, 1,024-byte names,
16 path components and a 200:1 expansion ratio. JSON/control metadata has an
8 MiB limit, with separate central/extra/comment limits. Consistent stored,
DEFLATE and ZIP64 inputs remain supported. Ambiguous names, links, encrypted
or unsupported records and undeclared files fail before target publication.
Use the lower-only flags documented in [cli-contract.md](/docs/raw/manuals/cli-contract.md)
when exporting, verifying, reviewing approval input or importing smaller expected data.
Export caps the shared source inventory at 65,536 visited nodes and applies a
3,600-second cooperative SQLite backup/validation/private-compaction deadline. It checks
logical database size including committed WAL, leaves the source journal mode
and WAL uncheckpointed, and inspects a private standalone snapshot read-only.
Artifact references and workflow metadata come from staged data. Detected
source identity/size changes or exceeded limits fail without replacing an
existing output. The deadline does not bound blocked OS I/O or the entire
export; these guarantees do not establish a verified backup and restore or prove
that external writers have stopped.
Preserve rejected legacy archives privately; do not bypass limits or assume
archive validation makes HMAC v1 input trustworthy.

Export now rejects snapshots that fail full SQLite integrity, foreign-key,
schema or migration-provenance checks before compacting/publishing them; it
never repairs or migrates the live source. Supported legacy snapshots retain
their verified-import migration path. Read-only inspection is limited to 4,096
schema objects, 32,000,000 aggregate physical-table rows (including FTS shadow
tables), 8 MiB SQLite values/rows and bounded workflow metadata, and a cooperative
3,600 seconds per connection. A separate 8 MiB `database_schema_bytes` budget bounds conservatively
encoded aggregate schema fingerprint input before shared validators materialize
it; see the CLI contract for accounting. It can reject literal schemas smaller
than 8 MiB, but does not alter supported migration fingerprints. Native SQLite
schema loading occurs first, so this is not a total parser/process RAM limit.
These provisional limits remain lower-only with no bypass flag. A refusal
calls for private review and the supported recovery/export
procedure, not increasing limits or modifying live schema to pass a check.
Recovery proof hashes also honor file/count/aggregate bounds and refuse files
that grow beyond their captured length.
Portability requests full integrity directly from the shared schema inspector.
Within its retained query-only read transaction, that full result also covers
the final assertion's weaker quick scan. Final foreign-key, version and layout
assertions and migration-provenance checks remain. Other diagnostic callers
keep their existing quick checks; no previously supplied result is trusted.
Semantic verification streams ledger records and resolves entity/event targets
through indexed queries against that same read-only snapshot; it does not copy
all entity identifiers or audit targets into growing Python dictionaries/sets.
This reduces reference-index memory growth, not the database's size or history.
Entity count is not a capacity guarantee: updates, audit/events, search indexes
and artifacts also consume the limits. Inspection and snapshot work each have a finite
one-hour ceiling; this allows longer offline work, including on hostile input,
and does not guarantee an entity count or whole-export completion time.
The provisional larger byte/row/time ceilings are
listed in the CLI contract; they are not an entity-count support guarantee.
Portability's read-only inspection and snapshot source/target connections set
a session-local 2,000 KiB suggested page cache and disable database memory
mapping, rather than inheriting a persisted cache-size hint from input or a
host mmap default. These settings do not rewrite the source header and are not
a hard process-memory ceiling: decoded JSON, SQLite query work and other
allocations remain separate resource costs.
The source snapshot read transaction ends as soon as SQLite backup completes,
before integrity checks or compaction of the private copy. Export does not issue
a source checkpoint; other writers may checkpoint their own committed work
without waiting for those private-copy checks. Source identity protections and
the lifecycle guard remain active, and a source-close failure aborts export.

## Initialize

```bash
op-sys init
```

Inside this git repository, the ledger resolves to `.op-sys` and is excluded through the repo-local git exclude file.

Initialization also enforces private local state: POSIX directories use `0700`
and files use `0600`; Windows uses a protected current-user-and-`SYSTEM` DACL.
The exclusion is written to the effective `info/exclude` file, not the tracked
`.gitignore`, so linked worktrees receive their own effective rule without a
shared source change.

Verify the state root without changing it:

```bash
op-sys state permissions
op-sys doctor
git status --short --untracked-files=all
git add --dry-run .
```

If the permissions check reports drift, repair it explicitly:

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

Ordinary commands also repair an upgraded state before reading it and report
that event as `state_permissions_repaired: true`. `doctor`, read-only
permission inspection, and bundle verification stay non-mutating.

The command reports paths and expected protection only; it never prints file
contents. Git exclusion is not encryption and cannot remove `.op-sys` data
that was already committed. Inspect repository history separately and rotate
any credential or key that was previously shared.

After an upgrade, `doctor` also reports persisted IDs that do not meet the
opaque-ID contract. Explicit IDs must be 1–128 ASCII characters, start with an
ASCII alphanumeric character, and then use only ASCII alphanumerics, `_`, `-`,
or `.`; `.`/`..`, path syntax, whitespace, controls, and Unicode lookalikes are
rejected. Unsafe legacy rows remain available to state export and
non-operational recovery inspection but cannot be operationally mutated or
launched. Export and recreate them with reviewed safe IDs; do not silently
rewrite relational references.

The diagnostic inventory includes schema-owned nested worker match, session
execution/launch, documented approval selector/context, and both top-level and
nested batch receipt identifier slots. Malformed known JSON roots and
documented context/results/refs container shapes, missing or inconsistent
receipt views, and non-object known resource slots are reported by stable field.
It also checks every canonical team-setting member worker reference (legacy
bundle checks use `team.json` before the settings migration).
It intentionally does not search arbitrary workflow data, event payloads,
audit snapshots, principals, idempotency keys, or unknown selector payloads.
Bundle verification/import applies the same database and team checks, with
value-free table/field diagnostics. Export preserves database records for
recovery and regenerates governance projections from the exact snapshot;
malformed canonical settings fail closed and need explicit offline recovery.
`state import` is an offline state-root replacement operation. Before invoking
it, stop every op-sys process and every other writer that can reach the target
state root, and keep them stopped until the command completes. The importer's
same-process active-store refusal is defense in depth, not a cross-process
writer fence; policy approval does not satisfy this shutdown precondition.

Export/import now hold the same persistent root schema lock used by migration
and writable startup. This prevents participating operations from crossing
their collection/publication windows. Root-lock contention waits at most five
seconds by default and reports `schema_migration_busy`; import additionally
keeps its existing immediate reservation lock. Let the current operation end
and retry only when the state is known safe. Do not delete or replace the lock
file to force progress. An already-open store or external writer is not fenced
by this startup/operation lock and must still be stopped for import. Local
governance and lock files are excluded from portable archive restoration.

Worker, entity, event, and relation types plus comment and artifact kinds
remain a stricter lowercase, letter-first, 1–64-character subset of the
opaque-ID grammar. `schema show` publishes both contracts.

## Schema Upgrades And Recovery

The current SQLite schema is version 13 and requires SQLite 3.35+ with FTS5.
Derived event-search rows are transactionally maintained; `doctor` checks
their consistency without repairing state. See [local query recovery](/docs/raw/manuals/local-query.md).
Inspecting the database is read-only:

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

The second form displays the same plan and remains a dry run until confirmation
is explicit:

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

Writable startup also runs this migration path when required. Migration is
an operation on existing initialized state; use `op-sys init` for a new state
root. The confirmed migration form refuses a missing database instead of
silently initializing one. Migration is supported from the exact v4-v9
structural fingerprints bound by the checked-in fixture-provenance manifest,
their valid committed migration prefixes, and exact origin-backed v10/v11 state.
Versions v1-v3, non-empty unversioned
state, unknown or corrupt layouts/history, checksum drift, and databases newer
than v12 fail closed without a best-effort rewrite. Migration is forward-only;
never open upgraded state with an older binary and do not attempt a downgrade.

For `op-sys init`, a missing, zero-byte, or valid empty-v0 database is fresh
only in an absent/empty state root, or alongside private empty recognized
managed containers and the exact private canonical migration lock left by an
interrupted fresh bootstrap. Any root state file, SQLite sidecar,
nonempty/unsafe managed container, noncanonical lock, or unknown top-level
entry is preserved and rejected for explicit recovery or reconciliation.

Fresh v12 state records its own checksum-bound creation origin. Existing fresh
and migrated v10/v11 origins remain byte-for-byte intact, with missing
`010_governance_settings` and `011_bound_approvals` receipts appended in order.
The migrated-v10 origin still binds its historical source and v10 route,
not a retroactively rewritten route.
Missing, empty, mixed, truncated, transplanted, or malformed history is invalid;
creation/origin records are not presented as last-applied migrations.

Migration 10→11 imports existing `policy.json` and `team.json` objects once into
versioned `settings` rows, retaining exact original UTF-8 content and its hash
in origin metadata. An absent legacy file uses recorded generation defaults;
malformed or unsafe files stop migration. Fresh state uses generation defaults
and does not adopt preseeded state files. Existing canonical rows are never
re-imported from JSON.

Migration 11→12 adds one-shot intent and consumption fields. Legacy approvals
keep their review data with NULL digest/intent and cannot authorize mutations;
re-request them using complete `--operation-json` or import `--bundle` input.
Handle state `consumed`, expiry of both pending and approved records, and
non-revival of terminal states. Canonical team settings gain explicit
operator IDs/roles and bootstrap `operator` only if the registry is absent.
Workers remain workers; unknown/external `system` IDs gain no authority.

Effective policy is base < team defaults < acting worker-type policy, with
explicit matching deny rules retained. These IDs, roles and votes are
cooperative metadata, not authentication. They cannot protect against anyone
with state/file/process authority. Review original effects alongside their
hashes, never put secrets in metadata/reasons, and follow the
[one-shot, TTL, batch, identity and recovery contract](/docs/raw/manuals/approvals.md) and
[synthetic policy example](/docs/examples/approval-policy.json).

Governed import reserves a private receipt below `governance/imports` and
prepares migration, consumption and audit in a private staged database before
publication. Its migration backup preserves the imported snapshot, not the
pre-import target. The non-imported governance tree retains that backup pair.
Never treat an import approval as a target backup or live rollout approval.

Restore separately preserves the overwritten target files and stale SQLite
sidecars at `governance/restores/<operation>/before/`, even after successful
publication or ordinary rollback. A private `receipt.json` records expected
before/after sizes and hashes, target identity, manifest digest and phase.
It is not a complete state-root backup or an independently verified recovery
drill. Old-file copies obey the archive per-file/aggregate byte ceilings;
large existing targets can therefore reject an otherwise small import.
Prepared state is also bounded again after migration/audit preparation.

Keep artifact and descriptor writers stopped while collecting an export.
Windows ordinary-file readers now retain native file/parent pins and reject
incompatible write/delete sharing. SQLite is treated separately: its backup
keeps an identity-only pin that allows database writers and exposes no raw
reader, while SQLite provides the consistent snapshot. This is not permission
to import online.
Private publication also refuses a target that appears or changes while its
replacement is copied. Do not retry through an intervening writer or remove
its data; retain the recovery evidence and restore the offline precondition.
The restore journal's prior-target check now reaches the final write/removal
helper, and rollback keeps its target check bound to the known-state byte
proof. Both staged and retained backup sources must match their expected full
size and SHA-256 during bounded copying, before publication. POSIX temporary
output keeps its original descriptor through publication/cleanup; a changed
temporary name is left untouched for review, never treated as cleanup
authority. Retained temporary files can also contain sensitive state. These
immediate checks do not provide atomic conditional replacement against an
uncooperative writer.
Windows publication now retains the exclusive creator descriptor and performs
a handle-relative rename under parent leases; target removal and pre-rename
temporary cleanup use checked deletion handles. Directory listing/traversal
rights are required for the parent leases. If a rename is attempted but fails
or its outcome is uncertain, the private temporary file is intentionally left
for review. Preserve it alongside the restore receipt and retained originals;
do not treat its name as evidence that it is safe to delete or replay.
Recovery-directory creation is also inside parent leases.
Private-parent creation and ACL repair likewise keep Windows paths pinned.
Snapshot staging requires a fresh destination and retains the private creator
until SQLite connections close. Its Windows sharing mode permits database
writes but denies replacement; a construction failure does not reopen the
created name for deletion. POSIX retains the creator too, closing it only after
SQLite so a raw descriptor close cannot discard an active SQLite lock.
These retained directories consume disk space and are not automatically
pruned or exported.

Private read-only SQLite inspections keep Windows parent/database pins until
the connection closes and recheck the named file afterward. POSIX checks the
name before/after opening and after close while holding its parent descriptor;
this does not remove the same-account pathname-stability requirement. Fresh
import receipts likewise retain their exclusive creator through final checks.
A partial receipt remains evidence: do not delete it to retry an approval.
The imported migration-backup pair is copied only to absent destinations and
must match expected complete bytes before publication. Preserve any unexpected
destination rather than overwriting it or treating it as cleanup authority.

If a process exits during restore, preserve the entire recovery directory and
the original bundle. Keep every writer stopped. `applying` may mean a partial
publication; `recovery_required` means ordinary rollback was not proven.
Earlier phases and `restored`/`rolled_back` are recorded observations only:
revalidate the files, hashes, target identity and any SQLite sidecars before
making a recovery decision. Do not copy an individual database or sidecar
back into a running root. Do not delete the journal or try a different import
to conceal the interrupted operation. Recovery requires target-specific
review and authority; the journal never authorizes automatic replay. The
existing governed one-shot complete-file finalization remains separate.

Normal writable startup, migration, export and another import are fenced by
unfinished journals/reservations anywhere in this root. Keep the root offline
and use read-only diagnostics. Admission checks at most 1,024 combined private
receipt files and 16 MiB aggregate metadata (also subject to the control-file
cap); it does not scan retained backup payloads. Damaged/missing metadata,
unexpected registry names or exceeded bounds require explicit evidence/retention
review. Do not delete or edit receipts, including abandoned temporary files,
to bypass the fence. Historical terminal records count toward these bounds;
there is no automatic archival or limit-raising switch.

For an exact governed retry, actor/approval and prepared-file validation still
apply. A new receipt binds its precise restore operation before publication.
Complete target-byte proof can finalize only that linked journal's metadata,
then consume the import receipt; backups remain untouched. A crash between
these two updates leaves the reservation blocking ordinary admission. Missing
links and unrelated pending operations are not guessed away, and partial
restores are never automatically replayed. Older valid one-shot receipts keep
their prior full-byte recovery only without ambiguous pending journals.

Ordinary proven rollback releases the reservation; a complete-byte crash
recovery can finalize without replay. Partial/changed/unsafe state retains the
receipt and returns `approval_import_recovery_required`. Keep writers stopped
for explicit offline recovery; do not remove the receipt as a retry mechanism.

Service settings changes, audit entries, and events commit together. JSON files
are post-commit projections; a failed projection can be rebuilt on writable
startup/settings access or explicitly through the store recovery API. Recovery
does not add audit/events. Read-only diagnostics use canonical rows without
repairing projections. Portable exports derive both files from the backed-up
database snapshot, and verification rejects a projection/database mismatch.
Do not edit projections to change policy or use them as rollback state. Prefer
patch-forward recovery; an offline pre-upgrade DB restore requires stopping
writers, retaining the upgraded DB, proving no later writes exist or explicitly
reconciling them, and rehearsing the verified backup at a new path first.

Before the first schema change, op-sys creates a private verified backup at
`<state-root>/backups/schema/schema-v<source>-<timestamp>-<nonce>.sqlite`.
It durably records the verified hash, size, source version and fingerprint in
the adjacent private `.receipt.json` file; keep the database and receipt
together and revalidate the pair before recovery.
Successful retention keeps the three newest recognized backups globally plus
the newest for every source version. Unknown files are not pruned. A persistent
private `locks/schema-migration.lock`, followed by an exclusive SQLite lock,
serializes migration. Stop other writers and retry if the command fails with
`schema_migration_busy`; do not remove the lock file.

### Routine opening and integrity diagnostics

Opening an already admitted local ledger is a metadata operation, not a
backup or a full integrity scan. Successful deep database validation writes a
private `locks/schema-admission.json` containing the current admission format,
schema version, root/database filesystem identities, canonical schema
fingerprint and migration-history digest. Each subsequent writable open checks
those identities and private permissions, the restore barrier and migration
lock, and the committed schema/history in SQLite read transactions. WAL data
is not ignored. Routine opens do not copy the database or run `quick_check`,
`integrity_check` or `foreign_key_check`; application writes do not invalidate
the admission record.

An ordinary open is not a non-mutating diagnostic command. Even its read-only
SQLite preflight may create WAL/SHM coordination files or update shared-memory
reader marks, including before rejecting changed schema/history. This does not
authorize application writes or schema repair; do not attempt to undo live SHM
bytes. Explicit schema diagnostics retain the separate private snapshot path.

Pre-existing databases without a record take the former deep path on their
first open after this upgrade; that one-time admission can still take substantial
time and scratch space on a large ledger. Missing, malformed, outdated or
identity-mismatched records never authorize the fast path. Copies and replaced
database files require deep revalidation; private permission/path failures and
schema/history changes fail closed. Stop writers and use explicit permission
repair or schema diagnostics for the reported error, not a hand-edited record.
The record is excluded from exports, and bundles cannot supply it. A restore
does not inherit admission from the replaced database. It is not a backup,
signature, whole-database hash or defense against someone with the owner's
filesystem authority. In-place out-of-band data edits and corruption in unread
application pages are not detected merely by routine opening.

Use `op-sys schema database` for explicit deep schema/integrity diagnostics;
it retains the private-snapshot path. Export verification, import/restore
validation and migration validation also keep their deep checks and resource
requirements. Routine-open performance is separate from those maintenance
operations; skipping their validation is not an optimization option.

Values removed from the public v10 model are retained in the private
`schema_migration_archive` table. It is not exposed through ledger SDK/CLI
queries or ledger replication, and it is excluded from public generic/substrate table
counts in portability manifests. Private state bundles and automatic
pre-migration SQLite backups are raw recovery artifacts and therefore retain
the archive or complete source database; protect both as sensitive state.

Recovery from an automatic verified migration backup is a deliberate operator
action:

1. Stop every op-sys process and every other writer to the state database.
2. Preserve the upgraded database and its migration evidence; do not overwrite it.
3. Copy the selected verified backup to a new private state path.
4. Verify SQLite integrity, schema identity, permissions, and application reads on that copy.
5. Reconcile writes accepted after the backup before switching callers to the recovered path.

An unsupported or non-empty unversioned database is different: migration
planning rejects it before creating an automatic verified migration backup.
Preserve it as a raw recovery artifact instead of treating the procedure above
as applicable:

1. Stop every op-sys process and every other writer that can reach the state
   root. Record the resolved state-root path and confirm that writers remain
   stopped for the whole capture.
2. Make a byte-preserving private copy of the complete state root, including
   `op-sys.sqlite`, any SQLite `-wal`/`-shm`/`-journal` sidecars, configuration,
   artifacts, and workflow descriptors. Use a filesystem copy tool appropriate
   to the host; do not copy only the main SQLite file while a writer is active.
   For example, on POSIX, with an absent destination and after confirming the
   writer stop:

   ```bash
   umask 077
   mkdir -m 700 /private/recovery
   test ! -e /private/recovery/op-sys-legacy-state.raw
   cp -a /path/to/legacy-state /private/recovery/op-sys-legacy-state.raw
   ```

   Use an ACL-preserving or offline snapshot tool instead where `cp -a` is not
   available. Keep the recovery parent private even when copied source modes
   were insecure.
3. As an additional portable capture, attempt an unsigned export to a path
   outside the managed state root:

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

   `state export` snapshots committed SQLite content and packages referenced
   state files. `--no-sign` avoids depending on a legacy signing key. The
   stopped-writer full state-root copy remains the primary raw preservation
   artifact if export cannot interpret the old layout.
4. Hash, access-restrict, label, and retain both captures. Record the source
   path, capture time, binary version, inspection `reason`, and hashes without
   placing secrets or record contents in the operator receipt.
5. Expect `op-sys state verify --bundle <bundle>` to reject a bundle whose
   database schema is unsupported or unversioned. That rejection confirms the
   current binary will not accept the database; it does not prove that the raw
   capture is corrupt. Do not use `state import`, `schema database migrate
   --yes`, `init`, or direct SQL to force it into a current state root.
6. Inspect a disposable private copy with an owner-approved legacy binary or
   read-only SQLite tooling. Inventory and reconcile every record family and
   referenced file, then manually recreate reviewed records in a newly
   initialized current state root. Preserve identifiers only when they satisfy
   the current identifier contract; explicitly map unsafe identifiers and all
   relational references rather than silently rewriting them.
7. Validate the recreated root with `op-sys doctor`, application reads, row and
   record-family reconciliation, and a normal current-schema export/verify
   drill before any caller is switched to it.

There is no in-place recovery or downgrade command for these inputs. Never
open an upgraded database with an older binary. Raw unsupported-state copies
and exports are not recognized migration backups and are not pruned by schema
backup retention; retain or dispose of them only under the state owner's
separate retention policy.

Authorize each migration or recovery for its intended target, preserve
verified backups and complete the documented recovery checks before resuming
writers.

Old isolation/worktree directories are ephemeral but must not be bulk-cleaned.
Only hash-named direct children carrying a matching run marker are eligible for
automatic removal. Quarantine an unmarked legacy directory for review. Copy
and worktree modes limit which changes are applied back to this checkout; they
are not an operating-system sandbox for untrusted worker code.

## Seed Work

```bash
WORK_ID=$(
  op-sys --output json ledger entity create \
    --type work_item \
    --workflow local.self-hosting \
    --title "Refresh CLI contract docs" \
    --data '{"status":"ready","paths":["README.md","docs/cli-contract.md","tests/test_cli.py"]}' |
  python3 -c 'import json, sys; print(json.load(sys.stdin)["payload"]["entity"]["entity_id"])'
)

op-sys ledger event append \
  --entity "$WORK_ID" \
  --type work_item.created \
  --workflow local.self-hosting \
  --payload '{"source":"self-hosting guide"}'
```

## Work Manually

```bash
op-sys worker create \
  --id manual-dev \
  --type manual \
  --mode passive \
  --match-entity-type work_item \
  --match-workflow local.self-hosting

op-sys ledger claim --entity "$WORK_ID" --worker manual-dev
op-sys ledger event append --entity "$WORK_ID" --type work_item.started --payload '{}'
op-sys ledger comment --entity "$WORK_ID" --body "Editing docs and focused CLI tests."
op-sys ledger entity patch --id "$WORK_ID" --patch '{"status":"done"}'
op-sys ledger event append --entity "$WORK_ID" --type work_item.completed --payload '{"validation":"focused tests passed"}'
op-sys ledger release --entity "$WORK_ID" --worker manual-dev
```

This flow keeps the dogfood path on generic rails: entities, events, comments, artifacts, claims, and audit.

## Optional Cloud and agent boundaries

Cloud is optional. The local ledger does not depend on a hosted connection.
Configure a candidate with a key supplied by file/stdin/environment variable name;
it is committed only after the server verifies the tenant and explicit versioned
capabilities. See [Cloud client safety](/docs/raw/manuals/cloud-client.md) for generations, secret
retention and verification. Ledger synchronization is explicit through
`ledgers sync`; execution mutations do not upload events.

MCP is local stdio, not a remote unauthenticated listener. Generated configuration
contains only state/repository/scope paths. Clients must complete the
[initialization lifecycle](/docs/raw/manuals/agent-mcp.md#protocol-and-lifecycle).

Worker environment filtering, worktrees and leases are not a security sandbox.
Actors are application policy identities, not proof of OS isolation. Keep untrusted
code and credentials in separately enforced OS/container boundaries. Before moving valuable state, prepare target-specific backup/restore, writer
fencing, reconciliation and explicit authorization for the intended target.
