SAFE_ROUTES has 19 entries (backends.js), not 18. reference.md and
reference.zh-CN.md both said '18 entries'; both now say 19.
reference §4 said the /api/enabled and /api/admin/session calls are
'admin-session Bearer-auth'd'. The code says otherwise: config_authorized
(notify.rs:423) accepts the shared worker token OR a valid admin session,
and create_admin_session (notify.rs:1187) is gated by worker_authorized
against the admin credential CONFIG_ENCRYPTION_KEY — it is what mints the
session, so it cannot be session-auth'd. Both languages now state the two
distinct credentials and why adding /api/enabled opens no new credential
path.
deployment §10.8 said every request-bearing entry point, listing /healthz
and /api/*, calls refresh_business_config. The actual 10 call sites cover
8 distinct paths (/ready, /worker, /reconcile, /push/jmap, /webhook/tg,
/api/config, /api/business-config, /api/telegram/register-webhook). GET
/healthz is a static 200 "ok" and never refreshes; /api/status,
/api/enabled, /api/push/register, /api/push/disable and the
/api/admin/session pair do not either. Both languages now list the real
set and name the exclusions.
design.md §5.7 listed the search trigger prefixes as English
'search'/'find'/'retrieval'; worker.rs:689 accepts the Chinese prefixes
搜索/查找/检索 and the help text states English aliases are not supported.
The two user-facing strings were also mistranslated: the empty-query
guidance prompt is 请提供搜索关键词,例如:/search 发票 (worker.rs:623)
and the no-match reply is 没有找到匹配「<query>」的邮件。
(worker.rs:792). The degraded-rendering marker is likewise a Chinese
string. SEARCH_SUBJECT_MAX=120 / SEARCH_PREVIEW_MAX=160 /
SEARCH_LIMIT=10 verified unchanged.
design.md §5.6/§5.7 were machine-translated from Chinese back into
English and were broken: 'the first 300 if it fails. characters', a
stray closing ** mid-sentence, '(none) deny_unknown_fields)' with a
mismatched paren, and 5 zero-width-space artefacts. charter.md:168 had a
broken '**Tables, lists, or values may not be copied across documents. **'
and opengaps.md had 4. All ZWSPs removed from docs/.
deployment.zh-CN.md §10.5/§10.6 were thin mistranslations: 'Worker 域'
for 'Worker URL', the debug-token requirement dropped entirely, and a
mangled '两者都使用用于验证部署的可用和版本'. Rewritten against the EN.
Also replaced a worker.rs:227 line anchor with the MetadataWorker doc
comment; that drops the repo's line-refs from 72 to 71, so new text no
longer adds to the drift surface.
No code changes; GATE-DOCS 6/6 (71 anchors, 455 section refs, 727 path
refs).
There is currently no FSM. The command route is parsed into `Intent` by `parse_intent` in `src/worker.rs`; the AI authorization state is a Boolean expiration time in Redis (see the AI authorization state section of `docs/reference.md` for the key and TTL), not a multi-step confirmation state.
There is currently **no FSM**. `parse_intent` in `src/worker.rs` parses the command line into an `Intent`; the AI consent state is a single boolean plus an expiry in Redis (key and TTL in the AI consent section of `docs/reference.md`), not a multi-step confirmation state.
Invariants that still hold true: AI digests must first be explicitly authorized by the user, and LLM must not be called without authorization. Once the authorization takes effect, the digest will pull the full text of the email body and send it to LLM (`read_email` requests `TextBody` + `BodyValues` and`fetch_text_body_values(true)`, see `src/domain/jmap/client.rs`), but the body will not be sent back to Telegram** - only the summary will be sent outbound, or it will fall back to the first 300 if it fails. characters (`worker.rs:227` Note: body text never reaches Telegram).
The invariant that still holds: an AI summary requires the user's explicit consent first — **without a consent state the LLM is never called**. Once consent is live the summary pulls the full email body and sends it to the LLM (`read_email` requests `TextBody` + `BodyValues`via `fetch_text_body_values(true)`, see `src/domain/jmap/client.rs`), but the body is not sent back to Telegram — outbound sends only the summary, or falls back to the first 300 characters of the body if the LLM call fails (`fallback` in `src/worker.rs`). See also the doc comment on `MetadataWorker`: "body text never reaches Telegram".
The designed 5-state FSM (`Idle` / `AwaitClarify` / `AwaitConfirm` / `Analyzing` / `AwaitFallback`), together with the state transition table and channel neutrality description, can be found in `docs/retired.md`.
The 5-state FSM that was designed (`Idle` / `AwaitClarify` / `AwaitConfirm` / `Analyzing` / `AwaitFallback`), with its state-transition table and channel-neutrality notes, is in `docs/retired.md`.
`/search <keyword>` and the Chinese prefix `search`/`find`/`retrieval` (**only prefix matching**, to avoid "Help me search..." being hijacked into a search) triggers `Intent::Search`, through `JmapService::search_emails(account_id, query, limit)` and `email_query`(`Filter::text`) to get the ID + `SearchSnippet/get` Highlight `subject`/`preview`.
`/search <keyword>`, plus the Chinese prefixes `搜索` / `查找` / `检索` (**prefix match only**, so "help me search…" is not hijacked into a search), route to `Intent::Search`, which goes through `JmapService::search_emails(account_id, query, limit)` with `email_query` (`Filter::text`) for the IDs and `SearchSnippet/get` for highlighted `subject` / `preview`.
Key boundaries:
Key boundaries:
- **Highlight downgrade**: `SearchSnippet/get` does not support (`unknownMethod`) or returns empty snippets instead of an error when it times out; rendering is downgraded to a pure ID list (`highlighted snippets are temporarily unavailable, the following are matching email IDs`), and snippets are not created.
- **Snippet degradation**: `SearchSnippet/get` being unsupported (`unknownMethod`) or timing out with empty snippets instead of an error degrades rendering to a plain ID list (`(高亮片段暂不可用,以下为匹配的邮件 ID)`); no snippets are fabricated.
- **Plain text outbound**: `<mark>`highlighted tags are stripped by `strip_mark_tags` (case-insensitive, unclosed tags are discarded), and then decoded in a single pass by `unescape_html_entities`; tags are stripped first and then entities are decoded to prevent the literal `<mark>` (escaped by the server as `<mark>`) in the mailbox body from being restored to a real tag and accidentally deleted. `subject`/`preview` have 120/160 character truncation upper limit respectively (`truncate_chars`, the same tool as text truncation).
- **Plain text outbound**: `<mark>` tags are stripped by `strip_mark_tags` (case-insensitive, unclosed tags discarded) and then decoded in one pass by `unescape_html_entities`; tags are stripped **before** entities are decoded so that a literal `<mark>` in the mailbox body (escaped by the server as `<mark>`) is not restored to a real tag and then accidentally deleted. `subject` and `preview` are capped at 120 and 160 characters (`truncate_chars`, the same helper as text truncation).
- **Failed mapping**: JMAP side failed → `SearchReply::Retry` → `process_telegram` returns `Err(())` → coordinator 503 + `Retry-After` retry (consistent with `/reconcile`, other JMAP paths), **no panic, no error stack returned to user**.
- **Failed mapping**: JMAP side failed → `SearchReply::Retry` → `process_telegram` returns `Err(())` → coordinator 503 + `Retry-After` retry (consistent with `/reconcile`, other JMAP paths), **no panic, no error stack returned to user**.
- **Empty query**: `/search`(no keywords) → The guidance prompt "Please provide search keywords, for example: /search invoice", no request is sent. No match → `No messages matching "..." were found. `.
- **Empty query**: `/search`with no keywords emits a guidance prompt (`请提供搜索关键词,例如:/search 发票`) and makes no request. No matches returns `没有找到匹配「<query>」的邮件。`.
- **Each hit contains `email_id`**, you can directly access `/summary <email_id>` to enter the AI summary process.
- **Each hit carries `email_id`**, so `/summary <email_id>` jumps straight into the AI summary flow.
- **Body-level highlighting is not possible in locked versions**: jmap-client `0.4.2`’s `SearchSnippet` only models `emailId`/`subject`/`preview`, without `bodyProperties`/`parts`. According to RFC 8621 §5, the body-level `body: String[Id]` is not modeled by this crate and (none) `deny_unknown_fields`) are silently discarded by serde. The text highlighting of each part needs to bypass the crate and be sent directly to the original JMAP, which is not currently implemented.
- **Body-level highlighting is not possible in locked versions**: jmap-client `0.4.2`’s `SearchSnippet` only models `emailId`/`subject`/`preview`, without `bodyProperties`/`parts`. Per RFC 8621 §5 the body-level `body: String[Id]` is not modeled by the crate and, with no `deny_unknown_fields`, is silently dropped by serde. Per-part body highlighting would require bypassing the crate and calling JMAP directly, which is not implemented.
- **No new environment variable**; `/search` will give a friendly error when the configuration is missing.
- **No new environment variable**; when the configuration is missing, `/search` reports a friendly error.
---
---
@ -416,7 +416,7 @@ Testing: **No integrated test directory**, and no stand-alone util tool module.
- `/ready` does end-to-end probing: configuration integrity + Redis reachability + outbound read-only probing (`GET {jmap_origin}/.well-known/jmap`, Basic authentication with configuration; `GET https://api.telegram.org/bot<token>/getMe`; each `PROBE_TIMEOUT` = 3000ms, **Parallel** (`tokio::join!`), worst-case scenario 3s); all four pass `200` and readiness report (`{"status":"ready","configured":...,"jmap":...,"telegram":...}`, where `jmap`/`telegram` is the real probe result), any one fails `503` (standard error envelope `{"error":"service_unavailable","request_id":<id>}` + `Retry-After: 30`). The probe is read-only, read-only configuration status, and will not trigger business side effects such as email synchronization, nor will it echo token or third-party response content; `refresh_business_config` only reads Redis, and has no state to write. Therefore `/ready` requires the outbound egress to the JMAP host and `api.telegram.org:443` to be reachable (if the egress requires a proxy, `/ready` is not available, see deployment.md).
- `/ready` does end-to-end probing: configuration integrity + Redis reachability + outbound read-only probing (`GET {jmap_origin}/.well-known/jmap`, Basic authentication with configuration; `GET https://api.telegram.org/bot<token>/getMe`; each `PROBE_TIMEOUT` = 3000ms, **Parallel** (`tokio::join!`), worst-case scenario 3s); all four pass `200` and readiness report (`{"status":"ready","configured":...,"jmap":...,"telegram":...}`, where `jmap`/`telegram` is the real probe result), any one fails `503` (standard error envelope `{"error":"service_unavailable","request_id":<id>}` + `Retry-After: 30`). The probe is read-only, read-only configuration status, and will not trigger business side effects such as email synchronization, nor will it echo token or third-party response content; `refresh_business_config` only reads Redis, and has no state to write. Therefore `/ready` requires the outbound egress to the JMAP host and `api.telegram.org:443` to be reachable (if the egress requires a proxy, `/ready` is not available, see deployment.md).
- **chat whitelist (hard constraint `SAF-CHAT-ALLOWLIST`)**: `CHAT_ALLOWLIST` is a **required** configuration; any inbound event (action triggered by TG command/callback) must verify `chat.id ∈ CHAT_ALLOWLIST` before **making any JMAP call, AI call or status change**. If it is not in the whitelist, **directly reject and terminate** (prevent token can be called by anyone after being leaked). Phase 0 has completed the `CHAT_ALLOWLIST` parsing skeleton; the forced rejection logic has been implemented with Telegram channel access (`telegram_webhook` of `src/notify.rs` verifies the whitelist before any JMAP/AI/status operation, and terminates if rejected).
- **chat whitelist (hard constraint `SAF-CHAT-ALLOWLIST`)**: `CHAT_ALLOWLIST` is a **required** configuration; any inbound event (action triggered by TG command/callback) must verify `chat.id ∈ CHAT_ALLOWLIST` before **making any JMAP call, AI call or status change**. If it is not in the whitelist, **directly reject and terminate** (prevent token can be called by anyone after being leaked). Phase 0 has completed the `CHAT_ALLOWLIST` parsing skeleton; the forced rejection logic has been implemented with Telegram channel access (`telegram_webhook` of `src/notify.rs` verifies the whitelist before any JMAP/AI/status operation, and terminates if rejected).
- **Command Minimization**: Only necessary commands are exposed; writing operations such as sending emails must be confirmed twice (sending emails is not currently implemented, see §10.3).
- **Command Minimization**: Only necessary commands are exposed; writing operations such as sending emails must be confirmed twice (sending emails is not currently implemented, see §10.3).
- **Rate**: No local token bucket is built on the outbound side; Telegram's outbound sending is retried according to the Redis operating parameter `max_retries` (see `docs/reference.md` §6.1 for default values and hard upper limits); currently only Redis current limiting is done for Push verification code writing (`ratelimit:push-verify:*`). 429 under the 30 msg/s limit of the Telegram server **Automatic backoff in `parameters.retry_after` seconds** (`channel.rs`, `f4cae00`): `retry_after_ms` is truncated to the 60s budget limit after parsing, and the exponential backoff is used when this field is missing or non-numeric `backoff_delay_ms` (starting from 250ms, capped 4s), the overall retry budget is 60s. There is still no local token bucket current limit - if the budget is exceeded, a failure will be returned directly and the upstream will try again.
- **Rate**: No local token bucket is built on the outbound side; Telegram's outbound sending is retried according to the Redis operating parameter `max_retries` (see `docs/reference.md` §6.1 for default values and hard upper limits); currently only Redis current limiting is done for Push verification code writing (`ratelimit:push-verify:*`). 429 under the 30 msg/s limit of the Telegram server **Automatic backoff in `parameters.retry_after` seconds** (`channel.rs`, `f4cae00`): `retry_after_ms` is truncated to the 60s budget limit after parsing, and the exponential backoff is used when this field is missing or non-numeric `backoff_delay_ms` (starting from 250ms, capped 4s), the overall retry budget is 60s. There is still no local token bucket current limit - if the budget is exceeded, a failure will be returned directly and the upstream will try again.
### 7.3.1 Configuration Management API
### 7.3.1 Configuration Management API
- `GET /` provides a SPA embedded in the Rust binary; `/assets/config.js` and `/assets/styles.css` provide page resources. The service does not read or write local files while running (`C-NO-LOCAL-WRITE`).
- `GET /` provides a SPA embedded in the Rust binary; `/assets/config.js` and `/assets/styles.css` provide page resources. The service does not read or write local files while running (`C-NO-LOCAL-WRITE`).
@ -432,7 +432,7 @@ Testing: **No integrated test directory**, and no stand-alone util tool module.
"max_retries": 3
"max_retries": 3
}
}
```
```
- The three timeout units are all milliseconds; the default value, value range and hard upper limit of `max_retries` are only authoritative with `docs/reference.md` §6.1 (the table below and the example response body above are only for illustration, and the values are not repeated). `max_retries` represents the maximum number of retries beyond the first request. When there is no configuration in Redis, GET returns the default value object; PUT successfully returns the same object after saving and persists to Redis (`C-REDIS-ONLY-STATE`).
- The three timeout units are all milliseconds; the default value, value range and hard upper limit of `max_retries` are only authoritative with `docs/reference.md` §6.1 (the table below and the example response body above are only for illustration, and the values are not repeated). `max_retries` represents the maximum number of retries beyond the first request. When there is no configuration in Redis, GET returns the default value object; PUT successfully returns the same object after saving and persists to Redis (`C-REDIS-ONLY-STATE`).
- `GET /api/business-config` reads back saved configuration for management SPA pre-populated form: returns `{ "configured", "revision", "values", "secrets_present" }`, where `values` is the value of 10 non-key fields and `secrets_present` is 6 Boolean existence of a key (`bot_token`, `jmap_password`, `telegram_webhook_secret`, `reconcile_token`, `worker_token`, `llm_api_key`) - **Never return the key value itself** (`SAF-NO-SECRET-ECHO`). Not yet saved, staleness returns `200` + `configured: false`, `revision: 0`, empty `values` and an existence boolean of all false. SPA therefore has only one code path and does not need to distinguish between first-time configuration and modified configuration.
- `GET /api/business-config` reads back saved configuration for management SPA pre-populated form: returns `{ "configured", "revision", "values", "secrets_present" }`, where `values` is the value of 10 non-key fields and `secrets_present` is 6 Boolean existence of a key (`bot_token`, `jmap_password`, `telegram_webhook_secret`, `reconcile_token`, `worker_token`, `llm_api_key`) - **Never return the key value itself** (`SAF-NO-SECRET-ECHO`). Not yet saved, staleness returns `200` + `configured: false`, `revision: 0`, empty `values` and an existence boolean of all false. SPA therefore has only one code path and does not need to distinguish between first-time configuration and modified configuration.
- `PUT /api/business-config` accepts `BusinessConfigPatch` (complete or partial), **only replaces the fields that appear in the submission body, and the rest inherits the stored values** (`BusinessConfigPatch::apply`); Push verification does not belong to Wire, is dynamically generated by Stalwart and written back by the backend. Verification is the only write gate, and the verification object is the merged configuration rather than the commit itself: patches are never verified individually, and existing complete wires are never discarded. `validate_business_wire` runs first, and returns the real `422` when rejected; if the merge result is legal, the configuration **must** be persisted (the merged Wire is persisted, not the request body), and then the client is built and the worker is switched to run. Therefore, when the dependency is not connected, `200` + `{ "persisted": true, "runtime_applied": false, "warnings": [{"component", "step", "detail"}] }` is returned instead of `503` - the configuration has been saved and the fault is reported truthfully instead of being silently swallowed by an unreachable JMAP. `runtime_applied` is only `true` when the reload submission is successful; in both cases, the `x-business-config-revision` header is returned; the request body can carry `revision` (that is, the `u64` returned by `GET`) as a control field - it does not participate in `apply`, does not enter Wire, and is not used as a saved setting. It is only used to determine whether this submission is based on the latest version. See the next article for the semantics of `409`. The response never echoes configuration or keys. The key is "replaced only after submission": the **omitted** key inherits the existing value, so the form backfilled by `GET` only needs to submit the fields to be changed; but the backend does not distinguish between "unsubmitted" and "submitted empty string", and explicitly submitting `""` will actually clear the key - "leave blank and keep" is a client contract implemented by SPA by discarding blank key fields before submission, not a server-side guarantee. `chat_allowlist` must be a non-empty list, empty arrays will be rejected by `validate_business_wire` (422). Incremental semantics only hold after **existing configuration**: if there is no existing configuration, there is no fallback value, and the patch must come with all required fields, otherwise `422` will be returned (the entry created from scratch is `POST /api/bootstrap`).
- `PUT /api/business-config` accepts `BusinessConfigPatch` (complete or partial), **only replaces the fields that appear in the submission body, and the rest inherits the stored values** (`BusinessConfigPatch::apply`); Push verification does not belong to Wire, is dynamically generated by Stalwart and written back by the backend. Verification is the only write gate, and the verification object is the merged configuration rather than the commit itself: patches are never verified individually, and existing complete wires are never discarded. `validate_business_wire` runs first, and returns the real `422` when rejected; if the merge result is legal, the configuration **must** be persisted (the merged Wire is persisted, not the request body), and then the client is built and the worker is switched to run. Therefore, when the dependency is not connected, `200` + `{ "persisted": true, "runtime_applied": false, "warnings": [{"component", "step", "detail"}] }` is returned instead of `503` - the configuration has been saved and the fault is reported truthfully instead of being silently swallowed by an unreachable JMAP. `runtime_applied` is only `true` when the reload submission is successful; in both cases, the `x-business-config-revision` header is returned; the request body can carry `revision` (that is, the `u64` returned by `GET`) as a control field - it does not participate in `apply`, does not enter Wire, and is not used as a saved setting. It is only used to determine whether this submission is based on the latest version. See the next article for the semantics of `409`. The response never echoes configuration or keys. The key is "replaced only after submission": the **omitted** key inherits the existing value, so the form backfilled by `GET` only needs to submit the fields to be changed; but the backend does not distinguish between "unsubmitted" and "submitted empty string", and explicitly submitting `""` will actually clear the key - "leave blank and keep" is a client contract implemented by SPA by discarding blank key fields before submission, not a server-side guarantee. `chat_allowlist` must be a non-empty list, empty arrays will be rejected by `validate_business_wire` (422). Incremental semantics only hold after **existing configuration**: if there is no existing configuration, there is no fallback value, and the patch must come with all required fields, otherwise `422` will be returned (the entry created from scratch is `POST /api/bootstrap`).
- `POST /api/business-config/preflight` performs exactly the same validation and client build on the submission body, returning component-by-component conclusions, **without writing, without touching the running worker**: `{ "persisted": false, "validation": { "ok", "errors" }, "components": { "jmap": {...}, "llm": ... } }`. Different from PUT, its submission body must be **complete**`BusinessConfigWire` (no patch merging), so SPA must first merge the value read back by `GET` into the local form before pre-verification. `components` is `null` when the verification has failed (rejected Wire does not need to probe the client again); when `llm_enabled`/`llm_allow_net` is false, `llm` is `null` instead of false `ok`. Authentication is consistent with the management session gate (`config_authorized`) and is deliberately not hung after `DEBUG_TOKEN`.
- `POST /api/business-config/preflight` performs exactly the same validation and client build on the submission body, returning component-by-component conclusions, **without writing, without touching the running worker**: `{ "persisted": false, "validation": { "ok", "errors" }, "components": { "jmap": {...}, "llm": ... } }`. Different from PUT, its submission body must be **complete**`BusinessConfigWire` (no patch merging), so SPA must first merge the value read back by `GET` into the local form before pre-verification. `components` is `null` when the verification has failed (rejected Wire does not need to probe the client again); when `llm_enabled`/`llm_allow_net` is false, `llm` is `null` instead of false `ok`. Authentication is consistent with the management session gate (`config_authorized`) and is deliberately not hung after `DEBUG_TOKEN`.
@ -556,7 +556,7 @@ The design target form once included six additional variants: `Jmap(#[from] jmap
- **Actual dependencies** (Cargo.toml current, `ARCH-DEPS-STAGE0`/`ARCH-DEPS-STAGE1` + `ARCH-DEPS-STAGE4`): `axum 0.8` (single HTTPS entrance), `async-trait`, `secrecy`, `subtle` (constant time authentication comparison), `serde`, `serde_json`, `thiserror`, `tokio`, `tracing`, `tracing-subscriber`, `url` (`JMAP_SESSION_URL` normalized parsing), `jmap-client =0.4.2` (`default-features = false, features = ["async","rustls"]`), `redis 0.27` (Redis XPING/PING liveness detection, `ARCH-STATE-REDIS`), `reqwest 0.13` (JMAP/TG HTTP client); dev-dependencies: `tower 0.5` (routing test). `teloxide` is not introduced (`ARCH-DEPS-STAGE4`): Telegram channel is implemented in `src/channel.rs` using reqwest self-development.
- **Actual dependencies** (Cargo.toml current, `ARCH-DEPS-STAGE0`/`ARCH-DEPS-STAGE1` + `ARCH-DEPS-STAGE4`): `axum 0.8` (single HTTPS entrance), `async-trait`, `secrecy`, `subtle` (constant time authentication comparison), `serde`, `serde_json`, `thiserror`, `tokio`, `tracing`, `tracing-subscriber`, `url` (`JMAP_SESSION_URL` normalized parsing), `jmap-client =0.4.2` (`default-features = false, features = ["async","rustls"]`), `redis 0.27` (Redis XPING/PING liveness detection, `ARCH-STATE-REDIS`), `reqwest 0.13` (JMAP/TG HTTP client); dev-dependencies: `tower 0.5` (routing test). `teloxide` is not introduced (`ARCH-DEPS-STAGE4`): Telegram channel is implemented in `src/channel.rs` using reqwest self-development.
- **Not yet introduced** (Documents must not claim to have been used): `teloxide` and other Telegram Bot frameworks (Telegram outbound is sent directly by `src/channel.rs` and `reqwest`, and the evaluation record is in `docs/retired.md`). **FIGMENT NOT USED**: Configured for manual `std::env` parsing (`ARCH-CONFIG-ENV`, §7.1).
- **Not yet introduced** (Documents must not claim to have been used): `teloxide` and other Telegram Bot frameworks (Telegram outbound is sent directly by `src/channel.rs` and `reqwest`, and the evaluation record is in `docs/retired.md`). **FIGMENT NOT USED**: Configured for manual `std::env` parsing (`ARCH-CONFIG-ENV`, §7.1).
- **Stage 1 dependency status** (`ARCH-DEPS-STAGE1`): `jmap-client`**Introduced** (currently `=0.4.2`, `default-features = false, features = ["async","rustls"]`, version and features **subject to `Cargo.toml`**). ⚠️ Its default features `["async","websockets","aws_lc_rs"]`**includes WebSocket stack**, so the default features must be turned off and `websockets` is not selected; JMAP only uses **HTTPS short requests** (Core/Mail) to comply with `C-NO-LONG-CONN` (no WS/SSE/long polling).
- **Stage 1 dependency status** (`ARCH-DEPS-STAGE1`): `jmap-client`**Introduced** (currently `=0.4.2`, `default-features = false, features = ["async","rustls"]`, version and features **subject to `Cargo.toml`**). ⚠️ Its default features `["async","websockets","aws_lc_rs"]`**includes WebSocket stack**, so the default features must be turned off and `websockets` is not selected; JMAP only uses **HTTPS short requests** (Core/Mail) to comply with `C-NO-LONG-CONN` (no WS/SSE/long polling).
- `ACCOUNT_ID`**optional** (`REQ-SINGLE-ACCOUNT`): **leave blank → take the default/main account** of the JMAP session; explicit values are used after verification; multiple accounts = multiple bot instances.
- `ACCOUNT_ID`**optional** (`REQ-SINGLE-ACCOUNT`): **leave blank → take the default/main account** of the JMAP session; explicit values are used after verification; multiple accounts = multiple bot instances.
- axum adopts **0.8** (`ARCH-AXUM-08`); if subsequent review decides to adjust the version, Cargo.toml will prevail and this section will be synchronized.
- axum adopts **0.8** (`ARCH-AXUM-08`); if subsequent review decides to adjust the version, Cargo.toml will prevail and this section will be synchronized.
- Currently SSE/WebSocket/long polling/SQLite/local volumes (`C-NO-LONG-CONN`/`NG-SQLITE-PERSIST`/`NG-LOCAL-VOLUME`) are not implemented; entrance authentication (`R1`/`SAF-AUTH-*`) is implemented as a fail-closed hard access control, and the Push, Streams worker and `/reconcile` business paths after authentication have been implemented.
- Currently SSE/WebSocket/long polling/SQLite/local volumes (`C-NO-LONG-CONN`/`NG-SQLITE-PERSIST`/`NG-LOCAL-VOLUME`) are not implemented; entrance authentication (`R1`/`SAF-AUTH-*`) is implemented as a fail-closed hard access control, and the Push, Streams worker and `/reconcile` business paths after authentication have been implemented.
@ -38,7 +38,7 @@ Original entry: Full code base **12 TTL write points, 17 TTL values**, but only
Three steps closed the issue:
Three steps closed the issue:
1. **True Redis Assertion** (commit `0890eb1`). `real_redis_ttl_tests` of `src/state.rs`, two `#[ignore]`-gated use cases, follow the pattern of `src/domain/jmap/client.rs:522`: skipped and returned when `REDIS_TEST_URL` is missing, the URL will not be logged. Assert actual PTTL for three atomic write points. Run: `REDIS_TEST_URL=… cargo test --locked -- --ignored ttl`.
1. **True Redis Assertion** (commit `0890eb1`). `real_redis_ttl_tests` of `src/state.rs`, two `#[ignore]`-gated use cases, follow the pattern of `src/domain/jmap/client.rs:522`: skipped and returned when `REDIS_TEST_URL` is missing, the URL will not be logged. Assert actual PTTL for three atomic write points. Run: `REDIS_TEST_URL=… cargo test --locked -- --ignored ttl`.
2. **Kill naked literals** (one round after commit `0890eb1`). All 17 values are included in `pub(crate) mod ttl` of `src/state.rs`, the call point changes the constant reference, and a new `ttl_contract_is_pinned` is added to assert the constant table one by one, with two sequential assertions (the heartbeat must be shorter than the lock, and the consent gear must be strictly increasing). Class B Lua embedded values that were out of reach in the original entry have also been connected - `retry_or_dlq` now uses `ttl::RETRY_COUNTER_SECONDS` interpolation to generate script strings, and there is no longer a second literal in the script. Changing the value now = changing the constant + assertion failure, both of which must be reviewed.
2. **Kill naked literals** (one round after commit `0890eb1`). All 17 values are included in `pub(crate) mod ttl` of `src/state.rs`, the call point changes the constant reference, and a new `ttl_contract_is_pinned` is added to assert the constant table one by one, with two sequential assertions (the heartbeat must be shorter than the lock, and the consent gear must be strictly increasing). Class B Lua embedded values that were out of reach in the original entry have also been connected - `retry_or_dlq` now uses `ttl::RETRY_COUNTER_SECONDS` interpolation to generate script strings, and there is no longer a second literal in the script. Changing the value now = changing the constant + assertion failure, both of which must be reviewed.
3. **Real machine green light** (this round, run with Upstash instance). The two assertions were actually connected to the real Redis to read back the PTTL and passed. The Class B Lua embedded value was verified on a real machine for the first time. The process is shown below in "Testing the four TTL test fixes".
3. **Real machine green light** (this round, run with Upstash instance). The two assertions were actually connected to the real Redis to read back the PTTL and passed. The Class B Lua embedded value was verified on a real machine for the first time. The process is shown below in "Testing the four TTL test fixes".
Contract baseline (see `docs/reference.md` §1 for the complete semantics of keys):
Contract baseline (see `docs/reference.md` §1 for the complete semantics of keys):
@ -67,7 +67,7 @@ Contract baseline (see `docs/reference.md` §1 for the complete semantics of key
Naked TTL literals no longer exist in production code; `worker.rs`'s agreed-upon test assertions still retain numeric literals, which is **deliberate** - use expected values independent of constants to test production code, otherwise if both sides are changed at the same time, the single test will always be green.
Naked TTL literals no longer exist in production code; `worker.rs`'s agreed-upon test assertions still retain numeric literals, which is **deliberate** - use expected values independent of constants to test production code, otherwise if both sides are changed at the same time, the single test will always be green.
This update fixed four bugs in the test itself.
This update fixed four bugs in the test itself.
@ -79,7 +79,7 @@ The fourth is that the real machine asserts that it is unstable. The first three
- The zero value case originally asserted `assert_within(pttl, 1, 500)` - requiring the 1 second floor to be read back within ±500 ms. But the readback occurs after the cross-network TLS round trip, and that second is usually consumed. Running three times in a row got `-2` (key has expired), `269`, `118` ms. There is nothing wrong with the product code itself: `SET … NX EX 1` is indeed implemented, and `-2` just proves that EX takes effect and the keys expire as expected. Change the criterion to "`pttl != -1`" - `-1` is the real regression to prevent (EX is silently discarded, the key never expires), plus "`pttl == -2 || pttl <= 1000 + 2000`" is a judgment that only sets an upper bound, because a value that is still alive will only count down from 1s. After the change, I ran 6 consecutive rounds with all green.
- The zero value case originally asserted `assert_within(pttl, 1, 500)` - requiring the 1 second floor to be read back within ±500 ms. But the readback occurs after the cross-network TLS round trip, and that second is usually consumed. Running three times in a row got `-2` (key has expired), `269`, `118` ms. There is nothing wrong with the product code itself: `SET … NX EX 1` is indeed implemented, and `-2` just proves that EX takes effect and the keys expire as expected. Change the criterion to "`pttl != -1`" - `-1` is the real regression to prevent (EX is silently discarded, the key never expires), plus "`pttl == -2 || pttl <= 1000 + 2000`" is a judgment that only sets an upper bound, because a value that is still alive will only count down from 1s. After the change, I ran 6 consecutive rounds with all green.
**Two TTL assertions have been run on the real Upstash instance (`rediss://`, TLS-only; plaintext `redis://` will receive a null reply after `AUTH` and disconnect, so TLS must be used)**: `SET … NX EX` (`claim_dedup`), `SET … EX 3600` (`set_ai_consent`), Lua embedded `EXPIRE 86400` (`retry_or_dlq`) The actual PTTL of the three atomic write points all fall within the 2s tolerance. Class B Lua embedded values that were out of reach in the original article are now also verified on real machines, not just constant references.
**Two TTL assertions have been run on the real Upstash instance (`rediss://`, TLS-only; plaintext `redis://` will receive a null reply after `AUTH` and disconnect, so TLS must be used)**: `SET … NX EX` (`claim_dedup`), `SET … EX 3600` (`set_ai_consent`), Lua embedded `EXPIRE 86400` (`retry_or_dlq`) The actual PTTL of the three atomic write points all fall within the 2s tolerance. Class B Lua embedded values that were out of reach in the original article are now also verified on real machines, not just constant references.
### 2. `newState` semantics of `Email/changes` (commit `269c8f6`)
### 2. `newState` semantics of `Email/changes` (commit `269c8f6`)