# Operator runbook — 0.2.1

## 1. Prepare the destination without touching production data

Use a buyer-authorised isolated Notion data source first. Create properties matching your `config.json` exactly. The supplied example needs:

- `Name` — title
- `Email` — email
- `Message` — rich text
- `Submitted` — date
- `Follow-up due` — date
- `Status` — select, with `New` available
- `Submission key` — rich text

Confirm the property names in `examples/config.json` before setup; the file is authoritative. A Notion **data-source UUID** is not necessarily its database UUID. Obtain it through the official API/UI; never paste a URL as an ID. Share only the agreed database with a limited integration that can read and insert content. The checker never writes, and the worker does not update existing rows or call schema-edit endpoints. **Select-value caveat:** Notion may add a missing option when a page is created with a new select name and the integration has the relevant write capability. The checker verifies configured `$status` options only; it cannot pre-validate future user-supplied select values. Prefer the example's fixed `$status` mapping, or agree and constrain all dynamic select values at the trusted source. Do not describe arbitrary select mapping as schema-immutable.

Copy the example config outside the extracted release and replace the fictional data source, form and mapping with verified values. Match the allowed form and source fields before any delivery. Config is non-secret but must be trusted and protected from modification. Exactly one title and at most nine explicit mappings are allowed; the source-key property is the tenth at most. Unknown bounded source fields are ignored rather than copied. Attachments and structured/non-string fields require separate scope and are rejected.

### Read-only setup check (before creating queue storage)

With `NOTION_TOKEN` already supplied securely in the environment, run:

```sh
python3 -m wix_notion --config config.json check
# Same command using the example path, after replacing its fictional configuration:
python3 -m wix_notion --config examples/config.json check
```

`--db` is unnecessary and ignored if passed; no DB, parent directory, SQLite connection or lock is touched. The checker performs only:

1. `GET /v1/data_sources/{configured UUID}` using the existing protected Notion transport.
2. If schema validation passes, one `POST /v1/data_sources/{configured UUID}/query` through `NotionProvider.find`, filtered on the reserved rich-text key with a fresh `setup-check:` UUID. POST here is a **read operation**, not a create. The probe is not an enquiry ID and does not sample real submissions.

Validation requires the exact data-source object/UUID, `in_trash: false`, a nonempty properties object, matching property names, distinct nonempty property IDs, matching type/settings objects, exactly the configured title (ID `title`), all configured properties including optional event fields, and the reserved rich-text key. Mapped select option IDs/names must be valid and distinct; the configured initial value must already exist for each `$status` mapping. It does not add missing properties/options. Unmapped columns are allowed with valid common schema fields; their type-specific semantics are not audited.

The retained API version is `2026-03-11`. Current data-source responses use `in_trash`; the deprecated `archived` alias was removed in that version. `is_archived` is documented for pages/query selection, not a required data-source field. If either archive spelling is nevertheless present on a data source, the checker accepts only literal `false`; missing `in_trash`, true/invalid/conflicting flags fail closed. See SOURCES.md.

**Success is schema/read-access verification only, never an insert-permission or production-ready claim.** Output explicitly leaves write permission, Wix source, hosting and live integration `not_tested`. Read access can succeed while inserting pages is forbidden. A complete returned row, if any, is validated by the inherited query adapter and discarded from output; neither an empty result nor a matching probe row establishes write access. A schema or permission change after this check can invalidate it.

#### Fixed diagnostics and limits

Exit **0**: both schema and read probe passed. Exit **2**: invalid invocation/config/credential, failed schema validation, failed HTTP/transport read, or incomplete/malformed query. Fix the prerequisite explicitly before rerunning; no automatic repair is attempted.

| Reason | Operator interpretation |
| --- | --- |
| `notion_token_required` | Supply the limited integration credential via environment, not arguments. |
| `invalid_configuration_or_input` | Repair config/token format or unsafe local-test URL. |
| `configuration_unavailable` | Config could not be opened/read; not a database error. |
| `schema_read_failed` | Schema GET was not HTTP 200, including transport failure. Confirm UUID, sharing and provider availability separately. |
| `invalid_data_source` | Invalid object/UUID/trash/archive/properties envelope. |
| `invalid_schema` | Malformed common property fields, duplicate IDs or wrong/missing/additional title. |
| `key_property_mismatch` | Reserved key column absent or not rich text. |
| `mapping_property_mismatch` | Mapped column absent or wrong type. |
| `invalid_select_options` | Malformed or duplicate option ID/name. |
| `initial_status_missing` | Configured initial `$status` option absent. Add it manually only with destination-owner approval. |
| `query_read_failed` | Query HTTP/transport/shape/read verification failed or result was partial. |

`mapping_index`, when present, is zero-based in config's `mappings`; diagnostics never echo schema names, tokens, response bodies, provider prose, request IDs or returned row contents. HTTP failures are intentionally grouped by stage, not a raw error dump. Ordinary argument-usage errors use argparse's exit 2/help text.

Limits: 65,536 config bytes; 2 MiB per provider response; common property names/IDs/types and select option names/IDs at most 200 characters; existing mapping limit of nine mappings plus key. Transport retains a 30-second socket timeout (not a whole-command deadline), strict production origin, disabled proxies and refused redirects. At most one schema GET and one query POST, no retries, sleeps, follow-up cursors, page reads or writes. A query with `has_more: true`, an incomplete `request_status`, malformed rows or contradictory cursor fails closed. No response content is persisted by this command.

Tests use synthetic tokens, environment-allow-listed CLI subprocesses and real loopback servers. They cover valid schema, each supported mapped type, bad/missing IDs/names/types, select option failures, archive/trash handling, malformed/oversized JSON, 403/404/429/5xx, disconnect/timeout, refused credential-forwarding redirects, partial queries and zero write calls. They also assert absent DB paths stay absent and existing files/symlinks remain untouched. Nothing here tests live integration capabilities, a Wix binding or a host installation.

## 2. Private storage and credentials

Create/use one private local directory (0700) and one SQLite database for this destination. The CLI refuses an existing parent readable by other users. SQLite contains plaintext mapped enquiry data; protect backups and disks, establish approved retention, and monitor size. Do not place the queue in a public web directory, network filesystem or source archive. Do not copy an active database or unlink its worker-lock file.

Supply secrets through a service manager's protected environment/secret facility:

- `INTAKE_TOKEN`: a cryptographically random secret (e.g. 32 random bytes encoded safely), shared only with the trusted Wix backend. The receiver checks format/length, not randomness. Never use synthetic tokens from the demo/tests.
- `NOTION_TOKEN`: limited Notion integration credential, needed by `work` and read-only `check`.

Never put either in command arguments, URLs, frontend Wix code, support messages or logs. The receiver does not need Notion credentials. Local ingest/status/recover commands cannot access the provider even when a Notion token exists in the environment.

## 3. Trusted Wix source — not a browser webhook

The authoritative event shape for the included pure normalizer is Wix Forms' submission-created backend event. `examples/wix-normalize.mjs` maps `event.entity._id`, `formId`, `_createdDate` and selected `submissions` field keys. It checks form, original identity and contradictory metadata, refuses anonymisation events, preserves timestamps and never manufactures an ID.

Copy the module into your site's **backend**, adapting only the import/extension for the editor. Bind it to the actual Wix Forms submission-created backend event. The official documentation currently labels the package `wixFormsV2` but its code example exports `wixForms_onSubmissionCreated`; confirm the editor-generated handler for your installed app rather than guessing a renamed handler. Backend events require a published test site; preview is not a live-event test. The normalizer was exercised in Node, not in Wix's runtime.

Example pure transformation (not a deployed handler):

```js
const normalized = normalizeWixEvent(event, verifiedFormId, {
  name: 'your_name_field_key',
  email: 'your_email_field_key',
  message: 'your_enquiry_field_key'
});
```

Your trusted server-side event transport sends `JSON.stringify(normalized)` to the configured HTTPS `/enquiries` endpoint, using the exact header contract below and the server-side intake secret. Use a transport which refuses redirects; the secret must never follow a redirect to a different origin. Keep the endpoint a trusted static configuration, never a field supplied by the customer. Store secrets through Wix's supported backend secret mechanism; the connector package does not acquire or provision them.

Alternatively use an existing trusted Wix automation whose HTTP action can send the exact verified original submission ID, timestamp, fields and bearer header. Check that capability in the actual account first. Generic form-browser events and unverified raw Wix public webhooks are **not** accepted as proof of authenticity. This component is not a Wix JWT verifier. Do not expose a frontend function that lets visitors choose IDs or arbitrary payloads using your backend secret.

The sender must retain the original Wix event/ID until durable acceptance; a timeout can occur after the intake committed. Replay the same normalized event and identity, not a fresh ID. On 4xx, retain the source record and repair the issue. Missing IDs cannot be reconstructed from the rejection digest. Configure a source-side failure review/retry path; this release does not claim Wix guarantees automatic delivery/retry. Site binding, source transport and its retention are client-specific setup, **not live-tested here**.

## 4. Start intake and advance the queue

With INTAKE_TOKEN securely present in the process environment:

```sh
python3 -m wix_notion --config config.json --db ./private/queue.sqlite3 serve --port 8787
```

It listens only on `127.0.0.1`. Put an operator-managed HTTPS reverse proxy in front with body/header limits, total request deadline, rate limiting and non-sensitive logs. The sequential Python receiver has a five-second inactivity timeout, not full public-server protection. The proxy must pass a single correct Content-Length and must not forward chunked bodies. No proxy/host has been provisioned in this release.

Only `POST /enquiries` is supported:

- One `Authorization` header with Bearer authentication, set server-side.
- One decimal `Content-Length`; no Transfer-Encoding/chunked body.
- `Content-Type: application/json` or `application/json; charset=utf-8`.
- At most 65,536 UTF-8 bytes; strict JSON (no duplicate keys, NaN/Infinity).
- Body matches `examples/event.json` with your verified source identity/data.

202 = stored locally, **not delivered**. 409 = same key, conflicting mapped payload. 422 = invalid JSON/fields, digest-only rejection stored for review. Authentication/framing/size failures are not stored; retain source. Storage failure never returns 202.

With NOTION_TOKEN securely present, advance one snapshot of queued work:

```sh
python3 -m wix_notion --config config.json --db ./private/queue.sqlite3 work
python3 -m wix_notion --config config.json --db ./private/queue.sqlite3 status
python3 -m wix_notion --config config.json --db ./private/queue.sqlite3 exceptions
```

`work` is one pass, not a daemon. Arrange an approved caller/service to invoke it regularly for deployment; this package does not install one. Concurrent invocations on the same local DB serialize on the OS lock. A pending unrelated job can progress even if another is uncertain, except while a genuine shared provider Retry-After cooldown is active.

Exit codes: 0 success/all delivered, 1 local storage failure, 2 invalid input/config/credential or missing recovery key, 3 worker pass ended with outstanding work. Always inspect job states, not just a 202 or command invocation.

## 5. Recovery — never force replay

`exceptions` exposes rejected-input digests and blocked/uncertain/sending jobs without raw enquiry contents. Inspect the fixed reason and retained source; do not copy credentials or provider payloads into chat.

- **Invalid source:** repair at source, keep the same original submission ID, then ingest again. The exception digest cannot restore the source body.
- **Definitively rejected create, e.g. 401/403:** repair access/schema; run `recover ORIGINAL_KEY`, then `work`. The receiver's returned `key` or `status` output supplies ORIGINAL_KEY.
- **Timeout, connection loss, 5xx, committed-503:** preserve DB and source ID. `work` reconciles the exact key or saved committed page ID. Matching destination and all values must verify before delivered.
- **No match after unknown write:** remains uncertain. It is deliberately not replayed, even after many empty reads. Investigate provider state. There is no force-send command.
- **Multiple matches/mismatched values:** inspect and resolve explicitly with the owner of that data. Do not delete records, merge them, change source identity or edit SQLite to trick the engine.
- **Blocked reconciliation:** `recover ORIGINAL_KEY` changes it only to reconciliation when prior commit is possible. It retains IDs, attempt history and cooldowns.
- **Exhausted retry budget:** recovery does not reset it. Escalate the job for manual investigation; no unlimited retry loop.

Changing mapping does not rewrite already queued immutable properties. Resolve a scope/config mistake against the original source carefully; there is no automatic destructive repair. Definite safe rejection recovery is tested; uncertain absence remains intentionally unresolved.

### Durable retry budgets and upgrading from 0.2.0

Version 0.2.1 persists `max_attempts` as a queue-wide ceiling. A larger value on a later `Engine` construction cannot raise it; a smaller value lowers it permanently for the queue. Workers already constructed refresh the stored ceiling under the same process lock before processing or recovery. The separate rate-limit response ceiling remains the smaller of the queue ceiling and six. The CLI uses six; custom limits are part of the Python `Engine` API, not a new command-line option.

Older queues did not store their historical ceiling. On the first 0.2.1 initialization, explicitly retain your original custom limit if you had one: otherwise the current default six is adopted. This is a migration limitation, not recovery of unknown historical configuration. All existing job attempts, rate counters, cooldowns, page IDs and uncertain states remain unchanged. Back up only a quiescent queue through your agreed maintenance process; upgrade every local worker together before resuming the installation. Mixed old/new workers are not covered by the new guarantee. This runbook does not operate or pause any service itself.

Lowering waits for an in-flight worker to release its lock, so it cannot undo attempts already authorised. Malformed/missing budget metadata on an existing worker fails closed with `invalid_retry_budget`; investigate protected storage rather than resetting it. A fresh initializer cannot distinguish manually deleted metadata from a legacy database, so do not delete/edit metadata, copy an active DB, or use a fresh queue to bypass exhaustion. Lost or tampered state remains outside the guarantee.

## 6. Acceptance in an actual authorised sandbox

Before production, submit one fictional Wix form through the actual event route; verify its original ID, the receiver's durable acknowledgement, the worker's delivered state and every value in Notion. Replay its event; confirm no second row. Submit a distinct ID for the same fictional adult; confirm a separate row. Check Unicode/multiline text, invalid fields, repaired permissions, source retry after lost acknowledgement, and required follow-up timing. Test the real reverse proxy and source-side retention. Do not assert these tests passed based on the included simulator.

## 7. Disconnect, retention and limitations

To disconnect your own installation, stop its sender/receiver/worker through its configured service controls, then revoke its limited provider token. Preserve a secured queue backup and unresolved-event list; removing the integration does not delete Notion records. Follow agreed personal-data retention before removing local data. No commands here operate on anyone else's services.

No queue quotas, alerts, scheduled runs, automated retention, multi-host coordination, schema management, customer communications, AI content generation or managed support. List/status/worker snapshot commands load the queue into memory. This is a small single-host reference connector, not a high-volume service. Independently running queues for the same destination, manual writers, a missing/replaced DB and provider visibility races outside the single local owner are not an exactly-once guarantee. External terms, hosting costs and customer access must be agreed separately.
