# ILMENO Agent Sync API

> **API build: `0.1.0+gb805d1f5` · deployed 2026-11-13 (UTC).**
> This page ships inside the server binary, so it always describes exactly
> the API that is deployed right now. **Re-fetch this page from time to
> time** — a daily check is plenty, or whenever a call behaves
> unexpectedly. If the build string above changed since your last read,
> re-read the whole document: endpoints or fields may have been added.
> Changes are additive whenever possible — always ignore unknown JSON
> fields in responses instead of erroring. The snapshot body additionally
> carries its own `schema` number for structural changes to the envelope.

Machine-readable reference for AI agents. Everything you need to read a
user's open tasks and create new ones is on this page.

- Base URL: `https://api.ilmeno.com/sync/v1`
- Auth: `Authorization: Bearer <token>` on every request. The user copies
  the token from the ILMENO iOS app (Settings → Imports & Sync → API).
- **End-to-end encryption:** everything you read or write is an AES-256-GCM
  envelope. The user copies the **encryption key** from the same screen;
  the server never has it. See "Encryption" below before your first call.
- Interactive test page (humans): `https://api.ilmeno.com/tools/sync-viewer`
- OpenAPI 3.1 document (same API, for tooling):
  `https://api.ilmeno.com/tools/sync-openapi.yaml`
- Human overview incl. how the user gets a token and what the server
  stores: `https://ilmeno.com/api/`

## Mental model

The iOS app mirrors its data to this server; **the device is the single
source of truth**. The mirror is as fresh as the user's last app usage:
the app pushes a full snapshot on every foregrounding and a few seconds
after every local change, and polls its inbox every ~3 minutes while
open. There is **no live connection** when the app is closed.

Consequences for you as an agent:

1. `GET /snapshot` may be hours old — check `exportedAt` before reasoning
   about "today".
2. Tasks you `POST /inbox` appear on the device the next time the user
   opens the app (or within ~3 minutes if it is open). They arrive marked
   with source `api` and a distinct icon.
3. **A task disappearing between two snapshots means it was completed or
   deleted.** Completed tasks are never included.
4. You can read, create, and **complete** tasks. You can NOT edit or
   delete existing tasks (deliberate design: an agent works on a mirror
   that may be hours old and must never overwrite what the user changed
   since; creating and completing are safe, text edits are not). If your
   use case genuinely needs editing, write to hello@ilmeno.com — tell us
   what you would change and how you would avoid overwriting the user. Completion is applied by
   the device with a "device wins" rule: if the task was already
   completed, trashed, or is gone by the time the device processes your
   item, it is silently ignored — never treat a completion as done until
   the task actually disappears from a later snapshot.

## Encryption (end-to-end) — read this first

The server stores and relays **ciphertext only**. The app encrypts the
snapshot before uploading; you decrypt it with the user's key. You encrypt
every inbox item with the same key; the device decrypts and applies it.
The server checks only the envelope shape and size — it cannot read a
title, a tag or a `taskId`, and it rejects nothing on content.

Key: 32 bytes, handed to you as URL-safe base64 (43 chars, like the
token). Envelope, in both directions:

```json
{"enc":"v1","alg":"A256GCM","comp":"deflate-raw",
 "nonce":"<base64, 12 bytes>","ct":"<base64, ciphertext || 16-byte GCM tag>"}
```

- `comp` is optional. The **snapshot** is raw-deflated (no zlib/gzip
  header) before encryption, so inflate after decrypting. **Inbox items
  you write are not compressed** — omit `comp`.
- Base64 may be standard or URL-safe, with or without padding; the app
  accepts both. The app writes standard base64.
- `ct` carries the GCM tag appended — the native output of Python
  `cryptography`, WebCrypto, Go; in Node append `cipher.getAuthTag()`.
- No additional authenticated data. Fresh random 12-byte nonce per item.
- Inside the snapshot envelope is exactly the JSON described under
  "Snapshot schema"; inside an inbox envelope exactly one create or
  complete item as described under `POST /inbox`.

Python (`pip install cryptography requests`):

```python
import base64, json, zlib, os, requests
from cryptography.hazmat.primitives.ciphers.aead import AESGCM

TOKEN, KEY_B64 = "…", "…"
def b64d(s): return base64.urlsafe_b64decode(s.replace("+", "-").replace("/", "_") + "=" * (-len(s) % 4))
key = AESGCM(b64d(KEY_B64))
H = {"Authorization": f"Bearer {TOKEN}"}

env = requests.get("https://api.ilmeno.com/sync/v1/snapshot", headers=H).json()
plain = key.decrypt(b64d(env["nonce"]), b64d(env["ct"]), None)
if env.get("comp") == "deflate-raw": plain = zlib.decompress(plain, -15)
snapshot = json.loads(plain)

def seal(item: dict) -> dict:
    nonce = os.urandom(12)
    ct = key.encrypt(nonce, json.dumps(item).encode(), None)   # ciphertext||tag
    return {"enc": "v1", "alg": "A256GCM",
            "nonce": base64.b64encode(nonce).decode(), "ct": base64.b64encode(ct).decode()}
requests.post("https://api.ilmeno.com/sync/v1/inbox", headers=H,
              json=seal({"title": "Water the plants", "contextTag": "personal"}))
```

Node (built-in `crypto` and `zlib`):

```js
import crypto from "node:crypto"; import zlib from "node:zlib";
const b64d = s => Buffer.from(s.replace(/-/g, "+").replace(/_/g, "/"), "base64");
const key = b64d(KEY_B64);
function open(env) {
  const ct = b64d(env.ct), d = crypto.createDecipheriv("aes-256-gcm", key, b64d(env.nonce));
  d.setAuthTag(ct.subarray(ct.length - 16));
  let plain = Buffer.concat([d.update(ct.subarray(0, ct.length - 16)), d.final()]);
  if (env.comp === "deflate-raw") plain = zlib.inflateRawSync(plain);
  return JSON.parse(plain.toString("utf8"));
}
function seal(item) {
  const nonce = crypto.randomBytes(12), c = crypto.createCipheriv("aes-256-gcm", key, nonce);
  const ct = Buffer.concat([c.update(JSON.stringify(item), "utf8"), c.final(), c.getAuthTag()]);
  return { enc: "v1", alg: "A256GCM", nonce: nonce.toString("base64"), ct: ct.toString("base64") };
}
```

What the server still sees: the size of the blob, when it changes, your
IP address, how many inbox items are pending. Nothing else.

A plaintext body (no `enc` field) is **refused with `400
encryption_required`** on both `POST /inbox` and `PUT /snapshot` (since
2026-11-04; before that the server relayed it and the app silently
dropped it, which an agent could not tell). If you see this code, you
are sending the plaintext — seal it first.

## Endpoints for agents

### GET /sync/v1/snapshot

Returns the latest snapshot as an **encryption envelope** (see above);
decrypt and inflate to get the JSON described under "Snapshot schema".
`404` with code `not_found` until the app has pushed at least once.

```bash
curl -s -H "Authorization: Bearer $TOKEN" \
  https://api.ilmeno.com/sync/v1/snapshot
```

### POST /sync/v1/inbox

Queues an operation for the device. Returns `{"id":"<uuid>"}` (the queue
item id, not a task id). **The body is an encryption envelope** whose
plaintext is one of the two operations below, selected by `op` — the
examples show the plaintext you seal:

**Create a task** (`op` omitted or `"create"`):

```bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"title":"Water the plants","contextTag":"personal","duration":"quick"}' \
  https://api.ilmeno.com/sync/v1/inbox
```

**Complete a task** (`op: "complete"` + the task's `id` from the snapshot):

```bash
curl -s -X POST -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"op":"complete","taskId":42}' \
  https://api.ilmeno.com/sync/v1/inbox
```

Completion semantics: the device runs its normal completion path
(recurring tasks spawn their next instance, pins are released, a series
already completed today is a no-op). Already done / trashed / unknown
`taskId` → silently ignored, device wins. Verify by watching the task
disappear from a later snapshot. All other payload fields are ignored on
a complete item.

Create-payload fields (everything except `title` is optional):

| Field | Type | Semantics |
|---|---|---|
| `op` | string | `create` (default) \| `complete`. |
| `taskId` | int | Only for `op: "complete"`: the snapshot task `id`. Required there, must be positive. |
| `title` | string, required, non-empty | Task title. |
| `notes` | string | Free text; lands as the task's **Content** (markdown body, `description` in the snapshot). |
| `firstStep` | string | The tiny first step (ILMENO's ADHD-core concept: make starting easier than not starting). Lands as the first checklist step (`steps[0]`) and in `firstStep`. Recommended. |
| `contextTag` | string | Name of an EXISTING context tag ("area"), matched case-insensitively against `name` and `display_name` from the snapshot's `tags` (entries with `is_context_tag: true`). Unknown names are silently ignored. You can never create new tags. **If you omit this (or the name doesn't match), the app runs its own AI classification** on the title — area, tags and a first step get filled automatically (user-toggleable). Set `contextTag` yourself when you want full control. |
| `tags` | array of strings | Names of existing sub-tags (`is_context_tag: false`). Unknown names are dropped silently. |
| `deadline` | string `YYYY-MM-DD` | Due date; lands as end-of-day local time on the device. Invalid format → `400`. |
| `duration` | string | `quick` \| `normal` \| `long` — the same vocabulary the snapshot uses (`deep` is accepted as an alias of `long`). Effort estimate; the device treats anything else as `normal`. |

Limits: payload ≤ 32 KB; at most 200 un-collected inbox items per
mailbox (then `429 inbox_full` — means the device hasn't synced for a
long time, stop posting). The server strips unknown keys of the envelope;
inside the plaintext the device ignores fields it does not know.

### Device-only endpoints — do not call these

`PUT /sync/v1/snapshot`, `GET /sync/v1/inbox`, `POST /sync/v1/inbox/ack`,
`DELETE /sync/v1/mailbox` exist for the app side of the protocol. They
work with your token, but calling them can overwrite the mirror or eat
inbox items before the device sees them. Agents use exactly two calls:
`GET /snapshot` and `POST /inbox`.

## Snapshot schema

Top-level envelope:

| Field | Type | Semantics |
|---|---|---|
| `schema` | int | Envelope version, currently `1`. |
| `exportedAt` | ISO-8601 string | When the device built this snapshot. Your staleness indicator. |
| `appVersion` | string | e.g. `"1.0 (1742)"`. |
| `tasks` | array | All OPEN tasks (not completed, not trashed). |
| `tags` | array | The full tag vocabulary (context tags = areas, plus sub-tags). |

All dates are ISO-8601 strings. All optional fields are present with
explicit `null` (never omitted). Key style is mixed (historical DB
naming) — use the exact names below.

### Task object

| Key | Type | Semantics |
|---|---|---|
| `id` | int | Stable task id. |
| `title` | string | Title. |
| `firstStep` | string | The small first step ("" if none). |
| `state` | string | `not_started` \| `in_progress` (only open states appear; `in_progress` = the user is working on it right now). |
| `context_tag_id` | int \| null | Id of the context tag (area) in `tags`. `null` = Inbox (untriaged). |
| `tagIds` | array of int | Sub-tag ids (look up in `tags`). |
| `steps` | array | Checklist: `{id, taskId, text, sortOrder, isDone}`. |
| `notes` | string \| null | User note. |
| `description` | string \| null | Longer markdown body (imports, share sheet). |
| `duration` | string | `quick` \| `normal` \| `long` — effort estimate (same values you may send on create). |
| `deadline` | ISO-8601 \| null | Absolute due moment. |
| `activeFrom` | ISO-8601 \| null | Task is hidden/deferred until this date (skip/schedule-later). In the future ⇒ not currently actionable. |
| `recurrence` | object \| null | Repeat rule: `{frequency: daily\|weekly\|monthly\|yearly, interval: int, weekdays: [int 1–7, 1 = Sunday], daysOfMonth: [int], monthOfYear: int\|null}`. Non-null ⇒ this is a recurring "rhythm" instance. |
| `deadlineOffsetDays` | int \| null | Recurring only: due N days after the instance appears. |
| `deadline_time_minutes` | int \| null | Recurring only: due time as minutes since midnight (`null` = end of day). |
| `deadline_reminder_minutes` | int \| null | Reminder N minutes before deadline (`null` = off). |
| `active_from_reminder_minutes` | int \| null | Reminder N minutes before `activeFrom`. |
| `series_id` | string \| null | Groups all instances of one recurring series (master task's id). |
| `frequency_target` | object \| null | Flexible goal: `{count: int, period: day\|week\|month, hard: bool}` — e.g. "3× per week". `hard` ⇒ series rests once met. |
| `skip_history` | array of ISO-8601 | Each time the user postponed ("skipped") the task. Long list ⇒ the user is stuck on it. |
| `pin_kind` | string \| null | `manual` = user pinned it to Now; `lba` = auto-pinned by Life-Balance-Awareness today; `null` = unpinned. |
| `time_preferences` | array of string | Soft "fits best" hints: `morning`, `afternoon`, `evening`, `weekday`, `weekend`. |
| `timeLoggedSeconds` | int | Accumulated focus-timer seconds. |
| `source` | string | Origin: `app`, `siri`, `share_sheet`, `csv_import`, `reminders_import`, `email_relay`, `api` (created by an agent), `import`. |
| `source_detail` | string \| null | Origin detail (e.g. Reminders list name). |
| `createdAt` / `updatedAt` | ISO-8601 | Lifecycle timestamps. |
| `deletedAt` | null | Always `null` here (trashed tasks are excluded). |
| `completed_at` | null | Always `null` here (completed tasks are excluded). |
| `aiClassifiedAt` | ISO-8601 \| null | When AI auto-classification last ran. |
| `excluded_context_sub_tag_ids` | array of int | Sub-contexts the task is hidden from (internal ranking detail). |

### Tag object

| Key | Type | Semantics |
|---|---|---|
| `id` | int | Referenced by `context_tag_id` / `tagIds`. |
| `name` | string | Canonical lowercase name — use this (or `display_name`) in inbox payloads. |
| `is_context_tag` | bool | `true` = context tag / life area (work, personal, …); `false` = sub-tag. |
| `display_name` | string \| null | Human-readable label for context tags. |
| `color` | string \| null | Hex color, e.g. `#3B82F6`. |
| `sort_order` | int | Display order among context tags. |
| `description` | string \| null | What belongs in this tag (written for AI classification — useful for you too). |
| `importance` | int 0–4 | Life-Balance weight; higher = the user cares more that this area doesn't starve. 0 = untracked. |
| `favorite_context_tag_ids` | array of int | Sub-tag ⇒ the areas it is a favorite of (UI sorting hint). |

## Privacy notes you should respect

- The mirror holds the user's personal task titles, notes and tags. Do
  not copy it into places the user did not ask for; do not log it.
- The app stores token and encryption key only in the iOS keychain; keep
  both in your own secret store, never in prompts or shared logs. The
  key is what keeps the server blind — treat it as the more sensitive
  of the two.
- If you omit `contextTag`, the device may run its own AI classification
  of the title (cloud model, user-toggleable). Set `contextTag` when the
  user wants no AI involved.

## Errors and limits

Errors always look like `{"error":{"code":"...","message":"..."}}`:

| HTTP | code | Meaning |
|---|---|---|
| 401 | `unauthorized` | Missing/malformed bearer token (or the user renewed access — ask them for the new token **and** key). |
| 404 | `not_found` | Valid token, but the app never pushed a snapshot (or access was renewed). |
| 400 | `bad_request` | Malformed JSON or an envelope with unsupported parameters (message says what). |
| 400 | `encryption_required` | The body is plaintext, not an envelope. Seal it with the user's key (see "Encryption"). |
| 500 | `internal` | Server-side failure. Retry later; if it persists, tell the user. |
| 429 | `rate_limited` / `inbox_full` | Back off. Limits: 300 requests/hour, 3000/day per IP; 200 pending inbox items. |

**When the user renews access** ("Renew access" in the app): the app
first collects any inbox items still waiting under the old token, then
deletes the old mailbox and mints a new token **and** a new encryption
key. Your old token answers `401`/`404` from then on, and the old key
cannot open the new snapshot — ask the user for both new values. Items
you posted before the renewal are not lost; items posted after it with
the old token are refused.

Sensible agent cadence: reading the snapshot a few times per hour is
plenty — it only changes when the user actually uses the app.
