
# Documents

> MCP: wywołaj `read_docs({ operations: [operation] })` i podaj tylko pola ze zwróconego `inputSchema`. Przykłady HTTP poniżej zawierają kopertę zapisu, `requestId` i identyfikatory nadawane przez MCP (`projectId` przy tworzeniu, `documentId` przy tworzeniu dokumentu). Nie dodawaj tych pól do wywołania MCP. Typ rewizji bierze się ze schematu operacji.

Use [bearer authentication](authentication.md) and project permissions. Responses use `Cache-Control: private, no-store`.

## Public document routes

| Request | Result |
| --- | --- |
| `GET /api/v1/projects/{projectId}/documents` | `{documents:[...]}`, optional `documentKind`; unpaginated. |
| `GET /api/v1/projects/{projectId}/documents/{documentId}` | `{state:"ready",document}` or `{state,documentId}`. |
| `GET /api/v1/projects/{projectId}/documents/{documentId}/body` | Editing snapshot. |
| `GET /api/v1/projects/{projectId}/documents/{documentId}/body-info` | `{state:"ready",revision}`; blocked reads become errors. |
| `PUT /api/v1/projects/{projectId}/documents/{documentId}/body` | Full Markdown replacement. |
| `GET /api/v1/projects/{projectId}/export-jobs/{jobId}/download` | Completed export bytes; optional `?filename=` selects a manifest member. |

## Read the full editing snapshot

Ready fields are `state`, `body:{state,markdown,revision,assetBaseUrl}`, `document` including `bodyRevision`, `config`, `exportConfig`, `blueprintSectionKeys`, `titlePage`, optional `sync:{state,lastSyncedRevision,lastPull?,error?,pausedReason?}`. `state`/`body.state` are `ready`; sync is `pending`, `synced`, `error`, or `paused`. Server content is canonical; GET may import Drive content/request pulls.

`titlePage` is the printed title page, `{blocks:[...]}`, or `null` when the document has none. Blocks follow the layout in reading order (main area, then footer), and each is one of `logo`, `companyName`, `companyDetails`, `documentLabel`, `copyNumber`, `title`, `pairs`, `signatures` (including people continued on the next page), `date` or `text`. Only blocks that print are listed: empty fields are left out. The map link and QR code print only when the export includes them and the map is shared, so they are not listed. The editable design, with its team layout, is `documents/design/get`.

Blocked `{state,documentId}` states are `pending`, `mapping-required`, `adoption-required`, `missing`, `unavailable`, `desktop-required`; not empty.

## Save with the body revision

PUT takes exactly `{changeId,baseRevision,markdown}`. UUID `changeId`, positive integer `body.revision`, maximum 5 MiB UTF-8. Preserve every `<!-- operat:section ... -->`, matching `<!-- /operat:section ... -->`, generated-block marker, child section and unrelated text. Send the entire edited document, not a section fragment.

| HTTP | Response |
| --- | --- |
| 200 | `{status:"saved",bodyRevision}`; unchanged text may retain revision. |
| 409 | `{status:"conflict",current:{bodyRevision,markdown}}` |
| 422 | `{status:"rejected",reason:"invalid_content"}` |
| 413 | `{status:"rejected",reason:"too_large"}` |

Rejections change nothing. Other errors/oversized envelopes use `{error,message}`. On conflict, reconcile text and use a new UUID/current revision. Retry uncertain delivery identically, boundedly. Replay remembers only the latest successful identity; intervening edits require rereading. Never reuse UUIDs for different text.

## Save example

Use the revision from GET and a fresh UUID. `markdown` contains the complete edited document.

```json
{
  "changeId": "<fresh-uuid-1>",
  "baseRevision": "<returned-revision>",
  "markdown": "COMPLETE_EDITED_MARKDOWN"
}
```

## Editor updates

Committed changes reach open editors through project events. Independent edits can merge; overlapping edits retain conflict drafts. GET excludes unsaved keystrokes. Public HTTP cannot read local-folder bodies.

[Operat creation, configuration, regeneration and export](#operat).

[Document actions](actions.md) add creation, blueprints, configuration, generated sections, title pages, assets and export jobs. Read `GET /api/v1/actions?domain=documents` for names and individual schema links.

The [calculation insertion sequence](calculations.md#insert-saved-calculations-into-s_6) saves calculations, preserves existing result selections, and applies generated S_6 content with revisions and preview tokens.

## Rename metadata conditionally

Ready document GET includes `document.configRevision`, `title`, and `exportBasename`. Capture these acknowledged values before constructing an intent. `exportBasename` must be unique within its project. POST `documents/update` through the [named action API](actions.md) with at least one update and expected values for exactly the updated fields.

```json
{
  "projectId": "p", "documentId": "d",
  "updates": {"title": "Reviewed title"},
  "precondition": {"kind": "metadata_fields", "observedConfigRevision": "<returned-revision>", "expected": {"title": "Observed title"}},
  "write": {"sessionId": "<fresh-uuid-2>", "lane": "project-presentation", "sequence": 1}
}
```

The owner compares the expected field values atomically. The observed revision records the read basis. Another field, another document, or a completed body save can change without rejecting this patch. Pending content or native effects still block metadata. Whole-config updates retain strict `expectedConfigRevision` checks. This contract does not edit unsaved body text.

Success returns `{document:{documentId,configRevision,title,exportBasename,updatedAt},change:{domain,revision,updatedAt}}` from the stored receipt. HTTP 409 `precondition_failed` returns bounded `current`, `conflictingFields`, `attempt`, and `recovery`. Reread and reconsider after a definitive conflict. A new intent uses a new sequence.

POST `projects/writes/status` with `{projectId,write}` to recover an uncertain metadata outcome. The user comes from authentication. `settled` includes operation `documents.metadata.update` and its original typed result or rejection. Exact receipt access requires current `documents.write`. `superseded` means a newer sequence has settled. `unseen` can mean the original request is still running. Status never executes a write or changes a receipt. Shared-camera receipts use operation `maps.view.set` and require current `map.edit`. Drawing receipts use `maps.features.mutate`, `maps.features.details`, `maps.features.upsert`, `maps.features.remove`, `maps.groups.create`, and `maps.groups.children`, also requiring current `map.edit`. Specification receipts require current `documents.write`; their exact operations are listed below. Other operation receipts are unsupported.

Retain the exact values, expected fields, read basis, and write envelope until the attempt settles. Retry only that identical payload after an uncertain answer. Changed target, values, or preconditions under the same attempt returns `attempt_payload_mismatch`; delayed older sequences return `write_superseded`. These errors preserve the stored receipt. Serialize all writes of one project/session/presentation lane, including renames of different documents. Use a new session UUID for an independent client.

Request rejection before the metadata owner receives the command cannot promise a durable refusal receipt. Metadata events publish after commit. Ordinary replay emits no duplicate event; process-crash notification recovery uses the existing stream reset and reread behavior.

## Author a specification

GET each action URL for its JSON Schema. POST the same URL with the parameter object. The six actions are under `/api/v1/actions/documents/specification/`.

| Action | Parameters beyond `projectId` and `documentId` | Result |
| --- | --- | --- |
| `create` | `title`, ordered `tasks:[{title,items:[{id} or {title}]}]`, `precondition:{kind:"document_absent"}`, `write` | Original document identity, task/item keys, template and blank item summaries, `localFileState:"ready"`. |
| `items/list` | None. | `tasks`, observed `bodyRevision`. |
| `items/add` | `expectedRevision`, `write`, `taskSectionKey`, `item:{id}` or `{title}`, optional `position` or `afterItemSectionKey`. | `addedItem`, `tasks`, `bodyRevision`. |
| `items/remove` | `expectedRevision`, `write`, `itemSectionKey`. | `removedItem`, `tasks`, `bodyRevision`. |
| `items/reorder` | `expectedRevision`, `write`, `taskSectionKey`, complete `orderedItemSectionKeys`. | `tasks`, `bodyRevision`. |
| `renumber` | `expectedRevision`, `write`. | `changed`, `tasks`, `bodyRevision`. |

Discover template IDs with `documents/specification/templates/list`. A custom item uses `{title}` and the packaged blank template. Task and item keys are deterministic slugs with collision suffixes. Preserve returned keys when editing. Creation requires a caller-chosen stable document ID that is absent.

Capture `bodyRevision` from `items/list` before each structural intent. All four edit actions require that exact `expectedRevision`, including a no-op reorder or renumber. HTTP 409 `specification_body_changed` includes `documentId`, `expectedRevision`, and `currentBodyRevision`. Reread the structure and reconsider the intent before sending a new attempt. Structural operations retain unrelated authored text and unknown sections.

Each mutation requires `write:{sessionId,lane:"project-presentation",sequence}`. Retain the complete normalized command and envelope. Serialize this lane with metadata, camera, and drawing writes from the same client. An identical retry returns the original result before template assembly or structural mutation runs again, including after an intervening body save or server restart. Changed document, values, or revision under the same attempt returns `attempt_payload_mismatch`. A newer sequence supersedes older attempts.

POST `projects/writes/status` with `{projectId,write}` to recover a retained result or terminal rejection. Its exact operations are `documents.specyfikacja.create`, `.renumber`, `.items.add`, `.items.remove`, and `.items.reorder`. Successful values have the same shape as the original action results. Mutation replay requires current `documents.write` and supported writer admission. Read-only status requires current `documents.write` without writer-version admission. An unseen status can race an in-flight command. Admission failure before owner dispatch has no durable receipt guarantee.

The server stores the prepared content and command outcome atomically. Ordinary replay does not advance revisions or emit another change event. Notifications retain the existing postcommit crash window. These structural commands operate on persisted content; unsaved editor buffers are outside this protocol. Local-folder execution retains its installed filesystem owner and admission.


## Calculation selections and refresh

Operat configuration uses `calculationSelections: [{ calculationId, resultKeys }]`.
`resultKeys` lists explicitly every result the operat states, at least one; the operat renders
only the listed results, and an empty list is rejected. Configuration describe returns
`calculations` with current result statuses and unavailable deleted selections. For example,
`{ "calculationId": "native:outlet-1", "resultKeys": ["catchment/snq"] }` selects SNQ alone.
Preserve unrelated configuration fields and existing selections when updating the full config.

Saving configuration leaves document text unchanged. Reconcile structure, then refresh S_6 or
its `calculation:<calculationId>` block through preview and apply. Retain the returned body revision,
configuration revision and input token for apply; a stale preview cannot authorize a replacement.
Inactive selected results are shown explicitly. Deleted selections require reselection before
refresh. S_9/S_10 and document totals use only the chosen results.

Calculation mentions use `@calculation:<calculationId>` for the whole calculation or
`@calculation:<calculationId>#<resultKey>[,<resultKey>...]` for an explicit ordered subset.
For example, `@calculation:outlet#catchment/ssq,catchment/snq` resolves one combined report with
only SSQ and SNQ. Scoped keys must be known, unique and non-empty, with no spaces; malformed
suffixes stay unresolved. Bare mentions deliberately include all results, including later additions.
Their reference-graph object is the calculation id; scoped edge payloads contain the same
`resultKeys` array, and whole-calculation payloads are `null`. Preserve the full token and its scope
when editing Markdown or replacing mention edges. See [calculation mentions](calculations.md)
for the shared parser, serializer and reference helper.
Calculation titles remain plain text in generated markers, headings, the TOC and quoted prose,
including titles containing parentheses or equation-looking text.

## Operat

### Create and configure

POST [`documents/create`](https://tarvena.pl/api/v1/actions/documents/create):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","title":"Operat wodnoprawny – wyloty","blueprintKey":"operat.core"}
```

Returns `{"state":"ready","document":{"id":"operat-demo-1"},"body":{"revision":"<returned-revision>"}}`.

POST [`documents/config/get`](https://tarvena.pl/api/v1/actions/documents/config/get):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1"}
```

Returns `{"configRevision":"<returned-revision>","config":{}}`.

Read the config and preserve fields outside your intended scope. For a new rainwater document:

POST [`documents/config/update`](https://tarvena.pl/api/v1/actions/documents/config/update):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","expectedConfigRevision":"<returned-revision>","config":{"schemaVersion":1,"waterServiceIds":["rainwater"],"specialWaterUseIds":[],"otherPermitScopeIds":[],"qualifiers":{"hasCombinedOverflow":false,"hasHydroelectricPlant":false,"hasIndustrialWastewaterWithEspeciallyHarmfulSubstances":false,"hasStormOverflow":false},"calculationSelections":[]}}
```

Returns `{"configRevision":"<returned-revision>"}`.

### Reconcile, then refresh

POST [`documents/structure/reconcile`](https://tarvena.pl/api/v1/actions/documents/structure/reconcile):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1"}
```

Returns `{"status":"preview","preview":{"baseRevision":"<returned-revision>","baseConfigRevision":"<returned-revision>","relevantInputToken":"<token>","canApplyAutomatically":true,"changes":[]}}`.

Review `changes`. Copy all three preview basis values into apply; `<token>` stands for the returned token, copied unchanged. Confirm removals only after reviewing their contents.

POST [`documents/structure/reconcile`](https://tarvena.pl/api/v1/actions/documents/structure/reconcile):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","apply":true,"changeId":"<fresh-uuid-1>","expectedRevision":"<returned-revision>","expectedConfigRevision":"<returned-revision>","relevantInputToken":"<token>"}
```

Returns `{"status":"accepted","revision":"<returned-revision>"}`.

On conflict preview again. For required removals, include the reviewed `confirmedRemovalSectionKeys` / `confirmedRemovalBlockKeys` from the preview.

POST [`documents/sections/refresh`](https://tarvena.pl/api/v1/actions/documents/sections/refresh):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","sectionKey":"S_2_1"}
```

Returns `{"status":"preview","preview":{"baseRevision":"<returned-revision>","baseConfigRevision":"<returned-revision>","relevantInputToken":"<token>","sectionKey":"S_2_1","sectionMarkdownPreview":"<generated Markdown>"}}`.

Review the generated Markdown, then apply its exact basis:

POST [`documents/sections/refresh`](https://tarvena.pl/api/v1/actions/documents/sections/refresh):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","sectionKey":"S_2_1","apply":true,"changeId":"<fresh-uuid-2>","expectedRevision":"<returned-revision>","expectedConfigRevision":"<returned-revision>","relevantInputToken":"<token>"}
```

Returns `{"status":"accepted","revision":"<returned-revision>"}`.

### Read and apply office notes

After evidence settles, read the automatically inferred ZZ and its parent RZGW:

POST [`projects/authority-office/get`](https://tarvena.pl/api/v1/actions/projects/authority-office/get):

```json
{"projectId":"<projectId>"}
```

Returns `{"officeId":"zz-biala-podlaska","rzgwId":"rzgw-lublin"}`.

Use the distinct non-null ids returned for this project. If neither resolves, skip the notes call;
omitting the filter fetches every office. If the current request names an office, use its verified
directory id.

POST [`authority-notes/list`](https://tarvena.pl/api/v1/actions/authority-notes/list):

```json
{"officeIds":["zz-biala-podlaska","rzgw-lublin"]}
```

### Fill generated sections

For body GET/PUT, revisions and section markers, use the [HTTP body editing protocol](documents.md).

Successful document API edits persist: a body PUT returning `status: "saved"` or a revision-checked
section preview/apply returning `status: "accepted"` has already saved the text. For cloud documents,
the database document is the live copy used by the editor and new exports of the current document;
no further save is needed. A preview alone does not save changes.

An applied source refresh overwrites manual edits inside the section body or generated-block body
it regenerates.

### Configure a separate non-technical description

If an applicable note requests separate S_0, read the existing preferences:

POST [`documents/export-config/get`](https://tarvena.pl/api/v1/actions/documents/export-config/get):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1"}
```

Preserve every other field in the returned `preferences`. Set only
`operatExportSection0Separately: true`, with the returned `configRevision` and a stable
`updateRequestId`. The following example assumes the other preferences have the values shown;
use the actual read values. Retain the same request UUID and payload on retry. On conflict reread
and merge the intended change with a new request UUID.

POST [`documents/export-config/update`](https://tarvena.pl/api/v1/actions/documents/export-config/update):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1","expectedConfigRevision":"<returned-revision>","updateRequestId":"<fresh-uuid-5>","preferences":{"format":"pdf","headerText":"","includeNumbering":true,"includePageNumbers":true,"includeToc":true,"numberingStartSectionKey":null,"operatExportSection0Separately":true,"includeMapLink":false}}
```

### Export and download

POST [`documents/export/admission`](https://tarvena.pl/api/v1/actions/documents/export/admission):

```json
{"projectId":"<projectId>","documentId":"operat-demo-1"}
```

Returns `{"kind":"remote_set"}`.

Use this admission kind for the cloud export request.

POST [`documents/export/create`](https://tarvena.pl/api/v1/actions/documents/export/create):

```json
{"kind":"remote_set","requestId":"<fresh-uuid-3>","request":{"projectId":"<projectId>","documentId":"operat-demo-1","format":"pdf"}}
```

Returns `{"jobId":"<fresh-uuid-4>"}`.

Use the returned job ID; `docx` and `html` are also supported.

POST [`documents/export/jobs/get`](https://tarvena.pl/api/v1/actions/documents/export/jobs/get):

```json
{"projectId":"<projectId>","jobId":"<fresh-uuid-4>"}
```

Returns `{"jobId":"<fresh-uuid-4>","state":"ready","manifest":[{"filename":"operat.pdf"}]}`.

Poll `documents/export/jobs/get` every 2–5 seconds until `state` is `ready`, `failed` or `expired`. A PDF of an Operat of about 50 pages is usually ready 10–30 seconds after creation; a queue of other exports adds to that.

<!-- enum documents/export/jobs/get output.state -->
Job states: `queued`, `rendering`, `ready`, `failed`, `expired`.

| `state` | Meaning | Next step |
| --- | --- | --- |
| `queued` | Admitted and waiting for a render slot. A service restart returns an interrupted job to this state. | Keep polling. |
| `rendering` | The export is being rendered. `manifest` is still `null`. | Keep polling. |
| `ready` | `manifest` lists the files with `filename`, `size` and `sha256`; `expiresAt` is one hour after `finishedAt`. | Download before `expiresAt`. |
| `failed` | No output. `error` is `document_missing` (the document or its version is gone), `render_failed` or `artifact_missing` (output lost before download). | Fix a missing document, then create a new export with a new `requestId`. |
| `expired` | The `ready` output passed `expiresAt` and was deleted. | Create a new export with a new `requestId`. |

Normally, finished jobs are deleted a day after `finishedAt`, and reading one then returns 404. Cleanup waits while the output is still being copied to Drive, so a job can stay `ready` past `expiresAt` or a day; treat `expiresAt` as the deadline to plan for, not a guarantee of expiry.

GET `/api/v1/projects/<projectId>/export-jobs/<fresh-uuid-4>/download?filename=operat.pdf` with the bearer token. URL-encode the actual manifest filename. Response is attachment bytes; omit `filename` for the combined artifact. Download before `expiresAt`; current export permission and the creating session’s user are required. Drive is optional.

[Document recovery](documents.md#save-with-the-body-revision).
