فهرست منبع

feat(italy): integrate query-book workflow with automatic OTP and final verification

zhangweijp 2 ماه پیش
والد
کامیت
62c2388999
75فایلهای تغییر یافته به همراه41362 افزوده شده و 421 حذف شده
  1. 5 1
      .gitignore
  2. 17 1
      booker.py
  3. 10 2
      config/config_booker.json
  4. 72 1
      config/config_sentinel.json
  5. 5 0
      config/ita_query_account.example.json
  6. 29 5
      config/test_conf.json
  7. 301 0
      docs/HANDOVER.md
  8. 145 0
      docs/ita_book_cs4a.md
  9. 192 0
      docs/ita_book_cs4b.md
  10. 1128 0
      docs/ita_book_cs4c.md
  11. 1969 0
      docs/ita_book_cs5.md
  12. 539 0
      docs/ita_otp_auto.md
  13. 3115 0
      docs/ita_plugin_discovery.md
  14. 2194 0
      docs/ita_plugin_generic_schengen_design.md
  15. 1078 0
      docs/ita_plugin_recovery_design.md
  16. 576 0
      docs/ita_query_book_acceptance.md
  17. 392 0
      docs/ita_query_recovery.md
  18. 294 0
      docs/vfs_plugin_deep_dive.md
  19. 457 0
      plugins/ita_booking_final.py
  20. 761 0
      plugins/ita_calendar_book.py
  21. 607 0
      plugins/ita_calendar_query.py
  22. 603 0
      plugins/ita_calendar_session.py
  23. 252 0
      plugins/ita_final_read_port.py
  24. 140 0
      plugins/ita_otp.py
  25. 1394 410
      plugins/ita_plugin.py
  26. 1168 0
      plugins/ita_protocol.py
  27. 464 0
      plugins/ita_reservation.py
  28. 66 0
      plugins/ita_turnstile.py
  29. 236 0
      plugins/ita_workflow.py
  30. 310 0
      test/test_add_ita_query_account.py
  31. 603 0
      test/test_debug_ita_book.py
  32. 1371 0
      test/test_debug_ita_book_gate.py
  33. 1377 0
      test/test_debug_ita_calendar_gate.py
  34. 362 0
      test/test_debug_ita_monitor.py
  35. 551 0
      test/test_debug_ita_production_query_gate.py
  36. 524 0
      test/test_debug_ita_query.py
  37. 1006 0
      test/test_debug_ita_query_book.py
  38. 483 0
      test/test_debug_ita_reservation.py
  39. 195 0
      test/test_debug_ita_session.py
  40. 558 0
      test/test_debug_ita_soak.py
  41. 197 0
      test/test_ita_booker_integration.py
  42. 615 0
      test/test_ita_booking_final.py
  43. 559 0
      test/test_ita_calendar_book.py
  44. 821 0
      test/test_ita_calendar_book_flow.py
  45. 221 0
      test/test_ita_calendar_query.py
  46. 393 0
      test/test_ita_calendar_soak.py
  47. 219 0
      test/test_ita_final_attribution.py
  48. 233 0
      test/test_ita_final_evidence.py
  49. 310 0
      test/test_ita_final_read_port.py
  50. 363 0
      test/test_ita_local_handoff.py
  51. 177 0
      test/test_ita_otp.py
  52. 1455 0
      test/test_ita_plugin.py
  53. 179 0
      test/test_ita_preflight.py
  54. 648 0
      test/test_ita_protocol.py
  55. 363 0
      test/test_ita_query_recovery.py
  56. 609 0
      test/test_ita_reservation.py
  57. 252 0
      test/test_ita_route_wiring.py
  58. 929 0
      test/test_ita_workflow.py
  59. 255 0
      test/test_plugin_tester_ita_config.py
  60. 280 0
      tools/add_ita_query_account.py
  61. 471 0
      tools/debug_ita_book.py
  62. 782 0
      tools/debug_ita_book_gate.py
  63. 1374 0
      tools/debug_ita_calendar_gate.py
  64. 300 0
      tools/debug_ita_monitor.py
  65. 513 0
      tools/debug_ita_query.py
  66. 77 0
      tools/debug_ita_query_book.py
  67. 320 0
      tools/debug_ita_reservation.py
  68. 432 0
      tools/debug_ita_session.py
  69. 1170 0
      tools/debug_ita_soak.py
  70. 180 0
      tools/ita_final_evidence.py
  71. 289 0
      tools/ita_local_handoff.py
  72. 635 0
      tools/ita_query_book_local.py
  73. 66 0
      utils/ita_local_profile.py
  74. 123 0
      utils/local_account.py
  75. 3 1
      vs_types.py

+ 5 - 1
.gitignore

@@ -31,6 +31,7 @@ env/
 !.env.example
 *.local
 secrets.json
+config/ita_query_account.local.json
 
 # —— Node(若子项目使用) ——
 node_modules/
@@ -63,6 +64,9 @@ logs/
 debug_pages/
 temp_browser_data/
 data/temp_browser_data/
+data/ita_query_profiles/
+data/ita_local_handoff/
+data/ita_soak/
 data/reg_session_*/
 data/proxy_states.json
 
@@ -78,4 +82,4 @@ data/**/*.png
 *.tmp
 *.temp
 
-downloads
+downloads

+ 17 - 1
booker.py

@@ -6,7 +6,7 @@ import random
 from datetime import datetime
 from typing import List, Dict, Callable, Optional
 
-from vs_types import GroupConfig, VSPlgConfig, Task, VSQueryResult, AppointmentType, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str
+from vs_types import GroupConfig, VSPlgConfig, Task, VSQueryResult, AppointmentType, AvailabilityStatus, GroupStatus, PluginStatus, utc_now_str, BookingOutcomeUnknownError
 from vs_plg_factory import VSPlgFactory
 from toolkit.thread_pool import ThreadPool
 from toolkit.vs_cloud_api import VSCloudApi
@@ -493,6 +493,8 @@ class OrderBookerGCO(BaseBookerGCO):
         task_data = None
 
         try:
+            if not task.book_allowed:
+                return
             with self.m_lock:
                 task_data = self.m_task_data_cache.get(str(task_id))
             if not task_data or task_data.get('status') in ['grabbed', 'pause', 'completed', 'cancelled']:
@@ -512,6 +514,20 @@ class OrderBookerGCO(BaseBookerGCO):
             else:
                 self._log(f"❌ BOOK FAILED for Order: {order_id}. Will retry on next signal.")
 
+        except BookingOutcomeUnknownError:
+            # Reuse the existing pause status/API. Never convert an uncertain
+            # website write into the ordinary "retry on next signal" branch.
+            with self.m_lock:
+                task.book_allowed = False
+                if str(task_id) in self.m_task_data_cache:
+                    self.m_task_data_cache[str(task_id)]["status"] = "pause"
+            try:
+                VSCloudApi.Instance().update_vas_task(str(task_id), {"status": "pause"})
+                self.redis_client.zrem(self.m_tracker_key, task_id)
+                self._remove_task(task, "booking outcome requires receipt review")
+                self._log(f"Task={task_id} paused: check its reservation before resuming.")
+            except Exception:
+                self._log(f"Task={task_id} blocked locally; cloud pause failed. Pause it manually before restarting.")
         except Exception as e:
             err_str = str(e)
             self._log(f"Exception during booking: {err_str}")

+ 10 - 2
config/config_booker.json

@@ -1631,7 +1631,7 @@
       "account_cd": 10800,
       "keep_alive": 120,
       "account_source": "order",
-      "booking_cooldown": 10,
+      "booking_cooldown": 45,
       "target_instances": 1,
       "max_bookings_per_account": 1
     },
@@ -1651,6 +1651,14 @@
       }
     ],
     "free_config": {
+      "query_mode": "services_probe",
+      "final_submit_enabled": false,
+      "apt_configs": {
+        "slot.dub.it.tourist": {
+          "service_id": 1321,
+          "capability": "services_probe_only"
+        }
+      },
       "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
     },
     "version": 2,
@@ -1658,4 +1666,4 @@
     "created_at": "2026-08-23T15:08:14",
     "updated_at": "2026-08-23T16:09:43"
   }
-]
+]

+ 72 - 1
config/config_sentinel.json

@@ -1,4 +1,67 @@
 [
+  {
+    "identifier": "ita.hong_kong",
+    "enable": false,
+    "debug": false,
+    "need_account": true,
+    "need_proxy": true,
+    "proxy_pool": ["proxy-cheap"],
+    "proxy_cd": 300,
+    "session_max_life": 1800,
+    "active_time_start": "00:00",
+    "active_time_end": "23:59",
+    "website": "https://prenotami.esteri.it/",
+    "sentinel": {
+      "account_source": "built-in",
+      "account_pool_id": "hkg.it.sentinel",
+      "account_cd": 1800,
+      "target_instances": 1,
+      "signal_ttl": 30,
+      "query_wait": {
+        "mode": "Random",
+        "fixed_wait": 60,
+        "random_min": 60,
+        "random_max": 300
+      }
+    },
+    "plugin_config": {
+      "lib_path": "plugins",
+      "plugin_bin": "ita_plugin.py",
+      "plugin_name": "ita_plugin",
+      "plugin_proto": "IVSPlg"
+    },
+    "appointment_types": [
+      {
+        "city": "Hong Kong",
+        "country": "Italy",
+        "visa_type": "Tourist",
+        "routing_key": "slot.hkg.it.tourist",
+        "weight": 10
+      }
+    ],
+    "free_config": {
+      "website": "https://prenotami.esteri.it/",
+      "query_mode": "calendar",
+      "otp_mode": "cloud",
+      "final_submit_enabled": false,
+      "apt_configs": {
+        "slot.hkg.it.tourist": {
+          "service_id": 4937,
+          "capability": "single_schengen_tourism",
+          "calendar_scan": {"lookahead_months": 12},
+          "form": {
+            "booking_type_control_id": "typeofbookingddl",
+            "booking_type_value": "1",
+            "booking_type_labels": ["Prenotazione Singola", "Single booking"],
+            "purpose_control_id": "ddls_0",
+            "purpose_value": "42",
+            "purpose_labels": ["Turismo", "Tourism"]
+          },
+          "mail": {"authorization_source": "account"}
+        }
+      }
+    }
+  },
   {
     "id": 27,
     "node_id": "yecaoyun",
@@ -1721,6 +1784,14 @@
       }
     ],
     "free_config": {
+      "query_mode": "services_probe",
+      "final_submit_enabled": false,
+      "apt_configs": {
+        "slot.dub.it.tourist": {
+          "service_id": 1321,
+          "capability": "services_probe_only"
+        }
+      },
       "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
     },
     "version": 2,
@@ -1728,4 +1799,4 @@
     "created_at": "2026-08-23T15:08:25",
     "updated_at": "2026-08-23T16:13:12"
   }
-]
+]

+ 5 - 0
config/ita_query_account.example.json

@@ -0,0 +1,5 @@
+{
+  "username": "",
+  "password": "",
+  "account_upload_token": ""
+}

+ 29 - 5
config/test_conf.json

@@ -281,22 +281,46 @@
       }
     },
     "ita_plugin": {
-      "group_id": "ita.dublin",
+      "group_id": "ita.hong_kong",
+      "debug": false,
       "account": {
         "username": "ita_user@example.com",
         "password": "ItaPassword123!"
       },
       "appointment_types": [
         {
-          "city": "Dublin",
+          "city": "Hong Kong",
           "country": "Italy",
           "visa_type": "Tourist",
-          "routing_key": "slot.dub.it.tourist",
+          "routing_key": "slot.hkg.it.tourist",
           "weight": 10
         }
       ],
       "free_config": {
-        "website": "https://prenotami.esteri.it/Home",
+        "website": "https://prenotami.esteri.it/",
+                "query_mode": "calendar",
+                "otp_mode": "cloud",
+        "final_submit_enabled": false,
+        "apt_configs": {
+                    "slot.hkg.it.tourist": {
+                        "service_id": 4937,
+                        "mail": {
+                            "authorization_source": "account"
+                        },
+            "capability": "single_schengen_tourism",
+            "calendar_scan": {
+              "lookahead_months": 12
+            },
+            "form": {
+              "booking_type_control_id": "typeofbookingddl",
+              "booking_type_value": "1",
+              "booking_type_labels": ["Prenotazione Singola", "Single booking"],
+              "purpose_control_id": "ddls_0",
+              "purpose_value": "42",
+              "purpose_labels": ["Turismo", "Tourism"]
+            }
+          }
+        },
         "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
       },
       "user_inputs": {
@@ -365,4 +389,4 @@
       }
     }
   }
-}
+}

+ 301 - 0
docs/HANDOVER.md

@@ -0,0 +1,301 @@
+# Coordinate 项目接手报告(Handover Report)
+
+> 生成时间:2026-08-25(本地时钟)
+> 作者视角:框架架构师 / 项目负责人(接手即用)
+> 本文所有论断均标注【已验证】或【未验证】,验证命令与结果见 §9。
+
+> 2026-08-30 Italy Query 更新:本地实现及 387 项 Italy 回归【已验证】;15 分钟受控重建 E51【已验证】:909 秒、3 次查询、1 次恢复、监测 OTP/AVANTI/final 均 0、exit 0,源码指纹一致。真实认证过期及 2/24 小时现场运行【未验证】。最新合同、完整终端命令、验收记录与必须完成的 ITA-OTP-01 见 [CS3R](./ita_query_recovery.md)。本条不更新下面 2026-08-25 的历史环境结论,也不代表 Book/生产上线完成。
+
+---
+
+> 2026-08-31 Italy Book 更新:用户回传 v8 实测最终请求 1 次,新增确认回执 Confermata / 2,日期 2026-09-03,分配时间 09:26,历史未变、请求审计通过。网站已显示确认;程序尚未识别新状态/完整归属,仍 unknown / exit 4,勿重跑提交或清除 claim。详见 [CS5 §27](./ita_book_cs5.md)。598 项为第 26 节先前本地离线证据;真实回传未包含 Book 源码指纹。下一步用已有回执只读完善成功判定,生产 final 仍关闭,跨进程阻断与自动 OTP 仍待完成。
+
+> 后续本地更新:已接入 Confermata / 2 → ACTIVE,并在原回执工具增加 --expect-confirmed;611 项 Italy 离线测试与 receipt-readonly-confirmed-v4 无网络预检通过。下一步执行 [CS5 §28](./ita_book_cs5.md) 的只读命令,不重跑预约。成功时表示已存在匹配的确认预约,不等同于已完成历史提交归属或生产 Book 成功接线。
+
+> 最新真实验收:receipt-readonly-confirmed-v4 / a4840ececb10 已由用户终端验证通过,existingReservationConfirmed=true,列表 2→2、五项业务请求 0、清理成功、EXIT_CODE=0。见 [CS5 §29](./ita_book_cs5.md)。下一步是最终结果与本次尝试归属接线,不重复提交或取消现有预约;生产 final 仍未开放。
+
+> 最新本地接线:book-final-attribution-v9 / 1949de666430 已完成最终核心→本地验收入口的成功回传,626 项 Italy 离线回归及无网络预检通过。只有已匹配的单次原生请求、唯一新增确认回执、服务/日期/分配时刻一致且历史未变,才返回 VSBookResult.success=True;网站分配时刻不替换为选择区间。详见 [CS5 §30](./ita_book_cs5.md)。本轮未操作真实网站或 claim,不能倒推旧 v8 的请求归属;生产 final 仍关闭。下一步复用既有 Booker/订单状态建设成功回传、持久未知结果暂停与恢复,自动 OTP 仍为待办。
+
+> 上线审查补充:已只读定位 webapp 任务后端,并离线复现 return_to_queue 将 pause/grabbed 覆盖为 pending;OrderBooker 对 FinalOutcomeUnknown 在两次信号中调用 Book 两次;成功上报入线程队列后 tracker 先被移除。详见 [CS5 §31](./ita_book_cs5.md)。修复需确认 webapp 共享任务接口与 Coordinate 调度层的改动范围,不能只补插件局部暂停便宣称可上线。本轮仅归档,未修改业务代码/后端或运行线上操作。
+
+> 2026-08-31 最新范围调整(优先于上面的跨仓库提案):负责人明确要求按现有 VFS/BLS 链路推进,不新增平台复杂度。本轮已接 `ItaPlugin.query/book` 的显式人工 OTP 工作模式,提取调试与生产共用的 Calendar 准备代码,复用最终提交/回执核心,标准 `VSBookResult` 继续走现有 OrderBooker 成功上报。未知结果只复用现有 `pause` API,不修改 webapp、Redis 结构或 Sweeper。原 626 项 + 新增 24 项离线测试通过;不是上线/真实新入口验收。旧配置默认仍停止在原边界,真实提交未启用;自动 OTP 仍为 ITA-OTP-01。配置、验证命令与剩余边界见 [CS5 §32](./ita_book_cs5.md)。
+
+> 最新用户终端验收:新 Query `--production-workflow` 单次正向通过,probe 0 无号、probe 1 正向,earliestDate=2026-09-03,finalSubmissionEnabled=false,清理成功、EXIT_CODE=0。见 [CS5 §33](./ita_book_cs5.md)。这是本次观察,不保证库存持续;末段日志未含源码指纹/完整请求计数。下一步验新 Book 公共入口至选位,最终提交仍关闭,OTP 自动化最后补。
+
+> 后续验证入口已准备:原 `debug_ita_book.py --production-workflow` 现在调用一次公共 Book,走申请人独立登录/人工 OTP/选位并读回核对,最终提交固定关闭;成功验收看 selectionVerified=true、末尾 finalRequests=0、清理成功和 exit 0,bookResultSuccess=false 为预期。新增 9 项测试,659 项 Italy 离线回归通过。完整命令见 [CS5 §34](./ita_book_cs5.md),本轮未做真实 Book 或部署。
+
+> 最新 Book 阻点已定位:§34 新入口在 Services 就停止,五类业务请求均 0。用户截图确认目标服务行显示“该服务已经预约过”,因此没有 /Services/Booking/4937 链接;不是机构/服务号错误或无号。已在原诊断中补充页面级已预约提示计数及核对说明,不将无 ID 绑定的行认定为目标,不把旧预约算作本次成功,不改调度/取消预约。665 项 Italy 离线回归通过;新入口选位实测需换为已授权且该服务尚无预约的申请人账号,最终提交继续关闭。详见 [CS5 §35](./ita_book_cs5.md)。
+
+> 最新验收(优先于上条待办):用户告知自行取消已有预约,随后新 Book `--production-workflow` 正向通过。选中 2026-09-03 / 09:15–10:00,remaining=2,selectionVerified=true;OTP 1、AVANTI 1、availability 3、timeSlots 2、final 0,清理成功、exit 0。bookResultSuccess=false 为预期停在最终提交前。新公共 Query 和 Book 选位均已有真实正向证据,不再重复该验收;下一步是复用原 OrderBooker 的最终结果/成功上报端到端验收及部署整包检查,OTP 自动化最后补。见 [CS5 §36](./ita_book_cs5.md)。本次只归档用户证据,未新增预约或部署。
+
+> 最新本地上线收尾:新增 `test_ita_booker_integration` 8 项,实际运行公共 Book/NativeFinalSubmitter/回执解析/原异步上报回调,外部边界全替身;673 项 Italy 回归通过。已补齐 requirements 既有 redis 依赖(本地 8.1.0),无替身 Booker 导入及 pip check 通过。生产无算法改动、无新队列、无真实预约/云写入/部署。当前 Italy 生产配置仍关闭且为旧探测路由;必须整包发布并处理人工 OTP 的交互终端,不能只热更 ita_plugin.py。下一项需要明确云端 task id,验收新公共 Book → 原 Booker → 实际订单更新。见 [CS5 §37](./ita_book_cs5.md)。
+
+## 0. 一句话定位
+
+**Coordinate 是一个面向"签证预约抢号"业务的分布式节点编排框架**:`Sentinel`(哨兵,扫档期)→ Redis 信号 → `Booker`(抢号工人)→ 云端订单系统闭环,`Standalone`(独立单账号模式)与 `Sweeper`(孤儿任务回收)为辅,所有节点通过云端 API 下发配置、实时热重载、秒级插件热升级。
+
+> 领域特殊性提示:本系统对接的是 TLSContact / VFS Global / BLS / 意大利 Prenot@Mi 等真实签证预约网站的浏览器自动化(DrissionPage + 反检测 + 拟人化操作 + OCR/打码),属于灰产边缘但合法的"抢预约"业务场景。接手时需注意合规边界与凭证安全。
+
+---
+
+## 1. 完成标准与验证结果对照(机械判定)
+
+| # | 断言 | 验证方式 | 结果 |
+|---|------|----------|------|
+| 1 | 全部 Python 文件语法合法 | `python3 -m py_compile main.py ... plugins/*.py ...` | ✅ exit 0,全部通过 |
+| 2 | 核心逻辑模块可导入(无副作用) | `python3 -c "import vs_types, vs_plg, gco_wrapper, ..."` | ✅ 通过 |
+| 3 | 云端配置 API 集成可用 | 只读 GET `/api/node-configurations/standalone?node_id=yecaoyun` | ✅ 返回 3 条 entries |
+| 4 | Redis 连接配置有效 | 原生 RESP:AUTH/PING/SELECT/DBSIZE | ✅ +OK / +PONG / DBSIZE=0 |
+| 5 | 测试套件可用 | `python3 -m pytest test/test_cloud_config.py -x -q` | ❌ **失败**(见 §8) |
+| 6 | Docker 可用 | `docker info` | ✅ Server 28.3.2 |
+| 7 | Git 工作区干净 | `git status` | ✅ clean,同步 origin/master |
+
+---
+
+## 2. 架构总览
+
+### 2.1 三种角色 + 一个守护进程
+
+```
+                 ┌──────────────────────────── 云端 (api.text.skin) ────────────────────────────┐
+                 │  MySQL: sentinel_entries / booker_entries / standalone_entries (节点配置)     │
+                 │  API: node-configurations / vas task pop/detail/update/return_to_queue       │
+                 │  API: slot_refresh start/success/fail, slots/report, wechat push             │
+                 │  Redis: PubSub vs:channel:upgrade[:node_id]  (插件升级指令)                   │
+                 └──────────────────────────────┬───────────────────────────────────────────────┘
+                                                │ HTTP (Bearer token)
+        ┌───────────────┬───────────────────────┼──────────────────────────┬───────────────────────┐
+        ▼               ▼                       ▼                          ▼                       ▼
+   main.py sentinel  main.py booker       main.py standalone         main_sweeper.py         (云端下发的配置)
+        │               │                       │                          │
+        │ 轮询云端配置(30s) + MD5 diff → 热重载 sync_groups()               │
+        │               │                       │                          │
+   SentinelGCO     BaseBookerGCO           StandaloneGCO             OrphanTaskSweeper
+   (monitor+creator) ├─BuiltinBookerGCO    (单账号自循环)              (回收心跳超时任务)
+        │            └─OrderBookerGCO            │                        │
+        │               │                        │                        │
+        ▼               ▼                        ▼                        ▼
+   VSPlgFactory(importlib 动态加载) ──────► plugins/*.py (IVSPlg 契约, 10 个插件)
+        │
+        ▼
+   DrissionPage 浏览器自动化 (CloakBrowser/ungoogled-chromium + mihomo 代理隧道 + OCR/打码)
+```
+
+### 2.2 数据流(核心闭环)
+
+1. **Sentinel**:`VSPlgFactory.create()` 实例化插件 → `create_session()`(登录拿会话)→ monitor 循环按 `QueryWaitConfig`(Loop/Fixed/Random)轮询 `query(apt_type)`;发现档期(`VSQueryResult.success`)→ 写 Redis `vs:signal:{routing_key}`(TTL=`sentinel.signal_ttl`,默认 180s)→ 上报云端 `slot_refresh_start/success` + `slot_snapshot_report`。
+2. **Booker(built-in)**:`_booking_trigger_loop` 每 100ms 轮询所有 `vs:signal:*` → 命中后**临时**从云端 Pop 订单(`get_vas_task_pop("auto.{routing_key}")`)→ `instance.book()` → 成功则 `update_vas_task(status=grabbed)` + 微信推送 → 单账号达到 `max_bookings_per_account` 后销毁实例。
+3. **Booker(order,1:1 绑定)**:creator 循环按 routing_key 配额从云端 Pop 订单 → 用**订单自带账号**建会话(1 实例=1 订单)→ 预订成功即销毁。
+4. **心跳与守护**:Booker 每 `keep_alive`(默认 60s ± 5s 高斯抖动)保活 + 健康检查;心跳 deadline 写入 Redis zset `vs:worker:tasks_tracker:{group_id}`(score=deadline 时间戳)。**Sweeper** 每 3s 扫描所有 tracker zset,score 过期 → 查云端任务状态,若仍 processing → `return_vas_task_to_queue` 强制归还。
+5. **状态监控**:所有角色每 60s 上报 `vs:status:{role}:{node_id}`(TTL=180s,`RoleStatus` 含 groups 聚合状态 + 本地已安装插件元数据列表)。
+
+### 2.3 配置与热重载
+
+- 配置来源:云端 MySQL → `GET /api/node-configurations/{sentinel|booker|standalone}?node_id=&pageSize=100`。
+- 本地缓存:`config/config_{role}.json`(`save_local_cache` 原子写 `.tmp` + `os.replace`)。
+- 启动:`load_remote_or_cache()` 云端优先、失败 fallback 本地缓存(云不可用时还能离线跑)。
+- 热重载:主循环每 `--poll-interval`(默认 30s)拉取 → MD5 对比(`compute_config_hash`,sort_keys 序列化)→ 变化则 `sync_groups()` 差异化 stop/update/start 各 `GCOWrapper`。
+
+### 2.4 插件升级闭环
+
+- 云端发布插件 → Redis `PUBLISH vs:channel:upgrade[:node_id]` → 节点 `start_upgrade_listener` 后台线程秒级接收 → `handle_plugin_upgrades`:
+  - 版本比较(`is_newer_version`,语义化数字元组)→ `download_and_install_plugin`(URL 下载或直传 code + **SHA256 校验** + **py_compile 语法预检** + 原子替换)
+  - `reload_wrappers_for_plugin`:停掉使用该插件的 Wrapper → `sys.modules.pop(plugin_name)` 清缓存 → 重建加载新代码。
+
+---
+
+## 3. 模块地图(顶层,16.7k 行 Python)
+
+### 3.1 入口与编排
+| 文件 | 职责 | 行数 |
+|---|---|---|
+| `main.py` | 统一入口:角色分发(sentinel/booker/standalone)、云端配置轮询热重载、RoleStatus 上报、PubSub 升级监听 | 367 |
+| `main_sweeper.py` | 孤儿任务回收守护进程(独立部署) | 128 |
+| `configure.py` | 集中配置:REDIS_CFG、TEST_TASK/TEST_ACCOUNT/TEST_PROXY(测试短路开关)、CHROME_PATH、MIHOMO_BIN_PATH、MIHOMO_RELAY_NODES | 145 |
+| `logger_setup.py` | 统一日志(终端 + 10MB×10 滚动文件),注入 `vs_log_macros` | 45 |
+| `download_deps.py` + `deps.txt` | 下载浏览器/mihomo 二进制到 `downloads/`(供 Docker 构建) | 44 |
+
+### 3.2 核心框架层
+| 文件 | 职责 |
+|---|---|
+| `vs_types.py` | 领域模型:`GroupConfig`/`SentinelConfig`/`BookerConfig`/`BookerStandaloneConfig`(pydantic v2)、`VSQueryResult`/`VSBookResult`/`VSPlgConfig`、`Task`、状态快照 `RoleStatus`/`GroupStatus`/`PluginStatus`、异常体系 `BizException`(code/http_status 双维度) |
+| `vs_plg.py` | **插件契约 `IVSPlg`**:set_config / set_log / create_session / query / book / keep_alive / health_check / cleanup / get_plugin_status(8 个抽象方法 + 元数据 `name/version/description`) |
+| `vs_plg_factory.py` | 插件工厂:importlib 按路径动态加载模块并实例化,强制 `isinstance(IVSPlg)` 校验 |
+| `gco_wrapper.py` | **GCO 生命周期包装器**:状态机 CREATED→LOADED→RUNNING→STOPPING→STOPPED→FAILED、日志环形缓冲(1000 条)+ 订阅、`update_config`/`get_status` 透传 |
+| `sentinel.py` | `SentinelGCO`:creator(按 `target_instances` 配额 spawn,Rate-limited 时 30s 退避 + `lock_account`)+ monitor(全局查询节流 `global_gap`)双线程 |
+| `booker.py` | `BaseBookerGCO`(trigger/maintain/creator 三循环 + hook 设计)+ `BuiltinBookerGCO` + `OrderBookerGCO` |
+| `standalone.py` | `StandaloneGCO`:单实例自循环(登录冷却→健康检查→加权随机选 routing_key→查询→自动预订→微信通知) |
+| `vs_log_macros.py` | 全局日志宏(VSC_INFO/ERROR/WARN/DEBUG),可注入 app logger |
+
+### 3.3 插件(10 个,全部实现 IVSPlg)
+| 插件 | 版本 | 行数 | 目标系统 |
+|---|---|---|---|
+| `vfs_plugin` | 1.0.1 | 1465 | VFS Global 全球多中心(最大插件) |
+| `bls_plugin` | 1.0.0 | 1107 | 西班牙 BLS |
+| `tls_plugin` | 1.0.0 | 1055 | TLSContact 欧洲多国 |
+| `ita_plugin` | 1.0.0 | 770 | 意大利 Prenot@Mi |
+| `grc_plugin` | 1.0.0 | 650 | 希腊/爱尔兰 SuperSaaS |
+| `usa_plugin` | 1.0.0 | 624 | 美签 USVisaScheduling |
+| `de_plugin` | 1.0.0 | 554 | 德国 Visametric |
+| `pol_plugin` | 1.0.0 | 447 | 波兰 e-konsulat |
+| `bel_plugin` | 1.0.0 | 443 | 比利时 |
+| `prt_plugin` | 1.0.0 | 94 | 葡萄牙(**仅骨架,未实现** create_session/query/book 全为 pass) |
+
+### 3.4 工具与基建
+| 模块 | 职责 |
+|---|---|
+| `toolkit/vs_cloud_api.py` | 云端 API 单例封装(账户轮转、代理轮转、任务 Pop/更新/归还、slot 上报、邮件抓取、微信推送、HTTP Session 托管) |
+| `toolkit/mihomo_tunnel.py` / `proxy_tunnel.py` | mihomo(Clash Meta) 代理隧道(多实例隔离 + dialer-proxy 链式路由) |
+| `toolkit/ocr_engine.py` + `data/ocr.pth`、`data/ctc.pth` | PyTorch 验证码 OCR(ddddocr + 自研 CNN) |
+| `toolkit/captcha_breaker.py` | 验证码兜底:QWEN-VL 打码(硬编码 API key) |
+| `toolkit/thread_pool.py` / `backoff.py` | 线程池单例 / 指数退避 |
+| `utils/safe_redis_cli.py` | Redis 安全封装:超时/重试一次/失败安全默认值,防死等 |
+| `utils/cloud_config.py` | 云端配置拉取、MD5、本地缓存原子写、fallback |
+| `utils/plugin_updater.py` | 插件扫描(**AST 静态解析元数据,不 import 防副作用**)、版本比较、下载安装+校验+原子替换 |
+| `utils/mouse.py`/`keyboard.py`/`scroll.py`/`fingerprint_utils.py`/`fake_utils.py` | 浏览器拟人化(人类轨迹鼠标、键盘、滚动、指纹) |
+| `utils/cloudflare_bypass_for_scraping.py` / `network_interceptor.py` | CF 挑战破解 / 网络拦截 |
+| `tools/proxy_uploader.py` | 代理批量导入云端 |
+
+### 3.5 遗留代码(不参与当前框架,勿动除非明确要求)
+`tls_registration_bot.py`(711) / `vfs_registration_bot.py`(615) / `tls_registration_gui.py`(837, PyQt5) / `test/tls_standalone.py`(780) —— 框架化之前的单点脚本,`main.py` 不引用。**建议**:确认无人使用后可归档删除或标记 deprecated。
+
+---
+
+## 4. Redis 键空间约定
+
+| Key | 类型 | 说明 |
+|---|---|---|
+| `vs:signal:{routing_key}` | string(TTL) | Sentinel 发现档期的信号载荷(group_id + apt_type + query_result 快照),Booker 消费后不删(信号自过期,防并发丢单) |
+| `vs:worker:tasks_tracker:{group_id}` | zset | score=心跳 deadline,member=task_id;OrderBooker 用 `heartbeat_ttl=120s`,Sweeper 据此回收 |
+| `vs:status:{role}:{node_id}` | string(TTL=180s) | RoleStatus 全量状态 |
+| `vs:channel:upgrade` / `vs:channel:upgrade:{node_id}` | pubsub | 插件升级指令通道 |
+
+**当前状态【已验证】**:`text.skin:6379` AUTH 通过、PING PONG、`DBSIZE=0`(db0 目前为空,无生产信号数据——可能是 staging 实例或业务未启动)。
+
+---
+
+## 5. 部署与运维
+
+### 5.1 Docker 部署(生产形态)
+- 镜像:`python:3.10-slim-bookworm`,Xvfb + dbus + 中文字体 + CloakBrowser(`CHROME_BIN=/opt/ungoogled-chromium/chrome`)+ mihomo(`MIHOMO_BIN=/bin/mihomo`)。
+- `docker-compose.yml`:4 个服务(visa-sentinel / visa-booker / visa-standalone / visa-sweeper),镜像 `coordinator:latest`,挂载 `./config ./logs ./data ./plugins`(**plugins 挂载=插件热升级落盘持久化**),`NODE_ID` 默认 `yecaoyun`,资源上限 CPU 2.0 / 内存 2G。
+- 构建前置:`downloads/` 目录(gitignore)需先跑 `python3 download_deps.py`(从 deps.txt 拉 CloakBrowser 与 mihomo Linux 包),否则 `docker build` 的 `COPY downloads/...` 会失败。
+- `entrypoint.sh`:清锁 → 起 dbus → 起 Xvfb :99 → exec 外部命令。
+- `.dockerignore`:排除 docs/test/日志/缓存,仅保留构建所需 Linux 依赖包。
+- 注意:compose 未内置 Redis 服务,依赖外部 `text.skin:6379`(凭据在 `configure.py`,已提交仓库——见 §7 风险 5)。
+
+### 5.2 本地运行
+- `python3 main.py sentinel [-c config/config_sentinel.json] [--poll-interval 30] [--status-interval 60]`
+  - 不带 `-c` = 云端模式(默认);带 `-c` = 纯本地模式。
+- `NODE_ID` 环境变量决定拉取哪份云端配置与状态 key。
+- **本地环境缺口【已验证】**:本机 conda base (Python 3.11.4) 缺少 `redis / DrissionPage / curl-cffi / ddddocr / bs4 / easyocr / psutil / pyyaml`,完整运行需 `pip install -r requirements.txt`(或建 venv)再跑;生产一律走 Docker。
+- **本机代理陷阱【已验证】**:shell 环境设置了 `HTTP(S)_PROXY=http://127.0.0.1:7897`(Clash),但 7897 未监听 → `requests` 直接跑会 ProxyError。绕开方式:`unset 代理变量` 或 `session.trust_env=False`。
+
+---
+
+## 6. 测试现状
+
+| 测试文件 | 状态 | 说明 |
+|---|---|---|
+| `test/test_cloud_config.py` | ❌ **坏** | `from utils.cloud_config import ... fetch_remote_config` —— 该函数已改名 `fetch_cloud_config`,import 即崩(pytest collection error)。另 mock 服务器逻辑与当前云端模式 API 已不匹配 |
+| `test/test.py` | 片段 | opencv 中值滤波示例,非测试 |
+| `test/regex_test.py` | 片段 | TLS 档期 HTML 解析正则实验 |
+| `test/test_capsolver.py` / `image_ocr_test.py` / `test_publish_slot.py` | 一次性脚本 | 依赖外部服务/依赖,未纳入 pytest |
+| `test/tls_standalone.py` | 遗留 | 旧单点脚本 |
+
+**结论:目前没有可用的自动化测试套件。** 接手第一件事应修复 `test_cloud_config.py`(改名 + 按新 `load_remote_or_cache` 语义重写),并为核心纯逻辑(配置解析、MD5、版本比较、状态聚合)补单元测试。
+
+---
+
+## 7. 代码审查发现(多疑资深工程师视角)
+
+### 7.1 已确认的问题(高确信度)
+1. **`Task.qw_cfg` 尾逗号 bug【已验证】**:`vs_types.py:220` `qw_cfg: Optional[QueryWaitConfig] = None,` —— Python 语法使默认值变成元组 `(None,)` 而非 `None`。实测 `Task(instance=object()).qw_cfg == (None,)`。当前是潜伏 bug(生产代码总是显式传 `qw_cfg`,Booker 任务不读该字段),但任何新代码若依赖默认值会直接 `AttributeError: 'tuple' object has no attribute 'mode'`。**修复:删掉尾逗号。**
+2. **测试套件损坏【已验证】**:见 §6。
+3. **文档与代码不一致【已读码确认】**:`handle_plugin_upgrades` docstring 示例用 `"plugin_name"`,代码实际读 `item.get("name")`。以代码为准(云端下发 "name"),docstring 需修正。
+4. **活跃时段用 UTC 判定(可能偏移 8 小时)【代码确认,业务语义待确认】**:`sentinel.py:129` / `booker.py:148` / `standalone.py:56` 用 `datetime.utcnow()` 但变量名叫 `current_bj_time`、注释写"北京"。Docker 里 TZ=Asia/Shanghai 不影响 `utcnow()`(它总是 UTC)。若业务期望北京时区,`active_time_start/end` 实际会偏移 8 小时生效。**需与业务确认后修复**(`datetime.now()` 或显式 `ZoneInfo("Asia/Shanghai")`)。
+
+### 7.2 值得商榷的设计(建议,勿擅自改)
+5. **生产凭据硬编码入库【高确信度】**:`vs_cloud_api.py` 的 `api_token`、`configure.py` 的 Redis 密码、`captcha_breaker.py` 的 QWEN key、config JSON 里的真实账号密码均已提交到 gogs 仓库。若这是生产环境,建议尽快轮换密钥并迁移到环境变量/secret 管理(Docker secrets / .env + `configure.py` 从环境读取)。**注意:改动涉及多处调用点,需单独排期。**
+6. **Sweeper 用 `KEYS vs:worker:tasks_tracker:*`**:键数量大时阻塞 Redis,建议换 `SCAN`(当前量级可接受)。
+7. **`configure.py` 中 `TEST_TASK/TEST_ACCOUNT/TEST_PROXY` 是运行时短路开关**(非 None 时 `get_vas_task_pop/get_next_account/get_next_proxy` 直接返回测试数据)—— 这是有用的本地联调机制,但生产误开会导致假数据,建议启动时打醒目标记日志。
+8. **Standalone `_init_instance` 无条件拉代理**:`get_next_proxy` 未按 `need_proxy` 门控(与 Sentinel/Booker 的 `if self.m_cfg.need_proxy` 不一致)。
+9. **README 缺失**:仓库根目录无 README(RDD 原则),本次接手报告可作起点。
+10. **`prt_plugin` 是空壳**(所有方法 pass):若 routing 配置里出现 `prt_plugin` 会静默"成功但无行为",建议禁用该插件或标注未完成。
+
+### 7.3 初步审查的自我反驳(原则 6)
+> 反驳:"你说 `_is_within_active_hours` 是 bug,但也许业务就是按 UTC 设计的,配置里 00:00–23:30 本来就是 UTC 意图。"
+> 回应:可能性存在,所以我标"待业务确认"而非直接修。但变量名 `current_bj_time` + 注释"判断当前是否在允许创建实例的时间段内"(无时区声明)+ Docker TZ 设为 Asia/Shanghai,三处证据都指向"期望北京时间"。在确认前不动作,符合"禁止顺手优化"。
+
+> 反驳:"Redis DBSIZE=0 说明这个实例是空的,你凭什么说生产闭环能跑通?"
+> 回应:我只验证了"连接与认证有效"和"云端配置拉取有效"两件事,未声称业务闭环已跑通。完整的端到端验证需要部署容器 + 真实信号,属上线前联调范畴(见 §10 下一步清单)。
+
+---
+
+## 8. 确信度与进度标注
+
+- 高确信度:模块职责、数据流、Redis 键空间、插件清单、部署形态、§7.1 的四个问题(全部有代码/命令证据)。
+- 中确信度:UTC 时区问题是否是 bug(需业务确认)、sweeper 实际生产规模。
+- 未验证(明确列出,不假装验证过):
+  - 插件真实浏览器端到端行为(本地缺 DrissionPage,且需要目标网站可达)——需要 Docker 环境或 venv。
+  - Redis PubSub 升级链路(需要云端主动 PUBLISH 触发,无法只读验证)。
+  - Docker 镜像构建(本地 `downloads/` 目录不存在,需先执行 download_deps.py 下载 ~ 依赖包)。
+  - 微信推送 / 邮件抓取 / 打码等外部依赖服务。
+
+---
+
+## 9. 验证命令清单(本文所有【已验证】的依据)
+
+```bash
+# 1. 语法全检
+python3 -m py_compile main.py main_sweeper.py booker.py sentinel.py standalone.py \
+  gco_wrapper.py vs_types.py vs_plg.py vs_plg_factory.py vs_log_macros.py configure.py \
+  logger_setup.py utils/*.py toolkit/*.py plugins/*.py tools/*.py   # exit 0
+
+# 2. 核心模块导入(无网络副作用)
+python3 -c "import vs_types, vs_plg, vs_plg_factory, gco_wrapper, configure, logger_setup"  # exit 0
+
+# 3. Task 默认值 bug 复现
+python3 -c "from vs_types import Task; print(Task(instance=object()).qw_cfg)"  # -> (None,)
+
+# 4. 云端只读 GET(绕开本地死代理)
+python3 -c "..." # session.trust_env=False 后 GET node-configurations → 3 条
+
+# 5. Redis 只读探测(原生 RESP,无需 redis 库)
+AUTH → +OK ; PING → +PONG ; SELECT 0 → +OK ; DBSIZE → :0
+
+# 6. 测试套件
+python3 -m pytest test/test_cloud_config.py -x -q   # exit 1: ImportError fetch_remote_config
+
+# 7. 环境
+python3 --version  # 3.11.4 (conda base);docker info → Server 28.3.2
+git status → clean ; git log → 124 commits,HEAD=9bee354 (2026-08-24, docker .dockerignore)
+```
+
+---
+
+## 10. 立即接手清单(按优先级)
+
+**P0(上线前必须)**
+1. 修复 `vs_types.py` Task 尾逗号 bug(一行)。
+2. 修复 `test/test_cloud_config.py`(改名 + 按新 API 重写)并让 pytest 全绿。
+3. 确认 UTC vs 北京时间语义(问业务),确认后修 `_is_within_active_hours`。
+
+**P1(质量)**
+4. 补核心纯逻辑单测:`compute_config_hash`、`is_newer_version`、`parse_group_configs`、状态聚合(这些不依赖浏览器,本地可跑)。
+5. 修正 `handle_plugin_upgrades` docstring。
+6. 评估密钥外置(至少 Redis 密码与 API token 支持环境变量覆盖)。
+
+**P2(体验/长期主义)**
+7. 写根 README(RDD:把本文档提炼为对外文档 + 快速开始)。
+8. `prt_plugin` 空壳处理(完成或禁用)。
+9. Sweeper KEYS→SCAN、Standalone 代理门控对齐。
+10. 遗留脚本(tls_registration_bot 等 4 个)确认后归档。
+
+---
+
+## 11. 参考文档(docs/ 内,均与代码一致)
+
+- `docs/node_config_cloud_storage_and_api.md` —— 节点配置云端化 + 轮询热重载设计(§3.1-3.3 与代码逐行对应)
+- `docs/config_entries_database_schema.md` —— booker/sentinel/standalone 三表 DDL 与字段映射
+- `docs/plugin_cloud_storage_and_api.md` —— 插件云端发布/升级/分发设计(`/plugins/publish`、`/plugins/upgrade/dispatch`、PubSub 通道)

+ 145 - 0
docs/ita_book_cs4a.md

@@ -0,0 +1,145 @@
+# CS4A:Book 日历时段选择工作记录
+
+日期:2026-08-30。状态:CS4A 离线已验证,尚未接入 Book 总入口或现场验收。
+
+Phase: VERIFIED(仅本文件限定的离线增量)。Approval: 本地开发、测试;不包含真实登录、
+OTP、取信、前置表单提交、最终预约、提交代码或上线。Evidence/Risks: 聚焦 25 项、Italy
+回归 245 项均通过;现场会话、响应新鲜度和完整 Book 仍未验证。
+
+本文件只记录 [总设计 CS4](./ita_plugin_generic_schengen_design.md) 的一个增量,不替代
+总设计或 [Discovery 事实账本](./ita_plugin_discovery.md)。负责人已允许推进 Book;没有
+Query 任务链接不作为阻塞条件。共享设计文档在本轮读取后发生变化,原修改完整保留。
+
+## 1. 本轮范围和文件
+
+只新增 `plugins/ita_calendar_book.py`、`test/test_ita_calendar_book.py` 和本工作记录。
+不修改 `ita_plugin.py`、`ita_protocol.py`、`ita_calendar_query.py`、调试工具、配置或邮箱服务。
+因此现有 `ItaPlugin.book()` 仍保持表单前安全停点,本轮不声称完整 Book 已接通。
+
+采用现有 Functional Core + Imperative Shell:新增的只是与 Calendar Query 并列的
+Book 浏览器适配层,不新增框架。复用 `parse_availability_packet()`、`parse_time_slots()`、
+`available_slot_candidates()`、`DateSelectionState`、`SlotSelectionState`、
+`approve_precommit()` 和 `guard_calendar()`。不复制地区分支或重写候选排序规则。
+
+## 2. 调用合同(实现前固定)
+
+```python
+approval = select_slot_before_final(
+    book_page,
+    target_day=target_day,
+    availability_packet=current_book_availability_packet,
+    time_slots_packet=current_book_time_slots_packet,
+)
+```
+
+前置条件:调用方已证明用户账号、route、日期偏好和 Calendar 准备状态;两个 packet 必须
+由该用户页面本次原生动作的监听取得,不能传 Query 快照、跨账号响应或持久化旧 packet。
+本模块不负责登录、OTP、翻月、日期点击或证明采集时间。内容一致不等于来源或新鲜度证明;
+这些能力属于后续 CS4 编排及现场验收,不能用本次离线结果替代。
+
+行为:
+
+1. 校验同源精确 path/method/status、请求字段和目标日期;TimeSlots 的 `idService`
+   必须匹配当前 DOM `#idServizio`,不拿 Services 的配置 `service_id` 替代。
+2. 复用双层 JSON 与容量规则。合法无号返回 `None`;错日、错服务、结构变化和容量冲突
+   抛明确错误,不冒充无号。
+3. 日期必须已被调用方选中,timeline/content 两个 selected 区域日期一致,且网站最终
+   handler 使用的第一个全局 selected 仍为正确时间线日期。不会偷偷改日期或补发请求。
+4. 在正确日期内容中按 daily ID、时间和数量定位唯一正向时段。使用 scoped hidden input,
+   不按全局重复 HTML id 查找;点击前后检查负向 class、红点和容量。
+5. 时段最多原生点击一次;正确候选已经唯一 active 时不重复点击。最终按钮始终禁用。
+6. 返回既有 `PrecommitApproval` 只表示本次选择态通过,不是预约成功或最终提交授权;
+   真正 final 前仍须重新校验、通过 FENCE/FINAL 验收并取得最终提交授权。
+
+## 3. 准出条件
+
+- 测试覆盖正向 `1/0`、无号 `0/-1`、容量冲突、错误日期/服务/域名/方法/状态、畸形响应、
+  重复节点、隐藏值/时间/数量不匹配、负向 active、页面漂移、不重复点击和异常脱敏。
+- 不导入调试工具或 Query 插件实例,不构造 HTTP 请求,不操作 OTP/AVANTI,不点击 final。
+- 运行时 ID 不进入返回对象 repr、日志或异常;新增 JS 用离线合成 DOM 检查。
+- 新模块测试、既有 Italy 回归、编译与 `git diff --check` 返回 0。
+- 真实网站操作为 0;真实 session 连续性、监听新鲜度、DOM 交互和预约成功仍待现场验证。
+
+## 4. 验证记录
+
+以下命令在仓库根目录执行;未启用真实浏览器、网站或邮箱服务。
+
+### 4.1 聚焦测试
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_ita_calendar_book
+```
+
+返回值:`0`;结果:`Ran 25 tests ... OK`,无跳过。包含真实执行新增 JS 源码的 Node
+合成 DOM 测试:正向选择、不重复点击、负向/遮挡/重复节点拒绝、点击后日期或域名漂移。
+合成 DOM 不是网站浏览器,不能证明真实布局、监听关联或会话有效性。
+
+### 4.2 既有 Italy 回归
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
+  test.test_add_ita_query_account \
+  test.test_debug_ita_book \
+  test.test_debug_ita_calendar_gate \
+  test.test_debug_ita_monitor \
+  test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_query \
+  test.test_debug_ita_session \
+  test.test_debug_ita_soak \
+  test.test_ita_calendar_book \
+  test.test_ita_calendar_query \
+  test.test_ita_local_handoff \
+  test.test_ita_plugin \
+  test.test_ita_protocol \
+  test.test_ita_route_wiring
+```
+
+返回值:`0`;结果:`Ran 245 tests in 3.359s ... OK`,无失败、无跳过。
+数量包含既有 220 项和新增 25 项,不代表全仓库或 VFS/BLS 的测试覆盖。
+
+### 4.3 静态检查与改动隔离
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -c 'from pathlib import Path; paths = [Path("plugins/ita_calendar_book.py"), Path("test/test_ita_calendar_book.py")]; [compile(path.read_bytes(), str(path), "exec") for path in paths]; print("COMPILE_OK files=2")'
+git diff --check
+```
+
+均返回 `0`;编译输出 `COMPILE_OK files=2`,没有写入字节码。
+
+三个新增文件另逐一执行 `git diff --no-index --check -- /dev/null <文件>`:均无空白错误
+输出;均返回 `1`,这是 no-index 比较中新文件与 `/dev/null` 不同的返回值,不能记为 `0`。
+新增文件还单独执行以下行尾空白检查:
+
+```sh
+awk '/[[:blank:]]+$/ { print FILENAME ":" FNR ": trailing whitespace"; ita_ws_failed=1 } END { if (!ita_ws_failed) print "NEW_FILES_WHITESPACE_OK files=3"; exit ita_ws_failed }' plugins/ita_calendar_book.py test/test_ita_calendar_book.py docs/ita_book_cs4a.md
+```
+
+返回值:`0`;结果:`NEW_FILES_WHITESPACE_OK files=3`。
+
+`shasum -a 256` 返回 `0`;下面七个共享文件与本轮实现前指纹完全一致:
+`plugins/ita_plugin.py`、`plugins/ita_protocol.py`、`plugins/ita_calendar_query.py`、
+`tools/debug_ita_calendar_gate.py`、`tools/debug_ita_book.py`、
+`config/config_sentinel.json`、`config/config_booker.json`。
+共享设计文档的并发修改未覆盖,原有脏工作区未回滚。
+
+## 5. 初见审查
+
+反驳:“参数都对上了,是否就能证明是用户账号刚查到的号?能否直接据此提交预约?”
+
+不能。响应内容和 DOM 一致只能证明本次选择态一致,不能证明响应来自哪个账号、是什么
+时候捕获,也不能保证下一瞬间号源仍在。本模块明确要求调用方完成账号/route 连续性和
+本次监听关联;它返回既有 `PrecommitApproval`,没有返回预约成功,更没有最终提交能力。
+最终按钮沿用现有 guard 禁用;这也不等于拦截页面全部网络副作用,后续现场 Gate 仍须
+独立确认最终请求数为 0。
+
+审查修正:在实际时段点击及随后回读时增加同源判断,防止首次 Python URL 检查后页面
+跳到同路径的其他域名;新增相应 JS 测试。未修改共享 helper。
+
+确信度:本轮离线合同为高;真实浏览器适配和完整 Book 尚未验证。
+
+## 6. 下一步(未在本轮实现)
+
+把现有登录/Calendar 准备能力接入 Book 编排,由**申请人自己的会话**重查日期、选日并
+监听本次 TimeSlots,然后调用本模块。沿用现有路由与日期偏好规则,不复制 Query 的
+浏览器、Cookie、OTP 或 daily ID。先在最终确认按钮前做一次现场验收;无需等待 Query
+任务链接,也不把本轮测试通过当作已预约或上线许可。

+ 192 - 0
docs/ita_book_cs4b.md

@@ -0,0 +1,192 @@
+# CS4B:Book 当前会话重查与入口接线
+
+日期:2026-08-30。状态:CS4B 离线已验证;尚未接入完整 Calendar 准备或现场验收。
+
+Phase: VERIFIED(仅离线合同)。Scope: 已准备 Calendar 的用户会话从重查走到最终按钮前。
+Non-goals: 不改 Query、共享框架、邮箱服务、生产配置或最终提交。
+Done: 离线证明请求来自本次 Book 监听、日期偏好生效、选日后时段/DOM 一致、最终点击为 0;
+Italy 回归、编译和差异检查返回 0。Approval: 负责人“继续吧”的本地开发授权。
+Evidence/Risks: [CS4A](./ita_book_cs4a.md) 已离线验证;完整 Book 和原生选日仍需现场验收。
+
+## 1. 先确定复用和文件归属
+
+本文件承接[总设计 §9、CS4](./ita_plugin_generic_schengen_design.md),不另立工作流框架。
+
+| 责任 | 既有参照 | 本轮落点 |
+|---|---|---|
+| 用户账号与调用入口 | OrderBooker、VFS/BLS 的独立 Book Session | `ita_plugin.py` 中增加薄入口;不改 Booker |
+| 用户日期偏好 | VFS `expected_start_date` / `expected_end_date` | 保留原字段,严格解析、不修改输入字典 |
+| 日期正向判断、范围过滤、排序 | `ita_protocol.py` | 直接复用 |
+| 刷新、原生翻月、单月递增、最终按钮保护 | `ita_calendar_query.py` | 直接调用,不改 Query 行为 |
+| 当前浏览器请求监听 | USA/TLS 的 `page.listen`,Q-CAL 的 `finally: stop` | 放在 `ita_calendar_book.py` |
+| 时段选择、点击后校验 | CS4A `select_slot_before_final()` | 直接调用 |
+| 最终结果类型 | `VSBookResult` | 停点仍返回 `success=False`,不填写预约编号 |
+
+修改范围:`plugins/ita_calendar_book.py`、`plugins/ita_plugin.py`;新增
+`test/test_ita_calendar_book_flow.py` 和本记录。原测试及共享文件原则上不修改。
+不增加地区分支、配置开关、邮箱 Provider 或 Redis 字段。
+
+## 2. 输入、流程和输出
+
+### 2.1 Book 的准备证明
+
+- `ItaPlugin.book()` 在 Calendar 分支只接受本实例**专属 Book 准备记录**;Query 的准备
+  标记不算证明,也不会被自动转换为 Book 标记。
+- 准备记录绑定本实例、当前浏览器对象和 tab、当前账号、登录代次、完整 route 和 Calendar
+  runtime service;重新配置、重新登录和 cleanup 清除记录。日历操作开始后,无论得到
+  正向停点、无号还是错误,都不允许自动再执行一次 Book;需要新的准备。请求开始前的
+  账号等参数校验不消耗网络操作额度。
+- 调用方必须在用户账号完成已验证的对应 route 的 OTP/AVANTI 跳转后登记。登记方法是
+  编排层内部接口,不是从 URL 推断 Sede 的方法,也不能证明调用方未观察到的站点事实。
+- `user_inputs.username` 必须匹配当前账号;仅一次 Book 执行。账号或 route 中途变化则
+  停止。未完成 Calendar 准备时保留既有“表单前停止”路径,不隐式发送 OTP/AVANTI。
+
+### 2.2 重新查询与候选策略
+
+1. 查询只用当前用户 `page`;不接收 Query 的 packet、Cookie、时段或 daily ID。
+2. 原生刷新 Calendar,监听本次 Availability 和页面自动产生的 TimeSlots。
+3. 两个 packet 均须来自当前 `tab_id`,并通过同源、方法、状态、字段、日期和 runtime
+   service 校验。每次开始监听清空旧队列,每次结束都停止;不写自定义 HTTP 请求。
+4. Availability 只产生日期候选;先按既有设计尝试范围内的 Query 提示日,但必须在当前
+   Book 响应中重新证明正向。提示失效时最多重新从起始月扫描一次,按用户范围内日期升序
+   回退。每个日期候选最多尝试一次;同一天先容量降序、再开始时间升序,沿用 CS4A。
+5. 已由网站自动选中的日期必须使用**本次刷新/翻月时捕获**的匹配 TimeSlots,不能重复
+   点击同一天并假设一定再发请求。换日期才执行一次原生点击并监听新的 TimeSlots。
+6. 请求完成后等待有限时间让 DOM 更新,核对 timeline/content 的实际日期;网站静默回退、
+   错服务、错月份、重复节点、结构冲突均报错,不能冒充无号。
+7. 每轮月数受当前 route 的 `calendar_scan.lookahead_months` 限制;提示日失效最多两轮。
+   翻月失败或未完整扫完不能报告“已验证整个范围无号”。号源仅在已扫描范围内有效。
+8. 当前日期已没有正向时段是正常竞争,可以尝试下一候选;已执行时段点击后出现错误则
+   直接停止,不换号、不盲目重试。
+9. 成功到达停点只保存当前进程内的 `PrecommitApproval`,返回 `VSBookResult(success=False,
+   label="calendar-ready-before-final")`;无合适号返回既有无号停点,异常明确抛出。
+
+本模块不会替调用方发送 OTP 或准备 Calendar。普通 `debug_ita_book.py` 目前仍停在表单;
+专用现场验收入口和完整准备编排另接,不能把本轮离线接线当作端到端预约已完成。
+
+## 3. 为什么需要监听两个响应
+
+E30 的网站初始化函数会程序化点击首日;E33 的 TimeSlots 来自该原生流程。当前已安装
+DrissionPage `Listener.start()` 会 `clear()` 队列和 request-id 集合,`DataPacket.tab_id`
+可绑定浏览器。先只监听 Availability 再停止,会漏掉已经发出的自动 TimeSlots。
+
+因此复用同一监听器的多 target 能力,不通过移除 `.selected`、伪造 DOM 或手写接口强迫
+网站重新发送请求。重复点击 selected 日期的实际网站行为仍待现场证明;实现不依赖它。
+
+## 4. 假设与准出测试
+
+- HK 正向、其他 route/配置同路径;源代码无城市名或真实 service ID 分支。
+- 第一个正向日已自动选中:使用本次时段响应,人工日期点击为 0;其他日期点击为 1。
+- 本次监听前的旧数据、错误 tab、错误日期/服务/月份、跳月、监听超时均拒绝。
+- 日期范围闭区间、跨年、提示日失效、当前月有号但不在用户范围、全部无号。
+- 正向日期的时段被抢完:尝试下一日;格式/容量冲突:报错而不是跳过。
+- 账号、route、page、登录代次变化或 Query 准备标记冒用:不查询、不选择。
+- 重复 Book 不重新执行;任何阶段失败最终按钮保持禁用、监听器停止。
+- 不输出密码、OTP、正文、runtime service、daily ID;不修改 `user_inputs`。
+- Node 合成 DOM 检查真实选日脚本;假浏览器检查入口到 CS4A 的完整离线链路。
+- 回归需覆盖既有 Query、表单安全停点和本轮新增代码。
+
+## 5. 验证与初见审查
+
+### 5.1 实际执行命令
+
+在仓库根目录执行:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_ita_calendar_book_flow
+```
+
+返回 `0`;`Ran 51 tests in 0.334s ... OK`,无跳过。
+测试运行实际 Book 入口和浏览器编排,仅替换浏览器/Network;选日 JS 另由 Node 的合成 DOM
+执行。假浏览器按已读的本站流程及本地监听器源码建模,不能代替真实页面时序与布局验收。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
+  test.test_add_ita_query_account \
+  test.test_debug_ita_book \
+  test.test_debug_ita_calendar_gate \
+  test.test_debug_ita_monitor \
+  test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_query \
+  test.test_debug_ita_session \
+  test.test_debug_ita_soak \
+  test.test_ita_calendar_book \
+  test.test_ita_calendar_book_flow \
+  test.test_ita_calendar_query \
+  test.test_ita_local_handoff \
+  test.test_ita_plugin \
+  test.test_ita_protocol \
+  test.test_ita_route_wiring
+```
+
+返回 `0`;`Ran 296 tests in 3.066s ... OK`,无失败、无跳过。包含原有 245 项和本次新增
+51 项。最早一次聚焦运行因直接导入了另一测试类而重复收集部分旧测试,已改为通过模块
+引用 fixture;这里的 51 和 296 均是修正后的最终实际数量。
+
+回归中显示的 `ITA_QCAL_*`、`ITA_PREFLIGHT_OK` 是假浏览器测试输出,不是新的网站登录、
+OTP 或生产 Query 现场证据。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -c 'from pathlib import Path; paths = [Path("plugins/ita_calendar_book.py"), Path("plugins/ita_plugin.py"), Path("test/test_ita_calendar_book_flow.py")]; [compile(path.read_bytes(), str(path), "exec") for path in paths]; print("COMPILE_OK files=3")'
+git diff --check
+awk '/[[:blank:]]+$/ { print FILENAME ":" FNR ": trailing whitespace"; ita_ws_failed=1 } END { if (!ita_ws_failed) print "BOOK_FILES_WHITESPACE_OK"; exit ita_ws_failed }' plugins/ita_calendar_book.py test/test_ita_calendar_book_flow.py docs/ita_book_cs4b.md
+```
+
+均返回 `0`。分别输出 `COMPILE_OK files=3`、无差异空白错误、`BOOK_FILES_WHITESPACE_OK`。
+编译不写入字节码;没有启动浏览器、读取真实账号配置、取信、发 OTP、执行预约、commit
+或部署。原有未提交修改保留。
+
+### 5.2 共享行为隔离
+
+执行 `shasum -a 256` 返回 `0`,下列文件与本轮开始时完全相同:
+
+- `plugins/ita_calendar_query.py`:`e78e19d0f39a6a71e6dcd0474e7353ade63a0f79fb91f5e0ef2b0676616c4802`
+- `plugins/ita_protocol.py`:`422e63226f3bbb3d9e4c1274d293ed34ccdc4b58e1b180f0c2bd9c199f9279a1`
+- `tools/debug_ita_calendar_gate.py`:`98021ab36ba8342210cc4deb6da1180328f85a9ef27c351f14ff77a472dda145`
+- `tools/debug_ita_book.py`:`100c27621bf9eae5d59b507625f127ea0f0151980695cbb40dd6dc72d4a21cb9`
+- `config/config_sentinel.json`:`90bb58bd4fe5f83ecd54c97e9c8e1760a7c8c8b3ca9c951295490bd5318a2b7c`
+- `config/config_booker.json`:`a6c7f0f7762916825a559014f94e92f443d995b68bd9ea06dcbb58ae663649c5`
+
+`ita_plugin.py` 只接入 Book 分支、准备记录和生命周期清理;没有编辑 `query()` 或
+`_query_calendar()` 的实现。Q-CAL 的复合源码指纹会因它包含 `ita_plugin.py` 而变化,
+不能把旧的现场日志当作新增 Book 的运行证明。
+
+### 5.3 初见审查
+
+反驳:“相同 URL 和日期的响应,也可能来自 Query 账号或旧请求,为什么能拿来 Book?”
+
+回应:本轮不是把旧 packet 传入 CS4A;是由当前 Book page 在原生动作前启动监听,清空
+旧请求集合并捕获新的 packet。它们还必须匹配当前 tab、当前 runtime service、当前日期,
+并通过点击后的 DOM 复核。Query 的准备标记和另一个插件实例的 Book 记录都不能使用。
+但这不是网站身份的独立认证:账号、route 和 AVANTI 连续性仍必须由后续准备编排证明;
+内部登记方法不能被当成“打开 Calendar 就授权”的捷径。跨账号现场 Gate 尚未关闭。
+
+反驳:“首日时段早已自动加载,再点一次就能重新拿到吗?”
+
+回应:不能假定。本轮在月加载阶段一起捕获自动 TimeSlots;只有它对应当前仍选中的日期
+时才使用。若后来切换过日期,即使又回到原自动日期,也会重新点击、监听,拒绝复用旧
+DOM 和 packet。对应的正常、后退和错误响应测试均通过。
+
+反驳:“返回无号,就意味着用户整个日期范围都没有号?”
+
+回应:只代表当前 Calendar 起始月、route lookahead 和用户日期范围的交集没有可用候选。
+不能外推更远未来;翻月失败、响应缺失、容量矛盾或日期回退均为错误,不返回正常无号。
+
+实际 HTTP `401` / `429` 映射为既有 `SessionExpiredOrInvalidError` / `RateLimiteddError`;
+其他协议或结构错误明确失败。最终按钮禁用与观察计数仍不是服务端占位证明或全网络写屏障。
+timeout 约束的是各次响应/DOM 等待,不声称覆盖浏览器连接阻塞的整体硬墙钟上限。
+
+## 6. 剩余工作与现场条件
+
+下一步是把**既有**手工 OTP/AVANTI 验收能力接到 Book 专用入口,使用申请人账号,不使用
+Query 的凭据或 profile。在真实 POST/跳转、服务/表单选择和账号连续性都确认后,才调用
+`_record_calendar_book_prepared_route()`,再执行这里已离线验证的 Book 分支。
+
+现场验收需证明:准备阶段 OTP/AVANTI 各最多一次;Book 重查期间二者增量为 0;最终请求
+始终为 0;请求月份/日期、当前显示时段和 `last_booking_precommit` 一致;预约/候补记录
+前后不变。若异常,停止并收集脱敏状态,不重发 OTP 或最终请求。
+
+自动接码、从普通订单 Session 自动准备 Calendar、跨账号正向传播、最终一次提交与对账
+仍未完成。旧 `debug_ita_book.py` 继续停在表单,不提供或暗示尚未实现的新 CLI 参数。
+
+确信度:本轮离线合同为高;真实 Book 全流程尚未验证,不能保证预约成功或宣称已上线。

+ 1128 - 0
docs/ita_book_cs4c.md

@@ -0,0 +1,1128 @@
+# CS4C:Book 专用现场验收入口
+
+日期:2026-08-30。最新状态:v6 香港单人旅游 Book 提交前现场验收通过,详见第 20 节;未提交最终预约。下方各版本记录保留为历史证据。
+
+Phase: VERIFIED(v6 单次真实提交前链路;不等于最终预约或跨地区生产验收)
+Scope: 独立申请人登录 → 既有表单检查 → 手工 OTP → 一次 AVANTI → 生产 Book 重查/选择 → 最终确认前停止。
+Non-goals: 不改 Query、生产配置、共享框架或邮箱服务;不自动接码、不最终预约、不提交代码或部署。
+Done: 专项与 Italy 回归返回 0;真实验收 passed=true、selectionVerified=true、exit 0,OTP/AVANTI 各一次、Book 重查不再发码或提交表单、最终请求为 0,预约/候补数量不变。
+Approval: 负责人“可以 请你继续”授权本地开发,并明确“用一个就行,这个账号可以复用”;现场命令由负责人自行执行。
+Evidence/Risks: [CS4B](./ita_book_cs4b.md) 离线合同及本文第 20 节单次香港真实提交前证据;跨账号调度、其他地区、最终提交与回执、服务器内部草稿不在本次证明范围。
+
+## 1. 这一步解决什么问题
+
+CS4B 已有 Calendar 之后的生产 Book 能力,但旧 `debug_ita_book.py` 只到前置表单。
+直接给 CS4B 填一个准备标记,不能证明申请人真的完成过当前服务的 OTP/AVANTI。
+本次新增一个可独立运行的验收入口,负责补齐这段证明,不改写生产调度器。
+
+工具运行只意味着一次受控实验。`passed=true` 表示已选好时段且安全停下,不表示预约成功。
+`VSBookResult.success` 必须仍为 `false`,预约编号等成功字段必须为空。
+
+## 2. 复用优先与文件归属
+
+| 能力 | 复用来源 | 本轮处理 |
+|---|---|---|
+| 申请人自己的 Session | VFS/BLS、OrderBooker、旧 Book 工具 | 既有临时浏览器,不复用 Query profile |
+| 显式复用本地账号 | `utils.local_account.load_local_account()` | 复用已有文件、权限与字段校验;不复制密码,不新建账号配置 |
+| route/form/calendar 配置 | `build_calendar_gate_config()` | 原样复用;本工具要求四个 route 字段显式提供 |
+| 可见单人/旅游选择、Privacy、Turnstile 等待 | Q-CAL 的 preflight | 原样复用;调用前加同源、表单路径/方法/enctype 边界检查 |
+| OTP 一次性动作、原生输入与回读 | Q-CAL `OneShotAction`、`_enter_otp` | 原样复用;仍手工输入,不读取邮箱 |
+| AVANTI 请求与跳转证明 | Q-CAL 监听、`validate_avanti_packet()` | 原样复用;额外绑定当前申请人 page/tab/登录代次 |
+| 请求计数、预约/候补记录计数 | Q-CAL `CalendarRequestAudit`、`read_reservation_snapshot` | 同一观察器覆盖准备、Book 和结束核对,不另造审计框架 |
+| 日期偏好、日历重查、选择与回读 | VFS 字段、CS4A/CS4B | 调用真正 `ItaPlugin.book()`,不复制 Calendar 算法 |
+
+只新增三个文件:
+
+- `tools/debug_ita_book_gate.py`:验收编排与 CLI。工具可以组合已有工具函数;生产插件不反向导入工具。
+- `test/test_debug_ita_book_gate.py`:无网络的合同、失败路径、账号隔离和实际 Book 链路测试。
+- 本文:设计、命令、测试证据、准出条件与限制。
+
+使用组合方式接线,不新建通用工作流、账号池、重试引擎或邮件 Provider。
+既有 Query 工具、生产插件和旧 Book 工具不计划修改;若确需改动,先说明具体原因。
+
+## 3. 输入与权限边界
+
+- 默认只做本地 `--preflight`,不读取凭据、不创建浏览器、不发网站请求。
+- 只有显式 `--run` 才允许登录、一次 OTP、一次 AVANTI 以及日历/时段选择。
+- 复用现有 route/form 环境变量,不把香港或 `4937` 写进实现分支。香港只用于下方示例。
+- 默认仍只接收 `ITA_BOOK_USERNAME` / `ITA_BOOK_PASSWORD`,或者在终端交互输入;不继承通用
+  `ITA_USERNAME` / `ITA_PASSWORD`,也不自动读取 Query 账号。
+- 本次授权通过 `--use-local-query-account` 显式选择 `config/ita_query_account.local.json`。
+  此时用户名和密码整对从该文件读取,不和环境变量混用,不再要求手工输入账号密码。
+  文件缺失、权限不安全或字段无效时停止,不静默换账号;`--preflight` 即使带此开关也不读凭据。
+- 使用临时浏览器,不接管用户 Chrome 或 Query 的持久化 profile。每轮重新登录。
+  同账号不等于同会话;本次不证明 Query/Book 跨账号传递,也不改生产订单账号来源。
+  验收前请暂停使用同一账号的 Query,避免网站侧会话或预约状态相互影响;工具不会代为停止进程。
+- 可选 `--expected-start-date` / `--expected-end-date` 映射到 VFS 原有同名字段,闭区间且严格
+  `YYYY-MM-DD`;未指定沿用 `2000-01-01` / `2100-01-01`。实际扫描仍受 route 月数限制。
+- 本工具不等待真实 Query 信号;它构造仅含 route 的本地调试触发,不捏造“发现有号”。
+  自动跨账号传播仍是另一项验收。
+
+## 4. 执行合同
+
+1. 在接触凭据/浏览器前校验 route、表单配置、日期偏好和 Chrome 路径。
+2. 读取申请人凭据,创建临时 Session;绑定插件、page、tab、账号、登录代次和 route。
+3. 启动既有被动请求审计,读取预约/候补数量基线。
+4. 调用一次 Book 的既有“表单前停止”分支。没有入口则返回“本轮无正向验收条件”,不发码。
+5. 确认同源目标表单、POST action、已观察的 `multipart/form-data`,没有文件控件;复用
+   preflight 操作已配置的可见选项和 Privacy,等待站点正常完成 Turnstile。
+6. OTP guard 在点击前消耗额度,监听当前 tab 的一次 GET,校验服务及 `SENT` 响应。
+   人工输入后复用 DOM 回读验证。不输出输入值;可见输入会保留在终端,用户不要回传它。
+7. 再次检查申请人、route、表单和一次性预算。仅在本次 AVANTI 期间打开原生确认框自动接受;
+   不论成功失败,立即关闭该设置,不能把自动接受带进 Calendar。
+8. 监听当前 tab 的 POST,复用直接 302/跟随重定向 200 两种证据验证。到达同源 Calendar,
+   禁用最终按钮,再登记 **Book 专属**准备记录,不登记 Query 记录。
+9. 调用一次生产 Book 的 Calendar 分支,按用户日期偏好重新扫描、选时段;这是第二次
+   `book()` 调用但属于不同阶段。必须分别报告 `entryBookCalls=1`、`calendarBookCalls=1`,
+   不能把两次调用写成“Book 只调用了一次”。Calendar 分支内部仍只执行一次。
+10. 复用选择快照做一次纯读取,确认当前显示日期/时段仍等于 `last_booking_precommit`。
+11. 读取预约/候补数量并比较,核对 Book 期间 OTP/AVANTI/最终请求增量均为 0。
+12. 停止监听/审计、关闭本工具创建的浏览器并清理临时目录,再发布最终验收结果。
+
+不能根据一张已存在的 Calendar 页面跳过步骤 2–8。任何身份/路径/结构/预算变化均停止。
+已发 OTP、已提交 AVANTI 或结果不明确时,不重试、不自动重新登录再发一次。
+失败时只尝试读取脱敏诊断、结束计数和预约数量,不重复写操作。
+
+本轮沿用 Q-CAL 的 DOM 同步、POST 路径与跳转证明;不会新增 multipart 序列化器,也不会
+输出/落盘完整 POST、Cookie、Token 或邮件。对完整 payload、服务端内部草稿的推断不在
+本轮证明范围内。表单 enctype 或未知字段不同的其他领区应停止发现,不能猜测兼容。
+
+## 5. 假设验证与离线测试计划
+
+| 假设或风险 | 离线证明 | 现场证明 |
+|---|---|---|
+| 只在明确选择时复用本地账号 | 默认不加载;开关选中完整凭据;文件错误停止;配置无 persistent profile | 用户暂停同账号 Query,在独立浏览器确认账号/领区 |
+| Form 准备属于当前申请人 | page/tab/账号/登录代次/route mutation 都停止 | 目标服务、单人/旅游选项与账户一致 |
+| OTP/AVANTI 只能一次 | 故障注入、重复请求、前后计数;中断不再点击 | 总计各 1 次;错误时不手工重跑 |
+| AVANTI 确实进入当前 Calendar | 原生 302、跟随 200、错误 tab/目的地/返回表单 fixtures | Network 与最终 DOM 一致 |
+| 不复用 Query 时段 | 实际 CS4B 在假浏览器中重查并回读;触发没有旧时段 | 新月份响应与屏幕选中时段一致 |
+| 选择不等于预约成功 | Book 返回 false、无成功字段、final=0 | 最终按钮保持禁用,预约/候补数量不变 |
+| 日历无号不假装通过 | 入口无号/范围内无号返回 2,passed=false | 换日期范围须人工决定,不自动扩大 |
+| 错误不泄密 | 注入含凭据/OTP/响应的异常,输出仅阶段和安全分类 | 回传 allowlist 结果行,不回传 OTP、请求正文或截图个人信息 |
+| 工具没有改变 Query | 只新增独立文件;核对共享依赖版本并运行列出的 Italy 回归 | 旧 Query 现场结果不冒充本轮 Book 证据 |
+
+## 6. 现场准出与返回码
+
+正向 Gate 必须全部满足:
+
+- 申请人会话完成当前服务的一次准备;Book 专属 route 记录有效。
+- `entryBookCalls=1`、`calendarBookCalls=1`。
+- 总 `otpRequests=1`、`avantiPosts=1`、`finalRequests=0`。
+- Book 期间 Availability 请求至少 1,OTP/AVANTI/最终请求增量均为 0。
+- 选择快照、`last_booking_precommit` 和偏好日期匹配;`bookResultSuccess=false`。
+- 预约与候补数量分别前后相同;监听、审计、浏览器清理无报告错误。
+
+返回码:`0` 本地预检通过或正向停点验收通过;`1` 合同/网站错误;`2` 本轮无正向号源;
+`3` 清理失败;`130` 人工中断。只有 `--run` 的 `passed=true` 才是现场正向停点证据。
+
+最终按钮保护与被动计数不是服务端写屏障;数量不变也不证明没有不可见草稿或临时状态。
+超时仍是各步骤预算,不声称覆盖浏览器底层连接的整体硬墙钟上限。
+
+## 7. 执行与验证记录
+
+### 7.1 v1 的离线验证记录(v2 见第 9 节)
+
+实施前相关基线测试:144 项通过,exit 0。没有启动真实浏览器或读取真实凭据。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_debug_ita_book_gate
+```
+
+最终专项测试 40 项通过,exit 0,无跳过。运行真正的两段 `ItaPlugin.book()`、Book 准备登记、
+Q-CAL preflight/OTP 输入回读/跳转校验/请求审计和 CS4B 日历编排;仅浏览器、登录和预约列表
+读数使用假对象。两个 Node 测试执行实际组合后的 JS,包括阻止错页面修改与正常的原生 hidden
+同步。测试输出不是网站验证证据。
+
+首轮 39 项测试通过,但清理故障注入的 mock 在测试对象析构时又抛出一次异常;已在测试清理
+阶段撤销故障注入,最终运行不再有这段输出。没有为此修改生产析构或清理逻辑。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
+  test.test_add_ita_query_account test.test_debug_ita_book \
+  test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate \
+  test.test_debug_ita_monitor test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak \
+  test.test_ita_calendar_book test.test_ita_calendar_book_flow \
+  test.test_ita_calendar_query test.test_ita_local_handoff test.test_ita_plugin \
+  test.test_ita_protocol test.test_ita_route_wiring
+```
+
+上述显式列出的 Italy 回归 336 项通过,exit 0,无失败、无跳过。最后一次运行输出
+`Ran 336 tests in 3.424s ... OK`。其他任务正在增加 Query 恢复能力,因此这里不宣称覆盖
+随后新增、未在该命令中列出的测试。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --help
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -c 'from pathlib import Path; paths = [Path("tools/debug_ita_book_gate.py"), Path("test/test_debug_ita_book_gate.py")]; [compile(path.read_bytes(), str(path), "exec") for path in paths]; print("COMPILE_OK files=2")'
+git diff --check
+```
+
+均返回 0;帮助只显示 CLI,编译输出 `COMPILE_OK files=2`,没有差异空白错误。
+新增文件另作尾随空白检查,因为 `git diff --check` 不覆盖 untracked 文件。
+
+`shasum -a 256` 返回 0。本轮只新增前述三个文件,没有编辑任何生产插件或 Query 工具。
+第一次回归后,工作区出现并行 Query 恢复改动(同时新增 `docs/ita_query_recovery.md`);
+后续 336 项回归仍通过。记录该次检查的共同依赖版本:
+
+- `plugins/ita_plugin.py`:开始为 `9fd72adedd9c67e4ba847311a634567d61a5b52e5c7230ba86ef55e0866653e1`,
+  后续为 `f56b0f4fa5b74633dc6b671673231ff654d21cbe1ec63951abec1090859b59ea`。
+- `plugins/ita_calendar_query.py`:开始为 `e78e19d0f39a6a71e6dcd0474e7353ade63a0f79fb91f5e0ef2b0676616c4802`,
+  后续为 `508dd8435515d7ed8bc75ff5a5cc0bd40e2aa94136b3086764b98d8c8aabdb83`。
+- `tools/debug_ita_calendar_gate.py`:开始为 `98021ab36ba8342210cc4deb6da1180328f85a9ef27c351f14ff77a472dda145`,
+  收尾回归时为 `85df8a093fdf3b796716eebb224d69e6e5b4dbc39cf3adcc1bf022f236621335`。
+
+其余已核对文件 `ita_calendar_book.py`、`ita_protocol.py`、`debug_ita_book.py`、
+`config_sentinel.json` / `config_booker.json` 保持本轮开始时的哈希。
+工具打印的组合 `source_sha256` 包含共享依赖,后续修改会使它变化;不能把本次日志当作
+未来版本的验证。全部并行/既有修改保留,没有 commit 或部署。
+
+### 7.2 初见审查
+
+反驳:“这又是一个只测 helper 的调试脚本,不能说明生产 Book 已接通。”
+
+回应:新测试运行真正 Book 的表单分支,再经受控准备登记运行真正 Calendar 分支,而不是
+mock 掉 `book()` 的返回值。现场工具也走相同调用路径。但它仍是**人工准备入口**,并没有
+把 OTP/AVANTI 接进普通订单调度,所以不能宣称生产 Book 已完整实现;这一缺口明确列在下节。
+
+反驳:“都选好时段了,为什么仍返回 Book 失败?”
+
+回应:本轮的 `VSBookResult.success=false` 是有意的提交前停点。工具独立输出
+`selectionVerified=true` / `passed=true`,仅代表安全验收通过,不误触发现有 Booker 的
+预约成功回写和通知。最终提交能力接入后才允许返回真实成功。
+
+### 7.3 负责人现场命令
+
+以下是香港示例,命令本身不含密码;申请人账号必须能访问该服务。先用 `--preflight` 做
+本地校验;准备好后将最后的 `--preflight` 改为 `--run`,只执行一次。
+以下命令使用已授权复用的本地账号。不要在命令中重新填写或清空 `ITA_BOOK_USERNAME/PASSWORD`。
+
+```sh
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 \
+python -B tools/debug_ita_book_gate.py --use-local-query-account --preflight
+echo "EXIT_CODE=$?"
+```
+
+`--use-local-query-account --run` 会读取已有本地账号、打开全新浏览器;无需再次输入账号密码,
+只需在收到邮件后输入可见 OTP。不带账号复用开关时,保留原有 Book 环境变量/交互输入行为。
+脚本自行选择已配置的单人/旅游、勾选 Privacy、发送一次 OTP、点击一次 AVANTI、选择时段。
+如出现人工验证,在该浏览器中自行处理;不要手工重发 OTP、点击 AVANTI 或最终 Prenota。
+本工具不会上传文件或最终预约。结束自动清理本工具浏览器,不保留现场用于之后提交。
+
+需要限制日期时,在末尾增加例如 `--expected-start-date 2026-10-01 --expected-end-date 2026-12-31`。
+日期不是预约承诺;工具只在当前返回、配置月数及你的偏好交集中查询。
+
+只回传 `ITA_BOOK_GATE_TOOL_CONTRACT`、`ITA_BOOK_GATE_SELECTION`、`ITA_BOOK_GATE_RESULT`、
+`ITA_BOOK_GATE_CLEANUP_OK` 和 `EXIT_CODE`。若失败再附 `ITA_BOOK_GATE_FAILED` / 脱敏诊断;
+不要回传 OTP 输入行、密码、完整请求/响应或个人信息截图。失败后先看原因,不直接重复执行。
+
+## 8. 与 VFS/BLS 同等级质量对齐的最短上线路线
+
+负责人最新要求:不追求完美,做到与既有 VFS/BLS 相同的交付质量。
+本轮只收敛后续计划,没有因此扩大当前实现或解除最终提交授权。
+
+源码参照:VFS `book()` 使用用户 Session、`_read_otp_email()` / `fetch_mail_content()`、重新查
+Calendar/TimeSlots,最终依据 `IsAppointmentBooked` 生成 `VSBookResult`;BLS 同样复用云端
+取信、重新取时段并返回统一结果。`OrderBookerGCO` 已从订单读取用户账号并创建独立实例。
+Italy 应复用这些现成层次,不另建邮件平台或任务系统。
+
+| 节点 | 剩余交付 | 通过标准 |
+|---|---|---|
+| 1. 提交前完整验收 | 本文新工具已离线验证,待现场 | 申请人登录→手工 OTP→AVANTI→真实时段→安全停止;final=0 |
+| 2. 接成普通生产 Book | 将准备编排接入生产,复用现有云端取信 API | 普通订单调用无需调试工具或人工输 OTP;账号、收件人和发送时间匹配 |
+| 3. 最终提交与成功结果 | 基于当前页面原生提交,识别真实响应和预约记录 | 真正预约后返回编号/日期/时间;无号、已预约和结果不明确分开处理;不盲目重提 |
+| 4. 一个真实订单闭环并小范围开启 | 复用现有信号、Booker、回写和通知 | Query→用户 Book→本站确认→订单成功回写/通知;关键异常测试通过,可关闭 Italy 配置回退 |
+
+1 是当前最短路径;2 与 3 可以在证据齐备后分别实现,最后合并做 4。不再把额外通用工作流
+重构、完整新邮件管理平台、所有领区现场验证作为首个领区上线前提。
+
+首发范围:通用单人短期申根旅游的**已验收领区配置**,先用香港完成真实闭环;核心实现不
+写香港分支。其他领区按同一配置/协议验证后启用,不能从香港一例宣称全球已验证。
+
+最低保留项是正确使用申请人账号、不误报成功、敏感值不进日志、结果不明不盲目重复提交。
+优先使用现有订单领取、任务状态和异常处理;若现有能力不足,只补 Italy 必需的小范围保护,
+不默认把跨进程写屏障平台化改造列为本轮前置。这里是规模收敛,不是已经证明现有任务机制
+具备跨进程 exactly-once,也不是放弃重复预约风险的验收。
+
+确信度:CS4C 离线合同为高;自动接码、最终提交及真实订单上线证据仍未取得。
+
+## 9. v2:按负责人授权复用已保存账号
+
+负责人明确“用一个就行,这个账号可以复用”。将其落实为本地验收的显式开关
+`--use-local-query-account`,不改变生产 Book 从订单取得申请人账号的合同。
+本次仅编辑本工具、其专项测试和本文,没有修改 Query、账号文件或生产配置。
+
+实现仍用组合:`_book_credentials()` 调用现有 `load_local_account()`,复用路径、权限、
+JSON 与必填字段校验。开关选中后,整对凭据来自已保存文件;不带开关仍用原 Book 输入路径。
+不复用 Query profile、Cookie、登录状态、Calendar 准备标记或旧时段。
+本地文件错误会停止,错误输出不包含加载器原始详情,不回退到另一个账号。
+源码指纹新增两个公共加载模块,但不包含账号配置文件或秘密值。
+
+### 9.1 验证记录
+
+均在本地执行,未启动浏览器、读取邮箱、发送 OTP、提交 AVANTI 或最终预约。
+
+| 命令 | 返回值与结果 |
+|---|---|
+| `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_debug_ita_book_gate` | exit 0;46 项通过,无跳过 |
+| 第 7.1 节显式列出的 16 个 Italy 测试模块命令 | exit 0;342 项通过,`Ran 342 tests in 3.135s ... OK` |
+| 第 7.3 节配置搭配 `--use-local-query-account --preflight` | exit 0;`external_requests=0 credentials_read=false browser_created=false` |
+| `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --help` | exit 0;显示新开关 |
+| `git diff --check` | exit 0 |
+
+另用真实加载器校验已有文件,命令不包含实际账号密码,输出仅为来源与存在性:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -c 'from tools.debug_ita_book_gate import _book_credentials; ita_book_username, ita_book_password = _book_credentials({}, use_local_query_account=True); assert ita_book_username and ita_book_password; print("ITA_BOOK_LOCAL_CREDENTIALS_OK username_present=true password_present=true external_requests=0 browser_created=false"); del ita_book_username, ita_book_password'
+```
+
+exit 0,输出 `source=local_query_file` 与 `ITA_BOOK_LOCAL_CREDENTIALS_OK`。
+这证明本地文件能被当前加载器接受,不证明网站登录有效。
+本次 CLI 预检标识为 `book-prefinal-manual-v2`,组合源码指纹为 `ab74bc1f9753`;
+共享依赖后续修改时指纹可能变化,不能据此复用旧的真实网站验收结果。
+
+新增测试覆盖:显式来源优先级、凭据不混用、默认不读本地文件、预检不读凭据、
+文件错误不回退且不泄密、完整 Book 假浏览器链路继续使用独立准备与最终请求为零。
+
+### 9.2 初见审查
+
+反驳:“用同一个账号,会不会把 Query 的状态直接当成 Book 的准备结果?”
+
+回应:只复用凭据,Book 仍创建临时浏览器并重新登录、完成自己的 OTP/AVANTI、登记自己的
+准备记录、重查时段。专项测试验证没有 persistent profile 或 Query 准备标记。
+同账号两个会话在服务器上是否互相影响尚未验证,现场请先暂停该账号的 Query;
+本次验收不宣称跨账号交接已验证,也不宣称预约已成功。
+
+## 10. v2 现场失败与 v3 最小修复
+
+### 10.1 用户回传事实(不保存 OTP 输入行)
+
+- OTP 发送 1 次,DOM 回读匹配;发送后前置检查为 ready。
+- AVANTI POST 1 次;失败阶段为 `calendar_preparation`,异常类型 `BizLogicError`。
+- `entryBookCalls=1`、`calendarBookCalls=0`,故不能把自动加载的 1 次 Availability 请求说成 Book 扫描。
+- `finalRequests=0`;预约和候补数量分别前后都是 0。
+- 清理阶段另报 `cleanup_listener / AttributeError`,最终 `passed=false`、exit 3。
+
+### 10.2 定位与实施边界
+
+清理问题已用本机安装的 DrissionPage `Listener.stop()` 离线复现:第一次 stop 后将
+`_driver` 设为 None,第二次仍执行 `_driver.stop()`,会抛 AttributeError。
+共享 `listen_once()` 已在 finally 停止监听,本工具末尾再停一次是错误的生命周期调用。
+测试假对象此前支持重复 stop,没有覆盖真实 SDK 行为。
+
+业务失败已缩小到 Book 准备登记,尤其是 `read_calendar_service()`;但原始异常被脱敏为
+通用消息,不能证明真实原因是缺控件、空值、长度、页面加载时序或其他情况。
+不得据此放宽标识长度限制、用 Services ID 替换 Calendar ID,或自动重复 OTP/AVANTI。
+
+v3 只改 Book 验收工具、其测试和本文:
+
+1. 清理时只关闭仍在监听的 listener;真正的活动监听清理异常仍报错。
+2. Calendar 准备失败时输出只读诊断:路径是否匹配、控件数量、值类型/长度等,不输出值。
+3. 对准备登记的四条已知固定错误映射稳定原因码;其他异常仍不输出原始详情。
+4. 用安装 SDK 的实际停止行为和非幂等测试 listener 覆盖回归;保持 final=0 与一次准备预算。
+
+完成标准:专项及显式 Italy 回归 exit 0;重复清理不再覆盖原始业务失败,诊断不泄露值。
+真实 Calendar 标识错误仍需新诊断才能定案,本轮不声称其已修复。
+
+### 10.3 v3 验证记录
+
+- 安装 SDK 的 `Listener.stop()` 离线重复调用实验:exit 0,输出
+  `LISTENER_DOUBLE_STOP_REPRODUCED external_requests=0`。使用 mock driver,没有创建浏览器。
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_debug_ita_book_gate`:
+  exit 0,54 项通过,`Ran 54 tests in 0.184s ... OK`。
+- 第 7.1 节显式列出的 16 个 Italy 测试模块命令:exit 0,350 项通过,
+  `Ran 350 tests in 3.412s ... OK`。未把测试中的 Q-CAL 日志当作网站证据。
+- 第 7.3 节配置及 `--use-local-query-account --preflight`:exit 0,
+  `external_requests=0 credentials_read=false browser_created=false`。
+- `git diff --check`:exit 0。新增文件另作尾随空白检查。
+
+版本为 `book-prefinal-manual-v3`,本次组合源码指纹 `0c11e4d186d8`。
+只修改工具、对应测试和本文,没有修改生产插件、Query、配置文件或安装的浏览器库。
+
+新增 8 项测试覆盖安装 SDK 的真实重复 stop 失败、活动监听正常清理与真实清理故障、
+非幂等 listener 下的完整流程、控件缺失/值类型/空值/空白/超长值拒绝、诊断自身失败不覆盖
+原业务错误、诊断不输出 runtime ID,以及只允许已知固定错误的原因码。
+
+### 10.4 初见审查与下一次现场取证
+
+反驳:“之前测试全过,为什么实际还会重复关闭出错?”
+
+回应:此前的 FakeListener.stop 支持重复调用,与当前 SDK 不符。现在 Book Gate 使用
+非幂等假对象,并有直接调用已安装 SDK 方法的回归;不能再用宽松替身掩盖这个差异。
+这只关闭已复现的清理错误,不证明其余真实浏览器行为都已覆盖。
+
+反驳:“后补诊断若显示控件正常,是否证明原异常是误报?”
+
+回应:不是。诊断明确标记 `afterFailure=true`,是失败后的额外只读快照。页面可能在两次
+读取之间变化,需结合 `reason`、`readSucceeded`、`snapshotKeysMatch`、`tabIdPresent`、
+控件数量以及值形状判断;不以此自动刷新、换标识或重复提交。
+
+以下为 v3 发布时的历史操作指引,现已由第 11 节取证结果取代,不应再次直接执行:
+
+下一次使用第 7.3 节相同配置,带 `--use-local-query-account --run`,只执行一次,先确认
+输出版本为 v3。该执行会重新登录并再次发送一次 OTP;不要连续重跑或手工重复点击 AVANTI。
+回传 `ITA_BOOK_GATE_TOOL_CONTRACT`、`ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC`(若有)、
+`ITA_BOOK_GATE_FAILED`、`ITA_BOOK_GATE_RESULT` 和退出码即可,删除验证码输入行。
+
+## 11. v3 现场回传:Calendar 已到达,运行时字段为空(2026-08-30)
+
+### 11.1 已观察事实与边界
+
+本节保存负责人回传的脱敏结果,不保存 OTP、账号或运行时标识值。
+
+- OTP DOM 回读匹配,发送后 preflight 为 ready;OTP=1、AVANTI POST=1。
+- 失败后的 Calendar 诊断为:路径匹配、tab ID 存在、快照键集合正确、
+  `#idServizio` 控件恰好 1 个,值类型为字符串、长度为 0、`valueAccepted=false`。
+- 明确错误码为 `calendar_service_unidentified`,阶段为 `calendar_preparation`。
+- `entryBookCalls=1`、`calendarBookCalls=0`:尚未执行 Book 的日历扫描和时段选择。
+- Availability 请求 1 次不能归因为 Book 扫描;`finalRequests=0`。
+- 预约和候补均为 0→0;`CLEANUP_OK`,exit 1。v2 的 listener 清理错误此次没有复现。
+
+确信度:上述日志事实为高。快照是 afterFailure 读取,不能证明最初读取时刻的全部状态,
+也不能仅凭空字符串确定网站赋值失败或页面加载过慢。
+
+### 11.2 为什么看到了 Reservation
+
+工具在 finally 中调用现有 `read_reservation_snapshot()`,通过新标签访问 `/Reservation`
+核对预约/候补数量;DrissionPage 的新标签默认在前台打开。因此用户在失败后看到 Reservation
+与本工具的对账行为一致,并不说明站点把 Book 的日历步骤替换成了预约列表。
+正常路径仍为 OTP/AVANTI→Calendar→重查日期和时段;此次中断在 Calendar 准备登记。
+
+### 11.3 尚缺的证据与下一步
+
+源码 `CaricaTimelineVerticale()` 已证明 TimeSlots 的 `idService` 从 `#idServizio` 读取,
+但既有取证没有证明该字段始终非空,也没有保存它的赋值逻辑。
+现有 Book 实现和测试把“非空运行时服务标识”设为前置条件;测试成功只能证明检查行为,
+不能倒推这个前置条件符合真实网站。
+
+需要区分以下假设,当前不批准其中任何一项作为修复依据:
+
+1. 字段由异步初始化填入,Book 读取过早。
+2. 字段只在日期/日历交互后填入,当前准备顺序不符合网站生命周期。
+3. 字段为空是该页面允许的请求形态,服务实际由其他上下文绑定;当前非空约束过强。
+
+下一步只读定位 Sources 全局搜索 `idServizio` 的命中及其调用上下文,必要时核对已发生的
+`RetrieveTimeSlots` 请求中 `idService` 的存在性、类型和空值状态。不得输出实际标识、
+Cookie、OTP 或完整请求;不得为了取证重发请求、调用初始化函数或点击最终预约。
+若需要改变运行时绑定合同,应先用网站证据确定替代的服务一致性校验,再调整 Book 和测试。
+不能直接删除校验、把配置的 Services ID 填入该字段,或先添加任意 sleep 试运气。
+
+该业务失败已在 v2/v3 两次现场执行中出现,不再要求负责人盲目重跑完整 OTP/AVANTI 流程。
+本轮 Chrome 只读标签清单仅取得 `/Reservation`;尝试在独立标签打开已知 Calendar URL 时
+控制调用超时,后续原浏览器句柄报告不可用。未取得 Calendar DOM 或赋值源码,不能把控制
+超时说成站点登录失败;也无法断言该次导航未在浏览器端发生。没有主动发送 OTP、提交表单、
+选择日期/时段或执行最终预约。
+
+### 11.4 本轮验证与初见审查
+
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_debug_ita_book_gate`:
+  exit 0,54 项通过(0.179s);不包含真实登录或真实时段选择。
+- `rg` / `sed` / `jq` 只读核对 Book、Query 共用工具、已存文档和指定附件:exit 0;
+  取得字段读取逻辑,未取得字段写入逻辑。
+- 本轮只更新本文;没有修改 Book、Query、配置或测试实现。
+
+反驳:“既然能进入 Calendar,直接允许空字段继续选择不就好了?”
+
+回应:进入 Calendar 证明导航成功,不证明服务绑定正确;但反过来,也不能未经证实就断定
+空字段必定错误。应先取得网站的实际初始化和请求证据,再保留必要的账号、路由、页面、
+日期及时段一致性检查。这是纠正协议假设,不是无限增加防御或放弃校验。
+
+## 12. 后续 v3 回传:预约基线为 1,仍停在 Calendar 准备(2026-08-30)
+
+Phase: DISCOVERY(本地修复已有授权,但根因证据尚不足,未实施猜测性修复)
+Scope: 空运行时标识的来源;不重复 OTP/AVANTI,不提交或修改现有预约。
+
+### 12.1 本次日志,不与第 11 节历史基线混合
+
+- `contract=book-prefinal-manual-v3`;Calendar 路径、快照键集合、tab 均通过形状检查。
+- `controlCount=1`、`valueType=str`、`valueLength=0`、`valueAccepted=false`。
+- `stage=calendar_preparation`、`reason=calendar_service_unidentified`。
+- `entryBookCalls=1`、`calendarBookCalls=0`;尚未调用生产 Book 的 Calendar 重查分支。
+- 请求计数:OTP 1、AVANTI 1、Availability 1、最终提交 0。
+- **预约 1→1,候补 0→0**;清理成功,exit 1。本轮开始前即有 1 条预约,不能称为本轮创建,
+  也不能仅凭数量判断其服务、日期、来源或是否导致本次错误。不删除、不取消这条预约。
+- 不保存用户日志中的 OTP 值或输入行。
+
+### 12.2 代码事实、未证实假设和执行决定
+
+`_wait_for_calendar()` 只等待 URL 到达 Calendar 和文档加载完成;紧接着 Book 准备登记
+调用严格的 `read_calendar_service()`。该读取要求一个 `#idServizio` 和非空字符串。
+这证明了“当前代码为什么拒绝”,并未证明“网站为什么为空”。
+
+只读等待存在可行的实现位置,但现在不能假定等一段时间就会填值。第 11.3 节中的异步赋值、
+交互后赋值、合法空字段三种解释仍未排除。因此本次不添加固定延时或轮询,不放宽读取校验,
+也不以配置中的 Services ID 替代 Calendar 运行时标识。此前提出的有界等待方案暂缓。
+
+下一证据入口:在已恢复的 Calendar 中只读检查 `idServizio` 的赋值源码,以及已经发生的
+`RetrieveTimeSlots` 请求里 `idService` 的存在性、类型、是否为空;不读取 Cookie/OTP,
+不回放请求,不为了取证调用初始化函数或选日期。确认协议事实后再选最小修复及回归用例。
+
+### 12.3 本轮验证与初见审查
+
+- Chrome 技能连接成功;`user.openTabs()` 只读列出 1 个 Prenot@Mi 标签,路径为
+  `/Reservation`。没有 Calendar 标签;未接管、导航、刷新、点击或提交任何页面。
+  这不是登录失效证据,也不是“Calendar 永久不存在”的结论。
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_plugin`:
+  **exit 0,167 项通过,2.300 秒**。只证明当前离线合同,不证明真实 Book 成功。
+- `git diff --check`:exit 0;本轮只补本文,未修改插件、工具、测试或配置。
+- 真实 Book 仍未通过;未重跑真实登录、OTP、AVANTI 或任何最终提交。
+
+反驳:“既然控件存在但为空,加等待是否能最快修好?”
+
+回应:只有空值确实是短暂初始化状态时才成立。如果站点允许空参数,等待再久也不能修好。
+优先取得一次真实请求和赋值证据,可以避免把同一业务失败再次交给用户用 OTP 试错。
+
+### 12.4 用户恢复 Calendar 后的只读取证尝试
+
+- 用户回复“已经恢复了”。Chrome `user.openTabs()` 与随后 `tabs.list()` 均返回
+  `Calendar - Prenot@Mi`、`/BookingCalendar`,确认标签已恢复;未输出查询参数。
+- 第一次接管/DOM 读取组合调用超时,未返回字段快照。随后按 Chrome 技能的
+  `browser-troubleshooting` 指引,尝试同一 Chrome 标签的 CDP 能力文档,亦超时。
+  两次后停止重试;没有切换浏览器、刷新、导航、发送 OTP、选择日期或提交预约。
+- 这些超时不能证明字段是否为空、账号是否过期或网站初始化是否失败。技能的连接边界
+  使本次直接取证暂停,改由用户读取 Network 中**已经发生**的 `RetrieveTimeSlots`
+  请求,确认载荷 `idService` 的空值状态;不回放请求、不索要完整请求或实际标识值。
+- 本轮仅补证据记录,未修改实现;未重跑业务测试,因为没有业务代码变更。
+
+## 13. 字段赋值来源已取得,实际空值语义仍待验证(2026-08-30)
+
+来源:负责人从当前网页 Sources 提供 `ValorizzaComponentiPagina(JsonServerInfo)` 和
+`CaricaTimelineVerticale(_Giorno, _ContenutiEventi)` 函数源码。以下为静态源码证据,
+不是已观察到函数执行完成或成功请求的证据。
+
+### 13.1 已确认的生产者与消费者
+
+`ValorizzaComponentiPagina()` 先从 `JsonServerInfo.substring(0, 10)` 取得日期字符串,
+初始化年/月控件,随后依次执行:
+
+```javascript
+_Servizio = JsonServerInfo.split(',')[1];
+$("#idServizio").val(_Servizio);
+CaricaTimelineOrizzontale(Mese, Anno, Oggi, _Servizio);
+```
+
+`CaricaTimelineVerticale()` 则读取这个字段,并使用既有 `EseguiAsync()` 发起时段查询:
+
+```javascript
+_idService = $("#idServizio").val();
+// RetrieveTimeSlots 的请求对象:
+{ selectedDay: _Giorno, idService: _idService }
+```
+
+确信度高:在这条初始化路径中,写字段发生在调用月份日期加载之前,不是必须选中时段后
+才写入。该函数将拆分得到的同一变量传给横向日期加载,并将其写入纵向时段加载要读的控件。
+这不证明它与配置中的 Services 入口 ID 相等,也不允许用配置值替换真实页面值。
+
+### 13.2 不把静态顺序当成现场根因
+
+- 所提供代码没有校验逗号第二段存在或非空;赋值语句存在不等于填入了有效非空标识。
+- 尚未取得此函数的调用点、实际参数、其他字段写入点或失败现场的请求载荷。
+  名称 `JsonServerInfo` 本身不能单独证明对应网络请求的响应格式或 callback 接线。
+- 本地 `_wait_for_calendar()` 仅等待 Calendar URL 和 `doc_loaded()`,并不显式等待该
+  初始化函数完成。因此存在就绪检查缺口,但不能据此宣称它就是本次空值的原因。
+- 之前现场已累计 1 次 Availability 请求。若该请求确实来自上述初始化调用,则发起前已
+  执行字段赋值;仍需区分赋空值、另一路初始化、后续改写或读取时序,不能只加延时结案。
+- 此前“必须交互后才赋值”的说法不适用于这段初始化路径;未证明其他路径不存在。
+
+最小下一证据:在当前 Calendar 的 Network 中读取一个**已经发生**的
+`RetrieveTimeSlots` 请求,只确认 Payload 的 `idService` 是非空、空字符串还是缺失。
+不要回放请求、重新发送 OTP、主动触发日期点击或输出字段实际值。
+若已有成功时段响应且参数为空,则必须重新评审非空前置约束;若参数非空,再核对 DOM
+及初始化就绪时机。当前页面证据不能自动追溯为先前失败 Session 的事实。
+
+### 13.3 验证及初见审查
+
+- `rg` / `sed` 核对本地 Calendar 等待、Book 准备登记、字段读取和既有记录:exit 0。
+- 本轮只追加本文;未改 Book、Query、工具、测试或配置。业务测试未运行,理由是没有
+  实现变更,离线测试无法补出网站真实参数。
+
+反驳:“已经找到赋值函数,为什么还不直接加一个等待?”
+
+回应:可见的同步顺序是先赋值、后请求日期;若源数据就是空的,等待不会改善结果。
+一次既有请求的字段形状核对可以区分不同修复方向,避免再次让负责人用 OTP 试错。
+
+## 14. 恢复现场的 TimeSlots 请求使用非空服务标识(2026-08-30)
+
+负责人回传当前已发生的 `RetrieveTimeSlots` 请求载荷:
+
+```json
+{"selectedDay":"2026-10-13","idService":"4937"}
+```
+
+- 确信度高:所提供载荷有 `idService` 字段,类型为字符串且非空;值与本次香港配置的
+  Services 入口 ID 相等。此处保存的是已知业务服务 ID,不保存账号、OTP、Cookie 或 Token。
+- 本次未提供对应 HTTP 状态码或响应体;不能仅凭请求载荷宣布该请求成功、当天有号,
+  或认为已证明服务器拒绝/接受空参数。
+- 当前恢复后的请求不能追溯为前一次失败 Session 的字段状态,也不能证明所有领区都使用
+  相同 ID 关系。继续保留从当前页面读取标识的合同,不改为配置值兜底。
+- 结合第 13 节归档源码,下一步只读比较当前 `#idServizio` 的原生 `.value` 与 jQuery
+  `.val()` 是否都与这条请求一致;检查控件数量,以区别字段就绪变化与读取方式差异。
+  不刷新、不选日期、不发起新请求。
+
+本轮只记录取证进展,未改实现,未运行业务测试;`git diff --check` 和本文尾随空白检查
+作为文档校验。真实 Book 尚未通过。
+
+## 15. 非空 TimeSlots 请求证据与 v4 就绪等待(2026-08-30)
+
+### 15.1 事实与修复置信边界
+
+负责人提供当前页面已发生的 `RetrieveTimeSlots` 请求载荷:
+
+```json
+{"selectedDay":"2026-10-13","idService":"4937"}
+```
+
+这证明该次请求携带非空字符串标识,且恰与当前 Services 入口 ID 数值相同;不证明所有
+领区或所有会话都相同,亦不构成“直接使用配置值”的依据。未同时提供该请求的状态码和
+响应,不能仅凭载荷宣称有号或预约成功。不得将它追溯为此前失败 Session 的请求。
+
+结合第 13 节赋值源码,可确认现有实现有一个就绪检查缺口:`doc_loaded()` 后直接严格读
+运行时字段,没有专门等待网站填值。补条件等待的设计依据已具备;但“早读就是先前失败的
+唯一根因”仍未证实。如果字段持续为空,v4 仍会停止,不把等待当作保证成功的办法。
+
+### 15.2 文件归属、复用和完成标准
+
+Phase: IMPLEMENTING→离线 VERIFIED;真实 Book 验收未通过。
+Approval: 延续负责人已授权的 Book 本地修复;无真实 OTP、AVANTI、最终预约、部署或提交。
+
+采用现有 Italy Book 的组合式浏览器适配器和 `monotonic` 条件轮询模式,不另建工作流或
+通用等待框架。严格字段读取、会话判断、日历 final guard、请求监听和协议解析继续复用。
+
+- `plugins/ita_calendar_book.py`:增加 `wait_for_calendar_service()`,复用结构化字段读取;
+  `read_calendar_service()` 在稳定阶段仍严格拒绝空值。在 Book 原生日历加载动作后等待
+  同一个已记录服务重新就绪,再处理已被 listener 捕获的响应;不为等待重复刷新或发请求。
+- `tools/debug_ita_book_gate.py`:AVANTI 后、登记准备状态前等待,默认最多 5 秒轮询;
+  成功即返回,不固定睡满 5 秒。等待后重新采样请求预算,不把这段时间的请求计入 Book
+  扫描增量。版本改为 `book-prefinal-calendar-ready-v4`。
+- 对应三个 Book 测试文件:补就绪、超时、漂移和刷新后的回归;本文保存来源和验收边界。
+- 未改 `plugins/ita_plugin.py`、Query 适配器、Q-CAL 工具、共享类型或生产配置。
+
+仅一个结构正确控件的**精确空字符串**属于可等待状态。缺控件、多控件、非字符串、空白、
+过长值、离开 Calendar、tab/申请人/路由变化及已记录服务变化均停止,不当作“尚未加载”。
+每轮检查上下文,并保持现有最终按钮 guard;不写服务值、不选日期、不触发网络或提交。
+5 秒是轮询预算,不是浏览器底层传输的硬墙钟上限;传输错误不会被循环吞掉或重试。
+
+持续空值在工具准备阶段输出 `calendar_service_not_ready`,保留现有脱敏快照和事后对账;
+不重复发送 OTP/AVANTI。其他字段识别错误仍用 `calendar_service_unidentified`。
+
+机械完成标准:就绪即返回、延迟就绪可继续、持续空值有界失败、结构/会话/服务漂移失败、
+刷新后等待不增加刷新次数、原有严格读取不变;聚焦及显式 Italy 回归 exit 0,预检无外部
+请求或凭据读取。该标准不包含真实时段选择或最终预约成功。
+
+### 15.3 验证记录
+
+第一轮聚焦测试 144 项中 1 项失败,原因是将字段读取移到等待函数后,底层传输异常未再
+经过工具原有的固定错误分类。已在工具边界恢复脱敏分类;等待函数仍不重试传输异常,
+申请人绑定错误继续原样传播。没有放宽测试或字段校验来消除失败。
+
+以下为修正后的实际结果,均不访问真实网站:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate test.test_ita_calendar_book test.test_ita_calendar_book_flow
+```
+
+exit 0,144 项通过,1.215 秒(新增 14 项)。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_route_wiring
+```
+
+exit 0,364 项通过,3.456 秒;这是显式列出的 16 个模块,不是对工作区所有测试的声明。
+测试产生的 Q-CAL 日志来自替身,不是现场请求证据。
+
+- 第 7.3 节香港配置搭配 `--use-local-query-account --preflight`:exit 0;
+  `external_requests=0 credentials_read=false browser_created=false`。
+- `git diff --check`:exit 0;新增/未跟踪文件另作尾随空白检查。
+- 本次预检版本 `book-prefinal-calendar-ready-v4`,源码指纹 `0bdd665ba78c`;
+  共享依赖变更会改变指纹,不能用这个值替代实际执行版本核对。
+
+### 15.4 初见审查与现场准出
+
+反驳:“等待会不会把切换到另一个账号/服务当成加载完成?”
+
+回应:等待前后检查申请人、路由、tab 和 Calendar 路径,刷新后还要求服务与准备记录一致;
+非空但不匹配不是待重试状态。稳定阶段的严格读取没有改成宽松等待。
+
+反驳:“新增测试是不是又只证明了理想替身?”
+
+回应:是离线行为证据,不能替代现场。因此只宣称就绪检查缺口已修复并通过离线验证,
+不宣称历史空值根因已唯一确定。下一次真实验收需核对 v4:若就绪继续,必须观察到
+`calendarBookCalls=1`、新时段响应和提交前选择回读;若仍超时,停止并按持续空值调查,
+不通过加长等待或盲目重发 OTP 继续试错。所有情况下 final 必须为 0,预约/候补对账不变。
+现场命令沿用第 7.3 节的明确路由配置和 `--use-local-query-account --run`;本轮没有执行。
+
+## 16. 恢复页面的 DOM/网站读法一致,复核已有 v4(2026-08-30)
+
+### 16.1 用户回传的当前页面证据
+
+```json
+{
+  "path": "/BookingCalendar",
+  "fieldCount": 1,
+  "ourRead": [{"empty": false, "matchesRequest": true}],
+  "websiteReadMatchesRequest": true
+}
+```
+
+比较基准为第 14 节已经发生的请求中的业务服务 ID。确信度高:这次恢复后的页面有且只有
+一个目标控件,原生 `.value` 与网站 jQuery `.val()` 均为非空,且都与请求一致。
+没有证据支持更换这两种读取方式或放宽非空约束;仍不能追溯证明旧失败 Session 的根因。
+
+### 16.2 不重复开发,验证工作区已有实现
+
+开始本轮代码核对时,工作区已经具有第 15 节的 v4、条件等待及回归测试。本轮直接复用和
+审查这些修改,没有重新实现等待,没有改插件、工具、测试、配置或现有用户改动。
+
+已核对以下行为:
+
+- 准备阶段使用网站当前字段值,不用 `4937` 或其他配置值兜底;已就绪时立即返回。
+- 精确空字符串只在初始化边界内等待;最多 5 秒的轮询预算,不重复 OTP/AVANTI。
+- 稳定阶段仍严格读取;Book 刷新后要求服务与准备记录一致。页面、tab、会话变化立即失败。
+- 等待结束后重新核算准备请求,不能把等待期间的请求冒充后续 Book 的新扫描。
+- 新的真实验收仍应停在最终确认前,final=0;已有预约基线可以为 1,但必须前后不变。
+
+### 16.3 新执行的验证,而非沿用旧测试结论
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring
+```
+
+exit 0,**415 项通过,3.433 秒**。显式覆盖 18 个 Italy 模块,包括 Calendar soak 和 Query
+恢复回归;不是工作区全部测试,也不是 415 次网站请求。
+
+```sh
+ITA_ROUTING_KEY=slot.hkg.it.tourist ITA_SERVICE_ID=4937 ITA_CITY='Hong Kong' ITA_VISA_TYPE='Tourist' ITA_CALENDAR_LOOKAHEAD_MONTHS=12 ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl ITA_BOOKING_TYPE_VALUE=1 ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' ITA_PURPOSE_CONTROL_ID=ddls_0 ITA_PURPOSE_VALUE=42 ITA_PURPOSE_LABELS='Turismo|Tourism' PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --preflight
+```
+
+exit 0;`book-prefinal-calendar-ready-v4`,组合源码指纹 `0bdd665ba78c`;
+`external_requests=0 credentials_read=false browser_created=false`。
+
+本轮真实 Book 未执行,仍为待验收,不声称已经选中时段或预约成功。下一次只需负责人在
+自己的终端执行同配置 `--run`;默认交互输入 Book 账号,只有明确需要复用已存账号时才加
+既有 `--use-local-query-account`。不得在终端输出回传中包含 OTP 或密码。
+
+初见审查反驳:“当前页面读到了非空值,是否证明 v4 必然修好旧失败?”
+
+回应:不能。当前恢复页面与旧 Session 是两份证据。v4 已离线证明能够等待延迟赋值且
+持续空值仍会明确失败;能否跨过旧现场失败点,必须看下一次实际执行,不能许诺 100%。
+
+## Book v4 现场验收与 v5 选择阶段诊断(2026-08-30)
+
+### 本次现场事实,不与其他会话的基线混合
+
+负责人运行 `book-prefinal-calendar-ready-v4`,组合指纹 `0bdd665ba78c`。
+只保存下列业务和结构证据,不保存回传日志中的 OTP、账号或浏览器指纹值。
+
+| 阶段 | 已观察结果 |
+|---|---|
+| 申请人登录 | 新临时浏览器,凭据来自已授权的本地账号文件;到达 `/UserArea` |
+| 准备 | OTP 1 次、DOM 写入匹配、AVANTI POST 1 次;进入 Calendar,准备登记通过 |
+| Book 日历分支 | `calendarBookCalls=1`,8 月候选日期 0、9 月 0、10 月 14 |
+| 失败 | `stage=production_book`、`type=BizLogicError`;v4 未输出具体原因 |
+| 全程请求统计 | Availability 4、OTP 1、AVANTI 1、final 0 |
+| 对账与退出 | 预约 0→0、候补 0→0,`CLEANUP_OK`,`passed=false`,exit 1 |
+
+这次真实执行越过了先前的 Calendar 准备登记失败,并执行了 Book 日历扫描;但不能据此
+证明过去空值的唯一原因。十月的 14 是正向日期候选数,不是已选定时段、已锁定名额或
+预约成功数。`bookRequestDelta=null` 表示未完成最终回读统计,不能解释为没有请求。
+
+根据日志位置和源码,失败范围在正向日期后的检查、日期/时段处理或其错误清理中;仍不能
+判断是否已经点击日期、是否收到目标日的时段响应、是否因控件被遮挡而停下。
+v4 的总计不包含 TimeSlots 次数,不能从 Availability=4 反推出这些动作。
+
+### 诊断缺口与本轮实施范围
+
+`_book_prepared_calendar()` 将适配器固定错误传为 `BizLogicError`,但验收工具 `_failure()`
+只对白名单内的 `calendar_preparation` 错误输出原因。`production_book` 下日期控件、
+时段响应和选择回读的不同错误都变成同一句通用输出。这是目前可确定的可诊断性缺口,
+不能拿任意一个候选业务原因直接实施点击或重试修复。
+
+Phase: IMPLEMENTING→离线 VERIFIED(仅诊断);Approval: 延续 Book 调试授权。
+本轮只改验收工具、其专项测试和本文;不改生产 Book 适配器、Query、配置、选择条件、
+等待时长、请求重试或最终提交规则。不新建日志框架,复用现有固定错误白名单模式。
+
+v5 `book-prefinal-selection-diagnostic-v5` 增加:
+
+1. `ITA_BOOK_GATE_FAILED.reason`:已知日期、时段、上下文和回读错误输出固定原因码。
+   例如 `date_control_timeout`、`timeslot_service_mismatch`、`slot_dom_timeout`、
+   `precommit_readback_rejected`。协议动态错误仅输出固定分类,不输出动态 code;未知错误
+   仍为 `unclassified_book_failure`,不直接打印原始异常正文或 traceback。
+2. `ITA_BOOK_GATE_SELECTION_DIAGNOSTIC`:只在生产 Book 失败后、Reservation 对账前,
+   读取当前 Calendar。输出控件数量、服务值是否存在、选中日期是否一致、首个 selected
+   是否为日期链接、final guard 状态,以及最多 12 个当前时段的可见性/遮挡/尺寸等布尔值。
+3. 不输出日期字段值、时间文本、运行时 ID、请求/响应正文、凭据或验证码。Python 接收端
+   限定键集合、类型、计数范围及列表长度;不符时只报 `readSucceeded=false`,不部分泄露。
+4. 诊断本身不点击、不滚动、不刷新、不写字段、不发请求;失败不覆盖原始错误。仍按原流程
+   对账并清理,不留下浏览器或自动开始第二次预约准备。
+
+快照明确标记 `afterFailure=true`,不能当作异常瞬间状态。`timeSlotResourceEntries` 是当前
+页面 Resource Timing 中可见的资源条目数,可能受保留范围影响,不是新增的网络审计总数。
+未被标红的时段也不自动等于有库存;可见性状态不能替代响应和日期/服务绑定检查。
+
+### 本轮验证
+
+机械完成标准:已知失败分类可区分、未知消息不泄漏;只读诊断能区分视口外与遮挡,格式
+异常/自身失败不破坏原错误;完整失败流程仍只准备一次、final=0、完成对账与清理。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate
+```
+
+exit 0,66 项通过,0.260 秒。测试包含静态原因文案与真实生产源码一致性、原始异常脱敏、
+诊断早于对账、未知字段/错误类型、传输失败保持原错误,以及 Node 合成 DOM 的视口外/
+被遮挡/超过 12 项情形。Node fixture 禁止点击和读取时段文本或隐藏 ID;它是离线脚本测试,
+不是网站截图或真实页面布局证据。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_route_wiring
+```
+
+exit 0,375 项通过,3.562 秒。覆盖的是以上 16 个模块,不宣称所有工作区测试都已运行。
+期间工作区已有同步补充的错误分类回归被保留;按最终文件重新执行了测试。
+
+- 第 7.3 节香港配置加 `--use-local-query-account --preflight`:exit 0;
+  `external_requests=0 credentials_read=false browser_created=false`。
+- 最终预检版本 `book-prefinal-selection-diagnostic-v5`,组合指纹 `b95134494446`。
+- `git diff --check` 及本轮未跟踪文件的尾随空白检查:exit 0。
+- 未运行真实登录、取信、OTP、AVANTI 或最终预约;本轮修复的是诊断,不是选时段故障本身。
+
+### 初见审查与下一次现场回传
+
+反驳:“怀疑时段没滚到屏幕里,为什么不直接加滚动或强制点击?”
+
+回应:当前日志没有证明失败在可见性检查;也可能是日期、服务或响应不匹配。强制点击会
+跳过原本有价值的检查。先输出固定原因和只读布局状态,再决定是否需要针对性的滚动修复。
+若将来快照显示时段在屏幕外,也必须结合具体原因和响应绑定,不能仅凭一个布尔值改业务。
+
+下一次沿用第 7.3 节完整配置及 `--use-local-query-account --run`,核对版本为 v5,
+只执行一次,不手动点击 AVANTI、重发 OTP 或最终 Prenota。回传:
+
+- `ITA_BOOK_GATE_TOOL_CONTRACT`
+- `ITA_BOOK_GATE_FAILED`(含 reason,若失败)
+- `ITA_BOOK_GATE_SELECTION_DIAGNOSTIC`(若失败)
+- `ITA_BOOK_GATE_RESULT`、`ITA_BOOK_GATE_CLEANUP_OK`、`EXIT_CODE`
+
+删除 OTP 输入行及任何个人资料。若同一阶段再失败,先依据诊断定位,不连续重跑。
+
+## 17. v4 已跨过准备阶段,候选日期后的失败与 v5 诊断复核
+
+### 17.1 本次现场事实(2026-08-30)
+
+用户执行版本 `book-prefinal-calendar-ready-v4`、指纹 `0bdd665ba78c`,与第 16 节预检一致。
+下列记录已去除账号、OTP、Session/端口等无关值,不保存原始终端输入:
+
+- 真实登录到 `/UserArea`;OTP 写入回读成功;OTP=1,AVANTI=1。
+- `CALENDAR_READY transition=followed_redirect_200 final_requests=0`:本轮已跨过空字段准备失败。
+- 生产 Book 月份日志:2026-08 candidates=0、2026-09 candidates=0、2026-10 candidates=14。
+- `FAILED stage=production_book type=BizLogicError`;原始原因未被 v4 工具输出。
+- `calendarBookCalls=1`、`entryBookCalls=1`;Availability=4,final=0,`bookRequestDelta=null`。
+- 预约 1→1、候补 0→0,清理成功,exit 1,`passed=false`。
+
+确信度高:已进入实际 Book 扫描,不再停在 Calendar 准备登记;14 是候选日期数量,不是
+已经拿到的时段数或预约数。结合当前 `_capture_month()` 的调用顺序,候选日志产生前已
+处理该月自动日期的 TimeSlots 并检查日期回读。失败范围为后续候选日的选择、时段响应、
+时段 DOM 匹配或提交前回读等;不能仅凭该日志判定按钮不可见、竞争失号或某个断言错误。
+
+### 17.2 当前 v5:仅改诊断,不猜测性放宽业务条件
+
+本轮读代码时,工作区已有 `book-prefinal-selection-diagnostic-v5` 及其新增测试,直接
+复用审查。v5 在生产 Book 失败时、预约数量对账和清理之前:
+
+1. 将已知固定错误映射为具体原因码;未知字符串不原样输出,协议错误只输出固定类别。
+2. 只读读取 Calendar 页面状态,输出字段/选中日期/时段的数量、布尔值,以及时段是否
+   有尺寸、在视口内、中心是否被遮挡。每次最多输出 12 个时段的形状,不读取日期、时间、
+   runtime ID、Cookie、OTP 或用户文本。`timeSlotResourceEntries` 是当前页面已有的
+   performance 资源条目数,不作为精确 HTTP 请求次数或响应成功的证明。
+3. 诊断标记 `afterFailure=true`;失败后快照不能冒充错误发生瞬间的状态。
+   诊断自身失败也不覆盖原业务错误,不点击、滚动、刷新、发码或回放请求。
+
+本轮额外修正一处已复现的问题:内部失败映射原先少了生产插件实际消息的 `Italy ` 前缀,
+导致该错误仍被输出为 `unclassified_book_failure`。新增专项测试先失败(exit 1),再仅
+修正精确消息映射并通过;未知消息依旧脱敏。更改位于既有 Book 验收工具及对应测试,
+不改生产 Book/Query 决策、框架、配置或最终提交边界。
+
+### 17.3 新执行的验证
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_plugin
+```
+
+exit 0,**191 项通过,2.332 秒**。
+
+第 16.3 节列出的相同 18 个模块命令重新执行:exit 0,**425 项通过,3.595 秒**。
+这包括新增诊断、账号/请求预算边界、真实诊断 JS 的离线执行、Book/Query 与恢复回归。
+这些是离线测试,不把日志中的替身请求计为网站证据。
+
+第 16.3 节相同香港环境变量配置及 `--preflight`:exit 0,
+`book-prefinal-selection-diagnostic-v5`、指纹 `b95134494446`;
+`external_requests=0 credentials_read=false browser_created=false`。
+
+真实 v5 运行未执行,业务失败原因仍待具体 `reason` 与
+`ITA_BOOK_GATE_SELECTION_DIAGNOSTIC`;不可声明“选择失败已修复”。负责人下一次执行相同
+配置 `--run` 仅为一次带诊断的定位;若失败,回传原因/诊断/汇总及退出码,不回传 OTP。
+
+### 17.4 初见审查
+
+反驳:“为什么测试通过,却仍需要再取一次现场日志?”
+
+回应:测试证明诊断能把已知失败分开、未知敏感信息不会泄露、且不增加预约动作;它无法
+从 v4 已丢失的错误详情恢复真实原因。现在先补可观察性,不以“候选日期存在”推断时段一定
+可选,也不提前滚动或取消防护来掩盖尚未定位的问题。下轮明确原因后只修对应环节。
+
+## 18. v5 明确为日期控件超时,尚缺目标日期的阻塞条件(2026-08-30)
+
+### 18.1 现场证据与定位
+
+用户执行 `book-prefinal-selection-diagnostic-v5`、指纹 `b95134494446`,已通过 Calendar
+准备,扫描 8、9 月无候选,10 月 14 个候选;随后为 `date_control_timeout`,阶段
+`production_book`,exit 1。OTP=1、AVANTI=1、Availability=4、final=0;
+预约 1→1,候补 0→0,清理正常。未保存账号、验证码或完整终端输入。
+
+事后状态:服务控件 1 个且非空;timeline/content 各选中 1 个、日期互相一致,第一个
+selected 是 timeline 日期;3 个时段均无 unavailable/redDot 标志、activeSlotCount=0。
+前两个时段在视口内且中心命中,第三个不在视口内;final guard 有效。
+TimeSlots 资源条目为 3,但此数不是精确网络请求次数或响应成功的证明。
+
+错误唯一对应 `_click_date()` **点击前**的等待超时:目标日期链接数量不为 1,或
+`candidateEnabled=false`。已选中目标日、点击未确认、点击后回读不一致都有别的错误。
+因此不能用第三个时段在视口外解释该错误,更不能据此修改时段点击。
+已有日期脚本允许 timeline 链接处于视口外;其 enabled 条件检查结构、class、CSS、尺寸。
+
+### 18.2 下一步只读探针,不再让用户完整重跑试错
+
+v5 诊断没有记录目标日期链接的阻塞条件;selected 日期互相相等不代表等于目标日期。
+目前不能断言是缺节点、异步禁用 class、CSS 隐藏或尺寸为零。
+
+在用户此前手动恢复的十月份 Calendar 中执行以下探针。仅拆开当前日期脚本的 enabled
+条件,不请求、点击、滚动或写字段,也不读取隐藏服务/时段 ID、账号或 OTP。
+若已没有这张页面,先告知,不要求为探针反复发送 OTP。
+
+```javascript
+(() => {
+  const links = [...document.querySelectorAll('.events a[data-date]')];
+  return JSON.stringify({
+    path: location.pathname,
+    linkCount: links.length,
+    dates: links.map(e => {
+      const c = e.classList, s = getComputedStyle(e), r = e.getBoundingClientRect();
+      const blocked = {
+        detached: !e.isConnected,
+        disabled: e.hasAttribute('disabled') || e.getAttribute('aria-disabled') === 'true' || c.contains('disabled'),
+        unavailable: c.contains('notAvailableDay'),
+        asyncDisabled: c.contains('input-async-disabilitato'),
+        asyncEnabledMissing: !c.contains('input-async-abilitato'),
+        hidden: s.display === 'none' || s.visibility === 'hidden',
+        pointerBlocked: s.pointerEvents === 'none',
+        transparent: !(parseFloat(s.opacity || '1') > 0),
+        noSize: !(r.width > 0 && r.height > 0)
+      };
+      return {
+        date: e.dataset.date,
+        selected: c.contains('selected'),
+        blockedBy: Object.keys(blocked).filter(k => blocked[k])
+      };
+    })
+  }, null, 2);
+})()
+```
+
+`blockedBy=[]` 只表示当前链接通过 enabled 条件,不证明有号,也不能追溯失败时状态。
+列表还可用于核对目标日期是否缺失或重复;应依据具体阻塞条件选择修复方式。
+
+### 18.3 验证与初见审查
+
+- `node -e` 隔离 VM 验证:exit 0,
+  `DATE_BLOCKER_PROBE_TESTS_OK cases=12 browser_created=false external_requests=0`。
+  覆盖正常、缺异步启用 class、异步禁用、宽/高为零、隐藏、pointer-events、业务禁用、
+  aria-disabled、断开连接、透明以及空列表。
+- 本轮只补文档及其中的诊断片段,没有修改 Book/Query/工具/配置,未运行真实预约。
+- 未凭猜测延长等待、强制点击或移除校验;真实故障尚未修复。
+
+反驳:“已知日期控件超时,直接删除 enabled 检查能否推进?”
+
+回应:组合条件为 false 不说明每个条件都多余;删掉它可能点击站点明确禁用的日期。
+先取得具体阻塞条件,只纠正错误假设,不把诊断测试通过说成 Book 已成功。
+
+## 19. 日期链接零尺寸的真实证据与 v6 最小修复(2026-08-30)
+
+Phase: VERIFIED(日期尺寸判断的离线回归);真实 Book 的完整提交前链路仍待验收。
+Approval: 沿用 Book 修复授权;不执行真实 OTP/AVANTI/最终预约,不改账号或生产配置。
+
+### 19.1 证据与根因边界
+
+用户按第 18 节探针读取到 `/BookingCalendar` 的 22 个日期链接:
+
+- 日期为 2026-10 的 01、02、05、06、07、08、09、12、13、14、15、16、19、20、21、22、
+  23、26、27、28、29、30 日;22 个全部包含 `blockedBy=noSize`。
+- 其中 10 月 13 日已选中,并额外包含 `pointerBlocked`。
+- 其余 21 个未选中日期仅有 `noSize`,没有结构断开、原生/ARIA/class 禁用、异步禁用、
+  缺异步启用 class、不可用日期标记、元素自身隐藏、pointer-events 或透明度阻塞。
+
+确信度高:当前日期脚本的尺寸门槛会拒绝这些未选中的真实链接。
+第 18 节 v5 错误为点击前 `date_control_timeout`,而既有站点源码的
+`InizializzaTimelineOrizzontale()` 使用日期链接自身的 `.click()`。
+据此确认的是“现有尺寸前置条件与观察到的日期 DOM 不兼容”;恢复页面仍不是旧失败瞬间,
+不宣称已经证明历史失败的所有因素,也不宣称真实 Book 已通过。
+
+### 19.2 改在哪里、为什么只改这一处
+
+复用现有组合式 Book 适配器,不新增浏览器层、通用重试框架或地区分支:
+
+- `plugins/ita_calendar_book.py`:仅在 `DATE_SELECTION_SCRIPT` 中移除
+  `getBoundingClientRect()` 及 width/height 正数条件。原本就调用链接 `.click()`,
+  不是依赖坐标的鼠标点击,因此日期动作不应以矩形尺寸作为必要条件。
+- 服务/页面一致性、单一目标日期、DOM 连接、原生/ARIA/class 禁用、异步启用、
+  不可用标记,以及元素自身 display/visibility/pointer-events/opacity 检查均保留。
+- 已选中的日期不重复点击。站点日期响应、所选日期回读和当前申请人绑定仍必须通过。
+- 时段选择的尺寸、视口和遮挡检查完全不变;没有强制点击时段或最终按钮,也没有取消
+  Calendar final guard。Query、OTP、预约状态及生产配置均未修改。
+- `test/test_ita_calendar_book_flow.py`:复用 Node 执行实际日期 JS 的既有测试架;
+  增加零宽、零高、零尺寸的正向回读,以及已选中且 pointer-blocked 的不重复点击用例。
+  旧 fixture 把“宽度为零”命名为 hidden,此次分离为真实 display:none 与零尺寸状态,
+  保留真正隐藏元素拒绝的断言,并补零尺寸同时禁用/隐藏/pointer-blocked 的拒绝用例。
+- `tools/debug_ita_book_gate.py`:仅将执行合同标识更新为
+  `book-prefinal-native-date-v6`,沿用 v5 的全部诊断与一次性动作预算。
+
+### 19.3 先复现,再修正,最后回归
+
+先增加零尺寸回归,在未改生产代码时运行:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_calendar_book_flow.BookDateJavaScriptTests.test_zero_size_enabled_dates_follow_native_click_and_readback
+```
+
+exit 1;1 项测试中的 zero_width、zero_height、zero_size 三个子用例均失败,
+均为 `candidateEnabled=false`。不是凭测试通过反推根因。
+
+修正后:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_calendar_book_flow.BookDateJavaScriptTests
+```
+
+exit 0,5 项通过,0.546 秒;覆盖原生日期动作及选择回读,最终点击次数为 0。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_plugin
+```
+
+exit 0,194 项通过,2.568 秒。
+
+第 16.3 节相同 18 模块 Italy 回归命令:exit 0,**428 项通过,3.835 秒**。
+该节相同香港环境变量与 `--preflight`:exit 0;
+`version=book-prefinal-native-date-v6 source_sha256=37ece5fab296`;
+`external_requests=0 credentials_read=false browser_created=false`。
+离线替身日志不作为网站请求证据。文档及未跟踪修改另做尾随空白检查。
+
+### 19.4 初见审查与下一步
+
+反驳:“去掉尺寸检查,会不会把业务禁用或没有号的日期也选上?”
+
+回应:尺寸不是号源信号。候选仍来自当前 Book 的正向 Availability 响应,并受用户日期
+偏好过滤;目标唯一、业务禁用、会话和服务一致性等约束未删。点击后还必须取得目标日
+TimeSlots 并回读当前日期,最终预约始终禁用。此次只纠正原生日期动作对布局尺寸的依赖。
+
+下一次真实验收由负责人在自己的终端执行同配置 `--run`。该轮只允许一次 OTP/AVANTI,
+确认前停止;回传选择/失败诊断、RESULT 与退出码,不回传验证码。若出现新的时段错误,
+按新的具体原因处理,不把本次日期修复宣称为整个 Book 已完成。
+
+## 20. v6 真实提交前验收通过(2026-08-30)
+
+### 20.1 来源与脱敏记录
+
+来源:负责人在自己的终端执行此前提供的香港单人旅游配置
+`python -B tools/debug_ita_book_gate.py --run`,回传结果及 `EXIT_CODE=0`。
+此处是用户执行的真实现场证据,不是助手在本轮新执行的网络测试。
+结果合同为 `book-prefinal-native-date-v6`;准备阶段指纹为 `1bf9f2b4783f`。
+该次回传未包含 Book 工具开头的 source_sha256,不补写为已观察到。
+不记录账号、OTP 输入、Cookie、Token、申请人资料或运行时隐藏标识。
+
+已观察:OTP 写入回读匹配、Calendar 通过 `followed_redirect_200` 到达;
+Book 重新扫描 2026-08、09、10 月,候选日期数分别为 0、0、14,
+选中当前申请人会话内的 2026-10-13 09:15 - 10:00,选择时余量 3。
+余量是该次现场快照,不保证随后仍有号,也不等于持有名额。
+
+```json
+{
+  "contract": "book-prefinal-native-date-v6",
+  "exitCode": 0,
+  "outcome": "pre_final",
+  "passed": true,
+  "selectionVerified": true,
+  "bookResultSuccess": false,
+  "entryBookCalls": 1,
+  "calendarBookCalls": 1,
+  "selectedDate": "2026-10-13",
+  "selectedTime": "09:15 - 10:00",
+  "remaining": 3,
+  "requests": {
+    "availabilityRequests": 4,
+    "avantiPosts": 1,
+    "finalRequests": 0,
+    "otpRequests": 1
+  },
+  "bookRequestDelta": {
+    "availabilityRequests": 3,
+    "avantiPosts": 0,
+    "finalRequests": 0,
+    "otpRequests": 0
+  },
+  "reservationCountBefore": 1,
+  "reservationCountAfter": 1,
+  "waitlistCountBefore": 0,
+  "waitlistCountAfter": 0
+}
+```
+
+另有 `ITA_BOOK_GATE_CLEANUP_OK`。`bookResultSuccess=false` 是本阶段正确合同:
+选中并回读不等于服务器确认预约,不应为了测试成功把业务成功字段改为 true。
+
+### 20.2 验收结论与剩余边界
+
+- 确信度高:本次真实登录、表单准备、手工 OTP、一次 AVANTI、生产 Book 重查与日期/时段
+  选择回读均完成;之前的日期控件超时在本轮未再出现,提交前 gate 通过。
+- 最终预约请求为 0;预约 1→1、候补 0→0。本次没有创建已确认的预约记录,
+  但数量一致并不能证明服务器内部没有草稿或其他未公开状态。
+- 不能据此宣布完整 Book 成功、所有地区通用性已现场验证或生产上线就绪。
+  自动接码/重新需要 OTP 仍是 `ITA-OTP-01`,不随本次通过自动消除。
+- 下一阶段应定义并验证最终提交与回执/预约列表的一致性合同,优先复用现有框架和 VFS/BLS。
+  请求结果不明时先核验服务器状态,不能盲目重发最终提交。
+- 已有 1 条预约的服务和状态未知;真实最终提交前必须确认不造成重复预约。
+  不取消现有预约、不自动再运行、不因本次成功自动扩大最终提交权限。
+
+### 20.3 本轮记录与初见审查
+
+本轮仅更新本文和当前阶段状态;没有修改生产代码、工具、配置或测试。
+文档验证使用 `git diff --check` 及针对未跟踪本文的显式尾随空白检查,
+同时解析本节 JSON 并断言 gate、选择、请求预算和预约前后计数一致。
+实际返回:`git diff --check` exit 0;`awk` 尾随空白检查 exit 0、
+`CS4C whitespace: OK`;`.venv/bin/python -B -c` JSON 合同断言 exit 0、
+`CS4C_V6_EVIDENCE_OK external_requests=0`。
+本轮不重跑应用测试:仅有文档变更,上轮离线验证保留在第 19 节,不冒充新执行结果。
+
+反驳:“passed=true,为什么还不能说预约成功?”
+
+回应:passed 指验收工具完成了它的合同,而本工具的合同恰好是最终提交前停止。
+finalRequests=0、bookResultSuccess=false、预约数量不变共同限定了成功的范围。
+必须另有最终提交响应及与申请人、服务、日期、时间一致的持久预约记录,才可报告预约成功。
+
+## 21. 旧预约已由用户取消;进入 CS5 离线开发(2026-08-30)
+
+负责人确认原有 1 条预约属于相同香港签证服务,并已自行取消。这是用户报告,尚未读取
+取消后的列表;不把原基线直接改为 0,也不推断取消记录一定从表格消失。
+
+负责人随后授权最终阶段开发与离线测试,真实提交仍须确认具体日期/时段后另行执行。
+实现、复用依据、469 项 Italy 回归及未完成的生产接线见 [CS5](./ita_book_cs5.md)。
+没有运行最终预约,没有让原 pre-final 工具获得最终提交能力。

+ 1969 - 0
docs/ita_book_cs5.md

@@ -0,0 +1,1969 @@
+# CS5:最终提交与预约结果核验
+
+最新状态(2026-08-31,第 30 节):最终核心和本地 Book 验收入口已接通本次提交归属与
+VSBookResult.success 回传,book-final-attribution-v9 / 1949de666430;626 项 Italy
+离线回归及无网络预检通过。新增请求证据与真实回执字段分开保存;响应格式未知时,
+仍可凭已匹配的单次请求、唯一新增确认回执和未变历史核验成功,并保留网站分配时刻。
+第 29 节真实只读验收仍有效,但不能倒推旧 v8 已具备本次新增的请求匹配证据。
+本轮未访问真实网站、重新预约、取消或清除 claim;生产 final 仍关闭,
+生产任务状态/持久未知结果阻断、自动 OTP 与原 v8 响应 unknown 的具体根因仍待完成。
+第 31 节新增生产链路审查:已离线复现未知结果被再次调用,以及后端回收覆盖 pause/grabbed;
+仅在插件内部补暂停不足以解决,需要明确共享任务后端的最小改动范围后继续实现。
+下文初始合同及早期“待采集”描述保留为历史记录,以后续证据节为准。
+
+日期:2026-08-30。Phase: VERIFIED(仅最终阶段核心的离线合同;生产接线仍未开放)。
+Scope: 复用既有 Book 的选择结果,补一次性原生提交、结果分类与只读对账。
+Non-goals: 不运行真实预约,不接自动 OTP,不开启生产 final,不改共享调度器。
+Done: 默认关闭;提交最多一次;有效旧预约阻止提交;取消记录不冒充有效预约;
+仅唯一匹配的新有效预约可返回成功;结果不明不重提;Italy 回归通过。
+Approval: 负责人“没问题,开始吧”承接“开发与离线测试,真实提交另行确认”的授权。
+Evidence/Risks: v6 提交前真实链路已通过;最终响应只有站点源码证据,预约列表的字段、
+状态和分页语义尚未采集,禁止凭空写真实 HTML 解析器。
+
+## 1. 可复用能力与代码归属
+
+- VFS `book()`:依据站点结果填充 `VSBookResult` 的 account、urn、book_date、book_time。
+- BLS `book()`:沿用同一结果类型,但其业务成功阶段不同,不能复制其网页字段到 Italy。
+- `ita_protocol.py`:复用 `PrecommitApproval`、日期/时段及正向库存合同。
+- `ita_calendar_book.py`:复用原有时段 DOM 回读和校验;仅提取公共的只读复核入口。
+- `ita_calendar_query.py`:复用同源 URL 检查、`listen_once` 的监听生命周期。
+- 新 `plugins/ita_booking_final.py`:单一最终阶段模块,组合上述能力;内部预约记录是
+  规范化领域对象,不声称是网站实际 JSON/HTML schema。
+- 新 `test/test_ita_booking_final.py`:纯数据、替身浏览器和实际 JavaScript 的离线验证。
+
+不新增调度/邮件/浏览器框架,不复制 Query 的状态。生产 `ItaPlugin.book()` 和原验收工具
+保持 pre-final;本阶段新增模块不被它们自动调用,也不新增可执行真实最终提交的 CLI。
+
+## 2. 已知事实与未验证假设
+
+已知源码:`#btnPrenotaNoOtp` 原生 handler 使用当前 `.fascia.act` 的隐藏 ID、
+完整 innerText 与 `.selected` 日期,POST `/BookingCalendar/InsertNewBooking`;
+回调读取 `errorMessage`、`url`。因此调用原生按钮,不手写最终 POST。
+
+未验证:真正成功/失败返回体、成功跳转页面、预约编号与服务标识所在列、取消/有效/候补
+状态、列表分页与加载完成标志。只实现独立的规范化读取接口;没有受验证的生产读取实现
+时不能接生产 final。非空 errorMessage 只是拒绝线索,不擅自解释为“失号”。
+
+用户确认旧的同服务预约已取消;这是用户报告,尚未取得取消后的列表证据。
+列表总数量不等于有效预约数,不能假定取消后总数量必须为 0。
+
+## 3. 技术合同
+
+1. 目标绑定申请人、route、服务和本次 Book 的 PrecommitApproval;最终调用须再次显式启用。
+2. 提交前读取当前申请人的完整预约快照。未知状态、未完成加载、分页不完整、上下文变化
+   均停止;同服务有效预约或候补阻止新增,取消记录保留在基线但不算有效预约。
+3. 复核选中状态,监听器先启动,再在同一同步 JS 中复核并仅临时启用原生最终按钮点击一次,
+   随即恢复禁用。不点击日期、时段或发 OTP,不跟随猜测的成功 URL 主动导航。
+4. 请求方法、同源路径、当前 tab、提交字段与当前选中值必须一致;响应只有 schema 合格
+   才分类为接受/拒绝线索。HTTP 200 或 errorMessage 为空都不能单独证明预约成功。
+5. 无论超时还是收到响应,只做只读对账。完整快照中出现唯一匹配申请人、服务、日期、时间
+   的新有效预约编号,且无冲突时才返回 `VSBookResult(success=True)`。
+6. 拒绝线索与完整快照无新增记录一致时返回明确失败;接受线索但没有记录、响应与记录冲突、
+   读取失败、错账号/服务或多条记录均为结果不明。结果不明抛固定安全错误,不伪装为可重试无号。
+7. 一次性对象进入执行即消耗;重复调用不能重发。结果不明只允许再次读取预约列表。
+
+一次性对象和 DOM 标记仅提供进程/页面内保护,不宣称跨进程 exactly-once。
+这里的一次指最多一次原生按钮动作;`listen_once` 取得一个 packet 不能单独证明整轮
+只发生一个 HTTP 请求。未来真实验收须继续复用 Q-CAL 的 `CalendarRequestAudit` 统计,
+不能把资源计数或单个响应当成完整网络审计。
+当前 OrderBooker 的失败分支会在下一信号重试,现有 tracker 不是提交结果账本。
+生产接线前必须落实既有任务状态的暂停/人工对账路径;如果现有机制不足,需要另行确认
+最小持久保护改动,不在本阶段暗中新增 Redis/数据库平台。
+
+## 4. 开发与测试计划
+
+先补只读选择复核并跑既有 Book 回归;再补最终模块及以下用例:
+
+- 默认关闭、未授权、错页面/tab/service/账号、选择失效均无提交。
+- 正向与已取消历史、已有有效预约、候补、未知状态、不完整快照、重复编号。
+- 原生点击、字段绑定、最终按钮重新禁用、重复调用不点击。
+- 合格响应+新记录成功;拒绝+无记录失败;超时+新记录只读恢复成功。
+- 接受但无记录、矛盾响应、错日期/时间/服务、多记录、读取异常均不误报成功。
+- 固定错误不泄露响应正文、Token、runtime ID 或申请人数据。
+- Query/原提交前入口不导入最终模块,final 配置仍拒绝开启。
+
+JS 用合成 DOM 执行真实脚本;预约快照明确是合成领域数据,不能用测试通过证明真实 HTML
+解析能力。源码与测试通过后再请负责人提供只读的预约列表表头/状态结构;不要求再发 OTP。
+
+## 5. 准出边界
+
+本地阶段:上述离线合同通过、现有 Italy 回归通过、默认入口仍不最终提交。
+真实阶段另行批准:先完成列表和成功回执证据接线,再由负责人确认具体日期/时间及执行
+一次真实预约。尚无真实回执时不宣称完整 Book 已修好或已可上线。
+
+## 6. 初见审查
+
+反驳:“为什么不直接沿用预约数量 0→1 就判成功?”
+
+回应:列表可能包含取消记录,且另一服务的预约也会增加数量;必须核对申请人、服务、
+日期、时间、状态和新编号。当前证据只支持数量检查,因此生产读取接线应等真实字段证据,
+不能靠扩大 success 判据跨过缺口。
+
+## 7. 实现与实际验证结果
+
+已实现:
+
+- `verify_precommit_selection()` 提取同一套只读日期/时段批准逻辑,原有选择路径调用同一
+  helper;不添加刷新、点击或请求。库存仍是选择时的快照,不能宣称锁号。
+- `FinalTarget` 明确绑定账号、登录代次、tab、route、服务、运行时服务及选中结果。
+- `NativeFinalSubmitter` 先复核选中,再通过既有 listener 包住一次原生按钮动作。
+  点击所在同步 JS 复用真实 `SLOT_SELECTION_SCRIPT`,检查后仅暂时启用按钮,finally 恢复。
+- `classify_final_packet()` 检查同源、POST、tab、HTTP 类型、实际提交字段和值形状,
+  拒绝重复表单/JSON 字段、跨源跳转、未知 schema。原始错误文案不会成为异常消息。
+- `FinalBookingAttempt` 单次执行;完整的规范化预约基线、取消/有效/候补区分、唯一新记录
+  核对、既有 `VSBookResult` 输出。超时可由只读新记录核实;矛盾或缺失证据维持 unknown。
+  Ctrl-C 在可能提交后也保留 unknown,之后只能只读核验,不能再执行提交。
+- 原生产 flag 仍拒绝开启,原工具不导入最终模块。未新增真实 final CLI、真实预约列表
+  解析器、自动 OTP、跨进程提交屏障或调度器改动;这些不被离线测试“替身实现”冒充完成。
+
+### 7.1 最终执行的命令与结果
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_booking_final
+```
+
+exit 0,**41 项通过,0.553 秒,无跳过**。包含 Node 执行实际组合原生提交 JS;测试的
+click 仅发生在合成 DOM,不是网页操作。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring test.test_ita_booking_final
+```
+
+exit 0,**469 项通过,4.157 秒,无跳过**。这些是显式列出的 Italy 模块,不是全仓库
+测试,也不把替身日志中的请求或 OTP 等待当成真实网站行为。
+
+```sh
+ITA_ROUTING_KEY=slot.hkg.it.tourist ITA_SERVICE_ID=4937 ITA_CITY='Hong Kong' ITA_VISA_TYPE='Tourist' ITA_CALENDAR_LOOKAHEAD_MONTHS=12 ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl ITA_BOOKING_TYPE_VALUE=1 ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' ITA_PURPOSE_CONTROL_ID=ddls_0 ITA_PURPOSE_VALUE=42 ITA_PURPOSE_LABELS='Turismo|Tourism' PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --preflight
+```
+
+exit 0,`book-prefinal-native-date-v6` 指纹 `bcc2da96cd22`;
+`external_requests=0 credentials_read=false browser_created=false`。
+指纹因共享 Book 只读逻辑提取改变;原 v6 真实结果仍只证明其当时的源码版本,新版本
+本轮只有离线回归。该 pre-final 指纹不包含未接入的新 final 模块,不作为 final 实测版本证据。
+
+```sh
+git diff --check
+awk '/[ \t]+$/ { print FILENAME ":" FNR; bad=1 } END { if (bad) exit 1; print "CS5 whitespace: OK" }' plugins/ita_calendar_book.py plugins/ita_booking_final.py test/test_ita_booking_final.py docs/ita_book_cs5.md
+```
+
+两项均 exit 0。显式 awk 覆盖未跟踪文件,不能只依赖 git diff 检查新增文件。
+
+中途一次新增“只读复核时状态改变”测试失败:测试使用了仅点击之后才生效的
+`after_overrides`,但此测试有意不点击;纠正为已有替身的当前状态 `overrides` 后通过。
+没有为让测试通过而放宽生产状态校验。
+
+### 7.2 剩余工作,不当成已完成
+
+1. 只读采集 `/Reservation` 的表头、有效/取消状态、服务/日期/时间/编号的结构,以及
+   DataTables 的数据和分页语义;不发 OTP、不点击预约或取消。
+2. 根据实际字段实现生产只读适配器;现有计数工具不能直接转换成完整预约快照。
+3. 核对真实 final 响应/成功回执,明确失败与结果不明的处理;运行前另行确认具体日期、
+   时间和一次真实预约权限。
+4. 在订单接线前落实持久的未知结果阻断/人工核验,不能让 `VSBookResult(false)` 触发盲重试。
+
+确信度:已执行的离线合同为高;真实预约列表协议、最终成功响应及生产闭环未验证。
+不宣称“完整 Book 已修好”“可直接生产开启”或跨地区全覆盖。
+
+## 8. 预约列表截图:取消记录保留,列表时间为单个时刻(2026-08-31)
+
+### 8.1 直接观察到的内容
+
+来源:负责人提供的“我的预约”列表截图。标题为 `Elenco Appuntamenti`,当前画面
+显示一条数据行和页码 1。截图没有地址栏、DOM 或 Network,因此不把 URL、全部分页、
+表格已完整加载等作为本轮新增已验证事实。不复制截图文件、姓名或完整预约编号。
+
+| 表头 | 含义 | 该行的非敏感证据 |
+|---|---|---|
+| Codice Prenotazione | 预约编号 | 非空、蓝色链接;具体值不记录 |
+| Ufficio | 办公室/部门 | Visti |
+| Servizio | 服务 | Visti Nazionali e Schengen |
+| Data | 日期 | 13 ottobre 2026,即 2026-10-13 |
+| Ora | 时间 | 10:25,单个 HH:mm 时刻 |
+| Stato | 状态 | Annullata,即已取消 |
+| Dati Richiedente | 申请人信息 | 存在姓名文本,具体值不记录 |
+
+确信度高:当前截图中的记录已取消,但仍展示在列表中。因此“预约列表行数大于 0”
+不能推出“有有效预约”,“取消后行数必须变为 0”也不成立。
+当前服务列只有显示名称,没有观察到稳定 service_id;申请人姓名不是登录账号身份的
+替代凭据。单张截图不能证明其他分页没有有效记录,不能据此标记规范化快照 complete。
+
+### 8.2 新发现的合同缺口:时间点不能直接当时间段
+
+当前 CS5 离线领域对象 `ReservationRecord.time_label` 要求 `HH:mm - HH:mm`,
+并与当前选中 `SlotCandidate.time_label` 精确相等。截图中 `Ora=10:25` 不满足这一格式。
+这是实际列表适配之前必须解决的合同缺口,不是将字符串解析一下就能自动接生产。
+
+不能擅自把 10:25 改成某个时间段、仅凭“落在区间内”认定属于目标时段,或删除时间核对。
+该取消记录也不是 v6 提交前测试产生的新预约;v6 的 finalRequests=0。
+目前不知道它当初选择的时间段,不能拿截图反推服务器的具体分配算法。
+
+下一项只读取证:查看该预约编号链接对应的详情,观察是否同时提供预约日期、具体时间、
+时间段、服务及状态,以及是否有可用于关联的结构。记录详情前仍遮住编号、姓名、条码等。
+若详情仍仅有单个时刻,则继续采集该显示值的来源与可关联字段,不猜区间映射。
+本轮没有点击该链接,没有读取其 href,链接是否打开详情仍待负责人观察。
+
+### 8.3 实施边界与验证
+
+- 本轮仅更新本文,没有修改业务代码、测试、配置,也没有操作网站或发送 OTP。
+- 不把取消状态的真实样本等同于有效/成功/候补等其他状态已验证。
+- CS5 的 41 项测试和 469 项 Italy 回归是第 7 节的历史离线结果;本轮未重跑。
+  合成数据通过不能证明当前时间字段合同适合真实预约列表。
+- 本轮验证:`git diff --check` exit 0;本文显式 `awk` 尾随空白检查 exit 0,
+  输出 `CS5 evidence whitespace: OK`。
+
+初见审查:既然已看到 `Annullata`,能否直接完成预约列表适配?
+
+回应:它关闭了“该状态如何表示取消”的可见文本证据,但没有关闭 DOM 读取、分页完整性、
+服务 ID 映射或具体时刻与所选时间段之间的关联。先把这些事实分开,避免取消判断正确、
+却在真正预约成功时因时间格式错误而持续报 unknown。
+
+## 9. 预约详情截图:类型、用途与状态分区(2026-08-31)
+
+### 9.1 直接观察
+
+来源:负责人随后提供预约详情截图。仅摘录以下业务信息,不复制图片、不记录完整预约
+编号、姓名、出生日期、邮箱、电话、地址或邮编。没有地址栏或 DOM/Network 证据。
+
+- `Dati Prenotazione` 区域显示意大利驻香港总领事馆;
+  `Servizio Consolare: Visti`、`Servizio Erogato: Visti Nazionali e Schengen`。
+- `Tipo Prenotazione: Prenotazione Singola`,支持该样本是单人预约。
+- `Data: 13 ottobre 2026`、`Ora: 10:25`、`* Stato: Annullata`。
+- 详情中的编号与前一列表截图相同,仅记录一致性,不保存实际编号值。
+- `Dati Richiedente` 区域另有一个 `Stato`,表示申请人国家,不是预约状态;
+  该区域还显示 `Motivo soggiorno: Turismo`,支持该样本的旅游用途。
+
+确信度高:该已取消样本的列表与详情显示同一天、同一具体时刻和取消状态。
+截图显示的详情区域仍没有所选时间段、时段 ID 或服务 ID,不能据此声称底层完全没有这些
+字段,也不能推断服务器如何从所选时间段分配具体时刻。它不是有效/成功预约状态的样本。
+
+### 9.2 对实现的约束
+
+1. 状态读取必须限于预约信息区域,不能在全文搜索第一个/任意 `Stato`,更不能把申请人
+   国家文本送入预约状态分类。详情区边界和实际 DOM 仍待验证。
+2. “选择的时间段”与“回执里的具体时刻”是两个不同格式;当前离线对象要求两者字符串
+   相等的假设尚不适用于这张真实截图。先取字段来源或关联证据,不直接改成区间包含。
+3. 旅游用途、单人类型和机构名称是本样本的业务证据,不把显示文本当稳定 service_id。
+4. 下一步读取实际 DOM 的节点/字段名称和区域结构,不再索取完整个人信息截图;不执行
+   点击、刷新、请求、发码或写入表单。
+
+### 9.3 只读结构探针
+
+在同一详情页 Console 执行。同步返回 JSON 字符串,不返回 Promise;只输出节点元数据、
+固定字段标签和区域归属,不输出字段值、正文、查询参数值或完整预约路径标识。
+它不是生产解析器;找不到区域、结果截断或 wrong_origin 时不能据此判定解析成功。
+
+```javascript
+(() => {
+  if (location.origin !== 'https://prenotami.esteri.it') {
+    return JSON.stringify({probe: 'ITA-RESERVATION-DETAIL-SHAPE-v1', error: 'wrong_origin'});
+  }
+  const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
+  const key = s => /^[A-Za-z_][A-Za-z0-9_.:-]{0,79}$/.test(s || '') &&
+    !/\d{6,}/.test(s) ? s : (s ? '<redacted>' : '');
+  const meta = e => e ? {
+    tag: e.tagName.toLowerCase(),
+    id: key(e.id),
+    classes: [...e.classList].map(key),
+    childTags: [...e.children].map(c => c.tagName.toLowerCase())
+  } : null;
+  const headings = [...document.querySelectorAll('h1,h2,h3,h4,h5,h6,strong,b')];
+  const booking = headings.find(e => clean(e.textContent) === 'Dati Prenotazione');
+  const applicant = headings.find(e => clean(e.textContent) === 'Dati Richiedente');
+  const labelOf = e => {
+    const m = clean(e.textContent).match(/^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:/);
+    return m ? m[1] : '';
+  };
+  const scope = e => {
+    if (!booking || !applicant) return 'unknown';
+    if (applicant.contains(e) || (applicant.compareDocumentPosition(e) & 4)) return 'applicant';
+    return (booking.compareDocumentPosition(e) & 4) ? 'booking' : 'unknown';
+  };
+  const labels = [...document.querySelectorAll('p,li,div,span,strong,b,td,th')]
+    .filter(e => labelOf(e) && ![...e.children].some(c => labelOf(c) === labelOf(e)));
+  const controls = [...document.querySelectorAll('input,select,textarea')];
+  return JSON.stringify({
+    probe: 'ITA-RESERVATION-DETAIL-SHAPE-v1',
+    onPrenotami: location.origin === 'https://prenotami.esteri.it',
+    pathShape: location.pathname.split('/').map(s => /^[A-Za-z]+$/.test(s) ? s : (s ? '<redacted>' : '')).join('/'),
+    bookingSection: {found: Boolean(booking), element: meta(booking), parent: meta(booking?.parentElement)},
+    applicantSectionFound: Boolean(applicant),
+    fields: labels.slice(0, 20).map(e => ({
+      label: labelOf(e), scope: scope(e), element: meta(e), parent: meta(e.parentElement)
+    })),
+    fieldsTruncated: labels.length > 20,
+    controls: controls.slice(0, 30).map(e => ({
+      tag: e.tagName.toLowerCase(), type: e.getAttribute('type') || '',
+      id: key(e.id), name: key(e.getAttribute('name'))
+    })),
+    controlsTruncated: controls.length > 30
+  }, null, 2);
+})()
+```
+
+### 9.4 验证与初见审查
+
+- `node -e` 合成 DOM 测试 exit 0:`RESERVATION_DETAIL_SHAPE_PROBE_OK cases=2 external_requests=0`,
+  覆盖预约/申请人区域两个同名状态字段、动态 ID 脱敏、无区域/无控件;断言输出不含
+  合成预约号、Token、具体时间或状态值。
+- 增加域名前置检查后,`node -e` 异域拒绝测试 exit 0:
+  `RESERVATION_DETAIL_WRONG_ORIGIN_OK external_requests=0`;异域不读取 DOM。
+- 本轮只更新本文及提供只读探针,没有改生产代码或运行网站操作。未重跑业务测试,
+  因为没有业务代码改动;`git diff --check` 和显式 `awk` 尾随空白检查均 exit 0。
+
+初见审查:截图已显示取消状态,为什么还读 DOM?
+
+回应:人眼可根据区域理解两个 `Stato`,自动程序需要真实节点边界;截图也没有稳定服务
+标识及时间关联字段。探针用于把这些位置查清,不把业务字段缺失误解释为没有预约。
+
+## 10. 详情 DOM v1 实测与字段补采(2026-08-31)
+
+### 10.1 负责人返回的只读证据
+
+来源:负责人运行第 9 节探针后返回的 JSON,不是本线程直接控制浏览器取得。
+
+- 页面在 Prenotami;路径形状为 `/ReservationDetail/Index/<redacted>`。
+- `Dati Prenotazione` 标题为 `h4.font-weight-normal`;其父节点为
+  `div.my-col-6`,直接子节点标签为 `h4`、`div`。
+- 找到了申请人区域标题。
+- 仅匹配到预约区域内的 `Stato`:节点为 `b`,父节点为 `label.align-form`。
+- 存在隐藏控件 `isDetail` 与 `IDTipoStatoPrenotazione`,各自 id/name 同名;
+  还存在打印按钮 `btnStampa` 与隐藏控件 `DetailToPrint`。
+- 本次输出没有读取这些控件的值,也没有得到状态码或完整字段布局。
+
+v1 的候选选择器遗漏了 `label`。已观察到状态字段使用此标签,但尚不能证明其他全部
+字段也使用它;“只匹配一个字段”不能当成“页面只提供一个字段”。
+
+### 10.2 补采范围与仍未关闭的缺口
+
+v2 加入 label,严格限制在已观察的预约区域,若区域不唯一或包含申请人标题即停止。
+只输出字段标签、节点结构、值是否存在及与已知取消样本是否相符,不输出编号及申请人值。
+唯一允许返回的隐藏值是精确控件 `IDTipoStatoPrenotazione` 的短数字候选;不读取
+`DetailToPrint.value`,不打印,不点击、不请求、不赋值页面。
+
+状态码需与同页 `Annullata` 交叉验证,不能凭字段名推定含义;
+一个取消样本不能建立成功、有效、候补或其他状态的完整映射。
+本探针中的日期/时间/文案仅为比对本次已知样本的诊断值,不是生产硬编码配置。
+具体时刻与选中时间段的关联、分页完整性与有效回执样本仍未验证。
+
+### 10.3 待负责人运行的 v2 探针
+
+```javascript
+(() => {
+  const probe = 'ITA-RESERVATION-DETAIL-SHAPE-v2';
+  const fail = error => JSON.stringify({probe, error});
+  if (location.origin !== 'https://prenotami.esteri.it' ||
+      !location.pathname.startsWith('/ReservationDetail/Index/')) return fail('wrong_page');
+  const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
+  const headings = [...document.querySelectorAll('h4')];
+  const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
+  const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
+  if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
+  const root = booking[0].parentElement;
+  if (!root || !root.classList.contains('my-col-6') || root.contains(applicant[0]))
+    return fail('unsafe_scope');
+  const parse = e => clean(e.textContent).match(
+    /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:\s*(.*)$/);
+  const candidates = [...root.querySelectorAll('label,p,span,b,strong')].filter(parse);
+  const fields = candidates.filter(e => !candidates.some(
+    other => other !== e && other.contains(e) && parse(other)[1] === parse(e)[1]));
+  if (fields.length > 20) return fail('too_many_fields');
+  const expected = {
+    'Servizio Consolare': 'Visti',
+    'Servizio Erogato': 'Visti Nazionali e Schengen',
+    'Tipo Prenotazione': 'Prenotazione Singola',
+    'Data': '13 ottobre 2026', 'Ora': '10:25', 'Stato': 'Annullata'
+  };
+  const codes = [...document.querySelectorAll('input#IDTipoStatoPrenotazione')];
+  let statusCode = null;
+  if (codes.length === 1 && codes[0].type === 'hidden' &&
+      codes[0].name === 'IDTipoStatoPrenotazione') {
+    const value = String(codes[0].value || '').trim();
+    if (/^\d{1,4}$/.test(value)) statusCode = value;
+  }
+  return JSON.stringify({
+    probe, pathShape: '/ReservationDetail/Index/<redacted>', scopeVerified: true,
+    fields: fields.map(e => {
+      const [, label, value] = parse(e);
+      return {
+        label, tag: e.tagName.toLowerCase(),
+        parentTag: e.parentElement.tagName.toLowerCase(),
+        childTags: [...e.children].map(c => c.tagName.toLowerCase()),
+        valuePresent: Boolean(value),
+        matchesKnownCancelledSample: label in expected ? value === expected[label] : null
+      };
+    }),
+    bookingStatusCount: fields.filter(e => parse(e)[1] === 'Stato').length,
+    cancelledTextMatched: fields.some(e => parse(e)[1] === 'Stato' && parse(e)[2] === 'Annullata'),
+    statusCodeControlCount: codes.length, statusCode,
+    sensitivePayloadRead: false
+  }, null, 2);
+})()
+```
+
+### 10.4 离线验证与边界
+
+- 合成 DOM `node -e` 验证 exit 0:
+  `DETAIL_SHAPE_V2_OK cases=7 external_requests=0`。
+  覆盖 label/b 去重、七类字段、安全区域、错误页面、缺少区域、重复及非数字状态码;
+  输出不含合成编号、申请人国家或非法状态码文本。
+- 仅补充本证据文档;没有修改生产代码、测试模块或配置,没有真实页面操作。
+- v2 网站执行结果待负责人提供;离线测试不是网站结构已完整验证。
+- 初见审查:隐藏状态码存在是否就能判成功?不能。还需实测值、状态语义和目标预约关联;
+  此轮仅缩小解析位置的不确定性,不放宽最终成功标准。
+
+## 11. 详情 DOM v2 实测:标签与字段值分离(2026-08-31)
+
+### 11.1 本轮事实
+
+来源:负责人返回 `ITA-RESERVATION-DETAIL-SHAPE-v2` 的 JSON。
+
+- `scopeVerified=true`,预约区域内匹配到七个不同字段标签:
+  Servizio Consolare、Servizio Erogato、Codice Prenotazione、Tipo Prenotazione、
+  Data、Ora、Stato。
+- 七个字段均为 `label`、父节点为 `div`;前六项无子元素,
+  Stato 的子元素为 `b`。预约状态标签数量为 1。
+- 七项 `valuePresent=false`,即探针从标签自身冒号后提取的文本均为空;
+  这不证明整行或整页实际值为空。字段值的位置仍待补采。
+- `statusCodeControlCount=1`、`statusCode="3"`:
+  依 v2 控件检查,该单一隐藏控件的 id/name 为 IDTipoStatoPrenotazione。
+- `cancelledTextMatched=false` 不能解释为“预约未取消”:
+  本次没有读到状态值,也没有证据证明用户此前截图里的取消状态发生变化。
+
+此前截图显示 Annullata,本轮看到隐藏码 3;暂记录为“取消样本中的状态码候选”,
+同页文字与码尚未在同一次读取中交叉确认,不据此上线全站状态映射。
+v2 离线测试覆盖值内嵌标签的合成布局,没有覆盖这次发现的标签/值分离布局。
+因此离线通过未能证明真实解析完整;本轮不放宽成功条件、不修改生产解析器。
+
+### 11.2 下一步只读 v3
+
+复用已验证的区域和七字段标签定位,检查每个字段标签父节点中的相邻元素/文本节点。
+每行只允许包含一个已识别的字段标签;多字段共用容器时仅返回数量,不混读字段值。
+只输出节点类型、值非空与已知样本匹配的布尔值;不输出实际预约号、字段正文、链接、
+申请人资料或打印载荷。不操作控件、不调用接口;状态码仍限精确隐藏控件及短数字值。
+诊断中的样本日期、时间、文案不是生产配置,也不是未知成功状态的推断依据。
+
+```javascript
+(() => {
+  const probe = 'ITA-RESERVATION-DETAIL-VALUES-v3';
+  const fail = error => JSON.stringify({probe, error});
+  if (location.origin !== 'https://prenotami.esteri.it' ||
+      !location.pathname.startsWith('/ReservationDetail/Index/')) return fail('wrong_page');
+  const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
+  const headings = [...document.querySelectorAll('h4')];
+  const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
+  const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
+  if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
+  const root = booking[0].parentElement;
+  if (!root?.classList.contains('my-col-6') || root.contains(applicant[0]))
+    return fail('unsafe_scope');
+  const nameOf = e => clean(e.textContent).match(
+    /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:/)?.[1];
+  const labels = [...root.querySelectorAll('label')].filter(nameOf);
+  if (labels.length !== 7 || new Set(labels.map(nameOf)).size !== 7)
+    return fail('fields_ambiguous');
+  const expected = {
+    'Servizio Consolare': 'Visti', 'Servizio Erogato': 'Visti Nazionali e Schengen',
+    'Tipo Prenotazione': 'Prenotazione Singola',
+    'Data': '13 ottobre 2026', 'Ora': '10:25', 'Stato': 'Annullata'
+  };
+  const fields = labels.map(e => {
+    const label = nameOf(e), row = e.parentElement;
+    const rowFieldCount = labels.filter(x => row.contains(x)).length;
+    const nodes = rowFieldCount === 1 ? [...row.childNodes] : [];
+    return {
+      label, rowFieldCount,
+      siblings: nodes.flatMap((n, index) => {
+        if (n === e || ![1, 3].includes(n.nodeType) ||
+            (n.nodeType === 1 && !['LABEL', 'SPAN', 'B', 'STRONG', 'DIV', 'P', 'A'].includes(n.tagName)))
+          return [];
+        const text = clean(n.textContent);
+        return [{
+          index, tag: n.nodeType === 3 ? '#text' : n.tagName.toLowerCase(),
+          childTags: [...(n.children || [])].map(c => c.tagName.toLowerCase()),
+          nonEmpty: Boolean(text),
+          matchesExpected: label in expected ? text === expected[label] : null
+        }];
+      })
+    };
+  });
+  const codes = [...document.querySelectorAll('input#IDTipoStatoPrenotazione')];
+  const value = codes.length === 1 && codes[0].type === 'hidden' &&
+    codes[0].name === 'IDTipoStatoPrenotazione' ? String(codes[0].value || '').trim() : '';
+  return JSON.stringify({
+    probe, fields, statusCode: /^\d{1,4}$/.test(value) ? value : null,
+    cancelledTextMatched: fields.find(f => f.label === 'Stato').siblings.some(n => n.matchesExpected === true)
+  }, null, 2);
+})()
+```
+
+### 11.3 验证与未完成项
+
+- `node -e` 合成 DOM 测试 exit 0:
+  `DETAIL_VALUES_V3_OK cases=8 external_requests=0`。
+  覆盖值在相邻 label/b、相邻文本、未知状态不匹配、区域重叠拒绝、异域拒绝、
+  多字段共用父容器不读取、重复状态控件及非法状态值;输出不含合成编号或未知原文。
+- v3 在真实页面的执行仍待负责人返回结果。未运行网站操作或重跑预约流程;
+  仅更新证据文档,没有改生产代码、测试模块或配置。
+- 仍未完成:有效预约的回执样本、所选时间段与最终分配时刻的关联、预约列表完整性。
+  本次补采不会解除最终提交边界,也不构成生产 Book 成功验收。
+
+## 12. 详情 DOM v3 实测:取消样本字段定位完成(2026-08-31)
+
+### 12.1 直接证据与结论
+
+来源:负责人返回 `ITA-RESERVATION-DETAIL-VALUES-v3` 的执行结果;本线程没有直接
+操作网站。七个字段均 `rowFieldCount=1`,说明各父容器只包含一个已识别的字段标签。
+
+| 字段 | 同行值节点(本样本) | 已核实内容 |
+| --- | --- | --- |
+| Servizio Consolare | childNodes[2],文本节点 | 与 Visti 精确匹配 |
+| Servizio Erogato | childNodes[2],文本节点 | 与 Visti Nazionali e Schengen 精确匹配 |
+| Codice Prenotazione | childNodes[2],文本节点 | 非空;未返回实际编号,未做编号匹配 |
+| Tipo Prenotazione | childNodes[2],文本节点 | 与 Prenotazione Singola 精确匹配 |
+| Data | childNodes[2],文本节点 | 与 13 ottobre 2026 精确匹配 |
+| Ora | childNodes[2],文本节点 | 与 10:25 精确匹配 |
+| Stato | childNodes[3],同级 b 元素 | 与 Annullata 精确匹配 |
+
+同一次执行返回 `statusCode="3"`、`cancelledTextMatched=true`。
+至此已验证本详情页样本中“3 ↔ Annullata(已取消)”,不再仅凭截图与另一次隐藏码
+读数推测。未验证其他状态码,不使用“不是 3 就是有效预约”的规则。
+
+v1/v2 未取得值的原因现已定位:前六项值是 label 之后的普通文本节点,状态值在
+label 之后的另一个 b 元素中;不是标签缺失,也不是这些业务值为空。
+本样本的详情字段定位问题关闭,不再重复要求负责人运行同类详情探针。
+
+### 12.2 对后续实现的约束与优先顺序
+
+1. 下一项开发应为既有最终阶段读取接口的只读适配:按预约区域和字段标签定位行,
+   读取标签之外的文本节点/元素,再做字段解析;不硬编码 childNodes 的数字下标,
+   因为空白节点数量随 HTML 排版变化。申请人区域另一个 Stato 不能参与状态分类。
+2. 保留取消记录作为预约基线历史,但不能用它证明有有效预约;未知状态或文字/代码
+   矛盾必须明确报告,不能当成功或自动当取消。完整预约列表与分页仍需独立确认。
+3. 本轮只证明编号值存在,没有证明编号格式、详情路径标识与编号相等,或服务显示名
+   等价于稳定 service_id。生产适配不可凭字段名称补造这些关系。
+4. 代码核查仍发现 `plugins/ita_booking_final.py` 的 `ReservationRecord.time_label`
+   和 `_read()` 只接受时间段,而真实详情是具体时刻 10:25;`_reconcile()` 还要求它
+   与所选时段字符串相等。此不匹配未修复,不能直接接通生产 final,也不能把区间包含
+   猜测替换为成功依据。下一开发合同须区分“所选时段”与“回执时刻”,明确关联证据。
+5. 继续复用第 1 节的最终阶段模块、现有 Book 选择结果和 VSBookResult;不另建调度、
+   浏览器或邮件平台。本轮没有新增模块或改变接口。
+
+建议下一项离线测试覆盖本次真实布局(普通文本兄弟节点和独立 b 状态),以及空白变化、
+申请人同名字段隔离、重复/缺失字段、取消码与文字冲突、未知状态、单时刻与时段分离。
+有了取消样本并不等于已取得有效预约样本;真实最终提交仍需另行确认,自动 OTP 仍为 TODO。
+
+### 12.3 本轮验证范围
+
+- 只更新本证据文档;未修改生产代码、测试或配置,工作区其他修改保留。
+- 未执行登录、OTP、Calendar 操作或预约提交;不把负责人提供的只读探针执行算成
+  自动 Book 成功,未声称已验证有效回执或其他地区。
+- 本轮无需重跑业务测试(无业务改动);历史离线测试结果见原节,不能代替本轮实测。
+- 准出结论仅为:本取消样本的字段定位与状态文字/码对应关系已验证。完整回执适配与
+  最终成功核验尚未完成。
+
+## 13. 下一项配合:预约列表覆盖范围(2026-08-31,待实测)
+
+负责人表示可配合。下一步只打开“我的预约” `/Reservation`,读取已加载表格的元数据,
+不点预约/取消,不发 OTP,不调用重新加载、分页切换或清除筛选的 API。
+
+### 13.1 复用现状及缺口
+
+已核查 `tools/debug_ita_calendar_gate.py:RESERVATION_SNAPSHOT_SCRIPT`:
+它针对 `dataTableReservations` 和 `dataTableReservationsWL` 使用
+`isDataTable(table)` 后的 `DataTable().rows().count()` 统计条数。
+现有计数合同没有记录服务端分页、总记录数或筛选状态,不能直接作为最终阶段“完整快照”。
+
+以下探针沿用这两个表的定位和初始化检查;仅在已初始化时读取实例。
+输出白名单表头、计数、分页与筛选是否存在;不输出搜索词、行数据、编号或申请人信息。
+未知 API/字段返回固定错误或 null,不猜测为空表,也不自动初始化缺失的 DataTable。
+
+### 13.2 只读探针
+
+```javascript
+(() => {
+  const probe = 'ITA-RESERVATION-LIST-COVERAGE-v1';
+  if (location.origin !== 'https://prenotami.esteri.it' || location.pathname !== '/Reservation')
+    return JSON.stringify({probe, error: 'wrong_page'});
+  const $ = window.jQuery;
+  const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
+  const knownHeaders = new Set([
+    'Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'
+  ]);
+  const integer = n => Number.isInteger(n) && n >= 0 ? n : null;
+  const tables = ['dataTableReservations', 'dataTableReservationsWL'].map(id => {
+    const matches = document.querySelectorAll('#' + id);
+    if (matches.length !== 1) return {id, count: matches.length};
+    const table = matches[0];
+    const headers = [...table.querySelectorAll('thead th')].map(e => {
+      const text = clean(e.textContent);
+      return knownHeaders.has(text) ? text : '<other>';
+    });
+    const base = {id, count: 1, headers,
+      domRowCount: table.querySelectorAll('tbody tr').length};
+    if (!$?.fn?.dataTable?.isDataTable(table)) return {...base, initialized: false};
+    try {
+      const api = $(table).DataTable();
+      const info = api.page.info();
+      return {
+        ...base, initialized: true,
+        loadedRows: integer(api.rows().count()),
+        filteredRows: integer(api.rows({search: 'applied'}).count()),
+        currentPageRows: integer(api.rows({page: 'current'}).count()),
+        page: integer(info.page), pages: integer(info.pages),
+        recordsTotal: integer(info.recordsTotal),
+        recordsDisplay: integer(info.recordsDisplay),
+        serverSide: typeof info.serverSide === 'boolean' ? info.serverSide : null,
+        globalSearchActive: Boolean(api.search()),
+        columnSearchActive: api.columns().search().toArray().some(v => Boolean(v))
+      };
+    } catch {
+      return {...base, initialized: true, error: 'metadata_unavailable'};
+    }
+  });
+  return JSON.stringify({
+    probe, readyState: document.readyState,
+    authenticatedMenuPresent: Boolean(document.querySelector('.app-menu')), tables
+  }, null, 2);
+})()
+```
+
+### 13.3 验证与判读边界
+
+- `node -e` 合成表格/API 测试 exit 0:
+  `RESERVATION_LIST_COVERAGE_PROBE_OK cases=7 external_requests=0`。
+  覆盖正常计数、错误页面、未初始化、缺表、重复表、API 失败与有筛选;
+  验证未初始化时不取得/创建实例,输出不含合成搜索词、未知表头或异常原文。
+- 等待负责人运行后再判断实际表格模式。服务端分页为 true、缺表、未知元数据等均不能
+  冒充完整结果;客户端已加载条数与总数相等也只是本次加载覆盖证据,不证明数据最新、
+  状态语义已全覆盖或身份已正确绑定。
+- 本轮仅补充文档和提供只读探针;不改生产模块或现有计数工具,不改变最终提交边界。
+
+## 14. 列表覆盖 v1 实测:主表当前页覆盖全部已报告记录(2026-08-31)
+
+### 14.1 已取得的证据
+
+负责人返回 `ITA-RESERVATION-LIST-COVERAGE-v1`:
+
+- 页面 `readyState=complete`,存在认证菜单。
+- 主表 `dataTableReservations` 唯一且已初始化;
+  DOM 行数、已加载行数、筛选后行数、当前页行数、recordsTotal、recordsDisplay 均为 1。
+  page=0(第一页)、pages=1、serverSide=false,全局和列筛选均未启用。
+- 本次主表不存在“还有下一页未读”或“筛选隐藏了其他已报告记录”的缺口。
+  这是本次已加载数据的覆盖证据,不自动等同服务端最新状态或最终完整快照。
+- 主表实际返回八个 th:前七项与截图表头匹配,第八项为探针白名单外的
+  `<other>`。此标记既可能是空表头,也可能是其他文字;不得直接猜测为操作列。
+- 候补表 `dataTableReservationsWL` 唯一,表头数 0、DOM 行数 0,未初始化。
+  不能仅凭未初始化直接判断候补数量为 0。
+
+本次探针没有返回预约行内容;之前的已取消样本不能替代对当前唯一行的状态复核。
+主表能完整读取也不意味着已核实该账号没有其他有效预约或候补。
+
+### 14.2 复用已有空表判断,补两个缺失标志
+
+再次核对 `tools/debug_ita_calendar_gate.py:RESERVATION_SNAPSHOT_SCRIPT`:
+未初始化分支要求无行、无表头、无 dataTable 类、无 dataTables_wrapper 祖先四项同时成立。
+前两项已观察到,后两项尚缺。后续生产适配还应沿用已有 bounded wait/稳定采样思路;
+单张 DOM 快照不能证明服务端不存在延迟加载的候补信息,不扩张现有判据的证明范围。
+
+下面短探针补查这两个标志,并仅观察额外表头是否为空;不初始化 DataTables、不读行值、
+不输出未知表头文字,不请求、不点击。若缺表或重复,结果为 null,不伪装为空表。
+
+```javascript
+(() => {
+  const probe = 'ITA-RESERVATION-EMPTY-SHAPE-v1';
+  if (location.origin !== 'https://prenotami.esteri.it' || location.pathname !== '/Reservation')
+    return JSON.stringify({probe, error: 'wrong_page'});
+  const matches = document.querySelectorAll('#dataTableReservationsWL');
+  const t = matches.length === 1 ? matches[0] : null;
+  const main = document.getElementById('dataTableReservations');
+  return JSON.stringify({
+    probe, readyState: document.readyState,
+    waitlist: {
+      tableCount: matches.length,
+      rowCount: t ? t.querySelectorAll('tbody tr').length : null,
+      headerCount: t ? t.querySelectorAll('thead th').length : null,
+      hasDataTableClass: t ? t.classList.contains('dataTable') : null,
+      hasWrapper: t ? Boolean(t.closest('.dataTables_wrapper')) : null
+    },
+    extraHeaders: main ? [...main.querySelectorAll('thead th')].slice(7).map((e, i) => ({
+      columnIndex: i + 7,
+      textEmpty: !String(e.textContent || '').trim(),
+      childTags: [...e.children].map(c => c.tagName.toLowerCase())
+    })) : null
+  }, null, 2);
+})()
+```
+
+### 14.3 本轮验证
+
+- `node -e` 合成 DOM 测试 exit 0:
+  `RESERVATION_EMPTY_SHAPE_OK cases=7 external_requests=0`;
+  覆盖空表、wrapper、dataTable 类、有行、缺表、非空未知表头和错误页面,
+  输出不含合成未知表头正文。
+- 上述短探针尚待负责人实测;本轮仅记录证据、提供只读脚本,没有修改生产代码、
+  测试文件或配置,也没有运行预约、OTP 或外部网络操作。
+- 当前准出仅主表本次记录的加载覆盖,不把候补表、身份绑定、有效回执、
+  时间段/具体时刻关联或完整 Book 宣告完成。
+
+## 15. 空候补表实测与本组结构取证结束(2026-08-31)
+
+### 15.1 新证据
+
+负责人返回 `ITA-RESERVATION-EMPTY-SHAPE-v1`,页面 readyState=complete:
+
+- 候补表唯一,rowCount=0、headerCount=0;hasDataTableClass=false、hasWrapper=false。
+  结合上一轮 initialized=false,本次符合现有 `RESERVATION_SNAPSHOT_SCRIPT` 的四项
+  structurallyEmpty 判据,可以按该工具的结构规则记作空候补表,而不是把未初始化
+  一概解释为 0。此结论仅限当前页面样本;运行时仍需重新读取并保留原有稳定等待。
+- 主表第八个表头(零基 columnIndex=7)textEmpty=true,且无子元素。
+  它是空表头,不是未知业务字段文字;未取得该列单元格内容,不推断它一定是操作列。
+
+至此第 12–15 节这组结构问题已闭合:详情值读取位置、取消文本/状态码、主表计数
+与分页覆盖、空候补表形状和额外空表头。无需重复请负责人运行这些同类探针。
+这并不补足真实成功回执、多页实测或其他状态码,也不能凭不同时间的样本宣布当前账号
+一定没有有效预约;后续最终提交前仍必须用同一账号的新鲜完整读取核验。
+
+### 15.2 下一阶段边界
+
+下一项应是只读回执适配及离线测试,沿用既有最终阶段读取接口、表格定位、有限等待
+与稳定采样,不新增通用调度/浏览器平台。详情解析依据字段标签与相邻节点,不依赖
+数字节点下标;候补表缺失、出现初始化痕迹但无可验证结果时不能默认为空。
+
+真实回执的 HH:mm 时刻与已选 HH:mm - HH:mm 时段需要分别建模,关联规则尚缺证据,
+不能通过删掉时间核验或随意做区间包含来接通 final。未知状态仍不能变成 ACTIVE。
+本轮只接受取证结果与记录,不将其视为已完成生产适配或新增一次真实预约的授权。
+
+### 15.3 本轮实际动作
+
+- 重新读取现有空表判断并核对本次返回的所有条件,只更新本文;没有业务代码、测试、
+  配置修改,没有网站操作,工作区原有修改保留。
+- 当前取证准出范围如 15.1;最终成功判定与生产 final 尚未准出。
+
+## 16. 只读回执适配开发合同(2026-08-31)
+
+Approval:负责人明确“开始开发吧”;本地开发与离线测试,不授权真实最终提交。
+
+- 代码归属:新 `plugins/ita_reservation.py` 为 Italy 站点只读适配器,组合当前
+  `page.run_js` 和 `same_origin_path`,沿用既有 DataTables 定位与空表判据。
+  独立于最终提交模块的写操作,不引入浏览器/调度/OTP 框架或新的第三方依赖。
+- 解析器输出站点事实(显示服务、编号、日期、具体时刻、已知/未知状态),不推断服务 ID、
+  账号身份或原始所选时段;因此不把读取事实直接冒充 FinalBookingAttempt 的完整领域快照。
+  身份/服务映射和真实成功关联接线仍为后续明确边界。
+- 列表只有同源、认证菜单、完成加载、无过滤、客户端已加载记录齐全、候补表可验证为空
+  时才返回本页覆盖结果;多页客户端数据须全部有可解析行节点,否则明确报错。
+  未证实的非空候补表 schema 不猜测解析,服务端分页不自动翻页。
+- 详情按预约标题与独立区域定位,每个标签只能对应一个字段,读取同一行的标签外值。
+  不读申请人正文、隐藏打印载荷或全页 HTML;不依赖节点数字下标。
+- 仅已观察 Annullata 及详情码 3 可识别为取消;未知/冲突状态不能推导 ACTIVE。
+- `ReservationRecord` 增加独立 appointment_time,原 time_label 表示有独立证据的时段,
+  可缺省。允许历史取消记录只有具体时刻;正向成功仍须验证所选时段关联。
+  不增加自动区间包含推断;仅有时刻的新记录保持结果不明,不能触发重复提交。
+- 测试归属:新 `test/test_ita_reservation.py` 验证纯解析、替身浏览器和实际只读 JavaScript;
+  扩展 `test/test_ita_booking_final.py` 验证取消基线与时间分离,不放宽既有默认关闭测试。
+- 准出:本轮新测试与既有 Italy 回归全部通过;无真实网站调用;日志/异常不泄露原文,
+  生产插件及原 pre-final 工具仍不导入最终提交模块。
+
+基线:`PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_booking_final`
+exit 0,41 tests,0.594 秒。不是本轮变更后的验证。
+
+## 17. 只读适配器实现与离线准出(2026-08-31)
+
+Phase: VERIFIED(仅第 16 节本地开发范围)。Approval: 本地开发和测试;无真实最终提交。
+
+### 17.1 实现与复用
+
+- 新 `plugins/ita_reservation.py`:`read_reservation_detail(page)` 读取当前详情,
+  `read_reservation_listing(page)` 在同一页面进行两次稳定读取;不自行导航、创建浏览器、
+  发请求、改变筛选或初始化 DataTables。重用 `same_origin_path`、既有表格 ID、空表条件、
+  有限等待/稳定采样模式及 `ReservationState`,没有新增第三方依赖。
+- 纯解析函数 `parse_reservation_detail()`、`parse_reservation_listing()` 接收读取投影,
+  返回冻结数据对象。采用“小型站点适配器 + 纯解析”,而非新框架/继承体系。
+  事实对象故意不等同 `ReservationSnapshot`:显示服务名称不是 service_id,认证菜单
+  也不是账号身份绑定;没有自动转换来伪造这些尚未验证的关联。
+- 详情按已知标题及区域定位,要求七个唯一字段标签与独立行,读取标签外的文本节点
+  或叶子 b;不硬编码第几个子节点。未知布局停止,而不是读取整页正文作为兜底。
+  只读已知隐藏状态控件,不读 DetailToPrint;返回对象 repr 不包含预约号或业务原文。
+- 列表读取全部已加载客户端行节点(包括非当前页的已加载行),校验总数、分页边界、
+  筛选与节点数量;服务端分页、延迟渲染缺节点或非空未验证候补结构明确停止。
+  第七列申请人和第八列内容均不读取;详情链接只接受同源详情路径,不跟随链接。
+- 仅意大利语已观察字段布局/日期格式与 Annullata 取消状态有支持;其他语言/状态不猜测。
+  逻辑不含香港名称、4937 服务 ID 或固定预约日期,其他地区仍需实际验证。
+- `plugins/ita_booking_final.py` 的 `ReservationRecord` 增加 `appointment_time`,
+  原 `time_label` 可为空但仍只表示有独立证据的所选时段。取消历史可只有实际 HH:mm;
+  新记录只有 HH:mm 即使落在所选区间内也不能判成功,结果不明只允许只读对账。
+  两字段都有时做矛盾检查;该负向检查不产生绑定证据。已有可靠时段绑定时才保留
+  回执具体时刻到原 `VSBookResult.book_time`,继续复用框架结果类型。
+- 原 `ItaPlugin`、Query、pre-final 验收工具和调度器未改动,final 开关仍拒绝开启;
+  新适配器未接为可执行最终提交的真实读取端口,不新增真实 final CLI。
+
+### 17.2 新测试与失败修正
+
+- 新 `test/test_ita_reservation.py`:32 项测试,覆盖纯字段/日期/时刻解析、取消和未知/冲突
+  状态、完整与不完整列表、空候补、链接校验、重复记录、稳定读取与页面变化、异常脱敏。
+- 实际只读 JS 在由合成 HTML 建成的 DOM 中执行,包含已观察的“标签 + 文本兄弟节点”和
+  “标签 + 独立 b 状态”布局;测试插入空白/注释、重复字段、私密单元格读取陷阱、
+  全部 11 行分两页、未初始化、筛选、服务端分页及延迟节点等情况。不是网站调用。
+- 扩展 `test/test_ita_booking_final.py` 至 47 项:增加仅有具体时刻的取消基线、有效旧记录
+  拦截、新记录不因时刻落在区间而确认、独立绑定后的时刻保留、矛盾时间和非法值等验证。
+- 首轮新测试因环境没有 BLS 源码引用的 bs4 库而导入失败(exit 1);没有安装或新增依赖。
+  改用 Python 标准库 HTMLParser 构建测试 DOM 后通过。生产适配器本来不依赖 bs4。
+
+### 17.3 实际执行结果
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_reservation test.test_ita_booking_final
+```
+
+最终 exit 0,79 项通过,1.529 秒,无跳过。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring test.test_ita_booking_final test.test_ita_reservation
+```
+
+exit 0,507 项通过,5.141 秒,无跳过。这是显式列出的 Italy 回归,不是全仓库测试。
+替身日志中的 Turnstile/日历等内容不是实际网站操作。
+
+```sh
+ITA_ROUTING_KEY=slot.hkg.it.tourist ITA_SERVICE_ID=4937 ITA_CITY='Hong Kong' ITA_VISA_TYPE='Tourist' ITA_CALENDAR_LOOKAHEAD_MONTHS=12 ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl ITA_BOOKING_TYPE_VALUE=1 ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' ITA_PURPOSE_CONTROL_ID=ddls_0 ITA_PURPOSE_VALUE=42 ITA_PURPOSE_LABELS='Turismo|Tourism' PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --preflight
+```
+
+exit 0;既有 pre-final 工具仍为 `book-prefinal-native-date-v6`、指纹 `bcc2da96cd22`,
+`external_requests=0 credentials_read=false browser_created=false`。该指纹不覆盖未接入的新
+读取器或最终模块,不能作为新读取器真实验收的证据。
+
+```sh
+git diff --check
+awk '/[ \t]+$/ { print FILENAME ":" FNR; bad=1 } END { if (bad) exit 1; print "Receipt adapter whitespace: OK" }' plugins/ita_reservation.py plugins/ita_booking_final.py test/test_ita_reservation.py test/test_ita_booking_final.py docs/ita_book_cs5.md
+```
+
+两项 exit 0;显式 awk 覆盖未跟踪的新文件。其他工作区修改保留,没有 commit/push。
+
+### 17.4 后续与初见审查
+
+下一项真实验收应只调用新读取器检查当前列表/取消详情,并只返回脱敏结果,不再反复
+手写采集已知结构的 Console 探针;本轮尚未运行该真实验收或增加登录/导航工具。
+之后才落实完整读取的账号/服务绑定,以及新增成功回执与本次选择的关联。
+实际最终提交、非空候补状态、多语言页面和其他地区未验证;自动 OTP 仍为 ITA-OTP-01。
+
+反驳:“507 项通过,是不是 Book 就可以上线了?”
+
+回应:不能。新模块可读取并校验已知页面事实,但没有把未证实的服务 ID、账号和时间段
+关联塞进最终领域快照,也没有拿取消样本冒充成功样本。准出的是解析和离线保护,不是
+真实最终预约或无人值守全链路。这样的分层能让后续补证接线,不必重写 Query/Book。
+
+## 18. 真实只读验收入口开发合同(2026-08-31)
+
+负责人授权“可以,继续吧”。目标是交付一条本地执行命令调用第 17 节读取器,
+不是本线程代替负责人进行真实登录/预约,也不是继续手写 Console 结构探针。
+
+- 新 `tools/debug_ita_reservation.py`:复用 `debug_ita_session` 的浏览器路径解析、
+  临时登录配置、账号密码交互;复用 `ItaPlugin.create_session()` / `cleanup()`。
+  现有代码没有通用接管普通 Chrome 的入口,故使用独立临时浏览器,不碰用户原窗口。
+- 默认/preflight 只做本地检查,不取凭据、不建浏览器;负责人执行 `--run` 才登录。
+  不要求地区/service_id;忽略继承的 Query/Calendar/debug 配置,不读取保存的团队账号。
+  用户凭据仅取 `ITA_BOOK_USERNAME/ITA_BOOK_PASSWORD` 或终端交互,不收命令行密码参数。
+- 登录停在 UserArea 后启动既有 `CalendarRequestAudit`,随后只导航到固定 Reservation、
+  列表中一条已取消记录的已校验详情链接,再回列表。最多读取一条取消详情,不制造样本。
+  只按已读取的链接导航,不手工拼接编号;不调用 Query/Book、GenerateOTP、AVANTI 或 final。
+- 比较列表与详情的编号、部门/服务、日期、具体时刻和取消状态,结果只打印布尔值与计数。
+  比较前后完整已加载列表未变化;审计期间预约 OTP/AVANTI/Calendar/final 请求均须为 0。
+  登录本身和普通页面 GET 有网络请求,不能宣称整个 --run 无请求。
+- 缺取消样本、状态矛盾、列表变化、上下文变化、审计断开或清理失败都不能 reported passed。
+  失败不截图、不输出页面 URL/正文/原异常或申请人资料;错误类别固定白名单。
+- 新 `test/test_debug_ita_reservation.py` 离线替身测试验收流程;复用真实读取函数,
+  不以替身输出替代实际网站验收。最终会交付负责人运行命令及需回传的脱敏结果行。
+
+## 19. 真实只读验收入口实现与本地验收(2026-08-31)
+
+Phase: VERIFIED(实现、离线回归、本地预检);真实页面验收待执行。
+本轮只新增工具/测试并更新本文件,没有修改生产 Query/Book 或开启 final。
+
+### 19.1 已实现与复用
+
+- `tools/debug_ita_reservation.py` 为组合式 CLI,复用既有登录配置、`ItaPlugin` 的
+  临时会话及清理、`CalendarRequestAudit`、第 17 节真实读取函数;不建新浏览器/调度框架。
+- 默认及 `--preflight` 不读申请人凭据、不构造插件实例、不访问网站;只有 `--run`
+  才使用申请人环境变量或用户名/隐藏密码交互。忽略 Query 账号文件、地区路由、debug
+  和持久 profile 配置,代理仍可复用原有配置。不需填写香港或任何 service_id。
+- 同一个新临时会话登录后,仅进行三次无重试导航:列表、已校验实际链接的一条取消详情、
+  列表。校验账号配置/session generation/tab/page 实例未被换掉。
+- 编号、部门、服务、日期、具体时刻、取消文案与状态码比对;详情须为单人预约。
+  列表前后按编号映射比对全部已加载记录,不把排序变化当成预约变化。
+- 仅输出固定阶段/原因、数量/布尔值、指纹;不输出编号、详情 URL、申请人信息、原始异常,
+  不截图。`auditVerified` 区分审计有效与断线后的旧计数;审计、清理失败均不可通过。
+
+审计只覆盖登录后的已知预约业务路径,不声称整个登录零网络请求或所有 POST 均为零。
+普通 GET 和站点遥测不是最终提交。生产 final、自动 OTP 和成功回执绑定均没有接入。
+
+### 19.2 本地验证证据
+
+新增 `test/test_debug_ita_reservation.py` 27 项离线测试。使用真实解析函数与实际
+`CalendarRequestAudit` 分类器,只替换浏览器和缩短审计等待;覆盖成功链路、空/缺取消
+样本、逐字段矛盾、多条记录及排序、会话/账号/tab 更换、越域链接、跳回登录、每类
+不应发生的业务请求、末次审计迟到请求、断线、清理失败、中断、脱敏和默认不执行。
+首次测试暴露替身重复登录未恢复 Dashboard,已修正替身的登录行为后重跑通过。
+
+最终执行:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring test.test_ita_booking_final test.test_ita_reservation test.test_debug_ita_reservation
+```
+
+exit 0,534 项,5.053 秒,无跳过;是列明范围的 Italy 回归,不是全仓库测试。
+输出中的 Calendar/Turnstile 等日志来自替身,不是本轮真实请求。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_reservation.py --preflight
+```
+
+exit 0;`receipt-readonly-gate-v1`,`source_sha256=1563bf14cae7`;
+`external_requests=0 credentials_read=false browser_created=false`。
+指纹覆盖本工具、读取器及相关 Italy/登录/审计源文件,不哈希或暴露账号配置。
+
+### 19.3 交给负责人执行
+
+```sh
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+PYTHONDONTWRITEBYTECODE=1 python -B tools/debug_ita_reservation.py --run
+echo "EXIT_CODE=$?"
+```
+
+在本地终端输入已有取消预约的申请人账号和密码;不需要预约 OTP。
+回传 `ITA_RECEIPT_GATE_RESULT=...` 和 `EXIT_CODE`,不需发送凭据、截图或完整页面内容。
+验收通过须 `passed=true`、`cancelledDetailMatched=true`、`listUnchanged=true`、
+`auditVerified=true`、`cleanupOk=true`、全部五项审计计数为 0、exit 0。
+
+若无取消样本或页面不符,只报当前固定阶段和原因,不自动制造预约或猜测新结构。
+即使通过,也仅验证取消回执读取;不能据此宣称成功预约已跑通。
+下一步再将完整读取结果与申请人/服务绑定,并验证新增有效回执与本次选择的关系。
+
+## 20. 首次真实读取失败:日期格式待定位(2026-08-31)
+
+### 20.1 负责人回传及本地核对
+
+负责人运行第 19 节命令,版本 `receipt-readonly-gate-v1`、指纹 `1563bf14cae7`。
+实际结果:登录成功;`stage=list_before`、`reason=date_unrecognized`、exit 1;
+`listReady=false`、`cancelledDetailMatched=false`、`listUnchanged=false`。
+审计有效,五项业务计数均为 0,临时浏览器清理成功。没有据此宣称列表为空、取消
+记录丢失或预约有变化;这些步骤都尚未读完。
+
+本地确认失败版本指纹一致,`_day("13 ottobre 2026")` 正常返回 `2026-10-13`。
+因此旧截图已知的意大利语日期可解析;程序实际获得的单元格内容尚未知。
+隐藏排序文本、不同显示格式或其他内容差异均为假设,不能选一个当成根因。
+
+### 20.2 最小续修范围
+
+Phase: VERIFIED(仅脱敏诊断和离线测试);实际日期故障未解决。
+Approval: 延续当前只读验收入口的开发/排查;不操作真实登录、不提交预约。
+
+- `plugins/ita_reservation.py` 增加只读日期诊断:核对同源 Reservation、认证菜单、
+  七个已知表头及可选第八空表头,且 DataTables 已初始化;只读已校验 Data 列。
+  最多三行、每行六个子节点。比较 textContent 与 innerText,以及子元素的隐藏状态。
+- 原始日期字符串仅在本地内存处理,输出数字替换为 D、字母替换为 L 的形状、长度、
+  截断标志、已知意大利月份序号、是否能被现有解析器接受;不输出原始日期、任意
+  属性/HTML、申请人列、编号或账号。输出 schema 不合格仅返回 available=false。
+- `tools/debug_ita_reservation.py` 在 list_before/list_after 的 date_unrecognized
+  时读取一次诊断,仍由原会话/账号/tab 校验、业务请求审计和 cleanup 包围。
+  原错误和 exit 1 保留,不能因诊断成功而把验收改成 passed。成功路径和详情错误
+  不触发该列表诊断,也没有添加新导航、OTP、表单动作或读取器宽松兜底。
+- 升级合同至 `receipt-readonly-date-diagnostic-v2`。没有改 Query/Book、日期规则或
+  最终提交权限。不是“日期 bug 已修复”的版本。
+
+### 20.3 测试与下一步
+
+新增 7 项测试,覆盖真实诊断 JS 的隐藏排序文本**假设样例**、原解析仍拒绝、错误表头、
+未初始化、未知字符串脱敏、输出边界、失败不中断清理、正常路径不额外读取。
+隐藏排序文本合成用例不是当前网站实际采用该结构的证据。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_reservation test.test_debug_ita_reservation
+```
+
+exit 0,66 项,1.024 秒。随后执行第 19.2 节同一完整 Italy 回归命令:
+exit 0,541 项,4.864 秒,无跳过;未真实访问网站。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_reservation.py --preflight
+```
+
+exit 0,指纹 `960ff39dcf3b`;external_requests=0、credentials_read=false、browser_created=false。
+负责人重跑原 `--run` 命令并回传 `ITA_RECEIPT_GATE_RESULT` 的 dateDiagnostic 即可。
+预计旧问题仍会导致 exit 1;先根据真实诊断决定修正方式,不让用户反复搜索整页 DOM,
+也不猜测日期格式或从混合文本随意截取一个日期。
+
+## 21. 根因确认与日期节点读取修正(2026-08-31)
+
+### 21.1 同版本真实证据
+
+负责人回传 `receipt-readonly-date-diagnostic-v2` / `960ff39dcf3b`:
+登录成功、失败仍在 list_before / date_unrecognized;审计有效、五项业务请求均为 0、
+cleanup 成功、exit 1。dateDiagnostic 可用且无行/节点截断,样本明确显示:
+
+| 部分 | 证据 |
+|---|---|
+| 第一个子节点 | kind=other、hidden=true,形状 DDDDDDDD DD:DD,长度 14,日期解析不接受 |
+| 第二个子节点 | kind=text、hidden=false,形状 DD LLLLLLL DDDD,长度 15,月份序号 10,解析接受 |
+| innerText | 与显示日期的形状/长度相同,解析接受 |
+| textContent | 两段文本被拼接,长度 29,解析不接受 |
+
+根因:原读取器对整个 Data 单元格调用 textContent,把隐藏元素的内容也拼入日期。
+不是意大利语月份不支持,也不是登录失败。隐藏值具体用于排序或其他功能尚未验证,
+修复不依赖猜测其用途、真实标签或值。不记录凭据/原始日期/隐藏值。
+
+### 21.2 代码归属与实施
+
+Phase: VERIFIED(本地修正与回归);真实回执验收仍待用户执行。
+Approval: 延续当前只读回执修复;无真实登录/预约动作、无提交/推送权限扩张。
+
+- 修改归属现有 `plugins/ita_reservation.py` 的 LIST_READ_SCRIPT。VFS/BLS 中未找到
+  可直接复用的 Prenot@Mi 日期格读取器;保留既有读取适配器、DataTables 获取方式、
+  数据合同、测试工具及被动审计,不新增框架或通用日期推断层。
+- 只读取 Data 格中唯一非空直接文本节点;跳过注释和空白;元素只有被明确证明隐藏
+  才排除。隐藏判断复用诊断使用的 computed display/visibility,并支持节点自身的
+  inline/hidden 标记;visibility:hidden 只允许叶节点,防止子节点覆盖成可见。
+- 不读、不解析、不记录隐藏元数据的值。可见包装元素、多段有歧义文本、只有隐藏值、
+  超出 16 子节点界限等仍拒绝,不从混合内容中用正则截取看似日期的子串。
+- 不直接切换成整个格的 innerText:未渲染或未附着在当前页面的 DataTables 行不能
+  依赖布局取值。继续读取所有已加载行,保留行数、分页、筛选、表头等完整性检查。
+  未显示页有明确 inline/hidden 标记的节点仍可校验;无法确认隐藏的结构不会猜测放行。
+- Python 日期解析规则、详情读取、Query/Book、最终提交开关均不变。
+  工具版本提升到 `receipt-readonly-date-node-v3`,保留原脱敏诊断以支持后续异常定位。
+
+### 21.3 验证
+
+更新已有隐藏内容测试,新增 6 项回归:与实际诊断相同的隐藏 other + 直接文本形状;
+隐藏值完全不读取;不访问日期格完整 textContent/innerText;有歧义可见节点拒绝;
+非法日期和可见混合元数据仍拒绝;11 条记录跨两页的隐藏文本均正确排除。
+标签与值使用合成数据,不把 synthetic label 或示例数字误记为网站实际值。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_reservation test.test_debug_ita_reservation
+```
+
+exit 0,72 项,1.469 秒。随后执行第 19.2 节同一 Italy 回归命令:
+exit 0,547 项,5.334 秒,无跳过。这是列明范围的离线测试,不是全仓库或真实网站验收。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_reservation.py --preflight
+```
+
+exit 0,版本 `receipt-readonly-date-node-v3`、指纹 `5793dc6a2eb6`;
+external_requests=0、credentials_read=false、browser_created=false。
+
+下一步:负责人在自己的终端执行同一 `--run` 命令,回传 ITA_RECEIPT_GATE_RESULT 与
+EXIT_CODE。即使日期读取通过,也继续要求详情匹配、列表不变、业务请求全零、清理成功;
+不能因这次故障修复就认定最终 Book 已验收。
+
+## 22. v3 真实只读验收通过(2026-08-31)
+
+Phase: VERIFIED(用户执行的列表/一条取消详情只读验收)。
+Scope: 核对并记录版本及验收结果;Non-goals: 不新增功能、不提交预约、不开启 final。
+Approval: 延续当前验收记录范围;无需负责人重复运行同一只读验收。
+Evidence/Risks: 下述为用户终端回传,不伪称由本线程发起或直接观察网站;
+已覆盖该取消样本,不能代替有效新预约、其他语言/地区或真实多页样本验收。
+
+### 22.1 版本与结果
+
+负责人在同一条消息中贴出两次运行:前段 v2 / `960ff39dcf3b` 仍因 date_unrecognized
+失败,是旧版本记录;后段 v3 / `5793dc6a2eb6` 为修正后的成功结果,两者分开判读。
+不能把前段失败继续当成 v3 阻塞。
+
+| v3 验收项 | 回传结果 |
+|---|---|
+| 合同 | receipt-readonly-date-node-v3 |
+| 源码指纹 | 5793dc6a2eb6 |
+| 登录 | ITA_RECEIPT_LOGIN_OK |
+| 阶段 / 整体结果 | completed / passed=true / exitCode=0 / EXIT_CODE=0 |
+| 列表读取 | listReady=true |
+| 取消详情比对 | cancelledDetailMatched=true |
+| 列表前后 | listUnchanged=true;记录数 1 → 1 |
+| 日期诊断 | dateDiagnostic=null,未触发失败诊断 |
+| 审计 / 清理 | auditVerified=true / cleanupOk=true |
+| 业务请求 | availabilityRequests、avantiPosts、finalRequests、otpRequests、timeSlotRequests 均为 0 |
+| 最终提交开关 | finalSubmissionEnabled=false |
+| 错误原因 | 空 |
+
+意义:新读取器已在该真实页面读取预约列表和既有取消详情,并核对前后列表不变。
+记录数为 1 是取消历史仍保留,不代表存在 1 个有效预约。正常登录和页面 GET 有网络
+请求;“零请求”仅指表中的五项被审计预约业务路径,不是全程无网络。
+
+### 22.2 本地核对与后续边界
+
+本轮本地执行:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_reservation.py --preflight
+```
+
+exit 0,合同及指纹与用户 v3 成功日志一致;external_requests=0、credentials_read=false、
+browser_created=false。本轮只更新本文件,没有改代码、运行真实登录或重复执行离线
+回归;第 21 节的 547 项测试属于此前同版本代码验证,不改写其执行时间。
+
+下一关键工作是把读取事实接入最终阶段的提交前检查和提交后对账:明确申请人/目标服务
+绑定、新有效状态、所选时段与站点分配时刻的关联,以及结果不明时禁止盲目重复提交。
+只读取消样本通过不会自动开启这些功能,也不能用已有取消记录充当新增成功回执。
+实际最终提交仍未执行,自动 OTP 仍是 ITA-OTP-01;不要求负责人重复本轮已通过的测试。
+
+## 23. 同会话回执读端接线合同(2026-08-31)
+
+负责人授权“可以的,开始吧”。Phase: APPROVED;本轮本地开发与离线验收,
+不进行真实提交、不启用生产 final、不修改共享 Booker 或云端任务状态。
+
+- 新 `plugins/ita_final_read_port.py` 组合 `ita_reservation` 的已验证读取器与
+  `ita_booking_final` 的现有 FinalTarget / ReservationSnapshot / FinalBookingAttempt
+  合同,复用 plugin 的申请人、route、Calendar preparation 和 precommit 上下文校验。
+  捕获之后换账号/实例/tab/浏览器/session generation/route/selection 都不能继续。
+- 为避免基线读取导航离开 Calendar 丢失选择,使用当前浏览器新建的背景标签
+  (new_context=false),检查浏览器对象及标签身份,读取列表、取消详情、返回列表,
+  前后快照一致后关闭自己创建的标签。不读/复制 Cookie/Token、不新建浏览器上下文。
+  单次最多校验 20 条详情,超出明确阻断;不冒充无限规模完整读取。
+- 回执仅有显示服务名称,不能推导 service_id;取消历史允许 service_id=None,
+  同时携带完整业务事实的 SHA-256 指纹以保留变化检测。None 仅适用于已取消历史,
+  不能用于 ACTIVE/WAITLIST 或归属判断,不构造假的服务 ID/时段。
+- 当前读端只接受已验证 Annullata/3 详情;未知/新增有效状态保持阻断。未来补有效
+  状态及服务/时段关联证据后再扩充适配,不用名称相同或时间落在区间内猜测成功。
+- 复用 FinalBookingAttempt 的一次执行、读后对账、FinalOutcomeUnknown 和
+  VSBookResult;新读端不调用 NativeFinalSubmitter、不提供自动提交入口。
+  用真实读端 + 替身浏览器证明基线可以进入现有核心,提交后出现未知记录只能对账、
+  不能返回成功或由同一 attempt 重提。
+- VFS 的 IsAppointmentBooked 与 BLS 的 model.Id/Liveness 是各自协议证据,复用
+  它们的统一结果类型而不移植成功条件。OrderBooker 对 success=false 下轮信号重试,
+  普通异常也不暂停;已有 pause 状态可阻止任务,但当前未形成提交前持久写屏障。
+  本轮不扩大为云端协议/调度器改造,生产 final 继续关闭。
+
+准出:同会话隔离读端、取消历史保留、上下文变化/列表变化/未知状态/清理失败阻断,
+提交后未知只读重查不重提;Italy 回归通过。真实背景标签读取及成功回执仍分别待验收。
+
+## 24. 同会话读端接线完成与可选验收入口(2026-08-31)
+
+Phase: VERIFIED(本地实现和离线合同);背景标签实测、最终成功实测待完成。
+沿用第 23 节授权;没有真实登录、OTP、预约提交、云端任务更新或 git commit/push。
+
+### 24.1 实现边界
+
+- `plugins/ita_final_read_port.py`:新增 FinalReceiptReadPort,构造时捕获当前 Book
+  precommit,复用 `_calendar_book_context_matches` 及实际列表/详情读取函数。
+  绑定申请人配置、session generation、route、Calendar page/tab、browser 和原 approval。
+  这是既有登录会话连续性校验,不宣称新增了服务端身份声明或从姓名推断账号。
+- 同浏览器背景标签只做 Reservation → 已校验实际详情链接 → Reservation 的 GET,
+  不调用 Book/Query,不操作 Cookie、OTP、最终按钮或主标签导航。读取上下文变化、
+  20 条详情上限超出、未知状态、列表变化、关闭标签失败均不返回有效快照。
+  仅清理自己创建并核对归属的标签,异常和中断仍释放锁并尝试清理。
+- 当前读端只接受空列表或全部为已验证取消历史的列表。取消记录保留 assigned HH:mm,
+  service_id 和 time_label 均留空,不复制本次目标值给历史记录。完整业务事实指纹
+  保留原领域模型中未表示的显示服务、部门、预约类型变化;指纹不是身份/服务绑定证据。
+- `plugins/ita_booking_final.py` 仅扩大取消历史的表达:无服务 ID 时必须为 CANCELLED
+  并携带合格指纹,ACTIVE/WAITLIST/UNKNOWN 不能使用该例外。原一次提交、未知只读
+  reconcile、统一 VSBookResult 均复用;新增未知记录仍报 FinalOutcomeUnknown。
+  同一 attempt 不能重提不等于跨进程写屏障,不能据此开放生产重试。
+- `tools/debug_ita_book_gate.py` 新增 `--verify-receipts` 可选参数,默认不改变原
+  pre-final 路径。选中日期/时段后调用上述读端,背景标签独立使用现有 CalendarRequestAudit,
+  审计完成和关闭后,再用原 verify_precommit_selection 复核主 Calendar 的选择。
+  历史数量还须与运行前计数一致。不会调用 FinalBookingAttempt.execute 或原生 final。
+- 新合同 `book-prefinal-receipt-baseline-v7`,指纹纳入新读端、回执读取器及 final 模块。
+  复用现有 --run 的临时申请人登录、手动 OTP、单次 AVANTI、全程预算与清理,不新建工具。
+  因为共享 final 模块文件变化,原 receipt v3 指纹也会变化;旧实测不冒充新依赖集实测。
+
+### 24.2 离线验证
+
+新增 `test/test_ita_final_read_port.py` 22 项,包含真实解析器/真实会话匹配方法与浏览器
+替身的接线测试;新增 final 取消历史校验 2 项、Book 工具 opt-in 接线测试 4 项,共新增
+28 项。场景包括:同会话标签归属、不碰 Calendar、所有主要上下文变化、空/取消/未知
+历史、详情字段变化保留、数量上限、标签/观察器清理失败、中断、未知仅对账不重提。
+工具测试使用真实 Book 与新读端,验证只读标签审计为零且原选择保留。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_final_read_port test.test_debug_ita_book_gate test.test_ita_booking_final
+```
+
+exit 0,141 项,0.739 秒。完整 Italy 回归:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring test.test_ita_booking_final test.test_ita_reservation test.test_debug_ita_reservation test.test_ita_final_read_port
+```
+
+exit 0,575 项,6.070 秒,无跳过。测试的提交回调全部是离线替身,不是实际预约。
+
+```sh
+ITA_ROUTING_KEY=slot.hkg.it.tourist ITA_SERVICE_ID=4937 ITA_CITY='Hong Kong' ITA_VISA_TYPE='Tourist' ITA_CALENDAR_LOOKAHEAD_MONTHS=12 ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl ITA_BOOKING_TYPE_VALUE=1 ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' ITA_PURPOSE_CONTROL_ID=ddls_0 ITA_PURPOSE_VALUE=42 ITA_PURPOSE_LABELS='Turismo|Tourism' PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book_gate.py --preflight --verify-receipts
+```
+
+exit 0,`book-prefinal-receipt-baseline-v7` / `0e8ec52fa61e`;external_requests=0、
+credentials_read=false、browser_created=false。这里香港只是参数样例,无地区硬编码。
+
+### 24.3 真实验收与未完成事项
+
+负责人可将上述命令中 --preflight 改为 --run,在自己的终端执行。会进入已验证的
+申请人登录与手动 OTP/AVANTI/选时段流程,然后增加只读核验;不会最终提交。
+成功须同时出现 ITA_BOOK_GATE_RECEIPT_BASELINE 的 verified=true、calendarSelectionPreserved=true、
+背景标签五项业务计数全零,以及最终 ITA_BOOK_GATE_RESULT.passed=true / EXIT_CODE=0。
+整轮准备允许 1 次 OTP 和 1 次 AVANTI;不可把这两个准备动作和背景只读审计混淆。
+
+若没有候选日期,沿用现有 exit 2,不算新读端通过;如果有未知/有效记录,当前读端会
+阻断而不是将其误判已取消或无预约。不要为测试清空/取消用户正常预约。
+
+下一阶段仍需:真实新有效回执状态及目标服务关联证据、所选时间段与站点分配具体时刻
+的关联;生产上线前还需复用现有任务 pause 机制落实可持久的未知结果阻断。
+本轮没有把暂停状态本身当作已实现的写屏障,没有增加新 Redis/数据库平台,也没有
+开启生产 final。新同会话读端解决的是读取接线和安全基线,不是宣称完整 Book 已成功。
+
+## 25. v7 提交前选择与回执基线组合实测通过(2026-08-31)
+
+Phase: VERIFIED(负责人回传的 pre-final + 同会话只读基线实测)。
+本节只记录验收,不改代码、不执行真实登录/OTP/预约,也不开放最终提交。
+
+### 25.1 来源与版本边界
+
+来源为负责人在自己的终端执行后回传的日志,不是代理直接观察浏览器所得。
+`ITA_BOOK_GATE_RESULT.contract=book-prefinal-receipt-baseline-v7`,`EXIT_CODE=0`。
+本次片段未包含 `ITA_BOOK_GATE_TOOL_CONTRACT` 的 source_sha256;其中 QCAL preparation
+指纹不能当作 Book 指纹,第 24 节本地预检指纹也不能反向证明用户此次运行的完整依赖集。
+不为补日志头要求重跑真实 OTP/选时段流程。原日志中的验证码、账号等敏感内容不落盘。
+
+### 25.2 观测结果
+
+- 登录后的准备链路:OTP 发送 1 次,写入回读匹配;AVANTI 1 次,进入 Calendar。
+- 生产 Book 扫描:2026-08 候选 0;2026-09 候选 1,在首个正向月份停止。
+- 选中日期 `2026-09-03`,时间段 `09:15 - 10:00`,当时余量 3,`selectionVerified=true`。
+  这些是当次观测,不保证现在仍有号;选中不表示已锁位或预约成功。
+- `receiptBaseline.verified=true`,`recordCount=1`,`calendarSelectionPreserved=true`。
+  只读基线审计的 availability、AVANTI、final、OTP、time-slot 五项业务请求均为 0。
+  零业务请求不表示未发生读取列表/详情所需的 GET。
+- 整轮 availability 请求 3、AVANTI 1、OTP 1、final 0;其中生产 Book 增量为
+  availability 2、AVANTI 0、OTP 0、final 0。不能把准备动作与背景只读审计混在一起。
+- 前后预约列表记录数均为 1,waitlist 均为 0;这是保留的历史记录,不等于 1 个有效预约。
+- `finalSubmissionEnabled=false`,`bookResultSuccess=false`,`outcome=pre_final`,
+  `passed=true`、`exitCode=0`,清理成功。`bookResultSuccess=false` 是未最终提交的
+  预期业务结果,不是本次组合验收失败。
+
+### 25.3 结论与下一阶段
+
+已验证第 24.3 节的组合准出条件:当前 Book 会话能选时段,读取取消历史,并保留原选择;
+该链路无需重复验收。香港依然是本次样例,不能把单地区实测等同于所有地区实测。
+
+尚未证明最终 Book 成功。下一阶段聚焦受控最终提交与真实成功回执闭环:补齐有效状态、
+目标服务及所选时间段与分配时刻的关联证据;最终结果不明时只能只读核对,不能盲目重提。
+生产 final 开放前还须落实可持久的未知结果阻断,自动 OTP 继续保留为 ITA-OTP-01。
+本次结果回传本身不扩大为真实最终提交或生产启用授权。
+
+## 26. 受控最终提交证据入口 v8(2026-08-31)
+
+Phase: VERIFIED(本地实现、离线合同与无网络预检);真实最终结果仍待负责人执行。
+Approval: 负责人“没问题,我可以配合你,继续吧”承接第 25 节之后的受控单次提交建议。
+本轮代理仅本地开发/测试,没有真实登录、OTP、提交、取消、云端变更或 git commit/push。
+
+### 26.1 设计、复用与边界
+
+目标:使负责人能够在自己终端用现有申请人 Book 链路完成一次真实提交,收集新回执的
+状态/日期/分配时间,为下一轮正式成功判定提供证据。不是提前宣布生产 Book 可用。
+
+- 保留 `tools/debug_ita_book_gate.py`,新增 opt-in `--submit-once`,必须同时指定
+  `--verify-receipts`;不另建登录、OTP、Calendar 扫描、选时段或 HTTP 重放实现。
+  默认/--preflight 无凭证读取、无浏览器创建、无网络动作;默认 --run 仍为 pre-final。
+- `tools/ita_final_evidence.py` 仅负责本地验收编排:复用 `FinalBookingAttempt`、
+  `NativeFinalSubmitter`、`FinalReceiptReadPort` 和原 `verify_precommit_selection`。
+  先显示 route/service/date/time,再要求完整输入 `BOOK YYYY-MM-DD HH:mm - HH:mm`。
+  任何其他输入取消。确认之后重新核验当前会话、取消历史和选择,不能拿旧选择直接提交。
+- 本地防重沿用 `tools/ita_local_handoff.py` 的私有目录和一次消费文件模式:复用
+  `_ensure_private_directory`,在已忽略的 `data/ita_local_handoff/` 内用 O_EXCL / 0600
+  创建 `final-evidence-once.claim`,flush/fsync 文件及目录完成后才进入原生提交。
+  文件只有版本和 possibly_submitted / automaticRetry=false,不保存账号、日期、编号或 OTP。
+  空/部分文件、符号链接或并发占用均阻止再次提交;异常、拒绝、清理、重启后不自动删除。
+  本地检查提前到凭证/OTP 之前;并发争用在真正提交之前再次原子判定。
+  当前是本 checkout 的保守全局一次闩锁,跨账号也阻断;不是分布式/生产订单写屏障。
+- 原生 final 仍由站点按钮处理器构造请求,本地工具不自造预约 POST、令牌或服务端状态。
+  原领域核心的“只执行一次、未知只读对账”照用,未改 `ItaPlugin.final_submit_enabled`。
+- `FinalReceiptReadPort.observe_receipts()` 共用现有背景标签归属、上下文、分页覆盖、
+  数量上限、列表/详情字段一致性、前后列表一致性及清理规则,只返回观测事实。
+  原 `__call__()` 仍只接受空/已取消基线;新 UNKNOWN 状态不能绕过该限制。
+  不把显示服务名变成 service_id,也不把具体时间落在区间内当作预约归属证明。
+- 采集日志只输出新记录的服务/部门/预约类型文本、状态文本和代码、日期、分配时间,
+  以及数量和布尔比对。最多输出 3 条新记录,超出标记截断,不输出 reference、详情 URL、
+  申请人资料、凭证或响应正文。这里的状态文本是站点数据,不是执行指令或已验证状态映射。
+- 主标签全程审计:最终请求至多 1 次,准备仍至多 1 OTP / 1 AVANTI;只读背景标签
+  五项业务请求必须为 0。新增 `requestAuditVerified` 区分审计通过与仅采集到结果。
+  结果不明、捕获中断、重复请求或其他异常均不解除本地防重,不指示自动重试。
+- 提交后输出 `ITA_BOOK_GATE_FINAL_EVIDENCE` 并停在终端,保留临时浏览器供人工只读查看。
+  用户按 Enter(或中断)后清理。不要为验收取消正常预约,也不要在保留页面再次提交。
+
+### 26.2 可证伪假设与验证
+
+| 假设 | 离线验证 | 真实验证状态 |
+| --- | --- | --- |
+| 默认为零 final,缺少显式标记/时段确认不能提交 | 默认、缺少 receipts、拒绝确认、无网络预检测试 | 旧 v7 已验证,v8 待回传 |
+| 复用的单次提交核心可接入原 Book 选时段结果 | 真实 Book + 真实 final core + 原生提交替身的组合测试 | 待 v8 实测 |
+| 进程重启/并发/写入失败不能触发第二次本地提交 | O_EXCL、并发唯一赢家、已有/部分 claim、fsync 失败、符号链接测试 | 本地合同已验;不是分布式保证 |
+| 新回执可用旧结构读取而状态保持未知 | 原真实解析器 + 合成新状态,严格读端仍拒绝 UNKNOWN | 实际新回执结构及状态待采集 |
+| 超时/异常/中断后不会误报成功、不会重提 | UNKNOWN、异常、中断、重复网络计数、保留标记测试 | 实际网络错误仍依现场;不强制制造失败 |
+
+新增 23 个测试:`test/test_ita_final_evidence.py` 18 个,既有 Book gate 测试新增 5 个。
+包括保留主 Calendar、背景标签清理、只读观察不放宽严格成功合同、日志不输出 reference、
+默认不调用提交端、拒绝/未知/中断/重复请求的组合接线。原 NativeFinalSubmitter 的
+JS/请求匹配测试继续复用;此处请求均为离线替身,没有实际预约。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_add_ita_query_account test.test_debug_ita_book test.test_debug_ita_book_gate test.test_debug_ita_calendar_gate test.test_debug_ita_monitor test.test_debug_ita_production_query_gate test.test_debug_ita_query test.test_debug_ita_session test.test_debug_ita_soak test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_calendar_query test.test_ita_calendar_soak test.test_ita_local_handoff test.test_ita_plugin test.test_ita_protocol test.test_ita_query_recovery test.test_ita_route_wiring test.test_ita_booking_final test.test_ita_reservation test.test_debug_ita_reservation test.test_ita_final_read_port test.test_ita_final_evidence
+```
+
+结果:exit 0,598 项,5.853 秒,无跳过;范围是列出的 Italy 测试,不是整个仓库。
+同路由参数运行下节命令将 --run 替换为 --preflight:exit 0,
+`book-final-evidence-once-v8` / `b929de85613e`;external_requests=0、credentials_read=false、
+browser_created=false。源码指纹含 final evidence 和本地 handoff 依赖,不含本地 claim。
+
+### 26.3 用户终端命令与准出
+
+```sh
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 \
+python -B tools/debug_ita_book_gate.py --run --verify-receipts --submit-once
+echo "EXIT_CODE=$?"
+```
+
+输入申请人凭证及一次 OTP;选好时段后只在该日期/时间适合真实预约时输入工具显示的
+完整确认短语。不是把本文件示例日期当作授权目标,实际目标以当次终端展示为准。
+出现 `ITA_BOOK_GATE_FINAL_EVIDENCE` 后回传该行及最终请求计数,不回传 OTP/个人资料。
+页面保留时可以查看新回执;如需截图,遮住姓名、编号、联系方式等,只保留业务状态。
+
+exit 4 = 已可能提交、需要人工核对、禁止重跑;不是普通可重试失败。
+`bookingConfirmed=false` / `passed=false` 保持诚实:当前还不能自动认定有效回执。
+exit 2 = 无候选或未确认(该工具未最终提交);exit 1 = 提交前阻断/检查失败;
+exit 3 = 清理失败。任何情况下只要最终请求可能发出,claim 均保留,不手动盲删。
+
+本轮真实准出是获取一次 final 网络证据和完整新回执事实、历史不受损、审计符合预算,
+不是要求未知解析器强行 success=true。如果响应/读取失败,保持只读人工核对,不再写。
+后续根据实测补齐状态与归属合同,另行实现生产持久阻断;自动 OTP 仍为 ITA-OTP-01。
+
+## 27. v8 真实单次提交与新增确认回执(2026-08-31)
+
+Phase: VERIFIED(用户回传的单次提交及只读回执证据;不代表程序成功判定或生产准出)。
+本节只记录结果并核对现有判定代码,不修改代码,不执行真实网站动作,不清除本地防重。
+
+### 27.1 版本与来源
+
+负责人在自己的终端运行第 26 节入口,并输入实际展示的日期/时段确认短语后回传日志。
+合同 `book-final-evidence-once-v8`;最终 `EXIT_CODE=4`,临时浏览器清理成功。
+片段未包含 Book TOOL_CONTRACT 的 source_sha256,不能用先前本地指纹补成实测指纹。
+未保存账号、验证码、预约编号、详情链接或个人资料;本节是回传证据,不是代理直接观测。
+
+### 27.2 实测事实
+
+- route `slot.hkg.it.tourist`,service_id `4937`。Book 选中 `2026-09-03`,
+  `09:15 - 10:00`,当时余量 3,选择复核通过;负责人确认该实际目标。
+- 提交前取消历史基线 1 条、verified=true,原 Calendar 选择保留;背景标签五项业务请求 0。
+- 最终请求 1 次;整轮 availability 3、AVANTI 1、OTP 1,`requestAuditVerified=true`。
+  `bookRequestDelta.finalRequests=0` 只描述前面的选时段步骤,不是整轮最终请求数。
+- `attempted=true`、`automaticRetry=false`。未触发重复最终提交。
+- 回执读取成功:`readVerified=true`、`historicalRecordsUnchanged=true`,
+  `recordCount=2`、`newRecordCount=1`、`newRecordsTruncated=false`。
+- 唯一新增记录:部门 `Visti`、服务 `Visti Nazionali e Schengen`,
+  类型 `Prenotazione Singola`;日期 `2026-09-03`,站点分配时刻 `09:26`;
+  状态文本 `Confermata`,状态代码 `2`。这是新增“已确认”回执的正向样本。
+- 日期与选择一致,09:26 在所选 09:15–10:00 内。区间内的具体时刻与区间本身不同,
+  不能要求 receipt 的 `09:26` 文本等于 Calendar 的 `09:15 - 10:00`。
+  时间包含关系本身仍不是可推广的服务/时段唯一归属证明,不反推隐藏 runtime ID。
+- 运行前后列表总数 1→2,waitlist 0→0。结合完整回执比较,原历史保留并新增确认记录;
+  不单凭数量增一判成功,也不把全部 2 条都当有效预约。
+
+### 27.3 为什么网站已确认而程序仍为 unknown
+
+本地只读检查 `plugins/ita_reservation.py::_state`,当前只编码了 Annullata / 3 → CANCELLED,
+其他状态返回 UNKNOWN。因此新观察到的 Confermata / 2 尚未被当前版本认定 ACTIVE。
+严格最终读端也尚未接受新有效状态的归属,`bookingConfirmed=false` / `passed=false` /
+`outcome=unknown_do_not_retry` / exit 4 是当前合同输出,不是网站拒绝预约的证据。
+
+`submissionSignal=unknown` 是另一个独立缺口:当前日志没有请求/响应结构诊断,无法判断
+究竟是监听/读取时序、请求字段、响应类型/字段还是其他校验未通过。不得仅凭此日志声称
+是某个字段为 null 或 HTTP 状态异常;也不为了重抓包再创建一条预约。
+
+结论:本次香港样例的真实动作链路已产生站点确认回执;程序到统一成功结果的闭环尚未完成。
+保留本地 claim,不重跑 --submit-once,不取消已有预约来重测;其他地区未因此自动实测通过。
+
+### 27.4 下一步最小工作
+
+1. 将本次状态文本/代码、列表与详情一致性、新旧记录差异及分配时刻形状作为脱敏回归样本。
+2. 完善有效状态与本次尝试归属判定,用现有预约做只读回查;不把目标 service_id/时段硬塞
+   给新记录,不把任意非取消状态都当成功,不要求再次最终提交。
+3. 给提交响应的未知原因提供不含正文/令牌的结构化诊断;没有证据的原因仍保持待确认。
+4. 保持生产 final 关闭,生产持久未知结果阻断和 ITA-OTP-01 仍待完成。
+
+本轮仅更新验收文档;第 26 节 598 项离线结果为先前代码证据,本轮没有重跑或冒称新测试。
+
+## 28. 确认状态映射与已有回执只读验收 v4(2026-08-31)
+
+Phase: VERIFIED(本地实现与离线测试);已有有效回执的新版本只读验收待负责人执行。
+Approval: 负责人“可以,继续吧,快速推进,我可以配合你”。本轮没有访问真实网站、
+发送 OTP、再次提交、取消预约或操作本地 claim,也未改生产 final / 共享调度器。
+
+### 28.1 改动与复用
+
+- `plugins/ita_reservation.py::_state` 增加已观察到的 Confermata / 2 → ACTIVE。
+  列表没有数字状态码,文本仅用来找候选;详情必须同时匹配确认文本和代码 2。
+  Annullata / 3 保留,文本代码矛盾、未知文本、仅代码 2 或未观察英文等仍 UNKNOWN。
+- `tools/debug_ita_reservation.py` 复用原临时申请人登录、列表/详情读取、全量覆盖检查、
+  前后列表一致性、被动审计和清理;新增 `--expect-confirmed`,要求明确日期、站点分配
+  HH:mm 和显示服务名称。匹配 0 条或多条都不选第一条冒充唯一目标。
+- 只跟随已解析的实际详情链接,核对编号(仅内存)、部门、服务、日期、分配时间、状态,
+  必须是 Prenotazione Singola。列表回查与审计/清理全部通过后才输出
+  `existingReservationConfirmed=true`。不输出预约编号、申请人字段或凭证。
+- 不引入新文件/框架或站点调用;只读工具不调用 query/book/final,不读写本地防重复 claim。
+  显示服务名匹配不是 service_id 绑定;`bookingAttemptAttributed=false` 始终明确区分
+  “现有确认预约核验”与“历史提交的唯一归属”。最终读端的空/取消基线限制未放宽。
+- 不为未知提交响应猜造成功 JSON、HTTP 状态或网络字段,不要求再提交一次重抓包。
+  自动 OTP、生产持久未知结果阻断、最终归属与统一成功结果仍是独立待完成项。
+
+### 28.2 测试与准出
+
+新增 13 个测试:解析器 4 项(确认样本、矛盾状态、取消/确认并存、非香港/不同日期),
+只读工具 9 项(唯一匹配、无网络预检、错误参数、歧义、详情不一致、历史变化、意外业务
+请求、CLI 接线等)。合成编号/链接,业务状态及分配时刻形状来自第 27 节证据。
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_ita_reservation test.test_debug_ita_reservation test.test_ita_final_read_port test.test_ita_final_evidence
+```
+
+exit 0,125 项,1.754 秒。按第 26.2 节列出的 23 个 Italy 测试模块再次完整回归:
+exit 0,611 项,6.049 秒,无跳过;这是 Italy 范围,不是整个仓库测试。
+
+下节命令把 --run 替换为 --preflight 的本地结果:exit 0,
+`receipt-readonly-confirmed-v4` / `a4840ececb10`;external_requests=0、credentials_read=false、
+browser_created=false。原 Book v8 将因共享解析器变化产生新指纹,不重跑真实提交。
+
+### 28.3 负责人只读验证命令
+
+```sh
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+PYTHONDONTWRITEBYTECODE=1 python -B tools/debug_ita_reservation.py --run \
+  --expect-confirmed \
+  --expected-date 2026-09-03 \
+  --expected-time 09:26 \
+  --expected-service 'Visti Nazionali e Schengen'
+echo "EXIT_CODE=$?"
+```
+
+只输入申请人登录凭证,不需要预约 OTP;读取 Reservation → 匹配详情 → Reservation。
+准出:`passed=true`、`confirmedDetailMatched=true`、`existingReservationConfirmed=true`、
+`listUnchanged=true`、`auditVerified=true`、五项业务请求全部 0、清理成功、EXIT_CODE=0。
+默认模式的 cancelledDetailMatched 在本确认模式为 false 是正常,不是失败。
+回传 ITA_RECEIPT_GATE_RESULT 即可。不能因只读测试失败就取消或重新创建已有预约。
+
+## 29. v4 已有确认回执只读实测通过(2026-08-31)
+
+Phase: VERIFIED(用户回传的现有确认预约只读验收)。本轮只更新证据文档,不修改代码,
+不运行真实登录/预约、不删除本地 claim,也不将历史离线测试冒充本轮重新运行。
+
+### 29.1 来源与验收结果
+
+负责人在自己终端执行第 28.3 节命令,回传合同 `receipt-readonly-confirmed-v4`,
+源码指纹 `a4840ececb10`,与第 28 节本地已测指纹一致。只记录脱敏结果,不保存凭证。
+
+- `passed=true`、`exitCode=0`、`stage=completed`、shell `EXIT_CODE=0`。
+- `confirmedDetailMatched=true`、`existingReservationConfirmed=true`,回执日期
+  `2026-09-03`、分配时刻 `09:26`;状态 `active`,站点文本/代码 `Confermata / 2`。
+- `serviceDisplayMatches=true`、`singleBooking=true`。这是显示服务匹配及单人类型核验,
+  不是读取到了 service_id 或 Calendar 的隐藏时段 ID。
+- `listReady=true`、`listUnchanged=true`,列表记录数前后均为 2。
+- `auditVerified=true`;availability、AVANTI、final、OTP、time-slot 五项业务请求均为 0。
+- `cleanupOk=true`、`finalSubmissionEnabled=false`,无日期诊断错误。
+- `cancelledDetailMatched=false` 为本次确认模式的预期;并非取消历史核验失败。
+- `bookingAttemptAttributed=false` 保持边界:已确认该登录账号存在目标显示服务/日期/时刻的
+  有效预约,但本只读工具没有绑定过去提交的 attempt 或向生产返回 Book 成功。
+
+### 29.2 当前结论与下一阶段
+
+第 28 节全部真实只读准出条件已满足,不需重复运行该验收或重新创建预约。
+结合第 27 节,香港样例已取得“单次真实提交产生新确认回执”及“新版本程序只读识别该
+有效回执”的分阶段证据;不能把两次不同会话的验证说成一个生产 Book 调用已经返回成功。
+
+接下来优先完善最终结果接线:把当前尝试与匹配回执的关联证据接入现有最终核验核心,
+向统一 VSBookResult 回传正确结果,避免真实预约成功后调度器仍按普通失败处理。
+现有确认回执用于只读/离线验证;不重跑 --submit-once,不清除防重复标记,不取消预约。
+原提交响应 unknown 的具体原因、生产持久未知结果阻断、自动 OTP 仍为未完成项。
+
+## 30. 本次提交归属与统一成功结果接线(2026-08-31)
+
+负责人“没问题,继续推进”授权下的本地实现与验证。本轮没有登录真实网站、发送 OTP、
+最终提交或取消预约,没有读取/删除真实 claim,没有开启生产 final 或修改共享调度器。
+用户已有的 2026-09-03 09:26 确认预约不需要重建,也不要求重复执行只读验收。
+
+### 30.1 复用与代码归属
+
+继续使用现有最终核心和读取端的组合/端口适配方式,不新增第二套预约流程或结果模型:
+
+| 现有文件 | 本次职责 |
+| --- | --- |
+| `plugins/ita_booking_final.py` | 原生单次提交;分别判定请求是否匹配、响应为何未知;最终核心输出原有 `VSBookResult` |
+| `plugins/ita_final_read_port.py` | 同一申请人会话读取完整基线/新回执;验证显示服务、状态、单人类型、日期和分配时刻 |
+| `tools/ita_final_evidence.py` | 复用核心、原生提交器和本地持久 claim;接通请求证据与回执、保留成功结果 |
+| `tools/debug_ita_book_gate.py` | 原请求审计证实最终请求恰好一次;汇总结果、后续审计、清理均通过才输出成功验收 |
+
+VFS/BLS 的统一 `VSBookResult`(account / urn / book_date / book_time)继续复用,
+不复制它们不同站点的成功字段。生产 `ItaPlugin.book()` 的 pre-final 边界保持不变。
+本轮唯一新增文件为离线测试 `test/test_ita_final_attribution.py`。
+
+### 30.2 成功判定合同
+
+1. 仍要求申请人、浏览器/标签、会话代次、route、准备上下文和 PrecommitApproval 连续一致。
+   提交前完整基线只允许空列表或已核实的取消历史;有效/未知记录不能直接跳过后重约。
+2. 从当前已到达的 Calendar URL 唯一 `selectedService` 参数捕获显示服务名称,不由
+   Hong Kong、4937、route 文案或配置猜造;缺失/重复名称不能建立新回执归属。
+3. 监听器观察到的原生 `POST /BookingCalendar/InsertNewBooking` 必须属于当前标签,
+   三个字段分别匹配已选隐藏 ID、日期、完整时段/库存文本。保留已验证请求的独立
+   `VerifiedSubmission`;未知响应不抹掉已经取得的请求证据。
+4. 验收入口须另证最终请求计数 0→1,其他业务请求无新增,再向读取端交付该证据。
+   单个 packet 不是“全程只有一次请求”的证明。未观察到匹配请求则不能建立归属。
+5. 同一申请人会话中,新旧列表完整且详情一致、历史业务字段指纹不变,只能新增一条回执。
+   新回执必须为 `Confermata / 2`、`Prenotazione Singola`、同一显示服务与日期,
+   网站分配 HH:mm 位于原选时段内。明确拒绝响应与新增确认回执矛盾时仍返回 unknown。
+6. 回执不包含 service_id 或所选时间区间,因此对应字段保持 None;关联来自单独的
+   已验证提交证据,不能把目标值硬塞进回执假装网站返回了这些字段。
+7. 核心确认后返回 `VSBookResult(success=True)`,预约编号仅保留在内存返回值,
+   book_time 使用网站实际分配时刻,例如 09:26,不替换成 09:15–10:00。
+   额外只读观察的 bookingConfirmed 仅在核心已确认且新读结果一致时才为 true。
+8. 最终入口完成后续请求审计、记录数检查和清理才 `passed=true / exit 0`;
+   后续重复请求、对账失败或清理失败不能报告验收通过。核心先前取得的确认事实保留,
+   失败不意味着可再次提交;本地 claim 无论成功/失败/未知都保留。
+
+这套归属依赖同一申请人工作流串行、验证期间没有另一客户端同时为其提交的运行前提。
+它是本次工作流证据关联,不是服务器回传的请求唯一 ID,也不是跨节点 exactly-once。
+正式接入生产前仍需用既有账号/订单协调和任务状态机制落实这一前提。
+
+### 30.3 诊断及收尾修正
+
+- 新 `submissionDiagnostic` 只返回 requestMatched 与固定原因:请求元数据、字段或
+  选中目标不匹配;响应元数据、正文、字段、目标地址不识别;原生动作/监听异常。
+  不输出原始请求、响应、令牌、账号、预约编号或服务器错误正文。
+- `submissionSignal=unknown` 不是一律失败:请求证据完整、唯一匹配回执确认且无矛盾时
+  可以成功;没有匹配请求或对账证据则仍 unknown,不自动重试。
+- 修复整链路测试发现的收尾错误:已授权提交后若尚停留 Calendar,不能再调用要求
+  历史 final 请求为 0 的 pre-final guard。原生提交器仍重新禁用按钮,提交后走最多一次
+  final 的审计;Query / pre-final 的零提交约束没有放宽。
+- 旧 v8 没有记录上述细分诊断,不能根据新代码猜测当时 unknown 的真实原因,也不能
+  将已有回执只读结果倒填为该历史 attempt 的完整请求归属证据。
+
+### 30.4 离线验证与准出
+
+新增 15 项测试:14 项归属/核心/读端/原生诊断测试,1 项真实入口组合测试含四个子场景。
+使用已观察业务形状及合成账号/编号/链接,不含真实凭证或网络操作。覆盖:
+
+- 唯一新确认回执返回成功与正确分配时刻;未知响应但请求匹配时仍可核验。
+- 请求证据缺失、审计未通过、会话/目标变化、服务/日期/时刻/单人类型/状态不符。
+- 已有有效基线阻止提交、历史变化、多个新增、明确拒绝与回执矛盾。
+- 核心→本地控制器→验收入口成功接线,及后续重复请求、清理失败、对账失败不误报通过。
+- claim 保留,未伪造回执字段,输出不泄露预约编号或账号。
+
+完整 Italy 回归:第 26.2 节原 23 个模块加 `test.test_ita_final_attribution`,
+`PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q ...`,
+**626 项,5.751 秒,OK / exit 0**;仅表示 Italy 测试范围,不是全仓库测试。
+
+香港样例配置下运行 `tools/debug_ita_book_gate.py --preflight --verify-receipts`,
+**book-final-attribution-v9 / 1949de666430,exit 0**;
+external_requests=0、credentials_read=false、browser_created=false。
+没有传入 --run 或 --submit-once。`git diff --check` 通过;未跟踪改动文件另做空白检查。
+
+本阶段已满足本地实现/离线整链路准出,不声称新版真实最终提交已验收,也不需要为开发
+重复创建预约。下一优先级:在最大化复用现有 Booker/订单状态的前提下,接生产任务成功
+回传与持久未知结果暂停/恢复;落实跨进程防重后再开放生产 final。ITA-OTP-01 保持待办。
+
+## 31. 生产上线缺口与任务后端竞争复现(2026-08-31)
+
+> 后续范围决定:本节保留为历史调查证据。§31.4 的共享后端改造不是当前实现前置条件;负责人要求按 VFS/BLS 现有链路先接通,见 §32。已知共享层风险并未因此被修复,也不宣称跨节点/崩溃场景严格一次性提交。
+
+负责人要求继续推进到 Query/Book 可上线,OTP 自动化放到最后。本轮核对 Coordinate
+实际代码,并只读检查已定位的 `/Users/zhangwei/JSWorkSpace/personal/webapp` 后端。
+没有修改后端或生产业务代码、调用真实任务 API、连接数据库/Redis、重新预约或删除 claim。
+发现原有任务接口不足以承载提交前原子认领,实施跨仓库共享接口修改前需要范围确认。
+
+### 31.1 可复用事实与已确认缺口
+
+| 部位 | 已有能力 | 上线缺口 |
+| --- | --- | --- |
+| Query 核心 | 逐月首个正向月份、最早日期、现有快照 | Sentinel 创建会话后没有完成 Calendar 准备/恢复接线;不能把调试工具准备态当生产能力 |
+| 会话恢复 | 同账号 checkpoint 恢复、15 分钟受控恢复证据 | 生产实例生命周期接入;需要 OTP 时保留人工接续,不要求本轮自动取码 |
+| Book 核心 | 独立申请人重查、选择、单次原生提交、回执归属 | 生产 `ItaPlugin.book()` 仍停在 pre-final,未连任务上下文与持久认领 |
+| OrderBooker | 原 `pause/grabbed` 状态、成功上报 | 普通异常含最终结果不明仍可被下一信号再次调用;任务缓存刷新间隔 15 分钟 |
+| 成功上报 | 原 `grabbed_history` 与通知格式 | 云端更新放在线程队列,而 tracker 先移除;进程退出可丢失尚未上报的成功结果 |
+| Sweeper / 后端 | 按状态排除暂停/成功;任务 pop 已用 MySQL 行锁 | 前端检查与后端重新入队不在一个原子操作内;回收接口无条件覆盖状态 |
+| 发布 | 现有容器与依赖清单 | Italy 已拆多模块,不能只热更单个 ita_plugin.py;应验证整包一致性与真实运行依赖 |
+
+本地 `.venv` 直接 import Booker 缺少 redis;requirements.txt 已声明该依赖。既有 Italy
+离线测试使用导入替身,因此 626 项通过不能被解释为真实 Sentinel/Booker 运行环境已验收。
+本轮未安装依赖或运行生产服务。此前 626 项结果为第 30 节证据,本轮没有声称重新运行。
+
+### 31.2 后端原代码证据
+
+- `webapp/app/services/vas_task_service.py::pop_vas_task`:只选 pending,
+  `with_for_update(skip_locked=True)`,提交 running 并递增 attempt_count;复用现成事务/锁模式。
+- `update`:读取一行后直接写 status / grabbed_history / meta;无期望状态或工作代次条件。
+- `pause`:直接设置 pause,不能证明两个请求中只有一个取得提交资格。
+- `return_to_queue`:读取当前行后直接设 pending;即使当前已 pause/grabbed 仍覆盖。
+- schema 与模型已有 `pending/running/pause/grabbed/cancelled/completed`;不要另造未支持的
+  `processing/outcome_unknown` 状态字符串。`meta` 可承载扩展事实,但普通 JSON 更新不是原子锁。
+- Coordinate Sweeper 先 detail、再 return_to_queue,这两个 HTTP 调用之间存在竞争窗口。
+  仅在 Sweeper 增加一次客户端状态检查仍不能关闭窗口,必须由后端原子条件保证。
+
+### 31.3 离线复现结果
+
+执行方式:用 AST 提取后端实际 update/pause/return_to_queue 方法,仅移除 staticmethod
+装饰器、延迟求值注解,使用内存会话替身执行原方法体;不 import 后端应用或数据库配置。
+客户端使用实际 OrderBooker `_execute_book_job` 与 BaseBooker `_push_success_notification`,
+云端 API、线程队列与 Redis 均为替身。它验证调用和状态转换缺口,不冒称真实数据库并发压测。
+
+复现最终 exit 0,后端服务源文件 SHA-256 前缀 `eae2f1408502`,externalRequests=0:
+
+```json
+{
+  "pause": {"beforeStaleRequeue": "pause", "afterStaleRequeue": "pending"},
+  "grabbed": {"beforeStaleRequeue": "grabbed", "afterStaleRequeue": "pending"},
+  "repeatedPauseRejected": false,
+  "clientUnknown": {"bookCallsOnTwoSignals": 2, "cloudPauseCalls": 0},
+  "clientSuccess": {"queuedAsyncWork": 1, "cloudWritesBeforeTrackerRemoval": 0, "trackerRemoved": true}
+}
+```
+
+注意 exit 0 表示复现断言成立,即确认当前缺口存在,不是修复测试通过。前两次复现脚本
+因本地缺 redis / 临时替身作用域导致导入失败,未执行任何外部调用;最终调整离线导入
+替身后得到以上结果,不将导入失败当作业务竞争证据。
+
+### 31.4 最小修正方向及待确认范围
+
+优先复用既有 MySQL 事务、任务行、attempt_count、pause/grabbed 和 meta,不另建调度器,
+不以本地 claim 或 Redis TTL 冒充持久提交账本。需要在以下范围关闭合同:
+
+1. Webapp 的 VAS 任务 service/schema/endpoint:提交前原子认领和持久记录;核对工作代次,
+   阻止失效 Worker;重新入队和一般状态更新不得覆盖已认领/结果未知/已成功任务。
+2. 同申请人多订单也需互斥,不能把“同 task_id 只能一个”误称为“同账号只能一个”;
+   复用现有账号/订单关系是否足够需进一步确认,若确需新增表/迁移另列范围,不先实施。
+3. Coordinate 的云任务客户端、Booker、Sweeper:传递受信任务上下文,结果未知暂停并
+   仅对账;确认成功先可靠保存,再结束任务,通知失败不触发再预约。
+4. 接完生产层后,复用现有 Calendar 准备/查询/Book/回执核心;自动 OTP 暂缓但保留人工
+   接续。不得把需要人工 OTP 错写成无人值守完成。
+5. 回归至少覆盖:两个 Worker 同时认领、旧 Worker 恢复、认领前后崩溃、暂停与回收竞争、
+   成功上报丢响应、重复信号、同账号不同订单、既有 VFS/BLS 行为兼容,以及整包发布预检。
+
+这不是必须重写 VFS/BLS 的结论,而是它们所在共享任务层尚缺本项目已经明确要求的
+持久一次性提交合同。下一步先确认允许进入 webapp 共享任务接口及 Coordinate 调度层,
+然后实现、离线并发/故障测试,必要时再请负责人执行受控真实验收;不擅自部署或改线上数据。
+
+## 32. 按 VFS/BLS 现有链路的最小生产接线(2026-08-31)
+
+### 32.1 范围与复用
+
+负责人明确授权:不扩展共享后端,按 VFS/BLS 的现有方式推进。现有链路仍为
+`Sentinel → VSQueryResult/Redis → OrderBooker → plugin.book → VSBookResult → grabbed_history`。
+不新增服务、表、队列、分布式锁、调度器或生产本地 claim;不修改 VFS/BLS 的站点代码。
+
+| 位置 | 职责 / 复用来源 |
+| --- | --- |
+| `plugins/ita_plugin.py` | 保留统一 query/book 接口及原默认行为;显式人工 OTP 工作模式进入完整流程 |
+| `plugins/ita_calendar_session.py` | 从已实测的 Calendar gate 提取表单检查、OTP 写入/读回、AVANTI 跳转验证和被动请求计数;调试工具改为引用同一份实现 |
+| `plugins/ita_workflow.py` | 轻量流程编排:准备 → 调用现有查询/选位模块 → 调用现有最终提交/回执模块;不 import tools |
+| `plugins/ita_calendar_query.py` / `ita_calendar_book.py` | 原逐月扫描、首个正向月份停止、最早日期、用户会话选位逻辑不重写 |
+| `ita_booking_final.py` / `ita_final_read_port.py` | 原生提交一次、请求归属、列表/详情回读、Confermata/2、网站分配时刻;复用而非重建 |
+| `booker.py` / `vs_types.py` | 成功仍走原上报;增加通用未知结果异常分支,禁止下一信号重提,复用现有 pause API |
+
+Query 使用团队账号,Book 使用订单申请人账号,禁止复用 Query 准备态。地区差异仍由
+`apt_configs[routing_key]` 的 service_id、表单控件和值/多语言标签配置;香港不是算法常量。
+
+### 32.2 可启用配置(本轮没有改动运行配置)
+
+沿用已有完整 single_schengen_tourism 路由配置,仅增加/设置下列 free_config 字段:
+
+| 用途 | query_mode | otp_mode | final_submit_enabled |
+| --- | --- | --- | --- |
+| 团队 Query | calendar | manual | false |
+| 申请人 Book,仅选位验收 | services_probe | manual | false |
+| 申请人 Book,真实提交 | services_probe | manual | true |
+
+不设置 otp_mode 时仍保持旧调试/准备边界,避免旧命令突然创建预约。Query 配置不得启用
+final。Book 的 services_probe 只用于进入该申请人的表单,不将入口存在当成有号结果。
+Book 单次公共调用现在可以从 Dashboard 一直走到选位/最终回执,不需要外部脚本分两次 book。
+
+OTP 暂时由操作者在同一终端输入;无 TTY 在发送 OTP 之前停止。多工作线程共享的锁仅用于
+避免终端输入串码,不锁账号/库存。准备中失败不会在每次查询时反复发送 OTP;重新登录后
+允许再次人工准备。已有准备会话继续扫描,不重新发送 OTP。自动取码/重取码仍是 ITA-OTP-01。
+这是可人工值守的接入版本,不是无人值守部署完成。
+
+### 32.3 最小结果处理
+
+- 成功:新增唯一匹配确认回执 + 原生请求归属,返回原 VSBookResult;book_time 使用网站
+  分配时刻,而不是所选时段。仍由现有 Booker 上报,不增加 Italy 专用上报器。
+- 明确无号/明确拒绝:返回原失败结果,按原调度策略等待下一信号。
+- 可能已提交但证据不足:抛通用 BookingOutcomeUnknownError(Italy 为 FinalOutcomeUnknown),
+  当前任务 book_allowed=false,调用现有任务 pause。只人工核查后恢复,不自动重提。
+- 暂停接口失败:保留当前进程禁用标记并提示人工暂停;不声称进程退出后仍能靠内存标记
+  阻断重入。§31 的后端重入队竞争、异步上报掉电窗口仍为共享层现状,不在本轮扩围。
+- CLI 的旧最终验收 claim 与既有真实确认预约没有修改、删除或重跑。
+
+### 32.4 离线验证与准出边界
+
+原 626 项 Italy 测试及新增 `test.test_ita_workflow` 24 项通过。新增覆盖:
+原接口从 Dashboard 准备并选位、Query 准备一次/不发布弱正向、默认不最终提交、显式
+申请人开关、Query/Book 身份隔离、OTP 冷却/写入验证、无终端发送前停止、错 tab、部分
+准备失败不重复发码、真实回执解析器与最终核心组合、缺单次请求证据保持未知、重复
+信号不重提、成功走原上报、暂停接口失败保留本地阻断、旧 Query CLI 的显式工作模式。
+
+测试均使用合成数据/浏览器与网络替身;没有登录、请求 OTP、预约、Redis 或云任务写入。
+`git diff --check`、Query CLI `--help` 通过。本地 `.venv` 缺 redis,Booker 测试沿用已有
+导入替身;真实部署环境仍须安装 requirements 依赖,不能把此结果等同于服务启动验收。
+
+研发接线准出:上述离线回归通过,旧默认行为保持、生产不依赖 tools、未改其他插件。
+上线准出尚待:新公共 Query 入口真实验证、申请人 Book 的新入口验证、部署依赖及整包
+发布检查。Italy 多模块必须随同发布,不能只更新 ita_plugin.py;当前没有执行部署。
+
+### 32.5 下一次真实验证命令(只 Query,不预约)
+
+沿用香港示例,路由全部显式传入。该命令调用生产 Query 入口;人工输入一次 OTP 后查
+最早日期并退出,不调用 book、不点击最终确认。使用已授权且确实归属香港机构的 Query
+账号;凭证留在本地,不粘贴密码/OTP。
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 python -B tools/debug_ita_query.py --production-workflow
+echo "EXIT_CODE=$?"
+```
+
+正向期望:ITA_QUERY_WORKFLOW_RESULT 中 earliestDate 有值、finalSubmissionEnabled=false,
+清理成功、exit 0。自然无号可以 exit 0,但不能据此证明正向查询。真实 Book 使用已有
+订单模式和申请人账号;现有确认预约未处理前不要为了验证再创建一笔。
+
+## 33. 新 Query 公共入口真实验证通过(用户终端回传)
+
+用户执行 §32.5 命令后回传:
+
+```text
+Italy Calendar probe index=0 available=0
+Italy Calendar probe index=1 available=1
+Italy Calendar found the first positive month; earliest_date=2026-09-03.
+ITA_QUERY_WORKFLOW_RESULT={"availabilityStatus":"Available","earliestDate":"2026-09-03","finalSubmissionEnabled":false,"success":true}
+ITA_QUERY_CLEANUP_OK
+EXIT_CODE=0
+```
+
+结论:新公共 Query 入口单次正向实测通过;扫描至首个正向月份后返回最早日期,清理成功。
+`2026-09-03` 是本次观察结果,不是未来仍可预约的保证。回传为末段日志,不含本次 OTP/
+AVANTI 数量或源码指纹,因此不补写未知计数,不声称独立 Network 审计或无人值守验收完成。
+工具输出 finalSubmissionEnabled=false;本轮未调用 Book、创建或取消预约,也未部署。
+下一步:验证新 Book 公共入口从申请人登录到选位的完整调用,保持最终提交关闭。
+
+## 34. 新 Book 公共入口选位验收命令
+
+在原 `tools/debug_ita_book.py` 增加 `--production-workflow`,复用原路由配置构建器、
+生产 `book()`、既有 precommit 读回验证和被动请求计数器;不新增生产预约流程。
+默认旧模式不变,新模式固定 `otp_mode=manual / final_submit_enabled=false`,不提供
+最终提交开关。单次公共 book 调用自行完成表单准备与选位;不会调用旧 gate 分两次 book。
+
+凭证只取 `ITA_BOOK_USERNAME/ITA_BOOK_PASSWORD` 或人工输入,不回落到通用 Query 环境
+凭证/Query 账号文件;申请人使用独立临时浏览器会话。该选位测试不要求取消已有确认预约。
+
+新增 9 项 CLI 测试,含身份传递/环境隔离、旧默认保留、无号不算选位通过、读回失败、
+意外最终请求、末尾审计失败、清理失败与参数冲突。659 项 Italy 离线回归通过(5.534 秒,
+exit 0);Book CLI `--help` 和 `git diff --check` 通过。本轮只有文档/本地 CLI/测试变更,
+未改变 Query/Book 生产算法,未操作真实浏览器、账号、OTP、预约或部署。
+
+下一次由用户在自己的终端执行(香港仅为配置样例):
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 python -B tools/debug_ita_book.py --production-workflow
+echo "EXIT_CODE=$?"
+```
+
+验收看 `ITA_BOOK_WORKFLOW_RESULT.selectionVerified=true`、选中日期/时段存在、
+`finalSubmissionEnabled=false`;末尾 `ITA_BOOK_WORKFLOW_AUDIT.finalRequests=0`,清理成功、
+EXIT_CODE=0。`bookResultSuccess=false` 是预期,因为测试停在最终提交之前。无号 exit 2
+表示本次缺选位正向证据,不表示发生预约。不要分享密码/OTP。新入口真实 Book 最终成功
+上报及部署环境验证仍未完成,不能把选位验收或既有 v8 预约回执当作这一环已经通过。
+
+## 35. 新 Book 入口被已有预约挡住:Services 现场证据与诊断补充
+
+2026-08-31,用户回传 §34 新公共入口失败:目标 `/Services/Booking/4937` 不存在,
+Services 表 1 个、行 9 个、其他 booking 链接 8 个、目标链接 0 个;五类业务请求均 0,
+清理成功、exit 1。不是 OTP、月份扫描或选位失败,尚未进入这些阶段。
+
+随后用户截图确认机构为香港总领馆,目标服务行 `Visti Nazionali e Schengen` 的预约
+单元格显示 `Prenotazione già effettuata per questo servizio`(该服务已经预约过),
+而不是 PRENOTA。相邻商务签证 EXTRA SLOTS 行仍有按钮,不能拿它替代旅游目标服务。
+本证据与此前已确认的现有预约一致;不需修改 4937,不将此情况当作库存为空,
+不取消已有预约、不直接拼接目标 URL 继续提交,也不将历史预约算作本次 Book 成功。
+
+### 35.1 最小实现与已知边界
+
+代码继续放在 `plugins/ita_plugin.py` 既有 Services 诊断函数中;复用原
+`ItaTargetServiceLinkMissingError`、调用链和清理逻辑,不新增工作流、路由字段、
+平台状态或 VFS/BLS 改动。新增 `already_booked_notice_row_count`:只统计单元格中
+完整匹配已观察意大利语提示的可见行,允许大小写/空白/末尾标点差异,返回计数而非
+服务行内容、邮箱或预约编号。其他文案仍不猜测。
+
+目标链接缺失且存在该提示时,异常补充“页面包含已预约提示,请核对目标行和现有预约”。
+**这是页面级诊断,不是自动完成的目标服务归属判断**:当前路由只有 service_id,
+无链接的行尚无已验证 ID 绑定;不能因另一个服务已预约就认定目标也已预约。截图中
+的目标归属由用户提供,生产代码不会硬编码香港或服务名。目标链接仍在时按原流程走,
+无关行不会阻止它;未知提示/无提示仍保留原缺链接错误。现有错误类型及调度重试语义
+未改变,本次不宣称实现“已有预约自动暂停订单”。
+
+### 35.2 验证与下一步
+
+新增 6 项离线测试:真实生产 JS 在合成 DOM 下的提示匹配/隐藏与否定文字排除、
+按行计数且不导出文本、缺链接提示不越权归属、其他服务已有预约不阻止目标、异常
+计数处理、Book 传播诊断而不制造成功。665 项 Italy 离线回归通过(6.419 秒、exit 0)。
+没有登录网站、发 OTP、提交/取消预约、修改账号或部署;现场新诊断尚未实测。
+
+新 Book 公共入口选位验收仍待完成:需要一名已授权、归属目标机构且该服务尚未预约的
+申请人账号,沿用 §34 最终提交关闭的命令。先前真实预约和 Query 正向证据继续有效,
+但不替代该新入口验收。OTP 自动化仍为 ITA-OTP-01,留到最后。
+
+## 36. 新 Book 公共入口选位真实验收通过(用户终端回传)
+
+用户先告知已自行取消该账号的预约,随后执行 §34 的 `--production-workflow` 命令,
+回传如下末段日志。取消操作由用户自行完成,本轮助手没有执行取消,也未独立读取
+取消回执;本次能继续至 Calendar 选位,说明此前的服务入口阻点在本次运行中已解除。
+
+```text
+Italy Book Calendar month=2026-08 candidates=0
+Italy Book Calendar month=2026-09 candidates=1
+Italy Book selected current user Calendar slot date=2026-09-03 time=09:15 - 10:00; stopped before final confirmation.
+ITA_BOOK_WORKFLOW_RESULT={"bookResultSuccess":false,"finalSubmissionEnabled":false,"remaining":2,"requests":{"availabilityRequests":3,"avantiPosts":1,"finalRequests":0,"otpRequests":1,"timeSlotRequests":2},"selectedDate":"2026-09-03","selectedTime":"09:15 - 10:00","selectionVerified":true}
+ITA_BOOK_WORKFLOW_AUDIT={"availabilityRequests":3,"avantiPosts":1,"finalRequests":0,"otpRequests":1,"timeSlotRequests":2}
+ITA_BOOK_CLEANUP_OK
+EXIT_CODE=0
+```
+
+结论:新公共 Book 入口到选位的真实验收通过,不再列为待办。报告与末尾请求审计一致:
+OTP 1 次、AVANTI 1 次、日历查询 3 次、时段查询 2 次、最终提交 0 次。选位读回验证
+通过、清理成功;`bookResultSuccess=false` 是停在最终提交前的预期结果,不是失败。
+`remaining=2` 是选位时观察到的余量,不是锁定名额或未来库存承诺。日志中的月份扫描
+与返回日期符合首个正向月份停止的合同。请求计数是本次完整准备/扫描流程的总计,
+不能把 3 次 availabilityRequests 都解释成扫描了 3 个月。
+
+证据范围:用户回传末段日志,未附本次源码指纹、完整登录日志、前后预约列表或
+独立网络导出,因此不补写这些缺失证据;此前 665 项离线测试仍是 §35 的历史结果,
+不是本轮重新执行的结果。本轮仅核对本地 CLI 合同并更新文档,无生产代码改动、
+真实浏览器操作、预约提交、云端写入或部署。
+
+下一阶段是上线收尾,而不是重复 Query/Book 选位测试:沿用 VFS/BLS 的现有
+OrderBooker/标准 VSBookResult 成功上报链路,完成新公共 Book 最终结果与订单状态的
+端到端验收,并检查部署依赖、Italy 多模块整包发布与运行配置。先前 gate 的真实预约
+证明站点最终提交可行,但不等于这条新生产链路已真实验收;本次选位通过也不等于
+已上线或无人值守可用。OTP 自动化继续留到 ITA-OTP-01,按用户要求最后完成。
+
+## 37. 原 Booker 成功上报链路贯通回归与发布检查
+
+### 37.1 实现决策:复用原流程,不新增 Italy 上报器
+
+用户授权继续推进 §36 后,本轮检查 `ItaPlugin.book` → `ita_workflow.book/submit_final`
+→ `NativeFinalSubmitter` → `FinalReceiptReadPort` → `VSBookResult` →
+`OrderBookerGCO._execute_book_job` → 原 `_push_success_notification`。
+现有接线已具备该路径,不需要增加生产分支、订单状态、队列或新上报接口。
+
+此前测试分别验证了 Book 最终核心与 Booker 调用上报入口,但 Booker 测试替换了
+`_push_success_notification`,没有证明实际组装的云端更新字段。为此新增
+`test/test_ita_booker_integration.py`,职责仅为这条跨模块连接的离线验收:复用现有
+Calendar 浏览器替身及回执样本,实际执行公共 Book、扫描/选位、NativeFinalSubmitter、
+最终核心、回执解析、原 Booker 任务移除及原异步上报回调。浏览器/数据包、被动 CDP
+计数、Redis、云接口和执行队列均为替身;测试从已准备的 Calendar 开始,不宣称独立
+验证了真实登录/OTP,也没有调用真实网络。生产代码仅修正两处过时的模块/类说明,
+不改变算法、配置开关或其他插件行为。
+
+新增 8 项验收覆盖:
+
+1. 正向结果交给原异步回调,订单 ID 正确,status=grabbed;grabbed_history 含正确
+   account/urn/slot_date,以及回执实际分配时刻而非所选时间区间;密码不进入上报。
+2. 最终提交关闭时,只选位,不更新订单、不通知。
+3. 原订单 expected_start_date / expected_end_date 传至生产选位逻辑。
+4. 服务器明确拒绝且回执没有新增时,保留原失败等待下一信号分支,不报告成功。
+5. 可能提交但未确认时走原 pause 接口,下一信号不重复提交。
+6. 有新增确认回执但请求归属不匹配时,不报告当前任务成功。
+7. 上报回调入队失败后,下一信号复用本次已确认结果,不再创建预约。
+8. 云接口失败时不发成功通知,记录原有失败日志;不把“已入队”当作“云端已更新”。
+
+第 8 项也保留了原 VFS/BLS 共享链路的已知限制:异步回调内部云端失败不会新增自动
+重投队列;本轮遵循用户要求不改平台语义,实际验收必须查云端订单结果。跨进程可靠性
+不是这组测试证明的内容。
+
+### 37.2 真实本地验证结果
+
+- 新增集成测试 8 项通过(0.026 秒)。
+- 完整 Italy 回归 673 项通过(6.459 秒,exit 0),包含新增模块。
+- 首次无替身导入发现 `.venv` 缺 redis;已补齐 requirements.txt 中原本声明的该依赖,
+  安装版本 redis 8.1.0。未新增依赖条目、未升级其他包。
+- 新进程真实导入 `booker`、`redis`、`plugins.ita_plugin`、`plugins.ita_workflow`
+  通过(exit 0),没有启动工作线程、Redis 连接、浏览器或云请求。
+- `python -m pip check` 通过;仅证明已安装包依赖一致,不等于全部部署组件已验收。
+- `git diff --check` 通过。未执行 commit/push、云写入、真实预约或部署。
+
+可在用户终端复核(全部离线、不预约):
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+PYTHONDONTWRITEBYTECODE=1 python -B -m unittest -v test.test_ita_booker_integration
+PYTHONDONTWRITEBYTECODE=1 python -B -c 'import booker, redis, plugins.ita_plugin, plugins.ita_workflow; print("ITA_BOOKER_IMPORT_OK")'
+python -m pip check
+```
+
+### 37.3 发布边界与下一次真实验收
+
+只读确认:本地 config_booker/config_sentinel 的 Italy 组仍 enable=false,旧 Dublin
+1321 / services_probe_only 路由、未配置人工 OTP、final_submit_enabled=false;未自动
+改成香港或启用。当前 CLI 的香港配置不等于已部署生产配置,云配置优先级也不能忽略。
+
+现有 `utils/plugin_updater.py` 一次只替换一个插件文件;Italy 此版本有 9 个生产模块:
+ita_plugin、ita_workflow、ita_calendar_session、ita_calendar_query、ita_calendar_book、
+ita_protocol、ita_booking_final、ita_final_read_port、ita_reservation,并依赖本次已有的
+booker.py/vs_types.py 共享改动。不能只发布 ita_plugin.py 后声称更新完整;沿用项目
+整仓/镜像发布方式,不建设新的热更新协议。Dockerfile 的 COPY . . 可包含整包,但
+实际镜像未构建/部署,代码暂未提交的事实也不能略过。
+
+人工 OTP 模式仍需可交互终端。默认 docker-compose 未配置 stdin_open/tty,不能将
+后台容器直接当作人工 OTP 已可运行;真实验收先在用户可输入 OTP 的终端进行。
+不将这一阶段命名为无人值守上线,自动接码仍归 ITA-OTP-01。
+
+下一项需要用户提供明确的云端任务 ID(task id),用于核对申请人、路由、允许日期、
+任务状态及最终结果归属,再给出针对该任务的真实验收命令。没有 ID 时不猜测任务、
+不让生产 Booker 任意领取队列任务、不伪造历史预约上报。到目前为止,真实预约核心
+与新入口选位已分别有现场证据,但新公共 Book → 原 Booker → 实际云端订单更新的
+端到端真实验收仍待完成;本节为离线接线及本地依赖检查通过,不是已部署。
+
+用户后续确认:目前没有用于验收的云端任务。该端到端真实订单验收保留为待办,不再
+要求现在提供 task id,不据此新建或任意领取订单。Redis 依赖已再次在项目 `.venv`
+核实:Python 客户端 redis 8.1.0 存在,Booker 无替身导入通过、pip check 通过。
+这是客户端依赖补齐,不是安装/启动 Redis 服务端,也未验证实际 Redis 连接或读写。

+ 539 - 0
docs/ita_otp_auto.md

@@ -0,0 +1,539 @@
+# Italy 自动 OTP:接入说明与验收
+
+更新:2026-08-31。范围:ITA-OTP-01,Book 自动接码及现有最终提交链路接线;Query 首次日历准备的自动 OTP 扩展见第 10 节。
+
+**最新状态(2026-08-31):用户现场已通过自动 OTP → Calendar → 选择时段的
+预确认验收,最终提交请求为 0(第 7 节)。第 8 节完成自动 OTP 复用现有最终提交的
+代码接线及 508 项离线回归;第 9 节用户现场通过空回执基线核对与选位保持验收。
+默认开关、现场命令仍不提交预约,自动完整最终提交及新回执归属尚待现场验收。
+第 1–6 节的“待现场验收/自动模式不可启用最终提交”是历史阶段合同,以第 8 节为最新代码边界。**
+
+## 1. 结论与边界
+
+本轮仅改 Italy 代码、对应测试和文档,复用现有 `VSCloudApi.fetch_mail_content()`。
+不改共享 SDK、邮件后台、nginx、其他插件、Booker 调度或生产配置;不改 Query 扫描。
+没有执行真实登录、邮箱读取、OTP 发送、表单提交或预约确认。
+
+已完成自动模式接线及离线验证。**真实自动接码仍待验收,不等于整个 Book 已可以上线。**
+此前用户已经验证人工 OTP → Calendar → 选择日期时间;那不是自动接码验收。
+`fetch-top` 找到测试邮件只能证明部分邮箱读取能力,不能证明本次 OTP 的时间筛选有效。
+此前 `/fetch` 的 504 保留为外部依赖风险,按用户要求不继续调查或修改。
+
+本次机械准出:人工模式回归通过;自动模式只调用一次现有取信接口;固定筛选参数;
+账号/会话变化、过期、歧义码、读取失败时不继续 AVANTI;没有自动重发或 top 回退;
+自动模式不可启用最终提交。现场验收是下一道门槛。
+
+## 2. 复用与文件归属
+
+| 文件 | 本轮职责 | 复用内容 |
+|---|---|---|
+| `plugins/ita_protocol.py` | 邮箱配置、确定性 OTP 解析 | 现有 route 配置与纯解析模块 |
+| `plugins/ita_otp.py` | Italy 的薄适配器、固定诊断 | 现有 `VSCloudApi.fetch_mail_content`,不再写 IMAP/HTTP 客户端 |
+| `plugins/ita_workflow.py` | 选择人工/云端取码、关联一次发送与读取 | 现有 preflight、原生按钮、OTP DOM 回读、AVANTI、Calendar 准备 |
+| `plugins/ita_plugin.py` | 显式 `otp_mode=cloud` 分流 | 现有公开 `book()`、申请人重查、时段选择 |
+| `tools/debug_ita_book.py` | `--production-workflow --auto-otp` 验收入口 | 单次调用生产 `plugin.book()`,不是另一套模拟 Book |
+
+设计采用组合:只替换“从哪里取验证码”,不重写登录、浏览器、表单、日历、选时段和调度。
+通用 route 中配置服务、预约类型、旅游目的、邮箱;Hong Kong 仅是命令示例。
+已有人工最终提交路径保留,本轮不扩大其授权。
+
+## 3. 自动模式如何工作
+
+1. 申请人账户独立登录并重新检查目标服务;不相信 Query 的旧日期时间。
+2. 进入真实表单,在发送前检查单人旅游 route、邮箱配置、会话和日志前提。
+3. 复用已有 preflight,记录 UTC 发送时间和单调时钟,然后原生点击一次发送 OTP。
+4. 确认本站返回 `SENT` 后,仅调用一次已有 `/fetch` 客户端方法。
+5. 提取验证码;重新检查账号、Session、tab、页面路径及本地时间窗口。
+6. 复用原有 OTP 输入与 DOM 一致性验证,再做 after-OTP preflight。
+7. 尚未过期才点击一次 AVANTI,进入 Calendar,复用 Book 重查和选择逻辑。
+8. 停在最终确认前:`final_submit_enabled=false`,不点击最终 Prenota。
+
+同一进程复用原有准备阶段锁,串行准备;不新建队列或跨服务锁。
+失败的准备保留同一 Session/标签/route 的尝试标记,重复信号不能自动重发。
+这不是跨进程或跨重新登录的去重;现场请仅开一个 Book 进程,不要同时手工发码。
+
+### 邮件合同
+
+| 参数 | 来源或规则 |
+|---|---|
+| `email` | route 的 `mail.authorization_email`,后台已登记的授权邮箱 |
+| `recipient` | 当前申请人站点 username,不取 Query 的账号 |
+| `sender` | 固定 `noreply-prenotami@esteri.it` |
+| `subjectKeywords` | 固定 `OTP Code`,不允许 CSV 扩大筛选 |
+| `bodyKeywords` | 固定 `OTP Code:` |
+| `sentDate` | 点击发送前记录的 UTC,`YYYY-MM-DD HH:MM:SS` |
+| `expiry` | 默认 300 秒;route 可设 1–300 的整数 |
+| `onlyText` | `true` |
+
+解析仅接受 `OTP Code:` 上下文后六位 ASCII 数字,保留前导零。
+HTML 只做非执行的文本投影;重复的同一码(plain + HTML)合并;不同码并存、
+模板未知、超长或格式异常则拒绝。邮件不进入 LLM,不执行其中任何指令。
+
+重要限制:后端只返回正文。客户端无法独立检查原始发件人、收件人或消息时间。
+固定完整 sender 参数不等于后端精确地址匹配,更不等于发件人认证。
+新旧邮件筛选依赖当前后台合同,现场尚未证明;不宣称“绝不会读到旧码”。
+本地窗口只能拒绝迟到的返回,不能中断阻塞的 SDK 调用,也不是网站 OTP 有效期的证明。
+UTC 时间只精确到秒,同一邮箱不要并行触发多个流程。
+
+### 失败行为
+
+- `/fetch` 504、授权/权限错误、限流或异常:固定的 Italy 错误,不输出正文或原始异常。
+- 邮箱 API 的 401 不伪装成预约网站 Session 失效,避免误导重登。
+- 无邮件或多个不同码:停止,不提交,不改用 `fetch-top`,不自动改成人工读码。
+- 取信后账号/Session/页面变了:丢弃码;窗口超时:不写入或不继续 AVANTI。
+- DOM 写入失败:不继续 AVANTI;自动模式屏蔽可能包含输入值的浏览器异常。
+- 人工模式保持原来行为,手工 OTP 输入可能保留在终端滚动记录。
+
+Italy 不改公共日志配置。共享 SDK 在 DEBUG 下会记录正文,因此自动模式在发送前、
+取信前检查其活动 logger;DEBUG 开启时拒绝自动运行。
+需要整个取信期间保持 INFO 或更高等级,不能中途改 logger;这不是对后台日志、
+第三方追踪系统或运行时日志热切换的全面脱敏保证。
+
+## 4. 本地操作:只做一次自动接码验收
+
+### 准备
+
+确认后台已经登记将接收 OTP 的邮箱;站点登录账户也应能收到该邮箱中的验证码。
+如果刚更换站点账号,确认它在香港且可以进入目标旅游服务。
+本次不要同时运行另一个 Query/Book 准备过程,不要手动点击发码或最终确认。
+
+不要把 Gmail 应用密码、邮箱后台 Bearer、网站密码放入这份文档或聊天。
+Gmail 应用密码仍由已有后台管理,Coordinate 这里只需要授权邮箱地址。
+
+### 执行
+
+在自己的终端执行下面命令。把 `已在后台登记的邮箱地址` 替换成真实登记地址;
+例如本人刚换过账号,不能沿用旧邮箱。其余香港字段来自此前现场协议,不是通用默认值。
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+ITA_OTP_AUTHORIZATION_EMAIL='已在后台登记的邮箱地址' \
+PYTHONDONTWRITEBYTECODE=1 \
+python -B tools/debug_ita_book.py --production-workflow --auto-otp
+echo "EXIT_CODE=$?"
+```
+
+1. 按提示在终端输入**申请人的 Prenot@Mi 登录账号和密码**,不是后台管理账号。
+   此模式只读取 `ITA_BOOK_USERNAME`/`ITA_BOOK_PASSWORD` 或提示输入,不静默借用 Query 账号。
+2. 浏览器如需本人处理验证,正常处理;脚本不替你绕过验证。
+3. 正常自动模式不再询问 `Italy booking OTP`:由后台查询新邮件、输入和回读。
+4. 等待脚本结束,不另外点击 AVANTI 或 Prenota,也不要连续重跑。
+
+### 看什么结果
+
+正常进入流程应看到 `ITA_BOOK_WORKFLOW_OTP mode=cloud final_submit_enabled=false`。
+正向验收需要同时满足:
+
+- 取信成功后出现 `Italy automatic OTP DOM write verified`;没有人工 OTP 提示。
+- `ITA_BOOK_WORKFLOW_RESULT` 中 `selectionVerified=true`、`finalSubmissionEnabled=false`。
+- 请求统计 `otpRequests=1`、`avantiPosts=1`、`finalRequests=0`。
+- 正常清理、`EXIT_CODE=0`。`bookResultSuccess=false` 是预期:本次并未最终预约。
+
+如果没有号,不能据此判定整条选时段链路通过。如果是 mailbox read failed/504,
+则自动接码这一环未通过,禁止以 `fetch-top` 成功代替;本轮先保留人工方式,不修后台。
+回到人工方式只需在**下一次人工决定的独立尝试**中去掉 `--auto-otp`,不是失败后自动回退。
+不要提供完整邮件、验证码或请求头;只回传上述状态与脱敏错误即可。
+
+## 5. 测试、准出与后续
+
+离线测试覆盖:固定 API 参数、前导零/HTML 重复、歧义/异常格式、无 top 回退、
+DEBUG 时零取信和零发码、SDK 200/401/403/429/504 的假传输、异常脱敏、
+发送时间顺序、当前申请人绑定、迟到返回/提交前过期、DOM 失败、同 Session 防重发、
+人工兼容、公开 Book 路由及自动模式最终提交禁用。
+
+执行命令:
+
+```bash
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q \
+  test.test_ita_otp test.test_ita_workflow test.test_debug_ita_book \
+  test.test_ita_protocol test.test_ita_plugin test.test_ita_calendar_book \
+  test.test_ita_calendar_book_flow test.test_ita_calendar_query \
+  test.test_ita_booker_integration test.test_ita_booking_final \
+  test.test_ita_final_attribution test.test_ita_final_read_port \
+  test.test_debug_ita_calendar_gate test.test_debug_ita_production_query_gate
+```
+
+2026-08-31 最终验证记录:
+
+| 检查 | 结果 |
+|---|---|
+| 上述 14 个模块的离线回归 | 387 tests,OK,退出码 0 |
+| `python -B tools/debug_ita_book.py --help` | 可见 `--auto-otp`,退出码 0;未登录或联网 |
+| `git diff --check` | 无输出,退出码 0 |
+| 共享 SDK、日志宏、Booker、两个生产配置的 SHA-256 前后比对 | 全部相同,未改动 |
+| 真实自动取信及站点验收 | 未执行,待用户终端操作 |
+
+测试全部是假邮箱/假浏览器或本地 JS fixture,不依赖真实账号。
+离线通过不能证明部署的邮箱权限、过滤语义、延迟、网络和真实邮件模板均满足要求。
+
+进入自动完整 Book 的下一道门槛:先真实通过上述预确认验收,再单独评估最终提交开关,
+沿用现有 final attribution/去重/结果不明处理,不另造最终预约实现。
+
+审查反驳:“top 已找到邮件,为什么不直接用 top 自动接码?”
+答:top 没有本次发送时间的过滤,正文又没有可核对的消息时间;读到旧码会白白消耗
+预约窗口。本轮复用带时间参数的现成接口,并把未通过的现场依赖明示,不扩大到后台改造。
+
+## 6. 2026-08-31:表单验证等待修复
+
+### 新现场证据及结论
+
+用户自动 Book 验收停在 `/Services/Booking/4937`,标题 `Booking - Prenot@Mi`,
+错误为 `Turnstile did not become ready before timeout`。审计中 OTP、AVANTI、Calendar、
+最终提交请求均为 0;退出码 1,清理成功。**本次根本没有调用自动取信接口。**
+
+已确认的两个代码缺陷:
+
+1. `wait_for_booking_preflight` 将“缺少 Turnstile 结果”和“AVANTI 禁用”合并成同一错误。
+   离线分别输入 token=false/button=false、token=true/button=true,旧代码均返回同一句错误。
+2. Italy Book 没有接入 VFS 已用的共享验证交互,而且生产调用没有传诊断函数,超时也
+   不输出最后状态,导致无法知道上述哪个条件失败。
+
+这不证明用户当时一定需要点击验证框,也不能证明网络、控件加载或网站回调没有问题。
+修复已确认缺陷后,仍需一次真实现场验收;不宣称唯一根因或 100% 实站成功。
+
+### 实现和复用边界
+
+- 等待、严格结构校验、状态分类仍在 `plugins/ita_calendar_session.py`,不建第二套表单流程。
+- 新增 `plugins/ita_turnstile.py` 的小型组合适配器,直接复用 VFS 的
+  `CloudflareBypasser.click_verification_button(is_dfs=False)`,共享工具未改动。
+- 不调用该工具的通用 `bypass()`:它基于页面标题判断成功,会把正常 Booking 标题当作
+  已离开挑战页,不能证明表单里的 Turnstile 已准备好。
+- 只在单一验证字段存在、表单与当前申请人 Session/标签仍匹配、结果缺失时尝试交互。
+  第一次等待至少 5 秒,随后间隔至少 10 秒;每次 Book 准备最多 3 次尝试,前后 OTP
+  两个阶段共享预算。交互返回成功也必须下一轮重新读取并验证网页状态。
+- 如果 token 已存在而只是 AVANTI 禁用,不触碰验证组件,不强制启用按钮。
+- 不自动刷新整页、不重置组件、不伪造/注入 token、不做广泛 DFS、不改变业务请求次数。
+  超过交互预算仍允许用户在剩余等待窗口内正常处理验证;轮询期限仍为原来的 120 秒。
+  浏览器调用自身的阻塞不受硬墙钟中断,不承诺整个操作精确在 120 秒内结束。
+- 仅正常 Book workflow 启用主动交互;Query 准备和旧诊断 Gate 默认仍是被动等待。
+  Query 扫描、其他插件、共享 SDK、生产配置未更改。
+
+### 新日志如何判读
+
+默认诊断会在首次等待、状态变化、每约 15 秒、就绪/拒绝/超时时输出:
+
+```text
+ITA_BOOK_PREFLIGHT_DIAGNOSTIC={...}
+ITA_BOOK_TURNSTILE_INTERACTION={...}
+```
+
+`contract` 为 `ita-book-preflight-v2`,状态含义:
+
+| state | 确定的观察 | 不能据此断言 |
+|---|---|---|
+| `turnstile_token_pending` | 未读到验证结果,AVANTI 未禁用 | 一定是验证码失败或需要点击 |
+| `avanti_disabled` | 验证结果存在,AVANTI 仍禁用 | 再做一次验证就能解决 |
+| `turnstile_and_avanti_pending` | 两个条件都未满足 | 哪个条件先导致问题 |
+| `ready` | 严格 preflight 已通过 | 最终预约成功 |
+
+诊断只输出白名单布尔值和计数,包括 `turnstileApiPresent`、`turnstileScriptPresent`、
+`documentVisible`;脚本标签存在不等于加载成功,API 存在不等于验证通过。
+不读取/输出 token 值、完整 HTML、申请人资料或任意错误正文。
+`clicked=true` 只代表交互工具报告点击成功,不是验证完成;`clicked=false` 也不证明被封禁。
+
+### 验证和现场下一步
+
+新增 `test.test_ita_preflight`,并扩展 `test.test_ita_workflow`,覆盖三种超时分类、
+默认诊断脱敏、交互间隔和上限、跨阶段预算、Session 变化、异常收敛、
+有 token 时不重复操作、点击后必须重新验证、Book 未就绪时零 OTP/零取信、Query 不启用交互。
+
+最终离线回归:本文件第 5 节的 14 个模块,加 `test.test_ita_preflight` 和
+`test.test_debug_ita_book_gate`,共 **484 tests,OK,退出码 0**。
+未执行真实网站验证;未发送 OTP 或预约。
+
+现场继续使用第 4 节完全相同的命令,无需新增配置。观察自动打开的浏览器,
+如果页面要求本人验证则正常处理,不额外点击 OTP/AVANTI/Prenota。
+成功时应经过 `state=ready` 再出现发码/自动取信日志。
+失败时回传上述两个新前缀、`ITA_BOOK_FAILED` 和 `ITA_BOOK_WORKFLOW_AUDIT`;
+如果仍卡住,新日志至少可以分清验证结果缺失和按钮未恢复,而不是重复猜测。
+
+审查反驳:“既然调用了 VFS 工具,就已经证明这次故障被根治了?”
+答:没有。复用解决的是 Italy 缺少现成验证交互的代码缺口;网站当时的真实失败原因
+没有被保存。必须以本次网页重新读回的状态和后续零/单次请求审计验收,不能以工具
+返回 true、旧测试通过或正常页面标题作为实站成功证据。
+
+## 7. 用户现场验收通过:自动 OTP 到预确认
+
+记录日期:2026-08-31。来源:用户在自己的终端执行本线程前述香港单人旅游 Book
+命令后回传的日志,非本助手直接操作或独立 Network 抓取。诊断合同为
+`ita-book-preflight-v2`;本段日志未包含启动时的 service_id,香港 4937 来自前置命令上下文。
+本轮只记录验收结果,没有修改代码、重新运行脚本、发 OTP 或提交预约。
+
+### 观察到的顺序
+
+1. before-OTP 状态为 `turnstile_token_pending`:AVANTI 未禁用、页面可见、表单与
+   PrivacyCheck 就绪、API/脚本存在、单一验证字段存在,但验证结果缺失。
+2. 共享交互第 1 次尝试报告 `clicked=true`、`helperFailed=false`。
+3. 下一次真实页面回读变为 `state=ready`、`turnstileTokenPresent=true`,不是仅凭点击返回值放行。
+4. 发送一次 OTP,自动查询授权邮箱,OTP DOM 写入回读 `matched=true`。
+5. after-OTP 状态 `ready`;`otpDisabled=true` 是发码后的按钮冷却,不阻断后续提交。
+6. 进入申请人的 Calendar,重新查询;2026-08 候选日期为 0,2026-09 为 1。
+7. 选择 `2026-09-23`、`09:15 - 10:00`,余量快照为 1;选择回读成功后停在最终确认前。
+8. 清理成功,退出码 0。
+
+脱敏结果快照:
+
+```json
+{
+  "bookResultSuccess": false,
+  "finalSubmissionEnabled": false,
+  "selectionVerified": true,
+  "selectedDate": "2026-09-23",
+  "selectedTime": "09:15 - 10:00",
+  "remaining": 1,
+  "requests": {
+    "availabilityRequests": 3,
+    "avantiPosts": 1,
+    "finalRequests": 0,
+    "otpRequests": 1,
+    "timeSlotRequests": 2
+  },
+  "cleanup": "ok",
+  "exitCode": 0
+}
+```
+
+最终 `ITA_BOOK_WORKFLOW_AUDIT` 与结果内请求统计一致。
+未保存邮箱地址、密码、OTP、Token、完整邮件或请求头。
+
+### 可以确认与不能扩大解释的部分
+
+- 本次预确认流程通过:网页验证交互、自动取信与填码、前置表单提交、日历重查、时段选择。
+- 本次卡点确实是验证结果缺失,而非 AVANTI 禁用;交互后网页回读满足条件,支持本次修复有效。
+  旧失败轮次没有这些状态证据,不能据此追溯性证明所有超时只有同一个根因。
+- `bookResultSuccess=false` 符合预确认合同;`finalRequests=0`,本次没有发出最终预约请求,
+  不能称为预约成功。余量 1 只是当时快照,不代表保留、锁定或现在仍有号。
+- 本次证明云端取信链路成功了一次,不证明此前 504 的原因已被修复、永不超时,
+  也不扩大为所有邮箱/机构/模板或并发场景都已现场验证。
+- 本段日志没有预约列表前后快照,不声称已独立证明服务器无草稿、无其他隐藏状态变化。
+
+下一道门槛是最终提交及回执归属验收。执行前必须明确申请人和可接受日期范围,
+在新的会话里重新读取号源并取得明确最终提交授权;不能重放本次日期、时段或旧上下文。
+继续复用现有最终提交、去重和结果不明处理,不在本次记录操作中改变开关。
+
+## 8. 自动 OTP 与现有最终提交接线、无提交回执验收入口
+
+日期:2026-08-31。用户“OK 继续推进”授权本地实现与离线验证;不等于授权这轮创建真实预约。
+本轮未执行真实浏览器、取信、OTP、AVANTI 或最终提交,未改生产配置、共享 SDK、邮件后端、
+VFS/BLS/TLS、Query 算法或 Booker。未读取、创建、删除本地真实 final claim。
+
+### 8.1 最小复用方案与实际改动
+
+- `plugins/ita_plugin.py`:复用 `_book_final_configuration_valid()` 统一配置检查,允许申请人
+  `services_probe` 模式在 `otp_mode=manual/cloud` 且显式布尔 `final_submit_enabled=true`
+  时接入已有最终提交。默认仍为 false;字符串 `"true"`、数字 `1` 不合法,Query 不可启用。
+- `plugins/ita_workflow.py`:去掉自动 OTP 的阶段性 pre-final 限制,改为复用同一申请人配置检查。
+  OTP 准备本身不执行最终提交;新鲜日历和时段选择仍由既有 Book 完成。显式开启后原样调用
+  `submit_final()` → `FinalBookingAttempt` → `NativeFinalSubmitter` → `FinalReceiptReadPort`。
+  未复制最终 POST、回执解析、成功上报、锁或调度器。
+- `tools/debug_ita_book.py`:增加 `--verify-receipts`,仅允许与 `--production-workflow` 一起使用。
+  在公开 `plugin.book()` 完成预确认选择后,直接复用既有 Book gate 的 `_verify_receipt_baseline()`:
+  同浏览器同会话后台标签读取列表及详情、检查身份和状态、核对读取前后列表、关闭自建标签、
+  重验原 Calendar 选位。复用其后台标签请求审计,并额外确认主标签业务计数没有变化。
+  普通 CLI 仍固定 `final_submit_enabled=false`,没有新增最终提交 CLI 开关。
+
+设计仍是组合:验证码来源与最终提交是两个独立开关。允许自动取码不等于允许创建预约,
+邮件正文不决定申请人、日期、路线或开关。固定筛选、六位 ASCII 解析、过期/会话检查、
+日志保护均未放宽;body-only 后端的发件人认证和时间证据限制仍保留,不增加邮件服务。
+
+### 8.2 本轮验证与准出
+
+离线测试新增/扩展于 `test/test_ita_workflow.py`、`test/test_debug_ita_book.py`:
+
+- 自动模式显式 final 开启时,重跑同一组 OTP 过期、账号变化、读取失败、DOM 写入验证、
+  禁止 Query 接码、禁止重复发送、日志保护用例;准备阶段不调用 final。
+- 自动模式仍默认停在 pre-final;显式开启后先重查选位再调用已有 submitter;无号不提交。
+- 已知 unknown 不再扫描/提交,confirmed 结果可重报而不再次预约;Query Session 和其他申请人被拒绝。
+- 自动模式复用真实本地回执解析器和最终核心:匹配请求加确认回执成功;缺请求证明保持 unknown;
+  清理审计失败不抹去已确认结果(全部是离线替身,不是真实提交)。
+- 新 CLI 标志默认关闭、必须显式工作流、与 auto-OTP 共存、仅调用一次公开 Book;回执失败
+  或读取中业务请求变化不报通过;无候选时不读取回执也不报正向验收成功。
+
+2026-08-31 执行以下 16 个模块,**508 tests,OK,退出码 0**:
+
+```text
+test.test_ita_preflight test.test_ita_otp test.test_ita_workflow test.test_debug_ita_book
+test.test_ita_protocol test.test_ita_plugin test.test_ita_calendar_book test.test_ita_calendar_book_flow
+test.test_ita_calendar_query test.test_ita_booker_integration test.test_ita_booking_final
+test.test_ita_final_attribution test.test_ita_final_read_port test.test_debug_ita_calendar_gate
+test.test_debug_ita_production_query_gate test.test_debug_ita_book_gate
+```
+
+`PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B tools/debug_ita_book.py --help`:退出码 0,新标志可见。
+`git diff --check`:退出码 0。其他插件、共享验证码工具、邮件 SDK 和两份生产配置 SHA-256
+与本轮前记录一致。以上是本地研发验收,不代表已部署或自动最终预约现场通过。
+
+### 8.3 下一道现场门槛(不创建预约)
+
+沿用第 4 节路由和已授权邮箱,只将命令结尾改为:
+
+```bash
+.venv/bin/python -B tools/debug_ita_book.py --production-workflow --auto-otp --verify-receipts
+```
+
+申请人独立登录 → 一次 OTP/一次 AVANTI → 重查选位 → 读取已有预约 → 校验选位不变 → 清理退出。
+应回传 `ITA_BOOK_WORKFLOW_RECEIPT_BASELINE`、`ITA_BOOK_WORKFLOW_RESULT`、
+`ITA_BOOK_WORKFLOW_AUDIT` 和退出码。要求 baseline `verified=true`、
+`calendarSelectionPreserved=true`、后台业务请求全 0、最终请求为 0、退出码 0。
+
+基线读取沿用已有约束:仅接受空预约列表或可完整核对的已取消历史。存在有效预约/候补、
+未知状态、覆盖不完整或同会话校验失败就停止,不会自动取消或修改旧预约。回传失败信息即可,
+不要为让测试通过而删记录/取消预约。新检查对该账号尚待现场验证。
+
+通过后再确定真实申请人、可接受日期范围及最终提交授权;实际日期必须重新查询,不重放第 7 节快照。
+最终动作后必须以匹配请求及新确认回执归属判断成功;结果不明保持暂停,不自动重试。
+既有进程内防重、Booker 暂停和本地受控 gate 的 claim 不等同跨进程 exactly-once;
+本轮没有增加分布式保证,也没有开启生产 final 或删除既有最终尝试记录。
+
+## 9. 用户现场验收通过:自动 OTP、选位与空回执基线
+
+记录日期:2026-08-31。来源:用户在自己的终端执行第 8 节新增的
+`--production-workflow --auto-otp --verify-receipts` 命令后回传的末段日志。
+本助手未独立控制浏览器或抓取 Network;香港 4937 路由来自前置命令上下文,
+本次日志片段未包含完整启动配置或代码指纹,不额外推定账号身份。
+
+### 9.1 观察到的结果
+
+- before-OTP 验证结果最初缺失,共享交互第 1 次报告 clicked=true,后续页面回读 ready。
+- 一次 OTP 发送后,自动取信与写入回读通过;after-OTP preflight 为 ready。
+- 申请人 Calendar 重查:2026-08 candidates=0,2026-09 candidates=10。
+- 当次选位:2026-09-01、10:05 - 11:05,余量快照为 1,selectionVerified=true。
+- 回执基线 verified=true、recordCount=0;calendarSelectionPreserved=true。
+- 回执读取后台标签的五类受审计业务请求均为 0。
+- 总计:availabilityRequests=3、avantiPosts=1、finalRequests=0、otpRequests=1、timeSlotRequests=2。
+  结果内计数与最后 WORKFLOW_AUDIT 一致;cleanup=ok,EXIT_CODE=0。
+
+脱敏核心证据:
+
+```json
+{
+  "receiptBaseline": {
+    "verified": true,
+    "recordCount": 0,
+    "calendarSelectionPreserved": true,
+    "finalSubmissionEnabled": false,
+    "businessRequests": {
+      "availabilityRequests": 0,
+      "avantiPosts": 0,
+      "finalRequests": 0,
+      "otpRequests": 0,
+      "timeSlotRequests": 0
+    }
+  },
+  "selectionVerified": true,
+  "selectedDate": "2026-09-01",
+  "selectedTime": "10:05 - 11:05",
+  "remaining": 1,
+  "bookResultSuccess": false,
+  "finalSubmissionEnabled": false,
+  "finalRequests": 0,
+  "cleanup": "ok",
+  "exitCode": 0
+}
+```
+
+### 9.2 准出与后续边界
+
+本次通过第 8.3 节的现场门槛:自动 OTP 至预确认选择、空预约列表的同会话基线读取,
+以及读取后选位保持。`bookResultSuccess=false` 是预确认模式的预期结果,不是流程失败。
+
+空基线只证明本次完整读取到 0 条记录,**没有现场覆盖非空预约详情、已取消历史、
+新确认回执解析或提交后的归属核对**。不能将“列表可读”当作“最终预约已成功”。
+受审计业务请求为 0 不等于所有 HTTP 请求为 0,也不证明不存在服务器内部草稿/会话状态变化。
+日期和余量是当时快照,未锁定或保留;下一次可能变化,不直接重放。
+
+下一步只需先明确真实预约可接受的日期范围,再落实申请人、单次最终提交授权及受控执行入口。
+实际提交前重新读取当前号源;提交后要求匹配请求与新确认回执,结果不明则停止、不重提。
+不为重复验证空基线而再次发 OTP;不取消、删除既有预约来制造验收条件。
+
+本轮只更新本文件,没有修改代码、生产配置、运行测试或请求真实网站/邮箱。
+第 8 节 508 项测试仍是上轮离线证据,不声称本轮重新执行。
+
+## 10. Query 首次日历准备复用自动 OTP(代码已验证,现场待配置)
+
+2026-08-31,用户授权把 Book 已有自动接码接入 Query。此前公共测试器在人工 OTP 模式已通过:一次验证框操作后 token 就绪,人工验证码 DOM 回读通过,扫描首个正向月份返回 `2026-09-01`,清理成功、exit 0。这个现场记录不是 Query 自动接码证据。
+
+### 10.1 最小改动与复用边界
+
+- `plugins/ita_plugin.py`:允许 `query_mode=calendar` 搭配 `otp_mode=cloud`,公开 Query 与人工模式一样进入现有准备函数;Query 开启最终提交仍被拒绝。
+- `plugins/ita_workflow.py`:Query/Book 根据显式角色与配置复用同一自动 OTP 分支。Query 必须是 Calendar 配置,Book 必须是申请人配置;账号身份、当前 tab/session、验证码有效窗口和最终开关检查继续有效。
+- 沿用原来的 `ita_otp.fetch_otp_from_cloud()` → `VSCloudApi.fetch_mail_content()`,未新增 API、IMAP、邮箱监听或自动化调度器。共享 SDK、VFS/BLS/TLS、邮件后端均未修改。
+- 发送 OTP 前记录 UTC 时间和单调时钟;以当前插件账号为收件人、配置的授权邮箱为读取目标。发送一次、读取一次,读取失败不回退人工、不改用 fetch-top、不在同一准备会话重复发码。
+- 已准备 Calendar 的查询跳过 OTP/AVANTI,照原算法逐月扫描。会话失效后的已有恢复策略未修改,不宣称池账号的所有恢复情况已无人值守。
+
+### 10.2 邮箱绑定与信任边界
+
+沿用 `apt_configs[routing_key].mail.authorization_email` 配置。它可以是账号自身邮箱,也可以是确实接收该账号转发邮件的已授权收件箱;程序不猜测转发关系、不把 Book 的邮箱自动借给 Query。
+
+固定发件人筛选 `noreply-prenotami@esteri.it`、主题 `OTP Code`、正文标记 `OTP Code:`、当前账号 recipient、发送时间窗口,以及带标记的六位 ASCII 数字解析均保持不变。不记录正文/验证码,不把邮件当指令、不送入大模型。这延续 `agent-email-inbox` 技能的固定来源与不可信输入处理原则,不引入 Resend 或其他新服务。
+
+共享接口仍只返回正文,From/To 子串匹配和邮件接收时间筛选依赖既有后端,不能据此宣称已独立验证发件人认证或邮件归属。既有 HTTP/IMAP 超时和可能置已读的行为也未在本轮修改。
+
+### 10.3 当前配置状态及复测方法
+
+只读检查发现:本地测试/调度配置无 `mail.authorization_email`,当前进程及 `.env` 也没有 `ITA_OTP_AUTHORIZATION_EMAIL`。因此暂未把公共测试配置从 manual 改成一个缺邮箱地址的 cloud 配置。已向用户询问本次 Query 应读取的后台授权邮箱;本轮没有真实发码、取信或登录。
+
+确认地址后可继续使用公共测试器,在上一条命令中、`run_pipeline()` 之前设置:
+
+```python
+import os
+from plugins.ita_protocol import OtpMailConfig, resolve_route_config
+from plugins.ita_otp import validate_cloud_otp_environment
+
+mail = OtpMailConfig(os.environ["ITA_OTP_AUTHORIZATION_EMAIL"])
+validate_cloud_otp_environment(mail, account.username)
+config = tester.config.free_config
+config.update(query_mode="calendar", otp_mode="cloud", final_submit_enabled=False)
+for appointment in tester.appointment_types:
+    config["apt_configs"][appointment.routing_key]["mail"] = {
+        "authorization_email": mail.authorization_email,
+    }
+    resolve_route_config(config["apt_configs"], appointment.routing_key)
+```
+
+此单邮箱示例只用于确认过邮箱映射的本次单账号测试,不是自动建立账号池邮箱绑定。DEBUG 邮件正文日志必须保持关闭;缺邮箱或日志不符合要求时在发送 OTP 前终止。网站仍可能要求人工完成人机验证,但不再应出现终端 OTP 输入提示。
+
+### 10.4 新鲜验证与准出
+
+- 定向 workflow / OTP / preflight:95 项通过,exit 0。
+- Italy 19 模块回归:561 项通过,exit 0。
+- 新增 8 项 Query 自动接码测试,复用 Book 表单 fixture 与真实 OTP 解析适配器:公开 Query 连续两次只准备一次、固定 SDK 筛选和收件人、无号不发码、失败不重发/不人工回退、过期拒绝、账号变更拒绝、歧义正文拒绝、缺邮箱拒绝、Query 与 Book 角色/最终开关隔离。其中角色与开关分支在同一测试中覆盖。
+- 所有网站/邮件返回为合成数据;未运行真实取信或预约。Query 自动 OTP 的现场准出仍是:自动取得并回读验证码 → Calendar 查询结果 → 清理成功,且没有最终预约请求。
+
+### 10.5 单账号池配置已确认(2026-08-31)
+
+用户确认 `hkg.it.sentinel` 已录入测试账号,且同名 Gmail `chatgptshareplus@gmail.com` 已登记邮箱授权。香港 Sentinel 新配置及公共测试配置现使用 `otp_mode=cloud`,路由 `mail.authorization_email` 指向该邮箱。此前 10.3 的“等待确认邮箱”已解除;本轮不再次登记账号/邮箱,不读取或保存应用专用密码。
+
+只复用现有账号池 SDK、Book/Query 共享 OTP 适配器和公共测试器。收件人动态取自所选池账号,固定发件人、主题、时间窗口与验证码解析不变;不新增邮箱服务、不把邮件交给大模型。香港组保持禁用,真实取池账号和接码尚需用户执行 [一次性验收命令](ita_query_book_acceptance.md#121-一次性池账号-query-验收)。一个池中扩容多个独立收件邮箱时,必须先补齐相应映射/转发验证,不能只添加账号就假定当前单邮箱配置适用于所有账号。
+
+### 10.6 用户现场回传:Query 自动接码已通过
+
+2026-08-31 用户回传:自动邮箱读取分支执行,`OTP_DOM_WRITE_VERIFIED matched=true`,后续 `otpValuePresent=true`,成功进入 Calendar;逐月查询从首个无号月份推进至首个正向月份,返回当时最早日期 `2026-09-01`、Available,cleanup 成功,公共测试器全部 PASS,`EXIT_CODE=0`(总耗时 98.49 秒)。本次没有记录任何 OTP 值或邮件正文。
+
+这补齐了当前测试账号 Query 自动接码的真实证据,不代表常驻恢复、多邮箱池或 Book 最终提交已通过。所贴日志缺少开头池来源标记,来源边界及下一节点见 [现场验收记录 12.3](ita_query_book_acceptance.md#123-用户现场回传自动-otp--query-通过)。不为补来源日志重新发送验证码。本轮只更新文档,未运行网站/邮箱请求或更改配置。
+
+### 10.7 多账号直接收件:不再固定测试邮箱
+
+用户授权解除单账号限制后,香港 Query 两份配置改为:
+
+```json
+"mail": {"authorization_source": "account"}
+```
+
+领取 A 账号就从 A 的后台授权邮箱读取;领取 B 账号就读取 B。既有生产 OTP 适配器按调用解析,不修改共享配置,所以后续新账号无需再修改固定邮箱地址。每个自己的收件邮箱仍须已登记授权;缺授权时不会借用旧账号邮箱或回退 fetch-top。
+
+原来 `"mail": {"authorization_email": "authorized-inbox@example.test"}` 默认仍为 `configured` 模式,兼容已有统一/转发收件箱与 Book 配置。两种模式显式选择,`account` 模式不能同时填固定 `authorization_email`。协议中的固定发件人/主题/正文标记、时间窗口、OTP 格式和当前账号身份检查保留,邮件仍作为不可信数据处理,不引入新的邮件服务或大模型。
+
+完整替代命令与验证记录见 [验收记录第 13 节](ita_query_book_acceptance.md#13-解除单账号邮箱限制使用实际池账号的授权邮箱)。不要只在旧命令中删掉相等检查后继续使用旧固定邮箱配置;请使用已更新的完整命令。

+ 3115 - 0
docs/ita_plugin_discovery.md

@@ -0,0 +1,3115 @@
+# Italy 插件调研记录:Prenot@Mi
+
+> 最近整理:2026-08-29(Asia/Shanghai)
+>
+> 当前阶段:REAL VERIFIED(Gate 1 `/UserArea` Session + Dublin 无号 Query + Hong Kong HK-7 真实 OTP/POST 至 Calendar + HK-28/E43 十月正向日期与 Slot);正向 Slot 尚未选择,最终预约仍未执行
+>
+> 目标:为 `plugins/ita_plugin.py` 的修复建立可追溯的网站事实、职责合同和安全边界。
+>
+> 本文不是“现有实现可上线”的证明。真实网站会变化,所有结论都必须结合证据标签和确信度阅读。
+
+## 0. 一句话结论
+
+Gate 1 已通过人工 Discovery 和一次真实自动登录验证:IAM 登录页为 `/signin/`,稳定字段名是 `callback_1`、`callback_2`;插件只提交一次凭据,随后到达 `/UserArea`,认证成功 DOM 同时包含 `.app-menu` 和 `/Services` 链接。调试命令输出 `ITA_SESSION_OK`、清理成功且 exit 0。
+
+Gate 2 已确认 Dublin 无号分支:`GET /Services/Booking/1321` 返回 `302 Location: /Services`,随后 `/Services` 通过非空 `#WNotAvailable` 显示“名额已耗尽”;没有 BookingCalendar、OTP 或预约业务 POST。Phase 1 最初只实现这个分支并在 Booking Form 前停止。当前工作树的后续版本仍遵守 **C 式副作用纪律**(不发送 OTP、不填写或提交表单),但会在 `200 + bookingForm` 时返回 `success=True + NoneAvailable` 弱信号。E43/R3 已认定该弱信号不适合作为生产精确号源;这是待替换的实现现状,不是目标合同。
+
+第一次真实自动 Query 完成了登录、单次 1321 探测和清理,但只观察到最终 `/Services`,自动化当时没有读到非空 `#WNotAvailable`,因此按设计 exit 1。用户同时确认屏幕上出现过意大利语弹窗,但弹窗随后消失,未取得该次原文。实现现已增加第二证据源:仅对白名单中的、此前真实记录过的无号意大利语文案进行保守分类;未知文案仍然停止并输出脱敏诊断。调试输出只保留语言无关的状态码,不把中文、英文或意大利语固化为框架合同。
+
+第二次真实自动 Query 使用更新后的同一单次工具,输出 `ITA_QUERY_NONE_AVAILABLE service_id=1321 status=NoAvailable`、`ITA_QUERY_CLEANUP_OK` 和 exit 0。至此,当前无号分支已同时具备人工 Network/DOM 证据、离线契约测试和真实自动化结果。
+
+Hong Kong 金丝雀已经取得前三个只读 Gate 的真实证据:香港 `/Services` 只有一条通用 `Visti Nazionali e Schengen` 入口,`service_id=4937`;在用户明确授权后只访问一次该入口,`GET /Services/Booking/4937` 直接返回 `200` Booking Form,没有重定向、BookingCalendar 或 OTP 请求。页面随后只读观察到单人预约 `Prenotazione Singola=1`、签证目的 `Turismo=42`、`otp-input`、`PrivacyCheck`、`cf-turnstile-response` 和 `AVANTI`。表单是 `POST /Services/Booking/4937`、`multipart/form-data`,但当前真实 DOM 没有文件上传控件。
+
+这组证据把 Query/Book 边界进一步收紧:`Prenota` 仍只是链接;`GET 入口 → 200 + bookingForm` 比链接更强,但自身没有日期、时段或容量,不能冒充真实号源。当前已经实现的 `services_probe` Query 必须在 OTP 前停止。后续设计中的“准备型 Calendar Query”是另一种显式模式:只有团队账号授权、每个 Session 一次 OTP + `AVANTI`、预约列表前后不变等 Gate 全部通过后,才允许进入 Calendar;进入后每轮 probe 逐月读取 Availability,只传播正向日期,不能再次发送 OTP 或执行最终预约。页面自动产生的 TimeSlots 可作校准/诊断,但具体时段必须由 Book 在用户自己的 Session 中重查。静态函数体已确认 OTP 候选请求是副作用性 `GET /BookingCalendar/GenerateOTP?ServiceID=4937`,仅当 HTTP 200 且原始响应文本精确等于 JSON 字符串 `"SENT"` 时才进入成功分支,并启动 120 秒前端冷却。
+
+HK-6 已关闭预约类型同步链:`typeofbookingddl` 的 change handler 调用 `ShowCompanions()`;单人值 `1` 会把同行人数 hidden 字段设为 `0`,并把经 DOMPurify 处理的选择写入 `hiddenTipoPrenotazione`。E16 已证明这两个 DOM id 分别提交为 `NumAccompagnatoriSelected` 和 `IdTipoPrenotazione`。结合 HK-5 的 `ddls_0 → hiddenSelezionato_0`,单人旅游的两条业务字段同步链均已闭环。
+
+HK-6 同时明确区分了“已定义函数”和“当前实际调用链”:页面定义 `getCaptchaToken()`,但本次对全部相关 inline script 上下文及预约类型、`bookingForm`、`AVANTI` 三个关键元素事件的采集,只观察到函数定义,没有观察到任何调用点;`bookingForm` 没有 direct submit handler,`AVANTI` 的唯一已观察 click handler 仍直接执行 jQuery form submit。因此当前静态合同不把 reCAPTCHA Enterprise 函数强行接入 Book,只把它标为未引用/候选路径;是否存在外部或委托调用、服务端是否要求该 token,只能由下一次受控真实 POST 证明。
+
+HK-7 真实提交前预检进一步校准了字段同步时机:用户选择单人和旅游后,预约类型 hidden 已为 `1`、同行人数 hidden 已为 `0`,但旅游 hidden 仍为初始 `0`;这与源码一致,因为 `ddls_0 → hiddenSelezionato_0` 不是 change handler,而是在 `AVANTI` click handler 内、form submit 前调用 `saveDdlValue()` 才发生。此前把“选择后立即应为 42”作为预检条件是错误的,现已更正;该值为 `0` 不是网站异常,也不应通过插件提前手工写入。
+
+HK-7 的唯一一次真实副作用链随后成功执行:用户先勾选 Privacy,再点击一次 OTP;`GET /BookingCalendar/GenerateOTP?ServiceID=4937` 返回 200/`SENT`,注册邮箱收到验证码。用户手工输入 OTP 后只点击一次 `AVANTI`;`POST /Services/Booking/4937` 返回 302,`Location` 指向 `/BookingCalendar?selectedService=Visti%20Nazionali%20e%20Schengen`,随后 `GET` 该 Calendar document 返回 200,浏览器最终 `location.pathname=/BookingCalendar`、标题为 `Calendar - Prenot@Mi`。POST 中只观察到 `cf-turnstile-response` 字段名,没有观察到 `g-recaptcha-response`,所以当前真实路径使用 Turnstile,未引用的 reCAPTCHA Enterprise 函数不属于本次成功链。日期、时间和最终确认点击均为 0。
+
+HK-8 在关机后恢复的同一 Calendar 页面完成零点击采集:页面显示 `agosto 2026`,采集到的 42 个日期格全部带 `disabled` class;`31/08/2026` 还同时带 `notAvailableDay active`。界面另有默认 `selected` 的 `2026-08-31` 日期条目和三个时间段,但每个时间段后都显示 `(0)`。这组相互制约的证据只能证明“页面默认聚焦并渲染了该日”,不能证明它可预约;当前最保守分类是 **Calendar 已加载,但没有取得任何可选 Slot 证据**。
+
+页面生命周期中已经出现三个 XHR 资源:`RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots`。本次脚本只是读取 Resource Timing,没有新发请求,也没有取得它们的 method、status 或 response schema。静态脚本同时确认最终动作候选为 `POST /BookingCalendar/InsertNewBooking`,字段名是 `idCalendarioGiornaliero`、`selectedDay`、`selectedHour`;该请求从未执行,仍属于不可逆最终确认边界。
+
+HK-9 进一步确认三个 `(0)` 时间段的 DOM class 都是 `fascia notAvailableFascia`,因此它们可以被语言无关地分类为不可预约;不再需要从 `(0)` 文案猜容量语义。但网站的 delegated handler 对所有 `.fascia` 都会移除旧 `act` 并给被点击项添加 `act`,没有在 handler 内排除 `notAvailableFascia`。这意味着自动化不能盲目点击 `.fascia`:必须在点击前由插件显式拒绝不可用 class,并在点击后交叉检查唯一 `.fascia.act` 仍是可用候选。
+
+最终 `#btnPrenotaNoOtp` 同样使用 document-level delegated handler:没有 `.fascia.act` 时只弹出“未选择时间段”并停止;有 active Slot 时才读取时间文字和 selected 日期,调用 `InsertNewBooking`。JSON response 的当前静态合同至少包含 `errorMessage` 和 `url`:无错误时直接跳转 `url`,有错误时显示 `errorMessage`,用户确认后仍跳转 `url`。真实成功 URL、预约编号、error callback 和服务端幂等语义仍未验证。
+
+HK-10 校正了 XHR 源码定位:尽管此前 DevTools 的 initiator 曾显示 `stormcaster.js`,用户在该文件内搜索 `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots` 均为 0 个匹配。因此不能把 initiator 直接等同于“业务 endpoint 字符串所在文件”;它可能是网络包裹/安全层,也可能只是调用栈归因结果。下一步必须使用 Sources 全局搜索定位真实定义或动态拼接位置。
+
+HK-11 的 Sources 全局搜索随后命中业务函数 `CaricaTimelineOrizzontale(_Mese, _Anno, _Oggi, _Servizio, _GiornoDaSelezionare)`,其函数开头设置 `Metodo = 'RetrieveCalendarAvailability'`。这证明 endpoint 名确实由业务函数作为方法片段持有,而不是写在 `stormcaster.js` 中;完整 URL、HTTP method、payload 和 success handler 仍需读取该函数余下部分。
+
+HK-12 取得完整编排函数:WebMethod 参数对象只有 `_Servizio` 和 `selectedDay=_Oggi`;success callback 参数对象只有 `GiornoDaSelezionare=_Oggi`;error callback 参数对象为空。函数随后调用 `EseguiAsync(Metodo, Parametri, CostruisciTimelineOrizzontale, StampaErroreInConsole)`。因此 URL、HTTP method 和序列化属于通用 `EseguiAsync`,日期 DOM 构建属于 `CostruisciTimelineOrizzontale`。签名中的 `_Mese`、`_Anno`、`_GiornoDaSelezionare` 在当前函数体内没有被引用,插件不能根据参数名擅自添加请求字段。
+
+HK-13 已取得 `EseguiAsync`:它固定执行 `POST urlServizio + Metodo`,把 `Parametri[0]` 用 `JSON.stringify` 序列化为 `application/json; charset=utf-8`,期望 JSON response;成功时原样把 `response` 和 `Parametri[1]` 传给 success callback。结合已观察的 `urlServizio='/BookingCalendar/'` 与 HK-12,Availability 当前静态合同为 `POST /BookingCalendar/RetrieveCalendarAvailability`,JSON 键为 `_Servizio`、`selectedDay`。error 分支丢弃 response/status/body,只无参调用错误 callback;插件不得复制这种不可诊断行为。
+
+HK-14 已取得 `CostruisciTimelineOrizzontale`:callback 首先对 jQuery 已按 JSON 接收的 `response` 再执行 `$.parseJSON`,说明当前 payload 是外层 JSON 中承载的 JSON 字符串;解析后为数组,元素至少包含 `DateLibere` 和 `SlotRimanenti`。每个元素都会进入 `GiorniConPrenotazioni` 并创建日期/事件 DOM,最后初始化时间线。数组非空只表示服务器返回日期记录,不能直接等同于“还有号”;本阶段当时仍需验证容量。E43 后已关闭正向组合,当前结论见第 2.17 节。
+
+HK-15 已取得 `InizializzaTimelineOrizzontale`:它先解绑 datetimepicker 的 `dp.update`/`dp.change`,再依次初始化日历、禁用无预约日期、切换异步控件的 CSS 状态并关闭 loader;随后查找请求日期对应的时间线链接。如果目标日期不存在,网站会静默回退到时间线第一天;找到链接后会由脚本调用 `.click()`。这解释了用户人工日期点击为 0 时为何仍可能自动出现 `RetrieveTimeSlots`:页面初始化自身会产生程序化日期点击,但真正响应 click 的 handler 仍需在其他源码中定位。Book 必须在异步稳定后重新读取实际 selected 日期并与用户偏好比较,禁止默许网站回退后预约错误日期。
+
+HK-16 已取得 `DisabilitaGiorniSenzaPrenotazioni`:它先把所有 datetimepicker `.day` 都标为 `disabled`,再按格式化日期与 `GiorniConPrenotazioni` 中的 `date@slot` 匹配。匹配后使用 JavaScript 的 `slot >= 0`:成立则添加 `availableDay` 并移除 `disabled`,不成立则添加 `notAvailableDay`。因此 `availableDay` 的精确含义只是“网站允许进入该日期”,不是“至少剩余一个时段”;数值 `0` 也会走 available 分支。插件必须继续要求 TimeSlots 中存在不带负向 class 的真实可选时段,不能仅凭日期 class 宣告有号。函数还没有清理旧的正负 class、没有处理重复日期并使用隐式数值转换;插件遇到同一天重复记录、正负 class 并存或非有限数值时应 fail-closed。
+
+HK-17 已取得 `AbilitaInputAsincroni`,并校正了此前推断:它没有注册任何 event handler,也没有调用 AJAX。函数只选择所有 `[data-async="true"]` 且当前不带 `.selected` 的元素,移除 `input-async-disabilitato`,添加 `input-async-abilitato`。这只是 CSS/可交互状态切换;真正的 date click handler 和 `RetrieveTimeSlots` 调用定义在别处。`input-async-abilitato`、`selected` 或 `data-async=true` 都不能单独作为有号证据,而且被 `.selected` 排除的元素不会在本函数中刷新 class,插件仍需防范陈旧状态。
+
+HK-18 已取得 `CaricaTimelineVerticale`:它从参数接收 `_Giorno`,从页面 `#idServizio` 读取运行时 `idService`,以 `{selectedDay, idService}` 作为 WebMethod 请求对象,通过已经确认的 `EseguiAsync` 执行 `POST /BookingCalendar/RetrieveTimeSlots`、JSON UTF-8。`_ContenutiEventi` 只作为 success callback 的第二个参数传给 `CostruisciSchedaFasce`,不是 request body。配置入口 `service_id=4937` 与 Calendar 页面 `#idServizio` 是两个来源不同的标识,当前绝不能混用;后者的准确业务语义仍待 callback/DOM 证据。函数中的 `_Giorno = _Giorno` 是无效果赋值,`_idService` 在本函数没有局部声明,插件不应复制这种潜在全局状态。
+
+HK-19 已取得 `CostruisciSchedaFasce`:TimeSlots response 与 Availability 一样还要经过 `$.parseJSON`,内层才是 Slot 数组。callback 从 `Parametri.selectedContent` 取得 jQuery 容器;当数组长度恰好为 1 时只设置展示参数 `unicaFascia=true`,随后对每个数组元素调用 `CreaFasce(item, unicaFascia)` 并把返回 HTML 追加到容器,最后调用 `CostruisciTimelineVerticale(Parametri)`。数组为空仍会进入后续 timeline 构建;数组非空或长度为 1 都不能证明可预约,因为本 callback 不过滤 item,而当前 DOM 又证明不可用 Slot 也会被渲染。具体 response 字段、`(0)`、普通/负向 class 仍由 `CreaFasce` 决定。
+
+HK-20 已取得 `CreaFasce`:TimeSlots item 至少包含 `SlotRimanenti`、`SlotLiberi`、嵌套的起止时间和 `IDCalendarioServizioGiornaliero`。`SlotRimanenti < 0` 才生成 `notAvailableFascia + dotRed`;非负值不加负向 class。`(0)` 的确切来源是 `SlotLiberi`,不是 `SlotRimanenti`。当数组只有一项时先自动赋 `act`,但负向判断随后会覆盖成 `notAvailableFascia`;因此唯一非负项会被自动选中,唯一负向项不会。这里记录的是取得 E43 前的源码边界;E43 随后用真实正向样本证明 `SlotLiberi=1 / SlotRimanenti=0` 是可用组合。最终实现仍必须交叉验证 class、两个字段、时间和 daily calendar ID,不能仅凭“没有负向 class”提交最终预约。
+
+HK-21 记录了 DevTools Sources 全局搜索 `TemplateFasce` 为 0 个匹配。这个结果只能证明当前可搜索 Sources 中没有该符号的明文定义,不能证明运行时没有模板:它仍可能来自动态脚本、闭包局部变量、压缩/改名或字符串拼接。继续重复搜索同一符号的边际价值很低,下一步改为只读已渲染 `.fascia` DOM,以 DOM 事实关闭 daily calendar ID、class、时间和数量的位置。
+
+HK-22 已取得第一条负向 Slot 的脱敏渲染 DOM:根元素为 `div.fascia.notAvailableFascia`,内部依次包含红点、时间 `span`、换行、数量 `span` 和 `input[type=hidden]#idHiddenFasciaServizio`;hidden value 只确认存在且为 8 位数字形状,没有记录真实值。父容器是 `li.selected.enter-right`,其三个直接子元素都是负向 `.fascia`。这里的父级 `selected` 表示当前时间线内容卡片,不能冒充 `.fascia.act` 的时段选择状态。daily calendar ID 在第一条 Slot 中的落点已经关闭,但三个 Slot 是否各自携带同名 input/不同值,以及最终 handler 如何从 active Slot 取值,仍需精确源码证明。
+
+HK-23 在恢复现场后取得 `TemplateFasce` 原文,它与 E37 的渲染 DOM 逐节点一致。模板在每一次 `CreaFasce` 调用中都写入固定的 `id="idHiddenFasciaServizio"`,只替换 value;结合 E34 的逐 item 追加循环,这会为多个 Slot 生成重复 HTML id。当前页面有 3 个 Slot,因此文档级 id selector 存在静默取错 daily ID 的结构风险。E36 仍保留为当时“搜索为 0”的历史事实,但已被 E38 的恢复后新证据更新,不能继续表示当前模板未知。
+
+HK-24 记录恢复现场后 DevTools Sources 全局搜索 `hiddenFieldServizio` 仍为 0 个匹配。E24 的既有采集已经证明最终 handler 上下文中存在这个局部变量,但当时赋值表达式被脱敏,因此当前搜索失败不能推翻旧证据,也不能补全表达式。按照同一错误最多两次的纪律,不再继续猜搜索词;下一步从当前页面 `document.scripts` 只读包含 `InsertNewBooking` 的 inline script 文本,并只对长数字字面量脱敏。
+
+HK-25 通过当前页面 `document.scripts` 命中唯一 inline script,关闭最终 serializer:handler 只检查 `.fascia.act` 数量不为 0,然后用 `$('.fascia.act input')[0].value` 取 daily ID、用第一个 active Slot 的 `innerText` 取 `selectedHour`、用全局第一个 `.selected` 的 `dataset.date` 取日期,再 POST `InsertNewBooking`。这说明重复 hidden id 不会直接影响网站原生 handler,因为它按 active Slot 的后代 input 取值;但 handler 没有检查 active Slot 唯一、没有拒绝 `notAvailableFascia`、没有限定 input 类型/id,也没有限定 selected 日期 selector。长期插件必须在触发原生 handler 前补齐这些不变量。
+
+HK-26 已取得当前全部 `.selected` 的 DOM 顺序:一共 2 个;index 0 是 `.events` 内带 `data-date` 的 `a.input-async-abilitato.selected`,index 1 是 `.events-content` 内同样带 `data-date` 的 `li.selected.enter-right`。jQuery 第一个元素与 DOM 第一个相同,因此原生 handler 在当前页面状态会从日期 link 取得 `selectedDay`,不会误取 events-content 容器。两个真实日期值均被脱敏,只证明格式都是 `YYYY-MM-DD`,尚不能证明值相等;长期插件应验证两个表示层日期完全一致,而不是固定假设 selected 数量永远为 2。
+
+HK-27 已用纯布尔采集关闭日期同步:selectedCount=2,两个元素都有 `data-date`,日期值完全相等;第一个仍是 `.events` 日期 link,timeline selected 和 content selected 各 1。原生 handler 在当前稳定页面状态下取得的日期与内容卡片日期一致。这个结论只证明当前页面的稳定态,不把“永远恰好 2 个”写进合同;Book 仍需在每次异步日期切换后重新验证角色和相等性。
+
+HK-28/E43 纠正了此前对 HK-8 的过度解释:HK-8 只证明 2026 年 8 月默认窗口和默认日期没有正向 Slot,不证明整个 Calendar 无号。用户向后浏览到 2026 年 10 月后,`RetrieveCalendarAvailability` 返回 22 个工作日条目:前 6 个条目为 `SlotLiberi=0 / SlotRimanenti=-1`,10 月 9 日起出现正向组合,代表样本包括 `1/0`、`4/3`、`8/7`、`10/9`。同一日期的 `RetrieveTimeSlots` 返回 3 个时段:两个为 `0/-1`,DOM 带 `notAvailableFascia + dotRed + (0)`;一个为 `1/0`,DOM 是普通 `fascia`、无红点并显示 `(1)`。timeline/content selected 各 1 且日期同为 2026-10-09;正向 Slot 内有且仅有一个 8 位数字形状的 hidden daily ID,具体值未记录。正向 Slot 未点击,`act=false`;最终按钮虽 enabled,但 `InsertNewBooking` 请求数经 Network 过滤确认为 0。
+
+HK-29/E44 随后完成安全选择:授权探针对上述正向候选只调用一次 `.click()`,独立 readback 得到唯一 `.fascia.act`;active 时间、selected 日期、`(1)` 和 hidden input 形状均与候选一致,且没有负向 class/红点。最终按钮未点击,当前页面 Resource Timing 中 `InsertNewBooking=0`,机械总判定为 `done=true`。该证据关闭选择态,不关闭最终 response、服务端对账或幂等。
+
+E43 已关闭当前页面版本的正负数量组合:正向必须至少满足 `SlotLiberi > 0` 且 `SlotRimanenti >= 0`;负向样本为 `SlotLiberi = 0` 且 `SlotRimanenti < 0`。本批样本中 `SlotRimanenti = SlotLiberi - 1`,但这只记录为观察关系,不提升成跨 Sede、跨版本的永恒公式。最终选择前仍需交叉验证 response、DOM、日期、时间和 active Slot。
+
+确信度:Dublin 无号分支、Hong Kong `4937` 服务入口、Booking Form、OTP、POST→Calendar、Calendar document、Availability/TimeSlots 正负 response、正负 Slot DOM、两个数量字段的当前正向/负向组合、Slot 模板/固定 hidden id、最终 delegated handler 及 serializer、selected 日期一致性、正向 Slot 点击后的唯一 active/后代一致性为高;真正的 date click handler、`#idServizio` 的准确业务语义、ServerInfo method/payload、最终真实响应、预约编号和幂等语义仍未验证。
+
+## 1. 范围与证据纪律
+
+### 1.1 本文记录什么
+
+- Prenot@Mi 已观察到的公开页、登录后页面和服务列表。
+- `create_session()`、`query()`、`book()` 应承担的职责。
+- 当前 Italy 代码与网站证据之间的差距。
+- 下一阶段人工协作和验证步骤。
+- 已执行、未执行以及不能声称已验证的事项。
+
+### 1.2 本文不记录什么
+
+- 用户名、密码、邮箱地址或个人资料。
+- Cookie、Authorization、JWT、CSRF Token、OTP。
+- OAuth `state`、PKCE `code_challenge` 等动态值。
+- 护照、身份证、居留证明或上传文件内容。
+- 未经真实页面或 Network 证明的接口字段值。
+
+### 1.3 证据标签
+
+| 标签 | 含义 |
+|---|---|
+| `[OBSERVED]` | 来自用户截图、用户实际运行日志或已完成浏览器调研记录的网站事实;后面必须注明来源。 |
+| `[SOURCE-INFERENCE]` | 从当前源码、配置、测试或 Git 历史推断出的实现意图;不能当作网站事实。 |
+| `[UNVERIFIED]` | 尚未取得足够页面或 Network 证据,或者网站状态已经变化。 |
+
+### 1.4 证据来源索引
+
+| 编号 | 来源 | 能证明什么 | 不能证明什么 |
+|---|---|---|---|
+| E1 | 2026-08-25 用户本地执行 `tools/debug_ita_session.py` 的日志 | 插件能打开公开首页并点击登录入口;当时因缺少 `_random_sleep()` 抛出 `AttributeError` | 登录表单字段、登录成功页、Services、Query 或 Book |
+| E2 | 公开页面浏览器调研记录 | `/` 是公开登录入口;存在 `#pingid-button`;登录使用 IAM/OIDC;公开文档请求返回 HTML | 登录后的业务流程 |
+| E3 | 用户提供的上海 `/Services` 截图 | 已登录 Services 表格结构;上海机构;明确“日历尚不可用”时没有预约链接 | Dublin 服务、预约链接是否代表有号 |
+| E4 | 用户转交的 Dublin `/Services` 只读调研报告 | Dublin 机构、8 个可见服务行、`/Services/Booking/1321` 等预约链接 | 点击后的请求、草稿、OTP、日历和最终确认 |
+| E5 | 当前工作树中的源码、配置、测试和 Git 历史 | 框架调用关系、现有硬编码、运行时错误和历史接口尝试 | 目标网站当前仍接受这些接口或字段 |
+| E6 | 被引用调研任务的浏览器控制记录 | Chrome 控制连接曾失效;有些预期调查没有实际执行 | 任何未取得 DOM/Network 的网站结论 |
+| E7 | 2026-08-26 用户在同一 Dublin 登录会话中执行的一次受控 Gate 2 | `1321` 无号时的 GET/302/回退链、无号 DOM 标志、没有 BookingCalendar/OTP/预约业务 POST | 有号分支、重复调用的长期限流表现、服务器内部是否写入短暂 Session 状态 |
+| E8 | 2026-08-26 用户在新无痕窗口执行的一次人工受控登录 | `/signin/` 表单字段、一次提交成功到达 `/UserArea`、认证 DOM 标志、`authenticate` Fetch 为 200 | 自动化鼠标/输入是否被网站接受、完整 callback 文档跳转链 |
+| E9 | 2026-08-26 用户执行修改后的 `tools/debug_ita_session.py` | 自动点击登录、识别 `/signin/`、只提交一次凭据、到达认证 `/UserArea`、清理成功、进程 exit 0 | 网站未来变更、长期重复登录稳定性、Query/Book 真实行为 |
+| E10 | 2026-08-27 新增 `tools/debug_ita_query.py` 及离线测试 | 工具锁定 `service_id=1321`,代码中只有一次 Query 调用、没有 Book 调用;无号与有号安全停止分支可测试 | 真实站点本次是否仍返回无号、服务端长期限流行为 |
+| E11 | 2026-08-27 用户执行第一次真实 `tools/debug_ita_query.py` | 自动登录成功;只调用一次 Query;最终为 `/Services`;未满足无号判据时 exit 1;清理成功;用户看到意大利语弹窗 | 该次弹窗原文、1321 GET 的 Network 元数据、弹窗是否与 E7 完全相同 |
+| E12 | 2026-08-27 用户执行更新后的第二次单次 `tools/debug_ita_query.py` | `service_id=1321` 被分类为 `NoAvailable`;清理成功;进程 exit 0 | 有号分支、长期重复调用、日历和 Book |
+| E13 | 2026-08-27 Booking Form 只读结构采集器及离线测试 | 只在 Query 的 available-safe-stop 分支读取 form/path/字段和按钮元数据;不读取 value,不提交,不调用 Book | 真实有号页面的字段、选项、表单 method/action |
+| E14 | 2026-08-28 用户在已登录 Hong Kong `/Services` 页面执行的脱敏只读 DOM 采集 | Hong Kong Sede;当前表格共 9 行、1 页;通用 `Visti Nazionali e Schengen` 唯一入口为 `/Services/Booking/4937` | 进入入口后的表单、具体日期、OTP 和预约成功 |
+| E15 | 2026-08-28 用户明确授权后对 Hong Kong `4937` 执行的一次受控入口访问及 Network 截图 | `GET /Services/Booking/4937` 返回 `200 document`;最终仍为 Booking 页面;初始化 XHR 为 `GetBookingTypes` 和 `GetDdlValuesByID/?id=34`;没有 BookingCalendar 或 OTP 请求 | `200` 是否必然有日期、服务器内部是否建立短暂状态、OTP/Calendar/最终提交协议 |
+| E16 | 2026-08-28 Hong Kong `4937` Booking Form 的脱敏只读 DOM 采集 | 表单 method/action/enctype;单人类型 `1`;`Turismo=42`;OTP、Privacy、Turnstile、`AVANTI` 字段;当前无文件上传控件 | hidden value、OTP endpoint、`AVANTI` payload、Calendar/Slot/最终确认 |
+| E17 | 2026-08-28 Chrome 控制通道诊断和人工协作记录 | Chrome 正在运行、扩展已启用、native host 正确,但标签接管连续超时;因此后续证据由用户在同一登录标签中受控采集 | 任何网站业务结论;它只解释证据采集方式 |
+| E18 | 2026-08-28 Hong Kong `4937` 页面 OTP/`AVANTI` 静态 handler 的脱敏只读采集 | `sendOTP()`、GenerateOTP GET endpoint、120 秒前端计时器、`saveDdlValue()`、确认框和 `bookingForm.submit()` 调用顺序 | 请求实际是否成功、OTP 发送目标、响应 schema、`AVANTI` 服务端副作用和 Calendar |
+| E19 | 2026-08-28 Hong Kong `4937` 页面关键函数体与 CAPTCHA callback 的脱敏只读采集 | OTP 成功判据为 HTTP 200 + 原始响应文本精确等于 `"SENT"`;`ddls_0 → hiddenSelezionato_0`;无文件控件时文件检查通过;Turnstile callback 控制 `AVANTI`;页面另有 reCAPTCHA Enterprise `BOOKING` token 函数 | OTP 是否真实送达、服务端限流、`typeofbookingddl → IdTipoPrenotazione`、reCAPTCHA 函数真实调用点、`AVANTI` payload/副作用和 Calendar |
+| E20 | 2026-08-28 Hong Kong `4937` 页面预约类型及 submit 调用链的脱敏只读采集,并与 E16 DOM 交叉验证 | `change → ShowCompanions()`;单人 `1 → hiddenTipoPrenotazione/IdTipoPrenotazione` 且同行人数 `0 → numAccSelected/NumAccompagnatoriSelected`;关键元素没有 form submit handler;唯一已观察 `AVANTI` 路径直接 submit;`getCaptchaToken()` 只观察到定义 | 外部脚本或 delegated native listener 是否另有调用、真实 POST 是否携带/要求 reCAPTCHA token、服务端副作用、Calendar 和 Slot |
+| E21 | 2026-08-28 HK-7 真实页面提交前预检 | path 为 Hong Kong `4937`;单人 visible/hidden=`1/1`、同行人数 hidden=`0`、旅游 visible/hidden=`42/0`;OTP 与 `AVANTI` enabled;Turnstile 字段 1 个、reCAPTCHA 字段 0 个 | 点击 `AVANTI` 后 `saveDdlValue()` 的运行时瞬间、OTP/POST 真实请求、token 内容、Calendar 和 Slot |
+| E22 | 2026-08-28 HK-7 唯一一次真实 OTP 与唯一一次 Booking Form POST | Privacy 先勾选;GenerateOTP GET 1 次、200、`SENT` 且邮件送达;POST 4937 1 次、302、Location 指向 BookingCalendar;Calendar GET 200 document 且最终 location/title 已确认;仅观察到 Turnstile 字段名;日期/时间/最终确认点击均为 0 | OTP 有效期、POST payload/token 值、服务端草稿状态、日期和时间接口、最终确认协议 |
+| E23 | 2026-08-28 关机后恢复的 Hong Kong Calendar 零点击脱敏采集 | `/BookingCalendar` 当前 DOM、42 个 disabled 日期格、`31/08/2026` 的 `notAvailableDay active`、默认 selected 日期和三个 `(0)` 时间段;页面生命周期中的三个 Calendar XHR path;静态 `InsertNewBooking` POST path/字段名 | XHR method/status/response schema;`(0)` 的精确定义;任何真实可用 Slot;最终 POST 的成功/失败响应;页面恢复前后的服务器状态连续性 |
+| E24 | 2026-08-28 Hong Kong Calendar Slot 与 final handler 零点击脱敏采集 | 三个时段均为 `.fascia.notAvailableFascia`;document-level `.fascia` click 会无条件添加 `act`;当前活跃 `#btnPrenotaNoOtp` 要求 `.fascia.act` 后调用 InsertNewBooking;旧 `GeneraOTP(true)` block 已注释;response 使用 `errorMessage`/`url` | 可用 Slot 的正向 class/容量 schema;CSS 是否阻止人工点击 unavailable;外部脚本是否还有其他 final listener;最终 POST 的真实 response/副作用;截断的 error callback |
+| E25 | 2026-08-28 用户在 DevTools Sources 打开的 `stormcaster.js` 中执行三次源码搜索 | `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots` 均无匹配;initiator 不能作为源码文件定位证据 | endpoint 是否被动态拼接;真正的业务脚本/inline source;`stormcaster.js` 的确切职责 |
+| E26 | 2026-08-28 用户使用 DevTools Sources 全局搜索 `RetrieveCalendarAvailability` | 命中 `CaricaTimelineOrizzontale(_Mese, _Anno, _Oggi, _Servizio, _GiornoDaSelezionare)`;函数内设置 `Metodo='RetrieveCalendarAvailability'` | 所在文件名、完整 URL 拼接、HTTP method、payload、response schema 和 DOM 更新逻辑 |
+| E27 | 2026-08-28 用户提供完整 `CaricaTimelineOrizzontale(...)` 函数 | WebMethod 参数为 `_Servizio`、`selectedDay=_Oggi`;success 参数为 `GiornoDaSelezionare=_Oggi`;error 参数为空;调用 `EseguiAsync(..., CostruisciTimelineOrizzontale, StampaErroreInConsole)`;三个签名参数未使用 | `EseguiAsync` 的 URL/method/serialization;availability response schema;日期 DOM 构建与错误处理 |
+| E28 | 2026-08-29 用户提供完整 `EseguiAsync(Metodo, Parametri, MetodoSuccess, MetodoError)` | `POST urlServizio+Metodo`;`Parametri[0]` JSON 序列化;content type 为 JSON UTF-8;response 按 JSON 解析并原样传给 success;error 只无参调用 callback | 各 endpoint response 字段;HTTP status/error body 分类;`RetrieveServerInfo` 是否也经该执行器调用 |
+| E29 | 2026-08-29 用户提供完整 `CostruisciTimelineOrizzontale(JsonGiorniTimelineOrizzontale, Parametri)` | response 再经 `$.parseJSON` 得到数组;元素字段为 `DateLibere`、`SlotRimanenti`;空数组设置 `GiorniDisponibili=0`;每项建立日期/事件 DOM并记录 `date@slots`;最后按 success 参数初始化时间线 | 正数/零值如何映射日期 class;真实 response 样本;`CreaGiorno`/`CreaEventiGiorno`/`InizializzaTimelineOrizzontale` 与 TimeSlots 调用链 |
+| E30 | 2026-08-29 用户提供完整 `InizializzaTimelineOrizzontale(GiornoDaSelezionare)` | datetimepicker 事件先解绑再初始化;调用日历初始化、无预约日期禁用和异步控件 class 切换;目标日期不存在时回退首个时间线日期;最后执行程序化 `.click()` | `DisabilitaGiorniSenzaPrenotazioni` 的正负日期规则;真正的 click/TimeSlots handler;程序化 click 是否是当前唯一 TimeSlots 触发源 |
+| E31 | 2026-08-29 用户提供完整 `DisabilitaGiorniSenzaPrenotazioni()` | 所有 `.day` 先 disabled;匹配 `date@slot` 后,`slot >= 0` 添加 `availableDay` 并移除 disabled,否则添加 `notAvailableDay`;`0` 也属于可点击分支 | `SlotRimanenti` 的真实类型/业务语义;重复日期和旧 class 是否由上游 DOM 重建消除;真正的 TimeSlots handler;正向 Slot class |
+| E32 | 2026-08-29 用户提供完整 `AbilitaInputAsincroni()` | 只处理 `[data-async="true"]:not(.selected)`;移除 `input-async-disabilitato` 并添加 `input-async-abilitato`;没有事件注册、click 或网络调用 | 谁注册真正的 click handler;`RetrieveTimeSlots` response/DOM 映射;`data-async` 由哪个构建函数赋值;selected 元素的 class 生命周期 |
+| E33 | 2026-08-29 用户提供完整 `CaricaTimelineVerticale(_Giorno, _ContenutiEventi)` | `Metodo='RetrieveTimeSlots'`;request 对象只有 `selectedDay=_Giorno`、`idService=$('#idServizio').val()`;通过 `EseguiAsync` POST JSON;success 为 `CostruisciSchedaFasce(response, _ContenutiEventi)` | 谁调用该函数;`#idServizio` 的精确业务语义;TemplateFasce DOM;真实正向 Slot 样本 |
+| E34 | 2026-08-29 用户提供完整 `CostruisciSchedaFasce(JsonFasceGiorno, Parametri)` | response 再经 `$.parseJSON` 得到数组;长度 1 只设置 `unicaFascia`;每项经 `CreaFasce` 生成 HTML 并追加至 `Parametri.selectedContent`;空数组仍调用 `CostruisciTimelineVerticale` | 真正 click handler;空数组最终 UI 状态;TemplateFasce DOM;真实正向 Slot 样本 |
+| E35 | 2026-08-29 用户提供完整 `CreaFasce(fascia, unicaFascia)` | item 字段含 `SlotRimanenti`、`SlotLiberi`、起止时间、`IDCalendarioServizioGiornaliero`;负数生成 `notAvailableFascia/dotRed`;唯一非负项自动 `act`;`(0)` 来自 `SlotLiberi` | 两个 Slot 字段的准确业务关系;TemplateFasce HTML/ID 放置;真实正向 item/DOM;daily calendar ID 如何进入最终 POST |
+| E36 | 2026-08-29 用户在 DevTools Sources 全局搜索 `TemplateFasce` | 0 个匹配;当前可搜索 Sources 中没有该符号的明文定义 | 运行时变量是否由动态脚本、闭包、压缩改名或字符串拼接产生;最终渲染 DOM;模板不存在 |
+| E37 | 2026-08-29 用户在 Hong Kong Calendar 运行脱敏只读 DOM 采集 | `/BookingCalendar` 有 3 个 Slot;第一项为 `.fascia.notAvailableFascia`,包含 `.dot.dotRed`、时间 span、数量 span、`input[type=hidden]#idHiddenFasciaServizio`;value 只确认 8 位数字形状;父 `li.selected.enter-right` 的三个直接子项均为负向 fascia | 三个 Slot 是否各有同名 input/不同值;真实 daily ID;最终 handler 的取值表达式;正向 Slot DOM |
+| E38 | 2026-08-29 用户恢复现场后提供完整 `const TemplateFasce = ...` | 模板精确层级与 E37 一致;每次渲染固定写入 `idHiddenFasciaServizio`,value 来自 `IDCalendarioServizioGiornaliero`;时间/数量/class 占位符位置闭环;逐 item 渲染会生成重复 HTML id | 最终 handler 是否正确限定 active Slot;真实 daily ID;正向 Slot;浏览器运行时对重复 id 的直接计数 |
+| E39 | 2026-08-29 用户恢复现场后在 DevTools Sources 搜索 `hiddenFieldServizio` | 0 个匹配;当前 Sources 搜索不能补回 E24 中被脱敏的赋值表达式 | 变量在当前 inline script 中是否仍存在;Sources 搜索为何遗漏;最终 handler 是否限定 active Slot;赋值表达式原文 |
+| E40 | 2026-08-29 用户在 `/BookingCalendar` 运行只读 `document.scripts` 采集 | 25 个 script 中唯一命中 scriptIndex 22 inline;handler 用第一个 `.fascia.act input` value、首个 active Slot `innerText`、全局首个 `.selected.dataset.date` 构造 InsertNewBooking POST;response 使用 `errorMessage/url` | 当前所有 `.selected` 的 DOM 顺序;多 active/多 input/负向 Slot 时网站行为;最终 POST 真实 response、幂等和副作用 |
+| E41 | 2026-08-29 用户在 `/BookingCalendar` 运行脱敏 selected DOM 采集 | selected 共 2 个;index 0 为 `.events` 内日期 link、index 1 为 `.events-content` 内 li;二者都有 `data-date` 且格式为 YYYY-MM-DD;jQuery/DOM 第一个一致 | 两个 data-date 的真实值是否相等;未来页面 selected 数量/顺序稳定性;正向日期切换后的同步行为 |
+| E42 | 2026-08-29 用户在 `/BookingCalendar` 运行 selected 日期纯布尔一致性检查 | selectedCount=2;全部有 data-date;全部日期值相等;第一个是 events 日期 link;timeline/content selected 各 1 | 真实日期值;异步切换瞬间的一致性;未来页面结构;真实正向 Slot |
+| E43 | 2026-08-29 用户向后浏览 Hong Kong Calendar,并提供正向 Availability、TimeSlots、DOM 与 final=0 证据 | 2026-10-09 的日期/时段正向组合为 `SlotLiberi=1 / SlotRimanenti=0`;两个负向时段为 `0/-1`;正向 DOM 无负向 class/红点并显示 `(1)`;selected 两层日期一致;每个 Slot 内 hidden daily ID 只记录 8 位数字形状;`InsertNewBooking=0` | 正向 Slot 点击后的唯一 `act`;请求所用 runtime service ID 的业务语义;其他 Sede/页面版本是否保持相同数量关系;最终真实响应 |
+| E45 | 2026-08-30 负责人回传 production_query 模式第二轮及聚合验收日志 | 第二轮 8/9 月正向 0、10 月正向 14,3 个月后停在首个正向月份,最早 2026-10-13;两轮均正向、Availability 共 6 次;OTP/AVANTI 各 1 次,final=0,Reservation/Waitlist 前后 0/0,cleanup OK、exit 0 | 第一轮具体最早日期、启动源码指纹、原始 Network、自动接码、长期/跨 Sede 稳定性和完整 Book |
+| E46 | 2026-08-30 现有 VFS/BLS、共享邮件 SDK 的只读走读及假邮件日志诊断;负责人回答接入状态“不确定” | 两插件共用 fetch_mail_content;SDK 只返回正文;DEBUG 日志可包含响应正文和收件人,默认 INFO 不输出该行;诊断全为合成数据、网络请求 0 | 当前 Italy 邮箱是否已被云端授权、真实邮件模板、云端筛选/重复邮件/时间窗口语义、任何真实邮件泄露 |
+| E47 | 2026-08-30 负责人分享已打开的 Gmail OTP 邮件标签;精确标签核对和两次只读访问尝试 | 首次浏览器实例、标签标识、标题及 URL 均匹配;标题以 OTP Code 开头;正文读取及恢复访问均超时,已停止重试 | 实际发件人、邮件主题字段、正文/验证码格式、有效期、云端邮箱授权;标题不能替代邮件内容证据 |
+| E48 | 2026-08-30 负责人手工转述同一封 Italy OTP 邮件的发件人、主题和验证码行 | 显示名 Prenotami;地址 noreply-prenotami@esteri.it;主题 OTP Code;正文片段 OTP Code:[OTP],本样本为 6 位数字;真实验证码未写入文件或用于任何请求 | 云端取信权限、实际收件人与账号的对应关系、完整邮件/HTML、邮件认证头、其他模板与有效期;不是自动接码验收 |
+| E49 | 2026-08-30 两名用户指定 luna_worker/max 分别只读调查 web-ui / webapp;主代理做调用合同与 MIME 提取离线复核 | web-ui 无邮箱授权页面;webapp 有管理员 IMAP 授权/取信 API;8 参数与 Coordinate 对齐;确认子串过滤、UTC 闭区间、最近 10 封候选、HTML 保留/重复、非硬超时与已读副作用;两仓无改动 | 线上代码版本、实际管理员 token、目标邮箱登记/登录有效性、真实邮件筛选与完整自动接码;不批准共享后端或 SDK 修改 |
+| E50 | 2026-08-30 负责人就 Query 账号邮箱是否已接入并授权现有云邮箱 API 回复“还没有,这个记下来当 todo 吧” | 接入/授权尚未完成,列为 ITA-OTP-01 待办并暂缓;自动接码保持未完成,已有人工 OTP 的生产 Query 验收不受影响 | 后续恢复时间、实际邮箱授权和受控取信结果;本次不执行邮箱接入、发码或取信 |
+| E51 | 2026-08-30 负责人回传 15 分钟 Calendar soak 的完整终端日志;版本 `qcal1-calendar-soak-v11`、指纹 `64b0581dbd3e` | 909 秒、3 次正向查询、1 次受控重建恢复、恢复后 2 次新查询;监测 OTP/AVANTI/final 均 0,预约/候补均 0 → 0,exit 0 | 重建后认证仍有效;不证明真实认证过期、断网或 2/24 小时稳定性;ITA-OTP-01 仍未完成 |
+
+## 2. 已取得的网站事实
+
+### 2.1 公开首页和登录入口
+
+| 结论 | 页面/URL | 证据 | 副作用 | 确信度 |
+|---|---|---|---|---|
+| 公开入口为根路径 | `/` | `[OBSERVED:E1,E2]` 页面标题为 Login,并存在登录入口 | 建立或刷新公开会话、反爬状态 | 高 |
+| 登录入口元素为 `#pingid-button` | `/` | `[OBSERVED:E1,E2]` | 点击后进入身份认证流程 | 高 |
+| 身份认证由 `iam.esteri.it` 的 OIDC/PingID 流程承接 | IAM authorize 页面 | `[OBSERVED:E2]` 登录链接含标准 OIDC/PKCE 参数名,回调指向 `/pingid` | 登录会改变认证 Session | 高 |
+| `/Home` 不是当前可靠的公开入口 | `/Home` | `[OBSERVED:E2]` 调研时进入 Radware Bot Manager/hCaptcha 页面 | 可能刷新反爬状态 | 高 |
+| 曾出现 `/signin/{编码后的完整 authorize URL}` 形式的 404 | IAM 登录过程 | `[OBSERVED:用户报告]`;动态 OAuth 参数未保存 | 未知 | 中 |
+| 当前正确 IAM 表单入口 path 为 `/signin/` | IAM 登录过程 | `[OBSERVED:E8]`;query、fragment 和动态 OAuth 值未保存 | 进入登录表单 | 高 |
+| 登录表单使用 `callback_1`、`callback_2` 和 `button[type=submit]` | `/signin/` | `[OBSERVED:E8]` 非敏感 DOM 元数据 | 输入并提交凭据会发起登录 | 高 |
+
+关于 404 的边界:正确的人工单次流程没有复现 404,仓库也没有构造 `/signin/{编码 URL}` 的代码;仍不能断言历史 404 的准确来源。自动化验证若再次遇到它,必须单次失败后停止,并只输出脱敏 path。
+
+### 2.2 登录成功状态
+
+| 结论 | 页面/URL | 证据 | 确信度 |
+|---|---|---|---|
+| 登录后的 Dashboard 路径为 `/UserArea` | `/UserArea` | `[OBSERVED:用户登录页和调研报告]` | 高 |
+| 登录后页面存在 `Prenota`、`Cambio Sede`、`Disconnetti` | `/UserArea` | `[OBSERVED:调研报告]` | 高 |
+| 普通 `Prenota` 导航指向 `/Services` | `/UserArea` | `[OBSERVED:调研报告]` | 高 |
+| `/UserArea` 存在一个 `.app-menu` 和一个 `/Services` 链接 | `/UserArea` | `[OBSERVED:E8]` 只读 DOM 统计 | 高 |
+| 一次人工凭据提交后成功到达 `/UserArea` | IAM → `/UserArea` | `[OBSERVED:E8]`;`authenticate` Fetch 为 200 | 高 |
+| `create_session()` 最合适的业务成功终点是认证后的 `/UserArea` | `/UserArea` | `[SOURCE-INFERENCE]`:认证与查询职责分离;A 合同已确认 | 高 |
+
+最后一项是职责设计建议,不是网站强制规则。实现时应同时检查 URL 和认证页面标志,不能只比较 URL 字符串。
+
+### 2.3 上海 Services 证据
+
+用户注册账号时最初选择上海,随后提供了已登录的 `/Services` 截图。
+
+已观察到:
+
+- 机构:意大利驻上海总领事馆。
+- 页面标题:`Index - Prenot@Mi`。
+- 表格列包含 `Tipologia`、`Servizio`、`Descrizione`、`Prenotazione`、`Link`、`Email`。
+- 当时可见的两行均为 AIRE 服务。
+- `Prenotazione` 显示 `Calendario prenotazioni ancora non disponibile`。
+- `Link` 显示 `Non ci sono link associati`,没有预约入口。
+
+这个页面证明:网站至少存在“服务行存在,但日历不可用且没有预约链接”的状态。它不能证明反命题——有 `Prenota` 链接仍然不等于有具体日期。
+
+确信度:高,来源为用户截图 E3。
+
+### 2.4 Dublin Services 证据
+
+用户后来通过 `Cambio Sede` 切换到 Dublin。转交的只读报告记录:
+
+- 机构:`AMBASCIATA D'ITALIA A DUBLINO, IRLANDA`。
+- URL:`/Services`。
+- 页面标题:`Index - Prenot@Mi`。
+- 页面有 8 个可见服务行,其中 7 行有 `Prenota` 链接,1 行明确显示日历尚不可用。
+
+| Tipologia | Servizio | Descrizione | 页面状态 | path |
+|---|---|---|---|---|
+| DOCUMENTI DI IDENTITA’/VIAGGIO | Carta d’identità | Carte d'Identita' Elettroniche | 有 `Prenota` | `/Services/Booking/287` |
+| CITTADINANZA | Cittadinanza per discendenza | Cittadinanza per discendenza | 日历尚不可用 | 无 |
+| VISTI | Visti | Visti Schengen e Nazionali | 有 `Prenota` | `/Services/Booking/1321` |
+| VISTI | Visti Schengen(90 天以内) | Visti per Familiare UE | 有 `Prenota` | `/Services/Booking/1322` |
+| VISTI | Visti Schengen(90 天以内) | Visti Affari | 有 `Prenota` | `/Services/Booking/1323` |
+| NOTARILE | Procure generali e speciali | Atti Notarili… | 有 `Prenota` | `/Services/Booking/5598` |
+| NOTARILE | Autenticazione di firme… | 仅限签名认证的服务说明 | 有 `Prenota` | `/Services/Booking/5600` |
+| DOCUMENTI DI IDENTITA’/VIAGGIO | Passaporto | Prenotazione appuntamenti passaporto | 有 `Prenota` | `/Services/Booking/5770` |
+
+注意:部分较长显示文本在转交报告中已经省略,本文没有补猜全文。预约控件的 `class`、`data-*`、`onclick`、`disabled`、`aria-disabled` 未取得可靠证据。
+
+确信度:中高,来源为 E4;点击后的同会话证据见 E7。
+
+### 2.5 Gate 2:Dublin 当前无号分支
+
+用户在 Network 清空且开启 Preserve log 后,只点击了一次 `Visti Schengen e Nazionali` 的 `Prenota`。实际链路为:
+
+```text
+GET /Services/Booking/1321
+  → 302 Found
+  → Location: /Services
+GET /Services
+  → 200 OK
+  → 弹窗:所选服务的可用名额已耗尽
+```
+
+Network 过滤结果:
+
+- `BookingCalendar`:0 个请求。
+- `otp`:0 个请求。
+- 预约业务 POST:0 个请求。
+- 自动 POST:4 个,均指向同一个 `/<dynamic-uuid>`,返回 `200 text/plain`,响应服务器标志为 `rdwr`。结合动态路径推断为 Radware 安全遥测,不是预约业务请求;没有读取或保存其 Payload。
+
+无号页面的稳定 DOM 证据:
+
+```html
+<input
+  id="WNotAvailable"
+  name="WNotAvailable"
+  type="hidden"
+  value="...非空的本地化无号消息..."
+>
+```
+
+页面使用 `jquery-confirm.js` 把该值渲染到 `.jconfirm-content`。弹窗容器 ID 形如 `jconfirm-box32262`,数字部分动态生成,不能作为选择器。
+
+实现判断必须同时满足:最终 path 为 `/Services`,并且 `#WNotAvailable` 的 `value` 非空。不能只判断 hidden input 是否存在,因为模板可能在空值时也渲染它。
+
+结论:A 方案被真实证据否定。`Prenota` 在无号时依旧存在;真正的无号门禁发生在服务入口 GET。B 方案仍未验证,因为本次请求在进入预约表单和日历之前就被服务器拦回。
+
+### 2.6 第一次真实自动 Query
+
+用户执行独立单次 Query 工具后:
+
+- 自动登录到 `/UserArea` 成功。
+- 工具输出 `query_attempt=1`,随后只探测 `service_id=1321`。
+- 最终 URL 为 `/Services`。
+- 当时没有读到非空 `#WNotAvailable`,因此输出 `ITA_QUERY_FAILED`、清理成功并 exit 1。
+- 用户确认运行过程中出现过意大利语弹窗,但弹窗已经消失,没有保存原文或截图。
+- 没有执行 Book、OTP、表单、日历或最终确认。
+
+这次结果不能被解释为“有号”或“无号”。它能证明 fail-closed 生效,也暴露了只依赖 hidden input 的可观测性缺口。用户粘贴的账号标识、动态端口、指纹和实例 ID 没有写入本文。
+
+### 2.7 第二次真实自动 Query
+
+更新后的工具增加了可见弹窗的保守分类,同时保持一次 Query、无重试、无 Book。用户执行后取得:
+
+- `ITA_QUERY_NONE_AVAILABLE service_id=1321 status=NoAvailable`
+- `ITA_QUERY_CLEANUP_OK`
+- `EXIT_CODE=0`
+
+这组结果机械证明当前真实无号分支已被插件正确识别并完成资源清理。它不证明有号分支、Calendar、OTP 或 Book 已经可用。
+
+### 2.8 Hong Kong Services 与目标服务
+
+用户在同一个已登录标签中读取 Hong Kong `/Services`。脱敏 DOM 结果为:
+
+- Sede:`CONSOLATO GENERALE D'ITALIA A HONG KONG, REPUBBLICA POPOLARE CINESE`。
+- 页面 path:`/Services`。
+- 页面标题:`Index - Prenot@Mi`。
+- 分页文本:`Previous 1 Next`;当前只有第 1 页。
+- 表格共 9 个服务行,均有 `PRENOTA` 入口。
+
+| Tipologia | Servizio | Descrizione | path |
+|---|---|---|---|
+| SERVIZI CONSOLARI | Servizi Consolari | AIRE/Stato Civile/Asseverazioni/Certificazioni Varie | `/Services/Booking/128` |
+| LEGALIZZAZIONI | Legalizzazioni di documenti | Asseverazione firma traduttore | `/Services/Booking/884` |
+| DOCUMENTI DI IDENTITA’/VIAGGIO | Passaporto | Domande di rilascio passaporto | `/Services/Booking/981` |
+| VISTI | Visti | Visti per Affari - EXTRA SLOTS | `/Services/Booking/1154` |
+| VISTI | Visti | Visti Nazionali e Schengen | `/Services/Booking/4937` |
+| DOCUMENTI DI IDENTITA’/VIAGGIO | Carta d’identità | Rilascio Carta d'Identità Elettronica (CIE) | `/Services/Booking/5085` |
+| CITTADINANZA | Cittadinanza per matrimonio | Domande Cittadinanza per Matrimonio e Discendenza | `/Services/Booking/5459` |
+| NOTARILE | Procure generali e speciali | Procure Generali e Speciali, Convenzioni Matrimoniali, Autentica di Firma | `/Services/Booking/5460` |
+| VISTI | Visti | Visti Studio/attività accademiche - EXTRA SLOTS | `/Services/Booking/5523` |
+
+`4937` 是当前页面唯一没有被限定为商务或学习 EXTRA SLOTS 的通用国家/申根签证入口。此时仍只能把它认定为“短期申根旅游的上层服务入口候选”;真正的 `Turismo` 语义由下一节的 Booking Form 选项确认。
+
+标签:`[OBSERVED:E14]`。Sede、行数、显示文本、href 和唯一性为高确信度;数字 ID 是否长期稳定为中。
+
+### 2.9 Hong Kong 服务入口成功分支
+
+用户明确授权只访问一次 `/Services/Booking/4937`,并在点击前清空 Network、保留日志。实际结果:
+
+```text
+GET /Services/Booking/4937
+  → 200 OK (document)
+  → 最终 URL 仍为 /Services/Booking/4937
+  → 页面标题 Booking - Prenot@Mi
+```
+
+没有观察到 `Location`,因此不是 Dublin 无号分支的 `302 → /Services`。页面初始化过程中观察到:
+
+| method | path | status | type | 当前解释 |
+|---|---|---:|---|---|
+| GET | `/Services/Booking/4937` | 200 | document | 预约前置页面入口 |
+| 未记录 | `/Services/GetBookingTypes` | 200 | XHR | 预约类型候选数据 |
+| 未记录 | `/Services/GetDdlValuesByID/?id=34` | 200 | XHR | 附加下拉选项数据 |
+
+本次 Network 中:
+
+- `BookingCalendar` 请求数为 0。
+- OTP 请求数为 0。
+- 没有填写、勾选或提交表单。
+- 没有选择日期、时间或最终确认。
+- 页面同时加载了 Cloudflare challenge 相关资源,并出现动态安全遥测请求;这些不能被当作预约业务接口。
+
+结论:`GET 服务入口 → 200 + bookingForm` 是已观察的“允许进入预约前置流程”阶段证据,早期记录曾命名为 `EntryAvailable`。E43 后的当前合同不把它发布为生产号源信号:它自身没有日期、范围或容量,也不能证明服务端内部没有建立短暂 Session 状态。
+
+标签:`[OBSERVED:E15]`。客户端请求链为高确信度;服务器内部副作用为未知。
+
+### 2.10 Hong Kong Booking Form 合同
+
+用户在不读取任何字段 value、不点击按钮的前提下采集真实 DOM。页面没有 alert。业务表单为:
+
+```text
+form#bookingForm
+method: POST
+action: /Services/Booking/4937
+enctype: multipart/form-data
+```
+
+页面还存在独立的 `POST /Account/LogOff` 登出表单,与预约协议无关。
+
+#### 已观察的业务控件
+
+| 业务含义 | DOM | 真实选项/约束 | 证据结论 |
+|---|---|---|---|
+| 预约类型 | `select#typeofbookingddl` | `Prenotazione Singola = 1`,当前唯一选项 | Hong Kong 当前服务只显示单人预约 |
+| 同行人数 | `select#ddlnumberofcompanions` | 当前 options 为空 | 单人应如何同步为 0 尚未观察 |
+| 签证目的 | `select#ddls_0` | `Turismo = 42` | 短期旅游业务语义已确认 |
+| 备注 | `textarea#BookingNotes[name=BookingNotes]` | 非 required | 当前为可选字段 |
+| OTP 输入 | `input#otp-input[name=otp-input]` | required,placeholder=`OTP` | OTP 位于 Calendar 之前的前置表单 |
+| OTP 发送 | `button#otp-send` | `type=button`,文字 `INVIA NUOVO CODICE`,onclick 调用 `sendOTP()` | 是明确外部副作用;endpoint 和静态成功判据见 §2.11–§2.12 |
+| 隐私同意 | `input#PrivacyCheck[name=PrivacyCheck]` | required | `AVANTI` 前置条件 |
+| Turnstile | `input[name=cf-turnstile-response]` | hidden;动态 value 未读取 | 与当前页面/浏览器上下文绑定 |
+| 下一步 | `button#btnAvanti` | `type=button`,文字 `AVANTI` | 静态 handler 与 E22 真实 POST/302 已观察;草稿语义未知 |
+
+`ddls_0` 的完整真实选项为:
+
+| value | text |
+|---:|---|
+| 31 | Affari |
+| 32 | Cure Mediche |
+| 33 | Gara Sportiva |
+| 34 | Lavoro Autonomo |
+| 35 | Lavoro Subordinato |
+| 36 | Missione |
+| 37 | Motivi Religiosi |
+| 38 | Ricerca |
+| 39 | Studio |
+| 40 | Transito |
+| 41 | Trasporto |
+| 42 | Turismo |
+| 43 | Turismo - Visita famiglia / amici |
+| 64 | Reingresso |
+| 65 | Altro |
+| 66 | Motivi Familiari/Ricongiungimento Familiare |
+
+空选项为 `value=0`,初始 selected。`42` 是本次真实 Hong Kong DOM 的值;实现不能未经其他 Sede 验证就把它提升为跨地区永恒常量,首选按配置和显示语义交叉校验。
+
+#### 页面同步字段
+
+以下 hidden 字段名已观察,但值按证据纪律没有读取:
+
+- `ServizioDescrizione`
+- `MessaggioRassicuranteWaitingList`
+- `isWaitingListEnabled`
+- `IDServizioConsolare`
+- `IDServizioErogato`
+- `IdTipoPrenotazione`
+- `NumMaxAccompagnatori`
+- `NumAccompagnatoriSelected`
+- `DatiAddizionaliPrenotante[0]._Descrizione`
+- `DatiAddizionaliPrenotante[0]._Obbligatorio`
+- `DatiAddizionaliPrenotante[0]._Id`
+- `DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoDatoAddizionale`
+- `DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.IDTipoControllo`
+- `DatiAddizionaliPrenotante[0]._TipoDatoAddizionale.RegEx`
+- `DatiAddizionaliPrenotante[0]._idSelezionato`
+
+可见 `select#typeofbookingddl` 和 `select#ddls_0` 自身没有 `name`。E19 已确认网站 JavaScript 会把 `ddls_0` 的非空、非零选择写入 `hiddenSelezionato_0`,后者对应 `DatiAddizionaliPrenotante[0]._idSelezionato`;因此 Hong Kong 的 `Turismo=42` 同步链已由静态函数闭环。E20 进一步确认 `typeofbookingddl` 的 change handler 会把经 DOMPurify 处理的选择写入 `hiddenTipoPrenotazione`,后者在 E16 中对应 `IdTipoPrenotazione`;单人 `1` 还会把 `numAccSelected/NumAccompagnatoriSelected` 设为 `0`。实现应触发网站原生 change 事件并验证同步结果,不能手工猜 hidden payload。
+
+当前真实表单没有 `input[type=file]`。因此 Hong Kong 样本不支持“预约前置页必须上传护照/居留文件”的假设;其他 Sede 是否存在文件字段仍需各自验证。
+
+标签:`[OBSERVED:E16,E19,E20]`。form、字段名、选项、required、按钮、单人和 `Turismo` hidden 同步为高确信度;真实请求仍未验证。
+
+### 2.11 Hong Kong OTP 与 `AVANTI` 静态 handler
+
+用户继续在同一页面执行脱敏只读脚本,只读取按钮绑定和相关 inline script,没有点击任何按钮。
+
+#### OTP handler
+
+`button#otp-send` 的 inline/native onclick 均调用:
+
+```javascript
+sendOTP();
+```
+
+没有观察到该按钮的 jQuery handler。`sendOTP()` 的静态调用顺序为:
+
+1. 隐藏 `#IdOtpSent` 和 `#IdOtpInvalid`。
+2. 禁用 `#otp-send`,显示 `#otp-loader`。
+3. 异步发起:
+
+   ```text
+   GET /BookingCalendar/GenerateOTP?ServiceID=4937
+   ```
+
+4. 回调后隐藏 loader、重新启用按钮。
+5. 成功分支显示 `#IdOtpSent` 并执行 `startOtpTimer(120)`。
+6. 失败分支显示 `#IdOtpInvalid`。
+
+当前页面还渲染了 `if (0 > 0) { startOtpTimer(0); }`;它只能说明本次页面初始剩余计时值为 0,不能证明服务器没有更长限流,也不能作为重试依据。E19 随后补齐完整比较表达式:只有 HTTP 200 且原始 `responseText` 精确等于 `"SENT"` 才被前端认作发送成功;这仍只是客户端协议,尚未由真实请求验证。
+
+最重要的协议事实:这个 endpoint 使用 HTTP GET,但业务语义是发送邮件 OTP,具有明确外部副作用。它必须按“命令”而非“安全 GET”处理:Query 永不调用,Book 每次单独授权后至多调用一次,响应不明时不自动重试。
+
+#### `AVANTI` handler
+
+`button#btnAvanti` 没有 inline/native onclick,但绑定了一个 jQuery `click` handler。已观察顺序:
+
+1. `#typeofbookingddl` 为 0 时显示预约类型错误并停止。
+2. 检查通用 `.boolean-datoaddizionale` 和 companion 条件。
+3. 隐藏 `#IdOtpSent`。
+4. 调用 `CheckMaxFileSize()`;失败则停止。
+5. 调用 `saveDdlValue()`。
+6. 使用原生 `window.confirm(...)` 显示 `#divRiepilogoPrenotazione` 摘要。
+7. 用户确认后调用 `$('#bookingForm').submit()`;取消则停止。
+
+`bookingForm` 自身没有观察到 inline/native/jQuery handler,因此当前最直接的静态合同仍是表单声明:
+
+```text
+POST /Services/Booking/4937
+multipart/form-data
+```
+
+E19 随后确认 `saveDdlValue()` 只处理当前附加下拉 `ddls_0 → hiddenSelezionato_0`;它没有处理预约类型。`CheckMaxFileSize()` 会遍历页面全部文件控件并拒绝大于 1 MiB 的首个文件;当前页面没有文件控件,因此循环为空并返回 `true`。这进一步证明它是跨服务共用脚本,不能因为 handler 中存在 AIRE/Passport 提示或文件检查就把它们当作 Hong Kong visa 的必需字段。
+
+静态 endpoint 列表还出现 `/Services/GetRelationshipType`;本次 Network 没有观察到它,当前只标记为 companion/multi-booking 候选,不纳入单人旅游主路径。
+
+页面另有多处启用/禁用 `#btnAvanti` 的代码行;E19 已补齐 Turnstile callback 上下文,详见下一节。
+
+标签:`[OBSERVED:E18]`。handler 绑定、代码中 endpoint 和调用顺序为高确信度;真实 Network、response、邮件目标、服务端状态变化为未验证。
+
+### 2.12 Hong Kong 关键函数体与 CAPTCHA 候选
+
+用户继续在同一 Booking Form 上执行零副作用静态采集。采集时 `#otp-send` 和 `#btnAvanti` 都处于 enabled;没有读取任何运行时 token,也没有点击按钮。
+
+#### OTP 的精确客户端判据
+
+`sendOTP()` 仅在 `readyState == 4 && status == 200` 时处理结果。其成功条件不是模糊文案,而是:
+
+```text
+raw responseText == "\"SENT\""
+```
+
+换成人话:响应体必须是一个 JSON 字符串,其内容为 `SENT`;浏览器拿到的原始文本包含外层双引号。成功后显示 `#IdOtpSent` 并执行 `startOtpTimer(120)`;HTTP 200 但内容不匹配时显示 `#IdOtpInvalid`。
+
+这个函数没有为非 200、网络错误或超时注册明确恢复分支。发生这些情况时,静态代码可能让 loader 或禁用状态悬而未决。插件因此不能只等待“按钮重新可用”,也不能在结果不明时自动重发;必须把它分类为 `OutcomeUnknown`,由人工核对邮件和页面状态。
+
+`startOtpTimer(120)` 每秒递减一次,归零后重新启用按钮。这只证明 120 秒客户端冷却,不证明服务器端限流也恰好为 120 秒。
+
+#### 字段同步和文件检查
+
+`saveDdlValue()` 的真实职责很窄:
+
+```text
+ddls_0 的值非空且非 0
+  → 写入 hiddenSelezionato_0
+```
+
+结合 E16 的 DOM,`Turismo=42` 会被同步至提交字段 `DatiAddizionaliPrenotante[0]._idSelezionato`。这个函数本身没有处理 `typeofbookingddl`;E20 随后在 `ShowCompanions()` 中找到并闭环了 `Prenotazione Singola=1 → IdTipoPrenotazione`,详见 §2.13。
+
+`CheckMaxFileSize()` 会检查所有 `input[type=file]` 的首个文件是否超过 1 MiB。Hong Kong 当前真实 DOM 的文件控件数为 0,所以函数保持初始 `true` 并正常通过;这不构成上传任何材料的要求。
+
+#### Turnstile 与 reCAPTCHA Enterprise
+
+页面源码包含两套不同的反自动化机制或候选代码,不能混为一个 Token,也不能仅凭函数存在就认定两者都在当前路径生效:
+
+1. Cloudflare Turnstile:`turnstileCallback()` 启用 `#btnAvanti`;`turnstileExpired()` 和 `turnstileTimeout()` 禁用按钮并调用 `turnstile.reset()`;`turnstileError()` 只显示错误提示,已采集片段中没有显式禁用或 reset。
+2. reCAPTCHA Enterprise:页面定义 `getCaptchaToken()`,以 action `BOOKING` 最多尝试三次取得非空 token,把它追加为 `bookingForm` 的 `g-recaptcha-response` hidden 字段,再提交表单。
+
+采集时 `#btnAvanti` 为 enabled,与 Turnstile callback 已完成相符,但单个状态快照不能证明 callback 一定刚刚执行,也不能保证 Token 到实际提交时仍有效。
+
+更关键的是,E18 的按钮 handler 在确认后直接调用 `bookingForm.submit()`,而 E19 又发现独立的 `getCaptchaToken()`。在 E19 时这构成进入 `AVANTI` 前的 P0;E20 随后确认已检查范围只出现函数定义、没有调用点,因此将其降为“未引用候选”。E22 最终以成功真实 POST 验证当前路径只有 Turnstile 字段名、没有 reCAPTCHA 字段名。实现不得自行复制 Token、绕过 CAPTCHA 或主动调用未引用函数;遇到人工 challenge 必须停下交给用户。
+
+标签:`[OBSERVED:E19]`。静态函数体、精确比较式、字段写入和 callback 代码为高确信度;真实 OTP 响应、Token 生命周期、`getCaptchaToken()` 调用关系和服务端校验仍未验证。
+
+### 2.13 Hong Kong 预约类型与当前 submit 调用链
+
+HK-6 对预约类型 select、`bookingForm`、`AVANTI` 和全部相关 inline script 上下文进行脱敏只读采集,没有触发事件或网络请求。
+
+#### 单人预约同步链
+
+`select#typeofbookingddl` 有一个 jQuery `change` handler:
+
+```text
+change
+  → ShowCompanions()
+  → aggiornaDettaglioPrenotazione()
+```
+
+`ShowCompanions()` 读取当前选择。单人值为字符串 `1` 时:
+
+```text
+typeofbookingddl = 1
+  → 隐藏同行人数和多人区域
+  → numAccSelected = 0
+  → 显示当前申请人信息
+  → hiddenTipoPrenotazione = DOMPurify.sanitize(1)
+```
+
+E16 的真实 DOM 已证明:
+
+| DOM id | 提交字段 name | 单人期望值 |
+|---|---|---:|
+| `hiddenTipoPrenotazione` | `IdTipoPrenotazione` | 1 |
+| `numAccSelected` | `NumAccompagnatoriSelected` | 0 |
+
+因此单人预约同步不是推断,而是 E16 + E20 的交叉证据。Book 应操作可见 select、触发原生 change 事件,再读取这两个非敏感业务 hidden 值做断言;不应绕过网页脚本直接拼 multipart 字段。
+
+#### 当前已观察 submit 路径
+
+本次事件检查结果:
+
+- `bookingForm`:没有 inline、native 或 direct jQuery submit handler。
+- `btnAvanti`:没有 inline/native click;有且仅观察到一个 direct jQuery click handler。
+- 该 click handler 在校验、`saveDdlValue()` 和用户确认后直接调用 `$('#bookingForm').submit()`。
+- `getCaptchaToken()` 完整函数存在,会生成 reCAPTCHA Enterprise `BOOKING` token、追加 `g-recaptcha-response` 后再次 submit。
+- 但采集到的 inline script 上下文与上述三个关键元素事件中,没有观察到 `getCaptchaToken()` 调用表达式;只观察到它的函数定义。
+
+最小、保守结论是:**当前唯一有证据的活跃路径是 `AVANTI → bookingForm.submit()`;`getCaptchaToken()` 是未引用候选,而不是当前 Book 合同。** 这不等于证明它是永久死代码:外部脚本、document-level delegated listener 或服务端策略仍未被静态采集完全排除。插件不得自行调用或删除它;下一 Gate 通过真实 Network 结果判断服务器实际接受哪条路径。
+
+标签:`[OBSERVED:E20]`。预约类型/同行人数同步和 direct element handler 为高确信度;“全页面不存在任何间接调用”不能由当前证据证明,确信度中。
+
+### 2.14 Hong Kong HK-7 提交前运行时预检
+
+用户在真实 `4937` 页面手工选择单人和旅游后,只读取得:
+
+| 项目 | 运行时值 | 解释 |
+|---|---:|---|
+| 可见预约类型 | 1 | 已选择单人 |
+| `hiddenTipoPrenotazione` | 1 | change handler 已同步 |
+| `numAccSelected` | 0 | 单人同行人数已同步 |
+| 可见旅游目的 | 42 | 已选择 `Turismo` |
+| `hiddenSelezionato_0` | 0 | 尚未点击 `AVANTI`,`saveDdlValue()` 还没运行 |
+| OTP button disabled | false | 当前可发送,但本预检没有点击 |
+| `AVANTI` disabled | false | Turnstile 当前可用;不保证之后不会过期 |
+| Turnstile 字段数量 | 1 | 没有读取 value |
+| reCAPTCHA 字段数量 | 0 | 当前尚未生成 `g-recaptcha-response` |
+
+这组运行时证据揭示两种不同同步时机:
+
+```text
+选择单人
+  → change 时立即同步 1/0
+
+选择 Turismo
+  → 可见值先为 42、hidden 暂为 0
+  → 点击 AVANTI 后执行 saveDdlValue()
+  → form submit 前才同步为 42
+```
+
+因此自动化的正确职责不是在选择旅游后立即要求 hidden=42,更不能提前手工赋值;它应确认可见选择为 42,并让网站原生 `AVANTI` handler 在提交边界执行同步。测试可以通过 handler spy/离线 fixture 验证调用顺序,真实运行不能为了观察中间值而改变网站流程。
+
+标签:`[OBSERVED:E21]`。提交前 DOM 状态为高确信度;click handler 执行后的瞬间状态和真实 POST 仍待 HK-7 后续步骤验证。
+
+### 2.15 Hong Kong HK-7 OTP 与 Calendar 入口真实链路
+
+用户按照一次性副作用预算完成操作,实际顺序为:
+
+```text
+选择单人 + Turismo
+  → 勾选 PrivacyCheck
+  → 点击一次 INVIA NUOVO CODICE
+  → GET GenerateOTP:200 / SENT
+  → 注册邮箱收到 OTP
+  → 用户手工输入 OTP
+  → 点击一次 AVANTI 并确认摘要框
+  → POST /Services/Booking/4937:302
+  → Location: /BookingCalendar?selectedService=Visti%20Nazionali%20e%20Schengen
+  → GET /BookingCalendar?...:200 document
+  → location.pathname = /BookingCalendar
+  → title = Calendar - Prenot@Mi
+  → STOP
+```
+
+Network 与页面证据:
+
+| 阶段 | 次数 | Method | Path | Status | 结果 |
+|---|---:|---|---|---:|---|
+| OTP | 1 | GET | `/BookingCalendar/GenerateOTP?ServiceID=4937` | 200 | Response 类别 `SENT`;邮件送达 |
+| 前置表单 | 1 | POST | `/Services/Booking/4937` | 302 | 重定向至 BookingCalendar |
+| Calendar document | 1 | GET | `/BookingCalendar?selectedService=Visti%20Nazionali%20e%20Schengen` | 200 | 最终文档;title=`Calendar - Prenot@Mi` |
+| 日期点击 | 0 | — | — | — | 未执行 |
+| 时间点击 | 0 | — | — | — | 未执行 |
+| 最终确认 | 0 | — | — | — | 未执行 |
+
+POST 字段检查没有复制任何值,只报告字段名:观察到 `cf-turnstile-response`,没有观察到 `g-recaptcha-response`。结合 E20 的“`getCaptchaToken()` 只有定义、没有调用点”,当前可以把 reCAPTCHA Enterprise 函数从 Book 主路径排除;未来页面如果真实出现该字段或 handler,再按 capability 重新发现,不能永久删除兼容判断。
+
+用户报告页面标题/主标题为:
+
+```text
+Visti Nazionali e Schengen — Selezionare una data e una fascia oraria disponibile
+```
+
+浏览器 Console 随后确认 `location.href` 与 302 Location 一致,`pathname=/BookingCalendar`,Network 中该请求为 GET 200 Document。先前报告的 `/Services/Booking/4937` 是 POST 请求 path,并非最终浏览器 path,证据冲突已消除。
+
+标签:`[OBSERVED:E22]`。OTP、邮件送达、POST/302/Location、Calendar GET 200 Document、最终 URL/title 和停止边界均为高确信度。
+
+### 2.16 Hong Kong HK-8/HK-9 Calendar 零点击 DOM 与 handler 协议
+
+用户关机后恢复浏览器,页面仍可直接显示此前进入的 Calendar。随后执行的采集脚本只读取当前 DOM、Resource Timing 和 inline script,不点击控件、不调用函数、不刷新页面。
+
+#### 页面与 DOM
+
+| 项目 | 已观察结果 | 保守解释 |
+|---|---|---|
+| Path / title | `/BookingCalendar` / `Calendar - Prenot@Mi` | Calendar 状态识别仍成立 |
+| 主标题 | `Visti Nazionali e Schengen`;选择可用日期和时间段 | 页面业务语义是日期/时间选择 |
+| form | 只有 `logoutForm → POST /Account/LogOff` | Calendar 不是通过普通 booking form 提交最终动作 |
+| 当前月份 | `agosto 2026` | 页面当前渲染 2026 年 8 月 |
+| 日期格 | 42 个 `td.day*`,全部 class 含 `disabled` | 当前快照没有取得任何可点击日期格证据 |
+| 今天 | `28/08/2026` 为 `day today disabled` | “今天”标记与可用性是不同维度 |
+| 8 月 31 日日期格 | `day disabled notAvailableDay active` | active 不能覆盖 disabled/notAvailable 语义 |
+| 8 月 31 日日期条目 | `a.input-async-abilitato.selected[data-date="2026-08-31"]` | selected 可能只是默认焦点/当前查看项,不能单独代表可预约 |
+| 8 月 31 日时段容器 | `li.selected[data-date="2026-08-31"]` | selected 同样只证明当前展示该日时段 |
+| 展示时段 | 三个 `div.fascia.notAvailableFascia`:`09:15–10:00 (0)`、`10:05–11:05 (0)`、`11:15–12:40 (0)` | class 已明确证明三者不可用;E35 已确认 `(0)` 来自 `SlotLiberi` |
+| 月份导航 | `Prev` 为 `inactive`;`Next` 存在 | 是否点击会发请求仍未执行 |
+| 最终按钮候选 | `button#btnPrenotaNoOtp`,文字 `PRENOTA`,DOM property `disabled=false` | enabled 不能替代日期/Slot 可用性校验;本次没有点击 |
+
+最关键的反直觉点是:**“selected”不等于“available”。** 同一个 `2026-08-31` 同时出现 selected 条目、`disabled notAvailableDay` 日期格和三个 `notAvailableFascia` 时间段。只看 selected 会制造假阳性;当前可以明确分类为“Calendar 已渲染默认日期,但没有可用 Slot”。
+
+#### 页面自动出现的 XHR 资源
+
+Resource Timing 中已有:
+
+```text
+/BookingCalendar/RetrieveServerInfo
+/BookingCalendar/RetrieveCalendarAvailability
+/BookingCalendar/RetrieveTimeSlots
+```
+
+三者的 `initiatorType` 均为 `xmlhttprequest`。因为本次日期、月份、时间和最终按钮点击都为 0,这些资源是在 Calendar 页面生命周期中自动出现的,不是本次采集脚本触发的业务动作。
+
+边界必须说清楚:Resource Timing 只能证明 path 和资源类型,不能给出 HTTP method、status、request payload 或 response schema。因此尚不能把历史代码中的 POST method 当成当前网站事实,也不能直接用这些接口写实现。
+
+#### Availability 编排函数
+
+当前源码已确认:
+
+```text
+CaricaTimelineOrizzontale(
+  _Mese,
+  _Anno,
+  _Oggi,
+  _Servizio,
+  _GiornoDaSelezionare
+)
+  → Metodo = RetrieveCalendarAvailability
+  → WebMethod 参数:
+       _Servizio   = _Servizio
+       selectedDay = _Oggi
+  → success callback 参数:
+       GiornoDaSelezionare = _Oggi
+  → error callback 参数:{}
+  → EseguiAsync(
+       Metodo,
+       Parametri,
+       CostruisciTimelineOrizzontale,
+       StampaErroreInConsole
+     )
+```
+
+这个函数是“编排层”,把三类参数和两个 callback 交给公共执行器:
+
+| 层 | 当前已知职责 | 当前未知 |
+|---|---|---|
+| `CaricaTimelineOrizzontale` | 选择 availability 方法片段,组织 WebMethod/success/error 三组参数 | 不直接暴露 HTTP method/URL |
+| `EseguiAsync` | 应负责真正发请求并调用 callback `[SOURCE-INFERENCE]` | URL 拼接、method、序列化、response 解包、异常语义 |
+| `CostruisciTimelineOrizzontale` | 应负责用成功响应构造日期 DOM `[SOURCE-INFERENCE]` | response 字段、可用/不可用 class 规则 |
+| `StampaErroreInConsole` | 作为 error callback 传入 | 错误参数与用户可见恢复方式 |
+
+三个形参 `_Mese`、`_Anno`、`_GiornoDaSelezionare` 在当前函数体里没有引用;实际 success 参数反而使用 `_Oggi` 作为 `GiornoDaSelezionare`。这可能是历史签名或通用 API 遗留,但现阶段只记录事实,不“顺手修正”,也不向请求中添加源码未传递的月份/年份字段。
+
+#### Availability HTTP 合同
+
+`EseguiAsync` 把上述编排转换成当前请求:
+
+```http
+POST /BookingCalendar/RetrieveCalendarAvailability
+Content-Type: application/json; charset=utf-8
+Accept/response parsing: JSON
+```
+
+JSON 的结构键为:
+
+```json
+{
+  "_Servizio": "<运行时值,不记录>",
+  "selectedDay": "<来自 _Oggi 的运行时值,不记录>"
+}
+```
+
+调用链可以机械表示为:
+
+```text
+url = urlServizio + Metodo
+    = /BookingCalendar/ + RetrieveCalendarAvailability
+
+request body = JSON.stringify(Parametri[0])
+
+HTTP success
+  → jQuery 把 response 解析为 JSON
+  → CostruisciTimelineOrizzontale(response, Parametri[1])
+
+HTTP error
+  → 丢弃 response/status/body
+  → StampaErroreInConsole()
+```
+
+这里需要区分“网站事实”和“插件应该怎么做”:POST、URL、JSON 键与 success 传递是当前网站事实;丢弃 error 详情是网站客户端的实现缺陷,不应成为插件设计。Italy 插件至少需要保留 HTTP status、响应类别和脱敏错误摘要,并把 401/403、429、5xx、网络超时、JSON schema 变化分别分类;结果不明时不伪装成“无号”。
+
+HK-13 当时只关闭 Availability,不能直接外推另外两个请求。HK-18 后,TimeSlots 复用 `EseguiAsync` 已由 `CaricaTimelineVerticale` 直接证明;现在只有 `RetrieveServerInfo` 的 method/payload 仍不能外推。
+
+#### Availability response 与日期构建合同
+
+success callback 的第一步是:
+
+```text
+JsonGiorniTimelineOrizzontale = $.parseJSON(response)
+```
+
+`EseguiAsync` 已要求 jQuery 按 JSON 处理 response,而 callback 还需要再 parse 一次,因此当前服务端载荷形态是“JSON 响应中的 JSON 字符串”,内层解析后才是日期数组。插件实现不能无条件假定直接数组;应显式验证外层类型,并在未来服务端改为直接数组时通过 capability/schema 分支兼容,而不是盲目 parse 两次。
+
+内层数组元素的当前字段:
+
+| 字段 | 当前用法 | 可确认语义 |
+|---|---|---|
+| `DateLibere` | 第一项用于比较/保存;每项截取前 10 字符并格式化 | 日期字符串;字面含义为“空闲日期” |
+| `SlotRimanenti` | 每项写入 `GiorniConPrenotazioni` 的 `date@slots` | 日期/时段 class 哨兵;`< 0` 为负向,非负值进入候选层;E43 已证明与 `SlotLiberi>0` 同时出现的 `0` 是正向 |
+
+数组级行为:
+
+```text
+数组为空
+  → GiorniDisponibili = 0
+
+数组非空
+  → primaDataDisponibile = 第一项 DateLibere
+  → 与 DataDisponibilita 比较
+     相同             → GiorniDisponibili = 2
+     第一日期更晚     → GiorniDisponibili = 1
+     第一日期更早     → GiorniDisponibili = 0
+     没有旧日期       → GiorniDisponibili = 2
+                         保存第一日期
+  → 清空并重建时间线
+  → 每个数组元素:
+       DateLibere 前 10 字符 → 格式化日期
+       记录 date@SlotRimanenti
+       CreaGiorno(...)
+       CreaEventiGiorno(...)
+  → InizializzaTimelineOrizzontale(GiornoDaSelezionare)
+```
+
+`GiorniDisponibili=0/1/2` 不能解释为“剩余名额数量”:源码用它表达第一可用日期相对旧 `DataDisponibilita` 的比较结果。真正的容量候选是每项 `SlotRimanenti`。
+
+同样不能使用 `array.length > 0` 直接判定 Available。函数对每个元素都创建 DOM,没有在此处过滤容量。E43 已确认日期层正向规则至少是 `SlotLiberi>0 AND SlotRimanenti>=0`;随后仍需读取同日 TimeSlots,并用 response 与 DOM 的正向合同交叉验证。
+
+#### Calendar 初始化与自动选日合同
+
+`CostruisciTimelineOrizzontale` 构建完日期 DOM 后调用 `InizializzaTimelineOrizzontale(GiornoDaSelezionare)`。当前完整函数的顺序是:
+
+```text
+存在 .cd-horizontal-timeline
+  → 初始化 horizontal timeline(eventsMinDistance=120)
+
+解绑 #datetimepicker 的 dp.update / dp.change
+  → InizializzaCalendario()
+  → DisabilitaGiorniSenzaPrenotazioni()
+  → AbilitaInputAsincroni()
+  → ShowLoader(false)
+
+格式化 GiornoDaSelezionare 为 YYYY-MM-DD
+  → 查找 .events a[data-date="目标日期"]
+  → 找不到:回退 .events ol li a:first-child
+  → 找到任一候选:由脚本调用该链接的 click()
+```
+
+这段代码给出四个重要结论:
+
+1. `off('dp.update')`/`off('dp.change')` 是重复初始化保护,避免同一个 calendar handler 被反复绑定;插件等待页面稳定时不能把同一轮重复事件误判成多个独立号源。
+2. 用户报告“日期点击次数为 0”与 `RetrieveTimeSlots` 出现并不冲突。这里的 `.click()` 是页面 JavaScript 产生的程序化点击,不是用户手工点击。
+3. 目标日期不存在时,网站不会失败,而会静默选第一个时间线日期。这是 UI 便利策略,不是 Book 可以接受的业务策略。插件必须在点击/异步加载后读取真实 selected 日期,并确认它仍满足用户日期偏好;否则以 `SelectedDateMismatch` 一类明确错误停止。
+4. 本函数本身没有出现 `RetrieveTimeSlots`,所以目前只能证明“程序化 click 是触发链的上游”。HK-17 又证明 `AbilitaInputAsincroni` 只切换 CSS class,并不注册 handler;具体 click handler、请求 method/payload 和 Slot DOM 构建仍需从其他源码定位,不能把因果链的最后一段补猜出来。
+
+`InizializzaCalendario → DisabilitaGiorniSenzaPrenotazioni → AbilitaInputAsincroni` 的调用顺序也很关键:日期 class 先被计算,随后只是把非 selected 的 `data-async=true` 元素切换成 enabled CSS class。HK-16 已关闭“哪些日期可以点”的规则,HK-17 已关闭 class 切换;真正的 click→TimeSlots handler 仍在别处。
+
+#### 日期禁用与可点击 class 合同
+
+`DisabilitaGiorniSenzaPrenotazioni()` 的当前算法是:
+
+```text
+读取 #datetimepicker 下所有 .day
+  → 每一天先添加 disabled
+  → 格式化该元素的 data-day
+  → 遍历 GiorniConPrenotazioni 中每个 "date@slot"
+     → 格式化 date 并比较
+     → 日期相同:
+        slot >= 0
+          → 添加 availableDay
+          → 移除 disabled
+        否则
+          → 添加 notAvailableDay
+```
+
+这里的 `slot >= 0` 是 JavaScript 带隐式数值转换的比较,而不是“严格正数”。典型结果为:
+
+| `slot` 候选 | 当前网页分支 | 能证明什么 |
+|---|---|---|
+| 当前日期没有任何匹配记录 | 不进入 slot 分支,保持 `disabled` | 该月日期格存在,但 Availability 没有提供对应记录 |
+| 正数或可转为正数的字符串 | `availableDay`,移除 `disabled` | 该日期可进入下一层 |
+| 数字 `0` 或字符串 `"0"` | 同样是 `availableDay`,移除 `disabled` | **不能证明存在剩余时段** |
+| 负数或可转为负数的字符串 | `notAvailableDay`,保留 `disabled` | 当前日期不可进入 |
+| 缺失、非数字字符串等导致比较为 false 的值 | `notAvailableDay`,保留 `disabled` | schema/数据异常与业务不可用被网页混在同一分支 |
+
+因此有号判据必须分两层:
+
+```text
+日期层:availableDay 且不含 disabled/notAvailableDay
+  只表示允许查询这一天
+
+时段层:至少一个由正向样本证明可用、且不含 notAvailableFascia/disabled 的 Slot
+  才能表示存在可预约机会
+```
+
+这也解释了为什么不能把 `SlotRimanenti` 名字或 `availableDay` class 当作最终事实:网页自己允许 `0` 进入日期层。E35 已确认时段文字的 `(0)` 来自另一个字段 `SlotLiberi`;它与控制 class 的 `SlotRimanenti` 不是同一个字段。
+
+源码还有三个必须由插件补强、但当前不能“顺手修改网站”的边界:
+
+1. 内层匹配没有 `break`,没有拒绝同一天的重复记录。若同一天出现相互冲突的 slot,DOM 可能同时带 `availableDay` 和 `notAvailableDay`;插件应拒绝重复/冲突数据。
+2. 函数每轮只统一添加 `disabled`,没有先移除旧的 `availableDay/notAvailableDay`。上游是否总会重建日期节点尚未证明;插件看到正负 class 并存时必须停止。
+3. 网页依赖隐式数值转换。插件解析 response 时应要求 slot 是可验证的有限数值;schema 异常应分类为结构变化,而不是悄悄当作“无号”。
+
+#### 异步控件 class 切换合同
+
+`AbilitaInputAsincroni()` 的完整行为只有:
+
+```text
+选择 [data-async="true"]:not(.selected)
+  → 移除 input-async-disabilitato
+  → 添加 input-async-abilitato
+```
+
+它没有执行以下任何动作:
+
+- 没有 `addEventListener`、jQuery `.on()` 或 `.click(handler)`。
+- 没有主动调用元素的 `.click()`。
+- 没有 AJAX、fetch 或 endpoint 字符串。
+- 没有读取日期、Slot 数量或用户偏好。
+- 没有设置原生 `disabled` 属性或 `aria-disabled`。
+
+所以函数名里的“Abilita/启用”具体指 CSS class 状态,不等于业务可用性,也不等于浏览器原生禁用状态。真正的交互很可能由别处预先注册的 delegated handler 根据 `input-async-abilitato`、`data-async` 或其他选择器接管,但在看到源码前只能标记为候选。
+
+`:not(.selected)` 还有一个生命周期风险:当前 selected 元素被刻意排除,不会在本函数中移除 disabled class 或添加 enabled class。它可能已经由其他函数正确设置,也可能保留上一轮状态;插件不能只看一个 class,必须在异步稳定后同时核对实际日期、正负日期 class 和 Slot 结果。
+
+#### TimeSlots HTTP 编排合同
+
+全局搜索 `RetrieveTimeSlots` 命中 `CaricaTimelineVerticale(_Giorno, _ContenutiEventi)`。它构造的三层参数与 Availability 使用同一约定:
+
+```text
+Parametri[0]:发送给 WebMethod
+  selectedDay = _Giorno
+  idService   = $('#idServizio').val()
+
+Parametri[1]:只传给 success callback
+  _ContenutiEventi
+
+Parametri[2]:error callback 参数
+  空对象
+```
+
+结合已经确认的 `EseguiAsync`,当前静态 HTTP 合同是:
+
+```text
+POST /BookingCalendar/RetrieveTimeSlots
+Content-Type: application/json; charset=utf-8
+Body:
+  selectedDay
+  idService
+
+HTTP success
+  → CostruisciSchedaFasce(response, _ContenutiEventi)
+
+HTTP error
+  → StampaErroreInConsole()
+    网站客户端仍丢弃 response/status/body
+```
+
+`_ContenutiEventi` 不是服务器请求字段。它是调用方传入的前端渲染上下文,并通过 `Parametri[1]` 交给 success callback。插件如果把它加入 JSON body,就是把 callback 参数误当协议字段。
+
+还有两个名称相近但不能混用的 ID:
+
+| 标识 | 来源 | 当前已知职责 |
+|---|---|---|
+| 配置 `service_id=4937` | routing/Sede 配置和 `/Services/Booking/4937` | 进入 Hong Kong 签证 Booking Form |
+| TimeSlots `idService` | Calendar 页 `$('#idServizio').val()` | 作为 TimeSlots WebMethod 参数;准确业务语义尚未关闭 |
+
+源码明确从 Calendar DOM 重新读取 `#idServizio`,所以长期实现必须沿当前用户 Session 获取并验证它,不能把配置入口 ID 直接代入。名称相似不构成相等证据。
+
+函数头部的 `_Giorno = _Giorno` 没有改变任何值,是当前页面的无效果语句。`_idService` 赋值在函数内没有 `let/var/const`;若外层也没有声明,就会写入全局。插件不复制这类隐式共享状态,而使用局部、不可变的 request DTO。
+
+本函数关闭了 TimeSlots method/path/request keys 和 success callback 名;E34/E35 随后关闭了内层数组、核心 item 字段和普通/负向 class 生成条件。谁调用 `CaricaTimelineVerticale` 仍未证明。
+
+#### TimeSlots response 与容器构建合同
+
+`CostruisciSchedaFasce(JsonFasceGiorno, Parametri)` 首先执行:
+
+```text
+JsonFasceGiorno = $.parseJSON(JsonFasceGiorno)
+```
+
+因此 TimeSlots 和 Availability 使用相同的双层载荷形态:`EseguiAsync` 先按 JSON 接收,callback 再把外层 JSON 字符串解析为内层数组。插件必须同时验证外层类型、内层是否为数组和每个 item 的 schema;parse 异常不能伪装成“无号”。
+
+当前 callback 的完整流程:
+
+```text
+selectedContent = Parametri.selectedContent
+unicaFascia = (数组长度 == 1)
+
+遍历每个 Slot item
+  → 读取 selectedContent 当前 HTML
+  → CreaFasce(item, unicaFascia) 返回新 HTML
+  → 把旧 HTML + 新 HTML 整体写回 selectedContent
+
+把 selectedContent 写回 Parametri
+  → CostruisciTimelineVerticale(Parametri)
+```
+
+`unicaFascia` 只由数组长度决定,并被传给 `CreaFasce`。它不能解释为“唯一可用时段”:长度为 1 的 item 仍可能代表容量为零或不可用;是否可预约完全由 item 字段和 `CreaFasce` 的 class/HTML 规则决定。
+
+数组边界同样需要 fail-closed:
+
+| 内层数组 | 当前网页行为 | 插件不能推断 |
+|---|---|---|
+| 空数组 | 不调用 `CreaFasce`,仍调用 `CostruisciTimelineVerticale` | 不能仅凭 timeline 初始化成功说有号 |
+| 1 项 | `unicaFascia=true`,创建一个 Slot HTML | 不能说该 Slot 可预约 |
+| 多项 | 每项都创建 Slot HTML | 不能用 `length>0` 或数量判断可预约 |
+
+当前 DOM 已证明 `.notAvailableFascia` 也会被渲染成时段项,所以“数组非空”和“页面出现时间文字”都不是正向信号。
+
+实现层还有两个值得记录但不在 Discovery 阶段修改的网站特征:每轮循环都以 `html()` 读取完整容器再整体写回,可能重建已有子节点;而返回 HTML 是否安全、是否包含负向 class,全由 `CreaFasce` 决定。Italy 插件应解析经过页面脚本稳定后的结构化 DOM,不拼接或信任任意 HTML 字符串。
+
+#### Slot item、显示数量与 class 生成合同
+
+`CreaFasce(fascia, unicaFascia)` 读取的当前 item 字段为:
+
+| 字段 | 当前用途 | 已证明范围 |
+|---|---|---|
+| `SlotRimanenti` | `< 0` 时生成负向 class | E43 正向为 `0`、负向为 `-1`;不能用 `> 0` 过滤 |
+| `SlotLiberi` | 替换模板中的 `@PostiDiponibili@` | E43 正向显示 `(1)`、负向显示 `(0)`;当前直接容量字段 |
+| `OrarioInizioFascia.Hours/Minutes` | moment 格式化为 `HH:mm` | 时段开始时间 |
+| `OrarioFineFascia.Hours/Minutes` | moment 格式化为 `HH:mm` | 时段结束时间 |
+| `IDCalendarioServizioGiornaliero` | 替换模板同名占位符 | E43 正负三个 Slot 各有一个 hidden value;只记录数字/长度 8,不记录具体值 |
+
+class 的覆盖顺序是:
+
+```text
+默认 classeDaAssegnare = ""
+
+如果 unicaFascia
+  → classeDaAssegnare = act
+
+如果 SlotRimanenti < 0
+  → classeDaAssegnare = notAvailableFascia
+  → classeDot = dotRed
+  → 覆盖此前可能设置的 act
+```
+
+因此可以机械区分:
+
+| 条件 | 最终 class 候选 | 能否直接预约 |
+|---|---|---|
+| 唯一 item 且 `SlotRimanenti < 0` | `notAvailableFascia`,不会保留 `act` | 否 |
+| 唯一 item 且 `SlotRimanenti >= 0` | `act` | 还需 `SlotLiberi>0` 和完整 precommit;E43 已证明 `SlotLiberi=1 / SlotRimanenti=0` 是正向组合 |
+| 多 item 且 `SlotRimanenti < 0` | `notAvailableFascia` | 否 |
+| 多 item 且 `SlotRimanenti >= 0` | 无附加状态 class | E43 中 `SlotLiberi>0` 且无负向 DOM 的 item 是正向候选 |
+
+`(0)` 的来源已经关闭:模板占位符 `@PostiDiponibili@` 使用
+`fascia.SlotLiberi`。E43 进一步取得正负对照:`SlotLiberi=0 / SlotRimanenti=-1`
+对应负向 DOM,`SlotLiberi=1 / SlotRimanenti=0`
+对应普通 `fascia + (1)`。两个字段都必须解析,不能把括号数字称作
+`SlotRimanenti`,也不能把 `SlotRimanenti=0` 判成无号。
+
+长期 Book 的候选判据至少需要:
+
+1. DOM 不含 `notAvailableFascia`、`disabled` 或冲突 class。
+2. item 的 `SlotRimanenti`、`SlotLiberi` 都能解析为有限整数,且必须满足
+   `SlotLiberi>0`、`SlotRimanenti>=0`。
+3. 起止时间格式合法,daily calendar ID 存在且来自当前 item。
+4. 点击/自动 `act` 后重新核对 selected 日期、时间、两个 Slot 字段和用户偏好。
+5. 与 E43 正向 allowlist 对照:`SlotRimanenti=0` 只有在
+   `SlotLiberi>0` 且 DOM 无负向标志时才是正向;`SlotLiberi=0` 一律不提交。
+
+源码直接把 response 字段替换进 HTML template,没有在当前函数做 escaping。插件不复刻字符串模板,而读取网站完成渲染后的 DOM并做结构化校验。
+
+HK-21 的 Sources 全局搜索当时没有找到 `TemplateFasce`。这不是“模板不存在”的证据;HK-22 随后以渲染 DOM 绕过符号定位,HK-23 在恢复现场后又取得模板原文。E36 因此只保留为带时间顺序的调查记录,当前合同以更新的 E38 为准。
+
+#### TemplateFasce 原文合同
+
+恢复后取得的模板等价结构为:
+
+```html
+<div class="fascia @attivo@">
+  <div>
+    <div class="dot @dotNonAttivo@"></div>
+    <span>@OraInizio@ - @OraFine@</span>
+    <br />
+    <span>(@PostiDiponibili@)</span>
+    <input
+      type="hidden"
+      id="idHiddenFasciaServizio"
+      value="@IDCalendarioServizioGiornaliero@"
+    />
+  </div>
+</div>
+```
+
+它把 E34–E37 串成一条完整生成链:
+
+```text
+TimeSlots item
+  → CreaFasce(item)
+  → 替换 class / 时间 / SlotLiberi / daily calendar ID
+  → CostruisciSchedaFasce 对每个 item 追加同一模板
+  → 每个 .fascia 内都生成 #idHiddenFasciaServizio
+```
+
+这是目标网站自身的重复 id 设计:`id` 按 HTML 语义本应在文档内唯一,但这里随着 Slot 数量重复。框架不能“忠实复制”这个脆弱点,而要在不改变网站 DOM 的前提下增加作用域约束:先找到唯一 `.fascia.act`,拒绝 `notAvailableFascia`,再只在该 Slot 子树内读取 `input[type=hidden][id="idHiddenFasciaServizio"]`。全局 `document.getElementById()`、`$('#idHiddenFasciaServizio')` 或未限定作用域的 selector 都不安全。
+
+#### 已渲染 Slot DOM 合同
+
+HK-22 的第一条负向 Slot 结构为:
+
+```text
+li.selected.enter-right
+  ├─ div.fascia.notAvailableFascia
+  │    └─ div
+  │         ├─ div.dot.dotRed
+  │         ├─ span                 # HH:mm - HH:mm
+  │         ├─ br
+  │         ├─ span                 # (SlotLiberi)
+  │         └─ input[type=hidden]
+  │              id=idHiddenFasciaServizio
+  │              value=<numeric-redacted length=8>
+  ├─ div.fascia.notAvailableFascia
+  └─ div.fascia.notAvailableFascia
+```
+
+这关闭了四条重要映射:
+
+1. `notAvailableFascia` 位于 Slot 根节点,`dotRed` 是内部冗余负向视觉信号。
+2. 时间和数量分别位于两个 `span`,中间有 `br`;根节点自身没有 direct text,但 `innerText` 会合并后代文字。
+3. 第一条 Slot 的 daily calendar ID 位于隐藏 input 的 `value`;真实值未记录,也不需要写进配置。
+4. `li.selected` 是三个 Slot 的共同父级,不是被用户选中的单个 Slot;最终选择状态仍应以 `.fascia.act` 为准,并同时拒绝负向 class。
+
+最终 handler 已知使用 `.fascia.act[0].innerText` 生成 `selectedHour`。结合当前 DOM,这个原生字符串可能同时包含时间、换行和括号数量;长期插件不应自行拼一个“看起来等价”的请求字符串,而应优先走网站原生选择/提交链,并在最终动作前验证 active Slot 的独立时间 span 与隐藏 ID。
+
+E38 已证明模板对每个 Slot 固定写入同一个 `idHiddenFasciaServizio`;E34 又证明模板按 item 重复追加。因此多个 Slot 会生成重复 id。虽然本轮没有读取三个真实 value,但这不影响 selector 风险结论:插件必须先锁定唯一且非负的 `.fascia.act`,再在其子树内读取一个 hidden input,遇到 0 个或多个立即停止。
+
+HK-25 已通过 `document.scripts` 取得最终 handler 的完整取值表达式,Sources 搜索缺口关闭。
+
+#### 最终 handler 序列化合同
+
+当前原生 handler 的核心逻辑是:
+
+```javascript
+if ($('.fascia.act').length == 0) {
+  return false;
+}
+
+let hiddenFieldServizio = $('.fascia.act input')[0].value;
+let oraFasce = $('.fascia.act')[0].innerText;
+let dataPren = $('.selected')[0].dataset.date;
+
+POST /BookingCalendar/InsertNewBooking
+  idCalendarioGiornaliero = hiddenFieldServizio
+  selectedDay             = dataPren
+  selectedHour            = oraFasce
+```
+
+逐行说人话:
+
+1. 网站只防“一个 active Slot 都没有”,不防多个 active Slot,也不防 active Slot 同时带 `notAvailableFascia`。
+2. daily ID 不是用重复的 document id 查找,而是从所有 active Slot 后代 input 中拿第一个 value;正常单 active/单 input 时能与该 Slot 对齐。
+3. selector 没有限定 `type=hidden` 或 `idHiddenFasciaServizio`。模板当前只有一个 input,所以今天成立;模板增加其他 input 后会静默取错。
+4. `selectedHour` 是整个 active Slot 的 `innerText`,会保留网站当前的时间/换行/括号数量格式;插件不应手工重建。
+5. `selectedDay` 来自整个 document 中第一个 `.selected`,依赖 DOM 顺序。页面已经观察到日期 link 和 events-content `li` 都可能带 selected,因此这是一个必须在提交前验证的脆弱点。
+
+HK-26 把当前顺序具体化:原生 selector 现在解析到 `.events a.selected[data-date]`,第二个才是 `.events-content li.selected[data-date]`。HK-27 又证明两个 selected 日期值相等。这证明当前稳定负向页面没有发生“第一个 selected 无日期”或“两个表示层日期不同步”的错误,但不能把当前数量和顺序写成长期保证。
+
+长期 Book 在触发原生 `#btnPrenotaNoOtp` 前必须机械断言:
+
+```text
+active Slot 数量 == 1
+active Slot 不含 notAvailableFascia/disabled/冲突 class
+active Slot 内目标 hidden input 数量 == 1
+hidden value 为当前 Slot 的合法非空 daily ID
+document 第一个 .selected 确实带 data-date
+document 第一个 .selected 是 .events 内的日期 link
+所有带 data-date 的 selected 元素日期值完全一致
+该日期等于插件刚刚选择且符合用户偏好的日期
+active Slot 的独立时间 span 与用户选择一致
+```
+
+任一条件失败都属于页面结构/状态冲突,必须停止,不能自行调用 AJAX。HK-27
+验证了负向稳定页的 selected 日期角色和一致性;E43 又在正向日期
+`2026-10-09` 验证 timeline/content 日期一致,并取得一个真实正向 Slot。
+下一份证据是安全选择该正向 Slot 后的唯一 `act`/后代 ID 一致性;仍禁止最终 POST。
+
+#### 静态最终确认线索
+
+当前 inline script 明确包含:
+
+```text
+POST /BookingCalendar/InsertNewBooking
+  idCalendarioGiornaliero = hiddenFieldServizio
+  selectedDay             = dataPren
+  selectedHour            = oraFasce
+  response type           = json
+```
+
+脚本从 `.fascia.act` 的文字取得 `selectedHour`,从 `$('.selected')[0].dataset.date` 取得 `selectedDay`。后一个选择器过宽:当前 DOM 同时有多个 `selected` 元素,插件实现不能盲抄,应使用更具体的日期选择器并交叉校验日期格和 active Slot。
+
+#### Slot 与最终按钮的 delegated handler
+
+E24 解释了为什么在具体元素上没有读到 direct handler:页面使用的是 document-level 事件委托。
+
+```text
+click 任意 .fascia
+  → 移除所有 .fascia.act
+  → 给当前元素添加 act
+
+click #btnPrenotaNoOtp
+  ├─ 没有 .fascia.act
+  │    → 弹出“尚未选择时间段”并停止
+  └─ 存在 .fascia.act
+       → selectedHour = 第一个 .fascia.act 的 innerText
+       → selectedDay  = 第一个 .selected 的 data-date
+       → POST InsertNewBooking
+```
+
+同一源码中还保留一个被完整注释的旧 `#btnPrenota → GeneraOTP(true)` block;它不是当前可执行 handler。结合 HK-7 已在前置 Booking Form 完成 OTP,当前有证据的活跃链是 `btnPrenotaNoOtp → InsertNewBooking`,Calendar 阶段不应再次发送 OTP。这个结论限定于当前页面已观察 handler;若未来按钮或外部 listener 改变,需要重新 capability discovery。
+
+危险点是 `.fascia` handler 本身没有检查 `notAvailableFascia`。当前三个不可用时段理论上也会在脚本事件层获得 `act`;CSS 是否阻止真实指针点击尚未验证,但自动化调用 click 时不能依赖 CSS。插件合同必须比网站 handler 更严格:
+
+1. 点击前拒绝含 `notAvailableFascia`、`disabled` 或未来负向 class 的元素。
+2. 只从正向样本确认过的可用 Slot 集合中选择。
+3. 点击后要求恰好一个 `.fascia.act`,且它仍不含任何负向 class、文字与目标时间一致。
+4. 日期必须用具体的 selected 日期元素交叉检查,不能盲抄网站宽泛的 `$('.selected')[0]`。
+
+最终 JSON callback 当前已确认两个字段:
+
+| response 字段 | 静态行为 | 当前边界 |
+|---|---|---|
+| `errorMessage` | trim 后为空视为无业务错误;非空则显示错误 modal | 具体错误类别未观察 |
+| `url` | 无错误时直接跳转;有错误时用户确认 modal 后也跳转 | 成功/失败 URL 形态和预约编号未观察 |
+
+`error` callback 在本次输出中被截断,不能补猜网络失败后的恢复行为。`InsertNewBooking` 很可能是真正产生预约的最终命令;Discovery 阶段禁止执行,也不能为“验证接口”而试发一次。
+
+标签:`[OBSERVED:E23,E24,E27,E28,E29,E30,E31,E32,E33,E34,E35,E36,E37,E38,E39,E40,E41,E42]`。本节保留 8 月默认窗口的历史负向样本和静态协议;它不能再被解释为“整个 Hong Kong Calendar 无号”。当前正向数量和 DOM 合同以更新的 E43 和第 2.17 节为准。
+
+### 2.17 Hong Kong HK-28/E43 正向日期与 Slot
+
+用户在同一个已认证 Calendar Session 中向后浏览到 2026 年 10 月。这个动作纠正了
+HK-8 的范围错误:8 月默认窗口没有可选 Slot,但 10 月确实存在正向日期和时段。
+
+`RetrieveCalendarAvailability` 的 response 仍是外层 JSON 字符串、内层数组。本次
+内层数组有 22 个工作日条目;源日期格式为 `DD/MM/YYYY 00:00:00`,下表统一写成
+`YYYY-MM-DD`:
+
+| 日期 | SlotLiberi | SlotRimanenti | 分类 |
+|---|---:|---:|---|
+| 2026-10-01 | 0 | -1 | 负向 |
+| 2026-10-02 | 0 | -1 | 负向 |
+| 2026-10-05 | 0 | -1 | 负向 |
+| 2026-10-06 | 0 | -1 | 负向 |
+| 2026-10-07 | 0 | -1 | 负向 |
+| 2026-10-08 | 0 | -1 | 负向 |
+| 2026-10-09 | 1 | 0 | 正向 |
+| 2026-10-12 | 8 | 7 | 正向 |
+| 2026-10-13 | 4 | 3 | 正向 |
+| 2026-10-14 | 8 | 7 | 正向 |
+| 2026-10-15 | 10 | 9 | 正向 |
+| 2026-10-16 | 8 | 7 | 正向 |
+| 2026-10-19 | 9 | 8 | 正向 |
+| 2026-10-20 | 9 | 8 | 正向 |
+| 2026-10-21 | 3 | 2 | 正向 |
+| 2026-10-22 | 10 | 9 | 正向 |
+| 2026-10-23 | 10 | 9 | 正向 |
+| 2026-10-26 | 10 | 9 | 正向 |
+| 2026-10-27 | 10 | 9 | 正向 |
+| 2026-10-28 | 10 | 9 | 正向 |
+| 2026-10-29 | 10 | 9 | 正向 |
+| 2026-10-30 | 10 | 9 | 正向 |
+
+因此当前页面版本的日期 truth table 为:
+
+| response 组合 | 当前页面含义 | Query 合同 |
+|---|---|---|
+| `SlotLiberi=0` 且 `SlotRimanenti<0` | 无号 | 不发信号 |
+| `SlotLiberi>0` 且 `SlotRimanenti>=0` | 有真实剩余量 | 进入 TimeSlots 交叉验证 |
+| 其他组合、缺字段、非有限整数 | 未验证/冲突 | fail-closed |
+
+同一 `2026-10-09` 的 `RetrieveTimeSlots` 返回 3 项:
+
+| 时间 | SlotLiberi | SlotRimanenti | DOM | 结论 |
+|---|---:|---:|---|---|
+| 09:15–10:00 | 0 | -1 | `notAvailableFascia`、`dotRed`、`(0)` | 不可用 |
+| 10:05–11:05 | 1 | 0 | 普通 `fascia`、无红点、`(1)` | 正向 Slot |
+| 11:15–12:40 | 0 | -1 | `notAvailableFascia`、`dotRed`、`(0)` | 不可用 |
+
+正向 DOM 采集同时确认:
+
+- timeline selected 恰好 1、content selected 恰好 1;
+- 两者 `data-date` 都是 `2026-10-09`;
+- 正向 Slot 内 hidden input 恰好 1;
+- hidden value 只记录“存在、数字、长度 8”,没有记录具体 daily ID;
+- 正向 Slot 尚未点击,所以 `act=false`;
+- `#btnPrenotaNoOtp` 虽然 enabled,但 enabled 不能代替 Slot 选择与 precommit;
+- Network 过滤 `InsertNewBooking` 的请求数为 0。
+
+E43 证明 `SlotRimanenti=0` 可以是正向状态,不能使用 `SlotRimanenti>0` 过滤,否则会
+漏掉真实的最后一个名额。当前最小正向判据是:
+
+~~~text
+SlotLiberi > 0
+AND SlotRimanenti >= 0
+AND DOM 不含 notAvailableFascia
+AND DOM 不含 dotRed
+AND 当前 Slot 内恰好一个合法 hidden daily ID
+AND timeline/content selected 日期一致
+~~~
+
+本批日期和时段样本都满足 `SlotRimanenti = SlotLiberi - 1`。这是一条高确信度的
+当前观察关系,不是跨 Sede 的配置常量;实现仍读取两个字段并拒绝矛盾组合。
+
+E43 没有关闭的部分只有:点击正向 Slot 后 `.fascia.act` 的唯一性与后代 ID
+一致性、最终 response、`/Reservation` 对账和幂等/恢复。下一 Gate 可以安全点击一次
+正向 Slot 并停在最终按钮前,但仍不得点击 `btnPrenotaNoOtp`。
+
+## 3. 当前目标服务映射
+
+当前有两个不同性质的真实样本:Dublin 提供稳定无号分支,Hong Kong 提供
+Booking Form、正向日期和正向 Slot。地区只通过配置映射,不应进入插件控制流。
+
+### 3.1 Dublin 无号样本
+
+```yaml
+slot.dub.it.tourist:
+  office: "AMBASCIATA D'ITALIA A DUBLINO, IRLANDA"
+  category: "VISTI"
+  service: "Visti"
+  description: "Visti Schengen e Nazionali"
+  service_id: 1321
+  path: "/Services/Booking/1321"
+```
+
+判断依据:
+
+- `1322` 明确是欧盟家庭成员签证。
+- `1323` 明确是商务签证。
+- `1321` 是当前列表中唯一的通用 Schengen 和国家签证入口。
+
+Dublin 仍然不能确认:
+
+- 页面没有直接出现 `Tourism`,所以 `slot.dub.it.tourist → 1321` 仍是候选映射。
+- `Tourism` 是否在进入预约表单后作为 Reason 选项出现。
+- 数字 ID 是否会随机构配置调整而变化。
+- `1321` 的链接是固定入口,还是只在某些开放状态出现。
+
+结论标签:`[OBSERVED:E4]` 服务行和 path;`[SOURCE-INFERENCE]` routing key 到该服务的业务映射。确信度:中。
+
+### 3.2 Hong Kong 正向样本
+
+```yaml
+slot.hkg.it.tourist:
+  office: "CONSOLATO GENERALE D'ITALIA A HONG KONG, REPUBBLICA POPOLARE CINESE"
+  category: "VISTI"
+  service: "Visti"
+  description: "Visti Nazionali e Schengen"
+  service_id: 4937
+  path: "/Services/Booking/4937"
+  booking_type:
+    text: "Prenotazione Singola"
+    value: 1
+  purpose:
+    text: "Turismo"
+    value: 42
+```
+
+证据链不是仅凭显示文本推断:
+
+1. `/Services` 中 `4937` 是唯一通用国家/申根签证入口 `[OBSERVED:E14]`。
+2. 单次 `GET /Services/Booking/4937` 返回 `200` Booking Form `[OBSERVED:E15]`。
+3. 同一表单的真实下拉选项包含且仅包含一个精确 `Turismo=42`,预约类型当前只有 `Prenotazione Singola=1` `[OBSERVED:E16]`。
+4. 网站 handler 会把单人 `1` 和同行人数 `0` 同步到具名 hidden 字段,把旅游 `42` 同步到附加数据 hidden 字段 `[OBSERVED:E19,E20]`。
+
+因此 Hong Kong 的“通用服务入口 → 单人 → 旅游”业务映射为高确信度。仍需避免两个过度外推:
+
+- `4937` 是 Hong Kong 当前服务 ID,不是全地区 Italy 常量。
+- `42` 是当前页面真实值;其他 Sede 必须通过相同 DOM 合同验证,不能只依赖数字。
+
+`slot.hkg.it.tourist` 是遵循现有 routing key 规则的配置候选,不是网站返回字段;生产启用前仍需与队列命名和账号池配置核对。
+
+## 4. 网站状态机
+
+```text
+Public Landing /
+  [OBSERVED]
+      │ 点击 #pingid-button
+      ▼
+IAM / PingID OIDC Login
+  [OBSERVED:/signin/;callback_1 + callback_2;提交一次]
+      │ 成功回到站点;callback 文档链未从 Network 取到
+      ▼
+Authenticated Dashboard /UserArea
+  [OBSERVED:.app-menu + /Services 链接]
+      │ 普通 Prenota 导航
+      ▼
+Services /Services
+  [OBSERVED:上海、Dublin、Hong Kong]
+      │ 按 routing key 解析当前 Sede 的 service_id
+      ▼
+Service Entry Gate
+  [OBSERVED:Dublin GET 1321;Hong Kong GET 4937]
+      ├─ Dublin 无号:302 → /Services → #WNotAvailable 非空
+      │  [OBSERVED:E7]
+      │
+      └─ Hong Kong 接受进入:200 → Booking Form
+         [OBSERVED:E15,E16]
+            │ 单人=1;Turismo=42;Notes 可选
+            │ Privacy required;Turnstile hidden
+            ▼
+         Send OTP (#otp-send)
+         [OBSERVED:真实 GET GenerateOTP 1 次]
+            │ HTTP 200 + raw responseText == "\"SENT\""
+            │ 注册邮箱收到 OTP;成功分支启动 120 秒 UI timer
+            │ OTP 有效期和服务端限流仍待验证
+            ▼
+         AVANTI (#btnAvanti)
+         [OBSERVED:真实点击 1 次;Turnstile;saveDdlValue → confirm → submit]
+            │ 单人 1 → IdTipoPrenotazione;同行人数 0
+            │ Turismo visible=42;pre-click hidden=0
+            │ click 内 saveDdlValue 后才写 _idSelezionato=42
+            │ POST 只观察到 cf-turnstile-response 字段名
+            │ 没有 g-recaptcha-response;POST /Services/Booking/4937 → 302
+            │ 是否创建草稿/占位仍待验证
+            ▼
+         Calendar
+         [OBSERVED:GET /BookingCalendar?... → 200 Document]
+            │ final pathname=/BookingCalendar
+            │ title=Calendar - Prenot@Mi
+            │ 页面生命周期自动出现三个 XHR path:
+            │ RetrieveServerInfo
+            │ RetrieveCalendarAvailability
+            │ RetrieveTimeSlots
+            │ Availability response 构建时间线后执行初始化:
+            │ 所有日期先 disabled;匹配 date@slot 后:
+            │ slot >= 0 → availableDay/可进入(0 也成立)
+            │ 比较不成立 → notAvailableDay/保留 disabled
+            │ 然后切换 data-async 控件 CSS class → 程序化 click 目标日期
+            │ 目标日期不存在时会静默回退首个日期
+            │ TimeSlots 请求由 CaricaTimelineVerticale 编排:
+            │ POST RetrieveTimeSlots JSON {selectedDay, idService}
+            │ idService 来自 Calendar DOM #idServizio,不是配置 ID 的已证同义词
+            │ response 再 parse 为数组,每项交给 CreaFasce 生成 HTML
+            │ 空数组仍初始化 vertical timeline;length=1 只设置 unicaFascia
+            │ SlotRimanenti < 0 → notAvailableFascia + dotRed
+            │ SlotLiberi → 括号显示数量;起止时间 → HH:mm
+            │ 唯一非负项自动 act;daily ID → Slot 内 hidden input
+            │ [OBSERVED:E23,E28-E44;Availability/TimeSlots 为 POST JSON,
+            │  正负 response/DOM 与安全点击后的唯一 act 已交叉验证]
+            │
+            ├─ 8 月默认窗口负向样本:
+            │  42 个日期格全部 disabled
+            │  31/08/2026 = disabled + notAvailableDay + active
+            │  默认 selected 日期的三个时段均为 notAvailableFascia 并显示 (0)
+            │  [OBSERVED:E23,E24]
+            │
+            └─ 10 月真实正向日期与 Slot
+               [OBSERVED:E43,E44]
+                  │ 2026-10-09:Availability = 1/0
+                  │ 10:05–11:05:TimeSlot = 1/0
+                  │ 普通 fascia、无红点、hidden daily ID 存在
+                  │ 安全点击一次后唯一 act,后代/时间/日期一致
+                  │ final 未点击;InsertNewBooking=0
+                  ▼
+               Final Confirmation
+               [STATIC OBSERVED:delegated handler → POST /BookingCalendar/InsertNewBooking]
+                  │ 字段:idCalendarioGiornaliero / selectedDay / selectedHour
+                  │ response:errorMessage / url
+                  ▼
+               Booking Result
+               [UNVERIFIED;Discovery 阶段禁止执行]
+```
+
+登录身份验证和预约 OTP 是两个不同职责域。前者用于建立业务登录 Session;后者在 HK-7 中仅凭单独明确授权执行过一次。这个样本不把 OTP 变成 Query 行为,也不意味着以后允许自动发送或重试。
+
+## 5. Query 职责合同
+
+### 5.1 框架上下文
+
+`Sentinel` 调用 `plugin.query(apt_type)`;只有 `result.success=True` 时才把快照写入 Redis。Booker 随后把快照反序列化,并在自己的插件实例中调用 `book(query_result, user_inputs)`。
+
+因此:
+
+- Query 的浏览器对象、DOM、Cookie 和临时页面状态不能传给 Book。
+- Query 结果是一个可能已经过期的信号,不是预约事实。
+- Book 必须假设自己的账号和 Session 与 Sentinel 不同。
+
+标签:`[SOURCE-INFERENCE:E5]`。确信度:高。
+
+### 5.2 三个候选方案
+
+| 方案 | 含义 | 优点 | 风险 | 当前结论 |
+|---|---|---|---|---|
+| A | Query 只看 Services 是否有 `Prenota` | 成本最低 | 无号时链接仍存在,会制造假“有号”信号 | 已由 E7 否定 |
+| B | 团队 Query 账号每个业务 Session 准备一次 Calendar,后续只读 Availability | E43 已用同日 TimeSlots 交叉证明正向日期容量;可复用 VFS/BLS 的“Query 给日期、Book 重查时段”合同 | 准备阶段需要一次 OTP + Booking Form POST;是否创建草稿、只读 probe 是否幂等、Session 寿命仍需 Gate | 推荐的生产方向,但 Q-CAL-1/Q-CAL-2 通过前不得启用 |
+| C | Query 只记录可进入流程的弱信号,Book 独立执行后续检查 | 副作用最少;适合 Discovery/人工告警 | 没有日期/时段,持续触发会浪费用户 OTP 与机会;现有三态也无法准确表达 | 保留为诊断和降级,不作为生产精确号源信号 |
+
+### 5.3 推荐的双模式合同
+
+输入:
+
+- `AppointmentType`;当前真实样本为 `slot.dub.it.tourist` 和候选 `slot.hkg.it.tourist`。
+- 插件配置中需要有可审查的 `routing_key → service_id + 业务语义交叉校验` 映射;不能把 `1321` 或 `4937` 做成插件全局常量。
+
+`services_probe`(当前已实现的零写模式)允许:
+
+1. 确认当前是有效认证 Session。
+2. 从 `/UserArea` 导航至 `/Services`。
+3. 读取服务表格和目标行。
+4. 使用 path 中的数字 ID 和显示文本交叉确认目标服务。
+5. 对当前服务入口只执行一次已观察的 GET 导航;识别无号后立即返回。
+6. 若得到 `200 + form#bookingForm`,只记录结构和 stage;不得选择字段、发送 OTP 或点击 `AVANTI`。当前代码会发布 `success=True + NoneAvailable` 弱信号;R3 要求生产配置不得使用它触发 OrderBooker。
+
+`calendar`(设计候选,Gate 未通过前禁用)允许:
+
+1. 使用已授权的团队账号和其注册邮箱;不共享给用户 Book 账号任何 Cookie、OTP 或页面状态。
+2. 每个认证/业务 Session 至多一次沿网站原生流程选择单人和旅游、完成 Privacy/Turnstile、发送 OTP、点击 `AVANTI`,并在前后只读核对预约列表没有新增记录。
+3. Calendar ready 后的后续 probe 不再发送 OTP、不再提交 Booking Form;只通过网站原生页面动作逐月读取 Availability。网站自动产生的 TimeSlots 可作诊断,但 Query 不主动按日期扇出请求。
+4. 不能只检查默认月份。必须在 route 配置的日期范围/向后月份范围内逐月扫描 Availability;8 月负向样本不能遮蔽 10 月正向库存。
+5. 用 `SlotLiberi>0 AND SlotRimanenti>=0` 选出正向日期;完整范围至少一个正向日期就发布 `Available`,`DateAvailability.times=[]`。
+6. 信号只携带正向日期,不携带 Query 账号时段、runtime service ID、daily ID、Cookie、OTP 或 Token;Book 必须在用户 Session 重查具体时段。
+
+两种模式都禁止:
+
+- 每轮 probe 重复发送 OTP 或重复点击 `AVANTI`。
+- 在 Gate 未通过或账号未授权时进入 `calendar` 准备阶段。
+- 用团队账号填写用户的个人资料、上传用户文件或执行最终预约。
+- 上传文件。
+- 创建草稿、占位或预约。
+- 选择最终时段或执行 `InsertNewBooking`。
+
+结果语义建议:
+
+| 网站状态 | 期望语义 | 当前模型注意事项 |
+|---|---|---|
+| 在配置日期范围内,Availability 至少有一个 `SlotLiberi>0 / SlotRimanenti>=0` 日期 | `Available` | E43 已用同日 TimeSlots 校准;快照只含日期、`times=[]` |
+| 明确显示候补 | `Waitlist` | 待真实网站验证 |
+| `302 → /Services` 且 `#WNotAvailable.value` 非空 | `NoneAvailable` | Phase 1 已实现为 `success=False` |
+| `200 → /Services/Booking/{id}` 且存在 `form#bookingForm` | 诊断 stage;不发布生产信号 | Hong Kong 已观察到它可进入 Calendar,但它自身不携带日期或库存 |
+| 默认月份无号,但配置范围内后续月份有正向日期 | `Available` | E43 已证明必须扫描完整配置范围,不能在默认月份提前返回无号 |
+| 服务行不存在 | `TargetServiceMissing` | 当前没有专门结果状态,应抛明确业务异常,不能伪装成无号 |
+| 登录跳回认证页 | `SessionExpiredOrInvalidError` | 需要重建 Session |
+| 429 或明确限流 | `RateLimiteddError` | 需要退避,不能伪装成无号 |
+| CAPTCHA、页面结构变化、关键字段缺失 | `BizLogicError` 或后续专门异常 | 不能伪装成无号 |
+| 只有 `Prenota` 链接,没有进入结果 | `ServiceEntryListed`,不发布可预约信号 | Dublin 已证明该链接在无号时仍存在 |
+
+### 5.4 当前实现决策
+
+现有 `AvailabilityStatus` 只有 `Available`、`Waitlist`、`NoneAvailable`。如果将 `Prenota` 或 `200 + bookingForm` 直接映射为带具体日期含义的 `Available`,Sentinel 会写 Redis 信号并触发 Booker,但我们仍不知道 Calendar 是否有日期。
+
+Gate 2 已证明不能让 Query 因为看到 `Prenota` 就返回 `success=True`。当前工作树的 Query 行为是:
+
+1. 从配置读取 `service_id=1321`,按精确 path 找入口,不依赖语言文本。
+2. 每次 Query 先重新加载 `/Services`,清掉上一次无号弹窗留下的 DOM 状态,再重新定位服务入口。
+3. 每次 Query 最多点击一次目标入口。
+4. 回到 `/Services` 后,非空 `#WNotAvailable.value` 仍是首选无号证据。
+5. hidden marker 缺失时,允许读取 `.jconfirm-content`;仅对白名单中已有真实证据的意大利语无号文案返回 `NoneAvailable`。
+6. 可见弹窗先进行大小写、空白和弯/直撇号归一化,但不做模糊语义猜测;未知文案继续作为结构错误。
+7. 调试工具对未知弹窗只输出最长 300 字符的脱敏文本,不保存截图;邮箱、长数字和长 token 会被替换。
+8. 进入预期 `bookingForm` 时不填写表单、不发送 OTP、不访问日历,但设置 `result.success=True`,保留 `availability_status=NoneAvailable` 和空 availability 后返回。这是 BLS 式弱信号,副作用为 0,却不能回答真实库存。
+
+E43 已证明 B 在“已准备好的同一 Calendar Session”中能够返回真实正向日期,并用同日 TimeSlots 交叉确认它不是名字诱导。生产 Query 因此只需传播日期,具体时段留给用户 Book 重查,最大化复用 VFS/BLS 并减少请求。但 E43 没有证明准备阶段零草稿、Calendar probe 可长期重复、Session 寿命或跨账号命中率。生产启用必须先通过 Q-CAL-1/Q-CAL-2 和跨账号 Gate;在此之前,当前弱信号只能用于 Discovery/人工告警,不能接生产 OrderBooker。确信度:正向日期语义高;生产重复探测安全性中低,待 Gate。
+
+## 6. Book 职责合同
+
+### 6.1 输入
+
+- Sentinel 的 `VSQueryResult`:只作为“值得重新检查”的线索。
+- Booker 的 `user_inputs`:用户日期偏好、经页面合同要求的申请资料;文件引用只在目标 Sede 真实出现文件控件时存在。
+- Booker 自己创建的有效登录 Session。
+
+### 6.2 必须负责
+
+1. 重新确认 Session 仍然有效。
+2. 重新解析目标服务,不能盲信旧 service ID 或旧页面状态。
+3. 重新查询当前日期和时间,不能直接使用 Sentinel 的旧时间段。
+4. 应用用户日期偏好。
+5. 通过可见控件选择 `Prenotazione Singola` 和 `Turismo`,触发网站原生事件链;选择后机械检查预约类型 visible/hidden=`1/1`、同行人数 hidden=`0`、旅游 visible=`42`。此时旅游 hidden 为 `0` 是真实预期,只有 `AVANTI` handler 内的 `saveDdlValue()` 才会在 form submit 前写成 `42`;插件不得提前手工赋值。
+6. 只填写当前页面明确要求的资料;Hong Kong 当前表单只有可选 Notes,没有文件上传控件。
+7. 在同一个用户浏览器上下文中完成 Cloudflare Turnstile;不能跨 Session 复制动态 Token,不能绕过 challenge。Hong Kong 当前成功 POST 只有 `cf-turnstile-response` 字段名,没有 `g-recaptcha-response`;插件不调用未引用的 `getCaptchaToken()`,但未来 DOM/handler 变化时重新 capability discovery。
+8. 只调用一次当前服务的 GenerateOTP endpoint;HTTP GET 仍按副作用命令处理。只有 HTTP 200 且原始响应文本精确为 JSON 字符串 `"SENT"` 才记为客户端成功;真实样本已同时观察邮件送达和 120 秒 UI 冷却。响应不明时不重试。
+9. 在 OTP、Privacy、字段同步和 Turnstile 条件有效后,沿网站 `AVANTI` 原生 click handler 提交一次。Hong Kong 真实样本为 `POST /Services/Booking/4937 → 302 Location: /BookingCalendar?...`;草稿语义未验证前禁止自动重试。
+10. 以 `GET /BookingCalendar?... → 200 Document`、pathname 和标题共同识别 Calendar;等待页面原生加载 `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots`。Availability 与 TimeSlots 已确认 POST JSON 请求合同,且 response 都是外层 JSON 字符串再解析为内层数组;两类 item 的正负 schema 已由 E43 关闭。TimeSlots 必须从当前 Calendar DOM 读取 `#idServizio`,不能复用 routing `service_id`。ServerInfo 合同、请求幂等性和 Session 寿命仍未关闭,因此不能脱离网站原生状态机随意重放。
+11. 不能只检查 Calendar 默认月份:必须遍历用户允许日期范围或显式配置的 lookahead 范围。每个月先解析 Availability;只有 `SlotLiberi>0` 且 `SlotRimanenti>=0` 才是正向日期候选。日期格还要具备 `availableDay` 且不得为 `disabled`/`notAvailableDay`,timeline/content 日期必须相同。网页会在目标日期不存在时静默回退并程序化点击第一天,因此每次异步更新后都必须重新读取实际 selected 日期,与候选日期和用户偏好做事后断言;不一致时停止。`selected`、`active`、`availableDay`、`input-async-abilitato`、`data-async=true` 或 enabled final button 中任何一个单独出现都不算有号。
+12. 对符合条件的日期读取 TimeSlots。正向 item 必须有 `SlotLiberi>0`、`SlotRimanenti>=0`、合法起止时间、唯一且合法的 daily calendar ID,并且 DOM 不含 `.notAvailableFascia`/`dotRed`;E43 已证明 `SlotLiberi=1 / SlotRimanenti=0` 是真实正向组合,不能把 `SlotRimanenti=0` 错判为无号。数组长度、自动 `act` 和页面出现时间文字仍不能独立作为有号判据。点击后验证恰好一个 `.fascia.act`,它仍是同一正向候选,并再次核对日期、时间、daily ID 和用户偏好。
+13. 最终确认候选是 `POST /BookingCalendar/InsertNewBooking`,当前静态字段为 `idCalendarioGiornaliero`、`selectedDay`、`selectedHour`。在取得完整响应合同、预约幂等键/恢复策略和用户最终授权前,禁止调用。
+14. 返回预约编号、日期、时间或明确失败原因;结果不明时先只读检查服务器状态,绝不重提最终 POST。
+
+### 6.3 副作用和重试边界
+
+| 阶段 | 风险 | 重试原则 |
+|---|---|---|
+| Session 检查、已证明只读的 Services/日历查询 | 低 | 可在确认幂等后有限重试 |
+| 在页面填写个人资料 | 向第三方传输敏感数据 | 需单独授权 |
+| 上传护照、居留证明 | 高敏感数据传输;Hong Kong 当前页面未出现文件控件 | 只有真实页面要求时才设计,并需单独授权 |
+| 获取/刷新 Turnstile 状态 | 与浏览器、页面和风控上下文绑定;过期/超时会禁用 `AVANTI` 并 reset | 保持同一 Session;出现人工 challenge 时停下交给用户 |
+| reCAPTCHA Enterprise `BOOKING` 候选函数 | 页面定义函数,但关键 handler 无调用;成功真实 POST 只观察到 Turnstile 字段名 | 当前 Hong Kong 主路径不调用;不删除 capability 检测,未来页面变化重新发现 |
+| `GET /BookingCalendar/GenerateOTP?ServiceID={id}` | 发邮件、至少 120 秒 UI 冷却、潜在服务端限流 | HTTP method 不改变副作用性质;不可盲目重复,需单独授权 |
+| 点击 `AVANTI` 提交预约前置表单 | 可能创建草稿、占位或进入 Calendar | 结果不明时先查服务器状态,不直接重试 |
+| Calendar 自动 XHR | 当前页面会自动请求 ServerInfo、Availability 和 TimeSlots;Availability/TimeSlots 已知 POST JSON 与双层数组编排;E43 已关闭 `0/-1` 负向与 `1/0` 正向组合;初始化还会程序化点击/回退;ServerInfo、长期幂等性和 Session 寿命未关闭 | 先等待网站原生页面加载;按配置范围逐月扫描,不能因默认月份无号提前结束;未证明幂等前不脱离原生状态机重放;不得混用配置/运行时 ID;异步结束后交叉核对 response、DOM、实际日期、两个 Slot 字段和时间 |
+| `POST /BookingCalendar/InsertNewBooking` | 高概率产生真实预约;静态字段已观察 | Discovery 阶段禁止;只有正向 Slot、完整响应合同、幂等/恢复策略和用户最终授权全部满足后才能执行一次;结果不明时禁止自动重试 |
+
+## 7. 当前代码差距
+
+以下结论只描述当前工作树,不代表网站行为。
+
+| 证据或合同 | 当前代码行为 | 风险 | 状态/下一步 |
+|---|---|---|---|
+| 登录后 Dashboard 已观察为 `/UserArea` | `create_session()` 要求 `/UserArea + .app-menu + /Services href` 并在此停止 | 网站未来可能变化 | 本地测试和一次真实自动登录均已验证 |
+| IAM 表单稳定字段已观察 | 使用 `callback_1`、`callback_2` 和 submit;凭据最多提交一次 | 历史 404 根因仍未知 | DOM 合同和一次真实自动登录已验证;失败时禁止自动重试 |
+| OAuth 动态值不应进入日志 | Router 和调试诊断只输出 scheme、host、path;异常 `/signin/{编码 URL}` 统一脱敏 | 第三方异常文本仍需测试覆盖 | 本地脱敏测试已添加 |
+| `/Home` 触发过 Radware/hCaptcha | 配置中的 `website` 仍为 `/Home`;代码主要检查 Cloudflare 文本 | 把反爬页、登录失效和业务页混在一起 | 明确入口与反爬分类;不照搬 VFS 的 Cloudflare 逻辑 |
+| Dublin 页面实际是意大利语 | Phase 1 Query 使用配置 ID 和精确 `/Services/Booking/{id}` path | 不再依赖 `Book`/英文服务名 | 已修复并有离线测试 |
+| Dublin `1321` 与 Hong Kong `4937` 是不同 Sede 的真实入口 | Sentinel/Booker Italy 配置仍是组级单值 `service_id=1321` | 插件和工具被锁在 Dublin,不能承载通用 Italy | 复用 VFS/BLS 的 `apt_configs`;routing key 解析配置,不写城市分支 |
+| `Prenota` 不等于有具体日期 | Query 每轮先重载 Services,再进入一次门禁;hidden marker 或已验证可见无号文案才返回无号 | 可见文案未来可能变化,长期限流表现未知 | 当前真实文案白名单已实现;未知文案 fail-closed |
+| 当前 `services_probe` Query 禁止发送预约 OTP | Query 源码不包含 OTP 路径 | 有号分支功能暂不可用 | 保留为默认安全模式;未来 `calendar` 模式只在独立 Gate 后每 Session 准备一次 |
+| 当前 Query 禁止填写或提交预约表单 | Query 进入 `bookingForm` 时返回 `success=True + NoneAvailable` 弱信号 | 不污染账号,但会触发 Booker,无法证明真实库存 | 生产禁用弱信号;准备型 Calendar Query 作为独立 Change Set/Gate |
+| Query 应返回真实证据 | 仅实现已观察的 `NoneAvailable`;不伪造日期 | 目前不会返回 `Available` | E43 已给出正向 parser 合同;仍需配置范围扫描、Q-CAL 安全性和离线实现 |
+| 真实 Query 验证必须与登录验证隔离 | `tools/debug_ita_query.py` 登录后只调用一次 Query,不重试且从不调用 Book | 长期重复探测仍可能触发风控 | 第二次单次 Dublin 无号验证已成功;Hong Kong 仅人工执行一次入口访问 |
+| 历史 Query 残留变量 | `valid_dates`、`valid_days`、Query 中的 `self._host` 已移除 | Book 仍引用不存在的 `self._host` | Query 已修复;Book 不在本阶段范围 |
+| Book 必须重查 | Book 直接使用 `slot_info.availability[0].times[0]` | 空列表报错;旧时间已失效;跨 Session 不可靠 | Book 只把快照当提示,在本 Session 中重查 |
+| Calendar 初始页面会自动加载 ServerInfo、Availability 和 TimeSlots;E43 已取得正向/负向 response 与 DOM;TemplateFasce 会逐 Slot 写入重复 hidden id;网站 handler 可给负向 `.fascia` 添加 act | 当前 Book 没有等待异步阶段,也没有区分 routing/runtime/daily ID,更没有 response/日期范围/Slot 分类器 | 只查默认月份会漏掉后续库存;发送错误 ID;用文档级重复 ID 取错 Slot;把数组非空、自动 act 或 enabled 按钮当有号 | 纯解析器使用 E43 truth table;逐月扫描配置范围;从正向 Slot 子树验证两个数量/时间/唯一 ID;点击后再验证唯一 act,最终默认禁用 |
+| Hong Kong 页面没有独立 email 输入;GenerateOTP URL 也没有 email 参数 | Book 读取不存在的 `self.config.account.email` | `AttributeError`;手工传 email 会偏离真实协议 | E22 已验证 OTP 发往当前登录账号的注册邮箱;删除独立 email 假设,沿 Session 发送 |
+| Hong Kong 表单结构和同步 handler 已验证 | Book 硬编码 Dublin 示例字段、Reason `42` 和文件字段 | `42` 恰好匹配 Hong Kong,但硬编码无法证明跨 Sede;真实页面没有文件控件 | 通过可见 select + 配置语义驱动;触发 change 后断言单人/同行人数/旅游 hidden,不手工伪造 multipart payload |
+| Hong Kong 有 Turnstile callback,并定义但未观察到调用 `getCaptchaToken()` | 当前 Book 没有可审计的 CAPTCHA 生命周期 | Token 过期、擅自调用模板遗留函数或跨 Session 复制都会导致提交失败/风控 | E22 成功 POST 只观察到 Turnstile;保持同一上下文并驱动原生 click,不调用未引用函数 |
+| 最终请求的静态 path/字段已观察,但从未执行 | Book 直接调用历史 `InsertNewBooking` 路径,并使用旧快照中的日期/时间 | 路径碰巧相同不代表 payload、响应或重试语义正确;可能重复真实预约 | 保留禁止执行;先关闭 Slot 正向 DOM、完整 handler/response schema、幂等与结果恢复合同,再沿网站原生链单次验证 |
+| 401/403/429 应分类 | Italy `_perform_request()` 只包装 fetch,未做完整状态映射;网站 `EseguiAsync` 自身也丢弃 error response | 登录失效、限流、服务器错误和无号混淆 | 参考统一异常语义,但不照搬 VFS URL/JWT/字段;插件主动保留 status/响应类别/脱敏摘要 |
+| Session 需要安全保活 | `keep_alive()` 为空 | Session 可能静默失效 | 观察一个明确只读、低频、可重复的业务请求后实现 |
+
+### 7.1 Phase 1 与 Gate 1 本地修复边界
+
+当前未提交差异包括 `_random_sleep(min_sec, max_sec)` 修复、保守 Query、`service_id=1321` 配置、`/UserArea` Session 合同和离线安全测试。Query 测试覆盖非空/空 `WNotAvailable`、连续两次无号探测前均重载 Services、未知有号表单、目标链接缺失、配置缺失和登录失效;Session 测试覆盖一次登录入口、一次凭据提交、提交后不刷新、认证 DOM 双标志和 URL 脱敏。
+
+当前证据仍不能证明:
+
+- 历史 404 的准确原因。
+- 网站未来变更后仍保持相同登录字段和 DOM。
+- 高频或长期重复登录不会触发额外风控。
+- 有号 Query 或 Book 可用于真实网站。
+
+## 8. Git 历史中的旧接口线索
+
+提交 `06a9291` 之前的 Italy 代码曾尝试:
+
+- `GET /Services/Booking/{service_id}`
+- `GET /BookingCalendar/RetrieveServerInfo`
+- `POST /BookingCalendar/RetrieveCalendarAvailability`
+- `POST /BookingCalendar/RetrieveTimeSlots`
+- `POST /BookingCalendar/GenerateOTP`(历史尝试;E18 当前页面静态代码实际使用带 `ServiceID` 的 GET,不能恢复旧 POST)
+- `POST /BookingCalendar/InsertNewBooking`
+
+在 HK-8 之前,这些路径只能标记为 `[SOURCE-INFERENCE:E5]`。E23 独立确认当前 Calendar 页面生命周期中确实出现三个 XHR path,当前 inline script 也定义最终 POST。E27/E28 确认 Availability 是 POST JSON;E33 确认 TimeSlots 是 POST JSON,request keys 为 `selectedDay/idService`,其中 runtime ID 来自 Calendar DOM;E34/E35 确认 TimeSlots 的双层数组、核心 item 字段、负向 class、显示数量和 daily ID 模板占位符;E37–E42 关闭 hidden DOM、模板、serializer 和 selected 日期;E43 又关闭真实正向/负向 response 与 DOM truth table。ServerInfo 合同、Calendar probe 长期幂等性、正向 Slot 点击后的 active 状态和最终 POST 仍未关闭。因此历史实现仍不能整体回滚,只能逐接口与当前证据交叉检查。历史 GenerateOTP POST 已被 E18/E22 的当前 GET 事实明确覆盖。
+
+## 9. 没有 Chrome 扩展时的人工协作流程
+
+Chrome 扩展是效率工具,不是修复的逻辑依赖。没有扩展时采用“用户操作、开发者分析”的方式:
+
+1. 开发者一次只给一个页面操作。
+2. 用户在同一个已登录 Chrome 中执行。
+3. 页面证据只提供 URL、标题、截图和非敏感文本。
+4. Network 证据只提供 method、path、status、类型和字段名。
+5. 不发送原始 HAR 或 `Copy as cURL`,因为它们通常包含 Cookie、Token 和个人信息。
+6. 每次准备发送 OTP、提交表单、上传文件或最终确认前,重新描述副作用并单独请求授权。
+7. 开发者把脱敏结构制成 fixture,先完成离线解析和契约测试,再进行下一次真实验证。
+
+这种方式比直接控制浏览器慢,但证据边界清楚,可以继续完成插件修复。
+
+2026-08-28 的实际诊断结果:Chrome 正在运行、目标 profile 的扩展已安装且启用、native host manifest 正确,相关只读检查均 exit 0;但列出/接管用户标签连续超时。按“同一错误最多两次”停止自动接管,打开新窗口恢复后仍超时,随后切换为本节人工流程。没有把浏览器实例 ID、标签 ID、进程 ID 或动态 Session 值写入本文。该记录只说明采集方式,不构成 Prenot@Mi 业务证据 `[OBSERVED:E17]`。
+
+## 10. 已完成与下一步 Discovery Gates
+
+### 10.1 目标
+
+只进入一次 Dublin 候选服务 `/Services/Booking/1321`,判断能否在预约 OTP 和表单提交之前取得安全、只读的号源证据。
+
+用户在同一已登录 Dublin 会话中完成了一次点击;没有重试,结果见 §2.5。
+
+### 10.2 最小操作边界
+
+允许:
+
+- 在已登录 Dublin 账号中打开 DevTools Network。
+- 清空当前请求列表。
+- 点击一次目标行的 `Prenota`。
+- 记录跳转 URL、页面标题、DOM 截图和脱敏 Network 元数据。
+
+禁止:
+
+- 填写预约类型、Reason、Notes 或个人资料。
+- 点击 OTP 发送。
+- 输入 OTP。
+- 勾选后提交隐私协议。
+- 上传文件。
+- 选择日期或时间。
+- 点击任何最终确认按钮。
+
+### 10.3 Gate 2 机械完成标准
+
+完成结果:
+
+1. 已记录 `GET /Services/Booking/1321`、`302`、document。
+2. 已记录 `Location: /Services`、最终 `/Services` 和无号弹窗。
+3. 已区分 4 个 Radware 自动安全 POST 与 0 个预约业务 POST。
+4. `BookingCalendar=0`,没有看到日期或时间。
+5. `otp=0`,没有资料上传、前置表单提交或最终确认请求。
+6. 已取得 `#WNotAvailable` hidden input 的非空 value 证据。
+7. A 已否定;B 因无号未能验证;继续维持 C 式副作用纪律。
+
+### 10.4 单次自动 Query 验证(无号分支已验证)
+
+为了避免把“登录验证”和“预约入口探测”混成一个含糊工具,新增独立入口 `tools/debug_ita_query.py`。它的固定合同是:
+
+1. 只针对 Dublin `service_id=1321`;若环境变量尝试指定其他 ID,配置阶段直接拒绝。
+2. 建立认证 Session 后只调用一次 `ItaPlugin.query()`;没有循环和自动重试。
+3. 永不调用 `book()`。
+4. 明确无号时输出 `ITA_QUERY_NONE_AVAILABLE ...` 并返回 exit 0。
+5. 若进入可能有号的 Booking Form,输出 `ITA_QUERY_SAFE_STOP ...` 并返回 exit 4;不会继续表单、OTP 或日历。
+6. 其他会话、结构或运行异常输出脱敏失败信息并返回 exit 1。
+7. 无论结果如何都执行清理;清理异常返回 exit 3。
+8. 工具不保存 Query 页面截图,避免把可能出现的个人资料写入磁盘。
+
+exit 4 是预期安全门,不表示继续修复或重试的授权。真实执行仍需由用户在本地交互输入凭据;凭据不会进入命令行参数、文档或聊天记录。
+
+第一次真实执行的结果见 §2.6:未满足无号判据时 exit 1,证明安全门有效。随后实现增加可见弹窗白名单,并继续输出语言无关的 `AvailabilityStatus`。第二次单次真实执行见 §2.7:返回 `NoAvailable`、清理成功且 exit 0,Phase 1 无号 Query Gate 已关闭。
+
+### 10.5 Hong Kong Booking Form 只读结构发现(已完成)
+
+`tools/debug_ita_query.py` 的只读采集器仍只有离线验证;本次真实结构由用户在 Hong Kong 已登录标签中按同一安全合同手工采集:
+
+1. 只读取当前 path、form method/action/enctype。
+2. 字段只读取 tag、type、id、name、required、label 和 select options;没有读取 input/hidden value。
+3. 按钮只读取 tag、type、id、name、文字以及是否存在 onclick;没有读取 handler 内容,没有点击。
+4. 不读取 Cookie、Web Storage、CSRF、Turnstile value、个人资料或 OTP。
+5. 结果确认单人 `1`、`Turismo=42`、OTP、Privacy、Turnstile 和 `AVANTI`;没有文件上传控件。
+6. 页面仍停留在 `/Services/Booking/4937`,没有发送 OTP 或提交表单。
+
+真实合同详见 §2.10,来源为 E16。这个 Gate 已关闭,但只关闭“页面结构是什么”,没有关闭“按钮会请求什么”。
+
+### 10.6 OTP 与 `AVANTI` 静态 handler 发现(已完成)
+
+用户完成零副作用只读检查:
+
+1. `#otp-send` 调用 `sendOTP()`。
+2. 静态代码使用 `GET /BookingCalendar/GenerateOTP?ServiceID=4937`。
+3. 成功分支显示发送成功并启动 120 秒 timer;失败分支显示 invalid。
+4. `#btnAvanti` 检查预约类型和通用附加字段,调用 `CheckMaxFileSize()`、`saveDdlValue()` 和原生摘要确认,然后提交 `bookingForm`。
+5. `bookingForm` 自身没有观察到事件 handler。
+6. 全程没有点击、请求、读取 hidden value、Cookie、Token、个人资料或 OTP。
+
+该 Gate 的机械完成标准已满足,完整证据见 §2.11 和 E18。
+
+### 10.7 关键函数体与 Turnstile callback 只读发现(已完成)
+
+用户已完成以下零副作用静态检查:
+
+1. 读取 `sendOTP()` 完整函数体,确认 response 的成功判据。
+2. 读取 `saveDdlValue()`,确认 `Turismo=42` 如何同步到 hidden 字段,并检查它是否同时处理 `Prenotazione Singola=1`。
+3. 读取 `CheckMaxFileSize()`,确认无文件控件时返回路径。
+4. 只提取 Turnstile/captcha callback 的函数名和相关源码,确认 `#btnAvanti` 的 enabled/disabled 状态由什么控制。
+5. 继续脱敏邮箱和长动态值;不读取任何运行时 token/value,不点击按钮。
+
+实际结果:
+
+- OTP response 已关闭:HTTP 200 + raw responseText 精确等于 `"SENT"`。
+- `Turismo=42` 同步已关闭:`ddls_0 → hiddenSelezionato_0`。
+- 无文件控件路径已关闭:`CheckMaxFileSize()` 返回 `true`。
+- Turnstile callback 合同已关闭:成功启用 `AVANTI`,过期/超时禁用并 reset。
+- `Prenotazione Singola=1 → IdTipoPrenotazione` 没有出现在 `saveDdlValue()` 中,仍未关闭。
+- 新发现 reCAPTCHA Enterprise `getCaptchaToken()`,但它与 E18 direct form submit 的调用关系仍未关闭。
+
+HK-5 当时机械地暴露了两个新的 P0,因此没有提前发送 OTP。HK-6 随后关闭预约类型同步,并把 reCAPTCHA 函数分类为“已定义但在已检查范围内未观察到调用”;详见下一 Gate。
+
+### 10.8 预约类型同步与 reCAPTCHA 调用链只读发现(已完成)
+
+继续停留在零副作用静态调查:
+
+1. 提取 `#typeofbookingddl` 的 inline/native/jQuery `change` 事件源码。
+2. 搜索 `hiddenTipoPrenotazione`、`IdTipoPrenotazione` 和 `typeofbookingddl` 的所有 inline script 上下文,确认单人 `1` 的同步责任方。
+3. 提取 `form#bookingForm` 的 inline/native/jQuery `submit` 事件源码。
+4. 搜索 `getCaptchaToken()` 的全部调用点以及 `g-recaptcha-response` 的创建路径,解释为何 E18 handler 直接 `submit()` 而页面又定义 token 函数。
+5. 只读取静态函数/handler,不读取运行时 token、hidden value、Cookie、个人资料或 OTP;不触发 change、submit、click 或网络请求。
+
+实际结果:
+
+1. `typeofbookingddl` change handler 调用 `ShowCompanions()` 和摘要更新函数。
+2. 单人 `1` 经 DOMPurify 写入 `hiddenTipoPrenotazione/IdTipoPrenotazione`,并把 `numAccSelected/NumAccompagnatoriSelected` 设为 `0`。
+3. `bookingForm` 没有 inline/native/direct jQuery submit handler。
+4. `AVANTI` 的唯一已观察 direct click handler 在确认后直接调用 form submit。
+5. `getCaptchaToken()` 只观察到定义,没有在采集到的 inline script 上下文或三个关键元素 handler 中发现调用点。
+6. 没有读取运行时 token、Cookie、个人资料或 OTP,没有触发任何事件或请求。
+
+机械完成标准已满足:预约类型链已闭环;reCAPTCHA 分支没有被猜成活跃路径,而是明确标为“当前已检查范围内未引用,等待真实 POST 验证”。完整证据见 §2.13 和 E20。
+
+### 10.9 一次真实 OTP 与一次受控 `AVANTI`(已完成)
+
+这个 Gate 已获得用户明确授权,并已用完唯一一次 OTP 与唯一一次 POST 预算。目标不是完成预约,而是取得 Booking Form → Calendar 的真实协议。
+
+允许且只允许:
+
+1. 重新进入一次 Hong Kong `4937` Booking Form,打开 Network 并清空记录。
+2. 通过可见控件选择单人 `1` 和旅游 `42`;只读确认预约类型 visible/hidden=`1/1`、同行人数 hidden=`0`、旅游 visible/hidden=`42/0`。旅游 hidden 将由后续原生 `AVANTI` handler 同步。
+3. 在 Turnstile 可用、用户能立即读取注册邮箱时,只点击一次 OTP 发送。
+4. 记录 GenerateOTP 的 method、path、status、脱敏响应类别和邮件是否送达;不复制 OTP。
+5. 用户手工输入 OTP、勾选 Privacy,点击一次 `AVANTI` 并确认一次原生摘要框。
+6. 记录 Booking Form POST 的 method、path、status、redirect/final path、页面标题和错误/Calendar DOM 标志;不读取或复制 Request Payload。
+7. 到达 Calendar 后立即停止,不选择日期、时间,不点击任何最终确认。
+
+失败即停:OTP 非明确 `SENT`、邮件未到、Turnstile 失败、POST 结果不明或页面出现未知错误时,均不自动重发或重提。
+
+机械完成标准:GenerateOTP 最多 1 次、Booking Form POST 最多 1 次;两者结果均可分类;能判断真实 submit 是否要求 reCAPTCHA,以及 POST 后是错误、Calendar 还是其他状态;日期选择、Slot 和最终确认请求均为 0。
+
+当前结果:
+
+- GenerateOTP=1:GET、200、`SENT`、邮件送达。
+- Booking Form POST=1:POST、302、Location 指向 `/BookingCalendar?...`。
+- Calendar document=1:GET、200、Document;最终 pathname=`/BookingCalendar`、title=`Calendar - Prenot@Mi`。
+- POST 只观察到 Turnstile 字段名,没有 reCAPTCHA 字段名。
+- 页面显示 Calendar 标题;日期/时间/最终确认点击均为 0。
+
+机械完成标准全部满足,HK-7 已关闭。OTP/POST 额度已用完,后续调查从 Calendar 当前页面开始,不会再次请求 OTP 或 POST。
+
+### 10.10 Calendar 日期协议零点击 Discovery(部分关闭)
+
+目标是在不点击日期、不触发时间选择、不提交最终预约的前提下,回答 Calendar 如何表达月份、可用日期和后续接口。
+
+允许:
+
+1. 只读当前 `/BookingCalendar` 的 DOM、form、按钮属性、日期单元格 class/data 属性和 inline handler 源码。
+2. 只读现有 Network 日志中 Calendar 页面加载时已经发生的请求 method/path/status/type。
+3. 搜索当前 inline script 中的 `RetrieveCalendarAvailability`、`RetrieveTimeSlots`、`InsertNewBooking` 等 endpoint 线索,只记录 method/path/字段名,不执行函数。
+
+禁止:
+
+- 点击月份、日期或时间。
+- 调用 availability/time-slot/final-confirm endpoint。
+- 读取或复制 Cookie、CSRF、OTP、Turnstile、个人资料或完整 Request Payload。
+- 刷新页面或再次进入 Booking Form。
+
+机械完成标准:区分“页面生命周期已自动取得的数据”和“必须交互后才发生的请求”;输出 Calendar DOM 状态、现有相关请求清单和静态 endpoint/handler;日期、时间、最终确认点击与新增业务请求均为 0。
+
+当前结果:
+
+- DOM、月份、42 个日期格、默认日期和三个 `(0)` 时间段已取得,见 §2.16。
+- 日期、月份、时间和最终按钮点击均为 0;采集脚本没有调用任何业务函数或 endpoint。
+- Resource Timing 已证明页面生命周期中存在三个自动 XHR path,但没有 method/status/response schema。
+- 静态脚本已证明最终候选为 `POST /BookingCalendar/InsertNewBooking`,并取得三个字段名;没有执行。
+- 因 Network method/status/type 与 response schema 尚未关闭,本 Gate 只完成 DOM/静态协议部分,不能标为全部完成。
+
+### 10.11 Calendar XHR 与 Slot handler 零点击闭环(部分关闭)
+
+下一步仍然只读,不点击、不刷新、不新发业务请求。目标是解释当前 `(0)`、可用日期 class 和 `.fascia.act` 的真实含义,并关闭三个自动 XHR 的当前调用合同。
+
+优先证据顺序:
+
+1. 从当前页面静态 script 提取 `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots` 的完整调用上下文:method、data 字段名、success handler 如何给日期和 Slot 加 class。
+2. 读取 `#btnPrenotaNoOtp`、日期元素、`.fascia`、月份 `Prev/Next` 的 direct handler;只读取源码,不触发事件。
+3. 若 DevTools 仍保留这三个已发生请求,只记录 method、status、type、response 顶层类型/字段名和数组长度;不复制值、完整 payload、Cookie 或 Token。
+
+机械完成标准:能用 handler/response schema解释 `disabled`、`availableDay`、`notAvailableDay`、`selected`、`.fascia.act` 和 `(0)` 的角色;三个 XHR 的 method/path/status/type 可分类;新增请求=0,所有点击=0,最终确认=0。若关机恢复导致旧 Network response 不可读,则明确记录“静态合同已关闭、真实 response 待下一次自然页面加载”,不刷新页面补证。
+
+当前结果:
+
+- 三个时段的负向 class 已关闭:均为 `.fascia.notAvailableFascia`。
+- `.fascia.act` 的生成链已关闭:document-level delegated click 对任意 `.fascia` 无条件添加 `act`,因此 `act` 本身不是可用性证据。
+- `#btnPrenotaNoOtp` 的 delegated handler、无 Slot 防线、最终 POST 字段和 `errorMessage/url` callback 已关闭。
+- 日期 class 映射已关闭:所有 `.day` 先 disabled;`slot >= 0` 添加 `availableDay` 并移除 disabled,否则添加 `notAvailableDay`。零值也属于日期层正向分支,不能代表可预约 Slot。
+- 具体元素 `directHandlers=[]` 与 delegated handler 并不冲突;它说明采集器必须同时检查 document-level events/inline scripts,不能只看元素自身。
+- 初始 inline script 和 `stormcaster.js` 没有三个完整 endpoint 名;后续 Sources 全局搜索已在其他业务源码中定位 Availability 与 TimeSlots 的动态方法片段。
+- Availability 的 POST/JSON 请求、核心 response 字段、日期构建和 class 合同已由 E27-E31 关闭;TimeSlots 的 POST/JSON 请求键、双层 response、核心 item 字段、时间/数量/daily ID 和负向 class 由 E33-E35 关闭。
+- 这是 E42 之前的阶段结论。E38–E42 随后关闭逐 Slot hidden 模板、final serializer 和 selected 日期;E43 关闭正向数量与 DOM。当前仍缺 ServerInfo 合同、长期幂等性和正向 Slot 点击后的唯一 active 验证。
+
+### 10.12 外部 Calendar 脚本与既有 XHR response 只读取证(进行中)
+
+仍然不刷新、不点击、不调用 endpoint。此前 initiator 指向过 `stormcaster.js`,但 E25 已证明三个 endpoint 名在该文件中均无匹配;这条线索只说明调用经过或被归因到该脚本,不能说明业务字符串定义在那里。
+
+下一步改为 DevTools Sources 全局搜索,而不是继续猜文件名。依次搜索完整 endpoint 名、去掉 `Retrieve` 后的核心词,以及公共前缀 `urlServizio`,定位定义或字符串拼接位置后提取:
+
+1. 三个 endpoint 的 method 和 request 字段名。
+2. success handler 读取哪些 response 字段。
+3. 什么条件给日期移除 `disabled`、添加/移除 `notAvailableDay`。
+4. 什么条件生成普通 `.fascia` 与 `.notAvailableFascia`,括号中的数字来自哪个字段。
+5. Network 若仍保留既有请求,只记录 status、response 顶层类型/字段名、数组长度;不复制业务值或完整 payload。
+
+机械完成标准:外部脚本 source/函数名可定位;三个 XHR 的 method 与字段 schema 可由静态源码或既有 Network 记录交叉证明;负向 Slot 和未来正向 Slot 可以用语言无关规则区分;新增请求=0、所有点击=0、最终确认=0。若 DevTools 已丢失 response,只关闭静态合同并明确缺口,不刷新补证。
+
+当前进度:
+
+- 全局搜索已定位并完整读取 `CaricaTimelineOrizzontale(...)`,源码文件名尚未记录。
+- 函数把 `RetrieveCalendarAvailability` 保存为 `Metodo`,动态拼接得到直接源码证据。
+- WebMethod 参数键已部分关闭:`_Servizio` 与 `selectedDay`;后者取 `_Oggi`。success callback 另收 `GiornoDaSelezionare=_Oggi`,不是服务端请求字段。
+- `EseguiAsync` 已完整读取:Availability 的 method/path/JSON content type、请求键和 success 传递已经关闭。
+- error 分支只无参调用 callback,网站客户端没有保留 status/body;插件设计必须补回诊断能力。
+- `CostruisciTimelineOrizzontale` 已完整读取:双层 JSON、`DateLibere/SlotRimanenti` 和数组到时间线的构建链已经关闭。
+- `InizializzaTimelineOrizzontale` 已完整读取:事件去重、初始化顺序、目标日期查找、缺失时回退首日和程序化 `.click()` 已关闭。
+- 人工点击日期为 0 仍出现 TimeSlots 已有合理的上游解释,但 `.click()` 到请求之间的 handler 尚未关闭,不能把推断写成完整 HTTP 合同。
+- `DisabilitaGiorniSenzaPrenotazioni` 已完整读取:所有日期先 disabled;匹配后 `slot >= 0` 进入 `availableDay` 并移除 disabled,否则进入 `notAvailableDay`。零值也可进入日期层,日期层不能代替 Slot 层。
+- 日期 class 合同已关闭,但 `SlotRimanenti` 类型/业务语义、重复记录处理和旧 class 生命周期仍未由 response 样本或上游 DOM 重建证明。
+- `AbilitaInputAsincroni` 已完整读取:只对非 selected 的 `data-async=true` 元素执行 disabled/enabled CSS class 切换;没有 event registration、click 或网络调用。
+- 此结果否定了“该函数负责绑定 TimeSlots handler”的先前候选解释;真正 handler 仍需全局定位。
+- 全局搜索 `RetrieveTimeSlots` 已命中并完整读取 `CaricaTimelineVerticale`:当前 method/path/JSON keys、DOM runtime ID 来源和 success callback 名已关闭。
+- `_ContenutiEventi` 是 callback context,不进入 request;配置 `service_id=4937` 与页面 `#idServizio` 不得混用。
+- `CostruisciSchedaFasce` 已完整读取:response 的双层 JSON/内层数组、`unicaFascia`、selectedContent 追加和后续 timeline 构建已关闭。
+- 空数组仍继续初始化;数组非空/唯一 item 都不是有号判据。
+- `CreaFasce` 已完整读取:`SlotRimanenti < 0` 生成负向 class,`SlotLiberi` 生成括号数字,起止时间和 daily calendar ID 字段已关闭;唯一非负 item 自动 `act`。
+- E43 已进一步证明 `SlotLiberi=1 / SlotRimanenti=0` 对应普通 `fascia`、无红点和 `(1)`;正向必须同时满足数量与 DOM,仍不能只凭非负值或单个 class。
+- Sources 全局搜索 `TemplateFasce` 曾为 0;恢复现场后已取得原文,并与脱敏渲染 DOM 交叉关闭 Slot 的 daily ID、class、时间、数量和重复 id 生成规则。
+- `document.scripts` 已唯一命中当前 final handler,关闭 active Slot 到最终 POST daily ID/时间/日期的序列化表达式。
+- 当前全部 `.selected` 的 DOM 顺序、`data-date` 存在性和值相等性已关闭;原生 handler 当前会取与内容卡片一致的 `.events` 日期 link。
+- E43 已取得自然正向日期和 Slot,E44 又以一次安全选择关闭唯一 active、后代、时间和日期一致性;两步均保持 `InsertNewBooking=0`。E1–E44 已回灌通用 Schengen R3 设计;负责人随后批准并已验证 CS1 纯协议与 CS2 通用路线接线。强 Query、最终按钮和 durable fence 仍由独立 Q-CAL/FINAL/FENCE Gate 禁止触达。
+
+## 11. 后续实现的机械完成标准
+
+未来取得代码修改授权后,Italy 修复至少应满足:
+
+1. `create_session()` 由真实 URL 和认证 DOM 双重判断成功,不依赖猜测页面。
+2. Dublin `1321` 和 Hong Kong `4937` 通过 VFS/BLS 风格的 `routing_key → apt_configs` 解析;源码没有 Hong Kong/Dublin 城市分支。
+3. 默认 `services_probe` 的测试证明 OTP/AVANTI/文件上传/final 全为 0;显式 `calendar` 模式则证明每个 Session 的准备阶段 OTP=1、AVANTI=1、final=0,后续每轮 probe 的三者增量都为 0。
+4. 无号、登录失效、限流、CAPTCHA、目标服务缺失和页面结构变化产生不同结果。
+5. 若采用准备型 Calendar Query,Q-CAL Gate 证明准备前后预约列表不变,后续重复 probe 不发邮件、不重复 AVANTI、不占用名额,并能在完整配置日期范围内返回真实正向日期,快照 `times=[]`。
+6. `200 + bookingForm` 只记录诊断 stage,不冒充具体日期,也不默认触发生产 OrderBooker;弱信号仅作为显式的 Discovery/人工告警能力。
+7. Book 每次执行都在用户自己的 Session 中重进服务,选择单人和旅游,并重新查询日期和时间。
+8. 可见 select 由网站脚本按真实时机同步 hidden:单人 `1/0` 在 change 时完成,`Turismo=42` 在 `AVANTI` 内的 `saveDdlValue()` 完成;插件不提前手工写 hidden,也不伪造 multipart payload。
+9. 字段能力来自真实 DOM;Hong Kong 不上传文件,其他 Sede 只有出现并验证文件控件后才启用上传。
+10. Turnstile 保持同一浏览器上下文并沿网站原生调用链执行;Hong Kong 成功真实 POST 未观察到 reCAPTCHA 字段,因此不主动调用 `getCaptchaToken()`;未来 DOM/handler 改变时重新发现,出现人工 challenge 时停止并交给用户。
+11. OTP 发送和敏感资料传输具有明确授权边界,失败后不会盲目重复。
+12. Calendar 解析器扫描完整配置日期范围,不能因默认月份无号提前结束。Query 对 Availability 要求 `SlotLiberi>0`、`SlotRimanenti>=0`,只发布日期且 `times=[]`。Book 在用户 Session 中额外解析 TimeSlots:合法时间、唯一 daily ID、无 `notAvailableFascia`/`dotRed`,selected 两层日期一致;E43 的 `1/0` 必须判正向,`0/-1` 必须判负向,其他组合 fail-closed。点击后还要断言唯一 `.fascia.act` 仍对应同一正向 item。
+13. `AVANTI`、Calendar、Slot 和最终提交逐 Gate 取得 method/path/schema;最终 `InsertNewBooking` 有完整成功/失败响应合同、幂等保护和结果恢复策略,结果不明时不会自动重试。
+14. Dublin 无号 fixture、Hong Kong 8 月负向 fixture 与 E43 十月正向 fixture 运行同一套插件路径;聚焦测试、语法检查和敏感信息扫描全部 exit 0。
+
+## 12. 当前验证记录
+
+### 12.1 初始文档整理实际执行
+
+- 读取 `phase-gated-delivery` 规范,确认只允许文档编辑和本地验证。
+- 读取被引用的调研任务,确认浏览器控制失败和未执行操作的边界。
+- `git status --short`:exit 0;确认已有用户修改,未覆盖、清理或回滚。
+- `rg --files docs test tools plugins ...`:exit 0;确认原先没有独立 Italy 调研文档。
+- `rg` 检查 `plugins/ita_plugin.py` 的 Session、Query、Book、OTP 和历史残留:exit 0。
+- 分段读取 `plugins/ita_plugin.py`、`vs_types.py`、`sentinel.py`、`booker.py`、Italy 测试和调试工具:exit 0。
+- `git log --follow -- plugins/ita_plugin.py`:exit 0。
+- `git show 06a9291^:plugins/ita_plugin.py` 配合 `rg`:exit 0;只作为历史代码线索。
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m unittest test.test_ita_plugin test.test_debug_ita_session`:exit 0;7 个离线测试全部通过,测试输出明确标记 `external_request=not-performed`。
+- 使用 `compile(...)` 检查 `plugins/ita_plugin.py` 和 `tools/debug_ita_session.py`:exit 0,输出 `compile: ok`。
+- 敏感模式扫描:exit 0;本文没有写入 Cookie、Authorization、密码、OTP 值或 OAuth 动态值。
+- `git diff --check -- docs/ita_plugin_discovery.md`:exit 0;由于本文是未跟踪新文件,又执行 `git diff --no-index --check /dev/null docs/ita_plugin_discovery.md` 并将“仅存在新文件差异”的 exit 1 归一化,最终 exit 0、无 whitespace error 输出。
+- 本次没有打开网站、登录、点击 `Prenota`、发送 OTP 或提交预约。
+- 本次没有修改 Python、JSON、测试或已有文档。
+
+### 12.2 Gate 2 实际执行
+
+- 用户确认页面仍为已登录 Dublin `/Services`,打开 Network、启用 Preserve log 并清空记录。
+- 只点击一次 `Visti Schengen e Nazionali` 的 `Prenota`;没有重试。
+- 已观察 `GET /Services/Booking/1321` → `302 Found` → `Location: /Services` → `GET /Services` → `200`。
+- 页面弹出“所选服务名额已耗尽”,DOM 中 `#WNotAvailable` 为 hidden input 且 value 非空。
+- `BookingCalendar` 过滤结果为 0;`otp` 过滤结果为 0。
+- POST 过滤结果为 4,均为相同动态 UUID path、`200 text/plain`、`Server: rdwr`;没有预约业务 POST。
+- 没有填写资料、上传文件、选择日期时间、提交表单或最终确认。
+- 没有读取或保存 Cookie、Token、OTP、Payload 或个人资料。
+
+### 12.3 历史运行证据
+
+- 用户执行 `python tools/debug_ita_session.py` 后,浏览器到达公开首页并点击登录入口。
+- 当次运行因 `ItaPlugin` 缺少 `_random_sleep` 失败,并执行了清理。
+- 当前工作树包含 `_random_sleep` 的本地修复;本次已验证相关离线测试,但不把真实登录、Query 或 Book 标记为已验证。
+
+### 12.4 Phase 1 实现验证
+
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m unittest -v test.test_ita_plugin test.test_debug_ita_session`:exit 0;15 个离线测试全部通过。
+- `compile(...)` 检查 `plugins/ita_plugin.py`、两份聚焦测试和 `tools/debug_ita_session.py`:exit 0;4 个文件均可编译。
+- `jq empty config/config_sentinel.json config/config_booker.json`:exit 0;两份配置均为合法 JSON。
+- 两条 `jq -e` 定向断言:exit 0;两份 `pernotami.ie.it` 配置都且仅有一组,`service_id` 均为 `1321`。
+- 对 `book()` 方法片段执行 SHA-256 基线比较:exit 0;方法内容与 Phase 1 修改前一致。
+- `git diff --check` 检查已跟踪改动,并用 `git diff --no-index --check` 检查新增测试和本文:exit 0;没有 whitespace error。
+- 对本文执行 Cookie、Authorization、JWT 和动态 UUID 值模式扫描:exit 0;未发现敏感值。
+- 第一次并行验证包装器在命令真正执行前因 JavaScript 模板插值语法错误退出;没有运行测试、没有修改文件。修正包装器后一次执行得到上述结果。
+- 本阶段没有执行真实网站自动 Query、自动登录或 Book;真实无号证据来自 Gate 2 的单次人工受控点击。
+
+### 12.5 Gate 1 Discovery 与本地实现验证
+
+- 用户在新无痕窗口打开 DevTools、保留 Network,并从公开根路径点击一次登录入口。
+- 正确 IAM 页面 path 为 `/signin/`;动态 query 和 fragment 未写入本文。
+- 只读 DOM 元数据显示用户名为 `callback_1`、密码为 `callback_2`、提交按钮为 `button[type=submit]`;动态数字 ID 不纳入合同。
+- 用户手动输入凭据并只提交一次,最终到达 `/UserArea`。
+- `/UserArea` 只读 DOM 统计为 `.app-menu=1`、`/Services` 链接数为 1。
+- Network 列表观察到 `authenticate...` Fetch 返回 200;没有查看 Payload 或 Response。
+- “文档”分类和 `UserArea` 文本筛选连续两次没有取得 callback 请求,按纪律停止相同策略;完整文档跳转链仍未验证。
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m unittest -v test.test_ita_plugin test.test_debug_ita_session`:exit 0;20 个离线测试全部通过。
+- 用户随后执行修改后的 `python tools/debug_ita_session.py`:插件在 `/signin/` 等待表单渲染,识别稳定字段后只提交一次凭据,下一 Router Step 到达 `/UserArea`。
+- 真实输出包含 `ITA_SESSION_OK url=https://prenotami.esteri.it/UserArea`、`ITA_SESSION_CLEANUP_OK` 和 `EXIT_CODE=0`。
+- 本次真实调试没有调用 Query、Book、Services、OTP 或预约流程;账号标识、密码、动态 OAuth 值、端口、指纹和实例 ID 均未写入本文。
+
+### 12.6 单次自动 Query 工具的离线验证
+
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m unittest -v test.test_debug_ita_query test.test_ita_plugin test.test_debug_ita_session`:exit 0;33 个离线测试全部通过。
+- 测试通过 AST 断言 `tools/debug_ita_query.py` 恰好存在一次 `.query(...)` 调用且不存在 `.book(...)` 调用。
+- 无号 fixture:exit 0,输出 `ITA_QUERY_NONE_AVAILABLE`,Query 调用次数为 1,清理成功。
+- property-only hidden value 和已验证意大利语可见弹窗 fixture 都映射为 `NoneAvailable`。
+- 近似但语义不同的意大利语以及未知可见弹窗不会被猜测为无号。
+- 无号结果只输出语言无关的 `NoAvailable` 状态,不绑定固定中文;未知弹窗诊断会脱敏邮箱、长数字和长 token。
+- 进入可能有号页面的 fixture:exit 4,输出 `ITA_QUERY_SAFE_STOP`,Query 调用次数为 1,清理成功且没有重试。
+- 意外返回 `Available` 的防御 fixture:exit 4;即使底层实现未来改变,也不会由调试工具继续进入 Book。
+- 未知异常 fixture:exit 1;URL 中的 query、fragment、OAuth 动态值已脱敏,且不保存截图。
+- 本节证明本地控制流与安全边界;两次真实执行结果分别见 §2.6 和 §2.7,更新后的无号分类已经获得真实验证。
+
+### 12.7 第二次真实自动 Query 验证
+
+- 用户在本地交互输入凭据,执行更新后的单次 Query 工具。
+- 输出 `ITA_QUERY_NONE_AVAILABLE service_id=1321 status=NoAvailable`。
+- 输出 `ITA_QUERY_CLEANUP_OK`。
+- Shell 输出 `EXIT_CODE=0`。
+- 没有执行 Book、OTP、表单、日历或最终确认。
+- 账号标识、密码、动态 OAuth 值、端口、指纹和实例 ID 均未写入本文。
+
+### 12.8 Booking Form 只读采集器验证
+
+- 第一次聚焦测试发现字段名 `__RequestVerificationToken` 被通用文本脱敏规则误判为秘密值,并且 `None` 被字符串化;测试 exit 1。
+- 修正为独立的 DOM 元数据脱敏规则后,第二次聚焦测试 exit 0;33 个测试全部通过。同一错误只修复一次。
+- safe-stop fixture 输出 form action path、method、字段名和按钮元数据,Query 调用次数仍为 1,Book 调用次数为 0。
+- fixture 故意注入字段 `value`、按钮 `value`、未知键和模拟个人信息;最终输出均不包含这些内容。
+- 静态测试确认采集脚本不包含 value、innerHTML、outerHTML、Cookie、Web Storage、click 或 submit 读取/动作。
+- 这些测试只证明本地采集器合同。Hong Kong 真实 Booking Form 随后由人工同边界采集,见 §2.10 和 §12.9;尚未由自动采集器在真实网站验证。
+
+### 12.9 Hong Kong Gate HK-1 至 HK-3 实际验证
+
+- HK-1:用户在已登录 Hong Kong `/Services` 执行脱敏只读 DOM 采集;确认 Sede、9 个服务行、单页分页和唯一通用签证入口 `/Services/Booking/4937`。
+- HK-1 附件定向 `jq -e` 断言:exit 0,输出 `true`;确认 path 为 `/Services`、Sede 包含 Hong Kong,且 `4937 / Visti Nazionali e Schengen` 精确匹配一行。
+- HK-2:用户明确授权后只点击一次 `4937`;观察 `GET /Services/Booking/4937`、`200 document`、无 Location、最终仍为 Booking 页面。
+- HK-2:初始化 XHR 为 `/Services/GetBookingTypes` 和 `/Services/GetDdlValuesByID/?id=34`,均为 200;BookingCalendar=0,OTP=0。
+- HK-3:用户执行只读 DOM 采集;确认 booking form 为 `POST /Services/Booking/4937`、`multipart/form-data`,单人 `1`、`Turismo=42`、OTP/Privacy/Turnstile/`AVANTI` 存在,当前没有文件控件。
+- HK-3 附件定向 `jq -e` 断言:exit 0,输出 `true`;上述关键 form 和控件断言全部成立。
+- 三个 Gate 均未读取 input/hidden value、Cookie、Token、OTP、个人资料或 Request Payload。
+- 三个 Gate 均未发送 OTP、点击 `AVANTI`、访问 Calendar、选择日期时间或执行预约。
+
+### 12.10 2026-08-28 证据文档更新验证
+
+- `git status --short`:exit 0;确认工作树原有修改全部保留,本文仍为未跟踪文档,没有修改插件、配置、测试或工具。
+- 分段读取本文和相关 Italy 设计文档:exit 0;选择本文作为网站证据的单一事实来源,没有复制 Hong Kong 专用设计文档。
+- 8 个 `rg -q` 内容断言:全部 exit 0;覆盖 E14、`GET 4937`、单人 `1`、`Turismo=42`、Turnstile、`EntryAvailable` 和下一 Gate。
+- code fence 偶数断言:exit 0。
+- 二级标题唯一性断言:exit 0。
+- trailing whitespace 反向扫描:exit 0,无匹配。
+- 用户账号标识、邮箱域和 Bearer 值反向扫描:exit 0,无匹配。
+- `git diff --check -- docs/ita_plugin_discovery.md`:exit 0。由于本文是未跟踪文件,另以 `git diff --no-index --check /dev/null ...` 的输出为准检查全文。
+- 本轮是纯文档变更,没有运行 Python 测试;理由是没有修改任何可执行代码。
+
+### 12.11 Hong Kong Gate HK-4 静态 handler 验证
+
+- 用户在同一 `/Services/Booking/4937` 页面执行脱敏只读脚本,没有点击按钮。
+- `#otp-send` 的 inline/native onclick 均为 `sendOTP()`,没有 jQuery handler。
+- 静态 endpoint 为 `GET /BookingCalendar/GenerateOTP?ServiceID=4937`;本 Gate 没有真正发送该请求。
+- callback 相关代码显示成功分支执行 `startOtpTimer(120)`,失败分支显示 `#IdOtpInvalid`;完整 response 判据尚未采集。
+- `#btnAvanti` 的 jQuery handler 调用 `CheckMaxFileSize()`、`saveDdlValue()`、原生确认框和 `bookingForm.submit()`。
+- endpoint 列表还包含 `/Services/GetRelationshipType`;本次 Network 没有该请求,只作为通用 companion 候选记录。
+- 输出中的邮箱已脱敏;没有记录 Cookie、Token、Turnstile value、个人资料或 OTP。
+- 没有执行 GenerateOTP、`AVANTI`、Calendar、Slot 或最终确认。
+
+### 12.12 Hong Kong Gate HK-5 关键函数与 CAPTCHA 静态验证
+
+- 用户在同一 `/Services/Booking/4937` 页面执行脱敏只读采集;`#otp-send` 和 `#btnAvanti` 的状态快照均为 enabled,但没有点击。
+- 附件结构化断言确认:path、按钮状态、四个目标函数、Turnstile callback 和 reCAPTCHA Enterprise `BOOKING` 代码均存在。
+- `sendOTP()` 的成功判据为 HTTP 200 且 raw responseText 精确等于 `"SENT"`;成功后执行 `startOtpTimer(120)`。
+- 非 200、网络错误和超时没有明确静态恢复分支;这被记录为结果不明且禁止自动重试,不被包装成“无号”。
+- `saveDdlValue()` 已确认 `ddls_0 → hiddenSelezionato_0`;没有确认 `typeofbookingddl → IdTipoPrenotazione`。
+- `CheckMaxFileSize()` 的阈值为 1 MiB;当前页面没有文件控件,因此遍历为空并返回 `true`。
+- Turnstile callback 启用 `AVANTI`,expired/timeout 禁用并 reset;另有 reCAPTCHA Enterprise `BOOKING` token 函数,但真实调用点仍未闭环。
+- 没有读取 Cookie、运行时 CAPTCHA Token、hidden value、个人资料或 OTP;没有执行 GenerateOTP、`AVANTI`、Calendar、Slot 或最终确认。
+- 首次附件 `jq -e` 断言错误地假设存在顶层 `inlineScripts`,返回 exit 5;随后只读列出真实 keys,确认 reCAPTCHA 片段位于 `turnstileContexts`,修正后的完整结构化断言返回 exit 0、输出 `true`。没有进行第三次同类尝试。
+- 文档关键内容断言返回 exit 0:覆盖 E19、精确 `SENT` 判据、旅游 hidden 同步、文件检查、Turnstile、reCAPTCHA 和下一 Gate。
+- code fence 偶数、二级标题唯一性、trailing whitespace 和敏感信息反向扫描全部 exit 0。
+- `git diff --check -- docs/ita_plugin_discovery.md` 返回 exit 0。本文为未跟踪文件,第一次 `git diff --no-index --check` 的 exit 1 来自“文件有差异”的 no-index 语义且无输出;改为以 `--check` 输出是否为空作为判据后返回 exit 0。
+- `git status --short` 返回 exit 0;工作区已有代码、配置、测试、工具和其他文档修改全部保留。本 Gate 只更新本证据文档,没有运行 Python 测试,理由是未修改可执行代码。
+
+### 12.13 Hong Kong Gate HK-6 预约类型与 submit 静态验证
+
+- 用户在同一 `/Services/Booking/4937` 页面执行脱敏只读采集;没有触发 change、click、submit 或网络请求。
+- 当前 HK-6 附件与 E16 DOM 附件的两组 `jq -e` 交叉断言均返回 exit 0、输出 `true`。
+- `typeofbookingddl` 的 direct jQuery change handler 调用 `ShowCompanions()` 和摘要更新函数。
+- `ShowCompanions()` 的单人分支把 `numAccSelected` 设为 `0`,随后把 DOMPurify 处理后的选择写入 `hiddenTipoPrenotazione`。
+- E16 交叉验证 `hiddenTipoPrenotazione name=IdTipoPrenotazione`、`numAccSelected name=NumAccompagnatoriSelected`;单人 `1/0` 同步链闭环。
+- `bookingForm` 没有 inline/native/direct jQuery submit handler;`AVANTI` 的唯一已观察 direct jQuery handler 直接调用 form submit。
+- `getCaptchaToken()` 的定义存在,但在采集到的 inline script 上下文及预约类型、form、`AVANTI` 三个关键元素 handler 中没有观察到调用点;没有将“未观察到”夸大为“全站不存在”。
+- 没有读取 Cookie、运行时 CAPTCHA Token、hidden 当前值、个人资料、Request Payload 或 OTP;没有发送 OTP、提交 `AVANTI`、进入 Calendar 或执行预约。
+- 文档 HK-6 合同和初见审查定向断言均返回 exit 0;覆盖 E20、§2.13、三条 hidden 映射、未引用候选分类、HK-7 单次副作用边界和不主动调用原则。
+- code fence 检查输出 `26`、exit 0;二级标题唯一性、trailing whitespace、敏感信息反向扫描、`git diff --check` 和全文 no-index whitespace 输出检查全部 exit 0。
+- `git status --short` 返回 exit 0;工作区已有修改全部保留。本 Gate 只更新本证据文档,没有运行 Python 测试,理由是未修改任何可执行代码。
+
+### 12.14 Hong Kong Gate HK-7 提交前预检
+
+- 用户在真实 `/Services/Booking/4937` 页面手工选择单人和旅游后执行只读预检;没有点击 OTP 或 `AVANTI`。
+- path、预约类型 visible/hidden=`1/1`、同行人数 hidden=`0`、旅游 visible/hidden=`42/0`。
+- OTP 与 `AVANTI` 均 enabled;Turnstile 字段数量为 1,reCAPTCHA 字段数量为 0;没有读取任何 token value。
+- `purposeHidden=0` 与 `saveDdlValue()` 只在 `AVANTI` handler 内执行的源码一致。此前预检把它预期为 `42` 的标准有误,已在同一 Gate 内停止并修正,没有继续消耗 OTP。
+- 当前仍满足 HK-7 副作用预算:GenerateOTP=0、Booking Form POST=0、Calendar/Slot/最终确认=0。
+- HK-7 预检合同断言、`git diff --check`、全文 no-index whitespace、二级标题唯一性、trailing whitespace 和敏感信息扫描全部 exit 0;code fence 输出 `28`、exit 0。
+- 本次只更新证据文档,没有运行 Python 测试;原因是没有修改可执行代码。
+
+### 12.15 Hong Kong Gate HK-7 真实 OTP 与 POST
+
+- 用户先勾选 Privacy,再只点击一次 OTP;该顺序没有阻止 OTP 请求。
+- GenerateOTP 请求数量 1:GET、200、Response 类别 `SENT`;注册邮箱收到验证码。没有在本文记录验证码。
+- 用户手工输入 OTP 后只点击一次 `AVANTI`;Booking Form POST 数量 1:POST `/Services/Booking/4937`、302 document。
+- 302 Location 为 `/BookingCalendar?selectedService=Visti%20Nazionali%20e%20Schengen`。
+- Console 确认最终 href 为 `/BookingCalendar?selectedService=Visti%20Nazionali%20e%20Schengen`、pathname=`/BookingCalendar`、title=`Calendar - Prenot@Mi`。
+- Network 确认 Calendar 主文档为 GET、200、Document;先前 `/Services/Booking/4937` 是 POST request path,不是 final path,冲突已消除。
+- POST 字段只报告名称:观察到 `cf-turnstile-response`,没有观察到 `g-recaptcha-response`;没有复制任何 token 或完整 payload。
+- 日期点击=0、时间点击=0、最终确认=0;没有自动重发 OTP 或重提 POST。
+- Calendar 校准后 HK-7 关键合同和陈旧结论反向断言均 exit 0;`git diff --check`、全文 no-index whitespace、二级标题唯一性、trailing whitespace 和敏感信息扫描全部 exit 0;code fence 输出 `32`、exit 0。
+- `git status --short` 返回 exit 0;工作区原有修改全部保留。本次只更新证据文档,没有运行 Python 测试,原因是没有修改可执行代码。
+
+### 12.16 Hong Kong Gate HK-8 Calendar 零点击采集
+
+- 用户关机后恢复浏览器,当前页面仍为 `/BookingCalendar?selectedService=...`;采集脚本只读取 DOM、Resource Timing 和 inline script,没有点击或调用函数。
+- 附件定向 `jq -e` 断言返回 exit 0、输出 `true`:path/title、唯一 logout form、42 个日期格全部含 `disabled`、`31/08/2026` 的 `notAvailableDay active`、默认 selected 日期、三个 `(0)` 时段和 final button 元数据全部存在。
+- 同一断言确认三个 Resource Timing XHR path 精确为 `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots`。
+- 同一断言确认静态脚本包含 `POST /BookingCalendar/InsertNewBooking` 和 `idCalendarioGiornaliero`、`selectedDay`、`selectedHour` 三个字段名。
+- Resource Timing 不包含 method/status/response schema,因此没有把 Git 历史中的 POST method 或旧 payload 当作当前网站事实。
+- 日期点击=0、月份点击=0、时间点击=0、最终按钮点击=0;新增业务请求=0;没有再次发送 OTP 或提交 Booking Form。
+- 文档内容断言、陈旧结论反向扫描、敏感信息扫描、二级标题唯一性和 trailing whitespace 检查全部 exit 0;code fence 数量为 36,exit 0。
+- `git diff --check` 与未跟踪文件全文 no-index whitespace 输出检查均 exit 0。
+- 第一次组合验证包装器在命令执行前因 JavaScript 模板字符串中的 Markdown 反引号导致 `SyntaxError`;没有运行任何 shell 检查、没有修改文件。移除该包装器歧义后的第二次组合验证 exit 0,没有进行第三次同类尝试。
+- 本 Gate 只更新本证据文档,没有修改插件、配置、测试或工具,也没有运行 Python 测试;理由是没有修改可执行代码。
+
+### 12.17 Hong Kong Gate HK-9 Slot 与 final handler 零点击采集
+
+- 用户在当前 `/BookingCalendar` 执行只读脚本;输出仍为 `Calendar - Prenot@Mi`,没有点击或请求。
+- 三个时段 DOM 均为 `div.fascia.notAvailableFascia`,文字分别包含三个时间范围和 `(0)`;负向分类不再依赖意大利语文案。
+- `directHandlers=[]`;inline script 证明实际使用 document-level delegated handlers,这两个事实一致而非证据冲突。
+- `.fascia` delegated click 会移除所有旧 `act`,再无条件给当前 `.fascia` 添加 `act`;源码没有排除 `notAvailableFascia`。
+- `#btnPrenotaNoOtp` delegated click 在没有 `.fascia.act` 时停止;否则读取第一个 active Slot 和第一个 selected 日期,调用 `POST /BookingCalendar/InsertNewBooking`。
+- 旧 `#btnPrenota → GeneraOTP(true)` 代码已注释;当前活跃 Calendar final handler 不生成第二次 OTP。
+- 当前静态 JSON callback 使用 `errorMessage` 和 `url`;`error` callback 被输出截断,没有补猜。
+- 日期点击=0、月份点击=0、时间点击=0、最终按钮点击=0;新增业务请求=0;没有再次发送 OTP 或提交任何表单。
+- 关键证据摘录的 `jq -n -e` 合同断言通过;文档 E24、负向 Slot、delegated handler、response 字段、下一 Gate 和初见审查内容均已逐项确认。
+- 第一套组合文档检查返回 exit 1,原因是验证脚本要求精确短语“插件必须在网站之上增加业务不变量”,而正文实际写的是语义正确的“框架必须在网站之上增加业务不变量”;这是测试断言过窄,不是文档缺陷。
+- 按纪律只做一次分项诊断:命令 exit 0;除上述错误期望外,内容项全部存在;陈旧结论、trailing whitespace、敏感信息扫描均通过;code fence=38 且为偶数;二级标题唯一;`git diff --check` 与全文 no-index whitespace 检查均通过。
+- 补记“Calendar 不发送第二次 OTP”后,第一条正则断言因未转义 `GeneraOTP(true)` 的括号返回 exit 1;改用 fixed-string 分项诊断后 exit 0,同时 `git diff --check` exit 0。没有进行第三次同类尝试。
+- 本 Gate 只更新本证据文档,没有修改插件、配置、测试或工具,也没有运行 Python 测试;理由是没有修改可执行代码。
+
+### 12.18 Hong Kong Gate HK-10 XHR 源码归因校准
+
+- 用户在 DevTools Sources 中打开 `stormcaster.js`,依次搜索 `RetrieveServerInfo`、`RetrieveCalendarAvailability`、`RetrieveTimeSlots`,三个结果均为 0。
+- 没有因为 Network initiator 名称而继续声称该文件包含业务 endpoint;文档已把“很可能位于 stormcaster”更正为待全局搜索。
+- 本步骤没有刷新页面、执行 endpoint、点击日期/Slot/final button,也没有修改插件代码。
+
+### 12.19 Hong Kong Gate HK-11 availability 函数定位
+
+- 用户通过 DevTools Sources 全局搜索命中 `CaricaTimelineOrizzontale(_Mese, _Anno, _Oggi, _Servizio, _GiornoDaSelezionare)`。
+- 已观察函数内 `Metodo='RetrieveCalendarAvailability'`;这解释了 endpoint 可由公共前缀与方法片段组合,而不必出现在 Network initiator 文件中。
+- 本次只提供函数开头,没有执行函数、刷新页面或产生业务请求;method/payload/response/DOM handler 继续标为未验证。
+- 落盘检查发现一条陈旧的重复 `E26/§12.19` 曾写成“全局搜索为 0”,与最新命中事实冲突;已删除该陈旧条目。证据编号、三级标题唯一性、陈旧文本反向扫描和 whitespace 检查均 exit 0。
+
+### 12.20 Hong Kong Gate HK-12 availability 编排函数
+
+- 用户提供 `CaricaTimelineOrizzontale(...)` 从声明到闭合大括号的完整源码。
+- `Parametri[0]` 注释为 WebMethod 参数,键为 `_Servizio` 与 `selectedDay`;`Parametri[1]` 注释为 success callback 参数,键为 `GiornoDaSelezionare`;`Parametri[2]` 是空 error callback 参数。
+- `selectedDay` 和 `GiornoDaSelezionare` 都取 `_Oggi`;`_Mese`、`_Anno`、`_GiornoDaSelezionare` 在当前函数体内未引用。
+- 执行链为 `EseguiAsync(Metodo, Parametri, CostruisciTimelineOrizzontale, StampaErroreInConsole)`;当前没有执行任何函数或请求。
+- 第一条内容检查因正则把函数调用的括号当作分组而 exit 1;改用 fixed-string 后,E27、函数/调用链、§12.20、证据编号与三级标题唯一性、whitespace 检查全部 exit 0。没有进行第三次同类尝试。
+
+### 12.21 Hong Kong Gate HK-13 Availability HTTP 合同
+
+- 用户提供完整 `EseguiAsync(Metodo, Parametri, MetodoSuccess, MetodoError)`。
+- URL 为 `urlServizio + Metodo`;结合当前页面 `urlServizio='/BookingCalendar/'` 和 `Metodo='RetrieveCalendarAvailability'`,静态 path 为 `/BookingCalendar/RetrieveCalendarAvailability`。
+- 请求固定为 POST;body 是 `JSON.stringify(Parametri[0])`;content type 为 `application/json; charset=utf-8`;jQuery 按 JSON 解析 response。
+- success 原样调用 `MetodoSuccess(response, Parametri[1])`;error 丢弃 response 并无参调用 `MetodoError()`;没有观察到内建重试。
+- 本步骤没有执行 AJAX、刷新页面、点击 Calendar 或修改插件代码。
+- Availability HTTP 合同、E28/§12.21、证据编号与三级标题唯一性、陈旧冲突反向扫描、敏感信息和 whitespace 检查全部 exit 0;没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.22 Hong Kong Gate HK-14 Availability response 与日期构建
+
+- 用户提供完整 `CostruisciTimelineOrizzontale(JsonGiorniTimelineOrizzontale, Parametri)`。
+- callback 对 response 再执行 `$.parseJSON`;内层数组元素读取 `DateLibere` 和 `SlotRimanenti`。
+- 空数组写 `GiorniDisponibili=0`;非空时该字段表达第一日期与旧 `DataDisponibilita` 的比较状态,不是 Slot 数量。
+- 每项都被写为 `date@slots` 并交给 `CreaGiorno/CreaEventiGiorno`,没有在本函数按 `SlotRimanenti` 过滤;最后调用 `InizializzaTimelineOrizzontale`。
+- 本步骤没有执行 callback、AJAX、刷新页面或点击 Calendar,也没有修改插件代码。
+- 第一条陈旧结论扫描因未识别“不能使用 array.length 判定”中的否定词而 exit 1;改用 fixed-string 后,E29/§12.22、证据编号与三级标题唯一性、敏感信息和 whitespace 检查全部 exit 0。没有进行第三次同类尝试。
+
+### 12.23 Hong Kong Gate HK-15 Calendar 初始化与自动选日
+
+- 用户提供完整 `InizializzaTimelineOrizzontale(GiornoDaSelezionare)`。
+- 函数先解绑 `#datetimepicker` 的 `dp.update`/`dp.change`,再依次初始化日历、禁用无预约日期、调用异步控件启用辅助函数并关闭 loader;HK-17 后确认该辅助函数只切换 CSS class,不绑定事件。
+- 它按 `data-date=YYYY-MM-DD` 查找目标日期;找不到时静默回退时间线第一项;找到候选后执行程序化 `.click()`。
+- 这解释了“人工日期点击 0 次但页面生命周期出现 TimeSlots”的上游机制;具体 click handler 和 TimeSlots HTTP 合同仍未补猜。
+- 已把静默回退识别为 P0 日期错配风险:未来 Book 必须在异步稳定后重新验证 actual selected date 与用户偏好,不一致即停止。
+- 本步骤没有执行函数、点击日期、调用 Calendar endpoint 或修改插件代码;只更新调研文档。
+- fixed-string 内容检查、E30/三级标题唯一性检查、陈旧下一步反向扫描、敏感信息扫描均返回 exit 0;随后对未跟踪文档执行直接行尾空白检查。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.24 Hong Kong Gate HK-16 日期禁用与可点击 class
+
+- 用户提供完整 `DisabilitaGiorniSenzaPrenotazioni()`;本步骤只读函数文本,没有执行。
+- 函数先给所有 datetimepicker `.day` 添加 `disabled`,再用格式化日期匹配 `GiorniConPrenotazioni` 的 `date@slot`。
+- `slot >= 0` 时添加 `availableDay` 并移除 `disabled`;否则添加 `notAvailableDay`。该比较包含零值和 JavaScript 隐式数值转换。
+- 因为零值也进入 `availableDay`,日期层只代表“可进入下一层”,不能代替 TimeSlots 的真实正向判据。
+- 已记录重复日期、正负 class 并存、旧 class 未清理和非有限数值四类 fail-closed 条件;是否会真实发生仍待 response 样本/上游 DOM 生命周期验证。
+- 本步骤没有点击日期、调用 Calendar endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string 合同、E31/三级标题唯一性、陈旧结论反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK16_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.25 Hong Kong Gate HK-17 异步控件 class 切换校准
+
+- 用户提供完整 `AbilitaInputAsincroni()`;本步骤只读函数文本,没有执行。
+- selector 为 `[data-async="true"]:not(.selected)`;逐项移除 `input-async-disabilitato` 并添加 `input-async-abilitato`。
+- 函数没有注册事件、调用 click、发起网络请求、读取 Slot 或设置原生 disabled/ARIA 状态。
+- 文档已把此前“绑定异步输入/该函数最可能闭环 TimeSlots”的候选解释更正为“只切换 CSS class”;真正 handler 继续待全局搜索。
+- selected 元素被排除,因此 class 可能来自其他生命周期步骤;插件不能用 enabled/selected/data-async 中任何单一标志判断有号。
+- 本步骤没有点击日期、调用 Calendar endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string 合同、E32/三级标题唯一性、陈旧推断反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK17_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.26 Hong Kong Gate HK-18 TimeSlots 请求编排
+
+- 用户提供完整 `CaricaTimelineVerticale(_Giorno, _ContenutiEventi)`;本步骤只读函数文本,没有执行。
+- `Metodo='RetrieveTimeSlots'`;WebMethod request 对象只有 `selectedDay=_Giorno` 和 `idService=$('#idServizio').val()`。
+- 结合 E28 的 `EseguiAsync`,当前合同为 POST `/BookingCalendar/RetrieveTimeSlots`、JSON UTF-8;success 调用 `CostruisciSchedaFasce(response, _ContenutiEventi)`。
+- `_ContenutiEventi` 属于 callback context,不进入 request body;error 参数为空,网站客户端继续丢弃网络错误详情。
+- 已明确区分 routing `service_id=4937` 与 Calendar DOM `#idServizio`;没有证据证明二者相等,插件不得替换。
+- `_Giorno=_Giorno` 是无效果语句;`_idService` 在本函数没有局部声明,长期实现不复制潜在全局状态。
+- 本步骤没有点击日期、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string HTTP/字段/callback 合同、E33/三级标题唯一性、陈旧未知结论反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK18_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.27 Hong Kong Gate HK-19 TimeSlots response 与容器构建
+
+- 用户提供完整 `CostruisciSchedaFasce(JsonFasceGiorno, Parametri)`;本步骤只读函数文本,没有执行。
+- response 经 `$.parseJSON` 得到内层数组;`selectedContent` 来自 `Parametri.selectedContent`。
+- 数组长度恰好为 1 时只设置 `unicaFascia=true`;每项都经 `CreaFasce(item, unicaFascia)` 返回 HTML并追加到容器。
+- 空数组不调用 `CreaFasce`,但仍调用 `CostruisciTimelineVerticale(Parametri)`;数组长度不能表示可预约性。
+- callback 本身不读取任何 Slot item 字段,也不决定普通/负向 class;这些合同继续归属 `CreaFasce`。
+- 本步骤没有点击日期/Slot、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string 双层 JSON/数组/callback 合同、E34/三级标题唯一性、陈旧下一步反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK19_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.28 Hong Kong Gate HK-20 Slot item 与 class 生成
+
+- 用户提供完整 `CreaFasce(fascia, unicaFascia)`;本步骤只读函数文本,没有执行。
+- 核心字段为 `SlotRimanenti`、`SlotLiberi`、起止时间嵌套对象和 `IDCalendarioServizioGiornaliero`。
+- `SlotRimanenti < 0` 生成 `notAvailableFascia + dotRed`;非负值不生成负向 class。
+- `SlotLiberi` 替换 `@PostiDiponibili@`,因此页面括号中的 `(0)` 来自它,而不是 `SlotRimanenti`。
+- `unicaFascia` 先赋 `act`;负向判断随后覆盖,因此唯一负向项不会保留 act,唯一非负项会自动 act。
+- 起止时间由 Hours/Minutes 格式化为 `HH:mm`;daily calendar ID 被写入 TemplateFasce 占位符,DOM 位置仍待模板定义。
+- 本步骤没有点击日期/Slot、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string item/class/数量/ID 合同、E35/三级标题唯一性、陈旧未知结论反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK20_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.29 Hong Kong Gate HK-21 TemplateFasce 定位失败与路线切换
+
+- 用户报告 DevTools Sources 全局搜索 `TemplateFasce` 没有结果;本步骤没有再次操作页面。
+- 该结果只证明当前可搜索 Sources 中没有明文符号,不证明运行时模板不存在,也不能据此猜测 HTML。
+- 调查路线从“继续搜索同一变量名”切换为“读取网站已渲染 `.fascia` 的脱敏 DOM 结构”。
+- 下一步只允许读取 tag、class、attribute 名、文本结构和运行时 value 是否存在;不记录 daily calendar ID 的实际值。
+- 本步骤没有点击日期/Slot、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string E36/路线切换合同、证据编号与三级标题唯一性、陈旧下一步反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK21_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.30 Hong Kong Gate HK-22 已渲染 Slot DOM
+
+- 用户在 `/BookingCalendar` 运行已批准的脱敏只读脚本;页面标题为 `Calendar - Prenot@Mi`,Slot 数量为 3。
+- 第一条根节点为 `div.fascia.notAvailableFascia`,内部依次观察到 `.dot.dotRed`、时间 span、br、数量 span 和 `input[type=hidden]#idHiddenFasciaServizio`。
+- hidden value 只记录为 8 位数字形状,没有保存真实 daily calendar ID。
+- 共同父节点为 `li.selected.enter-right`,其三个直接 Slot 子节点均带 `notAvailableFascia`;父级 selected 不等于 Slot 的 `.act`。
+- 本次深读只递归第一条 Slot,不能宣称三个 Slot 均有同名 hidden input 或不同 value。
+- 本步骤没有点击日期/Slot、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string DOM/hidden ID/下一步合同、E37/三级标题唯一性、陈旧结论反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK22_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.31 Hong Kong Gate HK-23 TemplateFasce 原文
+
+- 用户恢复现场后提供完整 `const TemplateFasce = ...`;本步骤只读取源码文本,没有执行模板或页面事件。
+- 模板原文与 E37 第一条 Slot 的渲染 DOM 逐节点一致,关闭了 class、时间、数量和 daily ID 占位符的准确位置。
+- `idHiddenFasciaServizio` 是模板中的固定 id,而 E34 会为每个 TimeSlots item 追加一次模板;多个 Slot 因此会生成重复 HTML id。
+- 重复 id 属于目标网站结构事实,插件不得用文档级 id selector 取 daily ID,必须限定在唯一 active、非负 Slot 子树内。
+- E36 保留为恢复前搜索 0 个匹配的历史证据;当前模板状态由更新的 E38 覆盖,不删除、不改写旧证据。
+- 本步骤没有点击日期/Slot、读取 hidden value、调用 TimeSlots、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string 模板占位符/重复 id/证据覆盖合同、E38/三级标题唯一性、陈旧当前状态反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK23_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.32 Hong Kong Gate HK-24 handler 搜索失败与替代取证
+
+- 用户恢复现场后在 DevTools Sources 全局搜索 `hiddenFieldServizio`,仍没有匹配结果。
+- E24 曾取得包含该变量的 final handler 上下文,但赋值表达式当时被脱敏;当前搜索 0 不能证明变量不存在。
+- 同一路线不再重试;替代方案是从当前页面 `document.scripts` 只读包含 `/BookingCalendar/InsertNewBooking` 的 inline script 上下文。
+- 替代采集必须限制输出行数,并脱敏 6 位以上数字字面量;不读取 hidden value、Cookie、Token 或表单资料。
+- 本步骤没有点击日期/Slot、调用 endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string E39/失败分类/替代路线合同、证据编号与三级标题唯一性、陈旧下一步反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK24_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.33 Hong Kong Gate HK-25 最终请求序列化
+
+- 用户在当前 `/BookingCalendar` 执行只读 `document.scripts` 采集;25 个 script 中唯一命中 scriptIndex 22 inline,endpoint 行 30、赋值行 24。
+- `hiddenFieldServizio = $('.fascia.act input')[0].value`:原生 handler 按 active Slot 后代 input 取第一个 value,不使用重复 document id。
+- `oraFasce = $('.fascia.act')[0].innerText`:最终 `selectedHour` 沿用网站完整显示文字格式。
+- `dataPren = $('.selected')[0].dataset.date`:最终日期依赖全局第一个 selected 元素和 DOM 顺序。
+- handler 只检查 active 数量是否为 0,没有检查唯一性、负向 class、input 类型/id 或 selected 元素是否有 `data-date`。
+- AJAX method/path/data keys 与 E24 一致;success 对 `errorMessage/url` 的分支再次交叉确认。
+- 本步骤没有执行 handler、点击日期/Slot、读取 hidden value、调用 endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string serializer/不变量/下一步合同、E40/三级标题唯一性、陈旧未知状态反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK25_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.34 Hong Kong Gate HK-26 selected 日期顺序
+
+- 用户在当前 `/BookingCalendar` 运行脱敏 selected DOM 采集;selectedCount=2,jQuery 第一个与 DOM 第一个一致。
+- index 0 是 `.events` 内的 `a.input-async-abilitato.selected`,带 `data-date`,格式为 YYYY-MM-DD。
+- index 1 是 `.events-content` 内的 `li.selected.enter-right`,同样带 `data-date`,格式为 YYYY-MM-DD。
+- 两个元素都不在 `.fascia` 内;原生 handler 在当前 DOM 顺序下会从 index 0 日期 link 取得日期。
+- 采集没有输出真实日期,因此尚不能证明两者值相等;下一步只验证相等性布尔值。
+- 本步骤没有点击日期/Slot、读取 daily ID、调用 endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string selected 顺序/角色/下一步合同、E41/三级标题唯一性、陈旧顺序未知状态反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK26_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.35 Hong Kong Gate HK-27 selected 日期一致性
+
+- 用户在当前 `/BookingCalendar` 运行纯布尔一致性检查;selectedCount=2。
+- `allSelectedHaveDataDate=true`、`allSelectedDatesEqual=true`,没有输出真实日期值。
+- `firstIsEventsDateLink=true`,timelineSelectedCount=1、contentSelectedCount=1。
+- 原生 handler 在当前稳定 DOM 中取得的 selectedDay 与内容卡片日期一致;异步切换后仍必须重新验证。
+- 本步骤没有点击日期/Slot、读取 daily ID、调用 endpoint、发送 OTP、提交表单或修改插件代码;只更新调研文档。
+- fixed-string 日期一致性/Discovery 收敛合同、E42/三级标题唯一性、陈旧相等性未知状态反向扫描、code fence 偶数、敏感信息和行尾空白检查全部返回 exit 0,输出 `HK27_DOC_CHECKS_OK`。没有运行 Python 测试,因为未修改可执行代码。
+
+### 12.36 Hong Kong Gate HK-28/E43 正向日期与 Slot
+
+- 用户在同一 `/BookingCalendar` Session 中向后浏览到 2026 年 10 月,纠正了“8 月默认窗口无号等于整个 Calendar 无号”的过度结论。
+- `RetrieveCalendarAvailability` 内层数组共有 22 个工作日条目;早期负向组合为 `SlotLiberi=0 / SlotRimanenti=-1`,10 月 9 日起出现 `1/0`,后续还出现 `4/3`、`8/7`、`9/8`、`10/9` 等正向组合。
+- 2026-10-09 的 `RetrieveTimeSlots` 有 3 项:两项 `0/-1` 对应 `notAvailableFascia + dotRed + (0)`;一项 `1/0` 对应普通 `fascia`、无红点和 `(1)`。
+- timeline/content selected 各 1 且日期一致;正向 Slot 内 hidden input 恰好 1,value 只记录“存在、数字、长度 8”,没有保存真实 daily ID。
+- 正向 Slot 未点击,`act=false`;最终按钮虽 enabled,但 Network 过滤 `InsertNewBooking` 的请求数为 0。因此本 Gate 没有预约副作用。
+- E43 已关闭 response/DOM 正向 allowlist,但没有关闭点击后唯一 `.fascia.act`、最终 response、`/Reservation` 对账或跨进程幂等。
+- 用户提供的 response 中含动态 daily ID;本文只保存结构形状和数量,不保存、回显或传播具体值。
+- 本步骤只更新事实与设计文档;没有修改插件、配置、工具或测试,也没有执行网站动作。
+
+### 12.37 Hong Kong Gate HK-29/E44 正向 Slot 安全选择
+
+- 用户在 E43 的同一香港 `/BookingCalendar` 正向样本上执行了经过授权的 SLOT-POS-B 探针;目标仍是 2026-10-09 的 `10:05 - 11:05`,页面库存仍显示 `(1)`。
+- 探针在点击前 fail-closed 核对:pathname 为 `/BookingCalendar`、timeline/content selected 日期均匹配、正向候选恰好 1、候选不带 `notAvailableFascia` 或 `dotRed`、hidden input 恰好 1,value 只验证“存在、全数字、长度 8”。
+- 探针源码只包含一次候选 `.click()`;原 Promise 已 fulfilled,用户没有重跑原探针。随后独立只读 readback 得到:`activeCount=1`、`activeTimeMatches=true`、`remainingIsOne=true`、`activeMarkedUnavailable=false`、`activeHasRedDot=false`。
+- timeline/content 的 selected 日期在点击后仍同时匹配目标日期;唯一 active Slot 的 hidden input 仍恰好 1,value 形状仍是“存在、全数字、长度 8”。本文没有读取或保存真实 daily ID。
+- 最终 `#btnPrenotaNoOtp` 仍存在,但本探针没有点击它。当前页面 Resource Timing 中 `/BookingCalendar/InsertNewBooking` 请求数为 0,readback 的机械总判定为 `done=true`。
+- 证据边界:Resource Timing 足以证明本次选择探针没有观察到最终 XHR,但不能替代未来 FINAL Gate 的 DevTools/CDP Network listener、服务端响应和 `/Reservation` 对账。
+- 自动 Chrome 标签接管先后在 30 秒和 120 秒超时;遵守同一错误最多两次后停止,改由用户在既有登录标签执行固定、脱敏、fail-closed 的探针。两次接管失败均未刷新、导航或点击页面。
+- E44 关闭了“正向 Slot 点击后唯一 active、后代形状、日期和时间一致且 final=0”的网站事实;没有关闭最终 response、`/Reservation` 对账、跨进程 durable fence 或生产 Query 的 Q-CAL Gates。
+- 本步骤没有修改插件、配置、工具或测试;只执行一次正向 Slot 页面选择和只读验收。
+
+### 12.38 CS1 离线实现检查点(不是网站新证据)
+
+- 负责人批准 R3 后,只授权实现通用纯协议模块与离线 fixture;生产 Query/Book 接线、
+  OTP、AVANTI 和最终预约均不在授权内。
+- 新增 `plugins/ita_protocol.py` 与 `test/test_ita_protocol.py`;没有修改
+  `ita_plugin.py`、配置、工具或现有测试。
+- 纯模块把 E43 的双层 JSON、日期/时段容量 allowlist、范围过滤和确定性排序,以及
+  E44 的日期/时段唯一选择与 precommit 一致性写成 fail-closed 合同。
+- 28 个协议测试与 30 个现有 Italy 回归测试均 exit 0;编译、纯导入、地区硬编码/
+  网络副作用和 whitespace 检查均 exit 0。当前虚拟环境没有 `ruff`,因此没有把它
+  写成已通过。
+- 本检查点没有调用浏览器或网站,真实 Italy 请求数为 0;它证明“协议核心可离线
+  判定”,不证明强 Query、Book、FINAL 或 FENCE 已经跑通。
+
+### 12.39 CS2 通用路线接线检查点(不是网站新证据)
+
+- 负责人单独批准 CS2 后,`ItaPlugin.query()`/`book()`、Sentinel/Booker Italy 配置与
+  本地 query/book/monitor/soak 工具统一改为
+  `routing_key → apt_configs[routing_key] → service_id/capability`;不再读取顶层
+  `service_id` 作为后备值。
+- Dublin/1321 和 Hong Kong/4937 只是两个离线 fixture,均调用同一个 route resolver;
+  AST 检查确认 Plugin 与工具没有基于这两个 service id、Dublin、Hong Kong 或 HKG 的
+  `if`/三元控制分支。
+- Dublin 只保留为调试工具在“完全没有 route 覆盖”时的兼容默认值。自定义 route 必须
+  原子提供 routing key、service id、city、visa type;部分覆盖直接拒绝,避免静默混线。
+- 生产配置显式保持 `query_mode=services_probe` 与 `final_submit_enabled=false`;未知
+  capability、缺失 route、Calendar query mode 或 final enablement 均 fail-closed。
+- 137 个 Italy 相关离线测试全部 exit 0;编译、配置 parity、控制分支、敏感操作与
+  whitespace 检查均 exit 0。当前环境没有 `ruff`,因此没有写成已通过。
+- 本检查点没有启动浏览器或请求 Prenot@Mi;OTP、AVANTI、InsertNewBooking 请求均为
+  0。它只关闭“通用路线接线”,不证明强 Query、用户 Book、FINAL 或 FENCE 已跑通。
+
+### 12.40 Q-CAL-1 账号与 Sede 对齐检查点(Gate 未关闭)
+
+- 负责人授权 Q-CAL-1 使用团队 Query 账号执行:预约计数前后对账、一次 OTP、一次
+  AVANTI、两次 Calendar 只读 probe;日期/时段选择和 `InsertNewBooking` 仍被禁止。
+- 第一次真实执行在 `/Reservation` 基线读取阶段停止。原因是正式预约表已初始化为
+  DataTable,而结构为空的候补表不会初始化 DataTables;旧工具错误地要求两张表都完成
+  初始化。本次没有进入目标服务,OTP、AVANTI、Calendar 和 final 请求均为 0。
+- 修正后已验证预约读取会等待稳定快照,同时接受“正式表已初始化 + 候补表结构性为空”这一
+  真实页面状态;聚焦测试 24/24、Italy 相关完整回归 163/163、语法编译和 whitespace
+  检查均 exit 0。
+- 第二次真实执行成功登录并取得脱敏基线:`reservations=0, waitlist=0`。随后 Services
+  页面稳定为 1 张表、8 个数据行、7 个预约链接,但目标
+  `/Services/Booking/4937` 的链接数为 0;插件抛出
+  `ItaTargetServiceLinkMissingError` 并清理成功,进程 exit 1。
+- 第二次执行仍发生在 OTP 之前:`GenerateOTP=0`、Booking Form POST=0、
+  `InsertNewBooking=0`,预约/候补基线没有被业务操作改变。因此它是一次安全的路由前置失败,
+  不是“香港 4937 无号”证据。
+- 可以确定的是当前认证账号所在 Sede 没有提供 4937;“当前就是 Dublin”只能由此前
+  Dublin 的 8 行/7 链接样本推断,尚未在本次运行直接读取 Sede 文本。Q-CAL-1 保持 OPEN。
+  下一次执行前必须让账号 Sede 与显式 route 对齐;原样重跑没有信息增益,也不被批准。
+- 负责人完成 Sede 调整后,使用同一团队 Query 账号执行了一次只读 Query 预检。插件精确
+  找到 `/Services/Booking/4937` 并进入该 Booking Form;form method/path 仍为
+  `POST /Services/Booking/4937`,结构采集仍观察到 `typeofbookingddl`、`ddls_0`、
+  `otp-input`、`PrivacyCheck`、`cf-turnstile-response` 和 `btnAvanti`,没有读取这些字段的
+  运行时值。
+- 预检只调用一次 `query()`,没有发送 OTP、点击 AVANTI、进入 Calendar 或调用 final;
+  清理成功。`debug_ita_query.py` 对 Booking Form 弱信号的既定退出码是 4,测试也明确断言
+  该合同,因此本次 exit 4 表示“安全发现正向入口并停止”,不是失败。
+- 这条证据关闭了本节的账号/Sede 对齐阻塞;Q-CAL-1 本身仍为 OPEN,下一次动作才会消费
+  一次 OTP 与一次 AVANTI 的副作用预算。
+- 对齐后的 Q-CAL-1 执行再次确认基线 `reservations=0, waitlist=0`,进入 4937 后只发送
+  一次 OTP,Network 合同通过并输出 `ITA_QCAL_OTP_SENT requests=1`。负责人在终端隐藏
+  输入验证码;验证码和邮件正文均未进入聊天或日志。
+- 执行随后在 AVANTI 前以 `Booking preflight rejected otpDisabled` fail-closed;
+  `AVANTI=0`、Booking Form POST=0、Calendar=0、`InsertNewBooking=0`。失败后使用同一
+  团队账号执行独立只读 `/Reservation` 审计,仍得到 `reservations=0, waitlist=0`,命令
+  exit 0。因此“本次 OTP 未新增预约/候补”已经完成前后对账。
+- 网站已知会在发送成功后启动 120 秒重发冷却,发送按钮 disabled 属于合法的 post-OTP
+  状态。当前工作树的 stage-aware 校验及 4 个聚焦测试均接受该状态并 exit 0,但真实进程
+  输出与当前源码矛盾;本次输出没有工具版本/合同指纹,无法判定是旧进程还是运行时值类型
+  差异。遵守副作用不盲重试纪律,Q-CAL-1 继续 OPEN。
+- 随后的单独本地授权已完成非敏感可审计增强:工具会在 route、凭据和浏览器之前输出
+  `qcal1-stage-aware-preflight-v1` 与当前源文件 SHA-256 短指纹;preflight 日志只包含
+  stage、snapshot 类型,以及 `otpDisabled`、`avantiDisabled`、`turnstileReady` 的
+  类型/布尔值。非布尔运行时值只显示类型并将 value 置为 null;额外字段不会进入日志。
+- 19 个 Q-CAL 聚焦测试、168 个 Italy 相关离线测试、语法编译、diff 和尾随空格检查全部
+  exit 0;测试明确覆盖 post-OTP disabled 冷却、旧进程指纹识别、非法 outcome 降级和私密
+  运行时值不泄漏。本步骤真实网站请求、OTP、AVANTI、Calendar、final 均为 0。
+- 本地 `data:` HTML 配合真实 Chromium/DrissionPage 的额外桥接测试确认:JavaScript
+  `disabled=true/false` 分别返回 Python `True/False`,两者精确类型均为 `bool`;命令
+  exit 0,未访问 Prenot@Mi。这排除了“true 被桥接为整数 1”的剩余假设。
+- 诊断缺口已经关闭,但 Q-CAL-1 仍为 OPEN。新的 OTP 必须重新取得明确授权;不能继承或
+  复用上次已经消耗的发送预算。
+- 新一次明确授权后,真实进程输出合同 `qcal1-stage-aware-preflight-v1` 及预期源码指纹。
+  pre-OTP 诊断为 `otpDisabled=false/bool/ready`,发送一次 OTP 并人工隐藏输入后,post-OTP
+  诊断为 `otpDisabled=true/bool/ready`;因此版本和 120 秒冷却修复均已在真实页面证明。
+- 工具随后原生点击 AVANTI 1 次,但因 `AVANTI response status was not 302` fail-closed;
+  本次没有执行 Calendar probe 或 `InsertNewBooking`。清理后独立只读 `/Reservation` 审计
+  仍是 `reservations=0, waitlist=0`,命令 exit 0,因此没有新增预约或候补。响应实际状态、
+  response URL 与当时页面 URL 未被旧诊断保存,不能由该次输出反推。
+- 为区分网站拒绝与监听器语义,本地临时 HTTP 服务真实执行
+  `POST /booking → 302 → GET /calendar 200`。Chromium/DrissionPage listener 最终返回
+  `request_method=POST, request_path=/booking, response_status=200,
+  response_path=/calendar, final_path=/calendar`,复现断言与命令均 exit 0,外部网站请求为 0。
+  安装版本的 listener 源码也显示 redirect 沿用 requestId,后续 response 会覆盖 packet 的
+  `_raw_response`;根因已定位为高层 packet 适配假设错误。
+- 下一步最小修复必须用三重证据接受 followed redirect:原始同源 POST 路径、packet 最终同源
+  Calendar response URL、浏览器最终 Calendar pathname。不得把任意 HTTP 200 放宽为成功;
+  直接 302 分支仍校验 Location。Q-CAL-1 继续 OPEN,代码修复和新 OTP 均需各自授权。
+- 负责人随后单独授权了上述本地修复,未授权新的真实网站执行。Q-CAL 工具现在把监听器的
+  两种等价表示归一化:直接 `302` 必须同时满足原始无 query 的同源 Booking POST、同源
+  Calendar Location 和浏览器最终 Calendar;followed `200` 必须同时满足同一原始 POST、
+  packet response URL 为同源 Calendar、浏览器最终页面也为同源 Calendar。其他状态、非默认
+  HTTPS 端口、带凭据的 URL、跨域或任一 pathname 不一致全部 fail-closed。
+- 工具会先有界等待浏览器到达 Calendar,再运行上述证据校验;通过时只输出
+  `direct_302` 或 `followed_redirect_200` 模式,不记录 query、Token 或表单数据。它没有放宽为
+  “任意 200 成功”;新语义合同标识为 `qcal1-stage-aware-redirect-v2`,也没有修改生产
+  `ItaPlugin`、Query/Book 合同或 final 边界。
+- 首次聚焦测试因修补测试文件时匹配了错误的同形 `):`,意外移除既有循环冒号而 exit 1;读取
+  精确行号后一次修正,第二次为 22/22、exit 0。最终包含 Q-CAL 在内的 Italy 离线回归为
+  171/171、exit 0;两份改动文件的内存编译、`git diff --check` 和尾随空格检查均 exit 0。
+  本步骤没有启动浏览器、访问 Prenot@Mi、发送 OTP 或点击 AVANTI/final。Q-CAL-1 仍为 OPEN;
+  下一次真实执行必须重新取得一次 OTP 与一次 AVANTI 的明确授权。
+- 新合同的第一次真实执行由 Codex 内部 PTY 启动,但终端无法正确交给负责人;进程已到隐藏
+  OTP 输入点,证明 OTP 已发送 1 次,随后被显式中止并清理。该次 AVANTI、Calendar 和 final
+  均为 0。负责人知情后另行明确授权第二次 OTP/AVANTI,并改由自己的终端执行。
+- 第二次执行输出了 `qcal1-stage-aware-redirect-v2` 与预期源码指纹;前后两个 preflight 均为
+  bool/ready,OTP 发送 1 次,随后 AVANTI POST 1 次。listener 已观察到 POST,但浏览器 30 秒
+  内没有进入 Calendar,工具以 `AVANTI did not reach Calendar before timeout` fail-closed;
+  Calendar availability probe 和 final 请求均为 0,清理成功,进程 exit 1。
+- 失败后使用同一团队 Query 账号执行独立只读 `/Reservation` 对账,结果仍为
+  `reservations=0, waitlist=0`,清理成功、命令 exit 0;因此两次 OTP 和第二次 AVANTI 均未新增
+  预约或候补。由于第一次和第二次执行各发送了一封 OTP,负责人是否输入了最新一封验证码是
+  当前必须先确认的事实;旧工具没有保存 AVANTI packet 的脱敏状态、最终 response path 或
+  Booking 页面可见错误,不能把 OTP 错误、Turnstile 失效或其他业务拒绝中的任何一个写成
+  已证明根因。再次发送 OTP 前应先关闭这一信息缺口,禁止盲重试。
+- 负责人随后确认第二次执行输入的是该次 `ITA_QCAL_OTP_SENT` 后最新收到的验证码,因此“误用
+  第一封旧 OTP”不再是该次失败的主假设。负责人同时观察到没有明显的 AVANTI 点击动画,并
+  不确定 OTP 是否真的留在页面字段中。代码顺序能证明工具通过了终端数字格式校验并调用了
+  `#otp-input.input(...)`;`_wait_for_calendar()` 只会在 AVANTI listener 返回匹配的 Booking
+  POST packet 后执行,所以 POST 被观察到也是高确信度事实。但旧合同没有做 OTP DOM 回读,
+  视觉上没有按钮动画也不能单独证明 click handler 未执行。
+- 经单独授权,本地工具合同升级为 `qcal1-avanti-diagnostic-v3`。Booking preflight 新增
+  `otpValuePresent` 布尔回证:发送前必须为 false,人工输入后必须为 true,否则在 AVANTI 前
+  fail-closed。AVANTI listener 返回后会明确输出 `ITA_QCAL_AVANTI_POST_OBSERVED`;若 POST
+  未出现、Calendar 超时或跳转证据不一致,则输出固定 allowlist 诊断。
+- 失败诊断只包含:合同/源码指纹、POST 是否观察及请求是否匹配、HTTP status 的安全数值形状、
+  response/Location/browser 的固定路径类别,以及 Booking Form、OTP presence、OTP-invalid
+  marker、AVANTI disabled、Turnstile ready、可见校验/确认框数量和 final 请求数量。它不读取
+  或输出 response body、query、OTP、Turnstile Token、表单值、错误文案或个人信息;未知类型
+  只保留类型名并把 value 置为 null。
+- Q-CAL 聚焦测试 24/24、完整 Italy 相关离线回归 173/173,均 exit 0;测试用伪造的 response
+  body、query、POST body 和运行时私密值做反向断言,序列化诊断命中为 0。本步骤没有启动
+  浏览器、访问 Prenot@Mi、发送 OTP、点击 AVANTI 或调用 final。下一次真实 Gate 才能用这些
+  字段区分“OTP 未写入”“POST 未出现”“Booking Form 被返回”和“Calendar response 未渲染”。
+- `qcal1-avanti-diagnostic-v3` 的首次真实执行立即关闭了 OTP 输入缺口:发送前
+  `otpValuePresent=false`,负责人输入本次最新 OTP 后仍为 false,工具在 AVANTI 前
+  fail-closed;因此该次 OTP=1,AVANTI/Calendar/final=0,清理成功、进程 exit 1。这个结果
+  证明上一轮“可能没有真正输入 OTP”的观察正确,且与验证码内容是否正确无关——错误数字也
+  应该让 DOM value 非空。
+- 只读检查当前 DrissionPage 实现后定位到 macOS 焦点差异:`element.input(..., clear=True)`
+  会先调用 `clear()`;macOS 的 clear 分支用 JavaScript 清空并发送 change,但不会调用
+  `_input_focus()`。随后键盘事件可能发给此前聚焦的元素。Italy IAM 登录路径一直采用“先
+  `human_click_ele()`,再 `input(clear=True)`”,而 Q-CAL OTP 路径此前漏掉了同一动作。
+- 经授权后 Q-CAL 最大化复用现有登录模式:先人类化点击 OTP input,再输入;随后在该元素的
+  浏览器上下文中只返回 `this.value === expectedOtp` 的布尔比较结果,实际 OTP 不返回、不记录。
+  比较不是精确 true 就在 AVANTI 前停止;通过时只输出
+  `ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true`。终端输入按负责人要求改为可见,并明确提示
+  本机 terminal scrollback 可能保留它;程序日志和文档仍不记录 OTP。
+- 新合同为 `qcal1-otp-readback-v4`。真实 Chromium + 本地 `data:` input 页面已机械验证点击、
+  清空、输入和精确浏览器内比对,输出 `LOCAL_OTP_FOCUS_READBACK_OK external_request=0`、
+  exit 0。Q-CAL 聚焦测试 27/27、完整 Italy 离线回归 176/176,均 exit 0。本地修复阶段没有
+  访问 Prenot@Mi、发送 OTP、点击 AVANTI 或调用 final。
+
+## 13. 当前开放问题
+
+| 问题 | 为什么重要 | 确信度/状态 |
+|---|---|---|
+| IAM 登录页当前真实字段和回调链是什么? | 决定 `create_session()` 选择器和 404 修复 | 字段、`/UserArea` 终点和一次真实自动登录已验证;callback 文档链未取得;高 |
+| 当前无号时 `/Services/Booking/1321` 的客户端链路是什么? | 决定 Query 如何识别无号 | 已验证 GET/302 回退,无预约业务 POST;高 |
+| 点击入口是否写入服务器内部的短暂 Session 状态? | 决定能否长期高频 Query | 客户端未见业务写请求,但不能证明服务器内部零写入;中 |
+| `200 + bookingForm` 是否始终意味着 Calendar 有日期? | 决定能否用入口代替库存查询 | E43 证明该样本后续月份有号,但 bookingForm 自身仍不携带日期/范围/容量,也没有跨 Session/跨 Sede 不变量;只能作诊断 stage,不能作精确生产信号,高 |
+| 有号时 OTP 前能否读取日历? | 决定采用 B 还是 C | Hong Kong 入口没有 Calendar 请求;三个 availability/time-slot XHR 只在 OTP + POST 后页面生命周期中出现,当前证据支持 C,中高 |
+| `Tourism` 的真实选项和值是什么? | 决定 routing key 到表单字段的映射 | Hong Kong 已验证 `Turismo=42`;跨 Sede 稳定性待验证;Hong Kong 高/全局中 |
+| 可见 select 如何同步 hidden 字段? | 决定能否可靠提交而不手工拼 payload | 单人 `1/0` 在 change 时同步;旅游 visible=42、hidden pre-click=0,并由 `AVANTI` 内 `saveDdlValue()` 在 submit 前写 42;Hong Kong 高 |
+| OTP 按钮调用哪个 endpoint、如何限流? | 决定副作用、账号模型和重试 | 真实 GET endpoint、200/`SENT`、邮件送达和 120 秒 UI timer 已验证;OTP 有效期及服务端限流仍未知,高/低 |
+| Turnstile 何时有效、失败时页面如何表现? | 决定 Book 能否保持同一浏览器上下文并安全恢复 | callback 启用、expired/timeout 禁用并 reset 已确认;error 片段只提示错误,运行时 Token 生命周期未验证,中高/低 |
+| reCAPTCHA Enterprise 是否属于当前活跃提交链? | 决定插件是否应调用 `getCaptchaToken()` | Hong Kong 成功真实 POST 只有 Turnstile 字段名、没有 reCAPTCHA;当前主路径不调用,未来页面能力变化再发现,高 |
+| `AVANTI` 的 method/path/payload 和草稿语义是什么? | 决定前置提交、幂等和恢复 | POST 4937 → 302 → BookingCalendar 已验证;完整 payload 未记录且不需要手工构造,服务端是否建立草稿仍未知,中高/低 |
+| Calendar document 的精确落点是什么? | 决定 Book 下一状态识别和恢复 | 已验证 GET `/BookingCalendar?selectedService=...`、200 Document、pathname/title;高 |
+| 日历和时间接口的当前 method/path/schema 是什么? | 决定 Book 的等待、解析和错误分类;也决定是否可能安全读取 | Availability/TimeSlots 的 method、request、双层数组、正负 item 与 DOM 已由 E27–E43 关闭;正向 Slot 点击后的唯一 active/后代一致性由 E44 关闭;ServerInfo、长期幂等性和 Session 寿命仍待验证,高/中低 |
+| Calendar `#idServizio` 与 routing `service_id` 是什么关系? | 决定 TimeSlots 是否会查错服务/日历,避免跨层 ID 混用 | 已证明来源不同:4937 来自 Services URL,TimeSlots 从当前 Calendar DOM 读取;是否数值相等及准确业务语义均未证明,高/低 |
+| `SlotRimanenti` 与 `SlotLiberi` 是什么关系? | 前者控制负向 class,后者显示数量;决定零值是否为真实机会 | E43 已证明负向 `0/-1`、正向 `1/0`,并观察到本批样本均满足 `Rimanenti=Liberi-1`;该公式不提升为跨 Sede 常量,解析器继续同时校验两个字段,高/中 |
+| Calendar 中 `disabled`、`availableDay`、`notAvailableDay`、`selected`、`.fascia.act` 和容量分别是什么语义? | 决定如何避免把默认焦点误判为有号 | E43 已关闭正向数量/DOM,E44 已关闭经过完整正向 preflight 后的唯一 active 状态;`selected`、`.act` 或 enabled final 单独出现仍不构成可提交证据,高 |
+| 哪个请求真正创建预约? | 决定幂等和最终确认边界 | active delegated handler 指向 `POST /BookingCalendar/InsertNewBooking`,字段和 `errorMessage/url` 已观察;真实响应与创建语义未执行,高/低 |
+| OTP 是否直接发往登录账号的注册邮箱? | 当前 Book 读取不存在的 `email` 属性,但 GenerateOTP URL 没有 email 参数、真实表单也没有 email 输入 | E22 已验证当前登录 Session 的注册邮箱收到 OTP;高 |
+| 生产 Query 是否可长期保持准备好的 Calendar Session? | 决定能否避免每轮 OTP/AVANTI,同时持续精确探测 | E43 只证明单个 Session 的正向读取;Q-CAL-1/Q-CAL-2 仍需验证预约列表不变、probe 幂等、Session 寿命和限流,中低 |
+
+## 14. 初见审查
+
+多疑的资深工程师可能会问:
+
+> “Dublin 的 `1321` 已经有 `Prenota`,为什么不直接修 Query,让它看到链接就返回 Available?”
+
+回应:
+
+1. Services 页面没有日期或时间证据。
+2. 同一页面确实会把“日历尚不可用”表现为没有链接,但这不能证明有链接时必然有号。
+3. 当前 `VSQueryResult.success=True` 会进入 Redis 并触发 Booker;把入口误报成号源会放大成真实预约副作用。
+4. Sentinel 与 Booker 使用不同实例,Query 中的页面状态不能传递。
+5. Hong Kong 已证明 `200 + bookingForm`,但进入时仍没有 Calendar 请求;因此正向分支也只证明“可进入”,没有证明“有具体日期”。
+
+因此,Phase 1 最初只实现 `#WNotAvailable.value` 非空的无号结果;当前工作树后来加入了 `bookingForm → success=True + NoneAvailable` 弱信号。E43 后的目标设计不再把该弱信号接入生产链,而是单独实现并 Gate“准备型 Calendar Query”:只有 Availability 返回 E43 已校准的正向日期才发布 `Available`,且 `times=[]`;用户 Book 再重查 TimeSlots。
+
+新的反驳是:
+
+> “Hong Kong `4937` 返回 200,为什么还不能直接认定有号并执行 Book?”
+
+回应:`200` 的权威含义只到 Booking Form。Calendar 位于 OTP 和 `AVANTI` 之后;E43 虽证明该香港 Session 的后续月份确有号,仍不能把 bookingForm 与“当前存在号源”画等号,因为表单响应本身没有日期、范围或容量。精确 Query 必须读取 Calendar 协议;Book 还要用用户账号独立重查。
+
+HK-7 后新增的反驳是:
+
+> “现在已经进入 Calendar,是否终于可以把 Query 返回成 Available?”
+
+回应:HK-7 当时仍不可以,因为只有 Calendar document,没有正向库存。E43 现在已经补上正向 Availability 与 TimeSlots,因此“强信号的解析语义”已关闭;但生产 Query 仍不能立刻启用,因为团队账号进入 Calendar 需要一次 OTP + `AVANTI`。只有 Q-CAL-1/Q-CAL-2 证明该准备动作不新增预约、后续 probe 不重复副作用并且 Session 可稳定复用,才允许发布 `Available`。
+
+HK-8 只能进一步机械回答:**默认的 8 月窗口**中,42 个日期格全部 `disabled`,8 月 31 日和三个时段均为负向。E43 已纠正其范围:向后到 10 月存在正向日期和时段。所以实现必须扫描完整配置日期范围,既不能把“进入 Calendar”当有号,也不能把“默认月份无号”当全局无号。
+
+另一个反驳是:
+
+> “8 月 31 日和时段容器都带 `selected`,最终 `PRENOTA` 按钮也没有 disabled,为什么不算可预约?”
+
+回应:在 8 月负向样本中,同一日期格带 `disabled notAvailableDay`,所有展示时段都是 `(0)`,没有 `.fascia.act`;E43 的正向候选在点击前也仍是 `act=false`。E44 证明通过完整正向 preflight 后可以得到唯一正确的 `.fascia.act`,但最终按钮在点击前后都 enabled,说明 enabled 本身仍没有库存或可提交语义。长期实现必须采用 response + DOM + 日期 + 时段 + 唯一 active 的多证据 AND 条件。
+
+HK-15 后还要防住一个更隐蔽的反驳:
+
+> “既然网站会在目标日期不存在时自动选第一天,插件跟随网站默认值不就可以了吗?”
+
+回应:不可以。网站的回退是展示层便利行为,不代表用户授权更换预约日期。`InizializzaTimelineOrizzontale` 会静默回退并程序化点击,所以一个看似正常的 `selected` 日期可能根本不是 Book 请求的日期。插件必须把“目标日期”和“实际 selected 日期”作为两个独立值,在每次异步更新后做事后断言;实际日期不满足用户偏好时应明确停止,而不是珍惜号源之名替用户做越权选择。
+
+HK-16 又带来一个容易被名称误导的反驳:
+
+> “DOM 已经叫 `availableDay`,数据又叫 `SlotRimanenti`,为什么还不能直接认为有号?”
+
+回应:因为可执行源码比英文名字更精确。网页实际使用 `slot >= 0`,数值 `0` 也会移除 `disabled` 并添加 `availableDay`。所以这里的 available 只能解释为“允许进入该日期并加载时段”,不能解释为“至少存在一个可预约时段”。只有 TimeSlots 返回并渲染出经过正向样本证明的可用 Slot,且日期/时段/用户偏好交叉一致,才可以把机会交给最终预约阶段。
+
+HK-17 后还要校正另一个名称诱导:
+
+> “`AbilitaInputAsincroni` 不是叫‘启用异步输入’吗,为什么不认为它绑定了 TimeSlots 请求?”
+
+回应:函数名表达作者意图,函数体才是证据。完整函数只有 selector 和两个 `classList` 操作,没有 event registration、click 或网络调用。它可能为别处已注册的 delegated handler 准备 selector 状态,但“可能”不能写成请求合同。下一步应直接全局搜索 `RetrieveTimeSlots`,而不是继续沿辅助函数名推测。
+
+HK-18 后,一个多疑的工程师还会问:
+
+> “TimeSlots 参数叫 `idService`,直接传已经确认的 Hong Kong `4937` 不就行了吗?”
+
+回应:不行。`4937` 来自 Services 入口 URL;当前 TimeSlots 源码明确从 Calendar 页 `#idServizio` 重新取值。两个变量名称相似,但来源、生命周期和页面阶段不同,没有相等证据。把 routing ID 硬塞进 Calendar API 可能返回错误时段、空结果或操作错误日历。插件必须从当前 Session 的 DOM 获取 runtime ID,并把缺失、非预期格式或跨页面变化分类为结构错误。
+
+HK-19 后还要拒绝一个“看起来很合理”的捷径:
+
+> “`unicaFascia=true` 已经表示唯一时段,为什么不能直接选择它?”
+
+回应:因为源码只检查 `JsonFasceGiorno.length == 1`,没有检查该 item 是否可用。`unicaFascia` 只是传给 `CreaFasce` 的布局/渲染参数候选;唯一一项完全可能最终生成 `notAvailableFascia`。同理,数组非空和页面出现时间文本也只能证明服务器返回并渲染了记录,不能证明容量大于零。真正的正向判据必须来自下一层 `CreaFasce`。
+
+HK-20 关闭源码后,这个反驳需要进一步细化:
+
+> “既然 `SlotRimanenti >= 0` 时网站不会加 `notAvailableFascia`,是否已经足够算可预约?”
+
+回应:单看 `SlotRimanenti >= 0` 仍然不够,但 E43 已补齐组合规则:`SlotLiberi=1 / SlotRimanenti=0` 与普通 `fascia`、无红点、`(1)` 同时出现;`0/-1` 与负向 class 同时出现。因此当前 allowlist 是 `SlotLiberi>0 AND SlotRimanenti>=0`,再叠加合法时间、唯一 daily ID、无负向 class 和 selected 日期一致。其他组合继续 fail-closed;`SlotRimanenti=0` 不能误判为无号。
+
+HK-21 后还要防止把搜索失败错误升级成业务结论:
+
+> “全局搜索不到 `TemplateFasce`,是不是可以按 `CreaFasce` 的 replace 顺序自己还原模板?”
+
+回应:不可以。replace 顺序只能证明哪些值被写入字符串,不能证明最终 tag 层级、attribute 名、隐藏 input 位置或运行时脚本是否又改写 DOM。自己还原模板会把猜测写进长期插件。网站已经渲染出的 `.fascia` 才是当前浏览器实际交互的对象,因此下一 Gate 直接读取脱敏 DOM,证据更短、更可靠。
+
+HK-22 后,一个多疑的工程师还会追问:
+
+> “已经找到 `#idHiddenFasciaServizio`,为什么不直接用 `document.querySelector` 读取它并 POST?”
+
+回应:E38/E40 后已经证明模板会重复该 HTML id,而网站原生 handler 是从 `.fascia.act` 后代 input 取值;E43 还证明每个正负 Slot 都有自己的动态 ID 形状。文档级 selector 仍可能取到错误时段,因此插件必须从唯一且正向的 `.fascia.act` 子树读取并复核一个 hidden input,沿网站原生 handler 提交,绝不手工拼最终 POST。
+
+HK-23 后,重复 id 已从“风险假设”升级为模板生成事实,但结论仍不是“可以自己发 POST”:
+
+> “既然模板和 hidden input 都找到了,直接从 active Slot 读取 value 再调用 InsertNewBooking,不是更快吗?”
+
+回应:读取 selector 可以按 active Slot 收紧,但最终请求仍有网站原生 `innerText` 格式、selected 日期作用域、并发抢占、response/幂等和不可逆副作用未验证。当前正确路线是用精确 handler 源码完成合同,再让 Book 驱动网站原生交互;不能因为找到了一个字段就绕过余下状态机。
+
+HK-24 后还要避免把工具能力边界误判成网站事实:
+
+> “Sources 搜索两次都找不到变量,是不是 E24 的代码已经失效,可以忽略?”
+
+回应:不能。E24 是当时页面脚本的直接采集,搜索失败只能说明当前 DevTools 索引/上下文没有命中。网页仍然必须以某种方式把 daily ID 放进最终请求。最短验证路线是读取当前 DOM 已加载的 inline script 文本;如果其中也没有 endpoint,才记录页面版本或状态发生变化,而不是直接删除旧合同。
+
+HK-25 关闭 serializer 后,一个多疑的工程师会问:
+
+> “原生 handler 已经按 `.fascia.act input` 取值,重复 id 风险不是已经不存在了吗?”
+
+回应:对原生 handler 的当前单 active/单 input 路径,重复 id 不会直接取错;这是 E40 对此前风险判断的精确校准。但 handler 仍只取第一个 active Slot、其中第一个任意 input,并依赖全局第一个 selected。框架仍需在触发原生 handler 前验证唯一 active、非负 class、唯一目标 hidden input和精确日期;重复 id 也意味着我们自己的解析器绝不能退回 document-level id selector。
+
+HK-26 又需要回应一个“当前正确即长期正确”的误区:
+
+> “第一个 selected 已经是日期 link,为什么还要额外校验?”
+
+回应:因为 selector 写的是全局 `.selected`,不是语义明确的日期 selector。当前 DOM 顺序只是本页面版本的事实;其他组件新增 selected、动画切换中的旧节点或未来重构都可能改变第一个元素。插件应在每次最终点击前断言第一个 selected 的角色,并验证横向日期 link 与内容卡片的日期值一致。
+
+HK-27 后还要拒绝一个更危险的跳跃:
+
+> “日期同步已经全部为 true,是否可以在当前三个不可用 Slot 中选一个试 POST?”
+
+回应:绝对不可以。日期同步只关闭 serializer 的一个前置条件;当前三个 Slot 仍全部是 `notAvailableFascia`,容量显示为 0,没有任何正向机会。对负向 Slot 添加 act 并 POST 只会绕过网站 UI 防线,既不能证明成功协议,也可能污染预约状态。真实最终 Gate 必须等待网站自然返回一个经过多证据验证的正向 Slot。
+
+HK-9 又补上了更强的反证:三个时段都明确带 `notAvailableFascia`。而网站的 delegated click handler 对所有 `.fascia` 都会添加 `act`,甚至没有在 JavaScript 层排除 unavailable。于是 `.fascia.act` 也不能单独当作可用证据;插件必须在点击前后都检查负向 class。
+
+另一个反驳是:
+
+> “既然网站自己的 handler 允许点击任意 `.fascia`,自动化照着点击再提交不是最贴近原生流程吗?”
+
+回应:不是。网页可能依赖 CSS、pointer-events 或正常用户路径阻止不可用项,但自动化 click 可以绕过这些交互限制并触发 delegated handler。照抄宽松 handler 会把 `notAvailableFascia` 人为变成 `act`,随后 final handler 就会构造真实 POST。框架必须在网站之上增加业务不变量,而不是把网站前端缺少的校验也复制进来。
+
+另一个反驳是:
+
+> “既然已经知道三个 availability/time-slot endpoint,为什么不让 Query 直接调用?”
+
+回应:这些 path 只在用户 Book Session 经过 OTP 和前置 POST 后的 Calendar 页面生命周期中被观察到。尚未证明它们在 Query Session 中独立可用、只读、幂等,也没有当前 method/payload/schema。直接调用既可能绕过网站状态机,也可能造成风控或错误信号;因此它们目前只属于 Book 的待验证内部读阶段。
+
+另一个反驳是:
+
+> “Network 的 initiator 明明写着 `stormcaster.js:2`,为什么不直接把它当作业务源码?”
+
+回应:initiator 反映的是浏览器观察到的调用栈归因,不保证 endpoint 字符串就写在该文件中。E25 已在 `stormcaster.js` 对三个完整名称逐一搜索并得到 0 个匹配;它可能包装了 XHR,也可能只是中间调用层。正确做法是 Sources 全局搜索或从已发生请求的 Initiator stack 向上追溯,而不是根据文件名补猜。
+
+另一个反驳是:
+
+> “静态代码已经写了 `InsertNewBooking`,为什么不发一次空请求看看错误响应?”
+
+回应:不能。这个 endpoint 位于最终 `PRENOTA` handler 中,字段直接是日历 ID、日期和时间,业务语义高度接近真实预约。空请求也可能消耗服务器状态、触发风控或产生不可判定结果,而且不能代表合法请求的响应合同。应先通过静态 handler、现有 response 和正向 Slot 样本完成设计,再在明确最终预约授权下只执行一次合法请求。
+
+另一个反驳是:
+
+> “既然 Hong Kong 已观察到 `service_id=4937` 和 `Turismo=42`,为什么不直接写死?”
+
+回应:`4937` 明确属于 Hong Kong Sede;Dublin 同类服务已经是 `1321`。`42` 虽可能来自平台级字典,但目前只有一个正向 Sede 样本。长期设计应复用 VFS/BLS 的 `apt_configs`,用 routing key 配置 service ID,并通过可见选项文本和配置值交叉校验;代码中不出现城市条件分支。
+
+另一个反驳是:
+
+> “GenerateOTP 使用 GET,是否可以像普通查询一样自动重试?”
+
+回应:不能。HTTP method 是网站实现细节,业务结果是向用户邮箱发送验证码并启动至少 120 秒 UI 冷却。它属于外部副作用命令。超时或响应不明时再次 GET 可能发送多封邮件、触发服务端限流或使旧验证码失效,因此 Query 永不调用,Book 也只能在明确授权后单次调用。
+
+另一个反驳是:
+
+> “前端看到 `"SENT"`,是否就能认定用户一定收到了 OTP?”
+
+回应:不能。它只证明服务器给前端返回了约定的成功标志,不能证明邮件最终投递、收件箱可访问或验证码仍未被后续发送覆盖。E22 同时观察到邮件送达,但真实 Book 仍应把网络响应和邮件/用户输入作为两个阶段;收不到时不能自动重发。120 秒只被证明是 UI 重发冷却,不是 OTP 有效期。
+
+另一个反驳是:
+
+> “`AVANTI` 当前 enabled,是否说明 CAPTCHA 已经解决,可以稍后直接提交?”
+
+回应:不能。enabled 只是一个时刻的页面快照;Turnstile 会过期或超时并 reset。E22 的成功 POST 证明当前 Hong Kong 路径沿原生 click、只带 Turnstile 字段即可进入 Calendar,但每次运行仍必须保持同一页面上下文并在提交前重新确认状态;不能缓存或复制 Token。
+
+另一个反驳是:
+
+> “既然 `getCaptchaToken()` 没有观察到调用点,为什么不删掉它,或者反过来由插件主动调用?”
+
+回应:两种做法都越过证据。E22 已证明当前 Hong Kong 成功 POST 只观察到 Turnstile 字段,没有 reCAPTCHA 字段,因此插件主路径不应主动调用它;但这仍不能证明其他 Sede 或未来页面永远不需要它。长期实现应保留 capability discovery,不把未引用函数写入当前流程,也不删除未来适配所需的判断能力。
+
+另一个反驳是:
+
+> “用户明明选择了 Turismo,为什么 hidden 还是 0;是不是页面坏了?”
+
+回应:不是。预约类型使用 change handler 立即同步,而旅游目的使用另一个时机:`AVANTI` click handler 在 form submit 前才调用 `saveDdlValue()`。HK-7 预检的 visible/hidden=`42/0` 正好印证这个顺序。自动化若提前手工写成 42,反而绕过了网站自己的控制流;正确做法是保持 visible=42,让原生 handler 完成同步。
+
+另一个反驳是:
+
+> “页面自己最多尝试三次获取 reCAPTCHA token,我们是否也可以把整个提交重试三次?”
+
+回应:不能。那三次只是在一次页面流程中尝试取得非空安全 Token,不是对 OTP、表单 POST 或预约业务的重试授权。业务提交结果不明时重复执行可能创建重复草稿、占位或预约,必须先查服务器状态。
+
+另一个反驳是:
+
+> “`AVANTI` handler 调用了文件检查和 AIRE/Passport 提示,是否说明 Visa Book 也必须实现这些字段?”
+
+回应:不能这样推断。真实 Hong Kong visa DOM 没有文件控件,AIRE 提示来自共用脚本的条件分支。插件应根据当前 DOM capability 驱动字段,而不是把共享模板里出现过的每条分支都做成强制业务合同。
+
+另一个反驳是:
+
+> “一次真实登录成功,是否足以宣称 Session 已经长期稳定?”
+
+回应:不足以证明长期稳定,也不能保证网站以后不改 DOM。它能机械证明的是当前实现完成了本阶段合同:正确识别 IAM 表单、只提交一次凭据、到达带双重认证标志的 `/UserArea`、退出时完成清理。长期稳定性仍需运行监控和网站变更后的回归验证,不能由单次成功外推。
+
+## Q-CAL-1 真实 Calendar 到达与翻月失败证据(2026-08-29)
+
+本轮真实 Gate 的敏感 OTP 值不记录;只保留固定形状证据:
+
+| 阶段 | 已观察事实 | 结论 |
+|---|---|---|
+| OTP 前 | form、Turnstile、OTP/AVANTI 控件均 ready | 可以执行一次已授权 OTP |
+| OTP 输入 | `ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true` | macOS focus/readback 修复真实有效 |
+| OTP 后 | `otpValuePresent=true`,其余 preflight 仍 ready | 值留在 DOM,允许一次 AVANTI |
+| AVANTI | Booking POST=1,transition=`followed_redirect_200` | 原生表单成功进入 Calendar |
+| Calendar | `/BookingCalendar` ready,final requests=0 | Calendar 已到达,未尝试最终预约 |
+| 第二 probe | `NoRectError: element has no location or size` | 失败发生在旧 `a.next` 点击,不是 availability parser |
+| 事后审计 | Reservation=0、Waitlist=0 | 本次没有创建预约或候补 |
+
+页面既有 Bootstrap datetimepicker,也有 `.cd-horizontal-timeline`。旧工具的
+`a.next:not(.inactive)` 属于横向 timeline 命名空间,无法承担“日历翻到下一月”的明确合同;
+负责人也直接观察到 Calendar 没有调整月份。
+
+v5 根据通用 Bootstrap 模板推断
+`#datetimepicker .datepicker-days th.next[data-action="next"]`,但真实运行在 Calendar 等待后
+仍得到 candidate=0/actionable=0;这条反证说明不能把第三方上游 DOM 当作 Prenot@Mi 事实。
+本次仍在翻月前停止,final=0;随后只读 `/Reservation` 对账为 0/0。
+
+同一认证状态无需 OTP 即可恢复 Calendar。只读源码和 DOM 探针进一步确认:
+
+- `InizializzaCalendario()` 创建 inline、Italian locale 的 datetimepicker;
+- 网站的 `dp.update` handler 从 `e.viewDate` 取年月并调用
+  `CaricaTimelineOrizzontale(...)`;
+- 空的 `#datetimepicker` 初始化后生成 4 个 `th.dtpicker-next`,其中只有 1 个可见;
+- 初始化自然产生 availability=1,time-slot=0、final=0;
+- 横向 timeline 的 `a.next` 不可见、无 `data-action`,与日历控件不是同一职责。
+
+因此 v6 只认 `#datetimepicker th.dtpicker-next`,继续过滤不可见、无矩形、被遮挡、disabled 和
+多个可交互候选,并只在唯一 actionable 候选时原子点击。
+
+后续一次纯只读 12 个月探针尝试取得了新的 Session 生命周期证据:持久化网页登录态已经
+过期,工具重新完成普通 IAM 登录并到达 `/UserArea` 后,旧的 Calendar 服务端准备态不能再
+通过直接访问 `/BookingCalendar` 恢复。该次执行在任何预约 OTP、AVANTI 或 Availability
+请求前停止,Reservation 基线为 0/0,清理成功,exit 1。这个失败不是“网站月份上限”,而是
+证明 Calendar 准备态不能被一次新的普通登录默认继承;完整 12 个月探针必须在同一认证
+Session 中重新执行一次已授权的 OTP + AVANTI,然后连续只读翻月。
+
+2026-08-30 随后复用负责人刚刚准备好的同一 Calendar Session,执行“找到首个正向日期即停”
+的真实只读扫描。当前月返回 1 个条目、正向 0;下一个月返回 22 个条目、正向 0;第二个未来
+月份返回 22 个条目、正向 15。严格 parser 得到当前最早正向日期为 `2026-10-12`,因此在
+第三次 Availability 请求后立即停止,没有继续探查更远月份。执行前后 Reservation/Waitlist
+均为 0/0,OTP=0、AVANTI=0、`InsertNewBooking`=0,清理成功,exit 0。
+
+这一结果也修正了旧快照:E43 曾观察到 `2026-10-09` 为正向日期,但当前实时响应的最早日期
+已经变为 `2026-10-12`。因此 Query 可以传播“发现时的最早日期线索”,Book 却必须使用用户
+账号重新查询日期和时段;任何旧日期都不能直接进入最终预约。
+
+单独看到 clicked=true 仍不能关闭证据:下一次真实 Gate 还必须捕获第二个
+`RetrieveCalendarAvailability` POST,严格解析 response,并确认前后 request 的
+`selectedDay` 属于不同年月。日志只发布 `selected_month_changed=true`,不发布真实日期或任何
+Token/OTP/表单值。v5 已由真实 candidate=0 证伪;替代合同版本为
+`qcal1-dtpicker-navigation-v6`。
+
+本地验证记录:聚焦 Q-CAL 测试 30/30、Italy 全量离线回归 179/179、两份 Python 内存编译、
+四份文件尾随空格检查均 exit 0。真实 Chromium 的 127.0.0.1 fixture 已观察
+`hidden=0, visible=1`,但整体命令因一个本机 Resource Timing 项触发过宽的“必须为 0”断言而
+exit 1;按连续两次本地浏览器尝试上限未再重试。因此“选对唯一可见控件”已有直接证据,
+但该 fixture 不能代表真实网站 selector。
+
+v6 随后在同一账号可恢复的 Calendar 状态上完成真实只读验证,全程 OTP=0、AVANTI=0:
+
+- 点击诊断:candidate=4、actionable=1、clicked=true;
+- 两个 availability response 均通过严格 parser,分别包含 1 和 22 个日期项;
+- 两个 request 的 `selectedDay` 解析为不同月份;
+- Reservation/Waitlist 前后均为 0/0,final=0;
+- 命令 exit 0,浏览器清理成功。
+
+因此“真实控件唯一可交互、网站自然发请求、请求月份确实变化”的 Q-CAL 翻月证据已关闭。
+配置范围内的多月循环、真实 available 分类接线以及 Book final 仍未由本次验证授权或实现。
+
+## E45:生产 Query 两轮现场验收通过(2026-08-30)
+
+来源:负责人在自己的终端执行 `python -B tools/debug_ita_calendar_gate.py`
+(production_query 模式)后回传的日志。本轮没有由助手重新访问网站。
+
+第二轮原始脱敏结构:
+
+```json
+{
+  "attempt": 2,
+  "availabilityCount": 1,
+  "availabilityStatus": "Available",
+  "earliestDate": "2026-10-13",
+  "lookaheadMonths": 12,
+  "months": [
+    {"month": "2026-08", "positiveDays": 0},
+    {"month": "2026-09", "positiveDays": 0},
+    {"month": "2026-10", "positiveDays": 14}
+  ],
+  "queryRequestDelta": {
+    "availabilityRequests": 3,
+    "avantiPosts": 0,
+    "finalRequests": 0,
+    "otpRequests": 0
+  },
+  "scannedMonths": 3,
+  "snapshotVerified": true,
+  "stopReason": "first_available_month",
+  "success": true,
+  "timesCount": 0
+}
+```
+
+聚合结构:
+
+```json
+{
+  "availabilityRequests": 6,
+  "avantiPosts": 1,
+  "calendarReady": true,
+  "finalRequests": 0,
+  "mode": "production_query",
+  "otpRequests": 1,
+  "passed": true,
+  "positiveQueries": 2,
+  "queryAttempts": 2,
+  "reservationCountAfter": 0,
+  "reservationCountBefore": 0,
+  "waitlistCountAfter": 0,
+  "waitlistCountBefore": 0
+}
+```
+
+负责人同时回传 `ITA_QCAL_GATE_CLEANUP_OK` 与 `EXIT_CODE=0`。已将日志字段与当前验收代码
+核对,10 项一致性检查通过。结论为“本次人工准备后的两轮生产 Query 验收通过”,高确信度。
+
+边界:
+
+- 未回传第一轮完整结果,不推断其具体日期;`positiveQueries=2` 是聚合报告的事实;
+- 未回传启动版本/源码指纹行和原始 Network,不宣称字节级运行溯源或独立复现;
+- 14 是十月份的正向日期数量,不是 14 个被占用或已锁定的时段;
+- `2026-10-13` 是本次观察结果,不延用早期 E43 的 `2026-10-09` 或后续旧样本的
+  `2026-10-12`;Book 仍必须以用户账号的实时结果为准;
+- final 请求为 0 且预约/候补数量没变化,不足以证明服务器内部不存在短暂草稿;
+- 未验证自动邮件读取、无人值守准备、长期运行、跨账号交接、另一 Sede 或最终预约。
+
+## E46:自动接码前置核对与日志诊断(2026-08-30)
+
+本轮只读核对以下现有代码,不读取真实邮箱,不发送 OTP:
+
+- VFS `_read_otp_email()`:共享云 API、当前账号 recipient、外部传入 `sent_at`;VFS 的
+  登录和申请人 OTP 调用均在发码前记 UTC 时间;
+- BLS `_read_otp_email()`:同一共享 API,外层循环调用;不把它的 `wait_sec` 等同于单次
+  SDK 请求的硬超时;
+- `toolkit/vs_cloud_api.py:361`:调用 `POST /api/email-authorizations/fetch`,参数为
+  email/sender/recipient/subjectKeywords/bodyKeywords/sentDate/expiry/onlyText;HTTP timeout
+  为 300 秒,成功仅返回 `data.body`,没有返回匹配邮件的元数据;
+- 该仓库没有邮箱授权状态查询或授权建立方法,也没有此邮箱后端实现;
+- 负责人对“接收 Italy OTP 的邮箱是否已接入该云服务”回答“不确定”。状态保持未知,
+  不能由手工收到 OTP 推断为云端有读取权限。
+
+另外只用 fake HTTP session、合成正文与收件人,将当前 `_perform_request()` 方法体配合
+真实 `VSC_DEBUG` 宏执行到内存日志。结果:DEBUG 下正文/收件人标记可见;INFO 下均不可见。
+诊断 exit 0、网络请求 0;它证明潜在日志路径,不证明发生过真实数据泄露。
+
+此问题和邮件模板、邮箱授权、过滤语义共同记入通用设计 §25。没有修改共享 SDK 或 VFS/BLS,
+没有设置转发或注册新邮箱服务。后续只请求一封已收到邮件的脱敏样本,不要求再次发 OTP。
+
+## E47:指定 OTP 邮件标签访问受阻(2026-08-30)
+
+负责人分享了现有 Gmail 邮件标签,目的是补齐 Italy OTP 邮件模板证据。本轮仅尝试读取
+该标签,不搜索其他邮件,不调用云端取信接口,不发送 OTP,不修改邮箱设置。
+
+实际检查:
+
+1. 检索当前工具,没有找到可读取该 Gmail 邮件的已连接邮件接口;没有建议安装新服务。
+2. Chrome 实例匹配数量为 1;`openTabs()` 返回的标签标识、标题和 URL 与负责人分享值
+   精确匹配,数量为 1。首次接管后再次核对 URL/标题均相同。
+3. 标题以 `OTP Code` 开头。它只是标签元数据,不是已读取的邮件主题字段,也不能证明
+   实际发件人、正文模板或验证码格式。
+4. 第一次读取 DOM 内容超时,没有返回任何邮件正文;准备的输出脱敏步骤未取得输入。
+5. 按浏览器恢复指引尝试一次同标签只读恢复,再次超时,没有取得正文。达到两次上限,
+   停止浏览器重试,没有切换其他浏览器、读取 Cookie、导出邮件或设置转发。
+
+未记录邮箱地址、邮件深链/标识、真实验证码或原始正文。没有运行生产 Query、Book、OTP
+发送或共享邮件 API。云端邮箱授权状态保持“未知”,邮件模板 Gate 保持“待补证”。
+
+下一步只需要负责人提供这封**已收到邮件**的脱敏截图或文字:实际发件人地址、主题、
+验证码相关正文;真实验证码用 `[OTP]` 替换,遮住收件人、姓名及动态链接。无需新发验证码。
+
+初见审查:“既然标题是 OTP Code,为什么不直接据此写匹配规则?”
+
+回应:标题不包含发件人或验证码上下文,同名邮件也可能来自其他系统。必须取得邮件字段
+与正文证据,才能设计精确匹配;浏览器可打开邮件也不等于共享云端 API 已有读取权限。
+
+## E48:Italy OTP 邮件文本样本(2026-08-30)
+
+来源:E47 浏览器读取失败后,负责人手工转述邮件字段及验证码相关正文。没有重新读取
+Gmail、云端邮件 API 或原始邮件;以下是脱敏记录,不是完整邮件导出。
+
+```json
+{
+  "source": "user_transcription",
+  "sender_display_name": "Prenotami",
+  "sender_address": "noreply-prenotami@esteri.it",
+  "subject": "OTP Code",
+  "body_excerpt_redacted": "OTP Code:[OTP]",
+  "observed_code_shape": "6 ASCII digits",
+  "recipient_verified": false,
+  "cloud_mail_access_verified": false,
+  "automatic_otp_verified": false
+}
+```
+
+### 已补齐的事实及边界
+
+- 对这份转述中的字段与六位数字形态,确信度高;邮件源认证、后台读取结果尚未验证。
+- `Prenotami` 是显示名,`noreply-prenotami@esteri.it` 才是发件地址,不能混作同一字段。
+- 已取得英文 `OTP Code:` 后紧跟数字的正文片段;不能据此宣称整封邮件只有一行、完整
+  正文只有一个候选,或所有语言/地区模板相同。
+- 未获得收件人、发送/接收时间、邮件唯一标识或验证码有效期。不能从 SDK 的 `expiry`
+  或页面重发倒计时倒推出该码的有效期,也不把当前打开的 Gmail 账号自动当作 recipient。
+- 发件地址和主题可用于定位邮件,但不是发送方真实性或防串号的独立证明;邮件认证信息、
+  当前账号过滤和发码后的时间窗口仍需已有后端合同或受控验证。
+- 本轮没有记录或使用真实验证码,没有登录、发码、填码、AVANTI、Calendar 或最终预约请求。
+
+### 对后续设计的影响(尚未实现)
+
+继续调用 VFS/BLS 已使用的 `VSCloudApi.fetch_mail_content()`。该样本可为 sender、
+subjectKeywords、bodyKeywords 提供候选过滤值,不再照搬 VFS/BLS 的站点文案。云端是否
+按地址精确匹配、如何组合关键字及如何排除旧邮件仍按 §25.3 验证,不能用传参代替验收。
+
+正文提取按已观察的 `OTP Code:` 上下文识别六位 ASCII 数字,保留字符串和前导零;
+无匹配、多个候选、格式不符或未知模板应停止,不能抓取全文任意六位数字或随意选首个。
+这是解析合同候选,不是已运行的 parser;完整正文与云端 `only_text` 输出仍需比对。
+
+下一项关键证据是现有云端邮件服务的授权记录/受控读取能力。当前不需要新的验证码样本,
+不请求密码、密钥或整个邮箱导出;先确认既有服务的管理入口,再核对准确的授权邮箱与
+当前 Italy 账号收件人的对应关系。共享 SDK 的日志/异常脱敏前置问题(E46)仍未修复。
+
+初见审查:“现在已经知道验证码格式,为什么还不能宣布自动接码完成?”
+
+回应:识别数字只解决解析;自动接码还要证明读取的是获授权邮箱里、当前账号本次发码后
+收到的邮件,且不会选到旧码/其他账号的码或把正文写进日志。E48 没有提供这些运行证据。
+
+## E49:现有前后台邮件服务复用调查(2026-08-30)
+
+### 范围、来源与版本
+
+负责人明确要求使用 `luna worker max` 子代理调查两个项目。实际使用两名 `luna_worker`
+子代理(该角色固定使用 Luna / max),各负责一个仓库,禁止写文件或访问实际邮箱/后台。
+主代理核对 Coordinate 调用端、关键源码及协议语义,并在内存中执行合成数据诊断。
+
+| 项目 | 调查版本/状态 | 定位与证据 |
+| --- | --- | --- |
+| `/Users/zhangwei/JSWorkSpace/personal/web-ui` | HEAD `b21b7ca`;工作区干净 | Next.js 14.1.0 / React 18,App Router;`package.json:6` 定义 dev,`:7` build,`:8` start;`src/app/layout.tsx:8` 为根布局 |
+| `/Users/zhangwei/JSWorkSpace/personal/webapp` | HEAD `fbb82bb`;`master...origin/master`;工作区干净 | FastAPI / SQLAlchemy Async;Docker 使用 Python 3.9;`starter.py:23` 生成启动命令,默认监听 `0.0.0.0:8888` |
+| Coordinate | 现有脏工作区保留 | `toolkit/vs_cloud_api.py:361` 为既有 VFS/BLS 共用的邮件客户端,本轮未修改 |
+
+两个项目及检查过的父目录均未发现适用 `AGENTS.md`。没有安装依赖、构建、启动服务、
+读取 `.env` 值、查询数据库、调用 IMAP/API、发送邮件或 OTP,也没有验证部署地址可用。
+以下“已确认”指当前源码/离线行为,不把本地 HEAD 等同于线上部署版本。
+
+### 1. 前端:已有后台,但没有邮箱授权管理页面
+
+关键文件:
+
+- [AdminSidebar.tsx](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/components/admin/AdminSidebar.tsx:28):
+  真实菜单包含 `/admin/users`、`/admin/accounts`、`/admin/tasks` 等,没有邮箱授权菜单。
+- [api.js](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/lib/api.js:4):API base URL 来自
+  `NEXT_PUBLIC_API_URL` 或源码默认值;`:17` 使用浏览器 `rsid` 注入 Bearer。
+- [next.config.js](/Users/zhangwei/JSWorkSpace/personal/web-ui/next.config.js:7):`/api/:path*`
+  rewrite 到配置的 host;没有本地 API handler 实现这套邮箱接口。
+- [BindEmailModal.tsx](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/components/BindEmailModal.tsx:73):
+  `/api/auth/send-bind-code` 与 `:94` 的 `/api/auth/bind-email` 是门户邮箱绑定验证。
+- [user.ts](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/types/user.ts:8):`email` 和
+  `email_verified` 表示门户邮箱验证,不能解释为 IMAP 授权已登记或仍有效。
+- [AccountDetailDrawer.tsx](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/components/admin/accounts/AccountDetailDrawer.tsx:131):
+  仅把任意 `extra_data` 内含 mail 的键分组;没有邮箱授权状态语义,还可能展示敏感值,
+  不应为核验而复制原始 JSON、Token 或 Cookie。
+- [TaskTable.tsx](/Users/zhangwei/JSWorkSpace/personal/web-ui/src/components/admin/tasks/TaskTable.tsx:127):
+  任务收件人来自用户输入;`:203` 的 `/api/vas/notification/send_email` 是出站通知,不是收信。
+
+在 `src/lib src/app src/components src/types docs` 与入口配置中,邮箱授权、取信和 OAuth
+相关限定搜索均未命中(exit 1 表示无匹配)。因此不要引导负责人去寻找不存在的“邮箱授权”
+菜单,也不要把 `/admin/users` 的“邮箱已验证”当作自动接码准入证据。
+
+### 2. 后端:管理入口和权限
+
+后端也没有另一套 HTML/template 管理页面。它提供 FastAPI 文档/API:
+
+- [main.py](/Users/zhangwei/JSWorkSpace/personal/webapp/app/main.py:27) 没有覆盖文档入口;
+  子代理核对本地 FastAPI 默认值为根路径 `/docs`、`/redoc`、`/openapi.json`,不是 `/api/docs`。
+  线上域名、反向代理路径及文档是否实际开放未验证。
+- [email.py](/Users/zhangwei/JSWorkSpace/personal/webapp/app/api/endpoints/email.py:47):
+  `GET /api/email-authorizations/email/{email}` 可按邮箱地址查单条登记;没有 exists-only 接口。
+- [main.py](/Users/zhangwei/JSWorkSpace/personal/webapp/app/main.py:176) 与
+  [auth.py](/Users/zhangwei/JSWorkSpace/personal/webapp/app/core/auth.py:24):邮箱路由要求
+  管理员 Bearer session;不是借用 Gmail 网页登录态,也不能仅凭有 token 就认为角色满足。
+- [模型](/Users/zhangwei/JSWorkSpace/personal/webapp/app/models/email_authorizations.py:5):
+  全局唯一 email、authorization_code、IMAP/SMTP/代理配置和时间戳;没有 owner/tenant、
+  active/revoked/expiry 或最近连通性检测字段。它是管理员级共享记录,不是每用户独立授权模型。
+- [get_by_email](/Users/zhangwei/JSWorkSpace/personal/webapp/app/services/email_authorizations_service.py:57)
+  使用数据库 `email ==`,没有主动 trim/lower;大小写细节仍取决于数据库。创建/修改只是
+  持久化,不试连邮箱;查到记录不等于凭据有效。删除是物理删除,本轮没有执行。
+
+**敏感响应边界:** [EmailAuthorizationOut](/Users/zhangwei/JSWorkSpace/personal/webapp/app/schemas/email_authorizations.py:32)
+继承包含 authorization_code 和代理凭据的字段;[success()](/Users/zhangwei/JSWorkSpace/personal/webapp/app/utils/response.py:6)
+会序列化 ORM 列。因此列表/详情不是脱敏输出,不要求负责人截图或粘贴完整 JSON。
+后续若只核对登记,需要在获授权的本地环境中只输出存在性和非敏感配置是否齐全,并丢弃凭据。
+
+### 3. 取信合同:客户端与后端已对齐的事实
+
+[fetch endpoint](/Users/zhangwei/JSWorkSpace/personal/webapp/app/api/endpoints/email.py:53)
+绑定 POST Query 参数而非 JSON body,和 Coordinate 现有 SDK 对齐:
+
+| 字段/行为 | 当前后端实现 | Italy 验收含义 |
+| --- | --- | --- |
+| `email` | 查询已存授权记录,以 `auth.email` 和 `authorization_code` 登录 IMAP | 必须确认实际登记与登录有效;不可从浏览器邮箱或门户状态推断 |
+| `sender` | raw From header 中大小写不敏感的子串 | 显示名和地址都可能被匹配;不是地址解析/精确相等或身份认证 |
+| `recipient` | raw To header 中大小写不敏感的子串 | 不查 Cc、Delivered-To 或信封收件人;别名/转发需专门验证 |
+| `subjectKeywords` | 逗号分割、trim,各候选 OR-any,大小写不敏感 | 不能把多个关键字理解成全部必须满足 |
+| `bodyKeywords` | 同样 OR-any,在合并正文字符串上匹配 | 不能用几个词拼成未经证实的严格模板筛选 |
+| `sentDate` | 严格秒格式,按 UTC 解释;比较最后一个 Received 头解析出的 UTC 时间 | 不是 Date 或 IMAP INTERNALDATE;秒精度不等于会话 nonce |
+| `expiry` | 时间窗口闭区间 `[sentDate, sentDate + expiry]`,另限制轮询时长 | 是邮件筛选窗口,不是 Prenot@Mi OTP 的真实有效期 |
+| `onlyText=True` | 仍合并 text/plain 与原始 text/html,保留 HTML;只不追加图片 | 不是 HTML 清理,也不能保证验证码只出现一次 |
+| 返回 | code=0,data 仅有 body;不返回命中邮件 metadata | 客户端无法据返回值重新精确验证 From/To/时间或唯一性 |
+
+核心实现见 [service.py:243](/Users/zhangwei/JSWorkSpace/personal/webapp/app/services/email_authorizations_service.py:243)、
+[过滤段:355](/Users/zhangwei/JSWorkSpace/personal/webapp/app/services/email_authorizations_service.py:355) 与
+[正文提取:1012](/Users/zhangwei/JSWorkSpace/personal/webapp/app/services/email_authorizations_service.py:1012)。
+
+现行 provider 是 `imaplib.IMAP4_SSL` 加可选 SOCKS5。同文件中未被 fetch endpoint 调用的
+legacy 数据库读信函数不是当前链路;没有为此另建 Provider、Resend 或数据库邮箱服务的必要。
+
+### 4. 不能遗漏的运行边界
+
+1. **候选范围:** `select("INBOX")`,`search(None, "ALL")` 后只取最近 10 个消息序列号,
+   再取 RFC822、解析 Received、排序和过滤。不是 IMAP UID 查询,也不是整个时间窗口内
+   的完整邮件搜索;繁忙主邮箱可能把目标邮件挤出候选范围。
+2. **不是唯一/消费语义:** 返回排序后第一个命中,不验证全体候选唯一;没有每邮箱锁、
+   去重或消费记录。重复调用可能拿到同一封;不能等同于“本次会话独占的一次性码”。
+3. **不是硬超时:** 每 3 秒轮询、循环预算为 `min(300, expiry)`,但建连、login、fetch
+   没有显式 socket timeout;不能保证整个请求 300 秒内完成。SDK 的 300 秒 HTTP timeout
+   是另一层限制,不能证明超时后服务端已停止。
+4. **不是完全只读邮箱:** 默认读写 SELECT + RFC822。RFC822 等价 BODY[],有隐式设置
+   `\Seen` 的协议副作用;BODY.PEEK 才是不会隐式设置该标志的替代形式。本轮未实测真实
+   邮箱已读状态。依据:[RFC 3501 §6.4.5](https://www.rfc-editor.org/rfc/rfc3501.html#section-6.4.5)。
+5. **错误不是一类:** `/fetch` 未命中等待结束为业务 40401 / HTTP 404;`/fetch-top` 无命中
+   是 code=0、body=null。无效日期、缺失 Subject、IMAP/解析错误可能进入全局 500,不能
+   当作“没收到邮件”一律处理。
+6. **不用 fetch-top 降级:** [fetch-top](/Users/zhangwei/JSWorkSpace/personal/webapp/app/services/email_authorizations_service.py:478)
+   没有 sentDate/time filter、不轮询;它不是当前会话新邮件筛选的安全替代。
+7. **文本并不等于唯一码:** multipart/alternative 可能同时输出 plain 和 HTML 中同一个码。
+   E48 的一行样本只能作为格式依据;不可将“前缀出现两次”直接视为两个不同验证码,也
+   不应未经验证就对任意转发/引用内容去重后取首码。
+
+源码可以关闭“后端到底怎么筛选”的知识缺口,不能关闭真实邮箱/新旧码/跨账号验收。
+填入完整地址并不能改变后端子串匹配语义;当前返回又没有 From/To metadata,所以仅在
+Italy 插件中添加“固定 sender 字符串”不能宣称已经做了本地精确地址校验。
+
+### 5. 隐私与独立安全建议(均未修改)
+
+- 既有 Coordinate SDK DEBUG 正文/参数日志风险仍见 E46。
+- [后端访问日志](/Users/zhangwei/JSWorkSpace/personal/webapp/app/main.py:38) 记录未脱敏完整
+  URL Query,其中可含邮箱、筛选文字及时间。后端 fetch 没有直接打印 OTP 正文,不将
+  这个事实和 SDK 的正文日志混为一谈。
+- endpoint 的 `print(auth)` 通常只输出模型默认 repr;当前类无自定义 repr,不能凭这一行
+  断言授权码已被打印。Received DEBUG 与全局异常详情仍需要日志配置/合成数据验收。
+- [iris.py](/Users/zhangwei/JSWorkSpace/personal/webapp/scripts/iris.py:14) 存在硬编码 Bearer
+  凭据;值未复制、未验证有效性。它调用发送接口,不是现行 fetch provider。列为独立凭据
+  管理复核项,不在 Italy 调研中擅自轮换、删除或修改。
+
+### 6. 实际验证记录
+
+子代理报告与主代理复核:
+
+- 两仓 `git status --short` / `git diff --name-only`:exit 0,输出为空;HEAD 如上。
+- 前端限定关键词/测试文件搜索:exit 1、无匹配;这证明所查范围未包含对应实现,不是运行错误。
+- 后端 endpoint/service/provider `rg`:exit 0;相关 8 个 Python 文件 AST parse:exit 0;
+  `rg -n 'EmailAuthorization|email-authorizations|fetch_email_authorizations|_extract_body|IMAP4_SSL' tests`
+  exit 1、无匹配。发现 27 个测试函数,但没有邮件 fetch 专项测试。
+- 子代理仅检查 FastAPI 构造默认文档参数,exit 0;没有 import 后端 app 或启动服务。
+- 主代理通过 `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -` 执行当前 SDK 方法的 AST
+  加 fake HTTP,验证八个 query 参数、空 body、一次调用、300 秒 HTTP timeout 与仅返回 body:
+
+```text
+CLIENT_CONTRACT_OK params=8 transport=query_string empty_body=true http_timeout_seconds=300 client_calls=1 returns_body_only=true
+NETWORK_REQUESTS=0 SYNTHETIC_DATA_ONLY=true
+```
+
+- 主代理以同一命令形式提取并执行现行 `_extract_body` 方法,不导入 webapp 应用;用五份
+  内存合成邮件验证 plain、HTML、multipart alternative、附件、图片,另用 AST 核对 endpoint
+  八个 Query 参数及 int/bool 绑定:
+
+```text
+BACKEND_BODY_CONTRACT_OK scenarios=5 assertions=7 html_retained=true alternative_prefix_occurrences=2 whitespace_collapsed=true
+CLIENT_SERVER_QUERY_BINDING_OK fields=8 expiry_type=int only_text_type=bool
+NETWORK_REQUESTS=0 APPLICATION_IMPORTS=0 SYNTHETIC_DATA_ONLY=true
+```
+
+上述两条 Python 诊断均 exit 0。它们验证现有行为,而不是宣布这些行为符合 Italy 生产准入。
+没有创建新的测试/生产文件;没有运行前端构建、后端 pytest 或真实取信。后端现有测试可能
+读取环境配置、连接数据库/Redis或外部 HTTP;此阶段不执行。Coordinate 业务代码未变,
+本轮也不重复运行已归档的 220 项业务回归来冒充跨项目在线验收。
+
+### 7. 下一步与初见审查
+
+先在负责人已授权的环境中核对**一个指定邮箱**的登记存在性、管理员身份及 IMAP 必需配置
+是否齐全;仅输出脱敏摘要,不传原始响应,不发送 OTP,不调用 fetch、不读取收件箱。
+如果登记缺失或凭据需更新,先明确授权与变更范围,不替负责人自动填写或开通。
+
+之后再收敛已定位的筛选、MIME、超时、日志与已读副作用合同;涉及 webapp/共享 SDK 的
+修改必须另行批准。继续复用现有 IMAP 服务、API、凭据登记和 VFS 的调用顺序,不新建后台
+页面或邮件服务来完成本阶段。
+
+初见审查:“既然 VFS/BLS 就是调用这套服务,Italy 直接换 sender/subject 不就行了?”
+
+回应:已有 API/provider 足以证明复用方向可行;但完整地址参数不改变子串匹配,onlyText
+不意味着纯文本,取信不保证唯一或无已读副作用。应复用既有链路并对 Italy 的真实邮件与
+准入条件做最小验证,而不是把其他插件使用过当作本次自动接码已通过的证据。
+
+## E51:15 分钟 Calendar 持续查询与受控重建(2026-08-30)
+
+负责人在自己的终端执行 `tools/debug_ita_soak.py --calendar --run --duration-seconds 900 --min-wait 300 --max-wait 300 --restart-after-probes 1`,使用既有香港 `4937` 配置,随后提供完整日志。版本为 `qcal1-calendar-soak-v11`,源码指纹 `64b0581dbd3e`,与本地已验证制品一致。
+
+结果:实际耗时 909 秒;3 次正向 Query 均重新扫描到 10 月,快照最早日期为 `2026-10-13`;一次受控正常关闭与重建,恢复后有 2 次新 Query。准备阶段 OTP 1、AVANTI 1;后续监测 OTP/AVANTI/final 均 0;审计缺口 0;预约/候补均 0 → 0;正常清理,`passed=true`、`EXIT_CODE=0`。
+
+完整脱敏 JSON、逐轮时间和验收核对记录在 [CS3R §11](./ita_query_recovery.md)。不复制日志中的 OTP、profile 标识、指纹 seed、调试端口或账号信息。
+
+边界:新实例直接到 `/UserArea`,`expiryCauses.authentication=0`、`configuredLifetime=0`;本次证明仍有效持久认证下的浏览器重建恢复,而不证明真实登录过期或自然断网恢复。无号、2/24 小时、跨账号/地区与 Book 最终预约仍依各自 Gate 验收。ITA-OTP-01 保留为必须完成的 TODO。

+ 2194 - 0
docs/ita_plugin_generic_schengen_design.md

@@ -0,0 +1,2194 @@
+# Italy 插件:通用短期申根旅游签证单人预约交付方案
+
+> 状态:CS3A VERIFIED(一次负责人现场回传);CS3B / OTP-AUTO 邮箱接入列为待办,暂缓
+>
+> 修订:2026-08-30 / R5(保留 R3/R4 的设计与历史验证记录)
+>
+> 当前 Query 恢复合同:[CS3R:掉线恢复与持续盯号](./ita_query_recovery.md)。本地实现、387 项 Italy 回归及零网络预检已验证;E51 的 15 分钟实测已通过(909 秒、3 次查询、1 次受控恢复、exit 0,版本指纹一致)。真实认证过期及 2/24 小时现场证据待补。自动处理重新需要 OTP 仍是必须完成的 ITA-OTP-01,不以人工停止点代替完成。CS3R 不授权上线或 Book 最终提交。
+>
+> 唯一事实源:[Italy Discovery](./ita_plugin_discovery.md)
+>
+> 历史实现记录:[Italy Recovery Design](./ita_plugin_recovery_design.md)
+>
+> 约束:香港是第一条正向协议样本,不是代码分支;Dublin 是无号回归样本,不是默认产品目标。CS3A 的人工准备加两次生产 Query 已通过一次现场验收;负责人确认 Query 邮箱尚未接入并授权云邮箱 API,要求记为待办。当前不执行邮箱接入、新的 OTP、真实取信、共享框架修改或最终预约。
+
+## 0. D0 设计审查什么算完成
+
+D0 只完成设计审查。以下条件必须同时满足,缺一项都不能说“方案完成”:
+
+1. 当前代码、VFS/BLS、Sentinel/OrderBooker 和 E1–E44 证据之间没有未解释的矛盾;
+2. “如何发现真实号源”“如何把信号交给用户账号”“如何只提交一次最终预约”各有机械判定合同;
+3. 所有 P0/P1 都有唯一状态:已关闭、由某个 Change Set 关闭,或由明确的外部 Gate 关闭;不得存在无负责人、无验证方法的“以后再看”;
+4. 配置、文件边界、状态机、重试、恢复、测试、准出、回滚全部可执行;
+5. 生产方案不依赖香港/Dublin 条件分支,不复制 Query 账号的 Cookie、页面对象或临时 Slot ID;
+6. E43/E44 正向 Slot 只用于解析、页面选择与 precommit 取证;没有最终授权时 InsertNewBooking 必须为 0;
+7. 文档结构检查、陈旧结论反向扫描、敏感信息扫描和 whitespace 检查全部 exit 0;
+8. D0 阶段对 plugins、tools、test 和 config 的新增修改数为 0。
+
+2026-08-29 负责人随后明确批准 R3、CS1 和 CS2。该批准不改写 D0 的历史完成标准;CS1/CS2 的实际文件、测试和边界记录在 §17、§23.2 与 §23.3。
+
+## 1. 结论先说人话
+
+旧方案只有一半正确。
+
+正确的一半是:
+
+~~~text
+团队账号负责发现
+  → Sentinel 发布短 TTL 信号
+  → 用户账号自己的热 Session 收到信号
+  → 用户账号重新检查
+  → 只使用当前 Session 的日期、时间和动态状态完成预约
+~~~
+
+不正确的一半是:把“能进入 bookingForm”当成足够好的生产信号。
+
+香港已经真实证明两件必须同时记住的事:
+
+~~~text
+GET /Services/Booking/4937
+  → 200 + bookingForm
+  → OTP + AVANTI
+  → Calendar
+  ├─ 默认 2026-08 窗口:日期/时段均为负向
+  └─ 向后到 2026-10:出现真实正向日期与时段
+       Availability:SlotLiberi=1 / SlotRimanenti=0
+       TimeSlot:普通 fascia、无红点、显示 (1)
+~~~
+
+所以,bookingForm 只表示“门开着”,不携带日期、扫描范围和容量;它既不能单独证明有号,也不能单独证明无号。若 Sentinel 每 60–300 秒都把这个弱事实发给用户 Book,用户账号会反复发送 OTP,却仍不知道目标日期范围内是否有 Slot。这既不能可靠回答“什么时候有号”,也不珍惜真实机会。
+
+R3 的推荐方案是:
+
+~~~text
+团队 Query 账号
+  ├─ 每个认证/业务 Session 至多一次:
+  │    原生选择单人 + 旅游 → Privacy → OTP → AVANTI
+  │    进入自己的 Calendar Session
+  │
+  └─ 后续每个 Query probe:
+       在配置日期范围内逐月读取 Availability
+       → 不能因默认月份无号提前结束
+       → 至少一个正向日期才返回 Available
+       → times 保持空;不把动态 Slot 状态跨账号传递
+
+Sentinel
+  → 原样发布 VSQueryResult Available 强信号
+
+用户 Book 账号
+  → 独立登录、独立 OTP、独立 Calendar
+  → 重查同一服务、日期和时段
+  → 满足全部提交前不变量后
+  → 原生点击一次 btnPrenotaNoOtp
+  → 只读核对预约结果
+~~~
+
+这叫“准备型 Calendar Query”。它复用 VFS/BLS 已有的最小强信号:Query 发布真实日期,`DateAvailability.times=[]`,Book 在自己的 Session 重新查具体时段;也复用现有账号池和信号链路。Query 不主动为每个日期扇出 TimeSlots 请求,页面原生自动产生的 TimeSlots 只作为诊断,不作为信号前提。它比旧弱信号多一次团队账号的 OTP + AVANTI 副作用,因此必须经过单独授权和无预约副作用 Gate。E43 已用同日 TimeSlots 交叉证明 Availability 的正向 `1/0` 确实对应一个真实时段,但没有替这些安全 Gate 背书。
+
+旧弱信号仍有价值,但只用于 Discovery、告警或手工唤醒,默认不得触发生产 Book。
+
+## 2. “100% 信心”如何工程化
+
+外部网站、自然放号和网络永远不受本项目 100% 控制。把这种不确定性口头改成“有信心”是不诚实的。
+
+本方案把 100% 定义成分阶段准入:
+
+| 阶段 | 达到 100/100 的机械条件 | 当前状态 |
+|---|---|---|
+| 设计一致性 | 本文无内部矛盾;P0/P1 全部有关闭路径;检查 exit 0 | 已验证 D0 |
+| CS1 配置与纯解析器 | 只实现已观察 schema;全部离线 fixture 通过;网站写请求 0 | 已验证:28 个协议测试 + 30 个现有 Italy 回归测试 |
+| CS2 通用路线接线 | Plugin、配置和本地工具只从 routing key 解析 route;HK/Dublin 同路径;网站请求 0 | 已验证:137 个相关离线测试 + 静态扫描 |
+| 强 Query | 团队账号准备 Calendar 被单独授权;预约列表前后不变;重复只读 probe 无 OTP/AVANTI/最终 POST | 外部 Gate |
+| Book 到最终按钮前 | 用户 Session 的 OTP、AVANTI、Calendar、正向 Slot 合同全部真实验证;最终 POST=0 | 外部 Gate |
+| 一次最终 Canary | 用户明确需要该真实预约;preflight 全绿;InsertNewBooking 次数=1;结果可权威核对 | 外部 Gate |
+| 生产准出 | 端到端 Canary 成功;异常响应和重启恢复不重复提交;第二 Sede 同协议验证 | 外部 Gate |
+
+纪律是:某阶段没有达到 100/100,就不进入该阶段的有副作用动作;不是把总置信度四舍五入成 100。
+
+## 3. 产品目标、范围和成功定义
+
+### 3.1 产品目标
+
+使用已明确授权的团队成员真实账号检测任意已配置 Prenot@Mi Sede 的单人短期申根旅游签证真实号源,并使用申请人自己的真实账号完成预约。
+
+香港用于跑通第一条完整成功链;通用性由配置和第二 Sede 回归证明。
+
+### 3.2 首版范围
+
+- 一位申请人;
+- 短期申根;
+- 目的为旅游;
+- 团队账号 Query,用户账号 Book;
+- 用户日期范围过滤;
+- 当前页面原生 Turnstile 状态;
+- 邮件 OTP;
+- 一个 OrderBooker 实例处理一份订单;
+- 最终返回预约编号、日期、时间和账号;
+- 未知页面、未知字段、未知 Slot 状态一律 fail-closed。
+
+### 3.3 明确不做
+
+- 家庭、多人、同行人;
+- 商务、探亲、学习、工作、国家 D 类签证;
+- 自动切换 Sede;
+- 自动取消、改期或候补;
+- 绕过 CAPTCHA、Turnstile、限流或网站公平机制;
+- 从传闻预测放号时间;
+- Query 与 Book 共享 Cookie、Profile、DOM 或 CSRF;
+- 为香港复制一个 ita_hk_plugin.py;
+- 在本项目中重做 Sentinel、OrderBooker、Redis、邮箱服务或工作流引擎;
+- 未经用户授权执行真实最终预约。
+
+### 3.4 什么才叫 Book 成功
+
+以下五项必须同时成立:
+
+1. POST /BookingCalendar/InsertNewBooking 在本次机会中恰好执行一次;
+2. 服务端结果或随后只读的 /Reservation 显示一条新预约;
+3. 预约编号、日期和时间来自同一条记录;
+4. 日期、时间、Sede 和目标 route 与本次选择一致;
+5. VSBookResult.success=True 且 urn/book_date/book_time/account 全部填充。
+
+OTP 发送成功、AVANTI 302、进入 Calendar、看到正向日期、点击 PRENOTA、HTTP 200 都不能单独算成功。
+
+## 4. 当前事实与代码现状
+
+### 4.1 已真实验证的网站链
+
+~~~text
+Public / IAM
+  → callback_1 + callback_2
+  → /UserArea
+  → /Services
+  → /Services/Booking/{service_id}
+     ├─ Dublin 1321:302 → /Services + 明确无号 marker
+     └─ Hong Kong 4937:200 + bookingForm
+          → single=1
+          → tourism=42
+          → PrivacyCheck
+          → GET GenerateOTP:200 / SENT / 邮件送达
+          → OTP 输入
+          → 原生 AVANTI
+          → POST /Services/Booking/4937:302
+          → GET /BookingCalendar?...:200
+          → Availability / TimeSlots
+          → btnPrenotaNoOtp
+          → POST InsertNewBooking
+             [从未执行]
+~~~
+
+关键纠正:
+
+- OTP 在 AVANTI 之前,不在 Calendar 之后;
+- Calendar 上的 btnPrenotaNoOtp 是最终预约按钮,不会再发送第二次 OTP;
+- bookingForm 本身不能表达号源;同一流程既观察到默认月份无号,也观察到后续月份有号;
+- selected、active、enabled 按钮都不等于有号;
+- 配置中的 Services service_id 与 Calendar DOM 的 #idServizio 不是同一来源,禁止混用;
+- 最终 handler 从 active Slot 的后代 input 取 daily calendar ID,而不是全局按重复 HTML id 查找。
+
+### 4.2 Calendar 已观察协议
+
+| 能力 | Method / Path | 已观察输入 | 已观察输出 |
+|---|---|---|---|
+| 日期 | POST /BookingCalendar/RetrieveCalendarAvailability | JSON:_Servizio、selectedDay | 外层 JSON 字符串,内层数组:DateLibere、SlotLiberi、SlotRimanenti |
+| 时段 | POST /BookingCalendar/RetrieveTimeSlots | JSON:selectedDay、idService | 外层 JSON 字符串,内层数组;含两个 Slot 数量、时间和 daily ID |
+| 最终预约 | POST /BookingCalendar/InsertNewBooking | form:idCalendarioGiornaliero、selectedDay、selectedHour | 静态观察含 errorMessage、url;真实结果未知 |
+
+网站当前前端判定:
+
+- 日期 `SlotLiberi>0 AND SlotRimanenti>=0` 是 E43 已观察的正向组合;`SlotRimanenti=0` 不能判无号;
+- Slot SlotRimanenti < 0 会得到 notAvailableFascia + dotRed;
+- SlotLiberi 用于显示括号中的数量;E43 正向 `1/0` 显示 `(1)`,负向 `0/-1` 显示 `(0)`;
+- 唯一非负 Slot 会自动带 act;
+- delegated click 甚至能给负向 Slot 加 act,所以 act 不是安全证据;
+- Calendar 初始化找不到目标日期时会静默回退到第一天并程序化点击;
+- 当前稳定 DOM 有一个 timeline selected 和一个 content selected,日期值相同。
+- 默认 8 月窗口没有正向 Slot,但 10 月存在;任何 Query 都必须扫描完整配置日期范围。
+
+### 4.3 当前代码已经做到哪里
+
+plugins/ita_plugin.py 当前只实现:
+
+1. IAM 登录并以 /UserArea + .app-menu + /Services 作为成功条件;
+2. 从顶层 free_config.service_id 查一个服务;
+3. Dublin 已知无号分类;
+4. bookingForm 返回 success=True + NoneAvailable 弱信号;
+5. Book 使用用户 Session 再调用一次 Query;
+6. 到达 bookingForm 后只采集 allowlist 结构,停在 AVANTI 前;
+7. keep_alive() 仍为空。
+
+尚未实现:
+
+- routing_key → apt_configs;
+- 香港和多 Sede 调试目标;
+- 表单选择、Turnstile preflight、OTP、AVANTI;
+- Calendar/TimeSlots 解析;
+- 正向 Slot 选择;
+- 最终一次性提交;
+- /Reservation 对账;
+- 模糊结果写屏障。
+
+当前调试工具和大部分 fixture 仍硬编码 Dublin 1321。这属于待通用化的实现债务,不是通用设计。
+
+## 5. 从大到小复用 VFS/BLS
+
+### 5.1 复用矩阵
+
+| 层级 | 现有参照 | Italy 决策 | 复用程度 |
+|---|---|---|---:|
+| 插件接口 | IVSPlg | 原样实现生命周期 | 100% |
+| Query 调度 | SentinelGCO | 原样使用账号池、节奏和 Redis 发布 | 100% |
+| 用户 Book | OrderBookerGCO | 原样使用 order 账号和热 Session | 100% |
+| 账号边界 | VFS/BLS 集成方式 | Query built-in;Book order;状态不共享 | 100% |
+| route 配置 | VFS/BLS apt_configs[routing_key] | Italy 从顶层单一 service_id 迁移到相同模式 | 100% |
+| 强信号 | VFS/BLS Available + dates | 生产 Query 发布真实 Calendar 正向日期,`times=[]`;Book 重查时段 | 100% |
+| 弱信号 | BLS success=True + NoneAvailable + [] | 仅 Discovery/降级诊断,不作为生产精确检测 | 有条件复用 |
+| Book 重查 | VFS Book 自己查 Calendar/TimeSlot | Italy 用户 Session 独立重查 | 100% |
+| 日期范围 | VFS 的 Book 内过滤纪律 | 复用边界;改为确定性排序,不复制随机选择 | 规则复用 |
+| OTP 邮箱 | VFS/BLS VSCloudApi.fetch_mail_content() | 复用 API;Italy 自己配置 sender/subject/regex | 100% 基建复用 |
+| 结果 | VSBookResult | 原样填充现有字段 | 100% |
+| 错误类型 | 现有 Biz/Session/RateLimit 类型 | 原样映射;Italy 增加站点内局部分类 | 100% |
+| 浏览器 Network | USA/TLS 的 page.listen 一次监听 | 用于监听原生动作结果,不手写敏感 POST | 复用现有能力 |
+| 最终恢复 | VFS/BLS 没有足够的模糊结果合同 | 先用 Prenot@Mi /Reservation 作为权威对账;失败才提框架扩展 | 需 Gate |
+
+### 5.2 复用的本质
+
+复用的是稳定控制结构:
+
+~~~text
+账号池
+→ Session
+→ Query 事实
+→ 标准结果
+→ Redis 信号
+→ 用户 Session 重查
+→ 标准 Book 结果
+~~~
+
+不复制:
+
+- VFS/BLS 私有 endpoint、payload、hidden field;
+- 另一个插件的重试次数;
+- 随机 Slot 选择;
+- 调试日志里的响应正文、OTP 或动态 Token;
+- 在 Book 中依赖 Query 插件实例内临时字段的做法;
+- 另一个网站的 CAPTCHA 处理。
+
+“最大化复用”不等于把别的网站偶然实现也当成规范。
+
+## 6. 目标架构与文件边界
+
+### 6.1 模式:Functional Core + Imperative Shell
+
+旧方案建议所有逻辑继续塞进 ita_plugin.py。E22–E44 之后,这个选择不再成立:当前文件已经接近 1,000 行,新增协议又包含双层 JSON、两个 Slot 数量、跨月扫描、异步日期回退、重复 id、selected 一致性和一次性提交屏障。
+
+推荐只新增一个小模块,不新增框架:
+
+~~~text
+plugins/ita_plugin.py
+  Imperative Shell / Site Adapter
+  - IVSPlg 生命周期
+  - 浏览器和原生 DOM 交互
+  - page.listen
+  - OTP/AVANTI/最终点击
+  - 阶段编排和写屏障
+
+plugins/ita_protocol.py
+  Functional Core
+  - route 配置校验
+  - 双层 JSON 解码
+  - CalendarDay / SlotCandidate 纯数据
+  - 日期范围过滤
+  - 候选排序
+  - precommit 不变量
+  - response 分类
+  - 不导入 DrissionPage,不访问网络
+~~~
+
+这样做的长期价值:
+
+- 网站输入可以用 E15–E44 脱敏 fixture 机械复现;
+- 最危险的“能不能提交”判断不依赖浏览器 timing;
+- 地区差异留在配置,不进入条件分支;
+- 浏览器层只负责执行已经由纯逻辑批准的动作;
+- 没有创建新的 scheduler、provider、signal 或 workflow engine。
+
+### 6.2 计划涉及的文件
+
+| 文件 | 职责 |
+|---|---|
+| plugins/ita_plugin.py | 站点适配、原生交互、一次性副作用和 IVSPlg |
+| plugins/ita_protocol.py | 新增;纯配置/解析/选择/不变量 |
+| config/config_sentinel.json | 每 Sede 的 apt_configs、Query 模式和安全开关 |
+| config/config_booker.json | 与 Sentinel 同一 route 合同、Book 模式和安全开关 |
+| test/test_ita_protocol.py | 新增;E15–E44 纯协议/选择态 fixture |
+| test/test_ita_plugin.py | 浏览器适配、写次数、错误和结果测试 |
+| 现有 test/test_debug_ita_*.py | 通用目标和安全停点回归 |
+| 现有 tools/debug_ita_*.py | 参数化 route;不复制香港工具 |
+| docs/ita_plugin_discovery.md | 只记录事实,不承载未来设计 |
+| 本文 | 唯一目标设计、Gate 和发布合同 |
+
+首版禁止修改:
+
+- sentinel.py
+- booker.py
+- vs_types.py
+- vs_plg.py
+- VFS/BLS 插件
+- Redis payload
+- 云端任务接口
+
+若实现被迫修改这些文件,当前 Change Set 立即停止,先提交最小失败测试和扩大范围理由。
+
+唯一已知的潜在例外是最终提交的跨进程持久写屏障。当前 OrderBooker 的 tracker 是
+心跳租约,云端 grabbed 状态又发生在成功结果之后;两者都不是“提交前已持久化”的
+证据。Gate FENCE-1 会先验证现有任务 API 能否原样承载这个屏障。不能承载时,必须
+另开一个最小框架 Change Set 并单独批准;在此之前 final 永久保持 disabled。
+
+## 7. 通用 route 配置
+
+### 7.1 配置形状
+
+示意,不是本轮对生产配置的修改:
+
+~~~json
+{
+  "query_mode": "calendar",
+  "final_submit_enabled": false,
+  "apt_configs": {
+    "slot.hkg.it.tourist": {
+      "service_id": 4937,
+      "capability": "single_schengen_tourism",
+      "calendar_scan": {
+        "lookahead_months": 3
+      },
+      "form": {
+        "booking_type_control_id": "typeofbookingddl",
+        "booking_type_value": "1",
+        "booking_type_labels": ["Prenotazione Singola", "Single booking"],
+        "purpose_control_id": "ddls_0",
+        "purpose_value": "42",
+        "purpose_labels": ["Turismo", "Tourism"]
+      },
+      "mail": {
+        "authorization_email": "<configured-outside-logs>",
+        "sender": "<gate-required>",
+        "subject_keywords": "<gate-required>",
+        "body_keywords": "<gate-required>",
+        "otp_pattern": "<gate-required>"
+      }
+    },
+    "slot.dub.it.tourist": {
+      "service_id": 1321,
+      "capability": "services_probe_only"
+    }
+  }
+}
+~~~
+
+### 7.2 为什么字段必须放 route 下
+
+- service id 随 Sede/服务变化;
+- 附加下拉位置和值可能变化;
+- OTP 邮件模板可能变化;
+- 一个运行组未来可能包含同一 Sede 的多个目标;
+- AppointmentType.routing_key 已经是 VFS/BLS 使用的稳定查找键。
+
+### 7.3 配置机械合同
+
+1. Query 和 Booker 对同一 routing key 的非秘密 route 配置完全一致;
+2. service_id 为正整数;
+3. capability 必须明确,不能默认猜成 live;
+4. live route 必须声明 single + short-stay Schengen + tourism;
+5. 表单 value 必须同时通过 DOM label allowlist 交叉确认;
+6. 任何新增 required 控件没有映射时,OTP=0、AVANTI=0;
+7. 顶层 free_config.service_id 在迁移完成后禁止继续作为运行时真相;
+8. 代码中不得出现 if city == ...、if service_id == 4937 一类业务分支。
+9. `calendar_scan.lookahead_months` 必须是正整数,并由产品日期窗口和 Q-CAL 实测校准;示例值 `3` 只用于表达“默认月份 + 后续月份”,不是全局常量。
+
+控件结构和值是主合同;本地化 label 只是第二重交叉检查。label allowlist 由 route
+配置扩展,不把实现限制为中文、意大利语或英语,也不允许仅凭翻译文案继续提交。
+
+### 7.4 Sede 隔离
+
+首版每个运行组只服务一个 Sede。一个账号池只放属于该 Sede 的账号;扩容用于容错,不用于提高单位时间请求频率。
+
+同一个 ItaPlugin 能处理多个 Sede,含义是“同一协议 + 不同配置”,不是“一个浏览器同时切换多个 Sede”。
+
+## 8. Query 设计:真正回答“什么时候有号”
+
+### 8.1 两种模式
+
+| 模式 | 行为 | 信号 | 用途 |
+|---|---|---|---|
+| services_probe | 只进入服务入口;不发 OTP | bookingForm 只记录诊断 | Dublin 回归、Discovery |
+| calendar | 团队账号每 Session 准备一次 Calendar;后续扫描只读 Availability | 至少一个正向日期才发 Available,times 为空 | 生产候选 |
+
+services_probe 不得把 bookingForm 弱信号交给生产 OrderBooker。
+
+### 8.2 Calendar Session 准备
+
+每个 Query 插件实例、每个 route、每个认证 Session 至多执行一次:
+
+~~~text
+Q0 AUTHENTICATED_USER_AREA
+  → Q1 ROUTE_RESOLVED
+  → Q2 SERVICE_ENTRY
+  → Q3 BOOKING_FORM_VALIDATED
+  → Q4 SINGLE_AND_TOURISM_SELECTED
+  → Q5 PRIVACY_AND_TURNSTILE_READY
+  → Q6 OTP_SENT_ONCE
+  → Q7 OTP_RECEIVED_AND_ENTERED
+  → Q8 AVANTI_SUBMITTED_ONCE
+  → Q9 CALENDAR_READY
+~~~
+
+它不会选择最终日期/时段,也不会点击 btnPrenotaNoOtp。
+
+这一步是团队账号的业务 Session 准备,不是普通只读 Query。必须由配置开关显式启用,且满足:
+
+- 账号所有者已授权;
+- 邮箱读取已授权;
+- 准备前后 /Reservation 没有新增预约;
+- 每次 Session OTP=1、AVANTI=1、最终 POST=0;
+- 结果不明时不重复 OTP/AVANTI;
+- 账号池增加不提高总 probe 频率。
+
+### 8.3 日常只读 probe
+
+Calendar ready 后,每轮:
+
+1. 校验仍是同一 host、route 和 Calendar;
+2. 从当前月份开始,按 `calendar_scan.lookahead_months` 逐月驱动网站原生 Calendar;默认月份无号不能提前结束,但首个正向月份必须立即停止;
+3. 每次动作前开启 `page.listen`,捕获当月 Availability response,并在 `finally` 停止监听;
+4. 双层解码日期数组,把 `DD/MM/YYYY 00:00:00` 严格归一化为内部日期;重复日期或冲突记录 fail-closed;
+5. 只保留 `SlotLiberi>0 AND SlotRimanenti>=0` 的日期,并应用扫描范围;
+6. 当前月份出现正向日期时,只在该月份内升序取最早一天并立即停止,不再请求更远月份;如果完整范围都没有正向日期,才返回 `success=False/NoneAvailable`;
+7. 首个正向月份返回 `Available`,`earliest_date` 与唯一一项 `DateAvailability(date=earliest, times=[])` 指向同一天;不传播该月其他日期;
+8. 不主动点击每个日期、不主动为每个日期查询 TimeSlots。网站初始化自动产生的 TimeSlots 可以用于诊断/一致性监控,但不能把其中的 daily ID 或时段放进跨账号快照;
+9. 未知 schema、超时、月份未完整扫描、challenge 或限流抛明确异常,不伪装无号。
+
+为什么这里不要求 Query 先拿到具体时段:VFS/BLS 的稳定合同本来就是“Query 给日期,Book 重查时间”;E43 又证明 Availability 的正向容量与同日 TimeSlots 一致。这样少一次主动交互、少一批请求,也避免把转瞬即逝的动态时段误当成用户账号事实。
+
+### 8.4 Query 输出
+
+| 当前事实 | success | status | payload |
+|---|---:|---|---|
+| 服务明确无号 | false | NoneAvailable | 空 |
+| bookingForm 但未准备 Calendar | false | NoneAvailable | 只记录 stage,不发生产信号 |
+| 完整配置范围内没有正向日期 | false | NoneAvailable | 空 |
+| 首个正向月份至少一个 E43 合同的正向日期 | true | Available | 该月最早日期,`times=[]`;不含 runtime/daily ID 或 token |
+| Waiting List | 只有真实验证后 | Waitlist | 首版默认不支持 |
+| 未知状态 | 异常 | 不伪造 | signal=0 |
+
+VSQueryResult 快照只传播可公开的日期线索。daily calendar ID、Calendar runtime service ID、Cookie、OTP、DOM 对象和 Query 账号时段不进入 Redis。
+
+### 8.5 现有信号协议的一个细节
+
+Sentinel 只在 query_result.success=True 时写 Redis;to_snapshot_payload() 本身不保存 success,Booker 反序列化后该字段会回到默认 false,但 Booker 以“Redis 信号存在”触发,不再次检查 success。
+
+首版不修改这个既有合同,但必须加回归测试固定它,避免以后误以为反序列化后的 success 仍为 true。
+
+## 9. Book 设计:如何珍惜一次真实机会
+
+### 9.1 原则
+
+- Query 快照只告诉“团队账号刚看到什么”;
+- 用户账号必须重新查;
+- 用户账号只能使用自己当前 Session 的动态状态;
+- 所有写动作至多一次;
+- 最终结果不明时只读对账;
+- 选择策略确定性,不随机。
+
+### 9.2 状态机
+
+~~~text
+B0  TRIGGER_VALIDATED
+ → B1  USER_SESSION_RECONCILED
+ → B2  SERVICE_RECHECKED
+ → B3  BOOKING_FORM_VALIDATED
+ → B4  FORM_SELECTIONS_VALIDATED
+ → B5  PRIVACY_AND_TURNSTILE_READY
+ → B6  OTP_SENT_ONCE
+ → B7  OTP_RECEIVED_AND_ENTERED
+ → B8  AVANTI_SUBMITTED_ONCE
+ → B9  CALENDAR_READY
+ → B10 CURRENT_AVAILABILITY_RECHECKED
+ → B11 CURRENT_SLOT_SELECTED
+ → B12 PRECOMMIT_VALIDATED
+ → B13 FINAL_CLICK_ONCE
+ → B14 OUTCOME_RECONCILED
+ → B15 VSBookResult
+~~~
+
+状态只存在于同一个插件实例的内存中,不创建新工作流服务。关键防重复标志:
+
+- otp_sent
+- avanti_submitted
+- final_submitted
+- outcome_unknown
+- 当前 routing_key
+
+这些标志只能防住同一进程内的重复动作,不能防住进程在最终点击附近崩溃后重启。
+在 B13 前还必须有一个以 task/order + route 为键的持久 final-attempt fence。fence 必须
+在点击前成功写入;重启看到 fence 后只能对账或人工处理,不能再次 final。
+
+这保证的是 at-most-once:正常成功路径 final=1;任何 crash/timeout 路径 final<=1。
+如果进程恰好在 fence 已写入、网站尚未收到请求时崩溃,宁可丢失这次机会,也不能
+自动制造第二次不可逆提交。网站没有已观察到的 idempotency key,因此不能诚实承诺
+同时做到“绝不重复”和“崩溃后绝不丢机会”。
+
+Session 变化会清除页面临时状态,但在任何新的最终写动作前仍必须先做 /Reservation 对账。
+
+### 9.3 启动时对账
+
+每次 book() 开头先检查:
+
+1. 当前订单是否已经存在目标预约;
+2. 上一次本地状态是否为 outcome_unknown;
+3. 当前页面是否仍在同一 route 的 Calendar;
+4. 是否处于 OTP 前端/服务端冷却。
+
+若已经存在预约,直接解析并返回成功;若存在持久 final-attempt fence 或结果未知,
+只做对账,不重新提交。
+
+这个步骤是发布 P0。当前 Booker 对 success=False 会在下一信号重试,单靠异常无法阻止进程重启后的重复写。
+当前插件 book() 也没有显式 task_id 上下文,现有云任务更新只在成功后异步执行;因此
+不能用插件内存、tracker TTL 或 grabbed 通知冒充持久 fence。
+
+### 9.4 用户表单
+
+Book 操作可见控件并触发网站原生事件:
+
+1. 选择配置的 single;
+2. 触发 change;
+3. 断言 visible/hidden booking type 一致;
+4. 断言 companion hidden 为 0;
+5. 选择配置的 tourism;
+6. 断言可见值正确;
+7. 允许旅游 hidden 在 AVANTI 前仍为 0;
+8. 检查全部 required 控件;未知 required=1 即停止;
+9. Hong Kong 当前 Notes 可选、文件控件为 0;其他 Sede 按各自 Gate;
+10. 勾 Privacy;
+11. 等待当前页面自己的 Turnstile 状态可用,不复制或日志输出 token。
+
+禁止直接给 hiddenTipoPrenotazione、numAccSelected、hiddenSelezionato_0 赋值。网页原生同步链本身就是协议的一部分。
+
+### 9.5 OTP
+
+顺序:
+
+~~~text
+记录 UTC sent_at
+→ 监听 GenerateOTP
+→ 原生点击 otp-send 一次
+→ 只接受 HTTP 200 + SENT
+→ VSCloudApi.fetch_mail_content()
+→ 只搜索 sent_at 之后的新邮件
+→ 正则只返回验证码,不输出正文
+→ 输入 otp-input
+~~~
+
+约束:
+
+- HTTP GET 也按有副作用命令处理;
+- 一次 Session 准备最多一次;
+- response 超时/不明不自动重发;
+- UI 120 秒只是前端冷却,不冒充服务端规则;
+- sender、subject、body keyword、验证码格式必须由真实邮件 Gate 配置;
+- recipient 默认取当前 Italy 账号的 username,但必须先验证该 username 确实是收件
+  邮箱;不得读取不存在的 VSAccount.email 属性;
+- authorization_email 对应现有 VSCloudApi.fetch_mail_content() 的第一个参数,必须从
+  私密配置取得且不得写入日志或 fixture;
+- 旧邮件、旧验证码、错误 recipient 必须命中 0 次;
+- 日志中 OTP、邮件正文和 sender 以外的个人信息命中 0。
+
+首个 Canary 可以人工输入 OTP;无人值守生产必须关闭邮件自动读取 Gate。
+
+### 9.6 AVANTI
+
+提交前:
+
+- form action/method/enctype 与 route 合同一致;
+- single visible/hidden=1/1;
+- companions hidden=0;
+- tourism visible 为配置值;
+- tourism hidden 允许为 0;
+- OTP 非空但不读取到日志;
+- Privacy checked;
+- Turnstile 字段存在且非空布尔为 true;
+- btnAvanti.disabled=false;
+- 未知 required=0;
+- OTP 发送次数=1;
+- AVANTI 提交次数=0。
+
+执行:
+
+1. 在监听 POST /Services/Booking/{service_id} 后原生点击 AVANTI;
+2. 接受网站原生摘要确认框;
+3. 不手工构造 multipart;
+4. 期望一次 POST、302 和 /BookingCalendar;
+5. 任何模糊结果不重复 AVANTI。
+
+### 9.7 Calendar 重查
+
+Book 与 Query 使用同一纯解析器,但使用完全不同的浏览器 Session。
+
+Book 忽略 Query 的 daily ID 和临时 DOM,只用 Query 的日期作为优先线索:
+
+1. 先重查 Query 提示日期;
+2. 若它已失效,再扫描用户日期范围内当前返回的日期;
+3. 每次 date click 后等待 TimeSlots 完成;
+4. 检查实际 selected 日期,拒绝网站静默回退;
+5. 再执行候选选择。
+
+### 9.8 候选排序
+
+首版确定性策略:
+
+1. 过滤 expected_start_date <= date <= expected_end_date;
+2. 日期升序;
+3. 在同一天按明确的正向剩余量降序;
+4. 再按开始时间升序;
+5. 取第一个。
+
+不复制 VFS 当前的随机 shuffle/random choice。确定性选择更容易审计,也不会在同一输入下随机偏离用户意图。
+
+## 10. Side-effect Budget 和重试
+
+| 操作 | 类别 | 同一阶段上限 | 结果不明 |
+|---|---|---:|---|
+| /UserArea、/Services | 只读 | 同一错误最多 2 次 | 重建 Session |
+| 服务入口 GET | 探测 | 每 probe 1 次 | 当前轮停止 |
+| Calendar document/已证明只读 XHR | 只读 | 同一错误最多 2 次 | 当前轮停止 |
+| DOM/纯解析 | 本地 | 可重算 | fail-closed |
+| GenerateOTP | 外部命令 | 每 Session/attempt 1 次 | 禁止重发 |
+| AVANTI form POST | 外部命令 | 每 Session/attempt 1 次 | 对账/停写 |
+| date/slot 原生选择 | 页面状态 | 每候选 1 次 | 重新读 DOM |
+| InsertNewBooking | 最终不可逆 | 每机会 1 次 | 只读对账 |
+
+“同一错误最多两次”只适用于可证明幂等的只读操作。OTP、AVANTI、最终 POST 不因为报错而获得第二次机会。
+
+## 11. 正向日期和 Slot 的提交前不变量
+
+E43 已关闭当前页面版本的零值语义,E44 已关闭安全点击后的唯一选择态;但二者仍不等于“可以最终提交”。解析器和 precommit 必须同时满足:
+
+### 11.1 日期
+
+- 日期能严格解析为 YYYY-MM-DD;
+- 在用户范围内;
+- Availability item 唯一对应;
+- `SlotLiberi > 0`;
+- `SlotRimanenti >= 0`;
+- 不带 disabled;
+- 不带 notAvailableDay;
+- 带已验证的正向状态;
+- timeline selected 恰好 1;
+- content selected 恰好 1;
+- 两者 data-date 完全相等;
+- 等于计划选择日期;
+- 没有发生静默回退。
+
+### 11.2 Slot
+
+- TimeSlots item schema 完整;
+- 起止时间合法且开始早于结束;
+- IDCalendarioServizioGiornaliero 存在,只保留在内存;
+- SlotRimanenti、SlotLiberi 都能解析成有限整数;
+- `SlotLiberi > 0` 且 `SlotRimanenti >= 0`;E43 的 `1/0` 必须判正向;
+- DOM 不带 notAvailableFascia;
+- DOM 不带 dotRed;
+- 点击后 .fascia.act 恰好 1;
+- active Slot 就是候选;
+- active Slot 内符合合同的 hidden input 恰好 1;
+- active Slot 日期/时间仍与选择一致。
+
+仅以下任一项单独出现都不够:
+
+- SlotRimanenti >= 0
+- SlotLiberi > 0
+- .act
+- enabled PRENOTA
+- 数组非空
+- 有时间文字
+- 日期带 selected/active/availableDay
+
+### 11.3 最终 handler
+
+不手写 InsertNewBooking 请求。先用纯逻辑批准 DOM 快照,再触发网站原生 btnPrenotaNoOtp:
+
+- 复用页面当前 token/serializer;
+- 避免猜 selectedHour 中空白和数量格式;
+- 避免错误使用重复的 idHiddenFasciaServizio;
+- 用 Network listener 验证 method/path/调用次数和响应 schema;
+- 请求体只检查字段名/形状,不打印值。
+
+## 12. 最终结果与模糊恢复
+
+### 12.1 已知响应
+
+当前静态合同:
+
+~~~text
+response.errorMessage
+response.url
+~~~
+
+真实成功 response、失败 response 和成功 URL 仍是外部 Gate。
+
+### 12.2 明确成功
+
+listener 取得响应后:
+
+1. 允许页面按原生 handler 跳转;
+2. 读取成功摘要或 /Reservation;
+3. 唯一匹配 route + date + time;
+4. 读取预约编号;
+5. 返回 VSBookResult。
+
+### 12.3 明确失败
+
+只有服务器明确表示 Slot 已失效/请求失败,且 /Reservation 明确没有新记录,才返回可重试失败。不会在同一调用中重提。
+
+### 12.4 结果未知
+
+包括:
+
+- 点击后 listener 超时;
+- 连接断开;
+- response 无法解析;
+- 页面卡住;
+- response.errorMessage 与页面状态冲突。
+
+处理:
+
+~~~text
+final_submitted = true
+outcome_unknown = true
+durable_final_attempt_fence = present
+→ 永久关闭当前实例的最终写入口
+→ 只读 /Reservation
+→ 找到唯一记录:成功
+→ 明确无记录且协议允许:失败
+→ 仍不确定:manual-reconciliation-required
+~~~
+
+下一次信号只允许再次对账。进程重启后每次 Book 开始仍先查 /Reservation。
+
+重启后若 durable fence 存在,即使 /Reservation 暂时没有记录,也不得自动 final;
+应在有界窗口内继续只读对账,超时后转人工。fence 何时归档、绝不能被普通失败路径
+清除,必须由 FENCE-1 的状态迁移测试固定。
+
+如果网站不能提供权威对账,现有 VSBookResult + Booker retry 无法安全表达未知结果;届时必须停止发布,再提出最小框架级 OutcomeUnknown/任务冻结扩展。不能在 Italy 内假装解决。
+
+## 13. Session、冷却和并发
+
+### 13.1 账号隔离
+
+| 角色 | 账号 | Profile | 可以做什么 |
+|---|---|---|---|
+| Query | 已授权团队成员 | 每账号独占 | 准备自己的 Calendar;只读发现;不最终预约 |
+| Book | 申请人自己 | 与 Query 完全独立 | 为自己的订单完成预约 |
+
+一个 Profile 同时只能有一个浏览器实例;现有文件锁继续复用。
+
+### 13.2 信号与 cooldown
+
+生产强信号沿用:
+
+~~~text
+signal_ttl = 30s
+booking_cooldown > signal_ttl
+target_instances = 1
+有效 Italy OrderBooker 部署数 = 1
+~~~
+
+强信号来自真实 Slot,不再每轮发送 bookingForm 弱信号。
+
+OTP 的 120 秒冷却不能只靠 booking_cooldown=45 保护。插件自己的 attempt guard 必须阻止同一 Session 重发;如果仍在同一路由 Calendar,下一次 book() 直接重查 Calendar,不重新走 OTP。
+
+### 13.3 Session 生命周期
+
+当前 Italy 配置的 session_max_life=900 会主动每 15 分钟淘汰 Session。准备型 Query 若照搬,会每 15 分钟重新发 OTP。
+
+不能猜一个更长值。Gate 必须测量:
+
+- 登录 Session 实际寿命;
+- Calendar Session 实际寿命;
+- 只读 probe 是否保持有效;
+- OTP/AVANTI 的实际频率;
+- 429/challenge。
+
+生产配置使用已验证寿命的保守下界。账号数量不能被用来掩盖 Session 设计错误。
+
+### 13.4 keep_alive
+
+- Sentinel 正在定期 Query,按 IVSPlg 合同通常不需要额外 keep_alive;
+- OrderBooker 在 /UserArea 时可以使用已证明只读的认证页;
+- OrderBooker 在 /BookingCalendar 时不得导航离开,只做 DOM 健康检查或已证明安全的 Calendar 只读动作;
+- keep_alive 永不进入服务、发送 OTP、提交表单或最终预约。
+
+## 14. 错误、日志和隐私
+
+### 14.1 错误分类
+
+| 状态 | 结果 |
+|---|---|
+| 已验证无号/无正向 Slot | 正常 success=False |
+| IAM 登录页或认证回跳 | SessionExpiredOrInvalidError |
+| 429 | RateLimiteddError,当前实例停止 |
+| 403/挑战 | 明确挑战/权限错误,不自动绕过 |
+| 目标 route 缺失 | 配置或结构错误 |
+| 未知弹窗/字段/schema | BizLogicError,signal=0 |
+| OTP timeout | OTP 专用业务错误,不重发 |
+| AVANTI 结果未知 | attempt 停写并对账 |
+| 最终结果未知 | manual reconciliation,禁止重提 |
+
+### 14.2 允许日志
+
+- stage;
+- routing key、service id;
+- path、method、status;
+- schema keys;
+- field/button/count;
+- 日期和展示时间;
+- elapsed time;
+- 写请求计数;
+- 脱敏错误类别。
+
+### 14.3 禁止日志
+
+- username、password;
+- Cookie、Authorization;
+- CSRF/OAuth/Turnstile 值;
+- OTP、邮件正文;
+- daily calendar ID;
+- 护照、生日、电话、地址;
+- 完整 HTML、HAR、POST body;
+- 任何可复用的动态 Session 值。
+
+## 15. 假设验证账本
+
+### 15.1 P0:不关闭就不能发布对应阶段
+
+| ID | 假设 | 当前状态 | 机械关闭标准 | 失败动作 |
+|---|---|---|---|---|
+| P0-01 | IAM 自动登录可达 /UserArea | 已关闭 E9 | 真实 exit 0 + DOM 双标志 | Session 不可用 |
+| P0-02 | Dublin 1321 无号分类安全 | 已关闭 E7/E12 | GET/302/marker;业务 POST=0 | 保留回归 |
+| P0-03 | Hong Kong 4937 是单人申根旅游样本 | 已关闭 E14–E20 | service/form/single/tourism 唯一 | 不配 live route |
+| P0-04 | bookingForm 能代表真实 Slot | 已否决 E15/E43 | 表单自身无日期、范围、容量;不能从某次后续有号外推恒真 | 禁止生产弱信号 |
+| P0-05 | 团队账号准备 Calendar 不创建预约/候补 | 外部 Q-CAL-1 | OTP=1、AVANTI=1、final=0;Reservation 前后相同 | 否决准备型 Query |
+| P0-06 | Calendar 重复 probe 是只读且稳定 | 外部 Q-CAL-2 | 连续 N 次;OTP/AVANTI/final=0;记录不变;无 429 | 不自动 probe |
+| P0-07 | Query 正向日期对用户账号可传播 | 外部 Q-XACC | 3 个自然窗口 3/3;Book 在 TTL 内重查到可用时段 | 调整模型/不发布 |
+| P0-08 | 用户 OTP + AVANTI 能进 Calendar | 已关闭 E21/E22 | OTP 1、POST 1、302、Calendar 200 | 不实现后段 |
+| P0-09 | Cloud API 能唯一读取 Italy 新 OTP | 外部 OTP-AUTO | sent_at 后唯一命中;旧码=0;日志泄漏=0 | Canary 手工,生产禁用 |
+| P0-10 | 正向 Slot 的两个数量和 DOM truth table 已知 | 已关闭 E43/E44 | response/DOM 一致;安全点击后唯一 active、后代、时间和日期一致 | 保留 final=0 回归 |
+| P0-11 | precommit 能拒绝负向/冲突状态 | CS1 纯核心已关闭;CS4 接线时复验 | E23–E44 mutation fixtures 全通过 | 不进入 final |
+| P0-12 | InsertNewBooking 真实 response 可分类 | 外部 FINAL-1 | 一次真实 Canary 收集脱敏 schema | 不发布 final |
+| P0-13 | /Reservation 可权威对账 | 外部 FINAL-2 | 成功/失败/响应丢失均唯一判断 | 提框架 Unknown 状态 |
+| P0-14 | 跨进程 durable fence 保证最终 at-most-once | FENCE-1 + CS5A + FINAL-2 | 正常 final=1;timeout/crash/restart final<=1;fence 后只对账 | 不发布 |
+| P0-15 | 通用实现无 Sede 分支 | CS1–CS5 | HK 正向 + Dublin 负向同一路径;源码扫描=0 | 拒绝合并 |
+| P0-16 | kill switch 真能阻止最终动作 | CS5 | final_submit_enabled=false 下 final=0 | 不进 Canary |
+
+### 15.2 P1:生产前关闭
+
+| ID | 条件 | 关闭位置 |
+|---|---|---|
+| P1-01 | 任一启用 locale/配置 label 不改变核心结构判断 | locale fixtures |
+| P1-02 | 新 required 字段必然停在 OTP/AVANTI 前 | mutation fixture |
+| P1-03 | Query/Book route 配置完全一致 | JSON contract |
+| P1-04 | snapshot 不含临时 ID/secret | serialization scan |
+| P1-05 | date fallback 被检测 | E30/E41/E42 fixtures |
+| P1-06 | duplicate hidden id 不会取错 | active-descendant fixture |
+| P1-07 | `1/0` 正向、`0/-1` 负向,其他零/负数/冲突组合按 allowlist fail-closed | E43 truth-table fixtures |
+| P1-08 | 一个 retained signal 最多触发一次 Book | Booker offline integration |
+| P1-09 | 订单 pause/cancel 不触发 Book | OrderBooker regression |
+| P1-10 | Query 账号数增加不放大总频率 | cadence test + soak |
+| P1-11 | Session/Calendar 寿命已校准 | Q-CAL-2 |
+| P1-12 | Book p95 小于自然 Slot 可用窗口 | Q-XACC telemetry |
+| P1-13 | 日志/异常/产物敏感命中 0 | security scan |
+| P1-14 | 真实正向链外的未知页面 signal/final 都为 0 | mutation suite |
+| P1-15 | 第二 Sede 按配置工作 | GEN-1 |
+
+所有内部设计问题都已分配给 Change Set;所有网站未知都已分配给外部 Gate。不存在无验证路径的内部 P0/P1。
+
+## 16. 真实网站 Gate
+
+每个 Gate 的授权只覆盖该 Gate,不能继承到下一个副作用。
+
+### Gate D0:批准本文
+
+只评审设计。网站请求=0,代码修改=0。
+
+### Gate Q-CAL-1:团队 Query Calendar 准备
+
+前提:一个属于目标 Sede、已授权且邮箱可访问的团队账号。
+
+动作:
+
+1. 记录 /Reservation 非敏感计数;
+2. 进入 4937;
+3. single + tourism + privacy;
+4. OTP 一次;
+5. AVANTI 一次;
+6. 到 Calendar 停止;
+7. 再读 Reservation 计数。
+
+通过:
+
+~~~text
+GenerateOTP = 1
+Booking form POST = 1
+InsertNewBooking = 0
+预约/候补新增 = 0
+Calendar ready = true
+~~~
+
+2026-08-29 的 Q-CAL-1 受控执行尚未关闭本 Gate:
+
+- 第一次执行在读取 `/Reservation` 基线时发现空候补表不会初始化 DataTables;工具在进入
+  服务、OTP 和 AVANTI 之前停止。该读取假设已离线修正并通过回归。
+- 第二次执行成功取得基线 `reservations=0, waitlist=0`,但当前认证账号的 Services 页面
+  没有目标 `/Services/Booking/4937`。页面结构为 8 个数据行、7 个预约链接,目标链接数为
+  0;工具在 OTP、AVANTI 和 Calendar 之前 fail-closed。
+- 两次执行的 `GenerateOTP`、Booking Form POST 和 `InsertNewBooking` 均为 0;没有新增预约
+  或候补。第二次输出只能证明“当前账号所在 Sede 与 Hong Kong 4937 路由不匹配”,不能仅凭
+  行数把当前 Sede 名称事实化为 Dublin。
+- Gate 状态仍为 **OPEN**。再次执行前必须先显式确认一个已授权团队 Query 账号当前属于
+  Hong Kong Sede,或经单独授权把该账号的 Sede 切换为 Hong Kong;不得原样重跑。
+- 账号 Sede 随后由负责人完成调整。一次零副作用 Query 预检已精确进入
+  `/Services/Booking/4937`,确认 form action 仍为同一路径,Booking Type、Purpose、OTP、
+  Privacy、Turnstile 与 AVANTI 结构仍存在;工具按“Booking Form 弱信号”合同返回 exit 4。
+  该 exit code 是安全停止,不是路由失败。预检没有发送 OTP、提交 AVANTI 或进入 Calendar,
+  因而只关闭“账号与 Hong Kong 4937 已对齐”,没有关闭 Q-CAL-1。
+- 对齐后的下一次受控执行取得 `reservations=0, waitlist=0` 基线并成功观察到一次
+  `GenerateOTP`,随后由负责人在隐藏终端提示中人工输入验证码。执行在 AVANTI 前因
+  `Booking preflight rejected otpDisabled` 停止;Booking Form POST 和
+  `InsertNewBooking` 仍为 0。独立只读审计随后再次得到 `reservations=0, waitlist=0`,证明
+  本次 OTP 没有新增预约或候补。
+- 网站在发送 OTP 后会让发送按钮进入冷却禁用态。当前工作树已有显式的
+  `BEFORE_OTP_SEND/AFTER_OTP_SEND` 阶段校验,且 4 个聚焦测试验证发送后
+  `otpDisabled=true` 可接受;真实输出却仍命中旧判据。由于该次进程没有输出非敏感工具版本
+  标识,不能证明它加载了哪一版合同,也不能排除运行时值形状差异。再次授权前必须先增加
+  可审计版本标识与脱敏 stage/type 诊断,再做零网站副作用回归;不得直接重发 OTP。
+- 上述本地前置工作已经完成:工具在读取 route、账号或启动浏览器前输出语义合同版本和
+  当前源码 SHA-256 短指纹;每次 preflight ready/rejected 只输出 allowlist 中的 stage、
+  snapshot 类型,以及 `otpDisabled`、`avantiDisabled`、`turnstileReady` 的类型与布尔值。
+  未知值只记录类型并把 value 置为 null,额外表单字段不会被序列化。19 个 Q-CAL 聚焦测试、
+  168 个 Italy 相关离线测试、语法编译、diff/尾随空格检查均 exit 0;真实网站请求为 0。
+  Q-CAL-1 仍为 OPEN,新的 OTP 仍需新的明确授权。
+- 另用本地 `data:` 页面和真实 Chromium/DrissionPage 桥接验证:JavaScript `true/false`
+  均返回 Python `bool`,命令 exit 0,外部网站请求为 0。由此排除“浏览器桥把 true 转为整数
+  1”的假设;上次输出来自旧合同进程成为当前最强解释,但仍须由下一次 source fingerprint
+  实证,不能写成已最终证明。
+- 新授权的真实执行随后输出了预期合同版本与源码指纹;pre-OTP 为
+  `otpDisabled=false`,post-OTP 为 `otpDisabled=true`,两个阶段都以 bool/ready 通过,从而
+  实证 stage-aware 修复已加载。执行发送 OTP 1 次并提交 AVANTI 1 次,但旧 validator 因
+  `packet.response.status != 302` 停止;Calendar probe 和 final 请求均为 0。独立只读审计仍为
+  `reservations=0, waitlist=0`,证明本次没有新增预约或候补。
+- 本地临时 HTTP 服务与真实 Chromium/DrissionPage 进一步机械复现:服务端执行
+  `POST /booking → 302 Location:/calendar → GET /calendar 200`,listener 返回的 packet 却是
+  `request_method=POST, request_path=/booking, response_status=200,
+  response_path=/calendar`,浏览器 final path 也是 `/calendar`;命令 exit 0,外部请求为 0。
+  DrissionPage 复用 redirect requestId 并用最终 response 覆盖原始 302,因此“packet 必须
+  直接暴露 302”是错误的适配器假设,不是 Italy 协议变化。
+- 最小修复不能接受任意 200:必须同时验证原始 request 仍是同源目标 POST、packet response
+  最终 URL 是同源 `/BookingCalendar`、浏览器最终 pathname 也是 `/BookingCalendar`;若底层
+  仍能直接提供 302,则继续验证 Location。修复和离线回归未获得本轮授权前不实施;新的 OTP
+  仍需再次单独授权。
+
+2026-08-29 最终状态:**Q-CAL-1 CLOSED**。
+
+- v5 真实运行已验证 OTP=1、Booking Form POST=1、Calendar ready=true、
+  InsertNewBooking=0;事后 Reservation/Waitlist 为 0/0;v6 只修改 Calendar selector,未改
+  OTP/AVANTI 合同;
+- 同一持久化认证状态随后无需 OTP/AVANTI 即可恢复 Calendar;
+- 真实只读翻月验证得到 candidate=4、actionable=1、clicked=true,并观察到两个不同月份的
+  availability request;
+- 只读验证前后 Reservation/Waitlist 均为 0/0,OTP=0、AVANTI=0、final=0;
+- 因此一次性 Calendar 准备与后续只读恢复均满足本 Gate;Q-CAL-2 的 cadence/寿命/限流仍需
+  独立 soak,不能由 Q-CAL-1 代替。
+
+### Gate Q-CAL-2:Calendar 只读 soak
+
+在同一团队账号 Calendar Session 里按计划 cadence 重查。
+
+通过:
+
+- Availability 逐月只读次数符合配置;没有主动按日期扇出 TimeSlots;页面原生自动 TimeSlots 单独计数;
+- OTP、AVANTI、final 增量均为 0;
+- Reservation 无变化;
+- Session/Calendar 寿命已量化;
+- 429/challenge=0;
+- 发生 schema 变化时 signal=0。
+
+### Gate SLOT-POS:自然正向 Slot,停在最终按钮前
+
+不制造 Slot,不点击 unavailable。
+
+阶段 A:response/DOM 正向语义,已由 E43 关闭:
+
+- Availability 的 `SlotLiberi>0 / SlotRimanenti>=0`;
+- TimeSlot 的 `1/0`、普通 `fascia`、无红点、显示 `(1)`;
+- timeline/content selected 日期一致;
+- 正向 Slot 有唯一 hidden daily ID 形状;
+- 正向 Slot 尚未点击、`act=false`;
+- `InsertNewBooking=0`。
+
+阶段 B:安全选择,已由 E44 关闭:
+
+1. 只点击一次已由阶段 A 批准的正向 Slot;
+2. 断言 `.fascia.act` 恰好 1;
+3. active Slot 仍无负向 class,后代 ID、时间和 selected 日期与候选一致;
+4. 运行纯 precommit,结果必须为 true;
+5. 不点击 `btnPrenotaNoOtp`,Network 中 `InsertNewBooking` 仍为 0。
+
+E44 实际结果:
+
+- 授权探针源码对 E43 批准的 `10:05 - 11:05` 候选只调用一次 `.click()`;原 Promise fulfilled 后没有重跑;
+- 独立只读 readback 得到唯一 `.fascia.act`,且 active 就是同一时间、同一 selected 日期的候选;
+- active 不带 `notAvailableFascia`/`dotRed`,仍显示 `(1)`;
+- active 后代 hidden input 恰好 1,动态值只验证“存在、全数字、长度 8”,没有读取或保存具体值;
+- `btnPrenotaNoOtp` 仍存在但点击数为 0;当前页面 Resource Timing 中 `InsertNewBooking` 为 0;机械总判定 `done=true`;
+- Resource Timing 只关闭本次选择态的“未观察到 final XHR”,不替代 FINAL Gate 的 Network listener、服务端 response 和 `/Reservation` 对账。
+
+禁止:InsertNewBooking。
+
+通过:阶段 A 和 B 都关闭,唯一正向候选满足 §11 全部不变量,最终 POST=0。
+
+### Gate Q-XACC:团队信号 → 用户账号
+
+团队 Query 观察正向日期后发布本地/Redis 信号;用户热 Session 独立重查具体时段。
+
+通过:
+
+- 3 个独立自然窗口 3/3;
+- 用户看到同一日期的可用时段,或在其允许范围内看到另一正向日期/时段;
+- 信号到 Book precommit 的 p95 有安全余量;
+- Query 与 Book 账号/Profile/Cookie 完全不同。
+
+### Gate OTP-AUTO:自动邮件读取
+
+通过:
+
+- sender/subject/body/regex 有真实证据;
+- sent_at 之后唯一命中;
+- 旧 OTP 0 命中;
+- recipient 错误 0 命中;
+- 日志/异常/产物不含 OTP/正文。
+
+### Gate FENCE-1:最终提交持久写屏障
+
+先只调查现有云任务 API 和 OrderBooker,不访问预约网站、不执行 final。
+
+通过必须同时满足:
+
+- 有稳定 task/order 标识可作为 fence key;
+- fence 写入发生在原生最终点击之前,并能被另一个进程读到;
+- 写入具备 compare-and-set 或等价的单写者保证;
+- 进程在 fence 前、fence 后点击前、请求发出后、response 前四个 crash point 都有测试;
+- fence 存在时 Booker 不会因新 Redis 信号再次 final;
+- 只有权威成功归档或人工处置能结束 fence,普通 false/exception 不能清除;
+- 不把 Cookie、OTP、daily ID 或 PII 写入 fence。
+
+若现有任务 API 不具备这些能力,结论不是“插件里写个文件”,而是提出最小框架/
+后端扩展并重新评审文件范围。该 Gate 未通过时 CS5 和 FINAL-1 均禁止。
+
+### Gate FINAL-1:一次真实 Canary
+
+前提:
+
+- 用户确实需要当前日期/时间的预约;
+- SLOT-POS、Q-XACC、OTP-AUTO、FENCE-1 已关闭;
+- final kill switch 的离线测试已通过;
+- 用户再次明确授权。
+
+动作:
+
+- 原生点击一次 btnPrenotaNoOtp;
+- InsertNewBooking 恰好 1;
+- 不人工重试;
+- 读取成功页和 Reservation。
+
+### Gate FINAL-2:结果对账
+
+用已取得的真实 response/成功页设计离线响应丢失测试,并在不制造第二个预约的前提下验证 Reservation。
+
+通过:成功、明确失败、网络结果未知三种路径都不会导致第二次 final。
+
+### Gate GEN-1:第二 Sede 通用性
+
+香港正向 fixture 与 Dublin 无号 fixture 必须走同一协议代码。随后选择一个合法的第二 Sede 做只读/前置 Gate。
+
+源码中的城市、领馆、1321、4937 控制分支命中必须为 0。
+
+### Gate PROD-1:受控上线
+
+- 单 Sentinel;
+- 单 Italy OrderBooker;
+- target_instances=1;
+- 强信号模式;
+- kill switch 已演练;
+- 可观察 stage/write counts;
+- 回滚命令和负责人明确;
+- 前 1 个生产订单人工旁路监控。
+
+## 17. 开发计划
+
+每个 Change Set 都需要单独批准。前一个完成不自动授权下一个。
+
+### CS0:设计与证据收敛
+
+本轮。
+
+完成:本文、历史文档状态、机械检查。
+
+### CS1:route 配置与纯协议核心(已验证)
+
+文件:
+
+- 新增 plugins/ita_protocol.py
+- 新增 test/test_ita_protocol.py
+- 只读运行现有 test/test_ita_plugin.py 作为回归;本 Change Set 不修改该用户已有文件
+
+内容:
+
+- 使用 VFS/BLS 同类的 `apt_configs[routing_key]` 配置入口,严格校验 capability、
+  service_id、扫描范围与表单控件配置;
+- 严格双层 JSON parser,只接受“外层 JSON 字符串包内层对象数组”;
+- 不可变 Calendar/Slot value objects,动态日历 ID 不进入 `repr`;
+- 日期范围过滤、跨年月份生成与确定性排序;
+- 按 E43 建立唯一的容量 allowlist:`SlotLiberi>0 && SlotRimanenti>=0` 为正向,
+  `0/-1` 为负向,矛盾组合 fail-closed;
+- 按 E44 校验日期与时段唯一选中、动态 ID、日期、时间、容量和负向标志均一致后,
+  才生成纯内存 `PrecommitApproval`;
+- 不导入浏览器或网络库,不登录、不发 OTP、不提交表单、不接触网站。
+
+完成结果:28 个聚焦协议测试 exit 0;30 个现有 Italy 回归测试 exit 0;编译、
+纯模块导入、地区硬编码/网络副作用、敏感信息与 whitespace 检查 exit 0;生产网站
+请求=0;`ita_plugin.py` 和生产 Query/Book 均未接入,现有 Italy 行为不变。
+
+### CS2:配置与调试工具通用化(已验证)
+
+内容:
+
+- Italy 插件按 apt_type.routing_key 解析;
+- Sentinel/Booker route parity;
+- debug query/book/monitor/soak/handoff 接受显式 route;
+- Dublin 默认仅作为兼容参数,不再锁死;
+- 未配置 capability fail-closed。
+
+完成:HK/Dublin fixture 同一实现;硬编码控制分支扫描=0。
+
+实际结果:
+
+- `ItaPlugin.query()` 与 `book()` 都通过
+  `apt_type.routing_key → free_config.apt_configs[routing_key]` 解析 route;顶层
+  `service_id` 不再是运行时 fallback;
+- Sentinel/Booker 的 Italy 配置拥有相同 `apt_configs`,并显式保持
+  `query_mode=services_probe`、`final_submit_enabled=false`;
+- query/book/monitor/soak 调试入口共用一个 route resolver;Dublin/1321 只在完全没有
+  route 环境变量时作为兼容默认值;自定义 route 的 key、service id、city、visa type
+  必须一次性全部提供,部分覆盖会 fail-closed;
+- `ita_local_handoff.py` 继续只接收显式 routing key/service id,没有新增地区分支;
+- `services_probe_only` 仍只允许弱入口探测与用户 Session 重查,Book 到达表单后停在
+  AVANTI 之前;没有接入 CS1 的 Calendar parser,也没有发送 OTP 或最终请求;
+- 137 个相关离线测试、编译、配置 parity、控制分支与 whitespace 检查均 exit 0;
+  真实 Italy 网站请求数为 0。
+
+### CS3A:生产 Calendar 扫描合同(离线及一次现场验收已验证)
+
+前提:Q-CAL-1 已关闭;实现仍需保持 final disabled,并由 Q-CAL-2 校准 cadence。
+
+内容:
+
+- 新增 `plugins/ita_calendar_query.py`,作为生产 Query 与 Q-CAL 工具唯一共享的浏览器适配层;
+- page.listen 一次性安全 wrapper、同源 method/path/body shape 校验;
+- 原生 Calendar refresh;
+- 唯一可操作 `#datetimepicker th.dtpicker-next` 与严格单月递增;
+- 首个正向月份立即停止,只发布该月最早日期;
+- 复用 VFS 风格 `Available + earliest_date + DateAvailability(times=[])`;
+- Calendar 最终按钮在每次 probe 后被 guard,`InsertNewBooking` 观察数必须为 0;
+- services weak signal 默认不发布。
+
+当前安全边界:`query_mode=calendar` 只接受同一插件实例中已经过 route 确认的
+`/BookingCalendar`;未完成准备时明确失败,不把 bookingForm 弱信号降级发布。默认生产配置
+仍是 `query_mode=services_probe`,因此本 Change Set 不会自动发送 OTP、点击 AVANTI 或启用强
+信号。
+
+### CS3B:Calendar Session 准备(未实现)
+
+内容:Query Calendar Session stage、OTP/AVANTI 一次性 guard,以及经过 OTP-AUTO Gate 的邮件
+读取适配。它必须先证明同一实例内 route 身份连续,不能把旧持久化 Calendar 或页面标题猜成
+当前 routing key。CS3A 完成不会自动授权 CS3B,也不会修改生产配置。
+
+### CS4:用户 Book 到最终按钮前
+
+内容:
+
+- 用户 Session 重查;
+- 原生 form selection;
+- OTP/AVANTI;
+- Calendar parser;
+- Slot 选择;
+- precommit;
+- 默认 final_submit_enabled=false 并在按钮前停止。
+
+### CS5A:跨进程持久写屏障
+
+前提:FENCE-1 已证明可复用路径,并单独批准可能扩大的文件范围。
+
+内容:只实现已批准的 task/order fence、状态读取和 crash-point 离线测试;不访问
+Prenot@Mi,不执行 final。若需要修改 booker.py、toolkit/vs_cloud_api.py 或后端合同,
+必须作为独立 Change Set,不夹带进 Italy 插件提交。
+
+### CS5:最终一次提交与对账
+
+前提:SLOT-POS、Q-XACC、OTP-AUTO、FENCE-1、CS5A 已关闭,且 FINAL-1 已授权。
+
+内容:
+
+- final listener;
+- 原生 click once;
+- response parser;
+- Reservation reconcile;
+- outcome_unknown 写屏障;
+- VSBookResult。
+
+### CS6:生产接入
+
+内容:
+
+- 启用真实 route;
+- cadence/session/cooldown 使用 Gate 数据;
+- kill switch;
+- canary rollout;
+- 观察与回滚。
+
+## 18. 测试计划
+
+### 18.1 纯协议单元测试
+
+- route 缺失/类型错误;
+- 双层 JSON 正常、空、单层、三层、坏 JSON、超大数组;
+- Availability 的 `DD/MM/YYYY 00:00:00` 日期格式、非法日期和重复日期;
+- 默认月份全负向、后续月份有正向时不得提前返回无号;
+- `lookahead_months` 边界、翻月顺序和完整范围为空;
+- TimeSlot 缺字段、非法时间、非整数数量;
+- E43 `SlotLiberi=1 / SlotRimanenti=0` 必须判正向;
+- E43 `SlotLiberi=0 / SlotRimanenti=-1` 必须判负向;
+- 其余 SlotRimanenti/SlotLiberi 组合按 allowlist 或冲突 fail-closed;
+- negative class + act 冲突;
+- selected 两层日期不一致;
+- 网站 fallback 到错误日期;
+- 多 active/零 active;
+- active Slot 多 input/零 input;
+- 重复 HTML id 但 active 后代唯一;
+- 日期边界;
+- 确定性排序。
+
+### 18.2 插件合同测试
+
+每个测试断言调用次数:
+
+| 场景 | OTP | AVANTI | final |
+|---|---:|---:|---:|
+| Dublin 无号 | 0 | 0 | 0 |
+| bookingForm / services_probe | 0 | 0 | 0 |
+| 未知 required | 0 | 0 | 0 |
+| Turnstile 未就绪 | 0 | 0 | 0 |
+| OTP response unknown | 1 | 0 | 0 |
+| AVANTI response unknown | 1 | 1 | 0 |
+| 配置扫描范围全部无正向日期 | 1 | 1 | 0 |
+| 默认月份无号、后续月份有 E43 正向日期 | 1 | 1 | 0 |
+| Availability 正向、TimeSlots 无正向(冲突) | 1 | 1 | 0 |
+| 负向 Slot 被手工加 act | 1 | 1 | 0 |
+| final disabled | 1 | 1 | 0 |
+| final listener timeout | 1 | 1 | 1 |
+| timeout 后再触发 | 不增加 | 不增加 | 仍为 1 |
+| reconcile 找到预约 | 不增加 | 不增加 | 仍为 1 |
+
+“默认月份无号、后续月份正向”还必须断言 Query 发布一次 `Available`,快照含正向日期且所有 `times=[]`;其他 final=0 场景不得发布错误强信号。
+
+另加 crash-point 矩阵:fence 前崩溃允许重新预检;fence 后点击前、请求发出后和
+response 前崩溃均不得产生第二次 final。正常成功 final=1,其余路径 final<=1。
+
+### 18.3 框架离线集成
+
+- Sentinel 只为强 Available 写生产信号;
+- snapshot 不含临时 ID/secret;
+- 反序列化 success 默认值的既有行为被固定;
+- retained signal 只触发一次 Book;
+- pause/cancelled task 不 Book;
+- Query/Book 是两个插件实例;
+- Book 不使用 Query 临时状态;
+- final kill switch;
+- Session 重建后先 reconcile。
+- durable fence 在进程重启和新信号后仍阻止 final;
+
+### 18.4 Mutation 测试
+
+主动修改 fixture:
+
+- 文案语言;
+- 控件 id;
+- 新 required;
+- 选项 value;
+- response 外层编码;
+- schema key;
+- selected 顺序;
+- class 冲突;
+- response errorMessage/url;
+- path/redirect。
+
+期望:未知变化 signal=0、final=0,而不是“尽量继续”。
+
+### 18.5 安全测试
+
+扫描:
+
+- password
+- Cookie/Authorization
+- OAuth/CSRF/Turnstile value
+- OTP 与邮件正文
+- daily calendar ID
+- 完整 POST body
+- 用户 PII
+
+测试日志、异常、snapshot、status file 命中必须为 0。
+
+### 18.6 计划验证命令
+
+~~~bash
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m unittest -v \
+  test.test_ita_protocol \
+  test.test_ita_plugin \
+  test.test_debug_ita_session \
+  test.test_debug_ita_query \
+  test.test_debug_ita_book \
+  test.test_debug_ita_monitor \
+  test.test_debug_ita_soak \
+  test.test_ita_local_handoff \
+  test.test_add_ita_query_account
+
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -m compileall -q \
+  plugins/ita_plugin.py plugins/ita_protocol.py tools test
+
+jq empty config/config_sentinel.json config/config_booker.json
+
+git diff --check
+~~~
+
+真实测试命令必须单独带显式 Gate/arm 开关;默认 CLI 仍是零网络 preflight。
+
+## 19. 准入、准出、回滚
+
+### 19.1 进入研发
+
+必须:
+
+- D0 明确批准;
+- 只做获批 Change Set;
+- Done 标准前置;
+- 工作树用户改动已盘点;
+- 外部 Gate 和内部实现不混在同一提交;
+- 默认 final disabled。
+
+### 19.2 进入最终 Canary
+
+必须:
+
+- 所有相关 P0 关闭;
+- 自然正向 Slot;
+- 用户确实需要该预约;
+- precommit 全绿;
+- /Reservation 可读;
+- final request counter 初始为 0;
+- kill switch 已验证;
+- 用户当次明确授权。
+
+### 19.3 生产准出
+
+必须:
+
+- 聚焦与回归测试 exit 0;
+- Q-CAL soak 通过;
+- Q-XACC 3/3;
+- FINAL-1/2 通过;
+- FENCE-1 和 CS5A 通过;
+- GEN-1 通过;
+- 敏感扫描 0;
+- 未知状态 fail-closed;
+- 一次性 final 在正常成功路径为 1,在 timeout/restart 路径为 <=1;
+- 真实成功返回完整 VSBookResult;
+- 运行配置默认不是 debug;
+- Runbook 和 kill switch 可执行。
+
+### 19.4 回滚
+
+按最小影响顺序:
+
+1. final_submit_enabled=false:保留观察,禁止最终写;
+2. query_mode=services_probe:停止团队账号 OTP/AVANTI;
+3. 禁用 Italy Booker group;
+4. 禁用 Italy Sentinel group;
+5. 回退对应 Change Set;
+6. 已发 OTP 不补发;结果未知只对账;
+7. 已成功预约不自动取消。
+
+回滚不删除用户数据、不清理不属于本 Change Set 的工作树修改。
+
+## 20. 可行性分析
+
+| 能力 | 可行性 | 当前确信度 | 原因 |
+|---|---|---:|---|
+| 登录 | 高 | 高 | 真实自动登录 exit 0 |
+| Dublin 无号 | 高 | 高 | DOM/Network/自动 Query 三重证据 |
+| route 通用化 | 高 | 高 | VFS/BLS 已有 apt_configs |
+| bookingForm 弱信号 | 技术可行但产品价值低 | 高 | 自身不含日期/范围/容量;不能回答“何时有号” |
+| 准备型 Calendar Query | 高,需副作用 Gate | 中高 | 完整进入链和 Calendar 协议已知 |
+| 日期/时段解析 | 高 | 高 | E43 已取得正负 response/DOM truth table;CS1 的解析与变异测试已验证 |
+| 正向 Slot 原生选择到 precommit | 高 | 高 | E44 已验证唯一 active、日期、时间、容量、动态 ID 形状一致且 final 请求为 0;CS1 纯 precommit 已验证 |
+| Query 日期→Book 时段传播 | 可行,需实测 | 中 | 与 VFS/BLS 契约一致;同站点库存共享仍需 Q-XACC 证明 |
+| 用户 Book 到 Calendar | 高 | 高 | E22 已真实通过 |
+| 自动邮件 OTP | 高,需邮件参数 | 中 | 基建存在;Italy filter 未关闭 |
+| 最终一次提交 | 技术路径清晰 | 中 | serializer 静态已知;真实 response 未执行 |
+| 模糊结果恢复 | 待 Gate | 低 | /Reservation 权威性与 durable fence 均未知 |
+| 跨 Sede 通用 | 架构可行 | 中高 | 配置化成立;需第二正向/前置样本 |
+
+当前对“设计结构和安全推进路径”的信心可以达到 100/100;对“现在就无人值守上线”的信心不是 100,因此方案明确不允许现在上线。
+
+## 21. 被否决的方案
+
+| 方案 | 否决原因 |
+|---|---|
+| Services 有 Prenota 就报有号 | Dublin 已证伪 |
+| bookingForm 就持续发弱信号 | 表单本身没有日期/范围/容量;会造成 OTP 噪音 |
+| Query 把临时 Slot ID交给 Book | 跨账号/Session,必然过期或错配 |
+| Query 每轮都 OTP + AVANTI | 邮件/限流/服务器状态副作用 |
+| 用户 Book 不重查直接最终提交 | 机会易失且账号不同 |
+| 手写 multipart/InsertNewBooking | 会绕过原生同步、token 和 serializer |
+| 只看 .selected/.act | 负向样本已证明会假阳性 |
+| 只看一个 Slot 数量字段 | 两个字段职责不同;E43 的正向还是 `1/0`,单看 `Rimanenti=0` 会误杀 |
+| 对 final/OTP/AVANTI 自动重试 | 可能重复邮件、草稿或预约 |
+| 为香港复制插件 | 立即形成地区分叉 |
+| 现在修改 Sentinel/Booker/VS 类型 | 现有强信号和账号架构足够 |
+| 所有逻辑继续堆进 ita_plugin.py | 接近 1,000 行且协议不变量已复杂到无法纯测 |
+| 提前设计大工作流引擎 | 一个局部 pure core + adapter 足够 |
+
+## 22. 初见审查
+
+### 反驳 1:“Query 发 OTP,不是违背 Query 无副作用吗?”
+
+回应:旧边界是在 Calendar 协议未知时设的安全默认。香港已经证明 bookingForm 自身不表达号源,而 E43 证明只有进入 Calendar 并扫描完整范围才能回答“什么时候有号”。R3 不允许每轮发 OTP,而是把一次 OTP + AVANTI 明确建模为“团队账号 Calendar Session 准备”,单独授权、每 Session 一次、前后核对 Reservation,后续 probe 只读。若 Q-CAL-1 发现草稿/预约副作用,就否决该方案,而不是偷偷继续。
+
+### 反驳 2:“为什么不继续用 BLS 弱信号,最大化复用?”
+
+回应:BLS 的弱信号是一种技术表达,不是所有网站都适合的产品语义。bookingForm 没有日期与容量,所以会持续触发但无法回答库存。生产优先复用 VFS 的强 Calendar 信号;BLS 弱信号保留给 Discovery/人工告警。
+
+### 反驳 3:“新增 ita_protocol.py 不是自己设计吗?”
+
+回应:没有新增框架或运行时组件。它只是把浏览器副作用与纯解析拆开,让 E23–E44 能机械测试。旧单文件方案形成于 Calendar 协议未知时;现在继续堆叠反而降低长期可验证性。文件增加 1 个,运行链路仍是原有 IVSPlg。
+
+### 反驳 4:“团队账号看到正向日期,用户账号可能已经看不到时段。”
+
+回应:所以 Query 结果只是“这个时刻团队账号看到了真实正向日期”的强事实,不是预约承诺;快照不携带 times/daily ID,用户 Book 必须重查。Q-XACC 要求 3 个自然窗口 3/3,并测量时间预算。失败就调整或否决跨账号模型,不能用推断上线。
+
+### 反驳 5:“为什么不预先把用户账号也放进 Calendar,抢得更快?”
+
+回应:当前 OrderBooker 在 create_session() 时没有把完整 user_inputs 传给插件,其他 Sede 可能有用户必填字段。现在修改通用框架属于过早扩权。先测量从热 /UserArea 到 precommit 的 p95;只有它确实错失 Slot,才用复现数据讨论最小的 prewarm 接口。
+
+### 反驳 6:“final listener timeout 后返回 false,Booker 还是会重试。”
+
+回应:不能简单返回 false,也不能只靠插件内存。B13 前必须写入跨进程 durable fence;
+timeout、异常、新信号或重启看到 fence 后都只能对账。当前 tracker/grabbed 流程不能
+证明具备该能力,所以 FENCE-1 是 FINAL-1 的前置 Gate;不足时必须单独扩展框架,
+不能在 Italy 内用本地文件假装解决。
+
+### 反驳 7:“既然 E43 已经有正向 Slot,为什么还不能直接开发最终点击?”
+
+回应:E43 已经足够实现双层解码、`1/0` 正向与 `0/-1` 负向分类和跨月扫描;E44 又证明通过完整正向 preflight 后,点击会得到唯一且正确的 `.fascia.act`。但最终 response、`/Reservation` 对账和 durable fence 仍未关闭。因此 CS1/CS3/CS4 可以在 final disabled 下推进,E44 关闭的选择态不能被偷换成 FINAL/FENCE 已关闭。
+
+### 反驳 8:“Query 不查 TimeSlots,怎么敢说 Available?”
+
+回应:这里的 `Available` 是“该时刻该 Sede 的某个日期有正容量”,不是“用户账号已锁定某个时间”。E43 中 Availability 的 `1/0` 与同日唯一正向 TimeSlot 的 `1/0`、普通 DOM、`(1)` 完整一致;VFS/BLS 也已经用“日期强信号、Book 重查时间”的合同运行。Query 快照明确 `times=[]`,Book 必须重查;库存若在两者之间被抢走,是正常竞争,不是 Query 伪造。若未来出现正向日期长期无法在 Book 侧得到任何时段,Q-XACC 会否决或降级该模型。
+
+### 反驳 9:“为什么不只查询 Calendar 打开时的默认月份?”
+
+回应:E43 已给出直接反例:默认 8 月窗口全负向,但向后到 10 月存在正向库存。只查默认月份会制造确定性的漏报。Query 必须在 route 配置的 lookahead 内从近到远逐月扫描;遇到首个正向月份立即停止,只有范围全部检查完且没有正向日期,才能返回无号。lookahead 是配置和 Gate 数据,不是写死香港月份。
+
+### 反驳 10:“这能保证永远预约成功吗?”
+
+回应:不能保证第三方库存和网络。但能保证:只在真实正向证据下尝试、用户账号独立重查、最终最多一次、结果不明不盲重提、未知变化安全停止。这是工程上可以验证的 100% 边界。
+
+### 反驳 11:“既然叫生产 Query,为什么不立即把生产配置切到 calendar?”
+
+回应:本 Change Set 把已验证的 Calendar 扫描合同放进生产插件代码,而不是把尚未关闭的
+Session 准备合同伪装成已完成。生产 `calendar` 分支会要求同一插件实例已经完成 route 确认;
+默认配置继续保持 `services_probe`。等 CS3B/OTP-AUTO 关闭后,再通过独立配置 Change Set
+启用。这既保留了生产代码与调试工具的单一实现,又避免上线一个只能靠人工 OTP 才能维持的
+半自动状态。
+
+## 23. 验证记录
+
+### 23.1 D0 设计验证
+
+2026-08-29 实际执行的文档级验证:
+
+- heading 去重、围栏计数与奇偶校验;
+- P0 与 P1 假设表的编号唯一性与连续性校验;
+- R3 引用的 E 编号与唯一事实源做集合差;
+- 陈旧流程反向扫描;
+- 邮箱、Bearer、Cookie、明文 password、Turnstile 值模式扫描;
+- trailing whitespace、文件末尾换行和本地文档链接检查;
+- 旧恢复文档 SUPERSEDED 指针检查;
+- git status 复核现有脏工作树,没有清理或回滚用户修改。
+
+以上最终命令组必须全部 exit 0;完整命令与返回值写在本轮交付报告。由于 D0 阶段
+只修改设计文档,当时没有运行 Python 测试,也没有把未运行的代码验证写成已验证。
+CS1 的后续验证单独记录在 §23.2,不能倒推成 D0 当时已经执行。
+
+过程异常:第一次更新历史文档时,patch 因尾部上下文已经演进而未应用;读取真实
+尾部后按实际内容重新执行成功。同一错误只出现一次,没有盲目重试。
+
+### 23.2 CS1 离线实现验证
+
+2026-08-29 在 CS1 授权边界内实际执行:
+
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_ita_protocol -v`:
+  exit 0,28 个测试全部通过;
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_ita_plugin -v`:
+  exit 0,30 个现有 Italy 回归测试全部通过;
+- 对 `plugins/ita_protocol.py` 和 `test/test_ita_protocol.py` 执行内存编译:exit 0;
+- 对协议模块执行 AST import allowlist 检查:exit 0,没有浏览器、HTTP、进程或文件 I/O
+  依赖;
+- 扫描香港、Dublin、HKG、1321、4937 和 URL/OTP/AVANTI/final/click 等控制分支:
+  exit 0;
+- 扫描超过 100 字符的代码行:0;trailing whitespace 与文件末尾换行检查:exit 0;
+- `ruff` 在当前 `.venv` 中未安装,因此明确记为未执行,不能写成已通过;
+- 本阶段没有调用浏览器、HTTP 客户端或真实网站调试工具,Italy 网站请求数为 0;
+- 没有修改 `ita_plugin.py`、配置、工具或现有测试,没有清理、回滚或覆盖工作区原有修改。
+
+### 23.3 CS2 通用路线接线验证
+
+2026-08-29 在 CS2 授权边界内实际执行:
+
+- `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest
+  test.test_ita_protocol test.test_ita_route_wiring test.test_ita_plugin
+  test.test_debug_ita_session test.test_debug_ita_query test.test_debug_ita_book
+  test.test_debug_ita_monitor test.test_debug_ita_soak test.test_ita_local_handoff`:
+  exit 0,137 个测试全部通过;
+- `test.test_ita_route_wiring` 用 Dublin/1321 与 Hong Kong/4937 fixture 调用同一个
+  `_resolve_route()`,并验证顶层 `service_id` 不回退、未知 capability fail-closed、
+  Sentinel/Booker route parity,以及运行时代码没有 Sede/service-id 控制分支;
+- 调试 route 的完全默认值和完全显式值均通过;只覆盖 route 的一部分会被拒绝,避免
+  组合出“某地 service id + 另一地 routing key/city”的混合路线;
+- 对 CS2 涉及的 Plugin、配置、工具和测试执行内存编译与 `git diff --check`:exit 0;
+- 对 `query()`/`book()` 与工具调用路径执行安全扫描:没有 GenerateOTP、
+  InsertNewBooking 或表单提交调用;配置保持 final disabled;
+- 初见审查新增原子 route 覆盖约束后,第一次聚焦回归因一个旧测试 fixture 少传
+  `ITA_VISA_TYPE` 返回 exit 1;修正 fixture 后第二次执行 exit 0,26 个测试全部通过,
+  没有超过两次;
+- `ruff` 在当前 `.venv` 中仍未安装,因此明确记为未执行,不能写成已通过;
+- 本阶段没有启动浏览器或调用真实网站,OTP、AVANTI、InsertNewBooking 请求数均为 0;
+  没有清理、回滚或覆盖工作区其他既有修改。
+
+### 23.4 Q-CAL 跳转监听适配验证
+
+2026-08-29 在单独批准的本地修复边界内完成:
+
+- 真实 Gate 已证明 pre/post OTP 阶段校验正确,但 AVANTI 后旧校验器要求 listener packet
+  必须保留原始 `302`,因而 fail-closed;独立 `/Reservation` 审计仍为
+  `reservations=0, waitlist=0`,没有新增预约或候补;
+- 本地 HTTP 服务与真实 Chromium/DrissionPage 机械复现了
+  `POST → 302 → GET Calendar 200` 会被高层 listener 表示为“原始 POST request + 最终
+  Calendar 200 response”,因此根因是客户端适配假设,不是网站拒绝的充分证据;
+- 修复只位于 Q-CAL 调试工具:直接 `302` 校验 Booking POST、Calendar Location 与浏览器
+  最终 Calendar;followed `200` 校验同一 Booking POST、packet 最终 Calendar URL 与浏览器
+  最终 Calendar。所有 URL 均要求同源,原始 POST 还要求无 query/fragment;任意证据不一致
+  均拒绝;
+- 通过时只记录 `direct_302` 或 `followed_redirect_200`,不会输出 query、Token、OTP、个人
+  数据或表单内容;语义合同升级为 `qcal1-stage-aware-redirect-v2`,生产 `ItaPlugin`、
+  Query/Book 合同和 final-disabled 边界均未修改;
+- 聚焦 Q-CAL 测试最终 22/22、完整 Italy 相关离线测试 171/171,均 exit 0;两份改动文件内存
+  编译、`git diff --check` 和尾随空格检查均 exit 0。首次聚焦测试因测试补丁误改另一个同形
+  冒号而 exit 1,读取精确行号后一次修正;
+- 本修复阶段没有启动浏览器、访问 Prenot@Mi、发送 OTP、点击 AVANTI 或调用 final。
+  Q-CAL-1 仍为 OPEN;下一次真实验证必须重新取得一次 OTP 与一次 AVANTI 的单独授权。
+- 新合同第一次真实启动因 Codex 内部终端无法交给负责人而在 OTP 隐藏输入点中止:OTP=1、
+  AVANTI=0、Calendar=0、final=0,清理成功。负责人随后单独批准第二次 OTP/AVANTI,并在自己
+  的终端执行。
+- 第二次真实执行确认合同和源码指纹正确,pre/post OTP 均 ready;OTP=1、AVANTI POST=1。
+  listener 已取得 POST packet,但浏览器未在 30 秒内进入 Calendar,工具 fail-closed,未执行
+  availability probe 或 final。随后独立只读 `/Reservation` 对账仍为 0/0、exit 0。
+- 当前不能把失败归因于网站协议变化:两次执行产生了两封 OTP,首先必须确认输入的是不是
+  第二次运行对应的最新验证码;若验证码无误,则下一步只增加 allowlist 脱敏诊断,记录响应
+  status/同源 path 与可见错误类别,不记录 OTP、Token、query、表单值或个人信息,再申请新的
+  一次性真实 Gate。禁止直接重试。
+
+### 23.5 Q-CAL AVANTI 失败可观测性
+
+负责人确认第二次真实 Gate 使用的是该次新收到的最新 OTP,因此旧验证码假设已降级;但旧
+工具只能证明调用过输入方法并观察到 Booking POST,无法证明 OTP 值留在 DOM,也没有保留
+Booking Form 返回后的安全错误形状。
+
+经单独授权完成的本地修复如下:
+
+- 合同升级为 `qcal1-avanti-diagnostic-v3`;OTP 输入前后分别要求
+  `otpValuePresent=false/true`,该字段只记录 presence,不记录值或长度;
+- Booking POST 被 listener 接收后输出固定计数标志;未观察到 POST、Calendar 等待超时或
+  redirect 校验失败都会打印同一 allowlist 失败诊断后再抛错,不会重试;
+- URL 只输出 `booking/calendar/services/user_area/other_same_origin/unexpected_origin/missing`
+  等固定类别;HTTP status 和 DOM 计数只接受合法数值,其余置 null;
+- DOM 只读取表单是否存在、OTP presence、OTP-invalid 是否可见、AVANTI/Turnstile 布尔状态、
+  可见 validation/confirm 数量和 final 请求数量。response body、query、OTP、Token、表单值、
+  错误文案和个人信息均不进入诊断;
+- Q-CAL 聚焦测试 24/24、Italy 完整离线回归 173/173,均 exit 0;私密 response/query/POST/DOM
+  sentinel 的序列化诊断命中为 0。本阶段真实网站、OTP、AVANTI、Calendar 和 final 请求均为
+  0。
+
+### 23.6 OTP macOS 焦点与精确回读
+
+`qcal1-avanti-diagnostic-v3` 的真实 Gate 在人工输入最新 OTP 后报告
+`otpValuePresent=false`,并在 AVANTI 前停止;该次 OTP=1,AVANTI/Calendar/final=0。这把
+问题从“验证码是否正确”收敛为“自动化没有把值保留在 OTP DOM input”。
+
+根因和修复均复用现有实现:
+
+- 当前 DrissionPage 在 macOS 上执行 `input(clear=True)` 时,clear 使用 JavaScript,但该分支
+  不主动 focus;后续键盘事件可能进入旧焦点;
+- Italy IAM 登录已经使用“先 `human_click_ele`、再 `input(clear=True)`”,Q-CAL OTP 改为同一
+  模式,不新增地区分支或另一套输入抽象;
+- 输入后把 expected OTP 作为浏览器函数参数,只返回 `this.value === expectedOtp` 的布尔值;
+  Python 和日志都不读取实际 DOM value。比较失败则 AVANTI=0;
+- 按负责人明确要求,终端 OTP 改为可见输入,提示 terminal scrollback 风险;日志仍只输出
+  `matched=true`,不记录 OTP;
+- 合同升级为 `qcal1-otp-readback-v4`。真实 Chromium + 本地 `data:` 页面验证 exit 0、外部
+  请求 0;Q-CAL 聚焦测试 27/27、Italy 离线回归 176/176,均 exit 0。本修复阶段没有真实
+  Prenot@Mi、OTP、AVANTI、Calendar 或 final 请求。
+
+### 23.7 Calendar 翻月控件与请求月份闭环
+
+`qcal1-otp-readback-v4` 的真实 Gate 已关闭进入 Calendar 的整条链路:OTP DOM 精确回读为
+true、AVANTI POST 观察到 1 次、redirect 表示为 followed 200、浏览器最终到达
+`/BookingCalendar`,且 final 请求为 0。随后工具在尝试第二个只读月份 probe 时抛出
+`NoRectError`;负责人也观察到页面没有翻月。事后独立 `/Reservation` 审计仍为
+`reservations=0, waitlist=0`。
+
+根因不是 availability 协议,而是旧工具把横向时间线的 `a.next` 当成日历翻月控件,并交给
+依赖元素矩形的 `human_click_ele()`。当前页面同时存在 Bootstrap datetimepicker 和横向
+timeline;两套控件都可能叫 `next`,但职责不同。
+
+第一版 v5 曾根据通用 Bootstrap datetimepicker 上游结构推断
+`#datetimepicker .datepicker-days th.next[data-action="next"]`。真实 Gate 到达 Calendar 后却
+稳定报告 candidate=0/actionable=0,证明该推断不适用于 Prenot@Mi 当前页面;它在翻月前
+fail-closed,OTP=1、AVANTI=1、final=0。随后独立 `/Reservation` 对账仍为 0/0。
+
+无需再次 OTP 即可恢复同一 Calendar 状态。真实只读探针取得了网站当前合同:
+
+- `InizializzaCalendario()` 对 `#datetimepicker` 调用 `datetimepicker({inline:true, locale:'it'})`;
+- 网站监听 `dp.update`,从 `e.viewDate` 取年月并调用
+  `CaricaTimelineOrizzontale(...)`,后者自然产生 availability POST;
+- 初始化后的 DOM 有 4 个 `th.dtpicker-next`,恰好 1 个可见;另有 4 个
+  `th.dtpicker-prev`,同样恰好 1 个可见;
+- 横向 timeline 的 `a.next` 仍存在但不可见,它没有 `data-action`,职责不是日历翻月;
+- 只调用网站初始化函数就自然观察到 availability=1,time-slot=0、final=0。
+
+v6 采用以下收敛合同:
+
+- 只匹配 `#datetimepicker th.dtpicker-next`;不再匹配 `.cd-horizontal-timeline a.next`,也不
+  依赖当前网站并不存在的 `.datepicker-days` 或 `data-action`;
+- 先过滤 disconnected、disabled、aria-disabled、display/visibility/pointer-events/opacity、
+  无 viewport 交集或被遮挡的节点;只有唯一 actionable 候选时才在同一浏览器脚本中点击;
+- 候选为 0 时有界等待,候选大于 1 时 fail-closed;不回退到坐标点击,不做第二次业务点击;
+- listener 必须观察到第二个 `POST RetrieveCalendarAvailability`,严格 parser 必须接受响应;
+  两次 request 的 `selectedDay` 还必须解析为不同年月,否则即使触发了请求也判定没有翻月;
+- 日志只输出候选数量、actionable 数量和 clicked 布尔值,不输出日期、response body、Token、
+  OTP 或运行时服务标识;合同升级为 `qcal1-dtpicker-navigation-v6`。
+
+早先 127.0.0.1 fixture 只证明“隐藏副本不点、唯一可见副本点一次”的通用过滤算法,不能证明
+网站 selector;v5 真实 candidate=0 已明确否定其网站结构假设。v6 因此只以网站函数源码和
+真实 DOM 为依据,不再从第三方上游模板反推 Prenot@Mi。
+
+v6 本地准出记录:Q-CAL 聚焦测试 30/30、含账号配置测试的 Italy 全量离线回归 179/179,均
+exit 0;源码指纹为 `ad4f07908ba5`。
+
+随后利用同一授权账号中可恢复的 Calendar 状态执行真实只读验证,不发送 OTP、不经过
+AVANTI:刷新 probe 返回 1 个日期项,点击 probe 返回 22 个日期项;两次 request 的
+`selectedDay` 被严格解析为不同月份。点击诊断为 candidate=4、actionable=1、clicked=true。
+执行前后 Reservation/Waitlist 均为 0/0,OTP=0、AVANTI=0、final=0,命令 exit 0、清理成功。
+这机械关闭了“真实控件可唯一选择、自然触发 availability、请求月份确实变化”的 Q-CAL 翻月
+合同,但不代表配置的三个月循环扫描或 Book final 已实现。
+
+初见审查反驳:
+
+> “既然 JavaScript `.click()` 不是真实鼠标点击,是否在绕过网站限制?”
+
+回应:这里不触碰日期、时段或最终预约,只驱动真实 DOM 已证明属于 `#datetimepicker` 的唯一
+可见 `.dtpicker-next`。网站自己的 `dp.update` handler 才负责发只读 availability 请求;工具
+不手工调用该 endpoint。使用 JS 的目的只是避免 DrissionPage 对三个隐藏副本读取 rect 的
+客户端异常。真正的业务结果仍要由自然产生的同源 availability 请求及 request 月份变化双重
+证明,任一不成立都停止。
+
+### 23.8 最多十二个未来月份的 Discovery 探针
+
+为了回答“网站最远允许翻到哪个月份”,Q-CAL 工具升级为
+`qcal1-bounded-horizon-v7`。这个版本没有改变生产 route 的
+`calendar_scan.lookahead_months` 语义;它仍表示包含当前月在内的总扫描月份数。工具另外增加
+仅用于 Discovery 的 `ITA_QCAL_FORWARD_MONTHS`,取值范围固定为 1–12,表示从当前月向后
+点击多少次。这样不会为了调研而污染生产配置合同。
+
+v7 复用 v6 已验证的 listener、严格 Availability parser、唯一可见
+`#datetimepicker th.dtpicker-next` 和 `/Reservation` 对账。它先刷新并解析当前月,再按上限
+逐月点击;每次 request 的月份必须恰好增加一个月,包含跨年。发现正向日期后仍继续,仅因为
+本次目标是探查网站边界;未来生产 Query 一旦发现正向日期必须立即返回。
+
+工具仍保持:OTP 最多 1 次、AVANTI 最多 1 次、每月只发自然产生的 Availability 请求,日期
+点击 0、时段点击 0、`InsertNewBooking` 0。下一月控件持续不可交互时只记录
+`next_control_unavailable`,不会在没有服务端证据时武断称为网站业务上限。
+
+离线准出:Q-CAL 聚焦测试 36/36、Italy 全量离线回归 185/185、两文件内存编译、尾随空格
+检查和 `git diff --check` 均 exit 0。真实 12 个月结果仍待负责人在自己的终端完成一次 OTP
+后取得;在取得输出前不得宣称网站上限已知。
+
+负责人随后把目标从“探最远边界”改为“验证最早可预约日期”。调试输出合同升级为
+`qcal1-earliest-date-v8`:它只从严格解析后的正向 `CalendarDay` 中取最小日期,并在
+`ITA_QCAL_MONTH_SCAN_RESULT.earliestAvailableDate` 输出 ISO 日期;无正向日期时输出 null。
+这不读取 DOM 文案,也不包含运行时日历 ID、Token 或具体时段。
+
+## 24. CS3A 当前落点与下一道 Gate
+
+R3、CS1、CS2 和 CS3A 已在离线边界内完成。生产 `ItaPlugin.query()` 现在拥有显式的
+`calendar` 分支,并与 Q-CAL 工具共同复用 `plugins/ita_calendar_query.py`:同一份代码负责
+listener、Availability 请求元数据校验、严格 parser、唯一原生翻月控件、最终按钮 guard 和月份
+单调递增。生产策略与 Discovery 策略刻意不同:Discovery 可继续探边界;生产在首个正向月份
+立即停止,只返回该月最早日期。
+
+这仍不等于“无人值守强 Query 已上线”,更不等于“完整 Italy Book 已跑通”:
+
+- 默认 Sentinel/Booker 配置仍是 `query_mode=services_probe`;
+- `calendar` 分支只接受已经由同一实例确认的 Calendar 状态,缺少准备态时 fail-closed;
+- CS3B 的自动 OTP、AVANTI 和 route 连续性尚未实现;
+- Q-CAL-2、Q-XACC、OTP-AUTO、FENCE 和 FINAL 仍是独立 Gate;
+- Book、时段选择和 `InsertNewBooking` 不在 CS3A 范围内。
+
+**CS3A 已取得一次现场通过结果**:负责人回传同一人工准备的 Session 内两次生产 Query
+均为正向、OTP/AVANTI 各一次、最终请求为零、前后预约数量不变及 exit 0,见 §24.4 和
+Discovery E45。旧工具只有 `services_probe` 加 `scan_calendar_horizon()` 的执行不能替代
+这一证明;本次验收模式直接调用生产分支。
+
+CS3B/OTP-AUTO 仍依赖云端邮箱授权、Italy 邮件匹配和安全日志证据,见 §25。负责人最新
+确认 Query 邮箱尚未接入并授权,要求列为待办(Discovery E50、ITA-OTP-01),暂不推进
+邮箱接入。已有人工 OTP 验证结果保留;无人值守自动接码仍未完成,不切换生产配置。
+
+### 24.1 CS3A 离线准出记录
+
+2026-08-30 已机械验证:
+
+- 生产扫描器从当前月开始严格逐月前进,首个正向月份立即停止;
+- 结果只发布首个正向月份中最早日期,`earliest_date` 与唯一
+  `DateAvailability(times=[])` 一致;
+- 首月正向、跨年、完整负向 horizon、月份跳跃、请求月份与响应日期不一致、下一月控件失效
+  均有离线测试;未知或不完整扫描 fail-closed,不能伪装成无号;
+- 生产 Query、Q-CAL 调试工具共同调用 `plugins/ita_calendar_query.py`,调试工具不再复制
+  listener、翻月、parser 或 final guard;
+- 生产模块不存在 `4937`、`Hong Kong`、`slot.hkg` 或 `HKG` 硬编码;
+- 默认配置未改变,OTP、AVANTI、日期点击、时段点击、最终预约和外部请求均为 0。
+
+实际命令与结果:
+
+1. 聚焦回归:90/90,exit 0;
+2. Italy 全量离线回归:198/198,exit 0;
+3. 8 个相关 Python 文件内存编译:exit 0;
+4. `git diff --check`:exit 0;新增文件及本轮相关测试/文档行尾空白检查:exit 0;
+5. 生产模块地区硬编码反向扫描:0 命中,命令 exit 0。
+
+全文件空白扫描曾以 exit 1 报出 `plugins/ita_plugin.py` 的历史行尾空格;
+`git diff --check` 证明本 Change Set 没有新增这些问题。遵守“不顺手优化”,本轮没有清理与
+功能无关的历史格式。
+
+### 24.2 CS3A 生产 Query 现场验收模式
+
+2026-08-30,负责人授权仅补现有调试工具的生产 Query 验收入口,人工完成一次 OTP 准备。
+工具合同为 `qcal1-production-query-v10`。本次没有修改扫描算法、生产配置、自动邮件读取或
+Book;真实网站执行由负责人在自己的终端进行。随后收到一次现场通过结果,详见 §24.4;
+这里保留当时批准的验收步骤与边界,不外推为长期稳定性或完整 Book 验收。
+
+#### 入口与复用边界
+
+- `tools/debug_ita_calendar_gate.py` 增加显式 `ITA_QCAL_MODE=production_query`;未指定时仍是
+  原有 `discovery_horizon` 模式,避免悄悄改变旧命令语义。
+- 复用原有账号、持久化浏览器 profile、route resolver、表单准备、OTP DOM 回读、一次性
+  AVANTI 和 `/Reservation` 前后计数;不新建第二套登录或预约流程。
+- 准备阶段仍只调用一次 `services_probe`。确认同一实例的 route 后,只在内存把模式改为
+  `calendar`,连续调用两次真实 `ItaPlugin.query()`,无论成功失败都恢复内存模式。
+- 两次生产调用均使用已有 `scan_until_first_available_month()`,不替换扫描函数、不伪造网络
+  响应,不调用旧 `scan_calendar_horizon()`。结果复用 VFS 风格 `VSQueryResult` 及已有
+  `to_snapshot_payload()`;只验证序列化,不向 Redis 发布测试信号。
+- 插件只新增本实例的 `last_calendar_query_scan` 诊断字段。每次 `query()` 开头清空,成功
+  扫描后写入;配置、Session 重建和 cleanup 也清空。它不是缓存,不参与下一次业务决策,
+  不进入共享快照,也不能作为 Book 的时间依据。
+- 被动 Network 计数借用仓库已有 CDP callback 注册方式。使用页面 driver,和生产
+  `page.listen` 的独立连接并存;拒绝覆盖已有 handler。不启用 Fetch 拦截、不改请求、
+  不保留 body、Cookie 或 Token,退出时卸载自己的 callback。
+
+#### 什么算现场验收完成
+
+1. 一次 Session 创建、一次 OTP、一次 AVANTI 后完成 **两次**生产 Calendar Query;
+   两次之间间隔 3 秒,不自动重试失败流程。
+2. 每次都逐月扫描,在首个正向月份停止,并返回该月最早日期;范围上限包含起始月。
+   第二次必须重新从第一次的初始月份扫描,不能直接把上次停留的月份当起点。
+3. 实际返回的 `success`、状态、最早日期、唯一 `DateAvailability(times=[])` 及共享快照
+   必须与该次生产扫描证据一致;不能只验证一条自行打印的日期。
+4. 每次 Query 的 Network 增量:OTP=0、AVANTI POST=0、最终请求=0,Availability 请求数
+   等于该次扫描月份数。页面初始化可能自动选择日期并读取时段,这不等于工具主动选时段。
+5. `/Reservation` 预约和候补数量前后相同;全程已知最终端点请求数为 0。
+6. 两次中至少一次自然得到正向日期,聚合输出 `passed=true`,cleanup 成功,进程返回 0。
+
+库存可能在两次查询之间变化,因此**不要求两次最早日期相同**。如果两次完整扫描都自然
+无号,只能证明负向查询完成,正向验收仍未关闭,返回 2。入口本身暂时无号时也返回 2,
+不会为了得到成功日志而发送 OTP。
+
+以上是客户端可观察的证据:已知请求的计数与预约数量没有变化,并不能证明服务器内部
+绝对没有草稿,也不替代 Q-CAL-2 的长期运行验证。本次不批准无人值守生产运行。
+
+#### 负责人终端命令
+
+香港仅作为已取得字段证据的 route 示例,算法和验收模式不绑定香港或 `4937`。
+最多扫描 12 个月,**每次一旦发现首个正向月份就停止**;不会为了用满上限继续翻页。
+两次查询都无号时可能各扫描满 12 个月。这不是无限循环。
+
+```sh
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_QCAL_MODE=production_query \
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 \
+python -B tools/debug_ita_calendar_gate.py
+echo "EXIT_CODE=$?"
+```
+
+`production_query` 模式只使用 route 的 `ITA_CALENDAR_LOOKAHEAD_MONTHS`,不使用仅属于旧
+Discovery 的 `ITA_QCAL_FORWARD_MONTHS`。OTP 仍由负责人输入一次;输入可见,终端历史可能
+保留验证码,回传输出时应删除该行。运行时不要手动翻月、刷新、选择时段或点击最终按钮,
+避免改变扫描证据和请求计数。
+
+需要回传:
+
+- `ITA_QCAL_TOOL_CONTRACT`(版本及源码指纹包含工具、生产插件、共享适配层、纯协议核心);
+- `ITA_QCAL_MODE`;
+- 两条 `ITA_QCAL_PRODUCTION_QUERY_RESULT`;
+- `ITA_QCAL_PRODUCTION_QUERY_GATE_RESULT`;
+- `ITA_QCAL_GATE_CLEANUP_OK` 和 `EXIT_CODE`;失败时同时提供脱敏的失败行。
+
+| 进程返回值 | 含义 |
+| --- | --- |
+| 0 | 两次生产 Query 合同与对账通过,至少一次自然正向,清理成功 |
+| 1 | 流程、协议或证据检查失败;不要重复发送 OTP 猜原因 |
+| 2 | 自然库存未提供正向样本,正向 Gate 未完成,不是假装程序成功 |
+| 3 | 清理异常,需要先检查残留状态 |
+
+#### 初见审查
+
+反驳:“工具也能自己扫出正确日期,怎么证明这次验证的是生产实现?”
+
+回应:验收主调用是生产 `ItaPlugin.query()`,扫描证据由其内部实际扫描器产生;工具只比对
+返回值和被动请求计数,不实现或替换扫描算法。离线集成测试保留真实 Query、共享扫描器、
+parser 和序列化,仅用假浏览器提供受控页面与响应;另外验证旧 horizon 入口没有被调用。
+这关闭本地接线路径问题,真实浏览器行为仍需上述现场 Gate,不能由 mock 测试代替。
+
+### 24.3 本次验收入口的离线验证记录
+
+2026-08-30,本轮未执行真实网站登录、OTP 发送、AVANTI 提交或 Book 操作;下述测试全部
+离线。生产配置未修改,工作区原有改动保留。
+
+执行命令及返回结果:
+
+```sh
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.test_debug_ita_production_query_gate
+# exit 0;21 tests,OK
+
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
+  test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_calendar_gate test.test_ita_plugin test.test_ita_calendar_query
+# exit 0;102 tests,OK
+
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
+  test.test_add_ita_query_account test.test_ita_protocol \
+  test.test_ita_calendar_query test.test_ita_route_wiring test.test_ita_plugin \
+  test.test_debug_ita_session test.test_debug_ita_query test.test_debug_ita_book \
+  test.test_debug_ita_calendar_gate test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_monitor test.test_debug_ita_soak test.test_ita_local_handoff
+# exit 0;220 tests,OK
+
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -c 'from pathlib import Path; paths = ["plugins/ita_plugin.py", "tools/debug_ita_calendar_gate.py", "test/test_debug_ita_production_query_gate.py", "test/test_debug_ita_calendar_gate.py", "test/test_ita_plugin.py"]; [compile(Path(p).read_bytes(), p, "exec") for p in paths]; print("COMPILE_OK files=" + str(len(paths)))'
+# exit 0;COMPILE_OK files=5;不生成 pyc
+
+git diff --check
+# exit 0
+
+if rg -n '[[:blank:]]+$' tools/debug_ita_calendar_gate.py test/test_debug_ita_production_query_gate.py test/test_debug_ita_calendar_gate.py test/test_ita_plugin.py docs/ita_plugin_generic_schengen_design.md; then exit 1; else test "$?" -eq 1; fi
+# exit 0;本轮所列文件没有行尾空白
+
+if rg -n '4937|Hong Kong|slot\.hkg|HKG' plugins/ita_plugin.py plugins/ita_calendar_query.py plugins/ita_protocol.py; then exit 1; else test "$?" -eq 1; fi
+# exit 0;生产模块没有香港特定常量
+```
+
+首次新入口聚焦测试为 101/101、exit 0,但测试替身使用 `__new__` 跳过真实初始化,析构时
+产生未初始化属性告警。修正测试替身的 cleanup,并补上“必须恰好两次”的负向检查后,
+再次验证 102/102、exit 0,无该告警;没有为消除测试告警而修改生产清理逻辑。
+
+### 24.4 CS3A 负责人现场回传通过(2026-08-30)
+
+唯一事实记录为 Discovery E45。负责人回传了第二轮完整结果及聚合结果:
+
+- 第二轮从 `2026-08`、`2026-09` 的正向日期数 `0/0` 扫描到 `2026-10` 的 `14` 个正向日期;
+  上限 12 个月、实际 3 个月,停止原因 `first_available_month`,最早日期 `2026-10-13`;
+- 返回 `Available`、唯一日期、`timesCount=0`,`snapshotVerified=true`;
+- 第二轮请求增量:Availability=3、OTP=0、AVANTI=0、final=0;
+- 聚合报告:Query=2、positiveQueries=2、Availability=6、OTP=1、AVANTI=1、final=0;
+  Reservation 和 Waitlist 前后均 `0/0`,`passed=true`;
+- `ITA_QCAL_GATE_CLEANUP_OK`,`EXIT_CODE=0`。
+
+这是负责人执行 `python -B tools/debug_ita_calendar_gate.py`(production_query 模式)的
+回传证据,不是助手再次访问网站。未回传第一轮完整结果、启动版本/源码指纹行和原始
+Network,因此不推断第一轮具体日期,也不宣称独立复现或完整字节级运行溯源。
+
+结论:本次人工准备后的生产 Query 验收通过,确信度高。该日期是发现时的线索,不是锁定
+库存;Book 仍需用用户账号重查,自动接码、长时间运行和跨 Sede 验证没有因此通过。
+
+## 25. CS3B / OTP-AUTO 前置核对(未开始业务实现)
+
+### 25.1 当前边界与结论
+
+当前待办(2026-08-30,负责人明确要求):
+
+- [ ] **ITA-OTP-01:自动处理首次及重新需要 OTP 的 Calendar 准备,包括邮箱接入和云邮箱 API 授权。** 状态:未完成、
+  暂缓;负责人已确认“还没有”。恢复时复用现有 VFS/BLS 取信链路,验证授权有效、目标
+  收件人与新验证码匹配、旧码/串号不命中及日志不泄露。完成标准为取得这些受控取信证据;
+  仅登记邮箱不算通过 OTP-AUTO;还需证明重登后仅一次安全接续到 Calendar。当前不执行自动接入、取信或发码,也不安排提醒;除该 TODO 外的恢复与持续查询按 CS3R 独立推进。
+
+此前负责人同意进行前置补证。已归档 E45、核对现有接码实现与前置条件;当时邮箱接入
+状态未知,现已由 E50 更新为未接入并暂缓。负责人分享的 Gmail 标签两次访问未取得正文(E47),随后通过
+手工转述补齐一份英文邮件的发件人、主题和验证码行(E48,已脱敏)。这不是完整原始邮件
+或云端取信结果。随后两名指定子代理已找到 webapp 中的原有 IMAP/API 实现,确认 web-ui
+没有邮箱授权页面(E49,详见 §26);线上授权仍未验证。不会为了收集证据重新发送 OTP,
+也不会读取其他邮件、开启转发、注册邮箱服务或修改业务/生产配置。
+
+可以直接复用的是现有邮箱读取 API 和 VFS 的调用顺序,而不是复制其他网站的固定邮箱、
+发件人或模板。接码能力是否对本次 Italy 账号真正可用,仍需真实邮箱授权和受控读取证据。
+
+### 25.2 已核对的复用依据
+
+| 现有来源 | 源码事实 | Italy 的复用方式/边界 |
+| --- | --- | --- |
+| `plugins/vfs_plugin.py:352`、`:891` | 在引发 OTP 的请求前记录 UTC `sent_at`,再传给 `_read_otp_email()` | 复用“先记时间,再单次发码,再取信”的顺序 |
+| `plugins/vfs_plugin.py:705` | 使用共享 `fetch_mail_content()`;recipient 取当前账号 username;正文 regex,另有 VFS 图片分支 | 直接复用共享 API;不照搬 VFS 图片识别、LLM 或其固定邮件过滤条件 |
+| `plugins/bls_plugin.py:943` | 同样调用共享 API;循环取信;其单次底层请求上限另由 SDK 决定 | 作为接口复用佐证;不能把 `wait_sec=30` 宣称为整个流程硬超时 |
+| `toolkit/vs_cloud_api.py:361` | `POST /api/email-authorizations/fetch`,返回 `data.body` 字符串 | 不新建 Provider、IMAP 客户端、Resend、消息队列或邮箱后端 |
+| `vs_types.py:127` | `VSAccount` 只有 id/username/password,没有 email 字段 | recipient 使用经确认的当前账号 username,不扩充账号模型 |
+| `tools/debug_ita_calendar_gate.py:745` | `OneShotAction` 在调用前消耗许可,异常也不允许同一 guard 再执行 | 复用现成“一次性动作”合同,不重新设计通用工作流引擎 |
+| Q-CAL 工具的 preflight、OTP 回读、AVANTI 校验 | 这些行为已经经历人工配合的真实验证 | 后续准备态接线复用这些行为;生产模块不得反向 import `tools` |
+| `plugins/tls_plugin.py` 的本轮检索 | 未找到 `fetch_mail_content` 或邮箱 OTP 读取调用 | 不把 TLS 插件当成已存在的邮箱接码实现;不推断其他注册工具的能力 |
+
+VFS/BLS 当前使用同一个写死的主邮箱。该值不是 Italy 账号,也不是可直接复制的授权依据;
+本轮没有记录其真实地址。`authorization_email` 必须来自已有、已获授权的私密配置。
+
+### 25.3 共享 API 的实际合同与未知项
+
+本节表格保留 E46 首次走读 Coordinate 调用端时的知识边界。后续 E49 已取得 webapp 实现,
+sender/recipient、关键字、时间窗口及 MIME 行为的最新结论以 §26 为准;线上授权和真实
+邮箱测试仍未完成。
+
+| Python 参数 | 发送字段 | 当前能证明的事实 |
+| --- | --- | --- |
+| `email` | `email` | VFS/BLS 传主邮箱;目标为 email-authorizations API,不能凭字符串就认为已授权 |
+| `sender` | `sender` | 过滤值会传给云端;精确地址、显示名、大小写如何匹配,客户端没有实现 |
+| `recipient` | `recipient` | VFS/BLS 传当前账号 username;跨账号筛选实际由云端负责 |
+| `subject_keywords` / `body_keywords` | `subjectKeywords` / `bodyKeywords` | 字符串原样传递;云端的包含、分词、AND/OR 语义尚未取得合同 |
+| `sent_date` | `sentDate` | VFS 使用 UTC `YYYY-MM-DD HH:mm:ss`;云端时区解释/比较边界需验证 |
+| `expiry` | `expiry` | 转为字符串;不能把调用方填写的 300 秒当成 Prenot@Mi 验证码有效期 |
+| `only_text` | `onlyText` | 默认 True;不需要沿用 VFS 的图片识别分支 |
+
+单次 HTTP timeout 在客户端固定为 300 秒。`fetch_mail_content()` 本身没有客户端重试循环;
+云端是否等待、怎样处理重复邮件并未由此证明。BLS 的外层轮询叠加这个 timeout,不能作为
+Italy 的准确等待预算;VFS 的单次调用路径更接近当前“发一次、取一次、不重发”合同。
+
+关键限制:客户端只返回正文,没有把命中邮件的 message id、sender、recipient、接收时间或
+命中数量交给调用者。因此“参数传对了”和“后台确实只读到这封新邮件”不是同一项验收。
+必须通过既有后端合同或受控正反样本验证,不能只用 mock 参数断言关闭旧码/串号风险。
+
+仓库没有邮箱授权查询或授权建立的 SDK 方法,也没有该服务后端实现。本轮没有猜测新的
+API 路由去访问后台。`fetch_mail_content_from_top()` 缺少当前会话的发送时间参数,不能用作
+失败后抓取旧验证码的 fallback。
+
+### 25.4 新发现的日志前置条件(需要单独批准的共享范围)
+
+`toolkit/vs_cloud_api.py:43` 的 `VSC_DEBUG` 会格式化请求参数及 `resp.text`。
+`vs_log_macros.py:15` 将它交给当前 logger;`logger_setup.py` 的应用 logger/handler 默认是
+INFO。本轮用全假的正文和收件人、内存 handler、fake HTTP session 复现:
+
+```text
+level=DEBUG body_visible=True recipient_visible=True
+level=INFO body_visible=False recipient_visible=False
+NETWORK_REQUESTS=0 SYNTHETIC_DATA_ONLY=true
+```
+
+诊断命令 exit 0 表示复现检查正常执行,**不是**“隐私 Gate 通过”。目前没有执行真实取信,
+没有证据表明已有真实 OTP 泄露,但 DEBUG 路径确实不满足 §14 的正文/验证码零日志合同。
+只在 Italy 插件里不打印 OTP,不能清除共享 SDK 已经输出的邮件正文。
+
+此外,共享 SDK 的 HTTP/业务异常可能包含云端原始响应文本,接入时需要明确禁止把其内容
+带入插件日志或 traceback。默认 INFO 只避免上述 DEBUG 行,不替代完整异常安全验证。
+
+拟处理方向仍是最大化复用:在原共享调用链给邮件请求做最小日志/异常脱敏,保持 API、请求
+参数、返回正文和状态分类不变;或找到已经存在且经过验证的等价隔离机制。当前未找到该
+机制。因为涉及原方案禁止修改的共享 SDK,必须先单独确认变更范围;本轮没有修改它,
+也不会另建邮箱服务来绕开这项问题。
+
+### 25.5 后续最小接线与验证顺序
+
+这是基于现有设计的待补证接线顺序,不是本轮已经实现的代码:
+
+1. `plugins/ita_protocol.py` 承接经过真实模板验证的 mail 配置/正文提取纯函数;输入输出
+   不做网络操作,不执行邮件 HTML 或指令,不接入大模型。E48 为英文前缀与六位数字提供
+   样本依据;完整正文、云端文本转换与唯一候选判定仍需验证,不猜测其他模板。
+2. `plugins/ita_plugin.py` 负责当前账号、route、Session 准备状态与共享 API 调用;复用 VFS
+   的时间记录和取信顺序、Q-CAL 的一次性 OTP/AVANTI,不改 Sentinel/Booker/账号模型。
+3. 将已有 Q-CAL 准备行为下沉到生产可用位置,调试工具调用同一实现;沿用 CS3A“生产与
+   调试共享适配层”的模式。文件拆分在准备态合同收敛后锁定,不先复制一套准备流程。
+4. 邮箱未授权、配置不完整、未知模板必须在发 OTP 前尽量失败;发码已发生后取信超时、
+   多码或格式不符则停止,不重新发码、不刷新 `sent_at` 追逐旧信。
+5. 进入 Calendar 后继续使用已验证的扫描器;第二轮 Query 不重做准备。Session 重建不能
+   假定旧 Calendar 仍有效;跨进程/跨 Session 的账号冷却由既有调度合同和 Q-CAL-2 单独验证。
+
+准入测试清单:
+
+- 纯解析:真实脱敏模板、前导零、多码、无匹配、格式错误、未知模板、超大正文;
+- API 接线:主邮箱与当前 recipient 分离、先记录时间后发送、只取一次、只取正文;
+- 后端 Gate:授权邮箱可读、错误 recipient 不命中、发送时间前的邮件不命中、重复邮件
+  的确定行为;这些不能由客户端 mock 代替;
+- 安全:INFO/DEBUG、HTTP 错误/业务错误/超时的日志与异常都不得出现合成 OTP/正文标记;
+- 状态:取信失败不重发 OTP,AVANTI 结果不明不重提,同会话第二轮 Query 的两种准备
+  请求增量均为零,错误 route/账号/Session 不复用准备态;
+- 回归:现有 220 项离线测试保持通过;最终真实 Gate 仍由负责人终端操作,final=0。
+
+E48 已补齐一份邮件字段与验证码行的手工样本,E49 已找到现有管理 API;无需重新发送
+OTP,也不再让负责人寻找 web-ui 中不存在的邮箱授权菜单。E50 已确认未接入并要求暂缓。
+后续恢复 ITA-OTP-01 时,从单个授权 Query 邮箱开始核对登记和实际可读性;不索取密码、
+密钥或整个接口响应,不把待办登记视为已经授权执行。
+
+### 25.6 本轮验证与初见审查
+
+2026-08-30,仅更新本文及 Discovery。七个受关注的业务/SDK/生产配置文件用 SHA-256 对比
+确认未改变;未运行登录/OTP/取信/AVANTI/Book,未修改任何邮箱设置。
+
+- Italy 全量回归沿用 §24.3 的完整 unittest 命令再次执行:220/220,exit 0;
+- DEBUG/INFO 对照诊断使用当前 `_perform_request` 的 AST 方法体、内存日志和 fake HTTP
+  响应,命令 exit 0,网络请求 0;结果为 §25.4 的潜在敏感日志路径已复现;
+- 文档行尾空白检查、`git diff --check`:exit 0。
+
+初见审查:“现成 API 都接收 recipient 和 sentDate,为什么不直接认为旧码/串号问题已解决?”
+
+回应:传参只是客户端事实;该客户端返回的只有正文,不能独立证明后台筛选的结果。沿用
+同一 API 是复用架构,补真实过滤与隐私验证是接入验收,两者并不冲突。没有这些证据,
+不能用一段能匹配六位数字的代码宣称无人值守接码已完成。
+
+### 25.7 邮件样本访问状态更新(E47)
+
+负责人已分享现有 OTP 邮件的 Chrome 标签。实例、标签标识、标题和 URL 首次核对均匹配,
+但正文读取及一次恢复访问均超时。达到两次上限后停止;没有实际取得发件人或正文,不能
+把标签标题 `OTP Code` 当成完整邮件模板,也不能关闭邮箱云端接入或 OTP-AUTO Gate。
+
+改由负责人提供同一封邮件的脱敏截图或文字,仅需发件人地址、主题和验证码相关正文;
+验证码用 `[OTP]` 替换,个人资料及动态链接移除。无需重新发送 OTP、导出整个邮箱或安装
+新邮件服务。现有 API 复用方向、共享 SDK 日志问题及后端正反样本验收要求均保持不变。
+
+### 25.8 邮件字段与提取合同候选(E48)
+
+负责人手工提供的样本已脱敏归档:显示名 `Prenotami`、发件地址
+`noreply-prenotami@esteri.it`、主题 `OTP Code`、正文片段 `OTP Code:[OTP]`,样本验证码
+为六位 ASCII 数字。样本转述的字段/形态确信度高,但并非助手读取原始邮件或云端命中结果。
+
+在不新增邮件服务的前提下,现有 `fetch_mail_content()` 的候选过滤值可收敛为上述发件地址、
+主题及正文前缀;`recipient` 仍是经核对的当前 Italy 账号,`authorization_email` 仍来自
+已授权的私密配置,两者不能混用。不能假设云端将地址、关键字和时间按期望精确组合匹配。
+
+解析沿用 VFS 的确定性正文提取模式,仅在 `OTP Code:` 上下文取六位数字,保留前导零;
+无匹配、多候选或未知模板均停止。完整正文是否还有其他候选、HTML 转文本形态、其他语言
+和有效期尚未取得证据;不能把这份样本扩大为全语言/全领区验证,也不使用全文任意六位
+数字或大模型猜码。具体实现与测试仍在独立 CS3B 范围内,当前没有新增代码。
+
+当前仍未关闭:云端邮箱授权/收件人对应关系、后台排除旧码/串号的正反例、SDK 日志/异常
+安全以及自动填码到 Calendar 的真实验收。人工分享邮件内容不等于授予云端服务新的权限。
+
+## 26. VFS/BLS 邮件链路跨项目复核(E49,未开始实现)
+
+### 26.1 复用结论与职责
+
+两名负责人指定的 `luna_worker/max` 分别只读调查 `web-ui@b21b7ca` 与 `webapp@fbb82bb`。
+结论是**可以复用原有整条邮件服务链路,不需要新建 Provider 或后台**,但现有行为不能
+直接宣称满足 Italy 的精确新邮件、隐私和一次性准备合同。完整证据与验证命令见 Discovery E49。
+
+| 层 | 已有实现 | 本阶段动作 |
+| --- | --- | --- |
+| web-ui | Next.js 门户、用户/站点账号/任务管理;门户绑定邮箱及 email_verified | 无邮箱授权页面,不新增页面,不把门户邮箱验证当作 IMAP 授权 |
+| Coordinate | VFS/BLS 共用 `VSCloudApi.fetch_mail_content()`,八参数 POST Query | 保留 API 调用路径与 VFS 发码前 UTC 时间记录顺序 |
+| webapp | FastAPI 管理员 API、邮箱凭据登记、IMAP 取信与候选筛选 | 使用现有服务;本轮只查源码,不修改、不实际取信 |
+
+管理 API 的已确认路径是 `GET /api/email-authorizations/email/{email}`;默认 API 文档在
+webapp 根路径 `/docs`(部署 host/反代路径未验证)。它要求管理员 Bearer session,并会
+返回包含授权码等凭据的对象,没有 exists-only 接口;不能让负责人粘贴完整 JSON。
+记录存在也不能证明 IMAP 凭据仍有效,模型没有 active/expiry/last-check 状态。
+
+### 26.2 从“未知”收敛出的实际合同差异
+
+1. `sender/recipient` 是 raw From/To 子串,不是精确邮箱地址;多关键字 CSV 是 OR-any。
+   单纯把完整官方发件地址填入参数,不能宣称完成了地址认证或本地精确校验。
+2. 取信只扫描 INBOX 最近 10 个消息序列号;按最后一个 Received 转 UTC 后排序,匹配
+   `[sentDate, sentDate + expiry]` 闭区间,取首个命中。没有唯一性、去重或消费语义。
+3. `onlyText=True` 仍保留 HTML,可重复输出 MIME plain/HTML 中的同一码。E48 的候选解析
+   规则必须覆盖此差异;相同码的 MIME 重复不等于不同验证码冲突,也不能未经验证便对
+   任意引用/转发去重并取首码。纯函数归一策略需在实现前固定并用真实云端形态验收。
+4. 后端轮询预算与 SDK HTTP timeout 不是端到端硬限时;IMAP 阻塞阶段无显式 socket timeout。
+5. 默认读写 SELECT + RFC822 有隐式已读副作用,最近候选邮件可能在筛选前已被读取。
+   未来现场 Gate 要说明这一邮箱状态影响;本轮没有执行 fetch。
+6. 返回只有 body,缺少 From/To/时间/唯一标识。客户端 mock 参数正确,不能关闭跨账号
+   或旧码验收;不能承诺在 Italy 端凭不存在的 metadata 做完整复核。
+
+### 26.3 最小下一步与变更纪律
+
+当前下一步只核对一个目标邮箱的登记存在性、管理员身份和非敏感配置完整性;在负责人
+自己的已授权环境执行,原始凭据不输出、不入日志。该检查不取信、不发 OTP、不修改登记。
+
+获得登记证据后,再制定最小的真实取信 Gate:账号/From/To/Received 时间、正常邮件与
+旧邮件/错误收件人、MIME形态、耗时和已读变化,不能仅测“能解析六位数字”。所需动作、
+目标邮箱和副作用另行说明,不把此轮只读源码调查当成真实取信授权。
+
+已定位的共享 SDK 日志问题、后端子串筛选与响应/日志风险是明确的接入约束;若关闭
+Italy 既定准入条件需要改 webapp 或 SDK,应提交小范围合同/测试计划并单独批准。不修改
+VFS/BLS 行为、不替换 Provider、不增加邮箱管理 UI,不在调查中顺手整改硬编码凭据。
+
+### 26.4 验证与确信度
+
+- 两仓静态调研、路由/字段对应:高;各仓 HEAD/clean 状态已记录。
+- 主代理实际 SDK 方法 + fake HTTP 验证:exit 0,八参数与空 body/一次调用均确认。
+- 主代理实际 `_extract_body` + 合成 MIME:五场景七断言通过,exit 0;HTML保留、相同前缀
+  出现两次、空白折叠已离线复现;endpoint八参数 Query/类型绑定也通过。
+- 这两项离线诊断网络请求为 0,不导入后端应用;没有运行会加载环境/数据库的 pytest。
+- 邮箱登记、实际登录有效性、线上部署一致性、自动接码及完整 Book:未验证,不宣称通过。
+
+初见审查:“是不是发现现有服务不够严格,就准备重写一套?”
+
+回应:不是。Provider、授权存储、管理员鉴权、API与调用顺序都有现成实现。当前只补事实
+和准入证据;若确需改变匹配或脱敏行为,也限定在既有链路的小范围变更,经批准后再做。

+ 1078 - 0
docs/ita_plugin_recovery_design.md

@@ -0,0 +1,1078 @@
+# Italy 插件修复设计:VFS/BLS 复用优先版(历史记录)
+
+> 文档状态:`SUPERSEDED / HISTORICAL IMPLEMENTATION LOG`
+>
+> 当前规范:`docs/ita_plugin_generic_schengen_design.md`(R3)。本文保留早期调查、决策演进和实现审计用途,不再作为下一阶段研发依据。
+>
+> 重要警告:本文形成于香港 E43 正向证据闭环之前。凡是将 `bookingForm` 弱信号用于生产触发、假定 OTP 位于 Calendar 之后、把默认月份无号外推成整个 Calendar 无号、或禁止进入 Calendar 的旧结论,均已被 R3 取代。
+>
+> 版本决策:以现有 VFS/BLS 技术方案为默认基线。能直接复用就不抽象,能通过现有配置解决就不新增框架能力,只有 Prenot@Mi 的网站差异留在 Italy 插件内。
+>
+> 本文主体是设计基线;实施进度见 §17。设计阶段及 2026-08-27 的
+> Change Set 1/2 离线实现均未登录网站、发送 OTP 或执行真实预约。
+
+---
+
+## 0. 本阶段完成标准
+
+本文满足以下条件才算完成:
+
+1. 从进程架构、账号模型、信号、插件生命周期、Query、Book、OTP、结果类型到测试,逐层说明复用 VFS/BLS 的哪一部分;
+2. 每个“新增设计”都有证据证明现有 VFS/BLS 无法表达;
+3. 首版修改范围被限制在 Italy 插件、Italy 配置、Italy 测试和调试工具;
+4. 每个未知网站行为都有真实验证 Gate;
+5. 不包含密码、Cookie、Token、OTP、个人资料或第三方密钥值。
+
+本版明确撤回上一版的以下首发设计:
+
+- 不新增 Signal v2;
+- 不新增 availability episode;
+- 不新增 Redis 原子 claim;
+- 不新增通用工作流引擎;
+- 不创建 `plugins/ita/` 子包;
+- 不修改 `VSQueryResult`、`AvailabilityStatus`、Sentinel、Booker、Standalone 或 Redis 客户端;
+- 不把 Italy 修复升级为框架重构项目。
+
+这些能力未来只有在现有 VFS/BLS 机制被真实证据证明不够用时,才作为独立改进提案讨论。
+
+---
+
+## 1. 一句话结论
+
+首版 Italy 应完整复用现有闭环:`Sentinel + 内置 Query 账号池 → VSQueryResult → Redis 30 秒信号 → OrderBooker 用户热 Session → plugin.book()`;Query 用 BLS 已存在的“成功触发但没有具体日期”表达法发弱信号,Book 用 VFS 的“在自己 Session 中重新加载、重新查 Calendar/TimeSlot、再提交”的方法完成预约,Italy 只实现 Prenot@Mi 特有的页面选择器、表单、Calendar、PRENOTA 和 OTP 顺序。
+
+用人话说:
+
+- **大架构不改**:继续使用项目现成的 Sentinel/Booker 接力;
+- **账号模型不改**:Query 是团队账号池,Book 是订单里的用户账号;
+- **信号协议不改**:继续写 `vs:signal:{routing_key}`;
+- **数据类型不改**:继续用 `VSQueryResult`、`DateAvailability`、`TimeSlot`、`VSBookResult`;
+- **OTP 基建不改**:继续调用现有 `VSCloudApi.fetch_mail_content()`;
+- **只写网站适配**:修正 Italy 自己的 Query 和 Book。
+
+---
+
+## 2. 合规前提
+
+项目方已经确认:
+
+- VFS/BLS 的整体技术方案属于允许复用的合规实现;
+- Query 池账号属于不同真实团队成员,已经明确授权;
+- Book 使用最终用户自己的真实账号。
+
+本文把这三点作为业务前提,不再重新设计另一套账号或合规体系。
+
+Italy 仍要保持与现有方案一致的身份边界:Query 账号只发现机会,用户账号完成属于自己的预约;不跨账号复制 Cookie、Session、CSRF 或页面状态。
+
+---
+
+## 3. 已验证事实与仍待验证事实
+
+### 3.1 已验证
+
+| 事实 | 证据 | 确信度 |
+|---|---|---|
+| IAM 登录字段为 `callback_1`、`callback_2` | 真实 DOM + 自动登录 | 高 |
+| 自动登录可以到 `/UserArea` | `ITA_SESSION_OK`、exit 0 | 高 |
+| Dublin 通用签证服务候选为 `service_id=1321` | Services DOM/href | 中高 |
+| 无号请求为 `GET /Services/Booking/1321` | Network | 高 |
+| 无号时 302 回到 `/Services` | Network `Location: /Services` | 高 |
+| 无号页面有非空 `#WNotAvailable` 和已知弹窗 | DOM | 高 |
+| 无号探测没有 Calendar、OTP 或预约业务 POST | Network | 高 |
+| 自动 Query 已正确返回 `NoAvailable` | 真实执行 exit 0 | 高 |
+
+### 3.2 官方业务顺序
+
+官方 Prenot@Mi 用户手册描述的顺序是:
+
+```text
+填写服务表单并接受隐私条款
+  → AVANTI
+  → Calendar
+  → 选择日期与时间
+  → PRENOTA
+  → 注册邮箱收到 OTP
+  → 输入 OTP 并点击 OK
+  → 显示预约摘要、预约编号和二维码
+```
+
+手册同时说明,不同领馆和不同服务的字段会变化。因此我们复用 VFS/BLS 的流程骨架,但不能复制它们的网站字段。
+
+来源:
+
+- [Prenot@Mi 官方用户手册 V2.0](https://consstoccarda.esteri.it/wp-content/uploads/2023/08/ManualeCittadino_2.0.pdf)
+- [意大利驻都柏林大使馆签证说明](https://ambdublino.esteri.it/en/servizi-consolari-e-visti/servizi-per-il-cittadino-straniero/visti/)
+
+### 3.3 仍待真实验证
+
+- Query 账号进入表单时,用户账号能否在 30 秒内进入同一表单;
+- `bookingForm` 当前 action、method、字段、Tourism 选项和文件要求;
+- `AVANTI` 的真实请求及副作用;
+- Calendar 日期和 TimeSlot 的真实数据来源;
+- `PRENOTA` 是否正好触发一次预约 OTP;
+- OTP 提交请求和成功页面结构;
+- 如何从预约摘要或 `/Reservation` 读取预约编号;
+- 哪一个只读页面适合 Italy `keep_alive()`。
+
+---
+
+## 4. 从大到小的复用矩阵
+
+### 4.1 第一层:进程与角色架构——直接复用
+
+| 能力 | 现有实现 | Italy 决策 | 是否新增 |
+|---|---|---|---:|
+| Query 角色 | `SentinelGCO` | 原样使用 | 否 |
+| Book 角色 | `OrderBookerGCO` | 原样使用 | 否 |
+| 插件加载 | `VSPlgFactory` | 原样使用 `ita_plugin.py` | 否 |
+| 生命周期 | `IVSPlg` | 原样实现 `create_session/query/book/keep_alive/...` | 否 |
+| 配置加载 | `GroupConfig` | 原样使用 `free_config` 与现有字段 | 否 |
+
+Italy 不新建 daemon、scheduler、queue、worker 或 service。
+
+### 4.2 第二层:账号模型——复用 BLS
+
+BLS 已经提供目标形态:
+
+```text
+Sentinel.account_source = built-in
+Booker.account_source   = order
+```
+
+Italy 当前配置本来就是:
+
+- Sentinel 从 `ie.it.sentinel` 账号池取 Query 账号;
+- OrderBooker 从订单 `user_inputs.username/password` 创建用户 Session;
+- `target_instances=1` 表示同一 routing key 只维持一个用户热实例。
+
+因此不新增 AccountProvider,不新增账号对象,也不把邮箱加进 `VSAccount`。Prenot@Mi 登录名本身就是注册邮箱,OTP 查询沿用 VFS/BLS 的 `self.config.account.username`。
+
+### 4.3 第三层:信号链路——直接复用
+
+现有链路:
+
+```text
+plugin.query()
+  → result.success=True
+  → Sentinel 写 vs:signal:{routing_key}
+  → TTL 30 秒
+  → OrderBooker 读取并反序列化 VSQueryResult
+  → task.instance.book(query_result, user_inputs)
+```
+
+Italy 原样使用:
+
+- Redis key 不变;
+- payload 不变;
+- TTL 不变;
+- trigger loop 不变;
+- 不增加 event ID;
+- 不增加 claim key;
+- 不修改 Sentinel/Booker。
+
+### 4.4 第四层:弱信号表达——复用 BLS 已有语义
+
+BLS 已存在以下结果:
+
+```python
+result.success = True
+result.availability_status = AvailabilityStatus.NoneAvailable
+result.availability = []
+```
+
+它表达的是:Query 成功到达值得 Booker 继续处理的阶段,但当前没有具体日期可以传递。
+
+Italy 的 `ENTRY_ACCEPTED` 完全复用这一表达:
+
+| 网站结果 | `success` | `availability_status` | `earliest_date` | Sentinel 行为 |
+|---|---:|---|---|---|
+| 明确无号 | `False` | `NoneAvailable` | `None` | 不发信号 |
+| 进入 `bookingForm` | `True` | `NoneAvailable` | `None` | 发 30 秒弱信号 |
+| 将来若 Query 能只读取到日期 | `True` | `Available` | 真实日期 | 发强信号 |
+
+这样无需新增 `EntryAvailable`、`SignalIntent` 或 Signal v2。
+
+Booker 的 `_is_date_of_interest()` 对 `NoneAvailable` 原本就返回 True,因此弱信号不会因为没有 `earliest_date` 而报错;用户日期偏好在 Book 读取 Calendar 后再判断。
+
+### 4.5 第五层:重复触发控制——复用现有 cooldown
+
+现有 Booker 在触发任务时设置:
+
+```text
+task.next_run = now + booking_cooldown
+```
+
+Italy 当前 `signal_ttl=30s`,但 `booking_cooldown=10s`,同一个信号理论上可能被重复消费。首版不新造原子 claim,只使用现有配置能力:
+
+```text
+signal_ttl       = 30s
+booking_cooldown = 45s
+target_instances = 1
+query_wait.random_min = 60s
+```
+
+机械约束:
+
+```text
+booking_cooldown > signal_ttl
+AND query_wait.random_min > booking_cooldown
+AND target_instances == 1
+AND 同一 Italy group 同时只有一个有效 OrderBooker 部署
+```
+
+在这个约束下,同一个 30 秒信号对当前 Italy 任务最多触发一次。若未来确实需要多节点或多 Booker,再用真实并发需求推动框架级 claim 设计,而不是现在预设。
+
+### 4.6 第六层:Book 内重新查询——复用 VFS
+
+VFS 的核心纪律是:Query 的日期只是起点;Book 在自己的 Session 中重新加载配置、查询 Calendar、查询 TimeSlot,最后提交当下仍存在的 slot。
+
+Italy 直接复用这条顺序:
+
+```text
+收到弱信号
+  → 用户 Session 中重新 GET service 1321
+  → 重新读取 bookingForm
+  → 提交 AVANTI
+  → 重新读取 Calendar
+  → 重新读取当日 TimeSlot
+  → 应用用户日期偏好
+  → 使用当前 slot 继续 PRENOTA
+```
+
+Italy 不读取 Query 账号的 Cookie、页面对象或临时参数,也不依赖 Query 的日期。
+
+### 4.7 第七层:OTP——直接复用 VFS/BLS 基建
+
+VFS/BLS 都使用:
+
+```python
+VSCloudApi.Instance().fetch_mail_content(...)
+```
+
+Italy 也使用该 API,并复用这些行为:
+
+- 以发送前 UTC 时间作为 `sent_at`;
+- 使用注册邮箱 `self.config.account.username`;
+- 按 sender、recipient、subject/body keyword 过滤;
+- 在有限窗口内等待;
+- 正则提取验证码;
+- 没有验证码时抛 `NotFoundError/BizLogicError`。
+
+Italy 只需真实验证自己的 sender、subject、验证码位数和有效期。不新增 `OtpProvider`、邮箱服务或消息队列。
+
+安全修正仍属于 Italy 必需实现:不打印 OTP,不把邮件正文写入日志。
+
+### 4.8 第八层:结果——复用 `VSBookResult`
+
+继续填充现有字段:
+
+```text
+success
+account
+urn             ← Prenot@Mi 预约编号
+book_date
+book_time
+label
+```
+
+不新增新的通用结果类。Italy 成功条件为:预约成功摘要或 `/Reservation` 中能读取到预约编号、日期和时间;不能只看 HTTP 200。
+
+---
+
+## 5. 明确不复用的内容
+
+最大化复用不等于复制网站私有细节:
+
+| 内容 | 为什么不能复用 | Italy 如何处理 |
+|---|---|---|
+| URL/endpoint | 三个网站不同 | 以 Prenot@Mi Network 证据实现 |
+| JWT/Turnstile/加密算法 | Prenot@Mi 使用 IAM 浏览器 Session | 保留当前 Italy 登录方式 |
+| VFS applicant/URN payload | Prenot@Mi 表单模型不同 | 解析真实 `bookingForm` |
+| BLS hidden fields/query params | BLS 页面私有 | Italy Book 在用户 Session 中实时读取 |
+| 服务 ID、字段 ID、Tourism option | 领馆和服务可变 | 真实 Dublin 1321 Gate 验证 |
+| OTP sender/subject | 每个站点不同 | 只复用邮件读取 API |
+| 成功响应字段 | 每个站点不同 | 解析 Prenot@Mi 摘要/Reservation |
+
+原则:**复用控制结构、基础设施和类型;网站协议只认真实证据。**
+
+---
+
+## 6. 最终目标数据流
+
+```text
+SentinelGCO(原样复用)
+  built-in Query 账号池,target_instances=1
+        │ ItaPlugin.query()
+        ▼
+GET /Services/Booking/1321
+        │
+        ├─ 302 + WNotAvailable
+        │    success=False,不写信号
+        │
+        └─ 进入 #bookingForm
+             success=True + NoneAvailable
+                       │
+                       ▼
+vs:signal:slot.dub.it.tourist,TTL=30s(原样复用)
+                       │
+                       ▼
+OrderBookerGCO(原样复用)
+  order 用户账号,热 Session,target=1,cooldown=45s
+                       │ ItaPlugin.book()
+                       ▼
+用户账号重查 → Form → AVANTI → Calendar → TimeSlot
+                       │
+              PRENOTA → OTP → OK
+                       │
+             摘要/Reservation → VSBookResult
+```
+
+---
+
+## 7. Italy Query 的最小实现
+
+### 7.1 保留当前已验证逻辑
+
+1. 每轮先加载 `/Services`,清除旧弹窗状态;
+2. 按精确 path `/Services/Booking/{service_id}` 找入口;
+3. 每轮最多导航一次;
+4. 回到 `/Services` 且 marker/已知 notice 非空,返回无号;
+5. 未知弹窗、未知 path、登录失效继续 fail-closed。
+
+### 7.2 唯一功能增量
+
+当前代码在出现 `#bookingForm` 时抛安全异常。Gate 通过后只改成:
+
+```python
+result.success = True
+result.availability_status = AvailabilityStatus.NoneAvailable
+result.earliest_date = None
+result.availability = []
+return result
+```
+
+Query 到此结束,仍然禁止填表、AVANTI、Calendar、日期/时间、PRENOTA 和 OTP。
+
+### 7.3 Query 账号池
+
+直接使用现有 Sentinel pool:
+
+- `target_instances=1`;
+- 使用现有全局 query gap 和 `query_wait`;
+- 429/挑战时使用现有账号锁定和 backoff;
+- Query 账号必须属于 Dublin 且能看到 1321;
+- 增加账号只用于轮换,不增加单位时间 Query 总数。
+
+首版不做 release-time 预测。判断“什么时候可能有号”的方式,是观察门禁从无号回退变成允许进入表单。
+
+---
+
+## 8. Italy Book 的最小实现
+
+Book 保持和 VFS/BLS 一样:一个 `book()` 主流程 + 若干站点 helper,仍位于 `plugins/ita_plugin.py`。
+
+### 8.1 主流程
+
+```text
+1. 检查用户 Session
+2. 用户账号重新进入 /Services/Booking/1321
+3. 若已无号:返回 VSBookResult(success=False)
+4. 读取当前 bookingForm、hidden fields 和动态字段
+5. 用 user_inputs 填写真实必填项并校验
+6. 接受 privacy,单次提交 AVANTI
+7. 读取当前 Calendar 日期
+8. 应用 expected_start_date / expected_end_date
+9. 查询候选日当前 TimeSlot
+10. 选择当前仍可用 slot
+11. 点击/提交 PRENOTA 一次
+12. 使用 VSCloudApi.fetch_mail_content() 读取 OTP
+13. 输入 OTP 并点击 OK 一次
+14. 解析成功摘要或 /Reservation
+15. 返回现有 VSBookResult
+```
+
+### 8.2 Helper 设计
+
+沿用 VFS/BLS 的方法拆分风格,在同一类中新增或重写:
+
+```python
+_enter_target_service()
+_extract_booking_form()
+_fill_booking_form(user_inputs)
+_submit_avanti_once()
+_query_calendar_dates()
+_query_time_slots(date)
+_select_slot(user_inputs)
+_submit_prenota_once(slot)
+_read_otp_email(sent_at)
+_submit_otp_once(otp)
+_extract_booking_result()
+```
+
+不引入工作流引擎。`book()` 只维护一个本地 `stage` 字符串用于脱敏诊断。
+
+### 8.3 表单处理
+
+复用 VFS/BLS 的实时读取原则:
+
+- hidden token 从当前用户页面读取;
+- fields/options 从当前表单读取;
+- `user_inputs` 只映射到已验证字段;
+- 新必填字段出现时停止,不猜默认值;
+- 文件通过真实 file input 或已验证请求提交;
+- 删除当前 Italy 代码中猜测的固定字段 ID、Reason 值和文件字段名。
+
+### 8.4 Calendar 与日期偏好
+
+复用 VFS Book 模式:
+
+- 弱信号没有日期,从当前 Calendar 读取;
+- 按用户日期范围过滤;
+- 对候选日期重新查询 TimeSlot;
+- 一个日期没有时间就继续下一个;
+- 最终使用 Book Session 刚取得的 slot ID。
+
+### 8.5 OTP
+
+复用 VFS/BLS:PRENOTA 前记录 UTC 时间;PRENOTA 一次;用 Cloud API 查 sent_at 之后的匹配邮件;OTP 一次提交;全程不输出 OTP。
+
+首个真实 Canary 可以先由用户手工输入 OTP;自动读取只在 Italy sender/subject/格式验证后打开。
+
+### 8.6 成功与重试
+
+成功必须取得预约编号、日期和时间。HTTP 200、收到 OTP、看到 Calendar 或发出 PRENOTA 都不算成功。
+
+| 操作 | 自动重试 |
+|---|---:|
+| Session/Services 只读 GET | 最多再试 1 次 |
+| Calendar/TimeSlot 只读查询 | 最多再试 1 次 |
+| 表单填写但未提交 | 可重建 1 次 |
+| AVANTI | 不盲重试 |
+| PRENOTA/发送 OTP | 不重试 |
+| OTP 提交 | 不重试 |
+
+写操作结果不明时检查当前页面和 `/Reservation`;仍不明就返回失败并人工处理。首版不新增 Redis 状态机。
+
+---
+
+## 9. Session 与 keep_alive
+
+`create_session()` 继续使用已真实验证的 Italy 登录,不复制 VFS JWT/BLS 登录。
+
+`keep_alive()` 复用 Booker 的现有定时调用,只寻找一个 Prenot@Mi 只读实现。候选依次为 `/UserArea`、`/Services`、已观察到的轻量认证请求。
+
+通过标准:连续覆盖两个 `session_max_life` 周期,Session 有效,Network 无预约业务写请求,429/challenge=0。
+
+---
+
+## 10. 完整假设验证方案
+
+### 10.1 P0:不通过就不实现对应步骤
+
+| ID | 假设 | 验证动作 | 机械通过标准 | 停止条件 |
+|---|---|---|---|---|
+| P0-01 | Query pool 账号可用于 Dublin 1321 | 每个候选账号只读登录 Services | 每个启用账号均显示 Dublin 与 `/Services/Booking/1321` | 不匹配即移出池 |
+| P0-02 | Query 弱信号对用户账号有意义 | Query A 进入 form 后,用户 B 30 秒内重查一次 | 至少 3 个独立机会中 3/3 用户账号也进入 form | 429/挑战停止当轮 |
+| P0-03 | Query 没有预约副作用 | 探测前后对比预约列表和 Network | 预约业务 POST=0,预约/Waiting List 无变化 | 有变化即禁用 Query |
+| P0-04 | `bookingForm` 可安全识别 | EntryAccepted 时只读采集 metadata | path、form、service ref 同时匹配;submit/OTP=0 | 不一致 fail-closed |
+| P0-05 | 表单字段完整可映射 | 采集 action/method/names/types/required/options | 所有必填字段有明确来源 | 未知必填禁止 AVANTI |
+| P0-06 | AVANTI 成功进入 Calendar | 单用户、单次授权提交 | 观察真实请求并进入 Calendar;调用次数=1 | 结果不明不重发 |
+| P0-07 | Calendar/TimeSlot 可读取 | AVANTI 后只读 Network/DOM | 取得 date、time、slot ref,可按用户范围过滤 | 未知写请求停止 |
+| P0-08 | PRENOTA 是 OTP 边界 | 选真实 slot 后单次点击 | PRENOTA=1、OTP 邮件=1、请求语义明确 | 不重复发送 |
+| P0-09 | OTP 后能确认真实预约 | 一次明确授权的 Canary | OTP submit=1,摘要/Reservation 有同一编号、日期、时间 | 不明时禁止二次提交 |
+| P0-10 | cooldown 防同信号重复 Book | 伪信号保持 30 秒,并按当前最短 60 秒 Query 间隔模拟 | `target=1,cooldown=45,min_query=60` 时同一信号 `book()` 总数=1 | 调用>1才重评 claim |
+| P0-11 | Cloud API 能读取 Italy OTP | 授权邮箱沙箱/首次 Canary | 只取 sent_at 后正确邮件,旧码不匹配,日志无 OTP | 错取或泄漏即禁用 |
+| P0-12 | Italy keep_alive 只读 | 运行两个 Session 周期 | 写请求=0,Session 有效,429/challenge=0 | 有副作用即废弃 |
+
+### 10.2 P1:上线前关闭
+
+| ID | 假设 | 机械验证 |
+|---|---|---|
+| P1-01 | ITA/ENG 不改变控制逻辑 | 两种 locale fixture 的 path/form 分类一致 |
+| P1-02 | 弱信号无日期时不提前过滤 | `_is_date_of_interest()` 返回 True,日期在 Book 内判断 |
+| P1-03 | 新必填字段安全停止 | mutation fixture 下 AVANTI=0 |
+| P1-04 | 文件错误在提交前发现 | 错误 fixture 下网络写请求=0 |
+| P1-05 | 取消订单阻止 Book | 取消状态下 `book()`=0 |
+| P1-06 | 无号回归不退化 | 输出 `NoAvailable`、cleanup OK、exit 0 |
+| P1-07 | 账号池不放大频率 | 增加账号后单位时间 Query 总数不增加 |
+| P1-08 | 未知页面不伪装 | 未知 fixture 均异常且 signal=0 |
+
+---
+
+## 11. 文件级修改方案
+
+首版只允许修改:
+
+| 文件 | 修改内容 |
+|---|---|
+| `plugins/ita_plugin.py` | 弱信号、Book、keep_alive 与 Italy helper |
+| `config/config_booker.json` | Italy `booking_cooldown: 45`,保持 target=1 |
+| `config/config_sentinel.json` | 原则上不改,保留 pool/TTL/query_wait |
+| `test/test_ita_plugin.py` | Query/Book/OTP fixture |
+| `test/test_debug_ita_query.py` | 单次 Query 安全合同 |
+| `tools/debug_ita_query.py` | 弱信号只报告,不 Book |
+| `tools/debug_ita_book.py` | 新增按 Gate 停止的单次 Book 调试器 |
+
+首版禁止修改 `sentinel.py`、`booker.py`、`standalone.py`、`vs_types.py`、`vs_plg.py`、`utils/safe_redis_cli.py` 和 VFS/BLS 插件。
+
+如果研发发现必须修改这些文件,先停止,提交“现有能力无法复用”的复现测试,再申请扩大范围。
+
+---
+
+## 12. 实现顺序
+
+### Change Set 1:Query 弱信号与 cooldown
+
+- `bookingForm` 返回 BLS 式弱信号;
+- Italy cooldown 改为 45 秒;
+- 离线证明 30 秒信号只调用一次 Book;
+- 调试 Query 只报告,不执行 Book。
+
+完成标准:
+
+```text
+Italy focused tests exit 0
+existing regression tests exit 0
+NoAvailable fixture: signal=0
+EntryAccepted fixture: signal=1
+30s retained signal: book_call_count=1
+debug query: book_call_count=0
+```
+
+### Change Set 2:用户 Session 重查与表单解析
+
+用户 Session 重进 1321,动态读取表单,默认停在 AVANTI 前;未知字段 fail-closed。
+
+### Change Set 3:AVANTI、Calendar、TimeSlot
+
+P0-05/06/07 通过后实现;默认停在 PRENOTA 前。
+
+### Change Set 4:PRENOTA 与 OTP
+
+P0-08/11 通过后实现;默认停在 OTP submit 前。
+
+### Change Set 5:最终预约
+
+用户明确授权后,OTP submit 一次,解析摘要/Reservation,返回 `VSBookResult`。
+
+---
+
+## 13. 测试矩阵
+
+| 场景 | 期望结果 | 写调用约束 |
+|---|---|---:|
+| 302 + `WNotAvailable` | `success=False` | 0 |
+| 已知无号弹窗 | `success=False` | 0 |
+| `bookingForm` | `success=True + NoneAvailable` | 0 |
+| 未知弹窗/path | 明确异常 | 0 |
+| 同一信号保留 30 秒 | Book 触发一次 | `book=1` |
+| 用户重查已无号 | Book 失败 | AVANTI/OTP=0 |
+| 新增未知必填字段 | 结构异常 | AVANTI=0 |
+| 日期不在用户范围 | Book 失败 | PRENOTA/OTP=0 |
+| Calendar 有日期无 TimeSlot | Book 失败 | PRENOTA/OTP=0 |
+| PRENOTA 后邮件延迟 | 等待至 timeout | PRENOTA=1 |
+| 读到旧 OTP | 忽略 | OTP submit=0 |
+| OTP 成功响应但无摘要 | 检查 Reservation | OTP submit=1 |
+| OTP 结果不明且无记录 | 人工处理 | OTP submit=1 |
+
+敏感信息扫描覆盖日志、异常和调试输出:密码、Cookie、Authorization、CSRF、OAuth 动态值、OTP、邮件正文和个人资料命中必须为 0。
+
+---
+
+## 14. 真实网站 Gate
+
+### Gate 0:批准复用优先设计
+
+接受现有 Sentinel/BLS/OrderBooker 信号语义;接受首版单 Booker + cooldown;接受 Italy 单文件结构;后续每个副作用单独授权。
+
+### Gate 1:离线 Query 弱信号
+
+Change Set 1 全部通过,不访问网站。
+
+### Gate 2:真实 Query Shadow
+
+Booker 禁用;无号分支稳定;首次 EntryAccepted 只输出弱信号与脱敏 metadata;表单提交=0、OTP=0。
+
+### Gate 3:跨账号与表单
+
+完成 P0-02/03/04/05;用户账号只进入表单,不提交。
+
+### Gate 4:AVANTI + Calendar
+
+逐次授权,停在 PRENOTA 前,完成 P0-06/07。
+
+### Gate 5:PRENOTA + OTP
+
+授权发送一次 OTP,停在 OTP submit 前,完成 P0-08/11。
+
+### Gate 6:单用户真实预约
+
+用户明确授权;OTP submit=1;摘要或 Reservation 取得编号、日期、时间;Cleanup OK;日志敏感值=0。
+
+### Gate 7:受控启用
+
+```text
+Sentinel target_instances = 1
+Booker target_instances   = 1
+booking_cooldown          = 45
+signal_ttl                = 30
+query_wait.random_min     = 60
+有效 Italy OrderBooker 部署数 = 1
+kill switch 已验证
+```
+
+---
+
+## 15. 可行性与确信度
+
+| 能力 | 可行性 | 确信度 |
+|---|---|---|
+| 登录 | 已实现并真实验证 | 高 |
+| 无号识别 | 已实现并真实验证 | 高 |
+| EntryAccepted 弱信号 | 直接复用 BLS 表达 | 中;缺真实有号样本 |
+| Query/用户账号接力 | 直接复用 BLS 架构 | 中;缺同窗验证 |
+| 用户热 Session | OrderBooker 已提供 | 中高 |
+| Calendar/TimeSlot | 复用 VFS Book 模式 | 低;缺 Italy 协议 |
+| OTP | 复用 VFS/BLS 基建 | 中;缺 Italy 邮件证据 |
+| 最终预约 | 流程清晰 | 低;缺真实 Canary |
+
+当前可以高信心进入 Change Set 1 的离线实现;不能编写 Calendar、OTP 和最终提交,因为对应 Italy 网站证据尚不存在。
+
+---
+
+## 16. 初见审查
+
+### 反驳 1:“现在真的做到最大化复用了吗?”
+
+回应:首版不修改 Sentinel、Booker、Redis、通用类型、接口或插件工厂;直接使用 BLS 的账号拆分与弱信号语义、VFS 的 Book 内重查、两者共有的 OTP Cloud API。运行代码只改 Italy 插件和 Italy cooldown 配置。不能复用的只剩 Prenot@Mi 自己的网页协议。
+
+### 反驳 2:“`success=True + NoneAvailable` 不直观,为什么仍采用?”
+
+回应:这是 BLS 已有且能被当前 Sentinel/Booker消费的表达:`success` 控制触发,`NoneAvailable` 表示没有具体日期。Italy 的 EntryAccepted 恰好也是“值得重查但没有日期”。为了复用现有协议,首版接受这个约定,用测试固定语义,不在 Italy 修复中重构通用模型。
+
+### 反驳 3:“不用原子 claim,会不会重复预约?”
+
+回应:首版部署约束是单 Italy OrderBooker、`target_instances=1`,并让 `booking_cooldown=45s` 大于 `signal_ttl=30s`。离线测试必须证明同一信号 `book_call_count=1`。只有未来需要多节点并发且该约束失效时,才讨论原子 claim。
+
+### 反驳 4:“为什么 Book 仍要重查?”
+
+回应:Sentinel 与 OrderBooker 本来就是不同插件实例、账号和 Session。VFS 已给出正确做法:Book 在自己的 Session 中重新查询当前 Calendar/TimeSlot。
+
+### 反驳 5:“为什么不复制 VFS/BLS 的 endpoint 和表单代码?”
+
+回应:复用的是框架和控制结构,不是第三方网站私有协议。复制别的网站 payload 不是复用,而是制造不可验证的硬编码。
+
+---
+
+## 17. 实施状态与下一 Gate(2026-08-27)
+
+### 17.1 已完成:Change Set 1
+
+1. `bookingForm` 返回 BLS 式弱信号:`success=True + NoneAvailable`;
+2. Italy `booking_cooldown` 从 10 秒调整为 45 秒;
+3. 离线证明 30 秒保留信号只触发一次现有 `OrderBookerGCO`;
+4. Query 调试器只调用一次 `query()`,调用 `book()` 次数为 0;
+5. 未修改 Sentinel、Booker、Redis、通用类型或 VFS/BLS。
+
+### 17.2 已完成:Change Set 2 的离线安全部分
+
+1. 删除 Italy 旧 `book()` 中未经网站证据支持的 OTP、硬编码表单、文件上传和最终确认实现;
+2. `book()` 在用户自己的 Session 中复用 `query()`,重新进入 1321;
+3. 用户重查无号时返回 `VSBookResult(success=False)`;
+4. 用户重查进入 `bookingForm` 时,只读取不含字段值的结构 metadata,并停在 AVANTI 前;
+5. 新增 `tools/debug_ita_book.py`:单次 Book 重查,`book_attempt=1`,`submit_attempts=0`;`--arm` 可先登录停在 `/UserArea`,收到 Query 弱信号后再按 Enter;等待期间按 `Ctrl+C` 会以 `book_attempts=0` 清理退出,不打印 traceback;
+6. Query 和 Book 均允许从上一次 `bookingForm` 状态重新加载 `/Services`,避免下一轮卡死。
+
+验证记录:
+
+```text
+.venv/bin/python -m unittest \
+  test.test_add_ita_query_account \
+  test.test_ita_plugin \
+  test.test_debug_ita_query \
+  test.test_debug_ita_book \
+  test.test_debug_ita_session
+
+Ran 56 tests
+OK
+ITALY_ACCOUNT_TOOL_TEST_EXIT=0
+external_request=not-performed
+```
+
+静态验证:8 个相关 Python 文件编译 exit 0;Italy 配置合同 exit 0;
+旧危险路径(OTP、BookingCalendar、InsertNewBooking、FormData 等)在
+`plugins/ita_plugin.py` 中命中 0;真实账号标记命中 0。
+
+仓库级 `test.test_cloud_config` 仍因 HEAD 基线中导入已不存在的
+`fetch_remote_config` 而失败;本次未越界修改该无关模块。带顶层外部 Redis
+写入的历史脚本也未通过 `unittest discover` 导入。
+
+### 17.2.1 真实单账号 Book 重查证据(2026-08-27)
+
+用户在 `--arm` 模式完成登录后只释放了一次 Book 重查,观察到:
+
+```text
+ITA_BOOK_RECHECK_START service_id=1321 book_attempt=1
+Target Italy service showed the verified no-availability notice.
+ITA_BOOK_RECHECK_NONE_AVAILABLE service_id=1321
+ITA_BOOK_CLEANUP_OK
+```
+
+结论:用户 Session 中的 1321 单次重查、已知无号分类、失败结果和清理分支
+均已真实验证。【高】本次没有进入 `bookingForm`,没有验证表单结构;也没有
+DevTools Network 记录,因此不把代码级零提交约束扩写成网络级证据。
+
+当前只有一个账号,所以 P0-02 的“Query 账号 A → 用户账号 B”跨账号同窗验证
+仍未完成。【低/待第二个已授权账号】同账号并发登录可能使旧 Session 失效,
+在取得网站证据前不采用该测试方式。
+
+### 17.2.2 Query 账号池接入准备(2026-08-27)
+
+已确认 Sentinel 从 `ie.it.sentinel` 调用现有 `/api/account/next`,现有账号写入口
+为 `/api/account/add`。VFS 注册脚本中的旧上传函数会输出账号标识并带 VFS
+专用 metadata,因此没有直接用于 Italy。
+
+新增 `tools/add_ita_query_account.py`,约束如下:
+
+- pool 和 service 固定为 `ie.it.sentinel` / `1321`;
+- 默认只做本地 preflight,不读取凭据、不发请求;
+- `--apply` 才允许一次 POST,自动重试次数为 0;
+- username、password、API Token 不接受命令行参数,也不写日志;
+- 传输结果不确定时 exit 5,并要求先在管理端核实再决定是否重试。
+
+```text
+ITA_ACCOUNT_UPLOAD_PREFLIGHT_OK pool=ie.it.sentinel service_id=1321 request_sent=false
+ITA_ACCOUNT_TOOL_DRY_RUN_EXIT=0
+```
+
+账号上传工具与 Italy 回归共 56 项测试通过;工具编译、空白和真实账号标记
+检查均 exit 0。真实 `/api/account/add` 尚未调用,等待单独授权。
+
+### 17.2.3 本地 Query 调试账号(2026-08-27)
+
+本地调试阶段优先读取 `config/ita_query_account.local.json`,供
+`tools/debug_ita_query.py`、`tools/debug_ita_monitor.py` 以及登录调试器显式的
+`--local-query-account` 模式使用:
+
+- 文件存在且有效:使用其中的 username/password;
+- 文件不存在:保留原环境变量或隐藏输入方式;
+- 文件存在但无效:安全停止,不回退另一个账号;
+- `tools/debug_ita_book.py` 不读取该文件,仍使用用户账号;
+- 不修改 Sentinel、`config_sentinel.json` 或生产账号池;
+- 不调用 `/api/account/add`。
+
+真实验证记录(用户执行,2026-08-27):
+
+```text
+ITA_SERVICE_ID=1321 python tools/debug_ita_query.py
+Successfully reached authenticated /UserArea.
+ITA_QUERY_PROBE_START service_id=1321 query_attempt=1
+ITA_QUERY_NONE_AVAILABLE service_id=1321 status=NoAvailable
+ITA_QUERY_CLEANUP_OK
+EXIT_CODE=0
+```
+
+由此已验证:【高】本地文件中的账号可被 Query 调试器读取、凭据有效、登录能
+到 `/UserArea`、Dublin `service_id=1321` 可查询、已知无号分支分类正确且
+cleanup 成功。该次没有 Network 录制,因此不把“没有预约业务写请求”列为
+本次新增证据;无号探测的网络副作用边界仍沿用此前人工 DevTools 记录。
+
+仍未验证:真实有号时是否进入 `bookingForm`、弱信号能否被另一个用户账号在
+30 秒内复现,以及 AVANTI 之后的 Calendar/TimeSlot。
+
+### 17.2.4 有界本地 Query 监控器(2026-08-27)
+
+新增 `tools/debug_ita_monitor.py`,只在本地 Discovery 阶段使用:
+
+- 默认执行为零网络 preflight,必须显式传 `--run` 才访问网站;
+- 复用 `debug_ita_query.py` 的本地账号、登录配置、Query、弱信号分类、表单
+  结构脱敏和失败诊断;
+- 一次进程只创建一个登录 Session;
+- 默认最多探测 10 次,间隔在 60–300 秒之间随机;最小值禁止低于 60 秒;
+- 每次无号才进入下一次等待;真实弱信号、未知非空结果或任何异常均立即停止;
+- 弱信号输出终端响铃及 `action=start-user-book-recheck-now`,不自动调用 Book;
+- Ctrl+C 返回 130 且执行 cleanup,不输出 traceback;
+- 不依赖 Redis,不调用 Book、AVANTI、Calendar、OTP 或最终确认。
+
+离线验证:监控器及 Italy 回归共 74 项测试通过,exit 0。真实循环尚未启动;
+没有因为新增监控器而产生网站请求。
+
+### 17.2.5 Radware 证据与本地 Query 持久化 Profile(2026-08-27)
+
+真实监控第一次在 IAM 授权阶段异常改道并以 exit 1 安全停止;随后独立的
+登录调试成功到达 `/UserArea`,但该调试 Session cleanup 后删除了全部临时
+浏览器资料。紧接着启动的第二次监控进入
+`validate.perfdrive.com/<dynamic-challenge>`,从未出现登录表单,也从未进入
+Query,最终 exit 1 且 cleanup 成功。按“同类错误最多两次”停止真实重试。
+
+代码审查确认:每个 Italy 插件实例原先都使用带随机 instance id 的
+`data/temp_browser_data/.../user_data`,cleanup 时完整删除。因此成功登录所
+获得的 Cookie、Radware 客户端状态和浏览器上下文不能被下一个本地 Query
+进程复用。这不证明持久化一定能通过 Radware,但证明原调试流程会主动丢失
+刚获得的会话连续性。
+
+本阶段增加以下边界:
+
+- 本地 Query 账号使用 `data/ita_query_profiles/<account-hash>`;路径不包含账号
+  明文,根目录和账号目录在 POSIX 上强制为 `0700`;
+- 目录被 `.gitignore` 忽略,Profile 只保存在本机;
+- Query 单次调试、Monitor 和登录调试器的显式 `--local-query-account` 模式
+  复用同一 Profile;
+- Book 调试器和生产默认配置不传 Profile,仍使用并删除临时目录;
+- 持久化 Profile 使用非阻塞文件锁,同一账号同一时刻只允许一个插件实例;
+- `validate.perfdrive.com` 被明确分类为
+  `ItaAuthenticationChallengeError`,动态 challenge path 在日志中脱敏;
+- 挑战只报告并停止,不刷新、不自动重试、不调用验证码服务,也不改变 IP 或
+  浏览器指纹来规避网站控制。
+
+离线回归共 83 项测试通过,exit 0。
+
+真实登录-only 验证(用户授权,2026-08-27):
+
+```text
+python tools/debug_ita_session.py --local-query-account --non-interactive
+Browser profile mode=persistent id=<redacted-profile-id>
+Successfully reached authenticated /UserArea.
+ITA_SESSION_OK url=https://prenotami.esteri.it/UserArea
+ITA_SESSION_CLEANUP_OK
+EXIT_CODE=0
+```
+
+验证后调试端口无监听;Profile 为 `0700`,存在浏览器状态,独占锁可重新获取,
+并继续被 Git 忽略。该次只登录,没有执行 Query、Book、OTP 或预约表单操作。
+
+第二个独立进程复用验证(用户再次授权,2026-08-27):Profile ID 与第一次
+一致;网站仍显示 IAM 登录表单,因此 OAuth 认证本身没有跨进程免登录;凭据只
+提交一次后成功返回 `/UserArea`,`ITA_SESSION_OK`、cleanup 和 exit 0 均成立,
+没有进入 Radware challenge。结束后端口无监听、Profile 仍为 `0700`、独占锁
+已释放且 Git 状态中不可见。
+
+精确结论:跨进程 Profile 复用已验证;跨进程免登录未实现;两个持久化 Profile
+进程连续登录成功且未出现 Radware,但样本不足以宣称永久消除挑战。仍待验证:
+同一 Profile 下的一次 `service_id=1321` Query。
+
+真实有界轮询验证(用户授权,2026-08-27):
+
+```text
+ITA_SERVICE_ID=1321 python tools/debug_ita_monitor.py \
+  --run --non-interactive --min-wait 60 --max-wait 90 --max-probes 3
+ITA_MONITOR_STARTED service_id=1321 session_attempts=1 max_probes=3
+ITA_MONITOR_NONE_AVAILABLE service_id=1321 probe=1
+ITA_MONITOR_WAIT next_probe=2 seconds=84
+ITA_MONITOR_NONE_AVAILABLE service_id=1321 probe=2
+ITA_MONITOR_WAIT next_probe=3 seconds=63
+ITA_MONITOR_NONE_AVAILABLE service_id=1321 probe=3
+ITA_MONITOR_MAX_PROBES_REACHED service_id=1321 probes=3
+ITA_MONITOR_CLEANUP_OK
+EXIT_CODE=0
+```
+
+同一个持久化 Profile 和同一个已认证浏览器 Session 完成 3 次真实 Query;两个
+等待值均不低于 60 秒,三次均命中已验证的无号文案,没有出现 Radware、未知
+结果或弱信号。结束后调试端口无监听、Profile 仍为 `0700`、独占锁已释放且
+Git 不可见。由此本地有界轮询能力已验证;生产账号池、长期保活和弱信号后的
+用户 Book 抢占仍属于后续 Gate。
+
+### 17.2.6 本地弱信号到用户 Book 的一次性交接(2026-08-27)
+
+生产链路已经由 Sentinel、Redis 和 OrderBooker 完成,因此本阶段没有创建第二套
+生产队列,也没有修改 `sentinel.py`、`booker.py`、`vs_types.py` 或 Redis
+payload。新增的 `tools/ita_local_handoff.py` 只是 Discovery 阶段的本地适配器:
+
+```text
+Query Monitor(团队授权账号 + Query Profile)
+  → 确认进入 bookingForm
+  → 原子写入 30 秒 metadata-only 本地信号
+  → Book Debugger(用户账号 + 独立临时 Profile)原子领取一次
+  → ItaPlugin.book() 在用户 Session 中重新查询 1321
+  → 无号:明确结束
+  → bookingForm:输出脱敏结构并停在 AVANTI 前
+```
+
+本地信号只包含固定 schema、`service_id`、`routing_key`、`booking-form`
+证据和签发时间;不包含账号、密码、Cookie、Token、表单值、日期或时间。目录权限
+为 `0700`、信号文件为 `0600`,路径被 Git 忽略。发布使用临时文件加原子替换,
+领取使用同目录原子重命名;两个消费者并发时只有一个能取得信号。信号超过 30 秒、
+目标不匹配、格式未知或权限异常时 fail-closed,不能触发 Book。
+
+这里保证的是本地 Discovery 所需的“至多一次”,不是分布式事务意义上的“恰好
+一次”:若 Book 在原子领取后、用户重查前进程崩溃,信号会丢失,不会自动重放。
+这是安全取舍——宁可错过一次调研机会,也不在结果未知时重复触发 Book。生产仍
+由既有信号 TTL、Booker cooldown 和用户 Session 重查合同负责,不依赖这个文件。
+
+`debug_ita_monitor.py` 只有显式指定 `--publish-local-signal` 才发布;无号、未知
+结果或异常均不发布。`debug_ita_book.py --wait-for-local-signal` 会先登录用户账号,
+最多等待 900 秒,并在领取后只调用一次 `book()`。自动模式在任何网站请求之前
+校验本地 Query 账号与 Book 用户账号不同;Book 不复用 Query Profile、Cookie
+或页面状态。
+
+两个终端的未来真实验证命令如下。终端 A 必须输入用户自己的 Book 账号,终端 B
+读取 `config/ita_query_account.local.json` 中不同的团队 Query 账号:
+
+```bash
+# Terminal A:先让用户 Book Session 就绪;账号和密码使用隐藏输入,不写入命令行
+python tools/debug_ita_book.py \
+  --wait-for-local-signal \
+  --signal-timeout 900
+
+# Terminal B:再启动有界 Query;只有 bookingForm 弱信号才发布本地交接
+ITA_SERVICE_ID=1321 python tools/debug_ita_monitor.py \
+  --run \
+  --non-interactive \
+  --publish-local-signal \
+  --min-wait 60 \
+  --max-wait 90 \
+  --max-probes 3
+```
+
+离线端到端测试已注入一个真实格式的弱信号,并机械证明:Query 与 Book 是两个
+插件实例;Query 调用 `query()` 一次、`book()` 零次;Book 原子领取一次并调用
+`book()` 一次;第二次领取为空;最终标签为
+`stage=before-avanti submit_attempts=0`。过期信号、目标不匹配和双消费者竞争也有
+独立测试。
+
+验证记录:
+
+```text
+.venv/bin/python -m unittest \
+  test.test_ita_local_handoff \
+  test.test_debug_ita_monitor \
+  test.test_add_ita_query_account \
+  test.test_ita_plugin \
+  test.test_debug_ita_query \
+  test.test_debug_ita_book \
+  test.test_debug_ita_session
+
+Ran 93 tests
+OK
+EXIT_CODE=0
+
+相关 Python 文件 compile: ok,EXIT_CODE=0
+Monitor 本地交接 preflight: external_request=false,EXIT_CODE=0
+Book CLI 参数检查:EXIT_CODE=0
+git diff --check:EXIT_CODE=0
+git diff --exit-code -- sentinel.py booker.py vs_types.py:EXIT_CODE=0
+git check-ignore data/ita_local_handoff/query-weak-signal.json:EXIT_CODE=0
+```
+
+真实交接尚未执行:当前网站没有出现弱信号,且本地目前只有一个账号。不能用
+同账号并发登录冒充“团队 Query 账号 → 用户 Book 账号”的 P0-02 证据。取得第二个
+已授权且属于 Dublin 的账号,并在真实开放窗口出现后,才执行上述两个终端命令。
+
+### 17.2.7 本地 24 小时 Query 稳定性验证(2026-08-28)
+
+新增 `tools/debug_ita_soak.py`,用于在接入生产 Sentinel 之前完成一天的本地
+稳定性验证。它复用现有 Query 本地账号、持久化 Profile、`ItaPlugin.query()`
+和弱信号判断,不新增第二套生产调度器,也不连接 Redis:
+
+- 默认只做零网络 preflight,显式 `--run` 才访问网站;
+- 以持续时间而非探测次数结束,默认且最长为 86,400 秒;
+- 同一已认证 Session 内每 60–300 秒随机探测一次;
+- 只有明确的 `SessionExpiredOrInvalidError` 才允许清理并重建 Session,重建前
+  至少等待 60 秒;正常过期不再受固定总次数限制,由 86,400 秒任务时长约束;
+- 连续两次新 Session 未成功 Query 就过期,或一小时内出现超过 6 次重新认证,
+  立即熔断,避免把异常认证循环放大;
+- `/Services/Booking/1321` 首次缺失记录脱敏结构并等待下一轮,连续第二次缺失
+  时停止;Radware、未知页面和未知业务结果均立即停止;
+- 进入 `bookingForm` 时写入 `weak_signal` 状态并立即停止,不调用 Book、AVANTI、
+  Calendar、OTP、表单提交或生产本地交接;
+- `data/ita_soak/status.json` 只保存固定 metadata,目录和文件权限分别为
+  `0700`、`0600`,并被 Git 忽略。
+
+为解决此前真实 10 次 Monitor 在第 3 次偶发找不到 1321 链接的问题,Italy
+Query 对目标链接的有界等待从 3 秒扩为 15 秒,并新增专用的
+`ItaTargetServiceLinkMissingError`。诊断只包含 path、文档 ready state、表格数、
+行数、Booking 链接数和目标链接数,不采集服务文本、账号或页面字段值。
+
+离线验证记录:
+
+```text
+.venv/bin/python -m unittest \
+  test.test_debug_ita_soak \
+  test.test_ita_local_handoff \
+  test.test_debug_ita_monitor \
+  test.test_add_ita_query_account \
+  test.test_ita_plugin \
+  test.test_debug_ita_query \
+  test.test_debug_ita_book \
+  test.test_debug_ita_session
+
+Ran 103 tests
+OK
+EXIT_CODE=0
+```
+
+其中加速的一天模拟以 300 秒固定间隔完成 288 次 Query,证明持续时间边界、
+一次缺链后恢复、连续两次缺链停止、显式 Session 过期后安全重建、弱信号立即
+停止、状态文件权限和零网络 preflight。相关文件 compile、`git diff --check`、
+生产 `sentinel.py/booker.py/vs_types.py` 零改动检查均为 exit 0。
+
+真实 15 分钟短测记录:
+
+```text
+ITA_SERVICE_ID=1321 .venv/bin/python tools/debug_ita_soak.py \
+  --run --non-interactive \
+  --duration-seconds 900 \
+  --min-wait 60 --max-wait 90 \
+  --max-session-attempts 2 --restart-wait 60
+
+ITA_SOAK_COMPLETED duration_seconds=900 probes=11 \
+  none_available=11 transient_errors=0 session_attempts=1
+ITA_SOAK_SESSION_CLEANUP_OK session=1 reason=soak-finished
+ITA_SOAK_CLEANUP_OK
+EXIT_CODE=0
+```
+
+同一真实登录 Session 完成 11 次探测,全部命中已验证的无号分支;未出现缺链、
+Radware、Session 过期、未知结果或弱信号。结束后状态为 `completed`,调试端口
+无监听,Profile 锁可重新获取。由此已验证“可安全启动一天本地稳定性测试”;
+尚未验证真实开放窗口和 `bookingForm` 弱信号。
+
+第一次启动 86,400 秒任务时,probe 1 成功,随机等待 205 秒后 probe 2 在读取
+页面前发生 DrissionPage `PageDisconnectedError`。状态正确写为 `failed`,
+cleanup 成功,系统电源日志没有睡眠记录,也没有本机 Chrome crash report;因此
+只能确认“浏览器/CDP 连接已经断开”,不能臆测网站拒绝或具体崩溃原因。
+
+基于这条真实证据,轮询器只新增一个窄恢复分支:首次
+`PageDisconnectedError` 清理旧实例、等待至少 60 秒并复用同一私密 Profile
+创建新 Session;若没有成功 Query 就连续第二次断连,则以
+`consecutive-browser-disconnects` 停止,不创建第三个 Session。其他未知异常仍
+立即停止。新增两项测试后 Italy 回归为 105 项,全部通过,exit 0。
+
+后续真实长测在 5,704 秒内完成 36 次探测、32 次已知无号和 3 次正常 Session
+过期重建;第 36 次发生一次 `PageDisconnectedError`,随后新 Chrome/CDP 启动
+抛出 `BrowserConnectError`,程序安全退出。这个证据同时证明两点:
+
+1. Prenot@Mi 的真实 Session 生命周期约为 20–30 分钟,固定 12 次上限不可能
+   支撑完整一天;
+2. 自动重新认证必须覆盖一次临时 Chrome/CDP 启动失败,但不能无限启动浏览器。
+
+因此本地 soak 的重认证模型调整为与 Sentinel 相同的“生命周期内持续重建”:
+
+- 默认 `max_session_attempts=0`,表示不设错误的固定总次数上限;
+- 每次明确过期后等待至少 60 秒,再使用同一授权账号和私密 Profile 登录;
+- 正常 Query 成功后,连续过期计数归零;连续第二次未成功 Query 就过期则停止;
+- 滚动一小时最多允许 6 次重新认证,第 7 次停止;
+- `BrowserConnectError` 允许等待 60 秒后重试一次,连续第二次失败停止;
+- 显式传入正数 `--max-session-attempts` 时仍可施加更严格的人工总上限。
+
+加速 24 小时测试让 Session 按 660 秒周期正常过期,实际经历至少 96 次过期与
+重新认证后仍运行到 86,400 秒并 exit 0;另有独立测试证明密集重登、连续过期、
+连续浏览器连接失败分别熔断。更新后的 Italy 回归共 110 项,全部通过,exit 0;
+生产 `sentinel.py`、`booker.py`、`vfs_plugin.py`、`bls_plugin.py` 和通用类型均未
+修改。
+
+切换到新实现后的真实验证(2026-08-28):新任务从零开始运行;前 6 次 Query
+均为已知无号。第 7 次探测明确抛出 `SessionExpiredOrInvalidError` 后,旧 Session
+cleanup 成功,等待 60 秒,自动登录到 `/UserArea` 并创建 Session 2;紧接着第
+8 次 Query 成功返回已知无号。状态快照随后显示:`state=running`、
+`session_attempts=2`、`session_expirations=1`、
+`consecutive_session_expirations=0`、`browser_connect_failures=0`。由此真实验证了
+“过期 → 清理 → 有界等待 → 重新认证 → 继续 Query”的完整闭环;24 小时终态仍
+需由正在运行的真实任务到时确认。
+
+### 17.3 历史终点与当前去向
+
+本文对应的早期 Gate 已由香港 E42 证据闭环取代。下一步不再沿用“禁止进入
+Calendar”的旧调查路径,而应转到当前规范 R3 的 D0、Q-CAL、SLOT-POS、FINAL
+和 PROD Gates。任何新的开发、测试或上线判断都必须以当前规范为准。

+ 576 - 0
docs/ita_query_book_acceptance.md

@@ -0,0 +1,576 @@
+# Italy Query → Book:复用现有框架的验收
+
+更新日期:2026-08-31。合同:`existing-framework-offline-v2`。
+
+**本轮完成的是“真实框架代码 + 模拟外部依赖”的离线协同验收,不是真实网站、真实 Redis 或上线验收。**
+
+## 1. 用户要求与这次纠偏
+
+- Query 使用团队已授权的池账号。
+- Book 使用目标申请人的订单账号。
+- 从大到小尽最大努力复用 VFS/BLS/TLS 现有实现,不再开发 Italy 专用调度、信号或接码基础设施。
+- 通用短期申根旅游签证、单人预约;香港只是现场案例,不在联调代码中硬编码地区或真实日期。
+- 不操作正式订单,不执行真实最终预约。
+
+上一版 `tools/debug_ita_query_book.py` 虽然复用了生产插件和 SDK,却自己维护了内存信号、TTL 和单次消费,又编排了一套账号与浏览器生命周期。这不符合“最大化复用”。
+
+本轮移除这些实现,包括 `LocalQuerySignal`、独立池账号适配、JSON 拼装/消费、手工 Book 派发和独立 session 管理。**旧 `--run` 参数已经失效,不能再照上一版命令执行。** 文件保留为薄薄的离线测试入口,不是另一套协调器。
+
+## 2. 实际使用哪些现成代码
+
+| 环节 | 本轮实际执行的方法 | 未再实现的能力 |
+|---|---|---|
+| 池账号领取、Query 配置及 Task 创建 | `SentinelGCO._spawn_sentinel_worker()` | 账号选择、冷却参数、配置绑定、失败清理 |
+| 实际查询、快照生成和发布 | `SentinelGCO._monitor_loop()` → `ItaPlugin.query()` → `redis_client.setex()` | 查询调度、JSON envelope、TTL 发布 |
+| 订单领取、申请人凭据绑定 | `OrderBookerGCO._spawn_worker()` | 订单队列名、账号映射、任务身份和可接受路由 |
+| 读取快照并触发订单 | `BaseBookerGCO._booking_trigger_loop()` | JSON 解码、路由筛选、订单日期筛选、冷却、线程创建和 join |
+| 实际执行预约逻辑 | `OrderBookerGCO._execute_book_job()` → `ItaPlugin.book()` | 订单有效性检查、用户输入传递、成功/失败处理 |
+| 重新查日期/时段 | 现有 `ita_workflow`、`ita_calendar_book` | 不使用 Query 的旧库存直接选中时段 |
+| 停止与清理 | 两个现有 GCO 的 `stop()` | 不新建生命周期管理器 |
+| 其他既有契约 | 原有信号保留、订单结果和 Sentinel 恢复测试 | 不复制已有测试场景的业务实现 |
+
+本地配置中 BLS/TLS 使用 `account_source=order`,VFS 使用 `built-in`;`main.get_gco_class()` 按这个配置选择共同框架。你的需求对应 BLS/TLS 的 **OrderBookerGCO**,不是把所有插件都强行改成同一种账号模式。
+
+既有自动 OTP 继续使用 `VSCloudApi.fetch_mail_content()`;邮件只通过原有筛选与确定性验证码解析,不当作指令、不送给大模型。本轮没有修改邮箱服务,也没有新增邮件组件。
+
+## 3. 哪些是真实代码,哪些是模拟
+
+**真实执行:** 上表的 GCO 构造、池/订单创建方法、两个循环、Task 数据结构、快照序列化/反序列化、订单条件判断、Book 线程、Italy 的日期扫描与库存重查、框架停止逻辑。
+
+**仅模拟外部边界:**
+
+- 账号池/订单 API 返回合成账号和合成订单;不上云领取真实资源。
+- Redis 使用已有 `FakeRetainedSignalRedis` fixture 和 Mock 命令边界;不建立真实 Redis 连接。
+- 插件工厂的创建返回既有合成浏览器 fixture;未测试动态模块加载。
+- 浏览器已经处于模拟的准备好 Calendar 状态;本轮不把实际登录、OTP、AVANTI 当成协同实测证据。
+- 浏览器清理是 Mock;测试验证的是 GCO 确实调用清理,不是 OS 上真实浏览器进程已退出。
+- 云端报告/通知/执行器使用 Mock。
+- 为有限次测试,只控制现有循环的退出事件和时钟;不复制循环内部业务代码。
+
+新增测试会阻止真实 socket 连接、HTTP 请求和子进程启动;真实框架的 Book 线程仍照常创建并 join。
+
+所以,“框架方法被验证”不等于“真实 Redis 时效、真实池冷却、真实邮箱和网站都通过了”。
+
+## 4. 保留现有规则,不另立 Italy 规则
+
+1. **信号不是全局消费一次。** 同一条有效信号可以触发多个符合路由和日期条件的订单,每个订单使用各自的账号。
+2. **同一订单不是永远只能触发一次。** 当前框架按 `booking_cooldown` 与订单状态判断;信号仍有效、冷却结束时,可能再次调用 Book。不能拿上一版单次消费语义替换它。
+3. **TTL 交给 Redis。** Sentinel 传递配置的 TTL;Booker 从 Redis 取不到数据就不触发。不另写 Italy 单调时钟或过期解码器。
+4. **新的无号查询不会主动删除此前的有效信号。** 这是现有 Sentinel 行为;旧信号保留到过期,Book 必须重新查当前库存。本轮记录并验证,不擅自修改公共策略。
+5. **查询结果不等于预订结果。** Query 可以报告有日期,Book 在申请人会话中发现该日期已经无号,再按订单条件回退寻找可用日期。
+6. 快照原本不包含 `success`,Booker 解码后它默认是 false;保持这个现成合同,不补造 true。
+7. 订单的 `expected_end_date` 先由 Booker 筛选;起止日期仍传给真实 Book 做选择。不能在测试入口丢掉订单条件。
+8. 当前公共框架没有我们上一版额外添加的“两端账号必须不同”全局校验。本轮使用两个不同合成账号验证来源和隔离,不新加公共政策。
+9. 新协同用例均保持最终提交关闭,pre-final 不更新订单成功、不通知。复用的旧 Book 集成套件还会模拟最终成功与未知结果,用于覆盖原有分支;所有网络与回执均为合成数据,不会创建真实预约。
+
+这些是复用边界,不是宣称现有公共框架具备完美的分布式幂等或无限自动恢复能力。
+
+## 5. 文件与开发范围
+
+仅修改此前本任务新增的三个文件:
+
+- `tools/debug_ita_query_book.py`:离线测试入口,原 341 行缩减为 55 行;没有自建信号、调度、账号领取或浏览器流程。
+- `test/test_debug_ita_query_book.py`:真实框架协同测试与 CLI 边界测试,复用既有 Query、Book、Redis fixtures。
+- 本文:替换旧方案及过时现场命令,保留纠偏原因和证据。
+
+未修改 Sentinel、Booker、共享类型、Italy 生产插件、VFS/BLS/TLS、共享 SDK、正式配置。工作区原有修改全部保留,没有提交或部署。
+
+设计方式:组合既有实现,并在测试中替换外部依赖;没有新增公共框架、调度模式或运行时抽象。
+
+## 6. 离线验证证据
+
+新增/替换文件中的 18 项测试覆盖:
+
+- 池账号 Query、订单账号 Book、真实 JSON 传递、用户会话重新查号。
+- 池/订单缺失、登录失败后的现有清理与退避。
+- 无号、协议错误不发布正向信号。
+- 过期信号不触发;有效信号遵循现有订单冷却。
+- 路由不匹配、日期不匹配、暂停订单。
+- 无效 JSON 进入原有删除分支。
+- 同一信号触发两个分别绑定的订单。
+- 后续无号查询保留此前尚未过期的信号。
+- 旧 `--run` 拒绝;空、跳过或失败套件不得报告通过。
+
+2026-08-31 当前代码实测:
+
+| 命令/范围 | 结果 |
+|---|---|
+| `python -B -m unittest -q test.test_debug_ita_query_book` | 18 tests,OK,exit 0 |
+| `python -B tools/debug_ita_query_book.py --offline` | 新框架用例 + 既有复用用例,共 26 tests,OK,exit 0 |
+| Italy 相关 18 个模块回归 | 546 tests,OK,exit 0 |
+
+18 个回归模块是:`test_ita_preflight`、`test_ita_otp`、`test_ita_workflow`、`test_debug_ita_book`、`test_ita_protocol`、`test_ita_plugin`、`test_ita_calendar_book`、`test_ita_calendar_book_flow`、`test_ita_calendar_query`、`test_ita_booker_integration`、`test_ita_booking_final`、`test_ita_final_attribution`、`test_ita_final_read_port`、`test_debug_ita_calendar_gate`、`test_debug_ita_production_query_gate`、`test_debug_ita_book_gate`、`test_debug_ita_query_book`、`test_ita_query_recovery`,均位于 `test` 包中。
+
+首次运行新用例时,Query fixture 的准备标记被真实 `set_config()` 清除,导致无法发布。这是测试装配问题:修正为在模拟登录/准备完成后记录标记;没有删除生产检查,也没有改 Query 算法。正向用例同时断言真实发布确实发生,避免“没有执行任何逻辑也通过”的假阳性。
+
+## 7. 你现在可以执行的命令
+
+在自己的终端:
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+PYTHONDONTWRITEBYTECODE=1 python -B tools/debug_ita_query_book.py --offline
+echo "EXIT_CODE=$?"
+```
+
+不需要填写任何账号、密码、池名或邮箱;不会打开浏览器。预期:
+
+```text
+ITA_QUERY_BOOK_TOOL=existing-framework-offline-v2
+Ran 26 tests ...
+OK
+ITA_QUERY_BOOK_FRAMEWORK_RESULT=... "passed": true, "liveAcceptance": false ...
+EXIT_CODE=0
+```
+
+不要再使用旧 `--run` 命令,也不要为了现场验收直接启动现有生产配置。
+
+## 8. 下一阶段准入条件
+
+离线框架复用验证已完成;真实协同还需要独立验收:
+
+1. 确认隔离测试环境:测试 API/订单和 Redis,不连接正式订单。当前尚未确认环境是否存在。
+2. 确认香港 Query 池名及账号机构/服务适用性;本地的 `ie.it.sentinel` 是 Dublin 配置,不能直接推定可用。
+3. 使用现有 GroupConfig / 启动方式,单 Query 实例、单订单 Book 实例,最终开关关闭。
+4. 先验证 Query 池账号如何完成/恢复 Calendar 准备:当前 Query 初次准备仍需人工 OTP,不把已准备的合成 fixture 当成池账号无人值守能力已完成。
+5. 现场观察真实框架发布/消费、订单账号绑定、库存重查与选中、零最终请求及清理。
+6. 最终提交、新预约回执归属与上线另行验收;本轮不扩大到这些动作。
+
+如果没有隔离环境,先解决测试依赖隔离,继续使用原框架;不要退回独立 Italy 信号机制,也不要冒险拿正式队列做试验。不能给网站预约成功率作 100% 保证;可以要求每个准出节点都有对应证据。
+
+## 9. 公共 PluginTester 的 Italy 查询配置
+
+`config/test_conf.json` 的 `ita_plugin` 已补齐香港现场样例:`slot.hkg.it.tourist`、服务 `4937`、单人旅游表单和最多 12 个月扫描;由现有 Query 逐月扫描,在首个正向月份停止并返回其中最早日期。地区与服务仍通过配置映射,不修改公共测试器或 Italy 算法。
+
+原有账号、密码、代理、个人资料及其他插件配置保留。账号必须已在网站绑定香港;本地修改路由不会替账号切换机构。
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B tools/plugin_tester.py --plugin ita_plugin -c config/test_conf.json
+echo "EXIT_CODE=$?"
+```
+
+这是实际网站查询命令,本次配置修改只做离线检查,未替用户执行。首次进入 Calendar 的准备阶段使用人工 OTP,可能发送一次验证码并提交 AVANTI;已准备好的 Calendar 查询不会每次发 OTP。最终提交开关为 `false`,不要手动点击最终 Prenota。
+
+此配置先不追加 `--book`:公共测试器的该参数继续使用同一个插件实例,不代表“池账号 Query → 申请人账号 Book”;当前 Calendar Query 配置也不允许作为申请人 Book 会话。真正双账号协同仍使用上文的既有 Sentinel/OrderBooker 框架。
+
+离线配置回归入口:`python -B -m unittest -q test.test_plugin_tester_ita_config`。使用真实 JSON 加载器与生产路由解析器,账号在测试加载时用合成值覆盖,不创建插件或浏览器。
+
+本次验证:配置与协议/查询定向回归 59 项通过;加入新配置测试后的 Italy 19 模块回归共 549 项通过(exit 0)。与修改前逐项比较确认:其他插件、原账号密码、代理、个人资料和原有私有配置均未变。公共测试器、生产插件和正式调度配置未修改;真实账号当前机构与现场查询仍待用户运行上述命令确认。
+
+## 10. Query 首次 Calendar 准备的 Turnstile 接入修复
+
+2026-08-31 用户提供的公共测试器日志确认:替换为私有 Query 账号并覆盖实际代理后,`create_session()` 已成功进入 `/UserArea`;服务 `4937` 的表单可打开。失败发生在发送 OTP 前,组件/API/脚本存在,但 `turnstileTokenPresent=false` 持续到超时,最终状态为 `turnstile_and_avanti_pending`。没有进入 Calendar,不能将本轮故障归因于登录或无号。
+
+代码原因:`ita_workflow.prepare_calendar()` 只在 `role == "book"` 时传入 `ItalyTurnstileRecovery`;Query 准备未接入同一处理。此证据说明程序的处理缺口,不足以单独证明网站未生成 token 的全部原因。
+
+授权修复:Query 与 Book 的首次 Calendar 准备共用现有恢复实例,继续复用 VFS 的 `CloudflareBypasser.click_verification_button(is_dfs=False)`;不新增验证码算法,不修改公共 helper、登录逻辑或日期扫描。保持初始等待 5 秒、间隔 10 秒、跨 OTP 前后合计最多 3 次操作,且只有真实 token 与可用 AVANTI 同时就绪才允许继续。正常已准备 Calendar 的查询不进入该处理,Query OTP 仍为人工输入,最终提交仍关闭。
+
+新增角色提示为 `Italy query Calendar preparation: reusing bounded Turnstile recovery.`;共用诊断沿用 `ITA_BOOK_*` 前缀以保持兼容,该前缀不代表调用了 Book。
+
+验证:定向准备/验证框测试 25 项通过;Italy 19 模块回归共 553 项通过,均 exit 0。覆盖 Query 成功后只记录 Query 准备、点击成功但无 token 时三次后仍不发送 OTP、OTP 前后共享预算、已成功的验证框不重复操作、已准备 Query 跳过整个准备路径,以及既有 Book 回归。所有外部网站/邮件交互均为模拟;真实通过情况待复测。
+
+以下命令替代第 9 节在本机直接使用默认账号/代理的启动命令。仍执行公共 `PluginTester`,只在内存覆盖账号与代理,不将私有密码写入被 Git 跟踪的配置或命令行参数。代理端口 `6268` 是本次本机诊断结果,不是其他机器的通用默认值。
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B -c '
+from utils.local_account import load_local_account
+from tools.plugin_tester import PluginTester
+account = load_local_account("config/ita_query_account.local.json")
+tester = PluginTester.from_json_config(
+    "ita_plugin", "config/test_conf.json",
+    user_override=account.username,
+    password_override=account.password,
+    proxy_override="http://127.0.0.1:6268",
+)
+raise SystemExit(0 if tester.run_pipeline(test_book=False) else 1)
+'
+echo "EXIT_CODE=$?"
+```
+
+现场只需配合页面要求的人机验证,并在终端提示后输入 OTP;不手动点击 OTP、AVANTI 或最终 Prenota。成功标准为验证通过、进入 Calendar 并获得 Query 结果,不能仅以 `clicked=true` 判定通过。如仍失败,收集固定诊断与页面错误文字,不记录账号、密码、验证码或验证 token。
+
+## 11. Query 自动 OTP 接入进展
+
+用户已实测第 10 节修复:验证框操作一次后 token 就绪,人工 OTP 写入回读通过,Query 返回最早日期 `2026-09-01`,公共测试器全部通过、exit 0。
+
+随后用户授权 Query 自动接码。现已复用 Book 的同一 OTP 分支及共享 SDK;95 项定向测试、561 项回归测试通过。Query 首次准备支持 `otp_mode=cloud`,已准备的扫描不再发码;最终提交仍关闭。
+
+本地尚缺确认过的 `mail.authorization_email`,因此保留当前可用的 manual 测试配置,没有擅自猜测授权邮箱或转发关系。自动接码的配置、测试、信任边界与现场准出见 [自动 OTP 文档第 10 节](ita_otp_auto.md#10-query-首次日历准备复用自动-otp代码已验证现场待配置)。本轮未运行真实网站/邮箱。
+
+## 12. 香港单账号池与自动 OTP 配置(2026-08-31)
+
+用户确认已在后台把测试账号加入 `hkg.it.sentinel`,并为同名 Gmail 登记了邮箱授权。以下配置取代第 11 节“缺邮箱配置”的现状,不把用户确认当成一次实际 API/邮箱连通性测试。
+
+- 在 `config/config_sentinel.json` 新增 `ita.hong_kong`,保留 Dublin 与其他组;账号来源仍是原来的 Sentinel → `VSCloudApi.get_next_account()`,没有本地账号回退。一个实例,账号冷却与会话寿命均 1800 秒,参考 TLS 的对齐配置;查询间隔沿用现有 Random 策略(60–300 秒)。这不是网站限流安全性的证明。
+- `enable=false`:仅完成本地配置,未发布云端配置、启动常驻 Sentinel 或连接 Redis/订单消费。`main.py` 仍沿用云端/缓存加载机制,不能把修改本地 JSON 当作已部署。
+- 香港服务 `4937`、单人旅游表单、最多 12 个月扫描、首个正向月份即停止保持不变。`otp_mode=cloud`,`mail.authorization_email=chatgptshareplus@gmail.com`;密码/邮箱授权码仍只在既有后台,不写入新配置。
+- `config/test_conf.json` 的香港 Query 同步自动 OTP 与邮箱配置;其中旧固定测试账号不作为本节验收来源。Book、公共测试器、共享 SDK、生产调度代码均不修改。
+- 此邮箱映射只验证当前一个账号。后续新增独立邮箱账号时,必须补齐接码映射或验证统一收件箱转发;“账号已经入池”不自动等于新邮箱可接码。发送时的 recipient 仍来自实际池账号,不能写死成测试邮箱。
+
+### 12.1 一次性池账号 Query 验收
+
+本节命令已更新为 `account-mailbox-v2`(见第 13 节):允许池中不同账号,邮箱来源由当前账号决定,不再检查其是否等于最初的固定邮箱。
+
+复用公共 `PluginTester` 和与 Sentinel 相同的 SDK 取号方法,不增加 Italy 专用运行器。仅运行一次 Query,不启动调度线程、Redis 或 Book;**不等同于真实 Query → 订单 Book 联调通过**。
+
+下面命令由用户在自己的终端执行。本轮助手未执行:取账号会立即把该账号置于 **30 分钟冷却**,即使后续浏览器失败也不会自动解除;不要反复领取/重置冷却。若后台已有冷却记录,需要等待其到期。代理 `6268` 是此前本机已验证端口,若本机端口变化须先调整;只覆盖本次浏览器代理,不改系统或其他插件配置。
+
+<!-- ITA_POOL_QUERY_COMMAND -->
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B -c '
+import json
+from pathlib import Path
+import configure
+from plugins.ita_protocol import resolve_route_config
+from plugins.ita_otp import validate_cloud_otp_environment, validate_cloud_otp_logging
+from toolkit.vs_cloud_api import VSCloudApi
+from tools.plugin_tester import PluginTester
+from vs_types import GroupConfig, VSAccount, VSPlgConfig
+
+groups = json.loads(Path("config/config_sentinel.json").read_text())
+group = GroupConfig.from_json(next(g for g in groups if g["identifier"] == "ita.hong_kong"))
+route = resolve_route_config(group.free_config["apt_configs"], group.appointment_types[0].routing_key)
+if configure.TEST_ACCOUNT:
+    raise SystemExit("Stop: TEST_ACCOUNT overrides the real pool; disable it first.")
+validate_cloud_otp_logging()
+print("ITA_POOL_QUERY_CONTRACT=account-mailbox-v2")
+try:
+    raw = VSCloudApi.Instance().get_next_account(group.sentinel.account_pool_id, group.sentinel.account_cd)
+except Exception as exc:
+    print("ITA_POOL_QUERY_ACCOUNT_FAILED type=" + type(exc).__name__)
+    raise SystemExit(1) from None
+if not isinstance(raw, dict) or raw.get("pool_name") != group.sentinel.account_pool_id or raw.get("status") != "active":
+    raise SystemExit("Stop: backend did not return an active account from the expected pool.")
+account = VSAccount.model_validate(raw)
+if not account.password:
+    raise SystemExit("Stop: the pooled account is missing its Prenot@Mi website password.")
+try:
+    validate_cloud_otp_environment(route.mail, account.username)
+except Exception as exc:
+    print("ITA_POOL_QUERY_MAIL_CONFIG_FAILED type=" + type(exc).__name__)
+    raise SystemExit(1) from None
+config = VSPlgConfig(account=account, debug=False, session_max_life=group.session_max_life,
+    free_config=group.free_config, proxy=PluginTester.parse_proxy_url("http://127.0.0.1:6268"))
+tester = PluginTester(group.plugin_config.plugin_name, group_id=group.identifier,
+    config=config, appointment_types=group.appointment_types)
+print("ITA_POOL_QUERY_SOURCE=cloud_pool pool=" + group.sentinel.account_pool_id + " book=false")
+raise SystemExit(0 if tester.run_pipeline(test_book=False) else 1)
+'
+echo "EXIT_CODE=$?"
+```
+<!-- /ITA_POOL_QUERY_COMMAND -->
+
+准出观察:出现 `ITA_POOL_QUERY_SOURCE=cloud_pool`;成功登录,自动 OTP 邮件读取和 DOM 回读通过;进入 Calendar 获得 Available+最早日期或有效 NoAvailable 结果;cleanup 成功、exit 0。不应出现人工输入 OTP 提示,也不要手动点击 OTP、AVANTI 或最终 Prenota;网站若要求人机验证,按页面完成。仅公共测试器显示“全部通过”不能单独证明当前有号,仍需看 Query 返回状态。
+
+失败时只反馈错误阶段和脱敏日志;不贴后台账号响应、验证码、Cookie 或完整邮件正文。本节命令在取号前检查 DEBUG 邮件日志与 TEST_ACCOUNT 覆盖,避免把测试常量误认为真实池取号。
+
+### 12.2 本轮离线证据
+
+- `python -B -m unittest -q test.test_plugin_tester_ita_config test.test_ita_route_wiring`:21 tests,OK,exit 0。
+- 20 个 Italy 模块联合回归:579 tests,OK,exit 0;在第 11 节 19 模块基础上纳入 `test_ita_route_wiring`。
+- 配置测试增加 8 项:公共测试配置与 Sentinel 路由/OTP 一致;禁用态/单实例/无明文凭据;真实 Sentinel spawner 绑定 SDK 返回账号;池不可用不回退;本文完整命令在模拟 SDK 下执行公共测试器且 Book 关闭;TEST_ACCOUNT 覆盖拒绝;后端错误脱敏;错误池/状态/邮箱映射/空密码拒绝。
+- 回归发现原路由测试还匹配旧的“所有 final 都禁用”错误文案;现有生产实现已区分显式申请人 Book 授权。本轮只同步该错误消息断言,仍要求裸 `final_submit_enabled=true` 被拒绝,不修改生产验证逻辑。
+- `git diff --check`:exit 0。未创建真实浏览器、领取后台账号、读取邮箱、发布 Redis 信号或提交预约;自动接码现场结果待用户回传。
+
+### 12.3 用户现场回传:自动 OTP + Query 通过
+
+2026-08-31,用户在收到第 12.1 节命令后回传公共测试器日志(本节证据来自用户终端,不是助手重新运行):
+
+- 表单验证先处于 `turnstile_token_pending`;一次 helper 操作后实际 `turnstileTokenPresent=true`、`outcome=ready`。
+- 日志明确进入 `Italy query OTP sent; waiting for the authorized mailbox (one read attempt).` 自动读取分支。
+- `ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true`;后续检查 `otpValuePresent=true`,进入 Calendar。所贴日志中没有人工 OTP 输入提示。
+- Calendar `probe index=0 available=0`、`index=1 available=11`;首个正向月份即停止,返回 `success=True`、`AvailabilityStatus.Available`、`earliest_date=2026-09-01`。这是当时快照,不表示号源现在仍在或已被预留。
+- 公共测试器各阶段 PASS,cleanup 成功,总耗时 98.49 秒、`EXIT_CODE=0`。
+
+结论:**该测试账号的自动 OTP → Calendar → 逐月最早日期 Query 单次真实链路已通过。** 不再把该链路列为仅离线验证。
+
+证据边界:本次截取从表单阶段开始,没有包含 `ITA_POOL_QUERY_SOURCE=cloud_pool pool=hkg.it.sentinel book=false` 或执行命令。若按第 12.1 节原命令执行,账号必经既有 SDK 池领取与返回池名检查,且无本地回退;仅凭这段后半程日志不能独立确认取号来源。需要补证时只补原运行的来源标记/确认命令,不为补日志重新登录、取号或发送 OTP。
+
+第 12.1 节入口明确 `test_book=False`、配置最终提交关闭;本次回传未包含网络审计计数或预约前后基线,因此不将“零最终请求”记为本次独立 Network 实测。共享诊断沿用 `ITA_BOOK_*` 前缀不代表执行了 Book。
+
+下一节点是原有 Sentinel → Redis 信号 → OrderBooker 的受控现场联调,Query 用池账号、Book 用目标用户账号,并在最终提交前停止。先落实隔离的信号/订单测试环境,避免误触正式订单;本次通过不等于常驻恢复、多人账号池、跨邮箱映射、真实 Book 或正式上线已验收。本轮只归档证据,不改变 `enable=false`,不启动任何外部流程。
+
+## 13. 解除单账号邮箱限制:使用实际池账号的授权邮箱
+
+用户新增池账号后,旧命令在 `account.username != route.mail.authorization_email` 或网站密码为空时退出。此检查是单账号验收命令的限制,不是 Prenot@Mi、SDK 或账号池要求。此前“加第二个账号就可直接重试”的说明遗漏了当前固定邮箱映射的前提;本节修正该限制。单独的 `ITA_POOL_QUERY_ACCOUNT_FAILED type=BizLogicError` 则只能证明后台取号失败,不能仅凭异常类型断言一定是冷却,需结合后台账号状态与 `next_use_time`。
+
+### 13.1 设计与复用
+
+- `plugins/ita_protocol.py` 的既有 `OtpMailConfig` 增加显式 `authorization_source`,默认 `configured` 保留原有固定/转发邮箱行为;`account` 通过 `mailbox_for(account_email)` 按本次账号解析收件邮箱,不修改共享 route、不缓存上一个账号的地址。配置同时提供 `account` 与固定地址会被拒绝,避免静默读错邮箱。
+- `plugins/ita_otp.py` 仍只调用既有 `VSCloudApi.fetch_mail_content`:账号来源模式将 `email` 和 `recipient` 都绑定本次账号邮箱;固定来源模式仍允许两者不同。固定 Prenot@Mi 发件人、主题、发送时间窗口、六位数字解析、失败不回退另一个邮箱/旧邮件、禁止 DEBUG 正文输出均保留。日志检查提取成共享 helper,供命令在领取账号前复用。
+- 香港 Sentinel 和公共测试配置改为 `mail: {"authorization_source": "account"}`,删除这两处固定邮箱地址;不改账号池调度、冷却、实例数、Book 配置或 SDK。`enable=false` 与最终提交关闭保持不变。
+- 第 12.1 节完整命令删除固定邮箱相等检查,保留网站密码必填与实际邮箱格式/日志检查。新增两个明确结果:`ITA_POOL_QUERY_CONTRACT=account-mailbox-v2` 和 `ITA_POOL_QUERY_MAIL_CONFIG_FAILED`。命令与正式 Sentinel 都使用生产 OTP 适配器,不只在测试命令里替换地址。
+
+### 13.2 使用前提及现场准出
+
+池中每个账号需在 Prenot@Mi 绑定目标机构、可登录,且其自己接收 OTP 的邮箱已经通过 `/api/email-authorizations` 登记;应用专用密码仍由现有后台保管。此模式不自动创建邮箱授权、不猜转发、不把缺授权伪装成可用。若账号的 OTP 实际转发至统一收件箱,应明确使用原 `configured` 模式,而不是对所有池账号反复改一个固定地址。
+
+多账号现场验收:等待已领取账号正常冷却到期,用第 12.1 节完整命令领取可用池账号,确认新命令版本、自动 OTP 写入验证、Query 结果及 cleanup/exit 0。助手本轮不领取账号、不发 OTP、不修改后台冷却。前一次单账号通过仍有效,但不能据此宣布本次新账号现场已通过。
+
+### 13.3 离线验证
+
+- OTP/工作流/公共配置/协议定向回归:126 tests,OK,exit 0。
+- 第 12.2 节同一组 20 模块完整回归:588 tests,OK,exit 0。
+- 最终 OTP 与公共配置/命令复核:28 tests,OK,exit 0;`git diff --check` exit 0。
+- 新增 9 项测试,覆盖 A→B→A 的不可变邮箱解析、旧固定邮箱兼容、来源歧义/错误配置拒绝、原发送人/模板/窗口约束、实际 SDK 参数跟随账号、授权失败不借别的邮箱、新账号公开 Query 连续两次只准备一次、完整命令接受第二个账号、DEBUG 在取号前拒绝以及无效邮箱在浏览器前拒绝(部分分支合并在同一用例)。
+- 更新原命令的单账号拒绝断言:不同的合法邮箱现为正向情况;缺网站密码、错误池/状态及无效邮箱仍拒绝。并未删除这些检查来制造通过。
+- 无浏览器/真实邮箱/账号后台操作,无部署、提交或冷却重置;正式 Sentinel/Booker 与共享 SDK、VFS/BLS/TLS 实现未修改。
+
+### 13.4 后续用户授权:解除失败测试造成的新账号冷却
+
+2026-08-31,用户明确要求更新新账号冷却。旧命令在领取账号后才执行单邮箱限制检查,因此即使未启动浏览器,后台领取动作也已推进 `next_use_time`。本次只补偿这次失败测试,不永久缩短池的默认冷却。
+
+- 后台只读查询确认 `hkg.it.sentinel` 中新账号为 `717`、状态 `active`,原 `next_use_time=2026-08-31T11:01:35` UTC(北京时间 19:01:35)。原账号 `716` 未修改。
+- 更新前再次核对目标账号身份和原时间;复用既有 `VSCloudApi.lock_account(717, lock_duration=0)`,仅发出一次 `/api/account/update` 请求。
+- 后台读回确认新时间为 `2026-08-31T10:46:24` UTC(北京时间 18:46:24),账号仍为 `active`,已满足时间上的领取条件。
+- 校验其他账号未变、目标账号其他业务字段未变;池默认 `account_cd=1800` 保持不变。没有领取账号、登录网站、读取 OTP 或运行 Query/Book,站点请求数为 0。
+
+此次更新只恢复可领取资格,不强制下一次领取账号 `717`;池仍按既有最早可用时间顺序分配。第 13.2、13.3 节“无后台操作”描述的是上一轮代码修改和离线验证,不包含此次单独授权的补偿操作。新账号自动 OTP + Query 现场结果仍待验证。
+
+## 14. 无需云端订单的本机真实联调入口
+
+2026-08-31,用户要求复刻正常 Query 发布、Book 感知并执行的行为,不将云端测试订单和上线配置作为前提;随后明确授权实现。合同:`existing-framework-local-prefinal-v1`。
+
+用户本轮另一次 Query 回传全部通过(94.66 秒),自动 OTP、两个月扫描、当时最早日期 `2026-09-01`。状态日志仍为原测试账号,不能作为新账号验收;该输出也不是 Redis → Booker 现场证据。
+
+### 14.1 复用方式与范围
+
+- 原 `tools/debug_ita_query_book.py` 默认仍离线;新增显式 `--local-preflight`、`--local-run`。旧 `--run` 继续拒绝,避免旧独立协调器命令误运行。
+- 现场装配放在 `tools/ita_query_book_local.py`,不改变生产 Sentinel、Booker、Italy 插件、SDK 或任何线上配置。模式采用“现有对象组合 + 测试边界替代”,不是另写 Query/Book 调度器。
+- 通过原插件工厂加载 Italy;执行真实 `OrderBookerGCO._spawn_worker`、`SentinelGCO._spawn_sentinel_worker`、`SentinelGCO._monitor_loop`、`BaseBookerGCO._booking_trigger_loop`、`OrderBookerGCO._execute_book_job` 和两者 `stop()`。
+- Query 仍由原 SDK 从配置的真实池领取一次,保留既有池名/冷却;两角色自动 OTP 仍用原生产适配器和真实邮箱授权。账号必须不同,分别使用临时浏览器会话;不共享 Cookie、验证码或库存 id。
+- 只替代云端订单的来源及上报:本地构造原有 `user_inputs` 数据结构,供原 OrderBooker 读取;不领取、创建、更新正式订单,不发通知。任何未明确支持的云端操作拒绝执行;成功上报在进入异步执行器前阻断。
+- 信号仍使用原 `setex`、原 JSON envelope、原 key 和原 TTL,Booker 仍通过原 `get`/解析/路由/日期/冷却逻辑判断;工具仅记录发布内容摘要并核对接收内容一致,不复制信号解析或有效期逻辑。
+- v1 使用本次进程独占的 `redis-server`,只开放临时 Unix socket,不监听 TCP、不写 RDB/AOF、不使用共享 Redis、不执行 FLUSHDB/FLUSHALL。临时 Redis、连接和目录在退出时清理;不是常驻服务,也未调用 `brew services start`。
+- 当前本机 Redis 依赖已安装(Homebrew Redis 8.10.1),并完成真实 Unix-socket 发布/读取/过期测试;不是启动整个 Coordinate 的 Docker 容器。
+
+### 14.2 有限执行顺序与边界
+
+先检查配置、Chrome、Redis 程序和本机代理端口,再获取 Book 用户资料;这些检查失败不领取池账号。先建立 Book 用户登录会话,再领取 Query 池账号并登录,最后执行一次原查询循环和一次原触发循环。这样不让信号在 Book 首次登录期间等待过期;Book 的 OTP/日历准备仍在原 Book 调用中执行。
+
+循环仅通过测试中的退出事件限定一次迭代,不改循环内部业务。没有启动 creator/maintain/cache-refresh 常驻线程、云端配置热更新或订单回写;因此此入口验证的是**真实单轮数据链路**,不是常驻生命周期/云端订单链路验收。信号过期或日期不匹配时本轮不补发、不重试。
+
+最终提交始终关闭,另对生产最终提交入口加测试拦截。复用 `CalendarRequestAudit` 和 `verify_precommit_selection`:两端最终请求必须为 0,单角色 OTP/AVANTI 不得超过一次;必须真实读回选中的日期、时段才可通过。pre-final 返回 `bookResult.success=False` 是既有合同,不能据此上报预约成功。
+
+Ctrl+C 后停止并清理原 GCO、审计和浏览器;若已有 Book 线程正在等待 SDK 调用,保留云端/最终提交保护直到它退出,不提前恢复依赖、不重试。该等待遵循既有 SDK/浏览器超时,不承诺任意阻塞都能立刻退出。
+
+池领取会按原规则更新冷却。若领取后才发现账号与 Book 用户相同,本轮拒绝继续且不自动解锁;选择一个不在 Query 池中的授权 Book 用户可避免这种情况。OTP 邮箱注册和网站账号所属机构是否正确,仍需事先满足,不能仅靠本地格式校验证明。
+
+### 14.3 完整现场命令
+
+无需修改 `config_booker.json`,也不需要后台测试订单。保持本机代理 `127.0.0.1:6268` 可用;Book 用户接收 OTP 的邮箱须已登记。执行:
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B tools/debug_ita_query_book.py \
+  --local-run \
+  --group ita.hong_kong \
+  --proxy http://127.0.0.1:6268
+echo "EXIT_CODE=$?"
+```
+
+随后在本地终端输入 **Book 目标用户** 的网站邮箱和网站密码(密码隐藏输入;不写入文件,不在聊天发送)。Query 账号自动从池中取得,不手填。也可显式使用既有私有 `--book-account-file` 或 `ITA_BOOK_USERNAME`/`ITA_BOOK_PASSWORD`;不会自动借用 Query 本地账号文件。
+
+默认使用生产 Book 的无额外日期限制行为,只做 pre-final 选中验收;需要测试用户日期限制时,入口接受 `--expected-start-date` / `--expected-end-date` 并原样进入现有订单过滤与 Book 日期选择。地区、service id、表单和邮箱策略均从所选 Query group 复制,不在装配模块硬编码香港服务号。
+
+只做环境检查、不开浏览器不取号:
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B tools/debug_ita_query_book.py \
+  --local-preflight \
+  --group ita.hong_kong \
+  --proxy http://127.0.0.1:6268
+echo "EXIT_CODE=$?"
+```
+
+其他机器若提示 `redis_server_missing_run_brew_install_redis`,需安装 Redis 可执行程序;不要因此启动共享 Redis 或手工改信号 key。两窗口若出现人机验证,按页面要求处理;不要手动点击 OTP、AVANTI 或最终 Prenota。
+
+成功摘要 `ITA_QUERY_BOOK_LOCAL_RESULT` 应同时满足:`passed=true`、`outcome=pre_final`、`queryCalls=1`、`bookCalls=1`、`signalPublished=true`、`signalReadByBooker=true`、`selectionVerified=true`、`cleanupVerified=true`;两端审计 `finalRequests=0`,`EXIT_CODE=0`。
+
+有效无号、日期过滤/过期不触发、Book 重查后无号均不伪装成完整联调通过,返回 exit 2;异常/清理失败返回非零。只有真正提交并核验新增回执的后续阶段才能宣称预约成功。
+
+### 14.4 本轮验证与未完成项
+
+- 20 模块 Italy 回归:**615 tests,OK,exit 0**,包括新装配测试与两个真实本机 Redis 集成用例;网站、账号池、邮件与云端订单在这些测试中均为合成依赖。
+- 真实临时 Redis 集成单独执行:2 tests,OK,exit 0;第一项验证原框架真实 setex/get 后触发,第二项使用真实服务器 TTL 到期后验证不触发 Book。网站和浏览器仍为 fixtures,禁止访问其他 socket。
+- 完整 CLI `--local-preflight`:exit 0,`ready=true`;未创建浏览器、领取账号、读取邮件或访问 Prenot@Mi。
+- 新用例覆盖不同账号/地区、原配置不变、动态邮箱、无号、写 Redis 失败、信号过期、日期过滤、池错误脱敏、同账号拒绝、异常返回成功、最终请求异常、重复 OTP、清理失败和中断;默认 `--offline` 仍不启动 Redis 子进程。
+- 首次 Redis 过期测试发现既有浏览器 fixture 将 `time.sleep` 替换为 Mock,导致测试未真实等待到期;修正测试为使用替换前的真实 sleep 后通过,未改生产 TTL。
+- 真实双账号登录 → 自动 OTP → Redis → Book 选中仍需用户运行 `--local-run` 回传;本轮不把历史单端成功拼成新的现场联调通过。未提交、部署或启用常驻分组,最终预约仍关闭。
+
+### 14.5 用户现场回传:真实单轮 Query → Redis → Book pre-final 通过
+
+2026-08-31,用户回传 `existing-framework-local-prefinal-v1` 摘要与 `EXIT_CODE=0`。
+这是用户自己终端的真实验收证据,不是助手重跑,也不延续第 14.4 节的“尚待现场验证”状态:
+
+- `liveAcceptance=true`、`passed=true`、`outcome=pre_final`;`queryCalls=1`、`bookCalls=1`。
+- `signalPublished=true`、`signalReadByBooker=true`;原框架真实 Redis 发布/读取已在本轮贯通。
+- 当时 Query 最早日期 `2026-09-01`;Book 重查后选中同日 `10:05 - 11:05`,`selectionVerified=true`。
+- Query 请求:availability=3、AVANTI=1、OTP=1、timeSlots=1、final=0。
+- Book 请求:availability=3、AVANTI=1、OTP=1、timeSlots=2、final=0。
+- `cleanupVerified=true`、`cloudOrders=false`、`finalSubmissionEnabled=false`。
+
+v1 入口强制不同账号、真实池领取及各自会话;该摘要不包含账号身份,不据此断言具体领取哪个邮箱。
+本轮只证明实时单轮协同到提交前;未创建预约、不验证云端订单回写/通知或常驻恢复。日期时段是当时快照,没有锁位。
+
+## 15. 显式真实单次提交模式
+
+2026-08-31,用户明确表示“我现在要的就是真实提交”。在原本机联调工具内增加
+`--local-run --submit-once`,最初合同为 `existing-framework-local-submit-once-v2`;用户随后明确要求无需确认输入,
+现行合同为 **`existing-framework-local-auto-submit-once-v3`**(见 15.5)。
+默认 `--local-run` 仍是 v1 pre-final;离线/预检不能携带 `--submit-once`。
+
+### 15.1 复用与文件归属
+
+- `tools/debug_ita_query_book.py`:只增加显式 CLI 开关/互斥校验和离线用例入口。
+- `tools/ita_query_book_local.py`:原组合装配增加独占防重复记录以及真实结果观察;
+  Query 的配置副本仍 final=false,只有本次 Book 内存副本设为 true,原配置文件完全不变。
+- 继续执行真实 `ItaPlugin.book` → `ita_workflow.book` → **原生产 `submit_final`** →
+  `FinalBookingAttempt` / `NativeFinalSubmitter` / `FinalReceiptReadPort`,没有重写提交接口、回执匹配器或轮询器。
+- 自动 OTP 原封不动。邮件仅按原发件人/模板/账号/窗口提取验证码;不新增邮件服务或 LLM 判断,不记录验证码/正文。
+- Book 返回原 `VSBookResult(success=True)` 后走原 Booker 成功分支;本地仅在原通知入口之前截获,
+  不进入异步云端订单更新/通知。unknown 保留原异常类型,走原暂停分支,仅将本地合成任务标记 pause。
+
+### 15.2 真实提交顺序与准出条件
+
+1. 显式使用 `--local-run --submit-once` 即启用自动真实提交,不要求交互终端。读取 Book 凭证后,先检查该申请人/服务的本地防重复记录,再创建浏览器或领取 Query 池账号。
+2. 原双会话 Query → Redis → Book 自动 OTP、日期/时段重查仍不变。无号或日期不匹配则不进入最终提交。
+3. 真正选中后,输出服务、日期、时段及 `automaticSubmission=true`,直接进入原生产最终流程,不等待确认句或按键。
+4. **仍由原生产最终核心读取新鲜预约基线**。已有有效预约、候补、无法核实的记录或上下文变化会阻断,不取消旧记录。
+5. 原生提交之前再次核对选位与零最终请求,复用 `tools.ita_final_evidence.claim_once` 的 O_EXCL + fsync 独占写入;然后只调用一次原生提交器。
+6. 只有原核心证实当前请求归属及唯一新增 `Confermata` 回执,才返回 Book 成功。页面跳转、HTTP 200 或按钮点击都不能单独算成功。
+7. 最终本机验收要求 `bookingConfirmed=true`、`bookResultSuccess=true`、`successHandledLocally=true`、
+   `passed=true`、`outcome=confirmed`、Query final=0、Book final=1、清理通过、EXIT_CODE=0。
+   `selectedTime` 是选择的时段,`confirmedTime` 是网站实际分配的时刻,二者不必是同一字符串。
+
+防重复文件位于既有私有目录的 `query-book-final/<sha256>.claim`;hash 绑定站点、规范化账号及 service_id,
+不绑定本轮 run id/日期/routing alias,重启或换路由别名不能自动再提交。文件内容只有已尝试状态,无密码、邮箱、验证码或预约编号。
+独占记录不自动清除;不同申请人的记录彼此隔离。这只是本 checkout 的验收防重复措施,不是分布式生产锁。
+旧 `final-evidence-once.claim` 不删除、不重置、不复用为新账号身份依据;`docs/ita_book_cs5.md` 第 29 节已有确认预约仍受网站基线检查保护,不重建或取消它。
+
+提交后无法核验返回 `outcome=unknown_do_not_retry`、EXIT_CODE=4;即使响应丢失也不二次提交。
+已经核实成功但诊断清理失败,同样保留 `bookingConfirmed=true` 并返回非零/4,不能为了修复清理而再预约。
+无号或信号/日期过滤未触发返回 2;预提交配置/基线失败返回 1。本工具不恢复云端订单写入,不宣称全生产常驻链路已经上线验收。
+
+### 15.3 完整真实执行命令
+
+保持本机代理可用,在用户自己的终端执行(**这次会真实占用预约名额**):
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+python -B tools/debug_ita_query_book.py \
+  --local-run \
+  --submit-once \
+  --group ita.hong_kong \
+  --proxy http://127.0.0.1:6268
+echo "EXIT_CODE=$?"
+```
+
+输入目标 Book 用户的网站账号/密码;Query 自动从池中领取,双方自动 OTP。
+选位后自动提交一次并核验回执,不要求输入 BOOK 确认句。运行前用可选日期范围参数表达真实可接受范围;未指定则沿用生产 Book 的无额外日期限制行为。
+除按网站要求完成真人验证外,不手动点击 OTP、AVANTI 或最终 Prenota。
+如果配置过 `ITA_BOOK_USERNAME`/`ITA_BOOK_PASSWORD` 或通过 `--book-account-file` 指定私有账号文件,沿用原凭证读取规则,无需再手填网站账号密码。未配置凭证时仍在启动阶段询问账号密码,这与最终提交确认无关。
+可选日期范围参数继续复用原订单过滤,不在本工具硬编码香港日期或时段。
+
+反馈 `ITA_QUERY_BOOK_LOCAL_RESULT` 和退出码即可,不贴密码/OTP/邮件正文。EXIT_CODE=4 时不要重跑,先核对预约回执。
+
+### 15.4 v2 历史验证
+
+- 新增 15 个离线用例:显式开关只影响 Book、终端前置、原 GCO + 原生产最终核心 + 原真实回执解析器贯通、
+  标准成功回调本地截获、实际分配时刻、拒绝确认、已有预约、响应未知但有匹配回执、缺回执暂停、
+  原生调用异常、无号、清理失败保留成功、重启/路由别名/残缺记录/符号链接阻断及 exit 4(部分分支合并在单例)。
+- 20 个相关 Italy 模块回归:**597 tests,OK,exit 0**,8.276 秒。包含真实私有 Redis 的两个本机集成用例;站点/邮箱/账号 API 仍为合成依赖。
+- 首轮扩展回归揭示测试边界的 `patch.dict(cloud.__dict__)` 会在退出时恢复运行前计数;改为仅添加/移除本地暂停方法,累计状态不再被恢复,重启断言及回归通过。
+- 默认离线 CLI:66 tests,OK,exit 0;CLI help 与 `git diff --check` 均通过。未登录网站、读取真实邮箱、领取真实池账号或提交预约。
+- 本轮真正创建预约的现场结果**待用户执行本节命令回传**。不能把第 14.5 节 pre-final 成功当作本次最终提交已通过。
+
+### 15.5 v3 修正:移除人工确认,按既有订单条件自动提交
+
+用户指出完整确认句不符合自动 Book 的预期。该额外步骤由验收工具引入,并非生产插件要求;现已移除。
+删除 `confirm` 回调、确认句输入、拒绝确认分支及最终提交对 TTY 的额外要求;不自动输入确认句来绕过旧逻辑。
+CLI `--submit-once` 是显式开关:启动后按原订单日期条件完成选位、原生产最终提交及回执核验。
+Query/默认 pre-final 仍关闭最终提交;已有预约检查、申请人绑定、独占防重复记录、未知结果暂停和退出码 4 均保留。
+未改生产插件、共享调度器、OTP、账号池或线上配置;未读取/清除已有 claim,也没有运行真实提交。
+
+更新离线用例:最终链路在 `builtins.input` 被设为一调用即失败时仍通过;配置了 Book 凭证的非交互启动无需 stdin;
+原有无号、日期过滤、身份不符、已有预约、重复提交及未知回执用例继续保留。默认离线 CLI 66 项通过(exit 0);
+与 15.4 相同的 20 个 Italy 模块回归 597 项通过(8.442 秒,exit 0)。CLI help 和 `git diff --check` 通过;真实提交尚待现场回传。
+
+### 15.6 用户授权解除两个测试账号的当前冷却
+
+用户回传 v3:Book 已到达认证 `/UserArea`,随后 `pool_allocation_failed`;Query/Book 调用均为 0、
+`possiblySubmitted=false`。后台只读查询(北京时间 2026-08-31 20:18:38)确认池内 716/717 均 active,
+可用时间分别为 20:27:14 / 20:35:37,当时均不可领取;这次失败不等于 Book 登录失败或已经提交。
+
+随后用户明确授权“都放开吧,我们要测试啊”。重新核对 `hkg.it.sentinel` 仅包含这两个 active 账号,
+逐项更新前再次比较账号业务身份和原 next_use_time,然后各调用一次既有
+`VSCloudApi.lock_account(id, lock_duration=0)`,不重复重试写入。
+
+- 北京时间 2026-08-31 **20:28:12** 读回:716、717 的 next_use_time 均为该时刻,均满足状态/时间领取条件。
+- 两次更新均成功;账号其他业务字段保持不变;仅更新这两个账号的当前冷却时间。
+- 未改池默认冷却、配置或其他池账号;没有领取账号、登录网站、发送 OTP、提交或取消预约。
+- 下次领取仍会按原 account_cd 更新冷却;本次不是永久取消账号池冷却。真实最终提交仍待用户现场结果。
+
+### 15.7 v4 修复:外层审计与生产最终提交共用一个监听器
+
+**现场证据**:用户回传 v3 已完成 Query、信号发布/读取、Book 自动 OTP 和选位,
+`selectionVerified=true`、`selectedDate=2026-09-01`、`selectedTime=10:05 - 11:05`;
+随后 `bookErrorType=CalendarGateError`、`finalRequests=0`、`possiblySubmitted=false`。
+这不是这次预约已成功或名额已保留的证据;失败发生在最终请求之前。
+
+**确定根因**:`ObservedPlugin.create_session()` 已在 Book page 的 CDP driver 注册
+`CalendarRequestAudit`。随后原生产 `ita_workflow.submit_final()` 又创建并启动第二个 audit,
+触发原有保护 `Passive request audit cannot replace an existing callback`,
+尚未创建 `FinalBookingAttempt`,也尚未执行 native submit 或写入本轮 claim。
+此前最终链路测试将内外两个 audit 都 Mock 掉,掩盖了这个真实组合冲突。
+
+**本次最小修复**:
+
+- `plugins/ita_workflow.py`:增加可选 keyword-only `request_audit`,借用调用方已启动的审计。
+  未传入时,普通生产调用仍自行创建、启动、停止;借用时不注册、不停止,不产生监听空窗。
+- `tools/ita_query_book_local.py`:将现有 Book observer 的 audit 显式传给原生产最终流程,
+  不新增事件分发器、不复制提交或回执核验逻辑。真实模式合同升为
+  `existing-framework-local-auto-submit-once-v4`,命令/自动 OTP/自动提交行为不变。
+- `plugins/ita_calendar_session.py`:核对借用方页面、driver、连接状态和原回调所有权;
+  每次实时 snapshot 同样核对所有权。最终审计必须包括时段请求;不覆盖其他回调、
+  不将断连后的 retained counters 当作最终请求证据。
+- 外层仍在停止 audit **之前**保存已连接且稳定的请求计数。若随后浏览器清理失败,
+  报告使用这份已保存快照,避免重新读取已停止的 audit 并把 confirmed 错改为 unknown。
+  清理失败仍不算验收通过,也不允许为了清理重新预约。
+
+**新鲜验证(2026-08-31,本地离线)**:
+
+1. 先将 `LocalFinalTests` 的两个 Mock audit 换为真实 audit,保留合成浏览器/CDP 传输和时钟:
+   原成功用例立即失败(exit 1),与现场同样为选位成功、`CalendarGateError`、最终请求 0。
+2. 修复后,现有最终链路测试使用真实 callback 注册/计数/settle/清理机制通过;
+   验证 Query/Book 各一个 audit、各 start/stop 一次,Book 最终请求只出现一次。
+3. 新增 `RealFinalAuditTests` 9 项,覆盖借用/独立所有权、原拒绝覆盖保护、已有预约、
+   错误页面/driver/断连/停止、回调被替换(含提交过程中)、缺时段覆盖,以及缺失/重复/混入其他请求不能归为成功。
+4. 扩大到 24 个 Italy 测试模块:**773 tests,OK,0 skipped,exit 0,9.480 秒**;
+   包含原 20 模块及 `test_debug_ita_production_query_gate`、`test_ita_calendar_soak`、
+   `test_debug_ita_book_gate`、`test_debug_ita_reservation` 的真实审计生命周期回归。
+5. `python -B tools/debug_ita_query_book.py --offline`:**75 tests,OK,0 skipped,exit 0**;
+   `--help` 与 `git diff --check` 通过。
+
+未登录网站、分配/解锁账号、发送 OTP、读取真实邮箱、重置 claim 或提交预约;未提交/推送代码、未部署。
+本轮按 phase-gated-delivery 限定为监听组合修复和离线验证。真实 Query → Book 最终成功仍需用户按 15.3 命令现场验收;
+本次离线成功不替代新增预约回执。遇到 `possiblySubmitted=true` 且结果未知/exit 4 时,仍先核验回执而非重跑。
+
+### 15.8 再次解除当前冷却:后台连接超时,未执行更新
+
+2026-08-31 20:51:36 +08,用户再次授权解除 `hkg.it.sentinel` 的当前冷却。
+先通过现有 SDK session 对 `/api/account/list_all` 做只读查询:默认连接两次分别在 15/20 秒超时;
+确认本机 6268 代理端口可连接后,经该代理只读查询同样在 15 秒超时(均 `ReadTimeout`)。
+未取得新鲜账号状态,因此本轮 **没有发出任何账号更新/领取请求**,没有改默认冷却、领取账号或预约。
+当前冷却是否已自然到期也未核实;不能沿用 15.6 的旧读回结果宣称本轮已解除。待后台连接恢复后再核对并更新。

+ 392 - 0
docs/ita_query_recovery.md

@@ -0,0 +1,392 @@
+# CS3R:Italy Query 恢复与持续盯号
+
+日期:2026-08-30。状态:IMPLEMENTING;本地准出及一次 15 分钟受控重建实测已验证(E51);真实认证过期恢复及长期运行仍待验收。
+
+Phase: IMPLEMENTING(本地准出、15 分钟受控重建已验证;整体尚未 VERIFIED)
+Scope: 已准备 Calendar 的持续生产 Query、故障分类、同账号会话重建、只读 Calendar 恢复、有限重试和人工接续边界。
+Non-goals: 不实现自动 OTP,不改 Book/最终提交、共享调度器或生产配置,不提交、推送或部署。
+Done: 本文故障矩阵均有离线断言,相关回归 exit 0;真实重建及持续运行另有版本、时长、请求计数和退出码证据。
+Approval: 负责人要求“把除了重新需要 OTP 的 TODO 之外的所有其他流程先完成”。
+Evidence/Risks: 387 项 Italy 回归及零网络 CLI 检查已验证(§8);同指纹现场回传证明 909 秒、3 次查询、1 次受控恢复且监测阶段无 OTP/AVANTI/final(§11)。重建后复用了仍有效的认证状态,不证明真实认证过期后的可恢复性。
+
+## 1. 目标,用人话说
+
+已经能查到最早日期,现在要让它能持续工作:没号继续等,有号报告后也继续查;网络短暂失败不误报,浏览器掉线后按限额重建;重建后确认还是同一账号、同一服务的 Calendar 才继续。
+
+重新需要 OTP 时输出 `needs_manual` 和 `ITA-OTP-01`,停止自动动作。这是暂时的接续点,不是删掉自动化要求,也不算无人值守验收通过。
+
+```text
+人工完成一次既有 Calendar 准备
+  → Query → 校验本次结果和请求 → 等待 → Query
+       ├─ 网络暂时失败 → 退避 → 最多再试一次
+       ├─ 登录过期 / 浏览器掉线 → 清理旧实例 → 同账号重建
+       │    → 只读恢复 + 身份重新核对 → Query
+       ├─ 限流 → 停止本轮,等待人工决定,不换账号绕过
+       ├─ 需要重新准备 / OTP → needs_manual,保留 TODO
+       └─ 未知结构 / 挑战 / 审计失败 → 停止,不发布错误号源
+```
+
+## 2. 可行性与证据边界
+
+| 项目 | 已有依据 | 本轮需要补齐 |
+|---|---|---|
+| 日期查询 | CS3A:两个生产 Query、逐月到首个正向月份、快照一致 | 持续多轮,正向后不退出 |
+| 失效回收 | VFS/BLS 的 `is_healthy=False`;Sentinel 的 health → cleanup → creator | Italy 异常正确进入同一机制 |
+| 浏览器重建 | 旧 soak 已有同账号、持久 profile、次数/时间上限 | 接续 Calendar 而不是退回弱 Services 探测 |
+| Calendar 恢复 | Q-CAL-1 曾在仍有效的持久认证状态下只读恢复 | 重登后重新核对;失败明确停下,不猜测可恢复 |
+| OTP 自动化 | VFS/BLS 邮件 API 调用顺序、Italy 邮件样本 | ITA-OTP-01,暂不实现,但必须完成 |
+| 长期频率 | 已有有限时长 soak 和间隔配置 | Calendar cadence 尚未实证;首次单实例、间隔至少 300 秒 |
+
+不承诺网站永不失效或预约成功率 100%。可机械承诺的是:每条路径有确定结果、失败不会变成有号/无号、写动作不被恢复机制重复执行。
+
+## 3. 最大化复用与文件归属
+
+| 文件/机制 | 职责 | 本轮处理 |
+|---|---|---|
+| `sentinel.py`、`main.py` | 账号/实例调度、Redis TTL、禁用组停止 | 原样复用,不另造守护进程、队列或生产轮询器 |
+| VFS/BLS 的异常 + 健康标志 | 区分过期、限流、拒绝;失效后回收 | Italy 薄适配;不复制网站专有端点或绕过逻辑 |
+| `plugins/ita_calendar_query.py` | Calendar 浏览器边界、扫描 | 增加可分类但不含响应正文的错误;保留唯一扫描实现 |
+| `plugins/ita_plugin.py` | IVSPlg 与网站能力衔接 | 标记失效;只读恢复前后重新校验账号、profile、完整 route 和 runtime service |
+| `tools/debug_ita_soak.py` | 已有有限时长、同账号重建、两次失败上限、状态文件 | 增加 Calendar 适配;继续使用同一个 soak 循环 |
+| `tools/debug_ita_calendar_gate.py` | 已验证的一次手工 OTP/AVANTI 和被动请求计数 | 准备完成后把同一实例交给 soak,不复制表单/发码实现 |
+| `plugins/ita_calendar_book.py` 的 `read_calendar_service()` | 已有严格只读 runtime service 读取 | 经插件现有依赖复用,不修改 Book 行为 |
+| `test/` | 故障、恢复、调用次数与回归 | 新增有边界的恢复测试;真实网站不能用 mock 替代 |
+
+设计方式:薄适配器 + 现有生命周期 + 组合既有验收工具。不增加通用状态机框架、邮件 Provider 或地区子类。香港只出现在现场示例配置中。
+
+## 4. 恢复合同
+
+### 4.1 错误分流
+
+| 观察 | Query 结果 | 本地盯号行为 |
+|---|---|---|
+| 明确 401 / 跳回 IAM 或登录入口 | `SessionExpiredOrInvalidError`,不再健康,旧扫描清空 | 清理一次、等待、同账号重建;连续两次即停 |
+| 浏览器断连 | 保留可识别断连类型,不再健康 | 同上,不复制 Cookie 或更换账号 |
+| 429 | 复用 `RateLimiteddError`,不再健康 | 本轮停止,不能自动换账号重试 |
+| 403 / 明确挑战页 | 拒绝/挑战类型 | `needs_manual`,不解验证码、不重新发 OTP |
+| 请求超时或 408/502/503/504 | 可区分的暂时网络错误,清空本次证据 | 有限退避;连续两次停止,不为了网络错误强制登录 |
+| 未知 schema、跨源、route/runtime 不符 | 明确协议/准备错误 | 停止,无号源发布、不盲目重试 |
+| Calendar 回到预约表单/未准备态 | `needs_manual` | `ITA-OTP-01` 接续;本轮发码/AVANTI 增量 0 |
+| 完整范围无正向日期 | `NoAvailable` | 记录成功的负向查询,等待下一轮 |
+| 首个正向月份 | `Available` + 最早日期 + `times=[]` | 记录标准快照,等待下一轮,不调用 Book |
+
+HTTP method 不能决定副作用:GenerateOTP 本身也是 GET。只读恢复仅使用已观察的 Calendar 导航与原生 Calendar 查询,绝不直接请求 GenerateOTP 或提交表单。
+
+### 4.2 重建不等于沿用旧认证证明
+
+仅在本进程已确认当前 route 的 Calendar 后,生成不落盘、不进入 Redis 的恢复参照:完整 route、账号绑定、持久 profile、同源 Calendar URL、runtime service。它不含 Cookie/OTP、预约日期、时段 ID,也不作为新 Session 已准备好的证明。
+
+重建使用相同配置和账号;新实例到 Dashboard 后,只访问一次已记录的 Calendar 地址。只有当前 URL/DOM/服务身份与参照匹配、最终按钮被保护,才重新登记当前实例的准备态。随后必须执行新的生产 Query,不能重用旧日期或 scan。
+
+参照不能用于另一个账号、profile、route 或 Book。进程重启后不从不可信文件重建此证明;重新走人工准备入口。完整进程重启后的自动 OTP 准备仍属于 ITA-OTP-01。
+
+### 4.3 有界运行与审计
+
+- 一个本地进程、一个账号、一个 route;300 秒是首次实验的保守下限,不是已证明的网站安全频率。
+- 时长沿用旧 soak 的 60 秒至 24 小时范围;首轮建议 15 分钟,之后 2 小时、24 小时逐步验收。
+- 重建前等待至少 60 秒;沿用连续两次故障和每小时最多六次重登的断路规则。成功登录不能清零“尚未成功查询”的连续失败数。
+- 同时统计成功正/负查询、错误、重建、Availability 及页面自动 TimeSlots;不得把一次 Query 当成一次 HTTP 请求。
+- `preparationRequests` 单独记录首次人工准备;`queryRequests` 记录准备后整个监测阶段,包含只读恢复页面自动产生的 Calendar 请求,而不只包含显式 `query()`。每个成功 Query 另有自己的请求增量。
+- `expiryCauses.configuredLifetime` 是本地配置主动回收,`expiryCauses.authentication` 才是认证失效观察;不能把配置寿命当作网站实际寿命。
+- 正向结果不终止监测,且只有新 scan 与标准快照一致才计为成功。当前失败时不把之前的正向日期冒充最新结果。
+- 复用被动审计,监测阶段 OTP/AVANTI/final 必须均为 0。审计断连形成缺口时明确报告,不能宣称全程请求数已证明。
+- 清理旧实例后才启动新实例,审计与 profile 锁释放失败时停止;Ctrl+C 不重新登录,退出码 130。
+- 只写脱敏本地状态;不写实际 Redis、不发邮件/外部通知、不创建预约。
+
+## 5. 开发与假设验证顺序
+
+1. 先补 HTTP/页面错误分类及健康标志,故障注入证明 Sentinel 能回收、异常不发布。
+2. 补只读恢复参照与当前实例重新核对;跨账号、服务、profile、跨源及 OTP 重入全部拒绝。
+3. 让既有 Q-CAL 准备流程交给同一 soak 循环;测试正负交替、短暂网络失败、断连重建、重登后缺准备、限流/结构变化、取消与清理失败。
+4. 受控现场:人工准备一次 → Query → 主动正常关闭本工具浏览器一次 → 重建 → 新 Query。该结果只证明受控重建,不冒充真实断网或完整登录过期。
+5. 15 分钟/2 小时/24 小时自然运行,另测真正过期和断连。若重新需要 OTP,停止并记 TODO;该停止路径可以验收,但不能算 24 小时连续无人值守通过。
+
+## 6. 准出、上线与回滚
+
+本地代码准出:故障矩阵通过、Italy 回归通过、diff 检查通过、无写动作、无敏感日志。初见审查必须回答“恢复是否用了旧身份/日期,以及失败后是否偷偷重发”。
+
+现场准出:记录命令/源码版本、实际时长、成功/错误/恢复次数、标准快照、请求审计及预约/候补前后计数、清理结果、退出码。未能取得结束计数或审计存在缺口,标为证据不完整,不能写 passed。
+
+生产仍单独准入:当前 Italy 组保持 disabled;旧 `services_probe` 的 `success=True` 弱信号会被现有 Sentinel 发布,所以它不是可在线降级的安全模式。回滚应禁用组,复用 `main.sync_groups()` 的 stop 路径。Sentinel 目前按实例数提高组频率,多账号总频率预算未关闭前只允许单实例实验。自动 OTP、真实长期寿命、跨账号和第二地区验证仍按总方案 Gate 管理。
+
+## 7. 必须完成的 TODO
+
+- [ ] **ITA-OTP-01(未完成,暂缓实现):自动处理首次及重新需要 OTP 的 Calendar 准备。** 复用既有 VFS/BLS 云邮箱 API、发送前时间戳、唯一新邮件匹配和单次动作保护;覆盖重登后接续。需要邮箱授权、旧码/串号/超时/重复提交回归以及真实验收。当前人工停止点不是该 TODO 的完成证据。
+
+## 8. 验证记录
+
+实施前代码检查确认:401/429 被合并成同一 Calendar 错误;Italy 过期分支未统一置 unhealthy;旧 soak 会在非空结果时停止。
+
+### 8.1 当前制品与执行结果
+
+- 合同版本:`qcal1-calendar-soak-v11`。
+- 源码指纹:`64b0581dbd3e`。指纹包含 Gate、Query 适配、Italy 插件、协议、共享 Book Calendar 边界、soak 和现有 backoff;任一相关源文件变动后必须重新验收。
+- 本轮仅本地文件编辑与离线执行,没有登录网站、发邮件、调用真实 Redis 或提交预约;没有提交、推送或上线。
+- 新增专用测试:`test/test_ita_query_recovery.py` 与 `test/test_ita_calendar_soak.py`。覆盖分类、旧证据失效、同账号恢复、错 route/profile/service 拒绝、正负交替、退避、断连/重建上限、OTP 重入停止、限流、审计缺口、清理失败与取消。
+- 故障注入运行的是实际 `ItaPlugin.query()`、Calendar 扫描与既有 soak 循环;浏览器和时钟替换为本地测试对象。另执行真实 `Sentinel._monitor_loop()` 的隔离测试,断言回收一次、没有 Redis 写入。它们不等于真实浏览器/网络验收。
+
+完整 Italy 回归实际执行:
+
+```bash
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q \
+  test.test_add_ita_query_account \
+  test.test_debug_ita_book \
+  test.test_debug_ita_book_gate \
+  test.test_debug_ita_calendar_gate \
+  test.test_debug_ita_monitor \
+  test.test_debug_ita_production_query_gate \
+  test.test_debug_ita_query \
+  test.test_debug_ita_session \
+  test.test_debug_ita_soak \
+  test.test_ita_calendar_book \
+  test.test_ita_calendar_book_flow \
+  test.test_ita_calendar_query \
+  test.test_ita_calendar_soak \
+  test.test_ita_local_handoff \
+  test.test_ita_plugin \
+  test.test_ita_protocol \
+  test.test_ita_query_recovery \
+  test.test_ita_route_wiring
+```
+
+结果:`Ran 387 tests in 3.266s`、`OK`、exit **0**。这是所列 Italy 测试模块的执行结果,不是全仓外部集成验收。
+
+定向回归实际执行:
+
+```bash
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q \
+  test.test_ita_query_recovery \
+  test.test_ita_calendar_soak \
+  test.test_debug_ita_calendar_gate
+```
+
+结果:`Ran 87 tests in 0.079s`、`OK`、exit **0**。
+
+其他检查:
+
+| 实际执行 | 返回值与观察 | 结论 |
+|---|---|---|
+| §9 的相同 HK 路由配置,不带 `--run` 的 CLI 预检 | exit 0;`ITA_SOAK_CALENDAR_PREFLIGHT_OK`、`external_request=false` | 参数及配置入口已验证;未读取账号或打开浏览器 |
+| `git diff --check` | exit 0,无输出 | 当前受跟踪文件 diff 无空白错误 |
+| `rg -n '[ \t]+$' docs/ita_query_recovery.md test/test_ita_query_recovery.py test/test_ita_calendar_soak.py` | exit 1,无输出;`rg` 的 1 表示无匹配 | 三个新增文件无尾随空白 |
+| `git diff --no-index --check -- /dev/null docs/ita_query_recovery.md` | exit 1,无输出(新文件产生差异) | 不能把此命令的 1 写成普通 `git diff --check` 的 exit 0 |
+
+曾尝试 `unittest discover -s test -p 'test*ita*.py' -q`:exit 1,收集阶段出现 5 个导入错误(`test/test.py` 与 `test` 包解析冲突,继而引入未安装的 `cv2`)。改用上面的显式模块入口后已验证通过,未安装额外依赖、未修改无关测试。没有运行需要真实云端/Redis 的全仓测试。
+
+### 8.2 初见审查
+
+反驳:“旧浏览器已经死了,凭什么用保存的信息继续?这不就是拿旧 Session 和旧日期冒充新的吗?”
+
+回应:保存的只是同账号/profile/route 的内存比较值。新实例必须自己登录、访问一次已观察的 Calendar URL、核对当前 runtime service,并重新执行 Query;旧 scan 先清空,日期不会传给新实例。回到表单直接 `needs_manual`,不重发 OTP,也不退回弱信号。错账号/route/profile/runtime、换 tab、过期与旧 scan 复用均有拒绝测试。
+
+另一个审查点是资源所有权:Gate 只交接一次浏览器和审计,恢复时先清理旧实例再创建新实例,清理失败不能报告成功。健康检查不吞掉 Ctrl+C;准备后的 route 以已确认的上下文为准,不重新解释环境变量。对应故障测试已通过。
+
+确信度:本地已覆盖合同及 E51 的一次受控恢复为**高**;真实认证过期恢复率及 2/24 小时稳定性为**待验证**,目前没有相应现场证据。
+
+## 9. 负责人终端的首次现场验证(已回传通过,命令保留供复现)
+
+### 9.1 这次只验证什么
+
+一个账号、一个地区配置,首次照旧手工输入 OTP,进入 Calendar 后:持续查询 15 分钟;第一次成功查询后,由程序正常关闭它创建的浏览器一次,再重建、只读恢复和重新查询。找到日期仍继续,不运行 Book、不选择时段、不点击最终确认。
+
+香港是现成样例,不是代码中的地区限制。账号必须仍绑定香港,不能与另一个进程共用该持久 profile。不要另开同一工具、手工切换机构、关闭它的窗口或发送第二次 OTP。首次手工准备所用时间不计入 900 秒,因此总等待时间会略长。每轮完成后等待 300 秒,不是每秒刷新。
+
+### 9.2 完整命令
+
+下列命令含 `--run`,**会真实登录,并执行既有一次 OTP/AVANTI 准备**。只在负责人自己的终端执行;本轮 Codex 未执行。只想先检查参数时,去掉 `--run`,其余保持不变。
+
+```bash
+cd /Users/zhangwei/JSWorkSpace/open_source/coordinate
+source .venv/bin/activate
+ITA_ROUTING_KEY=slot.hkg.it.tourist \
+ITA_SERVICE_ID=4937 \
+ITA_CITY='Hong Kong' \
+ITA_VISA_TYPE='Tourist' \
+ITA_CALENDAR_LOOKAHEAD_MONTHS=12 \
+ITA_SESSION_MAX_LIFE=900 \
+ITA_BOOKING_TYPE_CONTROL_ID=typeofbookingddl \
+ITA_BOOKING_TYPE_VALUE=1 \
+ITA_BOOKING_TYPE_LABELS='Prenotazione Singola|Single booking' \
+ITA_PURPOSE_CONTROL_ID=ddls_0 \
+ITA_PURPOSE_VALUE=42 \
+ITA_PURPOSE_LABELS='Turismo|Tourism' \
+PYTHONDONTWRITEBYTECODE=1 \
+python -B tools/debug_ita_soak.py \
+  --calendar --run --duration-seconds 900 \
+  --min-wait 300 --max-wait 300 --restart-after-probes 1
+echo "EXIT_CODE=$?"
+```
+
+这里沿用既有 900 秒本地 Session 回收配置;若它触发回收,报告单列 `configuredLifetime`,不能视为网站只允许登录 900 秒。`--restart-after-probes 1` 是一次受控正常关闭,不模拟故障,也不触碰用户另开的浏览器。
+
+### 9.3 回传什么、怎样判定
+
+只需回传 `ITA_QCAL_TOOL_CONTRACT`、`ITA_SOAK_CALENDAR_RESTORED`、最后一条 `ITA_SOAK_CALENDAR_RESULT` 和 `EXIT_CODE`。不要贴 OTP、密码、Cookie、完整请求头或私有账号文件。脱敏状态沿用 `data/ita_soak/status.json`;终端可见 OTP 仍可能留在终端滚动记录里。
+
+首次现场通过必须同时满足:
+
+1. 合同版本/指纹一致、exit 0、`passed=true`,实际监测达到 900 秒。
+2. `controlledRestart=true`、`restores >= 1`,新实例中 `queriesInCurrentSession >= 1`。
+3. `queryRequests.otpRequests/avantiPosts/finalRequests` 全为 0;首次人工准备的 `preparationRequests` 单独计数。
+4. `auditGaps=0`,预约/候补前后数量一致且 `reservationVerified=true`。
+5. 每次成功结果都有重新扫描和快照校验;没有日期也可以是正确的负向结果,不要求现场一定有号。
+
+| 退出码 | 意义 | 是否通过连续运行验收 |
+|---|---|---|
+| 0 | 本次有限时长运行证据完整 | 是,仅限本次工况和时长 |
+| 1 | 协议/业务错误或重试上限 | 否;保留脱敏原因,不盲目重跑 |
+| 2 | 参数/配置错误 | 否,尚未开始现场验证 |
+| 3 | 清理或状态落盘失败 | 否 |
+| 4 | `needs_manual`:重新准备/OTP,或网站人工验证 | 否;查看原因,OTP 对应 ITA-OTP-01 |
+| 5 | 网站限流 | 否;停止,不换账号继续试 |
+| 6 | 曾查询/恢复,但最终证据不完整 | 否;不能把“恢复后查到”当作全程审计通过 |
+| 130 | 人工 Ctrl+C | 否,正常取消 |
+
+15 分钟已按 E51 通过。负责人随后明确跳过本轮 2 小时测试,直接推进下一阶段;不再把追加长测作为 Book 提交前验收的前置。2/24 小时及自然过期仍属未验证,不改记为通过,也不后台启动。
+
+## 10. 当前交接状态
+
+- [x] 故障分类、健康失效、只读恢复、有限退避和持续查询的本地实现及离线回归。
+- [x] 复用既有工具的现场入口与零网络预检;首次人工 OTP 与监测请求分别审计。
+- [x] 负责人 15 分钟受控重建实测(E51:版本/指纹一致,909 秒,3 次查询、1 次恢复、exit 0)。
+- 本轮 2 小时测试按负责人决定跳过;2/24 小时自然寿命、真实断连/过期仍未验证,不阻塞当前 Book 提交前验收。
+- [ ] ITA-OTP-01,保留为必须完成的自动化任务。
+- [ ] 总方案的跨账号、第二地区、最终 Book Canary 和生产准入,仍按各自 Gate,不因本轮 Query 通过而自动完成。
+
+## 11. E51:15 分钟受控重建现场回传(2026-08-30)
+
+Phase: VERIFIED(仅本次受控重建与持续查询工况)。Approval: 负责人在自己的终端执行 §9.2;本轮仅归档,不新增运行、改代码、启用生产或提交预约。Evidence/Risks: 完整日志标头与本地已测试版本一致;认证自然过期、断网和 2/24 小时运行未覆盖。
+
+### 11.1 来源与机械结果
+
+负责人先回传结束摘要,后补充完整终端日志;以实际回传为依据,Codex 未代替负责人执行真实命令。只保存以下脱敏结果,不复制原日志中的 OTP、profile 标识、指纹 seed、调试端口或账号信息。
+
+```text
+ITA_QCAL_TOOL_CONTRACT version=qcal1-calendar-soak-v11 source_sha256=64b0581dbd3e
+ITA_SOAK_STARTED service_id=4937 routing_key=slot.hkg.it.tourist duration_seconds=900 min_wait=300 max_wait=300
+ITA_SOAK_CALENDAR_RESTORED restores=1 fresh_proof=true
+ITA_SOAK_COMPLETED duration_seconds=900 probes=3 none_available=0 transient_errors=0 session_attempts=2
+ITA_SOAK_SESSION_CLEANUP_OK session=2 reason=soak-finished
+ITA_SOAK_CLEANUP_OK
+EXIT_CODE=0
+```
+
+实际执行入口为 §9.2 完整 HK 配置加 `python -B tools/debug_ita_soak.py --calendar --run --duration-seconds 900 --min-wait 300 --max-wait 300 --restart-after-probes 1`;退出码 **0**。
+
+| 观察点 | 回传结果 | 可证明的结论 |
+|---|---|---|
+| 源码身份 | `qcal1-calendar-soak-v11` / `64b0581dbd3e` | 与 §8 已验证制品一致 |
+| 时长 | 配置 900 秒,最终 `elapsedSeconds=909` | 完成 15 分钟监测并收尾,未因找到号而提前退出 |
+| 查询 | 第 1/2/3 轮开始于 0/382/692 秒;3 次均正向 | 重建前 1 次、重建后 2 次真实新查询 |
+| 日期 | 三轮均扫描 8、9、10 月,首次正向月 10 月 | 本次快照最早 `2026-10-13`,不是当前库存永久承诺 |
+| 受控恢复 | 正常清理第 1 个实例,等 60 秒,再启动第 2 个实例;`restores=1` | 已准备 Calendar 的同 profile 重建可恢复 |
+| 准备与监测 | 准备 OTP 1、AVANTI 1;监测两者均 0;全部 final 0 | 没有因恢复重新发码或提交预约 |
+| 审计与对账 | `auditGaps=0`;预约/候补均 0 → 0 | 本次请求证据完整、前后数量不变 |
+| 清理与返回 | 两个实例分别清理成功,`passed=true`、exit 0 | 本次有限时长 Gate 已通过 |
+
+### 11.2 结果原值(脱敏结构化摘要)
+
+```json
+{
+  "auditGaps": 0,
+  "automaticOtpTodo": "ITA-OTP-01",
+  "controlledRestart": true,
+  "elapsedSeconds": 909,
+  "exitCode": 0,
+  "expiryCauses": {
+    "authentication": 0,
+    "configuredLifetime": 0
+  },
+  "failureReason": "",
+  "latestQuery": {
+    "automaticTimeSlots": 3,
+    "availabilityCount": 1,
+    "availabilityStatus": "Available",
+    "earliestDate": "2026-10-13",
+    "lookaheadMonths": 12,
+    "months": [
+      {
+        "month": "2026-08",
+        "positiveDays": 0
+      },
+      {
+        "month": "2026-09",
+        "positiveDays": 0
+      },
+      {
+        "month": "2026-10",
+        "positiveDays": 14
+      }
+    ],
+    "queryRequestDelta": {
+      "availabilityRequests": 3,
+      "avantiPosts": 0,
+      "finalRequests": 0,
+      "otpRequests": 0
+    },
+    "scannedMonths": 3,
+    "snapshotVerified": true,
+    "stopReason": "first_available_month",
+    "success": true,
+    "timesCount": 0
+  },
+  "mode": "calendar",
+  "negativeQueries": 0,
+  "passed": true,
+  "positiveQueries": 3,
+  "preparationRequests": {
+    "availabilityRequests": 1,
+    "avantiPosts": 1,
+    "finalRequests": 0,
+    "otpRequests": 1,
+    "timeSlotRequests": 0
+  },
+  "queriesInCurrentSession": 2,
+  "queryAttempts": 3,
+  "queryRequests": {
+    "availabilityRequests": 10,
+    "avantiPosts": 0,
+    "finalRequests": 0,
+    "otpRequests": 0,
+    "timeSlotRequests": 11
+  },
+  "reason": "",
+  "reservationAfter": {
+    "reservations": 0,
+    "waitlist": 0
+  },
+  "reservationBefore": {
+    "reservations": 0,
+    "waitlist": 0
+  },
+  "reservationVerified": true,
+  "restores": 1,
+  "sessionAttempts": 2,
+  "state": "completed"
+}
+```
+
+### 11.3 不能扩大成哪些结论
+
+- 第二个实例直接到 `/UserArea`,没有再次经过登录表单;`authentication=0`、`configuredLifetime=0`。这是**浏览器重建后继续使用仍有效的持久认证**,不是强制登录失效后重新认证的验收。
+- 本次没有自然断网/崩溃、无号轮次或账号切换;这些离线用例通过,不代表对应真实工况已经观察。
+- `queryRequests.availabilityRequests=10` 包含监测阶段的恢复页面请求,不只限于三次显式 Query 的 9 个 Availability 请求;自动 TimeSlots 总数 11 原样记录,不将其全部归因于某一个动作。
+- 2/24 小时运行、跨账号及第二地区验证、Book 最终 Canary、生产准入仍未完成。`ITA-OTP-01` 保持必须完成且暂缓,不能勾选完成。
+
+### 11.4 本轮归档验证与初见审查
+
+从负责人日志用 `rg` 仅提取合同、路由、查询和最终结果标记:exit 0。对版本、900 秒阈值、3 个逐轮结果、恢复次数、请求增量、预约计数和退出码执行结构化校核:**24 条断言通过**。本轮不重跑业务测试,因为没有修改 Python/配置;§8 的测试记录保留其原时间和制品身份。
+
+归档回读:§11.2 JSON 与负责人回传逐字段一致;`git diff --check` exit 0;新增归档所在文件尾随空白搜索 exit 1、无命中。对本轮关联的五个运行源文件及两份生产配置作前后 SHA-256 比较,内容均未变化。
+
+初见审查:“`passed=true` 是否等于无人值守的掉线恢复已经全部做好?”
+
+回应:否。完整日志明确显示重建时认证仍有效;本次关闭的是受控重建 Gate,不能关闭自然认证过期或 24 小时 Gate。对这种边界的限定来自实际行为,而不是仅相信 `passed` 一个字段。
+
+## 12. 下一阶段:复用现有 Book 提交前验收工具
+
+负责人要求跳过 2 小时长测并快速推进。当前直接复用 `tools/debug_ita_book_gate.py`,不再开发第二套入口:独立申请人登录、手工 OTP、一次 AVANTI、生产 Book 重查并选择真实时段,最终确认前停止。自动 OTP 保留 TODO;当前不执行最终预约。
+
+本轮未改业务代码。已执行 `PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest -q test.test_debug_ita_book_gate test.test_ita_calendar_book test.test_ita_calendar_book_flow test.test_ita_plugin`:167 项通过,exit 0。既有 HK 配置配合 `tools/debug_ita_book_gate.py --preflight`:exit 0,`external_requests=0 credentials_read=false browser_created=false`,版本 `book-prefinal-manual-v3`、指纹 `0c11e4d186d8`。
+
+现场命令交给负责人自己的终端执行,默认由其输入 Book 账号,不隐式读取 Query 私有账号文件。既有 CS4C 记录的 Calendar 准备失败仍需 v3 诊断补证,不凭 Query 的成功修改业务校验。成功标准是选中当前真实时段、最终请求 0、预约/候补前后不变、`passed=true`、exit 0;这不是最终预约成功。

+ 294 - 0
docs/vfs_plugin_deep_dive.md

@@ -0,0 +1,294 @@
+# 插件系统深度走读:以 vfs_plugin 为例
+
+> 配套文档:`docs/HANDOVER.md`(系统全景)。本文聚焦"插件系统是怎么设计出来的",用 vfs 插件作为解剖样本。
+> 行号引用:`plugins/vfs_plugin.py`(1466 行),框架侧引用 `vs_plg.py` / `vs_plg_factory.py` / `sentinel.py` / `booker.py` / `standalone.py`。
+
+---
+
+## 第一部分:插件系统是什么——三个文件、三个概念
+
+整个插件系统只有三个核心文件,对应三个概念:**契约(Interface)、工厂(Factory)、宿主(Host)**。
+
+```
+vs_plg.py           契约:IVSPlg 抽象基类 —— 定义"一个签证插件长什么样"
+vs_plg_factory.py   工厂:VSPlgFactory —— 定义"怎么把一个 .py 文件变成插件实例"
+sentinel/booker/standalone.py   宿主:GCO —— 定义"什么时候调用插件的哪个方法"
+```
+
+### 1.1 契约:IVSPlg(vs_plg.py,94 行)
+
+插件必须实现 8 个抽象方法,不多不少:
+
+| 方法 | 语义 | 宿主什么时候调用 |
+|---|---|---|
+| `set_config(cfg)` | 注入配置(账号/代理/业务参数) | 创建后立即 |
+| `set_log(logger)` | 注入日志函数 | 创建后立即 |
+| `create_session()` | 登录建会话;抛异常=失败 | 实例化时一次 |
+| `query(apt_type)` | 查档期,返回 `VSQueryResult` | 宿主循环反复调用 |
+| `book(slot_info, user_inputs)` | 抢号,返回 `VSBookResult` | 收到信号/命中档期时 |
+| `keep_alive()` | 保活;**不允许抛异常** | 周期调用 |
+| `health_check()` | 健康探活,返回 bool;**不允许抛异常** | 周期调用 |
+| `cleanup()` | 释放资源(关浏览器/删文件) | 任务销毁/组停止时 |
+
+外加两个约定:
+- 类属性 `name / version / description` —— 这是插件的"身份证",`utils/plugin_updater.py` 用 **AST 静态扫描**(不 import、不执行代码)就能读到版本号做升级判断(`plugin_updater.py:30-65`)。
+- 可选方法 `get_plugin_status()` —— 返回运行状态快照,供状态上报。
+
+**为什么是这 8 个方法?** 这是把"成千上万个具体签证网站"抽象成通用模式后的最小集合。观察所有签证预约网站:都要登录(会话)、都要查日期(查询)、都要填表提交(预订)、都要防掉线(保活)、都要判断登录是否过期(健康)、都要关浏览器(清理)。**变化的(每个网站的协议细节)留给插件,不变的(生命周期节奏、配额、退避、信号、订单流转)留在宿主。** 这就是框架开发的"抽象能力"——区分什么是变的、什么是不变的。
+
+### 1.2 工厂:VSPlgFactory(vs_plg_factory.py,63 行)
+
+```python
+register_plugin(plugin_name, module_path, class_name)  # 注册:名字 → 文件路径 + 类名
+create(group_id, plugin_name) -> IVSPlg               # 动态加载并实例化
+```
+
+关键实现:`importlib.util.spec_from_file_location` 按**文件路径**加载,而不是普通 `import`(`vs_plg_factory.py:41-48`)。
+
+**为什么按路径加载而不是 import?** 因为插件要支持**热升级**:
+1. 云端下发新版本 → 下载到 `plugins/xxx.py`(SHA256 校验 + `py_compile` 语法预检 + 原子替换,`plugin_updater.py:117-170`)
+2. 宿主把正在用旧代码的实例停掉,`sys.modules.pop(plugin_name)` 清掉模块缓存(`main.py:90`)
+3. 下次 `create()` 再加载时,读到的是磁盘上的新文件
+
+如果插件是普通 import 的模块,`sys.modules` 缓存会让"升级"永远加载旧代码。按路径加载 + 显式清缓存,是热升级闭环的地基。
+
+`create()` 里还有一个防御:实例化后强制 `isinstance(instance, IVSPlg)` 校验(`vs_plg_factory.py:54-56`),防止有人写了个"长得像插件但不是插件"的文件。
+
+### 1.3 宿主:GCO 怎么驱动插件
+
+以 Sentinel 为例,创建实例的完整链路(`sentinel.py:246-298`):
+
+```python
+plg_cfg = VSPlgConfig()                    # 组装插件配置
+plg_cfg.account = ...(从云端账号池取,带冷却)   # sentinel.py:261-262
+plg_cfg.proxy = ...(从云端代理池取,带冷却)     # sentinel.py:264-266
+instance = self.m_factory.create(group_id, plugin_name)  # 动态加载
+instance.set_log(logger)
+instance.set_config(plg_cfg)
+instance.create_session()                  # 登录
+task = Task(instance=instance, ...)        # 包进任务对象
+```
+
+之后 monitor 循环只做一件事:`task.instance.query(apt_type)`(`sentinel.py:202`)。发现档期 → 写 Redis 信号,**插件对"信号/Redis/云端"一无所知**。
+
+Booker 侧多了 `book()`:收到信号 → `task.instance.book(query_result, user_inputs)`(`booker.py:388`)。
+
+**设计亮点:宿主把插件当"黑盒工人",插件把宿主当"调度器"。** 插件代码里你找不到任何 Redis 操作、找不到订单队列逻辑——这些全是宿主的事。职责边界清晰到可以各自独立演进:新增一种签证网站 = 新增一个插件文件,框架一行不改;宿主加新能力(比如心跳) = 所有插件自动受益。
+
+---
+
+## 第二部分:vfs_plugin 解剖——一个真实插件做了什么
+
+VFS Global 是全球最大的签证外包商,它的预约系统是典型的 SPA(Angular 前端)+ 独立 API 域(`lift-api.vfsglobal.com`)+ Cloudflare 防护。这个插件就是和这套系统对抗的完整产物。
+
+### 2.0 模块级工具(vfs_plugin.py:1-114)
+
+| 工具 | 作用 | 为什么需要 |
+|---|---|---|
+| `VFS_PUBLIC_KEY_PEM` | VFS 的公钥(RSA) | VFS 登录密码必须 RSA-OAEP 加密后传输(2.3 详述) |
+| `COUNTRY_MAP` | 国家名 → ISO3 代码 | 申请人 payload 里 `nationalityCode` 要 ISO3,用户输入的是英文名 |
+| `get_alias_email()` | `xxx@gmail.com` → `xxx@text.skin` | VFS 邮箱字段校验域名(防虚假邮箱),用别名规避 |
+| `to_yyyymmdd()` | 日期格式转换 | VFS 不同接口返回 `MM/DD/YYYY` / `%m/%d/%Y %H:%M:%S` 等多种格式,统一成 `YYYY-MM-DD` |
+| `BrowserResponse` | 模拟 `requests.Response` | JS fetch 结果是个 dict,包装成类 Response 让上层代码像写普通 HTTP 客户端 |
+
+### 2.1 __init__:每实例完全隔离
+
+```python
+self.instance_id = uuid.uuid4().hex[:8]
+self.root_workspace = "data/temp_browser_data/{group_id}.{instance_id}"
+self.user_data_path = .../user_data
+```
+
+**每个实例有独立的浏览器用户数据目录 + 独立 instance_id。** 这是多实例并发的安全地基:Sentinel 一个组可以 spawn 多个 worker(`target_instances`),Booker 可能同时有 5 个实例,如果共享浏览器目录会互相踩 Cookie/锁文件。
+
+`set_config` 里有个细节(`vfs_plugin.py:155-159`):`free_config.country_code == 'chn'` 时把 API 域名切到 `lift-apicn.vfsglobal.com`——中国区有独立 API 域名。**业务配置(free_config)驱动行为差异,而不是写死在代码里**,这是插件"一文件多场景"的关键。
+
+### 2.2 create_session:四步建会话(vfs_plugin.py:201-373)
+
+#### 第 1 步:拉起浏览器(201-265)
+
+- **随机空闲 debug port**(`get_free_port()`):DrissionPage 走 CDP(Chrome DevTools Protocol),多实例必须端口隔离。
+- **代理接入两种模式**:
+  - 账号密码代理 → 起 **mihomo 隧道**(`MihomoTunnel`):本地起一个 Clash Meta 实例,配置 exit_node=目标代理、可选随机 relay_node=中继节点(`configure.MIHOMO_RELAY_NODES` 随机选),浏览器只连本地 `--proxy-server=127.0.0.1:随机端口`。**为什么这么绕?** 直连代理容易被检测,mihomo 可以做链式路由(出口伪装 + 中继混淆),且每个实例独立隧道进程、独立端口,互不干扰(`toolkit/mihomo_tunnel.py`)。
+  - 无密码代理 → 直接 `--proxy-server={proto}://{ip}:{port}`。
+- 反自动化参数:`--disable-blink-features=AutomationControlled`(去掉 `navigator.webdriver` 标志)、`--no-sandbox`、`--disable-dev-shm-usage`(容器内 /dev/shm 太小)、固定 1920x1080 视口。
+
+#### 第 2 步:过 Cloudflare 盾(278-325)
+
+这是全插件最"硬核"的部分。VFS 登录页挂了 Cloudflare Turnstile(无感验证码),拿不到它的 token 就登录不了。
+
+```python
+for i in range(40):                     # 最多等 40 秒
+    time.sleep(1)
+    ele = self.page.ele('@name=cf-turnstile-response', timeout=1)
+    if ele and ele.value:               # 隐藏 input 里出现 token = 过盾成功
+        cf_token = ele.value
+        break
+    if i > 2:
+        cf_bypasser.click_verification_button(False)  # 主动点验证按钮
+```
+
+配套 `CloudflareBypasser`(`utils/cloudflare_bypass_for_scraping.py`)做两件事:
+- **递归钻 shadow DOM + iframe**(`search_recursively_shadow_root_with_iframe`):Turnstile 组件是"shadow root 套 iframe 再套 shadow root"的俄罗斯套娃,必须一层层钻进去才能找到真正的验证按钮/输入框。
+- **handle_waiting_room**:VFS 高峰有"waiting room"排队页,检测到 `file d'attente` / `waitting room` 就每 10s 轮询,最多等 1 小时。
+
+过盾后从隐藏 input 的 value 里提取 cf_token——**Turnstile token 是登录请求的必填参数**(`captcha_api_key`)。
+
+#### 第 3 步:JS fetch 登录(327-367)——本插件最核心的逆向成果
+
+```python
+enc_password = self._encrypt_password(password)   # RSA-OAEP(SHA256) 加密
+client_src = self._get_client_source()            # RSA("GA;{UTC时间戳}Z")
+orange_src = self._get_orange_source(email)       # RSA("{email};{UTC时间戳}")
+data = {
+    "username": email,
+    "password": enc_password,
+    "captcha_version": "cloudflare-v1",
+    "captcha_api_key": cf_token,                  # Turnstile token
+    ...
+}
+resp = self._perform_request("POST", url, headers=headers, json_data=data)
+```
+
+三个逆向点:
+1. **密码 RSA-OAEP 加密**(`_encrypt_password`,604-613):VFS 前端用公钥加密密码再 POST,`cryptography` 库复刻。
+2. **请求签名**:`clientsource` = RSA 加密 `"GA;{时间戳}Z"`,`orangex` = RSA 加密 `"{email};{时间戳}"`——这是 VFS 的反爬签名(防脚本调用 API),插件把签名算法逆向出来了。
+3. **登录走浏览器内 fetch 而非 requests**(`_perform_request`,2.4 详述)——复用浏览器的 Cookie、TLS 指纹、UA、Origin。
+
+**OTP 分支**(361-364 + 705-781):若账号开了二次验证,登录响应返回 `enableOTPAuthentication`:
+- 用**云端邮件抓取 API**(`VSCloudApi.fetch_mail_content`)读 VFS 发来的 OTP 邮件——不依赖本地邮箱客户端;
+- 先正则找 6 位数字;找不到(VFS 有时把 OTP 做成图片)→ base64 图片丢给 **Qwen-VL 多模态大模型**识别(`toolkit/captcha_breaker.py:46-77`,prompt 甚至知道"OTP 箭头指向的才是真验证码");
+- 重新过盾拿新 Turnstile token(`_refresh_turnstile_token`,783-822:清空 input → `window.turnstile.reset()` → 轮询新 token),带 `otp` 字段重新提交登录。
+
+#### 第 4 步:会话建立后(369-373)
+
+- 记录 `session_create_time`(供 health_check 判定会话寿命);
+- 开**新标签页**查 `api.ipify.org` 拿出口 IP(`_get_realnetwork_ip`,555-583)。**为什么开新标签页而不是 fetch?** 注释写得很清楚:Top-Level Navigation 不带 `Origin` 头也不带 credentials,符合 ipify 的 CORS 规则。这个 IP 后面会作为申请人 payload 的 `ipAddress` 字段——VFS 的风控会校验"填表 IP"和"实际 IP"是否一致,提前拿到可以防误杀。
+
+### 2.3 _perform_request:插件的灵魂(397-526)
+
+**所有 API 调用(登录/查询/预订/保活)都走这一个方法**,它干的事是:把 HTTP 请求翻译成一段 JS,注入浏览器执行 `fetch`,再把结果翻译回 `BrowserResponse`。
+
+```js
+return fetch(url, options)          // credentials: "include" —— 自动带浏览器 Cookie
+    .then(async response => { ... 把 status/body/headers 打包返回 ... })
+```
+
+**为什么坚持用浏览器 fetch 而不是 requests?** 三层原因:
+1. **Cookie 自动携带**:`credentials: include`,浏览器自动带上登录后的会话 Cookie/JWT 相关状态;
+2. **环境指纹一致**:TLS 指纹、UA、`Sec-CH-UA`、`Origin` 全部是真实浏览器值——requests 的 TLS 指纹一眼假;
+3. **CF 盾的延续**:`lift-api` 域也受 Cloudflare 保护,用浏览器上下文发请求天然"过盾"。
+
+代价是性能(每次请求一次 JS 注入 + 网络往返),但正确性优先。
+
+**错误处理是这套系统的精华**——它把"反爬对抗"抽象成了标准 HTTP 语义:
+
+| 状态码 | 插件动作 | 宿主动作(框架层) |
+|---|---|---|
+| 401 | `is_healthy=False` + 抛 `SessionExpiredOrInvalidError` | 宿主销毁实例、重新 spawn(booker.py:498-502) |
+| 403 | 检测到 `"Just a moment"`(CF 盾)→ **自动重新过盾拿新 token → 递归重试**(最多 3 次);否则抛 `PermissionDeniedError` | 宿主退避 |
+| 429 | `is_healthy=False` + 抛 `RateLimiteddError` | 宿主 30s 退避 + 云端锁账号(sentinel.py:281-289) |
+| 0(fetch 网络错误) | 抛 `BizLogicError` | 宿主重试 |
+
+**亮点:403 自动过盾重试**(498-511)。请求打到一半被 CF 拦了,插件不慌:重置 Turnstile → 等新 token → 更新请求里的 `captcha_api_key` → 递归重发。这在抢号场景是生死攸关的——CF 盾可能随时插入,能自动恢复的抢号机才能活下来。
+
+另外注意 `debug` 模式(435-489):完整打印每个请求的 Headers/Body 和响应,这是"逆向调参"时期的可观测性设计,生产关掉避免刷屏(这也是最近 commit 在清理的"verbose logs")。
+
+### 2.4 query:查询链路(375-395 + 625-703)
+
+```python
+apt_config = self.free_config["apt_configs"][routing_key]  # 业务配置:这个 routing_key 对应哪个中心/类别
+self._fetch_configurations(apt_config)                     # 懒加载 master 数据
+result = self._query_earliest_slot(apt_config)             # 查最早档期
+```
+
+- `_query_earliest_slot`(625-646):POST `CheckIsSlotAvailable` → 响应含 `"WaitList"` 或 `earliestSlotLists[0].date`;
+- 结果归一化成 `VSQueryResult`(`availability_status` = Available / Waitlist / NoneAvailable 三态)——**插件内部千奇百怪的响应,出插件必须是统一三态**,这样宿主/信号/云端才能无脑消费。
+
+`_fetch_configurations`(648-703)是性能设计:VFS 的 master 数据(中心列表 → 签证类别 → 子类别)要三级 API 才能拿到,但一个会话内基本不变,所以**惰性加载 + 内存缓存**(`center_conf` / `category_conf` / `subcategory_conf`),只查一次。`_query_center` 用的是 GET 无鉴权接口(678-684),连登录都不需要。
+
+### 2.5 book:预订链路(824-992)——全插件最长的单方法
+
+11 个步骤,按业务顺序:
+
+1. **日期偏好预检**(837-842):`expected_start/end` 是订单用户填的期望区间,`earliest_date` 不在区间内直接放弃——**避免无谓地消耗账号和触发风控**。
+2. **master 配置懒加载**(849)。
+3. **OCR 分支**(854-860):如果该子类别 `isOCREnable`,先把护照照片上传(`_upload_applicant_documents`,1006-1044:支持 URL 下载或本地文件,base64 上传),拿到 `GUID` 等凭证,后面 payload 要用。
+4. **20 秒"冷静期"**(867-870):`booking_wait_applied` 标志位保证**每个插件实例只等一次**——VFS 风控会抓"刚登录就抢号"的行为,先装一会儿人。硬编码 20s,见"风险"。
+5. **提交主申请人**(875,`_add_primary_applicant`,1046-1165):构造一个 **60+ 字段的 applicant payload**——姓名全大写、生日转 `DD/MM/YYYY`、国家名转 ISO3、`ipAddress` 用真实出口 IP、`referenceNumber` 按子类别开关……全是逆向出来的"VFS 想要的格式"。成功后拿到 **URN**(预约单号)。失败重试 2 次,但 `"Capping has exceeded"`(当日预约上限)**不重试**(880-881)——识别"不可恢复错误"并立刻止损。
+6. **申请人 OTP**(889-899):`isApplicantOTPEnabled` 子类别 → 发 OTP → 云邮件读 → 验证。注意 `_applicant_otp_verify` 给 header 加了 `datacenter: GERMANY`(1187)——逆向出的又一个隐藏要求。
+7. **Waitlist 分流**(901-908):如果查到的档期是 Waitlist,走 `ConfirmWaitlist` 接口直接确认,流程结束——**不用选日期,因为日期不可选**。
+8. **按月扫日历选日期**(910-958):从 `expected_start` 到 `expected_end` 生成月份列表(`_get_filtered_covered_months`)→ 逐月 `_query_slot_calendar` 拿可预约日期 → 累积去重 → `_filter_dates` 过滤出区间内日期并 **random.shuffle 打乱**(防"每次都选同一天"的机器人特征)→ 对每个候选日期先 `_saveuseractionaudit`(**VFS 要求的"用户操作审计"步骤,不调这个接口就选不了时间**)→ `_query_slot_time` 拿时间段 → `random.choice` 随机选一个。
+9. **跳过增值服务 + 查费用**(967-968):`_submit_no_addition_service`(`/vas/mapvas`,不选任何 VAS)→ `_query_fee` 拿金额和币种。
+10. **提交预订**(971-976):`/appointment/schedule`,带 `allocationId`(选中时间段的 ID)和支付信息 → `IsAppointmentBooked` 判定成败。
+11. **支付链接解析**(984-991):如需在线支付,`_pay_request`(1324-1348)开新标签页访问 VFS 支付组件,等 URL 跳转后把最终支付链接抓回来——**返回给订单用户去付款**,机器人不替用户付钱。
+
+### 2.6 keep_alive / health_check(170-199)
+
+```python
+def keep_alive(self):
+    keep_alive_funcs = [self._get_application, self._query_center]
+    random.choice(keep_alive_funcs)()   # 随机挑一个真实 API 打一下
+```
+
+**亮点:保活不是发心跳包,而是随机执行一个真实业务 API。** 既维持了会话活性,又模拟了真实用户行为(对风控更友好)。失败则 `is_healthy=False`。
+
+`health_check` 三重判定:`is_healthy` 标志 + 页面 `run_js("return 1;")` 探活 + `session_max_life` 超时(超时返回 False,宿主重建会话)。两个方法都"不允许抛异常"——契约里写死的,因为宿主循环里任何异常都会打乱调度节奏。
+
+### 2.7 cleanup / get_plugin_status(1407-1460)
+
+- `cleanup`:关浏览器 → **删临时目录(3 次重试)** → 停 mihomo 隧道。抢号机跑久了会产生大量浏览器 profile(每个实例几十 MB),不删干净磁盘会爆;
+- `get_plugin_status`:把内部状态翻译成 `PluginStatus`(instance_id / account / proxy / current_url / session_age / state:`running` / `logging_in` / `unhealthy`)——宿主聚合后上报云端做监控大屏;
+- `__del__` 兜底:对象被 GC 时也尝试清理(防异常路径泄漏)。
+
+---
+
+## 第三部分:为什么这么设计——设计哲学总结
+
+1. **契约是"最小共识"**:8 个方法恰好覆盖"任何签证网站都要做的事",多一个侵入、少一个残缺。插件作者只需要看 `vs_plg.py` 一个文件就能写插件——低门槛;而宿主通过异常体系(401/403/429)获得"通用决策能力"——高天花板。这就是"Low Floor, High Ceiling"。
+
+2. **控制反转**:不是插件调用框架("我要查档期了"),而是框架调用插件("该你查了")。插件不知道 Redis、不知道订单队列、不知道信号,它只对 `query/book` 的入参出参负责。**替换插件 = 替换工人,不换工厂。**
+
+3. **对抗性设计内聚在插件里**:反爬对抗(CF 过盾、RSA 签名、浏览器 fetch、拟人化等待)全部在插件内部消化,框架层的调度逻辑保持纯净、可测试。框架只依赖"插件会按契约工作"这个信念。
+
+4. **归一化接口**:VFS 的三种档期状态(有/无/waitlist)→ 统一 `AvailabilityStatus`;千奇百怪的日期格式 → 统一 `YYYY-MM-DD`;浏览器 fetch 结果 → 统一 `BrowserResponse`。**接口的稳定性就是插件的可替换性。**
+
+5. **生产级资源管理**:实例隔离(独立端口/独立目录)、原子清理、`__del__` 兜底、内存缓存、失败重试带"不可恢复错误识别"——这些是"能长期跑"和"演示能跑"的分界线。
+
+---
+
+## 第四部分:亮点清单(vfs 插件值得抄作业的地方)
+
+| # | 亮点 | 位置 |
+|---|---|---|
+| 1 | **403 自动过盾重试**:请求被 CF 拦截后自动重置 Turnstile、换 token、递归重发,抢号机在盾前能自愈 | 498-511 |
+| 2 | **逆向 VFS 请求签名**:RSA-OAEP 加密的 `clientsource`/`orangex` 头 + 密码加密 | 604-623 |
+| 3 | **保活 = 随机真实业务 API**:既是心跳又是行为仿真 | 170-180 |
+| 4 | **OTP 双通道读取**:云邮件正文正则 → 失败再上 Qwen-VL 识图 | 705-737 |
+| 5 | **master 配置惰性缓存**:三级元数据只拉一次,会话内复用 | 648-703 |
+| 6 | **风控前置**:20s 冷静期(仅一次)、日期随机化、真实 IP 预取、审计步骤补齐 | 867/1376/555/1249 |
+| 7 | **不可恢复错误识别**:`Capping has exceeded` 不重试,止损 | 880-881 |
+| 8 | **可观测性**:debug 模式完整 TRAFFIC 日志 | 435-489 |
+| 9 | **多态适配**:Waitlist / OTP / OCR / 参考号,全部由子类别配置开关驱动,一个插件覆盖全球几十个中心 | 854/889/1136 |
+| 10 | **实例级隔离 + 彻底清理**:独立 profile、独立隧道、删除重试 | 144-150 / 1407-1434 |
+
+---
+
+## 第五部分:客观风险与可改进点(不做改动,仅记录)
+
+1. **`time.sleep(20)` 硬编码**(869):冷静期不可配置,改时长要改代码。建议进 `free_config`。
+2. **`master_email = "hujiarui8@gmail.com"` 硬编码**(707):读 OTP 邮件的"主邮箱"写死在代码里,换运营人就要改代码。建议进配置。
+3. **保活调用随机二选一**(172-175):`_query_center` 是 GET 全量中心列表(较重的响应),高频随机到它浪费带宽。可换成更轻的接口。
+4. **`real_ip` 获取失败 fallback 到代理 IP**(373):代理 IP 与风控记录可能不符,极端情况会误伤账号。值得观察线上日志。
+5. **OTP 图片识别依赖具体邮件模板**:prompt 里写死"OTP 箭头指向的验证码"(captcha_breaker.py:53),VFS 改模板就失效——属"对抗的宿命",但要知道这个脆弱点。
+6. **`_perform_request` 每次全量打印响应体**(debug 模式):响应 1KB 截断打印,已比早期好,仍建议加开关。
+
+---
+
+## 附:如果你要新写一个插件(比如接一个新签证网站)
+
+1. 复制 `prt_plugin.py`(最小骨架)或参考 `vfs_plugin.py` 结构;
+2. 只实现 8 个契约方法,遵守两条铁律:`keep_alive`/`health_check` 不抛异常;`create_session` 失败抛异常;
+3. 业务差异全放 `free_config`(用 `apt_configs` 按 routing_key 给配置),**不要写死任何中心/类别代码**;
+4. 所有 HTTP 走 `_perform_request` 式浏览器 fetch(如果网站有反爬)或 requests(如果网站裸奔),但**响应必须归一化成 `VSQueryResult` 三态**;
+5. 上传到云端插件仓库 → 下发 → 节点秒级热升级,框架零改动。

+ 457 - 0
plugins/ita_booking_final.py

@@ -0,0 +1,457 @@
+"""Italy final-stage building blocks shared by production and local validation.
+
+ReservationSnapshot is an internal read-port contract, NOT a discovered website
+schema. A real adapter must prove identity, status and pagination completeness
+before this module can be enabled. Attempts are process-local; the existing
+Booker task pause handles uncertain outcomes. No automatic retry is provided.
+The opt-in local evidence gate adds a checkout-local fence and human confirmation;
+it observes unknown receipts without claiming that production success is proven.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import threading
+import time
+from dataclasses import dataclass, field
+from datetime import date
+from enum import Enum
+from typing import Callable
+from urllib.parse import parse_qsl, urljoin
+
+from plugins.ita_calendar_book import SLOT_SELECTION_SCRIPT, verify_precommit_selection
+from plugins.ita_calendar_query import CALENDAR_PATH, listen_once, same_origin_path
+from plugins.ita_protocol import CalendarDay, MAX_PROTOCOL_PAYLOAD_CHARS, PrecommitApproval, SlotCandidate
+from vs_types import VSBookResult, BookingOutcomeUnknownError
+
+
+FINAL_PATH = "/BookingCalendar/InsertNewBooking"
+
+
+class FinalBookingError(RuntimeError):
+    """Fixed messages only: do not include page text, requests or credentials."""
+
+
+class FinalOutcomeUnknown(FinalBookingError, BookingOutcomeUnknownError):
+    def __init__(self):
+        super().__init__("Italy final outcome requires read-only reconciliation")
+
+
+class ReservationState(str, Enum):
+    ACTIVE = "active"
+    CANCELLED = "cancelled"
+    WAITLIST = "waitlist"
+    UNKNOWN = "unknown"
+
+
+class SubmissionSignal(str, Enum):
+    ACCEPTED = "accepted_hint"
+    REJECTED = "rejected_hint"
+    UNKNOWN = "unknown"
+
+
+def _text(value: object) -> bool:
+    return (isinstance(value, str) and 0 < len(value) <= 256 and value == value.strip()
+            and not any(ord(ch) < 32 or ord(ch) == 127 for ch in value))
+
+
+@dataclass(frozen=True, slots=True)
+class FinalTarget:
+    applicant: str = field(repr=False)
+    session_key: str = field(repr=False)
+    tab_id: str = field(repr=False)
+    routing_key: str
+    service_id: str = field(repr=False)
+    runtime_service: str = field(repr=False)
+    approval: PrecommitApproval = field(repr=False)
+    service_name: str | None = field(default=None, repr=False)
+
+    def __post_init__(self):
+        if not all(_text(getattr(self, key)) for key in (
+            "applicant", "session_key", "tab_id", "routing_key", "service_id", "runtime_service",
+        )):
+            raise FinalBookingError("Italy final target identity is invalid")
+        if not isinstance(self.approval, PrecommitApproval):
+            raise FinalBookingError("Italy final requires a Book precommit approval")
+        if self.service_name is not None and not _text(self.service_name):
+            raise FinalBookingError("Italy final displayed service is invalid")
+        day, slot = self.approval.calendar_day, self.approval.candidate
+        if (not isinstance(day, CalendarDay) or not isinstance(slot, SlotCandidate)
+                or day.day != slot.day or not day.is_available or not slot.is_available):
+            raise FinalBookingError("Italy final target inventory is inconsistent")
+
+
+@dataclass(frozen=True, slots=True, repr=False)
+class VerifiedSubmission:
+    """Native POST matched this exact session/tab/precommit; not a receipt field.
+
+    Created from an observed packet, even when its RESPONSE schema is unknown.
+    A caller must also enforce the one-request audit before passing it to a read port.
+    """
+
+    target: FinalTarget
+
+
+@dataclass(frozen=True, slots=True)
+class ReservationRecord:
+    """Normalized by a verified, identity-bound site reader.
+
+    time_label is an independently evidenced selected interval, not an interval
+    inferred from appointment_time. A real receipt may expose only the assigned
+    HH:mm time. That is enough to preserve cancelled history, not prove a new
+    record belongs to the selected slot. Cancelled history may have an unbound
+    service_id only with a fingerprint retaining all observed business facts.
+    This exception never establishes a target-service or selected-slot binding.
+    submission is a separate verified native-request witness, used by the bound
+    real read port for new active receipts. It never rewrites the receipt fields.
+    """
+
+    reference: str = field(repr=False)
+    service_id: str | None = field(repr=False)
+    day: date
+    time_label: str | None
+    state: ReservationState
+    appointment_time: str | None = None
+    receipt_fingerprint: str | None = field(default=None, repr=False)
+    submission: VerifiedSubmission | None = field(default=None, repr=False)
+
+
+def _valid_receipt_time(record: ReservationRecord) -> bool:
+    interval, assigned = record.time_label, record.appointment_time
+    if interval is None and assigned is None:
+        return False
+    if interval is not None and (
+        not isinstance(interval, str)
+        or re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9] - (?:[01][0-9]|2[0-3]):[0-5][0-9]", interval) is None
+        or interval[:5] >= interval[-5:]
+    ):
+        return False
+    assigned_valid = assigned is None or (
+        isinstance(assigned, str)
+        and re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", assigned) is not None
+    )
+    if not assigned_valid:
+        return False
+    # Negative consistency check only: containment never creates a binding.
+    return interval is None or assigned is None or interval[:5] <= assigned <= interval[-5:]
+
+
+@dataclass(frozen=True, slots=True)
+class ReservationSnapshot:
+    applicant: str = field(repr=False)
+    session_key: str = field(repr=False)
+    captured_at: float
+    complete: bool
+    records: tuple[ReservationRecord, ...] = field(repr=False)
+
+
+# Reuse the actual slot readback JS in the same synchronous browser turn as the
+# native final click, so a Python/browser round trip cannot select another slot.
+# Never reconstruct the POST payload: the website handler remains its owner.
+NATIVE_FINAL_SCRIPT = r"""
+/* coordinate:ita-native-final-once */
+const [serviceId, day, dailyId, timeLabel, capacity] = arguments;
+const state = (function () {
+""" + SLOT_SELECTION_SCRIPT + r"""
+}).apply(null, [serviceId, day, dailyId, timeLabel, capacity, false]);
+const positive = ['runtimeMatches', 'finalGuarded', 'firstSelectedMatches',
+  'dayPositive', 'candidateReady', 'activeIsCandidate', 'activeIdMatches',
+  'activeDayMatches', 'activeTimeMatches', 'activeCapacityMatches'];
+const negative = ['dayDisabled', 'dayNegative', 'activeUnavailable', 'activeRedDot', 'clicked'];
+const ready = positive.every(k => state[k] === true) && negative.every(k => state[k] === false) &&
+  ['matchingDateCount', 'candidateCount', 'activeCount', 'activeInputCount'].every(k => state[k] === 1) &&
+  JSON.stringify(state.timelineDays) === JSON.stringify([day]) &&
+  JSON.stringify(state.contentDays) === JSON.stringify([day]);
+const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
+if (!ready || buttons.length !== 1 || !buttons[0].isConnected ||
+    buttons[0].dataset.coordinateFinalAttemptConsumed) return {clicked: false};
+const button = buttons[0];
+button.dataset.coordinateFinalAttemptConsumed = 'true';
+try {
+  button.disabled = false;
+  button.removeAttribute('aria-disabled');
+  button.click();
+  return {clicked: true};
+} finally {
+  button.disabled = true;
+  button.setAttribute('aria-disabled', 'true');
+  button.dataset.coordinateFinalGuard = 'enabled';
+}
+"""
+
+
+def _unique_object(pairs):
+    result = {}
+    for key, value in pairs:
+        if key in result:
+            raise ValueError("duplicate field")
+        result[key] = value
+    return result
+
+
+def inspect_final_packet(packet: object, target: FinalTarget) -> tuple[SubmissionSignal, VerifiedSubmission | None, str]:
+    """Validate the observed request before interpreting a response as a hint.
+
+    Invalid metadata/HTTP/schema is UNKNOWN after a write, not a retryable
+    authentication/no-slot error. Never expose the raw server errorMessage.
+    """
+    evidence = None
+    reason = "request_metadata"
+    try:
+        path, parsed = same_origin_path(packet.url)
+        if (path != FINAL_PATH or parsed.query or parsed.fragment or packet.method != "POST"
+                or packet.tab_id != target.tab_id or getattr(packet, "is_failed", False)):
+            return SubmissionSignal.UNKNOWN, None, reason
+        reason = "request_fields"
+        body = packet.request.postData
+        if isinstance(body, str) and len(body) <= MAX_PROTOCOL_PAYLOAD_CHARS:
+            body = _unique_object(parse_qsl(body, keep_blank_values=True, strict_parsing=True))
+        if not isinstance(body, dict) or set(body) != {
+            "idCalendarioGiornaliero", "selectedDay", "selectedHour",
+        } or any(not isinstance(value, str) for value in body.values()):
+            return SubmissionSignal.UNKNOWN, None, reason
+        reason = "request_selection"
+        slot = target.approval.candidate
+        if body["idCalendarioGiornaliero"] != slot.daily_calendar_id or body["selectedDay"] != slot.day.isoformat():
+            return SubmissionSignal.UNKNOWN, None, reason
+        compact = lambda value: re.sub(r"\s+", "", value)
+        if compact(body["selectedHour"]) != compact(f"{slot.time_label}({slot.slots_free})"):
+            return SubmissionSignal.UNKNOWN, None, reason
+        evidence = VerifiedSubmission(target)
+        reason = "response_metadata"
+        response = packet.response
+        if type(response.status) is not int or response.status != 200:
+            return SubmissionSignal.UNKNOWN, evidence, reason
+        response_url = getattr(response, "url", None)
+        if response_url:
+            response_path, response_parsed = same_origin_path(response_url)
+            if response_path != FINAL_PATH or response_parsed.query or response_parsed.fragment:
+                return SubmissionSignal.UNKNOWN, evidence, reason
+        reason = "response_body"
+        raw = response.raw_body
+        if not isinstance(raw, str) or not 0 < len(raw) <= MAX_PROTOCOL_PAYLOAD_CHARS:
+            return SubmissionSignal.UNKNOWN, evidence, reason
+        data = json.loads(raw, object_pairs_hook=_unique_object)
+        reason = "response_fields"
+        if not isinstance(data, dict) or not {"errorMessage", "url"} <= set(data):
+            return SubmissionSignal.UNKNOWN, evidence, reason
+        error, destination = data["errorMessage"], data["url"]
+        if not isinstance(error, str) or not _text(destination):
+            return SubmissionSignal.UNKNOWN, evidence, reason
+        reason = "response_destination"
+        same_origin_path(urljoin(packet.url, destination))
+        return (SubmissionSignal.REJECTED if error.strip() else SubmissionSignal.ACCEPTED), evidence, "recognized"
+    except Exception:
+        return SubmissionSignal.UNKNOWN, evidence, reason
+
+
+def classify_final_packet(packet: object, target: FinalTarget) -> SubmissionSignal:
+    return inspect_final_packet(packet, target)[0]
+
+
+class NativeFinalSubmitter:
+    """One native click with the existing listener; no navigation/retry/OTP.
+
+    A process-local latch is not a durable task fence. Production reaches this
+    adapter only with explicit final-submit configuration; default pre-final
+    CLIs never call it. The opt-in local evidence gate has its own persistent fence.
+    """
+
+    def __init__(self, page: object, target: FinalTarget, session_is_current: Callable[[], bool]):
+        self.page, self.target, self.session_is_current = page, target, session_is_current
+        self._lock = threading.Lock()
+        self._consumed = False
+        self.submitted_selection: VerifiedSubmission | None = None
+        self.diagnostic = {"requestMatched": False, "reason": "not_observed"}
+
+    def __call__(self) -> SubmissionSignal:
+        with self._lock:
+            if self._consumed:
+                raise FinalBookingError("Italy native final attempt is already consumed")
+            self._consumed = True
+        target = self.target
+
+        def require_context():
+            if (self.session_is_current() is not True or self.page.tab_id != target.tab_id
+                    or same_origin_path(self.page.url)[0] != CALENDAR_PATH):
+                raise FinalBookingError("Italy native final context changed")
+
+        def action():
+            require_context()
+            slot = target.approval.candidate
+            raw = self.page.run_js(
+                NATIVE_FINAL_SCRIPT, target.runtime_service, slot.day.isoformat(),
+                slot.daily_calendar_id, slot.time_label, slot.slots_free,
+            )
+            if raw != {"clicked": True} or type(raw.get("clicked")) is not bool:
+                raise FinalBookingError("Italy native final click was not acknowledged")
+
+        try:
+            require_context()
+            verify_precommit_selection(self.page, runtime_service=target.runtime_service, approval=target.approval)
+            packet = listen_once(self.page, target=FINAL_PATH, method="POST", action=action, timeout=30)
+            signal, self.submitted_selection, reason = inspect_final_packet(packet, target)
+            self.diagnostic = {"requestMatched": self.submitted_selection is not None, "reason": reason}
+            return signal
+        except Exception:
+            # A lost browser acknowledgement can follow a committed write.
+            self.diagnostic = {"requestMatched": False, "reason": "native_or_listener_error"}
+            return SubmissionSignal.UNKNOWN
+
+
+class FinalBookingAttempt:
+    """Single-use orchestration; reconciliation only after a possible write.
+
+    read_reservations must perform a fresh, complete, read-only site read bound
+    to this applicant/session. The real read port accepts only empty/cancelled
+    baselines, then binds new confirmed receipts to a verified native request. submit_native
+    is an injected NativeFinalSubmitter (or an offline test double), not an HTTP
+    replay function. Context checks must work after a same-session redirect.
+    """
+
+    def __init__(
+        self, target: FinalTarget, *, read_reservations: Callable[[], ReservationSnapshot],
+        submit_native: Callable[[], SubmissionSignal], session_is_current: Callable[[], bool],
+    ):
+        if not isinstance(target, FinalTarget) or not all(callable(item) for item in (
+            read_reservations, submit_native, session_is_current,
+        )):
+            raise FinalBookingError("Italy final adapters are required")
+        self.target = target
+        self._read_reservations = read_reservations
+        self._submit_native = submit_native
+        self._session_is_current = session_is_current
+        self._lock = threading.Lock()
+        self._state = "ready"
+        self._signal = SubmissionSignal.UNKNOWN
+        self._before: ReservationSnapshot | None = None
+
+    @property
+    def state(self) -> str:
+        return self._state
+
+    def _require_context(self):
+        if self._session_is_current() is not True:
+            raise FinalBookingError("Italy final applicant or Session changed")
+
+    def _read(self) -> ReservationSnapshot:
+        self._require_context()
+        started = time.monotonic()
+        snapshot = self._read_reservations()
+        self._require_context()
+        now = time.monotonic()
+        if (not isinstance(snapshot, ReservationSnapshot) or snapshot.complete is not True
+                or snapshot.applicant != self.target.applicant or snapshot.session_key != self.target.session_key
+                or type(snapshot.captured_at) not in (int, float) or not started <= snapshot.captured_at <= now
+                or not isinstance(snapshot.records, tuple) or len(snapshot.records) > 512):
+            raise FinalBookingError("Italy reservation snapshot is incomplete or not current")
+        seen = set()
+        for record in snapshot.records:
+            if (not isinstance(record, ReservationRecord) or not _text(record.reference)
+                    or record.reference in seen or type(record.day) is not date
+                    or not _valid_receipt_time(record)
+                    or not isinstance(record.state, ReservationState) or record.state is ReservationState.UNKNOWN):
+                raise FinalBookingError("Italy reservation records require verified identity and status")
+            fingerprint = record.receipt_fingerprint
+            if fingerprint is not None and (not isinstance(fingerprint, str) or
+                                            re.fullmatch(r"[0-9a-f]{64}", fingerprint) is None):
+                raise FinalBookingError("Italy receipt fingerprint is invalid")
+            if record.submission is not None and not self._submitted_binding(record):
+                raise FinalBookingError("Italy receipt submission evidence does not match this attempt")
+            if not _text(record.service_id) and not (
+                    record.service_id is None and fingerprint is not None and
+                    (record.state is ReservationState.CANCELLED or self._submitted_binding(record))):
+                raise FinalBookingError("Italy live reservation service binding is unverified")
+            seen.add(record.reference)
+        return snapshot
+
+    def _submitted_binding(self, record: ReservationRecord) -> bool:
+        slot = self.target.approval.candidate
+        return (self._state in {"submitted", "unknown"} and
+                isinstance(record.submission, VerifiedSubmission) and
+                record.submission.target == self.target and _text(self.target.service_name) and
+                record.state is ReservationState.ACTIVE and record.service_id is None and
+                record.time_label is None and record.receipt_fingerprint is not None and
+                record.day == slot.day and isinstance(record.appointment_time, str) and
+                slot.time_label[:5] <= record.appointment_time <= slot.time_label[-5:])
+
+    def _live(self, snapshot: ReservationSnapshot) -> list[ReservationRecord]:
+        return [record for record in snapshot.records if (record.service_id == self.target.service_id or
+                self._submitted_binding(record))
+                and record.state in {ReservationState.ACTIVE, ReservationState.WAITLIST}]
+
+    def execute(self, *, enabled: bool = False) -> VSBookResult:
+        if enabled is not True:
+            raise FinalBookingError("Italy final submission is disabled")
+        if not self._lock.acquire(blocking=False):
+            raise FinalBookingError("Italy final attempt is already running")
+        try:
+            if self._state != "ready":
+                raise FinalBookingError("Italy final attempt is already consumed")
+            self._state = "checking"
+            try:
+                self._before = self._read()
+                self._require_context()
+            except Exception:
+                self._state = "blocked"
+                raise FinalBookingError("Italy final preflight blocked; no submission attempted") from None
+            if self._live(self._before):
+                self._state = "blocked"
+                raise FinalBookingError("Italy service already has an active reservation or waitlist")
+            self._state = "submitted"
+            try:
+                signal = self._submit_native()
+                self._signal = signal if isinstance(signal, SubmissionSignal) else SubmissionSignal.UNKNOWN
+            except Exception:
+                self._signal = SubmissionSignal.UNKNOWN
+            return self._reconcile()
+        finally:
+            # Ctrl-C/SystemExit must not make a possibly dispatched write look
+            # unattempted, nor make read-only reconciliation impossible.
+            if self._state == "submitted":
+                self._state = "unknown"
+            elif self._state == "checking":
+                self._state = "blocked"
+            self._lock.release()
+
+    def reconcile(self) -> VSBookResult:
+        """One read-only check. Never enters the native submit path."""
+        if not self._lock.acquire(blocking=False):
+            raise FinalBookingError("Italy final attempt is already running")
+        try:
+            if self._state != "unknown":
+                raise FinalBookingError("Italy final attempt does not need reconciliation")
+            return self._reconcile()
+        finally:
+            self._lock.release()
+
+    def _reconcile(self) -> VSBookResult:
+        self._state = "unknown"
+        try:
+            after = self._read()
+            live = self._live(after)
+            before = {record.reference: record for record in self._before.records}
+            after_by_id = {record.reference: record for record in after.records}
+            # Missing/modified history and unrelated new rows make attribution
+            # ambiguous. Do not equate a count increment with this appointment.
+            if any(after_by_id.get(key) != value for key, value in before.items()):
+                raise FinalOutcomeUnknown()
+            new = [record for record in after.records if record.reference not in before]
+            slot = self.target.approval.candidate
+            if (len(new) == 1 and len(live) == 1 and new[0] == live[0]
+                    and live[0].state is ReservationState.ACTIVE and live[0].day == slot.day
+                    and (live[0].time_label == slot.time_label or self._submitted_binding(live[0]))
+                    and self._signal is not SubmissionSignal.REJECTED):
+                self._state = "confirmed"
+                return VSBookResult(
+                    success=True, account=self.target.applicant, urn=live[0].reference,
+                    book_date=slot.day.isoformat(), book_time=live[0].appointment_time or slot.time_label,
+                )
+            if not new and not live and self._signal is SubmissionSignal.REJECTED:
+                self._state = "rejected"
+                return VSBookResult(success=False, label="italy-final-rejected")
+        except Exception:
+            pass
+        self._state = "unknown"
+        raise FinalOutcomeUnknown() from None

+ 761 - 0
plugins/ita_calendar_book.py

@@ -0,0 +1,761 @@
+"""Book-side Calendar response binding and native slot selection.
+
+The caller owns login, route continuity, date preferences and fresh packet
+capture in the applicant's browser. This adapter neither fetches inventory nor
+accepts a Query snapshot. A returned approval is a pre-final checkpoint, never
+permission to submit or evidence of a completed booking.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass, field
+from datetime import date, datetime
+from typing import Callable, Mapping
+
+from plugins.ita_calendar_query import (
+    CALENDAR_PATH,
+    AVAILABILITY_PATH,
+    DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
+    CalendarGateError,
+    CalendarProbeResult,
+    click_next_month,
+    guard_calendar,
+    listen_once,
+    month_text,
+    next_month_value,
+    parse_availability_packet,
+    refresh_calendar,
+    require_plain_nonnegative_int,
+    same_origin_path,
+)
+from plugins.ita_protocol import (
+    CalendarDay,
+    DateSelectionState,
+    ItaProtocolError,
+    PrecommitApproval,
+    SlotCandidate,
+    SlotSelectionState,
+    approve_precommit,
+    available_calendar_days,
+    available_slot_candidates,
+    month_starts,
+    parse_time_slots,
+)
+
+
+TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
+
+RUNTIME_SERVICE_SCRIPT = r"""
+/* coordinate:ita-book-runtime-service */
+const controls = Array.from(document.querySelectorAll('#idServizio'));
+return {
+  path: window.location.pathname,
+  count: controls.length,
+  value: controls.length === 1 ? controls[0].value : null,
+};
+"""
+
+SLOT_SELECTION_SCRIPT = r"""
+/* coordinate:ita-book-slot-selection */
+const [serviceId, day, dailyId, timeLabel, capacity, shouldClick] = arguments;
+const normalize = (text) => String(text || '').replace(/\s+/g, ' ').trim();
+const service = Array.from(document.querySelectorAll('#idServizio'));
+const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
+  window.location.pathname === '/BookingCalendar' &&
+  service.length === 1 && service[0].value === serviceId;
+const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
+const finalGuarded = finalButtons.length === 1 && finalButtons[0].disabled &&
+  finalButtons[0].dataset.coordinateFinalGuard === 'enabled';
+const timeline = Array.from(document.querySelectorAll('.events a.selected'));
+const content = Array.from(document.querySelectorAll('.events-content li.selected'));
+const links = Array.from(document.querySelectorAll('.events a[data-date]'))
+  .filter((element) => element.dataset.date === day);
+const link = links.length === 1 ? links[0] : null;
+const datesMatch = timeline.length === 1 && content.length === 1 &&
+  timeline[0].dataset.date === day && content[0].dataset.date === day;
+const firstSelectedMatches = datesMatch && document.querySelector('.selected') === timeline[0];
+const disabled = (element) => !element || element.hasAttribute('disabled') ||
+  element.getAttribute('aria-disabled') === 'true' ||
+  element.classList.contains('disabled') ||
+  element.classList.contains('input-async-disabilitato');
+const dayNegative = !link || link.classList.contains('notAvailableDay');
+const dayPositive = Boolean(link && link.classList.contains('input-async-abilitato'));
+const inputs = (slot) => slot ? Array.from(slot.querySelectorAll('input')) : [];
+const idMatches = (slot) => {
+  const fields = inputs(slot);
+  return fields.length === 1 && fields[0].type === 'hidden' &&
+    fields[0].id === 'idHiddenFasciaServizio' && fields[0].value === dailyId;
+};
+const timeMatches = (slot) => {
+  const spans = slot ? slot.querySelectorAll('span') : [];
+  return spans.length === 2 && normalize(spans[0].textContent) === timeLabel;
+};
+const capacityMatches = (slot) => {
+  const spans = slot ? slot.querySelectorAll('span') : [];
+  return spans.length === 2 && normalize(spans[1].textContent) === `(${capacity})`;
+};
+const negative = (slot) => !slot || slot.classList.contains('notAvailableFascia');
+const redDot = (slot) => Boolean(slot && slot.querySelector('.dotRed'));
+const actionable = (element) => {
+  if (!element || !element.isConnected || disabled(element)) return false;
+  const style = window.getComputedStyle(element);
+  if (style.display === 'none' || style.visibility === 'hidden' ||
+      style.pointerEvents === 'none' || Number.parseFloat(style.opacity || '1') <= 0) return false;
+  const rect = element.getBoundingClientRect();
+  const left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
+  const top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
+  if (right <= left || bottom <= top) return false;
+  const hit = document.elementFromPoint((left + right) / 2, (top + bottom) / 2);
+  return Boolean(hit && (hit === element || element.contains(hit)));
+};
+const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
+const matches = slots.filter(idMatches);
+const candidate = matches.length === 1 ? matches[0] : null;
+const candidateReady = Boolean(candidate && !negative(candidate) && !redDot(candidate) &&
+  timeMatches(candidate) && capacityMatches(candidate) && actionable(candidate));
+let active = Array.from(document.querySelectorAll('.fascia.act'));
+const alreadyActive = active.length === 1 && active[0] === candidate;
+let clicked = false;
+if (shouldClick === true && runtimeMatches && finalGuarded && datesMatch &&
+    firstSelectedMatches && links.length === 1 && !disabled(link) && !dayNegative &&
+    dayPositive && candidateReady && !alreadyActive) {
+  candidate.click();
+  clicked = true;
+}
+active = Array.from(document.querySelectorAll('.fascia.act'));
+const selected = active.length === 1 ? active[0] : null;
+return {
+  runtimeMatches, finalGuarded, firstSelectedMatches,
+  timelineDays: timeline.map((element) => element.dataset.date || ''),
+  contentDays: content.map((element) => element.dataset.date || ''),
+  matchingDateCount: links.length,
+  dayDisabled: disabled(link), dayNegative, dayPositive,
+  candidateCount: matches.length, candidateReady, clicked,
+  activeCount: active.length,
+  activeIsCandidate: Boolean(selected && selected === candidate),
+  activeUnavailable: negative(selected), activeRedDot: redDot(selected),
+  activeInputCount: inputs(selected).length,
+  activeIdMatches: idMatches(selected),
+  activeDayMatches: Boolean(selected && datesMatch && content[0].contains(selected)),
+  activeTimeMatches: timeMatches(selected),
+  activeCapacityMatches: capacityMatches(selected),
+};
+"""
+
+
+class CalendarBookError(CalendarGateError):
+    """A safe stage error; never includes response bodies or runtime IDs."""
+
+    def __init__(self, message: str, *, http_status: int | None = None):
+        super().__init__(message)
+        self.http_status = http_status
+
+
+class CalendarServiceNotReadyError(CalendarBookError):
+    """The service control stayed empty during a known initialization boundary."""
+
+
+_BOOL_FIELDS = {
+    "runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayDisabled",
+    "dayNegative", "dayPositive", "candidateReady", "clicked",
+    "activeIsCandidate", "activeUnavailable", "activeRedDot", "activeIdMatches",
+    "activeDayMatches", "activeTimeMatches", "activeCapacityMatches",
+}
+_COUNT_FIELDS = {"matchingDateCount", "candidateCount", "activeCount", "activeInputCount"}
+_DATE_FIELDS = {"timelineDays", "contentDays"}
+
+
+def _runtime_id(value: object) -> str:
+    if type(value) is int and value > 0:
+        return str(value)
+    if isinstance(value, str) and value and value == value.strip() and len(value) <= 128:
+        return value
+    raise CalendarBookError("Book runtime service identifier was invalid")
+
+
+def _read_calendar_service_value(page: object) -> str:
+    path, _ = same_origin_path(page.url)
+    if path != CALENDAR_PATH:
+        raise CalendarBookError("Book selection requires the current Calendar page")
+    raw = page.run_js(RUNTIME_SERVICE_SCRIPT)
+    if not isinstance(raw, dict) or set(raw) != {"path", "count", "value"}:
+        raise CalendarBookError("Book Calendar runtime context changed")
+    if raw["path"] != CALENDAR_PATH or type(raw["count"]) is not int or raw["count"] != 1:
+        raise CalendarBookError("Book Calendar requires one runtime service control")
+    if not isinstance(raw["value"], str):
+        raise CalendarBookError("Book Calendar runtime service control has no value")
+    return raw["value"]
+
+
+def read_calendar_service(page: object) -> str:
+    """Strict read for stable phases; empty values are never a valid identity."""
+    return _runtime_id(_read_calendar_service_value(page))
+
+
+def wait_for_calendar_service(
+    page: object, *, session_is_current: Callable[[], bool],
+    expected_service: str | None = None, timeout: float = 5,
+) -> str:
+    """Await the site's field assignment without requesting or retrying anything.
+
+    Call only after AVANTI or native Calendar loading. Stable-phase checks stay
+    strict: only an exactly empty string is pending, not malformed identities,
+    missing/duplicate controls, another service, or a changed applicant/tab.
+    The deadline bounds polling; browser transport failures propagate normally.
+    """
+    if type(timeout) not in (int, float) or not 0 <= timeout < float("inf"):
+        raise CalendarBookError("Book Calendar readiness timeout must be finite and nonnegative")
+    if not callable(session_is_current):
+        raise CalendarBookError("Book Calendar readiness requires a Session check")
+    if expected_service is not None:
+        expected_service = _runtime_id(expected_service)
+    tab_id = getattr(page, "tab_id", None)
+    if not isinstance(tab_id, str) or not tab_id:
+        raise CalendarBookError("Book Calendar tab identity was unavailable")
+    deadline = time.monotonic() + timeout
+
+    def require_session() -> None:
+        if session_is_current() is not True or getattr(page, "tab_id", None) != tab_id:
+            raise CalendarBookError("Book applicant, route or browser Session changed")
+        if same_origin_path(page.url)[0] != CALENDAR_PATH:
+            raise CalendarBookError("Book readiness left the current Calendar page")
+
+    while True:
+        require_session()
+        guard_calendar(page)
+        value = _read_calendar_service_value(page)
+        require_session()
+        if value != "":
+            service = _runtime_id(value)
+            if expected_service is not None and service != expected_service:
+                raise CalendarBookError("Book Calendar runtime service changed")
+            return service
+        remaining = deadline - time.monotonic()
+        if remaining <= 0:
+            raise CalendarServiceNotReadyError("Book Calendar service did not initialize before timeout")
+        time.sleep(min(0.1, remaining))
+
+
+def _request_day(value: object) -> date:
+    if isinstance(value, str):
+        for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
+            try:
+                return datetime.strptime(value, date_format).date()
+            except ValueError:
+                pass
+    raise CalendarBookError("Book TimeSlots request date format changed")
+
+
+def parse_book_time_slots(
+    packet: object, *, target_day: date, runtime_service_id: str,
+) -> tuple[SlotCandidate, ...]:
+    """Bind TimeSlots metadata to the selected day and current DOM service."""
+    try:
+        path, _ = same_origin_path(packet.url)
+        if str(packet.method).upper() != "POST" or path != TIME_SLOTS_PATH:
+            raise CalendarBookError("Book TimeSlots request method or path changed")
+        if type(packet.response.status) is not int or packet.response.status != 200:
+            raise CalendarBookError(
+                "Book TimeSlots response status was not 200",
+                http_status=packet.response.status if type(packet.response.status) is int else None,
+            )
+        body = packet.request.postData
+        if isinstance(body, str):
+            body = json.loads(body)
+        if not isinstance(body, dict) or set(body) != {"selectedDay", "idService"}:
+            raise CalendarBookError("Book TimeSlots request fields changed")
+        if _runtime_id(body["idService"]) != runtime_service_id:
+            raise CalendarBookError("Book TimeSlots request does not match the current service")
+        if _request_day(body["selectedDay"]) != target_day:
+            raise CalendarBookError("Book TimeSlots request does not match the target day")
+        candidates = parse_time_slots(packet.response.raw_body)
+        if any(item.day != target_day for item in candidates):
+            raise CalendarBookError("Book TimeSlots response contains another day")
+        return candidates
+    except CalendarBookError:
+        raise
+    except ItaProtocolError as exc:
+        raise CalendarBookError(f"Book TimeSlots protocol rejected ({exc.code})") from None
+    except Exception:
+        raise CalendarBookError("Book TimeSlots packet could not be validated") from None
+
+
+def _snapshot(page: object, service: str, target: date, candidate: SlotCandidate, *, click: bool) -> dict:
+    raw = page.run_js(
+        SLOT_SELECTION_SCRIPT, service, target.isoformat(), candidate.daily_calendar_id,
+        candidate.time_label, candidate.slots_free, click,
+    )
+    if not isinstance(raw, dict) or set(raw) != _BOOL_FIELDS | _COUNT_FIELDS | _DATE_FIELDS:
+        raise CalendarBookError("Book slot snapshot fields changed")
+    if any(type(raw[key]) is not bool for key in _BOOL_FIELDS):
+        raise CalendarBookError("Book slot snapshot boolean types changed")
+    for key in _COUNT_FIELDS:
+        require_plain_nonnegative_int(raw[key], key)
+    for key in _DATE_FIELDS:
+        if not isinstance(raw[key], list) or any(not isinstance(item, str) for item in raw[key]):
+            raise CalendarBookError("Book selected-date snapshot types changed")
+    return raw
+
+
+def _require_ready(raw: dict, target_day: date) -> None:
+    positive = ("runtimeMatches", "finalGuarded", "firstSelectedMatches", "dayPositive", "candidateReady")
+    if any(raw[key] is not True for key in positive):
+        raise CalendarBookError("Book candidate is not safely selectable")
+    if raw["dayDisabled"] or raw["dayNegative"]:
+        raise CalendarBookError("Book selected day is marked unavailable")
+    if raw["matchingDateCount"] != 1 or raw["candidateCount"] != 1:
+        raise CalendarBookError("Book date or slot is not unique")
+    expected = [target_day.isoformat()]
+    if raw["timelineDays"] != expected or raw["contentDays"] != expected:
+        raise CalendarBookError("Book timeline and content dates do not match the target")
+
+
+def _approve_selection_snapshot(
+    calendar_day: CalendarDay, candidate: SlotCandidate, raw: dict,
+) -> PrecommitApproval:
+    _require_ready(raw, candidate.day)
+    if raw["clicked"]:
+        raise CalendarBookError("Book readback unexpectedly clicked")
+    return approve_precommit(
+        calendar_day, candidate,
+        DateSelectionState(
+            planned_day=candidate.day, matching_availability_count=1,
+            timeline_selected_days=tuple(date.fromisoformat(item) for item in raw["timelineDays"]),
+            content_selected_days=tuple(date.fromisoformat(item) for item in raw["contentDays"]),
+            day_disabled=raw["dayDisabled"], day_not_available=raw["dayNegative"],
+            day_has_positive_state=raw["dayPositive"],
+        ),
+        SlotSelectionState(
+            active_slot_count=raw["activeCount"], active_is_candidate=raw["activeIsCandidate"],
+            active_has_unavailable_class=raw["activeUnavailable"], active_has_red_dot=raw["activeRedDot"],
+            active_hidden_input_count=raw["activeInputCount"],
+            active_daily_id_matches_candidate=raw["activeIdMatches"],
+            active_day_matches_candidate=raw["activeDayMatches"],
+            active_time_matches_candidate=raw["activeTimeMatches"],
+            active_capacity_matches_candidate=raw["activeCapacityMatches"],
+        ),
+    )
+
+
+def verify_precommit_selection(
+    page: object, *, runtime_service: str, approval: PrecommitApproval,
+) -> PrecommitApproval:
+    """Read the current selected slot; never select, refresh, or submit anything.
+
+    The caller still owns applicant/session binding and freshness of the Book
+    inventory. This is a consistency check, not a reservation or inventory lock.
+    """
+    if not isinstance(approval, PrecommitApproval):
+        raise CalendarBookError("Book selection requires a precommit approval")
+    try:
+        if read_calendar_service(page) != runtime_service:
+            raise CalendarBookError("Book Calendar runtime service changed")
+        raw = _snapshot(page, runtime_service, approval.candidate.day, approval.candidate, click=False)
+        return _approve_selection_snapshot(approval.calendar_day, approval.candidate, raw)
+    except CalendarBookError:
+        raise
+    except Exception:
+        raise CalendarBookError("Book precommit readback failed") from None
+
+
+def select_slot_before_final(
+    page: object, *, target_day: date, availability_packet: object, time_slots_packet: object,
+) -> PrecommitApproval | None:
+    """Select one positive slot from caller-captured Book packets; never submit.
+
+    Both packets must be fresh captures from this page. Their content alone
+    cannot prove capture time, applicant identity or route continuity. The
+    orchestrator must establish these preconditions before calling this method.
+    """
+    if type(target_day) is not date:
+        raise CalendarBookError("Book target day must be a date")
+    try:
+        service = read_calendar_service(page)
+        guard_calendar(page)
+        try:
+            probe = parse_availability_packet(availability_packet)
+            if probe.selected_month != (target_day.year, target_day.month):
+                raise CalendarBookError("Book Availability belongs to another month")
+            slots = parse_book_time_slots(
+                time_slots_packet, target_day=target_day, runtime_service_id=service,
+            )
+            days = [item for item in probe.days if item.day == target_day]
+            candidates = available_slot_candidates(slots, start_day=target_day, end_day=target_day)
+            if not days or not days[0].is_available:
+                if candidates:
+                    raise CalendarBookError("Book Availability and TimeSlots disagree")
+                return None
+            if not candidates:
+                return None
+            candidate = candidates[0]
+            before = _snapshot(page, service, target_day, candidate, click=False)
+            _require_ready(before, target_day)
+            if before["clicked"]:
+                raise CalendarBookError("Book read-only snapshot unexpectedly clicked")
+            if not (before["activeCount"] == 1 and before["activeIsCandidate"]):
+                acted = _snapshot(page, service, target_day, candidate, click=True)
+                _require_ready(acted, target_day)
+                if not acted["clicked"]:
+                    raise CalendarBookError("Book slot click was not acknowledged")
+            after = _snapshot(page, service, target_day, candidate, click=False)
+            return _approve_selection_snapshot(days[0], candidate, after)
+        finally:
+            guard_calendar(page)
+    except CalendarBookError:
+        raise
+    except ItaProtocolError as exc:
+        raise CalendarBookError(f"Book precommit rejected ({exc.code})") from None
+    except Exception:
+        raise CalendarBookError("Book Calendar selection or final guard failed") from None
+
+
+DATE_SELECTION_SCRIPT = r"""
+/* coordinate:ita-book-date-selection */
+const [serviceId, day, shouldClick] = arguments;
+const services = Array.from(document.querySelectorAll('#idServizio'));
+const runtimeMatches = window.location.origin === 'https://prenotami.esteri.it' &&
+  window.location.pathname === '/BookingCalendar' && services.length === 1 &&
+  services[0].value === serviceId;
+const buttons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
+const finalGuarded = buttons.length === 1 && buttons[0].disabled === true &&
+  buttons[0].dataset.coordinateFinalGuard === 'enabled';
+const candidates = Array.from(document.querySelectorAll('.events a[data-date]'))
+  .filter((link) => link.dataset.date === day);
+const link = candidates.length === 1 ? candidates[0] : null;
+const enabled = (element) => {
+  if (!element || !element.isConnected || element.hasAttribute('disabled') ||
+      element.getAttribute('aria-disabled') === 'true' ||
+      element.classList.contains('disabled') || element.classList.contains('notAvailableDay') ||
+      element.classList.contains('input-async-disabilitato') ||
+      !element.classList.contains('input-async-abilitato')) return false;
+  const style = window.getComputedStyle(element);
+  // Calendar timeline links can have zero layout size while logically enabled.
+  // The site's initialization uses HTMLElement.click(), as we do here, rather
+  // than a pointer hit. Keep disabled/style checks and response/date readback;
+  // do not require a clickable rectangle for this native date action.
+  return style.display !== 'none' && style.visibility !== 'hidden' &&
+    style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0;
+};
+const timeline = Array.from(document.querySelectorAll('.events a.selected'));
+const content = Array.from(document.querySelectorAll('.events-content li.selected'));
+const selectedMatches = timeline.length === 1 && content.length === 1 &&
+  timeline[0].dataset.date === day && content[0].dataset.date === day &&
+  document.querySelector('.selected') === timeline[0];
+const candidateEnabled = enabled(link);
+let clicked = false;
+if (shouldClick === true && runtimeMatches && finalGuarded && candidateEnabled && !selectedMatches) {
+  link.click();
+  clicked = true;
+}
+return {runtimeMatches, finalGuarded, candidateCount: candidates.length,
+        candidateEnabled, selectedMatches, clicked};
+"""
+
+
+@dataclass(frozen=True, slots=True)
+class _CapturedMonth:
+    probe: CalendarProbeResult
+    availability_packet: object = field(repr=False)
+    availability_service: str = field(repr=False)
+    automatic_day: date | None = None
+    automatic_slots_packet: object | None = field(default=None, repr=False)
+
+
+def book_date_preferences(user_inputs: Mapping[str, object]) -> tuple[date, date]:
+    """Use the VFS preference keys and inclusive bounds without mutating inputs."""
+    if not isinstance(user_inputs, Mapping):
+        raise CalendarBookError("Book user inputs must be a mapping")
+    dates = []
+    for key, default in (("expected_start_date", "2000-01-01"),
+                         ("expected_end_date", "2100-01-01")):
+        value = user_inputs.get(key, default)
+        try:
+            parsed = date.fromisoformat(value) if isinstance(value, str) else None
+        except ValueError:
+            parsed = None
+        if parsed is None or parsed.isoformat() != value:
+            raise CalendarBookError(f"Book {key} must use YYYY-MM-DD")
+        dates.append(parsed)
+    if dates[0] > dates[1]:
+        raise CalendarBookError("Book date preference start exceeds end")
+    return dates[0], dates[1]
+
+
+def _require_context(page: object, service: str, session_is_current: Callable[[], bool]) -> None:
+    if session_is_current() is not True:
+        raise CalendarBookError("Book applicant, route or browser Session changed")
+    if read_calendar_service(page) != service:
+        raise CalendarBookError("Book Calendar runtime service changed")
+    guard_calendar(page)
+
+
+def _require_packet_tab(page: object, packet: object) -> None:
+    tab = getattr(page, "tab_id", None)
+    if not isinstance(tab, str) or not tab or getattr(packet, "tab_id", None) != tab:
+        raise CalendarBookError("Book response did not belong to the current browser tab")
+    if getattr(packet, "is_failed", False) is not False:
+        raise CalendarBookError("Book browser request failed")
+
+
+def _post_body(packet: object) -> dict:
+    body = packet.request.postData
+    if isinstance(body, str):
+        body = json.loads(body)
+    if not isinstance(body, dict):
+        raise CalendarBookError("Book request body was not an object")
+    return body
+
+
+def _date_snapshot(page: object, service: str, day: date, *, click: bool = False) -> dict:
+    raw = page.run_js(DATE_SELECTION_SCRIPT, service, day.isoformat(), click)
+    boolean_keys = {"runtimeMatches", "finalGuarded", "candidateEnabled", "selectedMatches", "clicked"}
+    if not isinstance(raw, dict) or set(raw) != boolean_keys | {"candidateCount"}:
+        raise CalendarBookError("Book date control structure changed")
+    if any(type(raw[key]) is not bool for key in boolean_keys):
+        raise CalendarBookError("Book date control types changed")
+    require_plain_nonnegative_int(raw["candidateCount"], "candidateCount")
+    if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
+        raise CalendarBookError("Book date control context was not unique and guarded")
+    if not click and raw["clicked"]:
+        raise CalendarBookError("Book date readback unexpectedly clicked")
+    return raw
+
+
+def _wait_selected_day(page: object, service: str, day: date, *, timeout: float) -> None:
+    deadline = time.monotonic() + timeout
+    while True:
+        raw = _date_snapshot(page, service, day)
+        if raw["candidateCount"] == 1 and raw["selectedMatches"]:
+            return
+        if time.monotonic() >= deadline:
+            raise CalendarBookError("Book selected date did not match the response before timeout")
+        time.sleep(0.1)
+
+
+def _click_date(page: object, service: str, day: date, *, timeout: float) -> None:
+    deadline = time.monotonic() + timeout
+    while True:
+        raw = _date_snapshot(page, service, day)
+        if raw["selectedMatches"]:
+            raise CalendarBookError("Book date is already selected without a fresh captured response")
+        if raw["candidateCount"] == 1 and raw["candidateEnabled"]:
+            break
+        if time.monotonic() >= deadline:
+            raise CalendarBookError("Book date control was not ready before timeout")
+        time.sleep(0.1)
+    acted = _date_snapshot(page, service, day, click=True)
+    if not acted["clicked"]:
+        raise CalendarBookError("Book date click was not acknowledged")
+
+
+def _capture_month(
+    page: object, *, action: Callable[[], None], service: str,
+    session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
+    previous: _CapturedMonth | None = None,
+) -> _CapturedMonth:
+    """Capture Availability plus the site's automatic first-day TimeSlots."""
+    _require_context(page, service, session_is_current)
+    page.listen.start([AVAILABILITY_PATH, TIME_SLOTS_PATH], method="POST")
+    try:
+        action()
+        wait_for_calendar_service(
+            page, session_is_current=session_is_current,
+            expected_service=service, timeout=min(dom_timeout, timeout),
+        )
+        _require_context(page, service, session_is_current)
+        deadline = time.monotonic() + timeout
+        captured = {}
+        probe = None
+        # Only two matching responses belong to one normal month-load action.
+        for _ in range(2):
+            remaining = deadline - time.monotonic()
+            if remaining <= 0:
+                raise CalendarBookError("Book month responses exceeded the time budget")
+            packet = page.listen.wait(timeout=remaining, raise_err=False)
+            if not packet:
+                raise CalendarBookError("Book month response was not observed before timeout")
+            _require_packet_tab(page, packet)
+            status = packet.response.status
+            if type(status) is not int or status != 200:
+                raise CalendarBookError("Book Calendar response status was not 200",
+                                        http_status=status if type(status) is int else None)
+            path, _ = same_origin_path(packet.url)
+            if path not in {AVAILABILITY_PATH, TIME_SLOTS_PATH} or path in captured:
+                raise CalendarBookError("Book month produced an unexpected or duplicate response")
+            captured[path] = packet
+            if path == AVAILABILITY_PATH:
+                probe = parse_availability_packet(packet)
+                if previous and probe.selected_month != next_month_value(previous.probe.selected_month):
+                    raise CalendarBookError("Book Calendar did not advance exactly one month")
+                if not probe.days or TIME_SLOTS_PATH in captured:
+                    break
+            elif probe is not None:
+                break
+        if probe is None:
+            raise CalendarBookError("Book month did not return Availability")
+        availability_packet = captured[AVAILABILITY_PATH]
+        availability_service = _runtime_id(_post_body(availability_packet).get("_Servizio"))
+        if previous and availability_service != previous.availability_service:
+            raise CalendarBookError("Book Availability runtime service changed")
+        automatic = captured.get(TIME_SLOTS_PATH)
+        automatic_day = None
+        if probe.days:
+            if automatic is None:
+                raise CalendarBookError("Book automatic day response was not captured")
+            automatic_day = _request_day(_post_body(automatic).get("selectedDay"))
+            if automatic_day not in {item.day for item in probe.days}:
+                raise CalendarBookError("Book automatic day escaped current Availability")
+            auto_slots = parse_book_time_slots(automatic, target_day=automatic_day, runtime_service_id=service)
+            auto_inventory = next(item for item in probe.days if item.day == automatic_day)
+            if not auto_inventory.is_available and available_slot_candidates(auto_slots):
+                raise CalendarBookError("Book automatic Availability and TimeSlots disagree")
+            _wait_selected_day(page, service, automatic_day, timeout=dom_timeout)
+        elif automatic is not None:
+            raise CalendarBookError("Book empty Availability unexpectedly returned TimeSlots")
+        _require_context(page, service, session_is_current)
+        return _CapturedMonth(probe, availability_packet, availability_service, automatic_day, automatic)
+    finally:
+        page.listen.stop()
+
+
+def _try_day(
+    page: object, month: _CapturedMonth, day: date, *, service: str,
+    session_is_current: Callable[[], bool], timeout: float, dom_timeout: float,
+) -> PrecommitApproval | None:
+    _require_context(page, service, session_is_current)
+    current_date = _date_snapshot(page, service, day)
+    if day == month.automatic_day and current_date["selectedMatches"]:
+        times_packet = month.automatic_slots_packet
+        _wait_selected_day(page, service, day, timeout=dom_timeout)
+    else:
+        times_packet = listen_once(
+            page, target=TIME_SLOTS_PATH, method="POST",
+            action=lambda: _click_date(page, service, day, timeout=dom_timeout),
+            timeout=timeout,
+        )
+        _require_packet_tab(page, times_packet)
+        parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
+        _wait_selected_day(page, service, day, timeout=dom_timeout)
+    slots = parse_book_time_slots(times_packet, target_day=day, runtime_service_id=service)
+    candidates = available_slot_candidates(slots, start_day=day, end_day=day)
+    if not candidates:
+        # Inventory competition is not a protocol error. No slot was clicked.
+        _require_context(page, service, session_is_current)
+        return None
+    deadline = time.monotonic() + dom_timeout
+    while True:
+        _require_context(page, service, session_is_current)
+        raw = _snapshot(page, service, day, candidates[0], click=False)
+        if not raw["runtimeMatches"] or not raw["finalGuarded"] or raw["candidateCount"] > 1:
+            raise CalendarBookError("Book slot DOM changed its context or uniqueness")
+        if raw["candidateReady"]:
+            _require_ready(raw, day)
+            break
+        if time.monotonic() >= deadline:
+            raise CalendarBookError("Book slot DOM did not match the response before timeout")
+        time.sleep(0.1)
+    approval = select_slot_before_final(
+        page, target_day=day, availability_packet=month.availability_packet,
+        time_slots_packet=times_packet,
+    )
+    _require_context(page, service, session_is_current)
+    return approval
+
+
+def recheck_calendar_before_final(
+    page: object, *, lookahead_months: int, start_day: date, end_day: date,
+    session_is_current: Callable[[], bool], preferred_day: date | None = None,
+    month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
+    timeout: float = 30, dom_timeout: float = 5,
+    log: Callable[[str], None] | None = None,
+) -> PrecommitApproval | None:
+    """Fresh Book-only scan with an optional date hint; never submit a booking.
+
+    There are at most two bounded passes: the hinted day, then an ascending
+    fallback. The caller must attest the prepared applicant/route Session via
+    session_is_current. No external snapshot or cached response is accepted.
+    """
+    try:
+        # Use existing pure validators before starting any browser action.
+        month_starts(date(2000, 1, 1), lookahead_months)
+        if type(start_day) is not date or type(end_day) is not date:
+            raise CalendarBookError("Book date bounds must be dates")
+        available_calendar_days((), start_day=start_day, end_day=end_day)
+        if preferred_day is not None and type(preferred_day) is not date:
+            raise CalendarBookError("Book preferred day must be a date")
+        for value in (timeout, dom_timeout, month_click_interval_seconds):
+            if type(value) not in (int, float) or not 0 <= value < float("inf"):
+                raise CalendarBookError("Book time budget must be finite and nonnegative")
+        if timeout == 0 or not callable(session_is_current):
+            raise CalendarBookError("Book requires a positive timeout and a Session check")
+        service = read_calendar_service(page)
+        _require_context(page, service, session_is_current)
+        common = dict(service=service, session_is_current=session_is_current,
+                      timeout=timeout, dom_timeout=dom_timeout)
+
+        def initial() -> _CapturedMonth:
+            return _capture_month(page, action=lambda: refresh_calendar(page), **common)
+
+        def advance(previous: _CapturedMonth) -> _CapturedMonth:
+            if month_click_interval_seconds:
+                time.sleep(month_click_interval_seconds)
+            return _capture_month(page, action=lambda: click_next_month(page), previous=previous, **common)
+
+        def positive_days(month: _CapturedMonth) -> tuple:
+            return available_calendar_days(month.probe.days, start_day=start_day, end_day=end_day)
+
+        first = initial()
+        anchor = first.probe.selected_month
+        current = first
+        attempted = set()
+        if preferred_day is not None and start_day <= preferred_day <= end_day:
+            offset = (preferred_day.year - anchor[0]) * 12 + preferred_day.month - anchor[1]
+            if 0 <= offset < lookahead_months:
+                for _ in range(offset):
+                    current = advance(current)
+                if preferred_day in {item.day for item in positive_days(current)}:
+                    attempted.add(preferred_day)
+                    approval = _try_day(page, current, preferred_day, **common)
+                    if approval is not None:
+                        return approval
+                # A failed hint cannot cause a stale earlier month's response
+                # to be reused. Restart the native scan once and recapture.
+                first = initial()
+                if (first.probe.selected_month != anchor or
+                        first.availability_service != current.availability_service):
+                    raise CalendarBookError("Book fallback restart changed the Calendar anchor")
+
+        current = first
+        for index in range(lookahead_months):
+            if current.probe.selected_month > (end_day.year, end_day.month):
+                return None
+            days = positive_days(current)
+            if log:
+                log(f"Italy Book Calendar month={month_text(current.probe.selected_month)} candidates={len(days)}")
+            for item in days:
+                if item.day in attempted:
+                    continue
+                attempted.add(item.day)
+                approval = _try_day(page, current, item.day, **common)
+                if approval is not None:
+                    return approval
+            if current.probe.selected_month >= (end_day.year, end_day.month):
+                return None
+            if index + 1 < lookahead_months:
+                current = advance(current)
+        return None
+    except CalendarBookError:
+        raise
+    except ItaProtocolError as exc:
+        raise CalendarBookError(f"Book Calendar protocol rejected ({exc.code})") from None
+    except Exception:
+        raise CalendarBookError("Book Calendar recheck failed; no further action was attempted") from None
+    finally:
+        # Do not leave the final button enabled after a native refresh or error.
+        try:
+            if same_origin_path(page.url)[0] == CALENDAR_PATH:
+                guard_calendar(page)
+        except Exception:
+            raise CalendarBookError("Book final-button guard could not be verified") from None

+ 607 - 0
plugins/ita_calendar_query.py

@@ -0,0 +1,607 @@
+"""Shared browser adapter for read-only Prenot@Mi Calendar queries.
+
+The pure wire-format rules live in :mod:`plugins.ita_protocol`.  This module
+owns only the browser-facing mechanics that production Query and the Q-CAL
+diagnostic tool must share: one-shot listeners, strict packet metadata,
+native month navigation, the final-button guard, and bounded scanning.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from dataclasses import dataclass
+from datetime import date, datetime
+from typing import Any, Callable
+from urllib.parse import urljoin, urlparse
+
+from plugins.ita_protocol import (
+    CalendarDay,
+    ItaProtocolError,
+    available_calendar_days,
+    parse_calendar_availability,
+)
+
+
+CALENDAR_PATH = "/BookingCalendar"
+AVAILABILITY_PATH = "/BookingCalendar/RetrieveCalendarAvailability"
+MAX_QUERY_LOOKAHEAD_MONTHS = 120
+DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
+
+
+CALENDAR_GUARD_SCRIPT = r"""
+/* coordinate:ita-calendar-query-final-guard */
+const finalButtons = Array.from(
+  document.querySelectorAll('#btnPrenotaNoOtp')
+);
+finalButtons.forEach((button) => {
+  button.disabled = true;
+  button.setAttribute('aria-disabled', 'true');
+  button.dataset.coordinateFinalGuard = 'enabled';
+});
+const resources = performance.getEntriesByType('resource');
+return {
+  path: window.location.pathname,
+  calendarFunctionPresent:
+    typeof window.CaricaTimelineOrizzontale === 'function',
+  finalButtonCount: finalButtons.length,
+  allFinalButtonsGuarded: finalButtons.every(
+    (button) => button.disabled &&
+      button.dataset.coordinateFinalGuard === 'enabled'
+  ),
+  finalRequestCount: resources.filter(
+    (entry) => entry.name.includes(
+      '/BookingCalendar/InsertNewBooking'
+    )
+  ).length,
+  timeSlotRequestCount: resources.filter(
+    (entry) => entry.name.includes(
+      '/BookingCalendar/RetrieveTimeSlots'
+    )
+  ).length,
+};
+"""
+
+
+NEXT_MONTH_CONTROL_SCRIPT = r"""
+/* coordinate:ita-calendar-query-next-month */
+const shouldClick = arguments[0] === true;
+const selector = '#datetimepicker th.dtpicker-next';
+const candidates = Array.from(document.querySelectorAll(selector));
+const isActionable = (element) => {
+  if (
+    !element.isConnected ||
+    element.hasAttribute('disabled') ||
+    element.getAttribute('aria-disabled') === 'true'
+  ) {
+    return false;
+  }
+  const style = window.getComputedStyle(element);
+  if (
+    style.display === 'none' ||
+    style.visibility === 'hidden' ||
+    style.pointerEvents === 'none' ||
+    Number.parseFloat(style.opacity || '1') <= 0
+  ) {
+    return false;
+  }
+  const rect = element.getBoundingClientRect();
+  const left = Math.max(0, rect.left);
+  const right = Math.min(window.innerWidth, rect.right);
+  const top = Math.max(0, rect.top);
+  const bottom = Math.min(window.innerHeight, rect.bottom);
+  if (right <= left || bottom <= top) return false;
+  const topNode = document.elementFromPoint(
+    (left + right) / 2,
+    (top + bottom) / 2
+  );
+  return Boolean(topNode && (
+    topNode === element || element.contains(topNode)
+  ));
+};
+const actionable = candidates.filter(isActionable);
+let clicked = false;
+if (shouldClick && actionable.length === 1) {
+  clicked = true;
+  actionable[0].click();
+}
+return {
+  pathMatches: window.location.pathname === '/BookingCalendar',
+  candidateCount: candidates.length,
+  actionableCount: actionable.length,
+  clicked,
+};
+"""
+
+
+class CalendarGateError(RuntimeError):
+    """Fail-closed Calendar adapter error without sensitive response data."""
+
+
+class CalendarAuthenticationExpiredError(CalendarGateError):
+    """An observed response explicitly rejected the authenticated session."""
+
+
+class CalendarRateLimitedError(CalendarGateError):
+    """The server explicitly limited requests; callers must not rotate accounts."""
+
+
+class CalendarAccessDeniedError(CalendarGateError):
+    """Permission or browser verification requires operator attention."""
+
+
+class CalendarTransientError(CalendarGateError):
+    """A read failed without evidence that authentication or schema changed."""
+
+
+class CalendarNextMonthUnavailableError(CalendarGateError):
+    """Raised when the native next-month control cannot be used safely."""
+
+
+def require_plain_nonnegative_int(value: object, name: str) -> int:
+    if isinstance(value, bool) or not isinstance(value, int) or value < 0:
+        raise CalendarGateError(f"{name} must be a nonnegative integer")
+    return value
+
+
+def same_origin_path(raw_url: object) -> tuple[str, object]:
+    parsed = urlparse(str(raw_url or ""))
+    try:
+        port = parsed.port
+    except ValueError as exc:
+        raise CalendarGateError(
+            "Observed request used an unexpected origin"
+        ) from exc
+    if (
+        parsed.scheme != "https"
+        or parsed.hostname != "prenotami.esteri.it"
+        or port not in (None, 443)
+        or parsed.username is not None
+        or parsed.password is not None
+    ):
+        raise CalendarGateError("Observed request used an unexpected origin")
+    return parsed.path, parsed
+
+
+def header_value(headers: object, name: str) -> str:
+    if not hasattr(headers, "items"):
+        return ""
+    for key, value in headers.items():
+        if str(key).casefold() == name.casefold():
+            return str(value)
+    return ""
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarProbeResult:
+    days: tuple[CalendarDay, ...]
+    selected_day: str
+
+    def __post_init__(self) -> None:
+        if not isinstance(self.selected_day, str) or not self.selected_day.strip():
+            raise CalendarGateError("selected_day must be a non-empty string")
+        if any(not isinstance(item, CalendarDay) for item in self.days):
+            raise CalendarGateError("days must contain CalendarDay values")
+        selected_month = self.selected_month
+        if any(
+            (item.day.year, item.day.month) != selected_month
+            for item in self.days
+        ):
+            raise CalendarGateError(
+                "Availability response escaped the requested month"
+            )
+
+    @property
+    def item_count(self) -> int:
+        return len(self.days)
+
+    @property
+    def available_days(self) -> tuple[CalendarDay, ...]:
+        return available_calendar_days(self.days)
+
+    @property
+    def available_count(self) -> int:
+        return len(self.available_days)
+
+    @property
+    def selected_month(self) -> tuple[int, int]:
+        value = self.selected_day.strip()[:10]
+        for date_format in ("%Y-%m-%d", "%d/%m/%Y"):
+            try:
+                parsed = datetime.strptime(value, date_format)
+            except ValueError:
+                continue
+            return parsed.year, parsed.month
+        raise CalendarGateError(
+            "Availability selectedDay used an unknown date format"
+        )
+
+
+def next_month_value(value: tuple[int, int]) -> tuple[int, int]:
+    year, month = value
+    return (year + 1, 1) if month == 12 else (year, month + 1)
+
+
+def month_text(value: tuple[int, int]) -> str:
+    return f"{value[0]:04d}-{value[1]:02d}"
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarQueryScanResult:
+    """Result of scanning until the first positive month or the horizon end."""
+
+    probes: tuple[CalendarProbeResult, ...]
+    lookahead_months: int
+    stop_reason: str
+
+    def __post_init__(self) -> None:
+        _validate_lookahead_months(self.lookahead_months)
+        if not self.probes or any(
+            not isinstance(probe, CalendarProbeResult)
+            for probe in self.probes
+        ):
+            raise CalendarGateError(
+                "Calendar query scan requires parsed probe results"
+            )
+        if len(self.probes) > self.lookahead_months:
+            raise CalendarGateError(
+                "Calendar query scan exceeded the configured horizon"
+            )
+        for previous, current in zip(self.probes, self.probes[1:]):
+            if current.selected_month != next_month_value(
+                previous.selected_month
+            ):
+                raise CalendarGateError(
+                    "Calendar request did not advance exactly one month"
+                )
+
+        if self.stop_reason == "first_available_month":
+            if self.probes[-1].available_count == 0:
+                raise CalendarGateError(
+                    "first-available stop requires a positive final probe"
+                )
+            if any(probe.available_count for probe in self.probes[:-1]):
+                raise CalendarGateError(
+                    "Calendar query scanned beyond the first positive month"
+                )
+        elif self.stop_reason == "horizon_exhausted":
+            if len(self.probes) != self.lookahead_months:
+                raise CalendarGateError(
+                    "Calendar query ended before the configured horizon"
+                )
+            if any(probe.available_count for probe in self.probes):
+                raise CalendarGateError(
+                    "Calendar query ignored a positive month"
+                )
+        else:
+            raise CalendarGateError(
+                "Calendar query scan used an unknown stop reason"
+            )
+
+    @property
+    def scanned_months(self) -> int:
+        return len(self.probes)
+
+    @property
+    def available_days(self) -> tuple[CalendarDay, ...]:
+        if self.stop_reason != "first_available_month":
+            return ()
+        return self.probes[-1].available_days
+
+    @property
+    def earliest_available_date(self) -> date | None:
+        return (
+            self.available_days[0].day
+            if self.available_days
+            else None
+        )
+
+
+def _validate_lookahead_months(value: object) -> int:
+    if (
+        isinstance(value, bool)
+        or not isinstance(value, int)
+        or not 1 <= value <= MAX_QUERY_LOOKAHEAD_MONTHS
+    ):
+        raise CalendarGateError(
+            "lookahead_months must be between 1 and 120"
+        )
+    return value
+
+
+def listen_once(
+    page: object,
+    *,
+    target: str,
+    method: str,
+    action: Callable[[], Any],
+    timeout: float,
+) -> object:
+    """Listen around one native action and always stop the listener."""
+
+    page.listen.start(target, method=method)
+    try:
+        action()
+        packet = page.listen.wait(timeout=timeout)
+        if not packet:
+            raise CalendarTransientError(
+                f"Expected {method} {target} was not observed"
+            )
+        return packet
+    finally:
+        page.listen.stop()
+
+
+def parse_availability_packet(packet: object) -> CalendarProbeResult:
+    path, _ = same_origin_path(packet.url)
+    if str(packet.method).upper() != "POST" or path != AVAILABILITY_PATH:
+        raise CalendarGateError("Availability request method or path changed")
+    response = packet.response
+    status = response.status
+    if type(status) is not int:
+        raise CalendarGateError("Availability HTTP status was not an integer")
+    if status in {301, 302, 303, 307, 308}:
+        location = header_value(getattr(response, "headers", None), "Location")
+        destination = urlparse(urljoin(packet.url, location))
+        if location and destination.scheme == "https" and destination.hostname == "iam.esteri.it":
+            raise CalendarAuthenticationExpiredError("Calendar response redirected to IAM")
+    response_url = getattr(response, "url", None)
+    if isinstance(response_url, str) and response_url:
+        destination = urlparse(response_url)
+        if destination.scheme == "https" and destination.hostname == "iam.esteri.it":
+            raise CalendarAuthenticationExpiredError("Calendar response returned to IAM")
+        response_path, _ = same_origin_path(response_url)
+        if response_path != AVAILABILITY_PATH:
+            raise CalendarGateError("Availability response reached an unexpected path")
+    if status == 401:
+        raise CalendarAuthenticationExpiredError("Calendar authentication expired")
+    if status == 429:
+        raise CalendarRateLimitedError("Calendar request was rate limited")
+    if status == 403:
+        raise CalendarAccessDeniedError("Calendar access requires operator attention")
+    if status in {0, 408, 502, 503, 504}:
+        raise CalendarTransientError("Calendar request temporarily failed")
+    if status != 200:
+        raise CalendarGateError("Availability response status was not 200")
+
+    post_data = packet.request.postData
+    if isinstance(post_data, str):
+        try:
+            post_data = json.loads(post_data)
+        except json.JSONDecodeError as exc:
+            raise CalendarGateError(
+                "Availability request body was not JSON"
+            ) from exc
+    if not isinstance(post_data, dict) or set(post_data) != {
+        "_Servizio",
+        "selectedDay",
+    }:
+        raise CalendarGateError("Availability request keys changed")
+    if isinstance(post_data["_Servizio"], bool) or not str(
+        post_data["_Servizio"]
+    ).strip():
+        raise CalendarGateError("Availability runtime service id was empty")
+    if (
+        not isinstance(post_data["selectedDay"], str)
+        or not post_data["selectedDay"].strip()
+    ):
+        raise CalendarGateError("Availability selectedDay was empty")
+
+    try:
+        days = parse_calendar_availability(packet.response.raw_body)
+    except ItaProtocolError as exc:
+        raise CalendarGateError(
+            f"Availability response rejected ({exc.code})"
+        ) from exc
+    return CalendarProbeResult(
+        days=days,
+        selected_day=post_data["selectedDay"],
+    )
+
+
+def validate_next_month_snapshot(
+    raw: object,
+    *,
+    expected_clicked: bool,
+    allow_unready: bool = False,
+) -> dict[str, object]:
+    """Require the exact, non-sensitive Calendar month-control shape."""
+
+    if not isinstance(raw, dict):
+        raise CalendarGateError(
+            "Calendar next-month control did not return an object"
+        )
+    expected_keys = {
+        "pathMatches",
+        "candidateCount",
+        "actionableCount",
+        "clicked",
+    }
+    if set(raw) != expected_keys:
+        raise CalendarGateError(
+            "Calendar next-month control returned unexpected fields"
+        )
+    if raw["pathMatches"] is not True:
+        raise CalendarGateError(
+            "Calendar next-month control was evaluated outside Calendar"
+        )
+    candidate_count = require_plain_nonnegative_int(
+        raw["candidateCount"],
+        "candidateCount",
+    )
+    actionable_count = require_plain_nonnegative_int(
+        raw["actionableCount"],
+        "actionableCount",
+    )
+    if actionable_count > candidate_count:
+        raise CalendarGateError(
+            "Calendar next-month actionable count exceeded candidates"
+        )
+    if not isinstance(expected_clicked, bool):
+        raise CalendarGateError("expected_clicked must be a boolean")
+    if raw["clicked"] is not expected_clicked:
+        raise CalendarGateError(
+            "Calendar next-month click acknowledgement changed"
+        )
+    if actionable_count != 1 and not (
+        allow_unready and actionable_count == 0
+    ):
+        raise CalendarGateError(
+            "Calendar next-month control was not uniquely actionable"
+        )
+    return raw
+
+
+def click_next_month(
+    page: object,
+    *,
+    timeout: float = 10,
+    diagnostic: Callable[[object], None] | None = None,
+) -> None:
+    """Click only the unique visible Bootstrap day-view month control."""
+
+    deadline = time.monotonic() + timeout
+    last_raw: object = None
+    while time.monotonic() < deadline:
+        last_raw = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, False)
+        try:
+            snapshot = validate_next_month_snapshot(
+                last_raw,
+                expected_clicked=False,
+                allow_unready=True,
+            )
+        except CalendarGateError:
+            if diagnostic:
+                diagnostic(last_raw)
+            raise
+        if snapshot["actionableCount"] == 1:
+            break
+        time.sleep(0.25)
+    else:
+        if diagnostic:
+            diagnostic(last_raw)
+        raise CalendarNextMonthUnavailableError(
+            "Calendar next-month control was not actionable before timeout"
+        )
+
+    clicked = page.run_js(NEXT_MONTH_CONTROL_SCRIPT, True)
+    if diagnostic:
+        diagnostic(clicked)
+    validate_next_month_snapshot(clicked, expected_clicked=True)
+
+
+def refresh_calendar(page: object) -> None:
+    page.refresh()
+    page.wait.doc_loaded()
+
+
+def guard_calendar(page: object) -> dict[str, object]:
+    """Disable the final button and reject any observed final request."""
+
+    raw = page.run_js(CALENDAR_GUARD_SCRIPT)
+    if not isinstance(raw, dict):
+        raise CalendarGateError("Calendar guard did not return an object")
+    expected = {
+        "path": CALENDAR_PATH,
+        "calendarFunctionPresent": True,
+        "finalButtonCount": 1,
+        "allFinalButtonsGuarded": True,
+        "finalRequestCount": 0,
+    }
+    for key, expected_value in expected.items():
+        if raw.get(key) != expected_value:
+            raise CalendarGateError(f"Calendar guard rejected {key}")
+    return raw
+
+
+def capture_initial_probe(page: object) -> CalendarProbeResult:
+    packet = listen_once(
+        page,
+        target=AVAILABILITY_PATH,
+        method="POST",
+        action=lambda: refresh_calendar(page),
+        timeout=30,
+    )
+    probe = parse_availability_packet(packet)
+    guard_calendar(page)
+    return probe
+
+
+def capture_next_probe(page: object) -> CalendarProbeResult:
+    packet = listen_once(
+        page,
+        target=AVAILABILITY_PATH,
+        method="POST",
+        action=lambda: click_next_month(page),
+        timeout=30,
+    )
+    probe = parse_availability_packet(packet)
+    guard_calendar(page)
+    return probe
+
+
+def scan_until_first_available_month(
+    page: object,
+    *,
+    lookahead_months: int,
+    log: Callable[[str], None] | None = None,
+    month_click_interval_seconds: float = DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
+) -> CalendarQueryScanResult:
+    """Scan sequential months and stop immediately at the first positive one."""
+
+    months = _validate_lookahead_months(lookahead_months)
+    if (
+        isinstance(month_click_interval_seconds, bool)
+        or not isinstance(month_click_interval_seconds, (int, float))
+        or month_click_interval_seconds < 0
+    ):
+        raise CalendarGateError(
+            "month_click_interval_seconds must be nonnegative"
+        )
+
+    probes = [capture_initial_probe(page)]
+    if log:
+        log(
+            "Italy Calendar probe "
+            f"index=0 available={probes[0].available_count}"
+        )
+    if probes[0].available_count:
+        return CalendarQueryScanResult(
+            probes=tuple(probes),
+            lookahead_months=months,
+            stop_reason="first_available_month",
+        )
+
+    for index in range(1, months):
+        if month_click_interval_seconds:
+            time.sleep(month_click_interval_seconds)
+        try:
+            probe = capture_next_probe(page)
+        except CalendarNextMonthUnavailableError as exc:
+            raise CalendarGateError(
+                "Calendar scan ended before the configured horizon"
+            ) from exc
+        if probe.selected_month != next_month_value(
+            probes[-1].selected_month
+        ):
+            raise CalendarGateError(
+                "Calendar request did not advance exactly one month"
+            )
+        probes.append(probe)
+        if log:
+            log(
+                "Italy Calendar probe "
+                f"index={index} available={probe.available_count}"
+            )
+        if probe.available_count:
+            return CalendarQueryScanResult(
+                probes=tuple(probes),
+                lookahead_months=months,
+                stop_reason="first_available_month",
+            )
+
+    return CalendarQueryScanResult(
+        probes=tuple(probes),
+        lookahead_months=months,
+        stop_reason="horizon_exhausted",
+    )

+ 603 - 0
plugins/ita_calendar_session.py

@@ -0,0 +1,603 @@
+"""Shared Italy form preparation and passive request audit.
+
+Extracted from the real-tested Calendar gate. Production and diagnostic tools
+use the same protocol; no tool imports, credentials, or network calls on import.
+"""
+from __future__ import annotations
+
+import json
+import time
+from enum import Enum
+from threading import Lock
+from urllib.parse import parse_qs, urljoin, urlparse
+
+from plugins.ita_calendar_query import (
+    AVAILABILITY_PATH, CALENDAR_PATH, CalendarGateError,
+    header_value as _header, same_origin_path as _same_origin_path,
+)
+from plugins.ita_protocol import ItaRouteConfig
+
+OTP_PATH = "/BookingCalendar/GenerateOTP"
+
+
+def booking_preflight_state(raw: object) -> str:
+    """Classify observed readiness, not the unknown cause of a widget failure."""
+    if not isinstance(raw, dict):
+        return "snapshot_unavailable"
+    token, disabled = raw.get("turnstileTokenPresent"), raw.get("avantiDisabled")
+    if type(token) is not bool or type(disabled) is not bool:
+        return "invalid_snapshot"
+    if not token:
+        return "turnstile_and_avanti_pending" if disabled else "turnstile_token_pending"
+    return "avanti_disabled" if disabled else "ready"
+
+
+def safe_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> dict:
+    """Only bounded booleans/counts and fixed categories; never token/value/HTML."""
+    snapshot = raw if isinstance(raw, dict) else {}
+    result = {
+        "contract": "ita-book-preflight-v2",
+        "stage": stage.value if isinstance(stage, BookingPreflightStage) else "invalid",
+        "outcome": outcome if outcome in {"ready", "waiting", "rejected", "timeout", "read_failed"} else "invalid",
+        "state": booking_preflight_state(raw),
+    }
+    for key in ("pathMatches", "formPresent", "privacyChecked", "otpDisabled", "otpValuePresent",
+                "turnstileTokenPresent", "avantiDisabled", "turnstileApiPresent",
+                "turnstileScriptPresent", "documentVisible"):
+        value = snapshot.get(key)
+        result[key] = value if type(value) is bool else None
+    for key in ("turnstileCount", "avantiButtonCount", "unknownRequiredCount"):
+        value = snapshot.get(key)
+        result[key] = value if type(value) is int and 0 <= value <= 1000 else None
+    return result
+
+
+def _print_booking_preflight_diagnostic(raw: object, *, stage, outcome: str) -> None:
+    print("ITA_BOOK_PREFLIGHT_DIAGNOSTIC=" + json.dumps(
+        safe_booking_preflight_diagnostic(raw, stage=stage, outcome=outcome), sort_keys=True,
+    ), flush=True)
+
+
+def wait_for_booking_preflight(
+    page: object,
+    *,
+    script: str,
+    stage: BookingPreflightStage = None,
+    timeout: float = 120,
+    diagnostic=None,
+    wait_action=None,
+    check_current=None,
+) -> dict[str, object]:
+    """Wait without relaxing structure; optional bounded form interaction.
+
+    An interaction return value is never evidence of readiness: only the next
+    validated site snapshot can permit OTP/AVANTI. No recovery is enabled by
+    default; callers must explicitly supply their preparation recovery.
+    """
+
+    stage = stage if stage is not None else BookingPreflightStage.BEFORE_OTP_SEND
+    report = diagnostic or _print_booking_preflight_diagnostic
+    started = time.monotonic()
+    deadline = started + timeout
+    announced = False
+    raw = None
+    last_state = None
+    next_report = started
+    while (now := time.monotonic()) < deadline:
+        if check_current is not None:
+            check_current()
+        try:
+            raw = page.run_js(script)
+        except Exception:
+            report(None, stage=stage, outcome="read_failed")
+            raise CalendarGateError("Italy booking preflight read_failed") from None
+        if check_current is not None:
+            check_current()
+        try:
+            _validate_preflight_except_dynamic_token(raw, stage=stage)
+        except CalendarGateError:
+            report(
+                raw,
+                stage=stage,
+                outcome="rejected",
+            )
+            raise
+        if raw.get("turnstileTokenPresent") and not raw.get("avantiDisabled"):
+            try:
+                validate_booking_preflight(raw, stage=stage)
+            except CalendarGateError:
+                report(
+                    raw,
+                    stage=stage,
+                    outcome="rejected",
+                )
+                raise
+            report(
+                raw,
+                stage=stage,
+                outcome="ready",
+            )
+            return raw
+        if not announced:
+            print("ITA_BOOK_WAITING_FOR_FORM: watch the opened browser; complete any human verification. "
+                  "Do not click OTP, AVANTI, or final Prenota.", flush=True)
+            announced = True
+        state = booking_preflight_state(raw)
+        if state != last_state or now >= next_report:
+            report(raw, stage=stage, outcome="waiting")
+            last_state, next_report = state, now + 15
+        if wait_action is not None:
+            wait_action(raw, stage=stage, elapsed=now - started, remaining=deadline - now)
+        time.sleep(0.5)
+    report(raw, stage=stage, outcome="timeout")
+    raise CalendarGateError(f"Italy booking preflight timed out: {booking_preflight_state(raw)}")
+
+def guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
+    """Check scope before the reused script changes any visible form control."""
+    prefix = """
+/* coordinate:ita-book-gate-form-boundary */
+const bookGateForms = document.querySelectorAll('#bookingForm');
+const bookGateForm = bookGateForms.length === 1 ? bookGateForms[0] : null;
+let bookGateAction = null;
+try { bookGateAction = bookGateForm ? new URL(bookGateForm.action, location.href) : null; }
+catch (_) {}
+if (location.origin !== 'https://prenotami.esteri.it' ||
+    location.pathname !== BOOK_GATE_PATH || !bookGateForm ||
+    bookGateForm.method.toUpperCase() !== 'POST' ||
+    bookGateForm.enctype !== 'multipart/form-data' ||
+    !bookGateAction || bookGateAction.origin !== location.origin ||
+    bookGateAction.pathname !== BOOK_GATE_PATH || bookGateAction.search || bookGateAction.hash ||
+    bookGateForm.querySelectorAll('input[type="file"]').length !== 0) {
+  return {pathMatches: false, formPresent: false};
+}
+""".replace("BOOK_GATE_PATH", json.dumps(booking_path))
+    return prefix + _booking_preflight_script(route, booking_path)
+
+class BookingPreflightStage(Enum):
+    BEFORE_OTP_SEND = "before_otp_send"
+    AFTER_OTP_SEND = "after_otp_send"
+
+
+class CalendarRequestAudit:
+    """Passively count business requests across refreshes; never retain bodies.
+
+    The production page.listen owns a separate CDP connection. This diagnostic
+    callback uses the page driver and refuses to replace an existing handler.
+    It never enables Fetch interception or changes any browser request.
+    """
+
+    EVENT = "Network.requestWillBeSent"
+
+    def __init__(self, page: object, *, include_time_slots: bool = False) -> None:
+        self.page = page
+        self.driver = page.driver
+        self._callback = self._on_request
+        self._lock = Lock()
+        self._started = False
+        self._invalid_event = False
+        self._counts = {
+            "otpRequests": 0,
+            "avantiPosts": 0,
+            "availabilityRequests": 0,
+            "finalRequests": 0,
+        }
+        if include_time_slots:
+            self._counts["timeSlotRequests"] = 0
+
+    def enable_time_slot_counting(self) -> None:
+        """Opt in for the soak; existing gate counter shapes stay unchanged."""
+        with self._lock:
+            self._counts.setdefault("timeSlotRequests", 0)
+
+    def start(self) -> None:
+        if self._started:
+            raise CalendarGateError("Passive request audit was already started")
+        for name in ("event_handlers", "immediate_event_handlers"):
+            handlers = getattr(self.driver, name, None)
+            if not isinstance(handlers, dict) or self.EVENT in handlers:
+                raise CalendarGateError(
+                    "Passive request audit cannot replace an existing callback"
+                )
+        self.driver.set_callback(self.EVENT, self._callback, immediate=True)
+        self._started = True
+        try:
+            self.page.run_cdp("Network.enable")
+        except Exception:
+            self.stop()
+            raise
+
+    def stop(self) -> None:
+        if not self._started:
+            return
+        if self.driver.immediate_event_handlers.get(self.EVENT) is not self._callback:
+            raise CalendarGateError("Passive request audit callback changed")
+        self.driver.set_callback(self.EVENT, None, immediate=True)
+        self._started = False
+
+    def _on_request(self, **event: object) -> None:
+        request = event.get("request")
+        if (
+            not isinstance(request, dict)
+            or not isinstance(request.get("url"), str)
+            or not isinstance(request.get("method"), str)
+        ):
+            with self._lock:
+                self._invalid_event = True
+            return
+        try:
+            path, _ = _same_origin_path(request["url"])
+        except CalendarGateError:
+            return
+        method = request["method"].upper()
+        key = None
+        if path == OTP_PATH:
+            key = "otpRequests"
+        elif path == "/BookingCalendar/InsertNewBooking":
+            key = "finalRequests"
+        elif method == "POST" and path.startswith("/Services/Booking/"):
+            key = "avantiPosts"
+        elif path == AVAILABILITY_PATH:
+            key = "availabilityRequests"
+        elif path == "/BookingCalendar/RetrieveTimeSlots" and "timeSlotRequests" in self._counts:
+            key = "timeSlotRequests"
+        if key is not None:
+            with self._lock:
+                self._counts[key] += 1
+
+    def require_active_on(self, page: object) -> None:
+        """Validate a borrowed audit without registering or removing callbacks."""
+        if self.page is not page or self.driver is not getattr(page, "driver", None):
+            raise CalendarGateError("Passive request audit belongs to another page or driver")
+        if not self._started or self.driver.is_running is not True:
+            raise CalendarGateError("Passive request audit is not connected")
+        immediate = getattr(self.driver, "immediate_event_handlers", None)
+        regular = getattr(self.driver, "event_handlers", None)
+        if (not isinstance(immediate, dict) or immediate.get(self.EVENT) is not self._callback
+                or not isinstance(regular, dict) or self.EVENT in regular):
+            raise CalendarGateError("Passive request audit callback changed")
+
+    def snapshot(self) -> dict[str, int]:
+        self.require_active_on(self.page)
+        with self._lock:
+            if self._invalid_event:
+                raise CalendarGateError("Passive request audit received an invalid event")
+            return dict(self._counts)
+
+    def retained_snapshot(self) -> dict[str, int]:
+        """Best-effort last observed counters, not proof after a disconnect."""
+        with self._lock:
+            if self._invalid_event:
+                raise CalendarGateError("Passive request audit received an invalid event")
+            return dict(self._counts)
+
+    def settled_snapshot(self, *, timeout: float = 3) -> dict[str, int]:
+        # A read-only CDP round trip plus a bounded stable-count window lets
+        # already-arriving callbacks catch up before a per-query comparison.
+        self.page.run_cdp("Page.getFrameTree")
+        deadline = time.monotonic() + timeout
+        previous = self.snapshot()
+        stable_since = time.monotonic()
+        while time.monotonic() < deadline:
+            time.sleep(0.1)
+            current = self.snapshot()
+            if current != previous:
+                previous = current
+                stable_since = time.monotonic()
+            elif time.monotonic() - stable_since >= 0.3:
+                return current
+        raise CalendarGateError("Passive business-request counts did not settle")
+
+
+def validate_otp_packet(packet: object, *, service_id: int) -> None:
+    path, parsed = _same_origin_path(packet.url)
+    if str(packet.method).upper() != "GET" or path != OTP_PATH:
+        raise CalendarGateError("OTP request method or path changed")
+    if parse_qs(parsed.query) != {"ServiceID": [str(service_id)]}:
+        raise CalendarGateError("OTP request service id changed")
+    if packet.response.status != 200:
+        raise CalendarGateError("OTP response status was not 200")
+    raw_body = packet.response.raw_body
+    if not isinstance(raw_body, str):
+        raise CalendarGateError("OTP response body type changed")
+    try:
+        decoded = json.loads(raw_body)
+    except json.JSONDecodeError as exc:
+        raise CalendarGateError("OTP response was not the observed JSON string") from exc
+    if decoded != "SENT":
+        raise CalendarGateError("OTP response did not confirm SENT")
+
+
+def validate_avanti_packet(
+    packet: object,
+    *,
+    booking_path: str,
+    final_page_url: str,
+) -> str:
+    path, request_url = _same_origin_path(packet.url)
+    if (
+        str(packet.method).upper() != "POST"
+        or path != booking_path
+        or request_url.query
+        or request_url.fragment
+    ):
+        raise CalendarGateError("AVANTI request method or path changed")
+
+    status = packet.response.status
+    if status == 302:
+        raw_location = _header(packet.response.headers, "location")
+        redirect_path, _ = _same_origin_path(
+            urljoin("https://prenotami.esteri.it", raw_location)
+        )
+        if redirect_path != CALENDAR_PATH:
+            raise CalendarGateError("AVANTI redirect did not target Calendar")
+        transition_mode = "direct_302"
+    elif status == 200:
+        response_path, _ = _same_origin_path(
+            getattr(packet.response, "url", "")
+        )
+        if response_path != CALENDAR_PATH:
+            raise CalendarGateError(
+                "AVANTI followed response did not target Calendar"
+            )
+        transition_mode = "followed_redirect_200"
+    else:
+        raise CalendarGateError(
+            "AVANTI response status was not an allowed redirect representation"
+        )
+
+    final_path, _ = _same_origin_path(final_page_url)
+    if final_path != CALENDAR_PATH:
+        raise CalendarGateError("AVANTI browser did not finish on Calendar")
+    return transition_mode
+
+
+def validate_booking_preflight(
+    raw: object,
+    *,
+    stage: BookingPreflightStage = BookingPreflightStage.BEFORE_OTP_SEND,
+) -> None:
+    """Validate shared form shape and the stage-sensitive OTP-send control."""
+
+    if not isinstance(raw, dict):
+        raise CalendarGateError("Booking preflight did not return an object")
+    if not isinstance(stage, BookingPreflightStage):
+        raise CalendarGateError("Booking preflight stage is invalid")
+    true_fields = (
+        "pathMatches",
+        "formPresent",
+        "bookingTypeOptionMatched",
+        "purposeOptionMatched",
+        "bookingVisibleMatches",
+        "bookingHiddenMatches",
+        "companionsHiddenIsZero",
+        "purposeVisibleMatches",
+        "purposeHiddenIsPreSubmit",
+        "privacyChecked",
+        "turnstileTokenPresent",
+    )
+    for field_name in true_fields:
+        if raw.get(field_name) is not True:
+            raise CalendarGateError(
+                f"Booking preflight rejected {field_name}"
+            )
+    for field_name in (
+        "otpInputCount",
+        "otpButtonCount",
+        "avantiButtonCount",
+        "turnstileCount",
+    ):
+        if raw.get(field_name) != 1:
+            raise CalendarGateError(
+                f"Booking preflight rejected {field_name}"
+            )
+    otp_disabled = raw.get("otpDisabled")
+    if not isinstance(otp_disabled, bool) or (
+        stage is BookingPreflightStage.BEFORE_OTP_SEND
+        and otp_disabled
+    ):
+        raise CalendarGateError(
+            "Booking preflight rejected otpDisabled"
+        )
+    if raw.get("avantiDisabled") is not False:
+        raise CalendarGateError(
+            "Booking preflight rejected avantiDisabled"
+        )
+    otp_value_present = raw.get("otpValuePresent")
+    expected_otp_value_present = (
+        stage is BookingPreflightStage.AFTER_OTP_SEND
+    )
+    if (
+        not isinstance(otp_value_present, bool)
+        or otp_value_present is not expected_otp_value_present
+    ):
+        raise CalendarGateError(
+            "Booking preflight rejected otpValuePresent"
+        )
+    if raw.get("unknownRequiredCount") != 0:
+        raise CalendarGateError(
+            "Booking preflight rejected unknownRequiredCount"
+        )
+
+
+def _booking_preflight_script(
+    route: ItaRouteConfig,
+    booking_path: str,
+) -> str:
+    if route.booking_type is None or route.purpose is None:
+        raise CalendarGateError("Q-CAL route is missing form controls")
+    config = {
+        "bookingPath": booking_path,
+        "bookingTypeId": route.booking_type.control_id,
+        "bookingTypeValue": route.booking_type.value,
+        "bookingTypeLabels": list(route.booking_type.labels),
+        "purposeId": route.purpose.control_id,
+        "purposeValue": route.purpose.value,
+        "purposeLabels": list(route.purpose.labels),
+    }
+    config_json = json.dumps(config, ensure_ascii=False)
+    return f"""
+/* coordinate:ita-qcal-booking-preflight */
+const cfg = {config_json};
+const normalize = (value) => String(value || '')
+  .replace(/\\s+/g, ' ').trim().toLocaleLowerCase();
+const form = document.querySelector('#bookingForm');
+const booking = document.getElementById(cfg.bookingTypeId);
+const purpose = document.getElementById(cfg.purposeId);
+const bookingOption = booking
+  ? Array.from(booking.options).find(
+      (option) => option.value === cfg.bookingTypeValue
+    )
+  : null;
+const purposeOption = purpose
+  ? Array.from(purpose.options).find(
+      (option) => option.value === cfg.purposeValue
+    )
+  : null;
+const bookingLabels = cfg.bookingTypeLabels.map(normalize);
+const purposeLabels = cfg.purposeLabels.map(normalize);
+const bookingTypeOptionMatched = Boolean(
+  bookingOption && bookingLabels.includes(normalize(bookingOption.textContent))
+);
+const purposeOptionMatched = Boolean(
+  purposeOption && purposeLabels.includes(normalize(purposeOption.textContent))
+);
+if (bookingTypeOptionMatched && booking.value !== cfg.bookingTypeValue) {{
+  booking.value = cfg.bookingTypeValue;
+  booking.dispatchEvent(new Event('change', {{bubbles: true}}));
+}}
+if (purposeOptionMatched && purpose.value !== cfg.purposeValue) {{
+  purpose.value = cfg.purposeValue;
+  purpose.dispatchEvent(new Event('change', {{bubbles: true}}));
+}}
+const privacy = document.getElementById('PrivacyCheck');
+if (privacy && !privacy.checked) privacy.click();
+const allowedRequiredIds = new Set([
+  cfg.bookingTypeId,
+  cfg.purposeId,
+  'otp-input',
+  'PrivacyCheck',
+  'hiddenTipoPrenotazione',
+  'numAccSelected',
+  'hiddenSelezionato_0',
+]);
+const allowedRequiredNames = new Set([
+  'otp-input',
+  'PrivacyCheck',
+  'cf-turnstile-response',
+  '__RequestVerificationToken',
+]);
+const unknownRequired = form
+  ? Array.from(form.querySelectorAll('[required]')).filter((element) =>
+      !allowedRequiredIds.has(element.id) &&
+      !allowedRequiredNames.has(element.name)
+    )
+  : [];
+const bookingHidden = document.getElementById('hiddenTipoPrenotazione');
+const companionsHidden = document.getElementById('numAccSelected');
+const purposeHidden = document.getElementById('hiddenSelezionato_0');
+const otpInputs = document.querySelectorAll('#otp-input');
+const otpButtons = document.querySelectorAll('#otp-send');
+const avantiButtons = document.querySelectorAll('#btnAvanti');
+const turnstile = document.querySelectorAll(
+  'input[name="cf-turnstile-response"]'
+);
+return {{
+  pathMatches: window.location.pathname === cfg.bookingPath,
+  formPresent: Boolean(form),
+  bookingTypeOptionMatched,
+  purposeOptionMatched,
+  bookingVisibleMatches: Boolean(
+    booking && booking.value === cfg.bookingTypeValue
+  ),
+  bookingHiddenMatches: Boolean(
+    bookingHidden && bookingHidden.value === cfg.bookingTypeValue
+  ),
+  companionsHiddenIsZero: Boolean(
+    companionsHidden && companionsHidden.value === '0'
+  ),
+  purposeVisibleMatches: Boolean(
+    purpose && purpose.value === cfg.purposeValue
+  ),
+  purposeHiddenIsPreSubmit: Boolean(
+    purposeHidden && ['0', cfg.purposeValue].includes(purposeHidden.value)
+  ),
+  privacyChecked: Boolean(privacy && privacy.checked),
+  otpInputCount: otpInputs.length,
+  otpValuePresent: Boolean(
+    otpInputs.length === 1 && String(otpInputs[0].value || '').trim()
+  ),
+  otpButtonCount: otpButtons.length,
+  otpDisabled: otpButtons.length === 1 ? otpButtons[0].disabled : null,
+  avantiButtonCount: avantiButtons.length,
+  avantiDisabled:
+    avantiButtons.length === 1 ? avantiButtons[0].disabled : null,
+  turnstileCount: turnstile.length,
+  turnstileTokenPresent: Boolean(
+    turnstile.length === 1 && turnstile[0].value
+  ),
+  turnstileApiPresent: Boolean(window.turnstile),
+  turnstileScriptPresent: Boolean(document.querySelector(
+    'script[src^="https://challenges.cloudflare.com/turnstile/"]'
+  )),
+  documentVisible: document.visibilityState === 'visible',
+  unknownRequiredCount: unknownRequired.length,
+}};
+"""
+
+
+def _validate_preflight_except_dynamic_token(
+    raw: object,
+    *,
+    stage: BookingPreflightStage,
+) -> None:
+    if not isinstance(raw, dict):
+        raise CalendarGateError("Booking preflight did not return an object")
+    for key in ("turnstileTokenPresent", "avantiDisabled"):
+        if type(raw.get(key)) is not bool:
+            raise CalendarGateError(f"Booking preflight rejected {key}")
+    candidate = dict(raw)
+    candidate["turnstileTokenPresent"] = True
+    candidate["avantiDisabled"] = False
+    validate_booking_preflight(candidate, stage=stage)
+
+
+def _wait_for_calendar(page: object, timeout: float = 30) -> None:
+    deadline = time.monotonic() + timeout
+    while time.monotonic() < deadline:
+        if (urlparse(str(page.url or "")).path.rstrip("/") or "/") == CALENDAR_PATH:
+            page.wait.doc_loaded()
+            return
+        time.sleep(0.25)
+    raise CalendarGateError("AVANTI did not reach Calendar before timeout")
+
+
+def _element_or_fail(page: object, selector: str) -> object:
+    element = page.ele(selector, timeout=5)
+    if not element:
+        raise CalendarGateError(f"Required element is missing: {selector}")
+    return element
+
+
+def _read_manual_otp() -> str:
+    otp = input(
+        "Italy booking OTP "
+        "(visible; terminal scrollback may retain it): "
+    ).strip()
+    if not otp.isdigit() or not 4 <= len(otp) <= 12:
+        raise CalendarGateError("OTP must be 4-12 digits")
+    return otp
+
+
+def _enter_otp(plugin: object, otp: str) -> None:
+    """Focus, type, and compare in-page without returning the OTP value."""
+
+    otp_input = _element_or_fail(plugin.page, "#otp-input")
+    plugin.mouse.human_click_ele(otp_input)
+    otp_input.input(otp, clear=True)
+    value_matches = otp_input.run_js(
+        "return this.value === arguments[0];",
+        otp,
+    )
+    if value_matches is not True:
+        raise CalendarGateError("OTP DOM write verification failed")
+    print("ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true")

+ 252 - 0
plugins/ita_final_read_port.py

@@ -0,0 +1,252 @@
+"""Read-port adapter shared by production Book and local final validation.
+
+Preserves the applicant Calendar in its original tab. Reads existing receipts in
+an owned background tab of the SAME browser/context. Baselines allow only empty
+or cancelled history. A new confirmed receipt may bind to a verified native POST;
+observed receipt fields remain distinct from submission evidence.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import threading
+import time
+from dataclasses import dataclass, field
+from uuid import uuid4
+from urllib.parse import parse_qsl
+
+from plugins.ita_booking_final import (
+    FinalBookingError, FinalTarget, ReservationRecord, ReservationSnapshot, ReservationState, VerifiedSubmission,
+)
+from plugins.ita_calendar_query import CALENDAR_PATH, same_origin_path
+from plugins.ita_protocol import ItaCapability, ItaRouteConfig, PrecommitApproval
+from plugins.ita_reservation import read_reservation_detail, read_reservation_listing
+
+
+LIST_URL = "https://prenotami.esteri.it/Reservation"
+MAX_DETAIL_READS = 20
+
+
+@dataclass(frozen=True, repr=False)
+class ReceiptObservation:
+    """Bound display evidence only; UNKNOWN is never promoted to success."""
+
+    records: tuple = field(repr=False)  # (verified list row, matching detail)
+
+
+def _require(condition, reason):
+    if condition is not True:
+        raise FinalBookingError(reason)
+
+
+def _cancelled_record(row, detail) -> ReservationRecord:
+    _require(row.state is ReservationState.CANCELLED and detail.state is ReservationState.CANCELLED and
+             detail.status_code == "3" and all(getattr(row, field) == getattr(detail, field) for field in (
+                 "reference", "office", "service_name", "day", "appointment_time", "status_text")),
+             "Italy cancelled receipt is not verified")
+    # Equality of fingerprints preserves changes to fields absent from the final
+    # model (office, displayed service, booking type). It is NOT identity proof.
+    facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
+             detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
+    digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
+    return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.CANCELLED,
+                             appointment_time=detail.appointment_time, receipt_fingerprint=digest)
+
+
+def _confirmed_record(row, detail, submission: VerifiedSubmission) -> ReservationRecord:
+    target, slot = submission.target, submission.target.approval.candidate
+    _require(row.state is ReservationState.ACTIVE and detail.state is ReservationState.ACTIVE and
+             detail.status_code == "2" and detail.booking_type == "Prenotazione Singola" and
+             isinstance(target.service_name, str) and detail.service_name == target.service_name and
+             detail.day == slot.day and slot.time_label[:5] <= detail.appointment_time <= slot.time_label[-5:] and
+             all(getattr(row, key) == getattr(detail, key) for key in (
+                 "reference", "office", "service_name", "day", "appointment_time", "status_text")),
+             "Italy confirmed receipt does not match the submitted selection")
+    facts = [detail.reference, row.detail_url, detail.office, detail.service_name, detail.booking_type,
+             detail.day.isoformat(), detail.appointment_time, detail.status_text, detail.status_code]
+    digest = hashlib.sha256(json.dumps(facts, ensure_ascii=True, separators=(",", ":")).encode()).hexdigest()
+    # The website receipt supplies neither service_id nor the selected interval.
+    # Keep them None; the separate evidence explicitly identifies the native POST.
+    return ReservationRecord(detail.reference, None, detail.day, None, ReservationState.ACTIVE,
+                             appointment_time=detail.appointment_time, receipt_fingerprint=digest,
+                             submission=submission)
+
+
+class FinalReceiptReadPort:
+    """Capture an existing applicant Book precommit, then read fresh snapshots.
+
+    Uses the plugin's established session/route checks, not a caller-supplied
+    username assertion. Constructor does no navigation. Calling the port reads
+    only; it never touches final buttons, rebuilds calendars or generates OTP.
+    The owning Book workflow must serialize this with other browser work.
+    """
+
+    def __init__(self, plugin, route: ItaRouteConfig, *, observe_tab=None):
+        try:
+            _require(isinstance(route, ItaRouteConfig) and
+                     route.capability is ItaCapability.SINGLE_SCHENGEN_TOURISM,
+                     "Italy final read route is invalid")
+            self._plugin, self._route = plugin, route
+            _require(observe_tab is None or callable(observe_tab), "Italy receipt observer is invalid")
+            self._observe_tab = observe_tab
+            self._page = plugin.page
+            self._browser = self._page.browser
+            self._browser_id = self._browser.id
+            self._generation = plugin.session_create_time
+            self._prepared = plugin._calendar_book_prepared_context
+            self._approval = plugin.last_booking_precommit
+            self._username = plugin.config.account.username.strip().casefold()
+            _require(isinstance(self._approval, PrecommitApproval) and
+                     isinstance(self._prepared, tuple) and len(self._prepared) == 7 and
+                     isinstance(self._browser_id, str) and bool(self._browser_id) and
+                     same_origin_path(self._page.url)[0] == CALENDAR_PATH,
+                     "Italy final read requires the current Book precommit")
+            _, calendar_url = same_origin_path(self._page.url)
+            names = [value for key, value in parse_qsl(calendar_url.query, keep_blank_values=True)
+                     if key == "selectedService"]
+            service_name = names[0] if len(names) == 1 and names[0] else None
+            self._target = FinalTarget(self._username, uuid4().hex, self._page.tab_id,
+                                       route.routing_key, str(route.service_id), self._prepared[5], self._approval,
+                                       service_name=service_name)
+            self._lock = threading.Lock()
+            self._unusable = False
+            self._baseline = None
+            self._submission = None
+            _require(self.session_is_current(), "Italy final read Session is not current")
+        except Exception:
+            raise FinalBookingError("Italy final read context could not be captured") from None
+
+    @property
+    def target(self):
+        return self._target
+
+    def session_is_current(self) -> bool:
+        try:
+            p = self._plugin
+            same_origin_path(self._page.url)
+            return (not self._unusable and p.page is self._page and self._page.browser is self._browser and
+                    self._browser.id == self._browser_id and self._page.tab_id == self._target.tab_id and
+                    p.session_create_time == self._generation and p.is_healthy is True and
+                    p.last_booking_precommit is self._approval and
+                    p._calendar_book_prepared_context == self._prepared and
+                    p.config.account.username.strip().casefold() == self._username and
+                    p._calendar_book_context_matches(self._route, self._username) is True)
+        except Exception:
+            return False
+
+    def __call__(self) -> ReservationSnapshot:
+        snapshot = self._read(observation=False)
+        if self._submission is None:
+            self._baseline = snapshot
+        return snapshot
+
+    def record_submission(self, submission: VerifiedSubmission) -> None:
+        """Called only after a matched native POST and one-request audit."""
+        _require(self.session_is_current() and self._baseline is not None and self._submission is None and
+                 isinstance(submission, VerifiedSubmission) and submission.target == self.target and
+                 self.target.service_name is not None, "Italy submission binding is not current")
+        self._submission = submission
+
+    def observe_receipts(self) -> ReceiptObservation:
+        """Read unknown status text for controlled discovery, NOT reconciliation."""
+        return self._read(observation=True)
+
+    def _read(self, *, observation: bool):
+        if not self._lock.acquire(blocking=False):
+            raise FinalBookingError("Italy receipt read is already running")
+        receipt_page = None
+        finish_observation = None
+        close_failed = False
+        cleanup_interrupt = None
+        try:
+            _require(self.session_is_current(), "Italy final read Session changed")
+            origin = (self._page.url, self._page.tab_id)
+            candidate = self._browser.new_tab(background=True, new_context=False)
+            # Only close a separately identified tab created by our own browser.
+            # A broken factory returning the original/foreign page is not owned.
+            _require(candidate is not self._page and candidate.browser is self._browser and
+                     isinstance(candidate.tab_id, str) and bool(candidate.tab_id) and
+                     candidate.tab_id != self._target.tab_id, "Italy receipt tab ownership is unverified")
+            receipt_page, receipt_tab = candidate, candidate.tab_id
+            if self._observe_tab is not None:
+                finish_observation = self._observe_tab(receipt_page)
+                _require(callable(finish_observation), "Italy receipt observer did not start")
+
+            def context():
+                _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin and
+                         receipt_page.browser is self._browser and receipt_page.tab_id == receipt_tab,
+                         "Italy receipt read context changed")
+
+            def navigate(url):
+                context()
+                _require(receipt_page.get(url, retry=0, timeout=30) is not False,
+                         "Italy receipt navigation failed")
+                context()
+                same_origin_path(receipt_page.url)
+                _require(receipt_page.url == url, "Italy receipt navigation was redirected")
+
+            navigate(LIST_URL)
+            before = read_reservation_listing(receipt_page)
+            context()
+            _require(before.waitlist_count == 0 and len(before.rows) <= MAX_DETAIL_READS,
+                     "Italy receipt coverage exceeds supported verification")
+            if not observation and self._submission is None:
+                _require(all(row.state is ReservationState.CANCELLED for row in before.rows),
+                         "Italy live receipt attribution is not verified")
+            records = []
+            for row in before.rows:
+                # Only actual links accepted by the established listing parser.
+                navigate(row.detail_url)
+                detail = read_reservation_detail(receipt_page)
+                context()
+                _require(all(getattr(row, key) == getattr(detail, key) for key in (
+                    "reference", "office", "service_name", "day", "appointment_time", "status_text")),
+                    "Italy observed receipt does not match its list row")
+                if observation:
+                    records.append((row, detail))
+                elif row.state is ReservationState.CANCELLED:
+                    records.append(_cancelled_record(row, detail))
+                else:
+                    _require(self._submission is not None and self._baseline is not None and
+                             row.reference not in {r.reference for r in self._baseline.records},
+                             "Italy receipt is not new to this submission")
+                    records.append(_confirmed_record(row, detail, self._submission))
+            navigate(LIST_URL)
+            after = read_reservation_listing(receipt_page)
+            context()
+            _require({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and
+                     before.waitlist_count == after.waitlist_count, "Italy receipt history changed during read")
+            snapshot = (ReceiptObservation(tuple(records)) if observation else
+                        ReservationSnapshot(self._target.applicant, self._target.session_key,
+                                            time.monotonic(), True, tuple(records)))
+        except Exception:
+            raise FinalBookingError("Italy bound receipt read could not be verified") from None
+        finally:
+            if callable(finish_observation):
+                try:
+                    finish_observation()
+                except BaseException as exc:
+                    self._unusable = True
+                    if isinstance(exc, Exception):
+                        close_failed = True
+                    else:
+                        cleanup_interrupt = exc
+            if receipt_page is not None:
+                try:
+                    receipt_page.close()
+                except BaseException as exc:
+                    # Do not trust a later read after losing control of an owned tab.
+                    self._unusable = True
+                    if isinstance(exc, Exception):
+                        close_failed = True
+                    else:
+                        cleanup_interrupt = exc
+            self._lock.release()
+            if cleanup_interrupt is not None:
+                raise cleanup_interrupt
+            if close_failed:
+                raise FinalBookingError("Italy owned receipt tab cleanup failed") from None
+        _require(self.session_is_current() and (self._page.url, self._page.tab_id) == origin,
+                 "Italy final read context changed during cleanup")
+        return snapshot

+ 140 - 0
plugins/ita_otp.py

@@ -0,0 +1,140 @@
+"""Italy-only OTP adapter.
+
+The adapter deliberately reuses ``VSCloudApi.fetch_mail_content`` instead of
+creating another mail provider.  It adds the Italy contract around that call:
+one sent-time window, a fixed Prenot@Mi sender filter, deterministic body
+parsing, and fail-closed errors that never carry the raw mail body.
+
+The provider returns body only: its header/time filtering is a dependency, not
+independent sender authentication or freshness proof by this adapter.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from datetime import datetime, timezone
+
+import vs_log_macros
+from plugins.ita_calendar_query import CalendarGateError
+from plugins.ita_protocol import (
+    ItaProtocolError,
+    OtpMailConfig,
+    PRENOTAMI_OTP_SENDER,
+    parse_otp_body,
+)
+from toolkit.vs_cloud_api import VSCloudApi
+from vs_types import (
+    BizLogicError,
+    PermissionDeniedError,
+    RateLimiteddError,
+    SessionExpiredOrInvalidError,
+)
+
+
+_EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+_SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
+
+
+def utc_sent_at() -> str:
+    """Return the exact UTC format required by the existing cloud endpoint."""
+
+    return datetime.now(timezone.utc).strftime(_SENT_AT_FORMAT)
+
+
+def validate_cloud_otp_logging() -> None:
+    """Validate before any shared SDK call; never change logging state.
+
+    Existing SDK DEBUG output includes raw mail. Automatic Italy OTP therefore
+    requires a stable INFO-or-higher logger throughout the call. Runtime log
+    reconfiguration and backend logging are outside this local guarantee.
+    """
+    logger = getattr(vs_log_macros, "_active_logger", None)
+    if not isinstance(logger, logging.Logger) or logger.isEnabledFor(logging.DEBUG):
+        raise CalendarGateError("Italy automatic OTP requires DEBUG payload logging to be disabled")
+
+
+def validate_cloud_otp_environment(mail_config: OtpMailConfig, recipient: str) -> None:
+    """Validate the configured mailbox policy and actual account before OTP."""
+    if not isinstance(mail_config, OtpMailConfig):
+        raise CalendarGateError("Italy OTP mail configuration is missing")
+    recipient_value = _validate_recipient(recipient)
+    mail_config.mailbox_for(recipient_value)
+    validate_cloud_otp_logging()
+
+
+def _validate_recipient(recipient: str) -> str:
+    if not isinstance(recipient, str):
+        raise CalendarGateError("Italy OTP recipient must be an email address")
+    value = recipient.strip()
+    if not _EMAIL_PATTERN.fullmatch(value):
+        raise CalendarGateError("Italy OTP recipient must be an email address")
+    return value
+
+
+def _validate_sent_at(sent_at: str) -> str:
+    if not isinstance(sent_at, str):
+        raise CalendarGateError("Italy OTP sent time is invalid")
+    value = sent_at.strip()
+    try:
+        datetime.strptime(value, _SENT_AT_FORMAT)
+    except ValueError:
+        raise CalendarGateError("Italy OTP sent time is invalid") from None
+    return value
+
+
+def fetch_otp_from_cloud(
+    mail_config: OtpMailConfig,
+    *,
+    recipient: str,
+    sent_at: str,
+    api: VSCloudApi | None = None,
+) -> str:
+    """Read and parse one new Italy OTP through the existing cloud API.
+
+    The call is intentionally one-shot.  ``fetch-top`` is not a fallback and
+    no retry or second OTP request is issued after a read/parse failure.
+    """
+
+    validate_cloud_otp_environment(mail_config, recipient)
+    recipient_value = _validate_recipient(recipient)
+    sent_at_value = _validate_sent_at(sent_at)
+    try:
+        client = api if api is not None else VSCloudApi.Instance()
+        # Keep the body inside this scope; callers receive only the parsed
+        # digits and must not log either the body or the code.
+        body = client.fetch_mail_content(
+            email=mail_config.mailbox_for(recipient_value),
+            sender=PRENOTAMI_OTP_SENDER,
+            recipient=recipient_value,
+            subject_keywords=mail_config.subject_keywords,
+            body_keywords=mail_config.body_keywords,
+            sent_date=sent_at_value,
+            expiry=mail_config.expiry_seconds,
+            only_text=True,
+        )
+    except SessionExpiredOrInvalidError:
+        # Mail API authentication is NOT the appointment site's Session.
+        raise CalendarGateError("Italy OTP mailbox API authentication failed") from None
+    except PermissionDeniedError:
+        raise CalendarGateError(
+            "Italy OTP mailbox authorization is not permitted"
+        ) from None
+    except RateLimiteddError:
+        raise CalendarGateError("Italy OTP mailbox read was rate limited") from None
+    except BizLogicError:
+        # The shared SDK may include a provider response body in this error.
+        raise CalendarGateError("Italy OTP mailbox read failed") from None
+    except Exception:
+        # Suppress provider exception context in standard traceback rendering.
+        raise CalendarGateError("Italy OTP mailbox read failed") from None
+
+    try:
+        return parse_otp_body(body)
+    except ItaProtocolError as exc:
+        raise CalendarGateError(
+            f"Italy OTP mail rejected ({exc.code})"
+        ) from None
+
+
+__all__ = ["fetch_otp_from_cloud", "utc_sent_at", "validate_cloud_otp_environment", "validate_cloud_otp_logging"]

تفاوت فایلی نمایش داده نمی شود زیرا این فایل بسیار بزرگ است
+ 1394 - 410
plugins/ita_plugin.py


+ 1168 - 0
plugins/ita_protocol.py

@@ -0,0 +1,1168 @@
+"""Pure Prenot@Mi protocol parsing and precommit validation.
+
+This module is the functional core of the Italy plugin.  It deliberately owns
+no browser, network, session, OTP, or form-submission behavior.  Callers pass
+already-captured, sanitized data in and receive immutable value objects back.
+"""
+
+from __future__ import annotations
+
+import json
+import html
+import re
+from dataclasses import dataclass, field
+from datetime import date, datetime, time
+from enum import Enum
+from typing import Any, Mapping, Sequence
+
+
+MAX_PROTOCOL_ITEMS = 512
+MAX_PROTOCOL_PAYLOAD_CHARS = 1_000_000
+MAX_LOOKAHEAD_MONTHS = 120
+_SITE_DATE_PATTERN = re.compile(r"^\d{2}/\d{2}/\d{4} 00:00:00$")
+PRENOTAMI_OTP_SENDER = "noreply-prenotami@esteri.it"
+_EMAIL_PATTERN = re.compile(r"^[^@\s]+@[^@\s]+\.[^@\s]+$")
+_OTP_CONTEXT_PATTERN = re.compile(
+    r"(?<!\w)OTP\s+Code\s*:\s*([0-9]{6})(?!\w)",
+    re.IGNORECASE,
+)
+
+
+class ItaProtocolError(ValueError):
+    """Fail-closed protocol error with a stable, non-sensitive category."""
+
+    def __init__(self, code: str, message: str, *, path: str = "") -> None:
+        self.code = code
+        self.path = path
+        location = f" at {path}" if path else ""
+        super().__init__(f"Italy protocol error [{code}]{location}: {message}")
+
+
+class ItaCapability(str, Enum):
+    SERVICES_PROBE_ONLY = "services_probe_only"
+    SINGLE_SCHENGEN_TOURISM = "single_schengen_tourism"
+
+
+class InventoryState(str, Enum):
+    AVAILABLE = "available"
+    UNAVAILABLE = "unavailable"
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarScanConfig:
+    lookahead_months: int
+
+
+@dataclass(frozen=True, slots=True)
+class FormControlConfig:
+    control_id: str
+    value: str
+    labels: tuple[str, ...]
+
+
+@dataclass(frozen=True, slots=True)
+class OtpMailConfig:
+    """Allowlisted cloud-mail query settings for one Italy route.
+
+    The authorization mailbox is configured explicitly or derived per call
+    from the current account, never cached on a shared route or included in
+    diagnostic objects or log messages. The sender is
+    fixed to Prenot@Mi's observed official address; a route may not widen the
+    allowlist through configuration.
+    """
+
+    authorization_email: str | None = field(default=None, repr=False)
+    subject_keywords: str = "OTP Code"
+    body_keywords: str = "OTP Code:"
+    expiry_seconds: int = 300
+    authorization_source: str = "configured"
+
+    def __post_init__(self) -> None:
+        if self.authorization_source not in ("configured", "account"):
+            raise ItaProtocolError(
+                "otp_authorization_source_invalid",
+                "authorization source must be configured or account",
+                path="mail.authorization_source",
+            )
+        if self.authorization_source == "account":
+            if self.authorization_email is not None:
+                raise ItaProtocolError(
+                    "otp_authorization_source_conflict",
+                    "account source cannot also specify a fixed authorization mailbox",
+                    path="mail.authorization_email",
+                )
+        else:
+            object.__setattr__(self, "authorization_email", self._require_mailbox(self.authorization_email))
+        for field_name, expected in (("subject_keywords", "OTP Code"), ("body_keywords", "OTP Code:")):
+            value = getattr(self, field_name)
+            if not isinstance(value, str) or value.strip() != expected:
+                raise ItaProtocolError(
+                    "otp_filter_invalid",
+                    "mail filters must match the observed Prenot@Mi OTP template",
+                    path=f"mail.{field_name}",
+                )
+            object.__setattr__(self, field_name, value.strip())
+        if (
+            not isinstance(self.expiry_seconds, int)
+            or isinstance(self.expiry_seconds, bool)
+            or not 1 <= self.expiry_seconds <= 300
+        ):
+            raise ItaProtocolError(
+                "otp_expiry_invalid",
+                "mail expiry must be an integer between 1 and 300 seconds",
+                path="mail.expiry_seconds",
+            )
+
+    @staticmethod
+    def _require_mailbox(value: Any) -> str:
+        if not isinstance(value, str) or not _EMAIL_PATTERN.fullmatch(value.strip()):
+            raise ItaProtocolError(
+                "otp_authorization_email_invalid",
+                "authorization mailbox must be a valid email address",
+                path="mail.authorization_email",
+            )
+        return value.strip()
+
+    def mailbox_for(self, account_email: str) -> str:
+        """Bind per call; never mutate the route shared by pool instances.
+
+        Account mode requires that each account's own inbox has an existing
+        backend authorization. Configured mode preserves shared/forwarded
+        inbox support; recipient filtering remains bound to the site account.
+        """
+        return self._require_mailbox(
+            account_email if self.authorization_source == "account" else self.authorization_email
+        )
+
+
+@dataclass(frozen=True, slots=True)
+class ItaRouteConfig:
+    routing_key: str
+    service_id: int
+    capability: ItaCapability
+    calendar_scan: CalendarScanConfig | None = None
+    booking_type: FormControlConfig | None = None
+    purpose: FormControlConfig | None = None
+    mail: OtpMailConfig | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarDay:
+    day: date
+    slots_free: int
+    slots_remaining: int
+    state: InventoryState
+
+    def __post_init__(self) -> None:
+        _require_date(self.day, "CalendarDay.day")
+        slots_free = _require_int(self.slots_free, "CalendarDay.slots_free")
+        slots_remaining = _require_int(
+            self.slots_remaining,
+            "CalendarDay.slots_remaining",
+        )
+        expected_state = _classify_inventory(
+            slots_free,
+            slots_remaining,
+            path="CalendarDay",
+        )
+        if self.state is not expected_state:
+            raise ItaProtocolError(
+                "inventory_state_mismatch",
+                "declared state differs from the slot counters",
+                path="CalendarDay.state",
+            )
+
+    @property
+    def is_available(self) -> bool:
+        return self.state is InventoryState.AVAILABLE
+
+
+@dataclass(frozen=True, slots=True)
+class SlotCandidate:
+    day: date
+    start_time: time
+    end_time: time
+    slots_free: int
+    slots_remaining: int
+    state: InventoryState
+    daily_calendar_id: str = field(repr=False)
+
+    def __post_init__(self) -> None:
+        _require_date(self.day, "SlotCandidate.day")
+        start = _require_time(self.start_time, "SlotCandidate.start_time")
+        end = _require_time(self.end_time, "SlotCandidate.end_time")
+        if start >= end:
+            raise ItaProtocolError(
+                "time_range_invalid",
+                "slot start time must be earlier than end time",
+                path="SlotCandidate",
+            )
+        slots_free = _require_int(
+            self.slots_free,
+            "SlotCandidate.slots_free",
+        )
+        slots_remaining = _require_int(
+            self.slots_remaining,
+            "SlotCandidate.slots_remaining",
+        )
+        expected_state = _classify_inventory(
+            slots_free,
+            slots_remaining,
+            path="SlotCandidate",
+        )
+        if self.state is not expected_state:
+            raise ItaProtocolError(
+                "inventory_state_mismatch",
+                "declared state differs from the slot counters",
+                path="SlotCandidate.state",
+            )
+        if (
+            not isinstance(self.daily_calendar_id, str)
+            or not self.daily_calendar_id.isdigit()
+            or int(self.daily_calendar_id) <= 0
+        ):
+            raise ItaProtocolError(
+                "daily_id_invalid",
+                "runtime daily identifier must be a positive integer string",
+                path="SlotCandidate.daily_calendar_id",
+            )
+
+    @property
+    def is_available(self) -> bool:
+        return self.state is InventoryState.AVAILABLE
+
+    @property
+    def time_label(self) -> str:
+        return (
+            f"{self.start_time.strftime('%H:%M')} - "
+            f"{self.end_time.strftime('%H:%M')}"
+        )
+
+
+@dataclass(frozen=True, slots=True)
+class DateSelectionState:
+    planned_day: date
+    matching_availability_count: int
+    timeline_selected_days: tuple[date, ...]
+    content_selected_days: tuple[date, ...]
+    day_disabled: bool
+    day_not_available: bool
+    day_has_positive_state: bool
+
+    def __post_init__(self) -> None:
+        _require_date(self.planned_day, "DateSelectionState.planned_day")
+        _require_nonnegative_int(
+            self.matching_availability_count,
+            "DateSelectionState.matching_availability_count",
+        )
+        _require_date_tuple(
+            self.timeline_selected_days,
+            "DateSelectionState.timeline_selected_days",
+        )
+        _require_date_tuple(
+            self.content_selected_days,
+            "DateSelectionState.content_selected_days",
+        )
+        for field_name in (
+            "day_disabled",
+            "day_not_available",
+            "day_has_positive_state",
+        ):
+            _require_bool(
+                getattr(self, field_name),
+                f"DateSelectionState.{field_name}",
+            )
+
+
+@dataclass(frozen=True, slots=True)
+class SlotSelectionState:
+    active_slot_count: int
+    active_is_candidate: bool
+    active_has_unavailable_class: bool
+    active_has_red_dot: bool
+    active_hidden_input_count: int
+    active_daily_id_matches_candidate: bool
+    active_day_matches_candidate: bool
+    active_time_matches_candidate: bool
+    active_capacity_matches_candidate: bool
+
+    def __post_init__(self) -> None:
+        for field_name in (
+            "active_slot_count",
+            "active_hidden_input_count",
+        ):
+            _require_nonnegative_int(
+                getattr(self, field_name),
+                f"SlotSelectionState.{field_name}",
+            )
+        for field_name in (
+            "active_is_candidate",
+            "active_has_unavailable_class",
+            "active_has_red_dot",
+            "active_daily_id_matches_candidate",
+            "active_day_matches_candidate",
+            "active_time_matches_candidate",
+            "active_capacity_matches_candidate",
+        ):
+            _require_bool(
+                getattr(self, field_name),
+                f"SlotSelectionState.{field_name}",
+            )
+
+
+@dataclass(frozen=True, slots=True)
+class PrecommitApproval:
+    """Immutable value returned by :func:`approve_precommit`."""
+
+    calendar_day: CalendarDay
+    candidate: SlotCandidate
+
+
+def resolve_route_config(
+    apt_configs: Mapping[str, Any],
+    routing_key: str,
+) -> ItaRouteConfig:
+    """Resolve one VFS/BLS-style ``apt_configs[routing_key]`` entry."""
+
+    configs = _require_mapping(apt_configs, "apt_configs")
+    key = _require_nonempty_string(routing_key, "routing_key")
+    if key not in configs:
+        raise ItaProtocolError(
+            "route_missing",
+            "no route is configured for the requested routing key",
+            path="apt_configs",
+        )
+
+    raw_route = _require_mapping(configs[key], f"apt_configs.{key}")
+    service_id = _require_positive_int(
+        raw_route.get("service_id"),
+        f"apt_configs.{key}.service_id",
+    )
+
+    raw_capability = _require_nonempty_string(
+        raw_route.get("capability"),
+        f"apt_configs.{key}.capability",
+    )
+    try:
+        capability = ItaCapability(raw_capability)
+    except ValueError as exc:
+        raise ItaProtocolError(
+            "capability_unsupported",
+            "route capability is not supported",
+            path=f"apt_configs.{key}.capability",
+        ) from exc
+
+    if capability is ItaCapability.SERVICES_PROBE_ONLY:
+        return ItaRouteConfig(
+            routing_key=key,
+            service_id=service_id,
+            capability=capability,
+        )
+
+    calendar_scan_raw = _require_mapping(
+        raw_route.get("calendar_scan"),
+        f"apt_configs.{key}.calendar_scan",
+    )
+    calendar_scan = CalendarScanConfig(
+        lookahead_months=_require_lookahead_months(
+            calendar_scan_raw.get("lookahead_months"),
+            f"apt_configs.{key}.calendar_scan.lookahead_months",
+        )
+    )
+
+    form_raw = _require_mapping(
+        raw_route.get("form"),
+        f"apt_configs.{key}.form",
+    )
+    booking_type = _parse_form_control(
+        form_raw,
+        prefix="booking_type",
+        path=f"apt_configs.{key}.form",
+    )
+    purpose = _parse_form_control(
+        form_raw,
+        prefix="purpose",
+        path=f"apt_configs.{key}.form",
+    )
+    mail = _parse_mail_config(
+        raw_route.get("mail"),
+        path=f"apt_configs.{key}.mail",
+    )
+
+    return ItaRouteConfig(
+        routing_key=key,
+        service_id=service_id,
+        capability=capability,
+        calendar_scan=calendar_scan,
+        booking_type=booking_type,
+        purpose=purpose,
+        mail=mail,
+    )
+
+
+def decode_double_json_array(
+    payload: str,
+    *,
+    max_items: int = MAX_PROTOCOL_ITEMS,
+) -> tuple[Mapping[str, Any], ...]:
+    """Strictly decode the JSON-string-containing-a-JSON-array wire shape."""
+
+    if not isinstance(payload, str) or not payload:
+        raise ItaProtocolError(
+            "payload_type",
+            "payload must be a non-empty JSON string",
+        )
+    if len(payload) > MAX_PROTOCOL_PAYLOAD_CHARS:
+        raise ItaProtocolError(
+            "payload_too_large",
+            "payload exceeds the local parsing limit",
+        )
+    if not _is_positive_int(max_items):
+        raise ItaProtocolError(
+            "max_items_invalid",
+            "max_items must be a positive integer",
+        )
+
+    try:
+        outer = json.loads(payload)
+    except (TypeError, json.JSONDecodeError) as exc:
+        raise ItaProtocolError(
+            "outer_json_invalid",
+            "outer JSON cannot be decoded",
+        ) from exc
+    if not isinstance(outer, str):
+        raise ItaProtocolError(
+            "payload_layer_count",
+            "payload must contain exactly two JSON layers",
+        )
+    if len(outer) > MAX_PROTOCOL_PAYLOAD_CHARS:
+        raise ItaProtocolError(
+            "payload_too_large",
+            "inner payload exceeds the local parsing limit",
+        )
+
+    try:
+        items = json.loads(outer)
+    except (TypeError, json.JSONDecodeError) as exc:
+        raise ItaProtocolError(
+            "inner_json_invalid",
+            "inner JSON cannot be decoded",
+        ) from exc
+    if not isinstance(items, list):
+        raise ItaProtocolError(
+            "payload_layer_count",
+            "inner JSON must be an array",
+        )
+    if len(items) > max_items:
+        raise ItaProtocolError(
+            "item_limit_exceeded",
+            "response contains more items than the configured parsing limit",
+        )
+
+    result: list[Mapping[str, Any]] = []
+    for index, item in enumerate(items):
+        if not isinstance(item, Mapping):
+            raise ItaProtocolError(
+                "item_type",
+                "every response item must be an object",
+                path=f"items[{index}]",
+            )
+        result.append(item)
+    return tuple(result)
+
+
+def parse_calendar_availability(
+    payload: str,
+    *,
+    max_items: int = MAX_PROTOCOL_ITEMS,
+) -> tuple[CalendarDay, ...]:
+    """Parse and classify calendar-day capacity without guessing conflicts."""
+
+    items = decode_double_json_array(payload, max_items=max_items)
+    days: list[CalendarDay] = []
+    seen_days: set[date] = set()
+
+    for index, item in enumerate(items):
+        path = f"availability[{index}]"
+        parsed_day = _parse_site_date(
+            _require_key(item, "DateLibere", path),
+            f"{path}.DateLibere",
+        )
+        if parsed_day in seen_days:
+            raise ItaProtocolError(
+                "duplicate_calendar_day",
+                "calendar response contains a duplicate date",
+                path=path,
+            )
+        seen_days.add(parsed_day)
+
+        slots_free = _require_int(
+            _require_key(item, "SlotLiberi", path),
+            f"{path}.SlotLiberi",
+        )
+        slots_remaining = _require_int(
+            _require_key(item, "SlotRimanenti", path),
+            f"{path}.SlotRimanenti",
+        )
+        state = _classify_inventory(
+            slots_free,
+            slots_remaining,
+            path=path,
+        )
+        days.append(
+            CalendarDay(
+                day=parsed_day,
+                slots_free=slots_free,
+                slots_remaining=slots_remaining,
+                state=state,
+            )
+        )
+
+    return tuple(sorted(days, key=lambda item: item.day))
+
+
+def parse_time_slots(
+    payload: str,
+    *,
+    max_items: int = MAX_PROTOCOL_ITEMS,
+) -> tuple[SlotCandidate, ...]:
+    """Parse TimeSlots items while keeping the runtime ID memory-only."""
+
+    items = decode_double_json_array(payload, max_items=max_items)
+    candidates: list[SlotCandidate] = []
+    seen_ranges: set[tuple[date, time, time]] = set()
+    seen_daily_ids: set[str] = set()
+
+    for index, item in enumerate(items):
+        path = f"time_slots[{index}]"
+        parsed_day = _parse_site_date(
+            _require_key(item, "Data", path),
+            f"{path}.Data",
+        )
+        start_time = _parse_site_time(
+            _require_key(item, "OrarioInizioFascia", path),
+            f"{path}.OrarioInizioFascia",
+        )
+        end_time = _parse_site_time(
+            _require_key(item, "OrarioFineFascia", path),
+            f"{path}.OrarioFineFascia",
+        )
+        if start_time >= end_time:
+            raise ItaProtocolError(
+                "time_range_invalid",
+                "slot start time must be earlier than end time",
+                path=path,
+            )
+
+        slots_free = _require_int(
+            _require_key(item, "SlotLiberi", path),
+            f"{path}.SlotLiberi",
+        )
+        slots_remaining = _require_int(
+            _require_key(item, "SlotRimanenti", path),
+            f"{path}.SlotRimanenti",
+        )
+        state = _classify_inventory(
+            slots_free,
+            slots_remaining,
+            path=path,
+        )
+
+        daily_id = str(
+            _require_positive_int(
+                _require_key(item, "IDCalendarioServizioGiornaliero", path),
+                f"{path}.IDCalendarioServizioGiornaliero",
+            )
+        )
+        time_range = (parsed_day, start_time, end_time)
+        if time_range in seen_ranges:
+            raise ItaProtocolError(
+                "duplicate_time_range",
+                "time-slot response contains a duplicate time range",
+                path=path,
+            )
+        if daily_id in seen_daily_ids:
+            raise ItaProtocolError(
+                "duplicate_daily_id",
+                "time-slot response reuses a runtime daily identifier",
+                path=path,
+            )
+        seen_ranges.add(time_range)
+        seen_daily_ids.add(daily_id)
+
+        candidates.append(
+            SlotCandidate(
+                day=parsed_day,
+                start_time=start_time,
+                end_time=end_time,
+                slots_free=slots_free,
+                slots_remaining=slots_remaining,
+                state=state,
+                daily_calendar_id=daily_id,
+            )
+        )
+
+    return tuple(
+        sorted(
+            candidates,
+            key=lambda item: (item.day, item.start_time, item.end_time),
+        )
+    )
+
+
+def available_calendar_days(
+    days: Sequence[CalendarDay],
+    *,
+    start_day: date | None = None,
+    end_day: date | None = None,
+) -> tuple[CalendarDay, ...]:
+    """Return positive days in an inclusive date range, sorted ascending."""
+
+    start, end = _validate_date_range(start_day, end_day)
+    seen: set[date] = set()
+    selected: list[CalendarDay] = []
+    for index, item in enumerate(days):
+        if not isinstance(item, CalendarDay):
+            raise ItaProtocolError(
+                "calendar_day_type",
+                "days must contain CalendarDay values",
+                path=f"days[{index}]",
+            )
+        if item.day in seen:
+            raise ItaProtocolError(
+                "duplicate_calendar_day",
+                "days contain a duplicate date",
+                path=f"days[{index}]",
+            )
+        seen.add(item.day)
+        if item.is_available and _date_in_range(item.day, start, end):
+            selected.append(item)
+    return tuple(sorted(selected, key=lambda item: item.day))
+
+
+def available_slot_candidates(
+    candidates: Sequence[SlotCandidate],
+    *,
+    start_day: date | None = None,
+    end_day: date | None = None,
+) -> tuple[SlotCandidate, ...]:
+    """Filter and deterministically order positive Book-side candidates."""
+
+    start, end = _validate_date_range(start_day, end_day)
+    seen_ranges: set[tuple[date, time, time]] = set()
+    selected: list[SlotCandidate] = []
+    for index, item in enumerate(candidates):
+        if not isinstance(item, SlotCandidate):
+            raise ItaProtocolError(
+                "slot_candidate_type",
+                "candidates must contain SlotCandidate values",
+                path=f"candidates[{index}]",
+            )
+        identity = (item.day, item.start_time, item.end_time)
+        if identity in seen_ranges:
+            raise ItaProtocolError(
+                "duplicate_time_range",
+                "candidates contain a duplicate time range",
+                path=f"candidates[{index}]",
+            )
+        seen_ranges.add(identity)
+        if item.is_available and _date_in_range(item.day, start, end):
+            selected.append(item)
+
+    return tuple(
+        sorted(
+            selected,
+            key=lambda item: (
+                item.day,
+                -item.slots_free,
+                item.start_time,
+                item.end_time,
+            ),
+        )
+    )
+
+
+def parse_otp_body(
+    body: str,
+    *,
+    max_chars: int = MAX_PROTOCOL_PAYLOAD_CHARS,
+) -> str:
+    """Extract exactly one Prenot@Mi OTP from a cloud-mail body.
+
+    The cloud endpoint returns a body-only string and may include both the
+    plain-text and HTML MIME alternatives.  HTML tags are replaced with
+    spaces, then only the observed ``OTP Code:`` marker followed by six ASCII
+    digits is accepted.  Repeated identical matches (plain + HTML) are fine;
+    different candidates fail closed.  No caller should log ``body`` or the
+    returned code.
+    """
+
+    if not isinstance(body, str) or not body.strip():
+        raise ItaProtocolError(
+            "otp_body_invalid",
+            "OTP mail body must be a non-empty string",
+            path="mail.body",
+        )
+    if not isinstance(max_chars, int) or isinstance(max_chars, bool) or max_chars <= 0:
+        raise ItaProtocolError(
+            "otp_body_limit_invalid",
+            "OTP body limit must be a positive integer",
+            path="mail.max_chars",
+        )
+    if len(body) > max_chars:
+        raise ItaProtocolError(
+            "otp_body_too_large",
+            "OTP mail body exceeds the local parsing limit",
+            path="mail.body",
+        )
+
+    # The existing cloud service can concatenate text/plain and text/html.
+    # Projecting HTML to text avoids depending on a browser or executing any
+    # markup while preserving the marker when tags surround the code.
+    projected = html.unescape(re.sub(r"<[^>]{0,4096}>", " ", body))
+    projected = re.sub(r"\s+", " ", projected).strip()
+    matches = _OTP_CONTEXT_PATTERN.findall(projected)
+    unique = tuple(dict.fromkeys(matches))
+    if not unique:
+        raise ItaProtocolError(
+            "otp_not_found",
+            "mail body did not contain the expected OTP marker",
+            path="mail.body",
+        )
+    if len(unique) != 1:
+        raise ItaProtocolError(
+            "otp_ambiguous",
+            "mail body contained multiple different OTP candidates",
+            path="mail.body",
+        )
+    return unique[0]
+
+
+def month_starts(anchor_day: date, lookahead_months: int) -> tuple[date, ...]:
+    """Return deterministic month starts for the configured scan window."""
+
+    anchor = _require_date(anchor_day, "anchor_day")
+    months = _require_lookahead_months(lookahead_months, "lookahead_months")
+    result: list[date] = []
+    year = anchor.year
+    month = anchor.month
+    for _ in range(months):
+        result.append(date(year, month, 1))
+        month += 1
+        if month == 13:
+            year += 1
+            month = 1
+    return tuple(result)
+
+
+def approve_precommit(
+    calendar_day: CalendarDay,
+    candidate: SlotCandidate,
+    date_state: DateSelectionState,
+    slot_state: SlotSelectionState,
+) -> PrecommitApproval:
+    """Approve final-button readiness only when every observed invariant holds."""
+
+    if not isinstance(calendar_day, CalendarDay):
+        raise ItaProtocolError(
+            "precommit_type",
+            "calendar_day must be a CalendarDay",
+        )
+    if not isinstance(candidate, SlotCandidate):
+        raise ItaProtocolError(
+            "precommit_type",
+            "candidate must be a SlotCandidate",
+        )
+    if not isinstance(date_state, DateSelectionState):
+        raise ItaProtocolError(
+            "precommit_type",
+            "date_state must be a DateSelectionState",
+        )
+    if not isinstance(slot_state, SlotSelectionState):
+        raise ItaProtocolError(
+            "precommit_type",
+            "slot_state must be a SlotSelectionState",
+        )
+
+    checks = (
+        (calendar_day.is_available, "calendar day is not positively available"),
+        (candidate.is_available, "slot candidate is not positively available"),
+        (calendar_day.day == candidate.day, "calendar and slot dates differ"),
+        (
+            date_state.planned_day == candidate.day,
+            "selected date differs from the planned date",
+        ),
+        (
+            date_state.matching_availability_count == 1,
+            "planned date must map to exactly one availability item",
+        ),
+        (
+            date_state.timeline_selected_days == (candidate.day,),
+            "timeline must have exactly one matching selected date",
+        ),
+        (
+            date_state.content_selected_days == (candidate.day,),
+            "content must have exactly one matching selected date",
+        ),
+        (not date_state.day_disabled, "selected date is disabled"),
+        (
+            not date_state.day_not_available,
+            "selected date has a negative availability marker",
+        ),
+        (
+            date_state.day_has_positive_state,
+            "selected date lacks the verified positive state",
+        ),
+        (
+            slot_state.active_slot_count == 1,
+            "there must be exactly one active slot",
+        ),
+        (
+            slot_state.active_is_candidate,
+            "active slot is not the approved candidate",
+        ),
+        (
+            not slot_state.active_has_unavailable_class,
+            "active slot has an unavailable class",
+        ),
+        (
+            not slot_state.active_has_red_dot,
+            "active slot has a negative red marker",
+        ),
+        (
+            slot_state.active_hidden_input_count == 1,
+            "active slot must contain exactly one runtime identifier input",
+        ),
+        (
+            slot_state.active_daily_id_matches_candidate,
+            "active slot runtime identifier differs from the candidate",
+        ),
+        (
+            slot_state.active_day_matches_candidate,
+            "active slot date differs from the candidate",
+        ),
+        (
+            slot_state.active_time_matches_candidate,
+            "active slot time differs from the candidate",
+        ),
+        (
+            slot_state.active_capacity_matches_candidate,
+            "active slot capacity differs from the candidate",
+        ),
+    )
+    for passed, message in checks:
+        if not passed:
+            raise ItaProtocolError("precommit_rejected", message)
+
+    return PrecommitApproval(calendar_day=calendar_day, candidate=candidate)
+
+
+def _parse_form_control(
+    form: Mapping[str, Any],
+    *,
+    prefix: str,
+    path: str,
+) -> FormControlConfig:
+    return FormControlConfig(
+        control_id=_require_nonempty_string(
+            form.get(f"{prefix}_control_id"),
+            f"{path}.{prefix}_control_id",
+        ),
+        value=_require_nonempty_string(
+            form.get(f"{prefix}_value"),
+            f"{path}.{prefix}_value",
+        ),
+        labels=_require_string_tuple(
+            form.get(f"{prefix}_labels"),
+            f"{path}.{prefix}_labels",
+        ),
+    )
+
+
+def _parse_mail_config(
+    raw_mail: Any,
+    *,
+    path: str,
+) -> OtpMailConfig | None:
+    if raw_mail is None:
+        return None
+    mail = _require_mapping(raw_mail, path)
+    sender = mail.get("sender", PRENOTAMI_OTP_SENDER)
+    if not isinstance(sender, str) or sender.strip().casefold() != PRENOTAMI_OTP_SENDER:
+        raise ItaProtocolError(
+            "otp_sender_not_allowlisted",
+            "mail sender must match Prenot@Mi's official OTP address",
+            path=f"{path}.sender",
+        )
+    return OtpMailConfig(
+        authorization_email=mail.get("authorization_email"),
+        subject_keywords=mail.get("subject_keywords", "OTP Code"),
+        body_keywords=mail.get("body_keywords", "OTP Code:"),
+        expiry_seconds=mail.get("expiry_seconds", 300),
+        authorization_source=mail.get("authorization_source", "configured"),
+    )
+
+
+def _classify_inventory(
+    slots_free: int,
+    slots_remaining: int,
+    *,
+    path: str,
+) -> InventoryState:
+    if slots_free > 0 and slots_remaining >= 0:
+        return InventoryState.AVAILABLE
+    if slots_free == 0 and slots_remaining < 0:
+        return InventoryState.UNAVAILABLE
+    raise ItaProtocolError(
+        "inventory_conflict",
+        "slot counters do not match an observed allowlisted state",
+        path=path,
+    )
+
+
+def _parse_site_date(value: Any, path: str) -> date:
+    if not isinstance(value, str) or not _SITE_DATE_PATTERN.fullmatch(value):
+        raise ItaProtocolError(
+            "date_format",
+            "date must match DD/MM/YYYY 00:00:00",
+            path=path,
+        )
+    try:
+        return datetime.strptime(value, "%d/%m/%Y %H:%M:%S").date()
+    except ValueError as exc:
+        raise ItaProtocolError(
+            "date_invalid",
+            "date is not a real calendar date",
+            path=path,
+        ) from exc
+
+
+def _parse_site_time(value: Any, path: str) -> time:
+    mapping = _require_mapping(value, path)
+    hours = _require_int(_require_key(mapping, "Hours", path), f"{path}.Hours")
+    minutes = _require_int(
+        _require_key(mapping, "Minutes", path),
+        f"{path}.Minutes",
+    )
+    seconds = _require_int(mapping.get("Seconds", 0), f"{path}.Seconds")
+    milliseconds = _require_int(
+        mapping.get("Milliseconds", 0),
+        f"{path}.Milliseconds",
+    )
+    if seconds != 0 or milliseconds != 0:
+        raise ItaProtocolError(
+            "time_precision",
+            "sub-minute slot precision is not supported by the observed protocol",
+            path=path,
+        )
+    try:
+        return time(hour=hours, minute=minutes)
+    except ValueError as exc:
+        raise ItaProtocolError(
+            "time_invalid",
+            "slot time is outside the 24-hour clock",
+            path=path,
+        ) from exc
+
+
+def _validate_date_range(
+    start_day: date | None,
+    end_day: date | None,
+) -> tuple[date | None, date | None]:
+    start = _require_date(start_day, "start_day") if start_day is not None else None
+    end = _require_date(end_day, "end_day") if end_day is not None else None
+    if start is not None and end is not None and start > end:
+        raise ItaProtocolError(
+            "date_range_invalid",
+            "start_day must not be later than end_day",
+        )
+    return start, end
+
+
+def _date_in_range(
+    value: date,
+    start_day: date | None,
+    end_day: date | None,
+) -> bool:
+    return (
+        (start_day is None or value >= start_day)
+        and (end_day is None or value <= end_day)
+    )
+
+
+def _require_mapping(value: Any, path: str) -> Mapping[str, Any]:
+    if not isinstance(value, Mapping):
+        raise ItaProtocolError(
+            "mapping_required",
+            "value must be an object",
+            path=path,
+        )
+    return value
+
+
+def _require_key(mapping: Mapping[str, Any], key: str, path: str) -> Any:
+    if key not in mapping:
+        raise ItaProtocolError(
+            "field_missing",
+            "required field is missing",
+            path=f"{path}.{key}",
+        )
+    return mapping[key]
+
+
+def _require_nonempty_string(value: Any, path: str) -> str:
+    if not isinstance(value, str) or not value.strip():
+        raise ItaProtocolError(
+            "string_required",
+            "value must be a non-empty string",
+            path=path,
+        )
+    return value.strip()
+
+
+def _require_string_tuple(value: Any, path: str) -> tuple[str, ...]:
+    if isinstance(value, (str, bytes)) or not isinstance(value, Sequence):
+        raise ItaProtocolError(
+            "labels_required",
+            "labels must be a non-empty array of strings",
+            path=path,
+        )
+    labels = tuple(
+        _require_nonempty_string(item, f"{path}[{index}]")
+        for index, item in enumerate(value)
+    )
+    if not labels:
+        raise ItaProtocolError(
+            "labels_required",
+            "labels must be a non-empty array of strings",
+            path=path,
+        )
+    if len(set(labels)) != len(labels):
+        raise ItaProtocolError(
+            "labels_duplicate",
+            "labels must not contain duplicates",
+            path=path,
+        )
+    return labels
+
+
+def _is_positive_int(value: Any) -> bool:
+    return isinstance(value, int) and not isinstance(value, bool) and value > 0
+
+
+def _require_positive_int(value: Any, path: str) -> int:
+    if not _is_positive_int(value):
+        raise ItaProtocolError(
+            "positive_integer_required",
+            "value must be a positive integer",
+            path=path,
+        )
+    return value
+
+
+def _require_int(value: Any, path: str) -> int:
+    if not isinstance(value, int) or isinstance(value, bool):
+        raise ItaProtocolError(
+            "integer_required",
+            "value must be an integer",
+            path=path,
+        )
+    return value
+
+
+def _require_nonnegative_int(value: Any, path: str) -> int:
+    number = _require_int(value, path)
+    if number < 0:
+        raise ItaProtocolError(
+            "nonnegative_integer_required",
+            "value must be a non-negative integer",
+            path=path,
+        )
+    return number
+
+
+def _require_bool(value: Any, path: str) -> bool:
+    if not isinstance(value, bool):
+        raise ItaProtocolError(
+            "boolean_required",
+            "value must be a boolean",
+            path=path,
+        )
+    return value
+
+
+def _require_lookahead_months(value: Any, path: str) -> int:
+    months = _require_positive_int(value, path)
+    if months > MAX_LOOKAHEAD_MONTHS:
+        raise ItaProtocolError(
+            "lookahead_too_large",
+            "lookahead exceeds the local scan safety limit",
+            path=path,
+        )
+    return months
+
+
+def _require_date(value: Any, path: str) -> date:
+    if not isinstance(value, date) or isinstance(value, datetime):
+        raise ItaProtocolError(
+            "date_required",
+            "value must be a date",
+            path=path,
+        )
+    return value
+
+
+def _require_date_tuple(value: Any, path: str) -> tuple[date, ...]:
+    if not isinstance(value, tuple):
+        raise ItaProtocolError(
+            "date_tuple_required",
+            "value must be a tuple of dates",
+            path=path,
+        )
+    for index, item in enumerate(value):
+        _require_date(item, f"{path}[{index}]")
+    return value
+
+
+def _require_time(value: Any, path: str) -> time:
+    if not isinstance(value, time):
+        raise ItaProtocolError(
+            "time_required",
+            "value must be a time",
+            path=path,
+        )
+    if value.second != 0 or value.microsecond != 0:
+        raise ItaProtocolError(
+            "time_precision",
+            "slot time must use minute precision",
+            path=path,
+        )
+    return value
+
+
+__all__ = [
+    "CalendarDay",
+    "CalendarScanConfig",
+    "DateSelectionState",
+    "FormControlConfig",
+    "InventoryState",
+    "ItaCapability",
+    "ItaProtocolError",
+    "ItaRouteConfig",
+    "MAX_LOOKAHEAD_MONTHS",
+    "MAX_PROTOCOL_ITEMS",
+    "OtpMailConfig",
+    "PrecommitApproval",
+    "PRENOTAMI_OTP_SENDER",
+    "SlotCandidate",
+    "SlotSelectionState",
+    "approve_precommit",
+    "available_calendar_days",
+    "available_slot_candidates",
+    "decode_double_json_array",
+    "month_starts",
+    "parse_calendar_availability",
+    "parse_otp_body",
+    "parse_time_slots",
+    "resolve_route_config",
+]

+ 464 - 0
plugins/ita_reservation.py

@@ -0,0 +1,464 @@
+"""Read-only Prenot@Mi receipt adapter, not a final-submit read port.
+
+These objects contain observed display facts, not an inferred service/account
+binding or proof linking an assigned appointment time to a selected slot.
+Only observed Italian cancelled/confirmed states are classified; others stay UNKNOWN.
+No navigation, credentials, OTP, form writes or final actions live here.
+"""
+
+from __future__ import annotations
+
+import math
+import re
+import time
+from dataclasses import dataclass, field
+from datetime import date
+
+from plugins.ita_booking_final import ReservationState
+from plugins.ita_calendar_query import same_origin_path
+from plugins.ita_protocol import MAX_PROTOCOL_ITEMS
+
+
+LIST_PATH = "/Reservation"
+DETAIL_PREFIX = "/ReservationDetail/Index/"
+HEADERS = ("Codice Prenotazione", "Ufficio", "Servizio", "Data", "Ora", "Stato", "Dati Richiedente")
+DETAIL_LABELS = ("Servizio Consolare", "Servizio Erogato", "Codice Prenotazione",
+                 "Tipo Prenotazione", "Data", "Ora", "Stato")
+MONTHS_IT = ("gennaio", "febbraio", "marzo", "aprile", "maggio", "giugno", "luglio",
+             "agosto", "settembre", "ottobre", "novembre", "dicembre")
+
+
+class ReservationReadError(ValueError):
+    """Only adapter-owned reason codes; never include DOM text or browser errors."""
+
+    def __init__(self, reason: str):
+        self.reason = reason
+        super().__init__(f"Italy reservation read rejected: {reason}")
+
+
+@dataclass(frozen=True, slots=True, repr=False)
+class ReservationDetail:
+    reference: str
+    office: str
+    service_name: str
+    booking_type: str
+    day: date
+    appointment_time: str
+    status_text: str
+    status_code: str
+    state: ReservationState
+
+
+@dataclass(frozen=True, slots=True, repr=False)
+class ReservationListRow:
+    reference: str
+    detail_url: str
+    office: str
+    service_name: str
+    day: date
+    appointment_time: str
+    status_text: str
+    state: ReservationState
+
+
+@dataclass(frozen=True, slots=True)
+class ReservationListing:
+    """Coverage of the loaded client data, NOT a fresh account-bound snapshot."""
+
+    rows: tuple[ReservationListRow, ...] = field(repr=False)
+    page_count: int
+    waitlist_count: int = 0
+
+
+_CONTEXT_JS = r"""
+const clean = s => String(s || '').replace(/\s+/g, ' ').trim();
+const fail = reason => ({error: reason});
+if (window.location.origin !== 'https://prenotami.esteri.it') return fail('wrong_page');
+if (document.readyState !== 'complete') return fail('not_ready');
+if (!document.querySelector('.app-menu')) return fail('authentication_missing');
+"""
+
+DETAIL_READ_SCRIPT = _CONTEXT_JS + r"""
+/* coordinate:ita-reservation-detail-readonly */
+if (!/^\/ReservationDetail\/Index\/[^/]+$/.test(window.location.pathname)) return fail('wrong_page');
+const headings = Array.from(document.querySelectorAll('h4'));
+const booking = headings.filter(e => clean(e.textContent) === 'Dati Prenotazione');
+const applicant = headings.filter(e => clean(e.textContent) === 'Dati Richiedente');
+if (booking.length !== 1 || applicant.length !== 1) return fail('section_ambiguous');
+const root = booking[0].parentElement;
+if (!root || !root.classList.contains('my-col-6') || root.contains(applicant[0])) return fail('unsafe_scope');
+const nameOf = e => clean(e.textContent).match(
+  /^\*?\s*(Servizio Consolare|Servizio Erogato|Codice Prenotazione|Tipo Prenotazione|Data|Ora|Stato)\s*:\s*$/)?.[1];
+const labels = Array.from(root.querySelectorAll('label')).filter(nameOf);
+if (labels.length !== 7 || new Set(labels.map(nameOf)).size !== 7) return fail('fields_ambiguous');
+const fields = {};
+for (const label of labels) {
+  const row = label.parentElement;
+  if (labels.filter(e => row.contains(e)).length !== 1) return fail('row_ambiguous');
+  const values = [];
+  for (const node of row.childNodes) {
+    if (node === label || node.nodeType === 8) continue;
+    // The observed values are text siblings or one b. Do not read nested
+    // forms, print payloads, applicant sections or arbitrary HTML as values.
+    if (node.nodeType !== 3 && !(node.nodeType === 1 && node.tagName === 'B' && node.children.length === 0))
+      return fail('value_structure_changed');
+    const value = clean(node.textContent);
+    if (value) values.push(value);
+  }
+  if (values.length !== 1 || values[0].length > 256) return fail('value_ambiguous');
+  fields[nameOf(label)] = values[0];
+}
+const codes = document.querySelectorAll('input#IDTipoStatoPrenotazione');
+if (codes.length !== 1 || codes[0].type !== 'hidden' || codes[0].name !== 'IDTipoStatoPrenotazione')
+  return fail('status_control_ambiguous');
+return {path: window.location.pathname, fields, statusCode: clean(codes[0].value)};
+"""
+
+LIST_READ_SCRIPT = _CONTEXT_JS + r"""
+/* coordinate:ita-reservation-list-readonly */
+if (window.location.pathname !== '/Reservation') return fail('wrong_page');
+const readDateCell = cell => {
+  // Observed shape: optional hidden element(s), one non-empty text sibling.
+  // Do not use the whole cell's textContent (includes hidden metadata), nor
+  // innerText (unrendered DataTables pages can fall back to textContent).
+  const nodes = Array.from(cell.childNodes), values = [];
+  if (nodes.length > 16) return null;
+  for (const node of nodes) {
+    if (node.nodeType === 8) continue;
+    if (node.nodeType === 3) {
+      const value = clean(node.textContent);
+      if (value) values.push(value);
+      continue;
+    }
+    if (node.nodeType !== 1) return null;
+    const style = window.getComputedStyle(node);
+    // Own inline/hidden markers remain checkable for detached client rows.
+    // visibility:hidden only proves a leaf hidden: descendants can override it.
+    const hidden = node.hidden === true || node.style.display === 'none' || style.display === 'none';
+    const hiddenLeaf = node.children.length === 0 &&
+      (node.style.visibility === 'hidden' || style.visibility === 'hidden');
+    if (!hidden && !hiddenLeaf) return null;
+    // Hidden metadata is excluded structurally; never parse or log its value.
+  }
+  return values.length === 1 ? values[0] : null;
+};
+const $ = window.jQuery;
+const ids = ['dataTableReservations', 'dataTableReservationsWL'];
+const tables = [];
+for (const id of ids) {
+  const matches = document.querySelectorAll('#' + id);
+  if (matches.length !== 1) return fail('table_ambiguous');
+  const table = matches[0];
+  const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
+  if (!$?.fn?.dataTable?.isDataTable(table)) {
+    const empty = table.querySelectorAll('tbody tr').length === 0 && headers.length === 0 &&
+      !table.classList.contains('dataTable') && !table.closest('.dataTables_wrapper');
+    if (id !== ids[1] || !empty) return fail('not_ready');
+    tables.push({id, structuralEmpty: true});
+    continue;
+  }
+  // This getter is only used after isDataTable: it must never initialize a table.
+  const api = $(table).DataTable(), pageInfo = api.page.info();
+  const info = Object.fromEntries(['page', 'pages', 'start', 'end', 'length',
+    'recordsTotal', 'recordsDisplay', 'serverSide'].map(k => [k, pageInfo[k]]));
+  const count = api.rows().count();
+  if (!Number.isInteger(count) || count < 0 || count > 512) return fail('row_limit');
+  if (info.serverSide !== false || api.search() || api.columns().search().toArray().some(Boolean) ||
+      count !== info.recordsTotal || count !== info.recordsDisplay || api.rows({search: 'applied'}).count() !== count)
+    return fail('coverage_incomplete');
+  if (id === ids[1]) {
+    if (count !== 0) return fail('waitlist_schema_unverified');
+    tables.push({id, structuralEmpty: false, count, info});
+    continue;
+  }
+  const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
+  if (![7, 8].includes(headers.length) || expected.some((h, i) => headers[i] !== h) ||
+      (headers.length === 8 && headers[7] !== '')) return fail('headers_changed');
+  const nodes = api.rows().nodes().toArray();
+  if (nodes.length !== count) return fail('row_nodes_incomplete');
+  const rows = [];
+  for (const node of nodes) {
+    const cells = Array.from(node.children);
+    if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
+    const links = cells[0].querySelectorAll('a[href]');
+    if (links.length !== 1) return fail('detail_link_ambiguous');
+    const date = readDateCell(cells[3]);
+    if (date === null) return fail('date_cell_structure_changed');
+    const row = {reference: clean(cells[0].textContent), detailUrl: links[0].href,
+      office: clean(cells[1].textContent), service: clean(cells[2].textContent),
+      date, time: clean(cells[4].textContent), status: clean(cells[5].textContent)};
+    if (Object.values(row).some(v => typeof v !== 'string' || !v || v.length > 256)) return fail('field_invalid');
+    rows.push(row);
+    // Do not access applicant cell 6 or unnamed cell 7.
+  }
+  tables.push({id, structuralEmpty: false, headers, count, info, rows});
+}
+return {path: window.location.pathname, tables};
+"""
+
+
+DATE_DIAGNOSTIC_SCRIPT = _CONTEXT_JS + r"""
+/* coordinate:ita-reservation-date-diagnostic-readonly */
+if (window.location.pathname !== '/Reservation') return fail('wrong_page');
+const tables = document.querySelectorAll('#dataTableReservations');
+if (tables.length !== 1) return fail('table_ambiguous');
+const table = tables[0], $ = window.jQuery;
+const headers = Array.from(table.querySelectorAll('thead th')).map(e => clean(e.textContent));
+const expected = ['Codice Prenotazione', 'Ufficio', 'Servizio', 'Data', 'Ora', 'Stato', 'Dati Richiedente'];
+if (![7,8].includes(headers.length) || expected.some((v,i) => headers[i] !== v) ||
+    (headers.length === 8 && headers[7] !== '') || !$?.fn?.dataTable?.isDataTable(table))
+    return fail('headers_changed');
+const nodes = $(table).DataTable().rows().nodes().toArray();
+if (nodes.length > 512) return fail('row_limit');
+const samples = [];
+for (const row of nodes.slice(0,3)) {
+  const cells = Array.from(row.children);
+  if (cells.length !== headers.length || cells.some(c => c.tagName !== 'TD')) return fail('cells_changed');
+  // Only the verified Data column. No reference, account, applicant, HTML or attributes.
+  const cell = cells[3], children = Array.from(cell.childNodes);
+  const text = clean(cell.textContent), rendered = clean(cell.innerText);
+  if (text.length > 256 || rendered.length > 256) return fail('field_invalid');
+  const parts = children.slice(0,6).map(n => {
+    const style = n.nodeType === 1 ? window.getComputedStyle(n) : null;
+    return {kind: n.nodeType === 3 ? 'text' : (n.nodeType === 1 &&
+      ['SPAN','B','I','BR'].includes(n.tagName) ? n.tagName.toLowerCase() : 'other'),
+      text: clean(n.textContent), hidden: !!style && (style.display === 'none' || style.visibility === 'hidden')};
+  });
+  samples.push({text, rendered, parts, partsTruncated: children.length > 6});
+}
+return {path: window.location.pathname, samples, rowsTruncated: nodes.length > 3};
+"""
+
+
+def _date_shape(value: object) -> dict:
+    """Only structural symbols and known month indexes; never emit raw field text."""
+    if not isinstance(value, str) or len(value) > 256:
+        raise ValueError()
+    normalized = " ".join(value.split())
+    shape = "".join("D" if c.isdecimal() else "L" if c.isalpha() else c if c in " /:.,-" else "?"
+                    for c in normalized[:96])
+    months = [i for i, month in enumerate(MONTHS_IT, 1)
+              if re.search(r"(?<![A-Za-z])" + month + r"(?![A-Za-z])", normalized, re.IGNORECASE)]
+    try:
+        _day(normalized)
+        accepted = True
+    except ReservationReadError:
+        accepted = False
+    return {"shape": shape, "length": len(normalized), "truncated": len(normalized) > 96,
+            "italianMonths": months, "acceptedByCurrentParser": accepted}
+
+
+def read_reservation_date_diagnostic(page: object) -> dict:
+    """One bounded extra read on a failed list parse, not an alternate parser.
+
+    The raw verified date-cell strings stay local; only allowlisted shapes leave
+    this function. A malformed diagnostic cannot leak arbitrary browser output.
+    """
+    try:
+        raw = _read_current(page, DATE_DIAGNOSTIC_SCRIPT, detail=False)
+        if (set(raw) != {"path", "samples", "rowsTruncated"} or
+                type(raw["rowsTruncated"]) is not bool or not isinstance(raw["samples"], list) or
+                len(raw["samples"]) > 3):
+            raise ValueError()
+        samples = []
+        for item in raw["samples"]:
+            if (not isinstance(item, dict) or set(item) != {"text", "rendered", "parts", "partsTruncated"} or
+                    type(item["partsTruncated"]) is not bool or not isinstance(item["parts"], list) or
+                    len(item["parts"]) > 6):
+                raise ValueError()
+            parts = []
+            for part in item["parts"]:
+                if (not isinstance(part, dict) or set(part) != {"kind", "text", "hidden"} or
+                        part["kind"] not in ("text", "span", "b", "i", "br", "other") or
+                        type(part["hidden"]) is not bool):
+                    raise ValueError()
+                parts.append({"kind": part["kind"], "hidden": part["hidden"], **_date_shape(part["text"])})
+            samples.append({"text": _date_shape(item["text"]), "rendered": _date_shape(item["rendered"]),
+                            "textEqualsRendered": item["text"] == item["rendered"],
+                            "parts": parts, "partsTruncated": item["partsTruncated"]})
+        return {"available": True, "samples": samples, "rowsTruncated": raw["rowsTruncated"]}
+    except Exception:
+        return {"available": False}
+
+
+def _text(value: object) -> str:
+    if (not isinstance(value, str) or not 0 < len(value) <= 256 or value != value.strip()
+            or any(ord(c) < 32 or ord(c) == 127 for c in value)):
+        raise ReservationReadError("field_invalid")
+    return value
+
+
+def _day(value: object) -> date:
+    value = _text(value)
+    match = re.fullmatch(r"([0-9]{1,2}) ([A-Za-z]+) ([0-9]{4})", value)
+    if match:
+        try:
+            return date(int(match[3]), MONTHS_IT.index(match[2].casefold()) + 1, int(match[1]))
+        except ValueError:
+            pass
+    raise ReservationReadError("date_unrecognized") from None
+
+
+def _appointment_time(value: object) -> str:
+    value = _text(value)
+    if re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", value) is None:
+        raise ReservationReadError("time_unrecognized")
+    return value
+
+
+def _state(text: str, code: str | None = None) -> ReservationState:
+    # A list label is a candidate; a detail must also have its observed code.
+    # Never infer ACTIVE from "not cancelled" or from the numeric code alone.
+    if text.casefold() == "annullata" and code in (None, "3"):
+        return ReservationState.CANCELLED
+    if text.casefold() == "confermata" and code in (None, "2"):
+        return ReservationState.ACTIVE
+    return ReservationState.UNKNOWN
+
+
+def _detail_path(url: object) -> str:
+    try:
+        path, parsed = same_origin_path(url)
+        suffix = path.removeprefix(DETAIL_PREFIX)
+        if (not path.startswith(DETAIL_PREFIX) or not suffix or len(suffix) > 256
+                or any(c in suffix for c in "/\\%") or suffix in {".", ".."}
+                or parsed.query or parsed.fragment):
+            raise ValueError()
+        return path
+    except Exception:
+        raise ReservationReadError("detail_url_invalid") from None
+
+
+def parse_reservation_detail(raw: object) -> ReservationDetail:
+    if not isinstance(raw, dict) or set(raw) != {"path", "fields", "statusCode"}:
+        raise ReservationReadError("detail_schema_changed")
+    _detail_path("https://prenotami.esteri.it" + raw["path"] if isinstance(raw["path"], str) else None)
+    fields = raw["fields"]
+    if not isinstance(fields, dict) or set(fields) != set(DETAIL_LABELS):
+        raise ReservationReadError("fields_ambiguous")
+    values = {key: _text(value) for key, value in fields.items()}
+    code = raw["statusCode"]
+    if not isinstance(code, str) or not re.fullmatch(r"[0-9]{1,4}", code):
+        raise ReservationReadError("status_code_invalid")
+    return ReservationDetail(
+        values["Codice Prenotazione"], values["Servizio Consolare"], values["Servizio Erogato"],
+        values["Tipo Prenotazione"], _day(values["Data"]), _appointment_time(values["Ora"]),
+        values["Stato"], code, _state(values["Stato"], code),
+    )
+
+
+def _coverage(table: dict) -> tuple[int, int]:
+    info, count = table.get("info"), table.get("count")
+    if not isinstance(info, dict) or type(count) is not int or not 0 <= count <= MAX_PROTOCOL_ITEMS:
+        raise ReservationReadError("coverage_invalid")
+    keys = ("recordsTotal", "recordsDisplay", "page", "pages", "start", "end", "length")
+    if any(type(info.get(k)) is not int for k in keys) or info.get("serverSide") is not False:
+        raise ReservationReadError("coverage_invalid")
+    total, displayed, page, pages, start, end, length = (info[k] for k in keys)
+    if total != count or displayed != count or not 0 <= start <= end <= count:
+        raise ReservationReadError("coverage_incomplete")
+    expected_pages = (math.ceil(count / length) if length > 0 else 1) if count else 0
+    if (length not in (-1,) and length <= 0) or pages != expected_pages or not 0 <= page < max(1, pages):
+        raise ReservationReadError("pagination_invalid")
+    if start != (page * length if length > 0 else 0) or end != (min(start + length, count) if length > 0 else count):
+        raise ReservationReadError("pagination_invalid")
+    return count, pages
+
+
+def parse_reservation_listing(raw: object) -> ReservationListing:
+    if not isinstance(raw, dict) or set(raw) != {"path", "tables"} or raw["path"] != LIST_PATH:
+        raise ReservationReadError("list_schema_changed")
+    tables = raw["tables"]
+    if not isinstance(tables, list) or len(tables) != 2 or not all(isinstance(t, dict) for t in tables):
+        raise ReservationReadError("table_ambiguous")
+    main, waitlist = tables
+    if main.get("id") != "dataTableReservations" or waitlist.get("id") != "dataTableReservationsWL":
+        raise ReservationReadError("table_ambiguous")
+    if main.get("structuralEmpty") is not False or main.get("headers") not in (list(HEADERS), [*HEADERS, ""]):
+        raise ReservationReadError("headers_changed")
+    count, pages = _coverage(main)
+    if waitlist.get("structuralEmpty") is True:
+        if set(waitlist) != {"id", "structuralEmpty"}:
+            raise ReservationReadError("waitlist_ambiguous")
+    elif waitlist.get("structuralEmpty") is not False or _coverage(waitlist)[0] != 0:
+        raise ReservationReadError("waitlist_schema_unverified")
+    rows = main.get("rows")
+    if not isinstance(rows, list) or len(rows) != count:
+        raise ReservationReadError("row_nodes_incomplete")
+    result, references, destinations = [], set(), set()
+    for row in rows:
+        if not isinstance(row, dict) or set(row) != {"reference", "detailUrl", "office", "service", "date", "time", "status"}:
+            raise ReservationReadError("row_schema_changed")
+        values = {key: _text(value) for key, value in row.items()}
+        path = _detail_path(values["detailUrl"])
+        if values["reference"] in references or path in destinations:
+            raise ReservationReadError("duplicate_record")
+        references.add(values["reference"])
+        destinations.add(path)
+        result.append(ReservationListRow(values["reference"], values["detailUrl"], values["office"],
+                                        values["service"], _day(values["date"]), _appointment_time(values["time"]),
+                                        values["status"], _state(values["status"])))
+    return ReservationListing(tuple(result), pages)
+
+
+def _read_current(page: object, script: str, *, detail: bool) -> object:
+    try:
+        before_url, before_tab = page.url, page.tab_id
+        path, parsed = same_origin_path(before_url)
+        if parsed.query or parsed.fragment or (not detail and path != LIST_PATH):
+            raise ReservationReadError("wrong_page")
+        if detail:
+            _detail_path(before_url)
+        if not isinstance(before_tab, str) or not before_tab:
+            raise ReservationReadError("context_changed")
+        raw = page.run_js(script)
+        if page.url != before_url or page.tab_id != before_tab:
+            raise ReservationReadError("context_changed")
+        if not isinstance(raw, dict) or raw.get("path") != path:
+            reason = "not_ready" if isinstance(raw, dict) and raw == {"error": "not_ready"} else "page_read_rejected"
+            raise ReservationReadError(reason)
+        return raw
+    except ReservationReadError:
+        raise
+    except Exception:
+        raise ReservationReadError("browser_read_failed") from None
+
+
+def read_reservation_detail(page: object) -> ReservationDetail:
+    """Read the current detail page once. No URL, reference or PII is logged."""
+    return parse_reservation_detail(_read_current(page, DETAIL_READ_SCRIPT, detail=True))
+
+
+def read_reservation_listing(page: object, *, timeout: float = 5, poll_interval: float = 0.25) -> ReservationListing:
+    """Two stable reads within a bound, reusing the existing count tool pattern.
+
+Only not-ready states are polled; unsupported schemas/coverage fail closed.
+This checks the current page and never navigates, draws or clears filters.
+"""
+    if (any(type(v) not in (int, float) or not math.isfinite(v) or v <= 0 for v in (timeout, poll_interval))
+            or poll_interval > timeout or timeout > 60):
+        raise ReservationReadError("wait_config_invalid")
+    try:
+        binding = (page.url, page.tab_id)
+    except Exception:
+        raise ReservationReadError("browser_read_failed") from None
+    deadline, previous = time.monotonic() + timeout, None
+    while time.monotonic() < deadline:
+        try:
+            try:
+                context_matches = (page.url, page.tab_id) == binding
+            except Exception:
+                raise ReservationReadError("browser_read_failed") from None
+            if not context_matches:
+                raise ReservationReadError("context_changed")
+            current = parse_reservation_listing(_read_current(page, LIST_READ_SCRIPT, detail=False))
+        except ReservationReadError as error:
+            if error.reason != "not_ready":
+                raise
+            previous = None
+        else:
+            if current == previous:
+                return current
+            previous = current
+        time.sleep(min(poll_interval, max(0, deadline - time.monotonic())))
+    raise ReservationReadError("stability_timeout")

+ 66 - 0
plugins/ita_turnstile.py

@@ -0,0 +1,66 @@
+"""Bounded Calendar-preparation interaction, composing the existing VFS helper.
+
+This adapter never declares success: Italy's next preflight must observe the
+actual response field AND an enabled AVANTI. No refresh, reset, token injection,
+OTP action, blanket DFS search, or final submission lives here.
+"""
+from __future__ import annotations
+
+import json
+
+from plugins.ita_calendar_query import CalendarGateError
+from plugins.ita_calendar_session import BookingPreflightStage
+from utils.cloudflare_bypass_for_scraping import CloudflareBypasser
+
+
+class ItalyTurnstileRecovery:
+    """One instance per Query/Book preparation; three attempts across stages."""
+
+    MAX_ATTEMPTS = 3
+    INITIAL_DELAY = 5
+    RETRY_INTERVAL = 10
+
+    def __init__(self, page, *, check_current):
+        self.page = page
+        self.check_current = check_current
+        self.attempts = 0
+        self._stage = None
+        self._next_attempt = self.INITIAL_DELAY
+        self._helper = None
+
+    def __call__(self, raw, *, stage, elapsed, remaining):
+        if not isinstance(stage, BookingPreflightStage):
+            raise CalendarGateError("Italy Turnstile interaction stage invalid")
+        if (not isinstance(raw, dict) or raw.get("pathMatches") is not True
+                or raw.get("formPresent") is not True or type(raw.get("turnstileCount")) is not int
+                or raw.get("turnstileCount") != 1):
+            raise CalendarGateError("Italy Turnstile interaction requires the verified booking form")
+        if raw.get("turnstileTokenPresent") is not False:
+            return  # Never touch a verified widget to fix an unrelated button.
+        if self._stage is not stage:
+            self._stage = stage
+            self._next_attempt = self.INITIAL_DELAY
+        if self.attempts >= self.MAX_ATTEMPTS or elapsed < self._next_attempt or remaining < 2:
+            return
+
+        self.check_current()
+        self.attempts += 1
+        self._next_attempt = elapsed + self.RETRY_INTERVAL
+        clicked = False
+        failed = False
+        try:
+            if self._helper is None:
+                # Reuse the exact helper used by VFS. Suppress its free-form
+                # browser exceptions; emit only fixed Italy metadata below.
+                self._helper = CloudflareBypasser(self.page, log=False)
+            # Do NOT use bypass(): its page-title success check would accept
+            # "Booking - Prenot@Mi" while the embedded widget is still pending.
+            clicked = self._helper.click_verification_button(is_dfs=False) is True
+        except Exception:
+            failed = True
+        self.check_current()
+        print("ITA_BOOK_TURNSTILE_INTERACTION=" + json.dumps({
+            "contract": "ita-book-preflight-v2", "stage": stage.value,
+            "attempt": self.attempts, "maxAttempts": self.MAX_ATTEMPTS,
+            "clicked": clicked, "helperFailed": failed,
+        }, sort_keys=True), flush=True)

+ 236 - 0
plugins/ita_workflow.py

@@ -0,0 +1,236 @@
+"""Compose Italy's verified site adapters behind the normal plugin interface.
+
+No scheduler, queue, or local test-gate dependency. Calendar preparation uses
+one explicit manual/cloud OTP provider for either role. Only applicant Book
+may enter the separately enabled final submission and receipt reconciliation.
+"""
+from __future__ import annotations
+
+import re
+import sys
+from time import monotonic
+from threading import Lock
+
+from plugins import ita_calendar_session as preparation
+from plugins.ita_calendar_book import wait_for_calendar_service
+from plugins.ita_calendar_query import CALENDAR_PATH, CalendarGateError, guard_calendar, listen_once, same_origin_path
+from plugins.ita_booking_final import FinalBookingAttempt, FinalOutcomeUnknown, NativeFinalSubmitter, VerifiedSubmission
+from plugins.ita_final_read_port import FinalReceiptReadPort
+from plugins.ita_protocol import ItaCapability
+from plugins.ita_otp import fetch_otp_from_cloud, utc_sent_at, validate_cloud_otp_environment
+from plugins.ita_turnstile import ItalyTurnstileRecovery
+from vs_types import BizLogicError, PermissionDeniedError
+
+
+# Reuse the existing preparation lock, including cloud reads: no competing OTP
+# requests inside this process. This does not coordinate other worker processes.
+_OTP_INPUT_LOCK = Lock()
+
+
+def prepare_calendar(plugin, route, *, role):
+    """One native OTP + AVANTI, using the same functions as the tested gate."""
+    if (role not in {"query", "book"} or route.capability is not ItaCapability.SINGLE_SCHENGEN_TOURISM
+            or route.calendar_scan is None):
+        raise BizLogicError("Italy Calendar preparation requires a single-tourism route")
+    cloud = plugin.free_config.get("otp_mode") == "cloud"
+    if cloud:
+        query_config = plugin.free_config.get("query_mode", "services_probe") == "calendar"
+        if ((role == "query") != query_config
+                or plugin._book_final_configuration_valid() is not True):
+            raise PermissionDeniedError("Italy automatic OTP requires a matching Query/Book role and valid final configuration")
+        validate_cloud_otp_environment(route.mail, plugin.config.account.username)
+    elif plugin.free_config.get("otp_mode") != "manual" or not sys.stdin.isatty():
+        raise PermissionDeniedError("Italy Calendar needs an attached terminal for manual OTP (ITA-OTP-01)")
+    page, generation = plugin.page, plugin.session_create_time
+    username = plugin.config.account.username.strip().casefold()
+    tab_id = page.tab_id
+    booking_path = plugin._booking_path(route)
+
+    def current(path):
+        if (plugin.page is not page or page.tab_id != tab_id or plugin.session_create_time != generation
+                or plugin.config.account.username.strip().casefold() != username
+                or same_origin_path(page.url)[0] != path):
+            raise CalendarGateError("Italy preparation Session or page changed")
+
+    def packet_current(packet):
+        if getattr(packet, "tab_id", None) != tab_id or getattr(packet, "is_failed", None) is not False:
+            raise CalendarGateError("Italy preparation response came from another tab or failed")
+
+    def click(selector):
+        current(booking_path)
+        plugin.mouse.human_click_ele(preparation._element_or_fail(page, selector))
+
+    # A failed partial preparation cannot resend OTP on every Query signal.
+    # A fresh login/session permits another operator-assisted attempt.
+    preparation_key = (generation, tab_id, route.routing_key)
+    with _OTP_INPUT_LOCK:
+        if getattr(plugin, "_manual_preparation_attempt", None) == preparation_key:
+            raise PermissionDeniedError("Italy preparation failed; restore the session before retrying")
+        current(booking_path)
+        script = preparation.guarded_preflight_script(route, booking_path)
+        check_form = lambda: current(booking_path)
+        # Both roles must pass the same form before entering Calendar. Reuse
+        # one bounded recovery across both stages; prepared scans skip this path.
+        recovery = ItalyTurnstileRecovery(page, check_current=check_form)
+        plugin._log(f"Italy {role} Calendar preparation: reusing bounded Turnstile recovery.")
+        preparation.wait_for_booking_preflight(page, script=script,
+                                              check_current=check_form, wait_action=recovery)
+        plugin._manual_preparation_attempt = preparation_key
+        sent_at, sent_monotonic = None, None
+
+        def send_otp():
+            nonlocal sent_at, sent_monotonic
+            if cloud:
+                validate_cloud_otp_environment(route.mail, username)
+                sent_at, sent_monotonic = utc_sent_at(), monotonic()
+            click("#otp-send")
+
+        def check_cloud_window():
+            if cloud and (sent_monotonic is None or
+                          not 0 <= monotonic() - sent_monotonic < route.mail.expiry_seconds):
+                raise CalendarGateError("Italy OTP local read window expired; no automatic resend")
+
+        packet = listen_once(page, target=preparation.OTP_PATH, method="GET", timeout=30,
+                             action=send_otp)
+        packet_current(packet)
+        preparation.validate_otp_packet(packet, service_id=route.service_id)
+        current(booking_path)
+        if cloud:
+            check_cloud_window()
+            plugin._log(f"Italy {role} OTP sent; waiting for the authorized mailbox (one read attempt).")
+            otp = fetch_otp_from_cloud(route.mail, recipient=username, sent_at=sent_at)
+        else:
+            plugin._log(f"Italy {role} OTP sent; enter the code in this terminal.")
+            otp = preparation._read_manual_otp()
+        try:
+            pattern = r"[0-9]{6}" if cloud else r"[0-9]{4,12}"
+            if not isinstance(otp, str) or re.fullmatch(pattern, otp) is None:
+                raise CalendarGateError("Italy OTP format rejected")
+            current(booking_path)
+            check_cloud_window()
+            try:
+                preparation._enter_otp(plugin, otp)
+            except Exception:
+                if cloud:
+                    # Browser transport exceptions may contain typed values.
+                    raise CalendarGateError("Italy automatic OTP DOM write verification failed") from None
+                raise
+            if cloud:
+                plugin._log("Italy automatic OTP DOM write verified; continuing to Calendar.")
+        finally:
+            del otp
+        preparation.wait_for_booking_preflight(
+            page, script=script, stage=preparation.BookingPreflightStage.AFTER_OTP_SEND,
+            check_current=check_form, wait_action=recovery,
+        )
+        check_cloud_window()
+        try:
+            page.set.auto_handle_alert(accept=True)
+            packet = listen_once(page, target=booking_path, method="POST", timeout=30,
+                                 action=lambda: click("#btnAvanti"))
+            packet_current(packet)
+            preparation._wait_for_calendar(page)
+            current(CALENDAR_PATH)
+            preparation.validate_avanti_packet(packet, booking_path=booking_path, final_page_url=page.url)
+        finally:
+            page.set.auto_handle_alert(on_off=False)
+        guard_calendar(page)
+        wait_for_calendar_service(page, session_is_current=lambda: current(CALENDAR_PATH) is None)
+        if role == "query":
+            plugin._record_calendar_query_prepared_route(route)
+        else:
+            plugin._record_calendar_book_prepared_route(route)
+        plugin._manual_preparation_attempt = None
+
+
+def prepare_query_if_needed(plugin, apt_type):
+    """Return a negative entry result, or prepare and let Query scan real dates."""
+    if same_origin_path(plugin.page.url)[0] == CALENDAR_PATH:
+        return None  # Existing Query continuity checks remain authoritative.
+    route = plugin._resolve_route(apt_type)
+    entry = plugin._query_once(apt_type, query_mode="services_probe")
+    if not entry.success:
+        return entry
+    plugin._clear_calendar_query_state()
+    prepare_calendar(plugin, route, role="query")
+    return None
+
+
+def book(plugin, slot_info, user_inputs):
+    """Applicant-owned Calendar → existing pre-final adapter → standard result."""
+    if plugin._book_final_configuration_valid() is not True:
+        raise PermissionDeniedError("Italy final submission configuration is invalid")
+    if not isinstance(user_inputs, dict) or not isinstance(user_inputs.get("username"), str):
+        raise BizLogicError("Italy Book requires the applicant username")
+    username = user_inputs["username"].strip().casefold()
+    if (not username or username != plugin.config.account.username.strip().casefold()
+            or plugin.free_config.get("query_mode", "services_probe") == "calendar"
+            or getattr(plugin, "_calendar_query_route_key", None) is not None):
+        raise BizLogicError("Italy Book requires a separate applicant Session, not a Query Session")
+    route = plugin._resolve_route(slot_info.apt_type)
+    attempt = getattr(plugin, "_production_final_attempt", None)
+    if attempt is not None and attempt.state not in {"blocked", "rejected"}:
+        # The same task may retry success reporting, but must never submit twice.
+        result = getattr(plugin, "_production_book_result", None)
+        if (attempt.state == "confirmed" and result is not None
+                and attempt.target.applicant == username and attempt.target.routing_key == route.routing_key):
+            return result
+        raise FinalOutcomeUnknown()
+
+    if same_origin_path(plugin.page.url)[0] != CALENDAR_PATH:
+        entry = plugin._book_discovery_or_prepared(slot_info, user_inputs)
+        if entry.label != "booking-form-ready-before-avanti":
+            return entry
+        prepare_calendar(plugin, route, role="book")
+    elif plugin._calendar_book_context_matches(route, username):
+        # Refresh inventory on the next signal after a definite negative result.
+        plugin._calendar_book_attempted = False
+    result = plugin._book_discovery_or_prepared(slot_info, user_inputs)
+    if plugin.last_booking_precommit is None or plugin.free_config.get("final_submit_enabled") is not True:
+        return result
+    return submit_final(plugin, route)
+
+
+def submit_final(plugin, route, *, request_audit: preparation.CalendarRequestAudit | None = None):
+    """Reuse native submission and attribution with one audit per page.
+
+    A caller observing the whole workflow may lend its live audit. Ownership
+    stays with that caller; standalone production calls own their audit as
+    before. Neither path replaces callbacks or interrupts request coverage.
+    """
+    port = FinalReceiptReadPort(plugin, route)
+    owns_audit = request_audit is None
+    audit = preparation.CalendarRequestAudit(plugin.page, include_time_slots=True) if owns_audit else request_audit
+    if owns_audit:
+        audit.start()
+    else:
+        audit.require_active_on(plugin.page)
+        if "timeSlotRequests" not in audit.snapshot():
+            raise CalendarGateError("Final request audit must include time slots")
+    try:
+        before = audit.settled_snapshot()
+
+        def submit():
+            native = NativeFinalSubmitter(plugin.page, port.target, port.session_is_current)
+            signal = native()
+            after = audit.settled_snapshot()
+            if (after["finalRequests"] - before["finalRequests"] == 1
+                    and all(after[key] == before[key] for key in before if key != "finalRequests")
+                    and isinstance(native.submitted_selection, VerifiedSubmission)):
+                port.record_submission(native.submitted_selection)
+            return signal
+
+        attempt = FinalBookingAttempt(port.target, read_reservations=port, submit_native=submit,
+                                      session_is_current=port.session_is_current)
+        plugin._production_final_attempt = attempt
+        result = attempt.execute(enabled=True)
+        plugin._production_book_result = result if result.success else None
+        return result
+    finally:
+        # A diagnostic teardown failure must not turn a verified success into a
+        # generic booking failure (and a second real booking on the next signal).
+        if owns_audit:
+            try:
+                audit.stop()
+            except Exception:
+                plugin._log("Italy passive request audit cleanup failed; session needs cleanup.")

+ 310 - 0
test/test_add_ita_query_account.py

@@ -0,0 +1,310 @@
+import ast
+import io
+import json
+import subprocess
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+
+import requests
+
+from tools.add_ita_query_account import (
+    ACCOUNT_POOL,
+    ACCOUNT_UPLOAD_URL,
+    SERVICE_ID,
+    run_account_upload,
+)
+
+
+class FakeResponse:
+    def __init__(self, *, status_code=200, body=None, json_error=None):
+        self.status_code = status_code
+        self.body = body if body is not None else {"code": 0, "data": {"id": 42}}
+        self.json_error = json_error
+
+    def json(self):
+        if self.json_error is not None:
+            raise self.json_error
+        return self.body
+
+
+class FakeSession:
+    def __init__(self, *, response=None, error=None):
+        self.response = response or FakeResponse()
+        self.error = error
+        self.calls = []
+        self.trust_env = True
+
+    def post(self, url, **kwargs):
+        self.calls.append((url, kwargs))
+        if self.error is not None:
+            raise self.error
+        return self.response
+
+
+class AddItaQueryAccountTests(unittest.TestCase):
+    ENV = {
+        "ITA_QUERY_USERNAME": "authorized-query@example.test",
+        "ITA_QUERY_PASSWORD": "offline-password",
+        "VS_ACCOUNT_UPLOAD_TOKEN": "offline-api-token",
+    }
+
+    @staticmethod
+    def _run(*, env=None, apply=False, config_path=None, session=None):
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        with redirect_stdout(stdout), redirect_stderr(stderr):
+            exit_code = run_account_upload(
+                env or {},
+                apply=apply,
+                non_interactive=True,
+                config_path=config_path,
+                session=session,
+            )
+        return exit_code, stdout.getvalue(), stderr.getvalue()
+
+    def test_default_preflight_sends_no_request_and_needs_no_credentials(self):
+        session = FakeSession(error=AssertionError("post must not be called"))
+
+        exit_code, stdout, stderr = self._run(session=session)
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(session.calls, [])
+        self.assertIn(
+            "ITA_ACCOUNT_UPLOAD_PREFLIGHT_OK "
+            f"pool={ACCOUNT_POOL} service_id={SERVICE_ID} request_sent=false",
+            stdout,
+        )
+        self.assertEqual(stderr, "")
+
+    def test_cli_default_dry_run_starts_from_the_repository_root(self):
+        repo_root = Path(__file__).resolve().parents[1]
+        completed = subprocess.run(
+            [sys.executable, str(repo_root / "tools" / "add_ita_query_account.py")],
+            cwd=repo_root,
+            check=False,
+            capture_output=True,
+            text=True,
+        )
+
+        self.assertEqual(completed.returncode, 0)
+        self.assertIn("request_sent=false", completed.stdout)
+        self.assertEqual(completed.stderr, "")
+
+    def test_apply_sends_exactly_one_locked_pool_request_without_logging_secrets(self):
+        session = FakeSession()
+
+        exit_code, stdout, stderr = self._run(
+            env=self.ENV,
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(len(session.calls), 1)
+        url, kwargs = session.calls[0]
+        self.assertEqual(url, ACCOUNT_UPLOAD_URL)
+        self.assertEqual(kwargs["json"]["pool_name"], ACCOUNT_POOL)
+        self.assertEqual(kwargs["json"]["username"], self.ENV["ITA_QUERY_USERNAME"])
+        self.assertEqual(kwargs["json"]["password"], self.ENV["ITA_QUERY_PASSWORD"])
+        self.assertEqual(kwargs["json"]["extra_data"]["service_id"], SERVICE_ID)
+        self.assertEqual(kwargs["timeout"], 10)
+        self.assertFalse(session.trust_env)
+        self.assertIn("account_id=42 request_count=1", stdout)
+        combined_output = stdout + stderr
+        for secret in self.ENV.values():
+            self.assertNotIn(secret, combined_output)
+
+    def test_apply_reads_ignored_local_config_and_logs_no_secret(self):
+        local_values = {
+            "username": "local-authorized@example.test",
+            "password": "local-password",
+            "account_upload_token": "local-api-token",
+        }
+        session = FakeSession()
+        with tempfile.TemporaryDirectory() as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text(json.dumps(local_values), encoding="utf-8")
+            config_path.chmod(0o600)
+
+            exit_code, stdout, stderr = self._run(
+                apply=True,
+                config_path=config_path,
+                session=session,
+            )
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(len(session.calls), 1)
+        _, kwargs = session.calls[0]
+        self.assertEqual(kwargs["json"]["username"], local_values["username"])
+        self.assertEqual(kwargs["json"]["password"], local_values["password"])
+        combined_output = stdout + stderr
+        for secret in local_values.values():
+            self.assertNotIn(secret, combined_output)
+
+    def test_invalid_local_config_fails_before_request_without_content_leak(self):
+        session = FakeSession(error=AssertionError("post must not be called"))
+        with tempfile.TemporaryDirectory() as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text('{"password": "private-value",', encoding="utf-8")
+            config_path.chmod(0o600)
+
+            exit_code, stdout, stderr = self._run(
+                apply=True,
+                config_path=config_path,
+                session=session,
+            )
+
+        self.assertEqual(exit_code, 2)
+        self.assertEqual(session.calls, [])
+        self.assertEqual(stdout, "")
+        self.assertIn("local config is invalid JSON", stderr)
+        self.assertNotIn("private-value", stderr)
+
+    def test_environment_values_override_local_config(self):
+        local_values = {
+            "username": "stale@example.test",
+            "password": "stale-password",
+            "account_upload_token": "stale-token",
+        }
+        session = FakeSession()
+        with tempfile.TemporaryDirectory() as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text(json.dumps(local_values), encoding="utf-8")
+            config_path.chmod(0o600)
+
+            exit_code, _, _ = self._run(
+                env=self.ENV,
+                apply=True,
+                config_path=config_path,
+                session=session,
+            )
+
+        self.assertEqual(exit_code, 0)
+        _, kwargs = session.calls[0]
+        self.assertEqual(kwargs["json"]["username"], self.ENV["ITA_QUERY_USERNAME"])
+        self.assertEqual(kwargs["json"]["password"], self.ENV["ITA_QUERY_PASSWORD"])
+
+    def test_missing_non_interactive_credentials_fails_before_request(self):
+        session = FakeSession(error=AssertionError("post must not be called"))
+
+        exit_code, stdout, stderr = self._run(
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 2)
+        self.assertEqual(session.calls, [])
+        self.assertEqual(stdout, "")
+        self.assertIn("ITA_ACCOUNT_UPLOAD_CONFIG_ERROR", stderr)
+
+    def test_http_rejection_does_not_print_response_body_or_retry(self):
+        response = FakeResponse(
+            status_code=409,
+            body={"message": "authorized-query@example.test already exists"},
+        )
+        session = FakeSession(response=response)
+
+        exit_code, stdout, stderr = self._run(
+            env=self.ENV,
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(len(session.calls), 1)
+        self.assertEqual(stdout, "")
+        self.assertIn("status=409 request_count=1", stderr)
+        self.assertNotIn("already exists", stderr)
+        self.assertNotIn(self.ENV["ITA_QUERY_USERNAME"], stderr)
+
+    def test_transport_error_is_uncertain_and_explicitly_forbids_blind_retry(self):
+        session = FakeSession(error=requests.Timeout("sensitive request details"))
+
+        exit_code, stdout, stderr = self._run(
+            env=self.ENV,
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 5)
+        self.assertEqual(len(session.calls), 1)
+        self.assertEqual(stdout, "")
+        self.assertIn("ITA_ACCOUNT_UPLOAD_UNCERTAIN", stderr)
+        self.assertIn("action=verify-admin-before-retry", stderr)
+        self.assertNotIn("sensitive request details", stderr)
+
+    def test_invalid_success_json_is_uncertain_not_success(self):
+        session = FakeSession(
+            response=FakeResponse(json_error=ValueError("secret response"))
+        )
+
+        exit_code, stdout, stderr = self._run(
+            env=self.ENV,
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 5)
+        self.assertEqual(len(session.calls), 1)
+        self.assertEqual(stdout, "")
+        self.assertIn("type=InvalidJson", stderr)
+        self.assertNotIn("secret response", stderr)
+
+    def test_business_error_is_rejected_without_message_leak(self):
+        session = FakeSession(
+            response=FakeResponse(
+                body={"code": 40001, "message": "private server detail"}
+            )
+        )
+
+        exit_code, stdout, stderr = self._run(
+            env=self.ENV,
+            apply=True,
+            session=session,
+        )
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(len(session.calls), 1)
+        self.assertEqual(stdout, "")
+        self.assertIn("status=business-error", stderr)
+        self.assertNotIn("private server detail", stderr)
+
+    def test_source_has_one_post_call_no_retry_loop_and_no_secret_cli_flags(self):
+        source_path = (
+            Path(__file__).resolve().parents[1]
+            / "tools"
+            / "add_ita_query_account.py"
+        )
+        source = source_path.read_text(encoding="utf-8")
+        tree = ast.parse(source)
+        upload_function = next(
+            node
+            for node in tree.body
+            if isinstance(node, ast.FunctionDef)
+            and node.name == "run_account_upload"
+        )
+        post_calls = [
+            node
+            for node in ast.walk(upload_function)
+            if isinstance(node, ast.Call)
+            and isinstance(node.func, ast.Attribute)
+            and node.func.attr == "post"
+        ]
+        retry_loops = [
+            node
+            for node in ast.walk(upload_function)
+            if isinstance(node, (ast.For, ast.While))
+        ]
+
+        self.assertEqual(len(post_calls), 1)
+        self.assertEqual(retry_loops, [])
+        self.assertNotIn("--username", source)
+        self.assertNotIn("--password", source)
+        self.assertNotIn("--token", source)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 603 - 0
test/test_debug_ita_book.py

@@ -0,0 +1,603 @@
+import ast
+import io
+import tempfile
+import unittest
+from contextlib import ExitStack, redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from plugins.ita_plugin import (
+    BOOKING_CALENDAR_PREFINAL_STOP_LABEL,
+    BOOKING_FORM_DISCOVERY_STOP_LABEL,
+    BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+)
+from tools.debug_ita_book import (
+    _assert_distinct_local_accounts,
+    run_book_recheck_once,
+)
+from tools.debug_ita_session import DebugConfigurationError
+from vs_types import AvailabilityStatus, BizLogicError, VSAccount, VSBookResult
+
+
+class FakeBookDebugElement:
+    def __init__(self, text):
+        self.text = text
+
+
+class FakeBookDebugPage:
+    def __init__(self):
+        self.url = "https://prenotami.esteri.it/UserArea?state=sensitive-state"
+        self.popup_text = ""
+
+    def ele(self, selector, timeout=None):
+        del timeout
+        if selector == ".jconfirm-content" and self.popup_text:
+            return FakeBookDebugElement(self.popup_text)
+        return None
+
+
+class FakeBookDebugPlugin:
+    behavior = "none-available"
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = FakeBookDebugPage()
+        self.last_booking_form_structure = None
+        self.create_session_calls = 0
+        self.book_calls = 0
+        self.cleanup_called = False
+        self.last_trigger = None
+        self.events = []
+        FakeBookDebugPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        self.create_session_calls += 1
+        self.events.append("create-session")
+
+    def book(self, trigger, user_inputs=None):
+        del user_inputs
+        self.last_trigger = trigger
+        self.book_calls += 1
+        self.events.append("book")
+        if self.behavior == "booking-form":
+            self.last_booking_form_structure = {
+                "path": "/Services/Booking/1321",
+                "form": {
+                    "method": "POST",
+                    "action_path": "/Services/Booking/1321",
+                    "secret": "must-not-appear",
+                },
+                "field_count": 1,
+                "fields": [
+                    {
+                        "tag": "input",
+                        "type": "hidden",
+                        "id": "RequestToken",
+                        "name": "__RequestVerificationToken",
+                        "required": False,
+                        "value": "private@example.test",
+                    }
+                ],
+                "button_count": 1,
+                "buttons": [
+                    {
+                        "tag": "button",
+                        "type": "submit",
+                        "id": "btnAvanti",
+                        "name": None,
+                        "text": "Avanti",
+                        "value": "server-secret",
+                    }
+                ],
+            }
+            return VSBookResult(
+                success=False,
+                label=BOOKING_FORM_DISCOVERY_STOP_LABEL,
+            )
+        if self.behavior == "unexpected-success":
+            return VSBookResult(success=True)
+        if self.behavior == "unexpected-error":
+            self.page.popup_text = "Account private@example.test ref 12345678"
+            raise RuntimeError(
+                "failed at https://iam.esteri.it/signin/"
+                "?state=sensitive-state&code_challenge=sensitive-challenge"
+            )
+        return VSBookResult(
+            success=False,
+            label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+        )
+
+    def cleanup(self):
+        self.cleanup_called = True
+        self.events.append("cleanup")
+
+
+class DebugItaBookSafetyTests(unittest.TestCase):
+    def setUp(self):
+        FakeBookDebugPlugin.behavior = "none-available"
+        FakeBookDebugPlugin.last_instance = None
+
+    @staticmethod
+    def _run(*, arm=False, input_side_effect=None):
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        env = {
+            "ITA_USERNAME": "offline-test@example.test",
+            "ITA_PASSWORD": "offline-password",
+        }
+        if input_side_effect is None:
+            input_side_effect = lambda _prompt: (
+                FakeBookDebugPlugin.last_instance.events.append("release")
+            )
+        with (
+            patch(
+                "tools.debug_ita_book.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch("tools.debug_ita_book.ItaPlugin", FakeBookDebugPlugin),
+            patch.dict("tools.debug_ita_book.os.environ", {}, clear=False),
+            patch(
+                "builtins.input",
+                side_effect=input_side_effect,
+            ) as input_mock,
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_book_recheck_once(
+                env,
+                non_interactive=True,
+                arm=arm,
+            )
+        return exit_code, stdout.getvalue(), stderr.getvalue(), input_mock
+
+    def test_no_slot_recheck_calls_book_once_and_cleans_up(self):
+        exit_code, stdout, stderr, _input_mock = self._run()
+        plugin = FakeBookDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(plugin.create_session_calls, 1)
+        self.assertEqual(plugin.book_calls, 1)
+        self.assertTrue(plugin.last_trigger.success)
+        self.assertEqual(
+            plugin.last_trigger.availability_status,
+            AvailabilityStatus.NoneAvailable,
+        )
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn("book_attempt=1", stdout)
+        self.assertIn("ITA_BOOK_RECHECK_NONE_AVAILABLE service_id=1321", stdout)
+        self.assertIn("ITA_BOOK_CLEANUP_OK", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_booking_form_is_reported_without_values_or_submission(self):
+        FakeBookDebugPlugin.behavior = "booking-form"
+
+        exit_code, stdout, stderr, _input_mock = self._run()
+        plugin = FakeBookDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(plugin.book_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn("ITA_BOOKING_FORM_STRUCTURE=", stdout)
+        self.assertIn('"action_path": "/Services/Booking/1321"', stdout)
+        self.assertIn("stage=before-avanti submit_attempts=0", stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("server-secret", stdout)
+        self.assertNotIn("must-not-appear", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_unexpected_success_stops_safely(self):
+        FakeBookDebugPlugin.behavior = "unexpected-success"
+
+        exit_code, stdout, _stderr, _input_mock = self._run()
+
+        self.assertEqual(exit_code, 4)
+        self.assertIn("reason=unexpected-success-before-avanti", stdout)
+
+    def test_unexpected_error_is_sanitized_and_not_retried(self):
+        FakeBookDebugPlugin.behavior = "unexpected-error"
+
+        exit_code, stdout, stderr, _input_mock = self._run()
+        plugin = FakeBookDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(plugin.book_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertNotIn("sensitive-state", stdout)
+        self.assertNotIn("sensitive-challenge", stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("12345678", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_arm_waits_after_login_and_before_the_single_book_call(self):
+        exit_code, stdout, stderr, input_mock = self._run(arm=True)
+        plugin = FakeBookDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(
+            plugin.events,
+            ["create-session", "release", "book", "cleanup"],
+        )
+        input_mock.assert_called_once()
+        self.assertIn(
+            "ITA_BOOK_ARMED service_id=1321 "
+            "routing_key=slot.dub.it.tourist stage=user-area",
+            stdout,
+        )
+        self.assertEqual(stderr, "")
+
+    def test_ctrl_c_cancels_armed_mode_without_book_or_traceback(self):
+        exit_code, stdout, stderr, input_mock = self._run(
+            arm=True,
+            input_side_effect=KeyboardInterrupt,
+        )
+        plugin = FakeBookDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 130)
+        self.assertEqual(plugin.book_calls, 0)
+        self.assertEqual(plugin.events, ["create-session", "cleanup"])
+        input_mock.assert_called_once()
+        self.assertIn(
+            "ITA_BOOK_ARM_CANCELLED service_id=1321 "
+            "routing_key=slot.dub.it.tourist book_attempts=0",
+            stdout,
+        )
+        self.assertIn("ITA_BOOK_CLEANUP_OK", stdout)
+        self.assertNotIn("Traceback", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_local_signal_wait_claims_once_before_the_single_book_call(self):
+        claimed = []
+
+        def claim():
+            claimed.append("claim")
+            return object()
+
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        env = {
+            "ITA_USERNAME": "book-user@example.test",
+            "ITA_PASSWORD": "offline-password",
+        }
+        with (
+            patch(
+                "tools.debug_ita_book.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch("tools.debug_ita_book._assert_distinct_local_accounts"),
+            patch("tools.debug_ita_book.ItaPlugin", FakeBookDebugPlugin),
+            patch.dict("tools.debug_ita_book.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_book_recheck_once(
+                env,
+                non_interactive=True,
+                wait_for_local_signal=True,
+                signal_timeout=1,
+                signal_claimer=claim,
+                monotonic=lambda: 0.0,
+                sleep=lambda _seconds: None,
+            )
+
+        plugin = FakeBookDebugPlugin.last_instance
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(claimed, ["claim"])
+        self.assertEqual(plugin.events, ["create-session", "book", "cleanup"])
+        self.assertEqual(plugin.book_calls, 1)
+        self.assertEqual(plugin.config.account.username, "book-user@example.test")
+        self.assertEqual(plugin.config.account.password, "offline-password")
+        self.assertNotIn(
+            "persistent_browser_profile_path",
+            plugin.config.free_config,
+        )
+        self.assertIn("ITA_BOOK_SIGNAL_CLAIMED", stdout.getvalue())
+        self.assertEqual(stderr.getvalue(), "")
+
+    def test_local_signal_timeout_never_calls_book(self):
+        clock = iter([0.0, 0.0, 2.0])
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        env = {
+            "ITA_USERNAME": "book-user@example.test",
+            "ITA_PASSWORD": "offline-password",
+        }
+        with (
+            patch(
+                "tools.debug_ita_book.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch("tools.debug_ita_book._assert_distinct_local_accounts"),
+            patch("tools.debug_ita_book.ItaPlugin", FakeBookDebugPlugin),
+            patch.dict("tools.debug_ita_book.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_book_recheck_once(
+                env,
+                non_interactive=True,
+                wait_for_local_signal=True,
+                signal_timeout=1,
+                signal_claimer=lambda: None,
+                monotonic=lambda: next(clock),
+                sleep=lambda _seconds: None,
+            )
+
+        plugin = FakeBookDebugPlugin.last_instance
+        self.assertEqual(exit_code, 5)
+        self.assertEqual(plugin.book_calls, 0)
+        self.assertIn("ITA_BOOK_SIGNAL_WAIT_TIMEOUT", stdout.getvalue())
+        self.assertIn("book_attempts=0", stdout.getvalue())
+        self.assertEqual(stderr.getvalue(), "")
+
+    def test_automatic_handoff_rejects_the_same_query_and_book_account(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            account_path = Path(temp_dir) / "query-account.json"
+            account_path.touch()
+            with (
+                patch("tools.debug_ita_book.ITA_QUERY_ACCOUNT_FILE", account_path),
+                patch(
+                    "tools.debug_ita_book.load_local_account",
+                    return_value=VSAccount(
+                        username="same@example.test",
+                        password="query-secret",
+                    ),
+                ),
+                self.assertRaisesRegex(
+                    DebugConfigurationError,
+                    "different Query and Book accounts",
+                ),
+            ):
+                _assert_distinct_local_accounts("SAME@example.test")
+
+    def test_role_check_accepts_different_query_and_book_accounts(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            account_path = Path(temp_dir) / "query-account.json"
+            account_path.touch()
+            with (
+                patch("tools.debug_ita_book.ITA_QUERY_ACCOUNT_FILE", account_path),
+                patch(
+                    "tools.debug_ita_book.load_local_account",
+                    return_value=VSAccount(
+                        username="query@example.test",
+                        password="query-secret",
+                    ),
+                ) as query_loader,
+            ):
+                _assert_distinct_local_accounts("book@example.test")
+
+            query_loader.assert_called_once_with(account_path)
+
+    def test_entrypoint_has_one_book_call_and_no_query_call(self):
+        source_path = (
+            Path(__file__).resolve().parents[1] / "tools" / "debug_ita_book.py"
+        )
+        tree = ast.parse(source_path.read_text(encoding="utf-8"))
+        book_calls = []
+        query_calls = []
+        for node in ast.walk(tree):
+            if not isinstance(node, ast.Call):
+                continue
+            if not isinstance(node.func, ast.Attribute):
+                continue
+            if node.func.attr == "book":
+                book_calls.append(node)
+            if node.func.attr == "query":
+                query_calls.append(node)
+
+        self.assertEqual(len(book_calls), 1)
+        self.assertEqual(query_calls, [])
+
+
+class DebugItaBookWorkflowTests(unittest.TestCase):
+    """Exercise the CLI contract with synthetic adapters, never a real browser."""
+
+    def setUp(self):
+        from tools import debug_ita_book as cli
+        from plugins import ita_calendar_book as calendar
+        from plugins import ita_calendar_session as session
+        from test.test_debug_ita_calendar_gate import gate_env
+        from test.test_ita_booking_final import target
+        self.cli = cli
+        self.env = {**gate_env(), "ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret"}
+        self.plugin = Mock()
+        self.plugin.last_booking_form_structure = None
+        self.plugin.last_booking_precommit = target().approval
+        self.plugin.book.return_value = VSBookResult(success=False, label=BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
+        self.counts = {"otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 3,
+                       "timeSlotRequests": 3, "finalRequests": 0}
+        self.audit = Mock()
+        self.audit.settled_snapshot.side_effect = lambda: dict(self.counts)
+        self.stack = ExitStack()
+        self.addCleanup(self.stack.close)
+        self.stack.enter_context(patch.object(cli, "ItaPlugin", return_value=self.plugin))
+        self.stack.enter_context(patch.object(cli, "resolve_chrome_path", return_value=Path("/offline/chrome")))
+        self.credentials = self.stack.enter_context(patch.object(cli, "_get_credentials",
+            return_value=("applicant@example.test", "applicant-secret")))
+        self.stack.enter_context(patch.object(session, "CalendarRequestAudit", return_value=self.audit))
+        self.stack.enter_context(patch.object(calendar, "read_calendar_service", return_value="9001"))
+        self.readback = self.stack.enter_context(patch.object(calendar, "verify_precommit_selection"))
+
+    def run_workflow(self, **kwargs):
+        output = io.StringIO()
+        with redirect_stdout(output):
+            code = self.cli.run_book_recheck_once(self.env, non_interactive=False,
+                                                 production_workflow=True, **kwargs)
+        return code, output.getvalue()
+
+    def test_auto_otp_reuses_one_public_book_call_and_keeps_final_disabled(self):
+        self.env["ITA_OTP_AUTHORIZATION_EMAIL"] = "mailbox@example.test"
+        code, output = self.run_workflow(auto_otp=True)
+        self.assertEqual(code, 0)
+        config = self.plugin.set_config.call_args.args[0]
+        self.assertEqual(config.free_config["otp_mode"], "cloud")
+        self.assertIs(config.free_config["final_submit_enabled"], False)
+        route_config = next(iter(config.free_config["apt_configs"].values()))
+        self.assertEqual(route_config["mail"], {"authorization_email": "mailbox@example.test"})
+        self.plugin.book.assert_called_once()
+        self.assertNotIn("mailbox@example.test", output)
+        self.assertIn("mode=cloud", output)
+
+    def test_auto_otp_requires_explicit_mailbox_before_session(self):
+        with self.assertRaises(self.cli.DebugConfigurationError):
+            self.run_workflow(auto_otp=True)
+        self.plugin.create_session.assert_not_called()
+
+    def test_verify_receipts_reuses_existing_gate_after_selection_without_final(self):
+        baseline = {"verified": True, "recordCount": 0, "calendarSelectionPreserved": True,
+                    "businessRequests": {k: 0 for k in self.counts}, "finalSubmissionEnabled": False}
+        self.env["ITA_OTP_AUTHORIZATION_EMAIL"] = "mailbox@example.test"
+        with patch("tools.debug_ita_book_gate._verify_receipt_baseline", return_value=baseline) as verify:
+            code, output = self.run_workflow(auto_otp=True, verify_receipts=True)
+        self.assertEqual(code, 0)
+        verify.assert_called_once_with(self.plugin, self.plugin._resolve_route.return_value)
+        self.plugin.book.assert_called_once()
+        self.assertIs(self.plugin.set_config.call_args.args[0].free_config["final_submit_enabled"], False)
+        self.assertIn("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=", output)
+        self.assertIn('"calendarSelectionPreserved": true', output)
+        self.assertIn('"finalRequests": 0', output)
+
+    def test_receipt_failure_is_not_passed_or_retried(self):
+        from plugins.ita_booking_final import FinalBookingError
+        self.stack.enter_context(patch.object(self.cli, "_print_failure_context"))
+        with patch("tools.debug_ita_book_gate._verify_receipt_baseline",
+                   side_effect=FinalBookingError("Italy receipt baseline rejected")) as verify:
+            code, output = self.run_workflow(verify_receipts=True)
+        self.assertEqual(code, 1)
+        verify.assert_called_once()
+        self.plugin.book.assert_called_once()
+        self.assertNotIn("ITA_BOOK_WORKFLOW_RESULT=", output)
+        self.plugin.cleanup.assert_called_once()
+
+    def test_receipt_read_business_request_change_fails(self):
+        def unexpected(*args):
+            self.counts["otpRequests"] += 1
+            return {}
+        self.stack.enter_context(patch.object(self.cli, "_print_failure_context"))
+        with patch("tools.debug_ita_book_gate._verify_receipt_baseline", side_effect=unexpected):
+            code, output = self.run_workflow(verify_receipts=True)
+        self.assertEqual(code, 1)
+        self.assertNotIn("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=", output)
+        self.plugin.book.assert_called_once()
+
+    def test_no_candidate_skips_receipt_read_and_does_not_claim_pass(self):
+        self.plugin.book.return_value = VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
+        with patch("tools.debug_ita_book_gate._verify_receipt_baseline") as verify:
+            code, output = self.run_workflow(verify_receipts=True)
+        self.assertEqual(code, 2)
+        verify.assert_not_called()
+        self.assertNotIn("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=", output)
+
+    def test_receipt_flag_requires_workflow_and_defaults_off(self):
+        self.assertFalse(self.cli.parse_args([]).verify_receipts)
+        self.assertTrue(self.cli.parse_args(["--production-workflow", "--verify-receipts"]).verify_receipts)
+        with self.assertRaises(self.cli.DebugConfigurationError):
+            self.cli.run_book_recheck_once(self.env, non_interactive=False, verify_receipts=True)
+        self.credentials.assert_not_called()
+        self.plugin.create_session.assert_not_called()
+
+    def test_main_routes_both_opt_in_flags_and_rejects_receipts_alone(self):
+        with patch.object(self.cli, "run_book_recheck_once", return_value=0) as run:
+            self.assertEqual(self.cli.main(["--production-workflow", "--auto-otp", "--verify-receipts"]), 0)
+        self.assertIs(run.call_args.kwargs["verify_receipts"], True)
+        self.assertIs(run.call_args.kwargs["auto_otp"], True)
+        with patch.object(self.cli, "run_book_recheck_once") as run, redirect_stderr(io.StringIO()):
+            self.assertEqual(self.cli.main(["--verify-receipts"]), 2)
+        run.assert_not_called()
+
+    def test_auto_flag_without_workflow_rejected_before_login(self):
+        with self.assertRaises(self.cli.DebugConfigurationError):
+            self.cli.run_book_recheck_once(self.env, non_interactive=False, auto_otp=True)
+        self.credentials.assert_not_called()
+        self.plugin.create_session.assert_not_called()
+        self.assertTrue(self.cli.parse_args(["--production-workflow", "--auto-otp"]).auto_otp)
+
+    def test_one_public_book_call_with_applicant_identity_and_final_disabled(self):
+        code, output = self.run_workflow()
+        self.assertEqual(code, 0)
+        config = self.plugin.set_config.call_args.args[0]
+        self.assertEqual(config.account.username, "applicant@example.test")
+        self.assertEqual(config.free_config["otp_mode"], "manual")
+        self.assertEqual(config.free_config["query_mode"], "services_probe")
+        self.assertIs(config.free_config["final_submit_enabled"], False)
+        self.assertNotIn("persistent_browser_profile_path", config.free_config)
+        self.credentials.assert_called_once_with({"ITA_USERNAME": "", "ITA_PASSWORD": ""}, non_interactive=False)
+        self.plugin.book.assert_called_once()
+        self.assertEqual(self.plugin.book.call_args.kwargs["user_inputs"], {"username": "applicant@example.test"})
+        self.plugin.query.assert_not_called()
+        self.readback.assert_called_once()
+        self.audit.start.assert_called_once()
+        self.audit.stop.assert_called_once()
+        self.plugin.cleanup.assert_called_once()
+        self.assertIn('"selectionVerified": true', output)
+        self.assertIn('"finalRequests": 0', output)
+        self.assertIn("ITA_BOOK_CLEANUP_OK", output)
+        self.assertNotIn("applicant-secret", output)
+        self.assertNotIn("query-secret", output)
+
+    def test_book_specific_environment_is_used_not_general_query_credentials(self):
+        self.env.update(ITA_BOOK_USERNAME="book@example.test", ITA_BOOK_PASSWORD="book-secret")
+        self.run_workflow()
+        self.credentials.assert_called_once_with(
+            {"ITA_USERNAME": "book@example.test", "ITA_PASSWORD": "book-secret"}, non_interactive=False)
+
+    def test_no_candidate_does_not_claim_positive_acceptance(self):
+        self.plugin.book.return_value = VSBookResult(success=False, label=BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
+        code, output = self.run_workflow()
+        self.assertEqual(code, 2)
+        self.assertIn('"selectionVerified": false', output)
+        self.readback.assert_not_called()
+        self.plugin.cleanup.assert_called_once()
+
+    def test_selection_readback_failure_is_not_a_pass(self):
+        self.readback.side_effect = BizLogicError("synthetic readback mismatch")
+        self.stack.enter_context(patch.object(self.cli, "_print_failure_context"))
+        code, output = self.run_workflow()
+        self.assertEqual(code, 1)
+        self.assertNotIn("ITA_BOOK_WORKFLOW_RESULT=", output)
+        self.plugin.cleanup.assert_called_once()
+
+    def test_unexpected_final_request_fails_and_never_retries(self):
+        self.counts["finalRequests"] = 1
+        self.stack.enter_context(patch.object(self.cli, "_print_failure_context"))
+        code, output = self.run_workflow()
+        self.assertEqual(code, 1)
+        self.assertNotIn("ITA_BOOK_WORKFLOW_RESULT=", output)
+        self.plugin.book.assert_called_once()
+        self.plugin.cleanup.assert_called_once()
+
+    def test_late_audit_failure_invalidates_exit_code(self):
+        self.audit.settled_snapshot.side_effect = [self.counts, RuntimeError("audit lost")]
+        code, output = self.run_workflow()
+        self.assertEqual(code, 1)
+        self.assertIn("ITA_BOOK_WORKFLOW_AUDIT_FAILED", output)
+        self.audit.stop.assert_called_once()
+        self.plugin.cleanup.assert_called_once()
+
+    def test_cleanup_failure_invalidates_exit_code(self):
+        self.plugin.cleanup.side_effect = RuntimeError("cleanup failed")
+        with redirect_stderr(io.StringIO()):
+            code, _ = self.run_workflow()
+        self.assertEqual(code, 3)
+
+    def test_legacy_flags_rejected_before_credentials(self):
+        for kwargs in ({"non_interactive": True}, {"arm": True}, {"wait_for_local_signal": True}):
+            with self.subTest(kwargs=kwargs), self.assertRaises(DebugConfigurationError):
+                self.cli.run_book_recheck_once(self.env, production_workflow=True,
+                                              **{"non_interactive": False, **kwargs})
+        self.credentials.assert_not_called()
+        self.plugin.create_session.assert_not_called()
+
+    def test_cli_flag_defaults_off(self):
+        self.assertFalse(self.cli.parse_args([]).production_workflow)
+        self.assertTrue(self.cli.parse_args(["--production-workflow"]).production_workflow)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 1371 - 0
test/test_debug_ita_book_gate.py

@@ -0,0 +1,1371 @@
+import copy
+import json
+import shutil
+import subprocess
+import tempfile
+import unittest
+from contextlib import ExitStack, redirect_stdout
+from io import StringIO
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins import ita_calendar_book as calendar_book
+from plugins.ita_calendar_query import AVAILABILITY_PATH, CALENDAR_PATH
+from plugins.ita_plugin import BOOKING_FORM_DISCOVERY_SCRIPT, ItaPlugin
+from test import test_debug_ita_calendar_gate as prep_fixtures
+from test import test_debug_ita_production_query_gate as audit_fixtures
+from test import test_ita_calendar_book_flow as flow_fixtures
+from tools import debug_ita_book_gate as gate
+from tools import debug_ita_calendar_gate as preparation
+from vs_types import AvailabilityStatus, VSBookResult, VSQueryResult
+
+
+ORIGIN = "https://prenotami.esteri.it"
+USERNAME = "applicant@example.test"
+PASSWORD = "private-test-pass"
+OTP = "012345"
+
+
+def gate_env():
+    env = prep_fixtures.gate_env()
+    env.update(ITA_BOOK_USERNAME=USERNAME, ITA_BOOK_PASSWORD=PASSWORD)
+    return env
+
+
+class GateListener(flow_fixtures.FakeListener):
+    def stop(self):
+        # Installed DrissionPage stop() dereferences None on a repeated stop.
+        if not self.listening:
+            raise AttributeError("Fixture listener already stopped")
+        super().stop()
+
+    def start(self, targets, method):
+        # The same listener is used for preparation and the real Book scanner.
+        if targets in (preparation.OTP_PATH, self.page.booking_path):
+            self.starts += 1
+            self.target = targets
+            self.queue.clear()
+            self.listening = True
+            self.page.events.append("listen-start")
+        else:
+            super().start(targets, method)
+
+
+class GateElement:
+    def __init__(self, page, selector):
+        self.page, self.selector = page, selector
+
+    def input(self, value, *, clear):
+        if self.selector != "#otp-input" or clear is not True:
+            raise AssertionError("Unexpected input")
+        self.page.otp_value = value if self.page.otp_write_matches else ""
+
+    def run_js(self, script, value):
+        if script != "return this.value === arguments[0];":
+            raise AssertionError("Unexpected OTP readback")
+        return self.page.otp_value == value
+
+    def click(self):
+        if self.selector == "#otp-input":
+            return
+        if self.selector == "#otp-send":
+            self.page.otp_clicks += 1
+            packet = self.page.preparation_packet(preparation.OTP_PATH, "GET")
+            packet.url += "?ServiceID=" + str(self.page.service_id)
+            packet.response.raw_body = json.dumps("SENT")
+            self.page.emit(preparation.OTP_PATH, "GET")
+            if self.page.duplicate_otp:
+                self.page.emit(preparation.OTP_PATH, "GET")
+        elif self.selector == "#btnAvanti":
+            self.page.avanti_clicks += 1
+            if self.page.auto_accept is not True:
+                raise AssertionError("AVANTI confirmation was not enabled")
+            packet = self.page.preparation_packet(self.page.booking_path, "POST")
+            packet.response.status = self.page.avanti_status
+            packet.response.url = ORIGIN + CALENDAR_PATH
+            packet.response.headers = {"Location": CALENDAR_PATH + "?selectedService=fixture"}
+            self.page.url = ORIGIN + CALENDAR_PATH
+            self.page.emit(self.page.booking_path, "POST")
+            if self.page.duplicate_avanti:
+                self.page.emit(self.page.booking_path, "POST")
+            # The original page's Calendar bootstrap is not Book's fresh scan.
+            self.page.emit(AVAILABILITY_PATH, "POST")
+        else:
+            raise AssertionError("The gate must not click any other control")
+        if self.page.preparation_mutator:
+            self.page.preparation_mutator(packet, self.selector)
+        self.page.listen.queue.append(packet)
+
+
+class GatePage(flow_fixtures.FlowPage):
+    def __init__(self, months=None):
+        super().__init__(months)
+        self.url = ORIGIN + "/UserArea"
+        self.service_id = 4937
+        self.booking_path = "/Services/Booking/4937"
+        self.driver = audit_fixtures.FakeDriver()
+        self.listen = GateListener(self)
+        self.set = SimpleNamespace(auto_handle_alert=self.auto_handle_alert)
+        self.auto_accept = False
+        self.alert_settings = []
+        self.otp_value = ""
+        self.otp_write_matches = True
+        self.otp_clicks = self.avanti_clicks = 0
+        self.duplicate_otp = self.duplicate_avanti = False
+        self.avanti_status = 302
+        self.preparation_mutator = None
+        self.preflight_changes = {}
+        self.preflight_hook = None
+        self.commands = []
+
+    def auto_handle_alert(self, on_off=True, accept=True):
+        self.auto_accept = accept if on_off else False
+        self.alert_settings.append(self.auto_accept)
+
+    def run_cdp(self, name):
+        self.commands.append(name)
+        return {}
+
+    def emit(self, path, method="POST"):
+        if path.endswith("InsertNewBooking"):
+            self.guard_final_count += 1
+        callback = self.driver.immediate_event_handlers.get(preparation.CalendarRequestAudit.EVENT)
+        if callback:
+            callback(request={"url": ORIGIN + path, "method": method})
+
+    def preparation_packet(self, path, method):
+        return SimpleNamespace(
+            tab_id=self.tab_id, is_failed=False, url=ORIGIN + path, method=method,
+            response=SimpleNamespace(status=200, raw_body="", url=ORIGIN + path, headers={}),
+        )
+
+    def response_packet(self, path, body, items, day=None):
+        self.emit(path)
+        return super().response_packet(path, body, items, day)
+
+    def ele(self, selector, timeout=None):
+        if selector in ("#otp-send", "#otp-input", "#btnAvanti"):
+            return GateElement(self, selector)
+        return None
+
+    def run_js(self, script, *args):
+        if "coordinate:ita-book-gate-form-boundary" in script:
+            if self.preflight_hook:
+                self.preflight_hook()
+            return prep_fixtures.booking_preflight_snapshot(
+                pathMatches=self.url == ORIGIN + self.booking_path,
+                otpValuePresent=bool(self.otp_value), otpDisabled=self.otp_clicks > 0,
+                **self.preflight_changes,
+            )
+        if script == BOOKING_FORM_DISCOVERY_SCRIPT:
+            return {"path": self.booking_path, "form": {"method": "POST", "action_path": self.booking_path},
+                    "fields": [], "buttons": []}
+        if script == preparation.AVANTI_FAILURE_DIAGNOSTIC_SCRIPT:
+            return {"path": self.url.removeprefix(ORIGIN), "otpValuePresent": bool(self.otp_value),
+                    "bookingFormPresent": self.url == ORIGIN + self.booking_path}
+        return super().run_js(script, *args)
+
+
+def make_plugin(page):
+    # No constructor, files, browser, real credentials, mail or external service.
+    plugin = ItaPlugin.__new__(ItaPlugin)
+    plugin.group_id = "offline-book-gate"
+    plugin.logger = None
+    plugin.page = page
+    plugin._transient_user_data_path = "/unused/ita-book-gate-test"
+    plugin.mouse = SimpleNamespace(human_click_ele=lambda element: element.click())
+    plugin.session_create_time = 0
+    plugin.create_session = Mock(side_effect=lambda: setattr(plugin, "session_create_time", 123.0))
+    plugin.cleanup = Mock()
+
+    def enter(apt_type):
+        page.url = ORIGIN + page.booking_path
+        return VSQueryResult(success=True, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable)
+
+    plugin.query = Mock(side_effect=enter)
+    plugin.book = Mock(wraps=plugin.book)
+    plugin._record_calendar_book_prepared_route = Mock(wraps=plugin._record_calendar_book_prepared_route)
+    return plugin
+
+
+class BookGateFlowTests(unittest.TestCase):
+    def run_gate(self, page=None, *, env=None, execute=True, inputs=None, configure=None,
+                 otp_reader=None, before=None, after=None, reservation_hook=None,
+                 use_local_query_account=False, verify_receipts=False, submit_once=False,
+                 final_confirm=lambda _: "no", review_reader=lambda _: ""):
+        page = page or GatePage()
+        plugin = make_plugin(page)
+        # __del__ invokes cleanup again. Keep a fault-injection mock from raising
+        # an unraisable exception after this test has already asserted its result.
+        self.addCleanup(lambda: setattr(plugin.cleanup, "side_effect", None))
+        if configure:
+            configure(plugin, page)
+        captured = StringIO()
+        reservation_calls = []
+
+        def reservations(_page):
+            self.assertIs(_page, page)
+            reservation_calls.append(True)
+            if reservation_hook:
+                reservation_hook(plugin, page, len(reservation_calls))
+            return (before if len(reservation_calls) == 1 else after) or preparation.ReservationSnapshot(0, 0)
+
+        with ExitStack() as stack:
+            factory = stack.enter_context(patch.object(gate, "ItaPlugin", return_value=plugin))
+            stack.enter_context(patch.object(gate, "resolve_chrome_path", return_value=Path("/fixture/Chrome")))
+            stack.enter_context(patch.object(preparation, "read_reservation_snapshot", side_effect=reservations))
+            stack.enter_context(patch.object(preparation.CalendarRequestAudit, "settled_snapshot", lambda audit: audit.snapshot()))
+            stack.enter_context(patch.object(calendar_book, "click_next_month", side_effect=lambda _page: page.next_month()))
+            stack.enter_context(patch.object(calendar_book.time, "sleep"))
+            stack.enter_context(patch.dict(gate.os.environ, {}, clear=True))
+            stack.enter_context(redirect_stdout(captured))
+            code = gate.run_book_gate(env or gate_env(), execute=execute, user_inputs=inputs,
+                                      otp_reader=otp_reader or (lambda: OTP),
+                                      use_local_query_account=use_local_query_account,
+                                      verify_receipts=verify_receipts, submit_once=submit_once,
+                                      final_confirm=final_confirm, review_reader=review_reader)
+        output = captured.getvalue()
+        lines = [line for line in output.splitlines() if line.startswith("ITA_BOOK_GATE_RESULT=")]
+        report = json.loads(lines[-1].split("=", 1)[1]) if lines else None
+        return SimpleNamespace(code=code, report=report, output=output, plugin=plugin,
+                               page=page, factory=factory, reservation_calls=reservation_calls)
+
+    def assert_clean(self, result):
+        result.plugin.cleanup.assert_called_once()
+        self.assertFalse(result.page.listen.listening)
+        self.assertNotIn(preparation.CalendarRequestAudit.EVENT, result.page.driver.immediate_event_handlers)
+        self.assertFalse(result.page.auto_accept)
+        self.assertEqual(result.page.guard_final_count, 0)
+
+    def test_production_failures_are_distinct_and_diagnostic_precedes_reconciliation(self):
+        cases = (
+            ("Book date control was not ready before timeout", "date_control_timeout"),
+            ("Book TimeSlots request does not match the current service", "timeslot_service_mismatch"),
+            ("Book slot DOM did not match the response before timeout", "slot_dom_timeout"),
+            ("Book precommit rejected (precommit_rejected)", "precommit_readback_rejected"),
+        )
+        for message, reason in cases:
+            with self.subTest(reason=reason):
+                page = GatePage()
+                seen = []
+                original = page.run_js
+
+                def read(script, *args):
+                    if script == gate.BOOK_FAILURE_STATE_SCRIPT:
+                        seen.append(True)
+                        return book_failure_state()
+                    return original(script, *args)
+
+                def reconcile(plugin, page, count):
+                    if count == 2:
+                        self.assertEqual(seen, [True])
+
+                page.run_js = read
+                with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(message)):
+                    result = self.run_gate(page, reservation_hook=reconcile)
+                self.assertEqual(result.code, 1, result.output)
+                self.assertIn(f'"reason": "{reason}"', result.output)
+                self.assertIn('"readSucceeded": true', result.output)
+                self.assertEqual(result.report["calendarBookCalls"], 1)
+                self.assertEqual(result.report["requests"]["finalRequests"], 0)
+                self.assertEqual(result.report["requests"]["otpRequests"], 1)
+                self.assertEqual(result.report["requests"]["avantiPosts"], 1)
+                self.assertEqual(page.clicks, 0)
+                self.assert_clean(result)
+
+    def test_production_diagnostic_failure_does_not_replace_original_reason(self):
+        # GatePage deliberately has no implementation of this diagnostic script.
+        with patch.object(calendar_book, "_try_day", side_effect=calendar_book.CalendarBookError(
+            "Book slot click was not acknowledged",
+        )):
+            result = self.run_gate()
+        self.assertEqual(result.code, 1)
+        self.assertIn('"reason": "slot_click_not_acknowledged"', result.output)
+        self.assertIn('"readSucceeded": false', result.output)
+        self.assert_clean(result)
+
+    def test_full_gate_uses_real_book_and_stops_before_final(self):
+        result = self.run_gate()
+        self.assertEqual(result.code, 0, result.output)
+        report = result.report
+        self.assertIs(report["passed"], True)
+        self.assertEqual(report["outcome"], "pre_final")
+        self.assertEqual((report["entryBookCalls"], report["calendarBookCalls"]), (1, 1))
+        self.assertEqual(report["requests"], {"otpRequests": 1, "avantiPosts": 1,
+                                            "availabilityRequests": 2, "finalRequests": 0})
+        self.assertEqual(report["bookRequestDelta"], {"otpRequests": 0, "avantiPosts": 0,
+                                                    "availabilityRequests": 1, "finalRequests": 0})
+        self.assertEqual(report["selectedDate"], "2026-10-13")
+        self.assertEqual(report["selectedTime"], "10:05 - 11:05")
+        self.assertIs(report["bookResultSuccess"], False)
+        self.assertEqual(result.plugin.book.call_count, 2)
+        self.assertEqual(result.plugin.query.call_count, 1)
+        self.assertEqual(result.page.clicks, 1)
+        self.assertEqual(result.page.otp_value, OTP)
+        self.assertEqual(result.page.alert_settings, [True, False])
+        self.assertIsNone(result.plugin._calendar_query_route_key)
+        self.assertEqual(result.plugin._record_calendar_book_prepared_route.call_count, 1)
+        self.assertEqual(len(result.reservation_calls), 2)
+        self.assert_clean(result)
+        for secret in (USERNAME, PASSWORD, OTP, "80000113"):
+            self.assertNotIn(secret, result.output)
+
+    def test_opt_in_receipt_baseline_uses_real_read_port_and_keeps_calendar(self):
+        from test.test_ita_final_read_port import Browser
+
+        class AuditedBrowser(Browser):
+            def open_tab(self, **kwargs):
+                tab = super().open_tab(**kwargs)
+                tab.driver = audit_fixtures.FakeDriver()
+                tab.run_cdp = Mock(return_value={})
+                return tab
+
+        browser = AuditedBrowser()
+
+        def configure(plugin, page):
+            page.browser = browser
+            plugin.is_healthy = True
+
+        inventory = preparation.ReservationSnapshot(1, 0)
+        result = self.run_gate(configure=configure, verify_receipts=True, before=inventory, after=inventory)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertTrue(result.report["receiptBaseline"]["verified"])
+        self.assertTrue(result.report["receiptBaseline"]["calendarSelectionPreserved"])
+        self.assertEqual(result.report["receiptBaseline"]["recordCount"], 1)
+        self.assertTrue(all(v == 0 for v in result.report["receiptBaseline"]["businessRequests"].values()))
+        self.assertEqual(len(browser.pages), 1)
+        browser.pages[0].close.assert_called_once()
+        self.assertFalse(browser.pages[0].driver.immediate_event_handlers)
+        self.assertEqual(result.page.otp_clicks, 1)
+        self.assertEqual(result.report["requests"]["finalRequests"], 0)
+        self.assert_clean(result)
+
+    def test_receipt_verification_remains_opt_in_and_preflight_is_local(self):
+        with patch.object(gate, "_verify_receipt_baseline") as reader:
+            self.assertEqual(self.run_gate().code, 0)
+            self.assertEqual(self.run_gate(execute=False, verify_receipts=True).code, 0)
+            reader.assert_not_called()
+
+    def test_receipt_baseline_failure_does_not_pass_or_repeat_preparation(self):
+        with patch.object(gate, "_verify_receipt_baseline", side_effect=RuntimeError("PRIVATE-RAW")):
+            result = self.run_gate(verify_receipts=True)
+        self.assertEqual(result.code, 1)
+        self.assertFalse(result.report["passed"])
+        self.assertNotIn("PRIVATE-RAW", result.output)
+        self.assertEqual(result.page.otp_clicks, 1)
+        self.assertEqual(result.report["requests"]["finalRequests"], 0)
+        self.assert_clean(result)
+
+    def test_receipt_baseline_cli_flag_is_forwarded(self):
+        with patch.object(gate, "run_book_gate", return_value=0) as runner:
+            self.assertEqual(gate.main(["--preflight", "--verify-receipts"]), 0)
+            self.assertIs(runner.call_args.kwargs["verify_receipts"], True)
+            self.assertIs(runner.call_args.kwargs["execute"], False)
+
+    def test_final_mode_requires_receipts_and_default_never_calls_final_adapter(self):
+        with patch.object(gate.final_evidence, "FinalEvidenceRun") as final:
+            self.assertEqual(self.run_gate().code, 0)
+            result = self.run_gate(submit_once=True)
+            self.assertEqual(result.code, 1)
+            result.factory.assert_not_called()
+            final.assert_not_called()
+
+    def test_final_preflight_never_reads_credentials_or_creates_browser_or_fence(self):
+        with patch.object(gate.final_evidence, "require_unused_claim") as check, \
+                patch.object(gate.final_evidence, "claim_once") as claim, \
+                patch.object(gate, "_book_credentials") as credentials:
+            result = self.run_gate(execute=False, submit_once=True, verify_receipts=True)
+        self.assertEqual(result.code, 0)
+        check.assert_called_once()
+        claim.assert_not_called()
+        credentials.assert_not_called()
+        result.factory.assert_not_called()
+
+    def test_existing_final_fence_blocks_before_credentials(self):
+        with patch.object(gate.final_evidence, "require_unused_claim", side_effect=RuntimeError("secret")), \
+                patch.object(gate, "_book_credentials") as credentials:
+            result = self.run_gate(submit_once=True, verify_receipts=True)
+        self.assertEqual(result.code, 1)
+        credentials.assert_not_called()
+        result.factory.assert_not_called()
+        self.assertNotIn("secret", result.output)
+
+    def test_final_cli_opt_in_is_forwarded(self):
+        with patch.object(gate, "run_book_gate", return_value=0) as runner:
+            gate.main(["--preflight", "--verify-receipts", "--submit-once"])
+        self.assertIs(runner.call_args.kwargs["submit_once"], True)
+        self.assertIs(runner.call_args.kwargs["execute"], False)
+
+    def test_real_final_core_wiring_and_unknown_result_keeps_fence_and_requires_review(self):
+        from test.test_ita_final_read_port import Browser
+        from plugins.ita_booking_final import SubmissionSignal
+
+        class AuditedBrowser(Browser):
+            def open_tab(self, **kwargs):
+                tab = super().open_tab(**kwargs)
+                tab.driver = audit_fixtures.FakeDriver()
+                tab.run_cdp = Mock(return_value={})
+                return tab
+
+        for mode in ("decline", "submit", "interrupt", "duplicate"):
+            with self.subTest(mode=mode), tempfile.TemporaryDirectory() as folder:
+                page = GatePage()
+                browser = AuditedBrowser()
+                def configure(plugin, page):
+                    page.browser = browser
+                    plugin.is_healthy = True
+                path = Path(folder) / "final.claim"
+                original = gate.final_evidence.FinalEvidenceRun
+                checker = gate.final_evidence.require_unused_claim
+                def native():
+                    self.assertTrue(path.exists())
+                    page.emit("/BookingCalendar/InsertNewBooking", "POST")
+                    if mode == "duplicate":
+                        page.emit("/BookingCalendar/InsertNewBooking", "POST")
+                    if mode == "interrupt":
+                        raise KeyboardInterrupt()
+                    return SubmissionSignal.UNKNOWN
+                submit = Mock(side_effect=native)
+                review = Mock(return_value="")
+                inventory = preparation.ReservationSnapshot(1, 0)
+                with patch.object(gate.final_evidence, "FinalEvidenceRun",
+                                  side_effect=lambda *a, **kw: original(*a, **kw, claim_path=path)), \
+                        patch.object(gate.final_evidence, "require_unused_claim", side_effect=lambda p=path: checker(p)), \
+                        patch.object(gate.final_evidence, "NativeFinalSubmitter", return_value=submit):
+                    result = self.run_gate(page, configure=configure, verify_receipts=True, submit_once=True,
+                                           before=inventory, after=inventory,
+                                           final_confirm=(lambda _: "no") if mode == "decline" else
+                                           (lambda prompt: prompt.split("'")[1]), review_reader=review)
+                self.assertEqual(result.code, 2 if mode == "decline" else 4, result.output)
+                self.assertFalse(result.report["passed"])
+                self.assertFalse(result.report["bookResultSuccess"])
+                self.assertEqual(result.report["requestAuditVerified"], mode != "duplicate")
+                self.assertEqual(submit.call_count, 0 if mode == "decline" else 1)
+                self.assertEqual(review.call_count, 0 if mode == "decline" else 1)
+                self.assertEqual(path.exists(), mode != "decline")
+                self.assertEqual(result.report["requests"]["otpRequests"], 1)
+                self.assertEqual(result.report["requests"]["avantiPosts"], 1)
+                self.assertEqual(result.report["requests"]["finalRequests"],
+                                 0 if mode == "decline" else 2 if mode == "duplicate" else 1)
+                result.plugin.cleanup.assert_called_once()
+                self.assertFalse(page.listen.listening)
+                self.assertFalse(page.driver.immediate_event_handlers)
+                self.assertTrue(all(tab.close.call_count == 1 for tab in browser.pages))
+                self.assertIs(result.plugin.free_config["final_submit_enabled"], False)
+                if mode == "duplicate":
+                    self.assertIn('"stage": "final_request_audit"', result.output)
+                for secret in (USERNAME, PASSWORD, OTP, "SYNTHETIC-REFERENCE"):
+                    self.assertNotIn(secret, result.output)
+
+    def test_final_gate_exports_verified_success_and_late_failures_cannot_pass(self):
+        from test.test_ita_final_read_port import Browser
+        from test.test_ita_booking_final import final_packet
+        from plugins.ita_booking_final import inspect_final_packet
+        from plugins.ita_reservation import MONTHS_IT
+
+        class AuditedBrowser(Browser):
+            def open_tab(self, **kwargs):
+                tab = super().open_tab(**kwargs)
+                tab.driver = audit_fixtures.FakeDriver()
+                tab.run_cdp = Mock(return_value={})
+                return tab
+
+        for mode in ("success", "late_duplicate", "cleanup_failure", "reconcile_failure"):
+            with self.subTest(mode=mode), tempfile.TemporaryDirectory() as folder:
+                page, browser = GatePage(), AuditedBrowser()
+                path = Path(folder) / "final.claim"
+                original = gate.final_evidence.FinalEvidenceRun
+                checker = gate.final_evidence.require_unused_claim
+                def configure(plugin, page):
+                    page.browser = browser
+                    plugin.is_healthy = True
+                    if mode == "cleanup_failure":
+                        plugin.cleanup.side_effect = RuntimeError("PRIVATE")
+                def create_run(plugin, route, **kwargs):
+                    # The real Calendar URL exposes selectedService; the older
+                    # preparation fixture omits it. Supply that observed shape.
+                    page.url += "?selectedService=Visti%20Nazionali%20e%20Schengen"
+                    return original(plugin, route, **kwargs, claim_path=path)
+                def create_native(_page, target, _current):
+                    packet = final_packet(target)
+                    packet.response.raw_body = "unrecognized response fixture"
+                    signal, proof, reason = inspect_final_packet(packet, target)
+                    def click():
+                        self.assertTrue(path.exists())
+                        slot = target.approval.candidate
+                        shown_day = f"{slot.day.day} {MONTHS_IT[slot.day.month - 1]} {slot.day.year}"
+                        assigned = slot.start_time.strftime("%H:%M")
+                        table = browser.raw["tables"][0]
+                        new = {**table["rows"][0], "reference": "SYNTHETIC-NEW",
+                               "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/synthetic-new",
+                               "date": shown_day, "time": assigned, "status": "Confermata"}
+                        table["rows"].append(new)
+                        table["count"] = 2
+                        table["info"].update(recordsTotal=2, recordsDisplay=2, end=2)
+                        detail = copy.deepcopy(browser.receipt)
+                        detail.update(path="/ReservationDetail/Index/synthetic-new", statusCode="2")
+                        detail["fields"].update({"Codice Prenotazione": "SYNTHETIC-NEW",
+                                                 "Data": shown_day, "Ora": assigned, "Stato": "Confermata"})
+                        browser.receipts[new["detailUrl"]] = detail
+                        page.emit("/BookingCalendar/InsertNewBooking", "POST")
+                        return signal
+                    native = Mock(side_effect=click)
+                    native.submitted_selection = proof
+                    native.diagnostic = {"requestMatched": True, "reason": reason}
+                    return native
+                def review(_prompt):
+                    if mode == "late_duplicate":
+                        page.emit("/BookingCalendar/InsertNewBooking", "POST")
+                    return ""
+                def reservation_hook(plugin, _page, count):
+                    if mode == "reconcile_failure" and count == 2:
+                        raise RuntimeError("PRIVATE")
+                with patch.object(gate.final_evidence, "FinalEvidenceRun", side_effect=create_run), \
+                        patch.object(gate.final_evidence, "require_unused_claim", side_effect=lambda p=path: checker(p)), \
+                        patch.object(gate.final_evidence, "NativeFinalSubmitter", side_effect=create_native) as native:
+                    result = self.run_gate(page, configure=configure, verify_receipts=True, submit_once=True,
+                                           before=preparation.ReservationSnapshot(1, 0),
+                                           after=preparation.ReservationSnapshot(2, 0),
+                                           final_confirm=lambda prompt: prompt.split("'")[1],
+                                           review_reader=review, reservation_hook=reservation_hook)
+                self.assertEqual(result.code, {"success": 0, "late_duplicate": 1,
+                                               "cleanup_failure": 3, "reconcile_failure": 1}[mode], result.output)
+                self.assertEqual(result.report["bookResultSuccess"], mode == "success")
+                self.assertEqual(result.report["passed"], mode == "success")
+                self.assertTrue(result.report["finalEvidence"]["bookingConfirmed"])
+                self.assertEqual(result.report["finalEvidence"]["submissionSignal"], "unknown")
+                self.assertEqual(native.call_count, 1)
+                self.assertTrue(path.exists())
+                self.assertFalse(page.driver.immediate_event_handlers)
+                self.assertTrue(all(tab.close.call_count == 1 for tab in browser.pages))
+                for secret in (USERNAME, PASSWORD, OTP, "SYNTHETIC-NEW", "PRIVATE"):
+                    self.assertNotIn(secret, result.output)
+
+    def test_followed_redirect_200_is_accepted(self):
+        page = GatePage()
+        page.avanti_status = 200
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertIn("followed_redirect_200", result.output)
+        self.assert_clean(result)
+
+    def test_config_not_geography_controls_route(self):
+        env = gate_env()
+        env.update(ITA_ROUTING_KEY="slot.other.it.tourist", ITA_CITY="Another City", ITA_SERVICE_ID="9001")
+        page = GatePage()
+        page.service_id, page.booking_path = 9001, "/Services/Booking/9001"
+        result = self.run_gate(page, env=env)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(result.plugin._calendar_book_prepared_context[4].service_id, 9001)
+
+    def test_default_preflight_does_not_load_credentials_or_create_browser(self):
+        for reuse in (False, True):
+            with self.subTest(reuse=reuse), patch.object(
+                gate, "_book_credentials", side_effect=AssertionError("No credential access")
+            ), patch.object(gate, "load_local_account") as loader:
+                result = self.run_gate(execute=False, use_local_query_account=reuse)
+            self.assertEqual(result.code, 0, result.output)
+            loader.assert_not_called()
+            result.factory.assert_not_called()
+            result.plugin.create_session.assert_not_called()
+            self.assertEqual(result.reservation_calls, [])
+
+    def test_local_account_reuse_still_uses_independent_prefinal_book_flow(self):
+        with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
+            username=USERNAME, password=PASSWORD,
+        )) as loader, patch.object(gate, "_get_credentials") as prompt:
+            result = self.run_gate(use_local_query_account=True)
+        loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
+        prompt.assert_not_called()
+        self.assertEqual(result.code, 0, result.output)
+        self.assertTrue(result.report["passed"])
+        self.assertFalse(result.report["bookResultSuccess"])
+        self.assertEqual(result.report["requests"]["finalRequests"], 0)
+        self.assertEqual(result.plugin.config.account.username, USERNAME)
+        self.assertIsNone(result.plugin._calendar_query_route_key)
+        self.assertIsNone(result.plugin.free_config.get(gate.PERSISTENT_BROWSER_PROFILE_KEY))
+        self.assertIsNone(getattr(result.plugin, "_persistent_profile_path", None))
+        self.assertEqual(result.plugin.book.call_count, 2)
+        self.assertIn("source=local_query_file", result.output)
+        for secret in (USERNAME, PASSWORD, OTP):
+            self.assertNotIn(secret, result.output)
+        self.assert_clean(result)
+
+    def test_invalid_local_account_stops_before_browser_without_fallback(self):
+        with patch.object(gate, "load_local_account", side_effect=gate.LocalAccountConfigurationError(
+            f"untrusted loader detail {USERNAME} {PASSWORD}",
+        )), patch.object(gate, "_get_credentials") as prompt:
+            result = self.run_gate(use_local_query_account=True)
+        self.assertEqual(result.code, 1)
+        self.assertFalse(result.report["passed"])
+        result.factory.assert_not_called()
+        result.plugin.create_session.assert_not_called()
+        prompt.assert_not_called()
+        self.assertEqual(result.page.otp_clicks, 0)
+        self.assertEqual(result.page.avanti_clicks, 0)
+        self.assertEqual(result.reservation_calls, [])
+        self.assertIn("applicant_credentials", result.output)
+        for secret in (USERNAME, PASSWORD, "untrusted loader detail"):
+            self.assertNotIn(secret, result.output)
+
+    def test_calendar_service_failure_retains_business_exit_and_safe_diagnostic(self):
+        page = GatePage()
+        page.context_count = 0
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertEqual(result.report["calendarBookCalls"], 0)
+        self.assertEqual(result.report["requests"], {
+            "otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 1, "finalRequests": 0,
+        })
+        diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
+                                     if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
+        self.assertEqual(diagnostic["controlCount"], 0)
+        self.assertTrue(diagnostic["readSucceeded"])
+        self.assertTrue(diagnostic["afterFailure"])
+        self.assertIn('"reason": "calendar_service_unidentified"', result.output)
+        self.assertNotIn("cleanup_listener", result.output)
+        self.assertEqual(page.listen.stops, 2)  # OTP and AVANTI; no third stop.
+        self.assert_clean(result)
+
+    def test_calendar_identifier_shapes_stay_rejected_without_logging_values(self):
+        for value in ("", " ", "x" * 129, 7002, None):
+            with self.subTest(value_type=type(value).__name__), patch.object(
+                gate, "CALENDAR_READY_TIMEOUT_SECONDS", 0,
+            ):
+                page = GatePage()
+                page.service = value
+                result = self.run_gate(page)
+                self.assertEqual(result.code, 1, result.output)
+                self.assertEqual(result.report["calendarBookCalls"], 0)
+                reason = "calendar_service_not_ready" if value == "" else "calendar_service_unidentified"
+                self.assertIn(f'"reason": "{reason}"', result.output)
+                diagnostic = json.loads(next(line.split("=", 1)[1] for line in result.output.splitlines()
+                                             if line.startswith("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=")))
+                self.assertEqual(diagnostic["valueType"], type(value).__name__)
+                self.assertEqual(diagnostic["valueLength"], len(value) if isinstance(value, str) else None)
+                self.assertFalse(diagnostic["valueAccepted"])
+                self.assertNotIn("value", diagnostic)
+                self.assertNotIn("x" * 129, result.output)
+                self.assert_clean(result)
+
+    def test_calendar_initialization_can_finish_after_document_loaded(self):
+        page = GatePage()
+        original_run_js = page.run_js
+        reads = []
+
+        def delayed(script, *args):
+            result = original_run_js(script, *args)
+            if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
+                reads.append(True)
+                if len(reads) == 1:
+                    return {**result, "value": ""}
+            return result
+
+        page.run_js = delayed
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertGreater(len(reads), 1)
+        self.assertEqual(result.report["calendarBookCalls"], 1)
+        self.assertEqual(result.report["requests"]["otpRequests"], 1)
+        self.assertEqual(result.report["requests"]["avantiPosts"], 1)
+        self.assertEqual(result.report["requests"]["finalRequests"], 0)
+        self.assert_clean(result)
+
+    def test_diagnostic_read_failure_does_not_replace_the_primary_error(self):
+        page = GatePage()
+        original_run_js = page.run_js
+
+        def run_js(script, *args):
+            if script == calendar_book.RUNTIME_SERVICE_SCRIPT:
+                raise RuntimeError(f"{USERNAME} {PASSWORD} private-response")
+            return original_run_js(script, *args)
+
+        page.run_js = run_js
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1, result.output)
+        self.assertIn('"readSucceeded": false', result.output)
+        self.assertIn('"reason": "calendar_service_unidentified"', result.output)
+        for secret in (USERNAME, PASSWORD, "private-response"):
+            self.assertNotIn(secret, result.output)
+        self.assert_clean(result)
+
+    def test_active_listener_cleanup_failure_is_not_silenced(self):
+        def reservation_hook(plugin, page, count):
+            if count == 2:
+                page.listen.listening = True
+                page.listen.stop = Mock(side_effect=AttributeError("active listener failed"))
+
+        result = self.run_gate(reservation_hook=reservation_hook)
+        self.assertEqual(result.code, 3)
+        self.assertFalse(result.report["passed"])
+        self.assertIn("cleanup_listener", result.output)
+        result.page.listen.stop.assert_called_once()
+        result.plugin.cleanup.assert_called_once()
+        self.assertNotIn(preparation.CalendarRequestAudit.EVENT,
+                         result.page.driver.immediate_event_handlers)
+        self.assertEqual(result.page.guard_final_count, 0)
+
+    def test_no_route_fallback_is_allowed(self):
+        for name in prep_fixtures.gate_env():
+            with self.subTest(missing=name):
+                env = gate_env()
+                del env[name]
+                result = self.run_gate(env=env)
+                self.assertEqual(result.code, 1)
+                result.factory.assert_not_called()
+
+    def test_bad_preferences_fail_before_credentials(self):
+        for inputs in ({"expected_start_date": "20260230"}, {"username": "query@example.test"},
+                       {"expected_start_date": "2026-11-01", "expected_end_date": "2026-10-01"}):
+            with self.subTest(inputs=inputs), patch.object(gate, "_book_credentials") as credentials:
+                result = self.run_gate(inputs=inputs)
+                self.assertEqual(result.code, 1)
+                credentials.assert_not_called()
+                result.factory.assert_not_called()
+
+    def test_preferences_reach_real_book_without_changing_input(self):
+        page = GatePage([flow_fixtures.month("2026-10", {13: 1, 14: 1})])
+        inputs = {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-14"}
+        original = copy.deepcopy(inputs)
+        result = self.run_gate(page, inputs=inputs)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(result.report["selectedDate"], "2026-10-14")
+        self.assertEqual(page.date_clicks, ["2026-10-14"])
+        self.assertEqual(inputs, original)
+
+    def test_entry_unavailable_does_not_send_otp(self):
+        def configure(plugin, page):
+            plugin.query = Mock(return_value=VSQueryResult(success=False))
+        result = self.run_gate(configure=configure)
+        self.assertEqual(result.code, 2, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertEqual(result.report["calendarBookCalls"], 0)
+        self.assertEqual(result.page.otp_clicks, 0)
+        self.assert_clean(result)
+
+    def test_calendar_no_inventory_is_not_a_positive_gate(self):
+        page = GatePage([flow_fixtures.month("2026-10", {13: 0})])
+        result = self.run_gate(page, inputs={"expected_end_date": "2026-10-31"})
+        self.assertEqual(result.code, 2, result.output)
+        self.assertFalse(result.report["selectionVerified"])
+        self.assertFalse(result.report["passed"])
+        self.assertEqual(page.clicks, 0)
+        self.assert_clean(result)
+
+    def test_form_preflight_failure_does_not_send_otp(self):
+        page = GatePage()
+        page.preflight_changes = {"unknownRequiredCount": 1}
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        self.assertEqual(page.otp_clicks, 0)
+        self.assert_clean(result)
+
+    def test_otp_must_really_be_written_before_avanti(self):
+        page = GatePage()
+        page.otp_write_matches = False
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 0))
+        self.assert_clean(result)
+
+    def test_bad_manual_code_never_retries_or_reaches_avanti(self):
+        for value in ("", "123456", "123 abc", None):
+            with self.subTest(value=value):
+                result = self.run_gate(otp_reader=lambda: value)
+                self.assertEqual(result.code, 1)
+                self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
+                self.assert_clean(result)
+
+    def test_cancel_at_manual_otp_reconciles_and_cleans_without_retry(self):
+        reader = Mock(side_effect=KeyboardInterrupt)
+        result = self.run_gate(otp_reader=reader)
+        self.assertEqual(result.code, 130)
+        self.assertEqual((result.page.otp_clicks, result.page.avanti_clicks), (1, 0))
+        self.assertEqual(len(result.reservation_calls), 2)
+        self.assert_clean(result)
+
+    def test_eof_at_manual_otp_is_safe_cancellation(self):
+        result = self.run_gate(otp_reader=Mock(side_effect=EOFError))
+        self.assertEqual(result.code, 130)
+        self.assert_clean(result)
+
+    def test_duplicate_otp_is_detected_before_reading_code(self):
+        page = GatePage()
+        page.duplicate_otp = True
+        reader = Mock(return_value=OTP)
+        result = self.run_gate(page, otp_reader=reader)
+        self.assertEqual(result.code, 1)
+        reader.assert_not_called()
+        self.assertEqual(page.avanti_clicks, 0)
+        self.assertEqual(result.report["requests"]["otpRequests"], 2)
+        self.assert_clean(result)
+
+    def test_duplicate_avanti_never_records_prepared_context(self):
+        page = GatePage()
+        page.duplicate_avanti = True
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        result.plugin._record_calendar_book_prepared_route.assert_not_called()
+        self.assertEqual(page.refreshes, 0)
+        self.assert_clean(result)
+
+    def test_preparation_packets_are_bound_to_tab_service_and_response(self):
+        changes = (
+            lambda packet: setattr(packet, "tab_id", "old-query-tab"),
+            lambda packet: setattr(packet, "is_failed", True),
+            lambda packet: setattr(packet.response, "status", True),
+            lambda packet: setattr(packet, "url", ORIGIN + preparation.OTP_PATH + "?ServiceID=9001"),
+            lambda packet: setattr(packet.response, "raw_body", json.dumps("NOT_SENT")),
+        )
+        for index, mutate in enumerate(changes):
+            with self.subTest(index=index):
+                page = GatePage()
+                page.preparation_mutator = lambda packet, selector: mutate(packet) if selector == "#otp-send" else None
+                result = self.run_gate(page)
+                self.assertEqual(result.code, 1)
+                self.assertEqual(page.avanti_clicks, 0)
+                self.assert_clean(result)
+
+    def test_avanti_wrong_tab_or_transition_does_not_attest_calendar(self):
+        for variant in ("wrong-tab", "wrong-target", "bad-status", "response-form"):
+            with self.subTest(variant=variant):
+                page = GatePage()
+
+                def mutate(packet, selector):
+                    if selector != "#btnAvanti":
+                        return
+                    if variant == "wrong-tab":
+                        packet.tab_id = "another-tab"
+                    elif variant == "wrong-target":
+                        packet.response.headers["Location"] = "https://other.example/BookingCalendar"
+                    elif variant == "bad-status":
+                        packet.response.status = 500
+                    else:
+                        packet.response.status = 200
+                        packet.response.url = ORIGIN + page.booking_path
+
+                page.preparation_mutator = mutate
+                result = self.run_gate(page)
+                self.assertEqual(result.code, 1)
+                result.plugin._record_calendar_book_prepared_route.assert_not_called()
+                self.assertEqual(page.refreshes, 0)
+                self.assert_clean(result)
+
+    def test_avanti_timeout_does_not_repeat_and_disables_auto_accept(self):
+        with patch.object(preparation, "_wait_for_calendar", side_effect=preparation.CalendarGateError("timeout")):
+            result = self.run_gate()
+        self.assertEqual(result.code, 1)
+        self.assertEqual(result.page.avanti_clicks, 1)
+        self.assertEqual(result.page.alert_settings, [True, False])
+        self.assert_clean(result)
+
+    def test_account_route_tab_and_login_drift_stop_before_otp(self):
+        mutations = (
+            lambda plugin, page: setattr(plugin.config.account, "username", "other@example.test"),
+            lambda plugin, page: setattr(page, "tab_id", "other-tab"),
+            lambda plugin, page: setattr(plugin, "session_create_time", 124.0),
+            lambda plugin, page: plugin.free_config.update(final_submit_enabled=True),
+            lambda plugin, page: setattr(plugin, "_calendar_query_route_key", "slot.query.it.tourist"),
+            lambda plugin, page: plugin.free_config["apt_configs"]["slot.hkg.it.tourist"].update(service_id=9001),
+        )
+        for index, mutate in enumerate(mutations):
+            with self.subTest(index=index):
+                def configure(plugin, page):
+                    page.preflight_hook = lambda: mutate(plugin, page)
+                result = self.run_gate(configure=configure)
+                self.assertEqual(result.code, 1)
+                self.assertEqual(result.page.otp_clicks, 0)
+                self.assert_clean(result)
+
+    def test_account_change_while_reading_otp_does_not_write_code(self):
+        state = {}
+        def configure(plugin, page):
+            state["plugin"] = plugin
+        def reader():
+            state["plugin"].config.account.username = "another@example.test"
+            return OTP
+        result = self.run_gate(configure=configure, otp_reader=reader)
+        self.assertEqual(result.code, 1)
+        self.assertEqual(result.page.otp_value, "")
+        self.assertEqual(result.page.avanti_clicks, 0)
+        self.assert_clean(result)
+
+    def test_existing_calendar_is_not_accepted_as_a_fresh_login(self):
+        page = GatePage()
+        page.url = ORIGIN + CALENDAR_PATH
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        result.plugin.book.assert_not_called()
+        self.assertEqual(page.otp_clicks, 0)
+
+    def test_unexpected_book_success_is_never_reported_as_gate_success(self):
+        def configure(plugin, page):
+            plugin.book = Mock(return_value=VSBookResult(success=True, urn="private-reservation"))
+        result = self.run_gate(configure=configure)
+        self.assertEqual(result.code, 1)
+        self.assertEqual(result.page.otp_clicks, 0)
+        self.assertNotIn("private-reservation", result.output)
+        self.assert_clean(result)
+
+    def test_lost_selection_after_book_is_not_clicked_again(self):
+        def configure(plugin, page):
+            original = plugin.book
+            def call(*args, **kwargs):
+                result = original(*args, **kwargs)
+                if page.url.endswith(CALENDAR_PATH):
+                    page.active = False
+                return result
+            plugin.book = Mock(side_effect=call)
+        result = self.run_gate(configure=configure)
+        self.assertEqual(result.code, 1)
+        self.assertEqual(result.page.clicks, 1)
+        self.assert_clean(result)
+
+    def test_otp_during_book_fails_audit_without_repeating_preparation(self):
+        page = GatePage()
+        original = page.refresh
+        def refresh():
+            original()
+            page.emit(preparation.OTP_PATH, "GET")
+        page.refresh = refresh
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        self.assertEqual((page.otp_clicks, page.avanti_clicks), (1, 1))
+        self.assertFalse(result.report["passed"])
+        self.assert_clean(result)
+
+    def test_final_request_after_avanti_is_detected_before_book(self):
+        page = GatePage()
+        page.preparation_mutator = lambda packet, selector: (
+            page.emit("/BookingCalendar/InsertNewBooking") if selector == "#btnAvanti" else None
+        )
+        result = self.run_gate(page)
+        self.assertEqual(result.code, 1)
+        result.plugin._record_calendar_book_prepared_route.assert_not_called()
+        self.assertEqual(page.refreshes, 0)
+        self.assertEqual(result.report["requests"]["finalRequests"], 1)
+        self.assertFalse(page.auto_accept)
+
+    def test_reservation_change_prevents_positive_gate(self):
+        result = self.run_gate(after=preparation.ReservationSnapshot(1, 0))
+        self.assertEqual(result.code, 1)
+        self.assertFalse(result.report["passed"])
+        self.assert_clean(result)
+
+    def test_waitlist_change_prevents_positive_gate(self):
+        result = self.run_gate(after=preparation.ReservationSnapshot(0, 1))
+        self.assertEqual(result.code, 1)
+        self.assertFalse(result.report["passed"])
+
+    def test_late_business_request_during_reconciliation_is_detected(self):
+        def hook(plugin, page, count):
+            if count == 2:
+                page.emit(AVAILABILITY_PATH)
+        result = self.run_gate(reservation_hook=hook)
+        self.assertEqual(result.code, 1)
+        self.assertFalse(result.report["passed"])
+        self.assert_clean(result)
+
+    def test_failed_read_only_reconciliation_does_not_publish_passed(self):
+        def hook(plugin, page, count):
+            if count == 2:
+                raise RuntimeError("private-state")
+        result = self.run_gate(reservation_hook=hook)
+        self.assertEqual(result.code, 1)
+        self.assertNotIn("private-state", result.output)
+        self.assert_clean(result)
+
+    def test_cleanup_failure_has_distinct_return_code(self):
+        def configure(plugin, page):
+            plugin.cleanup.side_effect = RuntimeError("private browser details")
+        result = self.run_gate(configure=configure)
+        self.assertEqual(result.code, 3)
+        self.assertFalse(result.report["passed"])
+        self.assertNotIn("private browser details", result.output)
+
+    def test_provider_exception_does_not_log_credentials_code_or_body(self):
+        def configure(plugin, page):
+            plugin.create_session.side_effect = RuntimeError(f"{USERNAME} {PASSWORD} {OTP} BODY private")
+        result = self.run_gate(configure=configure)
+        self.assertEqual(result.code, 1)
+        for secret in (USERNAME, PASSWORD, OTP, "BODY private"):
+            self.assertNotIn(secret, result.output)
+        result.plugin.cleanup.assert_called_once()
+
+
+class BookGateInputTests(unittest.TestCase):
+    def test_cleanup_avoids_installed_sdk_duplicate_stop_failure(self):
+        from DrissionPage._units.listener import Listener
+
+        listener = Listener.__new__(Listener)
+        listener.listening = False
+        driver = listener._driver = Mock()
+        listener.stop()
+        driver.stop.assert_called_once()
+        self.assertIsNone(listener._driver)
+        # Prove the actual SDK failure, then exercise our guarded cleanup.
+        with self.assertRaises(AttributeError):
+            listener.stop()
+        gate._stop_listener_if_active(SimpleNamespace(listen=listener))
+        driver.stop.assert_called_once()
+
+    def test_cleanup_stops_an_active_listener(self):
+        listener = SimpleNamespace(listening=True, stop=Mock())
+        gate._stop_listener_if_active(SimpleNamespace(listen=listener))
+        listener.stop.assert_called_once()
+
+    def test_diagnostic_only_reads_the_calendar_and_never_emits_service_value(self):
+        for path in ("/BookingCalendar", "/Services"):
+            with self.subTest(path=path):
+                page = SimpleNamespace(url=ORIGIN + path, run_js=Mock(return_value={
+                    "path": path, "count": 1, "value": PASSWORD,
+                }))
+                captured = StringIO()
+                with redirect_stdout(captured):
+                    gate._print_calendar_preparation_diagnostic(page)
+                self.assertNotIn(PASSWORD, captured.getvalue())
+                diagnostic = json.loads(captured.getvalue().split("=", 1)[1])
+                if path == "/BookingCalendar":
+                    self.assertEqual(diagnostic["valueLength"], len(PASSWORD))
+                    page.run_js.assert_called_once_with(calendar_book.RUNTIME_SERVICE_SCRIPT)
+                else:
+                    self.assertFalse(diagnostic["pathMatches"])
+                    page.run_js.assert_not_called()
+
+    def test_preparation_reasons_only_allow_exact_known_messages(self):
+        for message, reason in (*gate._PREPARATION_FAILURES.items(), (PASSWORD, None)):
+            with self.subTest(reason=reason):
+                captured = StringIO()
+                with redirect_stdout(captured):
+                    gate._failure("calendar_preparation", gate.BizLogicError(message))
+                failure = json.loads(captured.getvalue().split("=", 1)[1])
+                self.assertEqual(failure.get("reason"), reason)
+                self.assertNotIn(PASSWORD, captured.getvalue())
+
+    def test_credentials_project_only_book_fields(self):
+        env = {"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret",
+               "ITA_BOOK_USERNAME": USERNAME, "ITA_BOOK_PASSWORD": PASSWORD}
+        with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
+                patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
+            self.assertEqual(gate._book_credentials(env), (USERNAME, PASSWORD))
+        helper.assert_called_once_with({"ITA_USERNAME": USERNAME, "ITA_PASSWORD": PASSWORD}, non_interactive=False)
+        loader.assert_not_called()
+
+    def test_query_credentials_do_not_supply_fallback(self):
+        with patch.object(gate, "_get_credentials", return_value=(USERNAME, PASSWORD)) as helper, \
+                patch.object(gate, "load_local_account") as loader, redirect_stdout(StringIO()):
+            gate._book_credentials({"ITA_USERNAME": "query@example.test", "ITA_PASSWORD": "query-secret"})
+        helper.assert_called_once_with({"ITA_USERNAME": "", "ITA_PASSWORD": ""}, non_interactive=False)
+        loader.assert_not_called()
+
+    def test_local_account_opt_in_uses_complete_saved_pair_and_never_prompts(self):
+        env = {"ITA_BOOK_USERNAME": "other@example.test", "ITA_BOOK_PASSWORD": "other-pass",
+               "ITA_USERNAME": "general@example.test", "ITA_PASSWORD": "general-pass"}
+        captured = StringIO()
+        with patch.object(gate, "load_local_account", return_value=SimpleNamespace(
+            username=USERNAME, password=PASSWORD,
+        )) as loader, patch.object(gate, "_get_credentials") as prompt, redirect_stdout(captured):
+            self.assertEqual(
+                gate._book_credentials(env, use_local_query_account=True), (USERNAME, PASSWORD),
+            )
+        loader.assert_called_once_with(gate.ITA_QUERY_ACCOUNT_FILE)
+        prompt.assert_not_called()
+        self.assertIn("source=local_query_file", captured.getvalue())
+        for secret in (USERNAME, PASSWORD, *env.values()):
+            self.assertNotIn(secret, captured.getvalue())
+
+    def test_local_loader_errors_are_safe_and_never_switch_credentials(self):
+        for reason in ("missing file", "unsafe permissions", "invalid JSON", "missing password"):
+            with self.subTest(reason=reason), patch.object(
+                gate, "load_local_account",
+                side_effect=gate.LocalAccountConfigurationError(f"{reason} {PASSWORD}"),
+            ), patch.object(gate, "_get_credentials") as prompt:
+                with self.assertRaises(gate.BookGateError) as caught:
+                    gate._book_credentials(gate_env(), use_local_query_account=True)
+                prompt.assert_not_called()
+                self.assertNotIn(PASSWORD, str(caught.exception))
+                self.assertIn("config/ita_query_account.local.json", str(caught.exception))
+
+    def test_local_secrets_are_not_part_of_source_fingerprint(self):
+        self.assertNotIn(gate.ITA_QUERY_ACCOUNT_FILE, gate.BOOK_GATE_SOURCE_PATHS)
+        self.assertIn(gate.REPO_ROOT / "utils" / "local_account.py", gate.BOOK_GATE_SOURCE_PATHS)
+
+    def test_cli_defaults_to_no_external_actions(self):
+        with patch.object(gate, "run_book_gate", return_value=0) as runner:
+            self.assertEqual(gate.main([]), 0)
+        self.assertIs(runner.call_args.kwargs["execute"], False)
+        self.assertIs(runner.call_args.kwargs["use_local_query_account"], False)
+
+    def test_cli_forwards_explicit_local_account_selection(self):
+        for mode, execute in (("--preflight", False), ("--run", True)):
+            with self.subTest(mode=mode), patch.object(gate, "run_book_gate", return_value=0) as runner:
+                self.assertEqual(gate.main(["--use-local-query-account", mode]), 0)
+            self.assertIs(runner.call_args.kwargs["execute"], execute)
+            self.assertIs(runner.call_args.kwargs["use_local_query_account"], True)
+
+    def test_cli_maps_vfs_preferences_to_real_inputs(self):
+        with patch.object(gate, "run_book_gate", return_value=0) as runner:
+            gate.main(["--run", "--expected-start-date", "2026-10-01", "--expected-end-date", "2026-12-31"])
+        self.assertIs(runner.call_args.kwargs["execute"], True)
+        self.assertEqual(runner.call_args.kwargs["user_inputs"],
+                         {"expected_start_date": "2026-10-01", "expected_end_date": "2026-12-31"})
+
+    def test_audit_rejects_non_integer_counts(self):
+        audit = Mock()
+        for value in (True, -1, "0", None):
+            audit.settled_snapshot.return_value = {
+                "otpRequests": value, "avantiPosts": 0, "availabilityRequests": 0, "finalRequests": 0,
+            }
+            with self.subTest(value=value), self.assertRaises(gate.BookGateError):
+                gate._counts(audit)
+
+    def test_no_query_session_loader_or_profile_setup_or_final_click_in_tool(self):
+        source = Path(gate.__file__).read_text()
+        # Only the explicitly read-only diagnostic may mention the final button.
+        self.assertEqual(source.count(gate.BOOK_FAILURE_STATE_SCRIPT), 1)
+        source = source.replace(gate.BOOK_FAILURE_STATE_SCRIPT, "")
+        for forbidden in ("_get_query_credentials(", "_prepare_query_profile(", "prepare_ita_query_profile(",
+                          "_record_calendar_query_prepared_route(", "#btnPrenotaNoOtp", "InsertNewBooking"):
+            self.assertNotIn(forbidden, source)
+        self.assertIn("preparation.OneShotAction", source)
+        self.assertIn("plugin.book(trigger", source)
+
+
+def book_failure_state():
+    result = {key: False for key in gate._BOOK_STATE_BOOLS}
+    result.update({key: 0 for key in gate._BOOK_STATE_COUNTS})
+    result.update(pathMatches=True, serviceValuePresent=True, serviceControlCount=1,
+                  finalButtonCount=1, finalGuarded=True, slotStates=[])
+    return result
+
+
+class BookProductionDiagnosticTests(unittest.TestCase):
+    def test_static_reason_messages_exist_in_the_current_producer_source(self):
+        source = Path(calendar_book.__file__).read_text() + (gate.REPO_ROOT / "plugins/ita_plugin.py").read_text()
+        for message in gate._PRODUCTION_BOOK_FAILURES:
+            if message == "Book precommit rejected (precommit_rejected)":
+                continue  # Produced by the existing protocol-code formatter.
+            with self.subTest(message=message):
+                self.assertIn(message, source)
+
+    def test_plugin_internal_failure_keeps_its_classification(self):
+        output = StringIO()
+        with redirect_stdout(output):
+            gate._failure("production_book", gate.BizLogicError(
+                "Italy Book Calendar failed before final confirmation",
+            ))
+        failure = json.loads(output.getvalue().split("=", 1)[1])
+        self.assertEqual(failure["reason"], "calendar_internal_failure")
+
+    def capture_state(self, raw):
+        page = SimpleNamespace(url=ORIGIN + CALENDAR_PATH, run_js=Mock(return_value=raw))
+        output = StringIO()
+        with redirect_stdout(output):
+            gate._print_production_book_diagnostic(page)
+        page.run_js.assert_called_once_with(gate.BOOK_FAILURE_STATE_SCRIPT)
+        return output.getvalue(), json.loads(output.getvalue().split("=", 1)[1])
+
+    def test_all_allowlisted_failures_publish_only_the_fixed_reason(self):
+        for message, reason in gate._PRODUCTION_BOOK_FAILURES.items():
+            with self.subTest(reason=reason):
+                output = StringIO()
+                with redirect_stdout(output):
+                    gate._failure("production_book", gate.BizLogicError(message))
+                result = json.loads(output.getvalue().split("=", 1)[1])
+                self.assertEqual(result["reason"], reason)
+                self.assertNotEqual(result["message"], message)
+
+    def test_unknown_body_and_wrong_stage_or_exception_type_are_not_exposed(self):
+        secret = f"Book slot DOM did not match the response before timeout {USERNAME} {PASSWORD} {OTP}"
+        for stage, error in (("production_book", gate.BizLogicError(secret)),
+                             ("production_book", RuntimeError(secret)),
+                             ("calendar_preparation", gate.BizLogicError(secret))):
+            with self.subTest(stage=stage, error_type=type(error).__name__):
+                output = StringIO()
+                with redirect_stdout(output):
+                    gate._failure(stage, error)
+                for value in (USERNAME, PASSWORD, OTP):
+                    self.assertNotIn(value, output.getvalue())
+                self.assertNotIn('"reason": "slot_dom_timeout"', output.getvalue())
+
+    def test_protocol_messages_emit_a_category_without_echoing_dynamic_code(self):
+        for label, expected in (("TimeSlots protocol", "timeslot_protocol_rejected"),
+                                ("Calendar protocol", "calendar_protocol_rejected"),
+                                ("precommit", "precommit_readback_rejected")):
+            output = StringIO()
+            with redirect_stdout(output):
+                gate._failure("production_book", gate.BizLogicError(f"Book {label} rejected (synthetic_code)"))
+            self.assertIn(f'"reason": "{expected}"', output.getvalue())
+            self.assertNotIn("synthetic_code", output.getvalue())
+
+    def test_valid_shape_is_reported_as_after_failure_not_original_error_state(self):
+        state = book_failure_state()
+        state["slotStates"] = [{**{key: False for key in gate._BOOK_SLOT_BOOLS}, "hiddenInputCount": 1}]
+        state["slotCount"] = 1
+        _, result = self.capture_state(state)
+        self.assertTrue(result["afterFailure"])
+        self.assertTrue(result["readSucceeded"])
+        self.assertEqual(result["state"], state)
+
+    def test_unexpected_fields_and_types_fail_closed_without_partial_values(self):
+        bad = []
+        state = book_failure_state()
+        bad.append({**state, "serviceValue": PASSWORD})
+        bad.append({**state, "serviceValuePresent": PASSWORD})
+        bad.append({**state, "slotCount": PASSWORD})
+        bad.append({**state, "slotCount": True})
+        bad.append({**state, "slotStates": [{"body": PASSWORD}]})
+        bad.append({**state, "slotStates": [{}] * 13})
+        bad.append({**state, "timeSlotResourceEntries": -1})
+        for raw in bad:
+            with self.subTest(raw_keys=tuple(raw)):
+                output, result = self.capture_state(raw)
+                self.assertFalse(result["readSucceeded"])
+                self.assertNotIn("state", result)
+                self.assertNotIn(PASSWORD, output)
+
+    def test_non_calendar_page_is_not_read(self):
+        page = SimpleNamespace(url=ORIGIN + "/Reservation", run_js=Mock())
+        output = StringIO()
+        with redirect_stdout(output):
+            gate._print_production_book_diagnostic(page)
+        page.run_js.assert_not_called()
+        self.assertIn('"readSucceeded": false', output.getvalue())
+
+    @unittest.skipUnless(shutil.which("node"), "Node is required for the read-only JS fixture")
+    def test_readonly_script_distinguishes_offscreen_and_obscured_slots(self):
+        fixture = r"""
+const script = process.argv[1], mode = process.argv[2];
+let measured = [];
+const makeSlot = (index) => ({
+  index,
+  classList: {contains: value => index === 0 && value === 'notAvailableFascia'},
+  querySelector: () => null,
+  querySelectorAll: () => [{get value() {throw Error('must not read slot identity');}}],
+  getBoundingClientRect: () => {
+    measured.push(index);
+    const left = index === 1 ? 1100 : 10;
+    return {left, right:left+100, top:20, bottom:60, width:100, height:40};
+  },
+  contains: () => false,
+  get innerText() {throw Error('must not read slot text');},
+  click: () => {throw Error('must not click');},
+});
+const slots = Array.from({length:mode === 'many' ? 13 : 3}, (_, index) => makeSlot(index));
+const timelineLink = {dataset:{date:'2026-10-13'}};
+const document = {
+  querySelector: selector => selector === '.selected' ? timelineLink : null,
+  querySelectorAll: selector => {
+    if (selector === '#idServizio') return [{value:'private-runtime-identifier'}];
+    if (selector === '.events a.selected') return [timelineLink];
+    if (selector === '.events-content li.selected') return [{dataset:{date:'2026-10-13'},querySelectorAll:()=>slots}];
+    if (selector === '#btnPrenotaNoOtp') return [Object.freeze({disabled:true,dataset:{coordinateFinalGuard:'enabled'}})];
+    if (selector === '.fascia.act') return [];
+    throw Error('unexpected selector');
+  },
+  elementFromPoint: () => slots[0],
+};
+const window = {innerWidth:1000, innerHeight:800,
+  getComputedStyle:()=>({display:'block',visibility:'visible',pointerEvents:'auto',opacity:'1'})};
+const location = {origin:'https://prenotami.esteri.it',pathname:'/BookingCalendar'};
+const performance = {getEntriesByType:()=>[
+  {name:location.origin+'/BookingCalendar/RetrieveTimeSlots'},
+  {name:'https://other.example.test/BookingCalendar/RetrieveTimeSlots'},
+  {name:'not-a-url'},
+]};
+const result = new Function('document','window','location','performance',script)(document,window,location,performance);
+console.log(JSON.stringify({result,measured}));
+"""
+        for mode in ("normal", "many"):
+            with self.subTest(mode=mode):
+                result = subprocess.run([shutil.which("node"), "-e", fixture, gate.BOOK_FAILURE_STATE_SCRIPT, mode],
+                                        text=True, capture_output=True, timeout=10)
+                self.assertEqual(result.returncode, 0, result.stderr)
+                self.assertNotIn("private-runtime-identifier", result.stdout)
+                raw = json.loads(result.stdout)["result"]
+                self.assertTrue(raw["selectedDatesMatch"])
+                self.assertTrue(raw["firstSelectedIsTimeline"])
+                self.assertTrue(raw["finalGuarded"])
+                self.assertEqual(raw["timeSlotResourceEntries"], 1)
+                self.assertFalse(raw["slotStates"][1]["inViewport"])
+                self.assertTrue(raw["slotStates"][1]["cssVisible"])
+                self.assertTrue(raw["slotStates"][2]["inViewport"])
+                self.assertFalse(raw["slotStates"][2]["centerHit"])
+                self.assertEqual(len(raw["slotStates"]), 12 if mode == "many" else 3)
+                self.assertEqual(raw["slotStatesTruncated"], mode == "many")
+                _, accepted = self.capture_state(raw)
+                self.assertTrue(accepted["readSucceeded"])
+
+
+class BookGateFormBoundaryScriptTests(unittest.TestCase):
+    def test_valid_boundary_uses_original_preflight_and_native_hidden_sync(self):
+        node = shutil.which("node")
+        if node is None:
+            self.fail("Node is required to validate the real preparation script")
+        config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
+        route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
+        script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
+        harness = r"""
+const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
+                  href: 'https://prenotami.esteri.it/Services/Booking/4937'};
+const hidden = {value: '0'}, companions = {value: '1'}, purposeHidden = {value: '0'};
+const booking = {value: '0', options: [{value: '1', textContent: 'Single booking'}],
+                 dispatchEvent: () => { hidden.value = '1'; companions.value = '0'; }};
+const purpose = {value: '0', options: [{value: '42', textContent: 'Tourism'}], dispatchEvent: () => {}};
+const privacy = {checked: false, click() { this.checked = true; }};
+const form = {action: location.href, method: 'post', enctype: 'multipart/form-data', querySelectorAll: () => []};
+const ids = {typeofbookingddl: booking, ddls_0: purpose, PrivacyCheck: privacy,
+             hiddenTipoPrenotazione: hidden, numAccSelected: companions, hiddenSelezionato_0: purposeHidden};
+const selectors = {'#bookingForm': [form], '#otp-input': [{value: ''}], '#otp-send': [{disabled: false}],
+                   '#btnAvanti': [{disabled: false}], 'input[name="cf-turnstile-response"]': [{value: 'fixture-only'}]};
+const document = {getElementById: (id) => ids[id], querySelector: () => form,
+                  querySelectorAll: (selector) => selectors[selector] || []};
+const output = new Function('document', 'location', 'window', SCRIPT)(document, location, {location});
+if (purposeHidden.value !== '0') throw Error('Must not write purpose hidden before native AVANTI');
+process.stdout.write(JSON.stringify(output));
+""".replace("SCRIPT", json.dumps(script))
+        completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
+        self.assertEqual(completed.returncode, 0, completed.stderr)
+        preparation.validate_booking_preflight(json.loads(completed.stdout))
+
+    def test_actual_script_checks_scope_before_reused_form_mutations(self):
+        node = shutil.which("node")
+        if node is None:
+            self.fail("Node is required to validate the real preparation boundary script")
+        config = preparation.build_calendar_gate_config(gate_env(), username=USERNAME, password=PASSWORD)
+        route = gate.resolve_route_config(config.free_config["apt_configs"], "slot.hkg.it.tourist")
+        script = gate._guarded_preflight_script(route, "/Services/Booking/4937")
+        harness = r"""
+const script = SCRIPT;
+const scenarios = ['wrongOrigin', 'wrongPath', 'noForm', 'twoForms', 'getForm',
+                   'wrongAction', 'queryAction', 'changedEnctype', 'upload'];
+for (const scenario of scenarios) {
+  let mutationReads = 0;
+  const location = {origin: 'https://prenotami.esteri.it', pathname: '/Services/Booking/4937',
+                    href: 'https://prenotami.esteri.it/Services/Booking/4937'};
+  const form = {method: 'post', enctype: 'multipart/form-data', action: location.href,
+                querySelectorAll: () => scenario === 'upload' ? [{}] : []};
+  if (scenario === 'wrongOrigin') location.origin = 'https://other.example';
+  if (scenario === 'wrongPath') location.pathname = '/BookingCalendar';
+  if (scenario === 'getForm') form.method = 'get';
+  if (scenario === 'wrongAction') form.action = 'https://other.example/Services/Booking/4937';
+  if (scenario === 'queryAction') form.action += '?changed=1';
+  if (scenario === 'changedEnctype') form.enctype = 'text/plain';
+  const document = {
+    querySelectorAll: () => scenario === 'noForm' ? [] : scenario === 'twoForms' ? [form, form] : [form],
+    querySelector: () => { mutationReads++; throw Error('Must stop before preflight'); }
+  };
+  const result = new Function('document', 'location', script)(document, location);
+  if (result.pathMatches !== false || mutationReads !== 0) throw Error(scenario);
+}
+process.stdout.write('FORM_BOUNDARY_OK');
+""".replace("SCRIPT", json.dumps(script))
+        completed = subprocess.run([node, "-e", harness], capture_output=True, text=True, timeout=10)
+        self.assertEqual(completed.returncode, 0, completed.stderr)
+        self.assertEqual(completed.stdout, "FORM_BOUNDARY_OK")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 1377 - 0
test/test_debug_ita_calendar_gate.py

@@ -0,0 +1,1377 @@
+import ast
+import hashlib
+import json
+import unittest
+from contextlib import redirect_stdout
+from io import StringIO
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from plugins.ita_calendar_query import CALENDAR_GUARD_SCRIPT
+from plugins.ita_protocol import InventoryState, resolve_route_config
+from tools.debug_ita_calendar_gate import (
+    BookingPreflightStage,
+    CalendarGateError,
+    CalendarGateEvidence,
+    CalendarMonthScanResult,
+    CalendarNextMonthUnavailableError,
+    CalendarProbeResult,
+    NEXT_MONTH_CONTROL_SCRIPT,
+    OneShotAction,
+    QCAL_TOOL_CONTRACT_VERSION,
+    QCAL_TOOL_SOURCE_FINGERPRINT,
+    ReservationSnapshot,
+    _click_next_month,
+    _enter_otp,
+    _read_manual_otp,
+    build_calendar_gate_config,
+    listen_once,
+    parse_availability_packet,
+    read_reservation_snapshot,
+    resolve_qcal_forward_months,
+    run_calendar_gate,
+    safe_avanti_failure_diagnostic,
+    safe_next_month_diagnostic,
+    safe_preflight_diagnostic,
+    scan_calendar_horizon,
+    validate_avanti_packet,
+    validate_booking_preflight,
+    validate_next_month_snapshot,
+    validate_otp_packet,
+    wait_for_booking_preflight,
+)
+
+
+def gate_env():
+    return {
+        "ITA_ROUTING_KEY": "slot.hkg.it.tourist",
+        "ITA_SERVICE_ID": "4937",
+        "ITA_CITY": "Hong Kong",
+        "ITA_VISA_TYPE": "Tourist",
+        "ITA_CALENDAR_LOOKAHEAD_MONTHS": "3",
+        "ITA_BOOKING_TYPE_CONTROL_ID": "typeofbookingddl",
+        "ITA_BOOKING_TYPE_VALUE": "1",
+        "ITA_BOOKING_TYPE_LABELS": "Prenotazione Singola|Single booking",
+        "ITA_PURPOSE_CONTROL_ID": "ddls_0",
+        "ITA_PURPOSE_VALUE": "42",
+        "ITA_PURPOSE_LABELS": "Turismo|Tourism",
+    }
+
+
+def booking_preflight_snapshot(**changes):
+    snapshot = {
+        "pathMatches": True,
+        "formPresent": True,
+        "bookingTypeOptionMatched": True,
+        "purposeOptionMatched": True,
+        "bookingVisibleMatches": True,
+        "bookingHiddenMatches": True,
+        "companionsHiddenIsZero": True,
+        "purposeVisibleMatches": True,
+        "purposeHiddenIsPreSubmit": True,
+        "privacyChecked": True,
+        "otpInputCount": 1,
+        "otpValuePresent": False,
+        "otpButtonCount": 1,
+        "otpDisabled": False,
+        "avantiButtonCount": 1,
+        "avantiDisabled": False,
+        "turnstileCount": 1,
+        "turnstileTokenPresent": True,
+        "unknownRequiredCount": 0,
+    }
+    snapshot.update(changes)
+    return snapshot
+
+
+class FakeResponse:
+    def __init__(self, status, *, url="", raw_body="", headers=None):
+        self.status = status
+        self.url = url
+        self.raw_body = raw_body
+        self.headers = headers or {}
+
+
+class FakePacket:
+    def __init__(
+        self,
+        *,
+        method,
+        url,
+        status,
+        response_url="",
+        raw_body="",
+        headers=None,
+        post_data=None,
+    ):
+        self.method = method
+        self.url = url
+        self.response = FakeResponse(
+            status,
+            url=response_url,
+            raw_body=raw_body,
+            headers=headers,
+        )
+        self.request = SimpleNamespace(postData=post_data)
+
+
+class FakeListener:
+    def __init__(self, packet=None):
+        self.packet = packet
+        self.starts = []
+        self.waits = []
+        self.stop_count = 0
+
+    def start(self, target, method=None):
+        self.starts.append((target, method))
+
+    def wait(self, timeout=None):
+        self.waits.append(timeout)
+        return self.packet
+
+    def stop(self):
+        self.stop_count += 1
+
+
+class FakeReservationTab:
+    def __init__(self, outputs):
+        self.outputs = list(outputs)
+        self.wait = SimpleNamespace(doc_loaded=lambda: None)
+        self.close_count = 0
+
+    def run_js(self, _script):
+        if len(self.outputs) > 1:
+            return self.outputs.pop(0)
+        return self.outputs[0]
+
+    def close(self):
+        self.close_count += 1
+
+
+class CalendarGateConfigTests(unittest.TestCase):
+    def test_builds_one_explicit_live_route_with_final_disabled(self):
+        config = build_calendar_gate_config(
+            gate_env(),
+            username="offline@example.test",
+            password="not-a-real-password",
+        )
+        free_config = config.free_config
+        route = resolve_route_config(
+            free_config["apt_configs"],
+            "slot.hkg.it.tourist",
+        )
+
+        self.assertEqual(free_config["query_mode"], "services_probe")
+        self.assertIs(free_config["final_submit_enabled"], False)
+        self.assertEqual(route.service_id, 4937)
+        self.assertEqual(route.capability.value, "single_schengen_tourism")
+        self.assertEqual(route.calendar_scan.lookahead_months, 3)
+        self.assertEqual(route.booking_type.control_id, "typeofbookingddl")
+        self.assertEqual(route.booking_type.value, "1")
+        self.assertEqual(route.purpose.value, "42")
+
+    def test_missing_any_live_route_field_fails_closed(self):
+        for missing in (
+            "ITA_CALENDAR_LOOKAHEAD_MONTHS",
+            "ITA_BOOKING_TYPE_CONTROL_ID",
+            "ITA_BOOKING_TYPE_LABELS",
+            "ITA_PURPOSE_VALUE",
+        ):
+            with self.subTest(missing=missing):
+                env = gate_env()
+                env.pop(missing)
+                with self.assertRaisesRegex(CalendarGateError, missing):
+                    build_calendar_gate_config(
+                        env,
+                        username="offline@example.test",
+                        password="not-a-real-password",
+                    )
+
+    def test_resolves_a_separate_bounded_discovery_horizon(self):
+        self.assertEqual(resolve_qcal_forward_months({}), 1)
+        self.assertEqual(
+            resolve_qcal_forward_months({"ITA_QCAL_FORWARD_MONTHS": "12"}),
+            12,
+        )
+        for invalid in ("0", "13", "invalid", "1.5"):
+            with self.subTest(invalid=invalid):
+                with self.assertRaisesRegex(
+                    CalendarGateError,
+                    "ITA_QCAL_FORWARD_MONTHS",
+                ):
+                    resolve_qcal_forward_months(
+                        {"ITA_QCAL_FORWARD_MONTHS": invalid}
+                    )
+
+
+class GateValueObjectTests(unittest.TestCase):
+    def test_reservation_snapshot_requires_nonnegative_plain_integers(self):
+        self.assertEqual(
+            ReservationSnapshot(reservations=0, waitlist=1).total,
+            1,
+        )
+        for kwargs in (
+            {"reservations": -1, "waitlist": 0},
+            {"reservations": True, "waitlist": 0},
+            {"reservations": 0, "waitlist": "0"},
+        ):
+            with self.subTest(kwargs=kwargs):
+                with self.assertRaises(CalendarGateError):
+                    ReservationSnapshot(**kwargs)
+
+    def test_gate_evidence_passes_only_the_exact_qcal_contract(self):
+        empty = ReservationSnapshot(0, 0)
+        evidence = CalendarGateEvidence(
+            before=empty,
+            after=empty,
+            otp_requests=1,
+            avanti_posts=1,
+            availability_requests=2,
+            final_requests=0,
+            calendar_ready=True,
+        )
+        self.assertTrue(evidence.passed)
+
+        variants = (
+            {"after": ReservationSnapshot(1, 0)},
+            {"otp_requests": 0},
+            {"avanti_posts": 2},
+            {"availability_requests": 1},
+            {"final_requests": 1},
+            {"calendar_ready": False},
+        )
+        for changes in variants:
+            with self.subTest(changes=changes):
+                values = {
+                    "before": evidence.before,
+                    "after": evidence.after,
+                    "otp_requests": evidence.otp_requests,
+                    "avanti_posts": evidence.avanti_posts,
+                    "availability_requests": evidence.availability_requests,
+                    "final_requests": evidence.final_requests,
+                    "calendar_ready": evidence.calendar_ready,
+                }
+                values.update(changes)
+                self.assertFalse(CalendarGateEvidence(**values).passed)
+
+    def test_one_shot_action_marks_attempt_before_calling(self):
+        calls = []
+        guard = OneShotAction("OTP")
+        self.assertEqual(guard.run(lambda: calls.append("called") or 7), 7)
+        self.assertEqual(calls, ["called"])
+
+        with self.assertRaisesRegex(CalendarGateError, "OTP.*already attempted"):
+            guard.run(lambda: calls.append("second"))
+        self.assertEqual(calls, ["called"])
+
+        failing = OneShotAction("AVANTI")
+        with self.assertRaisesRegex(RuntimeError, "ambiguous"):
+            failing.run(
+                lambda: (_ for _ in ()).throw(RuntimeError("ambiguous"))
+            )
+        with self.assertRaisesRegex(CalendarGateError, "already attempted"):
+            failing.run(lambda: None)
+
+
+class NetworkContractTests(unittest.TestCase):
+    def test_listener_always_stops_and_performs_one_action(self):
+        packet = object()
+        listener = FakeListener(packet)
+        page = SimpleNamespace(listen=listener)
+        actions = []
+
+        result = listen_once(
+            page,
+            target="/safe-endpoint",
+            method="POST",
+            action=lambda: actions.append("one"),
+            timeout=9,
+        )
+
+        self.assertIs(result, packet)
+        self.assertEqual(actions, ["one"])
+        self.assertEqual(listener.starts, [("/safe-endpoint", "POST")])
+        self.assertEqual(listener.waits, [9])
+        self.assertEqual(listener.stop_count, 1)
+
+        failing_listener = FakeListener(None)
+        failing_page = SimpleNamespace(listen=failing_listener)
+        with self.assertRaisesRegex(CalendarGateError, "not observed"):
+            listen_once(
+                failing_page,
+                target="/safe-endpoint",
+                method="GET",
+                action=lambda: None,
+                timeout=1,
+            )
+        self.assertEqual(failing_listener.stop_count, 1)
+
+        raising_listener = FakeListener(packet)
+        raising_page = SimpleNamespace(listen=raising_listener)
+        with self.assertRaisesRegex(RuntimeError, "action failed"):
+            listen_once(
+                raising_page,
+                target="/safe-endpoint",
+                method="POST",
+                action=lambda: (_ for _ in ()).throw(
+                    RuntimeError("action failed")
+                ),
+                timeout=1,
+            )
+        self.assertEqual(raising_listener.stop_count, 1)
+
+    def test_otp_requires_exact_get_route_status_and_json_string(self):
+        packet = FakePacket(
+            method="GET",
+            url=(
+                "https://prenotami.esteri.it/BookingCalendar/GenerateOTP"
+                "?ServiceID=4937"
+            ),
+            status=200,
+            raw_body='"SENT"',
+        )
+        validate_otp_packet(packet, service_id=4937)
+
+        bad_packets = (
+            FakePacket(
+                method="POST",
+                url=packet.url,
+                status=200,
+                raw_body='"SENT"',
+            ),
+            FakePacket(
+                method="GET",
+                url=packet.url,
+                status=201,
+                raw_body='"SENT"',
+            ),
+            FakePacket(
+                method="GET",
+                url=packet.url,
+                status=200,
+                raw_body="SENT",
+            ),
+            FakePacket(
+                method="GET",
+                url=packet.url.replace("4937", "1321"),
+                status=200,
+                raw_body='"SENT"',
+            ),
+        )
+        for bad in bad_packets:
+            with self.subTest(packet=bad):
+                with self.assertRaises(CalendarGateError):
+                    validate_otp_packet(bad, service_id=4937)
+
+    def test_avanti_accepts_direct_302_to_the_observed_calendar(self):
+        packet = FakePacket(
+            method="POST",
+            url="https://prenotami.esteri.it/Services/Booking/4937",
+            status=302,
+            headers={
+                "Location": (
+                    "/BookingCalendar?selectedService="
+                    "Visti%20Nazionali%20e%20Schengen"
+                )
+            },
+        )
+        mode = validate_avanti_packet(
+            packet,
+            booking_path="/Services/Booking/4937",
+            final_page_url=(
+                "https://prenotami.esteri.it/BookingCalendar"
+                "?selectedService=Visti"
+            ),
+        )
+        self.assertEqual(mode, "direct_302")
+
+    def test_avanti_accepts_only_a_triply_consistent_followed_200(self):
+        packet = FakePacket(
+            method="POST",
+            url="https://prenotami.esteri.it/Services/Booking/4937",
+            status=200,
+            response_url=(
+                "https://prenotami.esteri.it/BookingCalendar"
+                "?selectedService=Visti"
+            ),
+        )
+        mode = validate_avanti_packet(
+            packet,
+            booking_path="/Services/Booking/4937",
+            final_page_url="https://prenotami.esteri.it/BookingCalendar",
+        )
+        self.assertEqual(mode, "followed_redirect_200")
+
+    def test_avanti_rejects_inconsistent_redirect_evidence(self):
+        cases = (
+            {
+                "status": 200,
+                "response_url": "https://prenotami.esteri.it/Services",
+                "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
+            },
+            {
+                "status": 200,
+                "response_url": "https://example.test/BookingCalendar",
+                "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
+            },
+            {
+                "status": 200,
+                "response_url": (
+                    "https://prenotami.esteri.it:444/BookingCalendar"
+                ),
+                "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
+            },
+            {
+                "status": 200,
+                "response_url": "https://prenotami.esteri.it/BookingCalendar",
+                "final_page_url": "https://prenotami.esteri.it/Services",
+            },
+            {
+                "status": 201,
+                "response_url": "https://prenotami.esteri.it/BookingCalendar",
+                "final_page_url": "https://prenotami.esteri.it/BookingCalendar",
+            },
+        )
+        for case in cases:
+            with self.subTest(case=case):
+                bad = FakePacket(
+                    method="POST",
+                    url=(
+                        "https://prenotami.esteri.it/Services/Booking/4937"
+                    ),
+                    status=case["status"],
+                    response_url=case["response_url"],
+                )
+                with self.assertRaises(CalendarGateError):
+                    validate_avanti_packet(
+                        bad,
+                        booking_path="/Services/Booking/4937",
+                        final_page_url=case["final_page_url"],
+                    )
+
+    def test_avanti_rejects_bad_direct_redirects_and_requests(self):
+        for method, request_url, location in (
+            (
+                "POST",
+                "https://prenotami.esteri.it/Services/Booking/4937",
+                "/Services",
+            ),
+            (
+                "POST",
+                "https://prenotami.esteri.it/Services/Booking/4937",
+                "https://example.test/BookingCalendar",
+            ),
+            (
+                "POST",
+                "https://prenotami.esteri.it/Services/Booking/4937?retry=1",
+                "/BookingCalendar",
+            ),
+            (
+                "GET",
+                "https://prenotami.esteri.it/Services/Booking/4937",
+                "/BookingCalendar",
+            ),
+            (
+                "POST",
+                "https://prenotami.esteri.it/Services/Booking/1321",
+                "/BookingCalendar",
+            ),
+            (
+                "POST",
+                "https://example.test/Services/Booking/4937",
+                "/BookingCalendar",
+            ),
+            (
+                "POST",
+                "https://prenotami.esteri.it/Services/Booking/4937",
+                "",
+            ),
+        ):
+            with self.subTest(
+                method=method,
+                request_url=request_url,
+                location=location,
+            ):
+                packet = FakePacket(
+                    method=method,
+                    url=request_url,
+                    status=302,
+                    headers={"Location": location},
+                )
+                with self.assertRaises(CalendarGateError):
+                    validate_avanti_packet(
+                        packet,
+                        booking_path="/Services/Booking/4937",
+                        final_page_url=(
+                            "https://prenotami.esteri.it/BookingCalendar"
+                        ),
+                    )
+
+    def test_avanti_failure_diagnostic_is_strictly_allowlisted(self):
+        packet = FakePacket(
+            method="POST",
+            url="https://prenotami.esteri.it/Services/Booking/4937",
+            status=200,
+            response_url=(
+                "https://prenotami.esteri.it/Services/Booking/4937"
+                "?private-response-query"
+            ),
+            raw_body="private-response-body",
+            headers={
+                "Location": (
+                    "/BookingCalendar?private-location-query"
+                )
+            },
+            post_data="private-form-data",
+        )
+        raw = {
+            "path": "/Services/Booking/4937",
+            "bookingFormPresent": True,
+            "otpValuePresent": True,
+            "otpInvalidVisible": False,
+            "avantiDisabled": False,
+            "turnstileTokenPresent": False,
+            "visibleValidationCount": 1,
+            "visibleConfirmCount": 0,
+            "finalRequestCount": 0,
+            "mustNotLeak": "private-runtime-value",
+        }
+
+        diagnostic = safe_avanti_failure_diagnostic(
+            packet,
+            raw,
+            booking_path="/Services/Booking/4937",
+        )
+
+        self.assertEqual(
+            set(diagnostic),
+            {
+                "outcome",
+                "contract",
+                "sourceFingerprint",
+                "snapshotType",
+                "bookingPostObserved",
+                "requestMatches",
+                "responseStatus",
+                "responsePath",
+                "locationPath",
+                "browserPath",
+                "bookingFormPresent",
+                "otpValuePresent",
+                "otpInvalidVisible",
+                "avantiDisabled",
+                "turnstileReady",
+                "visibleValidationCount",
+                "visibleConfirmCount",
+                "finalRequestCount",
+            },
+        )
+        self.assertEqual(diagnostic["outcome"], "booking_form_returned")
+        self.assertIs(diagnostic["bookingPostObserved"], True)
+        self.assertIs(diagnostic["requestMatches"], True)
+        self.assertEqual(
+            diagnostic["responseStatus"],
+            {"type": "int", "value": 200},
+        )
+        self.assertEqual(diagnostic["responsePath"], "booking")
+        self.assertEqual(diagnostic["locationPath"], "calendar")
+        self.assertEqual(diagnostic["browserPath"], "booking")
+        self.assertEqual(
+            diagnostic["otpValuePresent"],
+            {"type": "bool", "value": True},
+        )
+        serialized = json.dumps(diagnostic)
+        for private_value in (
+            "private-response-query",
+            "private-response-body",
+            "private-location-query",
+            "private-form-data",
+            "private-runtime-value",
+        ):
+            self.assertNotIn(private_value, serialized)
+
+    def test_avanti_failure_diagnostic_degrades_unknown_values(self):
+        diagnostic = safe_avanti_failure_diagnostic(
+            None,
+            "private-runtime-value",
+            booking_path="/Services/Booking/4937",
+        )
+
+        self.assertEqual(
+            diagnostic["outcome"],
+            "booking_post_not_observed",
+        )
+        self.assertIs(diagnostic["bookingPostObserved"], False)
+        self.assertEqual(diagnostic["responsePath"], "missing")
+        self.assertEqual(diagnostic["browserPath"], "missing")
+        self.assertEqual(
+            diagnostic["otpValuePresent"],
+            {"type": "NoneType", "value": None},
+        )
+        self.assertNotIn(
+            "private-runtime-value",
+            json.dumps(diagnostic),
+        )
+
+    def test_availability_packet_reuses_the_strict_protocol_parser(self):
+        inner = json.dumps(
+            [
+                {
+                    "DateLibere": "01/10/2026 00:00:00",
+                    "SlotLiberi": 0,
+                    "SlotRimanenti": -1,
+                },
+                {
+                    "DateLibere": "02/10/2026 00:00:00",
+                    "SlotLiberi": 1,
+                    "SlotRimanenti": 0,
+                },
+            ]
+        )
+        packet = FakePacket(
+            method="POST",
+            url=(
+                "https://prenotami.esteri.it/BookingCalendar/"
+                "RetrieveCalendarAvailability"
+            ),
+            status=200,
+            raw_body=json.dumps(inner),
+            post_data=json.dumps(
+                {"_Servizio": "runtime-only", "selectedDay": "01/10/2026"}
+            ),
+        )
+
+        result = parse_availability_packet(packet)
+
+        self.assertEqual(result.item_count, 2)
+        self.assertEqual(result.available_count, 1)
+        self.assertEqual(result.selected_day, "01/10/2026")
+        self.assertEqual(result.selected_month, (2026, 10))
+        self.assertEqual(result.days[0].state, InventoryState.UNAVAILABLE)
+        self.assertEqual(result.days[1].state, InventoryState.AVAILABLE)
+
+        packet.request.postData = json.dumps(
+            {
+                "_Servizio": "runtime-only",
+                "selectedDay": "01/10/2026",
+                "guessed": True,
+            }
+        )
+        with self.assertRaisesRegex(CalendarGateError, "request keys"):
+            parse_availability_packet(packet)
+
+
+class NextMonthControlTests(unittest.TestCase):
+    def test_snapshot_requires_one_actionable_control_and_exact_shape(self):
+        ready = {
+            "pathMatches": True,
+            "candidateCount": 4,
+            "actionableCount": 1,
+            "clicked": False,
+        }
+        self.assertIs(
+            validate_next_month_snapshot(
+                ready,
+                expected_clicked=False,
+            ),
+            ready,
+        )
+
+        unready = {**ready, "actionableCount": 0}
+        validate_next_month_snapshot(
+            unready,
+            expected_clicked=False,
+            allow_unready=True,
+        )
+        for changed, message in (
+            ({**ready, "actionableCount": 2}, "uniquely actionable"),
+            ({**ready, "candidateCount": True}, "candidateCount"),
+            ({**ready, "clicked": True}, "acknowledgement"),
+            ({**ready, "private": "value"}, "unexpected fields"),
+        ):
+            with self.subTest(changed=changed):
+                with self.assertRaisesRegex(CalendarGateError, message):
+                    validate_next_month_snapshot(
+                        changed,
+                        expected_clicked=False,
+                    )
+
+    def test_click_waits_then_atomically_clicks_once(self):
+        outputs = [
+            {
+                "pathMatches": True,
+                "candidateCount": 4,
+                "actionableCount": 0,
+                "clicked": False,
+            },
+            {
+                "pathMatches": True,
+                "candidateCount": 4,
+                "actionableCount": 1,
+                "clicked": False,
+            },
+            {
+                "pathMatches": True,
+                "candidateCount": 4,
+                "actionableCount": 1,
+                "clicked": True,
+            },
+        ]
+        calls = []
+
+        def run_js(script, should_click):
+            calls.append((script, should_click))
+            return outputs.pop(0)
+
+        stdout = StringIO()
+        with redirect_stdout(stdout):
+            with patch("tools.debug_ita_calendar_gate.time.sleep"):
+                _click_next_month(
+                    SimpleNamespace(run_js=run_js),
+                    timeout=1,
+                )
+
+        self.assertEqual(
+            [should_click for _script, should_click in calls],
+            [False, False, True],
+        )
+        self.assertTrue(
+            all(script == NEXT_MONTH_CONTROL_SCRIPT for script, _ in calls)
+        )
+        self.assertEqual(
+            stdout.getvalue().count("ITA_QCAL_NEXT_MONTH_DIAGNOSTIC="),
+            1,
+        )
+        self.assertIn('"clicked": {"type": "bool", "value": true}', stdout.getvalue())
+
+    def test_click_uses_a_distinct_error_for_an_unavailable_boundary(self):
+        with self.assertRaises(CalendarNextMonthUnavailableError):
+            _click_next_month(
+                SimpleNamespace(run_js=lambda _script, _click: None),
+                timeout=0,
+            )
+
+    def test_diagnostic_allowlist_never_serializes_unknown_values(self):
+        raw = {
+            "pathMatches": True,
+            "candidateCount": 4,
+            "actionableCount": 1,
+            "clicked": False,
+            "private": "private-runtime-value",
+        }
+
+        diagnostic = safe_next_month_diagnostic(raw)
+
+        self.assertEqual(
+            set(diagnostic),
+            {
+                "contract",
+                "sourceFingerprint",
+                "snapshotType",
+                "pathMatches",
+                "candidateCount",
+                "actionableCount",
+                "clicked",
+            },
+        )
+        self.assertNotIn("private-runtime-value", json.dumps(diagnostic))
+
+
+class CalendarHorizonScanTests(unittest.TestCase):
+    @staticmethod
+    def packet(month: int, available: bool = False) -> FakePacket:
+        slots_free = 1 if available else 0
+        slots_remaining = 0 if available else -1
+        inner = json.dumps(
+            [
+                {
+                    "DateLibere": f"01/{month:02d}/2026 00:00:00",
+                    "SlotLiberi": slots_free,
+                    "SlotRimanenti": slots_remaining,
+                }
+            ]
+        )
+        return FakePacket(
+            method="POST",
+            url=(
+                "https://prenotami.esteri.it/BookingCalendar/"
+                "RetrieveCalendarAvailability"
+            ),
+            status=200,
+            raw_body=json.dumps(inner),
+            post_data=json.dumps(
+                {
+                    "_Servizio": "runtime-only",
+                    "selectedDay": f"01/{month:02d}/2026",
+                }
+            ),
+        )
+
+    def test_scans_the_initial_month_plus_the_forward_limit(self):
+        packets = [
+            self.packet(8),
+            self.packet(9, available=True),
+            self.packet(10),
+        ]
+        actions = []
+        guards = []
+
+        def fake_listen(_page, *, action, **_kwargs):
+            action()
+            return packets.pop(0)
+
+        stdout = StringIO()
+        with redirect_stdout(stdout):
+            with patch(
+                "tools.debug_ita_calendar_gate.listen_once",
+                side_effect=fake_listen,
+            ), patch(
+                "tools.debug_ita_calendar_gate._refresh_calendar",
+                side_effect=lambda _page: actions.append("refresh"),
+            ), patch(
+                "tools.debug_ita_calendar_gate._click_next_month",
+                side_effect=lambda _page: actions.append("next"),
+            ), patch(
+                "tools.debug_ita_calendar_gate._calendar_guard",
+                side_effect=lambda _page: guards.append("guard"),
+            ), patch("tools.debug_ita_calendar_gate.time.sleep"):
+                result = scan_calendar_horizon(
+                    SimpleNamespace(),
+                    forward_months=2,
+                )
+
+        self.assertEqual(actions, ["refresh", "next", "next"])
+        self.assertEqual(guards, ["guard", "guard", "guard"])
+        self.assertEqual(result.forward_clicks, 2)
+        self.assertEqual(result.availability_requests, 3)
+        self.assertEqual(result.stop_reason, "forward_limit_reached")
+        self.assertEqual(result.probes[1].available_count, 1)
+        self.assertEqual(result.probes[-1].available_count, 0)
+        self.assertEqual(result.safe_dict()["monthsWithAvailability"], 1)
+        self.assertEqual(
+            result.safe_dict()["earliestAvailableDate"],
+            "2026-09-01",
+        )
+        self.assertEqual(result.safe_dict()["furthestMonth"], "2026-10")
+        self.assertIn("ITA_QCAL_MONTH_SCAN_RESULT=", stdout.getvalue())
+
+    def test_stops_cleanly_when_the_native_next_control_is_unavailable(self):
+        packets = [self.packet(8)]
+
+        def fake_listen(_page, *, action, **_kwargs):
+            action()
+            return packets.pop(0)
+
+        with patch(
+            "tools.debug_ita_calendar_gate.listen_once",
+            side_effect=fake_listen,
+        ), patch(
+            "tools.debug_ita_calendar_gate._refresh_calendar",
+        ), patch(
+            "tools.debug_ita_calendar_gate._click_next_month",
+            side_effect=CalendarNextMonthUnavailableError("bounded-stop"),
+        ), patch(
+            "tools.debug_ita_calendar_gate._calendar_guard",
+        ), patch("tools.debug_ita_calendar_gate.time.sleep"):
+            result = scan_calendar_horizon(
+                SimpleNamespace(),
+                forward_months=12,
+            )
+
+        self.assertEqual(result.forward_clicks, 0)
+        self.assertEqual(result.stop_reason, "next_control_unavailable")
+        self.assertTrue(result.safe_dict()["nextControlUnavailable"])
+
+    def test_result_rejects_skipped_or_excess_months(self):
+        august = CalendarProbeResult(
+            days=(),
+            selected_day="01/08/2026",
+        )
+        october = CalendarProbeResult(
+            days=(),
+            selected_day="01/10/2026",
+        )
+        with self.assertRaisesRegex(CalendarGateError, "exactly one month"):
+            CalendarMonthScanResult(
+                probes=(august, october),
+                requested_forward_months=2,
+                stop_reason="next_control_unavailable",
+            )
+        with self.assertRaisesRegex(CalendarGateError, "ended before"):
+            CalendarMonthScanResult(
+                probes=(august,),
+                requested_forward_months=2,
+                stop_reason="forward_limit_reached",
+            )
+
+    def test_result_accepts_an_exact_cross_year_transition(self):
+        december = CalendarProbeResult(
+            days=(),
+            selected_day="01/12/2026",
+        )
+        january = CalendarProbeResult(
+            days=(),
+            selected_day="01/01/2027",
+        )
+
+        result = CalendarMonthScanResult(
+            probes=(december, january),
+            requested_forward_months=1,
+            stop_reason="forward_limit_reached",
+        )
+
+        self.assertEqual(result.safe_dict()["startMonth"], "2026-12")
+        self.assertEqual(result.safe_dict()["furthestMonth"], "2027-01")
+        self.assertIsNone(result.safe_dict()["earliestAvailableDate"])
+
+
+class BookingPreflightTests(unittest.TestCase):
+    def test_diagnostic_is_stage_specific_and_strictly_allowlisted(self):
+        raw = booking_preflight_snapshot(otpDisabled=1)
+        raw["mustNotLeak"] = "private-runtime-value"
+
+        diagnostic = safe_preflight_diagnostic(
+            raw,
+            stage=BookingPreflightStage.AFTER_OTP_SEND,
+            outcome="rejected",
+        )
+
+        self.assertEqual(
+            set(diagnostic),
+            {
+                "contract",
+                "sourceFingerprint",
+                "outcome",
+                "stage",
+                "snapshotType",
+                "otpDisabled",
+                "otpValuePresent",
+                "avantiDisabled",
+                "turnstileReady",
+            },
+        )
+        self.assertEqual(
+            diagnostic["contract"],
+            QCAL_TOOL_CONTRACT_VERSION,
+        )
+        self.assertEqual(
+            diagnostic["sourceFingerprint"],
+            QCAL_TOOL_SOURCE_FINGERPRINT,
+        )
+        self.assertEqual(diagnostic["stage"], "after_otp_send")
+        self.assertEqual(
+            diagnostic["otpDisabled"],
+            {"type": "int", "value": None},
+        )
+        self.assertEqual(
+            diagnostic["otpValuePresent"],
+            {"type": "bool", "value": False},
+        )
+        self.assertNotIn(
+            "private-runtime-value",
+            json.dumps(diagnostic),
+        )
+
+        invalid_outcome = safe_preflight_diagnostic(
+            raw,
+            stage=BookingPreflightStage.AFTER_OTP_SEND,
+            outcome="private-runtime-value",
+        )
+        self.assertEqual(invalid_outcome["outcome"], "invalid")
+        self.assertNotIn(
+            "private-runtime-value",
+            json.dumps(invalid_outcome),
+        )
+
+    def test_rejected_preflight_logs_shape_without_runtime_values(self):
+        raw = booking_preflight_snapshot(otpDisabled=1)
+        raw["mustNotLeak"] = "private-runtime-value"
+        page = SimpleNamespace(run_js=lambda _script: raw)
+        stdout = StringIO()
+
+        with redirect_stdout(stdout):
+            with self.assertRaisesRegex(CalendarGateError, "otpDisabled"):
+                wait_for_booking_preflight(
+                    page,
+                    script="safe-script",
+                    stage=BookingPreflightStage.AFTER_OTP_SEND,
+                    timeout=1,
+                )
+
+        output = stdout.getvalue()
+        self.assertIn("ITA_QCAL_PREFLIGHT_DIAGNOSTIC=", output)
+        self.assertIn('"stage": "after_otp_send"', output)
+        self.assertIn('"type": "int"', output)
+        self.assertNotIn("private-runtime-value", output)
+
+    def test_preflight_requires_exact_safe_shape_without_reading_tokens(self):
+        raw = booking_preflight_snapshot()
+        validate_booking_preflight(raw)
+
+        for key in (
+            "pathMatches",
+            "purposeHiddenIsPreSubmit",
+            "privacyChecked",
+            "turnstileTokenPresent",
+            "otpDisabled",
+            "otpValuePresent",
+            "avantiDisabled",
+        ):
+            with self.subTest(key=key):
+                changed = dict(raw)
+                changed[key] = key in {
+                    "otpDisabled",
+                    "otpValuePresent",
+                    "avantiDisabled",
+                }
+                with self.assertRaisesRegex(CalendarGateError, key):
+                    validate_booking_preflight(changed)
+
+        changed = dict(raw)
+        changed["unknownRequiredCount"] = 1
+        with self.assertRaisesRegex(CalendarGateError, "unknownRequiredCount"):
+            validate_booking_preflight(changed)
+
+    def test_post_otp_accepts_cooldown_without_relaxing_structure(self):
+        cooldown = booking_preflight_snapshot(
+            otpDisabled=True,
+            otpValuePresent=True,
+        )
+
+        with self.assertRaisesRegex(CalendarGateError, "otpDisabled"):
+            validate_booking_preflight(cooldown)
+        validate_booking_preflight(
+            cooldown,
+            stage=BookingPreflightStage.AFTER_OTP_SEND,
+        )
+        validate_booking_preflight(
+            booking_preflight_snapshot(otpValuePresent=True),
+            stage=BookingPreflightStage.AFTER_OTP_SEND,
+        )
+
+        for key, value in (
+            ("otpDisabled", None),
+            ("otpValuePresent", False),
+            ("otpButtonCount", 0),
+            ("formPresent", False),
+            ("unknownRequiredCount", 1),
+        ):
+            with self.subTest(key=key):
+                changed = dict(cooldown)
+                changed[key] = value
+                with self.assertRaisesRegex(CalendarGateError, key):
+                    validate_booking_preflight(
+                        changed,
+                        stage=BookingPreflightStage.AFTER_OTP_SEND,
+                    )
+
+    def test_dynamic_wait_rechecks_token_without_relaxing_structure(self):
+        base = booking_preflight_snapshot(
+            avantiDisabled=True,
+            turnstileTokenPresent=False,
+        )
+        ready = dict(base)
+        ready["avantiDisabled"] = False
+        ready["turnstileTokenPresent"] = True
+        outputs = [base, ready]
+        page = SimpleNamespace(run_js=lambda _script: outputs.pop(0))
+
+        with patch("tools.debug_ita_calendar_gate.time.sleep"):
+            result = wait_for_booking_preflight(
+                page,
+                script="safe-script",
+                timeout=1,
+            )
+
+        self.assertIs(result, ready)
+
+    def test_post_otp_wait_accepts_disabled_send_button(self):
+        base = booking_preflight_snapshot(
+            otpDisabled=True,
+            otpValuePresent=True,
+            avantiDisabled=True,
+            turnstileTokenPresent=False,
+        )
+        ready = dict(base)
+        ready["avantiDisabled"] = False
+        ready["turnstileTokenPresent"] = True
+        outputs = [base, ready]
+        page = SimpleNamespace(run_js=lambda _script: outputs.pop(0))
+
+        stdout = StringIO()
+        with redirect_stdout(stdout):
+            with patch("tools.debug_ita_calendar_gate.time.sleep"):
+                result = wait_for_booking_preflight(
+                    page,
+                    script="safe-script",
+                    stage=BookingPreflightStage.AFTER_OTP_SEND,
+                    timeout=1,
+                )
+
+        self.assertIs(result, ready)
+        self.assertIn('"outcome": "ready"', stdout.getvalue())
+        self.assertIn('"stage": "after_otp_send"', stdout.getvalue())
+        self.assertIn('"type": "bool"', stdout.getvalue())
+
+
+class OtpEntryTests(unittest.TestCase):
+    def test_manual_otp_is_visible_and_still_validated(self):
+        prompt = StringIO()
+        with patch("builtins.input", return_value="123456") as input_mock:
+            with redirect_stdout(prompt):
+                result = _read_manual_otp()
+
+        self.assertEqual(result, "123456")
+        input_mock.assert_called_once_with(
+            "Italy booking OTP "
+            "(visible; terminal scrollback may retain it): "
+        )
+        self.assertNotIn("123456", prompt.getvalue())
+
+        for invalid in ("", "123", "1234567890123", "12a456"):
+            with self.subTest(invalid=invalid):
+                with patch("builtins.input", return_value=invalid):
+                    with self.assertRaisesRegex(
+                        CalendarGateError,
+                        "OTP must be 4-12 digits",
+                    ):
+                        _read_manual_otp()
+
+    def test_otp_entry_focuses_before_typing_and_compares_in_page(self):
+        events = []
+
+        class FakeOtpElement:
+            def input(self, value, clear=False):
+                events.append(("input", value, clear))
+
+            def run_js(self, script, value):
+                events.append(("compare", script, value))
+                return True
+
+        otp_element = FakeOtpElement()
+        plugin = SimpleNamespace(
+            page=SimpleNamespace(
+                ele=lambda selector, timeout=0: (
+                    otp_element if selector == "#otp-input" else None
+                )
+            ),
+            mouse=SimpleNamespace(
+                human_click_ele=lambda element: events.append(
+                    ("click", element)
+                )
+            ),
+        )
+        stdout = StringIO()
+
+        with redirect_stdout(stdout):
+            _enter_otp(plugin, "123456")
+
+        self.assertEqual(events[0], ("click", otp_element))
+        self.assertEqual(events[1], ("input", "123456", True))
+        self.assertEqual(events[2][0], "compare")
+        self.assertIn("this.value === arguments[0]", events[2][1])
+        self.assertEqual(events[2][2], "123456")
+        self.assertIn(
+            "ITA_QCAL_OTP_DOM_WRITE_VERIFIED matched=true",
+            stdout.getvalue(),
+        )
+        self.assertNotIn("123456", stdout.getvalue())
+
+    def test_otp_entry_fails_before_avanti_when_readback_differs(self):
+        otp_element = SimpleNamespace(
+            input=lambda _value, clear=False: None,
+            run_js=lambda _script, _value: False,
+        )
+        plugin = SimpleNamespace(
+            page=SimpleNamespace(ele=lambda _selector, timeout=0: otp_element),
+            mouse=SimpleNamespace(human_click_ele=lambda _element: None),
+        )
+
+        with self.assertRaisesRegex(
+            CalendarGateError,
+            "OTP DOM write verification failed",
+        ):
+            _enter_otp(plugin, "123456")
+
+
+class ToolContractTests(unittest.TestCase):
+    def test_contract_is_logged_before_route_or_credentials_are_read(self):
+        tool_path = (
+            Path(__file__).resolve().parents[1]
+            / "tools"
+            / "debug_ita_calendar_gate.py"
+        )
+        shared_path = (
+            Path(__file__).resolve().parents[1]
+            / "plugins"
+            / "ita_calendar_query.py"
+        )
+        plugin_path = tool_path.parents[1] / "plugins" / "ita_plugin.py"
+        protocol_path = tool_path.parents[1] / "plugins" / "ita_protocol.py"
+        expected_fingerprint = hashlib.sha256(
+            tool_path.read_bytes()
+            + (tool_path.parents[1] / "plugins" / "ita_calendar_session.py").read_bytes()
+            + shared_path.read_bytes()
+            + plugin_path.read_bytes() + protocol_path.read_bytes()
+            + (tool_path.parents[1] / "plugins" / "ita_calendar_book.py").read_bytes()
+            + (tool_path.parents[1] / "tools" / "debug_ita_soak.py").read_bytes()
+            + (tool_path.parents[1] / "toolkit" / "backoff.py").read_bytes()
+        ).hexdigest()[:12]
+        self.assertEqual(
+            QCAL_TOOL_SOURCE_FINGERPRINT,
+            expected_fingerprint,
+        )
+
+        stdout = StringIO()
+        with patch(
+            "tools.debug_ita_calendar_gate.resolve_debug_route",
+            side_effect=CalendarGateError("offline-stop"),
+        ):
+            with redirect_stdout(stdout):
+                with self.assertRaisesRegex(
+                    CalendarGateError,
+                    "offline-stop",
+                ):
+                    run_calendar_gate({})
+
+        self.assertEqual(
+            stdout.getvalue().strip(),
+            "ITA_QCAL_TOOL_CONTRACT "
+            f"version={QCAL_TOOL_CONTRACT_VERSION} "
+            f"source_sha256={QCAL_TOOL_SOURCE_FINGERPRINT}",
+        )
+
+
+class ReservationSnapshotTests(unittest.TestCase):
+    def test_reads_both_initialized_datatables_and_always_closes_tab(self):
+        loading = {
+            "path": "/Reservation",
+            "authenticated": True,
+            "tableCount": 2,
+            "ready": False,
+            "reservations": None,
+            "waitlist": None,
+        }
+        ready = {
+            **loading,
+            "ready": True,
+            "reservations": 2,
+            "waitlist": 1,
+        }
+        tab = FakeReservationTab([loading, ready, ready])
+        opened_urls = []
+        page = SimpleNamespace(
+            new_tab=lambda url: opened_urls.append(url) or tab
+        )
+
+        with patch("tools.debug_ita_calendar_gate.time.sleep"):
+            result = read_reservation_snapshot(
+                page,
+                timeout=1,
+                settle_seconds=0,
+            )
+
+        self.assertEqual(result, ReservationSnapshot(2, 1))
+        self.assertEqual(opened_urls, ["https://prenotami.esteri.it/Reservation"])
+        self.assertEqual(tab.close_count, 1)
+
+    def test_invalid_counts_fail_and_close_tab(self):
+        tab = FakeReservationTab(
+            [
+                {
+                    "path": "/Reservation",
+                    "authenticated": True,
+                    "tableCount": 2,
+                    "ready": True,
+                    "reservations": True,
+                    "waitlist": 0,
+                }
+            ]
+        )
+        page = SimpleNamespace(new_tab=lambda _url: tab)
+
+        with self.assertRaises(CalendarGateError):
+            read_reservation_snapshot(
+                page,
+                timeout=1,
+                settle_seconds=0,
+            )
+        self.assertEqual(tab.close_count, 1)
+
+
+class SourceSafetyTests(unittest.TestCase):
+    def test_gate_source_never_clicks_or_submits_the_final_control(self):
+        path = (
+            Path(__file__).resolve().parents[1]
+            / "tools"
+            / "debug_ita_calendar_gate.py"
+        )
+        source = path.read_text(encoding="utf-8")
+        tree = ast.parse(source)
+        violations = []
+        one_shot_calls = []
+        for node in ast.walk(tree):
+            if not isinstance(node, ast.Call):
+                continue
+            function = node.func
+            function_name = (
+                function.attr
+                if isinstance(function, ast.Attribute)
+                else function.id
+                if isinstance(function, ast.Name)
+                else ""
+            )
+            string_arguments = {
+                child.value
+                for child in ast.walk(node)
+                if isinstance(child, ast.Constant)
+                and isinstance(child.value, str)
+            }
+            if function_name in {"submit", "click"} and any(
+                "btnPrenotaNoOtp" in value
+                or "InsertNewBooking" in value
+                for value in string_arguments
+            ):
+                violations.append((function_name, node.lineno))
+            if function_name == "human_click_ele" and any(
+                "btnPrenotaNoOtp" in value
+                for value in string_arguments
+            ):
+                violations.append((function_name, node.lineno))
+            if function_name == "run" and isinstance(function, ast.Attribute):
+                if isinstance(function.value, ast.Name):
+                    one_shot_calls.append(function.value.id)
+
+        self.assertEqual(violations, [])
+        self.assertEqual(one_shot_calls.count("otp_guard"), 1)
+        self.assertEqual(one_shot_calls.count("avanti_guard"), 1)
+        self.assertIn("button.disabled = true", CALENDAR_GUARD_SCRIPT)
+        self.assertIn('OneShotAction("OTP")', source)
+        self.assertIn('OneShotAction("AVANTI")', source)
+        self.assertIn(
+            '#datetimepicker',
+            NEXT_MONTH_CONTROL_SCRIPT,
+        )
+        self.assertIn(
+            'th.dtpicker-next',
+            NEXT_MONTH_CONTROL_SCRIPT,
+        )
+        for forbidden_selector in (
+            "btnPrenotaNoOtp",
+            "InsertNewBooking",
+            ".fascia",
+            ".events a",
+            "a.next",
+            "data-action",
+            "fetch(",
+            "XMLHttpRequest",
+        ):
+            self.assertNotIn(
+                forbidden_selector,
+                NEXT_MONTH_CONTROL_SCRIPT,
+            )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 362 - 0
test/test_debug_ita_monitor.py

@@ -0,0 +1,362 @@
+import ast
+import io
+import subprocess
+import sys
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from tools.debug_ita_monitor import (
+    DEFAULT_MAX_PROBES,
+    DEFAULT_MAX_WAIT_SECONDS,
+    MIN_SAFE_WAIT_SECONDS,
+    run_monitor,
+)
+from tools.debug_ita_session import DebugConfigurationError
+from vs_types import AvailabilityStatus, VSQueryResult
+
+
+class FakeMonitorPage:
+    def __init__(self):
+        self.url = "https://prenotami.esteri.it/Services"
+        self.form_structure = None
+
+    def ele(self, _selector, timeout=None):
+        del timeout
+        return None
+
+    def run_js(self, _script):
+        return self.form_structure
+
+
+class FakeMonitorPlugin:
+    sequence = ["none"]
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = FakeMonitorPage()
+        self.create_session_calls = 0
+        self.query_calls = 0
+        self.cleanup_calls = 0
+        FakeMonitorPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        self.create_session_calls += 1
+
+    def query(self, apt_type):
+        behavior = self.sequence[min(self.query_calls, len(self.sequence) - 1)]
+        self.query_calls += 1
+        if behavior == "weak":
+            self.page.form_structure = {
+                "path": "/Services/Booking/1321",
+                "form": {
+                    "method": "POST",
+                    "action_path": "/Services/Booking/1321",
+                    "secret": "must-not-appear",
+                },
+                "fields": [
+                    {
+                        "tag": "input",
+                        "type": "hidden",
+                        "id": "RequestToken",
+                        "name": "__RequestVerificationToken",
+                        "required": False,
+                        "value": "private@example.test",
+                    }
+                ],
+                "buttons": [],
+            }
+            return VSQueryResult(
+                success=True,
+                apt_type=apt_type,
+                availability_status=AvailabilityStatus.NoneAvailable,
+            )
+        if behavior == "unexpected":
+            return VSQueryResult(
+                success=True,
+                apt_type=apt_type,
+                availability_status=AvailabilityStatus.Available,
+            )
+        if behavior == "error":
+            raise RuntimeError(
+                "private@example.test failed with token "
+                "abcdefghijklmnopqrstuvwxyz123456"
+            )
+        return VSQueryResult(
+            success=False,
+            apt_type=apt_type,
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+
+    def cleanup(self):
+        self.cleanup_calls += 1
+
+
+class DebugItaMonitorTests(unittest.TestCase):
+    def setUp(self):
+        FakeMonitorPlugin.sequence = ["none"]
+        FakeMonitorPlugin.last_instance = None
+
+    @staticmethod
+    def _run(
+        *,
+        apply=True,
+        max_probes=3,
+        randint=lambda _minimum, _maximum: 60,
+        sleep=lambda _seconds: None,
+    ):
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        with (
+            patch(
+                "tools.debug_ita_monitor.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch(
+                "tools.debug_ita_monitor._get_query_credentials",
+                return_value=("offline@example.test", "offline-password"),
+            ) as credential_reader,
+            patch(
+                "tools.debug_ita_monitor._prepare_query_profile",
+                return_value=Path("/offline/ita-query-profile"),
+            ) as profile_preparer,
+            patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin),
+            patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_monitor(
+                {},
+                apply=apply,
+                non_interactive=True,
+                min_wait=MIN_SAFE_WAIT_SECONDS,
+                max_wait=DEFAULT_MAX_WAIT_SECONDS,
+                max_probes=max_probes,
+                randint=randint,
+                sleep=sleep,
+            )
+        return (
+            exit_code,
+            stdout.getvalue(),
+            stderr.getvalue(),
+            credential_reader,
+            profile_preparer,
+        )
+
+    def test_default_preflight_requires_no_credentials_or_plugin(self):
+        exit_code, stdout, stderr, credential_reader, profile_preparer = self._run(
+            apply=False
+        )
+
+        self.assertEqual(exit_code, 0)
+        credential_reader.assert_not_called()
+        profile_preparer.assert_not_called()
+        self.assertIsNone(FakeMonitorPlugin.last_instance)
+        self.assertIn("ITA_MONITOR_PREFLIGHT_OK", stdout)
+        self.assertIn("external_request=false", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_no_slot_monitor_reuses_one_session_and_stops_at_max_probes(self):
+        FakeMonitorPlugin.sequence = ["none", "none", "none"]
+        waits = []
+        random_values = iter([60, 300])
+
+        exit_code, stdout, stderr, _, _ = self._run(
+            max_probes=3,
+            randint=lambda _minimum, _maximum: next(random_values),
+            sleep=waits.append,
+        )
+        plugin = FakeMonitorPlugin.last_instance
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(plugin.create_session_calls, 1)
+        self.assertEqual(plugin.query_calls, 3)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertEqual(waits, [60, 300])
+        self.assertIn("probe=3", stdout)
+        self.assertIn("ITA_MONITOR_MAX_PROBES_REACHED", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_weak_signal_stops_immediately_and_prints_sanitized_alert(self):
+        FakeMonitorPlugin.sequence = ["none", "weak", "none"]
+        waits = []
+
+        exit_code, stdout, stderr, _, _ = self._run(
+            max_probes=3,
+            sleep=waits.append,
+        )
+        plugin = FakeMonitorPlugin.last_instance
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(plugin.create_session_calls, 1)
+        self.assertEqual(plugin.query_calls, 2)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertEqual(waits, [60])
+        self.assertIn("\aITA_MONITOR_WEAK_SIGNAL", stdout)
+        self.assertIn("action=start-user-book-recheck-now", stdout)
+        self.assertIn("ITA_BOOKING_FORM_STRUCTURE=", stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("must-not-appear", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_weak_signal_publishes_one_local_handoff_only_when_enabled(self):
+        FakeMonitorPlugin.sequence = ["weak"]
+        published = []
+
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        with (
+            patch(
+                "tools.debug_ita_monitor.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch(
+                "tools.debug_ita_monitor._get_query_credentials",
+                return_value=("offline@example.test", "offline-password"),
+            ),
+            patch(
+                "tools.debug_ita_monitor._prepare_query_profile",
+                return_value=Path("/offline/ita-query-profile"),
+            ),
+            patch("tools.debug_ita_monitor.ItaPlugin", FakeMonitorPlugin),
+            patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_monitor(
+                {},
+                apply=True,
+                non_interactive=True,
+                min_wait=MIN_SAFE_WAIT_SECONDS,
+                max_wait=DEFAULT_MAX_WAIT_SECONDS,
+                max_probes=3,
+                publish_local_signal=True,
+                signal_publisher=lambda: published.append("weak"),
+            )
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(published, ["weak"])
+        self.assertIn("ITA_MONITOR_HANDOFF_PUBLISHED", stdout.getvalue())
+        self.assertEqual(stderr.getvalue(), "")
+
+    def test_unexpected_result_stops_without_another_probe(self):
+        FakeMonitorPlugin.sequence = ["unexpected", "none"]
+
+        exit_code, stdout, _stderr, _, _ = self._run(max_probes=3)
+        plugin = FakeMonitorPlugin.last_instance
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertIn("ITA_MONITOR_SAFE_STOP", stdout)
+
+    def test_query_error_stops_without_retry_and_redacts_diagnostics(self):
+        FakeMonitorPlugin.sequence = ["error", "none"]
+
+        exit_code, stdout, stderr, _, _ = self._run(max_probes=3)
+        plugin = FakeMonitorPlugin.last_instance
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertIn("ITA_MONITOR_FAILED type=RuntimeError", stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("abcdefghijklmnopqrstuvwxyz123456", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_ctrl_c_during_wait_cleans_up_without_traceback(self):
+        def interrupted_sleep(_seconds):
+            raise KeyboardInterrupt
+
+        exit_code, stdout, stderr, _, _ = self._run(
+            max_probes=3,
+            sleep=interrupted_sleep,
+        )
+        plugin = FakeMonitorPlugin.last_instance
+
+        self.assertEqual(exit_code, 130)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertIn("ITA_MONITOR_CANCELLED", stdout)
+        self.assertIn("ITA_MONITOR_CLEANUP_OK", stdout)
+        self.assertNotIn("Traceback", stdout + stderr)
+
+    def test_unsafe_limits_fail_before_credentials_or_plugin(self):
+        with (
+            patch(
+                "tools.debug_ita_monitor._get_query_credentials",
+                side_effect=AssertionError("credentials must not be read"),
+            ),
+            patch(
+                "tools.debug_ita_monitor.ItaPlugin",
+                side_effect=AssertionError("plugin must not be created"),
+            ),
+            self.assertRaises(DebugConfigurationError),
+        ):
+            run_monitor(
+                {},
+                apply=True,
+                non_interactive=True,
+                min_wait=59,
+                max_wait=300,
+                max_probes=1,
+            )
+
+    def test_cli_default_is_a_real_zero_network_preflight(self):
+        repo_root = Path(__file__).resolve().parents[1]
+        completed = subprocess.run(
+            [sys.executable, str(repo_root / "tools" / "debug_ita_monitor.py")],
+            cwd=repo_root,
+            check=False,
+            capture_output=True,
+            text=True,
+        )
+
+        self.assertEqual(completed.returncode, 0)
+        self.assertIn("ITA_MONITOR_PREFLIGHT_OK", completed.stdout)
+        self.assertIn("external_request=false", completed.stdout)
+        self.assertEqual(completed.stderr, "")
+
+    def test_source_has_one_query_call_and_no_book_or_redis_dependency(self):
+        source_path = (
+            Path(__file__).resolve().parents[1]
+            / "tools"
+            / "debug_ita_monitor.py"
+        )
+        source = source_path.read_text(encoding="utf-8")
+        tree = ast.parse(source)
+        query_calls = [
+            node
+            for node in ast.walk(tree)
+            if isinstance(node, ast.Call)
+            and isinstance(node.func, ast.Attribute)
+            and node.func.attr == "query"
+        ]
+        book_calls = [
+            node
+            for node in ast.walk(tree)
+            if isinstance(node, ast.Call)
+            and isinstance(node.func, ast.Attribute)
+            and node.func.attr == "book"
+        ]
+
+        self.assertEqual(len(query_calls), 1)
+        self.assertEqual(book_calls, [])
+        self.assertNotIn("redis", source.lower())
+
+    def test_defaults_match_the_existing_italy_sentinel_cadence(self):
+        self.assertEqual(MIN_SAFE_WAIT_SECONDS, 60)
+        self.assertEqual(DEFAULT_MAX_WAIT_SECONDS, 300)
+        self.assertEqual(DEFAULT_MAX_PROBES, 10)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 551 - 0
test/test_debug_ita_production_query_gate.py

@@ -0,0 +1,551 @@
+import json
+import unittest
+from contextlib import ExitStack, redirect_stdout
+from datetime import date, datetime
+from io import StringIO
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins.ita_calendar_query import (
+    AVAILABILITY_PATH,
+    CALENDAR_GUARD_SCRIPT,
+    NEXT_MONTH_CONTROL_SCRIPT,
+    CalendarGateError,
+    CalendarProbeResult,
+    CalendarQueryScanResult,
+)
+from plugins.ita_plugin import ItaPlugin
+from plugins.ita_protocol import CalendarDay, InventoryState
+from tools.debug_ita_calendar_gate import (
+    OTP_PATH,
+    CalendarGateMode,
+    CalendarRequestAudit,
+    ReservationSnapshot,
+    build_calendar_gate_config,
+    resolve_qcal_mode,
+    run_calendar_gate,
+    run_production_query_acceptance,
+    validate_production_query_result,
+)
+from tools.debug_ita_query import resolve_debug_route
+from vs_types import AvailabilityStatus, DateAvailability, TimeSlot, VSQueryResult
+
+
+def gate_env():
+    return {
+        "ITA_QCAL_MODE": "production_query",
+        "ITA_ROUTING_KEY": "slot.sample.it.tourist",
+        "ITA_SERVICE_ID": "9001",
+        "ITA_CITY": "Sample City",
+        "ITA_VISA_TYPE": "Tourist",
+        "ITA_CALENDAR_LOOKAHEAD_MONTHS": "3",
+        "ITA_BOOKING_TYPE_CONTROL_ID": "typeofbookingddl",
+        "ITA_BOOKING_TYPE_VALUE": "1",
+        "ITA_BOOKING_TYPE_LABELS": "Single booking",
+        "ITA_PURPOSE_CONTROL_ID": "ddls_0",
+        "ITA_PURPOSE_VALUE": "42",
+        "ITA_PURPOSE_LABELS": "Tourism",
+    }
+
+
+def make_scan(positive_days=(12, 20), *, start_month=8):
+    probes = []
+    for month in range(start_month, 11):
+        days = (
+            tuple(
+                CalendarDay(date(2026, month, day), 1, 0, InventoryState.AVAILABLE)
+                for day in positive_days
+            )
+            if month == 10 and positive_days
+            else (CalendarDay(date(2026, month, 1), 0, -1, InventoryState.UNAVAILABLE),)
+        )
+        probes.append(CalendarProbeResult(days, f"01/{month:02d}/2026"))
+    return CalendarQueryScanResult(
+        probes=tuple(probes),
+        lookahead_months=11 - start_month,
+        stop_reason="first_available_month" if positive_days else "horizon_exhausted",
+    )
+
+
+def make_result(scan, apt_type):
+    earliest = scan.earliest_available_date
+    value = datetime.combine(earliest, datetime.min.time()) if earliest else None
+    return VSQueryResult(
+        success=earliest is not None,
+        apt_type=apt_type,
+        availability_status=(
+            AvailabilityStatus.Available if earliest else AvailabilityStatus.NoneAvailable
+        ),
+        earliest_date=value,
+        availability=[DateAvailability(date=value, times=[])] if earliest else [],
+    )
+
+
+class FakeDriver:
+    def __init__(self):
+        self.event_handlers = {}
+        self.immediate_event_handlers = {}
+        self.is_running = True
+
+    def set_callback(self, event, callback, immediate=False):
+        handlers = self.immediate_event_handlers if immediate else self.event_handlers
+        if callback is None:
+            handlers.pop(event, None)
+        else:
+            handlers[event] = callback
+
+
+class FakeAuditPage:
+    def __init__(self):
+        self.driver = FakeDriver()
+        self.commands = []
+        self.final_requests = 0
+        self.url = "https://prenotami.esteri.it/BookingCalendar"
+
+    def run_cdp(self, method):
+        self.commands.append(method)
+        return {}
+
+    def emit(self, path, method="POST", **request_fields):
+        if "/InsertNewBooking" in path:
+            self.final_requests += 1
+        callback = self.driver.immediate_event_handlers.get(CalendarRequestAudit.EVENT)
+        if callback:
+            callback(request={
+                "url": "https://prenotami.esteri.it" + path,
+                "method": method,
+                **request_fields,
+            })
+
+
+class FakeProductionListener:
+    def __init__(self, page):
+        self.page = page
+        self.starts = []
+        self.stops = 0
+
+    def start(self, target, method=None):
+        self.starts.append((target, method))
+        self.page.packet = None
+
+    def wait(self, timeout=None):
+        return self.page.packet
+
+    def stop(self):
+        self.stops += 1
+
+
+class FakeProductionPage(FakeAuditPage):
+    def __init__(self, plans, *, extra_request=None):
+        super().__init__()
+        self.plans = plans
+        self.extra_request = extra_request
+        self.refresh_calls = 0
+        self.month_index = 0
+        self.forward_clicks = []
+        self.packet = None
+        self.listen = FakeProductionListener(self)
+        self.wait = SimpleNamespace(doc_loaded=lambda: None)
+
+    def ele(self, selector, timeout=None):
+        if selector != "#pingid-button":
+            raise AssertionError(f"Unexpected production lookup: {selector}")
+        return None
+
+    def refresh(self):
+        self.refresh_calls += 1
+        self.month_index = 0
+        self._publish_month()
+        if self.extra_request:
+            self.emit(self.extra_request)
+
+    def _publish_month(self):
+        year, month, positive_days = self.plans[self.refresh_calls - 1][self.month_index]
+        items = [
+            {
+                "DateLibere": f"{day:02d}/{month:02d}/{year} 00:00:00",
+                "SlotLiberi": 1,
+                "SlotRimanenti": 0,
+            }
+            for day in positive_days
+        ] or [{
+            "DateLibere": f"01/{month:02d}/{year} 00:00:00",
+            "SlotLiberi": 0,
+            "SlotRimanenti": -1,
+        }]
+        self.emit(AVAILABILITY_PATH)
+        self.packet = SimpleNamespace(
+            url="https://prenotami.esteri.it" + AVAILABILITY_PATH,
+            method="POST",
+            request=SimpleNamespace(postData={
+                "_Servizio": "runtime-service",
+                "selectedDay": f"01/{month:02d}/{year}",
+            }),
+            response=SimpleNamespace(status=200, raw_body=json.dumps(json.dumps(items))),
+        )
+
+    def run_js(self, script, *args):
+        if script == CALENDAR_GUARD_SCRIPT:
+            return {
+                "path": "/BookingCalendar",
+                "calendarFunctionPresent": True,
+                "finalButtonCount": 1,
+                "allFinalButtonsGuarded": True,
+                "finalRequestCount": self.final_requests,
+                "timeSlotRequestCount": 0,
+            }
+        if script == NEXT_MONTH_CONTROL_SCRIPT:
+            clicked = args == (True,)
+            if clicked:
+                self.month_index += 1
+                plan = self.plans[self.refresh_calls - 1]
+                self.forward_clicks.append(plan[self.month_index][:2])
+                self._publish_month()
+            return {
+                "pathMatches": True,
+                "candidateCount": 1,
+                "actionableCount": 1,
+                "clicked": clicked,
+            }
+        raise AssertionError("Unexpected production script")
+
+
+def make_plugin(page):
+    env = gate_env()
+    route = resolve_debug_route(env)
+    config = build_calendar_gate_config(
+        env, username="offline@example.test", password="not-a-real-password", route=route
+    )
+    plugin = ItaPlugin.__new__(ItaPlugin)
+    plugin.page = page
+    plugin.config = config
+    plugin.free_config = config.free_config
+    plugin.group_id = "offline-production-query"
+    plugin.logger = Mock()
+    plugin.last_calendar_query_scan = None
+    plugin._calendar_query_route_key = route.routing_key
+    # __new__ deliberately skips real browser/filesystem setup in these tests.
+    plugin.cleanup = Mock()
+    return plugin, route
+
+
+class ProductionGateModeTests(unittest.TestCase):
+    def test_mode_is_explicit_and_discovery_remains_the_default(self):
+        self.assertIs(resolve_qcal_mode({}), CalendarGateMode.DISCOVERY_HORIZON)
+        self.assertIs(resolve_qcal_mode(gate_env()), CalendarGateMode.PRODUCTION_QUERY)
+        with self.assertRaisesRegex(CalendarGateError, "ITA_QCAL_MODE"):
+            resolve_qcal_mode({"ITA_QCAL_MODE": "typo"})
+
+    def test_invalid_mode_is_rejected_before_credentials(self):
+        with patch("tools.debug_ita_calendar_gate._get_query_credentials") as credentials:
+            with redirect_stdout(StringIO()):
+                with self.assertRaisesRegex(CalendarGateError, "ITA_QCAL_MODE"):
+                    run_calendar_gate({"ITA_QCAL_MODE": "typo"})
+        credentials.assert_not_called()
+
+
+class PassiveRequestAuditTests(unittest.TestCase):
+    def test_counts_metadata_across_redirects_without_retaining_sensitive_data(self):
+        page = FakeAuditPage()
+        audit = CalendarRequestAudit(page)
+        audit.start()
+        page.emit(OTP_PATH + "?ServiceID=9001", "GET", postData="secret-otp-body")
+        page.emit("/Services/Booking/9001", "POST", headers={"Cookie": "secret-cookie"})
+        page.emit("/BookingCalendar", "GET")
+        page.emit(AVAILABILITY_PATH)
+        page.emit("/BookingCalendar/RetrieveTimeSlots")
+        page.emit("/BookingCalendar/InsertNewBooking")
+        audit._on_request(request={"url": "https://other.test/BookingCalendar/GenerateOTP", "method": "GET"})
+        self.assertEqual(audit.snapshot(), {
+            "otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 1, "finalRequests": 1
+        })
+        self.assertNotIn("secret", repr(audit.__dict__))
+        self.assertEqual(page.commands, ["Network.enable"])
+        audit.stop()
+        self.assertEqual(page.driver.immediate_event_handlers, {})
+        self.assertEqual(page.driver.event_handlers, {})
+
+    def test_refuses_to_replace_an_existing_callback(self):
+        for name in ("event_handlers", "immediate_event_handlers"):
+            with self.subTest(name=name):
+                page = FakeAuditPage()
+                callback = Mock()
+                getattr(page.driver, name)[CalendarRequestAudit.EVENT] = callback
+                with self.assertRaisesRegex(CalendarGateError, "existing callback"):
+                    CalendarRequestAudit(page).start()
+                self.assertIs(getattr(page.driver, name)[CalendarRequestAudit.EVENT], callback)
+                self.assertEqual(page.commands, [])
+
+    def test_invalid_events_and_disconnection_fail_closed(self):
+        page = FakeAuditPage()
+        audit = CalendarRequestAudit(page)
+        audit.start()
+        audit._on_request(request=None)
+        with self.assertRaisesRegex(CalendarGateError, "invalid event"):
+            audit.snapshot()
+        audit.stop()
+        with self.assertRaisesRegex(CalendarGateError, "not connected"):
+            audit.snapshot()
+
+    def test_detaches_callback_when_network_enable_fails(self):
+        page = FakeAuditPage()
+        page.run_cdp = Mock(side_effect=RuntimeError("offline failure"))
+        with self.assertRaisesRegex(RuntimeError, "offline failure"):
+            CalendarRequestAudit(page).start()
+        self.assertEqual(page.driver.immediate_event_handlers, {})
+
+    def test_settled_snapshot_is_bounded_and_passive(self):
+        page = FakeAuditPage()
+        audit = CalendarRequestAudit(page)
+        audit.start()
+        try:
+            self.assertEqual(audit.settled_snapshot(timeout=1), audit.snapshot())
+        finally:
+            audit.stop()
+        self.assertEqual(page.commands, ["Network.enable", "Page.getFrameTree"])
+
+
+class ProductionResultContractTests(unittest.TestCase):
+    def test_positive_result_and_snapshot_match_the_real_scan(self):
+        scan = make_scan()
+        apt_type = resolve_debug_route(gate_env()).appointment_type()
+        report = validate_production_query_result(
+            make_result(scan, apt_type), scan, apt_type=apt_type, lookahead_months=3
+        )
+        self.assertEqual(report["earliestDate"], "2026-10-12")
+        self.assertEqual(report["stopReason"], "first_available_month")
+        self.assertEqual(report["timesCount"], 0)
+        self.assertTrue(report["snapshotVerified"])
+        self.assertNotIn("runtime", json.dumps(report))
+
+    def test_rejects_wrong_earliest_extra_dates_or_times(self):
+        scan = make_scan()
+        apt_type = resolve_debug_route(gate_env()).appointment_type()
+        for field, value in (
+            ("earliest_date", datetime(2026, 10, 20)),
+            ("success", False),
+            ("availability", []),
+            ("availability", [DateAvailability(date=datetime(2026, 10, 12), times=[TimeSlot(time="10:05")])]),
+            ("availability", [DateAvailability(date=datetime(2026, 10, 20))]),
+        ):
+            with self.subTest(field=field, value=value):
+                result = make_result(scan, apt_type)
+                setattr(result, field, value)
+                with self.assertRaises(CalendarGateError):
+                    validate_production_query_result(
+                        result, scan, apt_type=apt_type, lookahead_months=3
+                    )
+
+    def test_rejects_extra_snapshot_fields(self):
+        scan = make_scan()
+        apt_type = resolve_debug_route(gate_env()).appointment_type()
+        result = make_result(scan, apt_type)
+        payload = result.to_snapshot_payload()
+        payload["daily_id"] = "must-not-leak"
+        with patch.object(VSQueryResult, "to_snapshot_payload", return_value=payload):
+            with self.assertRaisesRegex(CalendarGateError, "snapshot contract"):
+                validate_production_query_result(
+                    result, scan, apt_type=apt_type, lookahead_months=3
+                )
+
+    def test_accepts_explicit_complete_negative_evidence(self):
+        scan = make_scan(())
+        apt_type = resolve_debug_route(gate_env()).appointment_type()
+        report = validate_production_query_result(
+            make_result(scan, apt_type), scan, apt_type=apt_type, lookahead_months=3
+        )
+        self.assertFalse(report["success"])
+        self.assertEqual(report["stopReason"], "horizon_exhausted")
+        self.assertIsNone(report["earliestDate"])
+
+
+class RealProductionEntryOfflineTests(unittest.TestCase):
+    def _run(self, page):
+        plugin, route = make_plugin(page)
+        audit = CalendarRequestAudit(page)
+        audit.start()
+        page.emit(OTP_PATH + "?ServiceID=9001", "GET")
+        page.emit("/Services/Booking/9001")
+        try:
+            with patch("tools.debug_ita_calendar_gate.time.sleep"), patch.object(
+                CalendarRequestAudit, "settled_snapshot", autospec=True,
+                side_effect=lambda value: value.snapshot(),
+            ), redirect_stdout(StringIO()):
+                reports = run_production_query_acceptance(plugin, route, audit)
+            return plugin, reports, audit.snapshot()
+        finally:
+            audit.stop()
+            self.assertEqual(plugin.free_config["query_mode"], "services_probe")
+
+    def test_real_query_and_real_scanner_stop_at_first_positive_month_twice(self):
+        plan = [(2026, 8, ()), (2026, 9, ()), (2026, 10, (20, 12))]
+        page = FakeProductionPage([plan, plan])
+        plugin, reports, counts = self._run(page)
+        self.assertEqual(page.refresh_calls, 2)
+        self.assertEqual(page.forward_clicks, [(2026, 9), (2026, 10)] * 2)
+        self.assertEqual(page.listen.stops, 6)
+        self.assertEqual([report["earliestDate"] for report in reports], ["2026-10-12"] * 2)
+        self.assertTrue(all(report["queryRequestDelta"]["otpRequests"] == 0 for report in reports))
+        self.assertEqual(counts, {
+            "otpRequests": 1, "avantiPosts": 1, "availabilityRequests": 6, "finalRequests": 0
+        })
+        self.assertIs(plugin.page, page)
+
+    def test_allows_inventory_to_change_without_requiring_equal_dates(self):
+        first = [(2026, 8, ()), (2026, 9, ()), (2026, 10, (12,))]
+        second = [(2026, 8, ()), (2026, 9, ()), (2026, 10, (13,))]
+        _, reports, _ = self._run(FakeProductionPage([first, second]))
+        self.assertEqual([report["earliestDate"] for report in reports], ["2026-10-12", "2026-10-13"])
+
+    def test_second_query_must_restart_from_the_same_initial_month(self):
+        first = [(2026, 8, ()), (2026, 9, ()), (2026, 10, (12,))]
+        second = [(2026, 9, (1,))]
+        with self.assertRaisesRegex(CalendarGateError, "same initial month"):
+            self._run(FakeProductionPage([first, second]))
+
+    def test_rejects_repeated_otp_or_extra_availability_requests(self):
+        plan = [(2026, 8, (1,))]
+        for extra in (OTP_PATH, AVAILABILITY_PATH):
+            with self.subTest(extra=extra):
+                with self.assertRaisesRegex(CalendarGateError, "read-only request contract"):
+                    self._run(FakeProductionPage([plan], extra_request=extra))
+
+    def test_two_negative_queries_remain_negative_not_fake_positive(self):
+        plan = [(2026, 8, ()), (2026, 9, ()), (2026, 10, ())]
+        _, reports, _ = self._run(FakeProductionPage([plan, plan]))
+        self.assertEqual(len(reports), 2)
+        self.assertFalse(any(report["success"] for report in reports))
+
+
+class ProductionGateWorkflowTests(unittest.TestCase):
+    def _run_gate(self, positives=(True, True), *, reservation_changed=False, query_error=None):
+        env = {**gate_env(), "ITA_QCAL_FORWARD_MONTHS": "ignored-in-production-mode"}
+        page = FakeAuditPage()
+        page.set = SimpleNamespace(auto_handle_alert=Mock())
+        plugin, route = make_plugin(page)
+        plugin.create_session = Mock()
+        plugin.mouse = SimpleNamespace(human_click_ele=Mock())
+        plugin.query = Mock(return_value=VSQueryResult(success=True))
+
+        def set_config(config):
+            plugin.config = config
+            plugin.free_config = config.free_config
+
+        plugin.set_config = Mock(side_effect=set_config)
+
+        def listen(_page, *, target, method, action, timeout):
+            action()
+            page.emit(target, method)
+            if target == OTP_PATH:
+                return SimpleNamespace(
+                    url="https://prenotami.esteri.it" + OTP_PATH + "?ServiceID=9001",
+                    method="GET",
+                    response=SimpleNamespace(status=200, raw_body=json.dumps("SENT")),
+                )
+            return SimpleNamespace(
+                url="https://prenotami.esteri.it" + route.booking_path,
+                method="POST",
+                response=SimpleNamespace(
+                    status=302, headers={"Location": "/BookingCalendar"}
+                ),
+            )
+
+        def acceptance(_plugin, _route, _audit):
+            if query_error:
+                raise query_error
+            reports = []
+            for positive in positives:
+                page.emit(AVAILABILITY_PATH)
+                reports.append({
+                    "success": positive,
+                    "queryRequestDelta": {"availabilityRequests": 1},
+                })
+            return tuple(reports)
+
+        stdout = StringIO()
+        with ExitStack() as stack:
+            stack.enter_context(patch.dict("os.environ"))
+            patches = {
+                "resolve_chrome_path": {"return_value": Path("/offline/chrome")},
+                "_get_query_credentials": {"return_value": ("offline@example.test", "not-a-real-password")},
+                "_prepare_query_profile": {"return_value": None},
+                "ItaPlugin": {"return_value": plugin},
+                "read_reservation_snapshot": {"side_effect": [
+                    ReservationSnapshot(0, 0),
+                    ReservationSnapshot(1 if reservation_changed else 0, 0),
+                ]},
+                "wait_for_booking_preflight": {"return_value": {}},
+                "_element_or_fail": {"side_effect": lambda _page, selector: selector},
+                "_enter_otp": {},
+                "_wait_for_calendar": {},
+                "_calendar_guard": {"return_value": {"finalRequestCount": 0}},
+                "listen_once": {"side_effect": listen},
+                "run_production_query_acceptance": {"side_effect": acceptance},
+                "scan_calendar_horizon": {},
+            }
+            mocks = {
+                name: stack.enter_context(patch("tools.debug_ita_calendar_gate." + name, **kwargs))
+                for name, kwargs in patches.items()
+            }
+            stack.enter_context(patch.object(
+                CalendarRequestAudit, "settled_snapshot", autospec=True,
+                side_effect=lambda value: value.snapshot(),
+            ))
+            stack.enter_context(redirect_stdout(stdout))
+            otp_reader = Mock(return_value="123456")
+            exit_code = run_calendar_gate(env, otp_reader=otp_reader)
+        return exit_code, stdout.getvalue(), plugin, page, mocks, otp_reader
+
+    def test_prepares_once_runs_production_mode_and_always_cleans_up(self):
+        code, output, plugin, page, mocks, otp_reader = self._run_gate()
+        self.assertEqual(code, 0)
+        plugin.create_session.assert_called_once()
+        plugin.set_config.assert_called_once()
+        plugin.cleanup.assert_called_once()
+        otp_reader.assert_called_once()
+        mocks["_enter_otp"].assert_called_once()
+        mocks["run_production_query_acceptance"].assert_called_once()
+        mocks["scan_calendar_horizon"].assert_not_called()
+        self.assertEqual(plugin.mouse.human_click_ele.call_count, 2)
+        self.assertEqual(page.driver.immediate_event_handlers, {})
+        self.assertIn("ITA_QCAL_PRODUCTION_QUERY_GATE_RESULT=", output)
+        self.assertIn('"passed": true', output)
+        self.assertNotIn("123456", output)
+        self.assertNotIn("not-a-real-password", output)
+
+    def test_natural_negative_evidence_returns_two_not_a_fake_pass(self):
+        code, output, plugin, _, _, _ = self._run_gate((False, False))
+        self.assertEqual(code, 2)
+        self.assertIn('"passed": false', output)
+        self.assertIn("ITA_QCAL_PRODUCTION_QUERY_NOT_READY", output)
+        plugin.cleanup.assert_called_once()
+
+    def test_gate_requires_exactly_two_query_reports(self):
+        code, output, plugin, _, _, _ = self._run_gate((True, True, True))
+        self.assertEqual(code, 1)
+        self.assertIn('"passed": false', output)
+        self.assertIn("exactly two Query calls", output)
+        plugin.cleanup.assert_called_once()
+
+    def test_reservation_change_fails_the_gate(self):
+        code, output, plugin, _, _, _ = self._run_gate(reservation_changed=True)
+        self.assertEqual(code, 1)
+        self.assertIn('"passed": false', output)
+        plugin.cleanup.assert_called_once()
+
+    def test_query_failure_does_not_repeat_preparation(self):
+        code, output, plugin, page, mocks, otp_reader = self._run_gate(
+            query_error=CalendarGateError("offline query failure")
+        )
+        self.assertEqual(code, 1)
+        otp_reader.assert_called_once()
+        mocks["_enter_otp"].assert_called_once()
+        self.assertEqual(plugin.mouse.human_click_ele.call_count, 2)
+        plugin.cleanup.assert_called_once()
+        self.assertEqual(page.driver.immediate_event_handlers, {})
+        self.assertIn("offline query failure", output)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 524 - 0
test/test_debug_ita_query.py

@@ -0,0 +1,524 @@
+import ast
+import io
+import json
+import os
+import stat
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+
+from tools.debug_ita_query import (
+    _BOOKING_FORM_DISCOVERY_SCRIPT,
+    DEFAULT_ITA_ROUTING_KEY,
+    DEFAULT_ITA_SERVICE_ID,
+    _get_query_credentials,
+    _prepare_query_profile,
+    _sanitize_booking_form_structure,
+    build_query_config,
+    resolve_debug_route,
+    run_query_once,
+)
+from tools.debug_ita_session import DebugConfigurationError
+from utils.ita_local_profile import ItaLocalProfileError, prepare_ita_query_profile
+from vs_types import (
+    AvailabilityStatus,
+    BizLogicError,
+    VSQueryResult,
+)
+
+
+class FakeQueryDebugElement:
+    def __init__(self, text):
+        self.text = text
+
+
+class FakeQueryDebugPage:
+    def __init__(self):
+        self.url = (
+            "https://prenotami.esteri.it/Services"
+            "?state=sensitive-state#sensitive-fragment"
+        )
+        self.popup_text = ""
+        self.form_structure = None
+
+    def ele(self, selector, timeout=None):
+        del timeout
+        if selector == ".jconfirm-content" and self.popup_text:
+            return FakeQueryDebugElement(self.popup_text)
+        return None
+
+    def run_js(self, script):
+        self.last_script = script
+        return self.form_structure
+
+
+class FakeQueryDebugPlugin:
+    behavior = "none-available"
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = FakeQueryDebugPage()
+        self.create_session_calls = 0
+        self.query_calls = 0
+        self.cleanup_called = False
+        FakeQueryDebugPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        self.create_session_calls += 1
+
+    def query(self, apt_type):
+        self.query_calls += 1
+        if self.behavior == "weak-entry-signal":
+            self.page.form_structure = {
+                "path": "/Services/Booking/1321",
+                "form": {
+                    "method": "POST",
+                    "action_path": "/Services/Booking/1321",
+                    "forbidden": "must-not-appear",
+                },
+                "field_count": 1,
+                "fields_truncated": False,
+                "fields": [
+                    {
+                        "tag": "input",
+                        "type": "hidden",
+                        "id": "RequestToken",
+                        "name": "__RequestVerificationToken",
+                        "required": False,
+                        "value": "private@example.test",
+                    }
+                ],
+                "button_count": 1,
+                "buttons_truncated": False,
+                "buttons": [
+                    {
+                        "tag": "button",
+                        "type": "submit",
+                        "id": "btnAvanti",
+                        "name": None,
+                        "text": "Avanti",
+                        "value": "server-secret",
+                    }
+                ],
+                "unknown": "must-not-appear",
+            }
+            return VSQueryResult(
+                success=True,
+                apt_type=apt_type,
+                availability_status=AvailabilityStatus.NoneAvailable,
+            )
+        if self.behavior == "unexpected-error":
+            self.page.popup_text = (
+                "Messaggio per private@example.test, riferimento 12345678 "
+                "token abcdefghijklmnopqrstuvwxyz123456."
+            )
+            raise RuntimeError(
+                "failed at https://iam.esteri.it/signin/"
+                "?state=sensitive-state&code_challenge=sensitive-challenge"
+            )
+        if self.behavior == "unexpected-result":
+            return VSQueryResult(
+                success=True,
+                apt_type=apt_type,
+                availability_status=AvailabilityStatus.Available,
+            )
+        return VSQueryResult(
+            success=False,
+            apt_type=apt_type,
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+
+    def cleanup(self):
+        self.cleanup_called = True
+
+
+class DebugItaQueryConfigTests(unittest.TestCase):
+    def test_default_query_config_uses_the_safe_compatibility_route(self):
+        config = build_query_config(
+            {},
+            username="offline-test@example.test",
+            password="offline-password",
+        )
+
+        self.assertEqual(
+            config.free_config,
+            {
+                "query_mode": "services_probe",
+                "final_submit_enabled": False,
+                "apt_configs": {
+                    DEFAULT_ITA_ROUTING_KEY: {
+                        "service_id": DEFAULT_ITA_SERVICE_ID,
+                        "capability": "services_probe_only",
+                    }
+                },
+            },
+        )
+
+    def test_query_config_adds_only_an_explicit_persistent_profile(self):
+        profile_path = Path("/private/local/ita-query-profile")
+
+        config = build_query_config(
+            {},
+            username="offline-test@example.test",
+            password="offline-password",
+            persistent_profile_path=profile_path,
+        )
+
+        self.assertEqual(
+            config.free_config,
+            {
+                "query_mode": "services_probe",
+                "final_submit_enabled": False,
+                "apt_configs": {
+                    DEFAULT_ITA_ROUTING_KEY: {
+                        "service_id": DEFAULT_ITA_SERVICE_ID,
+                        "capability": "services_probe_only",
+                    }
+                },
+                "persistent_browser_profile_path": str(profile_path),
+            },
+        )
+
+    def test_prepared_profile_is_private_deterministic_and_hides_username(self):
+        username = "Private.Query.Account@example.test"
+        with tempfile.TemporaryDirectory() as temp_dir:
+            profile_root = Path(temp_dir) / "profiles"
+
+            first = prepare_ita_query_profile(
+                username,
+                profile_root=profile_root,
+            )
+            second = prepare_ita_query_profile(
+                username.lower(),
+                profile_root=profile_root,
+            )
+
+            self.assertEqual(first, second)
+            self.assertNotIn("private.query.account", str(first).lower())
+            if os.name == "posix":
+                self.assertEqual(
+                    stat.S_IMODE(profile_root.stat().st_mode),
+                    0o700,
+                )
+                self.assertEqual(stat.S_IMODE(first.stat().st_mode), 0o700)
+
+    def test_prepare_query_profile_wraps_errors_without_exposing_username(self):
+        private_username = "private-query@example.test"
+        with patch(
+            "tools.debug_ita_query.prepare_ita_query_profile",
+            side_effect=ItaLocalProfileError(private_username),
+        ):
+            with self.assertRaises(DebugConfigurationError) as raised:
+                _prepare_query_profile(private_username)
+
+        self.assertNotIn(private_username, str(raised.exception))
+
+    def test_accepts_an_explicit_non_default_route(self):
+        env = {
+            "ITA_ROUTING_KEY": "slot.sample.it.tourist",
+            "ITA_SERVICE_ID": "9999",
+            "ITA_CITY": "Sample City",
+            "ITA_VISA_TYPE": "Short-stay tourism",
+        }
+
+        route = resolve_debug_route(env)
+        config = build_query_config(
+            env,
+            username="offline-test@example.test",
+            password="offline-password",
+            route=route,
+        )
+
+        self.assertEqual(route.service_id, 9999)
+        self.assertEqual(route.city, "Sample City")
+        self.assertEqual(
+            config.free_config["apt_configs"],
+            {
+                route.routing_key: {
+                    "service_id": 9999,
+                    "capability": "services_probe_only",
+                }
+            },
+        )
+
+    def test_local_query_account_takes_priority_over_environment(self):
+        local_values = {
+            "username": "local-query@example.test",
+            "password": "local-password",
+            "account_upload_token": "",
+        }
+        repo_root = Path(__file__).resolve().parents[1]
+        with tempfile.TemporaryDirectory(dir=repo_root) as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text(json.dumps(local_values), encoding="utf-8")
+            config_path.chmod(0o600)
+
+            with patch(
+                "tools.debug_ita_query.LOCAL_QUERY_ACCOUNT_FILE",
+                config_path,
+            ):
+                credentials = _get_query_credentials(
+                    {
+                        "ITA_USERNAME": "environment@example.test",
+                        "ITA_PASSWORD": "environment-password",
+                    },
+                    non_interactive=True,
+                )
+
+        self.assertEqual(
+            credentials,
+            (local_values["username"], local_values["password"]),
+        )
+
+    def test_invalid_existing_local_file_fails_without_environment_fallback(self):
+        local_values = {
+            "username": "private-local@example.test",
+            "password": "",
+            "account_upload_token": "",
+        }
+        repo_root = Path(__file__).resolve().parents[1]
+        with tempfile.TemporaryDirectory(dir=repo_root) as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text(json.dumps(local_values), encoding="utf-8")
+            config_path.chmod(0o600)
+
+            with (
+                patch(
+                    "tools.debug_ita_query.LOCAL_QUERY_ACCOUNT_FILE",
+                    config_path,
+                ),
+                self.assertRaises(DebugConfigurationError) as raised,
+            ):
+                _get_query_credentials(
+                    {
+                        "ITA_USERNAME": "fallback@example.test",
+                        "ITA_PASSWORD": "fallback-password",
+                    },
+                    non_interactive=True,
+                )
+
+        self.assertIn("password is required", str(raised.exception))
+        self.assertNotIn("private-local", str(raised.exception))
+        self.assertNotIn("fallback-password", str(raised.exception))
+
+    def test_missing_local_file_preserves_original_environment_fallback(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            missing_path = Path(temp_dir) / "missing.json"
+            with patch(
+                "tools.debug_ita_query.LOCAL_QUERY_ACCOUNT_FILE",
+                missing_path,
+            ):
+                credentials = _get_query_credentials(
+                    {
+                        "ITA_USERNAME": "fallback@example.test",
+                        "ITA_PASSWORD": "fallback-password",
+                    },
+                    non_interactive=True,
+                )
+
+        self.assertEqual(
+            credentials,
+            ("fallback@example.test", "fallback-password"),
+        )
+
+
+class DebugItaQuerySafetyTests(unittest.TestCase):
+    def setUp(self):
+        FakeQueryDebugPlugin.behavior = "none-available"
+        FakeQueryDebugPlugin.last_instance = None
+
+    @staticmethod
+    def _run():
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        env = {
+            "ITA_USERNAME": "offline-test@example.test",
+            "ITA_PASSWORD": "offline-password",
+        }
+        with (
+            patch(
+                "tools.debug_ita_query.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch("tools.debug_ita_query.ItaPlugin", FakeQueryDebugPlugin),
+            patch(
+                "tools.debug_ita_query.LOCAL_QUERY_ACCOUNT_FILE",
+                Path("/definitely-missing/ita_query_account.local.json"),
+            ),
+            patch(
+                "tools.debug_ita_query._prepare_query_profile",
+                return_value=Path("/offline/ita-query-profile"),
+            ),
+            patch.dict("tools.debug_ita_query.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_query_once(env, non_interactive=True)
+        return exit_code, stdout.getvalue(), stderr.getvalue()
+
+    def test_no_slot_result_is_reported_after_exactly_one_query(self):
+        exit_code, stdout, stderr = self._run()
+        plugin = FakeQueryDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(plugin.create_session_calls, 1)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn("query_attempt=1", stdout)
+        self.assertIn(
+            "ITA_QUERY_NONE_AVAILABLE service_id=1321 "
+            "routing_key=slot.dub.it.tourist status=NoAvailable",
+            stdout,
+        )
+        self.assertNotIn("ITA_QUERY_MESSAGE_ZH", stdout)
+        self.assertIn("ITA_QUERY_CLEANUP_OK", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_weak_entry_signal_is_reported_safely_without_retry(self):
+        FakeQueryDebugPlugin.behavior = "weak-entry-signal"
+
+        exit_code, stdout, stderr = self._run()
+        plugin = FakeQueryDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn(
+            "ITA_QUERY_WEAK_SIGNAL service_id=1321 "
+            "routing_key=slot.dub.it.tourist "
+            "status=NoAvailable evidence=booking-form",
+            stdout,
+        )
+        self.assertIn("ITA_BOOKING_FORM_STRUCTURE=", stdout)
+        self.assertIn('"action_path": "/Services/Booking/1321"', stdout)
+        self.assertIn('"name": "__RequestVerificationToken"', stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("server-secret", stdout)
+        self.assertNotIn("must-not-appear", stdout)
+        self.assertNotIn("ITA_QUERY_FAILED", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_unexpected_available_result_also_stops_safely(self):
+        FakeQueryDebugPlugin.behavior = "unexpected-result"
+
+        exit_code, stdout, _stderr = self._run()
+        plugin = FakeQueryDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn("reason=non-empty-availability-result", stdout)
+
+    def test_unexpected_error_is_sanitized_and_not_retried(self):
+        FakeQueryDebugPlugin.behavior = "unexpected-error"
+
+        exit_code, stdout, stderr = self._run()
+        plugin = FakeQueryDebugPlugin.last_instance
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(plugin.query_calls, 1)
+        self.assertTrue(plugin.cleanup_called)
+        self.assertIn("ITA_QUERY_FAILED type=RuntimeError", stdout)
+        self.assertIn(
+            "diagnostic_url=https://prenotami.esteri.it/Services",
+            stdout,
+        )
+        self.assertNotIn("sensitive-state", stdout)
+        self.assertNotIn("sensitive-challenge", stdout)
+        self.assertNotIn("sensitive-fragment", stdout)
+        self.assertIn("diagnostic_popup_text=Messaggio per <redacted-email>", stdout)
+        self.assertNotIn("private@example.test", stdout)
+        self.assertNotIn("12345678", stdout)
+        self.assertNotIn("abcdefghijklmnopqrstuvwxyz123456", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_entrypoint_has_one_query_call_and_no_book_call(self):
+        source_path = (
+            Path(__file__).resolve().parents[1] / "tools" / "debug_ita_query.py"
+        )
+        tree = ast.parse(source_path.read_text(encoding="utf-8"))
+        query_calls = []
+        book_calls = []
+        for node in ast.walk(tree):
+            if not isinstance(node, ast.Call):
+                continue
+            if not isinstance(node.func, ast.Attribute):
+                continue
+            if node.func.attr == "query":
+                query_calls.append(node)
+            if node.func.attr == "book":
+                book_calls.append(node)
+
+        self.assertEqual(len(query_calls), 1)
+        self.assertEqual(book_calls, [])
+
+    def test_book_debugger_never_uses_the_query_browser_profile(self):
+        source_path = (
+            Path(__file__).resolve().parents[1] / "tools" / "debug_ita_book.py"
+        )
+        source = source_path.read_text(encoding="utf-8")
+
+        self.assertNotIn("prepare_ita_query_profile", source)
+        self.assertNotIn("persistent_browser_profile_path", source)
+
+    def test_booking_form_discovery_script_never_reads_values_or_submits(self):
+        forbidden_fragments = (
+            ".value",
+            "getAttribute('value')",
+            'getAttribute("value")',
+            "outerHTML",
+            "innerHTML",
+            "document.cookie",
+            "localStorage",
+            "sessionStorage",
+            ".click(",
+            ".submit(",
+        )
+
+        for fragment in forbidden_fragments:
+            with self.subTest(fragment=fragment):
+                self.assertNotIn(fragment, _BOOKING_FORM_DISCOVERY_SCRIPT)
+
+    def test_booking_form_structure_uses_an_explicit_allowlist(self):
+        sanitized = _sanitize_booking_form_structure(
+            {
+                "path": "/Services/Booking/1321",
+                "form": {
+                    "method": "POST",
+                    "action_path": "/Services/Booking/1321",
+                    "csrf": "server-secret",
+                },
+                "fields": [
+                    {
+                        "tag": "input",
+                        "type": "text",
+                        "id": "Email",
+                        "name": "Email",
+                        "required": True,
+                        "value": "private@example.test",
+                    }
+                ],
+                "buttons": [],
+                "raw_html": "must-not-appear",
+            }
+        )
+
+        serialized = str(sanitized)
+        self.assertIn("/Services/Booking/1321", serialized)
+        self.assertNotIn("private@example.test", serialized)
+        self.assertNotIn("server-secret", serialized)
+        self.assertNotIn("must-not-appear", serialized)
+        self.assertNotIn("value", sanitized["fields"][0])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 1006 - 0
test/test_debug_ita_query_book.py

@@ -0,0 +1,1006 @@
+"""Real framework creation/publication/dispatch/execution, synthetic I/O only.
+
+No test-owned signal schema, expiry rule, account dispatcher or retry policy.
+The already-existing Redis fixture simulates a retained server key. Snapshot
+encoding/decoding, account binding, route/date/cooldown decisions and public
+Italy Query/Book remain the real implementations.
+"""
+import contextlib
+import copy
+from datetime import date
+import io
+import itertools
+import json
+import tempfile
+from pathlib import Path
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from tools import debug_ita_query_book as cli
+from test.test_ita_plugin import OrderBookerGCO, FakeRetainedSignalRedis
+from sentinel import SentinelGCO
+from test import test_ita_calendar_book_flow as book_flow
+from test.test_ita_query_recovery import RecoveryPage, prepared_plugin
+from vs_types import AvailabilityStatus, GroupConfig, QueryWaitMode
+
+
+class ExistingFrameworkJointTests(unittest.TestCase):
+    def setUp(self):
+        # Fail closed if a future test accidentally stops isolating I/O.
+        for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
+                       "requests.sessions.Session.request", "subprocess.Popen"):
+            self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
+        self.clock = {"now": 1000.0}
+        self.retained = None
+        self.query_page = RecoveryPage()
+        self.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [13, 20])]] * 10
+        self.query, self.route = prepared_plugin(self.query_page)
+        self.apt = self.route.appointment_type()
+        self.apt.weight = 1
+        self.query._transient_user_data_path = "/nonexistent/ita-framework-query"
+        self.query.free_config.update(otp_mode="manual", final_submit_enabled=False)
+        self.query.query = Mock(wraps=self.query.query)
+        # Existing fixture is already on Calendar; restore its prepared marker
+        # after the framework's real set_config clears per-session state.
+        self.query.create_session = Mock(side_effect=lambda:
+            self.query._record_calendar_query_prepared_route(self.query._resolve_route(self.apt)))
+        self.query.cleanup = Mock()
+        self.query._cleanup_attempted = True
+
+        self.inputs = {"username": "applicant@example.test", "password": "synthetic-applicant-password",
+                       "expected_start_date": "2026-08-01", "expected_end_date": "2026-10-31"}
+        self.order = {"id": 991, "order_id": "SYNTHETIC-ORDER", "status": "processing",
+                      "user_inputs": copy.deepcopy(self.inputs)}
+        self.cloud = Mock()
+        self.cloud.get_next_account.return_value = {
+            "id": 21, "username": "pool-query@example.test", "password": "synthetic-pool-password"}
+        self.cloud.get_vas_task_pop.return_value = self.order
+        self.redis = Mock()
+        self.redis.setex.side_effect = self.capture_redis_write
+        self.redis.get.side_effect = lambda key: (
+            self.retained.get(key) if self.retained is not None and key == self.signal_key else None)
+        self.redis.delete.side_effect = self.delete_redis_key
+        self.signal_key = "vs:signal:" + self.apt.routing_key
+        self.executor = Mock()
+        self.log = Mock()
+
+        # Existing test pattern: isolate only method dependencies, not methods.
+        # Use each loaded class's globals to avoid import-cache/stub ambiguity.
+        dependencies = {
+            "SafeRedisClient": Mock(return_value=self.redis),
+            "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud, lock_account=Mock()),
+            "time": SimpleNamespace(time=lambda: self.clock["now"], sleep=lambda _seconds: None),
+        }
+        for cls in (SentinelGCO, OrderBookerGCO):
+            self.enterContext(patch.dict(cls.__init__.__globals__, dependencies))
+        self.enterContext(patch.dict(OrderBookerGCO._execute_book_job.__globals__,
+                                    ThreadPool=SimpleNamespace(getInstance=lambda: self.executor)))
+        self.final = self.enterContext(patch("plugins.ita_workflow.submit_final",
+                                            side_effect=AssertionError("Final submission forbidden")))
+        # Query month navigation uses only the synthetic page above.
+        self.enterContext(patch("plugins.ita_calendar_query.time.sleep"))
+
+        self.query_config = GroupConfig(
+            identifier="offline-query", need_account=True, appointment_types=[self.apt],
+            plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.query.free_config),
+            sentinel={"account_pool_id": "fixture.query.pool", "account_cd": 10800,
+                      "signal_ttl": 30, "query_wait": {"mode": QueryWaitMode.Fixed, "fixed_wait": 1}})
+        self.book_plugin, self.book_page = self.new_book_plugin()
+        self.book_config = GroupConfig(
+            identifier="offline-book", need_account=True, appointment_types=[self.apt],
+            plugin_config={"plugin_name": "ita_plugin"}, free_config=copy.deepcopy(self.book_plugin.free_config),
+            booker={"account_source": "order", "target_instances": 1, "booking_cooldown": 45})
+        self.sentinel = SentinelGCO(self.query_config, {}, self.log)
+        self.booker = OrderBookerGCO(self.book_config, {}, self.log)
+        self.sentinel.m_factory.create = Mock(return_value=self.query)
+        self.booker.m_factory.create = Mock(return_value=self.book_plugin)
+        self.booker._execute_book_job = Mock(wraps=self.booker._execute_book_job)
+        # Real GCO stop/cleanup is exercised; browser cleanup remains a fixture.
+        self.addCleanup(self.sentinel.stop)
+        self.addCleanup(self.booker.stop)
+
+    def new_book_plugin(self):
+        page = book_flow.FlowPage([book_flow.month("2026-10", {13: 0, 14: 1})])
+        plugin, _, _ = book_flow.prepared_plugin(page, routing_key=self.apt.routing_key)
+        plugin.free_config.update(otp_mode="cloud", final_submit_enabled=False)
+        plugin.is_healthy = True
+        plugin._cleanup_attempted = True
+        plugin.cleanup = Mock()
+        # Login/OTP are already independently tested; this fixture starts at
+        # the prepared Calendar but binds it AFTER real order account wiring.
+        plugin.create_session = Mock(side_effect=lambda:
+            plugin._record_calendar_book_prepared_route(plugin._resolve_route(self.apt)))
+        plugin.book = Mock(wraps=plugin.book)
+        return plugin, page
+
+    def capture_redis_write(self, key, ttl, payload):
+        self.assertEqual(key, self.signal_key)
+        # Reuse existing retained-key fixture, not a new signal/TTL algorithm.
+        self.retained = FakeRetainedSignalRedis(json.loads(payload), self.clock,
+                                               ttl=self.clock["now"] + ttl)
+        return True
+
+    def delete_redis_key(self, key):
+        if key == self.signal_key:
+            self.retained = None
+        return 1
+
+    def spawn(self):
+        self.sentinel._spawn_sentinel_worker()
+        self.booker._spawn_worker(self.apt.routing_key)
+
+    def publish_once(self, *, positive=True):
+        # Bound the EXISTING loop to one cycle; do not reimplement its body.
+        with patch.object(self.sentinel.m_stop_event, "is_set", side_effect=[False, True]):
+            self.sentinel._monitor_loop()
+        if positive:
+            self.assertIsNotNone(self.retained, self.log.call_args_list)
+            self.assertIsNotNone(self.query.last_calendar_query_scan.earliest_available_date)
+
+    def trigger_once(self, page=None):
+        with book_flow.browser_navigation(page or self.book_page), \
+                patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
+            # Existing Thread creation and joins run as-is inside this loop.
+            self.booker._booking_trigger_loop()
+
+    def assert_no_final_or_success_report(self):
+        self.final.assert_not_called()
+        self.executor.enqueue.assert_not_called()
+        self.cloud.update_vas_task.assert_not_called()
+        self.cloud.push_weixin_text.assert_not_called()
+
+    def test_real_framework_pool_query_json_order_book_rechecks_current_inventory(self):
+        self.spawn()
+        self.assertEqual(len(self.sentinel.m_tasks), 1)
+        self.assertEqual(len(self.booker.m_tasks), 1)
+        self.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
+        self.cloud.get_vas_task_pop.assert_called_once_with("auto." + self.apt.routing_key)
+        self.assertEqual(self.query.config.account.username, "pool-query@example.test")
+        self.assertEqual(self.query.config.account.id, 21)
+        self.assertEqual(self.book_plugin.config.account.username, self.inputs["username"])
+        self.assertEqual(self.book_plugin.config.account.password, self.inputs["password"])
+        self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
+        self.assertEqual(self.booker.m_tasks[0].task_ref, 991)
+        self.assertEqual(self.booker.m_tasks[0].acceptable_routing_keys, [self.apt.routing_key])
+        self.assertIsNot(self.query.page, self.book_plugin.page)
+
+        self.publish_once()
+        self.query.query.assert_called_once_with(self.apt)
+        self.redis.setex.assert_called_once()
+        key, ttl, raw = self.redis.setex.call_args.args
+        self.assertEqual((key, ttl), (self.signal_key, 30))
+        payload = json.loads(raw)
+        self.assertEqual(set(payload), {"group_id", "apt_type", "query_result", "timestamp"})
+        self.assertEqual(payload["group_id"], self.query_config.identifier)
+        self.assertEqual(payload["apt_type"], self.apt.model_dump())
+        self.assertEqual(payload["query_result"]["earliest_date"], "2026-10-13")
+        self.assertEqual(payload["query_result"]["availability_status"], "Available")
+        self.assertNotIn("success", payload["query_result"])
+        self.assertNotIn("password", raw)
+        self.assertNotIn("pool-query", raw)
+        self.assertEqual(self.query_page.forward_clicks, [(2026, 9), (2026, 10)])
+
+        self.trigger_once()
+        self.booker._execute_book_job.assert_called_once()
+        self.book_plugin.book.assert_called_once()
+        trigger, inputs = self.book_plugin.book.call_args.args
+        self.assertEqual(trigger.apt_type, self.apt)
+        self.assertIs(trigger.availability_status, AvailabilityStatus.Available)
+        self.assertFalse(trigger.success)  # Actual framework decode default.
+        self.assertEqual(trigger.earliest_date.date(), date(2026, 10, 13))
+        self.assertEqual(inputs, self.inputs)
+        self.assertEqual(self.book_plugin.last_booking_precommit.candidate.day, date(2026, 10, 14))
+        self.assertEqual(self.book_page.refreshes, 2)  # Existing stale-hint fallback.
+        self.assertGreater(len(self.book_page.requests), 0)
+        self.assert_no_final_or_success_report()
+        self.sentinel.stop()
+        self.booker.stop()
+        self.query.cleanup.assert_called_once()
+        self.book_plugin.cleanup.assert_called_once()
+
+    def test_no_account_or_login_failure_does_not_create_query_task(self):
+        self.cloud.get_next_account.side_effect = RuntimeError("synthetic pool failure")
+        self.sentinel._spawn_sentinel_worker()
+        self.assertEqual(self.sentinel.m_tasks, [])
+        self.sentinel.m_factory.create.assert_not_called()
+        self.cloud.get_next_account.reset_mock(side_effect=True)
+        self.query.create_session.side_effect = RuntimeError("synthetic login failure")
+        self.sentinel._spawn_sentinel_worker()
+        self.assertEqual(self.sentinel.m_tasks, [])
+        self.query.cleanup.assert_called_once()
+        self.assertGreater(self.sentinel.m_spawn_cooldown_until, self.clock["now"])
+
+    def test_no_order_does_not_take_pool_account_for_book(self):
+        self.cloud.get_vas_task_pop.return_value = None
+        self.booker._spawn_worker(self.apt.routing_key)
+        self.assertEqual(self.booker.m_tasks, [])
+        self.booker.m_factory.create.assert_not_called()
+        self.cloud.get_next_account.assert_not_called()
+
+    def test_order_login_failure_uses_existing_cleanup_without_query_account_fallback(self):
+        self.book_plugin.create_session.side_effect = RuntimeError("synthetic login failure")
+        self.booker._spawn_worker(self.apt.routing_key)
+        self.assertEqual(self.booker.m_tasks, [])
+        self.assertEqual(self.booker.m_task_data_cache, {})
+        self.book_plugin.cleanup.assert_called_once()
+        self.cloud.get_next_account.assert_not_called()
+
+    def test_no_availability_does_not_publish_or_trigger_book(self):
+        self.query_page.outcomes = ["none"]
+        self.spawn()
+        self.publish_once(positive=False)
+        self.trigger_once()
+        self.redis.setex.assert_not_called()
+        self.book_plugin.book.assert_not_called()
+        self.cloud.slot_refresh_success.assert_called_once()
+        self.assert_no_final_or_success_report()
+
+    def test_bad_query_protocol_does_not_publish_a_positive_signal(self):
+        self.query_page.outcomes = ["malformed"]
+        self.spawn()
+        self.publish_once(positive=False)
+        self.trigger_once()
+        self.redis.setex.assert_not_called()
+        self.cloud.slot_refresh_fail.assert_called_once()
+        self.book_plugin.book.assert_not_called()
+
+    def test_server_expired_signal_does_not_trigger_book(self):
+        self.spawn()
+        self.publish_once()
+        self.clock["now"] += self.query_config.sentinel.signal_ttl + 1
+        self.trigger_once()
+        self.book_plugin.book.assert_not_called()
+
+    def test_same_signal_obeys_existing_task_cooldown_not_new_one_shot_rule(self):
+        self.query_config.sentinel.signal_ttl = 180
+        self.spawn()
+        self.publish_once()
+        self.trigger_once()
+        self.clock["now"] += 1
+        self.trigger_once()
+        self.book_plugin.book.assert_called_once()
+        self.clock["now"] += self.book_config.booker.booking_cooldown
+        self.trigger_once()
+        self.assertEqual(self.book_plugin.book.call_count, 2)
+        self.assert_no_final_or_success_report()
+
+    def test_unmatched_routing_key_is_filtered_by_real_trigger_loop(self):
+        self.spawn()
+        self.publish_once()
+        self.booker.m_tasks[0].acceptable_routing_keys = ["slot.other.it.tourist"]
+        self.trigger_once()
+        self.book_plugin.book.assert_not_called()
+
+    def test_date_outside_order_end_is_filtered_before_book(self):
+        self.order["user_inputs"]["expected_end_date"] = "2026-10-12"
+        self.spawn()
+        self.publish_once()
+        self.trigger_once()
+        self.book_plugin.book.assert_not_called()
+
+    def test_order_start_bound_reaches_real_book_selection(self):
+        self.order["user_inputs"]["expected_start_date"] = "2026-10-15"
+        self.spawn()
+        self.publish_once()
+        self.trigger_once()
+        self.book_plugin.book.assert_called_once()
+        self.assertIsNone(self.book_plugin.last_booking_precommit)
+        self.assert_no_final_or_success_report()
+
+    def test_paused_order_is_removed_without_book(self):
+        self.spawn()
+        self.publish_once()
+        self.order["status"] = "pause"
+        self.trigger_once()
+        self.book_plugin.book.assert_not_called()
+        self.assertEqual(self.booker.m_tasks, [])
+        self.book_plugin.cleanup.assert_called_once()
+
+    def test_corrupt_redis_payload_uses_existing_delete_branch(self):
+        self.spawn()
+        self.publish_once()
+        self.retained.payload = "invalid-json"
+        self.trigger_once()
+        self.redis.delete.assert_called_once_with(self.signal_key)
+        self.book_plugin.book.assert_not_called()
+
+    def test_one_shared_signal_can_trigger_two_separately_bound_orders(self):
+        self.spawn()
+        other, other_page = self.new_book_plugin()
+        other_order = copy.deepcopy(self.order)
+        other_order.update(id=992, order_id="SYNTHETIC-OTHER")
+        other_order["user_inputs"]["username"] = "second-applicant@example.test"
+        self.cloud.get_vas_task_pop.return_value = other_order
+        self.booker.m_factory.create.return_value = other
+        self.booker._spawn_worker(self.apt.routing_key)
+        self.publish_once()
+        # Both fixtures start directly in the positive month; no month-click
+        # adapter is needed for this two-thread test, only no-delay sleeps.
+        with patch.object(self.booker.m_stop_event, "is_set", side_effect=[False, True]):
+            self.booker._booking_trigger_loop()
+        self.book_plugin.book.assert_called_once()
+        other.book.assert_called_once()
+        self.assertEqual(other.config.account.username, "second-applicant@example.test")
+        self.assertIsNot(self.book_page, other_page)
+        self.assertEqual(other.last_booking_precommit.candidate.day, date(2026, 10, 14))
+        self.assertEqual(self.booker._execute_book_job.call_count, 2)
+        self.cloud.get_next_account.assert_called_once()
+        self.assert_no_final_or_success_report()
+
+    def test_later_negative_query_keeps_existing_signal_until_redis_expiry(self):
+        self.spawn()
+        self.publish_once()
+        original = self.retained.payload
+        self.query_page.outcomes = ["none"]
+        self.clock["now"] += 2
+        self.publish_once(positive=False)
+        self.assertEqual(self.query.query.call_count, 2)
+        self.redis.setex.assert_called_once()
+        self.redis.delete.assert_not_called()
+        self.assertEqual(self.retained.payload, original)
+
+
+class OfflineCliTests(unittest.TestCase):
+    def test_old_live_flag_is_rejected_before_loading_tests(self):
+        with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
+                contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught:
+            cli.main(["--run"])
+        self.assertEqual(caught.exception.code, 2)
+        load.assert_not_called()
+
+    def test_cli_runs_only_existing_framework_suite_and_reports_offline(self):
+        result = SimpleNamespace(testsRun=26, failures=[], errors=[], skipped=[], wasSuccessful=lambda: True)
+        with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames") as load, \
+                patch.object(cli.unittest, "TextTestRunner") as runner, \
+                contextlib.redirect_stdout(io.StringIO()) as output:
+            runner.return_value.run.return_value = result
+            self.assertEqual(cli.main([]), 0)
+        load.assert_called_once_with(cli.TEST_NAMES)
+        summary = json.loads(output.getvalue().split("ITA_QUERY_BOOK_FRAMEWORK_RESULT=")[1])
+        self.assertTrue(summary["passed"])
+        self.assertFalse(summary["liveAcceptance"])
+        self.assertEqual(summary["externalBoundaries"], "simulated")
+
+    def test_empty_skipped_or_failed_suite_does_not_pass(self):
+        for count, skipped, successful in ((0, [], True), (1, ["fixture"], True), (1, [], False)):
+            result = SimpleNamespace(testsRun=count, failures=[], errors=[], skipped=skipped,
+                                     wasSuccessful=lambda: successful)
+            with patch.object(cli.unittest.defaultTestLoader, "loadTestsFromNames"), \
+                    patch.object(cli.unittest, "TextTestRunner") as runner, \
+                    contextlib.redirect_stdout(io.StringIO()):
+                runner.return_value.run.return_value = result
+                self.assertEqual(cli.main(["--offline"]), 1)
+
+
+class LocalHarnessTests(unittest.TestCase):
+    """Same real GCO fixtures; site/pool/Redis are synthetic in offline runs."""
+
+    def setUp(self):
+        from tools import ita_query_book_local as local
+        self.local = local
+        self.fixture = ExistingFrameworkJointTests()
+        self.fixture.setUp()
+        self.addCleanup(self.fixture.doCleanups)
+        self.enterContext(contextlib.redirect_stdout(io.StringIO()))
+        self.enterContext(patch.object(local, "validate_cloud_otp_environment"))
+        f = self.fixture
+        f.cloud.get_next_account.return_value.update(pool_name="fixture.query.pool", status="active")
+        self.applicant = local.VSAccount(username=f.inputs["username"], password=f.inputs["password"])
+        self.cloud = local.LocalCloudBoundary(f.cloud, f.query_config,
+            SimpleNamespace(routing_key=f.route.routing_key, mail=None),
+            SimpleNamespace(model_dump=lambda: {}), self.applicant,
+            {key: f.inputs[key] for key in ("expected_start_date", "expected_end_date")})
+        self.enterContext(patch.object(local, "CalendarRequestAudit", return_value=Mock(**{
+            "settled_snapshot.return_value": {"otpRequests": 0, "avantiPosts": 0,
+                "availabilityRequests": 1, "timeSlotRequests": 1, "finalRequests": 0}})))
+        self.enterContext(patch.object(local.SentinelGCO, "_is_within_active_hours", return_value=True))
+        self.enterContext(patch.object(local.OrderBookerGCO, "_is_within_active_hours", return_value=True))
+        # Factories still belong to the GCO. Substitute only browser creation.
+        real_observe = local.observe_factory
+
+        def synthetic_factory(gco, role, stack, observed):
+            gco.m_factory.create = Mock(return_value=f.query if role == "query" else f.book_plugin)
+            return real_observe(gco, role, stack, observed)
+
+        self.enterContext(patch.object(local, "observe_factory", side_effect=synthetic_factory))
+        self.enterContext(book_flow.browser_navigation(f.book_page))
+
+    def run_case(self):
+        return self.local.run_framework_once(self.fixture.query_config, self.fixture.book_config,
+                                             self.fixture.route, self.cloud, {})
+
+    def test_one_real_framework_iteration_preserves_pool_order_signal_and_selection(self):
+        report = self.run_case()
+        self.assertTrue(report["passed"], report)
+        self.assertEqual(report["outcome"], "pre_final")
+        self.assertEqual((report["queryCalls"], report["bookCalls"]), (1, 1))
+        self.assertTrue(report["signalPublished"])
+        self.assertTrue(report["signalReadByBooker"])
+        self.assertTrue(report["selectionVerified"])
+        self.assertTrue(report["cleanupVerified"])
+        self.assertFalse(report["cloudOrders"])
+        self.fixture.cloud.get_next_account.assert_called_once_with("fixture.query.pool", 10800)
+        self.fixture.cloud.get_vas_task_pop.assert_not_called()
+        self.fixture.cloud.update_vas_task.assert_not_called()
+        self.fixture.cloud.slot_snapshot_report.assert_not_called()
+        self.assertNotEqual(self.fixture.query.config.account.username, self.fixture.book_plugin.config.account.username)
+        self.assertEqual(self.fixture.book_plugin.config.account.username, self.applicant.username)
+        self.assertEqual(self.fixture.book_plugin.book.call_args.args[1], self.cloud.order["user_inputs"])
+
+    def test_no_availability_does_not_call_book(self):
+        self.fixture.query_page.plans = [[(2026, 8, []), (2026, 9, []), (2026, 10, [])]] * 2
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["outcome"], "no_availability")
+        self.assertEqual(report["bookCalls"], 0)
+        self.assertFalse(report["signalPublished"])
+        self.assertTrue(report["cleanupVerified"])
+
+    def test_failed_redis_write_is_not_a_successful_handoff(self):
+        self.fixture.redis.setex.side_effect = lambda *_: False
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["reason"], "redis_publication_failed")
+        self.assertEqual(report["bookCalls"], 0)
+
+    def test_expired_signal_does_not_trigger_or_get_republished(self):
+        self.fixture.redis.get.side_effect = lambda *_: None
+        report = self.run_case()
+        self.assertTrue(report["signalPublished"])
+        self.assertFalse(report["signalReadByBooker"])
+        self.assertEqual(report["bookCalls"], 0)
+        self.assertEqual(report["outcome"], "not_triggered_expired_or_date_filtered")
+        self.fixture.redis.setex.assert_called_once()
+
+    def test_order_date_range_filters_real_trigger_without_calling_book(self):
+        self.cloud.order["user_inputs"]["expected_end_date"] = "2026-09-30"
+        report = self.run_case()
+        self.assertEqual(report["bookCalls"], 0)
+        self.assertTrue(report["signalReadByBooker"])
+        self.assertFalse(report["passed"])
+
+    def test_pool_failure_is_redacted_and_does_not_retry(self):
+        self.fixture.cloud.get_next_account.side_effect = RuntimeError("secret-password-and-body")
+        report = self.run_case()
+        self.assertEqual(report["reason"], "pool_allocation_failed")
+        self.assertEqual(self.cloud.pool_calls, 1)
+        self.assertNotIn("secret-password", json.dumps(report))
+        self.assertTrue(report["cleanupVerified"])
+
+    def test_same_account_cannot_masquerade_as_dual_account_acceptance(self):
+        self.fixture.cloud.get_next_account.return_value["username"] = self.applicant.username
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["reason"], "query_and_book_accounts_same_choose_other_applicant")
+        self.assertEqual(report["queryCalls"], 0)
+
+    def test_cloud_order_and_reporting_methods_are_not_forwarded(self):
+        for name in ("update_vas_task", "push_weixin_text", "get_vas_task", "return_vas_task_to_queue"):
+            with self.assertRaises(self.local.LocalAcceptanceError):
+                getattr(self.cloud, name)
+            getattr(self.fixture.cloud, name).assert_not_called()
+
+    def test_unexpected_final_request_fails_even_after_selection(self):
+        self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["finalRequests"] = 1
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["reason"], "unexpected_final_request_do_not_rerun")
+
+    def test_book_exception_does_not_escape_as_success_or_leak_body(self):
+        self.fixture.book_plugin.book.side_effect = RuntimeError("secret-otp-body")
+        report = self.run_case()
+        self.assertEqual(report["reason"], "book_failed")
+        self.assertEqual(report["bookErrorType"], "RuntimeError")
+        self.assertNotIn("secret-otp", json.dumps(report))
+        self.assertTrue(report["cleanupVerified"])
+
+    def test_final_success_cannot_be_reported_by_prefinal_test(self):
+        from vs_types import VSBookResult
+        self.fixture.book_plugin.book.side_effect = None
+        self.fixture.book_plugin.book.return_value = VSBookResult(success=True)
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["reason"], "unexpected_book_success_before_final")
+        self.fixture.cloud.update_vas_task.assert_not_called()
+        self.assertGreater(self.cloud.forbidden_calls, 0)
+
+    def test_book_login_failure_does_not_allocate_pool_account(self):
+        self.fixture.book_plugin.create_session.side_effect = RuntimeError("secret-provider-response")
+        report = self.run_case()
+        self.assertEqual(report["reason"], "applicant_session_not_created")
+        self.fixture.cloud.get_next_account.assert_not_called()
+        self.assertTrue(report["cleanupVerified"])
+
+    def test_interrupt_during_query_cleans_both_sessions_without_book(self):
+        self.fixture.query.query.side_effect = KeyboardInterrupt()
+        report = self.run_case()
+        self.assertEqual(report["outcome"], "interrupted")
+        self.assertTrue(report["cleanupVerified"])
+        self.assertEqual(report["bookCalls"], 0)
+
+    def test_cleanup_failure_invalidates_otherwise_successful_selection(self):
+        self.fixture.book_plugin.cleanup.side_effect = RuntimeError("synthetic-cleanup-failure")
+        report = self.run_case()
+        self.assertTrue(report["selectionVerified"])
+        self.assertFalse(report["passed"])
+        self.assertFalse(report["cleanupVerified"])
+
+    def test_repeated_otp_is_not_accepted_as_single_round(self):
+        self.local.CalendarRequestAudit.return_value.settled_snapshot.return_value["otpRequests"] = 2
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["reason"], "unexpected_repeated_preparation")
+
+
+class LocalFinalTests(unittest.TestCase):
+    """Native GCO + production Book/final core + real receipt parsers;
+    only browser/site responses, accounts and Redis are synthetic.
+    """
+
+    def setUp(self):
+        from plugins import ita_workflow
+        from plugins.ita_calendar_session import CalendarRequestAudit
+        from plugins.ita_booking_final import VerifiedSubmission, SubmissionSignal
+        from test.test_debug_ita_production_query_gate import FakeAuditPage, FakeDriver
+        from test.test_ita_final_read_port import Browser
+        from test.test_ita_reservation import confirmed_listing, confirmed_detail
+        # Save the real function before the pre-final fixture's guard patch.
+        production_submit = ita_workflow.submit_final
+        LocalHarnessTests.setUp(self)
+        self.fixture.final.side_effect = production_submit
+        self.fixture.book_config.free_config["final_submit_enabled"] = True
+        self.browser = Browser()
+        self.fixture.book_page.browser = self.browser
+        self.fixture.book_page.url += "?selectedService=Visti%20Nazionali%20e%20Schengen"
+        self.dispatches = 0
+        self.create_receipt = True
+        self.submit_signal = SubmissionSignal.ACCEPTED
+        self.tmp = self.enterContext(tempfile.TemporaryDirectory())
+        self.input = self.enterContext(patch("builtins.input", side_effect=AssertionError("Automatic Book must not request input")))
+        self.control = self.local.LocalFinalSubmission(self.applicant,
+            self.fixture.book_plugin._resolve_route(self.fixture.apt), root=self.tmp)
+        self.native = Mock(side_effect=self.dispatch)
+
+        # Keep REAL audit registration, callback ownership, counting and settle
+        # logic. Mocking both nested audits previously hid the live collision.
+        self.audits = []
+        page = self.fixture.book_page
+        page.driver = FakeDriver()
+        page.run_cdp = Mock(return_value={})
+        page.final_requests = 0
+        self.emit_book_request = lambda path: FakeAuditPage.emit(page, path)
+        original_packet = page.response_packet
+
+        def response_packet(path, *args, **kwargs):
+            self.emit_book_request(path)
+            return original_packet(path, *args, **kwargs)
+
+        page.response_packet = response_packet
+        def audit(page, **kwargs):
+            result = CalendarRequestAudit(page, **kwargs)
+            result.start = Mock(wraps=result.start)
+            result.stop = Mock(wraps=result.stop)
+            self.audits.append(result)
+            return result
+
+        self.local.CalendarRequestAudit.side_effect = audit
+        clock = itertools.count(0, 0.1)
+        self.enterContext(patch.object(ita_workflow.preparation, "time", SimpleNamespace(
+            monotonic=lambda: next(clock), sleep=lambda _seconds: None)))
+
+        def native_factory(page, target, current):
+            self.native.submitted_selection = VerifiedSubmission(target)
+            return self.native
+
+        self.enterContext(patch.object(ita_workflow, "NativeFinalSubmitter", side_effect=native_factory))
+        self.new_listing = confirmed_listing()
+        self.new_detail = confirmed_detail()
+        self.new_listing["tables"][0]["rows"][1].update(date="14 ottobre 2026", time="10:26")
+        self.new_detail["fields"].update(Data="14 ottobre 2026", Ora="10:26")
+
+    def dispatch(self):
+        self.assertTrue(self.control.claim_path.exists())
+        self.dispatches += 1
+        self.emit_book_request("/BookingCalendar/InsertNewBooking")
+        if self.create_receipt:
+            self.browser.raw = self.new_listing
+            self.browser.receipts[self.new_listing["tables"][0]["rows"][1]["detailUrl"]] = self.new_detail
+        return self.submit_signal
+
+    def run_case(self):
+        return self.local.run_framework_once(self.fixture.query_config, self.fixture.book_config,
+            self.fixture.route, self.cloud, {}, final_control=self.control)
+
+    def test_one_final_returns_standard_success_and_local_notification_without_cloud_write(self):
+        report = self.run_case()
+        self.assertTrue(report["passed"], report)
+        self.assertEqual(report["contract"], self.local.FINAL_CONTRACT)
+        self.assertEqual(report["outcome"], "confirmed")
+        self.assertTrue(report["bookingConfirmed"])
+        self.assertTrue(report["bookResultSuccess"])
+        self.assertTrue(report["successHandledLocally"])
+        self.assertEqual(report["selectedTime"], "10:05 - 11:05")
+        self.assertEqual(report["confirmedTime"], "10:26")
+        self.assertEqual(report["queryRequests"]["finalRequests"], 0)
+        self.assertEqual(report["bookRequests"]["finalRequests"], 1)
+        self.assertTrue(report["cleanupVerified"])
+        self.assertEqual(self.dispatches, 1)
+        self.assertEqual((report["queryCalls"], report["bookCalls"]), (1, 1))
+        self.fixture.cloud.update_vas_task.assert_not_called()
+        self.fixture.executor.enqueue.assert_not_called()
+        self.assertNotIn("CONFIRMED-SYNTHETIC", json.dumps(report))
+        self.assertEqual(len(self.audits), 2)  # One owner per Query/Book page.
+        for audit in self.audits:
+            audit.start.assert_called_once()
+            audit.stop.assert_called_once()
+            self.assertEqual(audit.driver.immediate_event_handlers, {})
+
+    def test_automatic_submission_never_reads_stdin(self):
+        report = self.run_case()
+        self.assertEqual(report["outcome"], "confirmed", report)
+        self.assertTrue(report["passed"])
+        self.assertTrue(self.control.claim_path.exists())
+        self.native.assert_called_once()
+        self.input.assert_not_called()
+
+    def test_active_baseline_blocks_before_claim_and_preserves_existing_booking(self):
+        self.browser.raw = self.new_listing
+        self.browser.receipts[self.new_listing["tables"][0]["rows"][1]["detailUrl"]] = self.new_detail
+        report = self.run_case()
+        self.assertFalse(report["passed"], report)
+        self.assertFalse(report["possiblySubmitted"])
+        self.assertFalse(self.control.claim_path.exists())
+        self.native.assert_not_called()
+
+    def test_missing_receipt_is_unknown_local_pause_no_cloud_update_or_retry(self):
+        self.create_receipt = False
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["outcome"], "unknown_do_not_retry", report)
+        self.assertEqual(self.cloud.order["status"], "pause")
+        self.assertEqual(report["bookRequests"]["finalRequests"], 1)
+        self.assertTrue(self.control.claim_path.exists())
+        self.assertEqual(self.dispatches, 1)
+        self.fixture.cloud.update_vas_task.assert_not_called()
+
+    def test_cleanup_failure_does_not_erase_confirmed_booking_or_allow_retry(self):
+        self.fixture.book_plugin.cleanup.side_effect = RuntimeError("fixture-cleanup")
+        report = self.run_case()
+        self.assertFalse(report["passed"], report)
+        self.assertTrue(report["bookingConfirmed"], report)
+        self.assertEqual(report["outcome"], "confirmed")
+        self.assertTrue(self.control.claim_path.exists())
+        self.assertEqual(self.dispatches, 1)
+
+    def test_unknown_response_with_verified_request_and_receipt_is_confirmed(self):
+        from plugins.ita_booking_final import SubmissionSignal
+        self.submit_signal = SubmissionSignal.UNKNOWN
+        self.assertTrue(self.run_case()["passed"])
+
+    def test_crash_during_native_call_retains_claim_and_never_retries(self):
+        self.native.side_effect = RuntimeError("synthetic-private-response")
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.assertEqual(report["outcome"], "unknown_do_not_retry")
+        self.assertTrue(report["possiblySubmitted"])
+        self.assertTrue(self.control.claim_path.exists())
+        self.native.assert_called_once()
+        self.assertNotIn("private-response", json.dumps(report))
+
+    def test_restart_is_blocked_before_second_pool_allocation(self):
+        from plugins.ita_booking_final import FinalBookingError
+        self.assertTrue(self.run_case()["passed"])
+        with self.assertRaises(FinalBookingError):
+            self.local.LocalFinalSubmission(self.applicant, self.control.route, root=self.tmp)
+        self.assertEqual(self.cloud.pool_calls, 1)
+        self.native.assert_called_once()
+
+    def test_negative_book_inventory_never_prompts_or_submits(self):
+        self.fixture.book_page.passes = [[book_flow.month("2026-10", {})]]
+        self.fixture.book_page.month_spec = self.fixture.book_page.passes[0][0]
+        report = self.run_case()
+        self.assertFalse(report["passed"])
+        self.input.assert_not_called()
+        self.native.assert_not_called()
+        self.assertFalse(self.control.claim_path.exists())
+
+
+class LocalFinalCompositionTests(unittest.TestCase):
+    def setUp(self):
+        from tools import ita_query_book_local as local
+        self.local = local
+        self.tmp = self.enterContext(tempfile.TemporaryDirectory())
+        self.applicant = SimpleNamespace(username="Applicant@example.test")
+        self.route = SimpleNamespace(service_id=9001, routing_key="slot.fixture.it.tourist")
+
+    def control(self, applicant=None, route=None):
+        return self.local.LocalFinalSubmission(applicant or self.applicant, route or self.route, root=self.tmp)
+
+    def test_claim_reuses_exclusive_helper_and_blocks_restarts_and_routing_aliases(self):
+        from plugins.ita_booking_final import FinalBookingError
+        control = self.control()
+        self.local.claim_once(control.claim_path)
+        for account, route in ((self.applicant, self.route),
+                               (SimpleNamespace(username=" applicant@EXAMPLE.test "),
+                                SimpleNamespace(service_id=9001, routing_key="alias"))):
+            with self.assertRaises(FinalBookingError):
+                self.control(account, route)
+        self.assertNotIn("applicant", str(control.claim_path))
+        self.assertNotIn("example.test", control.claim_path.read_text())
+        self.assertNotEqual(control.claim_path, self.control(SimpleNamespace(username="other@example.test")).claim_path)
+
+    def test_stale_or_wrong_owner_is_rejected_before_production_submission(self):
+        control = self.control()
+        production = Mock()
+        with self.assertRaises(self.local.LocalAcceptanceError):
+            control.submit(Mock(), self.route, {}, production)
+        production.assert_not_called()
+
+    def test_partial_claim_and_symlink_block_without_removal(self):
+        from plugins.ita_booking_final import FinalBookingError
+        control = self.control()
+        control.claim_path.parent.mkdir(parents=True)
+        control.claim_path.touch()
+        with self.assertRaises(FinalBookingError):
+            self.control()
+        other = self.control(SimpleNamespace(username="other@example.test"))
+        other.claim_path.symlink_to(Path(self.tmp) / "missing")
+        with self.assertRaises(FinalBookingError):
+            self.control(SimpleNamespace(username="other@example.test"))
+        self.assertTrue(other.claim_path.is_symlink())
+
+    def test_noninteractive_configured_run_never_prompts_and_retains_exit_contract(self):
+        args = SimpleNamespace(submit_once=True, local_run=True, local_preflight=False, book_account_file="fixture")
+        group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="fixture"))
+        route = SimpleNamespace(routing_key="fixture", mail=None)
+        applicant = SimpleNamespace(username="applicant@example.test", password="fixture-password")
+        result = {"passed": False, "outcome": "unknown_do_not_retry", "possiblySubmitted": True}
+        with contextlib.redirect_stdout(io.StringIO()), \
+                patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
+                patch("sys.stdin.isatty", return_value=False), \
+                patch("builtins.input", side_effect=AssertionError("No interactive input")) as prompt, \
+                patch.object(self.local, "check_dependencies", return_value=("fixture", "fixture")), \
+                patch.object(self.local, "load_local_account", return_value=applicant), \
+                patch.object(self.local, "validate_cloud_otp_environment"), \
+                patch.object(self.local, "LocalFinalSubmission"), \
+                patch.object(self.local, "build_groups", return_value=(Mock(), Mock())), \
+                patch.object(self.local, "LocalCloudBoundary"), \
+                patch.object(self.local.VSCloudApi, "Instance"), \
+                patch.object(self.local, "private_redis", return_value=contextlib.nullcontext({})), \
+                patch.object(self.local, "run_framework_once", return_value=result):
+            self.assertEqual(self.local.main_local(args), 4)
+            result.update(passed=True, outcome="confirmed")
+            self.assertEqual(self.local.main_local(args), 0)
+            prompt.assert_not_called()
+
+
+class LocalConfigurationTests(unittest.TestCase):
+    def setUp(self):
+        from tools import ita_query_book_local as local
+        self.local = local
+        self.enterContext(contextlib.redirect_stdout(io.StringIO()))
+
+    def settings_fixture(self):
+        args = SimpleNamespace(config="synthetic.json", group="synthetic-group", proxy="http://127.0.0.1:6268",
+                               expected_start_date=None, expected_end_date=None)
+        group = {"identifier": args.group, "plugin_config": {"plugin_name": "ita_plugin"},
+                 "sentinel": {"account_pool_id": "synthetic-pool", "signal_ttl": 30},
+                 "appointment_types": [{"routing_key": "slot.other.it.tourist", "weight": 1}],
+                 "free_config": {"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
+                                 "apt_configs": {"slot.other.it.tourist": {
+                                     "service_id": 9001, "capability": "single_schengen_tourism",
+                                     "calendar_scan": {"lookahead_months": 3},
+                                     "form": {"booking_type_control_id": "typeofbookingddl", "booking_type_value": "1",
+                                              "booking_type_labels": ["Single booking"], "purpose_control_id": "ddls_0",
+                                              "purpose_value": "42", "purpose_labels": ["Tourism"]},
+                                     "mail": {"authorization_source": "account"}}}}}
+        return args, group
+
+    def test_real_settings_parser_accepts_other_region_without_fixed_mailbox(self):
+        args, group = self.settings_fixture()
+        with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
+                patch.object(self.local.configure, "TEST_ACCOUNT", None), \
+                patch.object(self.local, "validate_cloud_otp_logging"):
+            source, route, proxy, preferences = self.local.load_settings(args)
+        self.assertEqual(route.service_id, 9001)
+        self.assertEqual(source.sentinel.account_pool_id, "synthetic-pool")
+        self.assertEqual(route.mail.mailbox_for("second@example.test"), "second@example.test")
+        self.assertEqual(proxy.port, 6268)
+        self.assertEqual(preferences, {})
+
+    def test_invalid_settings_cannot_reach_dependencies_or_pool(self):
+        args, template = self.settings_fixture()
+        for changes in ({"query_mode": "services_probe"}, {"otp_mode": "manual"}, {"final_submit_enabled": True}):
+            group = copy.deepcopy(template)
+            group["free_config"].update(changes)
+            with self.subTest(changes=changes), \
+                    patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
+                    patch.object(self.local.configure, "TEST_ACCOUNT", None), \
+                    patch.object(self.local, "validate_cloud_otp_logging"), \
+                    self.assertRaises(self.local.LocalAcceptanceError):
+                self.local.load_settings(args)
+
+    def test_public_proxy_and_reversed_date_range_are_rejected_before_run(self):
+        args, group = self.settings_fixture()
+        for proxy, start, end in (("http://remote.example.test:6268", None, None),
+                                  (args.proxy, "2026-10-31", "2026-10-01")):
+            args.proxy, args.expected_start_date, args.expected_end_date = proxy, start, end
+            with patch.object(self.local.Path, "read_text", return_value=json.dumps([group])), \
+                    patch.object(self.local.configure, "TEST_ACCOUNT", None), \
+                    patch.object(self.local, "validate_cloud_otp_logging"), self.assertRaises(Exception):
+                self.local.load_settings(args)
+
+    def test_successful_preflight_never_prompts_allocates_or_launches(self):
+        args = SimpleNamespace(local_preflight=True)
+        group = SimpleNamespace(sentinel=SimpleNamespace(account_pool_id="synthetic-pool"))
+        route = SimpleNamespace(routing_key="synthetic-route")
+        with patch.object(self.local, "load_settings", return_value=(group, route, Mock(), {})), \
+                patch.object(self.local, "check_dependencies", return_value=("redis-server", "/synthetic/chrome")), \
+                patch.object(self.local, "_get_credentials") as credentials, \
+                patch.object(self.local.VSCloudApi, "Instance") as api, \
+                patch.object(self.local, "private_redis") as private_redis:
+            self.assertEqual(self.local.main_local(args), 0)
+        credentials.assert_not_called()
+        api.assert_not_called()
+        private_redis.assert_not_called()
+
+    def test_default_cli_never_starts_local_run_and_explicit_mode_is_forwarded(self):
+        with patch.object(self.local, "main_local", return_value=7) as live:
+            self.assertEqual(cli.main(["--local-run", "--group", "my-route-group"]), 7)
+            self.assertEqual(live.call_args.args[0].group, "my-route-group")
+            self.assertTrue(live.call_args.args[0].local_run)
+
+    def test_preflight_checks_dependencies_before_api_or_credentials(self):
+        args = SimpleNamespace(local_preflight=True)
+        with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
+                patch.object(self.local, "check_dependencies", side_effect=self.local.LocalAcceptanceError("missing_dependency")), \
+                patch.object(self.local, "_get_credentials") as credentials, \
+                patch.object(self.local.VSCloudApi, "Instance") as api:
+            self.assertEqual(self.local.main_local(args), 1)
+        credentials.assert_not_called()
+        api.assert_not_called()
+
+    def test_group_copy_preserves_service_and_ttl_not_production_config(self):
+        group = GroupConfig(identifier="source", sentinel={"account_pool_id": "test-pool", "signal_ttl": 37},
+            appointment_types=[{"routing_key": "slot.other.it.tourist", "weight": 1}],
+            free_config={"query_mode": "calendar", "otp_mode": "cloud", "final_submit_enabled": False,
+                         "persistent_browser_profile_path": "/never-touch", "apt_configs": {"some-route": {"service_id": 999}}})
+        before = group.model_dump()
+        query, book = self.local.build_groups(group, "synthetic")
+        self.assertEqual(group.model_dump(), before)
+        self.assertEqual(query.sentinel.signal_ttl, 37)
+        self.assertEqual(query.sentinel.account_pool_id, "test-pool")
+        self.assertEqual(query.free_config["apt_configs"], before["free_config"]["apt_configs"])
+        self.assertEqual(book.booker.account_source, "order")
+        self.assertEqual(book.free_config["query_mode"], "services_probe")
+        self.assertNotIn("persistent_browser_profile_path", query.free_config)
+        self.assertFalse(book.free_config["final_submit_enabled"])
+
+    def test_final_flag_only_enables_applicant_copy_and_requires_live_cli(self):
+        group = GroupConfig(identifier="source", free_config={"final_submit_enabled": False})
+        group.appointment_types = [SimpleNamespace(weight=1)]
+        query, book = self.local.build_groups(group, "fixture", submit_once=True)
+        self.assertFalse(group.free_config["final_submit_enabled"])
+        self.assertFalse(query.free_config["final_submit_enabled"])
+        self.assertTrue(book.free_config["final_submit_enabled"])
+        with patch.object(self.local, "main_local", return_value=0) as live:
+            for args in (["--submit-once"], ["--local-preflight", "--submit-once"], ["--offline", "--submit-once"]):
+                with self.assertRaises(SystemExit), contextlib.redirect_stderr(io.StringIO()):
+                    cli.main(args)
+            live.assert_not_called()
+            self.assertEqual(cli.main(["--local-run", "--submit-once"]), 0)
+            self.assertTrue(live.call_args.args[0].submit_once)
+
+    def test_final_requires_explicit_live_mode_before_pool_or_browser(self):
+        args = SimpleNamespace(submit_once=True, local_run=False)
+        with patch.object(self.local, "load_settings", return_value=(Mock(), Mock(), Mock(), {})), \
+                patch.object(self.local, "check_dependencies") as dependencies, \
+                patch.object(self.local.VSCloudApi, "Instance") as api:
+            self.assertEqual(self.local.main_local(args), 1)
+        dependencies.assert_not_called()
+        api.assert_not_called()
+
+    def test_private_redis_is_owned_socket_only_no_shared_flush(self):
+        process = Mock()
+        process.poll.return_value = None
+        with patch.object(self.local.subprocess, "Popen", return_value=process) as popen, \
+                patch.object(self.local.redis, "Redis") as redis:
+            redis.return_value.ping.return_value = True
+            with self.local.private_redis("/synthetic/redis-server") as config:
+                self.assertTrue(config["unix_socket_path"].startswith("/tmp/ita-qb-"))
+                self.assertNotIn("host", config)
+                command = popen.call_args.args[0]
+                self.assertEqual(command[command.index("--port") + 1], "0")
+                self.assertEqual(command[command.index("--save") + 1], "")
+                self.assertEqual(command[command.index("--appendonly") + 1], "no")
+        process.terminate.assert_called_once()
+        process.wait.assert_called_once_with(timeout=5)
+        redis.return_value.flushdb.assert_not_called()
+        redis.return_value.flushall.assert_not_called()
+        self.assertFalse(self.local.Path(config["unix_socket_path"]).parent.exists())
+
+    def test_private_redis_cleanup_also_runs_when_test_fails(self):
+        process = Mock()
+        process.poll.return_value = None
+        with patch.object(self.local.subprocess, "Popen", return_value=process), \
+                patch.object(self.local.redis, "Redis") as redis:
+            redis.return_value.ping.return_value = True
+            with self.assertRaisesRegex(RuntimeError, "synthetic"):
+                with self.local.private_redis("/synthetic/redis-server"):
+                    raise RuntimeError("synthetic")
+        process.terminate.assert_called_once()
+
+    def test_private_redis_startup_failure_closes_client_and_never_yields(self):
+        process = Mock()
+        process.poll.return_value = 1
+        with patch.object(self.local.subprocess, "Popen", return_value=process), \
+                patch.object(self.local.redis, "Redis") as redis:
+            with self.assertRaisesRegex(self.local.LocalAcceptanceError, "private_redis_exited"):
+                with self.local.private_redis("/synthetic/redis-server"):
+                    self.fail("Dead Redis cannot be used")
+            redis.return_value.close.assert_called_once()
+
+
+class LocalRedisIntegrationTests(unittest.TestCase):
+    """Opt-in class: real disposable Redis, synthetic website/account I/O.
+
+Not included in the CLI's --offline TEST_NAMES, which promises no subprocesses.
+"""
+
+    def run_real_redis_case(self, *, expire=False):
+        import shutil
+        import socket
+        import time
+        from tools import ita_query_book_local as local
+        from utils.safe_redis_cli import SafeRedisClient
+        executable = shutil.which("redis-server")
+        if not executable:
+            self.skipTest("redis-server is needed for the explicitly selected Redis integration test")
+        original_connect = socket.socket.connect
+        real_sleep = time.sleep
+        with local.private_redis(executable) as config:
+            case = LocalHarnessTests()
+            case.setUp()
+            try:
+                def socket_only(connection, address):
+                    if address != config["unix_socket_path"]:
+                        raise AssertionError("Redis integration attempted non-owned socket")
+                    return original_connect(connection, address)
+
+                case.enterContext(patch.object(socket.socket, "connect", socket_only))
+                for cls in (local.SentinelGCO, local.OrderBookerGCO):
+                    case.enterContext(patch.dict(cls.__init__.__globals__, {"SafeRedisClient": SafeRedisClient}))
+                if expire:
+                    case.fixture.query_config.sentinel.signal_ttl = 1
+                    read = SafeRedisClient.get
+
+                    def after_expiry(client, key):
+                        real_sleep(1.1)  # Fixture mocks time.sleep; use actual server wall clock here.
+                        return read(client, key)
+
+                    case.enterContext(patch.object(SafeRedisClient, "get", after_expiry))
+                report = local.run_framework_once(case.fixture.query_config, case.fixture.book_config,
+                                                  case.fixture.route, case.cloud, config)
+            finally:
+                case.doCleanups()
+        self.assertFalse(local.Path(config["unix_socket_path"]).parent.exists())
+        return report
+
+    def test_real_framework_publishes_and_consumes_real_redis(self):
+        report = self.run_real_redis_case()
+        self.assertTrue(report["passed"], report)
+        self.assertTrue(report["signalPublished"])
+        self.assertTrue(report["signalReadByBooker"])
+        self.assertEqual(report["bookCalls"], 1)
+
+    def test_real_redis_expiry_prevents_book_without_republishing(self):
+        report = self.run_real_redis_case(expire=True)
+        self.assertTrue(report["signalPublished"])
+        self.assertFalse(report["signalReadByBooker"])
+        self.assertEqual(report["bookCalls"], 0)
+        self.assertFalse(report["passed"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 483 - 0
test/test_debug_ita_reservation.py

@@ -0,0 +1,483 @@
+"""Offline gate tests with the production receipt parsers and passive audit."""
+
+import copy
+import json
+import os
+import unittest
+from contextlib import ExitStack, redirect_stdout
+from io import StringIO
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins.ita_reservation import DETAIL_READ_SCRIPT, LIST_READ_SCRIPT, DATE_DIAGNOSTIC_SCRIPT, ReservationReadError
+from test.test_ita_reservation import detail, listing, confirmed_detail, confirmed_listing
+from test.test_debug_ita_production_query_gate import FakeDriver
+from tools import debug_ita_reservation as gate
+
+
+class ReceiptPage:
+    def __init__(self):
+        self.url = "https://prenotami.esteri.it/UserArea"
+        self.tab_id = "synthetic-tab"
+        self.driver = FakeDriver()
+        self.before = listing()
+        self.after = copy.deepcopy(self.before)
+        self.receipt = detail()
+        self.urls = []
+        self.diagnostic_reads = 0
+        self.on_get = lambda: None
+        self.run_cdp = Mock(return_value={})
+        self.ele = Mock(return_value=True)
+
+    def get(self, url, *, retry, timeout):
+        assert retry == 0 and timeout == 30
+        self.url = url
+        self.urls.append(url)
+        self.on_get()
+        return True
+
+    def run_js(self, script):
+        if script == LIST_READ_SCRIPT:
+            return copy.deepcopy(self.after if len(self.urls) == 3 else self.before)
+        if script == DETAIL_READ_SCRIPT:
+            return copy.deepcopy(self.receipt)
+        if script == DATE_DIAGNOSTIC_SCRIPT:
+            self.diagnostic_reads += 1
+            text = self.before["tables"][0]["rows"][0]["date"]
+            return {"path": "/Reservation", "samples": [{"text": text, "rendered": text,
+                    "parts": [{"kind": "text", "text": text, "hidden": False}],
+                    "partsTruncated": False}], "rowsTruncated": False}
+        raise AssertionError("Only receipt reads are allowed")
+
+    def emit(self, path, method="GET"):
+        callback = self.driver.immediate_event_handlers[gate.CalendarRequestAudit.EVENT]
+        callback(request={"url": "https://prenotami.esteri.it" + path, "method": method})
+
+
+def fake_plugin():
+    plugin = SimpleNamespace(page=ReceiptPage(), session_create_time=1, _persistent_profile_path=None)
+    plugin.set_log = Mock()
+
+    def set_config(config):
+        plugin.config = config
+        plugin.free_config = config.free_config
+
+    plugin.set_config = Mock(side_effect=set_config)
+    plugin.create_session = Mock(side_effect=lambda: setattr(
+        plugin.page, "url", "https://prenotami.esteri.it/UserArea"))
+    plugin.cleanup = Mock()
+    plugin.query = Mock(side_effect=AssertionError("Query forbidden"))
+    plugin.book = Mock(side_effect=AssertionError("Book forbidden"))
+    return plugin
+
+
+class ReceiptGateTests(unittest.TestCase):
+    def setUp(self):
+        self.stack = ExitStack()
+        self.addCleanup(self.stack.close)
+        self.plugin = fake_plugin()
+        self.factory = self.stack.enter_context(patch.object(gate, "ItaPlugin", return_value=self.plugin))
+        self.credentials = self.stack.enter_context(patch.object(
+            gate, "_get_credentials", return_value=("applicant@example.invalid", "SECRET-PASSWORD")))
+        self.stack.enter_context(patch.object(gate, "resolve_chrome_path", return_value=Path("/synthetic/chrome")))
+        # Reuse real request classification; only shorten the audit's settled window.
+        self.stack.enter_context(patch.object(gate.CalendarRequestAudit, "settled_snapshot",
+                                             gate.CalendarRequestAudit.snapshot))
+        self.stack.enter_context(patch("plugins.ita_reservation.time.sleep"))
+
+    def run_gate(self, *, execute=True, env=None, **kwargs):
+        output = StringIO()
+        with redirect_stdout(output):
+            code = gate.run_receipt_gate(env or {}, execute=execute, **kwargs)
+        text = output.getvalue()
+        rows = [line for line in text.splitlines() if line.startswith("ITA_RECEIPT_GATE_RESULT=")]
+        result = json.loads(rows[-1].split("=", 1)[1]) if rows else None
+        for secret in ("SECRET-PASSWORD", "applicant@example.invalid", "SYNTHETIC-REFERENCE", "synthetic-link"):
+            self.assertNotIn(secret, text)
+        self.plugin.query.assert_not_called()
+        self.plugin.book.assert_not_called()
+        return code, result, text
+
+    def test_preflight_has_no_credentials_browser_or_network(self):
+        code, result, text = self.run_gate(execute=False)
+        self.assertEqual(code, 0)
+        self.assertIsNone(result)
+        self.assertIn("external_requests=0 credentials_read=false browser_created=false", text)
+        self.factory.assert_not_called()
+        self.credentials.assert_not_called()
+
+    def test_only_explicit_boolean_enables_run(self):
+        for value in (1, "true", None):
+            code, result, _ = self.run_gate(execute=value)
+            self.assertEqual(code, 1)
+            self.assertEqual(result["reason"], "invalid_execution_flag")
+        self.factory.assert_not_called()
+
+    def test_success_reads_real_parsers_and_cleans_only_owned_browser(self):
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 0)
+        self.assertTrue(result["passed"])
+        self.assertTrue(result["cancelledDetailMatched"])
+        self.assertTrue(result["listUnchanged"])
+        self.assertEqual(result["reservationCountBefore"], 1)
+        self.assertEqual(result["reservationCountAfter"], 1)
+        self.assertEqual(result["postLoginBusinessRequests"], dict.fromkeys(gate.COUNTERS, 0))
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL,
+                         listing()["tables"][0]["rows"][0]["detailUrl"], gate.LIST_URL])
+        self.plugin.cleanup.assert_called_once()
+        self.assertEqual(self.plugin.page.driver.immediate_event_handlers, {})
+
+    def confirmed_setup(self):
+        page = self.plugin.page
+        page.before = confirmed_listing()
+        page.after = copy.deepcopy(page.before)
+        page.receipt = confirmed_detail()
+        return dict(expect_confirmed=True, expected_date="2026-09-03", expected_time="09:26",
+                    expected_service="Visti Nazionali e Schengen")
+
+    def test_existing_confirmed_receipt_is_verified_without_claiming_prior_attempt(self):
+        args = self.confirmed_setup()
+        code, result, text = self.run_gate(**args)
+        self.assertEqual(code, 0, text)
+        self.assertTrue(result["existingReservationConfirmed"])
+        self.assertTrue(result["confirmedDetailMatched"])
+        self.assertFalse(result["cancelledDetailMatched"])
+        self.assertFalse(result["bookingAttemptAttributed"])
+        self.assertTrue(result["listUnchanged"])
+        self.assertEqual(result["reservationCountBefore"], 2)
+        self.assertEqual(result["reservationCountAfter"], 2)
+        self.assertEqual(result["confirmedReceipt"]["state"], "active")
+        self.assertEqual(result["confirmedReceipt"]["assignedTime"], "09:26")
+        self.assertEqual(result["postLoginBusinessRequests"], dict.fromkeys(gate.COUNTERS, 0))
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL,
+                         confirmed_listing()["tables"][0]["rows"][1]["detailUrl"], gate.LIST_URL])
+        self.assertNotIn("CONFIRMED-SYNTHETIC", text)
+        self.plugin.cleanup.assert_called_once()
+
+    def test_confirmed_preflight_remains_local(self):
+        args = self.confirmed_setup()
+        code, _, _ = self.run_gate(execute=False, **args)
+        self.assertEqual(code, 0)
+        self.credentials.assert_not_called()
+        self.factory.assert_not_called()
+
+    def test_invalid_expectations_fail_before_credentials(self):
+        for key, value in (("expected_date", None), ("expected_date", "20260903"),
+                           ("expected_date", "2026-02-30"), ("expected_time", "09:15 - 10:00"),
+                           ("expected_time", "9:26"), ("expected_service", ""),
+                           ("expected_service", "name\n"), ("expected_service", "a" * 257)):
+            with self.subTest(key=key, value=value):
+                args = self.confirmed_setup()
+                args[key] = value
+                code, result, _ = self.run_gate(**args)
+                self.assertEqual(code, 1)
+                self.assertEqual(result["reason"], "confirmed_expectations_invalid")
+        self.credentials.assert_not_called()
+        self.factory.assert_not_called()
+
+    def test_expectations_without_mode_and_non_bool_mode_are_rejected(self):
+        self.assertEqual(self.run_gate(expected_date="2026-09-03")[1]["reason"],
+                         "confirmed_expectations_without_mode")
+        self.assertEqual(self.run_gate(expect_confirmed=1)[1]["reason"], "invalid_execution_flag")
+        self.credentials.assert_not_called()
+
+    def test_wrong_date_time_or_display_service_does_not_verify_another_receipt(self):
+        for key, value in (("expected_date", "2026-09-04"), ("expected_time", "09:15"),
+                           ("expected_service", "Different service")):
+            with self.subTest(key=key):
+                args = self.confirmed_setup()
+                self.plugin.page.urls.clear()
+                args[key] = value
+                code, result, _ = self.run_gate(**args)
+                self.assertEqual(code, 1)
+                self.assertEqual(result["reason"], "confirmed_sample_missing")
+                self.assertFalse(result["existingReservationConfirmed"])
+                self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+
+    def test_multiple_matching_confirmed_receipts_do_not_pick_first(self):
+        args = self.confirmed_setup()
+        table = self.plugin.page.before["tables"][0]
+        table["rows"].append({**table["rows"][1], "reference": "ANOTHER",
+                              "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/another"})
+        table["count"] = 3
+        table["info"].update(recordsTotal=3, recordsDisplay=3, end=3)
+        code, result, _ = self.run_gate(**args)
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "confirmed_sample_ambiguous")
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+
+    def test_confirmed_detail_requires_code_identity_fields_and_single_booking(self):
+        cases = (("statusCode", "3"), ("Codice Prenotazione", "WRONG"), ("Ora", "09:27"),
+                 ("Servizio Erogato", "Wrong"), ("Servizio Consolare", "Wrong"),
+                 ("Data", "4 settembre 2026"), ("Stato", "Annullata"),
+                 ("Tipo Prenotazione", "Prenotazione Multipla"))
+        for key, value in cases:
+            with self.subTest(key=key):
+                args = self.confirmed_setup()
+                self.plugin.page.urls.clear()
+                if key == "statusCode":
+                    self.plugin.page.receipt[key] = value
+                else:
+                    self.plugin.page.receipt["fields"][key] = value
+                code, result, _ = self.run_gate(**args)
+                self.assertEqual(code, 1)
+                self.assertEqual(result["reason"], "confirmed_detail_mismatch")
+                self.assertFalse(result["existingReservationConfirmed"])
+
+    def test_confirmed_history_changes_and_business_requests_still_reject(self):
+        args = self.confirmed_setup()
+        self.plugin.page.after["tables"][0]["rows"][0]["time"] = "10:26"
+        result = self.run_gate(**args)[1]
+        self.assertEqual(result["reason"], "listing_changed")
+        self.assertFalse(result["existingReservationConfirmed"])
+        args = self.confirmed_setup()
+        self.plugin.page.urls.clear()
+        self.plugin.page.on_get = lambda: self.plugin.page.emit("/BookingCalendar/InsertNewBooking", "POST")
+        result = self.run_gate(**args)[1]
+        self.assertEqual(result["reason"], "unexpected_business_request")
+        self.assertFalse(result["existingReservationConfirmed"])
+
+    def test_confirmed_cli_forwards_explicit_expectations_without_enabling_run(self):
+        with patch.object(gate, "run_receipt_gate", return_value=0) as runner:
+            gate.main(["--expect-confirmed", "--expected-date", "2026-09-03", "--expected-time", "09:26",
+                       "--expected-service", "Visti Nazionali e Schengen"])
+        self.assertFalse(runner.call_args.kwargs["execute"])
+        self.assertTrue(runner.call_args.kwargs["expect_confirmed"])
+        self.assertEqual(runner.call_args.kwargs["expected_time"], "09:26")
+
+    def test_inherited_query_debug_and_profile_settings_are_ignored(self):
+        env = {"ITA_DEBUG": "1", "ITA_SERVICE_ID": "bad", "ITA_ACCOUNT_ID": "bad",
+               "ITA_QUERY_ACCOUNT_FILE": "/private/account.json", "ITA_USERNAME": "QUERY-USER",
+               "ITA_PASSWORD": "QUERY-PASSWORD", "ITA_BOOK_USERNAME": "USER",
+               "ITA_BOOK_PASSWORD": "PASSWORD", "ITA_QCAL_MODE": "calendar_soak"}
+        self.assertEqual(self.run_gate(env=env)[0], 0)
+        self.credentials.assert_called_once_with(
+            {"ITA_USERNAME": "USER", "ITA_PASSWORD": "PASSWORD"}, non_interactive=False)
+        self.assertFalse(self.plugin.config.debug)
+        self.assertEqual(self.plugin.config.account.id, 0)
+        self.assertEqual(self.plugin.free_config,
+                         {"query_mode": gate.SERVICES_PROBE_QUERY_MODE, "final_submit_enabled": False})
+
+    def test_missing_cancelled_sample_does_not_open_a_detail(self):
+        self.plugin.page.before["tables"][0]["rows"][0]["status"] = "Confermata"
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "cancelled_sample_missing")
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+
+    def test_empty_list_never_manufactures_a_sample(self):
+        table = self.plugin.page.before["tables"][0]
+        table.update(count=0, rows=[])
+        table["info"].update(recordsTotal=0, recordsDisplay=0, end=0, pages=0)
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reservationCountBefore"], 0)
+        self.assertEqual(result["reason"], "cancelled_sample_missing")
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+
+    def test_multirow_list_order_change_is_not_a_reservation_change(self):
+        table = self.plugin.page.before["tables"][0]
+        row = {**table["rows"][0], "reference": "SECOND",
+               "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/second"}
+        table["rows"].append(row)
+        table.update(count=2)
+        table["info"].update(recordsTotal=2, recordsDisplay=2, end=2)
+        self.plugin.page.after = copy.deepcopy(self.plugin.page.before)
+        self.plugin.page.after["tables"][0]["rows"].reverse()
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 0)
+        self.assertEqual(result["reservationCountAfter"], 2)
+        self.assertEqual(len(self.plugin.page.urls), 3)  # Only one detail read.
+
+    def test_navigation_failure_and_auth_redirect_do_not_pass(self):
+        with patch.object(self.plugin.page, "get", return_value=False):
+            self.assertEqual(self.run_gate()[1]["reason"], "navigation_failed")
+        self.plugin.page.on_get = lambda: setattr(self.plugin.page, "url", "https://iam.esteri.it/signin/")
+        self.assertEqual(self.run_gate()[1]["reason"], "navigation_rejected")
+
+    def test_missing_login_markers_stops_before_audit_and_navigation(self):
+        self.plugin.page.ele.return_value = False
+        self.assertEqual(self.run_gate()[1]["reason"], "login_unverified")
+        self.assertEqual(self.plugin.page.urls, [])
+
+    def test_late_business_request_during_final_audit_rejects_success(self):
+        calls = 0
+
+        def snapshot(audit):
+            nonlocal calls
+            calls += 1
+            if calls == 4:
+                self.plugin.page.emit("/BookingCalendar/GenerateOTP")
+            return audit.snapshot()
+
+        with patch.object(gate.CalendarRequestAudit, "settled_snapshot", snapshot):
+            code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertFalse(result["passed"])
+        self.assertFalse(result["auditVerified"])
+        self.assertEqual(result["reason"], "unexpected_business_request")
+
+    def test_preflight_configuration_error_is_sanitized(self):
+        with patch.object(gate, "resolve_chrome_path", side_effect=gate.DebugConfigurationError("SECRET-PASSWORD")):
+            code, result, _ = self.run_gate(execute=False)
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "configuration_rejected")
+        self.credentials.assert_not_called()
+        self.factory.assert_not_called()
+
+    def test_each_mismatched_detail_field_is_rejected(self):
+        for key, value in (("Servizio Consolare", "Other"), ("Servizio Erogato", "Other"),
+                           ("Codice Prenotazione", "OTHER"), ("Data", "14 ottobre 2026"),
+                           ("Ora", "10:26"), ("Stato", "Confermata"),
+                           ("Tipo Prenotazione", "Prenotazione Multipla")):
+            with self.subTest(key=key):
+                self.plugin.page.urls.clear()
+                self.plugin.page.receipt = detail()
+                self.plugin.page.receipt["fields"][key] = value
+                code, result, _ = self.run_gate()
+                self.assertEqual(code, 1)
+                self.assertEqual(result["reason"], "cancelled_detail_mismatch")
+
+    def test_cancelled_status_code_must_also_match(self):
+        self.plugin.page.receipt["statusCode"] = "2"
+        self.assertEqual(self.run_gate()[1]["reason"], "cancelled_detail_mismatch")
+
+    def test_list_change_cannot_pass(self):
+        self.plugin.page.after["tables"][0]["rows"][0]["time"] = "10:26"
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertFalse(result["passed"])
+        self.assertEqual(result["reason"], "listing_changed")
+
+    def test_cross_origin_detail_link_not_followed(self):
+        self.plugin.page.before["tables"][0]["rows"][0]["detailUrl"] = "https://evil.invalid/secret"
+        self.assertEqual(self.run_gate()[0], 1)
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+
+    def test_session_context_change_is_rejected(self):
+        for attribute, value in (("session_create_time", 2), ("_persistent_profile_path", "/private")):
+            with self.subTest(attribute=attribute):
+                original = getattr(self.plugin, attribute)
+                self.plugin.page.on_get = lambda: setattr(self.plugin, attribute, value)
+                self.assertEqual(self.run_gate()[1]["reason"], "context_changed")
+                setattr(self.plugin, attribute, original)
+
+    def test_tab_change_is_rejected(self):
+        self.plugin.page.on_get = lambda: setattr(self.plugin.page, "tab_id", "OTHER-TAB")
+        self.assertEqual(self.run_gate()[1]["reason"], "context_changed")
+
+    def test_account_change_is_rejected(self):
+        self.plugin.page.on_get = lambda: setattr(self.plugin.config.account, "username", "OTHER")
+        self.assertEqual(self.run_gate()[1]["reason"], "context_changed")
+
+    def test_each_forbidden_business_request_is_detected(self):
+        for path, method in (("/BookingCalendar/GenerateOTP", "GET"),
+                             ("/Services/Booking/9001", "POST"),
+                             ("/BookingCalendar/InsertNewBooking", "POST"),
+                             ("/BookingCalendar/RetrieveCalendarAvailability", "POST"),
+                             ("/BookingCalendar/RetrieveTimeSlots", "POST")):
+            with self.subTest(path=path):
+                self.plugin.page.urls.clear()
+                self.plugin.page.on_get = lambda: self.plugin.page.emit(path, method)
+                code, result, _ = self.run_gate()
+                self.assertEqual(code, 1)
+                self.assertEqual(result["reason"], "unexpected_business_request")
+                self.assertGreater(sum(result["postLoginBusinessRequests"].values()), 0)
+
+    def test_ordinary_get_and_telemetry_are_not_claimed_absent(self):
+        def ordinary_requests():
+            self.plugin.page.emit("/Reservation")
+            self.plugin.page.emit("/synthetic-telemetry", "POST")
+        self.plugin.page.on_get = ordinary_requests
+        self.assertEqual(self.run_gate()[0], 0)
+
+    def test_disconnected_audit_fails(self):
+        self.plugin.page.on_get = lambda: setattr(self.plugin.page.driver, "is_running", False)
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "audit_unavailable")
+        self.assertIsNone(result["postLoginBusinessRequests"])
+
+    def test_audit_cannot_replace_another_callback(self):
+        self.plugin.page.driver.immediate_event_handlers[gate.CalendarRequestAudit.EVENT] = object()
+        self.assertEqual(self.run_gate()[0], 1)
+        self.assertEqual(self.plugin.page.urls, [])
+
+    def test_cleanup_and_stop_errors_never_pass(self):
+        self.plugin.cleanup.side_effect = RuntimeError("SECRET-PASSWORD")
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 3)
+        self.assertFalse(result["passed"])
+        self.assertEqual(result["reason"], "cleanup_failed")
+        self.plugin.cleanup.side_effect = None
+        self.plugin.page.urls.clear()
+        with patch.object(gate.CalendarRequestAudit, "stop", side_effect=RuntimeError("SECRET-PASSWORD")):
+            code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertFalse(result["passed"])
+        self.assertEqual(result["reason"], "audit_stop_failed")
+
+    def test_login_error_and_interrupt_are_sanitized_and_cleanup_runs(self):
+        for error, expected in ((RuntimeError("SECRET-PASSWORD"), 1), (KeyboardInterrupt(), 130)):
+            self.plugin.create_session.side_effect = error
+            self.plugin.cleanup.reset_mock()
+            self.assertEqual(self.run_gate()[0], expected)
+            self.plugin.cleanup.assert_called_once()
+            self.assertEqual(self.plugin.page.urls, [])
+
+    def test_parser_exception_reason_is_allowlisted(self):
+        with patch.object(gate, "read_reservation_listing", side_effect=ReservationReadError("SECRET-PASSWORD")):
+            self.assertEqual(self.run_gate()[1]["reason"], "receipt_read_rejected")
+
+    def test_unrecognized_list_date_adds_diagnostic_but_never_passes(self):
+        self.plugin.page.before["tables"][0]["rows"][0]["date"] = "2026-10-13"
+        code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "date_unrecognized")
+        self.assertEqual(result["stage"], "list_before")
+        self.assertTrue(result["dateDiagnostic"]["available"])
+        self.assertEqual(result["dateDiagnostic"]["samples"][0]["text"]["shape"], "DDDD-DD-DD")
+        self.assertEqual(self.plugin.page.diagnostic_reads, 1)
+        self.assertEqual(self.plugin.page.urls, [gate.LIST_URL])
+        self.assertTrue(result["auditVerified"])
+        self.plugin.cleanup.assert_called_once()
+
+    def test_failed_date_diagnostic_keeps_original_failure_and_cleanup(self):
+        self.plugin.page.before["tables"][0]["rows"][0]["date"] = "2026-10-13"
+        with patch.object(gate, "read_reservation_date_diagnostic", side_effect=RuntimeError("SECRET-PASSWORD")):
+            code, result, _ = self.run_gate()
+        self.assertEqual(code, 1)
+        self.assertEqual(result["reason"], "date_unrecognized")
+        self.assertEqual(result["dateDiagnostic"], {"available": False})
+        self.plugin.cleanup.assert_called_once()
+
+    def test_success_and_detail_failure_do_not_trigger_list_diagnostic(self):
+        self.assertEqual(self.run_gate()[0], 0)
+        self.assertEqual(self.plugin.page.diagnostic_reads, 0)
+        self.plugin.page.receipt["fields"]["Data"] = "2026-10-13"
+        self.plugin.page.urls.clear()
+        result = self.run_gate()[1]
+        self.assertEqual(result["reason"], "date_unrecognized")
+        self.assertEqual(result["stage"], "cancelled_detail")
+        self.assertIsNone(result["dateDiagnostic"])
+        self.assertEqual(self.plugin.page.diagnostic_reads, 0)
+
+    def test_browser_environment_restored(self):
+        with patch.dict(os.environ, {"CHROME_BIN": "/original/chrome"}):
+            self.assertEqual(self.run_gate()[0], 0)
+            self.assertEqual(os.environ["CHROME_BIN"], "/original/chrome")
+
+    def test_cli_default_and_preflight_do_not_execute(self):
+        for argv in ([], ["--preflight"]):
+            with patch.object(gate, "run_receipt_gate", return_value=0) as runner:
+                self.assertEqual(gate.main(argv), 0)
+                self.assertFalse(runner.call_args.kwargs["execute"])
+        with patch.object(gate, "run_receipt_gate", return_value=0) as runner:
+            gate.main(["--run", "--non-interactive"])
+            self.assertTrue(runner.call_args.kwargs["execute"])
+            self.assertTrue(runner.call_args.kwargs["non_interactive"])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 195 - 0
test/test_debug_ita_session.py

@@ -0,0 +1,195 @@
+import ast
+import io
+import json
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    _text_for_log,
+    _url_for_log,
+    build_local_query_session_config,
+    build_plugin_config,
+    run_preflight,
+    run_session,
+)
+
+
+class FakeDebugElement:
+    pass
+
+
+class FakeDebugPage:
+    url = (
+        "https://prenotami.esteri.it/UserArea"
+        "?state=sensitive-state#sensitive-fragment"
+    )
+
+    def ele(self, selector, timeout=None):
+        del timeout
+        if selector in {".app-menu", "@href=/Services"}:
+            return FakeDebugElement()
+        return None
+
+
+class FakeDebugPlugin:
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = FakeDebugPage()
+        self.instance_id = "offline"
+        self.cleanup_called = False
+        FakeDebugPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        return None
+
+    def cleanup(self):
+        self.cleanup_called = True
+
+
+class DebugItaSessionConfigTests(unittest.TestCase):
+    def test_builds_login_only_config_without_proxy_or_service_id(self):
+        config = build_plugin_config({}, username="test@example.com", password="secret")
+
+        self.assertEqual(config.account.username, "test@example.com")
+        self.assertEqual(config.proxy.ip, "")
+        self.assertEqual(config.free_config, {})
+        self.assertEqual(config.session_max_life, 900)
+
+    def test_rejects_partial_authenticated_proxy(self):
+        env = {
+            "ITA_PROXY_IP": "127.0.0.1",
+            "ITA_PROXY_PORT": "8080",
+            "ITA_PROXY_USERNAME": "proxy-user",
+        }
+
+        with self.assertRaisesRegex(
+            DebugConfigurationError,
+            "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD",
+        ):
+            build_plugin_config(env, username="test@example.com", password="secret")
+
+    def test_rejects_proxy_without_port(self):
+        with self.assertRaisesRegex(DebugConfigurationError, "ITA_PROXY_PORT"):
+            build_plugin_config(
+                {"ITA_PROXY_IP": "127.0.0.1"},
+                username="test@example.com",
+                password="secret",
+            )
+
+    def test_preflight_does_not_require_credentials(self):
+        chrome_path = Path("/test/chrome")
+        with patch("tools.debug_ita_session.resolve_chrome_path", return_value=chrome_path):
+            self.assertEqual(run_preflight({}), 0)
+
+    def test_local_query_login_config_uses_the_private_persistent_profile(self):
+        local_values = {
+            "username": "local-query@example.test",
+            "password": "offline-password",
+            "account_upload_token": "",
+        }
+        repo_root = Path(__file__).resolve().parents[1]
+        with tempfile.TemporaryDirectory(dir=repo_root) as temp_dir:
+            config_path = Path(temp_dir) / "ita_query_account.local.json"
+            config_path.write_text(json.dumps(local_values), encoding="utf-8")
+            config_path.chmod(0o600)
+            profile_path = Path(temp_dir) / "profile"
+            profile_path.mkdir(mode=0o700)
+
+            with (
+                patch(
+                    "tools.debug_ita_session.ITA_QUERY_ACCOUNT_FILE",
+                    config_path,
+                ),
+                patch(
+                    "tools.debug_ita_session.prepare_ita_query_profile",
+                    return_value=profile_path,
+                ),
+            ):
+                config = build_local_query_session_config({})
+
+        self.assertEqual(config.account.username, local_values["username"])
+        self.assertEqual(
+            config.free_config["persistent_browser_profile_path"],
+            str(profile_path),
+        )
+
+
+class DebugItaSessionSafetyTests(unittest.TestCase):
+    def test_url_logging_removes_dynamic_oauth_values(self):
+        self.assertEqual(
+            _url_for_log(
+                "https://iam.esteri.it/signin/"
+                "?state=sensitive-state&code_challenge=sensitive-challenge#/"
+            ),
+            "https://iam.esteri.it/signin/",
+        )
+        sanitized = _text_for_log(
+            "failed at https://iam.esteri.it/signin/"
+            "https%3A%2F%2Fiam.esteri.it%2Flogin"
+            "?state=sensitive-state&code_challenge=sensitive-challenge"
+        )
+        self.assertIn("https://iam.esteri.it/signin/<redacted>", sanitized)
+        self.assertNotIn("sensitive-state", sanitized)
+        self.assertNotIn("sensitive-challenge", sanitized)
+
+    def test_run_session_requires_user_area_markers_and_sanitizes_success_url(self):
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        env = {
+            "ITA_USERNAME": "offline-test@example.test",
+            "ITA_PASSWORD": "offline-password",
+        }
+
+        with (
+            patch(
+                "tools.debug_ita_session.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch("tools.debug_ita_session.ItaPlugin", FakeDebugPlugin),
+            patch.dict("tools.debug_ita_session.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_session(env, non_interactive=True)
+
+        self.assertEqual(exit_code, 0)
+        self.assertIn(
+            "ITA_SESSION_OK url=https://prenotami.esteri.it/UserArea",
+            stdout.getvalue(),
+        )
+        self.assertIn("ITA_SESSION_CLEANUP_OK", stdout.getvalue())
+        self.assertNotIn("sensitive-state", stdout.getvalue())
+        self.assertNotIn("sensitive-fragment", stdout.getvalue())
+        self.assertEqual(stderr.getvalue(), "")
+        self.assertTrue(FakeDebugPlugin.last_instance.cleanup_called)
+
+    def test_debug_entrypoint_never_calls_query_or_book(self):
+        source_path = (
+            Path(__file__).resolve().parents[1] / "tools" / "debug_ita_session.py"
+        )
+        tree = ast.parse(source_path.read_text(encoding="utf-8"))
+        forbidden_calls = [
+            node.func.attr
+            for node in ast.walk(tree)
+            if isinstance(node, ast.Call)
+            and isinstance(node.func, ast.Attribute)
+            and node.func.attr in {"query", "book"}
+        ]
+
+        self.assertEqual(forbidden_calls, [])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 558 - 0
test/test_debug_ita_soak.py

@@ -0,0 +1,558 @@
+import ast
+import io
+import json
+import os
+import stat
+import subprocess
+import sys
+import tempfile
+import unittest
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+
+from DrissionPage.errors import BrowserConnectError, PageDisconnectedError
+
+from plugins.ita_plugin import ItaTargetServiceLinkMissingError
+from tools.debug_ita_session import DebugConfigurationError
+from tools.debug_ita_soak import (
+    DAY_SECONDS,
+    DEFAULT_MAX_SESSION_ATTEMPTS,
+    DEFAULT_MAX_WAIT_SECONDS,
+    DEFAULT_MIN_WAIT_SECONDS,
+    run_soak,
+    write_soak_status,
+)
+from vs_types import (
+    AvailabilityStatus,
+    SessionExpiredOrInvalidError,
+    VSQueryResult,
+)
+
+
+class FakeClock:
+    def __init__(self):
+        self.now = 0.0
+
+    def monotonic(self):
+        return self.now
+
+    def wall_time(self):
+        return 1_800_000_000.0 + self.now
+
+    def sleep(self, seconds):
+        self.now += seconds
+
+
+class FakeSoakPage:
+    url = "https://prenotami.esteri.it/Services/Booking/1321"
+    title = "Index - Prenot@Mi"
+
+    def ele(self, _selector, timeout=None):
+        del timeout
+        return None
+
+    def run_js(self, _script):
+        return {
+            "path": "/Services/Booking/1321",
+            "form": {
+                "method": "POST",
+                "action_path": "/Services/Booking/1321",
+            },
+            "field_count": 0,
+            "fields": [],
+            "button_count": 0,
+            "buttons": [],
+        }
+
+
+class FakeSoakPlugin:
+    session_behaviors = [["none"]]
+    create_behaviors = ["ok"]
+    instances = []
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        session_index = len(self.instances)
+        configured_index = min(
+            session_index,
+            len(self.session_behaviors) - 1,
+        )
+        self.behaviors = list(self.session_behaviors[configured_index])
+        create_index = min(
+            session_index,
+            len(self.create_behaviors) - 1,
+        )
+        self.create_behavior = self.create_behaviors[create_index]
+        self.query_calls = 0
+        self.create_session_calls = 0
+        self.cleanup_calls = 0
+        self.page = FakeSoakPage()
+        self.last_booking_form_structure = None
+        self.last_service_list_structure = None
+        self.instances.append(self)
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        self.create_session_calls += 1
+        if self.create_behavior == "connect-error":
+            raise BrowserConnectError("offline browser connection failed")
+
+    def query(self, apt_type):
+        index = min(self.query_calls, len(self.behaviors) - 1)
+        behavior = self.behaviors[index]
+        self.query_calls += 1
+        if behavior == "missing-link":
+            self.last_service_list_structure = {
+                "path": "/Services",
+                "ready_state": "complete",
+                "table_count": 1,
+                "row_count": 0,
+                "booking_link_count": 0,
+                "target_link_count": 0,
+            }
+            raise ItaTargetServiceLinkMissingError(
+                "Italy target service link is missing after the bounded wait"
+            )
+        if behavior == "expired":
+            raise SessionExpiredOrInvalidError("offline session expired")
+        if behavior == "disconnected":
+            raise PageDisconnectedError("offline browser disconnected")
+        if behavior == "weak":
+            return VSQueryResult(
+                success=True,
+                apt_type=apt_type,
+                availability_status=AvailabilityStatus.NoneAvailable,
+            )
+        if behavior == "error":
+            raise RuntimeError(
+                "private@example.test token abcdefghijklmnopqrstuvwxyz123456"
+            )
+        return VSQueryResult(
+            success=False,
+            apt_type=apt_type,
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+
+    def cleanup(self):
+        self.cleanup_calls += 1
+
+
+class DebugItaSoakTests(unittest.TestCase):
+    def setUp(self):
+        FakeSoakPlugin.session_behaviors = [["none"]]
+        FakeSoakPlugin.create_behaviors = ["ok"]
+        FakeSoakPlugin.instances = []
+
+    @staticmethod
+    def _run(
+        *,
+        duration_seconds=120,
+        min_wait=60,
+        max_wait=60,
+        max_session_attempts=DEFAULT_MAX_SESSION_ATTEMPTS,
+        restart_wait=60,
+        sleep=None,
+    ):
+        clock = FakeClock()
+        statuses = []
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        if sleep is None:
+            sleep = clock.sleep
+        with (
+            patch(
+                "tools.debug_ita_soak.resolve_chrome_path",
+                return_value=Path("/test/chrome"),
+            ),
+            patch(
+                "tools.debug_ita_soak._get_query_credentials",
+                return_value=("query@example.test", "query-password"),
+            ) as credential_reader,
+            patch(
+                "tools.debug_ita_soak._prepare_query_profile",
+                return_value=Path("/offline/query-profile"),
+            ) as profile_preparer,
+            patch.dict("tools.debug_ita_soak.os.environ", {}, clear=False),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_soak(
+                {},
+                apply=True,
+                non_interactive=True,
+                duration_seconds=duration_seconds,
+                min_wait=min_wait,
+                max_wait=max_wait,
+                max_session_attempts=max_session_attempts,
+                restart_wait=restart_wait,
+                randint=lambda _minimum, _maximum: max_wait,
+                sleep=sleep,
+                monotonic=clock.monotonic,
+                wall_time=clock.wall_time,
+                plugin_factory=FakeSoakPlugin,
+                status_writer=lambda body: statuses.append(dict(body)),
+            )
+        return (
+            exit_code,
+            stdout.getvalue(),
+            stderr.getvalue(),
+            clock,
+            statuses,
+            credential_reader,
+            profile_preparer,
+        )
+
+    def test_accelerated_full_day_uses_one_session_and_completes(self):
+        result = self._run(
+            duration_seconds=DAY_SECONDS,
+            min_wait=DEFAULT_MAX_WAIT_SECONDS,
+            max_wait=DEFAULT_MAX_WAIT_SECONDS,
+        )
+        exit_code, stdout, stderr, clock, statuses, _, _ = result
+        plugin = FakeSoakPlugin.instances[0]
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(clock.now, DAY_SECONDS)
+        self.assertEqual(len(FakeSoakPlugin.instances), 1)
+        self.assertEqual(plugin.create_session_calls, 1)
+        self.assertEqual(plugin.query_calls, 288)
+        self.assertEqual(plugin.cleanup_calls, 1)
+        self.assertIn(
+            "ITA_SOAK_COMPLETED duration_seconds=86400 probes=288",
+            stdout,
+        )
+        self.assertIn("ITA_SOAK_CLEANUP_OK", stdout)
+        self.assertEqual(statuses[-1]["state"], "completed")
+        self.assertEqual(statuses[-1]["elapsed_seconds"], DAY_SECONDS)
+        self.assertEqual(statuses[-1]["exit_code"], 0)
+        self.assertEqual(stderr, "")
+
+    def test_accelerated_full_day_survives_many_normal_session_expirations(self):
+        FakeSoakPlugin.session_behaviors = [
+            ["none", "none", "expired"] for _ in range(200)
+        ]
+
+        result = self._run(
+            duration_seconds=DAY_SECONDS,
+            min_wait=DEFAULT_MAX_WAIT_SECONDS,
+            max_wait=DEFAULT_MAX_WAIT_SECONDS,
+        )
+        exit_code, stdout, stderr, clock, statuses, _, _ = result
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(clock.now, DAY_SECONDS)
+        self.assertGreaterEqual(statuses[-1]["session_expirations"], 96)
+        self.assertGreaterEqual(statuses[-1]["session_attempts"], 97)
+        self.assertEqual(
+            statuses[-1]["consecutive_session_expirations"],
+            0,
+        )
+        self.assertEqual(statuses[-1]["state"], "completed")
+        self.assertIn("ITA_SOAK_COMPLETED duration_seconds=86400", stdout)
+        self.assertNotIn("max-session-attempts-reached", stdout)
+        self.assertEqual(stderr, "")
+
+    def test_one_missing_link_is_recorded_then_next_probe_can_recover(self):
+        FakeSoakPlugin.session_behaviors = [["missing-link", "none"]]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run()
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(FakeSoakPlugin.instances[0].query_calls, 2)
+        self.assertIn("ITA_SOAK_TRANSIENT", stdout)
+        self.assertIn("consecutive=1 total=1", stdout)
+        self.assertIn("ITA_SERVICE_LIST_STRUCTURE=", stdout)
+        self.assertEqual(statuses[-1]["transient_errors"], 1)
+        self.assertEqual(stderr, "")
+
+    def test_second_consecutive_missing_link_stops_without_third_query(self):
+        FakeSoakPlugin.session_behaviors = [
+            ["missing-link", "missing-link", "none"]
+        ]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(FakeSoakPlugin.instances[0].query_calls, 2)
+        self.assertIn(
+            "ITA_SOAK_FAILED reason=consecutive-target-link-misses",
+            stdout,
+        )
+        self.assertEqual(statuses[-1]["state"], "failed")
+        self.assertEqual(statuses[-1]["exit_code"], 1)
+        self.assertEqual(stderr, "")
+
+    def test_expired_session_is_cleaned_then_recreated_after_safe_wait(self):
+        FakeSoakPlugin.session_behaviors = [["expired"], ["none"]]
+
+        exit_code, stdout, stderr, clock, statuses, _, _ = self._run()
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertEqual(FakeSoakPlugin.instances[0].cleanup_calls, 1)
+        self.assertEqual(FakeSoakPlugin.instances[1].cleanup_calls, 1)
+        self.assertEqual(clock.now, 120)
+        self.assertIn("ITA_SOAK_SESSION_EXPIRED", stdout)
+        self.assertIn("session_attempts=2", stdout)
+        self.assertEqual(statuses[-1]["session_attempts"], 2)
+        self.assertEqual(stderr, "")
+
+    def test_second_consecutive_session_expiration_stops_without_third_session(self):
+        FakeSoakPlugin.session_behaviors = [
+            ["expired"],
+            ["expired"],
+            ["none"],
+        ]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertIn(
+            "ITA_SOAK_FAILED reason=consecutive-session-expirations",
+            stdout,
+        )
+        self.assertEqual(statuses[-1]["session_expirations"], 2)
+        self.assertEqual(
+            statuses[-1]["consecutive_session_expirations"],
+            2,
+        )
+        self.assertEqual(statuses[-1]["state"], "failed")
+        self.assertEqual(stderr, "")
+
+    def test_reauthentication_rate_limit_stops_dense_login_loop(self):
+        FakeSoakPlugin.session_behaviors = [
+            ["none", "expired"] for _ in range(10)
+        ]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 1)
+        self.assertIn(
+            "ITA_SOAK_FAILED reason=reauthentication-rate-limit",
+            stdout,
+        )
+        self.assertEqual(statuses[-1]["session_expirations"], 7)
+        self.assertEqual(
+            statuses[-1]["session_reauthentications_last_hour"],
+            7,
+        )
+        self.assertEqual(statuses[-1]["state"], "failed")
+        self.assertEqual(stderr, "")
+
+    def test_disconnected_browser_is_cleaned_then_recreated_after_safe_wait(self):
+        FakeSoakPlugin.session_behaviors = [["disconnected"], ["none"]]
+
+        exit_code, stdout, stderr, clock, statuses, _, _ = self._run()
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertEqual(FakeSoakPlugin.instances[0].cleanup_calls, 1)
+        self.assertEqual(FakeSoakPlugin.instances[1].cleanup_calls, 1)
+        self.assertEqual(clock.now, 120)
+        self.assertIn("ITA_SOAK_BROWSER_DISCONNECTED", stdout)
+        self.assertIn("consecutive=1 total=1", stdout)
+        self.assertEqual(statuses[-1]["browser_disconnects"], 1)
+        self.assertEqual(statuses[-1]["session_attempts"], 2)
+        self.assertEqual(stderr, "")
+
+    def test_second_consecutive_browser_disconnect_stops_without_third_session(self):
+        FakeSoakPlugin.session_behaviors = [
+            ["disconnected"],
+            ["disconnected"],
+            ["none"],
+        ]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertEqual(FakeSoakPlugin.instances[0].cleanup_calls, 1)
+        self.assertEqual(FakeSoakPlugin.instances[1].cleanup_calls, 1)
+        self.assertIn(
+            "ITA_SOAK_FAILED reason=consecutive-browser-disconnects",
+            stdout,
+        )
+        self.assertEqual(statuses[-1]["browser_disconnects"], 2)
+        self.assertEqual(statuses[-1]["state"], "failed")
+        self.assertEqual(statuses[-1]["exit_code"], 1)
+        self.assertEqual(stderr, "")
+
+    def test_one_browser_connect_failure_is_retried_after_safe_wait(self):
+        FakeSoakPlugin.create_behaviors = ["connect-error", "ok"]
+        FakeSoakPlugin.session_behaviors = [["none"], ["none"]]
+
+        exit_code, stdout, stderr, clock, statuses, _, _ = self._run()
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertEqual(FakeSoakPlugin.instances[0].cleanup_calls, 1)
+        self.assertEqual(FakeSoakPlugin.instances[1].cleanup_calls, 1)
+        self.assertEqual(clock.now, 120)
+        self.assertIn("ITA_SOAK_BROWSER_CONNECT_FAILED", stdout)
+        self.assertIn("consecutive=1 total=1", stdout)
+        self.assertEqual(statuses[-1]["browser_connect_failures"], 1)
+        self.assertEqual(statuses[-1]["session_attempts"], 2)
+        self.assertEqual(stderr, "")
+
+    def test_second_browser_connect_failure_stops_without_third_attempt(self):
+        FakeSoakPlugin.create_behaviors = [
+            "connect-error",
+            "connect-error",
+            "ok",
+        ]
+
+        exit_code, stdout, stderr, _, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 1)
+        self.assertEqual(len(FakeSoakPlugin.instances), 2)
+        self.assertIn(
+            "ITA_SOAK_FAILED reason=consecutive-browser-connect-failures",
+            stdout,
+        )
+        self.assertEqual(statuses[-1]["browser_connect_failures"], 2)
+        self.assertEqual(statuses[-1]["state"], "failed")
+        self.assertEqual(statuses[-1]["exit_code"], 1)
+        self.assertEqual(stderr, "")
+
+    def test_weak_signal_stops_immediately_without_waiting_or_booking(self):
+        FakeSoakPlugin.session_behaviors = [["weak", "none"]]
+
+        exit_code, stdout, stderr, clock, statuses, _, _ = self._run(
+            duration_seconds=DAY_SECONDS
+        )
+
+        self.assertEqual(exit_code, 4)
+        self.assertEqual(clock.now, 0)
+        self.assertEqual(FakeSoakPlugin.instances[0].query_calls, 1)
+        self.assertIn("ITA_SOAK_WEAK_SIGNAL", stdout)
+        self.assertEqual(statuses[-1]["state"], "weak_signal")
+        self.assertEqual(statuses[-1]["exit_code"], 4)
+        self.assertEqual(stderr, "")
+
+    def test_default_preflight_reads_no_credentials_and_makes_no_session(self):
+        stdout = io.StringIO()
+        stderr = io.StringIO()
+        with (
+            patch(
+                "tools.debug_ita_soak._get_query_credentials",
+                side_effect=AssertionError("credentials must not be read"),
+            ),
+            redirect_stdout(stdout),
+            redirect_stderr(stderr),
+        ):
+            exit_code = run_soak(
+                {},
+                apply=False,
+                non_interactive=True,
+                duration_seconds=DAY_SECONDS,
+                min_wait=DEFAULT_MIN_WAIT_SECONDS,
+                max_wait=DEFAULT_MAX_WAIT_SECONDS,
+            )
+
+        self.assertEqual(exit_code, 0)
+        self.assertEqual(FakeSoakPlugin.instances, [])
+        self.assertIn("ITA_SOAK_PREFLIGHT_OK", stdout.getvalue())
+        self.assertIn("external_request=false", stdout.getvalue())
+        self.assertEqual(stderr.getvalue(), "")
+
+    def test_duration_over_one_day_is_rejected_before_credentials(self):
+        with (
+            patch(
+                "tools.debug_ita_soak._get_query_credentials",
+                side_effect=AssertionError("credentials must not be read"),
+            ),
+            self.assertRaises(DebugConfigurationError),
+        ):
+            run_soak(
+                {},
+                apply=True,
+                non_interactive=True,
+                duration_seconds=DAY_SECONDS + 1,
+                min_wait=DEFAULT_MIN_WAIT_SECONDS,
+                max_wait=DEFAULT_MAX_WAIT_SECONDS,
+            )
+
+    def test_status_file_is_private_and_contains_no_credentials(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            status_path = Path(temp_dir) / "ita_soak" / "status.json"
+            write_soak_status(
+                {
+                    "state": "running",
+                    "service_id": 1321,
+                    "elapsed_seconds": 60,
+                    "probes": 1,
+                },
+                status_path=status_path,
+            )
+            body = status_path.read_text(encoding="utf-8")
+
+            self.assertEqual(json.loads(body)["state"], "running")
+            self.assertNotIn("username", body.lower())
+            self.assertNotIn("password", body.lower())
+            self.assertNotIn("cookie", body.lower())
+            if os.name == "posix":
+                self.assertEqual(
+                    stat.S_IMODE(status_path.parent.stat().st_mode),
+                    0o700,
+                )
+                self.assertEqual(
+                    stat.S_IMODE(status_path.stat().st_mode),
+                    0o600,
+                )
+
+    def test_cli_default_is_zero_network_preflight(self):
+        repo_root = Path(__file__).resolve().parents[1]
+        completed = subprocess.run(
+            [sys.executable, str(repo_root / "tools" / "debug_ita_soak.py")],
+            cwd=repo_root,
+            check=False,
+            capture_output=True,
+            text=True,
+        )
+
+        self.assertEqual(completed.returncode, 0)
+        self.assertIn("ITA_SOAK_PREFLIGHT_OK", completed.stdout)
+        self.assertIn("duration_seconds=86400", completed.stdout)
+        self.assertIn("external_request=false", completed.stdout)
+        self.assertEqual(completed.stderr, "")
+
+    def test_source_has_one_query_call_and_no_book_call(self):
+        source_path = (
+            Path(__file__).resolve().parents[1] / "tools" / "debug_ita_soak.py"
+        )
+        tree = ast.parse(source_path.read_text(encoding="utf-8"))
+        query_calls = []
+        book_calls = []
+        for node in ast.walk(tree):
+            if not isinstance(node, ast.Call):
+                continue
+            if not isinstance(node.func, ast.Attribute):
+                continue
+            if node.func.attr == "query":
+                query_calls.append(node)
+            if node.func.attr == "book":
+                book_calls.append(node)
+
+        self.assertEqual(len(query_calls), 1)
+        self.assertEqual(book_calls, [])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 197 - 0
test/test_ita_booker_integration.py

@@ -0,0 +1,197 @@
+"""Prepared public Book -> native final adapter -> receipts -> original Booker.
+
+Only external boundaries are synthetic: browser/packets, passive CDP audit,
+Redis, cloud and the executor queue. No credentials or network are used.
+"""
+import json
+import threading
+import unittest
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins import ita_workflow
+from plugins.ita_booking_final import FINAL_PATH, NATIVE_FINAL_SCRIPT
+from test import test_ita_calendar_book_flow as flow
+from test.test_ita_final_read_port import Browser
+from test.test_ita_plugin import OrderBookerGCO
+from test.test_ita_reservation import confirmed_detail, confirmed_listing
+
+
+class FinalPage(flow.FlowPage):
+    def __init__(self):
+        super().__init__([flow.month("2026-09", {1: 0}), flow.month("2026-10", {13: 2})])
+        self.url += "?selectedService=Visti%20Nazionali%20e%20Schengen"
+        self.browser = Browser()
+        self.final_count = 0
+        self.create_receipt = True
+        self.response_error = ""
+        self.wrong_request_day = False
+
+    def run_js(self, script, *args):
+        if script != NATIVE_FINAL_SCRIPT:
+            return super().run_js(script, *args)
+        service, day, daily_id, time_label, capacity = args
+        assert service == self.service and self.active and day == self.selected_day
+        self.final_count += 1
+        if self.create_receipt:
+            raw, detail = confirmed_listing(), confirmed_detail()
+            raw["tables"][0]["rows"][1].update(date="13 ottobre 2026", time="10:25")
+            detail["fields"].update(Data="13 ottobre 2026", Ora="10:25")
+            self.browser.raw = raw
+            self.browser.receipts[raw["tables"][0]["rows"][1]["detailUrl"]] = detail
+        self.listen.queue.append(SimpleNamespace(
+            url="https://prenotami.esteri.it" + FINAL_PATH, method="POST",
+            tab_id=self.tab_id, is_failed=False,
+            request=SimpleNamespace(postData={
+                "idCalendarioGiornaliero": daily_id,
+                "selectedDay": "2026-10-14" if self.wrong_request_day else day,
+                "selectedHour": f"{time_label}\n({capacity})",
+            }),
+            response=SimpleNamespace(status=200, raw_body=json.dumps({
+                "errorMessage": self.response_error, "url": "/Reservation",
+            })),
+        ))
+        return {"clicked": True}
+
+
+class BookerIntegrationTests(unittest.TestCase):
+    def setUp(self):
+        self.page = FinalPage()
+        self.plugin, self.route, self.trigger = flow.prepared_plugin(self.page)
+        self.plugin.free_config.update(otp_mode="manual", final_submit_enabled=True)
+        self.plugin.is_healthy = True
+        self.plugin._log = Mock()
+        self.addCleanup(setattr, self.plugin, "_cleanup_attempted", True)
+        self.inputs = {"username": self.plugin.config.account.username,
+                       "password": "synthetic-not-for-reporting",
+                       "expected_start_date": "2026-09-01", "expected_end_date": "2026-10-31"}
+        self.task = SimpleNamespace(task_ref=991, book_allowed=True, instance=self.plugin)
+        self.booker = OrderBookerGCO.__new__(OrderBookerGCO)
+        self.booker.m_lock = threading.RLock()
+        self.booker.m_tasks = [self.task]
+        self.booker.m_task_data_cache = {"991": {
+            "status": "processing", "order_id": "SYNTHETIC-ORDER", "user_inputs": self.inputs,
+        }}
+        self.booker.m_tracker_key = "synthetic-tracker"
+        self.booker.redis_client = Mock()
+        self.booker._log = Mock()
+        self.booker._cleanup_task = Mock()
+        self.cloud = Mock()
+        self.queue = []
+        self.executor = Mock()
+        self.executor.enqueue.side_effect = self.queue.append
+        self.enterContext(patch.dict(self.booker._execute_book_job.__func__.__globals__,
+            VSCloudApi=SimpleNamespace(Instance=lambda: self.cloud),
+            ThreadPool=SimpleNamespace(getInstance=lambda: self.executor)))
+        self.audit = Mock()
+        self.audit.settled_snapshot.side_effect = lambda: {
+            "otpRequests": 0, "avantiPosts": 0, "availabilityRequests": 0,
+            "timeSlotRequests": 0, "finalRequests": self.page.final_count,
+        }
+        self.enterContext(patch.object(ita_workflow.preparation, "CalendarRequestAudit", return_value=self.audit))
+        self.enterContext(flow.browser_navigation(self.page))
+
+    def run_booker(self):
+        self.booker._execute_book_job(self.task, self.trigger)
+
+    def drain_reports(self):
+        while self.queue:
+            self.queue.pop(0)()
+
+    def test_real_final_receipt_result_reaches_original_async_cloud_payload(self):
+        self.run_booker()
+        self.assertEqual(self.page.final_count, 1)
+        self.assertEqual(self.plugin._production_final_attempt.state, "confirmed")
+        self.assertEqual(self.page.month_clicks, 1)
+        self.assertEqual(len(self.queue), 1)
+        self.cloud.update_vas_task.assert_not_called()  # Original async boundary.
+        self.assertEqual(self.booker.m_tasks, [])
+        self.booker._cleanup_task.assert_called_once_with(self.task, "booking success")
+        self.drain_reports()
+        self.cloud.update_vas_task.assert_called_once()
+        task_id, payload = self.cloud.update_vas_task.call_args.args
+        self.assertEqual(task_id, "991")
+        self.assertEqual(payload["status"], "grabbed")
+        history = payload["grabbed_history"]
+        self.assertEqual(history["urn"], "CONFIRMED-SYNTHETIC")
+        self.assertEqual(history["account"], self.inputs["username"].lower())
+        self.assertEqual(history["slot_date"], "2026-10-13")
+        self.assertEqual(history["slot_time"], "10:25")  # Assigned time, not 10:05–11:05.
+        self.assertEqual(history["payment_link"], "")
+        self.assertNotIn(self.inputs["password"], json.dumps(payload))
+        self.cloud.push_weixin_text.assert_called_once()
+        self.assertIn("SYNTHETIC-ORDER", self.cloud.push_weixin_text.call_args.args[0])
+        self.booker.redis_client.zrem.assert_called_once_with("synthetic-tracker", 991)
+        self.assertTrue(all(tab.close.call_count == 1 for tab in self.page.browser.pages))
+
+    def test_prefinal_does_not_update_order_or_notify(self):
+        self.plugin.free_config["final_submit_enabled"] = False
+        self.run_booker()
+        self.assertIsNotNone(self.plugin.last_booking_precommit)
+        self.assertEqual(self.page.final_count, 0)
+        self.assertEqual(self.booker.m_tasks, [self.task])
+        self.executor.enqueue.assert_not_called()
+        self.cloud.update_vas_task.assert_not_called()
+
+    def test_order_date_preferences_reach_production_selection(self):
+        self.inputs["expected_end_date"] = "2026-10-12"
+        self.run_booker()
+        self.assertIsNone(self.plugin.last_booking_precommit)
+        self.assertEqual(self.page.final_count, 0)
+        self.executor.enqueue.assert_not_called()
+        self.cloud.update_vas_task.assert_not_called()
+
+    def test_definite_rejection_keeps_original_retry_branch_without_success(self):
+        self.page.create_receipt, self.page.response_error = False, "Synthetic slot no longer available"
+        self.run_booker()
+        self.assertEqual(self.page.final_count, 1)
+        self.assertEqual(self.plugin._production_final_attempt.state, "rejected")
+        self.assertEqual(self.booker.m_tasks, [self.task])
+        self.assertTrue(self.task.book_allowed)
+        self.executor.enqueue.assert_not_called()
+        self.cloud.update_vas_task.assert_not_called()
+
+    def test_unknown_after_write_pauses_order_and_next_signal_never_resubmits(self):
+        self.page.create_receipt = False
+        self.run_booker()
+        self.run_booker()
+        self.assertEqual(self.page.final_count, 1)
+        self.assertFalse(self.task.book_allowed)
+        self.cloud.update_vas_task.assert_called_once_with("991", {"status": "pause"})
+        self.assertEqual(self.booker.m_tasks, [])
+        self.cloud.push_weixin_text.assert_not_called()
+        self.executor.enqueue.assert_not_called()
+
+    def test_unmatched_request_cannot_report_success_even_with_confirmed_receipt(self):
+        self.page.wrong_request_day = True
+        self.run_booker()
+        self.assertEqual(self.page.final_count, 1)
+        self.cloud.update_vas_task.assert_called_once_with("991", {"status": "pause"})
+        self.executor.enqueue.assert_not_called()
+
+    def test_executor_enqueue_failure_can_retry_cached_result_without_another_booking(self):
+        self.executor.enqueue.side_effect = RuntimeError("synthetic executor unavailable")
+        self.run_booker()
+        self.assertEqual(self.booker.m_tasks, [self.task])
+        self.assertEqual(self.page.final_count, 1)
+        self.executor.enqueue.side_effect = self.queue.append
+        self.run_booker()
+        self.drain_reports()
+        self.assertEqual(self.page.final_count, 1)
+        self.cloud.update_vas_task.assert_called_once()
+        self.assertEqual(self.booker.m_tasks, [])
+
+    def test_cloud_failure_is_not_a_verified_cloud_success(self):
+        # Existing VFS/BLS semantics: queue accepted != cloud acknowledged.
+        # Document this shared limitation; do not invent an Italy-only queue.
+        self.cloud.update_vas_task.side_effect = RuntimeError("synthetic cloud unavailable")
+        self.run_booker()
+        self.drain_reports()
+        self.assertEqual(self.page.final_count, 1)
+        self.cloud.push_weixin_text.assert_not_called()
+        self.assertTrue(any("Failed to update success state" in call.args[0]
+                            for call in self.booker._log.call_args_list))
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 615 - 0
test/test_ita_booking_final.py

@@ -0,0 +1,615 @@
+"""Offline final-stage contracts; reservation records are synthetic, not site fixtures."""
+
+import ast
+import json
+import shutil
+import subprocess
+import time
+import traceback
+import unittest
+from dataclasses import replace
+from datetime import date
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock
+from urllib.parse import urlencode
+
+from plugins.ita_booking_final import (
+    FINAL_PATH, NATIVE_FINAL_SCRIPT, FinalBookingAttempt, FinalBookingError,
+    FinalOutcomeUnknown, FinalTarget, NativeFinalSubmitter, ReservationRecord,
+    ReservationSnapshot, ReservationState, SubmissionSignal, classify_final_packet,
+)
+from plugins.ita_calendar_book import CalendarBookError, select_slot_before_final, verify_precommit_selection
+from test.test_ita_calendar_book import DAY, SERVICE, FakePage, packets
+
+
+def target():
+    page = FakePage()
+    approval = select_slot_before_final(
+        page, target_day=DAY, availability_packet=packets()[0], time_slots_packet=packets()[1],
+    )
+    return FinalTarget("applicant@example.test", "synthetic-session", "applicant-tab",
+                       "slot.fixture.it.tourist", "7001", SERVICE, approval)
+
+
+def receipt(state=ReservationState.ACTIVE, reference="NEW-1", **changes):
+    return replace(ReservationRecord(reference, "7001", DAY, "10:05 - 11:05", state), **changes)
+
+
+def final_packet(booking_target=None, *, error="", destination="/Reservation"):
+    booking_target = booking_target or target()
+    slot = booking_target.approval.candidate
+    return SimpleNamespace(
+        url="https://prenotami.esteri.it" + FINAL_PATH, method="POST",
+        tab_id=booking_target.tab_id, is_failed=False,
+        request=SimpleNamespace(postData={
+            "idCalendarioGiornaliero": slot.daily_calendar_id,
+            "selectedDay": slot.day.isoformat(), "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
+        }),
+        response=SimpleNamespace(status=200, raw_body=json.dumps({"errorMessage": error, "url": destination})),
+    )
+
+
+class ReadPort:
+    def __init__(self, booking_target, records=()):
+        self.target = booking_target
+        self.records = records
+        self.calls = 0
+        self.error = None
+        self.overrides = {}
+
+    def __call__(self):
+        self.calls += 1
+        if self.error:
+            raise self.error
+        return replace(ReservationSnapshot(
+            self.target.applicant, self.target.session_key, time.monotonic(), True, self.records,
+        ), **self.overrides)
+
+
+class FinalFlowTests(unittest.TestCase):
+    def setUp(self):
+        self.target = target()
+        self.reader = ReadPort(self.target)
+        self.current = Mock(return_value=True)
+        self.signal = SubmissionSignal.ACCEPTED
+        self.after = (receipt(),)
+        self.submission_error = None
+        self.after_hook = None
+        self.submit = Mock(side_effect=self._submit)
+        self.attempt = FinalBookingAttempt(
+            self.target, read_reservations=self.reader, submit_native=self.submit,
+            session_is_current=self.current,
+        )
+
+    def _submit(self):
+        self.reader.records = self.after
+        if self.after_hook:
+            self.after_hook()
+        if self.submission_error:
+            raise self.submission_error
+        return self.signal
+
+    def test_disabled_by_default_and_truthy_values_do_not_authorize(self):
+        for enabled in (False, None, 1, "true"):
+            with self.subTest(enabled=enabled), self.assertRaises(FinalBookingError):
+                self.attempt.execute(enabled=enabled)
+        self.assertEqual(self.reader.calls, 0)
+        self.submit.assert_not_called()
+        self.assertEqual(self.attempt.state, "ready")
+
+    def test_confirmed_new_record_returns_existing_framework_result(self):
+        result = self.attempt.execute(enabled=True)
+        self.assertTrue(result.success)
+        self.assertEqual(result.urn, "NEW-1")
+        self.assertEqual(result.account, self.target.applicant)
+        self.assertEqual(result.book_date, DAY.isoformat())
+        self.assertEqual(result.book_time, "10:05 - 11:05")
+        self.assertEqual(self.attempt.state, "confirmed")
+        self.assertEqual(self.reader.calls, 2)
+        self.submit.assert_called_once_with()
+
+    def test_cancelled_history_is_preserved_but_does_not_block(self):
+        old = receipt(ReservationState.CANCELLED, "OLD-1")
+        self.reader.records = (old,)
+        self.after = (old, receipt())
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+
+    def test_cancelled_history_may_have_only_an_assigned_appointment_time(self):
+        old = receipt(ReservationState.CANCELLED, "OLD-TIME", time_label=None, appointment_time="10:25")
+        self.reader.records = (old,)
+        self.after = (old, receipt())
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+        self.submit.assert_called_once_with()
+
+    def test_unbound_cancelled_history_requires_fingerprint_and_is_preserved(self):
+        old = receipt(ReservationState.CANCELLED, "OLD-UNBOUND", service_id=None,
+                      time_label=None, appointment_time="10:25", receipt_fingerprint="a" * 64)
+        self.reader.records = (old,)
+        self.after = (old, receipt())
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+
+    def test_missing_service_never_allows_live_or_untracked_history(self):
+        cases = [(ReservationState.ACTIVE, "a" * 64), (ReservationState.WAITLIST, "a" * 64),
+                 (ReservationState.CANCELLED, None), (ReservationState.CANCELLED, "SECRET"),
+                 (ReservationState.CANCELLED, True)]
+        for state, fingerprint in cases:
+            self.setUp()
+            self.reader.records = (receipt(state, service_id=None, receipt_fingerprint=fingerprint),)
+            with self.assertRaises(FinalBookingError):
+                self.attempt.execute(enabled=True)
+            self.submit.assert_not_called()
+
+    def test_assigned_time_alone_never_proves_new_booking_slot(self):
+        for assigned in ("10:05", "10:25", "11:05", "14:00"):
+            with self.subTest(assigned=assigned):
+                self.setUp()
+                self.after = (receipt(time_label=None, appointment_time=assigned),)
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt.execute(enabled=True)
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt.reconcile()
+                self.submit.assert_called_once_with()
+
+    def test_existing_active_point_time_record_still_blocks_submission(self):
+        self.reader.records = (receipt(time_label=None, appointment_time="10:25"),)
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.submit.assert_not_called()
+
+    def test_independently_bound_interval_preserves_assigned_receipt_time(self):
+        # Synthetic trusted read-port data, NOT proof the website supplies an interval.
+        self.after = (receipt(appointment_time="10:25"),)
+        self.assertEqual(self.attempt.execute(enabled=True).book_time, "10:25")
+
+    def test_conflicting_interval_and_assigned_time_is_not_confirmed(self):
+        self.after = (receipt(appointment_time="14:00"),)
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+        self.submit.assert_called_once_with()
+
+    def test_missing_or_malformed_assigned_time_blocks_baseline(self):
+        for assigned in (None, "", "24:00", "10:25:00", True, "10:25\n"):
+            with self.subTest(assigned=assigned):
+                self.setUp()
+                self.reader.records = (receipt(ReservationState.CANCELLED, time_label=None, appointment_time=assigned),)
+                with self.assertRaises(FinalBookingError):
+                    self.attempt.execute(enabled=True)
+                self.submit.assert_not_called()
+
+    def test_other_service_active_record_does_not_count_as_target_booking(self):
+        other = receipt(reference="OTHER", service_id="8001")
+        self.reader.records = (other,)
+        self.after = (other, receipt())
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+
+    def test_active_or_waitlist_blocks_before_submission(self):
+        for state in (ReservationState.ACTIVE, ReservationState.WAITLIST):
+            with self.subTest(state=state):
+                self.setUp()
+                self.reader.records = (receipt(state),)
+                with self.assertRaisesRegex(FinalBookingError, "active reservation or waitlist"):
+                    self.attempt.execute(enabled=True)
+                self.submit.assert_not_called()
+                self.assertEqual(self.attempt.state, "blocked")
+
+    def test_malformed_or_incomplete_baseline_blocks(self):
+        cases = [
+            {"complete": False}, {"complete": 1}, {"applicant": "another@example.test"},
+            {"session_key": "older-session"}, {"captured_at": 0}, {"captured_at": float("nan")},
+            {"captured_at": float("inf")}, {"captured_at": True},
+            {"records": []}, {"records": (receipt(ReservationState.UNKNOWN),)},
+            {"records": (receipt(), receipt())}, {"records": (receipt(reference=""),)},
+            {"records": (receipt(state="cancelled"),)}, {"records": (receipt(time_label="25:00 - 26:00"),)},
+            {"records": (receipt(time_label="11:05 - 10:05"),)},
+        ]
+        for overrides in cases:
+            with self.subTest(fields=list(overrides)):
+                self.setUp()
+                self.reader.overrides = overrides
+                with self.assertRaises(FinalBookingError):
+                    self.attempt.execute(enabled=True)
+                self.submit.assert_not_called()
+
+    def test_account_change_before_submission_blocks(self):
+        self.current.return_value = False
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.submit.assert_not_called()
+
+    def test_account_change_during_baseline_read_blocks(self):
+        self.current.side_effect = [True, False]
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.submit.assert_not_called()
+
+    def test_reader_exception_is_sanitized(self):
+        self.reader.error = RuntimeError("secret-raw-password")
+        with self.assertRaises(FinalBookingError) as caught:
+            self.attempt.execute(enabled=True)
+        self.assertNotIn("secret", str(caught.exception))
+        self.assertNotIn("secret", "".join(traceback.format_exception(caught.exception)))
+        self.submit.assert_not_called()
+
+    def test_explicit_rejection_and_no_record_returns_failure_without_retry(self):
+        self.signal = SubmissionSignal.REJECTED
+        self.after = ()
+        result = self.attempt.execute(enabled=True)
+        self.assertFalse(result.success)
+        self.assertEqual(result.label, "italy-final-rejected")
+        self.assertEqual(self.attempt.state, "rejected")
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.submit.assert_called_once_with()
+
+    def test_timeout_after_write_can_be_confirmed_by_fresh_record(self):
+        self.submission_error = TimeoutError("lost acknowledgement")
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+        self.submit.assert_called_once_with()
+
+    def test_unknown_response_cannot_be_reported_as_plain_no_availability(self):
+        self.signal, self.after = SubmissionSignal.UNKNOWN, ()
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+        self.assertEqual(self.attempt.state, "unknown")
+
+    def test_accepted_without_receipt_is_unknown_and_only_readback_can_resume(self):
+        self.after = ()
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.reader.records = (receipt(),)
+        self.assertTrue(self.attempt.reconcile().success)
+        self.submit.assert_called_once_with()
+        self.assertEqual(self.reader.calls, 3)
+
+    def test_unknown_reconciliation_never_submits(self):
+        self.after = ()
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+        for _ in range(2):
+            with self.assertRaises(FinalOutcomeUnknown):
+                self.attempt.reconcile()
+        self.submit.assert_called_once_with()
+
+    def test_mismatches_and_multiple_records_are_unknown(self):
+        cases = [
+            (receipt(service_id="wrong-service"),),
+            (receipt(day=date(2026, 10, 14)),),
+            (receipt(time_label="11:15 - 12:40"),),
+            (receipt(ReservationState.CANCELLED),),
+            (receipt(ReservationState.WAITLIST),),
+            (receipt(), receipt(reference="SECOND")),
+            (receipt(), receipt(reference="UNRELATED", service_id="another")),
+        ]
+        for records in cases:
+            with self.subTest(records=len(records)):
+                self.setUp()
+                self.after = records
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt.execute(enabled=True)
+                self.submit.assert_called_once_with()
+
+    def test_rejection_conflicting_with_receipt_is_unknown(self):
+        self.signal = SubmissionSignal.REJECTED
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+
+    def test_removed_or_changed_cancelled_history_is_not_count_based_success(self):
+        for records in ((receipt(),), (receipt(reference="OLD"),)):
+            with self.subTest(records=records):
+                self.setUp()
+                self.reader.records = (receipt(ReservationState.CANCELLED, "OLD"),)
+                self.after = records
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt.execute(enabled=True)
+
+    def test_after_read_failures_remain_unknown_and_sanitized(self):
+        self.after_hook = lambda: setattr(self.reader, "error", RuntimeError("secret-response-token"))
+        with self.assertRaises(FinalOutcomeUnknown) as caught:
+            self.attempt.execute(enabled=True)
+        self.assertNotIn("secret", "".join(traceback.format_exception(caught.exception)))
+        self.assertEqual(self.attempt.state, "unknown")
+
+    def test_after_identity_change_is_unknown(self):
+        self.after_hook = lambda: self.reader.overrides.update(applicant="other@example.test")
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt.execute(enabled=True)
+
+    def test_success_and_blocked_attempts_cannot_be_reused(self):
+        self.attempt.execute(enabled=True)
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        with self.assertRaises(FinalBookingError):
+            self.attempt.reconcile()
+        self.submit.assert_called_once_with()
+
+    def test_reentrant_submission_is_rejected(self):
+        def reentrant():
+            with self.assertRaises(FinalBookingError):
+                self.attempt.execute(enabled=True)
+            with self.assertRaises(FinalBookingError):
+                self.attempt.reconcile()
+        self.after_hook = reentrant
+        self.assertTrue(self.attempt.execute(enabled=True).success)
+        self.submit.assert_called_once_with()
+
+    def test_interrupted_write_can_only_resume_read_only(self):
+        self.submission_error = KeyboardInterrupt()
+        with self.assertRaises(KeyboardInterrupt):
+            self.attempt.execute(enabled=True)
+        self.assertEqual(self.attempt.state, "unknown")
+        with self.assertRaises(FinalBookingError):
+            self.attempt.execute(enabled=True)
+        self.assertTrue(self.attempt.reconcile().success)
+        self.submit.assert_called_once_with()
+
+    def test_interrupted_preflight_stays_blocked_without_submission(self):
+        self.reader.error = KeyboardInterrupt()
+        with self.assertRaises(KeyboardInterrupt):
+            self.attempt.execute(enabled=True)
+        self.assertEqual(self.attempt.state, "blocked")
+        self.submit.assert_not_called()
+
+    def test_objects_do_not_expose_identifiers_in_repr(self):
+        self.assertNotIn(self.target.applicant, repr(self.target))
+        self.assertNotIn("NEW-1", repr(receipt()))
+        self.assertNotIn(self.target.applicant, repr(self.reader()))
+
+
+class FinalPacketTests(unittest.TestCase):
+    def setUp(self):
+        self.target = target()
+
+    def test_known_static_schema_is_only_a_hint(self):
+        self.assertIs(classify_final_packet(final_packet(self.target), self.target), SubmissionSignal.ACCEPTED)
+        self.assertIs(classify_final_packet(final_packet(self.target, error="Qualsiasi errore"), self.target),
+                      SubmissionSignal.REJECTED)
+
+    def test_form_urlencoded_native_whitespace_is_accepted(self):
+        packet = final_packet(self.target)
+        packet.request.postData = urlencode(packet.request.postData)
+        self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.ACCEPTED)
+
+    def test_mismatched_metadata_is_unknown(self):
+        for field, value in (
+            ("url", "https://attacker.test" + FINAL_PATH), ("url", "https://prenotami.esteri.it/elsewhere"),
+            ("url", "https://prenotami.esteri.it" + FINAL_PATH + "?unexpected=1"),
+            ("method", "GET"), ("tab_id", "other-tab"), ("is_failed", True),
+        ):
+            with self.subTest(field=field):
+                packet = final_packet(self.target)
+                setattr(packet, field, value)
+                self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.UNKNOWN)
+
+    def test_non_200_is_unknown_even_for_auth_or_rate_limit(self):
+        for status in (True, "200", 302, 400, 401, 403, 409, 429, 500):
+            with self.subTest(status=status):
+                packet = final_packet(self.target)
+                packet.response.status = status
+                self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.UNKNOWN)
+
+    def test_wrong_request_values_or_extra_fields_are_unknown(self):
+        for key, value in (
+            ("idCalendarioGiornaliero", "123"), ("selectedDay", "2026-10-14"),
+            ("selectedHour", "10:05 - 11:05(0)"), ("selectedHour", None), ("extra", "secret"),
+        ):
+            with self.subTest(key=key):
+                packet = final_packet(self.target)
+                packet.request.postData[key] = value
+                self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.UNKNOWN)
+
+    def test_duplicate_post_field_is_unknown(self):
+        packet = final_packet(self.target)
+        packet.request.postData = urlencode(packet.request.postData) + "&selectedDay=2026-10-13"
+        self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.UNKNOWN)
+
+    def test_invalid_response_is_unknown_without_disclosing_text(self):
+        for raw in ("<html>secret</html>", "null", "[]", "{}", '{"errorMessage": ""}',
+                    '{"errorMessage": null, "url": "/Reservation"}',
+                    '{"errorMessage": "", "errorMessage": "secret", "url": "/Reservation"}',
+                    '{"errorMessage": "", "url": "https://attacker.test"}', "x" * 1_000_001):
+            with self.subTest(length=len(raw)):
+                packet = final_packet(self.target)
+                packet.response.raw_body = raw
+                self.assertIs(classify_final_packet(packet, self.target), SubmissionSignal.UNKNOWN)
+
+
+class NativePage(FakePage):
+    def __init__(self, booking_target):
+        super().__init__()
+        self.tab_id = booking_target.tab_id
+        self.active = True
+        self.final_clicks = 0
+        self.final_ack = True
+        self.final_exception = None
+        self.final_packet = final_packet(booking_target)
+        self.listen = SimpleNamespace(
+            start=Mock(), wait=Mock(side_effect=lambda **kwargs: self.final_packet), stop=Mock(),
+        )
+
+    def run_js(self, script, *args):
+        if script == NATIVE_FINAL_SCRIPT:
+            self.listen.start.assert_called_once_with(FINAL_PATH, method="POST")
+            if self.final_exception:
+                raise self.final_exception
+            self.final_clicks += int(self.final_ack)
+            return {"clicked": self.final_ack}
+        return super().run_js(script, *args)
+
+
+class NativeFinalTests(unittest.TestCase):
+    def setUp(self):
+        self.target = target()
+        self.page = NativePage(self.target)
+        self.current = Mock(return_value=True)
+        self.submit = NativeFinalSubmitter(self.page, self.target, self.current)
+
+    def test_real_adapter_uses_existing_listener_and_one_native_click(self):
+        self.assertIs(self.submit(), SubmissionSignal.ACCEPTED)
+        self.assertEqual(self.page.final_clicks, 1)
+        self.assertEqual(self.page.clicks, 0)
+        self.page.listen.stop.assert_called_once_with()
+        with self.assertRaises(FinalBookingError):
+            self.submit()
+        self.assertEqual(self.page.final_clicks, 1)
+
+    def test_wrong_context_or_unselected_slot_never_clicks(self):
+        for change in (lambda: setattr(self.page, "tab_id", "other"),
+                       lambda: setattr(self.page, "url", "https://attacker.test/BookingCalendar"),
+                       lambda: setattr(self.page, "service", "other"),
+                       lambda: setattr(self.page, "active", False),
+                       lambda: setattr(self.current, "return_value", False)):
+            self.setUp()
+            change()
+            self.assertIs(self.submit(), SubmissionSignal.UNKNOWN)
+            self.assertEqual(self.page.final_clicks, 0)
+
+    def test_context_change_after_listener_start_does_not_click(self):
+        self.current.side_effect = [True, False]
+        self.assertIs(self.submit(), SubmissionSignal.UNKNOWN)
+        self.assertEqual(self.page.final_clicks, 0)
+        self.page.listen.stop.assert_called_once_with()
+
+    def test_no_packet_or_browser_ack_is_unknown_without_retry(self):
+        for mode in ("timeout", "no_ack", "exception"):
+            with self.subTest(mode=mode):
+                self.setUp()
+                if mode == "timeout":
+                    self.page.final_packet = None
+                elif mode == "no_ack":
+                    self.page.final_ack = False
+                else:
+                    self.page.final_exception = RuntimeError("secret")
+                self.assertIs(self.submit(), SubmissionSignal.UNKNOWN)
+                self.page.listen.stop.assert_called_once_with()
+                with self.assertRaises(FinalBookingError):
+                    self.submit()
+                self.assertLessEqual(self.page.final_clicks, 1)
+
+    def test_precommit_readback_is_read_only(self):
+        self.assertEqual(verify_precommit_selection(
+            self.page, runtime_service=SERVICE, approval=self.target.approval,
+        ), self.target.approval)
+        self.assertEqual(self.page.clicks, 0)
+        self.assertEqual(self.page.final_clicks, 0)
+
+    def test_changed_candidate_is_not_reselected_during_readback(self):
+        for changes in ({"candidateReady": False}, {"dayNegative": True},
+                        {"activeCapacityMatches": False}, {"activeIdMatches": False},
+                        {"activeCount": 2}, {"activeTimeMatches": False}):
+            with self.subTest(changes=changes):
+                self.page.overrides = changes
+                with self.assertRaises(CalendarBookError):
+                    verify_precommit_selection(self.page, runtime_service=SERVICE, approval=self.target.approval)
+                self.assertEqual(self.page.clicks, 0)
+                self.assertEqual(self.page.final_clicks, 0)
+
+
+class ProductionBoundaryTests(unittest.TestCase):
+    def test_production_final_flag_still_rejected_without_browser_creation(self):
+        from plugins.ita_plugin import ItaPlugin
+        from vs_types import BizLogicError
+
+        # set_config rejects the flag before touching browser/profile paths.
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        for value in (True, 1, "true"):
+            with self.subTest(value=value), self.assertRaises(BizLogicError):
+                plugin.set_config(SimpleNamespace(free_config={"final_submit_enabled": value}))
+
+    def test_no_production_or_prefinal_tool_imports_final_module(self):
+        root = Path(__file__).resolve().parents[1]
+        for name in ("plugins/ita_plugin.py", "tools/debug_ita_book_gate.py", "tools/debug_ita_calendar_gate.py"):
+            tree = ast.parse((root / name).read_text())
+            for node in ast.walk(tree):
+                if isinstance(node, ast.ImportFrom):
+                    self.assertNotEqual(node.module, "plugins.ita_booking_final")
+                if isinstance(node, ast.Import):
+                    self.assertNotIn("plugins.ita_booking_final", [alias.name for alias in node.names])
+
+
+# Actual composed JavaScript in a synthetic DOM. Slot snapshot logic is covered
+# by the existing Book JS suite; this harness reuses that suite's DOM below.
+NATIVE_JS_HARNESS = r"""
+const fs = require('fs'), vm = require('vm');
+const {script, mode} = JSON.parse(fs.readFileSync(0, 'utf8'));
+let clicks = 0;
+const classes = (...names) => ({contains: name => names.includes(name)});
+const input = {type: 'hidden', id: 'idHiddenFasciaServizio', value: '80001001'};
+const slot = {
+  isConnected: true, classList: classes('fascia', 'act'),
+  hasAttribute: () => false, getAttribute: () => null,
+  querySelector: () => null,
+  querySelectorAll: selector => selector === 'input' ? [input] :
+    [{textContent: '10:05 - 11:05'}, {textContent: '(1)'}],
+  getBoundingClientRect: () => ({left: 0, right: 100, top: 0, bottom: 40}),
+  contains: e => e === slot,
+};
+const link = {dataset: {date: '2026-10-13'}, classList: classes('input-async-abilitato'),
+  hasAttribute: () => false, getAttribute: () => null};
+const content = {dataset: {date: '2026-10-13'}, querySelectorAll: () => [slot], contains: e => e === slot};
+const button = {isConnected: true, disabled: true, dataset: {coordinateFinalGuard: 'enabled'},
+  setAttribute: () => {}, removeAttribute: () => {}, click: () => {
+    if (button.disabled) throw new Error('clicked while disabled');
+    clicks++;
+    if (mode === 'throw_after_click') throw new Error('lost acknowledgement');
+  }};
+const service = {value: '7002'};
+if (mode === 'wrong_service') service.value = 'other';
+if (mode === 'wrong_day') link.dataset.date = '2026-10-14';
+if (mode === 'wrong_id') input.value = '80002002';
+if (mode === 'unavailable') slot.classList = classes('fascia', 'act', 'notAvailableFascia');
+if (mode === 'unguarded') button.disabled = false;
+if (mode === 'consumed') button.dataset.coordinateFinalAttemptConsumed = 'true';
+const document = {
+  querySelectorAll: selector => ({
+    '#idServizio': [service], '#btnPrenotaNoOtp': mode === 'duplicate_button' ? [button, button] : [button],
+    '.events a.selected': [link], '.events-content li.selected': [content],
+    '.events a[data-date]': [link], '.fascia.act': mode === 'no_active' ? [] : [slot],
+  })[selector] || [],
+  querySelector: () => link, elementFromPoint: () => slot,
+};
+const window = {location: {origin: 'https://prenotami.esteri.it', pathname: '/BookingCalendar'},
+  innerWidth: 1000, innerHeight: 800,
+  getComputedStyle: () => ({display: 'block', visibility: 'visible', pointerEvents: 'auto', opacity: '1'})};
+const context = vm.createContext({document, window});
+const action = new vm.Script('(function(){' + script + '})').runInContext(context);
+let result, thrown = false;
+try { result = action('7002', '2026-10-13', '80001001', '10:05 - 11:05', 1); }
+catch (_) { thrown = true; }
+if (mode === 'twice') action('7002', '2026-10-13', '80001001', '10:05 - 11:05', 1);
+process.stdout.write(JSON.stringify({clicks, disabled: button.disabled,
+  consumed: Boolean(button.dataset.coordinateFinalAttemptConsumed), result, thrown}));
+"""
+
+
+@unittest.skipUnless(shutil.which("node"), "node required for real JS offline execution")
+class NativeFinalJavaScriptTests(unittest.TestCase):
+    def run_js(self, mode):
+        proc = subprocess.run([shutil.which("node"), "-e", NATIVE_JS_HARNESS],
+                              input=json.dumps({"script": NATIVE_FINAL_SCRIPT, "mode": mode}),
+                              text=True, capture_output=True, timeout=10)
+        self.assertEqual(proc.returncode, 0, proc.stderr)
+        return json.loads(proc.stdout)
+
+    def test_native_click_once_and_reguard(self):
+        for mode in ("normal", "twice", "throw_after_click"):
+            with self.subTest(mode=mode):
+                state = self.run_js(mode)
+                self.assertEqual(state["clicks"], 1)
+                self.assertTrue(state["disabled"])
+                self.assertTrue(state["consumed"])
+
+    def test_unsafe_state_does_not_click(self):
+        for mode in ("wrong_service", "wrong_day", "wrong_id", "unavailable", "unguarded",
+                     "consumed", "duplicate_button", "no_active"):
+            with self.subTest(mode=mode):
+                state = self.run_js(mode)
+                self.assertFalse(state["thrown"])
+                self.assertEqual(state["clicks"], 0)
+                self.assertEqual(state["result"], {"clicked": False})
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 559 - 0
test/test_ita_calendar_book.py

@@ -0,0 +1,559 @@
+import ast
+import json
+import shutil
+import subprocess
+import traceback
+import unittest
+from datetime import date, datetime
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import patch
+
+from plugins import ita_calendar_book as book_calendar
+
+from plugins.ita_calendar_book import (
+    RUNTIME_SERVICE_SCRIPT,
+    SLOT_SELECTION_SCRIPT,
+    TIME_SLOTS_PATH,
+    CalendarBookError,
+    parse_book_time_slots,
+    select_slot_before_final,
+)
+from plugins.ita_calendar_query import AVAILABILITY_PATH, CALENDAR_GUARD_SCRIPT
+from test.test_ita_protocol import availability_item, double_json, slot_item
+
+
+DAY = date(2026, 10, 13)
+SERVICE = "7002"
+DAILY_ID = 80001001
+
+
+def packet(path, body, items):
+    return SimpleNamespace(
+        url="https://prenotami.esteri.it" + path,
+        method="POST",
+        request=SimpleNamespace(postData=body),
+        response=SimpleNamespace(status=200, raw_body=double_json(items)),
+    )
+
+
+def packets(*, free=1, remaining=0):
+    availability = packet(
+        AVAILABILITY_PATH,
+        {"_Servizio": "month-runtime-key", "selectedDay": "01/10/2026"},
+        [availability_item("13/10/2026 00:00:00", free, remaining)],
+    )
+    times = packet(
+        TIME_SLOTS_PATH,
+        {"selectedDay": DAY.isoformat(), "idService": SERVICE},
+        [slot_item("13/10/2026 00:00:00", (10, 5), (11, 5), free, remaining, DAILY_ID)],
+    )
+    return availability, times
+
+
+class FakePage:
+    def __init__(self):
+        self.url = "https://prenotami.esteri.it/BookingCalendar"
+        self.service = SERVICE
+        self.context_count = 1
+        self.active = False
+        self.events = []
+        self.overrides = {}
+        self.after_overrides = {}
+        self.click_ack = True
+        self.browser_error = None
+        self.guard_final_count = 0
+        self.last_candidate = None
+
+    @property
+    def clicks(self):
+        return self.events.count("slot-click")
+
+    def run_js(self, script, *args):
+        if self.browser_error:
+            raise RuntimeError(self.browser_error)
+        if script == RUNTIME_SERVICE_SCRIPT:
+            return {"path": "/BookingCalendar", "count": self.context_count, "value": self.service}
+        if script == CALENDAR_GUARD_SCRIPT:
+            self.events.append("guard")
+            return {
+                "path": "/BookingCalendar", "calendarFunctionPresent": True,
+                "finalButtonCount": 1, "allFinalButtonsGuarded": True,
+                "finalRequestCount": self.guard_final_count,
+            }
+        if script != SLOT_SELECTION_SCRIPT:
+            raise AssertionError("Unknown browser action")
+        service, day, daily_id, label, capacity, click = args
+        self.last_candidate = (daily_id, label, capacity)
+        if click and self.click_ack:
+            self.events.append("slot-click")
+            self.active = True
+        raw = {
+            "runtimeMatches": service == self.service, "finalGuarded": True,
+            "firstSelectedMatches": True, "timelineDays": [day], "contentDays": [day],
+            "matchingDateCount": 1, "dayDisabled": False, "dayNegative": False,
+            "dayPositive": True, "candidateCount": 1, "candidateReady": True,
+            "clicked": click and self.click_ack, "activeCount": int(self.active),
+            "activeIsCandidate": self.active, "activeUnavailable": not self.active,
+            "activeRedDot": False, "activeInputCount": int(self.active),
+            "activeIdMatches": self.active, "activeDayMatches": self.active,
+            "activeTimeMatches": self.active, "activeCapacityMatches": self.active,
+        }
+        raw.update(self.overrides)
+        if self.clicks:
+            raw.update(self.after_overrides)
+        return raw
+
+
+def select(page, pair=None):
+    availability, times = pair or packets()
+    return select_slot_before_final(
+        page, target_day=DAY, availability_packet=availability, time_slots_packet=times,
+    )
+
+
+class CalendarServiceReadinessTests(unittest.TestCase):
+    def setUp(self):
+        self.page = FakePage()
+        self.page.tab_id = "book-tab"
+        self.now = 0.0
+        self.sleeps = []
+        self.sleep_hook = None
+        self.enterContext(patch.object(book_calendar.time, "monotonic", side_effect=lambda: self.now))
+        self.enterContext(patch.object(book_calendar.time, "sleep", side_effect=self.advance))
+
+    def advance(self, seconds):
+        self.sleeps.append(seconds)
+        self.now += seconds
+        if self.sleep_hook:
+            self.sleep_hook()
+
+    def wait(self, **kwargs):
+        options = {"session_is_current": lambda: True, "timeout": 0.25}
+        options.update(kwargs)
+        return book_calendar.wait_for_calendar_service(self.page, **options)
+
+    def test_ready_returns_immediately_without_network_or_clicks(self):
+        self.assertEqual(self.wait(), SERVICE)
+        self.assertEqual(self.sleeps, [])
+        self.assertEqual(self.page.events, ["guard"])
+
+    def test_empty_then_ready_uses_actual_value_without_full_delay(self):
+        self.page.service = ""
+        self.sleep_hook = lambda: setattr(self.page, "service", "synthetic-runtime-key")
+        self.assertEqual(self.wait(), "synthetic-runtime-key")
+        self.assertEqual(self.sleeps, [0.1])
+        self.assertEqual(self.page.clicks, 0)
+
+    def test_empty_timeout_is_bounded_and_does_not_supply_a_default_id(self):
+        self.page.service = ""
+        with self.assertRaises(book_calendar.CalendarServiceNotReadyError):
+            self.wait()
+        self.assertAlmostEqual(sum(self.sleeps), 0.25)
+        self.assertEqual(self.page.service, "")
+        self.assertEqual(self.page.clicks, 0)
+
+    def test_stable_phase_strict_read_does_not_wait(self):
+        self.page.service = ""
+        with self.assertRaises(CalendarBookError):
+            book_calendar.read_calendar_service(self.page)
+        self.assertEqual(self.sleeps, [])
+
+    def test_zero_budget_accepts_ready_but_rejects_empty_without_sleep(self):
+        self.assertEqual(self.wait(timeout=0), SERVICE)
+        self.page.service = ""
+        with self.assertRaises(book_calendar.CalendarServiceNotReadyError):
+            self.wait(timeout=0)
+        self.assertEqual(self.sleeps, [])
+
+    def test_invalid_structure_or_value_is_not_treated_as_pending(self):
+        for attribute, value in (("context_count", 0), ("context_count", 2),
+                                 ("context_count", True), ("service", None),
+                                 ("service", 4937), ("service", " "),
+                                 ("service", "x" * 129)):
+            with self.subTest(attribute=attribute, value_type=type(value).__name__):
+                original = getattr(self.page, attribute)
+                setattr(self.page, attribute, value)
+                with self.assertRaises(CalendarBookError) as caught:
+                    self.wait()
+                self.assertNotIsInstance(caught.exception, book_calendar.CalendarServiceNotReadyError)
+                self.assertEqual(self.sleeps, [])
+                setattr(self.page, attribute, original)
+
+    def test_service_change_after_refresh_is_not_accepted(self):
+        self.page.service = ""
+        self.sleep_hook = lambda: setattr(self.page, "service", "other-service")
+        with self.assertRaisesRegex(CalendarBookError, "runtime service changed"):
+            self.wait(expected_service=SERVICE)
+
+    def test_tab_or_path_drift_during_wait_stops(self):
+        for attribute, value in (("tab_id", "other-tab"), ("url", "https://prenotami.esteri.it/UserArea")):
+            with self.subTest(attribute=attribute):
+                original = getattr(self.page, attribute)
+                self.page.service = ""
+                self.sleep_hook = lambda: setattr(self.page, attribute, value)
+                with self.assertRaises(CalendarBookError):
+                    self.wait()
+                setattr(self.page, attribute, original)
+
+    def test_session_change_during_dom_read_is_checked_before_accepting_value(self):
+        checks = iter([True, False])
+        with self.assertRaisesRegex(CalendarBookError, "Session changed"):
+            self.wait(session_is_current=lambda: next(checks))
+        self.assertEqual(self.sleeps, [])
+
+    def test_guard_violation_and_transport_failure_are_not_retried(self):
+        self.page.guard_final_count = 1
+        with self.assertRaises(book_calendar.CalendarGateError):
+            self.wait()
+        self.page.guard_final_count = 0
+        self.page.browser_error = "browser offline"
+        with self.assertRaises(RuntimeError):
+            self.wait()
+        self.assertEqual(self.sleeps, [])
+
+    def test_invalid_wait_contract_is_rejected(self):
+        for timeout in (-1, True, "1", float("inf"), float("nan")):
+            with self.subTest(timeout=timeout), self.assertRaises(CalendarBookError):
+                self.wait(timeout=timeout)
+        with self.assertRaises(CalendarBookError):
+            self.wait(session_is_current=None)
+        self.assertEqual(self.page.events, [])
+
+
+class BookPacketTests(unittest.TestCase):
+    def test_positive_one_zero_uses_current_runtime_service(self):
+        _, times = packets()
+        result = parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)
+        self.assertEqual(len(result), 1)
+        self.assertTrue(result[0].is_available)
+        self.assertNotIn(str(DAILY_ID), repr(result))
+
+    def test_accepts_json_request_and_day_month_year_date(self):
+        _, times = packets()
+        times.request.postData = json.dumps({"selectedDay": "13/10/2026", "idService": int(SERVICE)})
+        self.assertEqual(len(parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)), 1)
+
+    def test_rejects_wrong_metadata_without_disclosing_packet(self):
+        mutations = [
+            lambda p: setattr(p, "url", "https://other.example.test" + TIME_SLOTS_PATH),
+            lambda p: setattr(p, "url", "https://prenotami.esteri.it/BookingCalendar/Other"),
+            lambda p: setattr(p, "method", "GET"),
+            lambda p: setattr(p.response, "status", 302),
+            lambda p: setattr(p.response, "status", True),
+            lambda p: p.request.postData.update(idService="4937"),
+            lambda p: p.request.postData.update(idService=True),
+            lambda p: p.request.postData.update(idService=None),
+            lambda p: p.request.postData.update(selectedDay="2026-10-14"),
+            lambda p: p.request.postData.update(selectedDay="2026-10-13-unverified"),
+            lambda p: p.request.postData.update(unexpected="secret-body-marker"),
+            lambda p: setattr(p.request, "postData", "secret-body-marker"),
+            lambda p: setattr(p.response, "raw_body", "secret-body-marker"),
+            lambda p: setattr(p.response, "raw_body", json.dumps([])),
+        ]
+        for mutate in mutations:
+            with self.subTest(mutation=mutations.index(mutate)):
+                _, times = packets()
+                mutate(times)
+                try:
+                    parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)
+                except CalendarBookError:
+                    self.assertNotIn("secret-body-marker", traceback.format_exc())
+                else:
+                    self.fail("Invalid packet was accepted")
+
+    def test_rejects_wrong_response_day_before_capacity_filtering(self):
+        _, times = packets()
+        times.response.raw_body = double_json([
+            slot_item("14/10/2026 00:00:00", (10, 5), (11, 5), 0, -1, DAILY_ID),
+        ])
+        with self.assertRaisesRegex(CalendarBookError, "another day"):
+            parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)
+
+    def test_capacity_conflict_is_not_no_availability(self):
+        _, times = packets(free=1, remaining=-1)
+        with self.assertRaises(CalendarBookError):
+            parse_book_time_slots(times, target_day=DAY, runtime_service_id=SERVICE)
+
+
+class BookSelectionTests(unittest.TestCase):
+    def test_selects_once_and_returns_only_precommit_approval(self):
+        page = FakePage()
+        result = select(page)
+        self.assertEqual(result.candidate.day, DAY)
+        self.assertEqual(result.candidate.time_label, "10:05 - 11:05")
+        self.assertFalse(hasattr(result, "success"))
+        self.assertNotIn(str(DAILY_ID), repr(result))
+        self.assertEqual(page.events, ["guard", "slot-click", "guard"])
+
+    def test_repeated_selection_does_not_repeat_native_click(self):
+        page = FakePage()
+        select(page)
+        select(page)
+        self.assertEqual(page.clicks, 1)
+
+    def test_no_slots_returns_none_and_never_clicks(self):
+        page = FakePage()
+        self.assertIsNone(select(page, packets(free=0, remaining=-1)))
+        self.assertEqual(page.events, ["guard", "guard"])
+
+    def test_slots_disappearing_after_positive_day_is_safe_none(self):
+        page = FakePage()
+        availability, _ = packets()
+        _, times = packets(free=0, remaining=-1)
+        self.assertIsNone(select(page, (availability, times)))
+        self.assertEqual(page.clicks, 0)
+
+    def test_positive_slots_with_negative_day_is_conflict(self):
+        page = FakePage()
+        availability, _ = packets(free=0, remaining=-1)
+        _, times = packets()
+        with self.assertRaisesRegex(CalendarBookError, "disagree"):
+            select(page, (availability, times))
+        self.assertEqual(page.clicks, 0)
+
+    def test_reuses_capacity_then_start_time_ordering(self):
+        page = FakePage()
+        availability, times = packets(free=8, remaining=7)
+        times.response.raw_body = double_json([
+            slot_item("13/10/2026 00:00:00", (9, 0), (10, 0), 1, 0, 80001002),
+            slot_item("13/10/2026 00:00:00", (12, 0), (13, 0), 4, 3, 80001003),
+            slot_item("13/10/2026 00:00:00", (10, 0), (11, 0), 4, 3, 80001004),
+        ])
+        result = select(page, (availability, times))
+        self.assertEqual(result.candidate.time_label, "10:00 - 11:00")
+        self.assertEqual(page.last_candidate, ("80001004", "10:00 - 11:00", 4))
+
+    def test_rejects_bad_context_before_any_click(self):
+        for field, value in (("url", "https://other.example.test/BookingCalendar"),
+                             ("url", "https://prenotami.esteri.it/UserArea"),
+                             ("context_count", 2), ("context_count", True),
+                             ("service", ""), ("service", None)):
+            with self.subTest(field=field, value=value):
+                page = FakePage()
+                setattr(page, field, value)
+                with self.assertRaises(CalendarBookError):
+                    select(page)
+                self.assertEqual(page.clicks, 0)
+
+    def test_rejects_wrong_availability_month(self):
+        page = FakePage()
+        availability, times = packets()
+        availability.request.postData["selectedDay"] = "01/11/2026"
+        availability.response.raw_body = double_json([])
+        with self.assertRaisesRegex(CalendarBookError, "another month"):
+            select(page, (availability, times))
+        self.assertEqual(page.clicks, 0)
+
+    def test_preclick_invariants_reject_without_clicking(self):
+        mutations = [
+            {"runtimeMatches": False}, {"finalGuarded": False},
+            {"firstSelectedMatches": False}, {"timelineDays": []},
+            {"contentDays": ["2026-10-14"]}, {"dayDisabled": True},
+            {"dayNegative": True}, {"dayPositive": False}, {"matchingDateCount": 2},
+            {"candidateCount": 2}, {"candidateReady": False}, {"clicked": True},
+            {"candidateCount": True}, {"candidateReady": 1},
+            {"extra": "unexpected"}, {"contentDays": "2026-10-13"},
+        ]
+        for changes in mutations:
+            with self.subTest(changes=changes):
+                page = FakePage()
+                page.overrides = changes
+                with self.assertRaises(CalendarBookError):
+                    select(page)
+                self.assertEqual(page.clicks, 0)
+                self.assertEqual(page.events[-1], "guard")
+
+    def test_failed_click_is_not_retried(self):
+        page = FakePage()
+        page.click_ack = False
+        with self.assertRaisesRegex(CalendarBookError, "acknowledged"):
+            select(page)
+        self.assertEqual(page.clicks, 0)
+
+    def test_postclick_drift_is_rejected_and_not_retried(self):
+        mutations = [
+            {"runtimeMatches": False}, {"contentDays": ["2026-10-14"]},
+            {"activeCount": 2}, {"activeIsCandidate": False},
+            {"activeUnavailable": True}, {"activeRedDot": True},
+            {"activeInputCount": 2}, {"activeIdMatches": False},
+            {"activeDayMatches": False}, {"activeTimeMatches": False},
+            {"activeCapacityMatches": False},
+        ]
+        for changes in mutations:
+            with self.subTest(changes=changes):
+                page = FakePage()
+                page.after_overrides = changes
+                with self.assertRaises(CalendarBookError):
+                    select(page)
+                self.assertEqual(page.clicks, 1)
+                self.assertEqual(page.events[-1], "guard")
+
+    def test_observed_final_request_is_never_accepted(self):
+        page = FakePage()
+        page.guard_final_count = 1
+        with self.assertRaises(CalendarBookError):
+            select(page)
+        self.assertEqual(page.clicks, 0)
+
+    def test_browser_exception_does_not_leak_content(self):
+        page = FakePage()
+        page.browser_error = "secret-browser-body-marker"
+        try:
+            select(page)
+        except CalendarBookError:
+            self.assertNotIn("secret-browser-body-marker", traceback.format_exc())
+        else:
+            self.fail("Browser failure was accepted")
+
+    def test_requires_date_not_datetime_or_string(self):
+        for target in (DAY.isoformat(), datetime(2026, 10, 13), None):
+            with self.subTest(target=target):
+                page = FakePage()
+                availability, times = packets()
+                with self.assertRaises(CalendarBookError):
+                    select_slot_before_final(page, target_day=target,
+                                             availability_packet=availability, time_slots_packet=times)
+                self.assertEqual(page.events, [])
+
+    def test_adapter_has_no_query_tool_network_or_final_action(self):
+        path = Path(__file__).resolve().parents[1] / "plugins/ita_calendar_book.py"
+        source = path.read_text()
+        module = ast.parse(source)
+        imports = [node.module or "" for node in ast.walk(module) if isinstance(node, ast.ImportFrom)]
+        self.assertFalse(any(name.startswith("tools") or name == "plugins.ita_plugin" for name in imports))
+        for token in ("GenerateOTP", "btnAvanti", "InsertNewBooking", "fetch(", "XMLHttpRequest", ".submit("):
+            self.assertNotIn(token, source)
+        self.assertEqual(SLOT_SELECTION_SCRIPT.count("candidate.click()"), 1)
+
+
+JS_HARNESS = r"""
+const vm = require('node:vm');
+const payload = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
+const mode = payload.mode;
+const day = '2026-10-13';
+let slotClicks = 0, finalClicks = 0;
+function element(classes = [], extras = {}) {
+  const set = new Set(classes);
+  return Object.assign({
+    dataset: {}, isConnected: true, children: [], style: {},
+    classList: {contains: (c) => set.has(c), add: (c) => set.add(c), remove: (c) => set.delete(c)},
+    hasAttribute: () => false, getAttribute: () => null,
+    getBoundingClientRect: () => ({left: 20, right: 200, top: 20, bottom: 100}),
+    contains(other) {return other === this || this.children.some((c) => c.contains(other));},
+  }, extras);
+}
+const timeline = element(['input-async-abilitato', 'selected'], {dataset: {date: day}});
+const content = element(['selected'], {dataset: {date: day}});
+const input = element([], {type: 'hidden', id: 'idHiddenFasciaServizio', value: '80001001'});
+const spans = [element([], {textContent: '10:05 - 11:05'}), element([], {textContent: '(1)'})];
+const candidate = element([], {children: [input, ...spans]});
+const fields = [input];
+let red = false;
+candidate.querySelectorAll = (selector) => selector === 'input' ? fields : selector === 'span' ? spans : [];
+candidate.querySelector = (selector) => selector === '.dotRed' && red ? element(['dotRed']) : null;
+const slots = [candidate];
+content.children = slots;
+content.querySelectorAll = (selector) => selector === '.fascia' ? slots : [];
+const finalButton = element([], {disabled: true, dataset: {coordinateFinalGuard: 'enabled'}, click: () => finalClicks++});
+const service = {value: '7002'};
+let occluded = false;
+candidate.click = () => {
+  slotClicks++;
+  slots.forEach((slot) => slot.classList.remove('act'));
+  candidate.classList.add('act');
+  if (mode === 'drift') content.dataset.date = '2026-10-14';
+  if (mode === 'drift_origin') window.location.origin = 'https://other.example.test';
+};
+if (mode === 'already_active') candidate.classList.add('act');
+if (mode === 'negative') candidate.classList.add('notAvailableFascia');
+if (mode === 'red') red = true;
+if (mode === 'wrong_time') spans[0].textContent = '09:00 - 10:00';
+if (mode === 'wrong_capacity') spans[1].textContent = '(0)';
+if (mode === 'wrong_id') input.value = '80009999';
+if (mode === 'extra_input') fields.push(element([], {type: 'hidden', value: 'extra'}));
+if (mode === 'duplicate_slot') slots.push(candidate);
+if (mode === 'wrong_date') content.dataset.date = '2026-10-14';
+if (mode === 'wrong_service') service.value = '7003';
+if (mode === 'unguarded_final') finalButton.disabled = false;
+if (mode === 'hidden') candidate.style.display = 'none';
+if (mode === 'occluded') occluded = true;
+if (mode === 'disabled_day') timeline.classList.add('input-async-disabilitato');
+const document = {
+  querySelectorAll(selector) {
+    if (selector === '#idServizio') return [service];
+    if (selector === '#btnPrenotaNoOtp') return [finalButton];
+    if (selector === '.events a.selected') return [timeline];
+    if (selector === '.events-content li.selected') return [content];
+    if (selector === '.events a[data-date]') return [timeline];
+    if (selector === '.fascia.act') return slots.filter((slot) => slot.classList.contains('act'));
+    throw Error('Unexpected selector ' + selector);
+  },
+  querySelector(selector) {
+    if (selector === '.selected') return mode === 'foreign_selected_first' ? element(['selected']) : timeline;
+    throw Error('Unexpected selector ' + selector);
+  },
+  elementFromPoint: () => occluded ? element() : candidate,
+};
+const window = {
+  location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it', pathname: '/BookingCalendar'},
+  innerWidth: 1000, innerHeight: 800,
+  getComputedStyle: (item) => Object.assign({display: 'block', visibility: 'visible', pointerEvents: 'auto', opacity: '1'}, item.style),
+};
+const run = (click) => vm.runInNewContext('(function(){' + payload.source + '\n}).apply(null, args)',
+  {document, window, args: ['7002', day, '80001001', '10:05 - 11:05', 1, click]}, {timeout: 1000});
+const before = run(false), acted = run(true), after = run(false);
+process.stdout.write(JSON.stringify({before, acted, after, slotClicks, finalClicks}));
+"""
+
+
+@unittest.skipUnless(shutil.which("node"), "Node is required for offline JavaScript DOM-contract checks")
+class BookJavaScriptContractTests(unittest.TestCase):
+    def run_case(self, mode):
+        result = subprocess.run(
+            [shutil.which("node"), "-e", JS_HARNESS],
+            input=json.dumps({"source": SLOT_SELECTION_SCRIPT, "mode": mode}),
+            text=True, capture_output=True, timeout=10, check=True,
+        )
+        return json.loads(result.stdout)
+
+    def test_actual_script_clicks_only_positive_candidate(self):
+        result = self.run_case("positive")
+        self.assertTrue(result["before"]["candidateReady"])
+        self.assertEqual(result["slotClicks"], 1)
+        self.assertEqual(result["finalClicks"], 0)
+        self.assertTrue(result["after"]["activeIsCandidate"])
+        self.assertTrue(result["after"]["activeIdMatches"])
+        self.assertTrue(result["after"]["activeCapacityMatches"])
+
+    def test_actual_script_does_not_click_again_when_already_selected(self):
+        result = self.run_case("already_active")
+        self.assertEqual(result["slotClicks"], 0)
+        self.assertTrue(result["after"]["activeIsCandidate"])
+
+    def test_actual_script_rejects_unsafe_dom_before_click(self):
+        modes = ("negative", "red", "wrong_time", "wrong_capacity", "wrong_id", "extra_input",
+                 "duplicate_slot", "wrong_date", "wrong_service", "unguarded_final", "hidden",
+                 "occluded", "disabled_day", "foreign_selected_first", "wrong_origin")
+        for mode in modes:
+            with self.subTest(mode=mode):
+                result = self.run_case(mode)
+                self.assertEqual(result["slotClicks"], 0)
+                self.assertEqual(result["finalClicks"], 0)
+
+    def test_actual_script_readback_exposes_postclick_date_drift(self):
+        result = self.run_case("drift")
+        self.assertEqual(result["slotClicks"], 1)
+        self.assertFalse(result["after"]["firstSelectedMatches"])
+        self.assertFalse(result["after"]["activeDayMatches"])
+        self.assertEqual(result["finalClicks"], 0)
+
+    def test_actual_script_readback_exposes_postclick_origin_drift(self):
+        result = self.run_case("drift_origin")
+        self.assertEqual(result["slotClicks"], 1)
+        self.assertFalse(result["after"]["runtimeMatches"])
+        self.assertEqual(result["finalClicks"], 0)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 821 - 0
test/test_ita_calendar_book_flow.py

@@ -0,0 +1,821 @@
+import copy
+import json
+import shutil
+import subprocess
+import traceback
+import unittest
+from contextlib import contextmanager
+from datetime import date, datetime
+from unittest.mock import Mock, patch
+
+from plugins import ita_calendar_book as book_calendar
+from plugins.ita_calendar_book import (
+    DATE_SELECTION_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH,
+    CalendarBookError, book_date_preferences, recheck_calendar_before_final,
+)
+from plugins.ita_calendar_query import AVAILABILITY_PATH, CalendarNextMonthUnavailableError
+from plugins.ita_plugin import (
+    BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin,
+)
+from test.test_ita_calendar_book import FakePage, SERVICE, packet
+from test import test_ita_plugin as plugin_fixtures
+from test.test_ita_protocol import availability_item, slot_item
+from vs_types import (
+    AppointmentType, BizLogicError, DateAvailability, RateLimiteddError,
+    SessionExpiredOrInvalidError, TimeSlot, VSAccount, VSPlgConfig, VSQueryResult,
+)
+
+
+def month(value, inventory, *, automatic_day=None, slots=None):
+    """Synthetic inventory only; IDs and accounts below never leave the tests."""
+    return {"month": value, "inventory": inventory, "automatic_day": automatic_day,
+            "slots": slots or {}}
+
+
+def positive_month():
+    return month("2026-10", {13: 1})
+
+
+class FakeListener:
+    def __init__(self, page):
+        self.page = page
+        self.queue = []
+        self.listening = False
+        self.starts = 0
+        self.stops = 0
+        self.target = None
+
+    def start(self, targets, method):
+        self.starts += 1
+        self.target = targets
+        self.queue.clear()  # Matches the installed Listener.start contract.
+        self.listening = True
+        self.page.events.append("listen-start")
+        if method != "POST":
+            raise AssertionError("Unexpected listener method")
+
+    def wait(self, timeout, raise_err=False):
+        if not self.listening:
+            raise AssertionError("Wait without listener")
+        if self.page.wait_hook:
+            self.page.wait_hook()
+        if not self.queue:
+            return False
+        result = self.queue.pop(0)
+        if result.url.endswith(TIME_SLOTS_PATH):
+            self.page.selected_day = getattr(result, "fixture_day", None)
+            self.page.content_day = self.page.render_day or self.page.selected_day
+            self.page.current_slots = getattr(result, "fixture_slots", [])
+            self.page.active = False
+        return result
+
+    def stop(self):
+        self.stops += 1
+        self.queue.clear()
+        self.listening = False
+        self.page.events.append("listen-stop")
+
+
+class FlowPage(FakePage):
+    def __init__(self, months=None, *, passes=None):
+        super().__init__()
+        self.tab_id = "book-tab"
+        self.listen = FakeListener(self)
+        self.wait = Mock()
+        self.quit = Mock()
+        self.passes = passes or [months or [positive_month()]]
+        self.refreshes = 0
+        self.month_index = 0
+        self.month_spec = self.passes[0][0]
+        self.selected_day = None
+        self.content_day = None
+        self.current_slots = []
+        self.date_clicks = []
+        self.month_clicks = 0
+        self.requests = []
+        self.request_mutator = None
+        self.wait_hook = None
+        self.render_day = None
+        self.reverse_responses = False
+        self.drop_automatic = False
+        self.duplicate_availability = False
+        self.date_ack = True
+        self.date_candidate_count = None
+        self.date_enabled = True
+        self.date_runtime_matches = True
+
+    def response_packet(self, path, body, items, day=None):
+        result = packet(path, body, items)
+        result.tab_id = self.tab_id
+        result.is_failed = False
+        result.fixture_day = day
+        result.fixture_slots = items
+        if self.request_mutator:
+            self.request_mutator(result)
+        self.requests.append(result)
+        return result
+
+    def times_packet(self, day):
+        number = int(day[-2:])
+        free = self.month_spec["slots"].get(number, self.month_spec["inventory"].get(number, 0))
+        day_value = date.fromisoformat(day)
+        items = [slot_item(day_value.strftime("%d/%m/%Y 00:00:00"), (10, 5), (11, 5),
+                           free, free - 1, 80000000 + self.refreshes * 100 + number)]
+        return self.response_packet(TIME_SLOTS_PATH, {"selectedDay": day, "idService": SERVICE}, items, day)
+
+    def load_month(self):
+        self.selected_day = self.content_day = None
+        value = self.month_spec["month"]
+        inventory = self.month_spec["inventory"]
+        items = [availability_item(date.fromisoformat(f"{value}-{day:02d}").strftime("%d/%m/%Y 00:00:00"),
+                                   free, free - 1) for day, free in inventory.items()]
+        availability = self.response_packet(
+            AVAILABILITY_PATH,
+            {"_Servizio": "calendar-runtime-key", "selectedDay": f"{value}-01"}, items,
+        )
+        responses = [availability]
+        if self.duplicate_availability:
+            responses.append(availability)
+        elif inventory and not self.drop_automatic:
+            auto = self.month_spec["automatic_day"] or min(inventory)
+            responses.append(self.times_packet(f"{value}-{auto:02d}"))
+        if self.reverse_responses:
+            responses.reverse()
+        self.listen.queue.extend(responses)
+
+    def refresh(self):
+        self.refreshes += 1
+        self.month_index = 0
+        self.month_spec = self.passes[min(self.refreshes - 1, len(self.passes) - 1)][0]
+        self.events.append("refresh")
+        self.load_month()
+
+    def next_month(self):
+        self.month_clicks += 1
+        self.month_index += 1
+        sequence = self.passes[min(self.refreshes - 1, len(self.passes) - 1)]
+        if self.month_index >= len(sequence):
+            raise CalendarNextMonthUnavailableError("No next month in fixture")
+        self.month_spec = sequence[self.month_index]
+        self.events.append("next-month")
+        self.load_month()
+
+    def run_js(self, script, *args):
+        if script == DATE_SELECTION_SCRIPT:
+            service, day, click = args
+            count = int(day[:7] == self.month_spec["month"] and int(day[-2:]) in self.month_spec["inventory"])
+            if self.date_candidate_count is not None:
+                count = self.date_candidate_count
+            selected = day == self.selected_day == self.content_day
+            clicked = bool(click and self.date_ack and not selected)
+            raw = {"runtimeMatches": self.date_runtime_matches and service == self.service,
+                   "finalGuarded": True, "candidateCount": count,
+                   "candidateEnabled": self.date_enabled, "selectedMatches": selected, "clicked": clicked}
+            if clicked:
+                self.date_clicks.append(day)
+                self.events.append("date-click")
+                self.listen.queue.append(self.times_packet(day))
+            return raw
+        raw = super().run_js(script, *args)
+        if script == SLOT_SELECTION_SCRIPT:
+            _, day, daily_id, label, free, _ = args
+            matching = [item for item in self.current_slots
+                        if str(item["IDCalendarioServizioGiornaliero"]) == daily_id]
+            raw["timelineDays"] = [self.selected_day] if self.selected_day else []
+            raw["contentDays"] = [self.content_day] if self.content_day else []
+            raw["firstSelectedMatches"] = day == self.selected_day == self.content_day
+            raw["candidateCount"] = len(matching)
+            raw["candidateReady"] = len(matching) == 1 and matching[0]["SlotLiberi"] == free
+            raw.update(self.after_overrides if self.clicks else {})
+        return raw
+
+
+@contextmanager
+def browser_navigation(page):
+    with patch.object(book_calendar, "click_next_month", side_effect=lambda _page: page.next_month()), \
+            patch.object(book_calendar.time, "sleep"):
+        yield
+
+
+def run_flow(page, **kwargs):
+    options = dict(lookahead_months=3, start_day=date(2026, 8, 1), end_day=date(2026, 12, 31),
+                   session_is_current=lambda: True, month_click_interval_seconds=0, dom_timeout=0)
+    options.update(kwargs)
+    with browser_navigation(page):
+        return recheck_calendar_before_final(page, **options)
+
+
+class BookCalendarFlowTests(unittest.TestCase):
+    def assert_stopped(self, page):
+        self.assertFalse(page.listen.listening)
+        self.assertEqual(page.listen.starts, page.listen.stops)
+
+    def test_refresh_waits_for_runtime_reassignment_without_repeating_refresh(self):
+        page = FlowPage()
+        original_run_js = page.run_js
+        pending_reads = []
+
+        def delayed(script, *args):
+            result = original_run_js(script, *args)
+            if script == book_calendar.RUNTIME_SERVICE_SCRIPT and page.refreshes:
+                pending_reads.append(True)
+                if len(pending_reads) == 1:
+                    return {**result, "value": ""}
+            return result
+
+        page.run_js = delayed
+        self.assertIsNotNone(run_flow(page, dom_timeout=1))
+        self.assertEqual(page.refreshes, 1)
+        self.assertEqual(page.clicks, 1)
+        self.assertEqual(len(page.requests), 2)
+        self.assert_stopped(page)
+
+    def test_empty_after_refresh_times_out_without_selecting_or_refreshing_again(self):
+        page = FlowPage()
+        original_refresh = page.refresh
+
+        def empty_refresh():
+            original_refresh()
+            page.service = ""
+
+        page.refresh = empty_refresh
+        with self.assertRaises(book_calendar.CalendarServiceNotReadyError):
+            run_flow(page)
+        self.assertEqual(page.refreshes, 1)
+        self.assertEqual(page.clicks, 0)
+        self.assert_stopped(page)
+
+    def test_automatic_positive_day_uses_fresh_response_without_date_click(self):
+        page = FlowPage()
+        result = run_flow(page)
+        self.assertEqual(result.candidate.day, date(2026, 10, 13))
+        self.assertEqual(result.candidate.daily_calendar_id, "80000113")
+        self.assertEqual(page.refreshes, 1)
+        self.assertEqual(page.date_clicks, [])
+        self.assertEqual(page.clicks, 1)
+        self.assertEqual(len(page.requests), 2)
+        self.assert_stopped(page)
+
+    def test_native_date_click_is_followed_by_current_time_slots(self):
+        page = FlowPage([month("2026-10", {1: 0, 13: 1})])
+        result = run_flow(page)
+        self.assertEqual(result.candidate.day, date(2026, 10, 13))
+        self.assertEqual(page.date_clicks, ["2026-10-13"])
+        self.assertEqual(page.listen.starts, 2)
+        self.assertEqual(len(page.requests), 3)
+        self.assert_stopped(page)
+
+    def test_old_listener_queue_is_cleared_before_month_action(self):
+        page = FlowPage()
+        stale = packet(TIME_SLOTS_PATH, {}, [])
+        stale.tab_id = "query-tab"
+        page.listen.queue.append(stale)
+        result = run_flow(page)
+        self.assertIsNotNone(result)
+        self.assertIsNot(page.requests[-1], stale)
+
+    def test_can_collect_automatic_response_before_availability_delivery(self):
+        page = FlowPage()
+        page.reverse_responses = True
+        self.assertIsNotNone(run_flow(page))
+        self.assertEqual(page.date_clicks, [])
+
+    def test_cross_year_scan_stops_at_first_usable_day(self):
+        page = FlowPage([month("2026-12", {1: 0}), month("2027-01", {5: 1}), month("2027-02", {1: 4})])
+        result = run_flow(page, end_day=date(2027, 3, 1))
+        self.assertEqual(result.candidate.day, date(2027, 1, 5))
+        self.assertEqual(page.month_clicks, 1)
+
+    def test_applies_inclusive_preferences_even_if_earlier_month_is_positive(self):
+        page = FlowPage([month("2026-09", {1: 2}), month("2026-10", {12: 2, 13: 1, 14: 3})])
+        result = run_flow(page, start_day=date(2026, 10, 13), end_day=date(2026, 10, 13))
+        self.assertEqual(result.candidate.day, date(2026, 10, 13))
+        self.assertEqual(page.date_clicks, ["2026-10-13"])
+        self.assertEqual(page.month_clicks, 1)
+
+    def test_date_inventory_race_tries_next_day_without_repeating_failed_candidate(self):
+        page = FlowPage([month("2026-10", {13: 1, 14: 2}, slots={13: 0})])
+        result = run_flow(page)
+        self.assertEqual(result.candidate.day, date(2026, 10, 14))
+        self.assertEqual(page.date_clicks, ["2026-10-14"])
+        self.assertEqual(page.clicks, 1)
+
+    def test_later_automatic_day_is_recaptured_after_another_date_was_selected(self):
+        page = FlowPage([month("2026-10", {13: 1, 14: 1}, automatic_day=14, slots={13: 0})])
+        result = run_flow(page)
+        self.assertEqual(result.candidate.day, date(2026, 10, 14))
+        self.assertEqual(page.date_clicks, ["2026-10-13", "2026-10-14"])
+
+    def test_valid_hint_is_rechecked_before_earlier_dates(self):
+        page = FlowPage([month("2026-09", {9: 2}), month("2026-10", {12: 2, 13: 1})])
+        result = run_flow(page, preferred_day=date(2026, 10, 13))
+        self.assertEqual(result.candidate.day, date(2026, 10, 13))
+        self.assertEqual(page.refreshes, 1)
+        self.assertEqual(page.date_clicks, ["2026-10-13"])
+
+    def test_missing_hint_restarts_once_and_uses_new_earlier_month_response(self):
+        first = [month("2026-09", {9: 0}), month("2026-10", {13: 0})]
+        second = [month("2026-09", {9: 1}), month("2026-10", {13: 0})]
+        page = FlowPage(passes=[first, second])
+        result = run_flow(page, preferred_day=date(2026, 10, 13))
+        self.assertEqual(result.candidate.day, date(2026, 9, 9))
+        self.assertEqual(result.candidate.daily_calendar_id, "80000209")
+        self.assertEqual(page.refreshes, 2)
+
+    def test_hint_slot_race_does_not_repeat_same_day_on_fallback(self):
+        page = FlowPage([month("2026-10", {13: 1, 14: 1}, slots={13: 0})])
+        result = run_flow(page, preferred_day=date(2026, 10, 13))
+        self.assertEqual(result.candidate.day, date(2026, 10, 14))
+        self.assertEqual(page.refreshes, 2)
+        self.assertNotIn("2026-10-13", page.date_clicks)
+
+    def test_hint_outside_preference_or_horizon_is_not_followed(self):
+        for hint in (date(2027, 10, 13), date(2026, 9, 30)):
+            with self.subTest(hint=hint):
+                page = FlowPage()
+                result = run_flow(page, preferred_day=hint, start_day=date(2026, 10, 1))
+                self.assertEqual(result.candidate.day, date(2026, 10, 13))
+                self.assertEqual(page.refreshes, 1)
+
+    def test_full_negative_horizon_returns_none_without_slot_clicks(self):
+        page = FlowPage([month("2026-08", {1: 0}), month("2026-09", {}), month("2026-10", {1: 0})])
+        self.assertIsNone(run_flow(page))
+        self.assertEqual(page.month_clicks, 2)
+        self.assertEqual(page.date_clicks, [])
+        self.assertEqual(page.clicks, 0)
+        self.assert_stopped(page)
+
+    def test_no_month_beyond_user_end_is_requested(self):
+        page = FlowPage([month("2026-10", {1: 0})])
+        self.assertIsNone(run_flow(page, end_day=date(2026, 10, 31)))
+        self.assertEqual(page.month_clicks, 0)
+
+    def test_missing_next_month_is_an_error_not_no_inventory(self):
+        page = FlowPage([month("2026-10", {})])
+        with self.assertRaises(CalendarBookError):
+            run_flow(page)
+        self.assert_stopped(page)
+
+    def test_month_jump_is_rejected(self):
+        page = FlowPage([month("2026-08", {}), month("2026-10", {13: 1})])
+        with self.assertRaisesRegex(CalendarBookError, "exactly one month"):
+            run_flow(page)
+        self.assertEqual(page.clicks, 0)
+        self.assert_stopped(page)
+
+    def test_fallback_anchor_change_is_rejected(self):
+        page = FlowPage(passes=[[month("2026-10", {13: 0})], [month("2026-11", {13: 1})]])
+        with self.assertRaisesRegex(CalendarBookError, "anchor"):
+            run_flow(page, preferred_day=date(2026, 10, 13))
+        self.assertEqual(page.clicks, 0)
+
+    def test_bad_packet_metadata_is_never_used_or_retried(self):
+        mutations = [
+            lambda p: setattr(p, "tab_id", "query-tab"),
+            lambda p: setattr(p, "is_failed", True),
+            lambda p: setattr(p, "url", "https://other.example.test" + AVAILABILITY_PATH),
+            lambda p: setattr(p, "method", "GET"),
+            lambda p: setattr(p.response, "status", 429),
+            lambda p: p.request.postData.update(_Servizio=None),
+        ]
+        for mutate in mutations:
+            with self.subTest(mutation=mutations.index(mutate)):
+                page = FlowPage()
+                page.request_mutator = mutate
+                with self.assertRaises(CalendarBookError):
+                    run_flow(page)
+                self.assertEqual(page.refreshes, 1)
+                self.assertEqual(page.clicks, 0)
+                self.assert_stopped(page)
+
+    def test_time_slots_from_wrong_date_or_service_fail(self):
+        for field, value in (("selectedDay", "2026-10-14"), ("idService", "wrong-service")):
+            page = FlowPage()
+            page.request_mutator = lambda p: p.request.postData.update({field: value}) if p.url.endswith(TIME_SLOTS_PATH) else None
+            with self.subTest(field=field), self.assertRaises(CalendarBookError):
+                run_flow(page)
+            self.assertEqual(page.clicks, 0)
+            self.assert_stopped(page)
+
+    def test_date_click_response_is_bound_to_that_day_and_tab(self):
+        for field in ("tab", "day"):
+            with self.subTest(field=field):
+                page = FlowPage([month("2026-10", {1: 0, 13: 1})])
+
+                def corrupt_after_click(result):
+                    if not page.date_clicks:
+                        return
+                    if field == "tab":
+                        result.tab_id = "old-query-tab"
+                    else:
+                        result.request.postData["selectedDay"] = "2026-10-01"
+
+                page.request_mutator = corrupt_after_click
+                with self.assertRaises(CalendarBookError):
+                    run_flow(page)
+                self.assertEqual(page.date_clicks, ["2026-10-13"])
+                self.assertEqual(page.clicks, 0)
+                self.assert_stopped(page)
+
+    def test_availability_service_must_remain_same_across_months(self):
+        page = FlowPage([month("2026-09", {}), positive_month()])
+        page.request_mutator = lambda p: p.request.postData.update(_Servizio="changed") if page.month_clicks and p.url.endswith(AVAILABILITY_PATH) else None
+        with self.assertRaisesRegex(CalendarBookError, "runtime service changed"):
+            run_flow(page)
+
+    def test_missing_automatic_response_and_duplicate_month_stop_listener(self):
+        for option in ("drop_automatic", "duplicate_availability"):
+            with self.subTest(option=option):
+                page = FlowPage()
+                setattr(page, option, True)
+                with self.assertRaises(CalendarBookError):
+                    run_flow(page)
+                self.assertEqual(page.date_clicks, [])
+                self.assert_stopped(page)
+
+    def test_negative_availability_but_positive_auto_slot_is_conflict(self):
+        page = FlowPage([month("2026-10", {13: 0}, slots={13: 1})])
+        with self.assertRaisesRegex(CalendarBookError, "disagree"):
+            run_flow(page)
+        self.assertEqual(page.clicks, 0)
+
+    def test_site_date_fallback_does_not_select_wrong_day(self):
+        page = FlowPage()
+        page.render_day = "2026-10-01"
+        with self.assertRaisesRegex(CalendarBookError, "selected date"):
+            run_flow(page)
+        self.assertEqual(page.clicks, 0)
+        self.assert_stopped(page)
+
+    def test_failed_date_click_is_not_retried(self):
+        page = FlowPage([month("2026-10", {1: 0, 13: 1})])
+        page.date_ack = False
+        with self.assertRaisesRegex(CalendarBookError, "acknowledged"):
+            run_flow(page)
+        self.assertEqual(page.date_clicks, [])
+        self.assert_stopped(page)
+
+    def test_bad_date_control_is_rejected_without_click(self):
+        for field, value in (("date_candidate_count", 2), ("date_enabled", False),
+                             ("date_runtime_matches", False)):
+            with self.subTest(field=field):
+                page = FlowPage([month("2026-10", {1: 0, 13: 1})])
+                setattr(page, field, value)
+                with self.assertRaises(CalendarBookError):
+                    run_flow(page)
+                self.assertEqual(page.date_clicks, [])
+                self.assert_stopped(page)
+
+    def test_post_slot_click_error_stops_without_trying_another_day(self):
+        page = FlowPage([month("2026-10", {13: 1, 14: 2})])
+        page.after_overrides = {"activeIdMatches": False}
+        with self.assertRaises(CalendarBookError):
+            run_flow(page)
+        self.assertEqual(page.clicks, 1)
+        self.assertEqual(page.date_clicks, [])
+
+    def test_context_invalid_before_or_during_capture_blocks_selection(self):
+        page = FlowPage()
+        with self.assertRaises(CalendarBookError):
+            run_flow(page, session_is_current=lambda: False)
+        self.assertEqual(page.refreshes, 0)
+        current = [True]
+        page = FlowPage()
+        page.wait_hook = lambda: current.__setitem__(0, False)
+        with self.assertRaises(CalendarBookError):
+            run_flow(page, session_is_current=lambda: current[0])
+        self.assertEqual(page.clicks, 0)
+        self.assert_stopped(page)
+
+    def test_invalid_settings_do_not_navigate(self):
+        for kwargs in ({"lookahead_months": True}, {"lookahead_months": 0},
+                       {"start_day": None}, {"end_day": date(2025, 1, 1)},
+                       {"preferred_day": "2026-10-13"}, {"timeout": 0},
+                       {"timeout": float("nan")}, {"dom_timeout": -1}):
+            with self.subTest(kwargs=kwargs):
+                page = FlowPage()
+                with self.assertRaises(CalendarBookError):
+                    run_flow(page, **kwargs)
+                self.assertEqual(page.refreshes, 0)
+
+    def test_provider_error_does_not_leak_raw_body(self):
+        page = FlowPage()
+        page.wait_hook = Mock(side_effect=RuntimeError("secret-response-body"))
+        try:
+            run_flow(page)
+        except CalendarBookError:
+            self.assertNotIn("secret-response-body", traceback.format_exc())
+        else:
+            self.fail("Provider error was accepted")
+        self.assert_stopped(page)
+
+
+class BookPreferenceTests(unittest.TestCase):
+    def test_uses_existing_keys_and_does_not_mutate_inputs(self):
+        values = {"expected_start_date": "2026-10-13", "expected_end_date": "2026-10-13", "other": "keep"}
+        before = copy.deepcopy(values)
+        self.assertEqual(book_date_preferences(values), (date(2026, 10, 13), date(2026, 10, 13)))
+        self.assertEqual(values, before)
+        self.assertEqual(book_date_preferences({}), (date(2000, 1, 1), date(2100, 1, 1)))
+
+    def test_rejects_unknown_formats_and_inverted_range(self):
+        for values in (None, {"expected_start_date": None}, {"expected_start_date": "20261013"},
+                       {"expected_start_date": "2026-02-30"}, {"expected_start_date": "secret-input"},
+                       {"expected_start_date": "2026-10-14", "expected_end_date": "2026-10-13"}):
+            with self.subTest(values=values), self.assertRaises(CalendarBookError) as raised:
+                book_date_preferences(values)
+            self.assertNotIn("secret-input", str(raised.exception))
+
+
+def prepared_plugin(page, *, routing_key="slot.example.it.tourist"):
+    plugin = plugin_fixtures.ItaPluginQuerySafetyTests._plugin(
+        page, routing_key=routing_key, service_id=9001,
+        capability="single_schengen_tourism", lookahead_months=3,
+    )
+    plugin.config = VSPlgConfig(account=VSAccount(username="applicant@example.test"), free_config=plugin.free_config)
+    plugin.instance_id = "book-offline"
+    plugin.session_create_time = 111.0
+    plugin._transient_user_data_path = "/nonexistent/ita-book-flow-test"
+    plugin._reset_calendar_book_state()
+    route = plugin._resolve_route(AppointmentType(routing_key=routing_key))
+    plugin._record_calendar_book_prepared_route(route)
+    plugin.query = Mock(side_effect=AssertionError("Calendar Book must not call Query"))
+    trigger = VSQueryResult(apt_type=AppointmentType(routing_key=routing_key))
+    return plugin, route, trigger
+
+
+class BookEntryTests(unittest.TestCase):
+    def test_real_entry_runs_flow_and_keeps_book_result_unsuccessful(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        inputs = {"username": "applicant@example.test", "expected_start_date": "2026-10-13",
+                  "expected_end_date": "2026-10-13"}
+        original = copy.deepcopy(inputs)
+        with browser_navigation(page):
+            result = plugin.book(trigger, inputs)
+        self.assertFalse(result.success)
+        self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
+        self.assertEqual((result.urn, result.book_date, result.book_time, result.account), ("", "", "", ""))
+        self.assertEqual(plugin.last_booking_precommit.candidate.day, date(2026, 10, 13))
+        self.assertNotIn("80000113", str(plugin.logger.call_args_list))
+        self.assertNotIn("applicant@example.test", str(plugin.logger.call_args_list))
+        self.assertEqual(inputs, original)
+        plugin.query.assert_not_called()
+
+    def test_entry_treats_query_date_as_hint_not_inventory(self):
+        page = FlowPage([month("2026-10", {13: 0, 14: 1})])
+        plugin, _, trigger = prepared_plugin(page)
+        trigger.earliest_date = datetime(2026, 10, 13)
+        trigger.availability = [DateAvailability(date=datetime(2026, 10, 13),
+                                               times=[TimeSlot(time="01:23", label="stale-query-slot")])]
+        with browser_navigation(page):
+            result = plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
+        self.assertEqual(plugin.last_booking_precommit.candidate.day, date(2026, 10, 14))
+        self.assertEqual(plugin.last_booking_precommit.candidate.time_label, "10:05 - 11:05")
+
+    def test_query_preparation_cannot_be_converted_into_book_preparation(self):
+        page = FlowPage()
+        plugin, route, trigger = prepared_plugin(page)
+        plugin._calendar_query_route_key = route.routing_key
+        with self.assertRaises(BizLogicError):
+            plugin._record_calendar_book_prepared_route(route)
+        with self.assertRaises(BizLogicError):
+            plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertEqual(page.refreshes, 0)
+
+    def test_url_alone_is_not_a_book_preparation_proof(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        plugin._reset_calendar_book_state()
+        with self.assertRaises(BizLogicError):
+            plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertEqual(page.refreshes, 0)
+        plugin.query.assert_not_called()
+
+    def test_missing_or_different_applicant_is_rejected(self):
+        for inputs in (None, {}, {"username": "other@example.test"}):
+            with self.subTest(inputs=inputs):
+                page = FlowPage()
+                plugin, _, trigger = prepared_plugin(page)
+                with self.assertRaises(BizLogicError):
+                    plugin.book(trigger, inputs)
+                self.assertEqual(page.refreshes, 0)
+
+    def test_changed_account_page_login_or_route_is_rejected(self):
+        mutations = [
+            lambda p: setattr(p.config.account, "username", "other@example.test"),
+            lambda p: setattr(p, "page", FlowPage()),
+            lambda p: setattr(p, "session_create_time", 222.0),
+            lambda p: setattr(p.page, "tab_id", "another-tab"),
+            lambda p: p.free_config["apt_configs"]["slot.example.it.tourist"].update(service_id=9002),
+            lambda p: p.free_config.update(final_submit_enabled=True),
+            lambda p: setattr(p.page, "service", "another-runtime"),
+        ]
+        for mutation in mutations:
+            with self.subTest(mutation=mutations.index(mutation)):
+                page = FlowPage()
+                plugin, _, trigger = prepared_plugin(page)
+                mutation(plugin)
+                with self.assertRaises(BizLogicError):
+                    plugin.book(trigger, {"username": "applicant@example.test"})
+                self.assertEqual(page.refreshes, 0)
+
+    def test_preparation_from_another_plugin_instance_is_rejected(self):
+        page = FlowPage()
+        first, _, _ = prepared_plugin(page)
+        second, _, trigger = prepared_plugin(page)
+        second._calendar_book_prepared_context = first._calendar_book_prepared_context
+        with self.assertRaises(BizLogicError):
+            second.book(trigger, {"username": "applicant@example.test"})
+
+    def test_second_book_call_does_not_repeat_any_network_action(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        with browser_navigation(page):
+            plugin.book(trigger, {"username": "applicant@example.test"})
+            with self.assertRaisesRegex(BizLogicError, "already attempted"):
+                plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertEqual(page.refreshes, 1)
+        self.assertEqual(page.clicks, 1)
+
+    def test_no_inventory_within_preferences_is_not_reported_as_success(self):
+        page = FlowPage([month("2026-10", {13: 0})])
+        plugin, _, trigger = prepared_plugin(page)
+        with browser_navigation(page):
+            result = plugin.book(trigger, {"username": "applicant@example.test", "expected_end_date": "2026-10-31"})
+        self.assertFalse(result.success)
+        self.assertEqual(result.label, BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
+        self.assertIsNone(plugin.last_booking_precommit)
+
+    def test_mid_capture_account_change_invalidates_preparation(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        page.wait_hook = lambda: setattr(plugin.config.account, "username", "other@example.test")
+        with browser_navigation(page), self.assertRaises(BizLogicError):
+            plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertIsNone(plugin._calendar_book_prepared_context)
+        self.assertIsNone(plugin.last_booking_precommit)
+        self.assertEqual(page.clicks, 0)
+
+    def test_lifecycle_operations_clear_book_preparation(self):
+        for action in ("config", "login", "cleanup"):
+            with self.subTest(action=action):
+                plugin, _, _ = prepared_plugin(FlowPage())
+                if action == "config":
+                    plugin.set_config(plugin.config)
+                elif action == "login":
+                    with patch("plugins.ita_plugin.ChromiumOptions", side_effect=RuntimeError("offline stop")):
+                        with self.assertRaises(RuntimeError):
+                            plugin.create_session()
+                else:
+                    plugin.cleanup()
+                self.assertIsNone(plugin._calendar_book_prepared_context)
+                self.assertIsNone(plugin.last_booking_precommit)
+
+    def test_http_auth_and_rate_limit_use_existing_framework_errors(self):
+        for status, error in ((401, SessionExpiredOrInvalidError), (429, RateLimiteddError)):
+            with self.subTest(status=status):
+                page = FlowPage()
+                plugin, _, trigger = prepared_plugin(page)
+                page.request_mutator = lambda p: setattr(p.response, "status", status)
+                with browser_navigation(page), self.assertRaises(error):
+                    plugin.book(trigger, {"username": "applicant@example.test"})
+                self.assertIsNone(plugin._calendar_book_prepared_context)
+                self.assertEqual(page.clicks, 0)
+
+    def test_provider_failure_at_entry_is_sanitized_and_invalidates_proof(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        page.browser_error = "secret-provider-body"
+        try:
+            plugin.book(trigger, {"username": "applicant@example.test"})
+        except BizLogicError:
+            self.assertNotIn("secret-provider-body", traceback.format_exc())
+        else:
+            self.fail("Provider failure was accepted")
+        self.assertIsNone(plugin._calendar_book_prepared_context)
+
+    def test_two_route_keys_share_the_same_calendar_flow(self):
+        for key in ("slot.hkg.it.tourist", "slot.dub.it.tourist"):
+            with self.subTest(key=key):
+                page = FlowPage()
+                plugin, _, trigger = prepared_plugin(page, routing_key=key)
+                with browser_navigation(page):
+                    result = plugin.book(trigger, {"username": "applicant@example.test"})
+                self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
+
+    def test_query_mode_does_not_drive_the_prepared_book_branch(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        plugin.free_config["query_mode"] = "calendar"
+        with browser_navigation(page):
+            result = plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
+        plugin.query.assert_not_called()
+
+    def test_final_request_observation_rejects_instead_of_reporting_precommit(self):
+        page = FlowPage()
+        plugin, _, trigger = prepared_plugin(page)
+        page.guard_final_count = 1
+        with browser_navigation(page), self.assertRaises(BizLogicError):
+            plugin.book(trigger, {"username": "applicant@example.test"})
+        self.assertIsNone(plugin.last_booking_precommit)
+        self.assertEqual(page.refreshes, 0)
+        self.assertEqual(page.clicks, 0)
+
+
+DATE_JS_HARNESS = r"""
+const vm = require('node:vm');
+const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
+let clicks = 0, finalClicks = 0;
+const zeroSize = mode.startsWith('zero_size') || mode === 'selected_zero_size';
+function node(day) {
+  const classes = new Set(['input-async-abilitato']);
+  return {dataset: {date: day}, isConnected: true,
+    classList: {contains: c => classes.has(c), add: c => classes.add(c)},
+    hasAttribute: () => false, getAttribute: () => null,
+    getBoundingClientRect: () => ({width: zeroSize || mode === 'zero_width' ? 0 : 90,
+                                  height: zeroSize || mode === 'zero_height' ? 0 : 30, left: 3000}),
+  };
+}
+const old = node('2026-10-01'), link = node('2026-10-13');
+let selected = ['already_selected', 'selected_zero_size'].includes(mode) ? link : old;
+const content = node(selected.dataset.date);
+link.click = () => {clicks++; selected = link; content.dataset.date = link.dataset.date;};
+if (['disabled', 'zero_size_disabled'].includes(mode)) link.classList.add('input-async-disabilitato');
+if (mode === 'negative') link.classList.add('notAvailableDay');
+const final = {disabled: mode !== 'unguarded', dataset: {coordinateFinalGuard: 'enabled'}, click: () => finalClicks++};
+const document = {
+  querySelectorAll(q) {
+    if (q === '#idServizio') return [{value: mode === 'wrong_service' ? 'wrong' : '7002'}];
+    if (q === '#btnPrenotaNoOtp') return [final];
+    if (q === '.events a[data-date]') return mode === 'duplicate' ? [old, link, link] : [old, link];
+    if (q === '.events a.selected') return [selected];
+    if (q === '.events-content li.selected') return [content];
+    throw Error('Unexpected selector');
+  },
+  querySelector(q) {if (q === '.selected') return selected; throw Error('Unexpected selector');},
+};
+const window = {
+  location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it', pathname: '/BookingCalendar'},
+  getComputedStyle: element => ({
+    display: ['hidden', 'zero_size_hidden'].includes(mode) ? 'none' : 'block',
+    visibility: 'visible', opacity: '1',
+    pointerEvents: mode === 'zero_size_pointer_blocked' ||
+      (mode === 'selected_zero_size' && element === selected) ? 'none' : 'auto',
+  }),
+};
+const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)',
+  {document, window, args: ['7002', '2026-10-13', click]}, {timeout: 1000});
+const before = run(false), acted = run(true), after = run(false);
+process.stdout.write(JSON.stringify({before, acted, after, clicks, finalClicks}));
+"""
+
+
+@unittest.skipUnless(shutil.which("node"), "Node is required for the native-date script contract")
+class BookDateJavaScriptTests(unittest.TestCase):
+    def run_case(self, mode):
+        completed = subprocess.run([shutil.which("node"), "-e", DATE_JS_HARNESS],
+                                   input=json.dumps({"source": DATE_SELECTION_SCRIPT, "mode": mode}),
+                                   text=True, capture_output=True, timeout=10, check=True)
+        return json.loads(completed.stdout)
+
+    def test_native_date_selection_can_target_offscreen_timeline_and_never_final(self):
+        result = self.run_case("positive")
+        self.assertEqual(result["clicks"], 1)
+        self.assertTrue(result["after"]["selectedMatches"])
+        self.assertEqual(result["finalClicks"], 0)
+
+    def test_already_selected_date_is_not_clicked_again(self):
+        result = self.run_case("already_selected")
+        self.assertEqual(result["clicks"], 0)
+        self.assertTrue(result["before"]["selectedMatches"])
+
+    def test_zero_size_enabled_dates_follow_native_click_and_readback(self):
+        for mode in ("zero_width", "zero_height", "zero_size"):
+            with self.subTest(mode=mode):
+                result = self.run_case(mode)
+                self.assertTrue(result["before"]["candidateEnabled"])
+                self.assertEqual(result["clicks"], 1)
+                self.assertTrue(result["after"]["selectedMatches"])
+                self.assertEqual(result["finalClicks"], 0)
+
+    def test_selected_zero_size_pointer_blocked_date_is_not_reclicked(self):
+        result = self.run_case("selected_zero_size")
+        self.assertTrue(result["before"]["selectedMatches"])
+        self.assertFalse(result["before"]["candidateEnabled"])
+        self.assertEqual(result["clicks"], 0)
+        self.assertEqual(result["finalClicks"], 0)
+
+    def test_guarded_native_date_action_rejects_unsafe_controls(self):
+        for mode in ("disabled", "negative", "unguarded", "wrong_service", "wrong_origin", "duplicate", "hidden",
+                     "zero_size_disabled", "zero_size_hidden", "zero_size_pointer_blocked"):
+            with self.subTest(mode=mode):
+                result = self.run_case(mode)
+                self.assertEqual(result["clicks"], 0)
+                self.assertEqual(result["finalClicks"], 0)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 221 - 0
test/test_ita_calendar_query.py

@@ -0,0 +1,221 @@
+import json
+import unittest
+from unittest.mock import Mock, patch
+
+from plugins.ita_calendar_query import (
+    CalendarGateError,
+    CalendarNextMonthUnavailableError,
+    CalendarProbeResult,
+    scan_until_first_available_month,
+)
+from plugins.ita_protocol import parse_calendar_availability
+
+
+def double_json(items):
+    return json.dumps(json.dumps(items))
+
+
+def probe(year, month, capacities):
+    items = [
+        {
+            "DateLibere": f"{day:02d}/{month:02d}/{year:04d} 00:00:00",
+            "SlotLiberi": slots_free,
+            "SlotRimanenti": slots_remaining,
+        }
+        for day, slots_free, slots_remaining in capacities
+    ]
+    return CalendarProbeResult(
+        days=parse_calendar_availability(double_json(items)),
+        selected_day=f"01/{month:02d}/{year:04d}",
+    )
+
+
+class CalendarProductionScanTests(unittest.TestCase):
+    def test_rejects_dates_outside_the_requested_month(self):
+        october_days = parse_calendar_availability(
+            double_json(
+                [
+                    {
+                        "DateLibere": "01/10/2026 00:00:00",
+                        "SlotLiberi": 1,
+                        "SlotRimanenti": 0,
+                    }
+                ]
+            )
+        )
+
+        with self.assertRaisesRegex(
+            CalendarGateError,
+            "escaped the requested month",
+        ):
+            CalendarProbeResult(
+                days=october_days,
+                selected_day="01/09/2026",
+            )
+
+    def test_stops_on_the_initial_positive_month(self):
+        august = probe(2026, 8, [(20, 2, 1), (12, 1, 0)])
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=august,
+        ) as initial, patch(
+            "plugins.ita_calendar_query.capture_next_probe"
+        ) as next_probe:
+            result = scan_until_first_available_month(
+                Mock(),
+                lookahead_months=12,
+                month_click_interval_seconds=0,
+            )
+
+        initial.assert_called_once()
+        next_probe.assert_not_called()
+        self.assertEqual(result.stop_reason, "first_available_month")
+        self.assertEqual(result.scanned_months, 1)
+        self.assertEqual(
+            result.earliest_available_date.isoformat(),
+            "2026-08-12",
+        )
+
+    def test_scans_sequentially_then_stops_at_the_first_positive_month(self):
+        august = probe(2026, 8, [(31, 0, -1)])
+        september = probe(2026, 9, [(30, 0, -1)])
+        october = probe(
+            2026,
+            10,
+            [(20, 8, 7), (12, 1, 0), (1, 0, -1)],
+        )
+        november = probe(2026, 11, [(2, 10, 9)])
+        log = Mock()
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=august,
+        ), patch(
+            "plugins.ita_calendar_query.capture_next_probe",
+            side_effect=[september, october, november],
+        ) as next_probe:
+            result = scan_until_first_available_month(
+                Mock(),
+                lookahead_months=12,
+                log=log,
+                month_click_interval_seconds=0,
+            )
+
+        self.assertEqual(next_probe.call_count, 2)
+        self.assertEqual(result.stop_reason, "first_available_month")
+        self.assertEqual(result.scanned_months, 3)
+        self.assertEqual(
+            result.earliest_available_date.isoformat(),
+            "2026-10-12",
+        )
+        self.assertEqual(
+            [item.day.isoformat() for item in result.available_days],
+            ["2026-10-12", "2026-10-20"],
+        )
+        self.assertEqual(log.call_count, 3)
+
+    def test_returns_none_only_after_the_complete_horizon(self):
+        months = [
+            probe(2026, month, [(1, 0, -1)])
+            for month in (8, 9, 10)
+        ]
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=months[0],
+        ), patch(
+            "plugins.ita_calendar_query.capture_next_probe",
+            side_effect=months[1:],
+        ) as next_probe:
+            result = scan_until_first_available_month(
+                Mock(),
+                lookahead_months=3,
+                month_click_interval_seconds=0,
+            )
+
+        self.assertEqual(next_probe.call_count, 2)
+        self.assertEqual(result.stop_reason, "horizon_exhausted")
+        self.assertEqual(result.scanned_months, 3)
+        self.assertIsNone(result.earliest_available_date)
+        self.assertEqual(result.available_days, ())
+
+    def test_accepts_an_exact_cross_year_transition(self):
+        december = probe(2026, 12, [(1, 0, -1)])
+        january = probe(2027, 1, [(4, 1, 0)])
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=december,
+        ), patch(
+            "plugins.ita_calendar_query.capture_next_probe",
+            return_value=january,
+        ):
+            result = scan_until_first_available_month(
+                Mock(),
+                lookahead_months=2,
+                month_click_interval_seconds=0,
+            )
+
+        self.assertEqual(
+            result.earliest_available_date.isoformat(),
+            "2027-01-04",
+        )
+
+    def test_rejects_a_skipped_month_instead_of_publishing_a_signal(self):
+        august = probe(2026, 8, [(1, 0, -1)])
+        october = probe(2026, 10, [(1, 1, 0)])
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=august,
+        ), patch(
+            "plugins.ita_calendar_query.capture_next_probe",
+            return_value=october,
+        ):
+            with self.assertRaisesRegex(
+                CalendarGateError,
+                "exactly one month",
+            ):
+                scan_until_first_available_month(
+                    Mock(),
+                    lookahead_months=2,
+                    month_click_interval_seconds=0,
+                )
+
+    def test_incomplete_native_navigation_is_not_misreported_as_no_slots(self):
+        august = probe(2026, 8, [(1, 0, -1)])
+
+        with patch(
+            "plugins.ita_calendar_query.capture_initial_probe",
+            return_value=august,
+        ), patch(
+            "plugins.ita_calendar_query.capture_next_probe",
+            side_effect=CalendarNextMonthUnavailableError("bounded"),
+        ):
+            with self.assertRaisesRegex(
+                CalendarGateError,
+                "before the configured horizon",
+            ):
+                scan_until_first_available_month(
+                    Mock(),
+                    lookahead_months=2,
+                    month_click_interval_seconds=0,
+                )
+
+    def test_rejects_invalid_scan_bounds(self):
+        for value in (True, 0, 121):
+            with self.subTest(value=value):
+                with self.assertRaisesRegex(
+                    CalendarGateError,
+                    "lookahead_months",
+                ):
+                    scan_until_first_available_month(
+                        Mock(),
+                        lookahead_months=value,
+                        month_click_interval_seconds=0,
+                    )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 393 - 0
test/test_ita_calendar_soak.py

@@ -0,0 +1,393 @@
+"""Exercise the existing soak loop with real Italy Query and fake browser IO."""
+
+import io
+import json
+import tempfile
+import time
+import unittest
+from contextlib import ExitStack, redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from DrissionPage.errors import BrowserConnectError
+
+from plugins.ita_plugin import ItaPlugin
+from test.test_debug_ita_production_query_gate import gate_env
+from test.test_debug_ita_soak import FakeClock
+from test.test_ita_query_recovery import RecoveryPage, prepared_plugin
+from tools.debug_ita_calendar_gate import CalendarRequestAudit, ReservationSnapshot
+from tools.debug_ita_soak import (
+    CalendarSoakContext, calendar_soak_limits, main, run_soak,
+)
+from tools.debug_ita_session import DebugConfigurationError
+
+
+class CalendarSoakLifecycleTests(unittest.TestCase):
+    def run_case(
+        self, outcomes=("available",), *, restored_outcomes=("available",),
+        restore_outcome="calendar", duration=900, restart=0,
+        max_sessions=0, end_snapshot=None, cleanup_failure=False,
+        create_outcomes=("ok",), interrupt_wait=False, interrupt_health=False,
+        soak_env=None,
+    ):
+        clock = FakeClock()
+        output = io.StringIO()
+        statuses = []
+        instances = []
+        pages = []
+        with tempfile.TemporaryDirectory() as task_tmp, ExitStack() as stack:
+            profile = Path(task_tmp) / "profile"
+            profile.mkdir(mode=0o700)
+            profile = profile.resolve()  # Match set_config's canonical macOS /private/var path.
+            stack.enter_context(patch.object(
+                CalendarRequestAudit, "settled_snapshot", CalendarRequestAudit.snapshot,
+            ))
+            stack.enter_context(patch("plugins.ita_calendar_query.time.sleep", clock.sleep))
+            stack.enter_context(patch(
+                "tools.debug_ita_calendar_gate.read_reservation_snapshot",
+                return_value=end_snapshot or ReservationSnapshot(0, 0),
+            ))
+            credentials = stack.enter_context(patch(
+                "tools.debug_ita_soak._get_query_credentials",
+                side_effect=AssertionError("must not reload credentials after preparation"),
+            ))
+
+            def make_instance(query_outcomes, *, restoring=False):
+                page = RecoveryPage(query_outcomes, restore_outcome=restore_outcome)
+                plugin, route = prepared_plugin(page)
+                plugin.instance_id = f"offline-{len(instances)}"
+                plugin._transient_user_data_path = str(Path(task_tmp) / plugin.instance_id / "user-data")
+                plugin.root_workspace = str(Path(task_tmp) / plugin.instance_id)
+                plugin._persistent_profile_path = profile
+                plugin.user_data_path = str(profile)
+                plugin.free_config["persistent_browser_profile_path"] = str(profile)
+                plugin._profile_lock_handle = None
+                plugin.tunnel = None
+                plugin.book = Mock(side_effect=AssertionError("Book must not run in Query soak"))
+                create_index = max(0, len(instances) - 1)
+                create_outcome = create_outcomes[min(create_index, len(create_outcomes) - 1)]
+
+                def create():
+                    plugin._clear_calendar_query_state()
+                    if create_outcome == "connect-error":
+                        raise BrowserConnectError("offline connection failed")
+                    plugin.page.url = "https://prenotami.esteri.it/UserArea"
+                    plugin.is_healthy = True
+                    plugin.session_create_time = time.time()
+
+                plugin.create_session = Mock(side_effect=create)
+
+                def cleanup():
+                    page.driver.is_running = False
+                    plugin.page = None
+                    plugin.is_healthy = False
+                    plugin._clear_calendar_query_state()
+                    if cleanup_failure:
+                        raise RuntimeError("private@example.test secret-token")
+
+                plugin.cleanup = Mock(side_effect=cleanup)
+                instances.append(plugin)
+                pages.append(page)
+                return plugin, route
+
+            initial, route = make_instance(outcomes)
+            audit = CalendarRequestAudit(initial.page, include_time_slots=True)
+            audit.start()
+            initial.page.emit("/BookingCalendar/GenerateOTP?ServiceID=9001", "GET")
+            initial.page.emit("/Services/Booking/9001", "POST")
+            context = CalendarSoakContext(
+                plugin=initial, route=route, request_audit=audit, before=ReservationSnapshot(0, 0),
+            )
+            if interrupt_health:
+                initial.page.run_js = Mock(side_effect=KeyboardInterrupt)
+
+            def factory(_group_id):
+                return make_instance(restored_outcomes, restoring=True)[0]
+
+            def sleep(seconds):
+                if interrupt_wait:
+                    raise KeyboardInterrupt
+                clock.sleep(seconds)
+
+            with redirect_stdout(output), redirect_stderr(output):
+                code = run_soak(
+                    gate_env() if soak_env is None else soak_env, apply=True, non_interactive=True,
+                    duration_seconds=duration, min_wait=300, max_wait=300,
+                    max_session_attempts=max_sessions, restart_after_probes=restart,
+                    plugin_factory=factory, prepared_calendar=context,
+                    sleep=sleep, monotonic=clock.monotonic, wall_time=clock.wall_time,
+                    randint=lambda minimum, maximum: minimum,
+                    status_writer=lambda body: statuses.append(json.loads(json.dumps(body))),
+                )
+            credentials.assert_not_called()
+            for instance in instances:
+                instance.book.assert_not_called()
+            for page in pages:
+                self.assertEqual(page.driver.immediate_event_handlers, {})
+            result_lines = [line for line in output.getvalue().splitlines()
+                            if line.startswith("ITA_SOAK_CALENDAR_RESULT=")]
+            self.assertEqual(len(result_lines), 1)
+            report = json.loads(result_lines[0].split("=", 1)[1])
+            # Assert ownership before object finalizers can call cleanup again.
+            cleanup_calls = [instance.cleanup.call_count for instance in instances]
+            for instance in instances:
+                instance.cleanup = Mock()  # neutralize __del__, not loop verification
+            return SimpleResult(code, report, statuses, output.getvalue(), instances, pages, cleanup_calls)
+
+    def test_positive_negative_positive_continues_with_fresh_results(self):
+        result = self.run_case(["available", "none", "available"])
+        self.assertEqual(result.code, 0, result.output)
+        self.assertTrue(result.report["passed"])
+        self.assertEqual(result.report["positiveQueries"], 2)
+        self.assertEqual(result.report["negativeQueries"], 1)
+        self.assertEqual(result.report["queryRequests"]["availabilityRequests"], 5)
+        self.assertEqual(result.report["queryRequests"]["timeSlotRequests"], 3)
+        self.assertEqual(result.cleanup_calls, [1])
+        self.assertEqual(len(result.instances), 1)
+        self.assertEqual(result.report["latestQuery"]["earliestDate"], "2026-08-12")
+        self.assertNotIn("private@example.test", result.output)
+
+    def test_controlled_restart_uses_same_profile_and_new_query_without_otp(self):
+        result = self.run_case(restart=1)
+        self.assertEqual(result.code, 0, result.output)
+        self.assertTrue(result.report["controlledRestart"])
+        self.assertEqual(result.report["restores"], 1)
+        self.assertEqual(result.cleanup_calls, [1, 1])
+        self.assertEqual(result.pages[0].refresh_calls, 1)
+        self.assertGreater(result.pages[1].refresh_calls, 0)
+        self.assertEqual(result.pages[1].get_calls, ["https://prenotami.esteri.it/BookingCalendar"])
+        for key in ("otpRequests", "avantiPosts", "finalRequests"):
+            self.assertEqual(result.report["queryRequests"][key], 0)
+
+    def test_prepared_context_owns_route_without_reloading_environment(self):
+        result = self.run_case(restart=1, soak_env={})
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(result.report["restores"], 1)
+        self.assertEqual(result.cleanup_calls, [1, 1])
+        self.assertEqual(result.statuses[-1]["service_id"], 9001)
+
+    def test_expired_session_rebuilds_then_continues_new_queries(self):
+        result = self.run_case(["expired"])
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(result.report["restores"], 1)
+        self.assertEqual(result.cleanup_calls, [1, 1])
+        self.assertGreater(result.report["positiveQueries"], 0)
+        self.assertEqual(result.instances[1].create_session.call_count, 1)
+
+    def test_disconnect_recovers_but_reports_audit_gap_not_false_pass(self):
+        result = self.run_case(["disconnect"])
+        self.assertEqual(result.code, 6, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertEqual(result.report["auditGaps"], 1)
+        self.assertEqual(result.report["restores"], 1)
+        self.assertGreater(result.report["positiveQueries"], 0)
+        self.assertEqual(result.cleanup_calls, [1, 1])
+
+    def test_two_expirations_stop_without_third_session(self):
+        result = self.run_case(["expired"], restored_outcomes=["expired"])
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["reason"], "consecutive-session-expirations")
+        self.assertEqual(len(result.instances), 2)
+        self.assertEqual(result.cleanup_calls, [1, 1])
+
+    def test_transient_network_failure_retries_same_browser(self):
+        result = self.run_case(["timeout", "available"])
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(len(result.instances), 1)
+        self.assertGreater(result.report["positiveQueries"], 0)
+        self.assertEqual(result.report["restores"], 0)
+
+    def test_two_transient_failures_stop_without_relogin_or_third_probe(self):
+        result = self.run_case(["timeout"])
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.pages[0].attempts, 2)
+        self.assertEqual(result.report["reason"], "consecutive-calendar-network-errors")
+        self.assertEqual(len(result.instances), 1)
+
+    def test_otp_reentry_is_pending_todo_not_attempted_again(self):
+        result = self.run_case(["expired"], restore_outcome="form")
+        self.assertEqual(result.code, 4, result.output)
+        self.assertEqual(result.report["state"], "needs_manual")
+        self.assertEqual(result.report["automaticOtpTodo"], "ITA-OTP-01")
+        self.assertIsNone(result.report["latestQuery"])
+        self.assertEqual(result.pages[1].refresh_calls, 0)
+        self.assertEqual(result.report["queryRequests"]["otpRequests"], 0)
+        self.assertEqual(result.report["queryRequests"]["avantiPosts"], 0)
+
+    def test_rate_limit_stops_without_account_rotation_or_relogin(self):
+        result = self.run_case(["available", "rate"])
+        self.assertEqual(result.code, 5, result.output)
+        self.assertEqual(result.report["state"], "rate_limited")
+        self.assertEqual(len(result.instances), 1)
+        self.assertEqual(result.pages[0].attempts, 2)
+        self.assertIsNone(result.report["latestQuery"])
+
+    def test_permission_denied_stops_for_operator(self):
+        result = self.run_case(["denied"])
+        self.assertEqual(result.code, 4, result.output)
+        self.assertEqual(result.report["state"], "needs_manual")
+        self.assertEqual(result.pages[0].attempts, 1)
+
+    def test_unknown_schema_stops_without_false_inventory_or_secret_log(self):
+        result = self.run_case(["malformed"])
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["positiveQueries"], 0)
+        self.assertEqual(result.report["negativeQueries"], 0)
+        self.assertEqual(result.pages[0].attempts, 1)
+        self.assertNotIn("secret-token", result.output)
+        self.assertNotIn("private@example.test", result.output)
+
+    def test_unexpected_write_request_cannot_pass(self):
+        result = self.run_case(["unexpected-otp"])
+        self.assertNotEqual(result.code, 0, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertEqual(result.report["queryRequests"]["otpRequests"], 1)
+        self.assertEqual(result.report["positiveQueries"], 0)
+
+    def test_wrong_service_after_relogin_stops_without_querying_it(self):
+        result = self.run_case(["expired"], restore_outcome="wrong-service")
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.pages[1].refresh_calls, 0)
+        self.assertFalse(result.report["passed"])
+
+    def test_unverified_reservation_counts_cannot_pass(self):
+        result = self.run_case(end_snapshot=ReservationSnapshot(1, 0))
+        self.assertEqual(result.code, 6, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertFalse(result.report["reservationVerified"])
+
+    def test_cancel_does_not_recreate_or_submit(self):
+        result = self.run_case(interrupt_wait=True)
+        self.assertEqual(result.code, 130, result.output)
+        self.assertEqual(result.cleanup_calls, [1])
+        self.assertFalse(result.report["passed"])
+
+    def test_cancel_during_health_probe_cleans_up_without_relogin(self):
+        result = self.run_case(interrupt_health=True)
+        self.assertEqual(result.code, 130, result.output)
+        self.assertEqual(result.cleanup_calls, [1])
+        self.assertEqual(len(result.instances), 1)
+        self.assertEqual(result.pages[0].attempts, 0)
+        self.assertFalse(result.report["passed"])
+
+    def test_cleanup_failure_is_not_reported_as_success(self):
+        result = self.run_case(cleanup_failure=True)
+        self.assertEqual(result.code, 3, result.output)
+        self.assertFalse(result.report["passed"])
+        self.assertNotIn("secret-token", result.output)
+
+    def test_connect_error_reuses_existing_bounded_creation_retry(self):
+        result = self.run_case(["expired"], create_outcomes=["connect-error", "ok"])
+        self.assertEqual(result.code, 0, result.output)
+        self.assertEqual(len(result.instances), 3)
+        self.assertEqual(result.cleanup_calls, [1, 1, 1])
+
+    def test_session_attempt_cap_stops_instead_of_silently_finishing(self):
+        result = self.run_case(["expired"], max_sessions=1)
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["reason"], "max-session-attempts-reached")
+        self.assertEqual(len(result.instances), 1)
+
+    def test_failed_cleanup_during_recovery_prevents_another_browser(self):
+        result = self.run_case(["expired"], cleanup_failure=True)
+        self.assertEqual(result.code, 3, result.output)
+        self.assertEqual(result.report["reason"], "cleanup-failed")
+        self.assertEqual(len(result.instances), 1)
+        self.assertNotIn("ITA_SOAK_CLEANUP_OK", result.output)
+
+    def test_two_connection_failures_stop_using_existing_cap(self):
+        result = self.run_case(["expired"], create_outcomes=["connect-error"])
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["reason"], "consecutive-browser-connect-failures")
+        self.assertEqual(len(result.instances), 3)  # prepared + two failed starts
+
+    def test_two_disconnections_stop_without_third_browser(self):
+        result = self.run_case(["disconnect"], restored_outcomes=["disconnect"])
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["reason"], "consecutive-browser-disconnects")
+        self.assertEqual(len(result.instances), 2)
+
+    def test_hourly_reauthentication_cap_survives_successful_queries_between_failures(self):
+        result = self.run_case(["expired"], restored_outcomes=["available", "expired"], duration=7200)
+        self.assertEqual(result.code, 1, result.output)
+        self.assertEqual(result.report["reason"], "reauthentication-rate-limit")
+        self.assertEqual(len(result.instances), 7)
+
+    def test_deadline_before_successful_retry_is_incomplete_not_a_pass(self):
+        result = self.run_case(["timeout"], duration=60)
+        self.assertEqual(result.code, 6, result.output)
+        self.assertEqual(result.report["positiveQueries"], 0)
+
+    def test_unexercised_requested_restart_is_not_marked_verified(self):
+        result = self.run_case(restart=100)
+        self.assertEqual(result.code, 6, result.output)
+        self.assertFalse(result.report["controlledRestart"])
+
+
+class SimpleResult:
+    def __init__(self, code, report, statuses, output, instances, pages, cleanup_calls):
+        self.code, self.report, self.statuses, self.output = code, report, statuses, output
+        self.instances, self.pages, self.cleanup_calls = instances, pages, cleanup_calls
+
+
+class CalendarSoakCliTests(unittest.TestCase):
+    def test_gate_transfers_the_same_prepared_instance_and_cleanup_once(self):
+        from test import test_debug_ita_production_query_gate as workflow
+        from tools.debug_ita_calendar_gate import CalendarGateMode
+
+        def soak(_env, *, plugin, route, request_audit, before):
+            self.assertEqual(route.service_id, 9001)
+            self.assertEqual(before, ReservationSnapshot(0, 0))
+            self.assertEqual(request_audit.snapshot()["otpRequests"], 1)
+            self.assertEqual(request_audit.snapshot()["avantiPosts"], 1)
+            plugin.page.set.auto_handle_alert.assert_called_with(accept=False)
+            request_audit.stop()
+            plugin.cleanup()
+            return 0
+
+        with patch("tools.debug_ita_calendar_gate.resolve_qcal_mode", return_value=CalendarGateMode.CALENDAR_SOAK), \
+                patch("tools.debug_ita_soak.run_prepared_calendar_soak", side_effect=soak) as handoff:
+            code, output, plugin, page, mocks, otp_reader = workflow.ProductionGateWorkflowTests()._run_gate()
+        self.assertEqual(code, 0, output)
+        handoff.assert_called_once()
+        otp_reader.assert_called_once()
+        plugin.cleanup.assert_called_once()
+        mocks["run_production_query_acceptance"].assert_not_called()
+        mocks["scan_calendar_horizon"].assert_not_called()
+
+    def test_preflight_checks_calendar_config_without_credentials_or_browser(self):
+        output = io.StringIO()
+        with patch.dict("os.environ", gate_env(), clear=True), \
+                patch("tools.debug_ita_calendar_gate.run_calendar_gate") as run, \
+                patch("tools.debug_ita_soak._get_query_credentials") as credentials, \
+                redirect_stdout(output):
+            code = main(["--calendar", "--duration-seconds", "900"])
+        self.assertEqual(code, 0)
+        run.assert_not_called()
+        credentials.assert_not_called()
+        self.assertIn("external_request=false", output.getvalue())
+
+    def test_unsafe_cadence_is_rejected_before_gate_or_otp(self):
+        with patch.dict("os.environ", gate_env(), clear=True), \
+                patch("tools.debug_ita_calendar_gate.run_calendar_gate") as run, \
+                redirect_stderr(io.StringIO()):
+            code = main(["--calendar", "--run", "--min-wait", "10"])
+        self.assertEqual(code, 2)
+        run.assert_not_called()
+
+    def test_actual_gate_is_only_entered_with_run(self):
+        with patch.dict("os.environ", gate_env(), clear=True), \
+                patch("tools.debug_ita_calendar_gate.run_calendar_gate", return_value=0) as run:
+            self.assertEqual(main(["--calendar", "--run", "--restart-after-probes", "1"]), 0)
+        env = run.call_args.args[0]
+        self.assertEqual(env["ITA_QCAL_MODE"], "calendar_soak")
+        self.assertEqual(env["ITA_SOAK_RESTART_AFTER_PROBES"], "1")
+
+    def test_limits_reject_bad_values_before_external_actions(self):
+        for value in ("nan", "0", "86401"):
+            with self.subTest(value=value), self.assertRaises(DebugConfigurationError):
+                calendar_soak_limits({"ITA_SOAK_DURATION_SECONDS": value})
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 219 - 0
test/test_ita_final_attribution.py

@@ -0,0 +1,219 @@
+"""Submission-to-receipt wiring, offline only. No historical attempt is replayed."""
+
+import copy
+import json
+import tempfile
+import unittest
+from contextlib import redirect_stdout
+from dataclasses import replace
+from datetime import date, time
+from io import StringIO
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from plugins.ita_booking_final import (
+    FinalBookingAttempt, FinalBookingError, FinalOutcomeUnknown, NativeFinalSubmitter,
+    ReservationState, SubmissionSignal, VerifiedSubmission, inspect_final_packet,
+)
+from plugins.ita_final_read_port import FinalReceiptReadPort
+from test import test_ita_final_read_port as fixtures
+from test.test_ita_booking_final import final_packet, NativePage, target
+from test.test_ita_reservation import confirmed_detail, confirmed_listing
+from tools import ita_final_evidence as evidence
+
+
+class AttributionTests(unittest.TestCase):
+    def setUp(self):
+        fixtures.FinalReadPortTests.setUp(self)
+        # Match the observed business shape, with synthetic IDs/account/links.
+        old = self.plugin.last_booking_precommit
+        day = date(2026, 9, 3)
+        self.plugin.last_booking_precommit = replace(old,
+            calendar_day=replace(old.calendar_day, day=day),
+            candidate=replace(old.candidate, day=day, start_time=time(9, 15), end_time=time(10)))
+        self.main.url += "?selectedService=Visti%20Nazionali%20e%20Schengen"
+        self.port = FinalReceiptReadPort(self.plugin, self.route)
+
+    def add_confirmed(self):
+        self.browser.raw = confirmed_listing()
+        self.browser.receipts[self.browser.raw["tables"][0]["rows"][1]["detailUrl"]] = confirmed_detail()
+
+    def attempt(self, *, change=None, signal=SubmissionSignal.ACCEPTED, proof=True):
+        def submit():
+            if proof:
+                self.port.record_submission(inspect_final_packet(final_packet(self.port.target), self.port.target)[1])
+            self.add_confirmed()
+            if change:
+                change()
+            return signal
+        self.submit = Mock(side_effect=submit)
+        return FinalBookingAttempt(self.port.target, read_reservations=self.port,
+                                   submit_native=self.submit, session_is_current=self.port.session_is_current)
+
+    def test_real_shape_returns_success_and_assigned_time_without_fabricated_receipt_fields(self):
+        attempt = self.attempt()
+        result = attempt.execute(enabled=True)
+        self.assertTrue(result.success)
+        self.assertEqual(result.book_date, "2026-09-03")
+        self.assertEqual(result.book_time, "09:26")
+        self.assertEqual(result.urn, "CONFIRMED-SYNTHETIC")
+        snapshot = self.port()
+        record = next(r for r in snapshot.records if r.state is ReservationState.ACTIVE)
+        self.assertIsNone(record.service_id)
+        self.assertIsNone(record.time_label)
+        self.assertEqual(record.submission.target, self.port.target)
+        self.assertTrue(all(p.close.call_count == 1 for p in self.browser.pages))
+        self.main.get.assert_not_called()
+        self.submit.assert_called_once()
+        with self.assertRaises(FinalBookingError):
+            attempt.execute(enabled=True)
+
+    def test_unknown_response_with_matched_request_and_new_confirmed_receipt_can_succeed(self):
+        self.assertTrue(self.attempt(signal=SubmissionSignal.UNKNOWN).execute(enabled=True).success)
+
+    def test_rejected_response_conflicting_with_new_receipt_remains_unknown(self):
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt(signal=SubmissionSignal.REJECTED).execute(enabled=True)
+
+    def test_active_receipt_without_request_proof_cannot_be_attributed(self):
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.attempt(proof=False).execute(enabled=True)
+
+    def test_baseline_active_receipt_still_blocks_before_any_submission(self):
+        self.add_confirmed()
+        attempt = self.attempt()
+        with self.assertRaises(FinalBookingError):
+            attempt.execute(enabled=True)
+        self.submit.assert_not_called()
+
+    def test_proof_requires_baseline_current_session_and_exact_target(self):
+        proof = VerifiedSubmission(self.port.target)
+        with self.assertRaises(FinalBookingError):
+            self.port.record_submission(proof)
+        self.port()
+        for key, value in (("session_key", "another"), ("tab_id", "other"), ("service_id", "other"),
+                           ("service_name", "other"), ("applicant", "other@example.test")):
+            with self.subTest(key=key), self.assertRaises(FinalBookingError):
+                self.port.record_submission(VerifiedSubmission(replace(self.port.target, **{key: value})))
+        self.plugin.session_create_time += 1
+        with self.assertRaises(FinalBookingError):
+            self.port.record_submission(proof)
+
+    def test_displayed_service_is_read_from_calendar_not_invented_from_route(self):
+        self.assertEqual(self.port.target.service_name, "Visti Nazionali e Schengen")
+        for query in ("", "?selectedService=one&selectedService=two"):
+            self.main.url = self.main.url.split("?")[0] + query
+            port = FinalReceiptReadPort(self.plugin, self.route)
+            self.assertIsNone(port.target.service_name)
+            port()
+            with self.assertRaises(FinalBookingError):
+                port.record_submission(VerifiedSubmission(port.target))
+
+    def test_service_date_time_type_and_status_mismatch_never_become_success(self):
+        # Recreate for each trial: a final attempt cannot be reused.
+        cases = [("service", "Servizio Erogato", "Wrong service"),
+                 ("date", "Data", "4 settembre 2026"), ("time", "Ora", "10:01"),
+                 ("status", "Stato", "Unverified"), (None, "Tipo Prenotazione", "Prenotazione Multipla"),
+                 (None, "statusCode", "3")]
+        for row_key, detail_key, value in cases:
+            with self.subTest(key=detail_key):
+                self.setUp()
+                def change():
+                    raw = self.browser.raw["tables"][0]["rows"][1]
+                    d = self.browser.receipts[raw["detailUrl"]]
+                    if row_key:
+                        raw[row_key] = value
+                    (d if detail_key == "statusCode" else d["fields"])[detail_key] = value
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt(change=change).execute(enabled=True)
+
+    def test_modified_history_or_multiple_new_receipts_remain_unknown(self):
+        for mode in ("history", "multiple"):
+            with self.subTest(mode=mode):
+                self.setUp()
+                def change():
+                    table = self.browser.raw["tables"][0]
+                    if mode == "history":
+                        table["rows"][0]["time"] = "10:26"
+                        self.browser.receipt["fields"]["Ora"] = "10:26"
+                    else:
+                        row = {**table["rows"][1], "reference": "SECOND-NEW",
+                               "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/second-new"}
+                        d = copy.deepcopy(self.browser.receipts[table["rows"][1]["detailUrl"]])
+                        d["path"] = "/ReservationDetail/Index/second-new"
+                        d["fields"]["Codice Prenotazione"] = "SECOND-NEW"
+                        table["rows"].append(row)
+                        table["count"] = 3
+                        table["info"].update(recordsTotal=3, recordsDisplay=3, end=3)
+                        self.browser.receipts[row["detailUrl"]] = d
+                with self.assertRaises(FinalOutcomeUnknown):
+                    self.attempt(change=change).execute(enabled=True)
+
+    def test_current_evidence_controller_reuses_core_and_keeps_claim_after_success(self):
+        with tempfile.TemporaryDirectory() as directory, \
+                patch.object(evidence, "verify_precommit_selection"), redirect_stdout(StringIO()):
+            run = evidence.FinalEvidenceRun(self.plugin, self.route,
+                    claim_path=Path(directory) / "claim", verify_submission=lambda: True)
+            signal, proof, reason = inspect_final_packet(final_packet(run.port.target), run.port.target)
+            native = Mock(side_effect=lambda: (self.add_confirmed(), signal)[1])
+            native.submitted_selection = proof
+            native.diagnostic = {"requestMatched": True, "reason": reason}
+            with patch.object(evidence, "NativeFinalSubmitter", return_value=native):
+                report = run.execute(confirm=lambda prompt: prompt.split("'")[1])
+            self.assertTrue(run.result.success)
+            self.assertTrue(report["bookingConfirmed"])
+            self.assertTrue(report["receiptEvidence"]["bookingConfirmed"])
+            self.assertEqual(report["confirmedTime"], "09:26")
+            self.assertTrue(run.claim_path.exists())
+            self.assertNotIn("CONFIRMED-SYNTHETIC", json.dumps(report))
+            self.assertNotIn(run.port.target.applicant, json.dumps(report))
+
+    def test_missing_single_request_audit_prevents_attribution(self):
+        with tempfile.TemporaryDirectory() as directory, \
+                patch.object(evidence, "verify_precommit_selection"), redirect_stdout(StringIO()):
+            run = evidence.FinalEvidenceRun(self.plugin, self.route,
+                    claim_path=Path(directory) / "claim", verify_submission=lambda: False)
+            native = Mock(side_effect=lambda: (self.add_confirmed(), SubmissionSignal.ACCEPTED)[1])
+            native.submitted_selection = VerifiedSubmission(run.port.target)
+            native.diagnostic = {"requestMatched": True, "reason": "recognized"}
+            with patch.object(evidence, "NativeFinalSubmitter", return_value=native):
+                report = run.execute(confirm=lambda prompt: prompt.split("'")[1])
+            self.assertFalse(report["bookingConfirmed"])
+            self.assertFalse(report["receiptEvidence"]["bookingConfirmed"])
+            self.assertTrue(run.claim_path.exists())
+
+
+class PacketEvidenceTests(unittest.TestCase):
+    def test_diagnostic_preserves_matched_request_for_unknown_response_without_raw_data(self):
+        t = target()
+        p = final_packet(t)
+        p.response.raw_body = "SECRET-not-json"
+        signal, proof, reason = inspect_final_packet(p, t)
+        self.assertIs(signal, SubmissionSignal.UNKNOWN)
+        self.assertEqual(proof.target, t)
+        self.assertEqual(reason, "response_body")
+        self.assertNotIn("SECRET", repr((signal, proof, reason)))
+
+    def test_request_mismatch_never_creates_proof(self):
+        t = target()
+        for key in ("idCalendarioGiornaliero", "selectedDay", "selectedHour"):
+            p = final_packet(t)
+            p.request.postData[key] = "wrong"
+            self.assertIsNone(inspect_final_packet(p, t)[1])
+        p = final_packet(t)
+        p.tab_id = "wrong"
+        self.assertEqual(inspect_final_packet(p, t)[2], "request_metadata")
+
+    def test_native_adapter_exposes_only_verified_request_and_fixed_diagnostic(self):
+        t = target()
+        page = NativePage(t)
+        page.final_packet.response.raw_body = '{"errorMessage":null,"url":"/Reservation"}'
+        native = NativeFinalSubmitter(page, t, lambda: True)
+        self.assertIs(native(), SubmissionSignal.UNKNOWN)
+        self.assertEqual(native.submitted_selection.target, t)
+        self.assertEqual(native.diagnostic, {"requestMatched": True, "reason": "response_fields"})
+        self.assertEqual(page.final_clicks, 1)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 233 - 0
test/test_ita_final_evidence.py

@@ -0,0 +1,233 @@
+"""Offline one-shot discovery; no credentials, browser launch or website calls."""
+
+import json
+import os
+import tempfile
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import redirect_stdout
+from io import StringIO
+from pathlib import Path
+from unittest.mock import Mock, patch
+
+from plugins.ita_booking_final import FinalBookingError, SubmissionSignal
+from test import test_ita_final_read_port as port_fixtures
+from test.test_ita_reservation import listing, detail
+from tools import ita_final_evidence as evidence
+
+
+class ClaimTests(unittest.TestCase):
+    def setUp(self):
+        self.temp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temp.cleanup)
+        self.path = Path(self.temp.name) / "private" / "once.claim"
+
+    def test_preflight_does_not_create_directory(self):
+        evidence.require_unused_claim(self.path)
+        self.assertFalse(self.path.parent.exists())
+
+    def test_claim_is_exclusive_private_and_contains_no_identity(self):
+        evidence.claim_once(self.path)
+        self.assertEqual(json.loads(self.path.read_text()), {
+            "schema": 1, "state": "possibly_submitted", "automaticRetry": False})
+        self.assertEqual(self.path.stat().st_mode & 0o777, 0o600)
+        self.assertEqual(self.path.parent.stat().st_mode & 0o777, 0o700)
+        with self.assertRaises(FileExistsError):
+            evidence.claim_once(self.path)
+        with self.assertRaises(FinalBookingError):
+            evidence.require_unused_claim(self.path)
+
+    def test_partial_claim_blocks_and_is_not_removed_after_fsync_failure(self):
+        with patch.object(evidence.os, "fsync", side_effect=OSError("synthetic")):
+            with self.assertRaises(OSError):
+                evidence.claim_once(self.path)
+        with self.assertRaises(FinalBookingError):
+            evidence.require_unused_claim(self.path)
+
+    def test_dangling_symlink_and_directory_are_blocked(self):
+        self.path.parent.mkdir()
+        self.path.symlink_to(self.path.parent / "missing")
+        with self.assertRaises(FinalBookingError):
+            evidence.require_unused_claim(self.path)
+        with self.assertRaises(FileExistsError):
+            evidence.claim_once(self.path)
+        self.assertFalse((self.path.parent / "missing").exists())
+
+    def test_symlink_parent_is_not_written_through(self):
+        other = Path(self.temp.name) / "other"
+        other.mkdir()
+        self.path.parent.symlink_to(other, target_is_directory=True)
+        with self.assertRaises(ValueError):
+            evidence.claim_once(self.path)
+        self.assertEqual(list(other.iterdir()), [])
+
+    def test_concurrent_claims_have_one_winner(self):
+        def claim(_):
+            try:
+                evidence.claim_once(self.path)
+                return True
+            except FileExistsError:
+                return False
+        with ThreadPoolExecutor(max_workers=4) as pool:
+            self.assertEqual(sum(pool.map(claim, range(4))), 1)
+
+
+class FinalEvidenceTests(unittest.TestCase):
+    def setUp(self):
+        port_fixtures.FinalReadPortTests.setUp(self)
+        self.temp = tempfile.TemporaryDirectory()
+        self.addCleanup(self.temp.cleanup)
+        self.path = Path(self.temp.name) / "private" / "once.claim"
+        self.check = patch.object(evidence, "verify_precommit_selection").start()
+        self.native = Mock(return_value=SubmissionSignal.ACCEPTED)
+        self.factory = patch.object(evidence, "NativeFinalSubmitter", return_value=self.native).start()
+        self.output = StringIO()
+        patcher = redirect_stdout(self.output)
+        patcher.__enter__()
+        self.addCleanup(lambda: patcher.__exit__(None, None, None))
+
+    def run_object(self):
+        return evidence.FinalEvidenceRun(self.plugin, self.route, claim_path=self.path)
+
+    def confirm(self, _prompt):
+        slot = self.plugin.last_booking_precommit.candidate
+        return f"BOOK {slot.day.isoformat()} {slot.time_label}"
+
+    def test_decline_never_reads_or_submits_or_claims(self):
+        run = self.run_object()
+        report = run.execute(confirm=lambda _: "no")
+        self.assertEqual(report["outcome"], "confirmation_declined")
+        self.assertFalse(self.path.exists())
+        self.native.assert_not_called()
+        self.browser.new_tab.assert_not_called()
+        with self.assertRaises(FinalBookingError):
+            run.execute(confirm=self.confirm)
+
+    def test_existing_fence_blocks_before_prompt(self):
+        evidence.claim_once(self.path)
+        prompt = Mock()
+        with self.assertRaises(FinalBookingError):
+            self.run_object().execute(confirm=prompt)
+        prompt.assert_not_called()
+        self.native.assert_not_called()
+
+    def test_unknown_response_uses_core_and_persists_fence_before_click(self):
+        def native():
+            self.assertTrue(self.path.exists())
+            return SubmissionSignal.UNKNOWN
+        self.native.side_effect = native
+        run = self.run_object()
+        report = run.execute(confirm=self.confirm)
+        self.native.assert_called_once()
+        self.assertTrue(report["attempted"])
+        self.assertEqual(report["outcome"], "unknown_do_not_retry")
+        self.assertTrue(report["receiptEvidence"]["readVerified"])
+        self.assertTrue(report["receiptEvidence"]["historicalRecordsUnchanged"])
+        self.assertFalse(report["bookingConfirmed"])
+        with self.assertRaises(FinalBookingError):
+            self.run_object().execute(confirm=self.confirm)
+        self.assertTrue(self.path.exists())
+
+    def test_rejection_is_not_a_retry_instruction(self):
+        self.native.return_value = SubmissionSignal.REJECTED
+        report = self.run_object().execute(confirm=self.confirm)
+        self.assertEqual(report["outcome"], "rejected_do_not_retry")
+        self.assertTrue(self.path.exists())
+        self.native.assert_called_once()
+
+    def test_native_exception_or_interrupt_still_leaves_fence(self):
+        for error in (RuntimeError("SECRET"), KeyboardInterrupt()):
+            with self.subTest(error=type(error).__name__):
+                path = Path(self.temp.name) / type(error).__name__ / "claim"
+                self.native.side_effect = error
+                run = evidence.FinalEvidenceRun(self.plugin, self.route, claim_path=path)
+                if isinstance(error, KeyboardInterrupt):
+                    with self.assertRaises(KeyboardInterrupt):
+                        run.execute(confirm=self.confirm)
+                else:
+                    run.execute(confirm=self.confirm)
+                self.assertTrue(path.exists())
+                self.assertTrue(run.possibly_submitted)
+                self.assertFalse(run.report["bookingConfirmed"])
+                self.assertNotIn("SECRET", self.output.getvalue())
+
+    def test_claim_failure_never_calls_native(self):
+        with patch.object(evidence, "claim_once", side_effect=OSError("PRIVATE")):
+            with self.assertRaises(FinalBookingError):
+                self.run_object().execute(confirm=self.confirm)
+        self.native.assert_not_called()
+        self.assertNotIn("PRIVATE", self.output.getvalue())
+
+    def test_unknown_old_receipt_blocks_before_claim(self):
+        self.browser.raw["tables"][0]["rows"][0]["status"] = "Unverified"
+        with self.assertRaises(FinalBookingError):
+            self.run_object().execute(confirm=self.confirm)
+        self.native.assert_not_called()
+        self.assertFalse(self.path.exists())
+
+    def test_selection_changes_during_confirmation_blocks_before_claim(self):
+        def confirm(prompt):
+            answer = self.confirm(prompt)
+            self.check.side_effect = RuntimeError("changed")
+            return answer
+        with self.assertRaises(FinalBookingError):
+            self.run_object().execute(confirm=confirm)
+        self.assertFalse(self.path.exists())
+        self.native.assert_not_called()
+
+    def test_new_unknown_receipt_is_observed_without_assigning_success_or_leaking_reference(self):
+        # Empty initial baseline, then one new unknown receipt. Values are
+        # synthetic evidence shapes, NOT an asserted mapping for the live site.
+        table = self.browser.raw["tables"][0]
+        table["rows"], table["count"] = [], 0
+        table["info"].update(pages=0, end=0, recordsTotal=0, recordsDisplay=0)
+        def native():
+            self.browser.raw = listing()
+            self.browser.receipt = detail()
+            self.browser.raw["tables"][0]["rows"][0]["status"] = "SYNTHETIC-NEW-STATE"
+            self.browser.receipt["fields"]["Stato"] = "SYNTHETIC-NEW-STATE"
+            self.browser.receipt["statusCode"] = "999"
+            return SubmissionSignal.ACCEPTED
+        self.native.side_effect = native
+        run = self.run_object()
+        report = run.execute(confirm=self.confirm)
+        observation = report["receiptEvidence"]
+        self.assertTrue(observation["readVerified"])
+        self.assertEqual(observation["newRecordCount"], 1)
+        self.assertEqual(observation["newRecords"][0]["classifiedState"], "unknown")
+        self.assertEqual(observation["newRecords"][0]["statusCode"], "999")
+        self.assertFalse(report["bookingConfirmed"])
+        self.assertNotIn("SYNTHETIC-REFERENCE", json.dumps(report))
+        self.assertNotIn("synthetic-link", json.dumps(report))
+        self.assertEqual(self.main.url, "https://prenotami.esteri.it/BookingCalendar")
+        self.assertTrue(all(p.close.call_count == 1 for p in self.browser.pages))
+
+    def test_unknown_observation_does_not_relax_strict_read_port(self):
+        self.browser.raw["tables"][0]["rows"][0]["status"] = "Unverified"
+        self.browser.receipt["fields"]["Stato"] = "Unverified"
+        self.browser.receipt["statusCode"] = "999"
+        observation = self.port.observe_receipts()
+        self.assertEqual(observation.records[0][1].state.value, "unknown")
+        with self.assertRaises(FinalBookingError):
+            self.port()
+
+    def test_observation_mismatch_and_context_change_are_blocked(self):
+        self.browser.receipt["fields"]["Ora"] = "12:00"
+        with self.assertRaises(FinalBookingError):
+            self.port.observe_receipts()
+        self.browser.new_tab.reset_mock()
+        self.plugin.is_healthy = False
+        with self.assertRaises(FinalBookingError):
+            self.port.observe_receipts()
+        self.browser.new_tab.assert_not_called()
+
+    def test_review_keeps_browser_until_reader_returns(self):
+        reader = Mock(return_value="")
+        evidence.wait_for_receipt_review(reader=reader)
+        reader.assert_called_once()
+        self.assertIn("Do NOT rerun", self.output.getvalue())
+        self.main.close.assert_not_called()
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 310 - 0
test/test_ita_final_read_port.py

@@ -0,0 +1,310 @@
+"""Real read-port orchestration + receipt parsers, offline browser only."""
+
+import copy
+import ast
+import traceback
+import unittest
+from dataclasses import replace
+from pathlib import Path
+from types import MethodType, SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins.ita_booking_final import FinalBookingAttempt, FinalBookingError, FinalOutcomeUnknown, SubmissionSignal
+from plugins.ita_final_read_port import FinalReceiptReadPort, LIST_URL, MAX_DETAIL_READS
+from plugins.ita_plugin import ItaPlugin
+from plugins.ita_protocol import ItaCapability, ItaRouteConfig, CalendarScanConfig
+from plugins.ita_reservation import DETAIL_READ_SCRIPT, LIST_READ_SCRIPT
+from test.test_ita_booking_final import target
+from test.test_ita_reservation import detail, listing
+
+
+class ReceiptTab:
+    def __init__(self, browser, index):
+        self.browser = browser
+        self.tab_id = f"receipt-{index}"
+        self.url = "about:blank"
+        self.urls = []
+        self.list_visits = 0
+        self.close = Mock(side_effect=lambda: browser.on_close(self))
+
+    def get(self, url, *, retry, timeout):
+        assert retry == 0 and timeout == 30
+        self.urls.append(url)
+        self.url = url
+        self.list_visits += url == LIST_URL
+        self.browser.on_get(self)
+        return True
+
+    def run_js(self, script):
+        if script == LIST_READ_SCRIPT:
+            raw = self.browser.after if self.list_visits > 1 and self.browser.after else self.browser.raw
+            return copy.deepcopy(raw)
+        if script == DETAIL_READ_SCRIPT:
+            return copy.deepcopy(self.browser.receipts.get(self.url, self.browser.receipt))
+        raise AssertionError("Unexpected non-receipt browser action")
+
+
+class Browser:
+    def __init__(self):
+        self.id = "synthetic-browser"
+        self.raw, self.receipt = listing(), detail()
+        self.receipts = {}
+        self.after = None
+        self.pages = []
+        self.on_get = lambda page: None
+        self.on_close = lambda page: None
+        self.new_tab = Mock(side_effect=self.open_tab)
+
+    def open_tab(self, *, background, new_context):
+        assert background is True and new_context is False
+        tab = ReceiptTab(self, len(self.pages))
+        self.pages.append(tab)
+        return tab
+
+
+class FinalReadPortTests(unittest.TestCase):
+    def setUp(self):
+        self.sleeper = patch("plugins.ita_reservation.time.sleep").start()
+        self.addCleanup(patch.stopall)
+        self.browser = Browser()
+        self.main = SimpleNamespace(browser=self.browser, tab_id="calendar-tab",
+                                    url="https://prenotami.esteri.it/BookingCalendar")
+        self.main.get = Mock(side_effect=AssertionError("Calendar navigation forbidden"))
+        self.main.close = Mock(side_effect=AssertionError("Calendar close forbidden"))
+        self.main.run_js = Mock(side_effect=AssertionError("Calendar mutation forbidden"))
+        approval = target().approval
+        self.route = ItaRouteConfig("slot.fixture.it.tourist", 7001,
+                                    ItaCapability.SINGLE_SCHENGEN_TOURISM, CalendarScanConfig(3))
+        self.plugin = SimpleNamespace(page=self.main, session_create_time=1, is_healthy=True,
+                                      config=SimpleNamespace(account=SimpleNamespace(username="Applicant@example.test")),
+                                      free_config={"final_submit_enabled": False},
+                                      last_booking_precommit=approval, _calendar_query_route_key=None)
+        self.plugin._calendar_book_prepared_context = (
+            id(self.plugin), self.main, "applicant@example.test", 1, self.route, "7001", self.main.tab_id)
+        self.plugin._resolve_route = lambda apt: self.route
+        self.plugin._book_final_configuration_valid = MethodType(ItaPlugin._book_final_configuration_valid, self.plugin)
+        self.plugin._calendar_book_context_matches = MethodType(ItaPlugin._calendar_book_context_matches, self.plugin)
+        self.port = FinalReceiptReadPort(self.plugin, self.route)
+
+    def test_constructor_never_opens_or_changes_browser(self):
+        self.browser.new_tab.assert_not_called()
+        self.assertTrue(self.port.session_is_current())
+        self.assertEqual(self.port.target.applicant, "applicant@example.test")
+        self.assertEqual(self.port.target.service_id, "7001")
+
+    def test_real_parsers_create_bound_cancelled_baseline_without_invented_ids(self):
+        snapshot = self.port()
+        self.assertTrue(snapshot.complete)
+        self.assertEqual(snapshot.applicant, self.port.target.applicant)
+        self.assertEqual(snapshot.session_key, self.port.target.session_key)
+        row, = snapshot.records
+        self.assertIsNone(row.service_id)
+        self.assertIsNone(row.time_label)
+        self.assertEqual(row.appointment_time, "10:25")
+        self.assertRegex(row.receipt_fingerprint, r"^[0-9a-f]{64}$")
+        self.assertNotIn("SYNTHETIC-REFERENCE", repr(snapshot))
+        self.assertEqual(self.browser.pages[0].urls, [LIST_URL,
+                         listing()["tables"][0]["rows"][0]["detailUrl"], LIST_URL])
+        self.browser.pages[0].close.assert_called_once()
+        self.main.get.assert_not_called()
+        self.main.close.assert_not_called()
+        self.main.run_js.assert_not_called()
+
+    def test_no_query_preparation_can_be_used(self):
+        self.plugin._calendar_query_route_key = "slot.fixture.it.tourist"
+        with self.assertRaises(FinalBookingError):
+            FinalReceiptReadPort(self.plugin, self.route)
+        self.browser.new_tab.assert_not_called()
+
+    def test_capture_requires_precommit_and_final_disabled(self):
+        for change in (lambda: setattr(self.plugin, "last_booking_precommit", None),
+                       lambda: self.plugin.free_config.update(final_submit_enabled=True)):
+            self.setUp()
+            change()
+            with self.assertRaises(FinalBookingError):
+                FinalReceiptReadPort(self.plugin, self.route)
+
+    def test_each_binding_change_rejects_before_opening_a_tab(self):
+        changes = (
+            lambda: setattr(self.plugin.config.account, "username", "OTHER"),
+            lambda: setattr(self.plugin, "session_create_time", 2),
+            lambda: setattr(self.main, "tab_id", "OTHER"),
+            lambda: setattr(self.browser, "id", "OTHER"),
+            lambda: setattr(self.plugin, "is_healthy", False),
+            lambda: setattr(self.plugin, "last_booking_precommit", replace(self.port.target.approval)),
+            lambda: setattr(self, "route", replace(self.route, service_id=8001)),
+        )
+        for change in changes:
+            self.setUp()
+            change()
+            with self.assertRaises(FinalBookingError):
+                self.port()
+            self.browser.new_tab.assert_not_called()
+
+    def test_context_change_during_read_closes_only_owned_tab(self):
+        self.browser.on_get = lambda page: setattr(self.plugin, "session_create_time", 2)
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.browser.pages[0].close.assert_called_once()
+        self.main.close.assert_not_called()
+
+    def test_factory_returning_calendar_or_foreign_tab_is_not_owned(self):
+        for candidate in (self.main, SimpleNamespace(browser=Browser(), tab_id="foreign", close=Mock())):
+            self.browser.new_tab.side_effect = None
+            self.browser.new_tab.return_value = candidate
+            with self.assertRaises(FinalBookingError):
+                self.port()
+            candidate.close.assert_not_called()
+
+    def test_wrong_origin_login_redirect_or_detail_identity_rejects(self):
+        self.browser.on_get = lambda page: setattr(page, "url", "https://iam.esteri.it/signin/")
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.browser.pages[0].close.assert_called_once()
+        self.browser.on_get = lambda page: None
+        self.browser.receipt["fields"]["Codice Prenotazione"] = "OTHER"
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.browser.pages[-1].close.assert_called_once()
+
+    def test_list_change_during_read_rejects(self):
+        self.browser.after = listing()
+        self.browser.after["tables"][0]["rows"][0]["time"] = "10:26"
+        with self.assertRaises(FinalBookingError):
+            self.port()
+
+    def test_unknown_status_and_code_do_not_become_active_or_cancelled(self):
+        self.browser.raw["tables"][0]["rows"][0]["status"] = "Confermata"
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.assertEqual(self.browser.pages[0].urls, [LIST_URL])
+        self.browser.raw = listing()
+        self.browser.receipt["statusCode"] = "1"
+        with self.assertRaises(FinalBookingError):
+            self.port()
+
+    def test_cancelled_display_metadata_changes_are_preserved_in_fingerprint(self):
+        first = self.port()
+        self.browser.receipt["fields"]["Tipo Prenotazione"] = "Changed type"
+        second = self.port()
+        self.assertNotEqual(first.records[0], second.records[0])
+        self.assertNotEqual(first.records[0].receipt_fingerprint, second.records[0].receipt_fingerprint)
+
+    def test_detail_limit_never_produces_partial_snapshot(self):
+        main = self.browser.raw["tables"][0]
+        base = main["rows"][0]
+        count = MAX_DETAIL_READS + 1
+        main["rows"] = [{**base, "reference": f"REF-{i}",
+                         "detailUrl": f"https://prenotami.esteri.it/ReservationDetail/Index/{i}"} for i in range(count)]
+        main.update(count=count)
+        main["info"].update(recordsTotal=count, recordsDisplay=count, end=10, pages=3)
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.assertEqual(self.browser.pages[0].urls, [LIST_URL])
+
+    def test_empty_verified_history_can_be_read(self):
+        table = self.browser.raw["tables"][0]
+        table.update(count=0, rows=[])
+        table["info"].update(recordsTotal=0, recordsDisplay=0, end=0, pages=0)
+        self.assertEqual(self.port().records, ())
+        self.assertEqual(self.browser.pages[0].urls, [LIST_URL, LIST_URL])
+
+    def test_cleanup_failure_poisoned_port_cannot_be_reused(self):
+        def bad_close(page):
+            raise RuntimeError("PRIVATE-CONTENT")
+        self.browser.on_close = bad_close
+        with self.assertRaises(FinalBookingError) as caught:
+            self.port()
+        self.assertNotIn("PRIVATE", "".join(traceback.format_exception(caught.exception)))
+        self.assertFalse(self.port.session_is_current())
+        with self.assertRaises(FinalBookingError):
+            self.port()
+        self.assertEqual(self.browser.new_tab.call_count, 1)
+
+    def test_error_or_keyboard_interrupt_always_closes_owned_tab(self):
+        for error in (RuntimeError("PRIVATE-CONTENT"), KeyboardInterrupt()):
+            self.setUp()
+            self.browser.on_get = Mock(side_effect=error)
+            with self.assertRaises((FinalBookingError, KeyboardInterrupt)):
+                self.port()
+            self.browser.pages[0].close.assert_called_once()
+
+    def test_changed_calendar_during_cleanup_cannot_return_snapshot(self):
+        self.browser.on_close = lambda page: setattr(self.main, "url", "https://prenotami.esteri.it/UserArea")
+        with self.assertRaises(FinalBookingError):
+            self.port()
+
+    def test_observer_brackets_navigation_and_finishes_before_owned_close(self):
+        events = []
+
+        def observe(page):
+            self.assertEqual(page.url, "about:blank")
+            events.append("start")
+            return lambda: events.append("finish")
+
+        self.browser.on_get = lambda page: events.append("get")
+        self.browser.on_close = lambda page: events.append("close")
+        port = FinalReceiptReadPort(self.plugin, self.route, observe_tab=observe)
+        port()
+        self.assertEqual(events, ["start", "get", "get", "get", "finish", "close"])
+
+    def test_observer_failure_or_interrupt_closes_tab_and_releases_lock(self):
+        for error in (RuntimeError("PRIVATE-CONTENT"), KeyboardInterrupt()):
+            self.setUp()
+            finish = Mock(side_effect=error)
+            port = FinalReceiptReadPort(self.plugin, self.route, observe_tab=lambda page: finish)
+            with self.assertRaises((FinalBookingError, KeyboardInterrupt)):
+                port()
+            self.browser.pages[0].close.assert_called_once()
+            self.assertFalse(port.session_is_current())
+            self.assertFalse(port._lock.locked())
+
+    def test_read_port_has_no_booking_or_cookie_operations(self):
+        path = Path(__file__).resolve().parents[1] / "plugins/ita_final_read_port.py"
+        tree = ast.parse(path.read_text())
+        for node in ast.walk(tree):
+            if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute):
+                self.assertNotIn(node.func.attr, {"click", "submit", "input", "book", "query", "cookies", "quit"})
+
+    def test_read_port_composes_with_final_core_without_retries(self):
+        submit = Mock(return_value=SubmissionSignal.REJECTED)
+        attempt = FinalBookingAttempt(self.port.target, read_reservations=self.port,
+                                     submit_native=submit, session_is_current=self.port.session_is_current)
+        with self.assertRaises(FinalBookingError):
+            attempt.execute()
+        submit.assert_not_called()
+        result = attempt.execute(enabled=True)  # Explicit offline double; no native submit.
+        self.assertFalse(result.success)
+        self.assertEqual(attempt.state, "rejected")
+        submit.assert_called_once()
+        with self.assertRaises(FinalBookingError):
+            attempt.execute(enabled=True)
+
+    def test_new_unverified_live_receipt_leaves_outcome_unknown_and_reconcile_only(self):
+        def submitted():
+            self.browser.raw["tables"][0]["rows"][0]["status"] = "Confermata"
+            return SubmissionSignal.ACCEPTED
+        submit = Mock(side_effect=submitted)
+        attempt = FinalBookingAttempt(self.port.target, read_reservations=self.port,
+                                     submit_native=submit, session_is_current=self.port.session_is_current)
+        with self.assertRaises(FinalOutcomeUnknown):
+            attempt.execute(enabled=True)
+        with self.assertRaises(FinalOutcomeUnknown):
+            attempt.reconcile()
+        with self.assertRaises(FinalBookingError):
+            attempt.execute(enabled=True)
+        submit.assert_called_once()
+        self.assertEqual(attempt.state, "unknown")
+
+    def test_cancelled_detail_metadata_change_after_write_cannot_be_rejected_as_no_change(self):
+        def submitted():
+            self.browser.receipt["fields"]["Tipo Prenotazione"] = "Changed type"
+            return SubmissionSignal.REJECTED
+        attempt = FinalBookingAttempt(self.port.target, read_reservations=self.port,
+                                     submit_native=submitted, session_is_current=self.port.session_is_current)
+        with self.assertRaises(FinalOutcomeUnknown):
+            attempt.execute(enabled=True)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 363 - 0
test/test_ita_local_handoff.py

@@ -0,0 +1,363 @@
+import io
+import json
+import os
+import stat
+import tempfile
+import unittest
+from concurrent.futures import ThreadPoolExecutor
+from contextlib import redirect_stderr, redirect_stdout
+from pathlib import Path
+from unittest.mock import patch
+
+from plugins.ita_plugin import BOOKING_FORM_DISCOVERY_STOP_LABEL
+from tools.debug_ita_book import run_book_recheck_once
+from tools.debug_ita_monitor import run_monitor
+from tools.ita_local_handoff import (
+    ItaLocalHandoffError,
+    ItaLocalSignalStaleError,
+    claim_local_weak_signal,
+    publish_local_weak_signal,
+)
+from vs_types import AvailabilityStatus, VSBookResult, VSQueryResult
+
+
+SERVICE_ID = 1321
+ROUTING_KEY = "slot.dub.it.tourist"
+
+
+class _FlowPage:
+    url = "https://prenotami.esteri.it/Services/Booking/1321"
+
+    def ele(self, _selector, timeout=None):
+        del timeout
+        return None
+
+    def run_js(self, _script):
+        return {
+            "path": "/Services/Booking/1321",
+            "form": {
+                "method": "POST",
+                "action_path": "/Services/Booking/1321",
+            },
+            "field_count": 0,
+            "fields": [],
+            "button_count": 1,
+            "buttons": [
+                {
+                    "tag": "button",
+                    "type": "submit",
+                    "id": "btnAvanti",
+                    "name": None,
+                    "text": "Avanti",
+                }
+            ],
+        }
+
+
+class _FlowQueryPlugin:
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = _FlowPage()
+        self.query_calls = 0
+        self.book_calls = 0
+        self.cleanup_calls = 0
+        _FlowQueryPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        return None
+
+    def query(self, apt_type):
+        self.query_calls += 1
+        return VSQueryResult(
+            success=True,
+            apt_type=apt_type,
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+
+    def cleanup(self):
+        self.cleanup_calls += 1
+
+
+class _FlowBookPlugin:
+    last_instance = None
+
+    def __init__(self, group_id):
+        self.group_id = group_id
+        self.page = _FlowPage()
+        self.last_booking_form_structure = self.page.run_js("")
+        self.query_calls = 0
+        self.book_calls = 0
+        self.cleanup_calls = 0
+        self.last_trigger = None
+        _FlowBookPlugin.last_instance = self
+
+    def set_log(self, logger):
+        self.logger = logger
+
+    def set_config(self, config):
+        self.config = config
+
+    def create_session(self):
+        return None
+
+    def book(self, trigger, user_inputs=None):
+        del user_inputs
+        self.last_trigger = trigger
+        self.book_calls += 1
+        return VSBookResult(
+            success=False,
+            label=BOOKING_FORM_DISCOVERY_STOP_LABEL,
+        )
+
+    def cleanup(self):
+        self.cleanup_calls += 1
+
+
+class ItaLocalHandoffStorageTests(unittest.TestCase):
+    def test_signal_is_private_metadata_only_and_consumed_once(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir) / "handoff"
+            signal_path = publish_local_weak_signal(
+                service_id=SERVICE_ID,
+                routing_key=ROUTING_KEY,
+                issued_at=100.0,
+                handoff_root=root,
+            )
+
+            body = signal_path.read_text(encoding="utf-8")
+            payload = json.loads(body)
+            self.assertEqual(payload["service_id"], SERVICE_ID)
+            self.assertEqual(payload["routing_key"], ROUTING_KEY)
+            self.assertEqual(payload["evidence"], "booking-form")
+            self.assertNotIn("username", body.lower())
+            self.assertNotIn("password", body.lower())
+            self.assertNotIn("cookie", body.lower())
+            if os.name == "posix":
+                self.assertEqual(stat.S_IMODE(root.stat().st_mode), 0o700)
+                self.assertEqual(stat.S_IMODE(signal_path.stat().st_mode), 0o600)
+
+            claimed = claim_local_weak_signal(
+                expected_service_id=SERVICE_ID,
+                expected_routing_key=ROUTING_KEY,
+                now=110.0,
+                handoff_root=root,
+            )
+            claimed_again = claim_local_weak_signal(
+                expected_service_id=SERVICE_ID,
+                expected_routing_key=ROUTING_KEY,
+                now=110.0,
+                handoff_root=root,
+            )
+
+            self.assertIsNotNone(claimed)
+            self.assertEqual(claimed.service_id, SERVICE_ID)
+            self.assertIsNone(claimed_again)
+
+    def test_stale_signal_is_rejected_and_removed(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir) / "handoff"
+            publish_local_weak_signal(
+                service_id=SERVICE_ID,
+                routing_key=ROUTING_KEY,
+                issued_at=100.0,
+                handoff_root=root,
+            )
+
+            with self.assertRaises(ItaLocalSignalStaleError):
+                claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=131.0,
+                    handoff_root=root,
+                )
+
+            self.assertIsNone(
+                claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=131.0,
+                    handoff_root=root,
+                )
+            )
+
+    def test_two_consumers_can_claim_the_signal_only_once(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir) / "handoff"
+            publish_local_weak_signal(
+                service_id=SERVICE_ID,
+                routing_key=ROUTING_KEY,
+                issued_at=100.0,
+                handoff_root=root,
+            )
+
+            def claim():
+                return claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=110.0,
+                    handoff_root=root,
+                )
+
+            with ThreadPoolExecutor(max_workers=2) as pool:
+                results = list(pool.map(lambda _index: claim(), range(2)))
+
+            self.assertEqual(sum(item is not None for item in results), 1)
+
+    def test_wrong_target_is_consumed_and_never_available_for_book(self):
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir) / "handoff"
+            publish_local_weak_signal(
+                service_id=9999,
+                routing_key=ROUTING_KEY,
+                issued_at=100.0,
+                handoff_root=root,
+            )
+
+            with self.assertRaisesRegex(
+                ItaLocalHandoffError,
+                "service_id does not match",
+            ):
+                claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=110.0,
+                    handoff_root=root,
+                )
+
+            self.assertIsNone(
+                claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=110.0,
+                    handoff_root=root,
+                )
+            )
+
+
+class ItaLocalHandoffFlowTests(unittest.TestCase):
+    def test_one_query_weak_signal_triggers_one_independent_book_recheck(self):
+        query_stdout = io.StringIO()
+        book_stdout = io.StringIO()
+        stderr = io.StringIO()
+
+        with tempfile.TemporaryDirectory() as temp_dir:
+            root = Path(temp_dir) / "handoff"
+
+            def publish():
+                publish_local_weak_signal(
+                    service_id=SERVICE_ID,
+                    routing_key=ROUTING_KEY,
+                    issued_at=100.0,
+                    handoff_root=root,
+                )
+
+            with (
+                patch(
+                    "tools.debug_ita_monitor.resolve_chrome_path",
+                    return_value=Path("/test/chrome"),
+                ),
+                patch(
+                    "tools.debug_ita_monitor._get_query_credentials",
+                    return_value=("query@example.test", "query-password"),
+                ),
+                patch(
+                    "tools.debug_ita_monitor._prepare_query_profile",
+                    return_value=Path("/offline/query-profile"),
+                ),
+                patch("tools.debug_ita_monitor.ItaPlugin", _FlowQueryPlugin),
+                patch.dict("tools.debug_ita_monitor.os.environ", {}, clear=False),
+                redirect_stdout(query_stdout),
+                redirect_stderr(stderr),
+            ):
+                monitor_exit = run_monitor(
+                    {},
+                    apply=True,
+                    non_interactive=True,
+                    min_wait=60,
+                    max_wait=60,
+                    max_probes=1,
+                    publish_local_signal=True,
+                    signal_publisher=publish,
+                )
+
+            def claim():
+                return claim_local_weak_signal(
+                    expected_service_id=SERVICE_ID,
+                    expected_routing_key=ROUTING_KEY,
+                    now=110.0,
+                    handoff_root=root,
+                )
+
+            with (
+                patch(
+                    "tools.debug_ita_book.resolve_chrome_path",
+                    return_value=Path("/test/chrome"),
+                ),
+                patch(
+                    "tools.debug_ita_book._get_credentials",
+                    return_value=("user@example.test", "user-password"),
+                ),
+                patch(
+                    "tools.debug_ita_book._assert_distinct_local_accounts"
+                ),
+                patch("tools.debug_ita_book.ItaPlugin", _FlowBookPlugin),
+                patch.dict("tools.debug_ita_book.os.environ", {}, clear=False),
+                redirect_stdout(book_stdout),
+                redirect_stderr(stderr),
+            ):
+                book_exit = run_book_recheck_once(
+                    {},
+                    non_interactive=True,
+                    wait_for_local_signal=True,
+                    signal_timeout=1,
+                    signal_claimer=claim,
+                    monotonic=lambda: 0.0,
+                    sleep=lambda _seconds: None,
+                )
+
+            query_plugin = _FlowQueryPlugin.last_instance
+            book_plugin = _FlowBookPlugin.last_instance
+            self.assertEqual(monitor_exit, 4)
+            self.assertEqual(book_exit, 4)
+            self.assertIsNot(query_plugin, book_plugin)
+            self.assertEqual(query_plugin.query_calls, 1)
+            self.assertEqual(query_plugin.book_calls, 0)
+            self.assertEqual(book_plugin.query_calls, 0)
+            self.assertEqual(book_plugin.book_calls, 1)
+            self.assertTrue(book_plugin.last_trigger.success)
+            self.assertEqual(
+                book_plugin.last_trigger.availability_status,
+                AvailabilityStatus.NoneAvailable,
+            )
+            self.assertEqual(book_plugin.cleanup_calls, 1)
+            self.assertIn(
+                "ITA_MONITOR_HANDOFF_PUBLISHED",
+                query_stdout.getvalue(),
+            )
+            self.assertIn("ITA_BOOK_SIGNAL_CLAIMED", book_stdout.getvalue())
+            self.assertIn(
+                "stage=before-avanti submit_attempts=0",
+                book_stdout.getvalue(),
+            )
+            combined_output = query_stdout.getvalue() + book_stdout.getvalue()
+            for secret in (
+                "query@example.test",
+                "query-password",
+                "user@example.test",
+                "user-password",
+            ):
+                self.assertNotIn(secret, combined_output)
+            self.assertIsNone(claim())
+            self.assertEqual(stderr.getvalue(), "")
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 177 - 0
test/test_ita_otp.py

@@ -0,0 +1,177 @@
+"""Italy-only cloud OTP contract: synthetic messages, no network or credentials."""
+import logging
+import traceback
+from io import StringIO
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+from plugins import ita_otp as otp
+from plugins.ita_calendar_query import CalendarGateError
+from plugins.ita_protocol import OtpMailConfig, ItaProtocolError, parse_otp_body, resolve_route_config
+from vs_types import BizLogicError, PermissionDeniedError, SessionExpiredOrInvalidError
+
+
+class OtpParserTests(TestCase):
+    def test_observed_marker_preserves_zero_and_deduplicates_mime_alternatives(self):
+        self.assertEqual(parse_otp_body('OTP Code:001234 <p>OTP Code: <b>001234</b></p>'), '001234')
+
+    def test_rejects_unknown_ambiguous_and_malformed_messages(self):
+        for body in (None, '', '123456', 'OTP Code:1234567', 'OTP Code:123456x',
+                     'OTP Code:123456', 'OTP Code:1234567',
+                     'OTP Code:123456 OTP Code:654321'):
+            with self.subTest(body=body), self.assertRaises(ItaProtocolError):
+                parse_otp_body(body)
+        with self.assertRaises(ItaProtocolError):
+            parse_otp_body('OTP Code:123456', max_chars=5)
+
+    def test_mail_filters_cannot_be_broadened(self):
+        for field, value in [('subject_keywords', 'OTP Code,anything'), ('body_keywords', 'Code'),
+                             ('expiry_seconds', True), ('expiry_seconds', 301)]:
+            with self.subTest(field=field), self.assertRaises(ItaProtocolError):
+                OtpMailConfig('mailbox@example.test', **{field: value})
+
+    def test_account_source_resolves_each_mailbox_without_mutating_shared_config(self):
+        config = OtpMailConfig(authorization_source="account")
+        for address in ("first@example.test", "second@example.test", "first@example.test"):
+            self.assertEqual(config.mailbox_for(address), address)
+            self.assertIsNone(config.authorization_email)
+            self.assertNotIn(address, repr(config))
+        self.assertEqual(config.authorization_source, "account")
+        with self.assertRaises(ItaProtocolError):
+            config.mailbox_for("not-an-email")
+
+    def test_mailbox_source_is_explicit_and_rejects_ambiguous_configuration(self):
+        for config in ({}, {"authorization_source": "unknown"}, {"authorization_source": None},
+                       {"authorization_source": "account", "authorization_email": "old@example.test"},
+                       {"authorization_source": "account", "authorization_email": ""}):
+            with self.subTest(config=config), self.assertRaises(ItaProtocolError):
+                OtpMailConfig(**config)
+        fixed = OtpMailConfig("shared@example.test")
+        self.assertEqual(fixed.mailbox_for("different@example.test"), "shared@example.test")
+
+    def test_route_parser_accepts_account_source_without_widening_sender_filters(self):
+        from test.test_ita_protocol import live_route
+        route = live_route()
+        route["mail"] = {"authorization_source": "account"}
+        result = resolve_route_config({"slot.sample.it.tourist": route}, "slot.sample.it.tourist")
+        self.assertEqual(result.mail.mailbox_for("pooled@example.test"), "pooled@example.test")
+        for key, value in (("sender", "other@example.test"), ("subject_keywords", "anything"),
+                           ("body_keywords", "anything"), ("expiry_seconds", 301)):
+            with self.subTest(key=key), self.assertRaises(ItaProtocolError):
+                changed = {**route, "mail": {**route["mail"], key: value}}
+                resolve_route_config({"slot.sample.it.tourist": changed}, "slot.sample.it.tourist")
+
+
+class CloudOtpTests(TestCase):
+    def setUp(self):
+        self.config = OtpMailConfig('mailbox@example.test')
+        self.client = Mock()
+        self.client.fetch_mail_content.return_value = 'OTP Code:001234'
+        self.logger = logging.Logger('offline-italy', level=logging.INFO)
+        p = patch.object(otp.vs_log_macros, '_active_logger', self.logger)
+        p.start()
+        self.addCleanup(p.stop)
+
+    def fetch(self):
+        return otp.fetch_otp_from_cloud(self.config, recipient='applicant@example.test',
+            sent_at='2026-08-31 01:02:03', api=self.client)
+
+    def test_exact_sdk_call_and_no_top_fallback(self):
+        self.assertEqual(self.fetch(), '001234')
+        self.client.fetch_mail_content.assert_called_once_with(
+            email='mailbox@example.test', sender='noreply-prenotami@esteri.it',
+            recipient='applicant@example.test', subject_keywords='OTP Code',
+            body_keywords='OTP Code:', sent_date='2026-08-31 01:02:03', expiry=300, only_text=True)
+        self.client.fetch_mail_content_from_top.assert_not_called()
+
+    def test_account_source_uses_each_actual_account_for_mailbox_and_recipient(self):
+        config = OtpMailConfig(authorization_source="account")
+        for address in ("first@example.test", "second@example.test", "first@example.test"):
+            with self.subTest(address=address):
+                self.client.reset_mock()
+                self.assertEqual(otp.fetch_otp_from_cloud(config, recipient=address,
+                    sent_at="2026-08-31 01:02:03", api=self.client), "001234")
+                self.client.fetch_mail_content.assert_called_once_with(
+                    email=address, recipient=address, sender="noreply-prenotami@esteri.it",
+                    subject_keywords="OTP Code", body_keywords="OTP Code:",
+                    sent_date="2026-08-31 01:02:03", expiry=300, only_text=True)
+                self.client.fetch_mail_content_from_top.assert_not_called()
+                self.assertIsNone(config.authorization_email)
+
+    def test_account_mailbox_failure_does_not_read_another_inbox(self):
+        config = OtpMailConfig(authorization_source="account")
+        self.client.fetch_mail_content.side_effect = PermissionDeniedError("private-provider-details")
+        with self.assertRaisesRegex(CalendarGateError, "not permitted"):
+            otp.fetch_otp_from_cloud(config, recipient="second@example.test",
+                sent_at="2026-08-31 01:02:03", api=self.client)
+        self.client.fetch_mail_content.assert_called_once()
+        self.assertEqual(self.client.fetch_mail_content.call_args.kwargs["email"], "second@example.test")
+        self.client.fetch_mail_content_from_top.assert_not_called()
+
+    def test_debug_logging_is_rejected_without_mutating_shared_logger_or_reading_mail(self):
+        self.logger.setLevel(logging.DEBUG)
+        before = list(self.logger.filters)
+        with self.assertRaisesRegex(CalendarGateError, 'DEBUG'):
+            self.fetch()
+        self.client.fetch_mail_content.assert_not_called()
+        self.assertEqual(self.logger.filters, before)
+        self.assertEqual(self.logger.level, logging.DEBUG)
+
+    def test_provider_failures_are_redacted_and_not_site_session_errors(self):
+        marker = 'PRIVATE_MAIL_CONTENT_001234'
+        for error in (BizLogicError(marker), PermissionDeniedError(marker),
+                      SessionExpiredOrInvalidError(marker), ValueError(marker), TimeoutError(marker)):
+            self.client.reset_mock()
+            self.client.fetch_mail_content.side_effect = error
+            with self.subTest(error=type(error).__name__):
+                with self.assertRaises(CalendarGateError) as caught:
+                    self.fetch()
+                rendered = ''.join(traceback.format_exception(caught.exception))
+                self.assertNotIn(marker, rendered)
+                self.client.fetch_mail_content.assert_called_once()
+                self.client.fetch_mail_content_from_top.assert_not_called()
+
+    def test_invalid_input_never_reads_mail(self):
+        with self.assertRaises(CalendarGateError):
+            otp.fetch_otp_from_cloud(self.config, recipient='not-an-address', sent_at='invalid', api=self.client)
+        self.client.fetch_mail_content.assert_not_called()
+
+    def test_real_sdk_contract_with_fake_transport_and_no_payload_output(self):
+        # Exercise the actual VFS/BLS shared SDK without its singleton settings
+        # or any external HTTP. Neither existing SDK nor global log state is edited.
+        client = object.__new__(otp.VSCloudApi)
+        client.base_url = "https://mail.example.test"
+        client.api_token = "synthetic-only"
+        client.session = Mock()
+        output = StringIO()
+        self.logger.addHandler(logging.StreamHandler(output))
+        for status in (200, 401, 403, 429, 504):
+            with self.subTest(status=status):
+                response = Mock(status_code=status, text="PRIVATE_MAIL OTP Code:001234")
+                response.json.return_value = {"code": 0, "data": {"body": "OTP Code:001234"}}
+                client.session.request.reset_mock()
+                client.session.request.return_value = response
+                if status == 200:
+                    self.assertEqual(otp.fetch_otp_from_cloud(self.config,
+                        recipient="applicant@example.test", sent_at="2026-08-31 01:02:03", api=client), "001234")
+                else:
+                    with self.assertRaises(CalendarGateError) as raised:
+                        otp.fetch_otp_from_cloud(self.config, recipient="applicant@example.test",
+                                                sent_at="2026-08-31 01:02:03", api=client)
+                    rendered = ''.join(traceback.format_exception(raised.exception))
+                    self.assertNotIn("PRIVATE_MAIL", rendered)
+                    self.assertNotIn("001234", rendered)
+                client.session.request.assert_called_once()
+                args = client.session.request.call_args.kwargs
+                self.assertEqual(args["params"]["sentDate"], "2026-08-31 01:02:03")
+                self.assertEqual(args["params"]["expiry"], "300")
+                self.assertEqual(args["timeout"], 300)
+        self.assertEqual(output.getvalue(), "")
+
+    def test_bad_mail_body_is_rejected_without_fallback(self):
+        for body in (None, "unknown template", "OTP Code:123456 OTP Code:654321"):
+            with self.subTest(body=body):
+                self.client.fetch_mail_content.return_value = body
+                with self.assertRaises(CalendarGateError):
+                    self.fetch()
+                self.client.fetch_mail_content_from_top.assert_not_called()

+ 1455 - 0
test/test_ita_plugin.py

@@ -0,0 +1,1455 @@
+import inspect
+import json
+import shutil
+import subprocess
+import sys
+import threading
+import types
+import unittest
+from datetime import date
+from pathlib import Path
+from tempfile import TemporaryDirectory
+from unittest.mock import Mock, patch
+
+from plugins.ita_plugin import (
+    BOOKING_FORM_DISCOVERY_STOP_LABEL,
+    BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+    PERSISTENT_BROWSER_PROFILE_KEY,
+    SERVICE_LINK_WAIT_SECONDS,
+    SERVICE_LIST_DIAGNOSTIC_SCRIPT,
+    ItaAuthenticationChallengeError,
+    ItaPlugin,
+    ItaTargetServiceLinkMissingError,
+)
+
+try:
+    from booker import OrderBookerGCO
+except ModuleNotFoundError as exc:
+    if exc.name != "redis":
+        raise
+    redis_stub = types.ModuleType("redis")
+    redis_stub.Redis = Mock
+    with patch.dict(sys.modules, {"redis": redis_stub}):
+        from booker import OrderBookerGCO
+from vs_types import (
+    AppointmentType,
+    AvailabilityStatus,
+    BizLogicError,
+    GroupConfig,
+    SessionExpiredOrInvalidError,
+    Task,
+    VSAccount,
+    VSPlgConfig,
+    VSQueryResult,
+)
+
+
+class FakeChromiumOptions:
+    def set_local_port(self, _port):
+        return self
+
+    def set_user_data_path(self, _path):
+        return self
+
+    def set_paths(self, **_kwargs):
+        return self
+
+    def set_argument(self, _argument):
+        return self
+
+    def headless(self, _enabled):
+        return self
+
+
+class FakeWait:
+    def doc_loaded(self):
+        return None
+
+    def load_start(self):
+        return None
+
+
+class FakeRect:
+    viewport_size = (1920, 1080)
+
+
+class FakeElement:
+    def __init__(self, page, name):
+        self.page = page
+        self.name = name
+
+    def input(self, value, clear=False):
+        self.page.input_values[self.name] = {
+            "value": value,
+            "clear": clear,
+        }
+
+
+class FakePage:
+    URLS = {
+        "landing": "https://prenotami.esteri.it/",
+        "pingid": (
+            "https://iam.esteri.it/signin/?realm=/external"
+            "&state=sensitive-state"
+            "&code_challenge=sensitive-challenge#/"
+        ),
+        "dashboard": "https://prenotami.esteri.it/UserArea",
+        "services": "https://prenotami.esteri.it/Services",
+        "radware": (
+            "https://validate.perfdrive.com/"
+            "8ab9454422ad153e7d4ce3a5b41556a7/"
+        ),
+    }
+
+    def __init__(
+        self,
+        *,
+        submit_succeeds=True,
+        has_services_link=True,
+        login_target="pingid",
+    ):
+        self.state = "landing"
+        self.submit_succeeds = submit_succeeds
+        self.has_services_link = has_services_link
+        self.login_target = login_target
+        self.wait = FakeWait()
+        self.rect = FakeRect()
+        self.clicked = []
+        self.input_values = {}
+        self.refresh_calls = 0
+        self.quit_called = False
+        self.quit_force = None
+
+    @property
+    def url(self):
+        return self.URLS[self.state]
+
+    @property
+    def title(self):
+        return {
+            "landing": "Login",
+            "pingid": "Sign in",
+            "dashboard": "Home",
+            "services": "Services",
+            "radware": "Access Denied",
+        }[self.state]
+
+    @property
+    def html(self):
+        return ""
+
+    def get(self, _url):
+        self.state = "landing"
+
+    def refresh(self):
+        self.refresh_calls += 1
+
+    def quit(self, force=False):
+        self.quit_called = True
+        self.quit_force = force
+
+    def ele(self, selector, timeout=None):
+        del timeout
+        if selector == "tag:a@@href=/Language/ChangeLanguage?lang=2":
+            return FakeElement(self, "language") if self.state == "landing" else None
+        if selector == "#pingid-button" and self.state == "landing":
+            return FakeElement(self, "login")
+        if selector == "@name=callback_1" and self.state == "pingid":
+            return FakeElement(self, "username")
+        if selector == "@name=callback_2" and self.state == "pingid":
+            return FakeElement(self, "password")
+        if selector == "tag:button@type=submit" and self.state == "pingid":
+            return FakeElement(self, "submit")
+        if selector == ".app-menu" and self.state == "dashboard":
+            return FakeElement(self, "app-menu")
+        if (
+            selector == "@href=/Services"
+            and self.state == "dashboard"
+            and self.has_services_link
+        ):
+            return FakeElement(self, "book")
+        return None
+
+
+class FakeMouse:
+    def __init__(self, page, debug=False):
+        self.page = page
+        self.debug = debug
+
+    def move(self, _x, _y):
+        return None
+
+    def human_click_ele(self, element):
+        if element is None:
+            raise AssertionError("The state machine attempted to click a missing element")
+        self.page.clicked.append(element.name)
+        if element.name == "login":
+            self.page.state = self.page.login_target
+        elif element.name == "submit" and self.page.submit_succeeds:
+            self.page.state = "dashboard"
+        elif element.name == "book":
+            self.page.state = "services"
+
+
+class FakeKeyboard:
+    def __init__(self, page):
+        self.page = page
+
+
+class FakeQueryWait:
+    def __init__(self):
+        self.load_start_calls = 0
+        self.doc_loaded_calls = 0
+
+    def load_start(self):
+        self.load_start_calls += 1
+
+    def doc_loaded(self):
+        self.doc_loaded_calls += 1
+
+
+class FakeQueryElement:
+    def __init__(
+        self,
+        page,
+        name,
+        attributes=None,
+        *,
+        text="",
+        property_value=None,
+    ):
+        self.page = page
+        self.name = name
+        self.attributes = attributes or {}
+        self.text = text
+        self.value = property_value
+
+    def attr(self, name):
+        return self.attributes.get(name)
+
+
+class FakeQueryPage:
+    URLS = {
+        "services": "https://prenotami.esteri.it/Services",
+        "user_area": "https://prenotami.esteri.it/UserArea",
+        "no_slots": "https://prenotami.esteri.it/Services",
+        "property_no_slots": "https://prenotami.esteri.it/Services",
+        "visible_no_slots": "https://prenotami.esteri.it/Services",
+        "unknown_popup": "https://prenotami.esteri.it/Services",
+        "empty_warning": "https://prenotami.esteri.it/Services",
+        "login": "https://iam.esteri.it/login/oauth2/authorize",
+        "calendar": "https://prenotami.esteri.it/BookingCalendar",
+        "unknown": "https://prenotami.esteri.it/Unexpected",
+    }
+
+    def __init__(
+        self,
+        outcome="no_slots",
+        *,
+        has_link=True,
+        initial_state="services",
+        service_id=1321,
+        already_booked_notice_rows=0,
+    ):
+        self.outcome = outcome
+        self.has_link = has_link
+        self.state = initial_state
+        self.service_id = service_id
+        self.already_booked_notice_rows = already_booked_notice_rows
+        self.wait = FakeQueryWait()
+        self.clicked = []
+        self.get_calls = []
+        self.looked_up = []
+        self.run_js_calls = []
+
+    @property
+    def url(self):
+        if self.state in {"booking_form", "booking_path_without_form"}:
+            return (
+                "https://prenotami.esteri.it/Services/Booking/"
+                f"{self.service_id}"
+            )
+        return self.URLS[self.state]
+
+    def get(self, url):
+        self.get_calls.append(url)
+        if url != "https://prenotami.esteri.it/Services":
+            raise AssertionError(f"Unexpected query navigation: {url}")
+        self.state = "services"
+
+    def run_js(self, script):
+        self.run_js_calls.append(script)
+        if "coordinate:ita-service-list-structure" in script:
+            return {
+                "path": "/Services",
+                "ready_state": "complete",
+                "table_count": 1,
+                "row_count": 0,
+                "booking_link_count": 0,
+                "target_link_count": 0,
+                "already_booked_notice_row_count": self.already_booked_notice_rows,
+            }
+        if self.state != "booking_form":
+            return None
+        return {
+            "path": f"/Services/Booking/{self.service_id}",
+            "form": {
+                "method": "POST",
+                "action_path": f"/Services/Booking/{self.service_id}",
+                "untrusted": "must-not-survive",
+            },
+            "field_count": 2,
+            "fields_truncated": False,
+            "fields": [
+                {
+                    "tag": "input",
+                    "type": "hidden",
+                    "id": "RequestToken",
+                    "name": "__RequestVerificationToken",
+                    "required": False,
+                    "value": "must-not-survive",
+                },
+                {
+                    "tag": "select",
+                    "type": None,
+                    "id": "BookingType",
+                    "name": "BookingType",
+                    "required": True,
+                },
+            ],
+            "button_count": 1,
+            "buttons_truncated": False,
+            "buttons": [
+                {
+                    "tag": "button",
+                    "type": "submit",
+                    "id": "btnAvanti",
+                    "name": None,
+                    "text": "Avanti",
+                    "value": "must-not-survive",
+                }
+            ],
+            "untrusted": "must-not-survive",
+        }
+
+    def ele(self, selector, timeout=None):
+        self.looked_up.append((selector, timeout))
+        if selector == "#pingid-button" and self.state == "login":
+            return FakeQueryElement(self, "login")
+        if (
+            selector
+            == f"tag:a@@href=/Services/Booking/{self.service_id}"
+            and self.state == "services"
+            and self.has_link
+        ):
+            return FakeQueryElement(self, f"booking-{self.service_id}")
+        if selector == "#WNotAvailable" and self.state == "no_slots":
+            return FakeQueryElement(
+                self,
+                "not-available",
+                {"value": "No appointments are currently available."},
+            )
+        if selector == "#WNotAvailable" and self.state == "property_no_slots":
+            return FakeQueryElement(
+                self,
+                "property-not-available",
+                property_value="No appointments are currently available.",
+            )
+        if selector == "#WNotAvailable" and self.state == "empty_warning":
+            return FakeQueryElement(self, "empty-warning", {"value": "  "})
+        if selector == ".jconfirm-content" and self.state == "visible_no_slots":
+            return FakeQueryElement(
+                self,
+                "visible-not-available",
+                text=(
+                    "  STANTE L’ELEVATA RICHIESTA\n"
+                    "i posti disponibili per il servizio scelto sono esauriti.  "
+                ),
+            )
+        if selector == ".jconfirm-content" and self.state == "unknown_popup":
+            return FakeQueryElement(
+                self,
+                "unknown-popup",
+                text="Il servizio richiede una nuova verifica.",
+            )
+        if selector == "#bookingForm" and self.state == "booking_form":
+            return FakeQueryElement(self, "booking-form")
+        return None
+
+
+class FakeQueryMouse:
+    def __init__(self, page):
+        self.page = page
+
+    def human_click_ele(self, element):
+        if element is None:
+            raise AssertionError("Query attempted to click a missing element")
+        self.page.clicked.append(element.name)
+        self.page.state = self.page.outcome
+
+
+class ItaPluginRandomSleepTests(unittest.TestCase):
+    def test_random_sleep_uses_generated_duration_within_requested_range(self):
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        plugin.group_id = "test-group"
+        plugin.logger = Mock()
+        plugin.page = None
+        plugin.root_workspace = "/nonexistent/ita-plugin-unit-test"
+        plugin.tunnel = None
+
+        with (
+            patch("plugins.ita_plugin.random.uniform", return_value=4.25) as uniform,
+            patch("plugins.ita_plugin.time.sleep") as sleep,
+        ):
+            plugin._random_sleep(3, 5)
+
+        uniform.assert_called_once_with(3, 5)
+        sleep.assert_called_once_with(4.25)
+        plugin.logger.assert_called_once_with(
+            "[ItaPlugin] [test-group] "
+            "Anti-Rate-Limit: Sleeping for 4.25 seconds..."
+        )
+
+
+class ItaPluginCreateSessionStateMachineTests(unittest.TestCase):
+    @staticmethod
+    def _config():
+        return VSPlgConfig(
+            account=VSAccount(
+                id=0,
+                username="offline-test@example.test",
+                password="offline-password",
+            )
+        )
+
+    def test_stops_at_authenticated_user_area_without_opening_services(self):
+        fake_page = FakePage()
+        config = self._config()
+        logger = Mock()
+
+        with TemporaryDirectory() as workspace:
+            with patch(
+                "plugins.ita_plugin.os.path.abspath",
+                return_value=str(Path(workspace)),
+            ):
+                plugin = ItaPlugin("offline-state-machine")
+            plugin.set_log(logger)
+            plugin.set_config(config)
+
+            with (
+                patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
+                patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
+                patch("plugins.ita_plugin.HumanMouse", FakeMouse),
+                patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
+                patch("plugins.ita_plugin.time.sleep"),
+            ):
+                try:
+                    plugin.create_session()
+                finally:
+                    plugin.cleanup()
+
+        self.assertEqual(fake_page.state, "dashboard")
+        self.assertGreater(plugin.session_create_time, 0)
+        self.assertEqual(
+            fake_page.clicked,
+            ["login", "username", "password", "submit"],
+        )
+        self.assertEqual(
+            fake_page.input_values,
+            {
+                "username": {
+                    "value": "offline-test@example.test",
+                    "clear": True,
+                },
+                "password": {
+                    "value": "offline-password",
+                    "clear": True,
+                },
+            },
+        )
+        self.assertEqual(fake_page.refresh_calls, 0)
+        self.assertTrue(fake_page.quit_called)
+
+        log_output = "\n".join(
+            call.args[0] for call in logger.call_args_list if call.args
+        )
+        self.assertIn("https://iam.esteri.it/signin/", log_output)
+        self.assertNotIn("sensitive-state", log_output)
+        self.assertNotIn("sensitive-challenge", log_output)
+
+    def test_never_resubmits_credentials_or_refreshes_after_login_submission(self):
+        fake_page = FakePage(submit_succeeds=False)
+        config = self._config()
+
+        with TemporaryDirectory() as workspace:
+            with patch(
+                "plugins.ita_plugin.os.path.abspath",
+                return_value=str(Path(workspace)),
+            ):
+                plugin = ItaPlugin("offline-stalled-login")
+            plugin.set_log(Mock())
+            plugin.set_config(config)
+
+            with (
+                patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
+                patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
+                patch("plugins.ita_plugin.HumanMouse", FakeMouse),
+                patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
+                patch("plugins.ita_plugin.time.sleep"),
+            ):
+                try:
+                    with self.assertRaisesRegex(
+                        BizLogicError,
+                        "Failed to create authenticated /UserArea session",
+                    ):
+                        plugin.create_session()
+                finally:
+                    plugin.cleanup()
+
+        self.assertEqual(fake_page.clicked.count("login"), 1)
+        self.assertEqual(fake_page.clicked.count("username"), 1)
+        self.assertEqual(fake_page.clicked.count("password"), 1)
+        self.assertEqual(fake_page.clicked.count("submit"), 1)
+        self.assertEqual(fake_page.refresh_calls, 0)
+
+    def test_requires_user_area_services_link_as_authentication_marker(self):
+        fake_page = FakePage(has_services_link=False)
+        config = self._config()
+
+        with TemporaryDirectory() as workspace:
+            with patch(
+                "plugins.ita_plugin.os.path.abspath",
+                return_value=str(Path(workspace)),
+            ):
+                plugin = ItaPlugin("offline-incomplete-dashboard")
+            plugin.set_log(Mock())
+            plugin.set_config(config)
+
+            with (
+                patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
+                patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
+                patch("plugins.ita_plugin.HumanMouse", FakeMouse),
+                patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
+                patch("plugins.ita_plugin.time.sleep"),
+            ):
+                try:
+                    with self.assertRaisesRegex(
+                        BizLogicError,
+                        "Failed to create authenticated /UserArea session",
+                    ):
+                        plugin.create_session()
+                finally:
+                    plugin.cleanup()
+
+        self.assertEqual(fake_page.state, "dashboard")
+        self.assertEqual(fake_page.clicked.count("submit"), 1)
+
+    def test_create_session_source_has_no_language_or_services_navigation(self):
+        create_session_source = inspect.getsource(ItaPlugin.create_session)
+
+        self.assertNotIn("ChangeLanguage", create_session_source)
+        self.assertNotIn("book_btn", create_session_source)
+
+    def test_radware_validation_is_classified_before_credentials_or_refresh(self):
+        fake_page = FakePage(login_target="radware")
+        config = self._config()
+        logger = Mock()
+
+        with TemporaryDirectory() as workspace:
+            with patch(
+                "plugins.ita_plugin.os.path.abspath",
+                return_value=str(Path(workspace)),
+            ):
+                plugin = ItaPlugin("offline-radware")
+            plugin.set_log(logger)
+            plugin.set_config(config)
+
+            with (
+                patch("plugins.ita_plugin.ChromiumOptions", FakeChromiumOptions),
+                patch("plugins.ita_plugin.ChromiumPage", return_value=fake_page),
+                patch("plugins.ita_plugin.HumanMouse", FakeMouse),
+                patch("plugins.ita_plugin.HumanKeyboard", FakeKeyboard),
+                patch("plugins.ita_plugin.time.sleep"),
+            ):
+                try:
+                    with self.assertRaisesRegex(
+                        ItaAuthenticationChallengeError,
+                        "Radware browser validation",
+                    ):
+                        plugin.create_session()
+                finally:
+                    plugin.cleanup()
+
+        self.assertEqual(fake_page.clicked, ["login"])
+        self.assertEqual(fake_page.input_values, {})
+        self.assertEqual(fake_page.refresh_calls, 0)
+        log_output = "\n".join(
+            call.args[0] for call in logger.call_args_list if call.args
+        )
+        self.assertIn(
+            "https://validate.perfdrive.com/<redacted-challenge>",
+            log_output,
+        )
+        self.assertNotIn("8ab9454422ad153e7d4ce3a5b41556a7", log_output)
+
+
+class ItaPluginPersistentProfileTests(unittest.TestCase):
+    @staticmethod
+    def _new_plugin(*, transient_root: Path, profile_path: Path) -> ItaPlugin:
+        with patch(
+            "plugins.ita_plugin.os.path.abspath",
+            return_value=str(transient_root),
+        ):
+            plugin = ItaPlugin("offline-persistent-profile")
+        plugin.set_config(
+            VSPlgConfig(
+                account=VSAccount(
+                    id=0,
+                    username="offline-test@example.test",
+                    password="offline-password",
+                ),
+                free_config={
+                    PERSISTENT_BROWSER_PROFILE_KEY: str(profile_path),
+                },
+            )
+        )
+        return plugin
+
+    def test_cleanup_preserves_explicit_persistent_profile(self):
+        with TemporaryDirectory() as temp_dir:
+            base = Path(temp_dir)
+            profile_path = base / "persistent" / "profile-id"
+            profile_path.mkdir(parents=True, mode=0o700)
+            profile_path.chmod(0o700)
+            marker = profile_path / "cookie-state"
+            marker.write_text("offline", encoding="utf-8")
+            transient_root = base / "transient"
+
+            plugin = self._new_plugin(
+                transient_root=transient_root,
+                profile_path=profile_path,
+            )
+            plugin.cleanup()
+
+            self.assertEqual(plugin.user_data_path, str(profile_path.resolve()))
+            self.assertTrue(marker.exists())
+            self.assertFalse(transient_root.exists())
+
+    def test_default_cleanup_still_deletes_transient_profile(self):
+        with TemporaryDirectory() as temp_dir:
+            transient_root = Path(temp_dir) / "transient"
+            with patch(
+                "plugins.ita_plugin.os.path.abspath",
+                return_value=str(transient_root),
+            ):
+                plugin = ItaPlugin("offline-transient-profile")
+            marker = Path(plugin.user_data_path) / "cookie-state"
+            marker.parent.mkdir(parents=True)
+            marker.write_text("offline", encoding="utf-8")
+
+            plugin.cleanup()
+
+            self.assertFalse(transient_root.exists())
+
+    def test_persistent_profile_is_exclusively_locked_until_cleanup(self):
+        with TemporaryDirectory() as temp_dir:
+            base = Path(temp_dir)
+            profile_path = base / "persistent" / "profile-id"
+            profile_path.mkdir(parents=True, mode=0o700)
+            profile_path.chmod(0o700)
+            first = self._new_plugin(
+                transient_root=base / "transient-one",
+                profile_path=profile_path,
+            )
+            second = self._new_plugin(
+                transient_root=base / "transient-two",
+                profile_path=profile_path,
+            )
+
+            try:
+                first._acquire_persistent_profile_lock()
+                with self.assertRaisesRegex(BizLogicError, "already in use"):
+                    second._acquire_persistent_profile_lock()
+            finally:
+                first.cleanup()
+
+            try:
+                second._acquire_persistent_profile_lock()
+                self.assertIsNotNone(second._profile_lock_handle)
+            finally:
+                second.cleanup()
+
+    def test_rejects_persistent_profile_inside_temporary_workspace(self):
+        with TemporaryDirectory() as temp_dir:
+            transient_root = Path(temp_dir) / "transient"
+            profile_path = transient_root / "user_data"
+            profile_path.mkdir(parents=True, mode=0o700)
+            profile_path.chmod(0o700)
+
+            with self.assertRaisesRegex(
+                BizLogicError,
+                "outside the temporary workspace",
+            ):
+                self._new_plugin(
+                    transient_root=transient_root,
+                    profile_path=profile_path,
+                )
+
+
+@unittest.skipUnless(shutil.which("node"), "Node is required for the DOM-script fixture")
+class ItaServiceNoticeScriptTests(unittest.TestCase):
+    def _inspect(self, rows):
+        # Execute the production JS against a synthetic DOM, never a live tab.
+        harness = r"""
+const payload = JSON.parse(require('fs').readFileSync(0, 'utf8'));
+const rows = payload.rows.map((cells) => ({cells: cells.map((cell) => ({
+    innerText: cell.text,
+    getClientRects: () => cell.noSize ? [] : [{}],
+    style: {visibility: cell.visibility || 'visible'},
+}))}));
+const table = {querySelectorAll: (selector) => {
+    if (selector !== 'tbody tr') throw Error('unexpected table selector');
+    return rows;
+}};
+const document = {readyState: 'complete', querySelectorAll: (selector) => {
+    if (selector === 'table') return [table];
+    if (selector === 'a[href^="/Services/Booking/"]') return [];
+    throw Error('unexpected document selector');
+}};
+const window = {location: {pathname: '/Services'}, getComputedStyle: (cell) => cell.style};
+process.stdout.write(JSON.stringify(new Function('document', 'window', payload.script)(document, window)));
+"""
+        result = subprocess.run(
+            [shutil.which("node"), "-e", harness],
+            input=json.dumps({"rows": rows, "script": SERVICE_LIST_DIAGNOSTIC_SCRIPT}),
+            text=True, capture_output=True, check=True, timeout=10,
+        )
+        return json.loads(result.stdout)
+
+    def test_only_exact_rendered_notice_matches(self):
+        notice = "Prenotazione già effettuata per questo servizio"
+        for cell, expected in (
+            ({"text": notice}, 1),
+            ({"text": "  PRENOTAZIONE GIÀ\nEFFETTUATA PER QUESTO\u00a0SERVIZIO.  "}, 1),
+            ({"text": notice, "noSize": True}, 0),
+            ({"text": notice, "visibility": "hidden"}, 0),
+            ({"text": "Non " + notice}, 0),
+            ({"text": "PRENOTA"}, 0),
+            ({"text": "Annullata"}, 0),
+            ({"text": "Unknown notice"}, 0),
+        ):
+            with self.subTest(cell=cell):
+                self.assertEqual(self._inspect([[cell]])["already_booked_notice_row_count"], expected)
+
+    def test_counts_rows_not_cells_and_does_not_export_row_content(self):
+        notice = {"text": "Prenotazione già effettuata per questo servizio"}
+        result = self._inspect([[notice, notice, {"text": "synthetic-private-row-value"}]])
+        self.assertEqual(result["already_booked_notice_row_count"], 1)
+        self.assertEqual(result["row_count"], 1)
+        self.assertEqual(result["target_link_count"], 0)
+        self.assertNotIn("synthetic-private-row-value", json.dumps(result))
+        self.assertNotIn("Prenotazione", json.dumps(result))
+
+
+class ItaPluginQuerySafetyTests(unittest.TestCase):
+    @staticmethod
+    def _appointment_type(
+        routing_key="slot.dub.it.tourist",
+        *,
+        city="Dublin",
+    ):
+        return AppointmentType(
+            routing_key=routing_key,
+            city=city,
+            country="Italy",
+            visa_type="Tourist",
+        )
+
+    @staticmethod
+    def _plugin(
+        page,
+        *,
+        service_id=1321,
+        routing_key="slot.dub.it.tourist",
+        query_mode="services_probe",
+        capability="services_probe_only",
+        lookahead_months=3,
+    ):
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        plugin.group_id = "offline-query"
+        plugin.logger = Mock()
+        plugin.page = page
+        plugin.mouse = FakeQueryMouse(page)
+        route = {
+            "service_id": service_id,
+            "capability": capability,
+        }
+        if capability == "single_schengen_tourism":
+            route.update(
+                {
+                    "calendar_scan": {
+                        "lookahead_months": lookahead_months,
+                    },
+                    "form": {
+                        "booking_type_control_id": "typeofbookingddl",
+                        "booking_type_value": "1",
+                        "booking_type_labels": ["Single booking"],
+                        "purpose_control_id": "ddls_0",
+                        "purpose_value": "42",
+                        "purpose_labels": ["Tourism"],
+                    },
+                }
+            )
+        plugin.free_config = {
+            "query_mode": query_mode,
+            "final_submit_enabled": False,
+            "apt_configs": {
+                routing_key: route,
+            },
+        }
+        plugin.ita_url = "https://prenotami.esteri.it"
+        plugin.root_workspace = "/nonexistent/ita-plugin-query-test"
+        plugin.tunnel = None
+        plugin._calendar_query_route_key = (
+            routing_key if query_mode == "calendar" else None
+        )
+        return plugin
+
+    def test_returns_none_available_only_for_non_empty_w_not_available(self):
+        page = FakeQueryPage(outcome="no_slots")
+        plugin = self._plugin(page)
+        apt_type = self._appointment_type()
+
+        result = plugin.query(apt_type)
+
+        self.assertFalse(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
+        self.assertEqual(result.apt_type, apt_type)
+        self.assertEqual(page.clicked, ["booking-1321"])
+        self.assertEqual(page.wait.load_start_calls, 1)
+        self.assertEqual(page.wait.doc_loaded_calls, 2)
+
+    def test_returns_none_available_for_property_only_w_not_available(self):
+        page = FakeQueryPage(outcome="property_no_slots")
+        plugin = self._plugin(page)
+
+        result = plugin.query(self._appointment_type())
+
+        self.assertFalse(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_returns_none_available_for_verified_visible_italian_notice(self):
+        page = FakeQueryPage(outcome="visible_no_slots")
+        plugin = self._plugin(page)
+
+        result = plugin.query(self._appointment_type())
+
+        self.assertFalse(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_unknown_visible_notice_fails_closed(self):
+        page = FakeQueryPage(outcome="unknown_popup")
+        plugin = self._plugin(page)
+
+        with self.assertRaisesRegex(BizLogicError, "unrecognized visible"):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_changed_notice_is_not_guessed_as_no_availability(self):
+        plugin = self._plugin(FakeQueryPage())
+
+        status = plugin._classify_service_notice(
+            "I posti disponibili per il servizio scelto non sono esauriti."
+        )
+
+        self.assertIsNone(status)
+
+    def test_reloads_services_before_each_no_slot_probe(self):
+        page = FakeQueryPage(outcome="no_slots")
+        plugin = self._plugin(page)
+        apt_type = self._appointment_type()
+
+        first_result = plugin.query(apt_type)
+        second_result = plugin.query(apt_type)
+
+        self.assertFalse(first_result.success)
+        self.assertFalse(second_result.success)
+        self.assertEqual(
+            page.get_calls,
+            [
+                "https://prenotami.esteri.it/Services",
+                "https://prenotami.esteri.it/Services",
+            ],
+        )
+        self.assertEqual(page.clicked, ["booking-1321", "booking-1321"])
+        self.assertEqual(page.wait.load_start_calls, 2)
+        self.assertEqual(page.wait.doc_loaded_calls, 4)
+
+    def test_empty_w_not_available_is_not_treated_as_no_slots(self):
+        page = FakeQueryPage(outcome="empty_warning")
+        plugin = self._plugin(page)
+
+        with self.assertRaisesRegex(BizLogicError, "non-empty"):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_booking_form_branch_returns_bls_style_weak_signal(self):
+        page = FakeQueryPage(outcome="booking_form")
+        plugin = self._plugin(page)
+
+        result = plugin.query(self._appointment_type())
+
+        self.assertTrue(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
+        self.assertIsNone(result.earliest_date)
+        self.assertEqual(result.availability, [])
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_booking_form_state_can_be_reprobed_on_the_next_query_cycle(self):
+        page = FakeQueryPage(outcome="booking_form")
+        plugin = self._plugin(page)
+        apt_type = self._appointment_type()
+
+        first_result = plugin.query(apt_type)
+        second_result = plugin.query(apt_type)
+
+        self.assertTrue(first_result.success)
+        self.assertTrue(second_result.success)
+        self.assertEqual(
+            page.get_calls,
+            [
+                "https://prenotami.esteri.it/Services",
+                "https://prenotami.esteri.it/Services",
+            ],
+        )
+        self.assertEqual(page.clicked, ["booking-1321", "booking-1321"])
+
+    def test_booking_path_without_form_fails_closed(self):
+        page = FakeQueryPage(outcome="booking_path_without_form")
+        plugin = self._plugin(page)
+
+        with self.assertRaisesRegex(BizLogicError, "without #bookingForm"):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, ["booking-1321"])
+
+    def test_missing_target_link_is_a_structure_error_not_no_slots(self):
+        page = FakeQueryPage(has_link=False)
+        plugin = self._plugin(page)
+
+        with self.assertRaisesRegex(
+            ItaTargetServiceLinkMissingError,
+            "target service link is missing",
+        ):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, [])
+        self.assertIn(
+            ("tag:a@@href=/Services/Booking/1321", SERVICE_LINK_WAIT_SECONDS),
+            page.looked_up,
+        )
+        self.assertEqual(
+            plugin.last_service_list_structure,
+            {
+                "path": "/Services",
+                "ready_state": "complete",
+                "table_count": 1,
+                "row_count": 0,
+                "booking_link_count": 0,
+                "target_link_count": 0,
+                "already_booked_notice_row_count": 0,
+            },
+        )
+
+    def test_missing_link_with_booked_notice_reports_context_without_attribution(self):
+        page = FakeQueryPage(has_link=False, already_booked_notice_rows=1)
+        plugin = self._plugin(page)
+
+        with self.assertRaises(ItaTargetServiceLinkMissingError) as raised:
+            plugin.query(self._appointment_type())
+
+        self.assertIn("Services contains an already-booked notice", str(raised.exception))
+        self.assertIn("not bound to the configured service ID", str(raised.exception))
+        self.assertEqual(plugin.last_service_list_structure["already_booked_notice_row_count"], 1)
+        self.assertEqual(page.clicked, [])
+        self.assertEqual(page.get_calls, ["https://prenotami.esteri.it/Services"])
+
+    def test_existing_other_service_booking_does_not_block_present_target_link(self):
+        page = FakeQueryPage(outcome="booking_form", already_booked_notice_rows=1)
+        plugin = self._plugin(page)
+
+        result = plugin.query(self._appointment_type())
+
+        self.assertTrue(result.success)
+        self.assertEqual(page.clicked, ["booking-1321"])
+        self.assertFalse(any("service-list-structure" in script for script in page.run_js_calls))
+
+    def test_invalid_notice_counts_do_not_claim_an_existing_booking(self):
+        for raw_count in (None, True, "1", -1, {}, []):
+            with self.subTest(raw_count=raw_count):
+                page = FakeQueryPage(has_link=False, already_booked_notice_rows=raw_count)
+                plugin = self._plugin(page)
+                with self.assertRaises(ItaTargetServiceLinkMissingError) as raised:
+                    plugin.query(self._appointment_type())
+                self.assertNotIn("already-booked notice", str(raised.exception))
+                self.assertEqual(page.clicked, [])
+
+    def test_book_propagates_existing_notice_without_creating_a_success(self):
+        page = FakeQueryPage(has_link=False, already_booked_notice_rows=1)
+        plugin = self._plugin(page)
+        trigger = VSQueryResult(apt_type=self._appointment_type())
+
+        with self.assertRaisesRegex(ItaTargetServiceLinkMissingError, "already-booked notice"):
+            plugin.book(trigger)
+
+        self.assertIsNone(plugin.last_booking_precommit)
+        self.assertEqual(page.clicked, [])
+
+    def test_invalid_route_service_id_is_a_configuration_error(self):
+        page = FakeQueryPage()
+        plugin = self._plugin(page, service_id=0)
+
+        with self.assertRaisesRegex(
+            BizLogicError,
+            "route configuration rejected.*positive_integer_required",
+        ):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, [])
+
+    def test_second_sede_uses_the_same_query_path_without_a_city_branch(self):
+        routing_key = "slot.hkg.it.tourist"
+        page = FakeQueryPage(
+            outcome="booking_form",
+            service_id=4937,
+        )
+        plugin = self._plugin(
+            page,
+            service_id=4937,
+            routing_key=routing_key,
+        )
+
+        result = plugin.query(
+            self._appointment_type(routing_key, city="Hong Kong")
+        )
+
+        self.assertTrue(result.success)
+        self.assertEqual(page.clicked, ["booking-4937"])
+
+    def test_calendar_mode_returns_vfs_style_earliest_date_only(self):
+        routing_key = "slot.sample.it.tourist"
+        page = FakeQueryPage(initial_state="calendar", service_id=9001)
+        plugin = self._plugin(
+            page,
+            service_id=9001,
+            routing_key=routing_key,
+            query_mode="calendar",
+            capability="single_schengen_tourism",
+            lookahead_months=12,
+        )
+        apt_type = self._appointment_type(
+            routing_key,
+            city="Sample City",
+        )
+        scan = types.SimpleNamespace(
+            earliest_available_date=date(2026, 10, 12)
+        )
+
+        with patch(
+            "plugins.ita_plugin.scan_until_first_available_month",
+            return_value=scan,
+        ) as scanner:
+            result = plugin.query(apt_type)
+
+        scanner.assert_called_once_with(
+            page,
+            lookahead_months=12,
+            log=plugin._log,
+        )
+        self.assertTrue(result.success)
+        self.assertEqual(
+            result.availability_status,
+            AvailabilityStatus.Available,
+        )
+        self.assertEqual(
+            result.earliest_date.strftime("%Y-%m-%d"),
+            "2026-10-12",
+        )
+        self.assertEqual(len(result.availability), 1)
+        self.assertEqual(
+            result.availability[0].date.strftime("%Y-%m-%d"),
+            "2026-10-12",
+        )
+        self.assertEqual(result.availability[0].times, [])
+        self.assertEqual(page.clicked, [])
+        self.assertIs(plugin.last_calendar_query_scan, scan)
+
+    def test_calendar_diagnostic_does_not_survive_a_failed_query(self):
+        routing_key = "slot.sample.it.tourist"
+        page = FakeQueryPage(initial_state="calendar", service_id=9001)
+        plugin = self._plugin(
+            page,
+            service_id=9001,
+            routing_key=routing_key,
+            query_mode="calendar",
+            capability="single_schengen_tourism",
+        )
+        plugin.last_calendar_query_scan = object()
+        plugin._calendar_query_route_key = None
+
+        with self.assertRaisesRegex(BizLogicError, "route continuity"):
+            plugin.query(self._appointment_type(routing_key, city="Sample City"))
+
+        self.assertIsNone(plugin.last_calendar_query_scan)
+
+    def test_calendar_mode_returns_none_only_after_scanner_exhaustion(self):
+        routing_key = "slot.sample.it.tourist"
+        page = FakeQueryPage(initial_state="calendar", service_id=9001)
+        plugin = self._plugin(
+            page,
+            service_id=9001,
+            routing_key=routing_key,
+            query_mode="calendar",
+            capability="single_schengen_tourism",
+        )
+        apt_type = self._appointment_type(
+            routing_key,
+            city="Sample City",
+        )
+
+        with patch(
+            "plugins.ita_plugin.scan_until_first_available_month",
+            return_value=types.SimpleNamespace(
+                earliest_available_date=None
+            ),
+        ):
+            result = plugin.query(apt_type)
+
+        self.assertFalse(result.success)
+        self.assertEqual(
+            result.availability_status,
+            AvailabilityStatus.NoneAvailable,
+        )
+        self.assertIsNone(result.earliest_date)
+        self.assertEqual(result.availability, [])
+
+    def test_calendar_mode_requires_a_route_confirmed_calendar_session(self):
+        routing_key = "slot.sample.it.tourist"
+        page = FakeQueryPage(initial_state="user_area", service_id=9001)
+        plugin = self._plugin(
+            page,
+            service_id=9001,
+            routing_key=routing_key,
+            query_mode="calendar",
+            capability="single_schengen_tourism",
+        )
+        plugin._calendar_query_route_key = None
+
+        with patch(
+            "plugins.ita_plugin.scan_until_first_available_month"
+        ) as scanner:
+            with self.assertRaisesRegex(
+                BizLogicError,
+                "preparation is not complete",
+            ):
+                plugin.query(
+                    self._appointment_type(
+                        routing_key,
+                        city="Sample City",
+                    )
+                )
+
+        scanner.assert_not_called()
+
+    def test_calendar_mode_rejects_a_different_prepared_route(self):
+        routing_key = "slot.sample.it.tourist"
+        page = FakeQueryPage(initial_state="calendar", service_id=9001)
+        plugin = self._plugin(
+            page,
+            service_id=9001,
+            routing_key=routing_key,
+            query_mode="calendar",
+            capability="single_schengen_tourism",
+        )
+        plugin._calendar_query_route_key = "slot.other.it.tourist"
+
+        with patch(
+            "plugins.ita_plugin.scan_until_first_available_month"
+        ) as scanner:
+            with self.assertRaisesRegex(
+                BizLogicError,
+                "route continuity",
+            ):
+                plugin.query(
+                    self._appointment_type(
+                        routing_key,
+                        city="Sample City",
+                    )
+                )
+
+        scanner.assert_not_called()
+
+    def test_calendar_mode_rejects_a_probe_only_route(self):
+        page = FakeQueryPage(initial_state="calendar")
+        plugin = self._plugin(page, query_mode="calendar")
+
+        with self.assertRaisesRegex(
+            BizLogicError,
+            "single_schengen_tourism",
+        ):
+            plugin.query(self._appointment_type())
+
+    def test_login_redirect_is_reported_as_expired_session(self):
+        page = FakeQueryPage(initial_state="login")
+        plugin = self._plugin(page)
+
+        with self.assertRaises(SessionExpiredOrInvalidError):
+            plugin.query(self._appointment_type())
+
+        self.assertEqual(page.clicked, [])
+
+    def test_query_source_contains_no_otp_or_submission_path(self):
+        query_source = inspect.getsource(ItaPlugin.query)
+        forbidden_fragments = (
+            "otp-send",
+            "otp-input",
+            "123456",
+            "PrivacyCheck",
+            "btnAvanti",
+            "InsertNewBooking",
+            "_perform_request",
+        )
+
+        for fragment in forbidden_fragments:
+            with self.subTest(fragment=fragment):
+                self.assertNotIn(fragment, query_source)
+
+
+class ItaPluginBookDiscoveryTests(unittest.TestCase):
+    @staticmethod
+    def _appointment_type():
+        return AppointmentType(
+            routing_key="slot.dub.it.tourist",
+            city="Dublin",
+            country="Italy",
+            visa_type="Tourist",
+        )
+
+    @classmethod
+    def _weak_signal(cls):
+        return VSQueryResult(
+            success=False,
+            apt_type=cls._appointment_type(),
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+
+    @staticmethod
+    def _plugin(page):
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        plugin.group_id = "offline-book-discovery"
+        plugin.logger = Mock()
+        plugin.page = page
+        plugin.mouse = FakeQueryMouse(page)
+        plugin.free_config = {
+            "query_mode": "services_probe",
+            "final_submit_enabled": False,
+            "apt_configs": {
+                "slot.dub.it.tourist": {
+                    "service_id": 1321,
+                    "capability": "services_probe_only",
+                }
+            },
+        }
+        plugin.ita_url = "https://prenotami.esteri.it"
+        plugin.root_workspace = "/nonexistent/ita-plugin-book-test"
+        plugin.tunnel = None
+        return plugin
+
+    def test_book_rechecks_once_and_returns_false_when_user_has_no_slot(self):
+        page = FakeQueryPage(outcome="no_slots", initial_state="user_area")
+        plugin = self._plugin(page)
+
+        result = plugin.book(self._weak_signal(), user_inputs={})
+
+        self.assertFalse(result.success)
+        self.assertEqual(result.label, BOOKING_RECHECK_NONE_AVAILABLE_LABEL)
+        self.assertEqual(page.clicked, ["booking-1321"])
+        self.assertEqual(page.run_js_calls, [])
+
+    def test_book_reads_allowlisted_structure_and_stops_before_avanti(self):
+        page = FakeQueryPage(outcome="booking_form", initial_state="user_area")
+        plugin = self._plugin(page)
+
+        result = plugin.book(self._weak_signal(), user_inputs={})
+
+        self.assertFalse(result.success)
+        self.assertEqual(result.label, BOOKING_FORM_DISCOVERY_STOP_LABEL)
+        self.assertEqual(page.clicked, ["booking-1321"])
+        self.assertEqual(len(page.run_js_calls), 1)
+        structure = plugin.last_booking_form_structure
+        self.assertEqual(structure["path"], "/Services/Booking/1321")
+        self.assertEqual(structure["form"]["method"], "POST")
+        self.assertEqual(structure["field_count"], 2)
+        self.assertNotIn("value", structure["fields"][0])
+        self.assertNotIn("untrusted", str(structure))
+
+    def test_book_fails_closed_when_form_metadata_has_an_unexpected_path(self):
+        page = FakeQueryPage(outcome="booking_form", initial_state="user_area")
+        page.state = "booking_form"
+        structure = page.run_js("fixture")
+        page.state = "user_area"
+        structure["path"] = "/Unexpected"
+        page.run_js_calls.clear()
+        page.run_js = Mock(return_value=structure)
+        plugin = self._plugin(page)
+
+        with self.assertRaisesRegex(BizLogicError, "unexpected path"):
+            plugin.book(self._weak_signal(), user_inputs={})
+
+        self.assertEqual(page.clicked, ["booking-1321"])
+        self.assertEqual(page.run_js.call_count, 1)
+
+    def test_book_source_contains_no_form_submission_calendar_or_otp_path(self):
+        book_source = inspect.getsource(ItaPlugin.book)
+        forbidden_fragments = (
+            "GenerateOTP",
+            "get_email_verify_code",
+            "fetch_mail_content",
+            "PrivacyCheck",
+            "btnAvanti",
+            "BookingCalendar",
+            "InsertNewBooking",
+            "_perform_request",
+            ".submit(",
+            ".click(",
+        )
+
+        for fragment in forbidden_fragments:
+            with self.subTest(fragment=fragment):
+                self.assertNotIn(fragment, book_source)
+
+
+class FakeRetainedSignalRedis:
+    def __init__(self, payload, clock, *, ttl):
+        self.payload = json.dumps(payload)
+        self.clock = clock
+        self.ttl = ttl
+
+    def get(self, _name):
+        if self.clock["now"] <= self.ttl:
+            return self.payload
+        return None
+
+    def delete(self, *_names):
+        return 0
+
+
+class CountingItaOrderBooker(OrderBookerGCO):
+    def _execute_book_job(self, task, query_result):
+        del task, query_result
+        self.book_calls += 1
+
+
+class ItaSignalReuseTests(unittest.TestCase):
+    @staticmethod
+    def _appointment_type():
+        return AppointmentType(
+            routing_key="slot.dub.it.tourist",
+            city="Dublin",
+            country="Italy",
+            visa_type="Tourist",
+        )
+
+    def test_retained_thirty_second_signal_triggers_one_book_call(self):
+        apt_type = self._appointment_type()
+        weak_result = VSQueryResult(
+            success=True,
+            apt_type=apt_type,
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+        payload = {
+            "apt_type": apt_type.model_dump(),
+            "query_result": weak_result.to_snapshot_payload(),
+        }
+        clock = {"now": 0.0}
+
+        task = Task(
+            instance=Mock(),
+            next_run=0.0,
+            task_ref=1,
+            acceptable_routing_keys=[apt_type.routing_key],
+            source_queue=apt_type.routing_key,
+            book_allowed=True,
+        )
+        config = GroupConfig(
+            identifier="pernotami.ie.it",
+            appointment_types=[apt_type],
+            booker={
+                "account_source": "order",
+                "target_instances": 1,
+                "booking_cooldown": 45,
+            },
+        )
+
+        booker = CountingItaOrderBooker.__new__(CountingItaOrderBooker)
+        booker.m_cfg = config
+        booker.m_logger = Mock()
+        booker.m_tasks = [task]
+        booker.m_lock = threading.RLock()
+        booker.m_stop_event = threading.Event()
+        booker.m_task_data_cache = {}
+        booker.redis_client = FakeRetainedSignalRedis(payload, clock, ttl=30)
+        booker.book_calls = 0
+
+        def fake_sleep(seconds):
+            clock["now"] += seconds
+            if clock["now"] > 31:
+                booker.m_stop_event.set()
+
+        booker_time = OrderBookerGCO._booking_trigger_loop.__globals__["time"]
+        with (
+            patch.object(booker_time, "sleep", side_effect=fake_sleep),
+            patch.object(booker_time, "time", side_effect=lambda: clock["now"]),
+        ):
+            booker._booking_trigger_loop()
+
+        self.assertEqual(booker.book_calls, 1)
+        self.assertGreater(task.next_run, 30)
+
+    def test_italy_config_keeps_existing_single_worker_cooldown_contract(self):
+        repo_root = Path(__file__).resolve().parents[1]
+        booker_groups = json.loads(
+            (repo_root / "config" / "config_booker.json").read_text()
+        )
+        sentinel_groups = json.loads(
+            (repo_root / "config" / "config_sentinel.json").read_text()
+        )
+        booker_group = next(
+            group
+            for group in booker_groups
+            if group["identifier"] == "pernotami.ie.it"
+        )
+        sentinel_group = next(
+            group
+            for group in sentinel_groups
+            if group["identifier"] == "pernotami.ie.it"
+        )
+
+        self.assertEqual(booker_group["booker"]["target_instances"], 1)
+        self.assertEqual(sentinel_group["sentinel"]["target_instances"], 1)
+        self.assertGreater(
+            booker_group["booker"]["booking_cooldown"],
+            sentinel_group["sentinel"]["signal_ttl"],
+        )
+        self.assertGreater(
+            sentinel_group["sentinel"]["query_wait"]["random_min"],
+            booker_group["booker"]["booking_cooldown"],
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 179 - 0
test/test_ita_preflight.py

@@ -0,0 +1,179 @@
+"""Offline regression for Italy form readiness; never contact the real site."""
+import io
+import json
+from contextlib import redirect_stdout
+from types import SimpleNamespace
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+from plugins import ita_calendar_session as session
+from plugins import ita_turnstile as turnstile
+from test.test_debug_ita_calendar_gate import booking_preflight_snapshot
+
+
+class PreflightWaitTests(TestCase):
+    def run_wait(self, raw, **kwargs):
+        page = SimpleNamespace(run_js=Mock(return_value=raw))
+        with patch.object(session.time, 'monotonic', side_effect=[0, 0, 121]), \
+             patch.object(session.time, 'sleep'):
+            return session.wait_for_booking_preflight(page, script='offline', **kwargs)
+
+    def test_timeout_distinguishes_token_and_button(self):
+        for token, disabled, expected in (
+            (False, False, 'turnstile_token_pending'),
+            (True, True, 'avanti_disabled'),
+            (False, True, 'turnstile_and_avanti_pending'),
+        ):
+            with self.subTest(expected=expected), redirect_stdout(io.StringIO()):
+                with self.assertRaises(session.CalendarGateError) as raised:
+                    self.run_wait(booking_preflight_snapshot(
+                        turnstileTokenPresent=token, avantiDisabled=disabled))
+                self.assertIn(expected, str(raised.exception))
+
+    def test_production_default_diagnostic_survives_timeout_without_private_values(self):
+        raw = booking_preflight_snapshot(turnstileTokenPresent=False)
+        raw.update(token='PRIVATE-TOKEN', email='private@example.test',
+                   turnstileApiPresent=True, documentVisible=False)
+        output = io.StringIO()
+        with redirect_stdout(output), self.assertRaises(session.CalendarGateError):
+            self.run_wait(raw)
+        lines = [line.split('=', 1)[1] for line in output.getvalue().splitlines()
+                 if line.startswith('ITA_BOOK_PREFLIGHT_DIAGNOSTIC=')]
+        self.assertTrue(lines)
+        payload = json.loads(lines[-1])
+        self.assertEqual(payload['outcome'], 'timeout')
+        self.assertFalse(payload['turnstileTokenPresent'])
+        self.assertFalse(payload['avantiDisabled'])
+        self.assertTrue(payload['turnstileApiPresent'])
+        self.assertNotIn('PRIVATE-TOKEN', output.getvalue())
+        self.assertNotIn('private@example.test', output.getvalue())
+
+    def test_ready_never_invokes_recovery(self):
+        action = Mock()
+        with redirect_stdout(io.StringIO()):
+            self.run_wait(booking_preflight_snapshot(), wait_action=action)
+        action.assert_not_called()
+
+    def test_bad_structure_never_invokes_recovery(self):
+        action = Mock()
+        with redirect_stdout(io.StringIO()), self.assertRaises(session.CalendarGateError):
+            self.run_wait(booking_preflight_snapshot(formPresent=False), wait_action=action)
+        action.assert_not_called()
+
+    def test_session_guard_runs_before_dom_read(self):
+        current = Mock(side_effect=session.CalendarGateError('session changed'))
+        page = SimpleNamespace(run_js=Mock())
+        with self.assertRaises(session.CalendarGateError):
+            session.wait_for_booking_preflight(page, script='offline', check_current=current)
+        page.run_js.assert_not_called()
+
+    def test_wait_action_does_not_substitute_for_a_new_ready_snapshot(self):
+        raw = booking_preflight_snapshot(turnstileTokenPresent=False)
+        action = Mock(return_value=True)
+        with redirect_stdout(io.StringIO()), self.assertRaises(session.CalendarGateError):
+            self.run_wait(raw, wait_action=action)
+        action.assert_called_once()
+
+    def test_bad_dynamic_boolean_is_not_hidden_by_wait_validation(self):
+        for field in ('turnstileTokenPresent', 'avantiDisabled'):
+            with self.subTest(field=field), redirect_stdout(io.StringIO()), \
+                 self.assertRaisesRegex(session.CalendarGateError, field):
+                self.run_wait(booking_preflight_snapshot(**{field: 'private-string'}))
+
+    def test_dom_exception_is_redacted(self):
+        page = SimpleNamespace(run_js=Mock(side_effect=ValueError('PRIVATE_JS_VALUE')))
+        output = io.StringIO()
+        with redirect_stdout(output), self.assertRaisesRegex(session.CalendarGateError, 'read_failed') as raised:
+            session.wait_for_booking_preflight(page, script='offline')
+        self.assertNotIn('PRIVATE_JS_VALUE', str(raised.exception) + output.getvalue())
+
+    def test_wait_can_observe_readiness_after_recovery(self):
+        page = SimpleNamespace(run_js=Mock(side_effect=[
+            booking_preflight_snapshot(turnstileTokenPresent=False), booking_preflight_snapshot()]))
+        action = Mock()
+        with patch.object(session.time, 'monotonic', side_effect=[0, 0, 1]), \
+             patch.object(session.time, 'sleep'), redirect_stdout(io.StringIO()):
+            result = session.wait_for_booking_preflight(page, script='offline', wait_action=action)
+        self.assertTrue(result['turnstileTokenPresent'])
+        self.assertEqual(page.run_js.call_count, 2)
+        action.assert_called_once()
+
+
+class TurnstileRecoveryTests(TestCase):
+    def setUp(self):
+        self.page = SimpleNamespace(title='Booking - Prenot@Mi', refresh=Mock(), run_js=Mock())
+        self.guard = Mock()
+        self.recovery = turnstile.ItalyTurnstileRecovery(self.page, check_current=self.guard)
+        self.helper = Mock()
+        self.helper.click_verification_button.return_value = True
+        self.factory = patch.object(turnstile, 'CloudflareBypasser', return_value=self.helper)
+        self.factory_mock = self.factory.start()
+        self.addCleanup(self.factory.stop)
+
+    def attempt(self, elapsed=5, remaining=100, raw=None, stage=None):
+        self.recovery(raw if raw is not None else booking_preflight_snapshot(turnstileTokenPresent=False),
+            stage=stage or session.BookingPreflightStage.BEFORE_OTP_SEND,
+            elapsed=elapsed, remaining=remaining)
+
+    def test_reuses_vfs_widget_method_not_title_based_bypass(self):
+        with redirect_stdout(io.StringIO()):
+            self.attempt()
+        self.factory_mock.assert_called_once_with(self.page, log=False)
+        self.helper.click_verification_button.assert_called_once_with(is_dfs=False)
+        self.helper.bypass.assert_not_called()
+        self.page.refresh.assert_not_called()
+        self.page.run_js.assert_not_called()
+        self.assertEqual(self.guard.call_count, 2)
+
+    def test_waits_initially_and_leaves_successful_widget_untouched(self):
+        self.attempt(elapsed=4)
+        self.attempt(elapsed=5, remaining=1)
+        self.attempt(raw=booking_preflight_snapshot(avantiDisabled=True))
+        self.attempt(raw=booking_preflight_snapshot())
+        self.factory_mock.assert_not_called()
+
+    def test_attempt_budget_and_interval_apply_even_if_control_cannot_be_clicked(self):
+        self.helper.click_verification_button.return_value = False
+        with redirect_stdout(io.StringIO()):
+            for seconds in (5, 5.5, 10, 15, 16, 25, 35, 55, 100):
+                self.attempt(elapsed=seconds)
+        self.assertEqual(self.recovery.attempts, 3)
+        self.assertEqual(self.helper.click_verification_button.call_count, 3)
+
+    def test_stage_change_does_not_reset_total_attempt_budget(self):
+        with redirect_stdout(io.StringIO()):
+            for seconds in (5, 15, 25):
+                self.attempt(elapsed=seconds)
+            self.attempt(elapsed=5, stage=session.BookingPreflightStage.AFTER_OTP_SEND)
+        self.assertEqual(self.helper.click_verification_button.call_count, 3)
+
+    def test_wrong_form_or_missing_field_cannot_interact(self):
+        for changes in ({'formPresent': False}, {'pathMatches': False}, {'turnstileCount': 2}):
+            with self.subTest(changes=changes), self.assertRaises(session.CalendarGateError):
+                self.attempt(raw=booking_preflight_snapshot(turnstileTokenPresent=False, **changes))
+        self.factory_mock.assert_not_called()
+
+    def test_session_change_prevents_interaction(self):
+        self.guard.side_effect = session.CalendarGateError('session changed')
+        with self.assertRaises(session.CalendarGateError):
+            self.attempt()
+        self.factory_mock.assert_not_called()
+
+    def test_helper_errors_are_bounded_and_do_not_leak_browser_data(self):
+        self.helper.click_verification_button.side_effect = RuntimeError('PRIVATE_BROWSER_DATA')
+        output = io.StringIO()
+        with redirect_stdout(output):
+            self.attempt()
+        payload = json.loads(output.getvalue().split('=', 1)[1])
+        self.assertTrue(payload['helperFailed'])
+        self.assertFalse(payload['clicked'])
+        self.assertNotIn('PRIVATE_BROWSER_DATA', output.getvalue())
+        self.assertEqual(self.recovery.attempts, 1)
+
+    def test_interaction_success_alone_cannot_release_preflight(self):
+        page = SimpleNamespace(run_js=Mock(return_value=booking_preflight_snapshot(turnstileTokenPresent=False)))
+        with patch.object(session.time, 'monotonic', side_effect=[0, 5, 121]), \
+             patch.object(session.time, 'sleep'), redirect_stdout(io.StringIO()):
+            with self.assertRaisesRegex(session.CalendarGateError, 'turnstile_token_pending'):
+                session.wait_for_booking_preflight(page, script='offline', wait_action=self.recovery)
+        self.helper.click_verification_button.assert_called_once()

+ 648 - 0
test/test_ita_protocol.py

@@ -0,0 +1,648 @@
+import copy
+import json
+import unittest
+from dataclasses import replace
+from datetime import date, time
+
+from plugins.ita_protocol import (
+    MAX_LOOKAHEAD_MONTHS,
+    MAX_PROTOCOL_ITEMS,
+    CalendarDay,
+    DateSelectionState,
+    InventoryState,
+    ItaCapability,
+    ItaProtocolError,
+    SlotCandidate,
+    SlotSelectionState,
+    approve_precommit,
+    available_calendar_days,
+    available_slot_candidates,
+    decode_double_json_array,
+    month_starts,
+    parse_calendar_availability,
+    parse_time_slots,
+    resolve_route_config,
+)
+
+
+def double_json(items):
+    return json.dumps(json.dumps(items, separators=(",", ":")))
+
+
+def availability_item(day, slots_free, slots_remaining):
+    return {
+        "DateLibere": day,
+        "SlotLiberi": slots_free,
+        "SlotRimanenti": slots_remaining,
+    }
+
+
+def time_value(hours, minutes, *, seconds=0, milliseconds=0):
+    return {
+        "Hours": hours,
+        "Minutes": minutes,
+        "Seconds": seconds,
+        "Milliseconds": milliseconds,
+    }
+
+
+def slot_item(
+    day,
+    start,
+    end,
+    slots_free,
+    slots_remaining,
+    daily_id,
+):
+    return {
+        "Data": day,
+        "OrarioInizioFascia": time_value(*start),
+        "OrarioFineFascia": time_value(*end),
+        "SlotLiberi": slots_free,
+        "SlotRimanenti": slots_remaining,
+        "IDCalendarioServizioGiornaliero": daily_id,
+    }
+
+
+def live_route():
+    return {
+        "service_id": 100,
+        "capability": "single_schengen_tourism",
+        "calendar_scan": {"lookahead_months": 3},
+        "form": {
+            "booking_type_control_id": "booking-type",
+            "booking_type_value": "single",
+            "booking_type_labels": ["Label One", "Label Two"],
+            "purpose_control_id": "purpose",
+            "purpose_value": "tourism",
+            "purpose_labels": ["Purpose One", "Purpose Two"],
+        },
+    }
+
+
+class ProtocolTestCase(unittest.TestCase):
+    def assert_protocol_error(self, code, action):
+        with self.assertRaises(ItaProtocolError) as raised:
+            action()
+        self.assertEqual(raised.exception.code, code)
+
+
+class RouteConfigTests(ProtocolTestCase):
+    def test_resolves_vfs_bls_style_live_route_without_locale_logic(self):
+        routing_key = "slot.sample.it.tourist"
+        result = resolve_route_config({routing_key: live_route()}, routing_key)
+
+        self.assertEqual(result.routing_key, routing_key)
+        self.assertEqual(result.service_id, 100)
+        self.assertIs(result.capability, ItaCapability.SINGLE_SCHENGEN_TOURISM)
+        self.assertEqual(result.calendar_scan.lookahead_months, 3)
+        self.assertEqual(result.booking_type.value, "single")
+        self.assertEqual(result.booking_type.labels, ("Label One", "Label Two"))
+        self.assertEqual(result.purpose.value, "tourism")
+
+    def test_resolves_minimal_services_probe_route(self):
+        routing_key = "slot.sample.it.probe"
+        result = resolve_route_config(
+            {
+                routing_key: {
+                    "service_id": 101,
+                    "capability": "services_probe_only",
+                }
+            },
+            routing_key,
+        )
+
+        self.assertIs(result.capability, ItaCapability.SERVICES_PROBE_ONLY)
+        self.assertIsNone(result.calendar_scan)
+        self.assertIsNone(result.booking_type)
+        self.assertIsNone(result.purpose)
+
+    def test_rejects_missing_route(self):
+        self.assert_protocol_error(
+            "route_missing",
+            lambda: resolve_route_config({}, "slot.sample.it.tourist"),
+        )
+
+    def test_rejects_invalid_service_ids(self):
+        for invalid in (0, -1, True, "100", None):
+            with self.subTest(invalid=invalid):
+                route = live_route()
+                route["service_id"] = invalid
+                self.assert_protocol_error(
+                    "positive_integer_required",
+                    lambda route=route: resolve_route_config(
+                        {"route": route},
+                        "route",
+                    ),
+                )
+
+    def test_rejects_unknown_or_missing_capability(self):
+        for invalid in (None, "", "guessed_live"):
+            with self.subTest(invalid=invalid):
+                route = live_route()
+                route["capability"] = invalid
+                expected = (
+                    "capability_unsupported"
+                    if invalid == "guessed_live"
+                    else "string_required"
+                )
+                self.assert_protocol_error(
+                    expected,
+                    lambda route=route: resolve_route_config(
+                        {"route": route},
+                        "route",
+                    ),
+                )
+
+    def test_live_route_requires_calendar_and_form_contracts(self):
+        variants = []
+        no_calendar = live_route()
+        no_calendar.pop("calendar_scan")
+        variants.append(no_calendar)
+        no_form = live_route()
+        no_form.pop("form")
+        variants.append(no_form)
+
+        for route in variants:
+            with self.subTest(keys=sorted(route)):
+                self.assert_protocol_error(
+                    "mapping_required",
+                    lambda route=route: resolve_route_config(
+                        {"route": route},
+                        "route",
+                    ),
+                )
+
+    def test_live_route_rejects_invalid_lookahead(self):
+        for invalid, expected in (
+            (0, "positive_integer_required"),
+            (True, "positive_integer_required"),
+            (MAX_LOOKAHEAD_MONTHS + 1, "lookahead_too_large"),
+        ):
+            with self.subTest(invalid=invalid):
+                route = live_route()
+                route["calendar_scan"]["lookahead_months"] = invalid
+                self.assert_protocol_error(
+                    expected,
+                    lambda route=route: resolve_route_config(
+                        {"route": route},
+                        "route",
+                    ),
+                )
+
+    def test_live_route_rejects_missing_empty_or_duplicate_labels(self):
+        for labels, expected in (
+            (None, "labels_required"),
+            ([], "labels_required"),
+            (["Same", "Same"], "labels_duplicate"),
+            (["Valid", ""], "string_required"),
+        ):
+            with self.subTest(labels=labels):
+                route = live_route()
+                route["form"]["purpose_labels"] = labels
+                self.assert_protocol_error(
+                    expected,
+                    lambda route=route: resolve_route_config(
+                        {"route": route},
+                        "route",
+                    ),
+                )
+
+
+class DoubleJsonTests(ProtocolTestCase):
+    def test_decodes_exactly_two_json_layers(self):
+        items = ({"value": 1}, {"value": 2})
+        self.assertEqual(decode_double_json_array(double_json(items)), items)
+        self.assertEqual(decode_double_json_array(double_json([])), ())
+
+    def test_rejects_bad_single_triple_and_non_array_payloads(self):
+        cases = (
+            ("not-json", "outer_json_invalid"),
+            (json.dumps([{"value": 1}]), "payload_layer_count"),
+            (json.dumps(json.dumps(json.dumps([]))), "payload_layer_count"),
+            (json.dumps(json.dumps({"value": 1})), "payload_layer_count"),
+            (json.dumps(json.dumps([1])), "item_type"),
+        )
+        for payload, expected in cases:
+            with self.subTest(expected=expected):
+                self.assert_protocol_error(
+                    expected,
+                    lambda payload=payload: decode_double_json_array(payload),
+                )
+
+    def test_rejects_non_string_and_item_limit(self):
+        for invalid in (None, b"[]", ""):
+            with self.subTest(invalid=invalid):
+                self.assert_protocol_error(
+                    "payload_type",
+                    lambda invalid=invalid: decode_double_json_array(invalid),
+                )
+
+        oversized = [{} for _ in range(MAX_PROTOCOL_ITEMS + 1)]
+        self.assert_protocol_error(
+            "item_limit_exceeded",
+            lambda: decode_double_json_array(double_json(oversized)),
+        )
+        self.assert_protocol_error(
+            "max_items_invalid",
+            lambda: decode_double_json_array(double_json([]), max_items=True),
+        )
+
+
+class CalendarAvailabilityTests(ProtocolTestCase):
+    def setUp(self):
+        self.items = [
+            availability_item("09/10/2026 00:00:00", 1, 0),
+            availability_item("31/08/2026 00:00:00", 0, -1),
+            availability_item("12/10/2026 00:00:00", 8, 7),
+        ]
+
+    def test_parses_e43_positive_and_negative_days_and_sorts(self):
+        days = parse_calendar_availability(double_json(self.items))
+
+        self.assertEqual(
+            tuple(item.day for item in days),
+            (date(2026, 8, 31), date(2026, 10, 9), date(2026, 10, 12)),
+        )
+        self.assertIs(days[0].state, InventoryState.UNAVAILABLE)
+        self.assertIs(days[1].state, InventoryState.AVAILABLE)
+        self.assertEqual((days[1].slots_free, days[1].slots_remaining), (1, 0))
+
+    def test_does_not_stop_after_an_earlier_negative_month(self):
+        days = parse_calendar_availability(double_json(self.items))
+        positives = available_calendar_days(days)
+
+        self.assertEqual(
+            tuple(item.day for item in positives),
+            (date(2026, 10, 9), date(2026, 10, 12)),
+        )
+
+    def test_filters_inclusive_date_boundaries_and_sorts(self):
+        days = parse_calendar_availability(double_json(self.items))
+        positives = available_calendar_days(
+            tuple(reversed(days)),
+            start_day=date(2026, 10, 9),
+            end_day=date(2026, 10, 9),
+        )
+
+        self.assertEqual(tuple(item.day for item in positives), (date(2026, 10, 9),))
+
+    def test_rejects_duplicate_invalid_and_conflicting_days(self):
+        duplicate = self.items + [self.items[0].copy()]
+        self.assert_protocol_error(
+            "duplicate_calendar_day",
+            lambda: parse_calendar_availability(double_json(duplicate)),
+        )
+
+        invalid_dates = (
+            "9/10/2026 00:00:00",
+            "31/02/2026 00:00:00",
+            "09/10/2026 01:00:00",
+        )
+        for invalid in invalid_dates:
+            with self.subTest(invalid=invalid):
+                item = availability_item(invalid, 1, 0)
+                self.assert_protocol_error(
+                    "date_format" if invalid != "31/02/2026 00:00:00" else "date_invalid",
+                    lambda item=item: parse_calendar_availability(double_json([item])),
+                )
+
+        for counters in ((0, 0), (1, -1), (-1, -2), (0, 1)):
+            with self.subTest(counters=counters):
+                item = availability_item(
+                    "09/10/2026 00:00:00",
+                    *counters,
+                )
+                self.assert_protocol_error(
+                    "inventory_conflict",
+                    lambda item=item: parse_calendar_availability(double_json([item])),
+                )
+
+    def test_rejects_missing_or_non_integer_counters(self):
+        missing = availability_item("09/10/2026 00:00:00", 1, 0)
+        missing.pop("SlotLiberi")
+        self.assert_protocol_error(
+            "field_missing",
+            lambda: parse_calendar_availability(double_json([missing])),
+        )
+
+        for invalid in (True, "1", 1.0, None):
+            with self.subTest(invalid=invalid):
+                item = availability_item("09/10/2026 00:00:00", invalid, 0)
+                self.assert_protocol_error(
+                    "integer_required",
+                    lambda item=item: parse_calendar_availability(double_json([item])),
+                )
+
+    def test_month_starts_cross_year_and_validate_bounds(self):
+        self.assertEqual(
+            month_starts(date(2026, 11, 20), 3),
+            (date(2026, 11, 1), date(2026, 12, 1), date(2027, 1, 1)),
+        )
+        self.assert_protocol_error(
+            "positive_integer_required",
+            lambda: month_starts(date(2026, 1, 1), 0),
+        )
+        self.assert_protocol_error(
+            "lookahead_too_large",
+            lambda: month_starts(
+                date(2026, 1, 1),
+                MAX_LOOKAHEAD_MONTHS + 1,
+            ),
+        )
+        self.assert_protocol_error(
+            "date_range_invalid",
+            lambda: available_calendar_days(
+                (),
+                start_day=date(2026, 2, 1),
+                end_day=date(2026, 1, 1),
+            ),
+        )
+
+
+class TimeSlotTests(ProtocolTestCase):
+    def setUp(self):
+        self.items = [
+            slot_item("09/10/2026 00:00:00", (9, 15), (10, 0), 0, -1, 101),
+            slot_item("09/10/2026 00:00:00", (10, 5), (11, 5), 1, 0, 102),
+            slot_item("09/10/2026 00:00:00", (11, 15), (12, 40), 0, -1, 103),
+        ]
+
+    def test_parses_e43_slots_without_exposing_runtime_id_in_repr(self):
+        slots = parse_time_slots(double_json(self.items))
+
+        self.assertEqual(len(slots), 3)
+        self.assertFalse(slots[0].is_available)
+        self.assertTrue(slots[1].is_available)
+        self.assertEqual(slots[1].time_label, "10:05 - 11:05")
+        self.assertEqual((slots[1].slots_free, slots[1].slots_remaining), (1, 0))
+        self.assertNotIn(slots[1].daily_calendar_id, repr(slots[1]))
+
+    def test_filters_and_sorts_by_day_capacity_then_start_time(self):
+        items = [
+            slot_item("12/10/2026 00:00:00", (9, 0), (10, 0), 4, 3, 201),
+            slot_item("09/10/2026 00:00:00", (10, 5), (11, 5), 1, 0, 202),
+            slot_item("09/10/2026 00:00:00", (11, 15), (12, 0), 8, 7, 203),
+        ]
+        candidates = available_slot_candidates(
+            tuple(reversed(parse_time_slots(double_json(items)))),
+            start_day=date(2026, 10, 9),
+            end_day=date(2026, 10, 12),
+        )
+
+        self.assertEqual(
+            tuple((item.day, item.slots_free, item.start_time) for item in candidates),
+            (
+                (date(2026, 10, 9), 8, time(11, 15)),
+                (date(2026, 10, 9), 1, time(10, 5)),
+                (date(2026, 10, 12), 4, time(9, 0)),
+            ),
+        )
+
+    def test_rejects_missing_invalid_or_conflicting_slot_fields(self):
+        missing = self.items[1].copy()
+        missing.pop("IDCalendarioServizioGiornaliero")
+        self.assert_protocol_error(
+            "field_missing",
+            lambda: parse_time_slots(double_json([missing])),
+        )
+
+        invalid_cases = []
+        end_before_start = copy.deepcopy(self.items[1])
+        end_before_start["OrarioFineFascia"] = time_value(9, 0)
+        invalid_cases.append((end_before_start, "time_range_invalid"))
+        invalid_hour = copy.deepcopy(self.items[1])
+        invalid_hour["OrarioInizioFascia"] = time_value(24, 0)
+        invalid_cases.append((invalid_hour, "time_invalid"))
+        invalid_precision = copy.deepcopy(self.items[1])
+        invalid_precision["OrarioInizioFascia"] = time_value(10, 5, seconds=1)
+        invalid_cases.append((invalid_precision, "time_precision"))
+        invalid_counter = copy.deepcopy(self.items[1])
+        invalid_counter["SlotLiberi"] = True
+        invalid_cases.append((invalid_counter, "integer_required"))
+        conflict = copy.deepcopy(self.items[1])
+        conflict["SlotLiberi"] = 0
+        conflict["SlotRimanenti"] = 0
+        invalid_cases.append((conflict, "inventory_conflict"))
+        invalid_id = copy.deepcopy(self.items[1])
+        invalid_id["IDCalendarioServizioGiornaliero"] = 0
+        invalid_cases.append((invalid_id, "positive_integer_required"))
+
+        for item, expected in invalid_cases:
+            with self.subTest(expected=expected):
+                self.assert_protocol_error(
+                    expected,
+                    lambda item=item: parse_time_slots(double_json([item])),
+                )
+
+    def test_rejects_duplicate_time_ranges_and_daily_ids(self):
+        duplicate_range = [self.items[1], copy.deepcopy(self.items[1])]
+        duplicate_range[1]["IDCalendarioServizioGiornaliero"] = 104
+        self.assert_protocol_error(
+            "duplicate_time_range",
+            lambda: parse_time_slots(double_json(duplicate_range)),
+        )
+
+        duplicate_id = [self.items[0], self.items[1]]
+        duplicate_id[1] = copy.deepcopy(duplicate_id[1])
+        duplicate_id[1]["IDCalendarioServizioGiornaliero"] = 101
+        self.assert_protocol_error(
+            "duplicate_daily_id",
+            lambda: parse_time_slots(double_json(duplicate_id)),
+        )
+
+    def test_value_objects_reject_inconsistent_manual_construction(self):
+        self.assert_protocol_error(
+            "inventory_state_mismatch",
+            lambda: CalendarDay(
+                day=date(2026, 10, 9),
+                slots_free=1,
+                slots_remaining=0,
+                state=InventoryState.UNAVAILABLE,
+            ),
+        )
+        self.assert_protocol_error(
+            "daily_id_invalid",
+            lambda: SlotCandidate(
+                day=date(2026, 10, 9),
+                start_time=time(10, 5),
+                end_time=time(11, 5),
+                slots_free=1,
+                slots_remaining=0,
+                state=InventoryState.AVAILABLE,
+                daily_calendar_id="not-numeric",
+            ),
+        )
+
+
+class PrecommitTests(ProtocolTestCase):
+    def setUp(self):
+        self.day = parse_calendar_availability(
+            double_json([availability_item("09/10/2026 00:00:00", 1, 0)])
+        )[0]
+        slots = parse_time_slots(
+            double_json(
+                [
+                    slot_item(
+                        "09/10/2026 00:00:00",
+                        (9, 15),
+                        (10, 0),
+                        0,
+                        -1,
+                        301,
+                    ),
+                    slot_item(
+                        "09/10/2026 00:00:00",
+                        (10, 5),
+                        (11, 5),
+                        1,
+                        0,
+                        302,
+                    ),
+                ]
+            )
+        )
+        self.negative_candidate = slots[0]
+        self.candidate = slots[1]
+        self.date_state = DateSelectionState(
+            planned_day=date(2026, 10, 9),
+            matching_availability_count=1,
+            timeline_selected_days=(date(2026, 10, 9),),
+            content_selected_days=(date(2026, 10, 9),),
+            day_disabled=False,
+            day_not_available=False,
+            day_has_positive_state=True,
+        )
+        self.slot_state = SlotSelectionState(
+            active_slot_count=1,
+            active_is_candidate=True,
+            active_has_unavailable_class=False,
+            active_has_red_dot=False,
+            active_hidden_input_count=1,
+            active_daily_id_matches_candidate=True,
+            active_day_matches_candidate=True,
+            active_time_matches_candidate=True,
+            active_capacity_matches_candidate=True,
+        )
+
+    def test_e44_positive_selection_approves_precommit(self):
+        approval = approve_precommit(
+            self.day,
+            self.candidate,
+            self.date_state,
+            self.slot_state,
+        )
+
+        self.assertIs(approval.calendar_day, self.day)
+        self.assertIs(approval.candidate, self.candidate)
+        self.assertNotIn(self.candidate.daily_calendar_id, repr(approval))
+
+    def test_state_objects_reject_python_bool_integer_ambiguity(self):
+        self.assert_protocol_error(
+            "integer_required",
+            lambda: replace(
+                self.date_state,
+                matching_availability_count=True,
+            ),
+        )
+        self.assert_protocol_error(
+            "integer_required",
+            lambda: replace(
+                self.slot_state,
+                active_slot_count=True,
+            ),
+        )
+        self.assert_protocol_error(
+            "boolean_required",
+            lambda: replace(
+                self.slot_state,
+                active_is_candidate=1,
+            ),
+        )
+        self.assert_protocol_error(
+            "date_tuple_required",
+            lambda: replace(
+                self.date_state,
+                timeline_selected_days=[self.day.day],
+            ),
+        )
+
+    def test_rejects_every_date_selection_conflict(self):
+        wrong_day = date(2026, 10, 10)
+        mutations = (
+            {"planned_day": wrong_day},
+            {"matching_availability_count": 0},
+            {"matching_availability_count": 2},
+            {"timeline_selected_days": ()},
+            {"timeline_selected_days": (self.day.day, self.day.day)},
+            {"content_selected_days": (wrong_day,)},
+            {"day_disabled": True},
+            {"day_not_available": True},
+            {"day_has_positive_state": False},
+        )
+        for mutation in mutations:
+            with self.subTest(mutation=mutation):
+                self.assert_protocol_error(
+                    "precommit_rejected",
+                    lambda mutation=mutation: approve_precommit(
+                        self.day,
+                        self.candidate,
+                        replace(self.date_state, **mutation),
+                        self.slot_state,
+                    ),
+                )
+
+    def test_rejects_every_active_slot_conflict(self):
+        mutations = (
+            {"active_slot_count": 0},
+            {"active_slot_count": 2},
+            {"active_is_candidate": False},
+            {"active_has_unavailable_class": True},
+            {"active_has_red_dot": True},
+            {"active_hidden_input_count": 0},
+            {"active_hidden_input_count": 2},
+            {"active_daily_id_matches_candidate": False},
+            {"active_day_matches_candidate": False},
+            {"active_time_matches_candidate": False},
+            {"active_capacity_matches_candidate": False},
+        )
+        for mutation in mutations:
+            with self.subTest(mutation=mutation):
+                self.assert_protocol_error(
+                    "precommit_rejected",
+                    lambda mutation=mutation: approve_precommit(
+                        self.day,
+                        self.candidate,
+                        self.date_state,
+                        replace(self.slot_state, **mutation),
+                    ),
+                )
+
+    def test_rejects_negative_candidate_even_if_dom_marks_it_active(self):
+        self.assert_protocol_error(
+            "precommit_rejected",
+            lambda: approve_precommit(
+                self.day,
+                self.negative_candidate,
+                self.date_state,
+                self.slot_state,
+            ),
+        )
+
+    def test_rejects_negative_calendar_day(self):
+        negative_day = parse_calendar_availability(
+            double_json([availability_item("09/10/2026 00:00:00", 0, -1)])
+        )[0]
+        self.assert_protocol_error(
+            "precommit_rejected",
+            lambda: approve_precommit(
+                negative_day,
+                self.candidate,
+                self.date_state,
+                self.slot_state,
+            ),
+        )
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 363 - 0
test/test_ita_query_recovery.py

@@ -0,0 +1,363 @@
+"""Offline recovery contracts; no browser, credentials, or website requests."""
+
+import json
+import sys
+import threading
+import time
+import types
+import unittest
+from dataclasses import fields, replace
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from DrissionPage.errors import PageDisconnectedError
+
+from plugins.ita_calendar_book import RUNTIME_SERVICE_SCRIPT
+from plugins.ita_calendar_query import (
+    AVAILABILITY_PATH, CalendarAccessDeniedError, CalendarAuthenticationExpiredError,
+    CalendarGateError, CalendarRateLimitedError, CalendarTransientError,
+    parse_availability_packet,
+)
+from plugins.ita_plugin import (
+    CalendarQueryCheckpoint, ItaCalendarPreparationRequiredError,
+    ItaCalendarTransientError, ItaPlugin,
+)
+from test.test_debug_ita_production_query_gate import (
+    FakeProductionPage, gate_env, make_plugin,
+)
+from vs_types import (
+    BizLogicError, PermissionDeniedError, RateLimiteddError,
+    SessionExpiredOrInvalidError,
+)
+
+
+class RecoveryPage(FakeProductionPage):
+    """Real Query and audit mechanics run against deterministic page responses."""
+
+    def __init__(self, outcomes=("available",), *, restore_outcome="calendar"):
+        plans = [[(2026, 8, [12])]] * 100
+        super().__init__(plans)
+        self.outcomes = list(outcomes)
+        self.attempts = 0
+        self.tab_id = "offline-tab"
+        self.runtime_service = "offline-runtime-service"
+        self.restore_outcome = restore_outcome
+        self.get_calls = []
+
+    def run_js(self, script, *args):
+        if script == RUNTIME_SERVICE_SCRIPT:
+            return {"path": "/BookingCalendar", "count": 1, "value": self.runtime_service}
+        if script == "return 1;":
+            if not self.driver.is_running:
+                raise PageDisconnectedError("offline disconnected")
+            return 1
+        return super().run_js(script, *args)
+
+    def get(self, url):
+        self.get_calls.append(url)
+        if self.restore_outcome == "form":
+            self.url = "https://prenotami.esteri.it/Services/Booking/9001"
+        elif self.restore_outcome == "expired":
+            self.url = "https://iam.esteri.it/signin/"
+        else:
+            self.url = url
+            if self.restore_outcome == "wrong-service":
+                self.runtime_service = "different-runtime-service"
+
+    def refresh(self):
+        outcome = self.outcomes[min(self.attempts, len(self.outcomes) - 1)]
+        self.attempts += 1
+        if outcome == "disconnect":
+            self.driver.is_running = False
+            raise PageDisconnectedError("offline private@example.test secret-token")
+        if outcome == "cancel":
+            raise KeyboardInterrupt
+        if outcome in {"expired", "timeout"}:
+            if outcome == "expired":
+                self.url = "https://iam.esteri.it/signin/"
+            self.packet = None
+            return
+        if outcome == "none":
+            self.plans[self.refresh_calls] = [(2026, month, []) for month in (8, 9, 10)]
+        super().refresh()
+        if outcome in {"rate", "denied"}:
+            self.packet.response.status = 429 if outcome == "rate" else 403
+        if outcome == "malformed":
+            self.packet.response.raw_body = "private@example.test secret-token"
+        if outcome == "unexpected-otp":
+            self.emit("/BookingCalendar/GenerateOTP?ServiceID=9001", "GET")
+        self.emit("/BookingCalendar/RetrieveTimeSlots")  # native auto-load, not a Query fanout
+
+
+def prepared_plugin(page=None):
+    page = page or RecoveryPage()
+    plugin, route = make_plugin(page)
+    plugin.free_config["query_mode"] = "calendar"
+    plugin.is_healthy = True
+    plugin.session_create_time = time.time()
+    plugin._persistent_profile_path = Path("/offline/query-profile")
+    plugin.user_data_path = str(plugin._persistent_profile_path)
+    plugin._query_stop_reason = None
+    plugin._reset_calendar_book_state()
+    return plugin, route
+
+
+def availability_packet(status=200, *, response_url=None):
+    response = SimpleNamespace(status=status, raw_body=json.dumps(json.dumps([])))
+    if response_url is not None:
+        response.url = response_url
+    return SimpleNamespace(
+        url="https://prenotami.esteri.it" + AVAILABILITY_PATH, method="POST",
+        request=SimpleNamespace(postData={"_Servizio": "test-runtime", "selectedDay": "01/08/2026"}),
+        response=response,
+    )
+
+
+class CalendarFailureClassificationTests(unittest.TestCase):
+    def test_distinguishes_http_failure_categories(self):
+        cases = {
+            401: CalendarAuthenticationExpiredError, 403: CalendarAccessDeniedError,
+            429: CalendarRateLimitedError, 408: CalendarTransientError,
+            502: CalendarTransientError, 503: CalendarTransientError,
+            504: CalendarTransientError, 418: CalendarGateError,
+        }
+        for status, expected in cases.items():
+            with self.subTest(status=status):
+                packet = availability_packet(status)
+                packet.response.raw_body = "private@example.test secret-token"
+                with self.assertRaises(expected) as caught:
+                    parse_availability_packet(packet)
+                self.assertNotIn("private@example.test", str(caught.exception))
+                self.assertNotIn("secret-token", str(caught.exception))
+
+    def test_followed_login_redirect_is_not_schema_or_no_inventory(self):
+        with self.assertRaises(CalendarAuthenticationExpiredError):
+            parse_availability_packet(availability_packet(response_url="https://iam.esteri.it/signin/"))
+
+    def test_direct_login_redirect_is_classified_without_exposing_oauth_values(self):
+        packet = availability_packet(302)
+        packet.response.headers = {"Location": "https://iam.esteri.it/signin/?state=secret-token"}
+        with self.assertRaises(CalendarAuthenticationExpiredError) as caught:
+            parse_availability_packet(packet)
+        self.assertNotIn("secret-token", str(caught.exception))
+
+    def test_invalid_http_status_is_not_a_retryable_network_failure(self):
+        for value in (False, "200", None):
+            with self.subTest(value=value), self.assertRaises(CalendarGateError) as caught:
+                parse_availability_packet(availability_packet(value))
+            self.assertNotIsInstance(caught.exception, CalendarTransientError)
+
+    def test_foreign_or_unexpected_response_never_becomes_inventory(self):
+        for url in ("https://foreign.example" + AVAILABILITY_PATH,
+                    "https://prenotami.esteri.it/Services"):
+            with self.subTest(url=url), self.assertRaises(CalendarGateError):
+                parse_availability_packet(availability_packet(response_url=url))
+
+    def test_auth_rate_and_permission_errors_invalidate_health_and_scan(self):
+        for outcome, expected in (("expired", SessionExpiredOrInvalidError),
+                                  ("rate", RateLimiteddError), ("denied", PermissionDeniedError)):
+            with self.subTest(outcome=outcome):
+                plugin, route = prepared_plugin(RecoveryPage([outcome]))
+                plugin.last_calendar_query_scan = object()
+                with self.assertRaises(expected):
+                    plugin.query(route.appointment_type())
+                self.assertFalse(plugin.is_healthy)
+                self.assertFalse(plugin.health_check())
+                self.assertIsNone(plugin.last_calendar_query_scan)
+                self.assertIsNone(plugin._calendar_query_route_key)
+                with self.assertRaises(SessionExpiredOrInvalidError):
+                    plugin.query(route.appointment_type())
+                self.assertEqual(plugin.page.attempts, 1)
+
+    def test_transient_error_keeps_valid_session_without_old_scan(self):
+        plugin, route = prepared_plugin(RecoveryPage(["timeout", "available"]))
+        plugin.last_calendar_query_scan = object()
+        with self.assertRaises(ItaCalendarTransientError):
+            plugin.query(route.appointment_type())
+        self.assertTrue(plugin.is_healthy)
+        self.assertIsNone(plugin.last_calendar_query_scan)
+        self.assertTrue(plugin.query(route.appointment_type()).success)
+
+    def test_browser_disconnection_invalidates_health_without_hiding_type(self):
+        plugin, route = prepared_plugin(RecoveryPage(["disconnect"]))
+        with self.assertRaises(PageDisconnectedError):
+            plugin.query(route.appointment_type())
+        self.assertFalse(plugin.health_check())
+        self.assertIsNone(plugin._calendar_query_route_key)
+
+    def test_configured_lifetime_and_health_probe_clear_preparation(self):
+        plugin, route = prepared_plugin()
+        plugin.capture_calendar_query_checkpoint(route.appointment_type())
+        plugin.session_create_time = 1
+        self.assertFalse(plugin.health_check())
+        self.assertFalse(plugin.is_healthy)
+        self.assertIsNone(plugin._calendar_query_checkpoint)
+
+    def test_health_probe_does_not_turn_operator_cancel_into_disconnection(self):
+        plugin, _ = prepared_plugin()
+        plugin.page.run_js = Mock(side_effect=KeyboardInterrupt)
+        with self.assertRaises(KeyboardInterrupt):
+            plugin.health_check()
+        self.assertTrue(plugin.is_healthy)
+
+
+class CalendarReadOnlyRestoreTests(unittest.TestCase):
+    def test_restore_rebinds_new_page_then_runs_real_fresh_query(self):
+        old, route = prepared_plugin()
+        old_result = old.query(route.appointment_type())
+        old_scan = old.last_calendar_query_scan
+        checkpoint = old.capture_calendar_query_checkpoint(route.appointment_type())
+        new, _ = prepared_plugin()
+        new._clear_calendar_query_state()
+        new.page.url = "https://prenotami.esteri.it/UserArea"
+        new.restore_calendar_query(route.appointment_type(), checkpoint)
+        self.assertEqual(new.page.get_calls, [checkpoint.calendar_url])
+        self.assertIsNone(new.last_calendar_query_scan)
+        result = new.query(route.appointment_type())
+        self.assertIsNot(new.last_calendar_query_scan, old_scan)
+        self.assertIsNot(result, old_result)
+        self.assertTrue(result.success)
+        self.assertEqual(new._calendar_query_route_key, route.routing_key)
+        self.assertEqual(new.page.refresh_calls, 1)
+
+    def test_checkpoint_contains_no_dates_credentials_or_slot_state(self):
+        plugin, route = prepared_plugin()
+        checkpoint = plugin.capture_calendar_query_checkpoint(route.appointment_type())
+        self.assertEqual({item.name for item in fields(checkpoint)},
+                         {"route", "username", "profile_path", "calendar_url", "runtime_service"})
+        self.assertNotIn(plugin.config.account.username, repr(checkpoint))
+        self.assertNotIn(plugin.config.account.password, repr(checkpoint))
+
+    def test_mismatched_owner_or_profile_or_config_is_rejected_before_navigation(self):
+        old, route = prepared_plugin()
+        checkpoint = old.capture_calendar_query_checkpoint(route.appointment_type())
+        for mutation in ("account", "profile", "route", "book", "query-mode"):
+            with self.subTest(mutation=mutation):
+                plugin, _ = prepared_plugin()
+                if mutation == "account":
+                    plugin.config.account.username = "other@example.test"
+                elif mutation == "profile":
+                    plugin._persistent_profile_path = Path("/offline/other")
+                elif mutation == "route":
+                    plugin.free_config["apt_configs"][route.routing_key]["service_id"] = 9002
+                elif mutation == "book":
+                    plugin._calendar_book_prepared_context = ("book",)
+                else:
+                    plugin.free_config["query_mode"] = "services_probe"
+                with self.assertRaises(BizLogicError):
+                    plugin.restore_calendar_query(route.appointment_type(), checkpoint)
+                self.assertEqual(plugin.page.get_calls, [])
+
+    def test_form_redirect_stops_at_pending_otp_todo_without_preparation(self):
+        old, route = prepared_plugin()
+        checkpoint = old.capture_calendar_query_checkpoint(route.appointment_type())
+        plugin, _ = prepared_plugin(RecoveryPage(restore_outcome="form"))
+        with self.assertRaisesRegex(ItaCalendarPreparationRequiredError, "ITA-OTP-01"):
+            plugin.restore_calendar_query(route.appointment_type(), checkpoint)
+        self.assertEqual(len(plugin.page.get_calls), 1)
+        self.assertEqual(plugin.page.refresh_calls, 0)
+        self.assertIsNone(plugin._calendar_query_route_key)
+        self.assertIsNone(plugin._calendar_query_checkpoint)
+
+    def test_wrong_runtime_service_cannot_reuse_old_proof(self):
+        old, route = prepared_plugin()
+        checkpoint = old.capture_calendar_query_checkpoint(route.appointment_type())
+        plugin, _ = prepared_plugin(RecoveryPage(restore_outcome="wrong-service"))
+        with self.assertRaisesRegex(BizLogicError, "service does not match"):
+            plugin.restore_calendar_query(route.appointment_type(), checkpoint)
+        self.assertIsNone(plugin._calendar_query_checkpoint)
+
+    def test_changed_runtime_tab_or_generation_rejects_next_query(self):
+        for mutation in ("service", "tab", "generation"):
+            with self.subTest(mutation=mutation):
+                plugin, route = prepared_plugin()
+                plugin.capture_calendar_query_checkpoint(route.appointment_type())
+                if mutation == "service":
+                    plugin.page.runtime_service = "changed"
+                elif mutation == "tab":
+                    plugin.page.tab_id = "changed"
+                else:
+                    plugin.session_create_time += 1
+                with self.assertRaises(BizLogicError):
+                    plugin.query(route.appointment_type())
+                self.assertEqual(plugin.page.refresh_calls, 0)
+
+    def test_checkpoint_cannot_redirect_to_external_origin(self):
+        plugin, route = prepared_plugin()
+        checkpoint = plugin.capture_calendar_query_checkpoint(route.appointment_type())
+        malicious = replace(checkpoint, calendar_url="https://foreign.example/BookingCalendar")
+        with self.assertRaises(CalendarGateError):
+            plugin.restore_calendar_query(route.appointment_type(), malicious)
+        self.assertEqual(plugin.page.get_calls, [])
+
+    def test_checkpoint_with_unobserved_query_parameters_is_rejected_before_navigation(self):
+        plugin, route = prepared_plugin()
+        checkpoint = plugin.capture_calendar_query_checkpoint(route.appointment_type())
+        unknown = replace(checkpoint, calendar_url=checkpoint.calendar_url + "?unknown=1")
+        with self.assertRaises(BizLogicError):
+            plugin.restore_calendar_query(route.appointment_type(), unknown)
+        self.assertEqual(plugin.page.get_calls, [])
+
+    def test_real_cleanup_reports_failure_instead_of_allowing_silent_recreation(self):
+        plugin, _route = prepared_plugin()
+        plugin.__dict__.pop("cleanup")
+        plugin.root_workspace = "/nonexistent/ita-offline-cleanup-test"
+        plugin.tunnel = SimpleNamespace(stop=Mock())
+        plugin._profile_lock_handle = None
+        page = plugin.page
+        page.quit = Mock(side_effect=RuntimeError("private@example.test secret-token"))
+        with self.assertRaises(BizLogicError) as caught:
+            plugin.cleanup()
+        self.assertNotIn("secret-token", str(caught.exception))
+        self.assertIsNone(plugin.page)
+        self.assertFalse(plugin.is_healthy)
+        plugin.__del__()
+        page.quit.assert_called_once()
+
+
+class ExistingSentinelLifecycleTests(unittest.TestCase):
+    def test_real_monitor_retires_failed_italy_session_once_without_publishing(self):
+        # Import from the same already-stubbed dependency environment as other
+        # repository tests. Neither __init__ nor live API/Redis is invoked.
+        from test.test_ita_plugin import GroupConfig, Task
+        try:
+            from sentinel import SentinelGCO
+        except ModuleNotFoundError as exc:
+            if exc.name != "redis":
+                raise
+            redis_stub = types.ModuleType("redis")
+            redis_stub.Redis = Mock
+            with patch.dict(sys.modules, {"redis": redis_stub}):
+                from sentinel import SentinelGCO
+        from vs_types import QueryWaitConfig, QueryWaitMode
+        plugin, route = prepared_plugin(RecoveryPage(["expired"]))
+        config = GroupConfig(identifier="offline-italy")
+        config.appointment_types = [route.appointment_type()]
+        config.appointment_types[0].weight = 1
+        config.sentinel.query_wait = QueryWaitConfig(mode=QueryWaitMode.Fixed, fixed_wait=60)
+        sentinel = SentinelGCO.__new__(SentinelGCO)
+        sentinel.m_cfg = config
+        sentinel.m_logger = Mock()
+        sentinel.redis_client = Mock()
+        sentinel.m_lock = threading.RLock()
+        sentinel.m_tasks = [Task(instance=plugin, qw_cfg=config.sentinel.query_wait, next_run=0)]
+        sentinel.m_stop_event = Mock()
+        sentinel.m_stop_event.is_set.side_effect = [False, False, True]
+        # Patch the loaded method's dependencies directly. patch.dict(sys.modules)
+        # removes temporary modules on exit, so string-based patch would import
+        # Sentinel again and require an installed/live Redis dependency.
+        isolated = {
+            "time": SimpleNamespace(sleep=lambda _delay: None, time=lambda: 1000),
+            "VSCloudApi": SimpleNamespace(Instance=Mock(return_value=Mock())),
+        }
+        with patch.dict(SentinelGCO._monitor_loop.__globals__, isolated):
+            sentinel._monitor_loop()
+        self.assertEqual(sentinel.m_tasks, [])
+        plugin.cleanup.assert_called_once()
+        sentinel.redis_client.setex.assert_not_called()
+        self.assertEqual(plugin.page.attempts, 1)
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 609 - 0
test/test_ita_reservation.py

@@ -0,0 +1,609 @@
+"""Synthetic fixtures reproducing observed markup; never calls the website."""
+
+import copy
+import json
+import shutil
+import subprocess
+import traceback
+import unittest
+from datetime import date
+from html.parser import HTMLParser
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+from plugins.ita_booking_final import ReservationState
+from plugins.ita_reservation import (
+    DETAIL_READ_SCRIPT, LIST_READ_SCRIPT, DATE_DIAGNOSTIC_SCRIPT, HEADERS, ReservationReadError,
+    parse_reservation_detail, parse_reservation_listing,
+    read_reservation_detail, read_reservation_listing, read_reservation_date_diagnostic,
+)
+
+
+def detail():
+    return {"path": "/ReservationDetail/Index/synthetic-link", "statusCode": "3", "fields": {
+        "Servizio Consolare": "Visti", "Servizio Erogato": "Visti Nazionali e Schengen",
+        "Codice Prenotazione": "SYNTHETIC-REFERENCE", "Tipo Prenotazione": "Prenotazione Singola",
+        "Data": "13 ottobre 2026", "Ora": "10:25", "Stato": "Annullata",
+    }}
+
+
+def listing():
+    return {"path": "/Reservation", "tables": [
+        {"id": "dataTableReservations", "structuralEmpty": False, "headers": [*HEADERS, ""], "count": 1,
+         "info": {"page": 0, "pages": 1, "start": 0, "end": 1, "length": 10,
+                  "recordsTotal": 1, "recordsDisplay": 1, "serverSide": False},
+         "rows": [{"reference": "SYNTHETIC-REFERENCE", "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/synthetic-link",
+                   "office": "Visti", "service": "Visti Nazionali e Schengen", "date": "13 ottobre 2026",
+                   "time": "10:25", "status": "Annullata"}]},
+        {"id": "dataTableReservationsWL", "structuralEmpty": True},
+    ]}
+
+
+def confirmed_detail():
+    """Observed 2026-08-31 business shape; identifiers remain synthetic."""
+    raw = detail()
+    raw.update(path="/ReservationDetail/Index/confirmed-synthetic", statusCode="2")
+    raw["fields"].update({"Codice Prenotazione": "CONFIRMED-SYNTHETIC", "Data": "3 settembre 2026",
+                          "Ora": "09:26", "Stato": "Confermata"})
+    return raw
+
+
+def confirmed_listing():
+    raw = listing()
+    table = raw["tables"][0]
+    table["rows"].append({**table["rows"][0], "reference": "CONFIRMED-SYNTHETIC",
+                          "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/confirmed-synthetic",
+                          "date": "3 settembre 2026", "time": "09:26", "status": "Confermata"})
+    table["count"] = 2
+    table["info"].update(recordsTotal=2, recordsDisplay=2, end=2)
+    return raw
+
+
+class ReceiptParsingTests(unittest.TestCase):
+    def test_observed_confirmed_pair_maps_active_without_inventing_slot_binding(self):
+        parsed = parse_reservation_detail(confirmed_detail())
+        self.assertIs(parsed.state, ReservationState.ACTIVE)
+        self.assertEqual(parsed.day, date(2026, 9, 3))
+        self.assertEqual(parsed.appointment_time, "09:26")
+        self.assertFalse(hasattr(parsed, "service_id"))
+        self.assertFalse(hasattr(parsed, "time_label"))
+
+    def test_confirmed_label_with_wrong_code_or_code_without_label_stays_unknown(self):
+        for label, code in (("Confermata", "3"), ("Confermata", "1"), ("Confermata", "02"),
+                            ("Annullata", "2"), ("Arbitrary", "2"), ("Confirmed", "2")):
+            with self.subTest(label=label, code=code):
+                raw = confirmed_detail()
+                raw["fields"]["Stato"], raw["statusCode"] = label, code
+                self.assertIs(parse_reservation_detail(raw).state, ReservationState.UNKNOWN)
+
+    def test_cancelled_history_and_confirmed_list_candidate_remain_distinct(self):
+        parsed = parse_reservation_listing(confirmed_listing())
+        self.assertEqual([row.state for row in parsed.rows],
+                         [ReservationState.CANCELLED, ReservationState.ACTIVE])
+        self.assertNotIn("CONFIRMED-SYNTHETIC", repr(parsed))
+
+    def test_confirmed_mapping_is_not_hong_kong_or_date_specific(self):
+        raw = confirmed_detail()
+        raw["fields"].update({"Data": "12 febbraio 2027", "Servizio Erogato": "Different service",
+                              "Ora": "14:30"})
+        self.assertIs(parse_reservation_detail(raw).state, ReservationState.ACTIVE)
+
+    def test_cancelled_detail_has_assigned_time_not_invented_interval_or_service_id(self):
+        result = parse_reservation_detail(detail())
+        self.assertEqual(result.day, date(2026, 10, 13))
+        self.assertEqual(result.appointment_time, "10:25")
+        self.assertIs(result.state, ReservationState.CANCELLED)
+        self.assertFalse(hasattr(result, "time_label"))
+        self.assertFalse(hasattr(result, "service_id"))
+        self.assertNotIn("SYNTHETIC-REFERENCE", repr(result))
+
+    def test_unknown_and_conflicting_states_never_become_active(self):
+        for text, code in (("Annullata", "2"), ("Confirmed", "3"), ("Confermata", "1"), ("Unknown", "99")):
+            with self.subTest(code=code):
+                raw = detail()
+                raw["fields"]["Stato"], raw["statusCode"] = text, code
+                self.assertIs(parse_reservation_detail(raw).state, ReservationState.UNKNOWN)
+
+    def test_invalid_dates_and_times_fail_without_raw_values(self):
+        for key, value in (("Data", "31 febbraio 2026"), ("Data", "10/13/2026"),
+                           ("Data", "13 SECRET 2026"), ("Ora", "10:05 - 11:05"),
+                           ("Ora", "24:00"), ("Ora", "10:25:00")):
+            with self.subTest(key=key):
+                raw = detail()
+                raw["fields"][key] = value
+                with self.assertRaises(ReservationReadError) as error:
+                    parse_reservation_detail(raw)
+                self.assertNotIn(value, str(error.exception))
+
+    def test_all_italian_months_parse_without_process_locale(self):
+        from plugins.ita_reservation import MONTHS_IT
+        for month, name in enumerate(MONTHS_IT, 1):
+            raw = detail()
+            raw["fields"]["Data"] = f"1 {name} 2027"
+            self.assertEqual(parse_reservation_detail(raw).day, date(2027, month, 1))
+
+    def test_missing_extra_empty_and_control_fields_are_rejected(self):
+        for change in (lambda r: r["fields"].pop("Ora"),
+                       lambda r: r["fields"].update({"Email": "private@example.test"}),
+                       lambda r: r["fields"].update({"Stato": ""}),
+                       lambda r: r["fields"].update({"Ora": "10:25\n"}),
+                       lambda r: r.update(statusCode=3),
+                       lambda r: r.update(statusCode="SECRET"),
+                       lambda r: r.update(path="/UserArea")):
+            raw = detail()
+            change(raw)
+            with self.assertRaises(ReservationReadError):
+                parse_reservation_detail(raw)
+
+    def test_listing_covered_with_structurally_empty_waitlist(self):
+        result = parse_reservation_listing(listing())
+        self.assertEqual(len(result.rows), 1)
+        self.assertEqual(result.waitlist_count, 0)
+        self.assertEqual(result.rows[0].appointment_time, "10:25")
+        self.assertIs(result.rows[0].state, ReservationState.CANCELLED)
+        self.assertNotIn("SYNTHETIC-REFERENCE", repr(result))
+        self.assertNotIn("SYNTHETIC-REFERENCE", repr(result.rows[0]))
+        self.assertFalse(hasattr(result, "complete"))  # Not a bound Final snapshot.
+
+    def test_loaded_multi_page_client_rows_are_supported_without_paging_actions(self):
+        raw = listing()
+        main = raw["tables"][0]
+        main["count"] = 2
+        main["rows"].append({**main["rows"][0], "reference": "SECOND", "detailUrl": "https://prenotami.esteri.it/ReservationDetail/Index/second"})
+        main["info"].update(recordsTotal=2, recordsDisplay=2, pages=2, length=1)
+        self.assertEqual(len(parse_reservation_listing(raw).rows), 2)
+
+    def test_empty_initialized_tables_and_show_all_page(self):
+        raw = listing()
+        main = raw["tables"][0]
+        main["info"]["length"] = -1
+        self.assertEqual(parse_reservation_listing(raw).page_count, 1)
+        main.update(count=0, rows=[])
+        main["info"].update(recordsTotal=0, recordsDisplay=0, pages=0, start=0, end=0)
+        raw["tables"][1] = {"id": "dataTableReservationsWL", "structuralEmpty": False,
+                            "count": 0, "info": copy.deepcopy(main["info"])}
+        self.assertEqual(parse_reservation_listing(raw).rows, ())
+
+    def test_coverage_and_pagination_changes_are_rejected(self):
+        for changes in ({"serverSide": True}, {"serverSide": 0}, {"recordsTotal": 2},
+                        {"recordsDisplay": 0}, {"pages": 2}, {"page": True}, {"page": 1},
+                        {"start": 1}, {"end": 2}, {"length": 0}):
+            with self.subTest(changes=changes):
+                raw = listing()
+                raw["tables"][0]["info"].update(changes)
+                with self.assertRaises(ReservationReadError):
+                    parse_reservation_listing(raw)
+
+    def test_bad_rows_headers_duplicate_links_and_missing_tables_rejected(self):
+        for mode in ("missing_table", "wrong_order", "header", "missing_node", "count_bool", "duplicate_ref", "duplicate_link"):
+            with self.subTest(mode=mode):
+                raw = listing()
+                main = raw["tables"][0]
+                if mode == "missing_table":
+                    raw["tables"].pop()
+                elif mode == "wrong_order":
+                    raw["tables"].reverse()
+                elif mode == "header":
+                    main["headers"][7] = "Unexpected"
+                elif mode == "missing_node":
+                    main["rows"] = []
+                elif mode == "count_bool":
+                    main["count"] = True
+                else:
+                    main["count"] = 2
+                    main["info"].update(recordsTotal=2, recordsDisplay=2, end=2)
+                    new = {**main["rows"][0]}
+                    new["detailUrl" if mode == "duplicate_ref" else "reference"] = (
+                        "https://prenotami.esteri.it/ReservationDetail/Index/second" if mode == "duplicate_ref" else "SECOND")
+                    main["rows"].append(new)
+                with self.assertRaises(ReservationReadError):
+                    parse_reservation_listing(raw)
+
+    def test_unsafe_detail_links_are_never_followed_or_accepted(self):
+        for url in ("https://attacker.test/ReservationDetail/Index/x", "javascript:alert(1)",
+                    "https://prenotami.esteri.it/Reservation/Cancel/x", "https://prenotami.esteri.it/ReservationDetail/Index/x?token=SECRET",
+                    "https://prenotami.esteri.it/ReservationDetail/Index/../x", "https://prenotami.esteri.it/ReservationDetail/Index/%2fSECRET"):
+            raw = listing()
+            raw["tables"][0]["rows"][0]["detailUrl"] = url
+            with self.assertRaises(ReservationReadError) as error:
+                parse_reservation_listing(raw)
+            self.assertNotIn("SECRET", str(error.exception))
+
+    def test_nonempty_waitlist_remains_unsupported(self):
+        raw = listing()
+        raw["tables"][1] = {"id": "dataTableReservationsWL", "structuralEmpty": False,
+                            "count": 1, "info": copy.deepcopy(raw["tables"][0]["info"])}
+        with self.assertRaisesRegex(ReservationReadError, "waitlist_schema_unverified"):
+            parse_reservation_listing(raw)
+
+
+class BrowserReadTests(unittest.TestCase):
+    def page(self, raw, *, detail_page=False):
+        return SimpleNamespace(url="https://prenotami.esteri.it" + (detail()["path"] if detail_page else "/Reservation"),
+                               tab_id="synthetic-tab", run_js=Mock(return_value=raw))
+
+    def test_detail_reads_current_page_once_without_navigation(self):
+        page = self.page(detail(), detail_page=True)
+        result = read_reservation_detail(page)
+        self.assertIs(result.state, ReservationState.CANCELLED)
+        page.run_js.assert_called_once_with(DETAIL_READ_SCRIPT)
+
+    def test_list_requires_two_stable_reads(self):
+        page = self.page(listing())
+        with patch("plugins.ita_reservation.time.sleep"):
+            self.assertEqual(len(read_reservation_listing(page).rows), 1)
+        self.assertEqual(page.run_js.call_count, 2)
+        self.assertTrue(all(call.args == (LIST_READ_SCRIPT,) for call in page.run_js.call_args_list))
+
+    def test_not_ready_and_changed_records_reset_stable_read(self):
+        original = listing()
+        changed = listing()
+        changed["tables"][0]["rows"][0]["time"] = "10:30"
+        page = self.page(original)
+        page.run_js.side_effect = [original, {"error": "not_ready"}, changed, changed]
+        with patch("plugins.ita_reservation.time.sleep"):
+            self.assertEqual(read_reservation_listing(page).rows[0].appointment_time, "10:30")
+        self.assertEqual(page.run_js.call_count, 4)
+
+    def test_wrong_origin_rejected_before_dom_read(self):
+        page = self.page(detail(), detail_page=True)
+        page.url = "https://attacker.test/ReservationDetail/Index/x"
+        with self.assertRaises(ReservationReadError):
+            read_reservation_detail(page)
+        page.run_js.assert_not_called()
+
+    def test_page_changes_during_read_rejected(self):
+        page = self.page(detail(), detail_page=True)
+        def change(_):
+            page.tab_id = "another-tab"
+            return detail()
+        page.run_js.side_effect = change
+        with self.assertRaisesRegex(ReservationReadError, "context_changed"):
+            read_reservation_detail(page)
+
+    def test_browser_error_message_from_page_is_not_echoed(self):
+        page = self.page({"error": "PRIVATE-PAGE-MESSAGE"}, detail_page=True)
+        with self.assertRaises(ReservationReadError) as error:
+            read_reservation_detail(page)
+        self.assertNotIn("PRIVATE", str(error.exception))
+
+    def test_returned_path_must_match_current_detail(self):
+        raw = detail()
+        raw["path"] = "/ReservationDetail/Index/another"
+        with self.assertRaises(ReservationReadError):
+            read_reservation_detail(self.page(raw, detail_page=True))
+
+    def test_tab_changes_between_stability_reads_rejected(self):
+        page = self.page(listing())
+        with patch("plugins.ita_reservation.time.sleep", side_effect=lambda _: setattr(page, "tab_id", "other")):
+            with self.assertRaisesRegex(ReservationReadError, "context_changed"):
+                read_reservation_listing(page)
+        self.assertEqual(page.run_js.call_count, 1)
+
+    def test_browser_errors_are_sanitized_without_exception_chain(self):
+        page = self.page(detail(), detail_page=True)
+        page.run_js.side_effect = RuntimeError("PRIVATE-TOKEN")
+        with self.assertRaises(ReservationReadError) as caught:
+            read_reservation_detail(page)
+        self.assertNotIn("PRIVATE-TOKEN", "".join(traceback.format_exception(caught.exception)))
+
+    def test_unready_read_is_bounded(self):
+        page = self.page({"error": "not_ready"})
+        with patch("plugins.ita_reservation.time.monotonic", side_effect=[0, 0, 0, 6]), patch("plugins.ita_reservation.time.sleep"):
+            with self.assertRaisesRegex(ReservationReadError, "stability_timeout"):
+                read_reservation_listing(page)
+        self.assertEqual(page.run_js.call_count, 1)
+
+    def test_invalid_wait_limits_fail_before_read(self):
+        page = self.page(listing())
+        for timeout, poll in ((True, .1), (0, .1), (61, .1), (float("inf"), .1), (1, 2)):
+            with self.assertRaises(ReservationReadError):
+                read_reservation_listing(page, timeout=timeout, poll_interval=poll)
+        page.run_js.assert_not_called()
+
+
+def detail_html():
+    rows = "".join(f'<div>\n<label>{name}:</label>\n{value}\n</div>'
+                   for name, value in detail()["fields"].items() if name != "Stato")
+    return f'''<div class="app-menu"></div><div class="my-col-6">
+      <h4>Dati Prenotazione</h4><div>{rows}
+      <div>\n<label><b>* Stato:</b></label>\n<b>Annullata</b>\n</div></div></div>
+      <div><h4>Dati Richiedente</h4><div data-private="true">PRIVATE-APPLICANT</div></div>
+      <input type="hidden" id="IDTipoStatoPrenotazione" name="IDTipoStatoPrenotazione" value="3">
+      <input type="hidden" name="DetailToPrint" value="PRIVATE-PRINT-PAYLOAD">
+      <button id="btnStampa">Print</button>'''
+
+
+def list_html():
+    heads = "".join(f"<th>{h}</th>" for h in [*HEADERS, ""])
+    cells = '<td><a href="/ReservationDetail/Index/synthetic-link">SYNTHETIC-REFERENCE</a></td>'
+    cells += ''.join(f'<td>{v}</td>' for v in ('Visti', 'Visti Nazionali e Schengen', '13 ottobre 2026', '10:25', 'Annullata'))
+    cells += '<td data-private="true">PRIVATE-APPLICANT</td><td data-private="true">PRIVATE-ACTIONS</td>'
+    return f'<div class="app-menu"></div><table id="dataTableReservations" class="dataTable"><thead><tr>{heads}</tr></thead><tbody><tr>{cells}</tr></tbody></table><table id="dataTableReservationsWL"></table>'
+
+
+def dom_tree(html):
+    class FixtureParser(HTMLParser):
+        def __init__(self):
+            super().__init__()
+            self.root = {"nodeType": 1, "tag": "document", "attrs": {}, "nodes": []}
+            self.stack = [self.root]
+
+        def handle_starttag(self, tag, attrs):
+            attrs = dict(attrs)
+            if "class" in attrs:
+                attrs["class"] = attrs["class"].split()
+            node = {"nodeType": 1, "tag": tag, "attrs": attrs, "nodes": []}
+            self.stack[-1]["nodes"].append(node)
+            if tag not in {"input", "br", "hr", "img", "meta", "link"}:
+                self.stack.append(node)
+
+        def handle_endtag(self, tag):
+            assert self.stack[-1]["tag"] == tag, "invalid synthetic HTML fixture"
+            self.stack.pop()
+
+        def handle_data(self, data):
+            self.stack[-1]["nodes"].append({"nodeType": 3, "text": data})
+
+        def handle_comment(self, data):
+            self.stack[-1]["nodes"].append({"nodeType": 8, "text": data})
+
+    parser = FixtureParser()
+    parser.feed(html)
+    return parser.root
+
+
+JS_HARNESS = r"""
+const fs = require('fs'), vm = require('vm');
+const {script, tree, mode, detail} = JSON.parse(fs.readFileSync(0, 'utf8'));
+const location = {origin: mode === 'wrong_origin' ? 'https://attacker.test' : 'https://prenotami.esteri.it',
+  pathname: detail ? '/ReservationDetail/Index/synthetic-link' : '/Reservation'};
+let apiGets = 0;
+class Node {
+  constructor(data, parent=null) {
+    this.nodeType=data.nodeType; this.tagName=(data.tag||'').toUpperCase(); this.attrs=data.attrs||{};
+    this.own=data.text||''; this.parentElement=parent; this.childNodes=(data.nodes||[]).map(n=>new Node(n,this));
+    this.classList={contains:s=>(this.attrs.class||[]).includes(s)};
+  }
+  get children(){return this.childNodes.filter(n=>n.nodeType===1);}
+  get hidden(){return 'hidden' in this.attrs;}
+  get style(){return Object.fromEntries((this.attrs.style||'').split(';').filter(Boolean)
+    .map(s=>s.split(':').map(v=>v.trim())));}
+  get textContent(){if(this.attrs['data-private']) throw Error('private cell read'); return this.own+this.childNodes.map(n=>n.textContent).join('');}
+  get innerText(){if(this.attrs['data-private'])throw Error('private cell read');
+    if((this.attrs.style||'').includes('display:none'))return '';
+    return this.own+this.childNodes.map(n=>n.innerText).join('');}
+  get value(){if(this.attrs.name==='DetailToPrint') throw Error('print payload read');return this.attrs.value||'';}
+  get type(){return this.attrs.type||'';}
+  get name(){return this.attrs.name||'';}
+  get href(){return new URL(this.attrs.href,location.origin).href;}
+  matches(selector){
+    if(selector.includes(' ')){const [parent,child]=selector.split(' ');return this.matches(child)&&Boolean(this.parentElement?.closest(parent));}
+    if(selector[0]==='.')return this.classList.contains(selector.slice(1));
+    if(selector[0]==='#')return this.attrs.id===selector.slice(1);
+    if(selector==='input#IDTipoStatoPrenotazione')return this.tagName==='INPUT'&&this.attrs.id==='IDTipoStatoPrenotazione';
+    if(selector==='a[href]')return this.tagName==='A'&&'href' in this.attrs;
+    return this.tagName.toLowerCase()===selector;
+  }
+  closest(s){return this.matches(s)?this:(this.parentElement?.closest(s)||null);}
+  contains(n){return this===n||this.children.some(c=>c.contains(n));}
+  querySelectorAll(s){return this.children.flatMap(c=>[...(c.matches(s)?[c]:[]),...c.querySelectorAll(s)]);}
+  querySelector(s){return this.querySelectorAll(s)[0]||null;}
+}
+const document=new Node(tree);
+document.readyState=mode==='loading'?'loading':'complete';
+const isDataTable=t=>mode!=='uninitialized'&&t.attrs.id==='dataTableReservations';
+function $(t){return {DataTable(){
+  apiGets++; if(!isDataTable(t))throw Error('initialized unexpectedly');
+  const nodes=t.querySelectorAll('tbody tr'); const count=nodes.length;
+  const info={page:0,pages:count?Math.ceil(count/10):0,start:0,end:Math.min(count,10),length:10,
+    recordsTotal:count,recordsDisplay:count,serverSide:mode==='server_side'};
+  if(mode==='partial')info.recordsTotal=count+1;
+  return {page:{info:()=>info},search:()=>mode==='filter'?'PRIVATE-SEARCH':'',
+    columns:()=>({search:()=>({toArray:()=>[mode==='column_filter'?'PRIVATE-SEARCH':'']})}),
+    rows:()=>({count:()=>count,nodes:()=>({toArray:()=>mode==='deferred_nodes'?[]:nodes})})};
+}};}
+$.fn={dataTable:{isDataTable}};
+const window={location,jQuery:$,getComputedStyle:n=>({
+  display:mode==='detached'?'':(n.style.display||'inline'),
+  visibility:mode==='detached'?'':(n.style.visibility||'visible')})};
+const raw=vm.runInNewContext('(function(){'+script+'})()', {window,document}, {timeout:1000});
+process.stdout.write(JSON.stringify({raw,apiGets}));
+"""
+
+
+@unittest.skipUnless(shutil.which("node"), "node required for actual readonly JS execution")
+class ActualJavaScriptTests(unittest.TestCase):
+    def run_js(self, *, detail_page=False, mode="normal", html=None, script=None):
+        proc = subprocess.run([shutil.which("node"), "-e", JS_HARNESS],
+                              input=json.dumps({"script": script or (DETAIL_READ_SCRIPT if detail_page else LIST_READ_SCRIPT),
+                                                "tree": dom_tree(html or (detail_html() if detail_page else list_html())),
+                                                "mode": mode, "detail": detail_page}),
+                              text=True, capture_output=True, timeout=10)
+        self.assertEqual(proc.returncode, 0, proc.stderr)
+        self.assertNotIn("PRIVATE-", proc.stdout)
+        return json.loads(proc.stdout)
+
+    def test_date_diagnostic_distinguishes_hidden_metadata_and_node_reader_excludes_it(self):
+        # Hidden-element + text shape is observed; tag and contents are synthetic.
+        html = list_html().replace('<td>13 ottobre 2026</td>',
+                                  '<td><span style="display:none">20261013</span>13 ottobre 2026</td>')
+        raw = self.run_js(html=html, script=DATE_DIAGNOSTIC_SCRIPT)["raw"]
+        page = SimpleNamespace(url="https://prenotami.esteri.it/Reservation", tab_id="synthetic-tab",
+                               run_js=Mock(return_value=raw))
+        diagnostic = read_reservation_date_diagnostic(page)
+        self.assertTrue(diagnostic["available"])
+        item = diagnostic["samples"][0]
+        self.assertFalse(item["textEqualsRendered"])
+        self.assertFalse(item["text"]["acceptedByCurrentParser"])
+        self.assertTrue(item["rendered"]["acceptedByCurrentParser"])
+        self.assertEqual(item["text"]["italianMonths"], [10])
+        self.assertTrue(item["parts"][0]["hidden"])
+        self.assertNotIn("20261013", json.dumps(diagnostic))
+        self.assertNotIn("13 ottobre 2026", json.dumps(diagnostic))
+        parsed = parse_reservation_listing(self.run_js(html=html)["raw"])
+        self.assertEqual(parsed.rows[0].day, date(2026, 10, 13))
+        # Python's strict date grammar has NOT been loosened to extract substrings.
+        mixed = listing()
+        mixed["tables"][0]["rows"][0]["date"] = "2026101313 ottobre 2026"
+        with self.assertRaisesRegex(ReservationReadError, "date_unrecognized"):
+            parse_reservation_listing(mixed)
+
+    def test_observed_hidden_other_element_then_text_shape_parses(self):
+        html = list_html().replace('<td>13 ottobre 2026</td>',
+                                  '<td><label style="display:none">20261013 09:35</label>13 ottobre 2026</td>')
+        raw = self.run_js(html=html, script=DATE_DIAGNOSTIC_SCRIPT)["raw"]
+        page = SimpleNamespace(url="https://prenotami.esteri.it/Reservation", tab_id="synthetic-tab",
+                               run_js=Mock(return_value=raw))
+        sample = read_reservation_date_diagnostic(page)["samples"][0]
+        self.assertEqual(sample["parts"][0]["kind"], "other")
+        self.assertEqual(sample["parts"][0]["shape"], "DDDDDDDD DD:DD")
+        self.assertEqual(sample["text"]["shape"], "DDDDDDDD DD:DDDD LLLLLLL DDDD")
+        result = parse_reservation_listing(self.run_js(html=html)["raw"])
+        self.assertEqual(result.rows[0].day, date(2026, 10, 13))
+
+    def test_hidden_date_metadata_is_not_read_or_assumed_to_be_a_sort_key(self):
+        for marker in ('style="display: none"', 'hidden', 'style="visibility: hidden"'):
+            with self.subTest(marker=marker):
+                html = list_html().replace('<td>13 ottobre 2026</td>',
+                    f'<td><label {marker} data-private="true">PRIVATE-METADATA</label>13 ottobre 2026</td>')
+                self.assertEqual(parse_reservation_listing(self.run_js(html=html)["raw"]).rows[0].day,
+                                 date(2026, 10, 13))
+
+    def test_unrendered_client_rows_use_text_nodes_not_cell_inner_text(self):
+        html = list_html().replace('<td>13 ottobre 2026</td>',
+            '<td data-private="true"><label style="display:none">20261013 09:35</label>13 ottobre 2026</td>')
+        # Reading the parent td textContent/innerText would throw. Detached style
+        # resolution is empty, but the child's own inline marker still exists.
+        output = self.run_js(html=html, mode="detached")
+        self.assertEqual(parse_reservation_listing(output["raw"]).rows[0].day, date(2026, 10, 13))
+
+    def test_visible_elements_and_ambiguous_text_nodes_are_not_silently_dropped(self):
+        for value in ('<label>20261013 09:35</label>13 ottobre 2026',
+                      '<span>13 ottobre 2026</span>',
+                      '13 ottobre 2026<!-- split -->14 ottobre 2026',
+                      '<label style="display:none">13 ottobre 2026</label>',
+                      '<label style="visibility:hidden"><span style="visibility:visible">Other</span></label>13 ottobre 2026',
+                      '<!-- comment -->' * 17 + '13 ottobre 2026'):
+            with self.subTest(value=value):
+                html = list_html().replace('<td>13 ottobre 2026</td>', f'<td>{value}</td>')
+                self.assertEqual(self.run_js(html=html)["raw"], {"error": "date_cell_structure_changed"})
+
+    def test_invalid_dates_and_visible_mixed_metadata_still_fail_strictly(self):
+        for value in ('31 febbraio 2026', '20261013 09:3513 ottobre 2026', '2026-10-13'):
+            with self.subTest(value=value):
+                html = list_html().replace('<td>13 ottobre 2026</td>',
+                    f'<td><label style="display:none">SORT</label>{value}</td>')
+                with self.assertRaisesRegex(ReservationReadError, "date_unrecognized"):
+                    parse_reservation_listing(self.run_js(html=html)["raw"])
+
+    def test_hidden_metadata_is_removed_on_all_loaded_client_pages(self):
+        html = list_html().replace('<td>13 ottobre 2026</td>',
+            '<td><label style="display:none">20261013 09:35</label>13 ottobre 2026</td>')
+        start, end = html.index('<tbody>') + len('<tbody>'), html.index('</tbody>')
+        row = html[start:end]
+        extra = ''.join(row.replace('SYNTHETIC-REFERENCE', f'REF-{i}').replace('synthetic-link', f'link-{i}')
+                        for i in range(10))
+        html = html[:end] + extra + html[end:]
+        result = parse_reservation_listing(self.run_js(html=html, mode="detached")["raw"])
+        self.assertEqual(len(result.rows), 11)
+        self.assertEqual(result.page_count, 2)
+        self.assertTrue(all(r.day == date(2026, 10, 13) for r in result.rows))
+
+    def test_date_diagnostic_does_not_initialize_or_read_wrong_headers(self):
+        for mode in ("wrong_origin", "uninitialized", "loading"):
+            output = self.run_js(mode=mode, script=DATE_DIAGNOSTIC_SCRIPT)
+            self.assertIn("error", output["raw"])
+            self.assertEqual(output["apiGets"], 0)
+        output = self.run_js(html=list_html().replace('<th>Data</th>', '<th>Other</th>'),
+                             script=DATE_DIAGNOSTIC_SCRIPT)
+        self.assertIn("error", output["raw"])
+        self.assertEqual(output["apiGets"], 0)
+
+    def test_date_diagnostic_masks_unknown_text_and_rejects_extra_payload(self):
+        raw = self.run_js(script=DATE_DIAGNOSTIC_SCRIPT)["raw"]
+        raw["samples"][0]["text"] = "SECRET-USER@example.invalid"
+        page = SimpleNamespace(url="https://prenotami.esteri.it/Reservation", tab_id="synthetic-tab",
+                               run_js=Mock(return_value=raw))
+        diagnostic = read_reservation_date_diagnostic(page)
+        self.assertTrue(diagnostic["available"])
+        self.assertNotIn("SECRET", json.dumps(diagnostic))
+        raw["samples"][0]["parts"][0]["kind"] = "SECRET-USER"
+        self.assertEqual(read_reservation_date_diagnostic(page), {"available": False})
+
+    def test_date_diagnostic_limits_output_and_context(self):
+        raw = self.run_js(script=DATE_DIAGNOSTIC_SCRIPT)["raw"]
+        raw["samples"] *= 4
+        page = SimpleNamespace(url="https://prenotami.esteri.it/Reservation", tab_id="synthetic-tab",
+                               run_js=Mock(return_value=raw))
+        self.assertEqual(read_reservation_date_diagnostic(page), {"available": False})
+        page.url = "https://prenotami.esteri.it/UserArea"
+        page.run_js.reset_mock()
+        self.assertEqual(read_reservation_date_diagnostic(page), {"available": False})
+        page.run_js.assert_not_called()
+
+    def test_actual_detail_script_parses_observed_text_siblings_and_b(self):
+        output = self.run_js(detail_page=True)
+        self.assertEqual(output["raw"], detail())
+        self.assertIs(parse_reservation_detail(output["raw"]).state, ReservationState.CANCELLED)
+        self.assertEqual(output["apiGets"], 0)
+
+    def test_blank_text_nodes_and_comments_do_not_define_field_positions(self):
+        html = detail_html().replace('<label>', '\n<!-- spacing -->\n<label>').replace('</label>', '</label>\n   ')
+        self.assertEqual(self.run_js(detail_page=True, html=html)["raw"], detail())
+
+    def test_unsafe_detail_shapes_fail_closed(self):
+        cases = {
+            "missing": detail_html().replace('<label>Ora:</label>', '<label>Other:</label>'),
+            "duplicate": detail_html().replace('<label>Ora:</label>', '<label>Ora:</label><label>Ora:</label>'),
+            "wrapped": detail_html().replace('10:25', '<span>10:25</span>'),
+            "code_duplicate": detail_html() + '<input id="IDTipoStatoPrenotazione" type="hidden">',
+            "section_duplicate": detail_html() + '<h4>Dati Prenotazione</h4>',
+            "no_auth": detail_html().replace('app-menu', 'no-menu'),
+            "inline_conflict": detail_html().replace('<label>Ora:</label>', '<label>Ora: 14:00</label>'),
+            "extra_value": detail_html().replace('10:25', '10:25<b>14:00</b>'),
+        }
+        for mode, html in cases.items():
+            with self.subTest(mode=mode):
+                self.assertIn("error", self.run_js(detail_page=True, html=html)["raw"])
+
+    def test_actual_list_script_returns_no_applicant_or_unnamed_cell_values(self):
+        output = self.run_js()
+        parsed = parse_reservation_listing(output["raw"])
+        self.assertEqual(parsed.rows[0].reference, "SYNTHETIC-REFERENCE")
+        self.assertEqual(output["apiGets"], 1)
+        self.assertEqual(parsed.waitlist_count, 0)
+
+    def test_reading_metadata_never_initializes_tables(self):
+        output = self.run_js(mode="uninitialized")
+        self.assertEqual(output["raw"], {"error": "not_ready"})
+        self.assertEqual(output["apiGets"], 0)
+
+    def test_duplicate_table_or_missing_link_is_rejected(self):
+        for html in (list_html() + '<table id="dataTableReservations"></table>',
+                     list_html().replace('href="/ReservationDetail/Index/synthetic-link"', 'data-no-link="true"')):
+            self.assertIn("error", self.run_js(html=html)["raw"])
+
+    def test_all_loaded_client_pages_are_read_without_page_draw(self):
+        html = list_html()
+        start, end = html.index('<tbody>') + len('<tbody>'), html.index('</tbody>')
+        row = html[start:end]
+        extra = ''.join(row.replace('SYNTHETIC-REFERENCE', f'REF-{i}').replace('synthetic-link', f'link-{i}') for i in range(10))
+        html = html[:end] + extra + html[end:]
+        result = parse_reservation_listing(self.run_js(html=html)["raw"])
+        self.assertEqual(len(result.rows), 11)
+        self.assertEqual(result.page_count, 2)
+
+    def test_filters_server_paging_partial_rows_and_loading_fail_closed(self):
+        for mode in ("server_side", "partial", "filter", "column_filter", "deferred_nodes", "loading", "wrong_origin"):
+            with self.subTest(mode=mode):
+                self.assertIn("error", self.run_js(mode=mode)["raw"])
+
+    def test_waitlist_with_initialization_traces_not_counted_as_empty(self):
+        for html in (list_html().replace('id="dataTableReservationsWL"', 'id="dataTableReservationsWL" class="dataTable"'),
+                     list_html().replace('<table id="dataTableReservationsWL"></table>', '<div class="dataTables_wrapper"><table id="dataTableReservationsWL"></table></div>')):
+            self.assertEqual(self.run_js(html=html)["raw"], {"error": "not_ready"})
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 252 - 0
test/test_ita_route_wiring.py

@@ -0,0 +1,252 @@
+import ast
+import json
+import unittest
+from pathlib import Path
+
+from plugins.ita_plugin import ItaPlugin
+from tools.debug_ita_query import (
+    DEFAULT_ITA_ROUTING_KEY,
+    DEFAULT_ITA_SERVICE_ID,
+    build_query_config,
+    resolve_debug_route,
+)
+from vs_types import AppointmentType, BizLogicError, VSPlgConfig
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+ITALY_GROUP_ID = "pernotami.ie.it"
+
+
+def appointment_type(routing_key, *, city):
+    return AppointmentType(
+        routing_key=routing_key,
+        country="Italy",
+        city=city,
+        visa_type="Tourist",
+    )
+
+
+def probe_route(service_id):
+    return {
+        "service_id": service_id,
+        "capability": "services_probe_only",
+    }
+
+
+class ItaPluginRouteWiringTests(unittest.TestCase):
+    @staticmethod
+    def _plugin(apt_configs):
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        plugin.page = None
+        plugin.root_workspace = "/nonexistent/ita-route-wiring"
+        plugin.tunnel = None
+        plugin._profile_lock_handle = None
+        plugin.free_config = {
+            "query_mode": "services_probe",
+            "final_submit_enabled": False,
+            "apt_configs": apt_configs,
+        }
+        return plugin
+
+    def test_two_sede_fixtures_use_the_same_route_resolver(self):
+        first_key = "slot.dub.it.tourist"
+        second_key = "slot.hkg.it.tourist"
+        plugin = self._plugin(
+            {
+                first_key: probe_route(1321),
+                second_key: probe_route(4937),
+            }
+        )
+
+        first = plugin._resolve_route(
+            appointment_type(first_key, city="Dublin")
+        )
+        second = plugin._resolve_route(
+            appointment_type(second_key, city="Hong Kong")
+        )
+
+        self.assertEqual(first.routing_key, first_key)
+        self.assertEqual(first.service_id, 1321)
+        self.assertEqual(second.routing_key, second_key)
+        self.assertEqual(second.service_id, 4937)
+
+    def test_top_level_service_id_is_not_a_runtime_fallback(self):
+        plugin = self._plugin({})
+        plugin.free_config["service_id"] = 1321
+
+        with self.assertRaisesRegex(
+            BizLogicError,
+            "route configuration rejected.*route_missing",
+        ):
+            plugin._resolve_route(
+                appointment_type("slot.sample.it.tourist", city="Sample")
+            )
+
+    def test_unknown_capability_fails_closed(self):
+        routing_key = "slot.sample.it.tourist"
+        plugin = self._plugin(
+            {
+                routing_key: {
+                    "service_id": 100,
+                    "capability": "guessed_live",
+                }
+            }
+        )
+
+        with self.assertRaisesRegex(
+            BizLogicError,
+            "route configuration rejected.*capability_unsupported",
+        ):
+            plugin._resolve_route(
+                appointment_type(routing_key, city="Sample")
+            )
+
+    def test_cs3_accepts_calendar_mode_but_keeps_final_disabled(self):
+        plugin = ItaPlugin.__new__(ItaPlugin)
+        plugin.page = None
+        plugin._transient_user_data_path = "/nonexistent/transient"
+        plugin.root_workspace = "/nonexistent/root"
+        plugin.tunnel = None
+        plugin._profile_lock_handle = None
+
+        plugin.set_config(
+            VSPlgConfig(free_config={"query_mode": "calendar"})
+        )
+        self.assertEqual(plugin.free_config["query_mode"], "calendar")
+
+        for free_config, expected in (
+            ({"query_mode": "unknown"}, "query_mode"),
+            ({"final_submit_enabled": True}, "final submission requires explicit OTP mode on an applicant Book configuration"),
+        ):
+            with self.subTest(free_config=free_config):
+                with self.assertRaisesRegex(BizLogicError, expected):
+                    plugin.set_config(VSPlgConfig(free_config=free_config))
+
+
+class ItaDebugRouteTests(unittest.TestCase):
+    def test_default_route_is_only_a_backward_compatible_default(self):
+        route = resolve_debug_route({})
+
+        self.assertEqual(route.routing_key, DEFAULT_ITA_ROUTING_KEY)
+        self.assertEqual(route.service_id, DEFAULT_ITA_SERVICE_ID)
+
+    def test_explicit_route_changes_key_service_and_display_metadata_together(self):
+        route = resolve_debug_route(
+            {
+                "ITA_ROUTING_KEY": "slot.sample.it.tourist",
+                "ITA_SERVICE_ID": "9001",
+                "ITA_CITY": "Sample City",
+                "ITA_VISA_TYPE": "Short-stay tourism",
+            }
+        )
+        config = build_query_config(
+            {
+                "ITA_ROUTING_KEY": route.routing_key,
+                "ITA_SERVICE_ID": str(route.service_id),
+                "ITA_CITY": route.city,
+                "ITA_VISA_TYPE": route.visa_type,
+            },
+            username="offline-test@example.test",
+            password="offline-password",
+        )
+
+        apt_type = route.appointment_type()
+        self.assertEqual(apt_type.routing_key, route.routing_key)
+        self.assertEqual(apt_type.city, route.city)
+        self.assertEqual(
+            config.free_config["apt_configs"][route.routing_key],
+            probe_route(route.service_id),
+        )
+        self.assertNotIn("service_id", config.free_config)
+        self.assertEqual(config.free_config["query_mode"], "services_probe")
+        self.assertIs(config.free_config["final_submit_enabled"], False)
+
+    def test_partial_route_override_fails_closed(self):
+        for env in (
+            {"ITA_SERVICE_ID": "4937"},
+            {"ITA_ROUTING_KEY": "slot.hkg.it.tourist"},
+            {
+                "ITA_ROUTING_KEY": "slot.hkg.it.tourist",
+                "ITA_SERVICE_ID": "4937",
+                "ITA_CITY": "Hong Kong",
+            },
+        ):
+            with self.subTest(env=env):
+                with self.assertRaisesRegex(
+                    ValueError,
+                    "route override must set",
+                ):
+                    resolve_debug_route(env)
+
+    def test_invalid_explicit_service_id_is_rejected(self):
+        for value in ("0", "-1", "not-an-integer"):
+            with self.subTest(value=value):
+                with self.assertRaisesRegex(ValueError, "ITA_SERVICE_ID"):
+                    resolve_debug_route(
+                        {
+                            "ITA_ROUTING_KEY": "slot.sample.it.tourist",
+                            "ITA_SERVICE_ID": value,
+                            "ITA_CITY": "Sample City",
+                            "ITA_VISA_TYPE": "Short-stay tourism",
+                        }
+                    )
+
+
+class ItaProductionConfigParityTests(unittest.TestCase):
+    @staticmethod
+    def _italy_group(path):
+        groups = json.loads(path.read_text(encoding="utf-8"))
+        return next(
+            group for group in groups if group["identifier"] == ITALY_GROUP_ID
+        )
+
+    def test_sentinel_and_booker_share_the_same_safe_route_contract(self):
+        sentinel = self._italy_group(
+            REPO_ROOT / "config" / "config_sentinel.json"
+        )
+        booker = self._italy_group(
+            REPO_ROOT / "config" / "config_booker.json"
+        )
+
+        for group in (sentinel, booker):
+            free_config = group["free_config"]
+            self.assertNotIn("service_id", free_config)
+            self.assertEqual(free_config["query_mode"], "services_probe")
+            self.assertIs(free_config["final_submit_enabled"], False)
+
+        self.assertEqual(
+            sentinel["free_config"]["apt_configs"],
+            booker["free_config"]["apt_configs"],
+        )
+        routing_key = sentinel["appointment_types"][0]["routing_key"]
+        self.assertIn(routing_key, sentinel["free_config"]["apt_configs"])
+
+    def test_runtime_code_has_no_sede_or_service_id_control_branch(self):
+        paths = [
+            REPO_ROOT / "plugins" / "ita_plugin.py",
+            REPO_ROOT / "tools" / "debug_ita_query.py",
+            REPO_ROOT / "tools" / "debug_ita_book.py",
+            REPO_ROOT / "tools" / "debug_ita_monitor.py",
+            REPO_ROOT / "tools" / "debug_ita_soak.py",
+            REPO_ROOT / "tools" / "debug_ita_calendar_gate.py",
+            REPO_ROOT / "tools" / "ita_local_handoff.py",
+        ]
+        forbidden_constants = {1321, 4937, "Dublin", "Hong Kong", "hkg"}
+        violations = []
+        for path in paths:
+            tree = ast.parse(path.read_text(encoding="utf-8"))
+            for node in ast.walk(tree):
+                if not isinstance(node, (ast.If, ast.IfExp)):
+                    continue
+                for child in ast.walk(node.test):
+                    if (
+                        isinstance(child, ast.Constant)
+                        and child.value in forbidden_constants
+                    ):
+                        violations.append((path.name, node.lineno, child.value))
+
+        self.assertEqual(violations, [])
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 929 - 0
test/test_ita_workflow.py

@@ -0,0 +1,929 @@
+"""Offline production-entry tests: no credentials, site calls, or cloud writes."""
+import ast
+import logging
+import itertools
+from dataclasses import replace
+from contextlib import ExitStack
+from datetime import datetime
+from pathlib import Path
+from io import StringIO
+from contextlib import redirect_stdout
+from types import MethodType, SimpleNamespace
+from unittest import TestCase
+from unittest.mock import Mock, patch
+
+from plugins import ita_workflow as workflow
+from plugins import ita_calendar_session as preparation
+from plugins.ita_booking_final import FinalOutcomeUnknown, SubmissionSignal, VerifiedSubmission
+from plugins.ita_plugin import ItaPlugin
+from plugins import ita_otp
+from plugins import ita_turnstile
+from plugins.ita_protocol import OtpMailConfig
+from test import test_ita_calendar_book_flow as flow
+from test.test_debug_ita_calendar_gate import booking_preflight_snapshot
+from test import test_ita_final_attribution as attribution
+from vs_types import AvailabilityStatus, BizLogicError, PermissionDeniedError, VSBookResult, VSPlgConfig, VSQueryResult
+
+
+class PreparationTests(TestCase):
+    def setUp(self):
+        _, self.route, _ = flow.prepared_plugin(flow.FlowPage())
+        self.path = f"/Services/Booking/{self.route.service_id}"
+        self.page = SimpleNamespace(url="https://prenotami.esteri.it" + self.path,
+                                    tab_id="fixture-tab", wait=Mock(), set=Mock())
+        self.otp_present = False
+        self.clicks = []
+        self.page.run_js = Mock(side_effect=lambda _: booking_preflight_snapshot(
+            otpValuePresent=self.otp_present, otpDisabled=self.otp_present))
+        otp_input = Mock()
+        otp_input.input.side_effect = lambda *a, **k: setattr(self, "otp_present", True)
+        otp_input.run_js.return_value = True
+        otp_input.selector = "#otp-input"
+        controls = {"#otp-input": otp_input, "#otp-send": SimpleNamespace(selector="#otp-send"),
+                    "#btnAvanti": SimpleNamespace(selector="#btnAvanti")}
+        self.page.ele = Mock(side_effect=lambda selector, **kwargs: controls[selector])
+        self.plugin = SimpleNamespace(
+            page=self.page, session_create_time=1, free_config={"otp_mode": "manual"},
+            config=SimpleNamespace(account=SimpleNamespace(username="fixture@example.test")),
+            mouse=SimpleNamespace(human_click_ele=lambda ele: self.clicks.append(ele.selector)),
+            _booking_path=lambda route: self.path, _log=Mock(),
+            _record_calendar_query_prepared_route=Mock(), _record_calendar_book_prepared_route=Mock(),
+        )
+        self.plugin._book_final_configuration_valid = MethodType(ItaPlugin._book_final_configuration_valid, self.plugin)
+        self.stack = ExitStack()
+        self.addCleanup(self.stack.close)
+        self.tty = self.stack.enter_context(patch.object(workflow.sys.stdin, "isatty", return_value=True))
+        self.reader = self.stack.enter_context(patch.object(preparation, "_read_manual_otp", return_value="123456"))
+        self.listener = self.stack.enter_context(patch.object(workflow, "listen_once", side_effect=self.listen))
+        self.stack.enter_context(patch.object(workflow, "guard_calendar"))
+        self.stack.enter_context(patch.object(workflow, "wait_for_calendar_service", return_value="9001"))
+
+    def listen(self, page, *, target, method, timeout, action):
+        action()
+        if target == self.path:
+            page.url = "https://prenotami.esteri.it/BookingCalendar?selectedService=Example"
+        return SimpleNamespace(tab_id=page.tab_id, is_failed=False, method=method,
+            url="https://prenotami.esteri.it" + target + ("?ServiceID=9001" if method == "GET" else ""),
+            response=SimpleNamespace(status=200, raw_body='"SENT"', url=page.url))
+
+    def test_native_preparation_sends_once_writes_once_and_records_query_role(self):
+        workflow.prepare_calendar(self.plugin, self.route, role="query")
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input", "#btnAvanti"])
+        self.assertEqual(self.listener.call_count, 2)
+        self.reader.assert_called_once()
+        self.plugin._record_calendar_query_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_book_prepared_route.assert_not_called()
+        self.assertEqual(self.page.run_js.call_count, 2)
+        self.assertIn("form-boundary", self.page.run_js.call_args.args[0])
+
+    def test_book_role_does_not_mark_query_prepared(self):
+        workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.plugin._record_calendar_book_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_no_terminal_stops_before_otp_or_form_changes(self):
+        self.tty.return_value = False
+        with self.assertRaises(PermissionDeniedError):
+            workflow.prepare_calendar(self.plugin, self.route, role="query")
+        self.listener.assert_not_called()
+        self.page.run_js.assert_not_called()
+
+    def test_wrong_otp_readback_prevents_avanti_and_repeated_otp(self):
+        self.page.ele("#otp-input").run_js.return_value = False
+        with self.assertRaisesRegex(preparation.CalendarGateError, "verification failed"):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        with self.assertRaises(PermissionDeniedError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input"])
+        self.assertEqual(self.listener.call_count, 1)
+
+    def test_wrong_tab_response_never_reads_otp_or_submits_form(self):
+        self.listener.side_effect = None
+        self.listener.return_value = SimpleNamespace(tab_id="foreign", is_failed=False)
+        with self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, self.route, role="query")
+        self.reader.assert_not_called()
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+
+class CloudPreparationTests(TestCase):
+    """Reuse the manual site's fixture, replacing only the OTP provider."""
+    listen = PreparationTests.listen
+
+    def setUp(self):
+        PreparationTests.setUp(self)
+        self.plugin.free_config["otp_mode"] = "cloud"
+        self.route = replace(self.route, mail=OtpMailConfig("mailbox@example.test"))
+        self.tty.return_value = False
+        self.stack.enter_context(patch.object(ita_otp.vs_log_macros, "_active_logger",
+                                             logging.Logger("offline-otp", logging.INFO)))
+        self.fetch = self.stack.enter_context(patch.object(workflow, "fetch_otp_from_cloud",
+                                                          return_value="001234"))
+        self.utc = self.stack.enter_context(patch.object(workflow, "utc_sent_at",
+                                                        return_value="2026-08-31 01:02:03"))
+
+    def test_automatic_preparation_without_tty_reuses_native_controls_and_readback(self):
+        observed = []
+        def fetch(mail, **kwargs):
+            observed.extend(self.clicks)
+            return "001234"
+        self.fetch.side_effect = fetch
+        output = StringIO()
+        with redirect_stdout(output):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(observed, ["#otp-send"])
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input", "#btnAvanti"])
+        self.fetch.assert_called_once_with(self.route.mail, recipient="fixture@example.test",
+                                           sent_at="2026-08-31 01:02:03")
+        self.page.ele("#otp-input").input.assert_called_once_with("001234", clear=True)
+        self.reader.assert_not_called()
+        self.assertNotIn("001234", output.getvalue() + str(self.plugin._log.call_args_list))
+        self.plugin._record_calendar_book_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_send_timestamp_is_captured_before_native_send(self):
+        def click(ele):
+            if ele.selector == "#otp-send":
+                self.utc.assert_called_once()
+            self.clicks.append(ele.selector)
+        self.plugin.mouse.human_click_ele = click
+        workflow.prepare_calendar(self.plugin, self.route, role="book")
+
+    def test_mail_failure_has_no_avanti_no_manual_fallback_no_same_session_resend(self):
+        self.fetch.side_effect = preparation.CalendarGateError("Italy OTP mailbox read failed")
+        with self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        with self.assertRaises(PermissionDeniedError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(self.clicks, ["#otp-send"])
+        self.fetch.assert_called_once()
+        self.reader.assert_not_called()
+
+    def test_late_response_is_discarded_before_dom_write(self):
+        with patch.object(workflow, "monotonic", side_effect=[0, 1, 300]):
+            with self.assertRaisesRegex(preparation.CalendarGateError, "window expired"):
+                workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(self.clicks, ["#otp-send"])
+
+    def test_expiration_during_preflight_prevents_avanti(self):
+        with patch.object(workflow, "monotonic", side_effect=[0, 1, 2, 300]):
+            with self.assertRaisesRegex(preparation.CalendarGateError, "window expired"):
+                workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input"])
+
+    def test_account_change_during_read_discards_code(self):
+        def changed(*args, **kwargs):
+            self.plugin.config.account.username = "other@example.test"
+            return "001234"
+        self.fetch.side_effect = changed
+        with self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertEqual(self.clicks, ["#otp-send"])
+
+    def test_cloud_dom_write_failure_is_redacted_and_stops_avanti(self):
+        self.page.ele("#otp-input").input.side_effect = RuntimeError("private typed 001234")
+        with self.assertRaisesRegex(preparation.CalendarGateError, "DOM write verification failed") as caught:
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.assertNotIn("001234", str(caught.exception))
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input"])
+
+    def test_wrong_cloud_role_or_invalid_final_flag(self):
+        with self.assertRaises(PermissionDeniedError):
+            workflow.prepare_calendar(self.plugin, self.route, role="query")
+        self.plugin.free_config["final_submit_enabled"] = 1
+        with self.assertRaises(PermissionDeniedError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.listener.assert_not_called()
+        self.fetch.assert_not_called()
+
+    def test_missing_mail_and_debug_logger_stop_before_any_site_action(self):
+        with self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, replace(self.route, mail=None), role="book")
+        ita_otp.vs_log_macros._active_logger.setLevel(logging.DEBUG)
+        with self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        self.listener.assert_not_called()
+        self.page.run_js.assert_not_called()
+
+
+class CloudFinalPreparationTests(CloudPreparationTests):
+    """Run the same OTP/session/expiry/privacy cases with final explicitly on."""
+    def setUp(self):
+        super().setUp()
+        self.plugin.free_config["final_submit_enabled"] = True
+
+    def test_preparation_does_not_itself_submit_final(self):
+        with patch.object(workflow, "submit_final") as submit:
+            workflow.prepare_calendar(self.plugin, self.route, role="book")
+        submit.assert_not_called()
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input", "#btnAvanti"])
+
+
+class CloudQueryPreparationTests(TestCase):
+    """Use the same preparation, mail adapter and fixtures as applicant Book."""
+    listen = PreparationTests.listen
+
+    def setUp(self):
+        CloudPreparationTests.setUp(self)
+        self.plugin.free_config.update(query_mode="calendar", final_submit_enabled=False)
+
+    def prepare(self):
+        workflow.prepare_calendar(self.plugin, self.route, role="query")
+
+    def query_plugin(self, results):
+        self.plugin.query = MethodType(ItaPlugin.query, self.plugin)
+        self.plugin._resolve_route = Mock(return_value=self.route)
+        self.plugin._query_once = Mock(side_effect=results)
+        self.plugin._clear_calendar_query_state = Mock()
+        return self.plugin
+
+    def test_public_query_prepares_once_with_shared_mail_adapter_and_no_terminal(self):
+        strong = VSQueryResult(success=True, availability_status=AvailabilityStatus.Available,
+                               earliest_date=datetime(2026, 10, 13))
+        plugin = self.query_plugin([VSQueryResult(success=True), strong, strong])
+        client = Mock()
+        client.fetch_mail_content.return_value = "OTP Code:001234"
+        self.fetch.side_effect = lambda *args, **kwargs: ita_otp.fetch_otp_from_cloud(
+            *args, **kwargs, api=client)
+        output = StringIO()
+        with patch.object(workflow, "submit_final") as final, redirect_stdout(output):
+            self.assertIs(plugin.query(Mock()), strong)
+            self.assertIs(plugin.query(Mock()), strong)
+        client.fetch_mail_content.assert_called_once_with(
+            email=self.route.mail.authorization_email, sender="noreply-prenotami@esteri.it",
+            recipient=plugin.config.account.username, subject_keywords="OTP Code",
+            body_keywords="OTP Code:", sent_date="2026-08-31 01:02:03", expiry=300, only_text=True)
+        client.fetch_mail_content_from_top.assert_not_called()
+        self.assertEqual(plugin._query_once.call_count, 3)
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input", "#btnAvanti"])
+        self.assertEqual(self.listener.call_count, 2)
+        self.reader.assert_not_called()
+        final.assert_not_called()
+        self.plugin._record_calendar_query_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_book_prepared_route.assert_not_called()
+        self.assertNotIn("001234", output.getvalue() + str(plugin._log.call_args_list))
+
+    def test_account_mailbox_query_uses_the_new_pool_account_without_fixed_address(self):
+        self.route = replace(self.route, mail=OtpMailConfig(authorization_source="account"))
+        self.plugin.config.account.username = "new-pool-account@example.test"
+        strong = VSQueryResult(success=True, availability_status=AvailabilityStatus.Available,
+                               earliest_date=datetime(2026, 10, 13))
+        plugin = self.query_plugin([VSQueryResult(success=True), strong, strong])
+        client = Mock()
+        client.fetch_mail_content.return_value = "OTP Code:001234"
+        self.fetch.side_effect = lambda *args, **kwargs: ita_otp.fetch_otp_from_cloud(*args, **kwargs, api=client)
+        with patch.object(workflow, "submit_final") as final, redirect_stdout(StringIO()):
+            self.assertIs(plugin.query(Mock()), strong)
+            self.assertIs(plugin.query(Mock()), strong)
+        client.fetch_mail_content.assert_called_once()
+        self.assertEqual(client.fetch_mail_content.call_args.kwargs["email"], "new-pool-account@example.test")
+        self.assertEqual(client.fetch_mail_content.call_args.kwargs["recipient"], "new-pool-account@example.test")
+        self.assertIsNone(self.route.mail.authorization_email)
+        self.assertEqual(self.clicks, ["#otp-send", "#otp-input", "#btnAvanti"])
+        self.reader.assert_not_called()
+        final.assert_not_called()
+
+    def test_negative_entry_never_sends_otp_or_reads_mail(self):
+        negative = VSQueryResult(success=False)
+        plugin = self.query_plugin([negative])
+        self.assertIs(plugin.query(Mock()), negative)
+        self.page.run_js.assert_not_called()
+        self.listener.assert_not_called()
+        self.fetch.assert_not_called()
+        self.reader.assert_not_called()
+
+    def test_mail_failure_never_resends_or_falls_back_to_manual_in_same_session(self):
+        self.fetch.side_effect = preparation.CalendarGateError("Italy OTP mailbox read failed")
+        with redirect_stdout(StringIO()):
+            with self.assertRaises(preparation.CalendarGateError):
+                self.prepare()
+            with self.assertRaises(PermissionDeniedError):
+                self.prepare()
+        self.fetch.assert_called_once()
+        self.reader.assert_not_called()
+        self.assertEqual(self.clicks, ["#otp-send"])
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_expired_mail_is_not_written(self):
+        with patch.object(workflow, "monotonic", side_effect=[0, 1, 300]), redirect_stdout(StringIO()):
+            with self.assertRaisesRegex(preparation.CalendarGateError, "window expired"):
+                self.prepare()
+        self.assertEqual(self.clicks, ["#otp-send"])
+        self.reader.assert_not_called()
+
+    def test_account_change_during_mail_read_prevents_code_write(self):
+        def changed(*args, **kwargs):
+            self.plugin.config.account.username = "other@example.test"
+            return "001234"
+        self.fetch.side_effect = changed
+        with redirect_stdout(StringIO()), self.assertRaises(preparation.CalendarGateError):
+            self.prepare()
+        self.assertEqual(self.clicks, ["#otp-send"])
+        self.reader.assert_not_called()
+
+    def test_ambiguous_mail_rejected_by_existing_parser_before_avanti(self):
+        client = Mock()
+        client.fetch_mail_content.return_value = "OTP Code:001234 OTP Code:654321"
+        self.fetch.side_effect = lambda *args, **kwargs: ita_otp.fetch_otp_from_cloud(
+            *args, **kwargs, api=client)
+        with redirect_stdout(StringIO()), self.assertRaisesRegex(preparation.CalendarGateError, "mail rejected"):
+            self.prepare()
+        self.assertEqual(self.clicks, ["#otp-send"])
+        self.reader.assert_not_called()
+        client.fetch_mail_content_from_top.assert_not_called()
+
+    def test_missing_mail_configuration_stops_before_site_actions(self):
+        self.route = replace(self.route, mail=None)
+        with self.assertRaisesRegex(preparation.CalendarGateError, "configuration is missing"):
+            self.prepare()
+        self.page.run_js.assert_not_called()
+        self.listener.assert_not_called()
+        self.fetch.assert_not_called()
+
+    def test_query_cannot_enable_final_submission_or_use_book_preparation(self):
+        for values, role in (({}, "book"), ({"final_submit_enabled": True}, "query")):
+            with self.subTest(role=role):
+                self.plugin.free_config.update(values)
+                with self.assertRaises(PermissionDeniedError):
+                    workflow.prepare_calendar(self.plugin, self.route, role=role)
+        self.page.run_js.assert_not_called()
+        self.listener.assert_not_called()
+        self.fetch.assert_not_called()
+
+class RecoveryWorkflowTests(TestCase):
+    listen = PreparationTests.listen
+
+    def setUp(self):
+        PreparationTests.setUp(self)
+        self.token_ready = False
+        self.page.run_js.side_effect = lambda _: booking_preflight_snapshot(
+            turnstileTokenPresent=self.token_ready,
+            otpValuePresent=self.otp_present, otpDisabled=self.otp_present)
+        self.helper = Mock()
+        self.helper.click_verification_button.return_value = False
+        self.factory = self.stack.enter_context(patch.object(ita_turnstile, 'CloudflareBypasser',
+                                                             return_value=self.helper))
+        self.stack.enter_context(patch.object(preparation.time, 'sleep'))
+
+    def assert_preparation_recovers(self, role):
+        def clicked(**kwargs):
+            self.assertEqual(self.clicks, [])
+            self.token_ready = True
+            return True
+        self.helper.click_verification_button.side_effect = clicked
+        times = itertools.chain([0, 0, 5, 6], itertools.count(7))
+        output = StringIO()
+        with patch.object(preparation.time, 'monotonic', side_effect=lambda: next(times)), redirect_stdout(output):
+            workflow.prepare_calendar(self.plugin, self.route, role=role)
+        self.helper.click_verification_button.assert_called_once_with(is_dfs=False)
+        self.assertEqual(self.clicks, ['#otp-send', '#otp-input', '#btnAvanti'])
+        self.reader.assert_called_once()
+        self.assertEqual(self.listener.call_count, 2)
+        self.assertIn('"state": "ready"', output.getvalue())
+        self.factory.assert_called_once_with(self.page, log=False)
+        self.helper.bypass.assert_not_called()
+
+    def test_book_interaction_is_followed_by_real_readback_before_one_otp(self):
+        self.assert_preparation_recovers('book')
+        self.plugin._record_calendar_book_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_query_reuses_book_recovery_then_records_only_query_preparation(self):
+        self.assert_preparation_recovers('query')
+        self.plugin._record_calendar_query_prepared_route.assert_called_once_with(self.route)
+        self.plugin._record_calendar_book_prepared_route.assert_not_called()
+
+    def test_query_three_clicks_without_token_cannot_release_otp(self):
+        self.helper.click_verification_button.return_value = True
+        with patch.object(preparation.time, 'monotonic', side_effect=[0, 0, 5, 15, 25, 35, 121]), \
+             redirect_stdout(StringIO()), self.assertRaisesRegex(preparation.CalendarGateError, 'turnstile_token_pending'):
+            workflow.prepare_calendar(self.plugin, self.route, role='query')
+        self.assertEqual(self.helper.click_verification_button.call_count, 3)
+        self.listener.assert_not_called()
+        self.reader.assert_not_called()
+        self.assertEqual(self.clicks, [])
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_query_stages_share_one_recovery_budget(self):
+        # The third click yields a real token. Expiry after sending OTP must not
+        # create a fresh recovery budget or allow AVANTI without a new token.
+        def clicked(**kwargs):
+            if self.helper.click_verification_button.call_count == 3:
+                self.token_ready = True
+            return True
+        self.helper.click_verification_button.side_effect = clicked
+        def click(ele):
+            self.clicks.append(ele.selector)
+            if ele.selector == '#otp-send':
+                self.token_ready = False
+        self.plugin.mouse.human_click_ele = click
+        ticks = [0, 0, 5, 15, 25, 26, 27, 27, 32, 42, 52, 148]
+        with patch.object(preparation.time, 'monotonic', side_effect=ticks), \
+             redirect_stdout(StringIO()), self.assertRaisesRegex(preparation.CalendarGateError, 'turnstile_token_pending'):
+            workflow.prepare_calendar(self.plugin, self.route, role='query')
+        self.factory.assert_called_once_with(self.page, log=False)
+        self.assertEqual(self.helper.click_verification_button.call_count, 3)
+        self.assertEqual(self.clicks, ['#otp-send', '#otp-input'])
+        self.assertEqual(self.listener.call_count, 1)
+        self.plugin._record_calendar_query_prepared_route.assert_not_called()
+
+    def test_query_ready_widget_does_not_invoke_helper(self):
+        self.token_ready = True
+        with redirect_stdout(StringIO()):
+            workflow.prepare_calendar(self.plugin, self.route, role='query')
+        self.factory.assert_not_called()
+        self.assertEqual(self.clicks, ['#otp-send', '#otp-input', '#btnAvanti'])
+
+    def test_prepared_query_skips_recovery_and_all_preparation_actions(self):
+        self.page.url = 'https://prenotami.esteri.it/BookingCalendar'
+        with patch.object(workflow, 'ItalyTurnstileRecovery') as recovery:
+            self.assertIsNone(workflow.prepare_query_if_needed(self.plugin, Mock()))
+        recovery.assert_not_called()
+        self.factory.assert_not_called()
+        self.listener.assert_not_called()
+        self.page.run_js.assert_not_called()
+
+    def test_book_timeout_is_diagnostic_and_sends_no_otp(self):
+        output = StringIO()
+        with patch.object(preparation.time, 'monotonic', side_effect=[0, 0, 5, 121]), \
+             redirect_stdout(output), self.assertRaisesRegex(preparation.CalendarGateError, 'turnstile_token_pending'):
+            workflow.prepare_calendar(self.plugin, self.route, role='book')
+        self.listener.assert_not_called()
+        self.reader.assert_not_called()
+        self.assertEqual(self.clicks, [])
+        self.assertIn('"outcome": "timeout"', output.getvalue())
+        self.helper.bypass.assert_not_called()
+
+    def test_cloud_book_timeout_never_calls_mail_api(self):
+        self.plugin.free_config['otp_mode'] = 'cloud'
+        self.route = replace(self.route, mail=OtpMailConfig('mailbox@example.test'))
+        with patch.object(preparation.time, 'monotonic', side_effect=[0, 0, 5, 121]), \
+             patch.object(workflow, 'fetch_otp_from_cloud') as fetch, \
+             patch.object(ita_otp.vs_log_macros, '_active_logger', logging.Logger('offline-cf', logging.INFO)), \
+             redirect_stdout(StringIO()), self.assertRaises(preparation.CalendarGateError):
+            workflow.prepare_calendar(self.plugin, self.route, role='book')
+        fetch.assert_not_called()
+        self.listener.assert_not_called()
+        self.reader.assert_not_called()
+
+
+class ProductionEntryTests(TestCase):
+    def setUp(self):
+        self.plugin, self.route, self.trigger = flow.prepared_plugin(flow.FlowPage())
+        self.plugin.free_config["otp_mode"] = "manual"
+        self.inputs = {"username": self.plugin.config.account.username}
+        self.plugin.is_healthy = True
+        self.plugin._log = Mock()
+        self.addCleanup(setattr, self.plugin, "_cleanup_attempted", True)
+
+    def test_prepared_book_reuses_real_calendar_adapter_and_defaults_to_prefinal(self):
+        with patch.object(workflow, "submit_final") as submit, patch.object(workflow, "prepare_calendar") as prepare:
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertFalse(result.success)
+        self.assertIsNotNone(self.plugin.last_booking_precommit)
+        self.assertEqual(result.label, "calendar-ready-before-final")
+        self.assertEqual(self.plugin.page.guard_final_count, 0)
+        submit.assert_not_called()
+        prepare.assert_not_called()
+
+    def test_cloud_book_reuses_selection_without_enabling_final(self):
+        self.plugin.free_config["otp_mode"] = "cloud"
+        with patch.object(workflow, "submit_final") as submit:
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertEqual(result.label, "calendar-ready-before-final")
+        self.assertIsNotNone(self.plugin.last_booking_precommit)
+        self.assertFalse(result.success)
+        submit.assert_not_called()
+
+    def test_cloud_final_uses_the_existing_submitter_after_fresh_selection(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+        confirmed = VSBookResult(success=True, book_date="2026-10-13", book_time="09:26")
+        with patch.object(workflow, "submit_final", return_value=confirmed) as submit:
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertIs(result, confirmed)
+        self.assertIsNotNone(self.plugin.last_booking_precommit)
+        submit.assert_called_once_with(self.plugin, self.route)
+
+    def test_invalid_final_flag_is_rejected_before_site_actions(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled="true")
+        with patch.object(workflow, "submit_final") as submit, \
+             patch.object(workflow, "prepare_calendar") as prepare, self.assertRaises(PermissionDeniedError):
+            self.plugin.book(self.trigger, self.inputs)
+        submit.assert_not_called()
+        prepare.assert_not_called()
+
+    def test_cloud_final_no_inventory_never_submits(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+        self.plugin.page = flow.FlowPage([flow.month(m, {}) for m in ("2026-10", "2026-11", "2026-12")])
+        self.plugin._record_calendar_book_prepared_route(self.route)
+        with patch.object(workflow, "submit_final") as submit, flow.browser_navigation(self.plugin.page):
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertFalse(result.success)
+        submit.assert_not_called()
+
+    def test_enabled_book_returns_standard_result_after_real_slot_selection(self):
+        self.plugin.free_config["final_submit_enabled"] = True
+        confirmed = VSBookResult(success=True, book_date="2026-10-13", book_time="09:26")
+        with patch.object(workflow, "submit_final", return_value=confirmed) as submit:
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertIs(result, confirmed)
+        self.assertIsNotNone(self.plugin.last_booking_precommit)
+        submit.assert_called_once_with(self.plugin, self.route)
+
+    def test_one_public_book_call_prepares_and_selects_from_dashboard(self):
+        plugin = self.plugin
+        plugin.page.url = "https://prenotami.esteri.it/UserArea"
+        plugin._calendar_book_prepared_context = None
+        plugin._inspect_booking_form_structure = Mock()
+        def entry(apt):
+            plugin.page.url = "https://prenotami.esteri.it" + plugin._booking_path(self.route)
+            return VSQueryResult(success=True)
+        plugin.query.side_effect = entry
+        def prepare(p, route, *, role):
+            self.assertEqual(role, "book")
+            p.page.url = "https://prenotami.esteri.it/BookingCalendar"
+            p._record_calendar_book_prepared_route(route)
+        with patch.object(workflow, "prepare_calendar", side_effect=prepare) as prep:
+            result = plugin.book(self.trigger, self.inputs)
+        prep.assert_called_once()
+        plugin.query.assert_called_once()
+        self.assertEqual(result.label, "calendar-ready-before-final")
+        self.assertIsNotNone(plugin.last_booking_precommit)
+
+    def test_final_config_requires_explicit_supported_applicant_mode(self):
+        for values, accepted in (({}, True), ({"otp_mode": "manual"}, True),
+                ({"otp_mode": "cloud"}, True),
+                ({"otp_mode": "cloud", "final_submit_enabled": True}, True),
+                ({"otp_mode": "cloud", "query_mode": "calendar"}, True),
+                ({"otp_mode": "cloud", "query_mode": "calendar", "final_submit_enabled": True}, False),
+                ({"otp_mode": "cloud", "final_submit_enabled": "true"}, False),
+                ({"otp_mode": "cloud", "final_submit_enabled": 1}, False),
+                ({"otp_mode": "manual", "final_submit_enabled": True}, True),
+                ({"final_submit_enabled": True}, False),
+                ({"otp_mode": "manual", "final_submit_enabled": 1}, False),
+                ({"otp_mode": "manual", "final_submit_enabled": True, "query_mode": "calendar"}, False)):
+            with self.subTest(values=values):
+                config = VSPlgConfig(free_config=values)
+                if accepted:
+                    self.plugin.set_config(config)
+                else:
+                    with self.assertRaises(BizLogicError):
+                        self.plugin.set_config(config)
+
+    def test_no_inventory_never_calls_final(self):
+        self.plugin.page = flow.FlowPage([flow.month(m, {}) for m in ("2026-10", "2026-11", "2026-12")])
+        self.plugin._record_calendar_book_prepared_route(self.route)
+        with patch.object(workflow, "submit_final") as submit, flow.browser_navigation(self.plugin.page):
+            result = self.plugin.book(self.trigger, self.inputs)
+        self.assertFalse(result.success)
+        submit.assert_not_called()
+
+    def test_query_or_another_applicant_cannot_book(self):
+        for query_key, username in ((self.route.routing_key, self.inputs["username"]), (None, "other@example.test")):
+            self.plugin._calendar_query_route_key = query_key
+            with self.assertRaises(BizLogicError), patch.object(workflow, "submit_final") as submit:
+                self.plugin.book(self.trigger, {"username": username})
+            submit.assert_not_called()
+
+    def test_unknown_attempt_cannot_rescan_or_submit_again(self):
+        self.plugin._production_final_attempt = SimpleNamespace(state="unknown")
+        with self.assertRaises(FinalOutcomeUnknown), patch.object(workflow, "submit_final") as submit:
+            self.plugin.book(self.trigger, self.inputs)
+        submit.assert_not_called()
+        self.assertEqual(self.plugin.page.refreshes, 0)
+
+    def test_cloud_unknown_attempt_is_not_retried(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+        self.plugin._production_final_attempt = SimpleNamespace(state="unknown")
+        with patch.object(workflow, "submit_final") as submit, \
+             patch.object(workflow, "prepare_calendar") as prepare, self.assertRaises(FinalOutcomeUnknown):
+            self.plugin.book(self.trigger, self.inputs)
+        submit.assert_not_called()
+        prepare.assert_not_called()
+        self.assertEqual(self.plugin.page.refreshes, 0)
+
+    def test_cloud_final_rejects_query_session_and_other_applicant(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+        for query_key, username in ((self.route.routing_key, self.inputs["username"]), (None, "other@example.test")):
+            self.plugin._calendar_query_route_key = query_key
+            with patch.object(workflow, "submit_final") as submit, self.assertRaises(BizLogicError):
+                self.plugin.book(self.trigger, {"username": username})
+            submit.assert_not_called()
+
+    def test_cloud_confirmed_result_does_not_create_second_booking(self):
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+        self.test_confirmed_result_can_be_reported_again_without_another_booking()
+
+    def test_confirmed_result_can_be_reported_again_without_another_booking(self):
+        result = VSBookResult(success=True, book_date="2026-10-13", book_time="09:26")
+        self.plugin._production_final_attempt = SimpleNamespace(state="confirmed", target=SimpleNamespace(
+            applicant=self.inputs["username"], routing_key=self.route.routing_key))
+        self.plugin._production_book_result = result
+        self.assertIs(self.plugin.book(self.trigger, self.inputs), result)
+        self.assertEqual(self.plugin.page.refreshes, 0)
+
+    def test_query_from_dashboard_prepares_once_and_never_returns_weak_positive(self):
+        plugin = self.plugin
+        plugin.query = MethodType(ItaPlugin.query, plugin)
+        plugin.free_config["query_mode"] = "calendar"
+        plugin.page.url = "https://prenotami.esteri.it/UserArea"
+        plugin._calendar_book_prepared_context = None
+        strong = VSQueryResult(success=True, availability_status=AvailabilityStatus.Available,
+                               earliest_date=datetime(2026, 10, 13), apt_type=self.trigger.apt_type)
+        plugin._query_once = Mock(side_effect=lambda apt, **kwargs: (
+            VSQueryResult(success=True) if kwargs else strong))
+        def prepare(p, route, *, role):
+            self.assertEqual(role, "query")
+            p.page.url = "https://prenotami.esteri.it/BookingCalendar"
+        with patch.object(workflow, "prepare_calendar", side_effect=prepare) as prep:
+            self.assertIs(plugin.query(self.trigger.apt_type), strong)
+            self.assertIs(plugin.query(self.trigger.apt_type), strong)
+        self.assertEqual(prep.call_count, 1)
+        self.assertEqual(plugin._query_once.call_count, 3)
+
+    def test_entry_no_availability_does_not_send_otp(self):
+        self.plugin.page.url = "https://prenotami.esteri.it/UserArea"
+        negative = VSQueryResult(success=False)
+        self.plugin._query_once = Mock(return_value=negative)
+        with patch.object(workflow, "prepare_calendar") as prep:
+            self.assertIs(workflow.prepare_query_if_needed(self.plugin, self.trigger.apt_type), negative)
+        prep.assert_not_called()
+
+    def test_production_modules_never_import_debug_tools(self):
+        root = Path(__file__).resolve().parents[1]
+        for filename in ("ita_workflow.py", "ita_calendar_session.py"):
+            tree = ast.parse((root / "plugins" / filename).read_text())
+            imports = [n.module for n in ast.walk(tree) if isinstance(n, ast.ImportFrom)]
+            self.assertFalse(any(name and name.startswith("tools") for name in imports))
+
+
+class FinalCompositionTests(TestCase):
+    def setUp(self):
+        attribution.AttributionTests.setUp(self)
+        self.plugin._log = Mock()
+        self.audit = Mock()
+        self.before = {k: 0 for k in ("otpRequests", "avantiPosts", "availabilityRequests", "finalRequests", "timeSlotRequests")}
+        self.after = {**self.before, "finalRequests": 1}
+        self.audit.settled_snapshot.side_effect = [self.before, self.after]
+
+    def add_confirmed(self):
+        attribution.AttributionTests.add_confirmed(self)
+
+    def run_final(self):
+        def native_factory(page, target, current):
+            native = Mock(side_effect=lambda: (self.add_confirmed(), SubmissionSignal.UNKNOWN)[1])
+            native.submitted_selection = VerifiedSubmission(target)
+            return native
+        with patch.object(workflow.preparation, "CalendarRequestAudit", return_value=self.audit), \
+                patch.object(workflow, "NativeFinalSubmitter", side_effect=native_factory) as factory:
+            result = workflow.submit_final(self.plugin, self.route)
+        self.assertEqual(factory.call_count, 1)
+        return result
+
+    def test_real_read_port_and_core_return_success_with_assigned_time(self):
+        result = self.run_final()
+        self.assertTrue(result.success)
+        self.assertEqual(result.book_time, "09:26")
+        self.assertEqual(self.plugin._production_final_attempt.state, "confirmed")
+        self.assertIs(self.plugin._production_book_result, result)
+        self.audit.stop.assert_called_once()
+
+    def test_missing_request_audit_leaves_unknown_attempt_not_false_result(self):
+        self.after["finalRequests"] = 0
+        with self.assertRaises(FinalOutcomeUnknown):
+            self.run_final()
+        self.assertEqual(self.plugin._production_final_attempt.state, "unknown")
+        self.audit.stop.assert_called_once()
+
+    def test_audit_cleanup_failure_does_not_erase_confirmed_result(self):
+        self.audit.stop.side_effect = RuntimeError("fixture")
+        self.assertTrue(self.run_final().success)
+        self.plugin._log.assert_called_once()
+
+
+class CloudFinalCompositionTests(FinalCompositionTests):
+    """Cloud mode shares the real read-port, receipt attribution and no-retry core."""
+    def setUp(self):
+        super().setUp()
+        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
+
+
+class RealFinalAuditTests(TestCase):
+    """Real audit ownership + production final core, synthetic CDP/receipts."""
+
+    def setUp(self):
+        from test.test_debug_ita_production_query_gate import FakeAuditPage
+        attribution.AttributionTests.setUp(self)
+        self.plugin._log = Mock()
+        transport = FakeAuditPage()
+        self.main.driver = transport.driver
+        self.main.run_cdp = transport.run_cdp
+        self.transport = transport
+        self.audit = preparation.CalendarRequestAudit(self.main, include_time_slots=True)
+        self.audit.start = Mock(wraps=self.audit.start)
+        self.audit.stop = Mock(wraps=self.audit.stop)
+        self.addCleanup(self.audit.stop)
+        clock = itertools.count(0, 0.1)
+        self.enterContext(patch.object(preparation, "time", SimpleNamespace(
+            monotonic=lambda: next(clock), sleep=lambda _seconds: None)))
+        self.on_submit = lambda: transport.emit("/BookingCalendar/InsertNewBooking")
+        self.native = Mock(side_effect=self.dispatch)
+
+        def native_factory(page, target, current):
+            self.assertIs(page, self.main)
+            self.native.submitted_selection = VerifiedSubmission(target)
+            return self.native
+
+        self.factory = self.enterContext(patch.object(workflow, "NativeFinalSubmitter", side_effect=native_factory))
+
+    def dispatch(self):
+        self.on_submit()
+        attribution.AttributionTests.add_confirmed(self)
+        return SubmissionSignal.UNKNOWN
+
+    def borrow(self):
+        return workflow.submit_final(self.plugin, self.route, request_audit=self.audit)
+
+    def test_shared_audit_counts_one_submit_and_remains_owned_by_caller(self):
+        self.audit.start()
+        callback = self.main.driver.immediate_event_handlers[self.audit.EVENT]
+        self.assertTrue(self.borrow().success)
+        self.native.assert_called_once()
+        self.audit.start.assert_called_once()
+        self.audit.stop.assert_not_called()
+        self.audit.require_active_on(self.main)
+        self.assertIs(self.main.driver.immediate_event_handlers[self.audit.EVENT], callback)
+        self.assertEqual(self.audit.snapshot()["finalRequests"], 1)
+        self.assertEqual(self.transport.commands.count("Network.enable"), 1)
+
+    def test_standalone_production_still_owns_start_and_stop(self):
+        with patch.object(preparation, "CalendarRequestAudit", return_value=self.audit) as factory:
+            self.assertTrue(workflow.submit_final(self.plugin, self.route).success)
+        factory.assert_called_once_with(self.main, include_time_slots=True)
+        self.audit.start.assert_called_once()
+        self.audit.stop.assert_called_once()
+        self.assertEqual(self.main.driver.immediate_event_handlers, {})
+
+    def test_nested_registration_without_explicit_borrow_still_refused(self):
+        self.audit.start()
+        with self.assertRaisesRegex(preparation.CalendarGateError, "existing callback"):
+            workflow.submit_final(self.plugin, self.route)
+        self.factory.assert_not_called()
+        self.audit.require_active_on(self.main)
+        self.browser.new_tab.assert_not_called()
+
+    def test_existing_reservation_blocks_without_stopping_borrowed_audit(self):
+        from plugins.ita_booking_final import FinalBookingError
+        self.audit.start()
+        attribution.AttributionTests.add_confirmed(self)
+        with self.assertRaises(FinalBookingError):
+            self.borrow()
+        self.factory.assert_not_called()
+        self.audit.stop.assert_not_called()
+        self.audit.require_active_on(self.main)
+        self.assertEqual(self.audit.snapshot()["finalRequests"], 0)
+
+    def test_wrong_page_driver_stopped_or_disconnected_audit_never_submits(self):
+        self.audit.start()
+        for target, attribute, replacement in (
+                (self.audit, "page", self.transport),
+                (self.main, "driver", object()),
+                (self.audit, "_started", False),
+                (self.audit.driver, "is_running", False)):
+            with self.subTest(attribute=attribute), patch.object(target, attribute, replacement):
+                with self.assertRaises(preparation.CalendarGateError):
+                    self.borrow()
+        self.factory.assert_not_called()
+        self.browser.new_tab.assert_not_called()
+        self.audit.stop.assert_not_called()
+
+    def test_replaced_callback_is_not_overwritten_or_accepted_as_proof(self):
+        self.audit.start()
+        for handlers in (self.audit.driver.event_handlers, self.audit.driver.immediate_event_handlers):
+            foreign = Mock()
+            with patch.dict(handlers, {self.audit.EVENT: foreign}):
+                with self.assertRaisesRegex(preparation.CalendarGateError, "callback changed"):
+                    self.borrow()
+                self.assertIs(handlers[self.audit.EVENT], foreign)
+        self.factory.assert_not_called()
+        self.audit.stop.assert_not_called()
+
+    def test_borrowed_audit_must_cover_time_slots(self):
+        self.audit.start()
+        with patch.dict(self.audit._counts, {"finalRequests": 0}, clear=True):
+            with self.assertRaisesRegex(preparation.CalendarGateError, "include time slots"):
+                self.borrow()
+        self.factory.assert_not_called()
+        self.browser.new_tab.assert_not_called()
+
+    def test_callback_lost_during_submission_cannot_confirm_from_stale_counters(self):
+        self.audit.start()
+        foreign = Mock()
+        handlers = self.audit.driver.immediate_event_handlers
+
+        def lose_callback():
+            self.transport.emit("/BookingCalendar/InsertNewBooking")
+            handlers[self.audit.EVENT] = foreign
+
+        self.on_submit = lose_callback
+        with patch.dict(handlers):
+            with self.assertRaises(FinalOutcomeUnknown):
+                self.borrow()
+            self.assertIs(handlers[self.audit.EVENT], foreign)
+            self.assertEqual(self.plugin._production_final_attempt.state, "unknown")
+            self.audit.stop.assert_not_called()
+        self.native.assert_called_once()
+        self.audit.require_active_on(self.main)
+
+    def test_missing_duplicate_or_mixed_requests_do_not_become_success(self):
+        for requests in ([], ["/BookingCalendar/InsertNewBooking"] * 2,
+                         ["/BookingCalendar/InsertNewBooking", "/BookingCalendar/RetrieveTimeSlots"]):
+            with self.subTest(requests=requests):
+                before_listing = self.browser.raw
+                self.audit.start()
+                self.on_submit = lambda: [self.transport.emit(path) for path in requests]
+                try:
+                    with self.assertRaises(FinalOutcomeUnknown):
+                        self.borrow()
+                    self.assertEqual(self.plugin._production_final_attempt.state, "unknown")
+                    self.audit.require_active_on(self.main)
+                finally:
+                    self.audit.stop()
+                    self.browser.raw = before_listing
+        self.assertEqual(self.native.call_count, 3)
+
+
+class BookerReuseTests(TestCase):
+    def setUp(self):
+        # Reuse existing offline Redis import fixture; never open Redis/cloud.
+        from test.test_ita_plugin import OrderBookerGCO
+        from threading import RLock
+        self.booker = OrderBookerGCO.__new__(OrderBookerGCO)
+        self.booker.m_lock = RLock()
+        self.booker.m_task_data_cache = {"fixture": {"status": "running", "order_id": "order", "user_inputs": {}}}
+        self.booker._log = Mock()
+        self.booker._remove_task = Mock()
+        self.booker._push_success_notification = Mock()
+        self.booker.redis_client = Mock()
+        self.booker.m_tracker_key = "fixture"
+        self.task = SimpleNamespace(task_ref="fixture", book_allowed=True, instance=Mock())
+        self.api = Mock()
+        api_patch = patch.dict(self.booker._execute_book_job.__func__.__globals__, VSCloudApi=self.api)
+        api_patch.start()
+        self.addCleanup(api_patch.stop)
+
+    def test_standard_success_still_uses_existing_reporting(self):
+        result = VSBookResult(success=True, book_date="2026-10-13", book_time="09:26")
+        self.task.instance.book.return_value = result
+        self.booker._execute_book_job(self.task, VSQueryResult())
+        self.booker._push_success_notification.assert_called_once_with("fixture", "order", result)
+
+    def test_unknown_pauses_using_existing_api_and_next_signal_does_nothing(self):
+        self.task.instance.book.side_effect = FinalOutcomeUnknown()
+        self.booker._execute_book_job(self.task, VSQueryResult())
+        self.booker._execute_book_job(self.task, VSQueryResult())
+        self.api.Instance.return_value.update_vas_task.assert_called_once_with("fixture", {"status": "pause"})
+        self.assertFalse(self.task.book_allowed)
+        self.task.instance.book.assert_called_once()
+        self.booker._push_success_notification.assert_not_called()
+
+    def test_pause_failure_keeps_task_blocked_locally(self):
+        self.task.instance.book.side_effect = FinalOutcomeUnknown()
+        self.api.Instance.return_value.update_vas_task.side_effect = RuntimeError("fixture")
+        self.booker._execute_book_job(self.task, VSQueryResult())
+        self.booker._execute_book_job(self.task, VSQueryResult())
+        self.assertFalse(self.task.book_allowed)
+        self.task.instance.book.assert_called_once()
+        self.booker._remove_task.assert_not_called()
+
+
+class QueryCliTests(TestCase):
+    def test_workflow_flag_reuses_route_builder_and_calls_standard_query(self):
+        from tools import debug_ita_query as cli
+        from test.test_debug_ita_calendar_gate import gate_env
+        plugin = Mock()
+        plugin.query.return_value = VSQueryResult(success=True, availability_status=AvailabilityStatus.Available,
+                                                   earliest_date=datetime(2026, 10, 13))
+        stdout = StringIO()
+        with patch.object(cli, "ItaPlugin", return_value=plugin), \
+                patch.object(cli, "resolve_chrome_path", return_value=Path("/offline/chrome")), \
+                patch.object(cli, "_get_query_credentials", return_value=("query@example.test", "fixture")), \
+                patch.object(cli, "_prepare_query_profile", return_value=Path("/offline/profile")), \
+                redirect_stdout(stdout):
+            code = cli.run_query_once(gate_env(), non_interactive=False, production_workflow=True)
+        self.assertEqual(code, 0)
+        config = plugin.set_config.call_args.args[0]
+        self.assertEqual(config.free_config["query_mode"], "calendar")
+        self.assertEqual(config.free_config["otp_mode"], "manual")
+        self.assertIs(config.free_config["final_submit_enabled"], False)
+        plugin.query.assert_called_once()
+        plugin.book.assert_not_called()
+        plugin.cleanup.assert_called_once()
+        self.assertIn("ITA_QUERY_WORKFLOW_RESULT=", stdout.getvalue())
+
+    def test_headless_workflow_rejected_before_credentials(self):
+        from tools import debug_ita_query as cli
+        with patch.object(cli, "_get_query_credentials") as credentials:
+            with self.assertRaises(cli.DebugConfigurationError):
+                cli.run_query_once({}, non_interactive=True, production_workflow=True)
+        credentials.assert_not_called()

+ 255 - 0
test/test_plugin_tester_ita_config.py

@@ -0,0 +1,255 @@
+"""Offline checks for the Italy profile consumed by the existing public tester."""
+
+import copy
+from contextlib import redirect_stdout
+import io
+import json
+import logging
+from pathlib import Path
+import shlex
+from types import SimpleNamespace
+import unittest
+from unittest.mock import Mock, patch
+
+from plugins.ita_protocol import ItaCapability, resolve_route_config
+from sentinel import SentinelGCO
+from tools.plugin_tester import PluginTester
+from vs_types import GroupConfig
+
+
+def hong_kong_group():
+    groups = json.loads((Path(__file__).resolve().parents[1] / "config/config_sentinel.json").read_text())
+    matches = [group for group in groups if group["identifier"] == "ita.hong_kong"]
+    if len(matches) != 1:
+        raise AssertionError("Expected exactly one Hong Kong Sentinel profile")
+    return GroupConfig.from_json(matches[0])
+
+
+class ItalyPublicTesterConfigTests(unittest.TestCase):
+    def setUp(self):
+        # Exercise the actual JSON loader and registration, never create a plugin,
+        # open a browser, or use the configured credentials in an assertion.
+        with patch("vs_plg_factory.VSC_INFO"), patch(
+            "tools.plugin_tester.VSPlgFactory.create",
+            side_effect=AssertionError("Offline configuration check must not create a plugin"),
+        ):
+            self.tester = PluginTester.from_json_config(
+                "ita_plugin",
+                str(Path(__file__).resolve().parents[1] / "config/test_conf.json"),
+                user_override="query@example.test",
+                password_override="synthetic-not-a-secret",
+                proxy_override="http://127.0.0.1:9999",
+            )
+
+    def test_existing_loader_resolves_one_hong_kong_appointment(self):
+        self.assertIsNone(self.tester.plugin)
+        self.assertEqual(self.tester.group_id, "ita.hong_kong")
+        self.assertEqual(len(self.tester.appointment_types), 1)
+        appointment = self.tester.appointment_types[0]
+        self.assertEqual(appointment.routing_key, "slot.hkg.it.tourist")
+        self.assertEqual(appointment.city, "Hong Kong")
+        self.assertEqual(appointment.country, "Italy")
+        self.assertEqual(appointment.visa_type, "Tourist")
+
+    def test_query_profile_uses_cloud_preparation_and_disables_final_submission(self):
+        config = self.tester.config
+        self.assertIs(config.debug, False)
+        self.assertEqual(config.free_config["query_mode"], "calendar")
+        self.assertEqual(config.free_config["otp_mode"], "cloud")
+        self.assertIs(config.free_config["final_submit_enabled"], False)
+
+    def test_existing_protocol_parser_accepts_evidenced_form_and_scan_settings(self):
+        route = resolve_route_config(
+            self.tester.config.free_config["apt_configs"],
+            self.tester.appointment_types[0].routing_key,
+        )
+        self.assertEqual(route.service_id, 4937)
+        self.assertIs(route.capability, ItaCapability.SINGLE_SCHENGEN_TOURISM)
+        self.assertEqual(route.calendar_scan.lookahead_months, 12)
+        self.assertEqual(route.booking_type.control_id, "typeofbookingddl")
+        self.assertEqual(route.booking_type.value, "1")
+        self.assertEqual(route.booking_type.labels, ("Prenotazione Singola", "Single booking"))
+        self.assertEqual(route.purpose.control_id, "ddls_0")
+        self.assertEqual(route.purpose.value, "42")
+        self.assertEqual(route.purpose.labels, ("Turismo", "Tourism"))
+        self.assertIsNotNone(route.mail)
+        self.assertEqual(route.mail.authorization_source, "account")
+        self.assertIsNone(route.mail.authorization_email)
+        self.assertEqual(route.mail.mailbox_for("query@example.test"), "query@example.test")
+
+    def test_public_tester_and_sentinel_share_route_and_otp_contract(self):
+        group = hong_kong_group()
+        config = self.tester.config.free_config
+        self.assertEqual(group.appointment_types, self.tester.appointment_types)
+        for key in ("website", "query_mode", "otp_mode", "final_submit_enabled", "apt_configs"):
+            self.assertEqual(group.free_config[key], config[key])
+
+
+class ItalySingleAccountPoolConfigTests(unittest.TestCase):
+    def setUp(self):
+        self.group = hong_kong_group()
+        # Do not create browsers, read account secrets or call a live backend.
+        for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
+                       "requests.sessions.Session.request", "subprocess.Popen"):
+            self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
+        self.cloud = Mock()
+        self.cloud.get_next_account.return_value = {
+            "id": 71, "pool_name": "hkg.it.sentinel", "username": "pooled@example.test",
+            "password": "synthetic-pool-password", "status": "active",
+        }
+        self.cloud.get_next_proxy.return_value = {"id": 72, "ip": "127.0.0.1", "port": 9999}
+        self.redis = Mock()
+        self.enterContext(patch.dict(SentinelGCO.__init__.__globals__, {
+            "SafeRedisClient": Mock(return_value=self.redis),
+            "VSCloudApi": SimpleNamespace(Instance=lambda: self.cloud),
+        }))
+        self.sentinel = SentinelGCO(self.group, {}, Mock())
+        self.plugin = Mock()
+        self.sentinel.m_factory.create = Mock(return_value=self.plugin)
+        self.addCleanup(self.sentinel.stop)
+
+    def test_profile_is_disabled_single_instance_cloud_query_without_local_credentials(self):
+        group = self.group
+        self.assertFalse(group.enable)
+        self.assertFalse(group.debug)
+        self.assertTrue(group.need_account)
+        self.assertEqual(group.sentinel.account_source, "built-in")
+        self.assertEqual(group.sentinel.account_pool_id, "hkg.it.sentinel")
+        self.assertEqual(group.sentinel.target_instances, 1)
+        self.assertEqual(group.sentinel.account_cd, group.session_max_life)
+        self.assertEqual(group.sentinel.account_cd, 1800)
+        self.assertEqual(group.free_config["otp_mode"], "cloud")
+        self.assertIs(group.free_config["final_submit_enabled"], False)
+        for key in ("account", "password", "local_account_file", "authorization_code"):
+            self.assertNotIn(key, group.free_config)
+        self.sentinel.start()
+        self.sentinel.m_factory.create.assert_not_called()
+        self.cloud.get_next_account.assert_not_called()
+
+    def test_existing_sentinel_spawner_binds_pool_account_and_mail_configuration(self):
+        before = copy.deepcopy(self.group)
+        self.sentinel._spawn_sentinel_worker()
+        self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
+        self.cloud.get_next_proxy.assert_called_once_with(self.group.proxy_pool, self.group.proxy_cd)
+        self.plugin.set_config.assert_called_once()
+        config = self.plugin.set_config.call_args.args[0]
+        self.assertEqual(config.account.id, 71)
+        self.assertEqual(config.account.username, "pooled@example.test")
+        self.assertEqual(config.account.password, "synthetic-pool-password")
+        self.assertEqual(config.free_config, self.group.free_config)
+        self.assertEqual(self.group, before)
+        self.plugin.create_session.assert_called_once()
+        self.assertEqual(len(self.sentinel.m_tasks), 1)
+        self.assertFalse(self.sentinel.m_tasks[0].book_allowed)
+        self.plugin.book.assert_not_called()
+        self.redis.setex.assert_not_called()
+
+    def test_empty_or_cooling_pool_does_not_fall_back_to_a_local_account(self):
+        self.cloud.get_next_account.side_effect = RuntimeError("synthetic unavailable pool")
+        self.sentinel._spawn_sentinel_worker()
+        self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
+        self.sentinel.m_factory.create.assert_not_called()
+        self.plugin.create_session.assert_not_called()
+        self.assertEqual(self.sentinel.m_tasks, [])
+
+
+class ItalyDocumentedPoolCommandTests(unittest.TestCase):
+    def setUp(self):
+        for target in ("socket.socket.connect", "socket.socket.connect_ex", "socket.create_connection",
+                       "requests.sessions.Session.request", "subprocess.Popen"):
+            self.enterContext(patch(target, side_effect=AssertionError("Offline test attempted external I/O")))
+        logger = logging.Logger("ita-pool-command-offline", level=logging.INFO)
+        self.enterContext(patch("vs_log_macros._active_logger", logger))
+        self.enterContext(patch("configure.TEST_ACCOUNT", None))
+        self.cloud = Mock()
+        self.cloud.get_next_account.return_value = {
+            "id": 71, "username": "first-pool-account@example.test",
+            "password": "synthetic-command-password", "pool_name": "hkg.it.sentinel", "status": "active",
+        }
+        self.enterContext(patch("toolkit.vs_cloud_api.VSCloudApi.Instance", return_value=self.cloud))
+        self.pipeline = self.enterContext(patch.object(PluginTester, "run_pipeline", autospec=True, return_value=True))
+        self.enterContext(patch("utils.local_account.load_local_account",
+                                side_effect=AssertionError("Pool test must not load a local account")))
+
+    def run_documented_command(self):
+        path = Path(__file__).resolve().parents[1] / "docs/ita_query_book_acceptance.md"
+        section = path.read_text().split("<!-- ITA_POOL_QUERY_COMMAND -->", 1)[1].split("<!-- /ITA_POOL_QUERY_COMMAND -->", 1)[0]
+        shell = section.split("```bash", 1)[1].split("```", 1)[0]
+        tokens = shlex.split(shell)
+        code = tokens[tokens.index("-c") + 1]
+        output = io.StringIO()
+        with redirect_stdout(output), self.assertRaises(SystemExit) as result:
+            exec(compile(code, str(path) + ":pool-query-command", "exec"), {"__name__": "__main__"})
+        return result.exception.code, output.getvalue()
+
+    def test_exact_documented_command_uses_existing_sdk_and_public_tester_query_only(self):
+        code, output = self.run_documented_command()
+        self.assertEqual(code, 0)
+        self.cloud.get_next_account.assert_called_once_with("hkg.it.sentinel", 1800)
+        self.pipeline.assert_called_once()
+        self.assertEqual(self.pipeline.call_args.kwargs, {"test_book": False})
+        tester = self.pipeline.call_args.args[0]
+        self.assertEqual(tester.config.account.id, 71)
+        self.assertEqual(tester.config.account.password, "synthetic-command-password")
+        self.assertEqual(tester.config.free_config, hong_kong_group().free_config)
+        self.assertEqual(tester.config.proxy.port, 6268)
+        self.assertIsNone(tester.plugin)
+        self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool pool=hkg.it.sentinel book=false", output)
+        self.assertNotIn("synthetic-command-password", output)
+        self.assertIn("ITA_POOL_QUERY_CONTRACT=account-mailbox-v2", output)
+
+    def test_second_pool_account_is_accepted_and_resolves_its_own_mailbox(self):
+        for address in ("first-pool-account@example.test", "second-pool-account@example.test"):
+            with self.subTest(address=address):
+                self.pipeline.reset_mock()
+                self.cloud.get_next_account.return_value["username"] = address
+                code, _ = self.run_documented_command()
+                self.assertEqual(code, 0)
+                tester = self.pipeline.call_args.args[0]
+                route = resolve_route_config(tester.config.free_config["apt_configs"],
+                                             tester.appointment_types[0].routing_key)
+                self.assertEqual(route.mail.mailbox_for(tester.config.account.username), address)
+                self.assertIsNone(route.mail.authorization_email)
+
+    def test_debug_payload_logging_stops_before_account_allocation(self):
+        with patch("vs_log_macros._active_logger", logging.Logger("unsafe-fixture", level=logging.DEBUG)):
+            with self.assertRaisesRegex(Exception, "DEBUG"):
+                self.run_documented_command()
+        self.cloud.get_next_account.assert_not_called()
+        self.pipeline.assert_not_called()
+
+    def test_test_account_override_stops_before_pool_allocation(self):
+        with patch("configure.TEST_ACCOUNT", {"username": "fixture@example.test"}):
+            code, _ = self.run_documented_command()
+        self.assertIn("TEST_ACCOUNT", code)
+        self.cloud.get_next_account.assert_not_called()
+        self.pipeline.assert_not_called()
+
+    def test_pool_failure_does_not_fall_back_or_print_backend_error_body(self):
+        self.cloud.get_next_account.side_effect = RuntimeError("synthetic-sensitive-response")
+        code, output = self.run_documented_command()
+        self.assertEqual(code, 1)
+        self.assertIn("ITA_POOL_QUERY_ACCOUNT_FAILED type=RuntimeError", output)
+        self.assertNotIn("synthetic-sensitive-response", output)
+        self.pipeline.assert_not_called()
+
+    def test_wrong_pool_empty_password_or_disabled_account_stops_before_browser(self):
+        original = self.cloud.get_next_account.return_value.copy()
+        for field, value in (("pool_name", "other.pool"), ("password", ""), ("status", "disable")):
+            with self.subTest(field=field):
+                self.cloud.get_next_account.return_value = {**original, field: value}
+                code, _ = self.run_documented_command()
+                self.assertIsInstance(code, str)
+                self.assertIn("Stop:", code)
+                self.pipeline.assert_not_called()
+
+    def test_invalid_account_email_stops_before_browser(self):
+        self.cloud.get_next_account.return_value["username"] = "not-an-email"
+        code, output = self.run_documented_command()
+        self.assertEqual(code, 1)
+        self.assertIn("ITA_POOL_QUERY_MAIL_CONFIG_FAILED", output)
+        self.pipeline.assert_not_called()
+
+
+if __name__ == "__main__":
+    unittest.main()

+ 280 - 0
tools/add_ita_query_account.py

@@ -0,0 +1,280 @@
+#!/usr/bin/env python3
+"""Safely add one authorized Prenot@Mi account to the Italy Query pool.
+
+The tool is locked to ``ie.it.sentinel`` and defaults to a no-network
+preflight. A real upload requires ``--apply``. Username, password, and API
+token are never accepted as command-line arguments or printed.
+"""
+
+from __future__ import annotations
+
+import argparse
+import getpass
+import os
+import re
+import sys
+from pathlib import Path
+from typing import Any, Mapping
+
+import requests
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from utils.local_account import (
+    LocalAccountConfigurationError,
+    read_local_account_config,
+)
+
+
+ACCOUNT_POOL = "ie.it.sentinel"
+ACCOUNT_UPLOAD_URL = "https://api.text.skin/api/account/add"
+SERVICE_ID = 1321
+DEFAULT_CONFIG_PATH = (
+    Path(__file__).resolve().parents[1]
+    / "config"
+    / "ita_query_account.local.json"
+)
+_SAFE_ACCOUNT_ID = re.compile(r"^[A-Za-z0-9_-]{1,64}$")
+_LOCAL_CONFIG_KEYS = {
+    "username": "ITA_QUERY_USERNAME",
+    "password": "ITA_QUERY_PASSWORD",
+    "account_upload_token": "VS_ACCOUNT_UPLOAD_TOKEN",
+}
+
+
+class AccountUploadConfigurationError(ValueError):
+    """Raised before any request when required local input is invalid."""
+
+
+def _local_config(path: Path) -> dict[str, str]:
+    """Read the optional ignored JSON file without exposing secret values."""
+    if not path.exists():
+        return {}
+    try:
+        body = read_local_account_config(path, allowed_root=None)
+    except LocalAccountConfigurationError as exc:
+        raise AccountUploadConfigurationError(
+            str(exc).replace("local account file", "local config")
+        ) from exc
+    return {
+        env_name: body.get(config_key, "")
+        for config_key, env_name in _LOCAL_CONFIG_KEYS.items()
+    }
+
+
+def _credential_source(
+    env: Mapping[str, str],
+    *,
+    config_path: Path | None,
+) -> dict[str, str]:
+    """Merge local config with explicit environment variables taking priority."""
+    source = _local_config(config_path) if config_path is not None else {}
+    for env_name in _LOCAL_CONFIG_KEYS.values():
+        if env.get(env_name, "").strip():
+            source[env_name] = env[env_name]
+    return source
+
+
+def _hidden_value(
+    env: Mapping[str, str],
+    name: str,
+    prompt: str,
+    *,
+    non_interactive: bool,
+) -> str:
+    value = env.get(name, "").strip()
+    if not value and not non_interactive:
+        value = getpass.getpass(prompt).strip()
+    if not value:
+        raise AccountUploadConfigurationError(f"{name} is required")
+    return value
+
+
+def _credentials(
+    env: Mapping[str, str],
+    *,
+    non_interactive: bool,
+) -> tuple[str, str, str]:
+    username = _hidden_value(
+        env,
+        "ITA_QUERY_USERNAME",
+        "Italy Query username (hidden): ",
+        non_interactive=non_interactive,
+    )
+    password = _hidden_value(
+        env,
+        "ITA_QUERY_PASSWORD",
+        "Italy Query password: ",
+        non_interactive=non_interactive,
+    )
+    api_token = _hidden_value(
+        env,
+        "VS_ACCOUNT_UPLOAD_TOKEN",
+        "Account API token: ",
+        non_interactive=non_interactive,
+    )
+    if any(character.isspace() for character in username) or "@" not in username:
+        raise AccountUploadConfigurationError(
+            "ITA_QUERY_USERNAME must be the account's email address"
+        )
+    return username, password, api_token
+
+
+def _payload(username: str, password: str) -> dict[str, Any]:
+    return {
+        "pool_name": ACCOUNT_POOL,
+        "username": username,
+        "password": password,
+        "extra_data": {
+            "site": "prenotami.esteri.it",
+            "country_code": "irl",
+            "mission_code": "ita",
+            "city": "Dublin",
+            "service_id": SERVICE_ID,
+            "role": "sentinel-query",
+        },
+    }
+
+
+def _authorization_value(api_token: str) -> str:
+    return api_token if api_token.startswith("Bearer ") else f"Bearer {api_token}"
+
+
+def _response_account_id(body: object) -> str:
+    if not isinstance(body, dict):
+        return "not-returned"
+    data = body.get("data")
+    if not isinstance(data, dict):
+        return "not-returned"
+    candidate = str(data.get("id") or data.get("account_id") or "")
+    return candidate if _SAFE_ACCOUNT_ID.fullmatch(candidate) else "not-returned"
+
+
+def run_account_upload(
+    env: Mapping[str, str],
+    *,
+    apply: bool,
+    non_interactive: bool,
+    config_path: Path | None = None,
+    session: Any | None = None,
+) -> int:
+    if not apply:
+        print(
+            "ITA_ACCOUNT_UPLOAD_PREFLIGHT_OK "
+            f"pool={ACCOUNT_POOL} service_id={SERVICE_ID} request_sent=false"
+        )
+        return 0
+
+    try:
+        source = _credential_source(env, config_path=config_path)
+        username, password, api_token = _credentials(
+            source,
+            non_interactive=non_interactive,
+        )
+    except AccountUploadConfigurationError as exc:
+        print(f"ITA_ACCOUNT_UPLOAD_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+    http = session or requests.Session()
+    if hasattr(http, "trust_env"):
+        http.trust_env = False
+    headers = {
+        "Accept": "application/json",
+        "Authorization": _authorization_value(api_token),
+        "Content-Type": "application/json",
+    }
+
+    try:
+        response = http.post(
+            ACCOUNT_UPLOAD_URL,
+            json=_payload(username, password),
+            headers=headers,
+            timeout=10,
+        )
+    except requests.RequestException as exc:
+        print(
+            "ITA_ACCOUNT_UPLOAD_UNCERTAIN "
+            f"pool={ACCOUNT_POOL} type={type(exc).__name__} "
+            "action=verify-admin-before-retry",
+            file=sys.stderr,
+        )
+        return 5
+
+    if response.status_code != 200:
+        print(
+            "ITA_ACCOUNT_UPLOAD_REJECTED "
+            f"pool={ACCOUNT_POOL} status={response.status_code} request_count=1",
+            file=sys.stderr,
+        )
+        return 4
+
+    try:
+        body = response.json()
+    except (TypeError, ValueError):
+        print(
+            "ITA_ACCOUNT_UPLOAD_UNCERTAIN "
+            f"pool={ACCOUNT_POOL} type=InvalidJson "
+            "action=verify-admin-before-retry",
+            file=sys.stderr,
+        )
+        return 5
+
+    if isinstance(body, dict) and body.get("code") not in (None, 0):
+        print(
+            "ITA_ACCOUNT_UPLOAD_REJECTED "
+            f"pool={ACCOUNT_POOL} status=business-error request_count=1",
+            file=sys.stderr,
+        )
+        return 4
+
+    print(
+        "ITA_ACCOUNT_UPLOAD_OK "
+        f"pool={ACCOUNT_POOL} account_id={_response_account_id(body)} "
+        "request_count=1"
+    )
+    return 0
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "Add one authorized account to ie.it.sentinel. Without --apply, "
+            "only a local preflight is performed."
+        )
+    )
+    parser.add_argument(
+        "--apply",
+        action="store_true",
+        help="Perform exactly one account upload request.",
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when local config values are missing.",
+    )
+    parser.add_argument(
+        "--config",
+        default=str(DEFAULT_CONFIG_PATH),
+        help=(
+            "Ignored local JSON config path. Environment variables override "
+            "values from this file."
+        ),
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    return run_account_upload(
+        os.environ,
+        apply=args.apply,
+        non_interactive=args.non_interactive,
+        config_path=Path(args.config).expanduser(),
+    )
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 471 - 0
tools/debug_ita_book.py

@@ -0,0 +1,471 @@
+#!/usr/bin/env python3
+"""Run one Italy Book recheck; by default stop before AVANTI.
+
+This discovery tool logs in with the eventual user's account, calls
+``ItaPlugin.book()`` exactly once with a weak Query trigger, and cleans up. The
+current Book implementation rechecks the explicitly configured route and reads
+allowlisted form structure. It never fills or submits the form, opens the
+Calendar, sends OTP, or confirms an appointment in default discovery mode.
+Explicit --production-workflow exercises applicant login/OTP/selection
+through the public Book entry. Final submission remains disabled in both modes.
+Optional --verify-receipts reuses the existing receipt-baseline gate after
+selection; it never enables final submission or consumes a final-attempt fence.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import sys
+import time
+from pathlib import Path
+from typing import Callable, Mapping
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_plugin import (
+    BOOKING_CALENDAR_PREFINAL_STOP_LABEL,
+    BOOKING_FORM_DISCOVERY_STOP_LABEL,
+    BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+    ItaPlugin,
+)
+from tools.debug_ita_query import (
+    ItaDebugRoute,
+    _print_booking_form_structure,
+    _print_failure_context,
+    build_query_config,
+    resolve_debug_route,
+)
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    _get_credentials,
+    _text_for_log,
+    resolve_chrome_path,
+)
+from tools.ita_local_handoff import (
+    ItaLocalSignalStaleError,
+    claim_local_weak_signal,
+)
+from utils.ita_local_profile import ITA_QUERY_ACCOUNT_FILE
+from utils.local_account import (
+    LocalAccountConfigurationError,
+    load_local_account,
+)
+from vs_types import AvailabilityStatus, BizLogicError, VSQueryResult
+
+
+class _BookArmCancelled(Exception):
+    """Internal control flow for a clean Ctrl+C while waiting in armed mode."""
+
+
+DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS = 900
+MAX_LOCAL_SIGNAL_WAIT_SECONDS = 900
+LOCAL_SIGNAL_POLL_SECONDS = 0.1
+
+
+def _assert_distinct_local_accounts(book_username: str) -> None:
+    """Fail closed unless local Query and Book roles use different accounts."""
+
+    if not ITA_QUERY_ACCOUNT_FILE.exists():
+        raise DebugConfigurationError(
+            "Automatic local handoff requires the private Italy Query account "
+            "file so Query and Book accounts can be verified as different"
+        )
+    try:
+        query_account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
+    except LocalAccountConfigurationError as exc:
+        raise DebugConfigurationError(
+            "Local Italy Query account config is invalid"
+        ) from exc
+    if (
+        query_account.username.strip().casefold()
+        == book_username.strip().casefold()
+    ):
+        raise DebugConfigurationError(
+            "Automatic local handoff requires different Query and Book accounts"
+        )
+
+
+def _wait_for_local_signal(
+    *,
+    route: ItaDebugRoute,
+    timeout_seconds: int,
+    signal_claimer: Callable[[], object | None] | None,
+    monotonic: Callable[[], float],
+    sleep: Callable[[float], None],
+) -> object | None:
+    claimer = signal_claimer or (
+        lambda: claim_local_weak_signal(
+            expected_service_id=route.service_id,
+            expected_routing_key=route.routing_key,
+        )
+    )
+    deadline = monotonic() + timeout_seconds
+    while True:
+        try:
+            signal = claimer()
+        except ItaLocalSignalStaleError:
+            print(
+                "ITA_BOOK_SIGNAL_IGNORED "
+                f"routing_key={route.routing_key} "
+                f"service_id={route.service_id} reason=stale",
+                flush=True,
+            )
+            signal = None
+        if signal is not None:
+            return signal
+        remaining = deadline - monotonic()
+        if remaining <= 0:
+            return None
+        try:
+            sleep(min(LOCAL_SIGNAL_POLL_SECONDS, remaining))
+        except KeyboardInterrupt:
+            raise _BookArmCancelled from None
+
+
+def run_book_recheck_once(
+    env: Mapping[str, str],
+    *,
+    non_interactive: bool,
+    arm: bool = False,
+    wait_for_local_signal: bool = False,
+    signal_timeout: int = DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS,
+    signal_claimer: Callable[[], object | None] | None = None,
+    monotonic: Callable[[], float] = time.monotonic,
+    sleep: Callable[[float], None] = time.sleep,
+    production_workflow: bool = False,
+    auto_otp: bool = False,
+    verify_receipts: bool = False,
+) -> int:
+    if type(verify_receipts) is not bool or (verify_receipts and not production_workflow):
+        raise DebugConfigurationError("--verify-receipts requires --production-workflow")
+    if auto_otp and not production_workflow:
+        raise DebugConfigurationError("--auto-otp requires --production-workflow")
+    if production_workflow and (non_interactive or arm or wait_for_local_signal):
+        raise DebugConfigurationError("--production-workflow requires interactive mode without legacy handoff flags")
+    route = resolve_debug_route(env)
+    route_log = (
+        f"service_id={route.service_id} routing_key={route.routing_key}"
+    )
+    if arm and wait_for_local_signal:
+        raise DebugConfigurationError(
+            "--arm and --wait-for-local-signal are mutually exclusive"
+        )
+    if (
+        wait_for_local_signal
+        and not 1 <= signal_timeout <= MAX_LOCAL_SIGNAL_WAIT_SECONDS
+    ):
+        raise DebugConfigurationError(
+            "signal_timeout must be between 1 and "
+            f"{MAX_LOCAL_SIGNAL_WAIT_SECONDS} seconds"
+        )
+
+    chrome_path = resolve_chrome_path(env)
+    os.environ["CHROME_BIN"] = str(chrome_path)
+
+    credential_env = env
+    if production_workflow:
+        # Match the existing Book gate: never silently borrow Query credentials.
+        credential_env = {"ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
+                          "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", "")}
+        print("ITA_BOOK_WORKFLOW_CREDENTIALS role=applicant profile=temporary source=book_environment_or_prompt", flush=True)
+    username, password = _get_credentials(credential_env, non_interactive=non_interactive)
+    if wait_for_local_signal:
+        _assert_distinct_local_accounts(username)
+    config_builder = build_query_config
+    if production_workflow:
+        from tools.debug_ita_calendar_gate import build_calendar_gate_config
+        config_builder = build_calendar_gate_config
+    config = config_builder(
+        env,
+        username=username,
+        password=password,
+        route=route,
+    )
+    if production_workflow:
+        config.free_config.update(query_mode="services_probe", otp_mode="manual", final_submit_enabled=False)
+        if auto_otp:
+            from plugins.ita_otp import validate_cloud_otp_environment
+            from plugins.ita_protocol import ItaProtocolError, OtpMailConfig
+            from plugins.ita_calendar_query import CalendarGateError
+            try:
+                mail = OtpMailConfig(env.get("ITA_OTP_AUTHORIZATION_EMAIL", ""))
+                validate_cloud_otp_environment(mail, username)
+            except (ItaProtocolError, CalendarGateError):
+                raise DebugConfigurationError(
+                    "Automatic OTP requires ITA_OTP_AUTHORIZATION_EMAIL and INFO-or-higher SDK logging"
+                ) from None
+            config.free_config["apt_configs"][route.routing_key]["mail"] = {
+                "authorization_email": mail.authorization_email,
+            }
+            config.free_config["otp_mode"] = "cloud"
+            print("ITA_BOOK_WORKFLOW_OTP mode=cloud final_submit_enabled=false", flush=True)
+
+    plugin = ItaPlugin(group_id="ita-book-local-debug")
+    plugin.set_log(lambda message: print(message, flush=True))
+    plugin.set_config(config)
+
+    trigger = VSQueryResult(
+        success=True,
+        apt_type=route.appointment_type(),
+        availability_status=AvailabilityStatus.NoneAvailable,
+    )
+    exit_code = 0
+    cleanup_error: Exception | None = None
+    audit = None
+    try:
+        plugin.create_session()
+        if production_workflow:
+            from plugins.ita_calendar_session import CalendarRequestAudit
+            audit = CalendarRequestAudit(plugin.page, include_time_slots=True)
+            audit.start()
+        if arm:
+            print(
+                "ITA_BOOK_ARMED "
+                f"{route_log} stage=user-area"
+            )
+            try:
+                input("Press Enter once the Query account reports a weak signal: ")
+            except KeyboardInterrupt:
+                raise _BookArmCancelled from None
+        should_recheck = True
+        if wait_for_local_signal:
+            print(
+                "ITA_BOOK_WAITING_FOR_LOCAL_SIGNAL "
+                f"{route_log} "
+                f"timeout_seconds={signal_timeout}",
+                flush=True,
+            )
+            signal = _wait_for_local_signal(
+                route=route,
+                timeout_seconds=signal_timeout,
+                signal_claimer=signal_claimer,
+                monotonic=monotonic,
+                sleep=sleep,
+            )
+            if signal is None:
+                print(
+                    "ITA_BOOK_SIGNAL_WAIT_TIMEOUT "
+                    f"{route_log} book_attempts=0"
+                )
+                exit_code = 5
+                should_recheck = False
+            else:
+                print(
+                    "ITA_BOOK_SIGNAL_CLAIMED "
+                    f"{route_log} "
+                    "evidence=booking-form",
+                    flush=True,
+                )
+
+        if should_recheck:
+            print(
+                "ITA_BOOK_RECHECK_START "
+                f"{route_log} book_attempt=1"
+            )
+            result = plugin.book(trigger, user_inputs={"username": username} if production_workflow else {})
+
+            if production_workflow:
+                from plugins.ita_calendar_book import read_calendar_service, verify_precommit_selection
+                counts = audit.settled_snapshot()
+                if counts["finalRequests"] != 0:
+                    raise BizLogicError("Book workflow observed an unexpected final request; do not rerun")
+                selected = result.label == BOOKING_CALENDAR_PREFINAL_STOP_LABEL and result.success is False
+                report = {"selectionVerified": False, "bookResultSuccess": result.success,
+                          "finalSubmissionEnabled": False, "requests": counts}
+                if selected:
+                    approval = plugin.last_booking_precommit
+                    verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page),
+                                               approval=approval)
+                    report.update(selectionVerified=True, selectedDate=approval.candidate.day.isoformat(),
+                                  selectedTime=approval.candidate.time_label, remaining=approval.candidate.slots_free)
+                    if verify_receipts:
+                        # Reuse the existing gate, including its background-tab
+                        # request audit and selection-preservation check.
+                        from tools.debug_ita_book_gate import _verify_receipt_baseline
+                        baseline = _verify_receipt_baseline(plugin, plugin._resolve_route(trigger.apt_type))
+                        if audit.settled_snapshot() != counts:
+                            raise BizLogicError("Receipt verification changed the Book request budget; do not rerun")
+                        report["receiptBaseline"] = baseline
+                        print("ITA_BOOK_WORKFLOW_RECEIPT_BASELINE=" + json.dumps(baseline, sort_keys=True), flush=True)
+                elif result.success or result.label != BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
+                    raise BizLogicError("Book workflow did not return the expected pre-final or no-availability result")
+                exit_code = 0 if selected else 2
+                print("ITA_BOOK_WORKFLOW_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
+            elif result.success:
+                print(
+                    "ITA_BOOK_SAFE_STOP "
+                    f"{route_log} "
+                    "reason=unexpected-success-before-avanti"
+                )
+                exit_code = 4
+            elif result.label == BOOKING_FORM_DISCOVERY_STOP_LABEL:
+                _print_booking_form_structure(
+                    plugin,
+                    raw_structure=plugin.last_booking_form_structure,
+                    route=route,
+                )
+                print(
+                    "ITA_BOOK_DISCOVERY_STOP "
+                    f"{route_log} "
+                    "stage=before-avanti submit_attempts=0"
+                )
+                exit_code = 4
+            elif result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
+                print(
+                    "ITA_BOOK_RECHECK_NONE_AVAILABLE "
+                    f"{route_log}"
+                )
+            else:
+                print(
+                    "ITA_BOOK_SAFE_STOP "
+                    f"{route_log} reason=unexpected-result"
+                )
+                exit_code = 4
+    except _BookArmCancelled:
+        label = (
+            "ITA_BOOK_SIGNAL_WAIT_CANCELLED"
+            if wait_for_local_signal
+            else "ITA_BOOK_ARM_CANCELLED"
+        )
+        print(
+            f"\n{label} {route_log} book_attempts=0"
+        )
+        exit_code = 130
+    except BizLogicError as exc:
+        print(
+            f"ITA_BOOK_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        if plugin.last_booking_form_structure is not None:
+            _print_booking_form_structure(
+                plugin,
+                raw_structure=plugin.last_booking_form_structure,
+                route=route,
+            )
+        exit_code = 1
+    except Exception as exc:
+        print(
+            f"ITA_BOOK_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        exit_code = 1
+    finally:
+        if audit is not None:
+            try:
+                counts = audit.settled_snapshot()
+                if counts["finalRequests"] != 0:
+                    exit_code = 1
+                print("ITA_BOOK_WORKFLOW_AUDIT=" + json.dumps(counts, sort_keys=True), flush=True)
+            except Exception:
+                exit_code = 1
+                print("ITA_BOOK_WORKFLOW_AUDIT_FAILED", flush=True)
+            finally:
+                try:
+                    audit.stop()
+                except Exception:
+                    exit_code = 1
+                    print("ITA_BOOK_WORKFLOW_AUDIT_CLEANUP_FAILED", flush=True)
+        try:
+            plugin.cleanup()
+            print("ITA_BOOK_CLEANUP_OK")
+        except Exception as exc:
+            cleanup_error = exc
+            print(
+                f"ITA_BOOK_CLEANUP_FAILED type={type(exc).__name__} "
+                f"message={_text_for_log(exc)}",
+                file=sys.stderr,
+            )
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "One-shot route-configured Italy Book recheck debugger "
+            "(default: stop before AVANTI; production-workflow: stop after selection; never confirm)."
+        )
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when credentials are missing.",
+    )
+    parser.add_argument(
+        "--production-workflow", action="store_true",
+        help="Exercise the public Book entry through manual OTP and Calendar selection; never submit final.",
+    )
+    parser.add_argument(
+        "--auto-otp", action="store_true",
+        help="Use the existing cloud mail API in production-workflow instead of prompting for OTP; never confirm.",
+    )
+    parser.add_argument(
+        "--verify-receipts", action="store_true",
+        help="With production-workflow, verify the existing receipt baseline without submitting a booking.",
+    )
+    wait_group = parser.add_mutually_exclusive_group()
+    wait_group.add_argument(
+        "--arm",
+        action="store_true",
+        help=(
+            "Log in and wait at /UserArea until Enter is pressed, then perform "
+            "the one safe Book recheck."
+        ),
+    )
+    wait_group.add_argument(
+        "--wait-for-local-signal",
+        action="store_true",
+        help=(
+            "Log in with the user account, atomically wait for one local Query "
+            "weak signal, then perform one independent safe recheck."
+        ),
+    )
+    parser.add_argument(
+        "--signal-timeout",
+        type=int,
+        default=DEFAULT_LOCAL_SIGNAL_WAIT_SECONDS,
+        help=(
+            "Maximum seconds to keep the user Session armed while waiting "
+            f"(ceiling: {MAX_LOCAL_SIGNAL_WAIT_SECONDS})."
+        ),
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    try:
+        if args.auto_otp and not args.production_workflow:
+            raise DebugConfigurationError("--auto-otp requires --production-workflow")
+        if args.verify_receipts and not args.production_workflow:
+            raise DebugConfigurationError("--verify-receipts requires --production-workflow")
+        if args.production_workflow:
+            extra = {"auto_otp": True} if args.auto_otp else {}
+            if args.verify_receipts:
+                extra["verify_receipts"] = True
+            return run_book_recheck_once(
+                os.environ, non_interactive=args.non_interactive, arm=args.arm,
+                wait_for_local_signal=args.wait_for_local_signal,
+                signal_timeout=args.signal_timeout, production_workflow=True, **extra,
+            )
+        return run_book_recheck_once(
+            os.environ,
+            non_interactive=args.non_interactive,
+            arm=args.arm,
+            wait_for_local_signal=args.wait_for_local_signal,
+            signal_timeout=args.signal_timeout,
+        )
+    except DebugConfigurationError as exc:
+        print(f"ITA_BOOK_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 782 - 0
tools/debug_ita_book_gate.py

@@ -0,0 +1,782 @@
+#!/usr/bin/env python3
+"""Prepare an applicant Calendar; default stops before final booking.
+
+Default/preflight is local-only. --run permits one manual OTP and one AVANTI
+in a new temporary browser. --use-local-query-account explicitly reuses the
+saved credentials only; Query browser profiles are never loaded.
+Q-CAL supplies preparation/audit helpers; CS4B owns all Calendar decisions.
+--submit-once adds a separately confirmed REAL submission for local discovery,
+with a persistent local fence and manual receipt review, never production final.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import math
+import os
+import re
+import sys
+from dataclasses import dataclass, field
+from pathlib import Path
+from typing import Callable, Mapping
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins import ita_calendar_book as calendar_book
+from plugins.ita_final_read_port import FinalReceiptReadPort
+from plugins.ita_calendar_query import CALENDAR_PATH, guard_calendar, same_origin_path
+from plugins.ita_plugin import (
+    BOOKING_CALENDAR_PREFINAL_STOP_LABEL,
+    BOOKING_FORM_DISCOVERY_STOP_LABEL,
+    BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+    PERSISTENT_BROWSER_PROFILE_KEY,
+    SERVICES_PROBE_QUERY_MODE,
+    ItaPlugin,
+)
+from plugins.ita_protocol import ItaRouteConfig, PrecommitApproval, resolve_route_config
+from tools import debug_ita_calendar_gate as preparation
+from tools import ita_final_evidence as final_evidence
+from tools.debug_ita_query import DEBUG_ROUTE_ENV_NAMES, _popup_text_for_log, resolve_debug_route
+from tools.debug_ita_session import _get_credentials, resolve_chrome_path
+from utils.ita_local_profile import ITA_QUERY_ACCOUNT_FILE
+from utils.local_account import LocalAccountConfigurationError, load_local_account
+from vs_types import AppointmentType, AvailabilityStatus, BizLogicError, VSBookResult, VSQueryResult
+
+
+BOOK_GATE_CONTRACT = "book-final-attribution-v9"
+CALENDAR_READY_TIMEOUT_SECONDS = 5
+BOOK_GATE_SOURCE_PATHS = (
+    Path(__file__), Path(preparation.__file__),
+    REPO_ROOT / "plugins" / "ita_calendar_session.py",
+    REPO_ROOT / "plugins" / "ita_plugin.py",
+    REPO_ROOT / "plugins" / "ita_calendar_book.py",
+    REPO_ROOT / "plugins" / "ita_calendar_query.py",
+    REPO_ROOT / "plugins" / "ita_protocol.py",
+    REPO_ROOT / "plugins" / "ita_final_read_port.py",
+    REPO_ROOT / "plugins" / "ita_reservation.py",
+    REPO_ROOT / "plugins" / "ita_booking_final.py",
+    REPO_ROOT / "tools" / "debug_ita_query.py",
+    REPO_ROOT / "tools" / "debug_ita_session.py",
+    REPO_ROOT / "tools" / "ita_final_evidence.py",
+    REPO_ROOT / "tools" / "ita_local_handoff.py",
+    REPO_ROOT / "utils" / "local_account.py",
+    REPO_ROOT / "utils" / "ita_local_profile.py",
+)
+BOOK_GATE_FINGERPRINT = hashlib.sha256(
+    b"".join(path.read_bytes() for path in BOOK_GATE_SOURCE_PATHS)
+).hexdigest()[:12]
+_COUNT_KEYS = {"otpRequests", "avantiPosts", "availabilityRequests", "finalRequests"}
+
+
+class BookGateError(ValueError):
+    """Tool-owned safe message, with no provider data or credential values."""
+
+
+@dataclass(frozen=True)
+class _ApplicantBinding:
+    plugin_id: int
+    page: object = field(repr=False)
+    tab_id: str = field(repr=False)
+    username: str = field(repr=False)
+    login_generation: float
+    route: ItaRouteConfig
+
+    @classmethod
+    def capture(cls, plugin: ItaPlugin, username: str, route: ItaRouteConfig):
+        page = plugin.page
+        generation = plugin.session_create_time
+        if (not page or not isinstance(page.tab_id, str) or not page.tab_id
+                or type(generation) not in (int, float)
+                or not math.isfinite(generation) or generation <= 0):
+            raise BookGateError("Applicant Session identity is unavailable")
+        binding = cls(id(plugin), page, page.tab_id, username.strip().casefold(), generation, route)
+        binding.require_current(plugin, expected_path="/UserArea")
+        return binding
+
+    def require_current(self, plugin: ItaPlugin, *, expected_path: str | None = None) -> None:
+        if (id(plugin) != self.plugin_id or plugin.page is not self.page
+                or self.page.tab_id != self.tab_id
+                or not self.username
+                or plugin.config.account.username.strip().casefold() != self.username
+                or plugin.session_create_time != self.login_generation
+                or plugin.free_config.get(PERSISTENT_BROWSER_PROFILE_KEY) is not None
+                or getattr(plugin, "_persistent_profile_path", None) is not None
+                or plugin.free_config.get("final_submit_enabled") is not False
+                or plugin.free_config.get("query_mode") != SERVICES_PROBE_QUERY_MODE
+                or getattr(plugin, "_calendar_query_route_key", None) is not None
+                or plugin._resolve_route(
+                    AppointmentType(routing_key=self.route.routing_key)
+                ) != self.route):
+            raise BookGateError("Applicant, browser, route or preparation identity changed")
+        path, _ = same_origin_path(self.page.url)
+        if expected_path is not None and path != expected_path:
+            raise BookGateError("Applicant browser is not on the expected stage")
+
+
+def _counts(audit: preparation.CalendarRequestAudit) -> dict[str, int]:
+    raw = audit.settled_snapshot()
+    if (not isinstance(raw, dict) or set(raw) != _COUNT_KEYS
+            or any(type(value) is not int or value < 0 for value in raw.values())):
+        raise BookGateError("Business-request audit shape changed")
+    return raw
+
+
+def _budget(counts: dict[str, int], *, otp: int, avanti: int, before_calendar: bool = False) -> None:
+    if (counts["otpRequests"] != otp or counts["avantiPosts"] != avanti
+            or counts["finalRequests"] != 0
+            or (before_calendar and counts["availabilityRequests"] != 0)):
+        raise BookGateError("Business requests exceeded the current one-shot budget")
+
+
+def _current_packet(packet: object, binding: _ApplicantBinding) -> None:
+    if (getattr(packet, "tab_id", None) != binding.tab_id
+            or getattr(packet, "is_failed", None) is not False
+            or type(packet.response.status) is not int):
+        raise BookGateError("Preparation response is not a completed request from this applicant tab")
+
+
+def _guarded_preflight_script(route: ItaRouteConfig, booking_path: str) -> str:
+    return preparation.calendar_session.guarded_preflight_script(route, booking_path)
+
+
+def _wait_preflight(plugin: ItaPlugin, binding: _ApplicantBinding, stage) -> None:
+    booking_path = f"/Services/Booking/{binding.route.service_id}"
+    binding.require_current(plugin, expected_path=booking_path)
+    preparation.wait_for_booking_preflight(
+        binding.page, script=_guarded_preflight_script(binding.route, booking_path), stage=stage,
+    )
+    binding.require_current(plugin, expected_path=booking_path)
+
+
+def _native_click(plugin: ItaPlugin, binding: _ApplicantBinding, selector: str) -> None:
+    binding.require_current(plugin, expected_path=f"/Services/Booking/{binding.route.service_id}")
+    plugin.mouse.human_click_ele(preparation._element_or_fail(binding.page, selector))
+
+
+def _require_stop_result(result: object) -> VSBookResult:
+    if (not isinstance(result, VSBookResult) or result.success is not False
+            or any(getattr(result, key) for key in
+                   ("session_id", "urn", "account", "book_date", "book_time", "payment_link"))):
+        raise BookGateError("Book returned appointment-success data during a pre-final gate")
+    return result
+
+
+def _selection_readback(
+    plugin: ItaPlugin, binding: _ApplicantBinding, user_inputs: dict, result: VSBookResult,
+) -> dict:
+    binding.require_current(plugin, expected_path=CALENDAR_PATH)
+    guard_calendar(binding.page)
+    if not plugin._calendar_book_context_matches(binding.route, binding.username):
+        raise BookGateError("Book-specific Calendar preparation is no longer current")
+    approval = plugin.last_booking_precommit
+    if result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL and approval is None:
+        return {"selectionVerified": False, "selectedDate": None, "selectedTime": None,
+                "remaining": None, "bookResultSuccess": False}
+    if result.label != BOOKING_CALENDAR_PREFINAL_STOP_LABEL or not isinstance(approval, PrecommitApproval):
+        raise BookGateError("Book did not return the expected pre-final checkpoint")
+    candidate = approval.candidate
+    start, end = calendar_book.book_date_preferences(user_inputs)
+    if (not start <= candidate.day <= end or not approval.calendar_day.is_available
+            or not candidate.is_available or candidate.day != approval.calendar_day.day):
+        raise BookGateError("Book checkpoint does not match positive inventory and date preferences")
+    service = calendar_book.read_calendar_service(binding.page)
+    raw = calendar_book._snapshot(binding.page, service, candidate.day, candidate, click=False)
+    calendar_book._require_ready(raw, candidate.day)
+    if (raw["clicked"] or raw["activeCount"] != 1 or raw["activeInputCount"] != 1
+            or raw["activeUnavailable"] or raw["activeRedDot"]
+            or not all(raw[key] for key in (
+                "activeIsCandidate", "activeIdMatches", "activeDayMatches",
+                "activeTimeMatches", "activeCapacityMatches",
+            ))):
+        raise BookGateError("Selected slot changed before the read-only gate readback")
+    return {"selectionVerified": True, "selectedDate": candidate.day.isoformat(),
+            "selectedTime": candidate.time_label, "remaining": candidate.slots_free,
+            "bookResultSuccess": False}
+
+
+def _book_credentials(
+    env: Mapping[str, str], *, use_local_query_account: bool = False,
+) -> tuple[str, str]:
+    if use_local_query_account:
+        try:
+            account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
+        except LocalAccountConfigurationError:
+            raise BookGateError(
+                "Local Query account is invalid; check config/ita_query_account.local.json "
+                "and its private file permissions"
+            ) from None
+        print("ITA_BOOK_GATE_CREDENTIALS role=applicant profile=temporary source=local_query_file", flush=True)
+        return account.username, account.password
+    # A projection rather than dict(env): Query/general credentials cannot leak
+    # into the fallback helper even when inherited from the user's terminal.
+    print("ITA_BOOK_GATE_CREDENTIALS role=applicant profile=temporary source=book_environment_or_prompt", flush=True)
+    return _get_credentials({
+        "ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
+        "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", ""),
+    }, non_interactive=False)
+
+
+def _resolve_inputs(env: Mapping[str, str], user_inputs: Mapping[str, str] | None):
+    if any(not str(env.get(name, "")).strip() for name in DEBUG_ROUTE_ENV_NAMES):
+        raise BookGateError("Book gate requires all four explicit ITA route fields")
+    preferences = dict(user_inputs or {})
+    if not set(preferences) <= {"expected_start_date", "expected_end_date"}:
+        raise BookGateError("Gate inputs may only contain the two date preferences")
+    calendar_book.book_date_preferences(preferences)
+    debug_route = resolve_debug_route(env)
+    chrome_path = resolve_chrome_path(env)
+    # Synthetic values only validate the existing config builder. Nothing leaves
+    # this process, and no account file or real credential is read in preflight.
+    config = preparation.build_calendar_gate_config(
+        env, username="preflight@example.test", password="local-only", route=debug_route,
+    )
+    route = resolve_route_config(config.free_config["apt_configs"], debug_route.routing_key)
+    return debug_route, route, chrome_path, preferences
+
+
+_PREPARATION_FAILURES = {
+    "Italy Book preparation requires a single-tourism Calendar route": "route_not_supported",
+    "Italy Book cannot reuse a Query preparation or another route": "query_or_route_mismatch",
+    "Italy Book preparation requires an authenticated user Session and final disabled": "applicant_session_not_ready",
+    "Italy Book preparation did not identify the current Calendar service": "calendar_service_unidentified",
+    "Italy Book Calendar service did not initialize before timeout": "calendar_service_not_ready",
+}
+
+
+_PRODUCTION_BOOK_FAILURES = {
+    "Book date control structure changed": "date_snapshot_structure_changed",
+    "Book date control types changed": "date_snapshot_types_changed",
+    "Book date control context was not unique and guarded": "date_context_not_ready",
+    "Book date readback unexpectedly clicked": "date_readback_clicked",
+    "Book date is already selected without a fresh captured response": "date_selected_without_fresh_response",
+    "Book date control was not ready before timeout": "date_control_timeout",
+    "Book date click was not acknowledged": "date_click_not_acknowledged",
+    "Book selected date did not match the response before timeout": "selected_date_timeout",
+    "Book TimeSlots request date format changed": "timeslot_request_date_format_changed",
+    "Book TimeSlots request method or path changed": "timeslot_request_route_changed",
+    "Book TimeSlots response status was not 200": "timeslot_response_status_rejected",
+    "Book TimeSlots request fields changed": "timeslot_request_fields_changed",
+    "Book TimeSlots request does not match the current service": "timeslot_service_mismatch",
+    "Book TimeSlots request does not match the target day": "timeslot_request_day_mismatch",
+    "Book TimeSlots response contains another day": "timeslot_response_day_mismatch",
+    "Book TimeSlots packet could not be validated": "timeslot_packet_invalid",
+    "Book slot snapshot fields changed": "slot_snapshot_fields_changed",
+    "Book slot snapshot boolean types changed": "slot_snapshot_types_changed",
+    "Book selected-date snapshot types changed": "selected_date_snapshot_types_changed",
+    "Book slot DOM changed its context or uniqueness": "slot_context_changed",
+    "Book slot DOM did not match the response before timeout": "slot_dom_timeout",
+    "Book candidate is not safely selectable": "candidate_not_selectable",
+    "Book selected day is marked unavailable": "selected_day_unavailable",
+    "Book date or slot is not unique": "date_or_slot_not_unique",
+    "Book timeline and content dates do not match the target": "selected_dates_mismatch",
+    "Book Availability and TimeSlots disagree": "inventory_disagreement",
+    "Book read-only snapshot unexpectedly clicked": "slot_snapshot_clicked",
+    "Book slot click was not acknowledged": "slot_click_not_acknowledged",
+    "Book readback unexpectedly clicked": "slot_readback_clicked",
+    "Book precommit rejected (precommit_rejected)": "precommit_readback_rejected",
+    "Book Calendar selection or final guard failed": "selection_or_guard_failed",
+    "Book applicant, route or browser Session changed": "applicant_context_changed",
+    "Book Calendar runtime service changed": "calendar_service_changed",
+    "Book response did not belong to the current browser tab": "response_tab_mismatch",
+    "Book browser request failed": "browser_request_failed",
+    "Book Calendar recheck failed; no further action was attempted": "calendar_recheck_failed",
+    "Italy Book Calendar failed before final confirmation": "calendar_internal_failure",
+    "Book final-button guard could not be verified": "final_guard_failed",
+}
+
+BOOK_FAILURE_STATE_SCRIPT = r"""
+/* coordinate:ita-book-failure-state-readonly */
+const service = Array.from(document.querySelectorAll('#idServizio'));
+const timeline = Array.from(document.querySelectorAll('.events a.selected'));
+const content = Array.from(document.querySelectorAll('.events-content li.selected'));
+const slots = content.length === 1 ? Array.from(content[0].querySelectorAll('.fascia')) : [];
+const finalButtons = Array.from(document.querySelectorAll('#btnPrenotaNoOtp'));
+const states = slots.slice(0, 12).map(slot => {
+  const style = window.getComputedStyle(slot), rect = slot.getBoundingClientRect();
+  const left = Math.max(0, rect.left), right = Math.min(window.innerWidth, rect.right);
+  const top = Math.max(0, rect.top), bottom = Math.min(window.innerHeight, rect.bottom);
+  const inViewport = right > left && bottom > top;
+  const hit = inViewport ? document.elementFromPoint((left + right)/2, (top + bottom)/2) : null;
+  return {
+    active: slot.classList.contains('act'),
+    markedUnavailable: slot.classList.contains('notAvailableFascia'),
+    redDot: Boolean(slot.querySelector('.dotRed')),
+    cssVisible: style.display !== 'none' && style.visibility !== 'hidden' &&
+      style.pointerEvents !== 'none' && Number.parseFloat(style.opacity || '1') > 0,
+    hasSize: rect.width > 0 && rect.height > 0,
+    inViewport,
+    centerHit: Boolean(hit && (hit === slot || slot.contains(hit))),
+    hiddenInputCount: slot.querySelectorAll('input[type="hidden"]').length,
+  };
+});
+return {
+  pathMatches: location.origin === 'https://prenotami.esteri.it' && location.pathname === '/BookingCalendar',
+  serviceControlCount: service.length,
+  serviceValuePresent: service.length === 1 && typeof service[0].value === 'string' && Boolean(service[0].value),
+  timelineSelectedCount: timeline.length, contentSelectedCount: content.length,
+  firstSelectedIsTimeline: timeline.length === 1 && document.querySelector('.selected') === timeline[0],
+  selectedDatesMatch: timeline.length === 1 && content.length === 1 && Boolean(timeline[0].dataset.date) &&
+    timeline[0].dataset.date === content[0].dataset.date,
+  slotCount: slots.length, activeSlotCount: document.querySelectorAll('.fascia.act').length,
+  finalButtonCount: finalButtons.length,
+  finalGuarded: finalButtons.length === 1 && finalButtons[0].disabled === true &&
+    finalButtons[0].dataset.coordinateFinalGuard === 'enabled',
+  timeSlotResourceEntries: performance.getEntriesByType('resource').filter(entry => {
+    try { const url = new URL(entry.name); return url.origin === location.origin &&
+      url.pathname === '/BookingCalendar/RetrieveTimeSlots'; } catch (_) { return false; }
+  }).length,
+  slotStatesTruncated: slots.length > states.length, slotStates: states,
+};
+"""
+
+_BOOK_STATE_BOOLS = {"pathMatches", "serviceValuePresent", "selectedDatesMatch", "firstSelectedIsTimeline",
+                     "finalGuarded", "slotStatesTruncated"}
+_BOOK_STATE_COUNTS = {"serviceControlCount", "timelineSelectedCount", "contentSelectedCount", "slotCount",
+                      "activeSlotCount", "finalButtonCount", "timeSlotResourceEntries"}
+_BOOK_SLOT_BOOLS = {"active", "markedUnavailable", "redDot", "cssVisible", "hasSize", "inViewport", "centerHit"}
+
+
+def _print_production_book_diagnostic(page: object) -> None:
+    """After-failure shape/visibility only; never emit browser text or field values."""
+    result = {"contract": BOOK_GATE_CONTRACT, "afterFailure": True, "readSucceeded": False}
+    try:
+        if same_origin_path(page.url)[0] != CALENDAR_PATH:
+            raise ValueError("Not Calendar")
+        raw = page.run_js(BOOK_FAILURE_STATE_SCRIPT)
+        if (not isinstance(raw, dict) or set(raw) != _BOOK_STATE_BOOLS | _BOOK_STATE_COUNTS | {"slotStates"}
+                or any(type(raw[key]) is not bool for key in _BOOK_STATE_BOOLS)
+                or any(type(raw[key]) is not int or not 0 <= raw[key] <= 100000 for key in _BOOK_STATE_COUNTS)
+                or not isinstance(raw["slotStates"], list) or len(raw["slotStates"]) > 12):
+            raise ValueError("Unrecognized state shape")
+        for slot in raw["slotStates"]:
+            if (not isinstance(slot, dict) or set(slot) != _BOOK_SLOT_BOOLS | {"hiddenInputCount"}
+                    or any(type(slot[key]) is not bool for key in _BOOK_SLOT_BOOLS)
+                    or type(slot["hiddenInputCount"]) is not int or not 0 <= slot["hiddenInputCount"] <= 100000):
+                raise ValueError("Unrecognized slot shape")
+        result.update(readSucceeded=True, state=raw)
+    except Exception:
+        pass  # Diagnostics must neither expose raw data nor replace the original failure.
+    print("ITA_BOOK_GATE_SELECTION_DIAGNOSTIC=" + json.dumps(result, sort_keys=True), flush=True)
+
+
+def _print_calendar_preparation_diagnostic(page: object) -> None:
+    """Read structural metadata after failure; never log the runtime ID itself."""
+    diagnostic = {"contract": BOOK_GATE_CONTRACT, "afterFailure": True, "readSucceeded": False}
+    try:
+        diagnostic["pathMatches"] = same_origin_path(page.url)[0] == CALENDAR_PATH
+        if diagnostic["pathMatches"]:
+            tab_id = getattr(page, "tab_id", None)
+            diagnostic["tabIdPresent"] = isinstance(tab_id, str) and bool(tab_id)
+            raw = page.run_js(calendar_book.RUNTIME_SERVICE_SCRIPT)
+            diagnostic["readSucceeded"] = True
+            diagnostic["snapshotIsObject"] = isinstance(raw, dict)
+            if isinstance(raw, dict):
+                count, value = raw.get("count"), raw.get("value")
+                diagnostic.update(
+                    snapshotKeysMatch=set(raw) == {"path", "count", "value"},
+                    snapshotPathMatches=raw.get("path") == CALENDAR_PATH,
+                    controlCountType=(type(count).__name__ if type(count) in (int, float, bool, str, type(None)) else "other"),
+                    controlCount=(count if type(count) is int and 0 <= count <= 10000 else None),
+                    valueType=(type(value).__name__ if type(value) in (str, int, float, bool, type(None)) else "other"),
+                    valueLength=len(value) if isinstance(value, str) else None,
+                    valuePresent=bool(value) if isinstance(value, str) else None,
+                    valueTrimmed=value == value.strip() if isinstance(value, str) else None,
+                    valueAccepted=False,
+                )
+                if isinstance(value, str):
+                    try:
+                        calendar_book._runtime_id(value)
+                        diagnostic["valueAccepted"] = True
+                    except calendar_book.CalendarBookError:
+                        pass
+    except Exception:
+        # The original failure must survive a failed best-effort readback.
+        diagnostic["readSucceeded"] = False
+    print("ITA_BOOK_GATE_CALENDAR_DIAGNOSTIC=" + json.dumps(diagnostic, sort_keys=True), flush=True)
+
+
+def _stop_listener_if_active(page: object) -> None:
+    # listen_once already stops it; the installed SDK's stop is not idempotent.
+    listener = page.listen
+    if listener.listening:
+        listener.stop()
+
+
+def _failure(stage: str, exc: BaseException) -> None:
+    # Provider exception strings may contain bodies, URLs, credentials or OTP.
+    message = str(exc) if type(exc) is BookGateError else "Stage failed; use the allowlisted diagnostic"
+    failure = {
+        "stage": stage, "type": type(exc).__name__, "message": message,
+    }
+    if stage == "calendar_preparation" and type(exc) is BizLogicError and isinstance(exc.message, str):
+        reason = _PREPARATION_FAILURES.get(exc.message)
+        if reason:
+            failure["reason"] = reason
+    elif stage == "production_book" and type(exc) is BizLogicError and isinstance(exc.message, str):
+        failure["reason"] = _PRODUCTION_BOOK_FAILURES.get(exc.message, "unclassified_book_failure")
+        if failure["reason"] == "unclassified_book_failure":
+            # Dynamic protocol codes never enter output; emit only a fixed category.
+            protocol = re.fullmatch(
+                r"Book (TimeSlots protocol|Calendar protocol|precommit) rejected \([a-z_]{1,64}\)",
+                exc.message,
+            )
+            if protocol:
+                failure["reason"] = {
+                    "TimeSlots protocol": "timeslot_protocol_rejected",
+                    "Calendar protocol": "calendar_protocol_rejected",
+                    "precommit": "precommit_readback_rejected",
+                }[protocol[1]]
+    print("ITA_BOOK_GATE_FAILED=" + json.dumps(failure, sort_keys=True), flush=True)
+
+
+def _receipt_observer(observed):
+    def observe(page):
+        audit = preparation.CalendarRequestAudit(page, include_time_slots=True)
+        audit.start()
+
+        def finish():
+            try:
+                counts = audit.settled_snapshot()
+                expected = _COUNT_KEYS | {"timeSlotRequests"}
+                if (not isinstance(counts, dict) or set(counts) != expected or
+                        any(type(value) is not int or value != 0 for value in counts.values())):
+                    raise BookGateError("Receipt tab emitted unexpected business requests")
+                observed.append(counts)
+            finally:
+                audit.stop()
+        return finish
+    return observe
+
+
+def _single_submission_verified(audit, before):
+    after = _counts(audit)
+    return (before["finalRequests"] == 0 and after["finalRequests"] == 1 and
+            all(after[k] == before[k] for k in _COUNT_KEYS - {"finalRequests"}))
+
+
+def _verify_receipt_baseline(plugin, route) -> dict:
+    """Optional background-tab acceptance; no final submission is reachable."""
+    observed = []
+
+    port = FinalReceiptReadPort(plugin, route, observe_tab=_receipt_observer(observed))
+    snapshot = port()
+    if not port.session_is_current() or len(observed) != 1:
+        raise BookGateError("Receipt read acceptance did not finish")
+    calendar_book.verify_precommit_selection(plugin.page, runtime_service=port.target.runtime_service,
+                                             approval=port.target.approval)
+    return {"verified": True, "recordCount": len(snapshot.records), "calendarSelectionPreserved": True,
+            "businessRequests": observed[0], "finalSubmissionEnabled": False}
+
+
+def run_book_gate(
+    env: Mapping[str, str], *, execute: bool = False,
+    use_local_query_account: bool = False,
+    user_inputs: Mapping[str, str] | None = None,
+    otp_reader: Callable[[], str] = preparation._read_manual_otp,
+    verify_receipts: bool = False,
+    submit_once: bool = False,
+    final_confirm: Callable[[str], str] = input,
+    review_reader: Callable[[str], str] = input,
+) -> int:
+    print(f"ITA_BOOK_GATE_TOOL_CONTRACT version={BOOK_GATE_CONTRACT} source_sha256={BOOK_GATE_FINGERPRINT}", flush=True)
+    plugin = binding = audit = None
+    before = after = observed = None
+    preparation_counts = book_counts = None
+    selection: dict = {}
+    receipt_baseline = None
+    final_run = None
+    audit_verified = False
+    entry_calls = calendar_calls = 0
+    stage, outcome, exit_code = "configuration", "failed", 1
+    try:
+        if type(verify_receipts) is not bool:
+            raise BookGateError("Receipt verification flag must be boolean")
+        if type(submit_once) is not bool or (submit_once and not verify_receipts):
+            raise BookGateError("One-shot final requires explicit receipt verification")
+        if submit_once:
+            final_evidence.require_unused_claim()
+        debug_route, route, chrome_path, preferences = _resolve_inputs(env, user_inputs)
+        if not execute:
+            print("ITA_BOOK_GATE_PREFLIGHT_OK external_requests=0 credentials_read=false browser_created=false", flush=True)
+            return 0
+        if execute is not True:
+            raise BookGateError("Book gate execute must be an explicit boolean")
+        stage = "applicant_credentials"
+        username, password = _book_credentials(env, use_local_query_account=use_local_query_account)
+        config = preparation.build_calendar_gate_config(
+            env, username=username, password=password, route=debug_route,
+        )
+        os.environ["CHROME_BIN"] = str(chrome_path)
+        plugin = ItaPlugin(group_id="ita-book-prefinal-gate")
+        plugin.set_log(lambda message: print(
+            _popup_text_for_log(str(message).replace(username, "<applicant>").replace(password, "<password>")),
+            flush=True,
+        ))
+        plugin.set_config(config)
+        stage = "applicant_login"
+        plugin.create_session()
+        binding = _ApplicantBinding.capture(plugin, username, route)
+        stage = "reservation_before"
+        audit = preparation.CalendarRequestAudit(binding.page)
+        audit.start()
+        before = preparation.read_reservation_snapshot(binding.page)
+        _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
+        print(f"ITA_BOOK_GATE_RESERVATION_BEFORE reservations={before.reservations} waitlist={before.waitlist}", flush=True)
+
+        inputs = {**preferences, "username": username}
+        trigger = VSQueryResult(
+            success=True, apt_type=debug_route.appointment_type(),
+            availability_status=AvailabilityStatus.NoneAvailable,
+        )
+        stage = "booking_form_entry"
+        binding.require_current(plugin)
+        entry_calls += 1
+        entry = _require_stop_result(plugin.book(trigger, user_inputs=inputs))
+        binding.require_current(plugin)
+        _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
+        if entry.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL:
+            outcome, exit_code = "entry_unavailable", 2
+        elif entry.label != BOOKING_FORM_DISCOVERY_STOP_LABEL:
+            raise BookGateError("Entry did not stop at the configured booking form")
+        else:
+            stage = "before_otp_send"
+            _wait_preflight(plugin, binding, preparation.BookingPreflightStage.BEFORE_OTP_SEND)
+            _budget(_counts(audit), otp=0, avanti=0, before_calendar=True)
+            otp_guard = preparation.OneShotAction("Book OTP")
+            stage = "otp_send"
+            otp_packet = otp_guard.run(lambda: preparation.listen_once(
+                binding.page, target=preparation.OTP_PATH, method="GET", timeout=30,
+                action=lambda: _native_click(plugin, binding, "#otp-send"),
+            ))
+            _current_packet(otp_packet, binding)
+            preparation.validate_otp_packet(otp_packet, service_id=route.service_id)
+            del otp_packet
+            _budget(_counts(audit), otp=1, avanti=0, before_calendar=True)
+            print("ITA_BOOK_GATE_OTP_SENT requests=1", flush=True)
+            stage = "manual_otp_input"
+            otp = otp_reader()
+            try:
+                if not isinstance(otp, str) or re.fullmatch(r"[0-9]{4,12}", otp) is None:
+                    raise BookGateError("Manual OTP must contain 4-12 ASCII digits")
+                binding.require_current(plugin, expected_path=debug_route.booking_path)
+                preparation._enter_otp(plugin, otp)
+            finally:
+                del otp
+            stage = "after_otp_send"
+            _wait_preflight(plugin, binding, preparation.BookingPreflightStage.AFTER_OTP_SEND)
+            _budget(_counts(audit), otp=1, avanti=0, before_calendar=True)
+
+            stage = "avanti_transition"
+            avanti_guard = preparation.OneShotAction("Book AVANTI")
+            avanti_packet = None
+            try:
+                binding.page.set.auto_handle_alert(accept=True)
+                avanti_packet = avanti_guard.run(lambda: preparation.listen_once(
+                    binding.page, target=debug_route.booking_path, method="POST", timeout=30,
+                    action=lambda: _native_click(plugin, binding, "#btnAvanti"),
+                ))
+                _current_packet(avanti_packet, binding)
+                preparation._wait_for_calendar(binding.page)
+                binding.require_current(plugin, expected_path=CALENDAR_PATH)
+                transition = preparation.validate_avanti_packet(
+                    avanti_packet, booking_path=debug_route.booking_path, final_page_url=binding.page.url,
+                )
+            except Exception:
+                preparation._print_avanti_failure_diagnostic(
+                    binding.page, avanti_packet, booking_path=debug_route.booking_path,
+                )
+                raise
+            finally:
+                binding.page.set.auto_handle_alert(on_off=False)
+                avanti_packet = None
+            stage = "calendar_preparation"
+            try:
+                guard_calendar(binding.page)
+                preparation_counts = _counts(audit)
+                _budget(preparation_counts, otp=1, avanti=1)
+                binding.require_current(plugin, expected_path=CALENDAR_PATH)
+                try:
+                    calendar_book.wait_for_calendar_service(
+                        binding.page,
+                        session_is_current=lambda: binding.require_current(
+                            plugin, expected_path=CALENDAR_PATH,
+                        ) is None,
+                        timeout=CALENDAR_READY_TIMEOUT_SECONDS,
+                    )
+                except calendar_book.CalendarServiceNotReadyError:
+                    raise BizLogicError("Italy Book Calendar service did not initialize before timeout") from None
+                except BookGateError:
+                    raise
+                except Exception:
+                    raise BizLogicError("Italy Book preparation did not identify the current Calendar service") from None
+                plugin._record_calendar_book_prepared_route(route)
+                preparation_counts = _counts(audit)
+                _budget(preparation_counts, otp=1, avanti=1)
+            except Exception:
+                _print_calendar_preparation_diagnostic(binding.page)
+                raise
+            print(f"ITA_BOOK_GATE_CALENDAR_READY transition={transition} final_requests=0", flush=True)
+
+            stage = "production_book"
+            calendar_calls += 1
+            result = _require_stop_result(plugin.book(trigger, user_inputs=inputs))
+            stage = "selection_readback"
+            selection = _selection_readback(plugin, binding, inputs, result)
+            book_counts = _counts(audit)
+            _budget(book_counts, otp=1, avanti=1)
+            if book_counts["availabilityRequests"] <= preparation_counts["availabilityRequests"]:
+                raise BookGateError("Book did not observe fresh Calendar availability requests")
+            print("ITA_BOOK_GATE_SELECTION=" + json.dumps(selection, sort_keys=True), flush=True)
+            if verify_receipts and selection["selectionVerified"]:
+                stage = "receipt_baseline"
+                receipt_baseline = _verify_receipt_baseline(plugin, route)
+                if receipt_baseline["recordCount"] != before.reservations:
+                    raise BookGateError("Receipt baseline count differs from the pre-run inventory")
+                binding.require_current(plugin, expected_path=CALENDAR_PATH)
+                print("ITA_BOOK_GATE_RECEIPT_BASELINE=" + json.dumps(receipt_baseline, sort_keys=True), flush=True)
+            outcome = "pre_final" if selection["selectionVerified"] else "no_candidate_in_scan_range"
+            exit_code = 0 if selection["selectionVerified"] else 2
+            if submit_once and selection["selectionVerified"]:
+                stage = "final_evidence"
+                binding.require_current(plugin, expected_path=CALENDAR_PATH)
+                _budget(_counts(audit), otp=1, avanti=1)
+                final_run = final_evidence.FinalEvidenceRun(
+                    plugin, route, observe_tab=_receipt_observer([]),
+                    verify_submission=lambda: _single_submission_verified(audit, book_counts),
+                )
+                final_run.execute(confirm=final_confirm)
+                outcome = final_run.report["outcome"]
+                exit_code = 4 if final_run.possibly_submitted else 2
+    except (KeyboardInterrupt, EOFError):
+        print(f"ITA_BOOK_GATE_CANCELLED stage={stage} retries=0", flush=True)
+        outcome, exit_code = "cancelled", 130
+    except Exception as exc:
+        if stage == "production_book" and binding is not None:
+            _print_production_book_diagnostic(binding.page)
+        _failure(stage, exc)
+        exit_code = 1
+    finally:
+        if final_run is not None and final_run.possibly_submitted:
+            # Never report an interrupted/lost acknowledgement as safely retryable.
+            outcome = final_run.report["outcome"]
+            exit_code = 0 if final_run.report["bookingConfirmed"] is True else 4
+            print("ITA_BOOK_GATE_FINAL_EVIDENCE=" + json.dumps(final_run.report, sort_keys=True), flush=True)
+            try:
+                final_evidence.wait_for_receipt_review(reader=review_reader)
+            except (KeyboardInterrupt, EOFError):
+                print("ITA_FINAL_REVIEW_INTERRUPTED do_not_retry=true", flush=True)
+            except Exception:
+                print("ITA_FINAL_REVIEW_UNAVAILABLE do_not_retry=true", flush=True)
+        # Best-effort read-only reconciliation, including failures after a write.
+        # No OTP, form action, or Calendar retry is performed during cleanup.
+        if binding is not None:
+            try:
+                binding.require_current(plugin)
+                # NativeFinalSubmitter re-guards its button. The pre-final guard
+                # asserts ZERO historical final requests, so it must not run
+                # after an authorized submission; the final audit checks <=1.
+                if (same_origin_path(binding.page.url)[0] == CALENDAR_PATH and
+                        not (final_run is not None and final_run.possibly_submitted)):
+                    guard_calendar(binding.page)
+                if before is not None:
+                    after = preparation.read_reservation_snapshot(binding.page)
+                    binding.require_current(plugin)
+                    print(f"ITA_BOOK_GATE_RESERVATION_AFTER reservations={after.reservations} waitlist={after.waitlist}", flush=True)
+                    if before != after and not (final_run is not None and final_run.possibly_submitted):
+                        raise BookGateError("Reservation or waitlist counts changed; do not retry")
+            except Exception as exc:
+                _failure("read_only_reconciliation", exc)
+                if exit_code in (0, 2):
+                    exit_code = 1
+        if audit is not None:
+            try:
+                observed = _counts(audit)
+                final_limit = 1 if final_run is not None and final_run.possibly_submitted else 0
+                if (observed["finalRequests"] > final_limit or observed["otpRequests"] > 1
+                        or observed["avantiPosts"] > 1):
+                    raise BookGateError("Final audit exceeded the one-shot side-effect budget")
+                if final_run is not None and final_run.report["bookingConfirmed"] is True:
+                    if (observed["finalRequests"] != 1 or before is None or after is None or
+                            after.reservations != before.reservations + 1 or after.waitlist != before.waitlist):
+                        raise BookGateError("Confirmed booking did not retain its final audit evidence")
+                if book_counts is not None and any(observed[k] != book_counts[k] for k in _COUNT_KEYS
+                                                  if k != "finalRequests" or final_limit == 0):
+                    raise BookGateError("Business requests changed after the Book readback")
+                audit_verified = True
+            except Exception as exc:
+                _failure("final_request_audit", exc)
+                if exit_code in (0, 2):
+                    exit_code = 1
+        cleanup_failed = False
+        for name, action in (
+            ("listener", (lambda: _stop_listener_if_active(binding.page)) if binding is not None else None),
+            ("audit", audit.stop if audit is not None else None),
+            ("browser", plugin.cleanup if plugin is not None else None),
+        ):
+            if action is not None:
+                try:
+                    action()
+                except Exception as exc:
+                    cleanup_failed = True
+                    _failure(f"cleanup_{name}", exc)
+        if cleanup_failed:
+            exit_code = 3
+        elif plugin is not None:
+            print("ITA_BOOK_GATE_CLEANUP_OK", flush=True)
+
+    report = {
+        "contract": BOOK_GATE_CONTRACT, "outcome": outcome, "passed": exit_code == 0,
+        "receiptBaseline": receipt_baseline,
+        "finalEvidence": final_run.report if final_run is not None else None,
+        "requestAuditVerified": audit_verified,
+        "exitCode": exit_code, "entryBookCalls": entry_calls, "calendarBookCalls": calendar_calls,
+        "requests": observed,
+        "bookRequestDelta": (
+            {key: book_counts[key] - preparation_counts[key] for key in _COUNT_KEYS}
+            if book_counts is not None and preparation_counts is not None else None
+        ),
+        "reservationCountBefore": before.reservations if before is not None else None,
+        "reservationCountAfter": after.reservations if after is not None else None,
+        "waitlistCountBefore": before.waitlist if before is not None else None,
+        "waitlistCountAfter": after.waitlist if after is not None else None,
+        **selection,
+    }
+    if final_run is not None:
+        report["bookResultSuccess"] = (exit_code == 0 and final_run.result is not None and
+                                       final_run.result.success is True)
+    print("ITA_BOOK_GATE_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
+    return exit_code
+
+
+def main(argv: list[str] | None = None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    mode = parser.add_mutually_exclusive_group()
+    mode.add_argument("--preflight", action="store_true", help="Local config check only (default).")
+    mode.add_argument("--run", action="store_true", help="Allow one OTP, one AVANTI and pre-final selection; never final booking.")
+    parser.add_argument(
+        "--use-local-query-account", action="store_true",
+        help="Use saved local Query credentials for this Book run, in a separate temporary browser.",
+    )
+    parser.add_argument("--expected-start-date", help="Inclusive applicant date preference, YYYY-MM-DD.")
+    parser.add_argument("--expected-end-date", help="Inclusive applicant date preference, YYYY-MM-DD.")
+    parser.add_argument("--verify-receipts", action="store_true", help="After selection, verify receipts in an owned background tab; never final booking.")
+    parser.add_argument("--submit-once", action="store_true",
+                        help="With --run --verify-receipts: confirm a REAL appointment once, then inspect receipts. Exit 4 means do NOT retry.")
+    args = parser.parse_args(argv)
+    preferences = {key: value for key in ("expected_start_date", "expected_end_date")
+                   if (value := getattr(args, key)) is not None}
+    return run_book_gate(
+        os.environ, execute=args.run, user_inputs=preferences,
+        use_local_query_account=args.use_local_query_account,
+        verify_receipts=args.verify_receipts,
+        submit_once=args.submit_once,
+    )
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1374 - 0
tools/debug_ita_calendar_gate.py

@@ -0,0 +1,1374 @@
+#!/usr/bin/env python3
+"""Run a bounded Italy Calendar discovery or production-Query safety gate.
+
+This tool is intentionally interactive.  It uses an authorized team Query
+account, sends exactly one booking OTP, submits the pre-calendar form exactly
+once, then either probes the discovery horizon or calls the real production
+Query twice in the same prepared session. Both modes compare non-sensitive
+Reservation counts before and after. This tool never explicitly selects a
+date or time slot and never clicks the final booking button. The site's own
+Calendar initialization may automatically select a date when it renders.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+import os
+import sys
+import time
+from dataclasses import dataclass
+from datetime import date, datetime
+from enum import Enum
+from pathlib import Path
+from threading import Lock
+from typing import Any, Callable, Mapping
+from urllib.parse import parse_qs, urljoin, urlparse
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_plugin import (
+    CALENDAR_QUERY_MODE,
+    SERVICES_PROBE_QUERY_MODE,
+    ItaPlugin,
+)
+from plugins import ita_calendar_session as calendar_session
+from plugins.ita_calendar_query import (
+    AVAILABILITY_PATH,
+    CALENDAR_PATH,
+    NEXT_MONTH_CONTROL_SCRIPT,
+    CalendarGateError,
+    CalendarNextMonthUnavailableError,
+    CalendarProbeResult,
+    CalendarQueryScanResult,
+    click_next_month,
+    guard_calendar,
+    header_value as _header,
+    listen_once,
+    month_text as _month_text,
+    next_month_value as _next_month_value,
+    parse_availability_packet,
+    refresh_calendar,
+    require_plain_nonnegative_int as _require_plain_nonnegative_int,
+    same_origin_path as _same_origin_path,
+    validate_next_month_snapshot,
+)
+from plugins.ita_protocol import (
+    ItaProtocolError,
+    ItaRouteConfig,
+    resolve_route_config,
+)
+from tools.debug_ita_query import (
+    ItaDebugRoute,
+    _get_query_credentials,
+    _prepare_query_profile,
+    build_query_config,
+    resolve_debug_route,
+)
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    _env_text,
+    _text_for_log,
+    resolve_chrome_path,
+)
+from vs_types import AppointmentType, AvailabilityStatus, VSPlgConfig, VSQueryResult
+
+
+RESERVATION_URL = "https://prenotami.esteri.it/Reservation"
+OTP_PATH = "/BookingCalendar/GenerateOTP"
+QCAL_TOOL_CONTRACT_VERSION = "qcal1-calendar-soak-v11"
+QCAL_TOOL_SOURCE_PATHS = (
+    Path(__file__),
+    REPO_ROOT / "plugins" / "ita_calendar_session.py",
+    REPO_ROOT / "plugins" / "ita_calendar_query.py",
+    REPO_ROOT / "plugins" / "ita_plugin.py",
+    REPO_ROOT / "plugins" / "ita_protocol.py",
+    REPO_ROOT / "plugins" / "ita_calendar_book.py",
+    REPO_ROOT / "tools" / "debug_ita_soak.py",
+    REPO_ROOT / "toolkit" / "backoff.py",
+)
+QCAL_TOOL_SOURCE_FINGERPRINT = hashlib.sha256(
+    b"".join(path.read_bytes() for path in QCAL_TOOL_SOURCE_PATHS)
+).hexdigest()[:12]
+QCAL_MODE_ENV = "ITA_QCAL_MODE"
+QCAL_PRODUCTION_QUERY_ATTEMPTS = 2
+QCAL_QUERY_INTERVAL_SECONDS = 3
+QCAL_FORWARD_MONTHS_ENV = "ITA_QCAL_FORWARD_MONTHS"
+QCAL_FORWARD_MONTHS_DEFAULT = 1
+QCAL_FORWARD_MONTHS_MAX = 12
+QCAL_MONTH_CLICK_INTERVAL_SECONDS = 1.5
+SAFE_PREFLIGHT_DIAGNOSTIC_OUTCOMES = frozenset({"ready", "waiting", "rejected", "timeout", "read_failed"})
+FORM_REQUIRED_ENV_NAMES = (
+    "ITA_CALENDAR_LOOKAHEAD_MONTHS",
+    "ITA_BOOKING_TYPE_CONTROL_ID",
+    "ITA_BOOKING_TYPE_VALUE",
+    "ITA_BOOKING_TYPE_LABELS",
+    "ITA_PURPOSE_CONTROL_ID",
+    "ITA_PURPOSE_VALUE",
+    "ITA_PURPOSE_LABELS",
+)
+
+
+RESERVATION_SNAPSHOT_SCRIPT = r"""
+/* coordinate:ita-qcal-reservation-counts */
+const ids = ['dataTableReservations', 'dataTableReservationsWL'];
+const hasJQuery = Boolean(window.jQuery);
+const hasDataTables = Boolean(
+  hasJQuery && jQuery.fn && jQuery.fn.dataTable
+);
+const tableState = (id) => {
+  const table = document.getElementById(id);
+  if (!table) return {ready: false, count: null};
+  const initialized = hasDataTables &&
+    jQuery.fn.dataTable.isDataTable(table);
+  if (initialized) {
+    return {
+      ready: true,
+      count: jQuery('#' + id).DataTable().rows().count(),
+    };
+  }
+  const structurallyEmpty =
+    table.querySelectorAll('tbody tr').length === 0 &&
+    table.querySelectorAll('thead th').length === 0 &&
+    !table.classList.contains('dataTable') &&
+    !table.closest('.dataTables_wrapper');
+  return {
+    ready: structurallyEmpty,
+    count: structurallyEmpty ? 0 : null,
+  };
+};
+const reservations = tableState(ids[0]);
+const waitlist = tableState(ids[1]);
+return {
+  path: window.location.pathname,
+  authenticated: Boolean(document.querySelector('.app-menu')),
+  tableCount: ids.filter((id) => document.getElementById(id)).length,
+  ready: reservations.ready && waitlist.ready,
+  reservations: reservations.count,
+  waitlist: waitlist.count,
+};
+"""
+
+
+AVANTI_FAILURE_DIAGNOSTIC_SCRIPT = r"""
+/* coordinate:ita-qcal-avanti-failure-diagnostic */
+const isVisible = (element) => Boolean(
+  element &&
+  element.getClientRects().length > 0 &&
+  window.getComputedStyle(element).visibility !== 'hidden'
+);
+const otpInputs = document.querySelectorAll('#otp-input');
+const otpInvalid = document.getElementById('IdOtpInvalid');
+const bookingForm = document.getElementById('bookingForm');
+const avantiButtons = document.querySelectorAll('#btnAvanti');
+const turnstile = document.querySelectorAll(
+  'input[name="cf-turnstile-response"]'
+);
+const validationNodes = new Set([
+  ...document.querySelectorAll('.field-validation-error'),
+  ...document.querySelectorAll('.validation-summary-errors li'),
+  ...document.querySelectorAll('[aria-invalid="true"]'),
+]);
+const visibleValidationCount = Array.from(validationNodes).filter(
+  isVisible
+).length;
+const visibleConfirmCount = Array.from(
+  document.querySelectorAll('.jconfirm-content')
+).filter(isVisible).length;
+const resources = performance.getEntriesByType('resource');
+return {
+  path: window.location.pathname,
+  bookingFormPresent: Boolean(bookingForm),
+  otpInputCount: otpInputs.length,
+  otpValuePresent: Boolean(
+    otpInputs.length === 1 && String(otpInputs[0].value || '').trim()
+  ),
+  otpInvalidVisible: isVisible(otpInvalid),
+  avantiButtonCount: avantiButtons.length,
+  avantiDisabled:
+    avantiButtons.length === 1 ? avantiButtons[0].disabled : null,
+  turnstileCount: turnstile.length,
+  turnstileTokenPresent: Boolean(
+    turnstile.length === 1 && turnstile[0].value
+  ),
+  visibleValidationCount,
+  visibleConfirmCount,
+  finalRequestCount: resources.filter(
+    (entry) => entry.name.includes(
+      '/BookingCalendar/InsertNewBooking'
+    )
+  ).length,
+};
+"""
+
+
+from plugins.ita_calendar_session import (
+    BookingPreflightStage,
+    CalendarRequestAudit,
+    validate_otp_packet,
+    validate_avanti_packet,
+    validate_booking_preflight,
+    _booking_preflight_script,
+    _validate_preflight_except_dynamic_token,
+    _wait_for_calendar,
+    _element_or_fail,
+    _read_manual_otp,
+    _enter_otp,
+)
+
+
+class CalendarGateMode(str, Enum):
+    DISCOVERY_HORIZON = "discovery_horizon"
+    PRODUCTION_QUERY = "production_query"
+    CALENDAR_SOAK = "calendar_soak"
+
+
+class PositiveQueryEvidenceUnavailable(CalendarGateError):
+    """Natural inventory did not provide evidence for the positive gate."""
+
+
+
+
+def resolve_qcal_mode(env: Mapping[str, str]) -> CalendarGateMode:
+    raw = _env_text(env, QCAL_MODE_ENV) or CalendarGateMode.DISCOVERY_HORIZON.value
+    try:
+        return CalendarGateMode(raw)
+    except ValueError as exc:
+        raise CalendarGateError(
+            "ITA_QCAL_MODE must be discovery_horizon, production_query, or calendar_soak"
+        ) from exc
+
+
+def _safe_boolean_shape(value: object) -> dict[str, object]:
+    """Describe one boolean without serializing an unexpected value."""
+
+    is_boolean = isinstance(value, bool)
+    return {
+        "type": type(value).__name__,
+        "value": value if is_boolean else None,
+    }
+
+
+def _safe_nonnegative_int_shape(value: object) -> dict[str, object]:
+    """Describe a count without serializing an unexpected value."""
+
+    is_count = (
+        isinstance(value, int)
+        and not isinstance(value, bool)
+        and value >= 0
+    )
+    return {
+        "type": type(value).__name__,
+        "value": value if is_count else None,
+    }
+
+
+def _safe_http_status_shape(value: object) -> dict[str, object]:
+    """Describe a conventional HTTP status without leaking response data."""
+
+    is_status = (
+        isinstance(value, int)
+        and not isinstance(value, bool)
+        and 100 <= value <= 599
+    )
+    return {
+        "type": type(value).__name__,
+        "value": value if is_status else None,
+    }
+
+
+def _safe_path_category(
+    raw_url: object,
+    *,
+    booking_path: str,
+) -> str:
+    """Map a URL to one fixed category without returning its raw value."""
+
+    if not str(raw_url or "").strip():
+        return "missing"
+    normalized = urljoin("https://prenotami.esteri.it", str(raw_url))
+    try:
+        path, _ = _same_origin_path(normalized)
+    except CalendarGateError:
+        return "unexpected_origin"
+    if path == booking_path:
+        return "booking"
+    if path == CALENDAR_PATH:
+        return "calendar"
+    if path == "/Services":
+        return "services"
+    if path == "/UserArea":
+        return "user_area"
+    return "other_same_origin"
+
+
+def safe_avanti_failure_diagnostic(
+    packet: object,
+    raw: object,
+    *,
+    booking_path: str,
+) -> dict[str, object]:
+    """Return allowlisted AVANTI evidence without body, query, or form values."""
+
+    snapshot = raw if isinstance(raw, dict) else {}
+    response = getattr(packet, "response", None)
+    packet_url = getattr(packet, "url", "")
+    request_matches = False
+    try:
+        request_path, parsed_request = _same_origin_path(packet_url)
+        request_matches = (
+            str(getattr(packet, "method", "")).upper() == "POST"
+            and request_path == booking_path
+            and not parsed_request.query
+            and not parsed_request.fragment
+        )
+    except CalendarGateError:
+        pass
+
+    response_path = _safe_path_category(
+        getattr(response, "url", ""),
+        booking_path=booking_path,
+    )
+    location_path = _safe_path_category(
+        _header(getattr(response, "headers", {}), "location"),
+        booking_path=booking_path,
+    )
+    browser_path = _safe_path_category(
+        snapshot.get("path"),
+        booking_path=booking_path,
+    )
+    diagnostic = {
+        "contract": QCAL_TOOL_CONTRACT_VERSION,
+        "sourceFingerprint": QCAL_TOOL_SOURCE_FINGERPRINT,
+        "snapshotType": type(raw).__name__,
+        "bookingPostObserved": packet is not None,
+        "requestMatches": request_matches,
+        "responseStatus": _safe_http_status_shape(
+            getattr(response, "status", None)
+        ),
+        "responsePath": response_path,
+        "locationPath": location_path,
+        "browserPath": browser_path,
+        "bookingFormPresent": _safe_boolean_shape(
+            snapshot.get("bookingFormPresent")
+        ),
+        "otpValuePresent": _safe_boolean_shape(
+            snapshot.get("otpValuePresent")
+        ),
+        "otpInvalidVisible": _safe_boolean_shape(
+            snapshot.get("otpInvalidVisible")
+        ),
+        "avantiDisabled": _safe_boolean_shape(
+            snapshot.get("avantiDisabled")
+        ),
+        "turnstileReady": _safe_boolean_shape(
+            snapshot.get("turnstileTokenPresent")
+        ),
+        "visibleValidationCount": _safe_nonnegative_int_shape(
+            snapshot.get("visibleValidationCount")
+        ),
+        "visibleConfirmCount": _safe_nonnegative_int_shape(
+            snapshot.get("visibleConfirmCount")
+        ),
+        "finalRequestCount": _safe_nonnegative_int_shape(
+            snapshot.get("finalRequestCount")
+        ),
+    }
+    if packet is None:
+        outcome = "booking_post_not_observed"
+    elif browser_path == "booking":
+        outcome = "booking_form_returned"
+    elif response_path == "calendar" and browser_path != "calendar":
+        outcome = "calendar_response_not_rendered"
+    else:
+        outcome = "unexpected_transition"
+    return {"outcome": outcome, **diagnostic}
+
+
+def safe_preflight_diagnostic(
+    raw: object,
+    *,
+    stage: BookingPreflightStage,
+    outcome: str,
+) -> dict[str, object]:
+    """Return an allowlisted diagnostic with no token or form values."""
+
+    snapshot = raw if isinstance(raw, dict) else {}
+    return {
+        "contract": QCAL_TOOL_CONTRACT_VERSION,
+        "sourceFingerprint": QCAL_TOOL_SOURCE_FINGERPRINT,
+        "outcome": (
+            outcome
+            if outcome in SAFE_PREFLIGHT_DIAGNOSTIC_OUTCOMES
+            else "invalid"
+        ),
+        "stage": (
+            stage.value
+            if isinstance(stage, BookingPreflightStage)
+            else "invalid"
+        ),
+        "snapshotType": type(raw).__name__,
+        "otpDisabled": _safe_boolean_shape(
+            snapshot.get("otpDisabled")
+        ),
+        "otpValuePresent": _safe_boolean_shape(
+            snapshot.get("otpValuePresent")
+        ),
+        "avantiDisabled": _safe_boolean_shape(
+            snapshot.get("avantiDisabled")
+        ),
+        "turnstileReady": _safe_boolean_shape(
+            snapshot.get("turnstileTokenPresent")
+        ),
+    }
+
+
+def safe_next_month_diagnostic(raw: object) -> dict[str, object]:
+    """Return only fixed-shape evidence for the Calendar month control."""
+
+    snapshot = raw if isinstance(raw, dict) else {}
+    return {
+        "contract": QCAL_TOOL_CONTRACT_VERSION,
+        "sourceFingerprint": QCAL_TOOL_SOURCE_FINGERPRINT,
+        "snapshotType": type(raw).__name__,
+        "pathMatches": _safe_boolean_shape(
+            snapshot.get("pathMatches")
+        ),
+        "candidateCount": _safe_nonnegative_int_shape(
+            snapshot.get("candidateCount")
+        ),
+        "actionableCount": _safe_nonnegative_int_shape(
+            snapshot.get("actionableCount")
+        ),
+        "clicked": _safe_boolean_shape(snapshot.get("clicked")),
+    }
+
+
+def _print_preflight_diagnostic(
+    raw: object,
+    *,
+    stage: BookingPreflightStage,
+    outcome: str,
+) -> None:
+    print(
+        "ITA_QCAL_PREFLIGHT_DIAGNOSTIC="
+        + json.dumps(
+            safe_preflight_diagnostic(
+                raw,
+                stage=stage,
+                outcome=outcome,
+            ),
+            sort_keys=True,
+        ),
+        flush=True,
+    )
+
+
+def _print_next_month_diagnostic(raw: object) -> None:
+    print(
+        "ITA_QCAL_NEXT_MONTH_DIAGNOSTIC="
+        + json.dumps(
+            safe_next_month_diagnostic(raw),
+            sort_keys=True,
+        ),
+        flush=True,
+    )
+
+
+def _print_avanti_failure_diagnostic(
+    page: object,
+    packet: object,
+    *,
+    booking_path: str,
+) -> dict[str, object]:
+    """Print one bounded allowlist even when the page snapshot itself fails."""
+
+    try:
+        raw = page.run_js(AVANTI_FAILURE_DIAGNOSTIC_SCRIPT)
+    except Exception:
+        raw = None
+    diagnostic = safe_avanti_failure_diagnostic(
+        packet,
+        raw,
+        booking_path=booking_path,
+    )
+    print(
+        "ITA_QCAL_AVANTI_FAILURE_DIAGNOSTIC="
+        + json.dumps(diagnostic, sort_keys=True),
+        flush=True,
+    )
+    return diagnostic
+
+
+@dataclass(frozen=True, slots=True)
+class ReservationSnapshot:
+    reservations: int
+    waitlist: int
+
+    def __post_init__(self) -> None:
+        _require_plain_nonnegative_int(self.reservations, "reservations")
+        _require_plain_nonnegative_int(self.waitlist, "waitlist")
+
+    @property
+    def total(self) -> int:
+        return self.reservations + self.waitlist
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarMonthScanResult:
+    probes: tuple[CalendarProbeResult, ...]
+    requested_forward_months: int
+    stop_reason: str
+
+    def __post_init__(self) -> None:
+        if (
+            isinstance(self.requested_forward_months, bool)
+            or not isinstance(self.requested_forward_months, int)
+            or not 1 <= self.requested_forward_months <= QCAL_FORWARD_MONTHS_MAX
+        ):
+            raise CalendarGateError(
+                "requested_forward_months must be between 1 and 12"
+            )
+        if not self.probes or any(
+            not isinstance(probe, CalendarProbeResult)
+            for probe in self.probes
+        ):
+            raise CalendarGateError(
+                "Calendar month scan requires parsed probe results"
+            )
+        if len(self.probes) > self.requested_forward_months + 1:
+            raise CalendarGateError(
+                "Calendar month scan exceeded its forward-month limit"
+            )
+        for previous, current in zip(self.probes, self.probes[1:]):
+            if current.selected_month != _next_month_value(
+                previous.selected_month
+            ):
+                raise CalendarGateError(
+                    "Calendar request did not advance exactly one month"
+                )
+        allowed_stop_reasons = {
+            "forward_limit_reached",
+            "next_control_unavailable",
+        }
+        if self.stop_reason not in allowed_stop_reasons:
+            raise CalendarGateError(
+                "Calendar month scan used an unknown stop reason"
+            )
+        if (
+            self.stop_reason == "forward_limit_reached"
+            and len(self.probes) != self.requested_forward_months + 1
+        ):
+            raise CalendarGateError(
+                "Calendar month scan ended before its forward limit"
+            )
+
+    @property
+    def availability_requests(self) -> int:
+        return len(self.probes)
+
+    @property
+    def forward_clicks(self) -> int:
+        return len(self.probes) - 1
+
+    @property
+    def earliest_available_date(self) -> date | None:
+        return min(
+            (
+                day.day
+                for probe in self.probes
+                for day in probe.days
+                if day.is_available
+            ),
+            default=None,
+        )
+
+    def safe_dict(self) -> dict[str, object]:
+        earliest = self.earliest_available_date
+        return {
+            "requestedForwardMonths": self.requested_forward_months,
+            "forwardClicks": self.forward_clicks,
+            "availabilityRequests": self.availability_requests,
+            "startMonth": _month_text(self.probes[0].selected_month),
+            "furthestMonth": _month_text(self.probes[-1].selected_month),
+            "monthsWithAvailability": sum(
+                probe.available_count > 0 for probe in self.probes
+            ),
+            "earliestAvailableDate": (
+                earliest.isoformat() if earliest is not None else None
+            ),
+            "stopReason": self.stop_reason,
+            "nextControlUnavailable": (
+                self.stop_reason == "next_control_unavailable"
+            ),
+        }
+
+
+@dataclass(frozen=True, slots=True)
+class CalendarGateEvidence:
+    before: ReservationSnapshot
+    after: ReservationSnapshot
+    otp_requests: int
+    avanti_posts: int
+    availability_requests: int
+    final_requests: int
+    calendar_ready: bool
+
+    def __post_init__(self) -> None:
+        for field_name in (
+            "otp_requests",
+            "avanti_posts",
+            "availability_requests",
+            "final_requests",
+        ):
+            _require_plain_nonnegative_int(
+                getattr(self, field_name),
+                field_name,
+            )
+        if not isinstance(self.calendar_ready, bool):
+            raise CalendarGateError("calendar_ready must be a boolean")
+
+    @property
+    def passed(self) -> bool:
+        return (
+            self.before == self.after
+            and self.otp_requests == 1
+            and self.avanti_posts == 1
+            and self.availability_requests >= 2
+            and self.final_requests == 0
+            and self.calendar_ready
+        )
+
+    def safe_dict(self) -> dict[str, object]:
+        return {
+            "reservationCountBefore": self.before.reservations,
+            "waitlistCountBefore": self.before.waitlist,
+            "reservationCountAfter": self.after.reservations,
+            "waitlistCountAfter": self.after.waitlist,
+            "otpRequests": self.otp_requests,
+            "avantiPosts": self.avanti_posts,
+            "availabilityRequests": self.availability_requests,
+            "finalRequests": self.final_requests,
+            "calendarReady": self.calendar_ready,
+            "passed": self.passed,
+        }
+
+
+class OneShotAction:
+    """An in-memory at-most-once guard that burns before the action starts."""
+
+    def __init__(self, name: str) -> None:
+        self.name = name
+        self.attempted = False
+
+    def run(self, action: Callable[[], Any]) -> Any:
+        if self.attempted:
+            raise CalendarGateError(f"{self.name} was already attempted")
+        self.attempted = True
+        return action()
+
+
+def _required_env_text(env: Mapping[str, str], name: str) -> str:
+    value = _env_text(env, name)
+    if not value:
+        raise CalendarGateError(f"{name} is required for Q-CAL-1")
+    return value
+
+
+def resolve_qcal_forward_months(env: Mapping[str, str]) -> int:
+    """Resolve the debug-only bound without changing route semantics."""
+
+    raw = _env_text(env, QCAL_FORWARD_MONTHS_ENV)
+    if not raw:
+        return QCAL_FORWARD_MONTHS_DEFAULT
+    try:
+        value = int(raw)
+    except ValueError as exc:
+        raise CalendarGateError(
+            f"{QCAL_FORWARD_MONTHS_ENV} must be an integer between 1 and 12"
+        ) from exc
+    if not 1 <= value <= QCAL_FORWARD_MONTHS_MAX:
+        raise CalendarGateError(
+            f"{QCAL_FORWARD_MONTHS_ENV} must be between 1 and 12"
+        )
+    return value
+
+
+def _split_labels(raw: str, name: str) -> list[str]:
+    labels = [label.strip() for label in raw.split("|") if label.strip()]
+    if not labels:
+        raise CalendarGateError(f"{name} must contain at least one label")
+    return labels
+
+
+def build_calendar_gate_config(
+    env: Mapping[str, str],
+    *,
+    username: str,
+    password: str,
+    persistent_profile_path: Path | None = None,
+    route: ItaDebugRoute | None = None,
+) -> VSPlgConfig:
+    """Build one explicit live-route config while keeping production mode off."""
+
+    resolved_debug_route = route or resolve_debug_route(env)
+    values = {
+        name: _required_env_text(env, name)
+        for name in FORM_REQUIRED_ENV_NAMES
+    }
+    try:
+        lookahead_months = int(values["ITA_CALENDAR_LOOKAHEAD_MONTHS"])
+    except ValueError as exc:
+        raise CalendarGateError(
+            "ITA_CALENDAR_LOOKAHEAD_MONTHS must be a positive integer"
+        ) from exc
+
+    config = build_query_config(
+        env,
+        username=username,
+        password=password,
+        persistent_profile_path=persistent_profile_path,
+        route=resolved_debug_route,
+    )
+    live_route = {
+        "service_id": resolved_debug_route.service_id,
+        "capability": "single_schengen_tourism",
+        "calendar_scan": {"lookahead_months": lookahead_months},
+        "form": {
+            "booking_type_control_id": values[
+                "ITA_BOOKING_TYPE_CONTROL_ID"
+            ],
+            "booking_type_value": values["ITA_BOOKING_TYPE_VALUE"],
+            "booking_type_labels": _split_labels(
+                values["ITA_BOOKING_TYPE_LABELS"],
+                "ITA_BOOKING_TYPE_LABELS",
+            ),
+            "purpose_control_id": values["ITA_PURPOSE_CONTROL_ID"],
+            "purpose_value": values["ITA_PURPOSE_VALUE"],
+            "purpose_labels": _split_labels(
+                values["ITA_PURPOSE_LABELS"],
+                "ITA_PURPOSE_LABELS",
+            ),
+        },
+    }
+    config.free_config["apt_configs"] = {
+        resolved_debug_route.routing_key: live_route,
+    }
+    try:
+        resolve_route_config(
+            config.free_config["apt_configs"],
+            resolved_debug_route.routing_key,
+        )
+    except ItaProtocolError as exc:
+        raise CalendarGateError(
+            f"Italy Q-CAL route configuration rejected ({exc.code})"
+        ) from exc
+    return config
+
+
+
+
+
+
+
+
+
+
+
+
+def wait_for_booking_preflight(page, *, script, stage=BookingPreflightStage.BEFORE_OTP_SEND, timeout=120):
+    return calendar_session.wait_for_booking_preflight(
+        page, script=script, stage=stage, timeout=timeout,
+        diagnostic=_print_preflight_diagnostic,
+    )
+
+
+def read_reservation_snapshot(
+    page: object,
+    *,
+    timeout: float = 20,
+    settle_seconds: float = 5,
+) -> ReservationSnapshot:
+    """Read both row counts after the page has had time to initialize tables."""
+
+    tab = page.new_tab(RESERVATION_URL)
+    try:
+        tab.wait.doc_loaded()
+        deadline = time.monotonic() + timeout
+        settle_deadline = time.monotonic() + settle_seconds
+        last_raw: object = None
+        last_snapshot: ReservationSnapshot | None = None
+        stable_samples = 0
+        while time.monotonic() < deadline:
+            last_raw = tab.run_js(RESERVATION_SNAPSHOT_SCRIPT)
+            if (
+                isinstance(last_raw, dict)
+                and last_raw.get("path") == "/Reservation"
+                and last_raw.get("authenticated") is True
+                and last_raw.get("tableCount") == 2
+                and last_raw.get("ready") is True
+                and time.monotonic() >= settle_deadline
+            ):
+                snapshot = ReservationSnapshot(
+                    reservations=last_raw.get("reservations"),
+                    waitlist=last_raw.get("waitlist"),
+                )
+                if snapshot == last_snapshot:
+                    stable_samples += 1
+                else:
+                    last_snapshot = snapshot
+                    stable_samples = 1
+                if stable_samples >= 2:
+                    return snapshot
+            time.sleep(0.25)
+        raise CalendarGateError(
+            "Reservation DataTables did not become ready before timeout"
+        )
+    finally:
+        tab.close()
+
+
+def _calendar_guard(page: object) -> dict[str, object]:
+    return guard_calendar(page)
+
+
+
+
+
+
+
+
+
+
+def _click_next_month(page: object, *, timeout: float = 10) -> None:
+    click_next_month(
+        page,
+        timeout=timeout,
+        diagnostic=_print_next_month_diagnostic,
+    )
+
+
+def scan_calendar_horizon(
+    page: object,
+    *,
+    forward_months: int,
+) -> CalendarMonthScanResult:
+    """Probe the initial month and a bounded number of native next-month pages."""
+
+    if (
+        isinstance(forward_months, bool)
+        or not isinstance(forward_months, int)
+        or not 1 <= forward_months <= QCAL_FORWARD_MONTHS_MAX
+    ):
+        raise CalendarGateError("forward_months must be between 1 and 12")
+
+    initial_packet = listen_once(
+        page,
+        target=AVAILABILITY_PATH,
+        method="POST",
+        action=lambda: _refresh_calendar(page),
+        timeout=30,
+    )
+    probes = [parse_availability_packet(initial_packet)]
+    _calendar_guard(page)
+    print(
+        "ITA_QCAL_PROBE index=0 "
+        f"items={probes[0].item_count} "
+        f"available={probes[0].available_count}"
+    )
+
+    stop_reason = "forward_limit_reached"
+    for index in range(1, forward_months + 1):
+        time.sleep(QCAL_MONTH_CLICK_INTERVAL_SECONDS)
+        try:
+            packet = listen_once(
+                page,
+                target=AVAILABILITY_PATH,
+                method="POST",
+                action=lambda: _click_next_month(page),
+                timeout=30,
+            )
+        except CalendarNextMonthUnavailableError:
+            stop_reason = "next_control_unavailable"
+            break
+        probe = parse_availability_packet(packet)
+        if probe.selected_month != _next_month_value(
+            probes[-1].selected_month
+        ):
+            raise CalendarGateError(
+                "Calendar request did not advance exactly one month"
+            )
+        probes.append(probe)
+        _calendar_guard(page)
+        print(
+            f"ITA_QCAL_PROBE index={index} "
+            f"items={probe.item_count} available={probe.available_count}"
+        )
+
+    result = CalendarMonthScanResult(
+        probes=tuple(probes),
+        requested_forward_months=forward_months,
+        stop_reason=stop_reason,
+    )
+    print(
+        "ITA_QCAL_MONTH_SCAN_RESULT="
+        + json.dumps(result.safe_dict(), sort_keys=True)
+    )
+    return result
+
+
+def _refresh_calendar(page: object) -> None:
+    refresh_calendar(page)
+
+
+def validate_production_query_result(
+    result: object,
+    scan: object,
+    *,
+    apt_type: AppointmentType,
+    lookahead_months: int,
+) -> dict[str, object]:
+    """Compare the public VFS-style result with this call's real scan evidence."""
+
+    if not isinstance(result, VSQueryResult):
+        raise CalendarGateError("Production Query did not return VSQueryResult")
+    if not isinstance(scan, CalendarQueryScanResult):
+        raise CalendarGateError("Production Query did not expose fresh scan evidence")
+    if scan.lookahead_months != lookahead_months:
+        raise CalendarGateError("Production Query used a different scan horizon")
+    if result.apt_type != apt_type:
+        raise CalendarGateError("Production Query returned a different route")
+
+    earliest = scan.earliest_available_date
+    positive = earliest is not None
+    expected_date = (
+        datetime.combine(earliest, datetime.min.time())
+        if positive else None
+    )
+    expected_status = (
+        AvailabilityStatus.Available if positive
+        else AvailabilityStatus.NoneAvailable
+    )
+    if (
+        result.success is not positive
+        or result.availability_status is not expected_status
+        or result.earliest_date != expected_date
+        or len(result.availability) != int(positive)
+    ):
+        raise CalendarGateError("Production Query result disagrees with scan evidence")
+    if positive and (
+        result.availability[0].date != expected_date
+        or result.availability[0].times != []
+    ):
+        raise CalendarGateError("Production Query must publish one earliest date without times")
+
+    # Exercise the existing Sentinel serialization, without publishing to Redis.
+    snapshot = result.to_snapshot_payload()
+    expected_snapshot = {
+        "routing_key": apt_type.routing_key,
+        "country": apt_type.country,
+        "city": apt_type.city,
+        "visa_type": apt_type.visa_type,
+        "availability_status": expected_status.value,
+        "earliest_date": earliest.isoformat() if positive else None,
+        "availability": [{"date": earliest.isoformat()}] if positive else [],
+        "snapshot_source": "worker",
+    }
+    if (
+        set(snapshot) != set(expected_snapshot) | {"snapshot_at"}
+        or any(snapshot.get(key) != value for key, value in expected_snapshot.items())
+        or not isinstance(snapshot.get("snapshot_at"), str)
+    ):
+        raise CalendarGateError("Production Query snapshot contract changed")
+
+    return {
+        "lookaheadMonths": lookahead_months,
+        "scannedMonths": scan.scanned_months,
+        "months": [
+            {"month": _month_text(probe.selected_month), "positiveDays": probe.available_count}
+            for probe in scan.probes
+        ],
+        "stopReason": scan.stop_reason,
+        "success": result.success,
+        "availabilityStatus": result.availability_status.value,
+        "earliestDate": earliest.isoformat() if positive else None,
+        "availabilityCount": len(result.availability),
+        "timesCount": 0,
+        "snapshotVerified": True,
+    }
+
+
+def _query_request_delta(
+    before: Mapping[str, int],
+    after: Mapping[str, int],
+    *,
+    expected_availability: int,
+) -> dict[str, int]:
+    keys = {"otpRequests", "avantiPosts", "availabilityRequests", "finalRequests"}
+    if set(before) != keys or set(after) != keys:
+        raise CalendarGateError("Production Query request counters changed shape")
+    delta = {}
+    for key in keys:
+        previous = _require_plain_nonnegative_int(before[key], key)
+        current = _require_plain_nonnegative_int(after[key], key)
+        delta[key] = _require_plain_nonnegative_int(current - previous, key)
+    if (
+        delta["otpRequests"] != 0
+        or delta["avantiPosts"] != 0
+        or delta["finalRequests"] != 0
+        or delta["availabilityRequests"] != expected_availability
+    ):
+        raise CalendarGateError("Production Query exceeded its read-only request contract")
+    return delta
+
+
+def run_production_query_acceptance(
+    plugin: ItaPlugin,
+    route: ItaDebugRoute,
+    request_audit: CalendarRequestAudit,
+) -> tuple[dict[str, object], ...]:
+    """Call the real Query twice; never replace its scanner or recreate Session."""
+
+    free_config = plugin.free_config
+    if (
+        free_config.get("query_mode") != SERVICES_PROBE_QUERY_MODE
+        or free_config.get("final_submit_enabled") is not False
+    ):
+        raise CalendarGateError("Production Query acceptance requires the safe debug config")
+    protocol_route = resolve_route_config(free_config["apt_configs"], route.routing_key)
+    if protocol_route.calendar_scan is None:
+        raise CalendarGateError("Production Query acceptance requires a Calendar route")
+    page = plugin.page
+    reports = []
+    start_month = None
+    free_config["query_mode"] = CALENDAR_QUERY_MODE
+    try:
+        for attempt in range(1, QCAL_PRODUCTION_QUERY_ATTEMPTS + 1):
+            if attempt > 1:
+                time.sleep(QCAL_QUERY_INTERVAL_SECONDS)
+            print(
+                "ITA_QCAL_PRODUCTION_QUERY_START "
+                f"attempt={attempt} total={QCAL_PRODUCTION_QUERY_ATTEMPTS}",
+                flush=True,
+            )
+            before = request_audit.settled_snapshot()
+            previous_scan = getattr(plugin, "last_calendar_query_scan", None)
+            apt_type = route.appointment_type()
+            result = plugin.query(apt_type)
+            scan = getattr(plugin, "last_calendar_query_scan", None)
+            if scan is previous_scan:
+                raise CalendarGateError("Production Query reused stale scan evidence")
+            if plugin.page is not page or plugin.free_config is not free_config:
+                raise CalendarGateError("Production Query changed its prepared Session")
+            report = validate_production_query_result(
+                result,
+                scan,
+                apt_type=apt_type,
+                lookahead_months=protocol_route.calendar_scan.lookahead_months,
+            )
+            current_start = scan.probes[0].selected_month
+            if start_month is not None and current_start != start_month:
+                raise CalendarGateError("Repeated Query did not restart from the same initial month")
+            start_month = current_start
+            after = request_audit.settled_snapshot()
+            report["queryRequestDelta"] = _query_request_delta(
+                before,
+                after,
+                expected_availability=scan.scanned_months,
+            )
+            _calendar_guard(page)
+            report["attempt"] = attempt
+            reports.append(report)
+            print(
+                "ITA_QCAL_PRODUCTION_QUERY_RESULT="
+                + json.dumps(report, sort_keys=True),
+                flush=True,
+            )
+    finally:
+        # Do not call set_config(): it would erase the prepared-route proof.
+        # This is an in-memory mode switch, never a production config write.
+        free_config["query_mode"] = SERVICES_PROBE_QUERY_MODE
+    return tuple(reports)
+
+
+def run_calendar_gate(
+    env: Mapping[str, str],
+    *,
+    otp_reader: Callable[[], str] = _read_manual_otp,
+) -> int:
+    print(
+        "ITA_QCAL_TOOL_CONTRACT "
+        f"version={QCAL_TOOL_CONTRACT_VERSION} "
+        f"source_sha256={QCAL_TOOL_SOURCE_FINGERPRINT}",
+        flush=True,
+    )
+    mode = resolve_qcal_mode(env)
+    if mode is CalendarGateMode.CALENDAR_SOAK:
+        # Validate limits before any credentials, browser, OTP, or form action.
+        from tools.debug_ita_soak import calendar_soak_limits
+        calendar_soak_limits(env)
+    forward_months = (
+        resolve_qcal_forward_months(env)
+        if mode is CalendarGateMode.DISCOVERY_HORIZON else None
+    )
+    route = resolve_debug_route(env)
+    chrome_path = resolve_chrome_path(env)
+    os.environ["CHROME_BIN"] = str(chrome_path)
+    username, password = _get_query_credentials(env, non_interactive=False)
+    profile_path = _prepare_query_profile(username)
+    config = build_calendar_gate_config(
+        env,
+        username=username,
+        password=password,
+        persistent_profile_path=profile_path,
+        route=route,
+    )
+    protocol_route = resolve_route_config(
+        config.free_config["apt_configs"],
+        route.routing_key,
+    )
+    booking_path = f"/Services/Booking/{protocol_route.service_id}"
+    print(
+        f"ITA_QCAL_MODE mode={mode.value} "
+        f"lookahead_months={protocol_route.calendar_scan.lookahead_months} "
+        f"query_attempts={QCAL_PRODUCTION_QUERY_ATTEMPTS if mode is CalendarGateMode.PRODUCTION_QUERY else 0}",
+        flush=True,
+    )
+
+    plugin = ItaPlugin(group_id="ita-qcal-gate")
+    plugin.set_log(lambda message: print(message, flush=True))
+    plugin.set_config(config)
+    otp_guard = OneShotAction("OTP")
+    avanti_guard = OneShotAction("AVANTI")
+    cleanup_error: Exception | None = None
+    request_audit: CalendarRequestAudit | None = None
+    exit_code = 0
+
+    try:
+        plugin.create_session()
+        if mode in {CalendarGateMode.PRODUCTION_QUERY, CalendarGateMode.CALENDAR_SOAK}:
+            request_audit = CalendarRequestAudit(
+                plugin.page, include_time_slots=mode is CalendarGateMode.CALENDAR_SOAK,
+            )
+            request_audit.start()
+        before = read_reservation_snapshot(plugin.page)
+        print(
+            "ITA_QCAL_RESERVATION_BEFORE "
+            f"reservations={before.reservations} waitlist={before.waitlist}"
+        )
+
+        entry = plugin.query(route.appointment_type())
+        if not entry.success:
+            if mode is CalendarGateMode.PRODUCTION_QUERY:
+                raise PositiveQueryEvidenceUnavailable(
+                    "Service currently has no entry; positive Query gate was not exercised"
+                )
+            raise CalendarGateError(
+                "Configured service did not reach the booking form"
+            )
+        preflight_script = _booking_preflight_script(
+            protocol_route,
+            booking_path,
+        )
+        wait_for_booking_preflight(
+            plugin.page,
+            script=preflight_script,
+            stage=BookingPreflightStage.BEFORE_OTP_SEND,
+        )
+
+        otp_packet = otp_guard.run(
+            lambda: listen_once(
+                plugin.page,
+                target=OTP_PATH,
+                method="GET",
+                action=lambda: plugin.mouse.human_click_ele(
+                    _element_or_fail(plugin.page, "#otp-send")
+                ),
+                timeout=30,
+            )
+        )
+        validate_otp_packet(
+            otp_packet,
+            service_id=protocol_route.service_id,
+        )
+        print("ITA_QCAL_OTP_SENT requests=1")
+
+        otp = otp_reader()
+        _enter_otp(plugin, otp)
+        del otp
+        wait_for_booking_preflight(
+            plugin.page,
+            script=preflight_script,
+            stage=BookingPreflightStage.AFTER_OTP_SEND,
+        )
+
+        plugin.page.set.auto_handle_alert(accept=True)
+        avanti_packet = None
+        try:
+            avanti_packet = avanti_guard.run(
+                lambda: listen_once(
+                    plugin.page,
+                    target=booking_path,
+                    method="POST",
+                    action=lambda: plugin.mouse.human_click_ele(
+                        _element_or_fail(plugin.page, "#btnAvanti")
+                    ),
+                    timeout=30,
+                )
+            )
+            print("ITA_QCAL_AVANTI_POST_OBSERVED requests=1")
+            _wait_for_calendar(plugin.page)
+            transition_mode = validate_avanti_packet(
+                avanti_packet,
+                booking_path=booking_path,
+                final_page_url=str(plugin.page.url or ""),
+            )
+            plugin._record_calendar_query_prepared_route(protocol_route)
+        except Exception:
+            _print_avanti_failure_diagnostic(
+                plugin.page,
+                avanti_packet,
+                booking_path=booking_path,
+            )
+            raise
+        finally:
+            if mode is CalendarGateMode.CALENDAR_SOAK:
+                plugin.page.set.auto_handle_alert(accept=False)
+        print(f"ITA_QCAL_AVANTI_TRANSITION mode={transition_mode}")
+        first_guard = _calendar_guard(plugin.page)
+        print("ITA_QCAL_CALENDAR_READY avanti_posts=1 final_requests=0")
+        if mode is CalendarGateMode.CALENDAR_SOAK:
+            # Transfer ownership, including cleanup, to the existing soak loop.
+            # Never leave alert auto-accept enabled during monitoring/recovery.
+            from tools.debug_ita_soak import run_prepared_calendar_soak
+            owned_plugin, owned_audit = plugin, request_audit
+            plugin, request_audit = None, None
+            return run_prepared_calendar_soak(
+                env, plugin=owned_plugin, route=route,
+                request_audit=owned_audit, before=before,
+            )
+
+        production_reports = ()
+        if mode is CalendarGateMode.PRODUCTION_QUERY:
+            preparation_counts = request_audit.settled_snapshot()
+            if (
+                preparation_counts["otpRequests"] != 1
+                or preparation_counts["avantiPosts"] != 1
+                or preparation_counts["finalRequests"] != 0
+            ):
+                raise CalendarGateError("Calendar preparation exceeded its one-shot request contract")
+            production_reports = run_production_query_acceptance(plugin, route, request_audit)
+            availability_requests = sum(
+                report["queryRequestDelta"]["availabilityRequests"]
+                for report in production_reports
+            )
+        else:
+            scan_result = scan_calendar_horizon(
+                plugin.page,
+                forward_months=forward_months,
+            )
+            availability_requests = scan_result.availability_requests
+            print(
+                "ITA_QCAL_MONTH_NAVIGATION_VERIFIED "
+                f"forward_clicks={scan_result.forward_clicks}"
+            )
+        last_guard = _calendar_guard(plugin.page)
+
+        after = read_reservation_snapshot(plugin.page)
+        print(
+            "ITA_QCAL_RESERVATION_AFTER "
+            f"reservations={after.reservations} waitlist={after.waitlist}"
+        )
+        final_requests = max(
+            first_guard["finalRequestCount"],
+            last_guard["finalRequestCount"],
+        )
+        observed_counts = request_audit.settled_snapshot() if request_audit is not None else None
+        if observed_counts is not None:
+            final_requests = max(final_requests, observed_counts["finalRequests"])
+        evidence = CalendarGateEvidence(
+            before=before,
+            after=after,
+            otp_requests=observed_counts["otpRequests"] if observed_counts is not None else 1,
+            avanti_posts=observed_counts["avantiPosts"] if observed_counts is not None else 1,
+            availability_requests=availability_requests,
+            final_requests=final_requests,
+            calendar_ready=True,
+        )
+        gate_result = evidence.safe_dict()
+        prefix = "ITA_QCAL_GATE_RESULT="
+        if mode is CalendarGateMode.PRODUCTION_QUERY:
+            positive_queries = sum(report["success"] for report in production_reports)
+            gate_result.update({
+                "mode": mode.value,
+                "queryAttempts": len(production_reports),
+                "positiveQueries": positive_queries,
+                "passed": (
+                    evidence.passed
+                    and len(production_reports) == QCAL_PRODUCTION_QUERY_ATTEMPTS
+                    and positive_queries > 0
+                ),
+            })
+            prefix = "ITA_QCAL_PRODUCTION_QUERY_GATE_RESULT="
+        print(prefix + json.dumps(gate_result, sort_keys=True), flush=True)
+        if (
+            mode is CalendarGateMode.PRODUCTION_QUERY
+            and len(production_reports) != QCAL_PRODUCTION_QUERY_ATTEMPTS
+        ):
+            raise CalendarGateError("Production gate requires exactly two Query calls")
+        if not evidence.passed:
+            raise CalendarGateError("Q-CAL-1 evidence did not pass")
+        if mode is CalendarGateMode.PRODUCTION_QUERY and not positive_queries:
+            raise PositiveQueryEvidenceUnavailable(
+                "Both Query calls completed without positive inventory; positive gate remains open"
+            )
+    except PositiveQueryEvidenceUnavailable as exc:
+        print(f"ITA_QCAL_PRODUCTION_QUERY_NOT_READY message={_text_for_log(exc)}", flush=True)
+        exit_code = 2
+    except (CalendarGateError, DebugConfigurationError) as exc:
+        print(
+            f"ITA_QCAL_GATE_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        exit_code = 1
+    except Exception as exc:
+        print(
+            f"ITA_QCAL_GATE_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        exit_code = 1
+    finally:
+        if request_audit is not None:
+            try:
+                request_audit.stop()
+            except Exception as exc:
+                cleanup_error = exc
+                print(
+                    "ITA_QCAL_AUDIT_CLEANUP_FAILED "
+                    f"type={type(exc).__name__} message={_text_for_log(exc)}",
+                    file=sys.stderr,
+                )
+        try:
+            if plugin is not None:
+                plugin.cleanup()
+                print("ITA_QCAL_GATE_CLEANUP_OK")
+        except Exception as exc:
+            cleanup_error = exc
+            print(
+                f"ITA_QCAL_GATE_CLEANUP_FAILED type={type(exc).__name__} "
+                f"message={_text_for_log(exc)}",
+                file=sys.stderr,
+            )
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def main() -> int:
+    return run_calendar_gate(os.environ)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 300 - 0
tools/debug_ita_monitor.py

@@ -0,0 +1,300 @@
+#!/usr/bin/env python3
+"""Run a bounded local Italy Query monitor with no booking side effects."""
+
+from __future__ import annotations
+
+import argparse
+import os
+import random
+import sys
+import time
+from pathlib import Path
+from typing import Callable, Mapping
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_plugin import ItaPlugin
+from tools.debug_ita_query import (
+    _get_query_credentials,
+    _is_nonempty_query_result,
+    _is_weak_entry_signal,
+    _popup_text_for_log,
+    _prepare_query_profile,
+    _print_booking_form_structure,
+    _print_failure_context,
+    build_query_config,
+    resolve_debug_route,
+)
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    resolve_chrome_path,
+)
+from tools.ita_local_handoff import (
+    ITA_LOCAL_SIGNAL_TTL_SECONDS,
+    publish_local_weak_signal,
+)
+from vs_types import BizLogicError
+
+
+MIN_SAFE_WAIT_SECONDS = 60
+DEFAULT_MAX_WAIT_SECONDS = 300
+DEFAULT_MAX_PROBES = 10
+MAX_ALLOWED_PROBES = 100
+
+
+class _MonitorCancelled(Exception):
+    """Internal control flow for a clean Ctrl+C."""
+
+
+def _validate_monitor_limits(
+    *,
+    min_wait: int,
+    max_wait: int,
+    max_probes: int,
+) -> None:
+    if min_wait < MIN_SAFE_WAIT_SECONDS:
+        raise DebugConfigurationError(
+            f"min_wait must be at least {MIN_SAFE_WAIT_SECONDS} seconds"
+        )
+    if max_wait < min_wait:
+        raise DebugConfigurationError("max_wait must be greater than min_wait")
+    if not 1 <= max_probes <= MAX_ALLOWED_PROBES:
+        raise DebugConfigurationError(
+            f"max_probes must be between 1 and {MAX_ALLOWED_PROBES}"
+        )
+
+
+def run_monitor(
+    env: Mapping[str, str],
+    *,
+    apply: bool,
+    non_interactive: bool,
+    min_wait: int,
+    max_wait: int,
+    max_probes: int,
+    publish_local_signal: bool = False,
+    signal_publisher: Callable[[], object] | None = None,
+    randint: Callable[[int, int], int] = random.randint,
+    sleep: Callable[[float], None] = time.sleep,
+) -> int:
+    route = resolve_debug_route(env)
+    route_log = (
+        f"service_id={route.service_id} routing_key={route.routing_key}"
+    )
+    _validate_monitor_limits(
+        min_wait=min_wait,
+        max_wait=max_wait,
+        max_probes=max_probes,
+    )
+
+    if not apply:
+        print(
+            "ITA_MONITOR_PREFLIGHT_OK "
+            f"{route_log} min_wait={min_wait} "
+            f"max_wait={max_wait} max_probes={max_probes} "
+            f"local_handoff={str(publish_local_signal).lower()} "
+            "external_request=false"
+        )
+        return 0
+
+    chrome_path = resolve_chrome_path(env)
+    os.environ["CHROME_BIN"] = str(chrome_path)
+    username, password = _get_query_credentials(
+        env,
+        non_interactive=non_interactive,
+    )
+    profile_path = _prepare_query_profile(username)
+    config = build_query_config(
+        env,
+        username=username,
+        password=password,
+        persistent_profile_path=profile_path,
+        route=route,
+    )
+
+    plugin = ItaPlugin(group_id="ita-monitor-local-debug")
+    plugin.set_log(lambda message: print(message, flush=True))
+    plugin.set_config(config)
+
+    exit_code = 0
+    cleanup_error: Exception | None = None
+    try:
+        plugin.create_session()
+        print(
+            "ITA_MONITOR_STARTED "
+            f"{route_log} session_attempts=1 "
+            f"max_probes={max_probes}"
+        )
+
+        for probe_number in range(1, max_probes + 1):
+            print(
+                "ITA_MONITOR_PROBE_START "
+                f"{route_log} probe={probe_number}"
+            )
+            result = plugin.query(route.appointment_type())
+
+            if _is_weak_entry_signal(result):
+                if publish_local_signal:
+                    publisher = signal_publisher or (
+                        lambda: publish_local_weak_signal(
+                            service_id=route.service_id,
+                            routing_key=route.routing_key,
+                        )
+                    )
+                    publisher()
+                    print(
+                        "ITA_MONITOR_HANDOFF_PUBLISHED "
+                        f"{route_log} "
+                        f"ttl_seconds={ITA_LOCAL_SIGNAL_TTL_SECONDS} "
+                        "payload=metadata-only",
+                        flush=True,
+                    )
+                _print_booking_form_structure(plugin, route=route)
+                print(
+                    "\aITA_MONITOR_WEAK_SIGNAL "
+                    f"{route_log} probe={probe_number} "
+                    "evidence=booking-form action=start-user-book-recheck-now",
+                    flush=True,
+                )
+                exit_code = 4
+                break
+
+            if _is_nonempty_query_result(result):
+                print(
+                    "ITA_MONITOR_SAFE_STOP "
+                    f"{route_log} probe={probe_number} "
+                    "reason=non-empty-availability-result"
+                )
+                exit_code = 4
+                break
+
+            print(
+                "ITA_MONITOR_NONE_AVAILABLE "
+                f"{route_log} probe={probe_number}"
+            )
+            if probe_number == max_probes:
+                print(
+                    "ITA_MONITOR_MAX_PROBES_REACHED "
+                    f"{route_log} probes={max_probes}"
+                )
+                break
+
+            wait_seconds = randint(min_wait, max_wait)
+            print(
+                "ITA_MONITOR_WAIT "
+                f"next_probe={probe_number + 1} seconds={wait_seconds}",
+                flush=True,
+            )
+            try:
+                sleep(wait_seconds)
+            except KeyboardInterrupt:
+                raise _MonitorCancelled from None
+    except _MonitorCancelled:
+        print(
+            "\nITA_MONITOR_CANCELLED "
+            f"{route_log}",
+        )
+        exit_code = 130
+    except KeyboardInterrupt:
+        print(
+            "\nITA_MONITOR_CANCELLED "
+            f"{route_log}",
+        )
+        exit_code = 130
+    except BizLogicError as exc:
+        print(
+            f"ITA_MONITOR_FAILED type={type(exc).__name__} "
+            f"message={_popup_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        exit_code = 1
+    except Exception as exc:
+        print(
+            f"ITA_MONITOR_FAILED type={type(exc).__name__} "
+            f"message={_popup_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        exit_code = 1
+    finally:
+        try:
+            plugin.cleanup()
+            print("ITA_MONITOR_CLEANUP_OK")
+        except Exception as exc:
+            cleanup_error = exc
+            print(
+                f"ITA_MONITOR_CLEANUP_FAILED type={type(exc).__name__} "
+                f"message={_popup_text_for_log(exc)}",
+                file=sys.stderr,
+            )
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "Bounded route-configured Italy Query monitor. Without --run, "
+            "performs a zero-network preflight only."
+        )
+    )
+    parser.add_argument(
+        "--run",
+        action="store_true",
+        help="Start the bounded real website monitor.",
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when local credentials are unavailable.",
+    )
+    parser.add_argument(
+        "--min-wait",
+        type=int,
+        default=MIN_SAFE_WAIT_SECONDS,
+        help=f"Minimum seconds between probes (floor: {MIN_SAFE_WAIT_SECONDS}).",
+    )
+    parser.add_argument(
+        "--max-wait",
+        type=int,
+        default=DEFAULT_MAX_WAIT_SECONDS,
+        help="Maximum seconds between probes.",
+    )
+    parser.add_argument(
+        "--max-probes",
+        type=int,
+        default=DEFAULT_MAX_PROBES,
+        help=f"Maximum probes in one run (ceiling: {MAX_ALLOWED_PROBES}).",
+    )
+    parser.add_argument(
+        "--publish-local-signal",
+        action="store_true",
+        help=(
+            "On a verified weak signal, atomically notify one local Book "
+            "debugger. Production signaling behavior is unchanged."
+        ),
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    try:
+        return run_monitor(
+            os.environ,
+            apply=args.run,
+            non_interactive=args.non_interactive,
+            min_wait=args.min_wait,
+            max_wait=args.max_wait,
+            max_probes=args.max_probes,
+            publish_local_signal=args.publish_local_signal,
+        )
+    except DebugConfigurationError as exc:
+        print(f"ITA_MONITOR_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 513 - 0
tools/debug_ita_query.py

@@ -0,0 +1,513 @@
+#!/usr/bin/env python3
+"""Run one isolated, route-configured Italy-plugin availability probe.
+
+This debug entrypoint logs in, calls ``ItaPlugin.query()`` exactly once for the
+configured route, and then cleans up. It never calls ``book()``
+and it does not retry the query.
+"""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import re
+import sys
+from dataclasses import dataclass
+from pathlib import Path
+from typing import Mapping
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_plugin import BOOKING_FORM_DISCOVERY_SCRIPT, ItaPlugin
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    _env_text,
+    _get_credentials,
+    _text_for_log,
+    _url_for_log,
+    build_plugin_config,
+    resolve_chrome_path,
+)
+from utils.local_account import (
+    LocalAccountConfigurationError,
+    load_local_account,
+)
+from utils.ita_local_profile import (
+    ITA_QUERY_ACCOUNT_FILE,
+    ItaLocalProfileError,
+    prepare_ita_query_profile,
+)
+from vs_types import AppointmentType, AvailabilityStatus, BizLogicError, VSPlgConfig
+
+
+DEFAULT_ITA_SERVICE_ID = 1321
+DEFAULT_ITA_ROUTING_KEY = "slot.dub.it.tourist"
+DEFAULT_ITA_CITY = "Dublin"
+DEFAULT_ITA_VISA_TYPE = "Tourist"
+DEBUG_ROUTE_CAPABILITY = "services_probe_only"
+DEBUG_ROUTE_ENV_NAMES = (
+    "ITA_ROUTING_KEY",
+    "ITA_SERVICE_ID",
+    "ITA_CITY",
+    "ITA_VISA_TYPE",
+)
+LOCAL_QUERY_ACCOUNT_FILE = ITA_QUERY_ACCOUNT_FILE
+_EMAIL_PATTERN = re.compile(r"\b[^\s@]+@[^\s@]+\.[^\s@]+\b")
+_LONG_TOKEN_PATTERN = re.compile(r"\b[A-Za-z0-9_-]{24,}\b")
+_LONG_NUMBER_PATTERN = re.compile(r"\b\d{6,}\b")
+_BOOKING_FORM_DISCOVERY_SCRIPT = BOOKING_FORM_DISCOVERY_SCRIPT
+
+
+@dataclass(frozen=True, slots=True)
+class ItaDebugRoute:
+    routing_key: str
+    service_id: int
+    city: str
+    visa_type: str
+
+    @property
+    def booking_path(self) -> str:
+        return f"/Services/Booking/{self.service_id}"
+
+    def appointment_type(self) -> AppointmentType:
+        return AppointmentType(
+            routing_key=self.routing_key,
+            country="Italy",
+            city=self.city,
+            visa_type=self.visa_type,
+        )
+
+    def apt_config(self) -> dict:
+        return {
+            "service_id": self.service_id,
+            "capability": DEBUG_ROUTE_CAPABILITY,
+        }
+
+
+def resolve_debug_route(env: Mapping[str, str]) -> ItaDebugRoute:
+    """Resolve one explicit debug route, retaining Dublin only as a default."""
+
+    route_values = {
+        name: _env_text(env, name)
+        for name in DEBUG_ROUTE_ENV_NAMES
+    }
+    configured_names = {
+        name for name, value in route_values.items() if value
+    }
+    if configured_names and configured_names != set(DEBUG_ROUTE_ENV_NAMES):
+        raise DebugConfigurationError(
+            "Italy route override must set ITA_ROUTING_KEY, ITA_SERVICE_ID, "
+            "ITA_CITY, and ITA_VISA_TYPE together"
+        )
+
+    routing_key = (
+        route_values["ITA_ROUTING_KEY"] or DEFAULT_ITA_ROUTING_KEY
+    )
+    raw_service_id = route_values["ITA_SERVICE_ID"]
+    try:
+        service_id = (
+            int(raw_service_id)
+            if raw_service_id
+            else DEFAULT_ITA_SERVICE_ID
+        )
+    except ValueError as exc:
+        raise DebugConfigurationError(
+            "ITA_SERVICE_ID must be a positive integer"
+        ) from exc
+    if service_id <= 0:
+        raise DebugConfigurationError(
+            "ITA_SERVICE_ID must be a positive integer"
+        )
+
+    city = route_values["ITA_CITY"] or DEFAULT_ITA_CITY
+    visa_type = route_values["ITA_VISA_TYPE"] or DEFAULT_ITA_VISA_TYPE
+    return ItaDebugRoute(
+        routing_key=routing_key,
+        service_id=service_id,
+        city=city,
+        visa_type=visa_type,
+    )
+
+
+def _get_query_credentials(
+    env: Mapping[str, str],
+    *,
+    non_interactive: bool,
+) -> tuple[str, str]:
+    """Prefer the ignored local Query account, then preserve the old fallback."""
+    if LOCAL_QUERY_ACCOUNT_FILE.exists():
+        try:
+            account = load_local_account(LOCAL_QUERY_ACCOUNT_FILE)
+        except LocalAccountConfigurationError as exc:
+            raise DebugConfigurationError(
+                f"Local Italy Query account config is invalid: {exc}"
+            ) from exc
+        return account.username, account.password
+    return _get_credentials(env, non_interactive=non_interactive)
+
+
+def _is_weak_entry_signal(result: object) -> bool:
+    return bool(
+        getattr(result, "success", False)
+        and getattr(result, "availability_status", None)
+        == AvailabilityStatus.NoneAvailable
+        and getattr(result, "earliest_date", None) is None
+        and not getattr(result, "availability", None)
+    )
+
+
+def _is_nonempty_query_result(result: object) -> bool:
+    return bool(
+        getattr(result, "success", False)
+        or getattr(result, "availability_status", None)
+        != AvailabilityStatus.NoneAvailable
+        or getattr(result, "earliest_date", None) is not None
+        or bool(getattr(result, "availability", None))
+    )
+
+
+def build_query_config(
+    env: Mapping[str, str],
+    *,
+    username: str,
+    password: str,
+    persistent_profile_path: Path | None = None,
+    route: ItaDebugRoute | None = None,
+) -> VSPlgConfig:
+    """Build a safe CS2 config for exactly one resolved route."""
+
+    resolved_route = route or resolve_debug_route(env)
+    config = build_plugin_config(
+        env,
+        username=username,
+        password=password,
+    )
+    config.free_config = {
+        "query_mode": "services_probe",
+        "final_submit_enabled": False,
+        "apt_configs": {
+            resolved_route.routing_key: resolved_route.apt_config(),
+        },
+    }
+    if persistent_profile_path is not None:
+        config.free_config = {
+            **config.free_config,
+            "persistent_browser_profile_path": str(persistent_profile_path),
+        }
+    return config
+
+
+def _prepare_query_profile(username: str) -> Path:
+    try:
+        return prepare_ita_query_profile(username)
+    except ItaLocalProfileError as exc:
+        raise DebugConfigurationError(
+            "Local Italy Query browser profile is invalid"
+        ) from exc
+
+
+def _appointment_type(
+    route: ItaDebugRoute | None = None,
+) -> AppointmentType:
+    return (route or resolve_debug_route({})).appointment_type()
+
+
+def _popup_text_for_log(value: object, *, limit: int = 300) -> str:
+    """Keep a short diagnostic notice while redacting likely identifiers."""
+
+    sanitized = re.sub(r"\s+", " ", _text_for_log(value)).strip()
+    sanitized = _EMAIL_PATTERN.sub("<redacted-email>", sanitized)
+    sanitized = _LONG_TOKEN_PATTERN.sub("<redacted-token>", sanitized)
+    sanitized = _LONG_NUMBER_PATTERN.sub("<redacted-number>", sanitized)
+    if len(sanitized) > limit:
+        return f"{sanitized[:limit]}...<truncated>"
+    return sanitized
+
+
+def _metadata_text(value: object, *, limit: int = 120) -> str | None:
+    if value is None:
+        return None
+    text = re.sub(r"\s+", " ", _text_for_log(value)).strip()
+    text = _EMAIL_PATTERN.sub("<redacted-email>", text)
+    text = _LONG_NUMBER_PATTERN.sub("<redacted-number>", text)
+    if len(text) > limit:
+        return f"{text[:limit]}...<truncated>"
+    return text or None
+
+
+def _sanitize_booking_form_structure(raw: object) -> dict | None:
+    """Allowlist structural metadata and discard every field value."""
+
+    if not isinstance(raw, dict):
+        return None
+
+    raw_form = raw.get("form") if isinstance(raw.get("form"), dict) else {}
+    raw_fields = raw.get("fields") if isinstance(raw.get("fields"), list) else []
+    raw_buttons = (
+        raw.get("buttons") if isinstance(raw.get("buttons"), list) else []
+    )
+
+    fields = []
+    for item in raw_fields[:100]:
+        if not isinstance(item, dict):
+            continue
+        fields.append(
+            {
+                "tag": _metadata_text(item.get("tag")),
+                "type": _metadata_text(item.get("type")),
+                "id": _metadata_text(item.get("id")),
+                "name": _metadata_text(item.get("name")),
+                "required": bool(item.get("required")),
+            }
+        )
+
+    buttons = []
+    for item in raw_buttons[:50]:
+        if not isinstance(item, dict):
+            continue
+        buttons.append(
+            {
+                "tag": _metadata_text(item.get("tag")),
+                "type": _metadata_text(item.get("type")),
+                "id": _metadata_text(item.get("id")),
+                "name": _metadata_text(item.get("name")),
+                "text": _metadata_text(item.get("text")),
+            }
+        )
+
+    return {
+        "path": _metadata_text(raw.get("path")),
+        "form": {
+            "method": _metadata_text(raw_form.get("method")),
+            "action_path": _metadata_text(raw_form.get("action_path")),
+        },
+        "field_count": int(raw.get("field_count") or len(raw_fields)),
+        "fields_truncated": bool(
+            raw.get("fields_truncated") or len(raw_fields) > 100
+        ),
+        "fields": fields,
+        "button_count": int(raw.get("button_count") or len(raw_buttons)),
+        "buttons_truncated": bool(
+            raw.get("buttons_truncated") or len(raw_buttons) > 50
+        ),
+        "buttons": buttons,
+    }
+
+
+def _print_booking_form_structure(
+    plugin: ItaPlugin,
+    *,
+    raw_structure: object = None,
+    route: ItaDebugRoute | None = None,
+) -> None:
+    """Read structure only; never read field values or submit the form."""
+
+    page = getattr(plugin, "page", None)
+    if page is None:
+        print("ITA_BOOKING_FORM_STRUCTURE=not-available")
+        return
+    try:
+        if raw_structure is None:
+            inspector = getattr(plugin, "_inspect_booking_form_structure", None)
+            raw_structure = (
+                inspector((route or resolve_debug_route({})).booking_path)
+                if callable(inspector)
+                else page.run_js(_BOOKING_FORM_DISCOVERY_SCRIPT)
+            )
+        structure = _sanitize_booking_form_structure(
+            raw_structure
+        )
+        if structure is None:
+            print("ITA_BOOKING_FORM_STRUCTURE=not-available")
+            return
+        print(
+            "ITA_BOOKING_FORM_STRUCTURE="
+            + json.dumps(structure, ensure_ascii=False, sort_keys=True)
+        )
+    except Exception as exc:
+        print(
+            "ITA_BOOKING_FORM_STRUCTURE=unavailable "
+            f"type={type(exc).__name__} message={_text_for_log(exc)}"
+        )
+
+
+def _print_failure_context(plugin: ItaPlugin) -> None:
+    """Print sanitized text diagnostics; never save Query screenshots."""
+
+    page = getattr(plugin, "page", None)
+    if page is None:
+        print("diagnostic_page=not-created")
+        return
+    try:
+        print(f"diagnostic_url={_url_for_log(page.url)}")
+    except Exception as exc:
+        print(
+            "diagnostic_url=unavailable "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+    try:
+        title = _popup_text_for_log(page.title, limit=120)
+        print(
+            f"diagnostic_title={title}"
+            if title
+            else "diagnostic_title=not-present"
+        )
+    except Exception as exc:
+        print(
+            "diagnostic_title=unavailable "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+    try:
+        popup = page.ele(".jconfirm-content", timeout=0.5)
+        popup_text = _popup_text_for_log(popup.text if popup else "")
+        print(
+            f"diagnostic_popup_text={popup_text}"
+            if popup_text
+            else "diagnostic_popup_text=not-present"
+        )
+    except Exception as exc:
+        print(
+            "diagnostic_popup_text=unavailable "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+
+
+def run_query_once(env: Mapping[str, str], *, non_interactive: bool, production_workflow: bool = False) -> int:
+    if production_workflow and non_interactive:
+        raise DebugConfigurationError("Production Calendar preparation currently requires manual OTP (ITA-OTP-01)")
+    route = resolve_debug_route(env)
+    chrome_path = resolve_chrome_path(env)
+    os.environ["CHROME_BIN"] = str(chrome_path)
+
+    username, password = _get_query_credentials(
+        env,
+        non_interactive=non_interactive,
+    )
+    profile_path = _prepare_query_profile(username)
+    config_builder = build_query_config
+    if production_workflow:
+        # Reuse route/env validation; production modules never import this tool.
+        from tools.debug_ita_calendar_gate import build_calendar_gate_config
+        config_builder = build_calendar_gate_config
+    config = config_builder(
+        env,
+        username=username,
+        password=password,
+        persistent_profile_path=profile_path,
+        route=route,
+    )
+    if production_workflow:
+        config.free_config.update(query_mode="calendar", otp_mode="manual", final_submit_enabled=False)
+
+    plugin = ItaPlugin(group_id="ita-query-local-debug")
+    plugin.set_log(lambda message: print(message, flush=True))
+    plugin.set_config(config)
+
+    exit_code = 0
+    cleanup_error: Exception | None = None
+    try:
+        plugin.create_session()
+        print(
+            "ITA_QUERY_PROBE_START "
+            f"service_id={route.service_id} "
+            f"routing_key={route.routing_key} query_attempt=1"
+        )
+        result = plugin.query(route.appointment_type())
+
+        if production_workflow and result.availability_status == AvailabilityStatus.Available and result.earliest_date:
+            print("ITA_QUERY_WORKFLOW_RESULT=" + json.dumps({
+                "success": result.success,
+                "availabilityStatus": result.availability_status.value,
+                "earliestDate": result.earliest_date.date().isoformat(),
+                "finalSubmissionEnabled": False,
+            }, sort_keys=True))
+        elif _is_weak_entry_signal(result):
+            _print_booking_form_structure(plugin, route=route)
+            print(
+                "ITA_QUERY_WEAK_SIGNAL "
+                f"service_id={route.service_id} "
+                f"routing_key={route.routing_key} "
+                f"status={result.availability_status.value} "
+                "evidence=booking-form"
+            )
+            exit_code = 4
+        elif _is_nonempty_query_result(result):
+            print(
+                "ITA_QUERY_SAFE_STOP "
+                f"service_id={route.service_id} "
+                f"routing_key={route.routing_key} "
+                "reason=non-empty-availability-result"
+            )
+            exit_code = 4
+        else:
+            print(
+                "ITA_QUERY_NONE_AVAILABLE "
+                f"service_id={route.service_id} "
+                f"routing_key={route.routing_key} "
+                f"status={result.availability_status.value}"
+            )
+    except BizLogicError as exc:
+        print(
+            f"ITA_QUERY_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        exit_code = 1
+    except Exception as exc:
+        print(
+            f"ITA_QUERY_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        _print_failure_context(plugin)
+        exit_code = 1
+    finally:
+        try:
+            plugin.cleanup()
+            print("ITA_QUERY_CLEANUP_OK")
+        except Exception as exc:
+            cleanup_error = exc
+            print(
+                f"ITA_QUERY_CLEANUP_FAILED type={type(exc).__name__} "
+                f"message={_text_for_log(exc)}",
+                file=sys.stderr,
+            )
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "One-shot route-configured Italy Query debugger "
+            "(one query, no retry, never books)."
+        )
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when credentials are missing.",
+    )
+    parser.add_argument(
+        "--production-workflow", action="store_true",
+        help="Use the production Calendar Query entry, including one manual OTP preparation; never book.",
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    try:
+        if args.production_workflow:
+            return run_query_once(os.environ, non_interactive=args.non_interactive, production_workflow=True)
+        return run_query_once(os.environ, non_interactive=args.non_interactive)
+    except DebugConfigurationError as exc:
+        print(f"ITA_QUERY_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 77 - 0
tools/debug_ita_query_book.py

@@ -0,0 +1,77 @@
+#!/usr/bin/env python3
+"""Offline acceptance of the existing Sentinel -> Redis -> OrderBooker code.
+
+No alternative signal format, TTL, account selector, dispatcher or browser
+lifecycle is implemented here. Tests execute the real framework methods;
+only external boundaries (pool/order API, Redis and browser) are simulated.
+The old live --run entry is deliberately unsupported. Explicit --local-run
+uses the same framework with a private Redis process and real site sessions;
+only order provision/reporting is local. Final booking requires --submit-once
+with --local-run; it then submits automatically within the configured date range.
+"""
+from __future__ import annotations
+
+import argparse
+import contextlib
+import io
+import json
+from pathlib import Path
+import sys
+import unittest
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+CONTRACT = "existing-framework-offline-v2"
+TEST_NAMES = (
+    "test.test_debug_ita_query_book.ExistingFrameworkJointTests",
+    "test.test_ita_plugin.ItaSignalReuseTests",
+    "test.test_ita_booker_integration",
+    "test.test_ita_query_recovery.ExistingSentinelLifecycleTests",
+    "test.test_debug_ita_query_book.LocalHarnessTests",
+    "test.test_debug_ita_query_book.LocalConfigurationTests",
+    "test.test_debug_ita_query_book.LocalFinalTests",
+    "test.test_ita_workflow.RealFinalAuditTests",
+    "test.test_debug_ita_query_book.LocalFinalCompositionTests",
+)
+
+
+def main(argv=None):
+    parser = argparse.ArgumentParser(description=__doc__)
+    mode = parser.add_mutually_exclusive_group()
+    mode.add_argument("--offline", action="store_true", help="Run offline framework acceptance (the default).")
+    mode.add_argument("--local-preflight", action="store_true", help="Check local dependencies/config only; no account allocation.")
+    mode.add_argument("--local-run", action="store_true", help="One real pool Query -> private Redis -> applicant Book; pre-final unless --submit-once.")
+    parser.add_argument("--submit-once", action="store_true", help="With --local-run, automatically create ONE REAL appointment without a confirmation prompt. Never retry an unknown result.")
+    parser.add_argument("--group", default="ita.hong_kong")
+    parser.add_argument("--config", default="config/config_sentinel.json")
+    parser.add_argument("--proxy", default="http://127.0.0.1:6268")
+    parser.add_argument("--book-account-file", help="Existing private local account JSON; otherwise prompt for applicant credentials.")
+    parser.add_argument("--expected-start-date")
+    parser.add_argument("--expected-end-date")
+    args = parser.parse_args(argv)
+    if args.submit_once and not args.local_run:
+        parser.error("--submit-once requires --local-run")
+    if args.local_preflight or args.local_run:
+        from tools.ita_query_book_local import main_local
+        return main_local(args)
+    print("ITA_QUERY_BOOK_TOOL=" + CONTRACT, flush=True)
+    # Fixtures use synthetic accounts only. Keep incidental fixture output out
+    # of the summary; unittest still reports failures through its own stream.
+    runner = unittest.TextTestRunner(stream=sys.stderr, verbosity=1)
+    with contextlib.redirect_stdout(io.StringIO()):
+        suite = unittest.defaultTestLoader.loadTestsFromNames(TEST_NAMES)
+        result = runner.run(suite)
+    passed = result.wasSuccessful() and result.testsRun > 0 and not result.skipped
+    print("ITA_QUERY_BOOK_FRAMEWORK_RESULT=" + json.dumps({
+        "contract": CONTRACT, "mode": "offline", "passed": passed,
+        "testsRun": result.testsRun, "failures": len(result.failures),
+        "errors": len(result.errors), "skipped": len(result.skipped),
+        "externalBoundaries": "simulated", "liveAcceptance": False,
+    }, sort_keys=True), flush=True)
+    return 0 if passed else 1
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 320 - 0
tools/debug_ita_reservation.py

@@ -0,0 +1,320 @@
+#!/usr/bin/env python3
+"""Accept the receipt reader against an existing receipt; never book.
+
+Default is a local preflight. --run uses a temporary applicant browser and only
+reads Reservation -> one cancelled detail -> Reservation after login. Neither
+raw receipts nor original exception messages are written to the console/files.
+--expect-confirmed instead checks one unique confirmed receipt matching the
+explicit date, assigned time and displayed service. This is existing-receipt
+verification, NOT attribution to a prior booking attempt or runtime service ID.
+"""
+
+from __future__ import annotations
+
+import argparse
+import hashlib
+import json
+import os
+import re
+import sys
+from datetime import date
+from pathlib import Path
+from typing import Mapping
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_booking_final import ReservationState
+from plugins.ita_calendar_query import same_origin_path
+from plugins.ita_plugin import ItaPlugin, SERVICES_PROBE_QUERY_MODE
+from plugins.ita_reservation import (
+    ReservationReadError, read_reservation_detail, read_reservation_listing,
+    read_reservation_date_diagnostic,
+)
+from tools.debug_ita_calendar_gate import CalendarRequestAudit
+from tools.debug_ita_session import (
+    DebugConfigurationError, _get_credentials, build_plugin_config, resolve_chrome_path,
+)
+
+CONTRACT = "receipt-readonly-confirmed-v4"
+LIST_URL = "https://prenotami.esteri.it/Reservation"
+COUNTERS = frozenset(("otpRequests", "avantiPosts", "availabilityRequests",
+                      "timeSlotRequests", "finalRequests"))
+CONFIG_ENV_KEYS = frozenset((
+    "ITA_PROXY_IP", "ITA_PROXY_PORT", "ITA_PROXY_PROTO", "ITA_PROXY_USERNAME",
+    "ITA_PROXY_PASSWORD", "ITA_PROXY_ID", "MIHOMO_BIN", "ITA_SESSION_MAX_LIFE",
+))
+READ_REASONS = frozenset((
+    "field_invalid", "date_unrecognized", "time_unrecognized", "detail_url_invalid",
+    "detail_schema_changed", "fields_ambiguous", "status_code_invalid", "coverage_invalid",
+    "coverage_incomplete", "pagination_invalid", "list_schema_changed", "table_ambiguous",
+    "headers_changed", "waitlist_ambiguous", "waitlist_schema_unverified", "row_nodes_incomplete",
+    "row_schema_changed", "duplicate_record", "wrong_page", "context_changed", "not_ready",
+    "page_read_rejected", "browser_read_failed", "wait_config_invalid", "stability_timeout",
+))
+
+
+class ReceiptGateError(ValueError):
+    pass
+
+
+def source_fingerprint() -> str:
+    digest = hashlib.sha256()
+    for name in (
+        "tools/debug_ita_reservation.py", "plugins/ita_reservation.py",
+        "plugins/ita_booking_final.py", "plugins/ita_plugin.py", "plugins/ita_protocol.py",
+        "plugins/ita_calendar_query.py", "plugins/ita_calendar_book.py",
+        "tools/debug_ita_session.py", "tools/debug_ita_calendar_gate.py",
+    ):
+        digest.update(name.encode())
+        digest.update((REPO_ROOT / name).read_bytes())
+    return digest.hexdigest()[:12]
+
+
+def build_receipt_config(env: Mapping[str, str], *, username: str, password: str):
+    # Explicit projection: saved Query accounts, persistent profiles, debug and
+    # regional/service settings must not leak into this applicant-only reader.
+    projected = {key: env[key] for key in CONFIG_ENV_KEYS if key in env}
+    config = build_plugin_config(projected, username=username, password=password)
+    config.free_config = {"query_mode": SERVICES_PROBE_QUERY_MODE, "final_submit_enabled": False}
+    return config
+
+
+def _check(condition: bool, reason: str) -> None:
+    if not condition:
+        raise ReceiptGateError(reason)
+
+
+def _check_page_url(page, expected: str) -> None:
+    try:
+        path, parsed = same_origin_path(page.url)
+    except Exception:
+        raise ReceiptGateError("navigation_rejected") from None
+    _check(page.url == expected and not parsed.query and not parsed.fragment and bool(path),
+           "navigation_rejected")
+
+
+def run_receipt_gate(env: Mapping[str, str], *, execute: bool = False,
+                     non_interactive: bool = False, expect_confirmed: bool = False,
+                     expected_date: str | None = None, expected_time: str | None = None,
+                     expected_service: str | None = None) -> int:
+    plugin = audit = None
+    audit_started = False
+    previous_chrome = os.environ.get("CHROME_BIN")
+    chrome_changed = False
+    result = {
+        "contract": CONTRACT, "passed": False, "exitCode": 1, "stage": "preflight",
+        "reason": "", "listReady": False, "cancelledDetailMatched": False,
+        "listUnchanged": False, "reservationCountBefore": None,
+        "reservationCountAfter": None, "postLoginBusinessRequests": None,
+        "cleanupOk": False, "auditVerified": False, "finalSubmissionEnabled": False,
+        "dateDiagnostic": None,
+        "confirmedDetailMatched": False, "existingReservationConfirmed": False,
+        "bookingAttemptAttributed": False, "confirmedReceipt": None,
+    }
+
+    def verify_audit():
+        result["auditVerified"] = False
+        try:
+            counts = audit.settled_snapshot()
+        except Exception:
+            raise ReceiptGateError("audit_unavailable") from None
+        _check(isinstance(counts, dict) and set(counts) == COUNTERS and
+               all(type(v) is int and v >= 0 for v in counts.values()), "audit_unavailable")
+        result["postLoginBusinessRequests"] = counts
+        _check(all(v == 0 for v in counts.values()), "unexpected_business_request")
+        result["auditVerified"] = True
+
+    try:
+        _check(all(type(v) is bool for v in (execute, non_interactive, expect_confirmed)),
+               "invalid_execution_flag")
+        print(f"ITA_RECEIPT_TOOL_CONTRACT version={CONTRACT} source_sha256={source_fingerprint()}", flush=True)
+        expected_day = None
+        if expect_confirmed:
+            try:
+                expected_day = date.fromisoformat(expected_date)
+                valid = (expected_day.isoformat() == expected_date and
+                         isinstance(expected_time, str) and
+                         re.fullmatch(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]", expected_time) is not None and
+                         isinstance(expected_service, str) and 0 < len(expected_service) <= 256 and
+                         expected_service == expected_service.strip() and
+                         all(ord(c) >= 32 and ord(c) != 127 for c in expected_service))
+            except (TypeError, ValueError):
+                valid = False
+            _check(valid, "confirmed_expectations_invalid")
+        else:
+            _check(all(v is None for v in (expected_date, expected_time, expected_service)),
+                   "confirmed_expectations_without_mode")
+        chrome = resolve_chrome_path(env)
+        build_receipt_config(env, username="preflight@example.invalid", password="placeholder")
+        if not execute:
+            print("ITA_RECEIPT_PREFLIGHT_OK external_requests=0 credentials_read=false browser_created=false")
+            return 0
+
+        result["stage"] = "credentials"
+        username, password = _get_credentials({
+            "ITA_USERNAME": env.get("ITA_BOOK_USERNAME", ""),
+            "ITA_PASSWORD": env.get("ITA_BOOK_PASSWORD", ""),
+        }, non_interactive=non_interactive)
+        config = build_receipt_config(env, username=username, password=password)
+        result["stage"] = "login"
+        os.environ["CHROME_BIN"] = str(chrome)
+        chrome_changed = True
+        plugin = ItaPlugin(group_id="ita-receipt-readonly")
+        plugin.set_log(lambda _message: None)
+        plugin.set_config(config)
+        print("ITA_RECEIPT_LOGIN_START profile=temporary role=applicant", flush=True)
+        plugin.create_session()
+        page = plugin.page
+        _check_page_url(page, "https://prenotami.esteri.it/UserArea")
+        _check(bool(page.ele(".app-menu", timeout=0.5)) and
+               bool(page.ele("@href=/Services", timeout=0.5)), "login_unverified")
+        tab_id, generation = page.tab_id, plugin.session_create_time
+        account_name = config.account.username
+        _check(isinstance(tab_id, str) and bool(tab_id) and generation > 0, "context_changed")
+
+        def verify_context():
+            _check(plugin.page is page and page.tab_id == tab_id and
+                   plugin.session_create_time == generation and
+                   plugin.config.account.username == account_name and
+                   plugin._persistent_profile_path is None and
+                   plugin.free_config == {"query_mode": SERVICES_PROBE_QUERY_MODE,
+                                          "final_submit_enabled": False}, "context_changed")
+
+        def navigate(url):
+            verify_context()
+            _check(page.get(url, retry=0, timeout=30) is not False, "navigation_failed")
+            verify_context()
+            _check_page_url(page, url)
+
+        verify_context()
+        print("ITA_RECEIPT_LOGIN_OK", flush=True)
+        result["stage"] = "audit_start"
+        audit = CalendarRequestAudit(page, include_time_slots=True)
+        audit.start()
+        audit_started = True
+        result["stage"] = "list_before"
+        navigate(LIST_URL)
+        before = read_reservation_listing(page)
+        verify_context()
+        verify_audit()
+        result.update(listReady=True, reservationCountBefore=len(before.rows))
+        if expect_confirmed:
+            candidates = [row for row in before.rows if row.state is ReservationState.ACTIVE and
+                          row.day == expected_day and row.appointment_time == expected_time and
+                          row.service_name == expected_service]
+            _check(len(candidates) == 1, "confirmed_sample_missing" if not candidates else
+                   "confirmed_sample_ambiguous")
+            sample = candidates[0]
+        else:
+            sample = next((row for row in before.rows if row.state is ReservationState.CANCELLED), None)
+            _check(sample is not None, "cancelled_sample_missing")
+        result["stage"] = "confirmed_detail" if expect_confirmed else "cancelled_detail"
+        # The actual link has already passed the receipt adapter's strict URL validation.
+        navigate(sample.detail_url)
+        receipt = read_reservation_detail(page)
+        verify_context()
+        verify_audit()
+        wanted_state = ReservationState.ACTIVE if expect_confirmed else ReservationState.CANCELLED
+        wanted_code = "2" if expect_confirmed else "3"
+        _check(receipt.state is wanted_state and receipt.status_code == wanted_code and
+               receipt.booking_type == "Prenotazione Singola" and
+               all(getattr(receipt, field) == getattr(sample, field) for field in (
+                   "reference", "office", "service_name", "day", "appointment_time", "status_text")),
+               "confirmed_detail_mismatch" if expect_confirmed else "cancelled_detail_mismatch")
+        if expect_confirmed:
+            result["confirmedDetailMatched"] = True
+            result["confirmedReceipt"] = {
+                "date": receipt.day.isoformat(), "assignedTime": receipt.appointment_time,
+                "state": receipt.state.value, "statusText": receipt.status_text,
+                "statusCode": receipt.status_code, "singleBooking": True,
+                "serviceDisplayMatches": True,
+            }
+        else:
+            result["cancelledDetailMatched"] = True
+        result["stage"] = "list_after"
+        navigate(LIST_URL)
+        after = read_reservation_listing(page)
+        verify_context()
+        verify_audit()
+        result["reservationCountAfter"] = len(after.rows)
+        _check({r.reference: r for r in before.rows} == {r.reference: r for r in after.rows} and
+               before.waitlist_count == after.waitlist_count, "listing_changed")
+        result.update(listUnchanged=True, stage="completed", exitCode=0)
+    except KeyboardInterrupt:
+        result.update(reason="interrupted", exitCode=130)
+    except DebugConfigurationError:
+        result.update(reason="configuration_rejected")
+    except ReservationReadError as exc:
+        result.update(reason=exc.reason if exc.reason in READ_REASONS else "receipt_read_rejected")
+        if exc.reason == "date_unrecognized" and result["stage"] in ("list_before", "list_after"):
+            try:
+                verify_context()
+                result["dateDiagnostic"] = read_reservation_date_diagnostic(page)
+                verify_context()
+            except Exception:
+                result["dateDiagnostic"] = {"available": False}
+    except ReceiptGateError as exc:
+        # Only fixed reasons constructed above, not raw website/browser exceptions.
+        safe = {"navigation_rejected", "navigation_failed", "invalid_execution_flag", "login_unverified",
+                "context_changed", "audit_unavailable", "unexpected_business_request",
+                "cancelled_sample_missing", "cancelled_detail_mismatch", "listing_changed",
+                "confirmed_expectations_invalid", "confirmed_expectations_without_mode",
+                "confirmed_sample_missing", "confirmed_sample_ambiguous", "confirmed_detail_mismatch"}
+        result.update(reason=str(exc) if str(exc) in safe else "gate_rejected")
+    except Exception:
+        result.update(reason="stage_failed")
+    finally:
+        if audit_started:
+            try:
+                verify_audit()
+            except Exception as exc:
+                result.update(exitCode=1 if result["exitCode"] == 0 else result["exitCode"])
+                if not result["reason"]:
+                    result["reason"] = ("unexpected_business_request" if
+                                        isinstance(exc, ReceiptGateError) and
+                                        str(exc) == "unexpected_business_request" else "audit_unavailable")
+        if audit is not None:
+            try:
+                audit.stop()
+            except Exception:
+                result.update(exitCode=1, auditVerified=False,
+                              reason=result["reason"] or "audit_stop_failed")
+        if plugin is not None:
+            try:
+                plugin.cleanup()
+                result["cleanupOk"] = True
+            except Exception:
+                result.update(exitCode=3, reason="cleanup_failed")
+        if chrome_changed:
+            if previous_chrome is None:
+                os.environ.pop("CHROME_BIN", None)
+            else:
+                os.environ["CHROME_BIN"] = previous_chrome
+
+    result["passed"] = (result["exitCode"] == 0 and result["cleanupOk"] and
+                        result["listUnchanged"] and result["auditVerified"])
+    result["existingReservationConfirmed"] = result["passed"] and result["confirmedDetailMatched"]
+    print("ITA_RECEIPT_GATE_RESULT=" + json.dumps(result, sort_keys=True), flush=True)
+    return result["exitCode"]
+
+
+def main(argv=None) -> int:
+    parser = argparse.ArgumentParser(description=__doc__)
+    mode = parser.add_mutually_exclusive_group()
+    mode.add_argument("--preflight", action="store_true", help="Local checks only (default)")
+    mode.add_argument("--run", action="store_true", help="Log in and read an existing cancelled sample")
+    parser.add_argument("--non-interactive", action="store_true", help="Require ITA_BOOK_USERNAME/PASSWORD")
+    parser.add_argument("--expect-confirmed", action="store_true", help="Read one existing confirmed receipt matching all three expectations; never submit")
+    parser.add_argument("--expected-date", help="Existing receipt date, YYYY-MM-DD")
+    parser.add_argument("--expected-time", help="Assigned receipt time, HH:mm (not a slot range)")
+    parser.add_argument("--expected-service", help="Exact displayed service name, not a service ID")
+    args = parser.parse_args(argv)
+    return run_receipt_gate(os.environ, execute=args.run, non_interactive=args.non_interactive,
+                            expect_confirmed=args.expect_confirmed, expected_date=args.expected_date,
+                            expected_time=args.expected_time, expected_service=args.expected_service)
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 432 - 0
tools/debug_ita_session.py

@@ -0,0 +1,432 @@
+#!/usr/bin/env python3
+"""Run an isolated Italy-plugin login session without querying or booking.
+
+Credentials are read from environment variables or interactive prompts. They are
+never accepted as command-line arguments, which keeps them out of shell history
+and process listings.
+"""
+
+from __future__ import annotations
+
+import argparse
+import getpass
+import os
+import re
+import sys
+import traceback
+from datetime import datetime
+from pathlib import Path
+from typing import Mapping
+from urllib.parse import urlparse
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+import configure
+from plugins.ita_plugin import PERSISTENT_BROWSER_PROFILE_KEY, ItaPlugin
+from utils.ita_local_profile import (
+    ITA_QUERY_ACCOUNT_FILE,
+    ItaLocalProfileError,
+    prepare_ita_query_profile,
+)
+from utils.local_account import LocalAccountConfigurationError, load_local_account
+from vs_types import VSAccount, VSPlgConfig, VSProxy
+
+
+MACOS_CHROME_PATH = Path(
+    "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome"
+)
+
+
+class DebugConfigurationError(ValueError):
+    """Raised when the isolated debug session is configured unsafely."""
+
+
+_URL_PATTERN = re.compile(r"https?://[^\s\"'<>]+")
+_DYNAMIC_OAUTH_PARAMETER_PATTERN = re.compile(
+    r"\b(state|code|code_challenge|goto)=([^&\s]+)",
+    re.IGNORECASE,
+)
+
+
+def _url_for_log(raw_url: str) -> str:
+    parsed = urlparse(str(raw_url or ""))
+    path = parsed.path or "/"
+    if path.startswith("/signin/") and path != "/signin/":
+        path = "/signin/<redacted>"
+    if parsed.scheme and parsed.netloc:
+        return f"{parsed.scheme}://{parsed.netloc}{path}"
+    return path
+
+
+def _text_for_log(value: object) -> str:
+    sanitized = _URL_PATTERN.sub(
+        lambda match: _url_for_log(match.group(0)),
+        str(value),
+    )
+    return _DYNAMIC_OAUTH_PARAMETER_PATTERN.sub(
+        lambda match: f"{match.group(1)}=<redacted>",
+        sanitized,
+    )
+
+
+def _env_text(env: Mapping[str, str], name: str) -> str:
+    return env.get(name, "").strip()
+
+
+def _env_int(
+    env: Mapping[str, str],
+    name: str,
+    *,
+    default: int,
+    minimum: int = 0,
+) -> int:
+    raw_value = _env_text(env, name)
+    if not raw_value:
+        return default
+    try:
+        value = int(raw_value)
+    except ValueError as exc:
+        raise DebugConfigurationError(f"{name} must be an integer") from exc
+    if value < minimum:
+        raise DebugConfigurationError(f"{name} must be >= {minimum}")
+    return value
+
+
+def _env_bool(env: Mapping[str, str], name: str, *, default: bool) -> bool:
+    raw_value = _env_text(env, name).lower()
+    if not raw_value:
+        return default
+    if raw_value in {"1", "true", "yes", "on"}:
+        return True
+    if raw_value in {"0", "false", "no", "off"}:
+        return False
+    raise DebugConfigurationError(
+        f"{name} must be one of: 1/0, true/false, yes/no, on/off"
+    )
+
+
+def resolve_chrome_path(env: Mapping[str, str]) -> Path:
+    candidates = [
+        getattr(configure, "CHROME_PATH", None),
+        _env_text(env, "CHROME_BIN"),
+        str(MACOS_CHROME_PATH),
+    ]
+    for candidate in candidates:
+        if candidate:
+            path = Path(candidate).expanduser().resolve()
+            if path.is_file() and os.access(path, os.X_OK):
+                return path
+    raise DebugConfigurationError(
+        "Chromium executable not found. Set CHROME_BIN to an executable browser."
+    )
+
+
+def resolve_mihomo_path(env: Mapping[str, str]) -> Path:
+    candidates = [
+        getattr(configure, "MIHOMO_BIN_PATH", None),
+        _env_text(env, "MIHOMO_BIN"),
+    ]
+    for candidate in candidates:
+        if candidate:
+            path = Path(candidate).expanduser().resolve()
+            if path.is_file() and os.access(path, os.X_OK):
+                return path
+    raise DebugConfigurationError(
+        "Authenticated proxy requires an executable Mihomo binary. Set MIHOMO_BIN."
+    )
+
+
+def validate_proxy_settings(
+    env: Mapping[str, str],
+) -> tuple[str, int, str, str]:
+    proxy_ip = _env_text(env, "ITA_PROXY_IP")
+    proxy_username = _env_text(env, "ITA_PROXY_USERNAME")
+    proxy_password = _env_text(env, "ITA_PROXY_PASSWORD")
+    proxy_port = _env_int(
+        env,
+        "ITA_PROXY_PORT",
+        default=0,
+        minimum=0,
+    )
+
+    if not proxy_ip and (proxy_port or proxy_username or proxy_password):
+        raise DebugConfigurationError(
+            "ITA_PROXY_IP is required when other proxy settings are present"
+        )
+    if proxy_ip and proxy_port <= 0:
+        raise DebugConfigurationError(
+            "ITA_PROXY_PORT must be greater than zero when ITA_PROXY_IP is set"
+        )
+    if bool(proxy_username) != bool(proxy_password):
+        raise DebugConfigurationError(
+            "ITA_PROXY_USERNAME and ITA_PROXY_PASSWORD must be provided together"
+        )
+    if proxy_username:
+        resolve_mihomo_path(env)
+
+    return proxy_ip, proxy_port, proxy_username, proxy_password
+
+
+def build_plugin_config(
+    env: Mapping[str, str],
+    *,
+    username: str,
+    password: str,
+) -> VSPlgConfig:
+    username = username.strip()
+    if not username:
+        raise DebugConfigurationError("Italy test username is required")
+    if not password:
+        raise DebugConfigurationError("Italy test password is required")
+
+    proxy_ip, proxy_port, proxy_username, proxy_password = validate_proxy_settings(env)
+
+    service_id = _env_int(env, "ITA_SERVICE_ID", default=0, minimum=0)
+    free_config = {"service_id": service_id} if service_id else {}
+
+    return VSPlgConfig(
+        debug=_env_bool(env, "ITA_DEBUG", default=False),
+        account=VSAccount(
+            id=_env_int(env, "ITA_ACCOUNT_ID", default=0, minimum=0),
+            username=username,
+            password=password,
+        ),
+        proxy=VSProxy(
+            id=_env_int(env, "ITA_PROXY_ID", default=0, minimum=0),
+            proto=_env_text(env, "ITA_PROXY_PROTO") or "http",
+            ip=proxy_ip,
+            port=proxy_port,
+            username=proxy_username,
+            password=proxy_password,
+        ),
+        free_config=free_config,
+        session_max_life=_env_int(
+            env,
+            "ITA_SESSION_MAX_LIFE",
+            default=900,
+            minimum=1,
+        ),
+    )
+
+
+def _credential_status(env: Mapping[str, str]) -> str:
+    username_set = bool(_env_text(env, "ITA_USERNAME"))
+    password_set = bool(env.get("ITA_PASSWORD", ""))
+    return "ready" if username_set and password_set else "missing"
+
+
+def _proxy_status(env: Mapping[str, str]) -> str:
+    if not _env_text(env, "ITA_PROXY_IP"):
+        return "none"
+    if _env_text(env, "ITA_PROXY_USERNAME"):
+        return "authenticated"
+    return "direct"
+
+
+def run_preflight(env: Mapping[str, str]) -> int:
+    chrome_path = resolve_chrome_path(env)
+    validate_proxy_settings(env)
+    proxy_status = _proxy_status(env)
+    mihomo_status = "not-required"
+    if proxy_status == "authenticated":
+        mihomo_status = str(resolve_mihomo_path(env))
+
+    print("ITA_PREFLIGHT_OK")
+    print(f"python={sys.version.split()[0]}")
+    print(f"chrome={chrome_path}")
+    print(f"credentials={_credential_status(env)}")
+    print(f"proxy={proxy_status}")
+    print(f"mihomo={mihomo_status}")
+    print(f"service_id={'set' if _env_text(env, 'ITA_SERVICE_ID') else 'not-required-for-login'}")
+    print("external_request=not-performed")
+    return 0
+
+
+def _get_credentials(env: Mapping[str, str], *, non_interactive: bool) -> tuple[str, str]:
+    username = _env_text(env, "ITA_USERNAME")
+    password = env.get("ITA_PASSWORD", "")
+    if username and password:
+        return username, password
+    if non_interactive or not sys.stdin.isatty():
+        raise DebugConfigurationError(
+            "Set ITA_USERNAME and ITA_PASSWORD, or run interactively to enter them."
+        )
+    if not username:
+        username = input("Italy test username: ").strip()
+    if not password:
+        password = getpass.getpass("Italy test password: ")
+    return username, password
+
+
+def build_local_query_session_config(env: Mapping[str, str]) -> VSPlgConfig:
+    """Build a login-only config that shares the private local Query profile."""
+
+    try:
+        account = load_local_account(ITA_QUERY_ACCOUNT_FILE)
+        profile_path = prepare_ita_query_profile(account.username)
+    except (LocalAccountConfigurationError, ItaLocalProfileError) as exc:
+        raise DebugConfigurationError(
+            "Local Italy Query session configuration is invalid"
+        ) from exc
+
+    config = build_plugin_config(
+        env,
+        username=account.username,
+        password=account.password,
+    )
+    config.free_config = {
+        **config.free_config,
+        PERSISTENT_BROWSER_PROFILE_KEY: str(profile_path),
+    }
+    return config
+
+
+def _save_failure_diagnostics(plugin: ItaPlugin, output_dir: Path) -> None:
+    page = getattr(plugin, "page", None)
+    if page is None:
+        print("diagnostic_page=not-created")
+        return
+
+    try:
+        print(f"diagnostic_url={_url_for_log(page.url)}")
+    except Exception as exc:
+        print(
+            "diagnostic_url=unavailable "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+    try:
+        print(f"diagnostic_title={page.title}")
+    except Exception as exc:
+        print(
+            "diagnostic_title=unavailable "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+
+    output_dir.mkdir(parents=True, exist_ok=True)
+    timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")
+    screenshot_path = output_dir / f"ita-{plugin.instance_id}-{timestamp}.png"
+    try:
+        page.get_screenshot(path=str(screenshot_path), full_page=False)
+        print(f"diagnostic_screenshot={screenshot_path}")
+    except Exception as exc:
+        print(
+            "diagnostic_screenshot=failed "
+            f"({type(exc).__name__}: {_text_for_log(exc)})"
+        )
+
+
+def run_session(
+    env: Mapping[str, str],
+    *,
+    non_interactive: bool,
+    use_local_query_profile: bool = False,
+) -> int:
+    chrome_path = resolve_chrome_path(env)
+    os.environ["CHROME_BIN"] = str(chrome_path)
+
+    if use_local_query_profile:
+        config = build_local_query_session_config(env)
+    else:
+        username, password = _get_credentials(
+            env,
+            non_interactive=non_interactive,
+        )
+        config = build_plugin_config(env, username=username, password=password)
+    output_dir = Path(
+        _env_text(env, "ITA_DEBUG_OUTPUT_DIR") or REPO_ROOT / "data" / "ita_debug"
+    ).expanduser()
+
+    plugin = ItaPlugin(group_id="ita-local-debug")
+    plugin.set_log(lambda message: print(message, flush=True))
+    plugin.set_config(config)
+
+    exit_code = 0
+    cleanup_error: Exception | None = None
+    try:
+        plugin.create_session()
+        page = plugin.page
+        current_url = page.url if page else ""
+        current_path = urlparse(current_url).path.rstrip("/") or "/"
+        has_app_menu = bool(page and page.ele(".app-menu", timeout=0.5))
+        has_services_link = bool(page and page.ele("@href=/Services", timeout=0.5))
+        if (
+            current_path != "/UserArea"
+            or not has_app_menu
+            or not has_services_link
+        ):
+            raise RuntimeError(
+                "create_session returned without authenticated /UserArea "
+                f"markers: {_url_for_log(current_url)}"
+            )
+        print(f"ITA_SESSION_OK url={_url_for_log(current_url)}")
+    except Exception as exc:
+        print(
+            f"ITA_SESSION_FAILED type={type(exc).__name__} "
+            f"message={_text_for_log(exc)}"
+        )
+        _save_failure_diagnostics(plugin, output_dir)
+        sanitized_traceback = _text_for_log(
+            "".join(traceback.format_exception(type(exc), exc, exc.__traceback__))
+        )
+        print(sanitized_traceback, file=sys.stderr, end="")
+        exit_code = 1
+    finally:
+        try:
+            plugin.cleanup()
+            print("ITA_SESSION_CLEANUP_OK")
+        except Exception as exc:
+            cleanup_error = exc
+            print(
+                f"ITA_SESSION_CLEANUP_FAILED type={type(exc).__name__} "
+                f"message={_text_for_log(exc)}",
+                file=sys.stderr,
+            )
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description="Isolated Italy plugin login debugger (never queries or books)."
+    )
+    parser.add_argument(
+        "--preflight",
+        action="store_true",
+        help="Check the local runtime without opening a browser or making a request.",
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when credentials are missing.",
+    )
+    parser.add_argument(
+        "--local-query-account",
+        action="store_true",
+        help=(
+            "Use the ignored local Italy Query account and its persistent "
+            "browser profile; still performs login only."
+        ),
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    try:
+        if args.preflight:
+            return run_preflight(os.environ)
+        return run_session(
+            os.environ,
+            non_interactive=args.non_interactive,
+            use_local_query_profile=args.local_query_account,
+        )
+    except DebugConfigurationError as exc:
+        print(f"ITA_DEBUG_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 1170 - 0
tools/debug_ita_soak.py

@@ -0,0 +1,1170 @@
+#!/usr/bin/env python3
+"""Run a duration-bounded local Italy Query soak with no booking actions."""
+
+from __future__ import annotations
+
+import argparse
+import json
+import os
+import random
+import stat
+import sys
+import time
+import uuid
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Callable, Mapping
+
+from DrissionPage.errors import BrowserConnectError, PageDisconnectedError
+
+
+REPO_ROOT = Path(__file__).resolve().parents[1]
+if str(REPO_ROOT) not in sys.path:
+    sys.path.insert(0, str(REPO_ROOT))
+
+from plugins.ita_plugin import (
+    CALENDAR_QUERY_MODE,
+    ItaAuthenticationChallengeError,
+    ItaCalendarPreparationRequiredError,
+    ItaCalendarTransientError,
+    ItaPlugin,
+    ItaTargetServiceLinkMissingError,
+)
+from tools.debug_ita_query import (
+    _get_query_credentials,
+    _is_nonempty_query_result,
+    _is_weak_entry_signal,
+    _popup_text_for_log,
+    _prepare_query_profile,
+    _print_booking_form_structure,
+    _print_failure_context,
+    build_query_config,
+    resolve_debug_route,
+)
+from tools.debug_ita_session import (
+    DebugConfigurationError,
+    resolve_chrome_path,
+)
+from plugins.ita_calendar_query import CalendarGateError, guard_calendar
+from toolkit.backoff import ExponentialBackoff
+from vs_types import BizLogicError, PermissionDeniedError, RateLimiteddError, SessionExpiredOrInvalidError
+
+
+DAY_SECONDS = 24 * 60 * 60
+MIN_DURATION_SECONDS = 60
+DEFAULT_MIN_WAIT_SECONDS = 60
+DEFAULT_MAX_WAIT_SECONDS = 300
+DEFAULT_MAX_SESSION_ATTEMPTS = 0
+DEFAULT_SESSION_RESTART_WAIT_SECONDS = 60
+MAX_CONSECUTIVE_TARGET_LINK_MISSES = 2
+MAX_CONSECUTIVE_BROWSER_DISCONNECTS = 2
+MAX_CONSECUTIVE_SESSION_EXPIRATIONS = 2
+MAX_CONSECUTIVE_BROWSER_CONNECT_FAILURES = 2
+SESSION_REAUTHENTICATION_WINDOW_SECONDS = 60 * 60
+MAX_SESSION_REAUTHENTICATIONS_PER_WINDOW = 6
+SOAK_STATUS_PATH = REPO_ROOT / "data" / "ita_soak" / "status.json"
+CALENDAR_MIN_WAIT_SECONDS = 300
+_STATUS_KEYS = frozenset(
+    {
+        "state",
+        "service_id",
+        "routing_key",
+        "duration_seconds",
+        "elapsed_seconds",
+        "probes",
+        "none_available",
+        "transient_errors",
+        "consecutive_transient_errors",
+        "session_attempts",
+        "session_expirations",
+        "consecutive_session_expirations",
+        "session_reauthentications_last_hour",
+        "browser_disconnects",
+        "consecutive_browser_disconnects",
+        "browser_connect_failures",
+        "consecutive_browser_connect_failures",
+        "started_at",
+        "updated_at",
+        "exit_code",
+        "reason",
+        "calendar",
+    }
+)
+
+
+class _SoakCancelled(Exception):
+    """Internal control flow for a clean Ctrl+C."""
+
+
+class ItaSoakStatusError(ValueError):
+    """Raised when the private local soak status cannot be written safely."""
+
+
+class ItaSoakBrowserConnectLimitError(RuntimeError):
+    """Raised after two consecutive browser/CDP connection failures."""
+
+
+class ItaSoakSessionAttemptLimitError(RuntimeError):
+    """Raised when an optional explicit Session-attempt limit is reached."""
+
+
+def calendar_soak_limits(env: Mapping[str, str]) -> dict[str, int]:
+    """Parse the explicit Calendar experiment limits without reading secrets."""
+    defaults = {
+        "duration_seconds": 900,
+        "min_wait": CALENDAR_MIN_WAIT_SECONDS,
+        "max_wait": CALENDAR_MIN_WAIT_SECONDS,
+        "max_session_attempts": DEFAULT_MAX_SESSION_ATTEMPTS,
+        "restart_wait": DEFAULT_SESSION_RESTART_WAIT_SECONDS,
+        "restart_after_probes": 0,
+    }
+    limits = {}
+    for key, default in defaults.items():
+        try:
+            limits[key] = int(env.get(f"ITA_SOAK_{key.upper()}", str(default)))
+        except (TypeError, ValueError):
+            raise DebugConfigurationError(f"ITA_SOAK_{key.upper()} must be an integer") from None
+    _validate_soak_limits(**{key: value for key, value in limits.items() if key != "restart_after_probes"})
+    if limits["min_wait"] < CALENDAR_MIN_WAIT_SECONDS:
+        raise DebugConfigurationError("Calendar soak min_wait must be at least 300 seconds")
+    if limits["restart_after_probes"] < 0:
+        raise DebugConfigurationError("restart_after_probes must be nonnegative")
+    return limits
+
+
+class CalendarSoakContext:
+    """Calendar-specific evidence, composed with the existing soak lifecycle.
+
+    No scheduler, OTP reader, account pool, or publisher lives here. The owner
+    transfers a single already-prepared plugin and audit to run_soak().
+    """
+
+    def __init__(self, *, plugin, route, request_audit, before):
+        self.initial_plugin = plugin
+        self.route = route
+        self.config = plugin.config
+        self.before = before
+        self.audit = request_audit
+        self.audit.enable_time_slot_counting()
+        preparation = self.audit.settled_snapshot()
+        if (preparation["otpRequests"] != 1 or preparation["avantiPosts"] != 1
+                or preparation["finalRequests"] != 0):
+            raise CalendarGateError("Calendar preparation exceeded the one-shot contract")
+        self.preparation_counts = preparation
+        plugin.free_config["query_mode"] = CALENDAR_QUERY_MODE
+        self.config.free_config["query_mode"] = CALENDAR_QUERY_MODE
+        self.checkpoint = plugin.capture_calendar_query_checkpoint(route.appointment_type())
+        self.counts = {key: 0 for key in preparation}
+        self.last_counts = preparation
+        self.query_before = None
+        self.previous_scan = None
+        self.positive_queries = 0
+        self.negative_queries = 0
+        self.restores = 0
+        self.audit_gaps = 0
+        self._gap_recorded = False
+        self.reservation_verified = False
+        self.after = None
+        self.queries_in_current_session = 0
+        self.latest = None
+        self.failure_reason = ""
+        self.expiry_causes = {"configuredLifetime": 0, "authentication": 0}
+
+    def _collect(self, *, allow_disconnected: bool = False):
+        if self.audit is None:
+            return None
+        if self.audit.driver.is_running is not True:
+            if not allow_disconnected:
+                raise PageDisconnectedError("Calendar audit disconnected")
+            if not self._gap_recorded:
+                self.audit_gaps += 1
+                self._gap_recorded = True
+            current = self.audit.retained_snapshot()
+        else:
+            current = self.audit.settled_snapshot()
+        if set(current) != set(self.last_counts):
+            raise CalendarGateError("Calendar soak request counter shape changed")
+        delta = {key: current[key] - self.last_counts[key] for key in current}
+        if any(type(value) is not int or value < 0 for value in delta.values()):
+            raise CalendarGateError("Calendar soak request counters moved backwards")
+        for key, value in delta.items():
+            self.counts[key] += value
+        self.last_counts = current
+        if any(self.counts[key] for key in ("otpRequests", "avantiPosts", "finalRequests")):
+            raise CalendarGateError("Calendar soak observed a forbidden preparation/final request")
+        return current
+
+    def attach_restored_session(self, plugin):
+        from tools.debug_ita_calendar_gate import CalendarRequestAudit
+        self.audit = CalendarRequestAudit(plugin.page, include_time_slots=True)
+        self.audit.start()
+        self.last_counts = {key: 0 for key in self.counts}
+        self._gap_recorded = False
+        self.queries_in_current_session = 0
+        self.latest = None
+        plugin.restore_calendar_query(self.route.appointment_type(), self.checkpoint)
+        self._collect()
+        self.restores += 1
+        print(f"ITA_SOAK_CALENDAR_RESTORED restores={self.restores} fresh_proof=true", flush=True)
+
+    def begin_query(self, plugin):
+        self.latest = None  # A failed new probe must not expose an old date as current.
+        self.failure_reason = ""
+        self.previous_scan = plugin.last_calendar_query_scan
+        self.query_before = self._collect()
+
+    def record_query(self, plugin, result):
+        from tools.debug_ita_calendar_gate import _query_request_delta, validate_production_query_result
+        scan = plugin.last_calendar_query_scan
+        if scan is self.previous_scan:
+            raise CalendarGateError("Calendar soak reused old scan evidence")
+        report = validate_production_query_result(
+            result, scan, apt_type=self.route.appointment_type(),
+            lookahead_months=self.checkpoint.route.calendar_scan.lookahead_months,
+        )
+        after = self._collect()
+        standard_keys = {"otpRequests", "avantiPosts", "availabilityRequests", "finalRequests"}
+        report["queryRequestDelta"] = _query_request_delta(
+            {key: self.query_before[key] for key in standard_keys},
+            {key: after[key] for key in standard_keys},
+            expected_availability=scan.scanned_months,
+        )
+        report["automaticTimeSlots"] = after["timeSlotRequests"] - self.query_before["timeSlotRequests"]
+        guard_calendar(plugin.page)
+        if result.success:
+            self.positive_queries += 1
+        else:
+            self.negative_queries += 1
+        self.latest = report
+        self.queries_in_current_session += 1
+        print("ITA_SOAK_CALENDAR_QUERY_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
+
+    def close_session(self):
+        if self.audit is None:
+            return
+        audit = self.audit
+        try:
+            self._collect(allow_disconnected=True)
+        finally:
+            try:
+                audit.stop()
+            finally:
+                self.audit = None
+
+    def verify_end(self, plugin):
+        from tools.debug_ita_calendar_gate import read_reservation_snapshot
+        if plugin is None or not plugin.page:
+            return
+        self._collect(allow_disconnected=True)
+        if self.audit is None or self.audit.driver.is_running is not True:
+            return
+        after = read_reservation_snapshot(plugin.page)
+        self.after = after
+        if after != self.before:
+            raise CalendarGateError("Calendar soak reservation or waitlist counts changed")
+        self.reservation_verified = True
+
+    def safe_dict(self):
+        return {
+            "mode": "calendar", "positiveQueries": self.positive_queries,
+            "negativeQueries": self.negative_queries, "restores": self.restores,
+            "queryRequests": dict(self.counts), "auditGaps": self.audit_gaps,
+            "preparationRequests": dict(self.preparation_counts),
+            "expiryCauses": dict(self.expiry_causes),
+            "reservationVerified": self.reservation_verified,
+            "reservationBefore": {"reservations": self.before.reservations, "waitlist": self.before.waitlist},
+            "reservationAfter": (
+                {"reservations": self.after.reservations, "waitlist": self.after.waitlist}
+                if self.after is not None else None
+            ),
+            "queriesInCurrentSession": self.queries_in_current_session,
+            "latestQuery": self.latest, "failureReason": self.failure_reason,
+            "automaticOtpTodo": "ITA-OTP-01",
+        }
+
+
+def run_prepared_calendar_soak(env, *, plugin, route, request_audit, before) -> int:
+    """Take ownership from Q-CAL after exactly one manual preparation."""
+    try:
+        limits = calendar_soak_limits(env)
+        context = CalendarSoakContext(
+            plugin=plugin, route=route, request_audit=request_audit, before=before,
+        )
+    except Exception as exc:
+        print(f"ITA_SOAK_CALENDAR_SETUP_FAILED type={type(exc).__name__}", flush=True)
+        cleanup_failed = False
+        for action in (request_audit.stop, plugin.cleanup):
+            try:
+                action()
+            except Exception:
+                cleanup_failed = True
+        return 3 if cleanup_failed else 1
+    return run_soak(
+        env, apply=True, non_interactive=True, prepared_calendar=context, **limits,
+    )
+
+
+def _ensure_private_directory(path: Path) -> Path:
+    if path.is_symlink():
+        raise ItaSoakStatusError("Italy soak status directory must not be a symlink")
+    try:
+        path.mkdir(mode=0o700, parents=True, exist_ok=True)
+    except OSError as exc:
+        raise ItaSoakStatusError(
+            f"cannot create Italy soak status directory ({type(exc).__name__})"
+        ) from exc
+    if path.is_symlink() or not path.is_dir():
+        raise ItaSoakStatusError(
+            "Italy soak status path must be a private directory"
+        )
+    if os.name == "posix":
+        try:
+            path.chmod(0o700)
+            mode = stat.S_IMODE(path.stat().st_mode)
+        except OSError as exc:
+            raise ItaSoakStatusError(
+                f"cannot secure Italy soak status directory ({type(exc).__name__})"
+            ) from exc
+        if mode != 0o700:
+            raise ItaSoakStatusError(
+                "Italy soak status directory permissions must be 700"
+            )
+    return path.resolve()
+
+
+def write_soak_status(
+    body: Mapping[str, object],
+    *,
+    status_path: str | Path = SOAK_STATUS_PATH,
+) -> Path:
+    """Atomically write a metadata-only local status snapshot."""
+
+    unsupported = sorted(set(body) - _STATUS_KEYS)
+    if unsupported:
+        raise ItaSoakStatusError(
+            "Italy soak status contains unsupported keys: "
+            + ", ".join(unsupported)
+        )
+    path = Path(status_path).expanduser()
+    if not path.is_absolute():
+        path = REPO_ROOT / path
+    directory = _ensure_private_directory(path.parent)
+    resolved_path = directory / path.name
+    encoded = json.dumps(
+        dict(body),
+        ensure_ascii=True,
+        sort_keys=True,
+        separators=(",", ":"),
+    ).encode("utf-8")
+    temporary = directory / (
+        f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
+    )
+    descriptor: int | None = None
+    try:
+        flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+        flags |= getattr(os, "O_NOFOLLOW", 0)
+        descriptor = os.open(temporary, flags, 0o600)
+        if os.name == "posix":
+            os.fchmod(descriptor, 0o600)
+        with os.fdopen(descriptor, "wb") as handle:
+            descriptor = None
+            handle.write(encoded)
+            handle.flush()
+            os.fsync(handle.fileno())
+        os.replace(temporary, resolved_path)
+        if os.name == "posix":
+            resolved_path.chmod(0o600)
+            if stat.S_IMODE(resolved_path.stat().st_mode) != 0o600:
+                raise ItaSoakStatusError(
+                    "Italy soak status file permissions must be 600"
+                )
+    except ItaSoakStatusError:
+        raise
+    except OSError as exc:
+        raise ItaSoakStatusError(
+            f"cannot write Italy soak status ({type(exc).__name__})"
+        ) from exc
+    finally:
+        if descriptor is not None:
+            os.close(descriptor)
+        try:
+            temporary.unlink()
+        except FileNotFoundError:
+            pass
+        except OSError:
+            pass
+    return resolved_path
+
+
+def _validate_soak_limits(
+    *,
+    duration_seconds: int,
+    min_wait: int,
+    max_wait: int,
+    max_session_attempts: int,
+    restart_wait: int,
+) -> None:
+    if not MIN_DURATION_SECONDS <= duration_seconds <= DAY_SECONDS:
+        raise DebugConfigurationError(
+            f"duration_seconds must be between {MIN_DURATION_SECONDS} "
+            f"and {DAY_SECONDS}"
+        )
+    if min_wait < DEFAULT_MIN_WAIT_SECONDS:
+        raise DebugConfigurationError(
+            f"min_wait must be at least {DEFAULT_MIN_WAIT_SECONDS} seconds"
+        )
+    if max_wait < min_wait:
+        raise DebugConfigurationError("max_wait must be greater than min_wait")
+    if max_session_attempts < 0:
+        raise DebugConfigurationError(
+            "max_session_attempts must be 0 (duration-bounded) or positive"
+        )
+    if restart_wait < DEFAULT_SESSION_RESTART_WAIT_SECONDS:
+        raise DebugConfigurationError(
+            "restart_wait must be at least "
+            f"{DEFAULT_SESSION_RESTART_WAIT_SECONDS} seconds"
+        )
+
+
+def _service_list_structure_for_log(plugin: ItaPlugin) -> str:
+    raw = getattr(plugin, "last_service_list_structure", None)
+    if not isinstance(raw, dict):
+        return "not-available"
+    allowed = {
+        "path": raw.get("path"),
+        "ready_state": raw.get("ready_state"),
+        "table_count": int(raw.get("table_count") or 0),
+        "row_count": int(raw.get("row_count") or 0),
+        "booking_link_count": int(raw.get("booking_link_count") or 0),
+        "target_link_count": int(raw.get("target_link_count") or 0),
+    }
+    return json.dumps(allowed, ensure_ascii=True, sort_keys=True)
+
+
+def run_soak(
+    env: Mapping[str, str],
+    *,
+    apply: bool,
+    non_interactive: bool,
+    duration_seconds: int,
+    min_wait: int,
+    max_wait: int,
+    max_session_attempts: int = DEFAULT_MAX_SESSION_ATTEMPTS,
+    restart_wait: int = DEFAULT_SESSION_RESTART_WAIT_SECONDS,
+    randint: Callable[[int, int], int] = random.randint,
+    sleep: Callable[[float], None] = time.sleep,
+    monotonic: Callable[[], float] = time.monotonic,
+    wall_time: Callable[[], float] = time.time,
+    plugin_factory: Callable[[str], ItaPlugin] | None = None,
+    status_writer: Callable[[Mapping[str, object]], object] | None = None,
+    prepared_calendar: CalendarSoakContext | None = None,
+    restart_after_probes: int = 0,
+) -> int:
+    # The prepared instance owns its verified route. Do not reinterpret the
+    # environment after ownership has transferred from the Calendar gate.
+    route = prepared_calendar.route if prepared_calendar is not None else resolve_debug_route(env)
+    route_log = (
+        f"service_id={route.service_id} routing_key={route.routing_key}"
+    )
+    _validate_soak_limits(
+        duration_seconds=duration_seconds,
+        min_wait=min_wait,
+        max_wait=max_wait,
+        max_session_attempts=max_session_attempts,
+        restart_wait=restart_wait,
+    )
+    if prepared_calendar is not None and min_wait < CALENDAR_MIN_WAIT_SECONDS:
+        raise DebugConfigurationError("Calendar soak min_wait must be at least 300 seconds")
+    if type(restart_after_probes) is not int or restart_after_probes < 0:
+        raise DebugConfigurationError("restart_after_probes must be a nonnegative integer")
+    if restart_after_probes and prepared_calendar is None:
+        raise DebugConfigurationError("Controlled restart requires the prepared Calendar mode")
+    if not apply:
+        print(
+            "ITA_SOAK_PREFLIGHT_OK "
+            f"{route_log} "
+            f"duration_seconds={duration_seconds} "
+            f"min_wait={min_wait} max_wait={max_wait} "
+            f"max_session_attempts={max_session_attempts} "
+            "external_request=false"
+        )
+        return 0
+
+    if prepared_calendar is None:
+        chrome_path = resolve_chrome_path(env)
+        os.environ["CHROME_BIN"] = str(chrome_path)
+        username, password = _get_query_credentials(
+            env,
+            non_interactive=non_interactive,
+        )
+        profile_path = _prepare_query_profile(username)
+        config = build_query_config(
+            env,
+            username=username,
+            password=password,
+            persistent_profile_path=profile_path,
+            route=route,
+        )
+    else:
+        config = prepared_calendar.config
+    factory = plugin_factory or ItaPlugin
+    writer = status_writer or write_soak_status
+    apt_type = route.appointment_type()
+
+    monitor_started = monotonic()
+    started_wall = wall_time()
+    plugin: ItaPlugin | None = prepared_calendar.initial_plugin if prepared_calendar else None
+    current_session = 1 if prepared_calendar else 0
+    probes = 0
+    none_available = 0
+    transient_errors = 0
+    consecutive_transient_errors = 0
+    session_attempts = current_session
+    session_expirations = 0
+    consecutive_session_expirations = 0
+    session_reauthentication_times: list[float] = []
+    browser_disconnects = 0
+    consecutive_browser_disconnects = 0
+    browser_connect_failures = 0
+    consecutive_browser_connect_failures = 0
+    exit_code = 0
+    final_state = "running"
+    final_reason = ""
+    cleanup_error: Exception | None = None
+    controlled_restart_done = False
+    consecutive_calendar_network_errors = 0
+    network_backoff = ExponentialBackoff(
+        base_delay=restart_wait, max_delay=max_wait, jitter_range=(0, 0),
+    )
+
+    def elapsed_seconds() -> int:
+        elapsed = max(0.0, monotonic() - monitor_started)
+        return min(duration_seconds, int(elapsed))
+
+    def status_body(state: str, *, code: int | None = None) -> dict:
+        now = wall_time()
+        current_monotonic = monotonic()
+        reauthentications_last_hour = sum(
+            1
+            for timestamp in session_reauthentication_times
+            if 0
+            <= current_monotonic - timestamp
+            < SESSION_REAUTHENTICATION_WINDOW_SECONDS
+        )
+        body = {
+            "state": state,
+            "service_id": route.service_id,
+            "routing_key": apt_type.routing_key,
+            "duration_seconds": duration_seconds,
+            "elapsed_seconds": elapsed_seconds(),
+            "probes": probes,
+            "none_available": none_available,
+            "transient_errors": transient_errors,
+            "consecutive_transient_errors": consecutive_transient_errors,
+            "session_attempts": session_attempts,
+            "session_expirations": session_expirations,
+            "consecutive_session_expirations": (
+                consecutive_session_expirations
+            ),
+            "session_reauthentications_last_hour": (
+                reauthentications_last_hour
+            ),
+            "browser_disconnects": browser_disconnects,
+            "consecutive_browser_disconnects": (
+                consecutive_browser_disconnects
+            ),
+            "browser_connect_failures": browser_connect_failures,
+            "consecutive_browser_connect_failures": (
+                consecutive_browser_connect_failures
+            ),
+            "started_at": datetime.fromtimestamp(
+                started_wall,
+                tz=timezone.utc,
+            ).isoformat(),
+            "updated_at": datetime.fromtimestamp(
+                now,
+                tz=timezone.utc,
+            ).isoformat(),
+        }
+        if code is not None:
+            body["exit_code"] = code
+        if final_reason:
+            body["reason"] = final_reason
+        if prepared_calendar is not None:
+            body["calendar"] = prepared_calendar.safe_dict()
+        return body
+
+    def emit_status(state: str, *, code: int | None = None) -> None:
+        writer(status_body(state, code=code))
+
+    def cleanup_session(reason: str) -> None:
+        nonlocal plugin, cleanup_error
+        if plugin is None:
+            return
+        instance = plugin
+        plugin = None
+        try:
+            try:
+                if prepared_calendar is not None:
+                    prepared_calendar.close_session()
+            finally:
+                instance.cleanup()
+        except Exception as exc:
+            cleanup_error = exc
+            raise
+        print(
+            "ITA_SOAK_SESSION_CLEANUP_OK "
+            f"session={current_session} reason={reason}",
+            flush=True,
+        )
+
+    def wait_before_session_restart() -> bool:
+        remaining = duration_seconds - (monotonic() - monitor_started)
+        wait_seconds = min(float(restart_wait), max(0.0, remaining))
+        if wait_seconds:
+            print(
+                "ITA_SOAK_SESSION_RESTART_WAIT "
+                f"seconds={int(wait_seconds)}",
+                flush=True,
+            )
+            sleep(wait_seconds)
+        return monotonic() - monitor_started < duration_seconds
+
+    def start_session() -> bool:
+        nonlocal plugin
+        nonlocal current_session
+        nonlocal session_attempts
+        nonlocal transient_errors
+        nonlocal browser_connect_failures
+        nonlocal consecutive_browser_connect_failures
+
+        while monotonic() - monitor_started < duration_seconds:
+            if (
+                max_session_attempts > 0
+                and session_attempts >= max_session_attempts
+            ):
+                raise ItaSoakSessionAttemptLimitError
+            session_attempts += 1
+            current_session = session_attempts
+            instance = factory("ita-soak-local-debug")
+            plugin = instance
+            instance.set_log(lambda message: print(message, flush=True))
+            instance.set_config(config)
+            try:
+                instance.create_session()
+            except BrowserConnectError:
+                browser_connect_failures += 1
+                transient_errors += 1
+                consecutive_browser_connect_failures += 1
+                print(
+                    "ITA_SOAK_BROWSER_CONNECT_FAILED "
+                    f"session_attempt={current_session} "
+                    f"consecutive={consecutive_browser_connect_failures} "
+                    f"total={browser_connect_failures}",
+                    flush=True,
+                )
+                cleanup_session("browser-connect-failed")
+                if (
+                    consecutive_browser_connect_failures
+                    >= MAX_CONSECUTIVE_BROWSER_CONNECT_FAILURES
+                ):
+                    raise ItaSoakBrowserConnectLimitError
+                if not wait_before_session_restart():
+                    return False
+                continue
+
+            consecutive_browser_connect_failures = 0
+            if prepared_calendar is not None:
+                prepared_calendar.attach_restored_session(instance)
+            print(
+                "ITA_SOAK_SESSION_STARTED "
+                f"session={current_session} "
+                f"session_attempts={session_attempts}",
+                flush=True,
+            )
+            return True
+        return False
+
+    try:
+        if plugin is None:
+            start_session()
+        print(
+            "ITA_SOAK_STARTED "
+            f"{route_log} "
+            f"duration_seconds={duration_seconds} "
+            f"min_wait={min_wait} max_wait={max_wait}",
+            flush=True,
+        )
+        emit_status("running")
+
+        while True:
+            if monotonic() - monitor_started >= duration_seconds:
+                final_state = "completed"
+                print(
+                    "ITA_SOAK_COMPLETED "
+                    f"duration_seconds={duration_seconds} probes={probes} "
+                    f"none_available={none_available} "
+                    f"transient_errors={transient_errors} "
+                    f"session_attempts={session_attempts}",
+                    flush=True,
+                )
+                break
+
+            if (prepared_calendar is not None and restart_after_probes
+                    and not controlled_restart_done
+                    and prepared_calendar.positive_queries + prepared_calendar.negative_queries >= restart_after_probes):
+                # A deliberate normal close tests ownership and restore, not
+                # a fabricated website outage or an authentication expiry.
+                controlled_restart_done = True
+                emit_status("controlled_restart")
+                cleanup_session("controlled-restart")
+                if not wait_before_session_restart():
+                    continue
+                start_session()
+                emit_status("running")
+                continue
+
+            probes += 1
+            print(
+                "ITA_SOAK_PROBE_START "
+                f"probe={probes} session={current_session} "
+                f"elapsed_seconds={elapsed_seconds()}",
+                flush=True,
+            )
+            try:
+                if prepared_calendar is not None:
+                    if not plugin.health_check():
+                        if getattr(plugin, "_query_stop_reason", None) == "browser_disconnected":
+                            raise PageDisconnectedError("Calendar browser disconnected")
+                        raise SessionExpiredOrInvalidError("Calendar Session health expired")
+                    prepared_calendar.begin_query(plugin)
+                result = plugin.query(apt_type)
+                if prepared_calendar is not None:
+                    prepared_calendar.record_query(plugin, result)
+            except ItaCalendarTransientError:
+                if prepared_calendar is None:
+                    raise
+                prepared_calendar.latest = None
+                transient_errors += 1
+                consecutive_calendar_network_errors += 1
+                prepared_calendar.failure_reason = "transient-network"
+                emit_status("cooldown")
+                if consecutive_calendar_network_errors >= 2:
+                    final_state, final_reason, exit_code = "failed", "consecutive-calendar-network-errors", 1
+                    break
+                remaining = duration_seconds - (monotonic() - monitor_started)
+                sleep(min(network_backoff.calculate(consecutive_calendar_network_errors), max(0.0, remaining)))
+                continue
+            except ItaTargetServiceLinkMissingError:
+                consecutive_session_expirations = 0
+                consecutive_browser_disconnects = 0
+                transient_errors += 1
+                consecutive_transient_errors += 1
+                print(
+                    "ITA_SERVICE_LIST_STRUCTURE="
+                    + _service_list_structure_for_log(plugin),
+                    flush=True,
+                )
+                print(
+                    "ITA_SOAK_TRANSIENT "
+                    "type=ItaTargetServiceLinkMissingError "
+                    f"consecutive={consecutive_transient_errors} "
+                    f"total={transient_errors}",
+                    flush=True,
+                )
+                if (
+                    consecutive_transient_errors
+                    >= MAX_CONSECUTIVE_TARGET_LINK_MISSES
+                ):
+                    final_state = "failed"
+                    final_reason = "consecutive-target-link-misses"
+                    exit_code = 1
+                    print(
+                        "ITA_SOAK_FAILED "
+                        "reason=consecutive-target-link-misses",
+                        flush=True,
+                    )
+                    break
+            except PageDisconnectedError:
+                if prepared_calendar is not None:
+                    prepared_calendar.latest = None
+                    prepared_calendar.failure_reason = "browser-disconnected"
+                browser_disconnects += 1
+                transient_errors += 1
+                consecutive_browser_disconnects += 1
+                consecutive_transient_errors = 0
+                print(
+                    "ITA_SOAK_BROWSER_DISCONNECTED "
+                    f"session={current_session} "
+                    f"consecutive={consecutive_browser_disconnects} "
+                    f"total={browser_disconnects}",
+                    flush=True,
+                )
+                cleanup_session("browser-disconnected")
+                if (
+                    consecutive_browser_disconnects
+                    >= MAX_CONSECUTIVE_BROWSER_DISCONNECTS
+                ):
+                    final_state = "failed"
+                    final_reason = "consecutive-browser-disconnects"
+                    exit_code = 1
+                    print(
+                        "ITA_SOAK_FAILED "
+                        "reason=consecutive-browser-disconnects",
+                        flush=True,
+                    )
+                    break
+                if not wait_before_session_restart():
+                    continue
+                start_session()
+                emit_status("running")
+                continue
+            except SessionExpiredOrInvalidError:
+                if prepared_calendar is not None:
+                    prepared_calendar.latest = None
+                    prepared_calendar.failure_reason = "session-expired"
+                    expiry_cause = (
+                        "configuredLifetime"
+                        if getattr(plugin, "_query_stop_reason", None) == "configured_lifetime_reached"
+                        else "authentication"
+                    )
+                    prepared_calendar.expiry_causes[expiry_cause] += 1
+                session_expirations += 1
+                consecutive_session_expirations += 1
+                consecutive_transient_errors = 0
+                consecutive_browser_disconnects = 0
+                current_monotonic = monotonic()
+                session_reauthentication_times[:] = [
+                    timestamp
+                    for timestamp in session_reauthentication_times
+                    if 0
+                    <= current_monotonic - timestamp
+                    < SESSION_REAUTHENTICATION_WINDOW_SECONDS
+                ]
+                session_reauthentication_times.append(current_monotonic)
+                reauthentications_last_hour = len(
+                    session_reauthentication_times
+                )
+                print(
+                    "ITA_SOAK_SESSION_EXPIRED "
+                    f"session={current_session} "
+                    f"session_expirations={session_expirations} "
+                    f"consecutive={consecutive_session_expirations} "
+                    f"reauthentications_last_hour="
+                    f"{reauthentications_last_hour}",
+                    flush=True,
+                )
+                cleanup_session("session-expired")
+                if (
+                    consecutive_session_expirations
+                    >= MAX_CONSECUTIVE_SESSION_EXPIRATIONS
+                ):
+                    final_state = "failed"
+                    final_reason = "consecutive-session-expirations"
+                    exit_code = 1
+                    print(
+                        "ITA_SOAK_FAILED "
+                        "reason=consecutive-session-expirations",
+                        flush=True,
+                    )
+                    break
+                if (
+                    reauthentications_last_hour
+                    > MAX_SESSION_REAUTHENTICATIONS_PER_WINDOW
+                ):
+                    final_state = "failed"
+                    final_reason = "reauthentication-rate-limit"
+                    exit_code = 1
+                    print(
+                        "ITA_SOAK_FAILED "
+                        "reason=reauthentication-rate-limit",
+                        flush=True,
+                    )
+                    break
+                if not wait_before_session_restart():
+                    continue
+                start_session()
+                emit_status("running")
+                continue
+            else:
+                consecutive_calendar_network_errors = 0
+                consecutive_transient_errors = 0
+                consecutive_session_expirations = 0
+                consecutive_browser_disconnects = 0
+                if prepared_calendar is not None:
+                    if not result.success:
+                        none_available += 1
+                elif _is_weak_entry_signal(result):
+                    _print_booking_form_structure(plugin, route=route)
+                    final_state = "weak_signal"
+                    final_reason = "booking-form"
+                    exit_code = 4
+                    print(
+                        "\aITA_SOAK_WEAK_SIGNAL "
+                        f"{route_log} probe={probes} "
+                        "evidence=booking-form",
+                        flush=True,
+                    )
+                    break
+                elif _is_nonempty_query_result(result):
+                    final_state = "safe_stop"
+                    final_reason = "unexpected-non-empty-result"
+                    exit_code = 4
+                    print(
+                        "ITA_SOAK_SAFE_STOP "
+                        "reason=unexpected-non-empty-result",
+                        flush=True,
+                    )
+                    break
+                if prepared_calendar is None:
+                    none_available += 1
+                    print(
+                        "ITA_SOAK_NONE_AVAILABLE "
+                        f"probe={probes} session={current_session}",
+                        flush=True,
+                    )
+
+            emit_status("running")
+            remaining = duration_seconds - (monotonic() - monitor_started)
+            if remaining <= 0:
+                continue
+            wait_seconds = min(float(randint(min_wait, max_wait)), remaining)
+            print(
+                "ITA_SOAK_WAIT "
+                f"next_probe={probes + 1} seconds={int(wait_seconds)}",
+                flush=True,
+            )
+            sleep(wait_seconds)
+    except ItaSoakBrowserConnectLimitError:
+        final_state = "failed"
+        final_reason = "consecutive-browser-connect-failures"
+        exit_code = 1
+        print(
+            "ITA_SOAK_FAILED "
+            "reason=consecutive-browser-connect-failures",
+            flush=True,
+        )
+    except ItaSoakSessionAttemptLimitError:
+        final_state = "failed"
+        final_reason = "max-session-attempts-reached"
+        exit_code = 1
+        print(
+            "ITA_SOAK_FAILED reason=max-session-attempts-reached",
+            flush=True,
+        )
+    except ItaCalendarPreparationRequiredError:
+        final_state, final_reason, exit_code = "needs_manual", "calendar-preparation-required", 4
+        if prepared_calendar is not None:
+            prepared_calendar.latest = None
+            prepared_calendar.failure_reason = final_reason
+        print("ITA_SOAK_NEEDS_MANUAL todo=ITA-OTP-01 otp_sent=false avanti_submitted=false", flush=True)
+    except (PermissionDeniedError, ItaAuthenticationChallengeError):
+        final_state, final_reason, exit_code = "needs_manual", "website-verification-required", 4
+        print("ITA_SOAK_NEEDS_MANUAL reason=website-verification-required", flush=True)
+    except RateLimiteddError:
+        final_state, final_reason, exit_code = "rate_limited", "server-rate-limit", 5
+        print("ITA_SOAK_RATE_LIMITED retry=false account_rotation=false", flush=True)
+    except KeyboardInterrupt:
+        final_state = "cancelled"
+        final_reason = "operator-cancelled"
+        exit_code = 130
+        print(
+            "\nITA_SOAK_CANCELLED reason=operator-cancelled",
+            flush=True,
+        )
+    except (BizLogicError, CalendarGateError) as exc:
+        final_state = "failed"
+        final_reason = "business-error"
+        exit_code = 1
+        print(
+            f"ITA_SOAK_FAILED type={type(exc).__name__} "
+            f"message={'details-withheld' if prepared_calendar else _popup_text_for_log(exc)}",
+            flush=True,
+        )
+        if plugin is not None and prepared_calendar is None:
+            _print_failure_context(plugin)
+    except Exception as exc:
+        final_state = "failed"
+        final_reason = "unexpected-error"
+        exit_code = 1
+        print(
+            f"ITA_SOAK_FAILED type={type(exc).__name__} "
+            f"message={'details-withheld' if prepared_calendar else _popup_text_for_log(exc)}",
+            flush=True,
+        )
+        if plugin is not None and prepared_calendar is None:
+            _print_failure_context(plugin)
+    finally:
+        if prepared_calendar is not None:
+            if exit_code != 0:
+                prepared_calendar.latest = None
+                prepared_calendar.failure_reason = final_reason
+            try:
+                prepared_calendar.verify_end(plugin)
+            except Exception as exc:
+                print(f"ITA_SOAK_END_EVIDENCE_UNAVAILABLE type={type(exc).__name__}", flush=True)
+            if exit_code == 0:
+                has_queries = prepared_calendar.positive_queries + prepared_calendar.negative_queries > 0
+                if (not has_queries or prepared_calendar.audit_gaps
+                        or not prepared_calendar.reservation_verified
+                        or prepared_calendar.queries_in_current_session == 0
+                        or consecutive_calendar_network_errors
+                        or consecutive_session_expirations or consecutive_browser_disconnects
+                        or (restart_after_probes and not controlled_restart_done)):
+                    final_state, final_reason, exit_code = "incomplete", "calendar-evidence-incomplete", 6
+        try:
+            cleanup_session("soak-finished")
+        except Exception as exc:
+            cleanup_error = exc
+        if cleanup_error is not None:
+            final_state = "failed"
+            final_reason = "cleanup-failed"
+            print(
+                f"ITA_SOAK_CLEANUP_FAILED type={type(cleanup_error).__name__} "
+                f"message={'details-withheld' if prepared_calendar else _popup_text_for_log(cleanup_error)}",
+                file=sys.stderr,
+                flush=True,
+            )
+        else:
+            print("ITA_SOAK_CLEANUP_OK", flush=True)
+        final_code = 3 if cleanup_error is not None else exit_code
+        if prepared_calendar is not None and final_code != 0:
+            prepared_calendar.failure_reason = final_reason
+            prepared_calendar.latest = None
+        try:
+            emit_status(final_state, code=final_code)
+        except Exception as exc:
+            cleanup_error = cleanup_error or exc
+            if prepared_calendar is not None:
+                final_state, final_reason = "failed", "status-write-failed"
+                prepared_calendar.failure_reason = final_reason
+            print(
+                f"ITA_SOAK_STATUS_FAILED type={type(exc).__name__}",
+                file=sys.stderr,
+                flush=True,
+            )
+        if prepared_calendar is not None:
+            report = prepared_calendar.safe_dict()
+            report.update({
+                "state": final_state, "reason": final_reason,
+                "elapsedSeconds": max(0, int(monotonic() - monitor_started)), "queryAttempts": probes,
+                "sessionAttempts": session_attempts,
+                "controlledRestart": controlled_restart_done,
+                "exitCode": 3 if cleanup_error is not None else exit_code,
+                "passed": cleanup_error is None and exit_code == 0,
+            })
+            print("ITA_SOAK_CALENDAR_RESULT=" + json.dumps(report, sort_keys=True), flush=True)
+
+    return 3 if cleanup_error is not None else exit_code
+
+
+def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
+    parser = argparse.ArgumentParser(
+        description=(
+            "Duration-bounded route-configured Italy Query soak. Without --run, "
+            "performs a zero-network preflight only."
+        )
+    )
+    parser.add_argument(
+        "--calendar",
+        action="store_true",
+        help="Use one manual Calendar preparation, then the production Query and read-only recovery.",
+    )
+    parser.add_argument(
+        "--run",
+        action="store_true",
+        help="Start the real website soak.",
+    )
+    parser.add_argument(
+        "--non-interactive",
+        action="store_true",
+        help="Fail instead of prompting when local credentials are unavailable.",
+    )
+    parser.add_argument(
+        "--duration-seconds",
+        type=int,
+        default=None,
+        help=f"Soak duration in seconds (maximum: {DAY_SECONDS}).",
+    )
+    parser.add_argument(
+        "--min-wait",
+        type=int,
+        default=None,
+        help=f"Minimum seconds between probes (Calendar floor: {CALENDAR_MIN_WAIT_SECONDS}; entry-probe floor: {DEFAULT_MIN_WAIT_SECONDS}).",
+    )
+    parser.add_argument(
+        "--max-wait",
+        type=int,
+        default=None,
+        help="Maximum seconds between probes.",
+    )
+    parser.add_argument(
+        "--max-session-attempts",
+        type=int,
+        default=DEFAULT_MAX_SESSION_ATTEMPTS,
+        help=(
+            "Optional total Session-attempt limit; 0 uses the duration and "
+            "reauthentication circuit breakers only."
+        ),
+    )
+    parser.add_argument(
+        "--restart-wait",
+        type=int,
+        default=DEFAULT_SESSION_RESTART_WAIT_SECONDS,
+        help=(
+            "Minimum seconds before recreating an explicitly expired Session "
+            f"(floor: {DEFAULT_SESSION_RESTART_WAIT_SECONDS})."
+        ),
+    )
+    parser.add_argument(
+        "--restart-after-probes", type=int, default=0,
+        help="Calendar only: normally close/recreate once after this many successful queries (0 disables).",
+    )
+    return parser.parse_args(argv)
+
+
+def main(argv: list[str] | None = None) -> int:
+    args = parse_args(argv)
+    try:
+        if args.calendar:
+            from tools.debug_ita_calendar_gate import build_calendar_gate_config, run_calendar_gate
+            env = dict(os.environ)
+            for key in (
+                "duration_seconds", "min_wait", "max_wait", "max_session_attempts",
+                "restart_wait", "restart_after_probes",
+            ):
+                value = getattr(args, key)
+                if value is not None:
+                    env[f"ITA_SOAK_{key.upper()}"] = str(value)
+            limits = calendar_soak_limits(env)
+            # Configuration only: no credential lookup, profile creation, or login.
+            build_calendar_gate_config(
+                env, username="preflight@example.invalid", password="unused-preflight",
+            )
+            if not args.run:
+                print("ITA_SOAK_CALENDAR_PREFLIGHT_OK " + json.dumps(limits, sort_keys=True)
+                      + " external_request=false", flush=True)
+                return 0
+            if args.non_interactive:
+                raise DebugConfigurationError("Calendar preparation currently requires manual OTP input")
+            env["ITA_QCAL_MODE"] = "calendar_soak"
+            return run_calendar_gate(env)
+        if args.restart_after_probes:
+            raise DebugConfigurationError("--restart-after-probes requires --calendar")
+        return run_soak(
+            os.environ,
+            apply=args.run,
+            non_interactive=args.non_interactive,
+            duration_seconds=args.duration_seconds if args.duration_seconds is not None else DAY_SECONDS,
+            min_wait=args.min_wait if args.min_wait is not None else DEFAULT_MIN_WAIT_SECONDS,
+            max_wait=args.max_wait if args.max_wait is not None else DEFAULT_MAX_WAIT_SECONDS,
+            max_session_attempts=args.max_session_attempts,
+            restart_wait=args.restart_wait,
+        )
+    except (DebugConfigurationError, CalendarGateError) as exc:
+        print(f"ITA_SOAK_CONFIG_ERROR: {exc}", file=sys.stderr)
+        return 2
+
+
+if __name__ == "__main__":
+    raise SystemExit(main())

+ 180 - 0
tools/ita_final_evidence.py

@@ -0,0 +1,180 @@
+"""Opt-in local final discovery. Never enables the production Book switch.
+
+Reuses the final core, native website click and bound receipt reader. A private,
+exclusive file prevents a second attempt in this checkout even after a crash.
+It is deliberately never removed automatically. This is NOT a distributed
+production fence, nor proof that an unknown receipt is an active appointment.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+from pathlib import Path
+
+from plugins.ita_booking_final import (
+    FinalBookingAttempt, FinalBookingError, FinalOutcomeUnknown, NativeFinalSubmitter,
+    ReservationState, SubmissionSignal, VerifiedSubmission,
+)
+from plugins.ita_calendar_book import verify_precommit_selection
+from plugins.ita_final_read_port import FinalReceiptReadPort, _cancelled_record
+from tools.ita_local_handoff import ITA_LOCAL_HANDOFF_ROOT, _ensure_private_directory
+
+
+FINAL_CLAIM = ITA_LOCAL_HANDOFF_ROOT / "final-evidence-once.claim"
+
+
+def require_unused_claim(path: Path = FINAL_CLAIM) -> None:
+    # Includes dangling symlinks. No file/directory creation during preflight.
+    if path.exists() or path.is_symlink():
+        raise FinalBookingError("Local final attempt is already fenced; reconcile before any new attempt")
+
+
+def claim_once(path: Path = FINAL_CLAIM) -> None:
+    """O_EXCL before dispatch; even partial/empty files remain blocking."""
+    parent = _ensure_private_directory(path.parent)
+    if parent != path.parent.resolve():
+        raise FinalBookingError("Local final fence directory changed")
+    descriptor = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600)
+    with os.fdopen(descriptor, "wb") as stream:
+        stream.write(b'{"schema":1,"state":"possibly_submitted","automaticRetry":false}\n')
+        stream.flush()
+        os.fsync(stream.fileno())
+    directory = os.open(parent, os.O_RDONLY | getattr(os, "O_DIRECTORY", 0))
+    try:
+        os.fsync(directory)
+    finally:
+        os.close(directory)
+
+
+class FinalEvidenceRun:
+    """One local diagnostic, using the original Book session and selection."""
+
+    def __init__(self, plugin, route, *, observe_tab=None, claim_path=FINAL_CLAIM, verify_submission=None):
+        self.plugin = plugin
+        self.port = FinalReceiptReadPort(plugin, route, observe_tab=observe_tab)
+        self.claim_path = claim_path
+        self.possibly_submitted = False
+        self.signal = SubmissionSignal.UNKNOWN
+        self._used = False
+        self.before = None
+        self.result = None
+        self._verify_submission = verify_submission
+        self.report = {"attempted": False, "automaticRetry": False, "bookingConfirmed": False,
+                       "receiptEvidence": None, "outcome": "not_submitted"}
+
+    def _current_selection(self):
+        if not self.port.session_is_current():
+            raise FinalBookingError("Final evidence Session changed")
+        verify_precommit_selection(self.plugin.page, runtime_service=self.port.target.runtime_service,
+                                   approval=self.port.target.approval)
+
+    def execute(self, *, confirm=input) -> dict:
+        if self._used:
+            raise FinalBookingError("Local final evidence run is already consumed")
+        self._used = True
+        require_unused_claim(self.claim_path)
+        self._current_selection()
+        slot = self.port.target.approval.candidate
+        phrase = f"BOOK {slot.day.isoformat()} {slot.time_label}"
+        print("ITA_FINAL_CONFIRM_TARGET=" + json.dumps({
+            "routingKey": self.port.target.routing_key, "serviceId": self.port.target.service_id,
+            "date": slot.day.isoformat(), "timeRange": slot.time_label,
+            "remainingAtSelection": slot.slots_free,
+        }, sort_keys=True), flush=True)
+        answer = confirm(
+            "This creates a REAL appointment in the current applicant account. "
+            f"Type exactly '{phrase}' to submit ONCE; anything else cancels: "
+        )
+        if answer != phrase:
+            self.report["outcome"] = "confirmation_declined"
+            return self.report
+
+        def read():
+            snapshot = self.port()
+            if not self.possibly_submitted:
+                self.before = snapshot
+            return snapshot
+
+        def submit():
+            self._current_selection()
+            # Fail closed before native dispatch if exclusive creation/fsync fails.
+            claim_once(self.claim_path)
+            self.possibly_submitted = True
+            self.report.update(attempted=True, outcome="unknown_do_not_retry")
+            native = NativeFinalSubmitter(
+                self.plugin.page, self.port.target, self.port.session_is_current,
+            )
+            self.signal = native()
+            diagnostic = getattr(native, "diagnostic", None)
+            if type(diagnostic) is dict and set(diagnostic) == {"requestMatched", "reason"}:
+                self.report["submissionDiagnostic"] = diagnostic
+            proof = getattr(native, "submitted_selection", None)
+            if (isinstance(proof, VerifiedSubmission) and callable(self._verify_submission) and
+                    self._verify_submission() is True):
+                self.port.record_submission(proof)
+            return self.signal
+
+        attempt = FinalBookingAttempt(self.port.target, read_reservations=read, submit_native=submit,
+                                      session_is_current=self.port.session_is_current)
+        try:
+            self.result = attempt.execute(enabled=True)
+            if self.result.success is True:
+                self.report.update(bookingConfirmed=True, outcome="confirmed",
+                                   confirmedDate=self.result.book_date, confirmedTime=self.result.book_time)
+            elif self.result.success is False and self.possibly_submitted:
+                self.report["outcome"] = "rejected_do_not_retry"
+        except FinalOutcomeUnknown:
+            if not self.possibly_submitted:
+                raise FinalBookingError("Final evidence blocked before native dispatch") from None
+        finally:
+            self.report["submissionSignal"] = self.signal.value
+        if self.possibly_submitted:
+            self.report["receiptEvidence"] = self.collect_receipts()
+        return self.report
+
+    def collect_receipts(self) -> dict:
+        """One read-only observation. No receipt/reference/PII payload persisted."""
+        if not self.possibly_submitted or self.before is None:
+            raise FinalBookingError("No local final attempt to observe")
+        try:
+            observed = self.port.observe_receipts()
+            before = {r.reference: r for r in self.before.records}
+            current = {row.reference: (row, detail) for row, detail in observed.records}
+            unchanged = all(ref in current and _cancelled_record(*current[ref]) == old
+                            for ref, old in before.items())
+            new = [(row, detail) for row, detail in observed.records if row.reference not in before]
+            slot = self.port.target.approval.candidate
+            # Observation alone never establishes attribution. Only mirror an
+            # already verified final-core result when this fresh read agrees.
+            confirmed = bool(
+                self.result is not None and self.result.success is True and unchanged and len(new) == 1 and
+                new[0][1].reference == self.result.urn and new[0][1].state is ReservationState.ACTIVE and
+                new[0][1].status_code == "2" and new[0][1].booking_type == "Prenotazione Singola" and
+                new[0][1].service_name == self.port.target.service_name and
+                new[0][1].day.isoformat() == self.result.book_date and
+                new[0][1].appointment_time == self.result.book_time
+            )
+            return {
+                "readVerified": True, "historicalRecordsUnchanged": unchanged,
+                "recordCount": len(current), "newRecordCount": len(new),
+                "newRecordsTruncated": len(new) > 3, "bookingConfirmed": confirmed,
+                "newRecords": [{
+                    "officeText": d.office, "serviceText": d.service_name,
+                    "bookingTypeText": d.booking_type, "date": d.day.isoformat(),
+                    "assignedTime": d.appointment_time, "statusText": d.status_text,
+                    "statusCode": d.status_code, "classifiedState": d.state.value,
+                    "dateMatchesSelection": d.day == slot.day,
+                    "assignedTimeWithinSelection": slot.time_label[:5] <= d.appointment_time <= slot.time_label[-5:],
+                } for _, d in new[:3]],
+            }
+        except Exception:
+            # Browser/DOM errors and page bodies never enter logs. The fence stays.
+            return {"readVerified": False, "bookingConfirmed": False}
+
+
+def wait_for_receipt_review(*, reader=input) -> None:
+    print("ITA_FINAL_REVIEW_REQUIRED: Do NOT rerun or submit again. The browser is kept open. "
+          "Inspect Reservation / the new receipt only; do not cancel an appointment. "
+          "Share the diagnostic and redact personal data from any screenshot.", flush=True)
+    reader("After inspection, press Enter to close this temporary browser: ")

+ 289 - 0
tools/ita_local_handoff.py

@@ -0,0 +1,289 @@
+"""Private, one-shot local handoff from Italy Query discovery to Book recheck.
+
+This is a debug-only adapter. Production continues to use the existing
+Sentinel -> Redis -> Booker path. The file contains metadata only and is
+atomically claimed so a weak signal cannot trigger two local Book attempts.
+"""
+
+from __future__ import annotations
+
+import json
+import math
+import os
+import stat
+import time
+import uuid
+from dataclasses import dataclass
+from pathlib import Path
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+ITA_LOCAL_HANDOFF_ROOT = PROJECT_ROOT / "data" / "ita_local_handoff"
+ITA_LOCAL_SIGNAL_NAME = "query-weak-signal.json"
+ITA_LOCAL_SIGNAL_SCHEMA = 1
+ITA_LOCAL_SIGNAL_KIND = "italy-query-weak-signal"
+ITA_LOCAL_SIGNAL_EVIDENCE = "booking-form"
+ITA_LOCAL_SIGNAL_TTL_SECONDS = 30
+ITA_LOCAL_SIGNAL_MAX_BYTES = 4096
+ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS = 5
+
+
+class ItaLocalHandoffError(ValueError):
+    """Raised when the local handoff artifact is unsafe or invalid."""
+
+
+class ItaLocalSignalStaleError(ItaLocalHandoffError):
+    """Raised after an expired signal has been atomically consumed."""
+
+
+@dataclass(frozen=True)
+class ItaLocalWeakSignal:
+    service_id: int
+    routing_key: str
+    evidence: str
+    issued_at: float
+
+
+def _ensure_private_directory(path: Path) -> Path:
+    if path.is_symlink():
+        raise ItaLocalHandoffError("local handoff directory must not be a symlink")
+    try:
+        path.mkdir(mode=0o700, parents=True, exist_ok=True)
+    except OSError as exc:
+        raise ItaLocalHandoffError(
+            f"cannot create local handoff directory ({type(exc).__name__})"
+        ) from exc
+    if path.is_symlink() or not path.is_dir():
+        raise ItaLocalHandoffError(
+            "local handoff path must be a private directory"
+        )
+    if os.name == "posix":
+        try:
+            path.chmod(0o700)
+            mode = stat.S_IMODE(path.stat().st_mode)
+        except OSError as exc:
+            raise ItaLocalHandoffError(
+                f"cannot secure local handoff directory ({type(exc).__name__})"
+            ) from exc
+        if mode != 0o700:
+            raise ItaLocalHandoffError(
+                "local handoff directory permissions must be 700"
+            )
+    return path.resolve()
+
+
+def _resolved_root(handoff_root: str | Path | None) -> Path:
+    root = Path(handoff_root or ITA_LOCAL_HANDOFF_ROOT).expanduser()
+    if not root.is_absolute():
+        root = PROJECT_ROOT / root
+    return _ensure_private_directory(root)
+
+
+def _write_private_file(path: Path, content: bytes) -> None:
+    temp_path = path.parent / f".{path.name}.{os.getpid()}.{uuid.uuid4().hex}.tmp"
+    flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL
+    flags |= getattr(os, "O_NOFOLLOW", 0)
+    descriptor: int | None = None
+    try:
+        descriptor = os.open(temp_path, flags, 0o600)
+        if os.name == "posix":
+            os.fchmod(descriptor, 0o600)
+        with os.fdopen(descriptor, "wb") as handle:
+            descriptor = None
+            handle.write(content)
+            handle.flush()
+            os.fsync(handle.fileno())
+        os.replace(temp_path, path)
+        if os.name == "posix":
+            path.chmod(0o600)
+            if stat.S_IMODE(path.stat().st_mode) != 0o600:
+                raise ItaLocalHandoffError(
+                    "local handoff signal permissions must be 600"
+                )
+    except ItaLocalHandoffError:
+        raise
+    except OSError as exc:
+        raise ItaLocalHandoffError(
+            f"cannot publish local handoff signal ({type(exc).__name__})"
+        ) from exc
+    finally:
+        if descriptor is not None:
+            os.close(descriptor)
+        try:
+            temp_path.unlink()
+        except FileNotFoundError:
+            pass
+        except OSError:
+            pass
+
+
+def publish_local_weak_signal(
+    *,
+    service_id: int,
+    routing_key: str,
+    issued_at: float | None = None,
+    handoff_root: str | Path | None = None,
+) -> Path:
+    """Atomically publish one short-lived, metadata-only weak signal."""
+
+    if (
+        isinstance(service_id, bool)
+        or not isinstance(service_id, int)
+        or service_id <= 0
+    ):
+        raise ItaLocalHandoffError("local handoff service_id must be positive")
+    normalized_routing_key = str(routing_key or "").strip()
+    if not normalized_routing_key:
+        raise ItaLocalHandoffError("local handoff routing_key is required")
+    timestamp = time.time() if issued_at is None else float(issued_at)
+    if not math.isfinite(timestamp):
+        raise ItaLocalHandoffError("local handoff issued_at must be finite")
+    payload = {
+        "schema": ITA_LOCAL_SIGNAL_SCHEMA,
+        "kind": ITA_LOCAL_SIGNAL_KIND,
+        "service_id": service_id,
+        "routing_key": normalized_routing_key,
+        "evidence": ITA_LOCAL_SIGNAL_EVIDENCE,
+        "issued_at": timestamp,
+    }
+    encoded = json.dumps(
+        payload,
+        ensure_ascii=True,
+        sort_keys=True,
+        separators=(",", ":"),
+    ).encode("utf-8")
+    root = _resolved_root(handoff_root)
+    signal_path = root / ITA_LOCAL_SIGNAL_NAME
+    _write_private_file(signal_path, encoded)
+    return signal_path
+
+
+def _read_claimed_payload(path: Path) -> dict:
+    flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)
+    descriptor: int | None = None
+    try:
+        descriptor = os.open(path, flags)
+        file_stat = os.fstat(descriptor)
+        if not stat.S_ISREG(file_stat.st_mode):
+            raise ItaLocalHandoffError(
+                "local handoff signal must be a regular file"
+            )
+        if os.name == "posix" and stat.S_IMODE(file_stat.st_mode) != 0o600:
+            raise ItaLocalHandoffError(
+                "local handoff signal permissions must be 600"
+            )
+        content = os.read(descriptor, ITA_LOCAL_SIGNAL_MAX_BYTES + 1)
+    except ItaLocalHandoffError:
+        raise
+    except OSError as exc:
+        raise ItaLocalHandoffError(
+            f"cannot read local handoff signal ({type(exc).__name__})"
+        ) from exc
+    finally:
+        if descriptor is not None:
+            os.close(descriptor)
+    if len(content) > ITA_LOCAL_SIGNAL_MAX_BYTES:
+        raise ItaLocalHandoffError("local handoff signal is too large")
+    try:
+        payload = json.loads(content.decode("utf-8"))
+    except (UnicodeDecodeError, json.JSONDecodeError) as exc:
+        raise ItaLocalHandoffError("local handoff signal is invalid JSON") from exc
+    if not isinstance(payload, dict):
+        raise ItaLocalHandoffError("local handoff signal must be a JSON object")
+    return payload
+
+
+def claim_local_weak_signal(
+    *,
+    expected_service_id: int,
+    expected_routing_key: str,
+    ttl_seconds: int = ITA_LOCAL_SIGNAL_TTL_SECONDS,
+    now: float | None = None,
+    handoff_root: str | Path | None = None,
+) -> ItaLocalWeakSignal | None:
+    """Atomically consume and validate one weak signal, or return ``None``."""
+
+    if ttl_seconds <= 0:
+        raise ItaLocalHandoffError("local handoff ttl_seconds must be positive")
+    root = _resolved_root(handoff_root)
+    signal_path = root / ITA_LOCAL_SIGNAL_NAME
+    try:
+        signal_stat = signal_path.lstat()
+    except FileNotFoundError:
+        return None
+    except OSError as exc:
+        raise ItaLocalHandoffError(
+            f"cannot inspect local handoff signal ({type(exc).__name__})"
+        ) from exc
+    if not stat.S_ISREG(signal_stat.st_mode):
+        raise ItaLocalHandoffError("local handoff signal must be a regular file")
+
+    claim_path = root / (
+        f".{ITA_LOCAL_SIGNAL_NAME}.{os.getpid()}.{uuid.uuid4().hex}.claim"
+    )
+    try:
+        try:
+            os.replace(signal_path, claim_path)
+        except FileNotFoundError:
+            return None
+        payload = _read_claimed_payload(claim_path)
+        expected_keys = {
+            "schema",
+            "kind",
+            "service_id",
+            "routing_key",
+            "evidence",
+            "issued_at",
+        }
+        if set(payload) != expected_keys:
+            raise ItaLocalHandoffError(
+                "local handoff signal has an unsupported schema"
+            )
+        if payload["schema"] != ITA_LOCAL_SIGNAL_SCHEMA:
+            raise ItaLocalHandoffError(
+                "local handoff signal schema version is unsupported"
+            )
+        if payload["kind"] != ITA_LOCAL_SIGNAL_KIND:
+            raise ItaLocalHandoffError("local handoff signal kind is invalid")
+        if payload["evidence"] != ITA_LOCAL_SIGNAL_EVIDENCE:
+            raise ItaLocalHandoffError("local handoff signal evidence is invalid")
+        if payload["service_id"] != expected_service_id:
+            raise ItaLocalHandoffError(
+                "local handoff signal service_id does not match"
+            )
+        if payload["routing_key"] != expected_routing_key:
+            raise ItaLocalHandoffError(
+                "local handoff signal routing_key does not match"
+            )
+        issued_at_raw = payload["issued_at"]
+        if isinstance(issued_at_raw, bool) or not isinstance(
+            issued_at_raw, (int, float)
+        ):
+            raise ItaLocalHandoffError(
+                "local handoff signal issued_at is invalid"
+            )
+        issued_at = float(issued_at_raw)
+        current_time = time.time() if now is None else float(now)
+        if not math.isfinite(issued_at) or not math.isfinite(current_time):
+            raise ItaLocalHandoffError(
+                "local handoff signal timestamp is invalid"
+            )
+        if issued_at - current_time > ITA_LOCAL_SIGNAL_FUTURE_SKEW_SECONDS:
+            raise ItaLocalHandoffError(
+                "local handoff signal timestamp is in the future"
+            )
+        if current_time - issued_at > ttl_seconds:
+            raise ItaLocalSignalStaleError("local handoff signal has expired")
+        return ItaLocalWeakSignal(
+            service_id=expected_service_id,
+            routing_key=expected_routing_key,
+            evidence=ITA_LOCAL_SIGNAL_EVIDENCE,
+            issued_at=issued_at,
+        )
+    finally:
+        try:
+            claim_path.unlink()
+        except FileNotFoundError:
+            pass
+        except OSError:
+            pass

+ 635 - 0
tools/ita_query_book_local.py

@@ -0,0 +1,635 @@
+"""Finite live acceptance wiring, not a second scheduler.
+
+Execute existing GCO spawn/monitor/trigger/stop methods. Only order API and
+telemetry are substituted; pool allocation and Italy OTP keep their SDK.
+Redis is an owned, non-persistent Unix-socket subprocess (never shared Redis).
+This module is loaded only by explicit --local-preflight / --local-run.
+"""
+from __future__ import annotations
+
+from contextlib import ExitStack, contextmanager
+import copy
+import hashlib
+import json
+import os
+from pathlib import Path
+import shutil
+import socket
+import subprocess
+import tempfile
+import threading
+import time
+from types import SimpleNamespace
+from unittest.mock import patch
+from uuid import uuid4
+
+import redis
+
+import configure
+from booker import OrderBookerGCO
+from sentinel import SentinelGCO
+from plugins.ita_calendar_book import book_date_preferences, read_calendar_service, verify_precommit_selection
+from plugins.ita_calendar_session import CalendarRequestAudit
+from plugins.ita_otp import validate_cloud_otp_environment, validate_cloud_otp_logging
+from plugins.ita_plugin import (
+    BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL,
+    PERSISTENT_BROWSER_PROFILE_KEY,
+)
+from plugins.ita_protocol import ItaCapability, resolve_route_config
+from plugins.ita_booking_final import FinalBookingError, FinalOutcomeUnknown
+from plugins import ita_workflow
+from tools.ita_final_evidence import claim_once, require_unused_claim
+from tools.ita_local_handoff import ITA_LOCAL_HANDOFF_ROOT
+from toolkit.vs_cloud_api import VSCloudApi
+from tools.debug_ita_session import _get_credentials, resolve_chrome_path
+from tools.plugin_tester import PluginTester
+from utils.local_account import load_local_account
+from vs_types import AvailabilityStatus, GroupConfig, VSAccount
+
+
+CONTRACT = "existing-framework-local-prefinal-v1"
+FINAL_CONTRACT = "existing-framework-local-auto-submit-once-v4"
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class LocalAcceptanceError(RuntimeError):
+    """Only static diagnostic codes, never credentials or upstream bodies."""
+
+
+def emit(event, **fields):
+    print("ITA_QUERY_BOOK_" + event + "=" + json.dumps(fields, sort_keys=True), flush=True)
+
+
+def load_settings(args):
+    validate_cloud_otp_logging()
+    if configure.TEST_ACCOUNT:
+        raise LocalAcceptanceError("test_account_override_enabled")
+    path = Path(args.config)
+    groups = json.loads((path if path.is_absolute() else ROOT / path).read_text())
+    matches = [g for g in groups if g.get("identifier") == args.group]
+    if len(matches) != 1:
+        raise LocalAcceptanceError("group_missing_or_ambiguous")
+    source = GroupConfig.from_json(matches[0])
+    if (source.plugin_config.plugin_name != "ita_plugin" or len(source.appointment_types) != 1
+            or not source.sentinel.account_pool_id or source.sentinel.signal_ttl <= 0
+            or source.free_config.get("query_mode") != "calendar"
+            or source.free_config.get("otp_mode") != "cloud"
+            or source.free_config.get("final_submit_enabled") is not False):
+        raise LocalAcceptanceError("requires_single_calendar_query_group_with_cloud_otp_and_final_disabled")
+    apt = source.appointment_types[0]
+    route = resolve_route_config(source.free_config.get("apt_configs", {}), apt.routing_key)
+    if (route.capability != ItaCapability.SINGLE_SCHENGEN_TOURISM
+            or route.mail is None or route.mail.authorization_source != "account"):
+        raise LocalAcceptanceError("requires_single_tourism_route_and_account_mailbox")
+    preferences = {key: value for key, value in (
+        ("expected_start_date", args.expected_start_date), ("expected_end_date", args.expected_end_date)) if value}
+    book_date_preferences(preferences)
+    proxy = PluginTester.parse_proxy_url(args.proxy)
+    if proxy.ip not in {"127.0.0.1", "localhost", "::1"} or not 1 <= proxy.port <= 65535:
+        raise LocalAcceptanceError("requires_explicit_loopback_proxy")
+    return source, route, proxy, preferences
+
+
+def build_groups(source, run_id, *, submit_once=False):
+    """Copy existing config; do not publish or edit production groups."""
+    query = source.model_copy(deep=True)
+    query.identifier = "ita-local-query-" + run_id
+    query.enable, query.debug, query.need_account, query.need_proxy = True, False, True, True
+    query.sentinel.target_instances = 1
+    query.proxy_pool = ["local-test-proxy"]
+    query.free_config.pop(PERSISTENT_BROWSER_PROFILE_KEY, None)
+    query.appointment_types[0].weight = max(1, query.appointment_types[0].weight)
+    book = query.model_copy(deep=True)
+    book.identifier = "ita-local-book-" + run_id
+    book.booker.account_source = "order"
+    book.booker.target_instances = 1
+    book.free_config.update(query_mode="services_probe", otp_mode="cloud", final_submit_enabled=submit_once)
+    return query, book
+
+
+class LocalFinalSubmission:
+    """Single-dispatch fence around the EXISTING production final workflow.
+
+    No new receipt matcher, POST implementation or retry policy. Reuse the
+    exclusive/fsynced claim helper, scoped to site + applicant + service (not
+    run id, date or routing alias). A restart cannot silently submit again.
+    Legacy final-evidence-once.claim is never read, removed or reset here;
+    the production receipt baseline still rejects existing active/unknown rows.
+    """
+
+    def __init__(self, applicant, route, *, root=ITA_LOCAL_HANDOFF_ROOT):
+        self.username = applicant.username.strip().casefold()
+        self.route = route
+        identity = json.dumps(["prenotami.esteri.it", self.username, str(route.service_id)])
+        self.claim_path = Path(root) / "query-book-final" / (hashlib.sha256(identity.encode()).hexdigest() + ".claim")
+        self.used = self.possibly_submitted = False
+        self.selection = {}
+        self.failure_reason = None
+        require_unused_claim(self.claim_path)  # Before browser/pool allocation.
+
+    def submit(self, plugin, route, observed, production_submit):
+        if (self.used or route != self.route or observed.get("book") is None
+                or observed["book"].plugin is not plugin
+                or plugin.config.account.username.strip().casefold() != self.username):
+            raise LocalAcceptanceError("final_applicant_or_route_changed")
+        self.used = True
+        require_unused_claim(self.claim_path)
+        approval = plugin.last_booking_precommit
+        verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page), approval=approval)
+        slot = approval.candidate
+        self.selection = {"selectionVerified": True, "selectedDate": slot.day.isoformat(), "selectedTime": slot.time_label}
+        emit("FINAL_TARGET", **self.selection, routingKey=route.routing_key, serviceId=route.service_id,
+             remaining=slot.slots_free, createsRealAppointment=True, automaticSubmission=True)
+
+        # Only wrap native dispatch. The production core FIRST reads a fresh
+        # receipt baseline and rejects active/waitlist/unknown history.
+        native_factory = ita_workflow.NativeFinalSubmitter
+        owner = self
+
+        class FencedNative:
+            def __init__(self, page, target, current):
+                if (page is not plugin.page or target.applicant != owner.username
+                        or target.service_id != str(route.service_id) or target.approval is not approval):
+                    raise LocalAcceptanceError("final_target_changed")
+                self.native = native_factory(page, target, current)
+
+            def __getattr__(self, name):
+                return getattr(self.native, name)
+
+            def __call__(self):
+                if owner.possibly_submitted or plugin.last_booking_precommit is not approval:
+                    raise LocalAcceptanceError("final_already_attempted_do_not_rerun")
+                for item in observed.values():
+                    if item.audit.settled_snapshot()["finalRequests"] != 0:
+                        raise LocalAcceptanceError("unexpected_final_request_do_not_rerun")
+                verify_precommit_selection(plugin.page, runtime_service=read_calendar_service(plugin.page), approval=approval)
+                claim_once(owner.claim_path)
+                owner.possibly_submitted = True
+                emit("FINAL_DISPATCH", automaticRetry=False, possiblySubmitted=True)
+                return self.native()
+
+        with patch.object(ita_workflow, "NativeFinalSubmitter", FencedNative):
+            try:
+                # This observer already owns the page's passive callback.
+                # Lend it to production final; keep coverage through cleanup.
+                return production_submit(plugin, route, request_audit=observed["book"].audit)
+            except FinalBookingError:
+                self.failure_reason = "receipt_baseline_or_final_context_rejected"
+                raise
+
+
+def check_dependencies(proxy):
+    executable = shutil.which("redis-server")
+    if not executable:
+        raise LocalAcceptanceError("redis_server_missing_run_brew_install_redis")
+    chrome = resolve_chrome_path(os.environ)
+    with socket.create_connection((proxy.ip, proxy.port), timeout=3):
+        pass  # Check before allocating a pool account. Not an internet test.
+    return executable, chrome
+
+
+@contextmanager
+def private_redis(executable):
+    # /tmp keeps the Unix socket below macOS's path-length limit. Only this
+    # owned directory/process is removed; no FLUSHDB, shared service or port.
+    with tempfile.TemporaryDirectory(prefix="ita-qb-", dir="/tmp") as directory:
+        unix_socket = str(Path(directory) / "redis.sock")
+        process = subprocess.Popen([
+            executable, "--port", "0", "--unixsocket", unix_socket,
+            "--unixsocketperm", "700", "--save", "", "--appendonly", "no",
+            "--dir", directory, "--daemonize", "no",
+        ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+        config = {"unix_socket_path": unix_socket, "db": 0, "decode_responses": True,
+                  "socket_timeout": 2, "socket_connect_timeout": 2}
+        client = redis.Redis(**config)
+        try:
+            deadline = time.monotonic() + 8
+            while True:
+                if process.poll() is not None:
+                    raise LocalAcceptanceError("private_redis_exited")
+                try:
+                    if client.ping():
+                        break
+                except redis.exceptions.RedisError:
+                    pass
+                if time.monotonic() >= deadline:
+                    raise LocalAcceptanceError("private_redis_not_ready")
+                time.sleep(0.1)
+            yield config
+        finally:
+            try:
+                client.close()
+            finally:
+                if process.poll() is None:
+                    process.terminate()
+                    try:
+                        process.wait(timeout=5)
+                    except subprocess.TimeoutExpired:
+                        process.kill()
+                        process.wait(timeout=5)
+
+
+class LocalCloudBoundary:
+    """Only cloud order/telemetry are local. Pool selection is never reimplemented."""
+
+    def __init__(self, api, group, route, proxy, applicant, preferences):
+        self.api, self.group, self.route, self.proxy = api, group, route, proxy
+        self.applicant = applicant
+        self.order = {"id": -1, "order_id": "LOCAL-ACCEPTANCE", "status": "processing",
+                      "user_inputs": {**preferences, "username": applicant.username, "password": applicant.password}}
+        self.pool_calls = self.order_calls = self.forbidden_calls = 0
+        self.query_account = None
+        self.error = None
+
+    def get_next_account(self, pool_name, account_cd):
+        self.pool_calls += 1
+        if self.pool_calls != 1 or (pool_name, account_cd) != (
+                self.group.sentinel.account_pool_id, self.group.sentinel.account_cd):
+            raise LocalAcceptanceError("unexpected_pool_allocation")
+        try:
+            raw = self.api.get_next_account(pool_name, account_cd)
+            if not isinstance(raw, dict) or raw.get("pool_name") != pool_name or raw.get("status") != "active":
+                raise LocalAcceptanceError("pool_account_invalid")
+            account = VSAccount.model_validate(raw)
+            if not account.password:
+                raise LocalAcceptanceError("pool_website_password_missing")
+            validate_cloud_otp_environment(self.route.mail, account.username)
+            if account.username.strip().casefold() == self.applicant.username.strip().casefold():
+                raise LocalAcceptanceError("query_and_book_accounts_same_choose_other_applicant")
+            self.query_account = account
+            emit("POOL", accountId=account.id, pool=pool_name, accountsDistinct=True)
+            return raw
+        except Exception as exc:
+            self.error = str(exc) if isinstance(exc, LocalAcceptanceError) else "pool_allocation_failed"
+            raise LocalAcceptanceError(self.error) from None
+
+    def get_next_proxy(self, *_args):
+        return self.proxy.model_dump()
+
+    def get_vas_task_pop(self, queue_name):
+        self.order_calls += 1
+        if queue_name != "auto." + self.route.routing_key or self.order_calls != 1:
+            raise LocalAcceptanceError("unexpected_local_order_request")
+        return copy.deepcopy(self.order)
+
+    def slot_refresh_start(self, *_args, **_kwargs):
+        pass
+
+    def slot_refresh_success(self, *_args, **_kwargs):
+        pass
+
+    def slot_refresh_fail(self, *_args, **_kwargs):
+        self.error = self.error or "query_failed"
+
+    def slot_snapshot_report(self, *_args, **_kwargs):
+        pass
+
+    def __getattr__(self, name):
+        # Reject cloud updates/notifications and any new dependency rather
+        # than silently forwarding a synthetic order id to the backend.
+        self.forbidden_calls += 1
+        raise LocalAcceptanceError("unexpected_cloud_operation")
+
+
+class ObservedPlugin:
+    """A test observer around a real factory-created plugin, not an algorithm."""
+
+    def __init__(self, plugin, role):
+        self.plugin, self.role = plugin, role
+        self.audit = None
+        self.calls = 0
+        self.result = None
+        self.error = None
+        self.cleanup_ok = False
+        self.last_counts = None
+
+    def __getattr__(self, name):
+        return getattr(self.plugin, name)
+
+    def create_session(self):
+        try:
+            self.plugin.create_session()
+            self.audit = CalendarRequestAudit(self.plugin.page, include_time_slots=True)
+            self.audit.start()
+        except Exception as exc:
+            self.error = type(exc).__name__
+            raise LocalAcceptanceError(self.role + "_session_failed") from None
+
+    def query(self, apt):
+        return self._call("query", apt)
+
+    def book(self, slot_info, user_inputs):
+        return self._call("book", slot_info, user_inputs)
+
+    def _call(self, operation, *args):
+        self.calls += 1
+        if operation != self.role or self.calls != 1:
+            raise LocalAcceptanceError("unexpected_plugin_invocation")
+        try:
+            self.result = getattr(self.plugin, operation)(*args)
+            return self.result
+        except Exception as exc:
+            self.error = type(exc).__name__
+            if isinstance(exc, FinalOutcomeUnknown):
+                raise  # Preserve the native Booker's pause-on-unknown branch.
+            raise LocalAcceptanceError(self.role + "_operation_failed") from None
+
+    def cleanup(self):
+        # The GCO may remove a failed instance before the final audit. Keep
+        # that failure visible; never turn retained counters into live proof.
+        try:
+            if self.audit is not None:
+                try:
+                    self.last_counts = self.audit.settled_snapshot()
+                finally:
+                    self.audit.stop()
+        finally:
+            self.plugin.cleanup()
+        self.cleanup_ok = True
+
+
+def observe_factory(gco, role, stack, observed):
+    factory_create = gco.m_factory.create
+    cfg = gco.m_cfg.plugin_config
+    gco.m_factory.register_plugin(cfg.plugin_name, str(ROOT / "plugins/ita_plugin.py"), "ItaPlugin")
+
+    def create(*args):
+        instance = ObservedPlugin(factory_create(*args), role)
+        observed[role] = instance
+        return instance
+
+    stack.enter_context(patch.object(gco.m_factory, "create", side_effect=create))
+
+
+def framework_log(message):
+    # GCO errors can include arbitrary provider exception strings. Keep only
+    # lifecycle markers here; plugin observers produce safe failure codes.
+    for marker in ("Triggering BOOK", "SLOT FOUND", "spawned", "Stopping", "Cleaned up",
+                   "Entering username", "Entering password", "Login form submitted",
+                   "Successfully reached authenticated /UserArea", "OTP sent",
+                   "automatic OTP DOM write verified", "Calendar found the first positive month"):
+        if marker in message:
+            emit("FRAMEWORK", marker=marker)
+            break
+
+
+def run_framework_once(query_group, book_group, route, cloud, redis_config, *, final_control=None):
+    observed, threads = {}, []
+    report = {"contract": FINAL_CONTRACT if final_control else CONTRACT, "passed": False, "outcome": "failed",
+              "cloudOrders": False, "finalSubmissionEnabled": final_control is not None, "liveAcceptance": True,
+              "queryCalls": 0, "bookCalls": 0, "signalPublished": False,
+              "signalReadByBooker": False, "selectionVerified": False, "cleanupVerified": False}
+    gc_objects = []
+    local_success_reports = []
+    if final_control:
+        report.update(bookingConfirmed=False, bookResultSuccess=False, automaticRetry=False)
+    with ExitStack() as stack:
+        def forbidden_cloud_write(*_args, **_kwargs):
+            cloud.forbidden_calls += 1
+            raise LocalAcceptanceError("unexpected_cloud_operation")
+
+        boundary = SimpleNamespace(Instance=lambda: cloud, lock_account=forbidden_cloud_write)
+        # Existing tests use these same dependency seams. Do not patch GCO
+        # implementation methods, signal serialization, filtering or TTL.
+        for cls in (SentinelGCO, OrderBookerGCO):
+            stack.enter_context(patch.dict(cls.__init__.__globals__, {"VSCloudApi": boundary}))
+        production_submit = ita_workflow.submit_final
+        stack.enter_context(patch.object(ita_workflow, "submit_final", side_effect=(
+            lambda plugin, actual_route: final_control.submit(plugin, actual_route, observed, production_submit)
+        ) if final_control else LocalAcceptanceError("final_submission_forbidden")))
+        sentinel = SentinelGCO(query_group, redis_config, framework_log)
+        booker = OrderBookerGCO(book_group, redis_config, framework_log)
+        # Block reporting BEFORE the shared asynchronous executor can enqueue
+        # anything. Its callback could otherwise outlive this patch scope.
+        def capture_success(task_id, order_id, result):
+            if (final_control is None or task_id != -1 or order_id != cloud.order["order_id"]
+                    or result is not observed["book"].result or result.success is not True
+                    or local_success_reports):
+                return forbidden_cloud_write()
+            local_success_reports.append(result)  # Standard callback; no cloud enqueue.
+
+        stack.enter_context(patch.object(booker, "_push_success_notification", side_effect=capture_success))
+        if final_control:
+            def local_pause(task_id, data):
+                if str(task_id) != "-1" or data != {"status": "pause"}:
+                    return forbidden_cloud_write()
+                cloud.order["status"] = "pause"
+            # Restore only this test seam, not the counters/state accumulated
+            # during the run (patch.dict(__dict__) would restore those too).
+            cloud.update_vas_task = local_pause
+            stack.callback(cloud.__dict__.pop, "update_vas_task", None)
+        gc_objects.extend((sentinel, booker))
+        observe_factory(sentinel, "query", stack, observed)
+        observe_factory(booker, "book", stack, observed)
+        signal_key = sentinel._get_redis_key(route.routing_key)
+        published_digest = None
+        original_setex, original_get = sentinel.redis_client.setex, booker.redis_client.get
+
+        def publish(key, ttl, payload):
+            nonlocal published_digest
+            ok = original_setex(key, ttl, payload)
+            if key == signal_key and ok:
+                published_digest = hashlib.sha256(payload.encode()).hexdigest()
+                report["signalPublished"] = True
+                emit("SIGNAL", published=True, ttl=ttl)
+            return ok
+
+        def read(key):
+            payload = original_get(key)
+            if key == signal_key and payload and published_digest:
+                data = payload.encode() if isinstance(payload, str) else payload
+                report["signalReadByBooker"] = hashlib.sha256(data).hexdigest() == published_digest
+            return payload
+
+        stack.enter_context(patch.object(sentinel.redis_client, "setex", side_effect=publish))
+        stack.enter_context(patch.object(booker.redis_client, "get", side_effect=read))
+        thread_class = threading.Thread
+
+        def tracked_thread(*args, **kwargs):
+            # Original trigger still starts and joins its own thread. Track
+            # ownership for Ctrl+C cleanup; don't create a second job runner.
+            finished = threading.Event()
+            target = kwargs.pop("target")
+
+            def observed_target(*target_args, **target_kwargs):
+                try:
+                    return target(*target_args, **target_kwargs)
+                finally:
+                    finished.set()
+
+            thread = thread_class(*args, target=observed_target, **kwargs, daemon=True)
+            threads.append((thread, finished))
+            return thread
+
+        stack.enter_context(patch.dict(booker._booking_trigger_loop.__globals__, {
+            "threading": SimpleNamespace(Thread=tracked_thread, RLock=threading.RLock, Event=threading.Event)}))
+        try:
+            emit("STAGE", stage="applicant_login", orderSource="local_only")
+            booker._spawn_worker(route.routing_key)
+            if len(booker.m_tasks) != 1:
+                raise LocalAcceptanceError("applicant_session_not_created")
+            emit("STAGE", stage="pool_login")
+            sentinel._spawn_sentinel_worker()
+            if len(sentinel.m_tasks) != 1:
+                raise LocalAcceptanceError(cloud.error or "query_session_not_created")
+            if observed["query"].page is observed["book"].page:
+                raise LocalAcceptanceError("browser_sessions_not_separate")
+            emit("STAGE", stage="query_and_publish")
+            # Exactly one iteration of the existing loops, as in the offline
+            # fixture. No independent queue, TTL, retry or polling algorithm.
+            with patch.object(sentinel.m_stop_event, "is_set", side_effect=[False, True]):
+                sentinel._monitor_loop()
+            query = observed["query"]
+            if query.error or query.result is None or cloud.error:
+                raise LocalAcceptanceError("query_did_not_complete")
+            if query.result.success and (query.result.availability_status != AvailabilityStatus.Available
+                                         or query.result.earliest_date is None):
+                raise LocalAcceptanceError("query_did_not_return_date_availability")
+            report["earliestDate"] = query.result.earliest_date.strftime("%Y-%m-%d") if query.result.earliest_date else None
+            if not query.result.success:
+                if query.result.availability_status != AvailabilityStatus.NoneAvailable:
+                    raise LocalAcceptanceError("unexpected_query_result")
+                report["outcome"] = "no_availability"
+            elif not report["signalPublished"]:
+                raise LocalAcceptanceError("redis_publication_failed")
+            else:
+                emit("STAGE", stage="booker_receive_and_select")
+                with patch.object(booker.m_stop_event, "is_set", side_effect=[False, True]):
+                    booker._booking_trigger_loop()
+                book = observed["book"]
+                if book.error:
+                    raise LocalAcceptanceError("book_failed")
+                if book.calls == 0:
+                    report["outcome"] = "not_triggered_expired_or_date_filtered"
+                elif (book.result is not None and book.result.success is False
+                      and book.result.label == BOOKING_CALENDAR_PREFINAL_STOP_LABEL):
+                    approval = book.last_booking_precommit
+                    verify_precommit_selection(book.page, runtime_service=read_calendar_service(book.page), approval=approval)
+                    report.update(selectionVerified=True, selectedDate=approval.candidate.day.isoformat(),
+                                  selectedTime=approval.candidate.time_label, outcome="pre_final")
+                elif book.result is not None and book.result.success:
+                    if final_control is None:
+                        raise LocalAcceptanceError("unexpected_book_success_before_final")
+                    attempt = getattr(book.plugin, "_production_final_attempt", None)
+                    if (not final_control.possibly_submitted or attempt is None or attempt.state != "confirmed"
+                            or book.plugin._production_book_result is not book.result
+                            or len(local_success_reports) != 1):
+                        raise LocalAcceptanceError("final_success_not_verified")
+                    report.update(**final_control.selection, outcome="confirmed", bookingConfirmed=True,
+                                  bookResultSuccess=True, confirmedDate=book.result.book_date,
+                                  confirmedTime=book.result.book_time, successHandledLocally=True)
+                elif (book.result is not None and book.result.success is False
+                      and book.result.label == BOOKING_RECHECK_NONE_AVAILABLE_LABEL):
+                    report["outcome"] = "book_no_selection"
+                elif final_control and final_control.possibly_submitted and book.result is not None and book.result.success is False:
+                    report["outcome"] = "rejected_do_not_retry"
+                else:
+                    raise LocalAcceptanceError("unexpected_book_result")
+            for role, item in observed.items():
+                # The owner snapshots before stopping its audit. Browser
+                # teardown may then fail; that does not invalidate these
+                # connected counters or justify reading a stopped audit.
+                counts = item.last_counts if item.last_counts is not None else item.audit.settled_snapshot()
+                report[role + "Requests"] = counts
+                expected_final = 1 if role == "book" and final_control and final_control.possibly_submitted else 0
+                if counts["finalRequests"] != expected_final:
+                    raise LocalAcceptanceError("unexpected_final_request_do_not_rerun")
+                if counts["otpRequests"] > 1 or counts["avantiPosts"] > 1:
+                    raise LocalAcceptanceError("unexpected_repeated_preparation")
+            if cloud.forbidden_calls:
+                raise LocalAcceptanceError("unexpected_cloud_operation")
+            report["passed"] = (report["outcome"] == ("confirmed" if final_control else "pre_final") and report["signalPublished"]
+                                and report["signalReadByBooker"] and cloud.pool_calls == cloud.order_calls == 1)
+        except KeyboardInterrupt:
+            report.update(outcome="interrupted", passed=False)
+        except Exception as exc:
+            report.update(passed=False, outcome="failed", errorType=type(exc).__name__,
+                          reason=str(exc) if isinstance(exc, LocalAcceptanceError) else "local_acceptance_failed")
+        finally:
+            for role, item in observed.items():
+                report[role + "Calls"] = item.calls
+                if item.error:
+                    report[role + "ErrorType"] = item.error
+            # Stop real GCOs and their owned pages before disposing Redis.
+            for gco in gc_objects:
+                gco.stop()
+            for item in observed.values():
+                if not item.cleanup_ok:
+                    try:
+                        item.cleanup()
+                    except Exception:
+                        report["passed"] = False
+            for thread, finished in threads:
+                if thread.ident is not None:
+                    # Keep cloud/final guards installed until the original
+                    # callback really exits, even if Ctrl+C interrupted join.
+                    # Outstanding SDK I/O follows its existing timeout.
+                    if not finished.is_set():
+                        emit("STAGE", stage="waiting_for_inflight_call_cleanup_no_retry")
+                    while not finished.is_set():
+                        try:
+                            finished.wait(timeout=0.5)
+                        except KeyboardInterrupt:
+                            report["passed"] = False
+                    thread.join(timeout=1)
+            report["cleanupVerified"] = (all(item.cleanup_ok for item in observed.values())
+                                         and not any(thread.is_alive() for thread, _ in threads))
+            report["passed"] = report["passed"] and report["cleanupVerified"]
+            if final_control:
+                # Preserve confirmed business outcome even if cleanup failed;
+                # never suggest a new booking to repair a diagnostic failure.
+                report.update(final_control.selection)
+                report.update(possiblySubmitted=final_control.possibly_submitted, automaticRetry=False)
+                if final_control.failure_reason:
+                    report["finalReason"] = final_control.failure_reason
+                if final_control.possibly_submitted and report["outcome"] not in {"confirmed", "rejected_do_not_retry"}:
+                    report.update(outcome="unknown_do_not_retry", passed=False)
+                for role, item in observed.items():
+                    if item.last_counts is not None:
+                        report[role + "Requests"] = item.last_counts
+            for gco in gc_objects:
+                gco.redis_client._client.close()
+    return report
+
+
+def main_local(args):
+    stage = "preflight"
+    try:
+        group, route, proxy, preferences = load_settings(args)
+        submit_once = getattr(args, "submit_once", False)
+        if submit_once and not getattr(args, "local_run", False):
+            raise LocalAcceptanceError("real_submission_requires_local_run")
+        executable, chrome = check_dependencies(proxy)
+        emit("PREFLIGHT", contract=FINAL_CONTRACT if submit_once else CONTRACT, ready=True, pool=group.sentinel.account_pool_id,
+             routingKey=route.routing_key, cloudOrders=False, finalSubmissionEnabled=submit_once)
+        if args.local_preflight:
+            return 0
+        stage = "applicant_credentials"
+        if args.book_account_file:
+            applicant = load_local_account(args.book_account_file)
+        else:
+            print("Book applicant account (not the Query pool account); OTP mailbox must already be authorized.", flush=True)
+            username, password = _get_credentials({"ITA_USERNAME": os.environ.get("ITA_BOOK_USERNAME", ""),
+                                                   "ITA_PASSWORD": os.environ.get("ITA_BOOK_PASSWORD", "")}, non_interactive=False)
+            applicant = VSAccount(username=username, password=password)
+        if not applicant.password:
+            raise LocalAcceptanceError("applicant_website_password_missing")
+        validate_cloud_otp_environment(route.mail, applicant.username)
+        final_control = LocalFinalSubmission(applicant, route) if submit_once else None
+        groups = build_groups(group, uuid4().hex[:10], submit_once=submit_once)
+        cloud = LocalCloudBoundary(VSCloudApi.Instance(), group, route, proxy, applicant, preferences)
+        stage = "local_redis_and_framework"
+        with private_redis(executable) as redis_config, patch.dict(os.environ, {"CHROME_BIN": str(chrome)}):
+            report = run_framework_once(*groups, route, cloud, redis_config, final_control=final_control)
+        emit("LOCAL_RESULT", **report)
+        if report.get("possiblySubmitted") and not report["passed"]:
+            return 4  # Receipt review, NEVER rerun to diagnose a possible write.
+        return 0 if report["passed"] else (2 if report["outcome"] in {
+            "no_availability", "book_no_selection", "not_triggered_expired_or_date_filtered"} else 1)
+    except KeyboardInterrupt:
+        emit("LOCAL_FAILED", stage=stage, reason="interrupted")
+        return 130
+    except Exception as exc:
+        emit("LOCAL_FAILED", stage=stage, errorType=type(exc).__name__,
+             reason=str(exc) if isinstance(exc, LocalAcceptanceError) else "check_local_configuration_or_dependency")
+        return 1

+ 66 - 0
utils/ita_local_profile.py

@@ -0,0 +1,66 @@
+"""Provision a private, account-scoped browser profile for local Italy Query tools."""
+
+from __future__ import annotations
+
+import hashlib
+import os
+import stat
+from pathlib import Path
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+ITA_QUERY_ACCOUNT_FILE = PROJECT_ROOT / "config" / "ita_query_account.local.json"
+ITA_QUERY_PROFILE_ROOT = PROJECT_ROOT / "data" / "ita_query_profiles"
+
+
+class ItaLocalProfileError(ValueError):
+    """Raised when a local Italy Query browser profile is unsafe to use."""
+
+
+def _ensure_private_directory(path: Path) -> Path:
+    if path.is_symlink():
+        raise ItaLocalProfileError("browser profile directory must not be a symlink")
+
+    try:
+        path.mkdir(mode=0o700, parents=True, exist_ok=True)
+    except OSError as exc:
+        raise ItaLocalProfileError(
+            f"cannot create browser profile directory ({type(exc).__name__})"
+        ) from exc
+
+    if path.is_symlink() or not path.is_dir():
+        raise ItaLocalProfileError(
+            "browser profile path must be a private directory"
+        )
+
+    if os.name == "posix":
+        try:
+            path.chmod(0o700)
+            mode = stat.S_IMODE(path.stat().st_mode)
+        except OSError as exc:
+            raise ItaLocalProfileError(
+                f"cannot secure browser profile directory ({type(exc).__name__})"
+            ) from exc
+        if mode != 0o700:
+            raise ItaLocalProfileError(
+                "browser profile directory permissions must be 700"
+            )
+
+    return path.resolve()
+
+
+def prepare_ita_query_profile(
+    username: str,
+    *,
+    profile_root: str | Path | None = None,
+) -> Path:
+    """Create a deterministic private profile without putting the username in its path."""
+
+    normalized_username = str(username or "").strip().casefold()
+    if not normalized_username:
+        raise ItaLocalProfileError("Italy Query username is required for its profile")
+
+    root = Path(profile_root or ITA_QUERY_PROFILE_ROOT).expanduser()
+    private_root = _ensure_private_directory(root)
+    profile_id = hashlib.sha256(normalized_username.encode("utf-8")).hexdigest()[:24]
+    return _ensure_private_directory(private_root / profile_id)

+ 123 - 0
utils/local_account.py

@@ -0,0 +1,123 @@
+"""Load a locally stored account without exposing its secret values."""
+
+from __future__ import annotations
+
+import json
+import os
+import stat
+from pathlib import Path
+
+from vs_types import VSAccount
+
+
+PROJECT_ROOT = Path(__file__).resolve().parents[1]
+LOCAL_ACCOUNT_KEYS = frozenset(
+    {"username", "password", "account_upload_token"}
+)
+
+
+class LocalAccountConfigurationError(ValueError):
+    """Raised when a local account file cannot be used safely."""
+
+
+def _resolved_path(
+    path: str | Path,
+    *,
+    allowed_root: Path | None,
+) -> Path:
+    candidate = Path(path).expanduser()
+    if not candidate.is_absolute():
+        candidate = (allowed_root or PROJECT_ROOT) / candidate
+    resolved = candidate.resolve()
+
+    if allowed_root is not None:
+        resolved_root = allowed_root.resolve()
+        if resolved != resolved_root and not resolved.is_relative_to(resolved_root):
+            raise LocalAccountConfigurationError(
+                "local account file must stay inside the configured project root"
+            )
+    return resolved
+
+
+def read_local_account_config(
+    path: str | Path,
+    *,
+    allowed_root: Path | None = PROJECT_ROOT,
+) -> dict[str, str]:
+    """Read the shared local JSON schema used by runtime and onboarding tools."""
+    if not str(path).strip():
+        raise LocalAccountConfigurationError("local_account_file is required")
+
+    resolved = _resolved_path(path, allowed_root=allowed_root)
+    try:
+        file_stat = resolved.stat()
+    except FileNotFoundError as exc:
+        raise LocalAccountConfigurationError(
+            "local account file does not exist"
+        ) from exc
+    except OSError as exc:
+        raise LocalAccountConfigurationError(
+            f"cannot inspect local account file ({type(exc).__name__})"
+        ) from exc
+
+    if os.name == "posix" and file_stat.st_mode & (stat.S_IRWXG | stat.S_IRWXO):
+        raise LocalAccountConfigurationError(
+            "local account file permissions must deny group and other access"
+        )
+
+    try:
+        raw_config = resolved.read_text(encoding="utf-8")
+    except OSError as exc:
+        raise LocalAccountConfigurationError(
+            f"cannot read local account file ({type(exc).__name__})"
+        ) from exc
+
+    try:
+        body = json.loads(raw_config)
+    except json.JSONDecodeError as exc:
+        raise LocalAccountConfigurationError(
+            f"local account file is invalid JSON at line {exc.lineno}, "
+            f"column {exc.colno}"
+        ) from exc
+
+    if not isinstance(body, dict):
+        raise LocalAccountConfigurationError(
+            "local account file must be a JSON object"
+        )
+
+    unexpected_keys = sorted(set(body) - LOCAL_ACCOUNT_KEYS)
+    if unexpected_keys:
+        raise LocalAccountConfigurationError(
+            "local account file contains unsupported keys: "
+            + ", ".join(unexpected_keys)
+        )
+
+    values: dict[str, str] = {}
+    for key in LOCAL_ACCOUNT_KEYS:
+        value = body.get(key, "")
+        if not isinstance(value, str):
+            raise LocalAccountConfigurationError(
+                f"local account field {key} must be a string"
+            )
+        values[key] = value
+    return values
+
+
+def load_local_account(
+    path: str | Path,
+    *,
+    allowed_root: Path | None = PROJECT_ROOT,
+) -> VSAccount:
+    """Build the framework account object from a private local JSON file."""
+    values = read_local_account_config(path, allowed_root=allowed_root)
+    username = values["username"].strip()
+    password = values["password"]
+    if not username:
+        raise LocalAccountConfigurationError(
+            "local account username is required"
+        )
+    if not password:
+        raise LocalAccountConfigurationError(
+            "local account password is required"
+        )
+    return VSAccount(id=0, username=username, password=password)

+ 3 - 1
vs_types.py

@@ -53,6 +53,9 @@ class BizLogicError(BizException):
     def __init__(self, message="Business logic error"):
         super().__init__(code=40001, message=message)
 
+class BookingOutcomeUnknownError(RuntimeError):
+    """A booking may already exist; pause for reconciliation, not a new attempt."""
+
 class AvailabilityStatus(str, Enum):
     NoneAvailable = "NoAvailable"
     Available = "Available"
@@ -301,4 +304,3 @@ class RoleStatus:
 # 语义化别名
 RunnerStatus = RoleStatus
 CoordinatorStatus = RoleStatus
-

برخی فایل ها در این مقایسه diff نمایش داده نمی شوند زیرا تعداد فایل ها بسیار زیاد است