# Start with a ledger

Veylar Record provides ledgers for records you define. CLI, Python SDK, MCP and
HTTP use the same domain operations, permission checks and results. Choose the
interface that fits your application or agent. Local CLI/SDK/MCP need no account,
HTTP server or network. HTTP needs a reachable managed or customer-hosted service.

Follow [installation](/docs/raw/manuals/installation.md) to set up the runtime before using this guide.

## 1. Start locally

In your project directory, run:

```sh
op-sys
op-sys --output json selection get
op-sys --output json ledgers inspect
```

First use creates and selects a local ledger with an explicit permissive contract.
Repeat use preserves the selection and its rules. Inside a Git repository, state
is normally `.op-sys`; outside one it is user-scoped. `op-sys where` shows the
resolved path. Use `--state-root /absolute/private/path` to isolate another store.
An existing selection may have a restrictive contract: inspect before writing.
Only first-use setup or explicit `ledgers create` creates a ledger; append does not.

For another ledger, run `op-sys --output json ledgers create --name example`, then
`op-sys selection update --connection local --ledger <returned-ledger-id>`.
Names are optional labels, not unique IDs or predefined product types.

For everyday terminal use, omit `--output json`: ledger create/get/list/inspect/update,
record append/outcome/get/list, and ledger status/sync show readable summaries.
Contract get/publish shows full rules; contract list shows published versions.
Ledger inspection separately identifies admitted versions and the default.
Record lists preview long payloads; `records get` prints the complete payload.
Read summaries show the observation source and whether observed coverage is complete.
Pagination is separate: follow the continuation when more results are available.
Use `--output json` for all fields, continuation tokens and automation; SDK and
MCP results remain structured objects.

## 2. Append and retrieve

The following record fits the new ledger's permissive contract:

```sh
op-sys --output json records append --operation-id first-record --payload '{"message":"Hello"}'
op-sys --output json records outcome --operation-id first-record
op-sys --output json records list --limit 20
```

CLI JSON wraps results in `payload`. An accepted append has `state: "accepted"`
and `acceptance.record_id`. Retrieve it with `records get --record-id <record-id>`.
Use `--ledger-id` to override the saved ledger for one operation. JSON inputs also
accept `@record.json` or `-` for stdin. Text, booleans and null remain their JSON
types; records need not be objects unless the ledger's contract requires objects.

Save an operation ID before dispatch. Retry the same ID with identical input and
the same authenticated principal; it returns the original acceptance. New intent
needs a new ID. Changing the payload under an accepted ID returns
`operation_conflict`. Outcome inspection is read-only and never retries a write.

Errors identify the failed operation, a stable code and a next step. For example,
`revision_conflict` means read the resource again and review concurrent changes
before updating with its current `expected_revision`. A permission denial means
check identity, credential scope and grants; signing in again does not grant access.
Expired authentication instead asks you to sign in. SDK, MCP, CLI JSON and HTTP
share the ledger error fields `code`, `message`, `retry` and `recovery`; validation
errors can also identify a `field`, and hosted errors include a `request_id`.
Pending and uncertain submissions remain distinct from accepted records.

Equivalent SDK use in the same project:

```python
from op_sys import OpSys
from op_sys.errors import OpSysError

client = OpSys(connection="local")
client.start()
client.ledgers.inspect()
try:
    result = client.records.append(operation_id="first-record", payload={"message": "Hello"})
    if result["state"] == "accepted":
        record = client.records.get(record_id=result["acceptance"]["record_id"])
        print(record["record"]["payload"])
    else:
        print(result)  # Inspect pending/uncertain recovery guidance.
except OpSysError as error:
    print(error.core_error)  # code, operation, retry and recovery
```

SDK results are direct objects. `OpSys(connection="work", ledger=ledger_id)` uses
an authenticated named service with the same methods. SDK/MCP clients retain their
initial selection until explicitly reconfigured; changing a default elsewhere
does not redirect a running client.

For MCP, launch `op-sys mcp serve` through your client's generated
`op-sys mcp config` configuration. After MCP initialization, these tools use the
same saved selection (or an explicit `ledger_id`):

```json
{"name":"op_sys_records_append","arguments":{"operation_id":"first-record","payload":{"message":"Hello"}}}
```

```json
{"name":"op_sys_records_outcome","arguments":{"operation_id":"first-record"}}
```

These are `tools/call` params, not whole JSON-RPC messages. Read `structuredContent`;
when `isError` is true it contains `error` with the domain code. The full stdio
handshake and limits are in [MCP access](/docs/raw/manuals/agent-mcp.md). No separate agent enrollment
or agent-provider integration is required.

A direct HTTP caller chooses its endpoint, credentials and authorized tenant:

```sh
curl --fail-with-body "$VEYLAR_ENDPOINT/v1/ledgers/$LEDGER_ID/records" \
  -H "Authorization: Bearer $ACCESS_TOKEN" -H "X-Veylar-Tenant: $TENANT_ID" \
  -H 'Content-Type: application/json' \
  --data '{"operation_id":"first-record","payload":{"message":"Hello"}}'
```

HTTP returns the direct result, or `{ "error": ... }` with the appropriate status.
An access token may need refreshing; do not copy another participant's credentials.
A script variable is illustrative credential input, not a recommendation to save
secrets in shell history. The [OpenAPI reference](/docs/raw/manuals/ledger-core.md#discover-cli-mcp-and-http-contracts)
specifies the complete routes and schemas. HTTP does not require a local replica.

## Attach a file

```sh
op-sys files upload --file ./evidence.pdf --media-type application/pdf
op-sys records append --operation-id with-evidence --payload '{"message":"Hello"}' \
  --attachments '[{"file_id":"<returned-file-id>","name":"Evidence"}]'
```

The contract must admit attachments and their declared media type/size. In Python:

```python
file = client.files.upload(data=b"Hello", media_type="text/plain")
result = client.records.append(operation_id="with-file", payload={"message": "Hello"},
                               attachments=[{"file_id": file["file_id"]}])
```

MCP `op_sys_files_upload` and HTTP `PUT /v1/ledgers/{ledger_id}/files/{file_id}/content` accept
the same wire arguments. For the five UTF-8 bytes `Hello`, the body is:

```json
{"sha256":"185f8db32271fe25f561a6fc938b2e264306ec304eda518007d1764826381969","size":5,"media_type":"text/plain","bytes_base64":"SGVsbG8=","complete":true}
```

MCP additionally takes `ledger_id` and `file_id` as arguments; HTTP puts them in
the path. These interfaces transfer bytes, never ask the server to open your local
file path. Save the file ID to resume upload; larger files use bounded chunks.
See [files](/docs/raw/manuals/ledger-files.md) for integrity checks, limits and independent permissions.

## 3. Publish when you want shared work

```sh
op-sys ledgers publish --endpoint https://records.example.com
```

Use the endpoint supplied by your workspace operator. Once configured, `op-sys ledgers publish` reuses the ledger's
remote, selected service, or sole saved connection. With multiple choices, supply
`--connection <name>`. It uses the selected ledger, or the only local ledger;
otherwise provide `--ledger-id`. No manual remote setup is necessary.

Interactive CLI use guides browser sign-in and organization selection. SDK, MCP
and JSON CLI calls return `state=setup_required` with the next setup step rather
than waiting for input. Continue the same operation once authentication is ready.
Authentication alone uploads nothing. A ledger URL identifies its service and
organization; it is not a credential or an invitation.

Publishing **moves write authority to the service** using the protected handoff
protocol, remembers `origin`, and keeps the selected local copy. It does not make
the ledger public or invite anyone. Your local identity maps to your verified
hosted identity for future permissions; historical authorship and acceptance stay
unchanged. Other local participants require explicit grant mappings. Unresolved
grants pause publishing rather than silently discarding permissions.

Only `state=published` means completion. Repeat the same request after a bounded
`synchronizing` or `transferring` result or interruption; the client retains the
transfer identity. `resolve_grants` includes the unresolved principals. Use the
existing [authority recovery](/docs/raw/manuals/ledger-authority.md) controls for explicit mapping.
The source stays fenced once handoff has started; timeouts never reopen it.

```python
progress = client.ledgers.publish(endpoint="https://records.example.com")
# Handle setup_required / resolve_grants; repeat bounded calls as directed.
# When published, progress["url"] is the clone URL to share with authorized peers.
```

MCP uses `op_sys_ledgers_publish` with the same inputs and result. Direct HTTP
integrations compose the public synchronization and authority-transfer exchanges;
the hosted service cannot upload a caller's local files by itself.

For a hosted replica while retaining local authority, explicitly use
`--mode copy`. That destination cannot accept shared writes. Named connections,
editable remotes and direct authority-transfer controls remain available for
advanced configurations.

## Keep using the same operations

After transfer, the local copy remains a replica. Online appends go to its hosted
authority; retained reads use the last observed authorized history. Run
`ledgers sync` explicitly to receive others' records and deliver any
prepared contributions. Reconnecting alone does neither.

Select `work` for current hosted reads, or `local` for retained reads. A local
replica cannot satisfy `freshness=current` and returns `authority_unavailable`;
it does not silently substitute stale data. An accepted append does not imply the
replica has all intervening history or every referenced file.

Offline preparation requires authorized validation context, `records.prepare`,
and `confirmation="allow_pending"`. A pending result is not accepted history.
See [contribution recovery](/docs/raw/manuals/ledger-contributions.md).

## Clone elsewhere and authorize participants

For collaboration, create a [ledger invitation](/docs/raw/manuals/ledger-core.md#invite-a-participant-to-a-ledger).
It can publish the selected local ledger and issue the requested permissions in
the same flow. The recipient previews the offer and accepts as their own
account. Use a [workspace invitation](/docs/raw/manuals/team-onboarding.md) when you want the
recipient to join the workspace.

Another authorized machine may use the hosted ledger directly or retain a copy:

```sh
op-sys ledgers clone "<ledger-url-returned-by-publish>"
op-sys records list
```

Cloning a URL remembers `origin` and selects the retained local ledger. It preserves
identities and only retains permitted history and files. Repeat `ledgers sync` to
finish bounded work. An already configured connection can also be supplied with
`--connection`, or used with the explicit `--ledger-id` form.

Each participant signs in independently and obtains their verified
`{issuer, subject}` from `identity get` after authenticated setup (the `hosted`
field) or authenticated `GET /v1/identity`. An administrator uses that exact tuple:

```python
owner = OpSys(connection="work", ledger=ledger_id)
policy = owner.access.get()
permissions = ["ledger.read", "contracts.read", "records.append", "records.read", "records.outcome.own"]
owner.access.grant(expected_revision=policy["revision"],
    principal=participant_principal, permissions=permissions)
```

For a direct grant, select the named service connection and ledger ID.
Workspace members can select their workspace with `selection update --workspace <workspace-id>`.
Independent collaborators can use their own service credentials and the explicit
`tenant_id` and `ledger_id` in HTTP calls. Invitation acceptance sets the hosted
ledger context in the supplied clients. Read history, contract and file access
each require their corresponding permissions. Adding file contribution needs `files.upload` and `files.read`; cloning
also needs `changes.read`. Service credential scopes and raw-data controls remain
upper bounds. Never share the owner's credential to grant ledger access.

To revoke, read the latest policy and call `access.revoke` with that revision,
the participant principal and the permissions to remove. Other grants remain
unchanged. Group-derived permissions remain effective until the group grant or
membership changes. `access.update` remains available for full-policy replacement.
On conflict, reread and reconcile. Revocation affects future authorized service
access; disconnected or independently exported copies cannot be recalled.

## Recover without guessing

| Result | Consumer action |
| --- | --- |
| `payload_invalid` | Inspect the admitted contract when authorized; correct the record as new intent. |
| `contract_not_admitted` | Select an admitted version for new work. Do not rewrite historical records. |
| `permission_denied` | Have an administrator review the specific right and credential scope. |
| `revision_conflict` | Read the latest definition/policy and reconcile before retrying. |
| `operation_conflict` | Restore the original retry input, or use a new ID for genuinely new intent. |
| `state: uncertain` | Check `records.outcome` using the original ID; an absent result is not cancellation. |
| `state: pending` | Run explicit synchronization when ready and inspect the contribution result. |
| `authority_unavailable` | Restore the configured authority or deliberately request retained reads; no silent fallback. |
| `resnapshot_required` | Restart the snapshot; do not combine a new continuation with old pages. |

`contributions withdraw` only withdraws work never dispatched by that client.
Once dispatch may have occurred, inspect the outcome; do not assume a timeout
prevented acceptance. These are public recovery operations, not queue manipulation.
Use `capabilities get --name records.append` or its SDK/MCP equivalent for
inputs, results, permissions, limits and environment availability.
