# Files, attachments and record references

A File stores immutable bytes in one ledger. An Attachment is a record's immutable
relationship to a File in that same ledger. Records and files have independent
read permissions. Reading a record does not imply that its files are available or
that the caller may download them.

This guide covers file operations, replica delivery and lifecycle controls.
Use the current file format; obsolete formats are not adopted.

## Upload and attach

```sh
op-sys files upload --ledger-id <ledger-id> --file ./evidence.pdf \
  --media-type application/pdf
# Use the returned file_id.
op-sys records append --ledger-id <ledger-id> \
  --payload '{"observation":"Consumer-defined data"}' \
  --attachments '[{"file_id":"<file-id>","name":"Evidence"}]'
op-sys files download --ledger-id <ledger-id> --file-id <file-id> \
  --output-file ./downloaded-evidence.pdf
```

The source path is read only by the supplied client running on your device. It is
never sent to the hosted API as an instruction to open a server file. Downloads
are written only after complete size and digest verification, using an atomic
replacement. The target directory must already exist; its permissions are not
changed. An existing output file is replaced only after successful verification.

```python
from pathlib import Path
from op_sys import OpSys

client = OpSys(connection="work")  # Or the selected local connection.
file = client.files.upload(
    ledger_id=ledger_id, data=Path("evidence.pdf"), media_type="application/pdf"
)
accepted = client.records.append(
    ledger_id=ledger_id, operation_id="observation-001",
    payload={"observation": "Consumer-defined data"},
    attachments=[{"file_id": file["file_id"], "name": "Evidence"}],
)
verified_file = client.files.read(
    ledger_id=ledger_id, file_id=file["file_id"], output=Path("downloaded-evidence.pdf")
)
```

A path output is published atomically after verification. A caller-supplied
binary stream receives chunks as they arrive; discard its partial output if the
helper raises. For small files, omitting `output` returns bytes in memory.
The SDK upload helper also accepts bytes or a binary stream. It computes size and SHA-256,
creates an independent file ID and sends bounded chunks. An interrupted helper
retains its file identity privately. Repeating it with the same input, principal
and destination resumes from the last acknowledged chunk. A response lost before
the checkpoint is safely replayed. File transfers honor temporary capacity
responses with bounded retries and the service Retry-After guidance.
For application-managed restart recovery, supply and retain `file_id` yourself.
The helper never queues delivery or retries automatically in the background.

Uploading does not accept a record. If append is rejected, its uploaded file stays
unattached and can be reused before cleanup. The original append operation ID is
independent of upload progress; retain it through retries.

## Rules and permissions

`files.upload` is required to upload. Only the original authenticated uploader can
continue or replay that file identity. New record attachments require
`records.append` and `files.read`. `files.read` also governs metadata inspection
and downloads. Service credential scopes, raw-data policies and tenant state
remain upper bounds on all ledger rights.

Contracts may constrain `file_rules.media_types`, `max_bytes` and `max_items`.
`*/*` permits any valid declared media type; otherwise exact media types apply.
Media types are declarations, not antivirus checks or content classification.
The initial permissive core contract allows up to 16 files of 1 GiB each.
A newly published contract without file rules permits no attachments.

Every new attachment requires fully uploaded, integrity-verified bytes at the
current authority. Partial uploads are rejected even if the payload schema is
permissive. Accepted append replay resolves the original acceptance without
rechecking file availability; this does not grant access to erased bytes.

IDs are scoped by ledger. Identical bytes may be stored as different File IDs with
different media types. Changing an existing ID's bytes or metadata conflicts.
Replacing a file requires a new ID and does not redirect existing attachments.
Obsolete content descriptors are not accepted as core File inputs.

## Availability and bounded transfer

`files.get` returns available or partial metadata, including `uploaded_bytes`.
For missing or erased identities, it returns the state and identity without
inventing or restoring erased size, type or digest metadata. Permission is checked
before lookup. A service outage returns an availability error, not a false claim
that the file is missing.

The canonical `files.upload` operation accepts a file ID, SHA-256, declared size,
media type and `bytes_base64`. Small transfers can omit `offset` (zero) and
`complete` (true). Larger transfers send chunks with exact offsets and set complete
only on the final chunk. Conflicting chunk replay, changed metadata, invalid base64,
size overflow and incorrect final digest are rejected atomically. Failed final
verification leaves earlier valid progress available for a correct retry.

`files.download` returns metadata and at most 1 MiB of decoded bytes, encoded as base64, with `offset` and
`next_offset`. It returns no bytes when unavailable. Each chunk request rechecks
permissions and stored integrity. Follow `next_offset` until null, then verify the
complete file's size and SHA-256 before exposing the download as successful.
The supplied `files.read` and CLI download helpers do this for you.

MCP exposes `op_sys_files_upload`, `op_sys_files_download`, `op_sys_files_get` and
`op_sys_references_resolve` with the same wire schemas. Direct HTTP uses:

- `PUT /v1/ledgers/{ledger_id}/files/{file_id}/content`
- `GET /v1/ledgers/{ledger_id}/files/{file_id}/content?offset=0`
- `GET /v1/ledgers/{ledger_id}/files/{file_id}`
- `POST /v1/references/resolve`

Files are bounded to 1 GiB, chunks to 1 MiB, active files to 1,024 and reserved
active bytes to 128 GiB per ledger. These initial storage bounds are discoverable
through `capabilities.get`; `records.limits` also reports file and chunk bounds. Empty files follow the same integrity rules.
No path parameter or request body asks a remote server to open a filesystem path.

## Abandoned uploads and retention

Core uploads that have never been attached are eligible for cleanup after seven
days without successful upload activity. Cleanup runs opportunistically during
uploads, in bounded windows; eligibility is not a promise of immediate removal.
Completed but unattached uploads are also eligible. Hosted legal holds prevent
cleanup. Cleanup and attachment acceptance use the same transaction lock, and
attachment acceptance marks the file referenced before committing the record.

Cleanup removes bytes and releases active file/byte capacity while retaining a
minimal permanent identity tombstone. A stale upload cannot revive that identity.
It never clears an accepted relationship. Core upload ownership, activity and
reference metadata live in the private file manifest. Local bytes live in the
private `ledger-files/` directory; hosted bytes live in private S3 objects (or the
configured filesystem for self-hosted services). Bytes are stored before the
manifest commits. Failed writes can leave unreferenced chunks, which bounded
maintenance reclaims after a day. Hosted erasure is queued durably with the
database tombstone and completed by maintenance. No accepted reference is
redirected to different bytes.

Back up the complete local state root, not just its SQLite file. Workspace
bundles include the verified chunks referenced by their captured database,
including pending contributions; the existing archive size and entry limits
still apply. Schema-migration SQLite backups are rollback checkpoints inside
that state root. Hosted storage is configured by the service operator through the installation
settings. Database snapshots alone do not contain the hosted file bytes.

Retention and legal erasure are distinct from abandoned-upload cleanup. Retention
may remove attached bytes while a retained record still identifies the erased
File. The [lifecycle operations](/docs/raw/manuals/ledger-lifecycle.md) govern explicit file deletion. A downloaded copy
cannot be revoked by deleting its source.

## Resolve a record reference

```python
record = client.references.resolve(reference={
    "ledger_id": target_ledger_id,
    "record_id": target_record_id,
})
```

The reference resolves within the selected connection and its tenant/local store.
It carries no credentials, grants or external URL and never changes the client's
destination. Choose another configured connection explicitly to resolve a reference
there. Target `records.read` and current raw-data policy are required; possession
of the reference or membership in a collection grants nothing. Resolution does not
copy or enroll the target ledger. Its record, missing/erased or unavailable result
follows ordinary target-record lookup semantics.
