mirror of
https://github.com/kuhyx/diet-guard.git
synced 2026-11-26 21:07:25 +01:00
Add the Claude relay contract
Contract for the phone "send to Claude" button, written before any code: docs/DOCS-claude-relay.md, the shared Python/Dart fixture and its builder script. No code runs from this commit. Failure paths named in the contract: - locked sync / locked e2e key: fail closed, worker writes nothing, the request stays pending (phone keeps its hourglass) - invalid body, request older than 24 h, Claude timeout/failure/invalid JSON: fail closed, an error result is written and nothing is logged - duplicate event, expired lease or crash replay: idempotent by rid (entry id is uuid5 of the rid, checked before the Claude call) - due mode with nothing due: not an error, falls back to slot_for_log Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WzxdWZHWP4KZ6x5TcXDBFC
This commit is contained in:
parent
15a0899119
commit
3ce43b56df
@ -115,6 +115,9 @@ repos:
|
|||||||
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
- crdt-sync @ git+https://github.com/kuhyx/utils@crdt-sync-v0.11.1#subdirectory=crdt-sync
|
||||||
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
- freedays @ git+https://github.com/kuhyx/utils@freedays-v0.4.3#subdirectory=freedays
|
||||||
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
|
- sickdays @ git+https://github.com/kuhyx/utils@sickdays-v0.5.4#subdirectory=sickdays
|
||||||
|
- rtdb-relay @ git+https://github.com/kuhyx/utils@rtdb-relay-v0.1.1#subdirectory=rtdb_relay
|
||||||
|
- claude-agent-sdk==0.2.183
|
||||||
|
- httpx==0.28.1
|
||||||
- mcp>=2,<3
|
- mcp>=2,<3
|
||||||
- pydantic
|
- pydantic
|
||||||
- defusedxml==0.7.1
|
- defusedxml==0.7.1
|
||||||
|
|||||||
@ -2,7 +2,7 @@ name: diet_guard_app
|
|||||||
description: "Companion phone app for diet_guard: log meals on the go."
|
description: "Companion phone app for diet_guard: log meals on the go."
|
||||||
publish_to: 'none'
|
publish_to: 'none'
|
||||||
|
|
||||||
version: 1.0.163+1
|
version: 1.0.164+1
|
||||||
|
|
||||||
environment:
|
environment:
|
||||||
sdk: ^3.12.2
|
sdk: ^3.12.2
|
||||||
|
|||||||
232
docs/DOCS-claude-relay.md
Normal file
232
docs/DOCS-claude-relay.md
Normal file
@ -0,0 +1,232 @@
|
|||||||
|
# The "send to Claude" relay (contract)
|
||||||
|
|
||||||
|
The phone sends a food description and/or a photo. A worker on the PC runs
|
||||||
|
Claude on kuhy's Max subscription, **logs the meal at once (no review)** and
|
||||||
|
answers the phone. Transport is Firebase RTDB through the shared
|
||||||
|
`rtdb_relay` package (`kuhyx/utils`, tag `rtdb-relay-v0.1.1`), the same wire
|
||||||
|
format as the tutor app. No VPN, no open port, only kuhy's Google account.
|
||||||
|
|
||||||
|
This file is the contract both halves build against. The fixture
|
||||||
|
`tests/fixtures/claude_relay_contract.json` is read by the Python tests and
|
||||||
|
by the phone's Dart tests, so the two cannot drift. Regenerate it with
|
||||||
|
`scripts/build_claude_relay_fixture.py` (random nonces: bytes change, the
|
||||||
|
plaintext does not). The worker lives in `diet_guard/_claude_*.py`; the
|
||||||
|
estimator and its skill are described at the end.
|
||||||
|
|
||||||
|
## 1. Where it lives in RTDB
|
||||||
|
|
||||||
|
Root `R = diet-guard-sync/claude-e2e`. It is `E2eLayout.of("diet-guard-sync/claude")`,
|
||||||
|
chosen so its header path is **the existing header `diet-guard-sync/e2e`**,
|
||||||
|
the one `E2eLayout.of("diet-guard-sync/devices")` already uses. Same
|
||||||
|
passphrase, same Argon2id salt, same key: the phone unlocks nothing new. A
|
||||||
|
test asserts the two header paths are equal; a second header would be a
|
||||||
|
second salt and the phone could not open a request.
|
||||||
|
|
||||||
|
| Path under `R` | Writer | Value |
|
||||||
|
|---|---|---|
|
||||||
|
| `requests/{rid}/req` | phone | sealed unit, clear sibling `created` |
|
||||||
|
| `requests/{rid}/claim` | worker | clear `{by, lease_until, attempt, phase, at}` |
|
||||||
|
| `requests/{rid}/result` | worker | sealed unit, clear sibling `at` |
|
||||||
|
|
||||||
|
Every other path is refused by the sealer (fail closed). A sealed unit is
|
||||||
|
`{"_e2e": <blob>, <clear siblings>}`; the blob is crdt_sync's `E2eCipher`
|
||||||
|
over compact JSON with the unit's full path (`R/requests/{rid}/req`) as AAD,
|
||||||
|
so a blob copied to another path does not open. Byte format:
|
||||||
|
`~/src/utils/rtdb_relay/rtdb_relay/tests/data/e2e_vectors.json`. Both
|
||||||
|
`req` and `result` are sealed, **the photo included**: no food text or image
|
||||||
|
is ever in clear.
|
||||||
|
|
||||||
|
`rid` is a **ULID** (`[0-9A-HJKMNP-TV-Z]{26}`), not a uuid. `rtdb_relay`
|
||||||
|
never serves any other key, so a uuid-keyed request would sit unanswered
|
||||||
|
forever. This is a deliberate deviation from the first sketch ("id (uuid)");
|
||||||
|
the rid is the request's `id`.
|
||||||
|
|
||||||
|
## 2. Request (`requests/{rid}/req`)
|
||||||
|
|
||||||
|
Plaintext before sealing:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"kind": "meal", "dev": "<phone device id>", "sent_at": 1767225600000,
|
||||||
|
"body": {"text": "2 jajka sadzone i kromka chleba",
|
||||||
|
"photo_jpeg_b64": "<base64>", "client_slot_min": 720, "mode": "due"}}
|
||||||
|
```
|
||||||
|
|
||||||
|
plus the **clear** sibling `created` = `{".sv": "timestamp"}` (RTDB server
|
||||||
|
time, ms). `created`, not `sent_at`, drives the 24 h rule: a phone clock can
|
||||||
|
be wrong.
|
||||||
|
|
||||||
|
| Field | Rule |
|
||||||
|
|---|---|
|
||||||
|
| `kind` | exactly `"meal"`; anything else -> `unknown_kind` |
|
||||||
|
| `body.text` | optional string, 1..2000 chars after trim |
|
||||||
|
| `body.photo_jpeg_b64` | optional standard base64 of a JPEG (starts `FFD8`), longest side <= ~1024 px, <= 600 000 base64 chars |
|
||||||
|
| `body.client_slot_min` | required int 0..1439: the slot the phone would use now (its own `slotForLog`) |
|
||||||
|
| `body.mode` | required: `"due"` or `"normal"` |
|
||||||
|
|
||||||
|
At least one of `text` / `photo_jpeg_b64` is required. An invalid body gets
|
||||||
|
`bad_request` (below) and nothing is logged. The phone downsizes and
|
||||||
|
re-encodes the photo before sealing (the raw camera file is several MB).
|
||||||
|
|
||||||
|
## 3. Result (`requests/{rid}/result`)
|
||||||
|
|
||||||
|
`ok` is authoritative. Every result the meal handler writes also carries
|
||||||
|
`status` (`"logged"` | `"error"`); the two guard failures `unsealed` and
|
||||||
|
`unknown_kind` come from `rtdb_relay` before the handler and carry only
|
||||||
|
`ok: false`, so a client reads `status = ok ? "logged" : "error"`.
|
||||||
|
|
||||||
|
Logged (clear sibling `at` = server ms):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"ok": true, "kind": "meal", "status": "logged", "id": "<rid>",
|
||||||
|
"entry_id": "<uuid5 of rid>", "desc": "2 jajka sadzone i kromka chleba",
|
||||||
|
"grams": 190, "kcal": 410, "protein_g": 17.5, "carbs_g": 22, "fat_g": 26,
|
||||||
|
"slot_min": 720, "time": "2026-11-17T12:03:41+01:00"}
|
||||||
|
```
|
||||||
|
|
||||||
|
Error:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{"ok": false, "kind": "meal", "status": "error", "id": "<rid>",
|
||||||
|
"error_code": "estimate_failed", "code": "estimate_failed",
|
||||||
|
"error": "model returned no valid JSON", "retry": true}
|
||||||
|
```
|
||||||
|
|
||||||
|
`code` and `error_code` are the same string (`code` is `rtdb_relay`'s name,
|
||||||
|
`error_code` the phone-facing one). `error` is for the log, never the UI.
|
||||||
|
|
||||||
|
| `code` | Meaning | `retry` |
|
||||||
|
|---|---|---|
|
||||||
|
| `bad_request` | body fails section 2 | false |
|
||||||
|
| `expired` | `created` older than 24 h when the PC got to it | false |
|
||||||
|
| `estimate_timeout` | Claude exceeded 45 s | true |
|
||||||
|
| `estimate_failed` | Claude errored or the CLI/login is unusable | true |
|
||||||
|
| `estimate_invalid` | output not JSON / fails the schema / nonsense values | true |
|
||||||
|
| `unsealed`, `unknown_kind` | `rtdb_relay` guards | false |
|
||||||
|
| `internal` | a bug in the handler (visible, never a silent drop) | true |
|
||||||
|
|
||||||
|
**No answer is not an error.** If the PC cannot sync or the e2e key is
|
||||||
|
locked (`SyncError`, `E2eLockedError`, wrong or missing passphrase) the
|
||||||
|
worker writes nothing, leaves the request pending, logs why, and tries
|
||||||
|
again (section 6). The phone keeps its hourglass.
|
||||||
|
|
||||||
|
## 4. The slot
|
||||||
|
|
||||||
|
The PC decides; `client_slot_min` is never trusted in due mode. All maths
|
||||||
|
reuse `_slots.py` and `_gate.due_slots`; this feature changes none of it.
|
||||||
|
|
||||||
|
- **`"due"`**: after a narrow `pull_peer_logs()`, the entry's slot is
|
||||||
|
`due_slots(now)[0]`, the **oldest** elapsed-but-unlogged slot of today
|
||||||
|
(so a phone meal already logged elsewhere is seen). `client_slot_min` is
|
||||||
|
ignored.
|
||||||
|
- **`"due"` with nothing due** (already logged elsewhere, free day, sick
|
||||||
|
day, hold, or outside the enforcement window): not an error. Fall back to
|
||||||
|
`slot_for_log(now, schedule)`, the rule `ate` uses.
|
||||||
|
- **`"normal"`**: `nearest_slot(client_slot_min, schedule)`, the existing
|
||||||
|
nearest-slot rule, so a request that waited hours for a switched-off PC
|
||||||
|
still lands in the slot the phone saw when it was sent.
|
||||||
|
|
||||||
|
The entry's `time` is the processing time (`log_meal` forbids the past), and
|
||||||
|
`source` is `"claude"`. The logged slot is echoed as `slot_min`.
|
||||||
|
|
||||||
|
## 5. Order of work and why
|
||||||
|
|
||||||
|
```
|
||||||
|
phone: PUT req ──────────────────────────────────────────────────────────┐
|
||||||
|
PC: claim (ETag lease) -> validate -> age check -> already logged? -> │
|
||||||
|
narrow pull_peer_logs -> Claude estimate -> slot -> log_meal -> │
|
||||||
|
PUT result -> DELETE req -> publish_after_log (background) <────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
1. **Idempotent by request id, twice over.** The entry id is
|
||||||
|
`uuid5(NAMESPACE, rid)`. Before spending a Claude call the worker looks
|
||||||
|
for that id in the raw log (tombstones included). Found: it rebuilds the
|
||||||
|
result from the entry and logs nothing. So a duplicate SSE event, a lease
|
||||||
|
that expired, or a crash between `log_meal` and the result PUT (the
|
||||||
|
worker takes over its own dead claim on restart) all end in one entry.
|
||||||
|
2. **Pull before Claude.** `pull_peer_logs()` (the narrow one, ~84 ms) fails
|
||||||
|
closed. A failure means "do nothing" (section 3) before any model cost.
|
||||||
|
3. **Answer first, publish last.** `publish_after_log` is a full sync tick
|
||||||
|
(15 to 27 s). Run before the answer it would break the 30 s target, so
|
||||||
|
the order is log, result, delete `req`, then publish. The result already
|
||||||
|
carries everything the phone shows; the entry itself reaches the phone's
|
||||||
|
log through the normal sync a moment later. A failed publish is only
|
||||||
|
logged: the entry is durable locally and the next tick or lock carries it.
|
||||||
|
4. **Delete only `req`.** The photo is the heavy part and is useless after
|
||||||
|
the answer. `claim` and `result` stay so a phone that was offline when
|
||||||
|
the result landed still reads it. The phone should delete
|
||||||
|
`requests/{rid}` once it has shown the answer; the worker deletes any
|
||||||
|
answered node whose `result.at` is older than 24 h.
|
||||||
|
5. **Expiry.** A request whose `created` is older than 24 h when the worker
|
||||||
|
reaches it gets `expired` and nothing is logged; its `req` is deleted
|
||||||
|
like any other.
|
||||||
|
6. **Blocking work** (log file, sync, Claude) never runs on the event loop.
|
||||||
|
One lock serialises "resolve slot + `log_meal`" so two requests do not
|
||||||
|
take the same due slot.
|
||||||
|
|
||||||
|
## 6. The worker
|
||||||
|
|
||||||
|
`python -m diet_guard claude-worker`, run by `diet-guard-claude.service`
|
||||||
|
(systemd `--user`, `Restart=on-failure`, `WantedBy=default.target`).
|
||||||
|
|
||||||
|
- Event-driven: one SSE stream on `R/requests`. Reconnects forever with
|
||||||
|
1/2/5/10/30 s backoff; `auth_revoked` reconnects at once; `cancel` (the
|
||||||
|
rules now refuse the path) is fatal. Each reconnect begins with the whole
|
||||||
|
node, so requests that arrived while the PC was off are served in order.
|
||||||
|
- Waits are only for faults: the e2e unlock and a failed pre-pull retry
|
||||||
|
every 60 s / 30 s while something is pending. No idle timer.
|
||||||
|
- Session: its own Firebase app name `diet_guard_claude`
|
||||||
|
(`~/.config/diet_guard_claude/firebase_auth.json`), never the gate's
|
||||||
|
`diet_guard` file (two processes refreshing one token file corrupt it).
|
||||||
|
Seed once, see "Deploy". The database URL and API key come from
|
||||||
|
`~/.config/crdt-sync/firebase.json`; the passphrase from
|
||||||
|
`~/.config/crdt-sync/password`.
|
||||||
|
- One worker per PC. Claim leases last 300 s and renew every 60 s.
|
||||||
|
- Dependencies (`rtdb_relay`, `httpx`, `claude_agent_sdk`) are imported only
|
||||||
|
inside the worker's own modules, never by the gate or the CLI at load
|
||||||
|
time. System Python needs them before the unit starts (see "Deploy").
|
||||||
|
|
||||||
|
## 7. Security rules
|
||||||
|
|
||||||
|
`~/src/utils/firebase/database.rules.json` pins the **whole database** to
|
||||||
|
kuhy's uid (`.read` and `.write` on the root: `auth != null && auth.uid ===
|
||||||
|
<uid>`). `R` is a path inside that database, so **the existing rules already
|
||||||
|
cover it and no rules change is needed**. The tutor already runs under the
|
||||||
|
same rule at `tutor/v1-e2e`. The local rendered copy
|
||||||
|
(`~/.config/crdt-sync/database.rules.json`) matches that shape; the live
|
||||||
|
console copy could not be read without a signed-in uid (check with an
|
||||||
|
unauthenticated `curl "$DATABASE_URL/.json"`: must answer
|
||||||
|
`Permission denied`). A stranger who signs up with the public API key reads
|
||||||
|
and writes nothing. The worker's session must be kuhy's own account.
|
||||||
|
|
||||||
|
## 8. The estimator and its skill
|
||||||
|
|
||||||
|
`diet_guard/_claude_estimate.py` exposes the pure function
|
||||||
|
`estimate_meal(text: str | None, photo: bytes | None) -> Estimate` (also for
|
||||||
|
the Tk gate later). It runs Claude through `claude_agent_sdk` with an
|
||||||
|
**isolated `CLAUDE_CONFIG_DIR`** holding only a copy of the OAuth access
|
||||||
|
token (no refresh token) and `skills/diet-food/SKILL.md`. kuhy's own
|
||||||
|
`~/.claude` is never read except to copy the token: its hooks would make the
|
||||||
|
model answer with a grilling round.
|
||||||
|
|
||||||
|
- Input: the text, the photo as an image content block, and the closest
|
||||||
|
rows of the curated and derived food banks (`search_foods(text)`; for a
|
||||||
|
photo-only request the top rows by count).
|
||||||
|
- Output: strict JSON, enforced by `output_format` json_schema and
|
||||||
|
re-validated: `desc`, `grams` (>0), `kcal`, `protein_g`, `carbs_g`,
|
||||||
|
`fat_g` (all finite, >= 0, kcal <= 5000), optional `components`. Anything
|
||||||
|
else is `estimate_invalid`.
|
||||||
|
- Failure, timeout, invalid JSON or a missing login: an error result and
|
||||||
|
**nothing is logged** (fail closed).
|
||||||
|
|
||||||
|
## 9. Deploy (not done by the implementation)
|
||||||
|
|
||||||
|
1. `/usr/bin/python3 -m pip install --user --break-system-packages -e .`
|
||||||
|
from `~/src/diet-guard` (new deps: `claude-agent-sdk`, `rtdb-relay`,
|
||||||
|
`httpx`); verify `/usr/bin/python3 -c "import claude_agent_sdk, rtdb_relay, httpx"`.
|
||||||
|
2. Seed the worker's session once (one Google consent):
|
||||||
|
`python3 -m tool.seed_session --client-id ... --client-secret ... --app diet_guard_claude`
|
||||||
|
in `~/src/utils/crdt-sync`.
|
||||||
|
3. `bash install.sh` (copies and enables `diet-guard-claude.service` once
|
||||||
|
the session file exists).
|
||||||
|
4. Phone side: the sender, hourglass state and result screen. They follow
|
||||||
|
sections 1 to 3 and the fixture.
|
||||||
175
scripts/build_claude_relay_fixture.py
Executable file
175
scripts/build_claude_relay_fixture.py
Executable file
@ -0,0 +1,175 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
"""Regenerate the shared "send to Claude" relay contract fixture.
|
||||||
|
|
||||||
|
``tests/fixtures/claude_relay_contract.json`` is read by the Python tests
|
||||||
|
(``diet_guard/tests/test_claude_relay_contract.py``) and by the phone's Dart
|
||||||
|
tests, so the PC worker and the phone app seal, open and validate the same
|
||||||
|
bytes. The wire format is ``docs/DOCS-claude-relay.md``.
|
||||||
|
|
||||||
|
Sealed blobs use a fixed test key but a random nonce, so every run changes the
|
||||||
|
blob bytes; the plaintext and the clear siblings stay put. Readers *open* the
|
||||||
|
blobs and compare plaintext, they never compare ciphertext.
|
||||||
|
|
||||||
|
Run from the repo root:
|
||||||
|
|
||||||
|
.venv/bin/python scripts/build_claude_relay_fixture.py
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
from typing import Any
|
||||||
|
|
||||||
|
from crdt_sync import E2eCipher, E2eLayout
|
||||||
|
from rtdb_relay.layout import Layout
|
||||||
|
from rtdb_relay.seal import Sealer
|
||||||
|
|
||||||
|
OUT = Path(__file__).resolve().parent.parent / "tests" / "fixtures"
|
||||||
|
OUT_FILE = OUT / "claude_relay_contract.json"
|
||||||
|
|
||||||
|
KEY_HEX = bytes(range(32)).hex()
|
||||||
|
RID = "01JD5Z8K3M7Q2W9XH4TBN6VR0E"
|
||||||
|
ROOT = E2eLayout.of("diet-guard-sync/claude").prefix
|
||||||
|
HEADER = E2eLayout.of("diet-guard-sync/devices").e2e_path
|
||||||
|
CLEAR = ("requests/*/claim",)
|
||||||
|
UNITS = {"requests/*/req": ["created"], "requests/*/result": ["at"]}
|
||||||
|
CREATED_MS = 1_795_000_000_000
|
||||||
|
PHOTO_B64 = (
|
||||||
|
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgK"
|
||||||
|
"CgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/"
|
||||||
|
)
|
||||||
|
|
||||||
|
REQUEST: dict[str, Any] = {
|
||||||
|
"kind": "meal",
|
||||||
|
"dev": "6f1f0c1e-5b0a-4a3e-9f57-2c1d6f0e9a11",
|
||||||
|
"sent_at": CREATED_MS - 40,
|
||||||
|
"body": {
|
||||||
|
"text": "2 jajka sadzone i kromka chleba",
|
||||||
|
"photo_jpeg_b64": PHOTO_B64,
|
||||||
|
"client_slot_min": 720,
|
||||||
|
"mode": "due",
|
||||||
|
},
|
||||||
|
}
|
||||||
|
LOGGED: dict[str, Any] = {
|
||||||
|
"ok": True,
|
||||||
|
"kind": "meal",
|
||||||
|
"status": "logged",
|
||||||
|
"id": RID,
|
||||||
|
"entry_id": "7b0c5d52-8a43-5a63-b6f5-7d0f1c0e2a44",
|
||||||
|
"desc": "2 jajka sadzone i kromka chleba",
|
||||||
|
"grams": 190,
|
||||||
|
"kcal": 410,
|
||||||
|
"protein_g": 17.5,
|
||||||
|
"carbs_g": 22,
|
||||||
|
"fat_g": 26,
|
||||||
|
"slot_min": 720,
|
||||||
|
"time": "2026-11-17T12:03:41+01:00",
|
||||||
|
}
|
||||||
|
ERROR: dict[str, Any] = {
|
||||||
|
"ok": False,
|
||||||
|
"kind": "meal",
|
||||||
|
"status": "error",
|
||||||
|
"id": RID,
|
||||||
|
"error_code": "estimate_failed",
|
||||||
|
"code": "estimate_failed",
|
||||||
|
"error": "model returned no valid JSON",
|
||||||
|
"retry": True,
|
||||||
|
}
|
||||||
|
EXPIRED: dict[str, Any] = {
|
||||||
|
**ERROR,
|
||||||
|
"error_code": "expired",
|
||||||
|
"code": "expired",
|
||||||
|
"error": "request older than 24 h",
|
||||||
|
"retry": False,
|
||||||
|
}
|
||||||
|
CLAIM: dict[str, Any] = {
|
||||||
|
"by": "pc-worker",
|
||||||
|
"lease_until": CREATED_MS + 300_000,
|
||||||
|
"attempt": 1,
|
||||||
|
"phase": "claimed",
|
||||||
|
"at": CREATED_MS + 10,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _case(name: str, body: dict[str, object], *, valid: bool) -> dict[str, Any]:
|
||||||
|
return {"name": name, "valid": valid, "body": body}
|
||||||
|
|
||||||
|
|
||||||
|
def _body(**fields: object) -> dict[str, object]:
|
||||||
|
return {"client_slot_min": 480, "mode": "due", **fields}
|
||||||
|
|
||||||
|
|
||||||
|
# Body validation, shared by the PC (``_claude_contract``) and the phone.
|
||||||
|
BODY_CASES: list[dict[str, Any]] = [
|
||||||
|
_case("text only", _body(text="banan", mode="normal"), valid=True),
|
||||||
|
_case("photo only", _body(photo_jpeg_b64=PHOTO_B64, client_slot_min=0), valid=True),
|
||||||
|
_case("both", REQUEST["body"], valid=True),
|
||||||
|
_case("nothing to estimate", _body(), valid=False),
|
||||||
|
_case("blank text", _body(text=" "), valid=False),
|
||||||
|
_case("text too long", _body(text="x" * 2001), valid=False),
|
||||||
|
_case("bad mode", _body(text="a", mode="now"), valid=False),
|
||||||
|
_case("slot out of range", _body(text="a", client_slot_min=1440), valid=False),
|
||||||
|
_case("slot not int", _body(text="a", client_slot_min="480"), valid=False),
|
||||||
|
_case("missing slot", {"text": "a", "mode": "due"}, valid=False),
|
||||||
|
_case("photo not jpeg", _body(photo_jpeg_b64="aGVsbG8="), valid=False),
|
||||||
|
_case("photo not base64", _body(photo_jpeg_b64="@@@"), valid=False),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
def _sealer() -> Sealer:
|
||||||
|
layout = Layout(
|
||||||
|
root=ROOT,
|
||||||
|
clear=CLEAR,
|
||||||
|
units={k: frozenset(v) for k, v in UNITS.items()},
|
||||||
|
)
|
||||||
|
return Sealer(E2eCipher(bytes.fromhex(KEY_HEX)), layout)
|
||||||
|
|
||||||
|
|
||||||
|
def _node(
|
||||||
|
sealer: Sealer, path: str, plain: dict[str, Any], clear: dict[str, Any]
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""A stored unit: ``plain`` sealed for ``path`` plus its clear siblings."""
|
||||||
|
stored = sealer.seal(path, {**plain, **clear})
|
||||||
|
return {"path": path, "node": stored, "plain": plain, "clear": clear}
|
||||||
|
|
||||||
|
|
||||||
|
def build() -> dict[str, Any]:
|
||||||
|
"""The whole fixture as a JSON-ready dict."""
|
||||||
|
sealer = _sealer()
|
||||||
|
base = f"requests/{RID}"
|
||||||
|
answered = {"at": CREATED_MS + 9000}
|
||||||
|
return {
|
||||||
|
"version": 1,
|
||||||
|
"root": ROOT,
|
||||||
|
"header_path": HEADER,
|
||||||
|
"key_hex": KEY_HEX,
|
||||||
|
"rid": RID,
|
||||||
|
"layout": {"clear": list(CLEAR), "units": UNITS},
|
||||||
|
"limits": {
|
||||||
|
"text_max": 2000,
|
||||||
|
"photo_b64_max": 600_000,
|
||||||
|
"slot_max": 1439,
|
||||||
|
"expiry_hours": 24,
|
||||||
|
"estimate_timeout_s": 45,
|
||||||
|
},
|
||||||
|
"request": _node(sealer, f"{base}/req", REQUEST, {"created": CREATED_MS}),
|
||||||
|
"claim": {"path": f"{base}/claim", "node": CLAIM},
|
||||||
|
"results": {
|
||||||
|
"logged": _node(sealer, f"{base}/result", LOGGED, answered),
|
||||||
|
"error": _node(sealer, f"{base}/result", ERROR, answered),
|
||||||
|
"expired": _node(sealer, f"{base}/result", EXPIRED, answered),
|
||||||
|
},
|
||||||
|
"body_cases": BODY_CASES,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> None:
|
||||||
|
"""Write the fixture."""
|
||||||
|
OUT.mkdir(parents=True, exist_ok=True)
|
||||||
|
text = json.dumps(build(), indent=1, ensure_ascii=False)
|
||||||
|
OUT_FILE.write_text(text + "\n", encoding="utf-8")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
234
tests/fixtures/claude_relay_contract.json
vendored
Normal file
234
tests/fixtures/claude_relay_contract.json
vendored
Normal file
@ -0,0 +1,234 @@
|
|||||||
|
{
|
||||||
|
"version": 1,
|
||||||
|
"root": "diet-guard-sync/claude-e2e",
|
||||||
|
"header_path": "diet-guard-sync/e2e",
|
||||||
|
"key_hex": "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f",
|
||||||
|
"rid": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
|
||||||
|
"layout": {
|
||||||
|
"clear": [
|
||||||
|
"requests/*/claim"
|
||||||
|
],
|
||||||
|
"units": {
|
||||||
|
"requests/*/req": [
|
||||||
|
"created"
|
||||||
|
],
|
||||||
|
"requests/*/result": [
|
||||||
|
"at"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"limits": {
|
||||||
|
"text_max": 2000,
|
||||||
|
"photo_b64_max": 600000,
|
||||||
|
"slot_max": 1439,
|
||||||
|
"expiry_hours": 24,
|
||||||
|
"estimate_timeout_s": 45
|
||||||
|
},
|
||||||
|
"request": {
|
||||||
|
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/req",
|
||||||
|
"node": {
|
||||||
|
"_e2e": "AYkr3BaGDxFvr9QkhFAb1O/op1RoJGARMjrAnpbcvZ7rFxKVSy0kxKTbUSEqQarex+WBhoshvig8CgZ+X5Zpr6lOw+qoOLTEc+Oc31eUi3vyGipYm1zQDtowCQzTLaNXnWHaVtOqFf7cVZ8vsvSot08c0PI7zHjUbY7uCBQoF6q4sOekDm8k23UQSi9vkyd+EL1hPnjtBPCDCI6QoZq+T09YZxKeXm8oA7hWh0r5ZKMcD2n/2K4MLzyIEhi7kZtPH0Mq8adkSPHtPKkPYdKXhpXNVdChCmBXvzPhWJ6xi66p0FViGIVxhAg4IgCwxhzCyRHAYPjufAheZjbMJt+98aAHEGn2ZEImqIOu+o26GxgmxDXSu/u/IQSb5RJKdMheGFhKCpK6n8/7Qg/Z6keendoVMCwIYbhu0wNDs3qaxd+IaLYc33ABvKssu3kMnrwJ2jR6iDYgSrKe+qGxO4A=",
|
||||||
|
"created": 1795000000000
|
||||||
|
},
|
||||||
|
"plain": {
|
||||||
|
"kind": "meal",
|
||||||
|
"dev": "6f1f0c1e-5b0a-4a3e-9f57-2c1d6f0e9a11",
|
||||||
|
"sent_at": 1794999999960,
|
||||||
|
"body": {
|
||||||
|
"text": "2 jajka sadzone i kromka chleba",
|
||||||
|
"photo_jpeg_b64": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/",
|
||||||
|
"client_slot_min": 720,
|
||||||
|
"mode": "due"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"clear": {
|
||||||
|
"created": 1795000000000
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"claim": {
|
||||||
|
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/claim",
|
||||||
|
"node": {
|
||||||
|
"by": "pc-worker",
|
||||||
|
"lease_until": 1795000300000,
|
||||||
|
"attempt": 1,
|
||||||
|
"phase": "claimed",
|
||||||
|
"at": 1795000000010
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"results": {
|
||||||
|
"logged": {
|
||||||
|
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
|
||||||
|
"node": {
|
||||||
|
"_e2e": "AYLAiRb9+uIpXCSEC8v0bzwxY7kNzlTLgpo+Ys36nAlnFANO1/blHQ1t/hv+MdUNGqyMaPQWwOddC6QClMKcxq0LzG5xV+0DL4Q4XDNGszd+RJgp12iZaRoJMEPLzoDQcnyq0kSjlrZaVIii7fJIFZOTrsS7z22CfCYQNi37uWkmglocNwbOmZiuo7XP4xikJyADhNGJuseo8Hrvrjzm0AVfp2+vuubVpDY7xM7EGhn49yDz+iwFRpvqpmHbVD1mFqEY2l0UhGrWEt+WFW5nD5IOejPiVk9eehXJCEJadU+1t/+ADntYwoxyQjwiicgSAgUK4fU3rxNhUeGPgKLYWYXE8ALywAlf6ieoDlRX8bX+YmHTZDuxhA+vttsxkZhPtC6D2ZcyeokOuHRWTNOZBesAyFiLL+co5/8EqUhUAvRxyGU=",
|
||||||
|
"at": 1795000009000
|
||||||
|
},
|
||||||
|
"plain": {
|
||||||
|
"ok": true,
|
||||||
|
"kind": "meal",
|
||||||
|
"status": "logged",
|
||||||
|
"id": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
|
||||||
|
"entry_id": "7b0c5d52-8a43-5a63-b6f5-7d0f1c0e2a44",
|
||||||
|
"desc": "2 jajka sadzone i kromka chleba",
|
||||||
|
"grams": 190,
|
||||||
|
"kcal": 410,
|
||||||
|
"protein_g": 17.5,
|
||||||
|
"carbs_g": 22,
|
||||||
|
"fat_g": 26,
|
||||||
|
"slot_min": 720,
|
||||||
|
"time": "2026-11-17T12:03:41+01:00"
|
||||||
|
},
|
||||||
|
"clear": {
|
||||||
|
"at": 1795000009000
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"error": {
|
||||||
|
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
|
||||||
|
"node": {
|
||||||
|
"_e2e": "AQdF1d1WVvex3sIwfSAq4df+jWFbJ0/rJAF9FUy85X2pQXa98pAHUJ3CPd9AnGmy3nG+ARBc/IjpJjUi7D07Vg8uZGOy6/FRh91uI9F1LMBPZ/pgO65M5+KC7MGEKszcWzntp8vPkLpHw8ujBtN5mmwPrUkKpL+xH6t0mY6/mdSnEuByiy1OOO0FxH5gbvQ+DAO5JKLRsjNPHHj33NlQpejVUH3OUhlcZTDMIGIV4gY8say9dP5cWL+1ppkBLNxU3dnO/oc0pDM/S4+WqdEmJ1vMQyjkhU2hCTgrGAPNPE0YbQ==",
|
||||||
|
"at": 1795000009000
|
||||||
|
},
|
||||||
|
"plain": {
|
||||||
|
"ok": false,
|
||||||
|
"kind": "meal",
|
||||||
|
"status": "error",
|
||||||
|
"id": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
|
||||||
|
"error_code": "estimate_failed",
|
||||||
|
"code": "estimate_failed",
|
||||||
|
"error": "model returned no valid JSON",
|
||||||
|
"retry": true
|
||||||
|
},
|
||||||
|
"clear": {
|
||||||
|
"at": 1795000009000
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"expired": {
|
||||||
|
"path": "requests/01JD5Z8K3M7Q2W9XH4TBN6VR0E/result",
|
||||||
|
"node": {
|
||||||
|
"_e2e": "AQekXG0hCaJd2HLHF4wvRk5PZxqhrM+m+DsjWgdU8mLyay3/DX8T6za37LVF1IpM11hkJ9L6vpdJkH3Rfsfedh5NYssuAV+qF2uHCPeeJ9Iy9Anou9TQ/TkEhOBX6/3+y1AJyvSD/gxACZX32g5tzW+qA4fgbJyPgYIEo2SN5u27M2NrZQzXIpxUYaiqDt2eClAKZH/o6xfMOXVEHCV5QHdbGqxVBIMDZ0D+E8O9zVsNDpHxejaMwUf/vsvjolPhKN4pTqX0ksmW38LgSWU=",
|
||||||
|
"at": 1795000009000
|
||||||
|
},
|
||||||
|
"plain": {
|
||||||
|
"ok": false,
|
||||||
|
"kind": "meal",
|
||||||
|
"status": "error",
|
||||||
|
"id": "01JD5Z8K3M7Q2W9XH4TBN6VR0E",
|
||||||
|
"error_code": "expired",
|
||||||
|
"code": "expired",
|
||||||
|
"error": "request older than 24 h",
|
||||||
|
"retry": false
|
||||||
|
},
|
||||||
|
"clear": {
|
||||||
|
"at": 1795000009000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"body_cases": [
|
||||||
|
{
|
||||||
|
"name": "text only",
|
||||||
|
"valid": true,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "normal",
|
||||||
|
"text": "banan"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "photo only",
|
||||||
|
"valid": true,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 0,
|
||||||
|
"mode": "due",
|
||||||
|
"photo_jpeg_b64": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "both",
|
||||||
|
"valid": true,
|
||||||
|
"body": {
|
||||||
|
"text": "2 jajka sadzone i kromka chleba",
|
||||||
|
"photo_jpeg_b64": "/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAMCAgICAgMCAgIDAwMDBAYEBAQEBAgGBgUGCQgKCgkICQkKDA8MCgsOCwkJDRENDg8QEBEQCgwSExIQEw8QEBD/",
|
||||||
|
"client_slot_min": 720,
|
||||||
|
"mode": "due"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "nothing to estimate",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "due"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "blank text",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "due",
|
||||||
|
"text": " "
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "text too long",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "due",
|
||||||
|
"text": "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "bad mode",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "now",
|
||||||
|
"text": "a"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "slot out of range",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 1440,
|
||||||
|
"mode": "due",
|
||||||
|
"text": "a"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "slot not int",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": "480",
|
||||||
|
"mode": "due",
|
||||||
|
"text": "a"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "missing slot",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"text": "a",
|
||||||
|
"mode": "due"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "photo not jpeg",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "due",
|
||||||
|
"photo_jpeg_b64": "aGVsbG8="
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "photo not base64",
|
||||||
|
"valid": false,
|
||||||
|
"body": {
|
||||||
|
"client_slot_min": 480,
|
||||||
|
"mode": "due",
|
||||||
|
"photo_jpeg_b64": "@@@"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
Loading…
Reference in New Issue
Block a user