Browse Source

代码优化,无用文件删除

zhangweijp 2 tháng trước cách đây
mục cha
commit
df478e42e0
39 tập tin đã thay đổi với 736 bổ sung và 12321 xóa
  1. 3 1
      .gitignore
  2. 1 2
      config/config_booker.json
  3. 1 2
      config/config_sentinel.json
  4. 0 5
      config/ita_query_account.example.json
  5. 1 2
      config/test_conf.json
  6. 4 0
      docs/italy-refactor/01-technical-design.md
  7. 3 6
      docs/italy-refactor/04-test-plan.md
  8. 2 0
      docs/italy-refactor/06-execution-records.md
  9. 2 0
      docs/italy-refactor/README.md
  10. 77 53
      plugins/ita_plugin.py
  11. 0 310
      test/ita/test_add_ita_query_account.py
  12. 0 613
      test/ita/test_debug_ita_book.py
  13. 0 1212
      test/ita/test_debug_ita_book_gate.py
  14. 0 1578
      test/ita/test_debug_ita_calendar_gate.py
  15. 0 370
      test/ita/test_debug_ita_monitor.py
  16. 0 554
      test/ita/test_debug_ita_production_query_gate.py
  17. 0 861
      test/ita/test_debug_ita_query_book.py
  18. 0 26
      test/ita/test_debug_ita_reservation.py
  19. 0 571
      test/ita/test_debug_ita_soak.py
  20. 83 87
      test/ita/test_ita_booker_integration.py
  21. 147 216
      test/ita/test_ita_booking_final.py
  22. 0 614
      test/ita/test_ita_calendar_book.py
  23. 0 949
      test/ita/test_ita_calendar_book_flow.py
  24. 187 264
      test/ita/test_ita_calendar_query.py
  25. 0 446
      test/ita/test_ita_calendar_soak.py
  26. 127 10
      test/ita/test_ita_compact.py
  27. 0 16
      test/ita/test_ita_final_attribution.py
  28. 0 31
      test/ita/test_ita_final_evidence.py
  29. 0 39
      test/ita/test_ita_final_read_port.py
  30. 0 366
      test/ita/test_ita_local_handoff.py
  31. 38 1
      test/ita/test_ita_login_flow.py
  32. 0 1292
      test/ita/test_ita_plugin.py
  33. 0 363
      test/ita/test_ita_preflight.py
  34. 0 330
      test/ita/test_ita_query_recovery.py
  35. 0 61
      test/ita/test_ita_reservation.py
  36. 0 250
      test/ita/test_ita_route_wiring.py
  37. 39 27
      test/ita/test_ita_single_file.py
  38. 0 689
      test/ita/test_ita_workflow.py
  39. 21 104
      test/ita/test_plugin_tester_ita_config.py

+ 3 - 1
.gitignore

@@ -32,6 +32,7 @@ env/
 *.local
 secrets.json
 config/ita_query_account.local.json
+config/test_conf.local.json
 
 # —— Node(若子项目使用) ——
 node_modules/
@@ -81,5 +82,6 @@ data/**/*.png
 *.orig
 *.tmp
 *.temp
-
 downloads
+test/ita
+docs/italy-refactor

+ 1 - 2
config/config_booker.json

@@ -1658,8 +1658,7 @@
           "service_id": 1321,
           "capability": "services_probe_only"
         }
-      },
-      "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+      }
     },
     "version": 2,
     "updated_by": "769858626@qq.com",

+ 1 - 2
config/config_sentinel.json

@@ -1791,8 +1791,7 @@
           "service_id": 1321,
           "capability": "services_probe_only"
         }
-      },
-      "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+      }
     },
     "version": 2,
     "updated_by": "769858626@qq.com",

+ 0 - 5
config/ita_query_account.example.json

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

+ 1 - 2
config/test_conf.json

@@ -320,8 +320,7 @@
               "purpose_labels": ["Turismo", "Tourism"]
             }
           }
-        },
-        "capsolver_key": "03db1d1ff2f4a33e84ef1da99bd83336bed3710153525"
+        }
       },
       "user_inputs": {
         "first_name": "SAN",

+ 4 - 0
docs/italy-refactor/01-technical-design.md

@@ -6,6 +6,10 @@
 
 ## 1. 总体决策
 
+2026-09-02 测试范围更新:用户明确授权删除剩余 20 个导入失败的旧测试模块,具体范围见 [清理记录](records/CR-legacy-test-retirement.md)。对这 20 个文件不再要求逐个迁移后才能删除;其他有效测试保留。该决定不改变业务需求、公共复用和真实预约成功的准出要求,也不把未覆盖的历史场景记为已验证。
+
+2026-09-02 错误处理补充:按用户最新 CR 使用框架默认异常,公开入口不得将 Session、限流、权限或 NotFound 包装成统一普通失败。最终明确业务拒绝返回 `success=False`;网络/格式异常和标准状态码抛相应框架异常。它们仍交给既有 Booker 处理,不增加 Italy 重试状态机。当前提交响应与合成回执路径的证据边界见 [修复记录](records/CR-framework-error-fixes.md)。
+
 把 Italy 收敛为现有 Coordinate 框架中的薄网站适配器。采用现有 `IVSPlg` 接口、公共工具和少量网站专属函数;不新建插件内部调度框架、通用预约引擎或传输自动切换框架。
 
 ```text

+ 3 - 6
docs/italy-refactor/04-test-plan.md

@@ -6,6 +6,8 @@
 
 当前状态:以下为实施与验收要求,不是已执行结果。新版本测试证据填写在 [执行记录](06-execution-records.md)。
 
+2026-09-02 最新执行:用户明确授权删除剩余 20 个导入失败的旧测试模块,覆盖此前逐文件迁移这 20 个模块的要求。删除后当前目录完整发现 **131 项通过,0 errors、0 failures、0 skips**;未迁移的历史场景不因此获得覆盖证明,业务需求和真实预约准出不变。清单见 [旧测试清理记录](records/CR-legacy-test-retirement.md),此前结果见 [第 2 批](records/CR-query-selection-fixes.md) 和 [第 1 批](records/CR-framework-error-fixes.md)。
+
 ## 1. 测试策略
 
 1. 先建立旧实现的业务行为基线,再改代码。
@@ -104,12 +106,7 @@
 ```bash
 git diff --check
 wc -l plugins/ita_plugin.py
-PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest discover -s test/ita -t . -p 'test_ita*.py'
-PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest discover -s test/ita -t . -p 'test_debug_ita*.py'
-PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest test.ita.test_plugin_tester_ita_config test.ita.test_add_ita_query_account
-PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest \
-  test.ita.test_ita_protocol test.ita.test_ita_otp test.ita.test_ita_compact \
-  test.ita.test_ita_login_flow test.ita.test_ita_shared_lifecycle
+PYTHONDONTWRITEBYTECODE=1 .venv/bin/python -B -m unittest discover -s test/ita -t . -p 'test*.py'
 ```
 
 新增/迁移后必须检查上述 discovery 是否覆盖全部相关用例,不能只跑一个方便通过的文件。若某命令依赖旧结构,先迁移入口,不将其故障默默排除。

+ 2 - 0
docs/italy-refactor/06-execution-records.md

@@ -2,6 +2,8 @@
 
 版本:1.1;日期:2026-09-01。
 
+最新:[2026-09-02 按授权清理旧测试](records/CR-legacy-test-retirement.md)。20 个旧模块已删除,当前目录完整发现 131 项通过、0 错误、0 跳过;删除不等于历史场景全部覆盖。Italy 1.0.3、1202 行保持不变,原账号配置、公共模块和其他插件未改动,未执行真实预约或发布。[第 2 批](records/CR-query-selection-fixes.md) 和 [第 1 批](records/CR-framework-error-fixes.md) 为历史记录。
+
 本文件是后续工作的记录模板和索引,不要求为每个函数写报告。每个 W 工作包一份记录;过长记录可保存到本目录 `records/` 并在此链接。记录不得包含账号密码、Cookie、Bearer、OTP 或邮件授权码。
 
 ## 1. 当前记录

+ 2 - 0
docs/italy-refactor/README.md

@@ -2,6 +2,8 @@
 
 版本:1.1;建立日期:2026-09-01。
 
+**最新状态(2026-09-02,覆盖下方历史状态):** 按用户明确授权删除 20 个导入失败的旧测试模块,当前 `test/ita` 完整发现 **131 项通过,0 错误、0 跳过**。这不代表所有历史场景均已迁移或真实预约已成功。Italy 仍为 `1.0.3`、1202 行;本轮未改生产代码、原账号配置或其他插件。删除清单和恢复依据见 [旧测试清理记录](records/CR-legacy-test-retirement.md)。[第 2 批](records/CR-query-selection-fixes.md) 和 [第 1 批](records/CR-framework-error-fixes.md) 保留历史过程。
+
 最新架构决定(CR-001,2026-09-01,用户已确认):Italy 调试期允许记录 OTP、Token 与敏感表单;最终提交失败、超时或结果未确认按普通失败交回 Booker 后续重试。单次 `book()` 仍最多点击一次,Query 仍不得产生最终写入。此决定覆盖旧文档中的脱敏准出和 `BookingOutcomeUnknownError` 暂停策略。
 
 本目录记录用户要求的约 1000 行 Italy 插件技术方案,以及可行性、开发周期、测试和准出要求。后续相关开发必须以本目录为依据,不允许实现过程中另起一套架构。

+ 77 - 53
plugins/ita_plugin.py

@@ -20,7 +20,7 @@ from DrissionPage import ChromiumPage
 import vs_plg as _ita_host
 from vs_plg import IVSPlg
 from vs_types import (
-    AvailabilityStatus, BizLogicError, NotFoundError,
+    AvailabilityStatus, BizException, BizLogicError, NotFoundError,
     DateAvailability, PermissionDeniedError, PluginStatus, RateLimiteddError,
     SessionExpiredOrInvalidError, VSBookResult, VSQueryResult, utc_now_str,
 )
@@ -325,16 +325,6 @@ TIME_SLOTS_PATH = "/BookingCalendar/RetrieveTimeSlots"
 DEFAULT_MONTH_CLICK_INTERVAL_SECONDS = 1.5
 
 
-# Compatibility names for older diagnostics/tests. Runtime code raises the
-# framework exceptions directly so the host can apply its standard policy.
-CalendarGateError = BizLogicError
-CalendarAuthenticationExpiredError = SessionExpiredOrInvalidError
-CalendarRateLimitedError = RateLimiteddError
-CalendarAccessDeniedError = PermissionDeniedError
-CalendarTransientError = BizLogicError
-CalendarBookError = BizLogicError
-
-
 def same_origin_path(raw_url):
     try:
         parsed = urlparse(str(raw_url or ""))
@@ -342,7 +332,7 @@ def same_origin_path(raw_url):
     except ValueError:
         raise BizLogicError("Italy request left the expected origin") from None
     if (parsed.scheme != "https" or parsed.hostname != "prenotami.esteri.it"
-            or port not in (None, 443)):
+            or port not in (None, 443) or parsed.username is not None):
         raise BizLogicError("Italy request left the expected origin")
     return parsed.path
 
@@ -420,8 +410,14 @@ def wait_for_calendar_service(page, *, session_is_current, expected_service=None
     raise BizLogicError("Italy Calendar service did not initialize")
 
 
-def _calendar_post(page, path, payload, parser):
-    response = perform_browser_fetch(page, "POST", path, json_data=payload, timeout=30)
+def _calendar_post(page, path, payload, parser, *, form=False):
+    try:
+        response = perform_browser_fetch(
+            page, "POST", path, **{"data" if form else "json_data": payload}, timeout=30)
+    except BizException:
+        raise
+    except Exception as exc:
+        raise BizLogicError(f"Italy Calendar request failed: {type(exc).__name__}") from exc
     status, host = response.status_code, urlparse(str(response.url or "")).hostname
     if host == "iam.esteri.it" or status == 401:
         raise SessionExpiredOrInvalidError("Italy Calendar authentication expired")
@@ -429,23 +425,29 @@ def _calendar_post(page, path, payload, parser):
         raise PermissionDeniedError("Italy Calendar access denied")
     if status == 429:
         raise RateLimiteddError("Italy Calendar rate limited")
+    if status == 404:
+        raise NotFoundError("Italy Calendar endpoint is unavailable")
     if status in {0, 408, 502, 503, 504}:
         raise BizLogicError("Italy Calendar temporarily unavailable")
     if status != 200 or same_origin_path(response.url) != path:
         raise BizLogicError("Italy Calendar returned an unexpected response")
     try:
         return parser(response.text)
-    except ItaProtocolError as exc:
-        raise BizLogicError(f"Italy Calendar response rejected ({exc.code})") from exc
+    except (ValueError, TypeError) as exc:
+        raise BizLogicError(
+            f"Italy Calendar response rejected ({getattr(exc, 'code', type(exc).__name__)})") from exc
 
 
 def fetch_calendar_month(page, service, selected_day):
     selected = selected_day.strftime("%d/%m/%Y")
-    return _calendar_post(
+    days = _calendar_post(
         page, AVAILABILITY_PATH,
         {"_Servizio": _runtime_id(service), "selectedDay": selected},
         parse_calendar_availability,
     )
+    if any(item.day.replace(day=1) != selected_day.replace(day=1) for item in days):
+        raise BizLogicError("Italy Calendar returned dates for another month")
+    return days
 
 
 def fetch_calendar_slots(page, service, selected_day):
@@ -460,7 +462,7 @@ def fetch_calendar_slots(page, service, selected_day):
 
 
 def scan_until_first_available_month(
-    page, *, lookahead_months, log=None,
+    page, *, lookahead_months, log=None, check_current=None,
     month_click_interval_seconds=DEFAULT_MONTH_CLICK_INTERVAL_SECONDS,
 ):
     service, anchor = read_calendar_context(page)
@@ -468,7 +470,11 @@ def scan_until_first_available_month(
     for index, month in enumerate(month_starts(anchor, lookahead_months)):
         if index and month_click_interval_seconds:
             time.sleep(month_click_interval_seconds)
+        if check_current:
+            check_current()
         days = fetch_calendar_month(page, service, month)
+        if check_current:
+            check_current()
         scans.append(days)
         available = available_calendar_days(days)
         if log:
@@ -478,7 +484,7 @@ def scan_until_first_available_month(
     return tuple(scans)
 
 
-def click_next_month(page, *, timeout=10, diagnostic=None):
+def click_next_month(page, *, timeout=10):
     control = page.ele("css:#datetimepicker th.dtpicker-next", timeout=timeout)
     if not control:
         raise NotFoundError("Italy Calendar next-month control is unavailable")
@@ -491,7 +497,12 @@ def _snapshot(page, mode, service, day, candidate=None, click=False):
         CALENDAR_DOM_SCRIPT, mode, service, day.isoformat(), candidate.daily_calendar_id,
         candidate.time_label, candidate.slots_free, click,
     )
-    if not isinstance(raw, dict) or not raw.get("contextReady") or raw.get("candidateCount") != 1:
+    if (not isinstance(raw, dict) or type(raw.get("candidateCount")) is not int
+            or any(type(raw.get(key)) is not bool for key in (
+                "contextReady", "candidateReady", "selected", "clicked"))
+            or not raw["contextReady"] or raw["candidateCount"] not in (0, 1)
+            or (raw["candidateCount"] == 0 and (mode != "slot" or click
+                or raw["candidateReady"] or raw["selected"] or raw["clicked"]))):
         raise BizLogicError("Italy Calendar selection context changed")
     return raw
 
@@ -499,7 +510,8 @@ def _snapshot(page, mode, service, day, candidate=None, click=False):
 def verify_precommit_selection(page, *, runtime_service, candidate):
     raw = _snapshot(
         page, "slot", runtime_service, candidate.day, candidate, False)
-    if not raw.get("candidateReady") or not raw.get("selected"):
+    if (not candidate.is_available or raw["candidateCount"] != 1
+            or not raw["candidateReady"] or not raw["selected"]):
         raise BizLogicError("Italy Calendar selected slot changed")
     return candidate
 
@@ -513,6 +525,8 @@ def select_slot_before_final(
     if not inventory or not candidates:
         return None
     candidate, deadline = candidates[0], time.monotonic() + dom_timeout
+    if session_is_current and session_is_current() is not True:
+        raise SessionExpiredOrInvalidError("Italy applicant Session changed")
     _snapshot(page, "date", runtime_service, target_day, click=True)
     while time.monotonic() < deadline:
         if session_is_current and session_is_current() is not True:
@@ -598,6 +612,7 @@ FINAL_ACCEPTED_LABEL = "italy-final-accepted"
 
 
 def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VSBookResult:
+    result = VSBookResult(success=False, label=FINAL_FAILED_LABEL)
     try:
         page = plugin.page
         username = plugin.config.account.username.strip().casefold()
@@ -606,28 +621,28 @@ def _submit_final_once(plugin, route: ItaRouteConfig, slot: SlotCandidate) -> VS
                 or page.tab_id != prepared.tab_id or same_origin_path(page.url) != CALENDAR_PATH):
             raise BizLogicError("Italy final context is not current")
         verify_precommit_selection(page, runtime_service=prepared.runtime_service, candidate=slot)
-        response = perform_browser_fetch(page, "POST", FINAL_PATH, data={
+        data = _calendar_post(page, FINAL_PATH, {
             "idCalendarioGiornaliero": slot.daily_calendar_id,
             "selectedDay": slot.day.isoformat(),
             "selectedHour": f"{slot.time_label}\n({slot.slots_free})",
-        })
-        data = response.json()
-        if (response.status_code == 200 and same_origin_path(response.url) == FINAL_PATH
-                and isinstance(data, dict) and not str(data.get("errorMessage", "")).strip()
-                and isinstance(data.get("url"), str) and data["url"].strip()):
-            same_origin_path(urljoin("https://prenotami.esteri.it", data["url"]))
-            return VSBookResult(
-                success=True,
-                account=username,
-                label=FINAL_ACCEPTED_LABEL,
-                book_date=slot.day.isoformat(),
-                book_time=slot.time_label,
-            )
-    except Exception as exc:
-        plugin._log(f"Italy final submission failed: {type(exc).__name__}")
-    # The next Booker signal must re-enter the form and obtain fresh IDs.
-    plugin._reset_calendar_state()
-    return VSBookResult(success=False, label=FINAL_FAILED_LABEL)
+        }, json.loads, form=True)
+        if not isinstance(data, dict) or not isinstance(data.get("errorMessage"), str):
+            raise BizLogicError("Italy final response is missing its result")
+        if data["errorMessage"].strip():
+            return result
+        destination = data.get("url")
+        if not isinstance(destination, str) or not destination.strip():
+            raise BizLogicError("Italy final response is missing its receipt URL")
+        path = same_origin_path(urljoin("https://prenotami.esteri.it", destination.strip()))
+        if not re.fullmatch(r"/Reservation/?|/ReservationDetail/Index/[^/]+/?", path):
+            raise BizLogicError("Italy final response did not lead to a receipt")
+        result = VSBookResult(success=True, account=username, label=FINAL_ACCEPTED_LABEL,
+                              book_date=slot.day.isoformat(), book_time=slot.time_label)
+        return result
+    finally:
+        if not result.success:
+            # The next Booker signal must prepare again and obtain fresh IDs.
+            plugin._reset_calendar_state()
 
 
 _SENT_AT_FORMAT = "%Y-%m-%d %H:%M:%S"
@@ -684,7 +699,7 @@ def validate_booking_preflight(raw, *, after_otp=False, allow_pending=False):
 
 
 def wait_for_booking_preflight(page, *, script, after_otp=False, timeout=120,
-                               diagnostic=None, wait_action=None, check_current=None):
+                               check_current=None):
     deadline, bypasser, attempts, raw = time.monotonic() + timeout, None, 0, None
     while time.monotonic() < deadline:
         if check_current:
@@ -834,12 +849,6 @@ SERVICES_PROBE_QUERY_MODE = "services_probe"
 CALENDAR_QUERY_MODE = "calendar"
 
 
-# Compatibility names retained for callers of older Italy diagnostics.
-ItaAuthenticationChallengeError = PermissionDeniedError
-ItaTargetServiceLinkMissingError = NotFoundError
-ItaCalendarTransientError = BizLogicError
-
-
 @dataclass(frozen=True, repr=False, eq=False)
 class _PreparedCalendar:
     username: str
@@ -926,7 +935,7 @@ class ItaLoginFlow(BaseFlow):
 
 class ItaPlugin(IVSPlg):
     name = "ita_plugin"
-    version = "1.0.2"
+    version = "1.0.3"
     description = "意大利 Prenot@Mi 查询与预约插件"
 
     def __init__(self, group_id):
@@ -1044,6 +1053,11 @@ class ItaPlugin(IVSPlg):
     def create_session(self):
         self._log(f"Initializing Session (ID: {self.instance_id})...")
         self._invalidate_query_session()
+        account = getattr(self.config, "account", None)
+        username, password = getattr(account, "username", None), getattr(account, "password", None)
+        if (not isinstance(username, str) or not username.strip()
+                or not isinstance(password, str) or not password):
+            raise BizLogicError("Italy website username and password are required")
         options, self.tunnel = init_chromium_options(
             user_data_path=self.user_data_path,
             username_seed=self.config.account.username,
@@ -1060,13 +1074,15 @@ class ItaPlugin(IVSPlg):
         flow = ItaLoginFlow(self)
         try:
             flow.run(max_steps=40, timeout=120)
-        except BizLogicError:
+        except BizException:
             raise
         except Exception as exc:
             raise BizLogicError(f"Italy login failed: {type(exc).__name__}; url={self.page.url}") from None
 
     def query(self, apt_type):
-        if not self.health_check() or self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
+        if self.free_config.get("query_mode") != CALENDAR_QUERY_MODE:
+            raise BizLogicError("Italy Query requires query_mode=calendar")
+        if not self.health_check():
             raise SessionExpiredOrInvalidError("Italy Query Session is unavailable")
         route = self._resolve_route(apt_type)
         if same_origin_path(self.page.url) != CALENDAR_PATH:
@@ -1077,7 +1093,8 @@ class ItaPlugin(IVSPlg):
             prepare_calendar(self, route, role="query")
         self._require_calendar_context(route, role="query")
         probes = scan_until_first_available_month(
-            self.page, lookahead_months=route.lookahead_months, log=self._log)
+            self.page, lookahead_months=route.lookahead_months, log=self._log,
+            check_current=lambda: self._require_calendar_context(route, role="query"))
         available = available_calendar_days(probes[-1])
         if not available:
             return VSQueryResult(
@@ -1160,14 +1177,21 @@ class ItaPlugin(IVSPlg):
 
     def get_plugin_status(self):
         proxy = self.config.proxy if self.config else None
+        current_url = ""
+        if self.page:
+            try:
+                current_url = str(self.page.url)
+            except Exception:
+                pass  # Status reporting must still work after browser disconnection.
         return PluginStatus(
             instance_id=self.instance_id,
             is_healthy=self.is_healthy,
             state="running" if self.is_healthy else "unhealthy",
-            current_url=str(self.page.url if self.page else ""),
+            current_url=current_url,
             account=self.config.account.username if self.config else "",
             proxy=f"{proxy.ip}:{proxy.port}" if proxy and proxy.ip else "",
-            session_age_sec=0,
+            session_age_sec=max(0, int(time.time() - self.session_create_time))
+                if self.session_create_time > 0 else 0,
             last_active_at=utc_now_str(),
         )
 

+ 0 - 310
test/ita/test_add_ita_query_account.py

@@ -1,310 +0,0 @@
-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[2]
-        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[2]
-            / "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()

+ 0 - 613
test/ita/test_debug_ita_book.py

@@ -1,613 +0,0 @@
-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 = ""
-        self.form_structure = None
-
-    def run_js(self, script):
-        return self.form_structure
-
-    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.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.page.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[2] / "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 tools import debug_ita_calendar_gate as audit_module
-        from tools import debug_ita_book_gate as book_gate
-        from plugins import ita_plugin as calendar
-        from test.ita.test_debug_ita_calendar_gate import gate_env
-        from test.ita.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.approval = 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(audit_module, "CalendarRequestAudit", return_value=self.audit))
-        self.stack.enter_context(patch.object(
-            book_gate,
-            "book_with_approval",
-            side_effect=lambda plugin, trigger, user_inputs: (
-                plugin.book(trigger, user_inputs=user_inputs), self.approval
-            ),
-        ))
-        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_plugin 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()

+ 0 - 1212
test/ita/test_debug_ita_book_gate.py

@@ -1,1212 +0,0 @@
-import copy
-import ast
-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_plugin as calendar_book
-from plugins.ita_plugin import AVAILABILITY_PATH, CALENDAR_PATH
-from plugins.ita_plugin import ItaPlugin
-from test.ita import test_debug_ita_calendar_gate as prep_fixtures
-from test.ita import test_debug_ita_production_query_gate as audit_fixtures
-from test.ita 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(
-                formReady=self.url == ORIGIN + self.booking_path,
-                otpValuePresent=bool(self.otp_value), otpSendEnabled=self.otp_clicks == 0,
-                **self.preflight_changes,
-            )
-        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.is_healthy = False
-    def create():
-        plugin.session_create_time = 123.0
-        plugin.is_healthy = True
-    plugin.create_session = Mock(side_effect=create)
-    plugin.cleanup = Mock()
-
-    def enter(apt_type, **kwargs):
-        page.url = ORIGIN + page.booking_path
-        return VSQueryResult(success=True, apt_type=apt_type, availability_status=AvailabilityStatus.NoneAvailable)
-
-    plugin._enter_service = Mock(side_effect=enter)
-    plugin.query = Mock(side_effect=AssertionError("Book must not call public Query"))
-    plugin.book = Mock(wraps=plugin.book)
-    plugin._record_calendar_prepared_route = Mock(wraps=plugin._record_calendar_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)
-        result.plugin._enter_service.assert_called_once()
-        result.plugin.query.assert_not_called()
-        self.assertEqual(result.page.clicks, 1)
-        self.assertEqual(result.page.otp_value, OTP)
-        self.assertEqual(result.page.alert_settings, [True, False])
-        self.assertEqual(result.plugin._prepared_calendar.role, "book")
-        self.assertEqual(result.plugin._record_calendar_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_receipt_baseline_mode_is_retired_before_browser_creation(self):
-        with patch.object(gate, "_book_credentials") as credentials:
-            result = self.run_gate(execute=False, verify_receipts=True)
-        self.assertEqual(result.code, 1)
-        self.assertIn("Receipt-baseline mode is no longer", result.output)
-        credentials.assert_not_called()
-        result.factory.assert_not_called()
-
-    def test_submit_once_preflight_is_local_and_needs_no_persistent_fence(self):
-        with patch.object(gate, "_book_credentials") as credentials:
-            result = self.run_gate(execute=False, submit_once=True)
-        self.assertEqual(result.code, 0, result.output)
-        credentials.assert_not_called()
-        result.factory.assert_not_called()
-
-    def test_submit_once_delegates_to_one_production_result(self):
-        page = GatePage()
-
-        class FinalRun:
-            def __init__(self, plugin, route, **_kwargs):
-                self.plugin, self.route = plugin, route
-                self.possibly_submitted = False
-                self.result = None
-                self.report = {
-                    "attempted": False, "automaticRetry": True,
-                    "bookingConfirmed": False, "outcome": "not_submitted",
-                }
-
-            def execute(self, **_kwargs):
-                self.possibly_submitted = True
-                page.emit("/BookingCalendar/InsertNewBooking", "POST")
-                self.result = VSBookResult(
-                    success=True, account=USERNAME, book_date="2026-10-13",
-                    book_time="10:05 - 11:05",
-                )
-                self.report.update(
-                    attempted=True, bookingConfirmed=True, outcome="confirmed",
-                    confirmedDate=self.result.book_date, confirmedTime=self.result.book_time,
-                )
-                return self.report
-
-        with patch.object(gate.final_evidence, "FinalEvidenceRun", FinalRun):
-            result = self.run_gate(
-                page, submit_once=True,
-                before=preparation.ReservationSnapshot(1, 0),
-                after=preparation.ReservationSnapshot(1, 0),
-            )
-        self.assertEqual(result.code, 0, result.output)
-        self.assertTrue(result.report["passed"])
-        self.assertTrue(result.report["bookResultSuccess"])
-        self.assertEqual(result.report["requests"]["finalRequests"], 1)
-        self.assertTrue(result.report["finalEvidence"]["automaticRetry"])
-        result.plugin.cleanup.assert_called_once()
-        self.assertFalse(result.page.listen.listening)
-        self.assertFalse(result.page.driver.immediate_event_handlers)
-        self.assertEqual(result.page.guard_final_count, 1)
-
-    def test_final_cli_flag_is_forwarded_without_receipt_requirement(self):
-        with patch.object(gate, "run_book_gate", return_value=0) as runner:
-            self.assertEqual(gate.main(["--preflight", "--submit-once"]), 0)
-        self.assertIs(runner.call_args.kwargs["submit_once"], True)
-        self.assertIs(runner.call_args.kwargs["verify_receipts"], False)
-        self.assertIs(runner.call_args.kwargs["execute"], False)
-    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._prepared_calendar.route.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.assertEqual(result.plugin._prepared_calendar.role, "book")
-        self.assertIsNone(result.plugin.free_config.get(gate.PERSISTENT_BROWSER_PROFILE_KEY))
-        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._enter_service = 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 = {"formReady": False}
-        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_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_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, "_prepared_calendar", SimpleNamespace(role="query")),
-            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_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(",
-                          "#btnPrenotaNoOtp", "InsertNewBooking"):
-            self.assertNotIn(forbidden, source)
-        registrations = [node for node in ast.walk(ast.parse(source))
-                         if isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
-                         and node.func.attr == "_record_calendar_prepared_route"]
-        self.assertEqual(len(registrations), 1)
-        self.assertEqual({kw.arg: ast.literal_eval(kw.value) for kw in registrations[0].keywords}, {"role": "book"})
-        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 in {"Book precommit rejected (precommit_rejected)",
-                           "Book TimeSlots request fields changed"}:
-                continue  # Produced by the shared protocol/request formatters and covered by packet tests.
-            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.formReady !== 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()

+ 0 - 1578
test/ita/test_debug_ita_calendar_gate.py

@@ -1,1578 +0,0 @@
-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_plugin import CALENDAR_GUARD_SCRIPT
-from plugins.ita_plugin import resolve_route_config
-from tools.debug_ita_calendar_gate import (
-    BookingPreflightStage,
-    CalendarGateMode,
-    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,
-    compare_availability_transport,
-    listen_once,
-    parse_availability_packet,
-    read_reservation_snapshot,
-    resolve_qcal_forward_months,
-    resolve_qcal_mode,
-    run_calendar_gate,
-    safe_avanti_failure_diagnostic,
-    safe_next_month_diagnostic,
-    safe_preflight_diagnostic,
-    scan_calendar_horizon,
-    transport_comparison_report,
-    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 = {
-        "formReady": True,
-        "turnstileReady": True,
-        "otpValuePresent": False,
-        "otpSendEnabled": True,
-        "avantiEnabled": True,
-    }
-    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.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}
-                    )
-
-    def test_transport_comparison_is_explicit_and_default_remains_discovery(self):
-        self.assertIs(resolve_qcal_mode({}), CalendarGateMode.DISCOVERY_HORIZON)
-        self.assertIs(
-            resolve_qcal_mode({"ITA_QCAL_MODE": "transport_compare"}),
-            CalendarGateMode.TRANSPORT_COMPARE,
-        )
-        with self.assertRaisesRegex(CalendarGateError, "transport_compare"):
-            resolve_qcal_mode({"ITA_QCAL_MODE": "browser_fetch"})
-
-
-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.assertFalse(result.days[0].is_available)
-        self.assertTrue(result.days[1].is_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)
-
-    def test_browser_fetch_transport_matches_the_native_month_without_leaking_service(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,
-                },
-            ]
-        )
-        raw_body = json.dumps(inner)
-        packet = FakePacket(
-            method="POST",
-            url="https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability",
-            status=200,
-            raw_body=raw_body,
-            post_data=json.dumps(
-                {"_Servizio": "private-runtime-id", "selectedDay": "01/10/2026"}
-            ),
-        )
-        native = parse_availability_packet(packet)
-        calls = []
-
-        def fetch(*args, **kwargs):
-            calls.append((args, kwargs))
-            return SimpleNamespace(
-                status_code=200,
-                url=packet.url,
-                text=raw_body,
-            )
-
-        report = compare_availability_transport(
-            SimpleNamespace(), packet, native, fetch=fetch
-        )
-
-        self.assertEqual(
-            report,
-            {
-                "month": "2026-10",
-                "dayCount": 2,
-                "availableCount": 1,
-                "equivalent": True,
-            },
-        )
-        self.assertEqual(calls[0][0][1:3], ("POST", packet.url))
-        self.assertEqual(calls[0][1]["timeout"], 30)
-        self.assertEqual(
-            calls[0][1]["json_data"],
-            {"_Servizio": "private-runtime-id", "selectedDay": "01/10/2026"},
-        )
-        self.assertNotIn("private-runtime-id", json.dumps(report))
-
-    def test_browser_fetch_transport_rejects_inventory_status_and_raw_body_changes(self):
-        inner = json.dumps(
-            [{
-                "DateLibere": "01/10/2026 00:00:00",
-                "SlotLiberi": 0,
-                "SlotRimanenti": -1,
-            }]
-        )
-        packet = FakePacket(
-            method="POST",
-            url="https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability",
-            status=200,
-            raw_body=json.dumps(inner),
-            post_data={"_Servizio": "private-runtime-id", "selectedDay": "01/10/2026"},
-        )
-        native = parse_availability_packet(packet)
-        changed = json.dumps(json.dumps([{
-            "DateLibere": "01/10/2026 00:00:00",
-            "SlotLiberi": 1,
-            "SlotRimanenti": 0,
-        }]))
-        cases = (
-            (
-                SimpleNamespace(status_code=200, url=packet.url, text=changed),
-                "inventory differed",
-            ),
-            (
-                SimpleNamespace(status_code=429, url=packet.url, text="private-rate-body"),
-                "rate limited",
-            ),
-            (
-                SimpleNamespace(status_code=401, url=packet.url, text="private-auth-body"),
-                "authentication expired",
-            ),
-            (
-                SimpleNamespace(status_code=403, url=packet.url, text="private-denied-body"),
-                "access was denied",
-            ),
-            (
-                SimpleNamespace(status_code=503, url=packet.url, text="private-transient-body"),
-                "temporarily failed",
-            ),
-            (
-                SimpleNamespace(status_code=200, url="https://iam.esteri.it/signin/", text="private-login"),
-                "response URL changed",
-            ),
-            (
-                SimpleNamespace(status_code=200, url=packet.url, text="private-malformed-body"),
-                "response rejected",
-            ),
-        )
-        for response, expected in cases:
-            with self.subTest(expected=expected):
-                with self.assertRaisesRegex(CalendarGateError, expected) as caught:
-                    compare_availability_transport(
-                        SimpleNamespace(), packet, native,
-                        fetch=lambda *_args, **_kwargs: response,
-                    )
-                self.assertNotIn("private", str(caught.exception))
-
-    def test_transport_report_requires_two_reads_per_month_and_no_business_writes(self):
-        comparisons = [
-            {"month": "2026-08", "dayCount": 2, "availableCount": 0, "equivalent": True},
-            {"month": "2026-09", "dayCount": 3, "availableCount": 1, "equivalent": True},
-        ]
-        before = {
-            "otpRequests": 1,
-            "avantiPosts": 1,
-            "availabilityRequests": 0,
-            "finalRequests": 0,
-        }
-        after = {**before, "availabilityRequests": 4}
-
-        report = transport_comparison_report(
-            comparisons, before, after, native_requests=2
-        )
-
-        self.assertTrue(report["coverageComplete"])
-        self.assertTrue(report["requestContractMatched"])
-        self.assertEqual(report["emptyMonths"], 1)
-        self.assertEqual(report["positiveMonths"], 1)
-        self.assertEqual(
-            report["compareRequestDelta"],
-            {
-                "otpRequests": 0,
-                "avantiPosts": 0,
-                "availabilityRequests": 4,
-                "finalRequests": 0,
-            },
-        )
-
-        for changed in (
-            {**after, "otpRequests": 2},
-            {**after, "avantiPosts": 2},
-            {**after, "finalRequests": 1},
-            {**after, "availabilityRequests": 3},
-        ):
-            with self.subTest(changed=changed):
-                bad = transport_comparison_report(
-                    comparisons, before, changed, native_requests=2
-                )
-                self.assertFalse(bad["requestContractMatched"])
-
-
-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_transport_observer_receives_each_native_packet_after_guard(self):
-        packets = [self.packet(8), self.packet(9, available=True)]
-        events = []
-
-        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",
-            side_effect=lambda _page: events.append("refresh"),
-        ), patch(
-            "tools.debug_ita_calendar_gate._click_next_month",
-            side_effect=lambda _page: events.append("next"),
-        ), patch(
-            "tools.debug_ita_calendar_gate._calendar_guard",
-            side_effect=lambda _page: events.append("guard"),
-        ), patch("tools.debug_ita_calendar_gate.time.sleep"):
-            result = scan_calendar_horizon(
-                SimpleNamespace(),
-                forward_months=1,
-                packet_observer=lambda packet, probe: events.append(
-                    (packet.url, probe.selected_month)
-                ),
-            )
-
-        self.assertEqual(result.availability_requests, 2)
-        self.assertEqual(events[0:3], [
-            "refresh",
-            "guard",
-            (
-                "https://prenotami.esteri.it/BookingCalendar/RetrieveCalendarAvailability",
-                (2026, 8),
-            ),
-        ])
-        self.assertEqual(events[3], "next")
-        self.assertEqual(events[4], "guard")
-        self.assertEqual(events[5][1], (2026, 9))
-
-    def test_invalid_transport_observer_fails_before_browser_actions(self):
-        page = SimpleNamespace()
-        with self.assertRaisesRegex(CalendarGateError, "packet_observer"):
-            scan_calendar_horizon(page, forward_months=1, packet_observer=object())
-
-    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(otpSendEnabled=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",
-                "formReady",
-                "otpValuePresent",
-                "otpSendEnabled",
-                "avantiEnabled",
-                "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["otpSendEnabled"],
-            {"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(otpSendEnabled=1)
-        raw["mustNotLeak"] = "private-runtime-value"
-        page = SimpleNamespace(run_js=lambda _script: raw)
-        stdout = StringIO()
-
-        with redirect_stdout(stdout):
-            with self.assertRaisesRegex(CalendarGateError, "otpSendEnabled"):
-                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_timeout_diagnostic_stays_in_the_debug_gate(self):
-        raw = booking_preflight_snapshot(turnstileReady=False)
-        raw["mustNotLeak"] = "private-runtime-value"
-        page = SimpleNamespace(run_js=lambda _script: raw)
-        stdout = StringIO()
-
-        with patch("plugins.ita_plugin.time.monotonic", side_effect=[0, 0, 2]), \
-             patch("plugins.ita_plugin.time.sleep"), redirect_stdout(stdout), \
-             self.assertRaisesRegex(CalendarGateError, "turnstile_token_pending"):
-            wait_for_booking_preflight(page, script="safe-script", timeout=1)
-
-        output = stdout.getvalue()
-        self.assertIn("ITA_QCAL_PREFLIGHT_DIAGNOSTIC=", output)
-        self.assertIn('"outcome": "timeout"', 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 ("formReady", "turnstileReady", "otpValuePresent",
-                    "otpSendEnabled", "avantiEnabled"):
-            with self.subTest(key=key):
-                changed = dict(raw)
-                changed[key] = not changed[key]
-                with self.assertRaisesRegex(CalendarGateError, key):
-                    validate_booking_preflight(changed)
-
-    def test_post_otp_accepts_cooldown_without_relaxing_structure(self):
-        cooldown = booking_preflight_snapshot(
-            otpSendEnabled=False,
-            otpValuePresent=True,
-        )
-
-        with self.assertRaisesRegex(CalendarGateError, "otpValuePresent"):
-            validate_booking_preflight(cooldown)
-        validate_booking_preflight(
-            cooldown,
-            after_otp=True,
-        )
-
-        for key, value in (
-            ("otpSendEnabled", True),
-            ("otpValuePresent", False),
-            ("formReady", False),
-        ):
-            with self.subTest(key=key):
-                changed = dict(cooldown)
-                changed[key] = value
-                with self.assertRaisesRegex(CalendarGateError, key):
-                    validate_booking_preflight(
-                        changed,
-                        after_otp=True,
-                    )
-
-    def test_dynamic_wait_rechecks_token_without_relaxing_structure(self):
-        base = booking_preflight_snapshot(
-            avantiEnabled=False,
-            turnstileReady=False,
-        )
-        ready = dict(base)
-        ready["avantiEnabled"] = True
-        ready["turnstileReady"] = 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(
-            otpSendEnabled=False,
-            otpValuePresent=True,
-            avantiEnabled=False,
-            turnstileReady=False,
-        )
-        ready = dict(base)
-        ready["avantiEnabled"] = True
-        ready["turnstileReady"] = 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[2]
-            / "tools"
-            / "debug_ita_calendar_gate.py"
-        )
-        shared_path = (
-            Path(__file__).resolve().parents[2]
-            / "plugins"
-            / "ita_plugin.py"
-        )
-        plugin_path = tool_path.parents[1] / "plugins" / "ita_plugin.py"
-        protocol_path = tool_path.parents[1] / "plugins" / "ita_plugin.py"
-        expected_fingerprint = hashlib.sha256(
-            tool_path.read_bytes()
-            + (tool_path.parents[1] / "plugins" / "ita_plugin.py").read_bytes()
-            + shared_path.read_bytes()
-            + plugin_path.read_bytes() + protocol_path.read_bytes()
-            + (tool_path.parents[1] / "plugins" / "ita_plugin.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[2]
-            / "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()

+ 0 - 370
test/ita/test_debug_ita_monitor.py

@@ -1,370 +0,0 @@
-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._bind_query_profile",
-                return_value=Mock(),
-            ),
-            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._bind_query_profile",
-                return_value=Mock(),
-            ),
-            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[2]
-        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[2]
-            / "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()

+ 0 - 554
test/ita/test_debug_ita_production_query_gate.py

@@ -1,554 +0,0 @@
-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_plugin import (
-    AVAILABILITY_PATH,
-    CALENDAR_GUARD_SCRIPT,
-    NEXT_MONTH_CONTROL_SCRIPT,
-    CalendarGateError,
-    CalendarProbeResult,
-)
-from plugins.ita_plugin import ItaPlugin
-from plugins.ita_plugin import CalendarDay
-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)
-                for day in positive_days
-            )
-            if month == 10 and positive_days
-            else (CalendarDay(date(2026, month, 1), 0, -1),)
-        )
-        probes.append(CalendarProbeResult(days, f"01/{month:02d}/2026"))
-    return tuple(probes)
-
-
-def make_result(scan, apt_type):
-    available = scan[-1].available_days
-    earliest = available[0].day if available else None
-    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"
-        self.tab_id = "audit-fixture-tab"
-        self.runtime_service = "runtime-service"
-
-    def run_js(self, script, *args):
-        if "coordinate:ita-book-runtime-service" in script:
-            return {"path": "/BookingCalendar", "count": 1, "value": self.runtime_service}
-        if script == CALENDAR_GUARD_SCRIPT:
-            return {"path": "/BookingCalendar", "calendarFunctionPresent": True, "finalButtonCount": 1,
-                    "allFinalButtonsGuarded": True, "finalRequestCount": self.final_requests, "timeSlotRequestCount": 0}
-        raise AssertionError("Unexpected audit-page script")
-
-    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)
-        self.tab_id = "production-query-fixture-tab"
-        self.runtime_service = "runtime-service"
-
-    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 == 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,
-            }
-        return super().run_js(script, *args)
-
-
-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.is_healthy = True
-    plugin.session_create_time = 1.0
-    plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query")
-    # __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._enter_service = Mock(return_value=VSQueryResult(success=True))
-        plugin.query = Mock(side_effect=AssertionError("Preparation must not call public Query"))
-
-        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()
-        plugin._enter_service.assert_called_once()
-        plugin.query.assert_not_called()
-        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()

+ 0 - 861
test/ita/test_debug_ita_query_book.py

@@ -1,861 +0,0 @@
-"""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.ita.test_ita_plugin import OrderBookerGCO, FakeRetainedSignalRedis
-from sentinel import SentinelGCO
-from test.ita import test_ita_calendar_book_flow as book_flow
-from test.ita.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_prepared_route(self.query._resolve_route(self.apt), role="query"))
-        self.query.cleanup = Mock()
-
-        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_plugin.submit_final",
-                                            side_effect=AssertionError("Final submission forbidden")))
-        # Query month navigation uses only the synthetic page above.
-        self.enterContext(patch("plugins.ita_plugin.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 = 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_prepared_route(plugin._resolve_route(self.apt), role="book"))
-        original_book = plugin.book
-        plugin.observed_approval = None
-        def observed_book(trigger, inputs):
-            result, plugin.observed_approval = book_flow.book_with_approval(
-                plugin, trigger, inputs, call=original_book,
-            )
-            return result
-        plugin.book = Mock(side_effect=observed_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)
-
-    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.observed_approval.candidate.day, date(2026, 10, 14))
-        self.assertEqual(self.book_page.refreshes, 1)  # Applicant inventory is scanned once.
-        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.observed_approval)
-        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.observed_approval.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, on_created=None):
-            gco.m_factory.create = Mock(return_value=f.query if role == "query" else f.book_plugin)
-            return real_observe(gco, role, stack, observed, on_created=on_created)
-
-        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):
-    def setUp(self):
-        from tools import ita_query_book_local as local
-        self.local = local
-        self.applicant = SimpleNamespace(
-            username="Applicant@example.test", password="fixture-password")
-        self.route = SimpleNamespace(
-            service_id=9001, routing_key="slot.fixture.it.tourist",
-            capability="single_schengen_tourism", lookahead_months=3)
-        candidate = SimpleNamespace(
-            day=date(2026, 10, 13), time_label="10:05 - 11:05", slots_free=1)
-        self.approval = SimpleNamespace(candidate=candidate)
-        self.plugin = SimpleNamespace(config=SimpleNamespace(account=self.applicant))
-        self.audit = Mock()
-        self.audit.settled_snapshot.return_value = {
-            "otpRequests": 0, "avantiPosts": 0, "availabilityRequests": 0,
-            "timeSlotRequests": 0, "finalRequests": 0,
-        }
-        self.observed = {
-            "book": SimpleNamespace(plugin=self.plugin, audit=self.audit),
-            "query": SimpleNamespace(plugin=object(), audit=self.audit),
-        }
-        self.control = local.LocalFinalSubmission(self.applicant, self.route)
-
-    def submit(self, result):
-        production = Mock(return_value=result)
-        with patch.object(self.local, "verify_plugin_selection"):
-            returned = self.control.submit(
-                self.plugin, self.route, self.approval, self.observed, production)
-        production.assert_called_once_with(self.plugin, self.route, self.approval)
-        return returned
-
-    def test_standard_success_delegates_once_without_private_fence(self):
-        result = SimpleNamespace(success=True)
-        self.assertIs(self.submit(result), result)
-        self.assertTrue(self.control.used)
-        self.assertTrue(self.control.dispatched)
-        self.assertFalse(hasattr(self.control, "claim_path"))
-
-    def test_standard_failure_remains_retryable_by_the_shared_booker(self):
-        result = SimpleNamespace(success=False)
-        self.assertIs(self.submit(result), result)
-        self.assertTrue(self.control.dispatched)
-        self.assertNotEqual(getattr(self.control, "failure_reason", None), "unknown_do_not_retry")
-
-    def test_same_local_control_cannot_dispatch_twice_in_one_run(self):
-        self.submit(SimpleNamespace(success=False))
-        with self.assertRaises(self.local.LocalAcceptanceError):
-            self.control.submit(
-                self.plugin, self.route, self.approval, self.observed, Mock())
-
-    def test_wrong_applicant_or_existing_final_request_is_rejected(self):
-        production = Mock()
-        self.plugin.config.account.username = "other@example.test"
-        with self.assertRaises(self.local.LocalAcceptanceError):
-            self.control.submit(
-                self.plugin, self.route, self.approval, self.observed, production,
-            )
-        production.assert_not_called()
-
-
-class LocalFinalCompositionTests(unittest.TestCase):
-    def setUp(self):
-        from tools import ita_query_book_local as local
-        self.local = local
-
-    def test_noninteractive_failure_uses_ordinary_exit_code(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": "book_failed_retryable",
-            "finalDispatched": 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), 1)
-            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):
-            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), \
-                    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), \
-                    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()

+ 0 - 26
test/ita/test_debug_ita_reservation.py

@@ -1,26 +0,0 @@
-"""The legacy Italy reservation diagnostic is intentionally retired."""
-
-import unittest
-
-from plugins import ita_plugin
-from tools import debug_ita_reservation as diagnostic
-
-
-class RetiredReservationDiagnosticTests(unittest.TestCase):
-    def test_cli_reports_retired_without_browser_or_network(self):
-        self.assertEqual(diagnostic.main([]), 0)
-
-    def test_old_receipt_parsers_are_not_production_symbols(self):
-        for name in (
-            "LIST_READ_SCRIPT", "ReservationReadError", "ReservationState",
-            "read_reservation_listing",
-        ):
-            self.assertFalse(hasattr(ita_plugin, name), name)
-
-    def test_compatibility_entrypoints_fail_explicitly(self):
-        with self.assertRaises(diagnostic.ReservationDiagnosticRetired):
-            diagnostic.read_reservation_detail(object())
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 571
test/ita/test_debug_ita_soak.py

@@ -1,571 +0,0 @@
-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 Mock, 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):
-        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,
-            }
-        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.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":
-            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(
-                "tools.debug_ita_soak._bind_query_profile",
-                return_value=Mock(),
-            ),
-            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.assertIn('"target_link_count": 0', stdout)
-        self.assertNotIn("ITA_SERVICE_LIST_STRUCTURE=not-available", stdout)
-        self.assertEqual(statuses[-1]["transient_errors"], 1)
-        self.assertEqual(stderr, "")
-
-    def test_failed_diagnostic_does_not_interrupt_missing_link_recovery(self):
-        FakeSoakPlugin.session_behaviors = [["missing-link", "none"]]
-        with patch.object(FakeSoakPage, "run_js", side_effect=RuntimeError("server-secret")):
-            exit_code, stdout, stderr, _, statuses, _, _ = self._run()
-        self.assertEqual(exit_code, 0)
-        self.assertEqual(FakeSoakPlugin.instances[0].query_calls, 2)
-        self.assertEqual(FakeSoakPlugin.instances[0].cleanup_calls, 1)
-        self.assertEqual(statuses[-1]["transient_errors"], 1)
-        self.assertIn("ITA_SERVICE_LIST_STRUCTURE=not-available", stdout)
-        self.assertNotIn("server-secret", stdout)
-        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[2]
-        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[2] / "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()

+ 83 - 87
test/ita/test_ita_booker_integration.py

@@ -1,143 +1,139 @@
-"""Italy Book integration with the existing shared OrderBooker."""
-
+"""Real OrderBooker -> public Italy Book -> final response, external I/O mocked."""
 import json
 import threading
 import unittest
 from types import SimpleNamespace
 from unittest.mock import Mock, patch
 
-from plugins.ita_plugin import FINAL_PATH, NATIVE_FINAL_SCRIPT
-from test.ita import test_ita_calendar_book_flow as flow
-from test.ita.test_ita_plugin import OrderBookerGCO
-
-
-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.final_count = 0
-        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
-        self.final_count += 1
-        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,
-                url="https://prenotami.esteri.it" + FINAL_PATH,
-                raw_body=json.dumps({
-                    "errorMessage": self.response_error,
-                    "url": "/Reservation" if not self.response_error else "/BookingCalendar",
-                }),
-            ),
-        ))
-        return {"clicked": True}
+from booker import OrderBookerGCO
+from plugins import ita_plugin as ita
+from test.ita.test_ita_compact import Response, day, encoded, route_config, slot
+from vs_types import AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig, VSQueryResult
 
 
 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.service, self.date, self.daily_id = "4937", "2026-10-02", 12345678
+        self.selected, self.final_status, self.final_error = False, 200, ""
+        self.page = SimpleNamespace(tab_id="applicant-tab", run_js=Mock(side_effect=self.dom),
+                                    url="https://prenotami.esteri.it/BookingCalendar")
+        self.plugin = object.__new__(ita.ItaPlugin)
+        self.plugin.config = VSPlgConfig(account=VSAccount(username="applicant@example.test"),
+            free_config={"query_mode": "services_probe", "otp_mode": "cloud",
+                         "final_submit_enabled": True, "apt_configs": {"route": route_config()}})
+        self.plugin.free_config = self.plugin.config.free_config
+        self.plugin.page, self.plugin.is_healthy = self.page, True
         self.plugin._log = Mock()
-        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.route = self.plugin._resolve_route(AppointmentType(routing_key="route"))
+        self.plugin._record_calendar_prepared_route(self.route, role="book")
+        self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch", side_effect=self.response))
+        self.trigger = VSQueryResult(success=True, apt_type=AppointmentType(routing_key="route"),
+                                     availability_status=AvailabilityStatus.Available)
+        self.inputs = {"username": "applicant@example.test", "password": "synthetic-not-for-reporting",
+                       "expected_start_date": "2026-10-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,
-        }}
+            "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.booker._on_task_removed = Mock()
-        self.cloud = Mock()
-        self.queue = []
-        self.executor = Mock()
+        self.cloud, self.executor, self.queue = Mock(), Mock(), []
         self.executor.enqueue.side_effect = self.queue.append
-        self.enterContext(patch.dict(
-            self.booker._execute_book_job.__func__.__globals__,
+        self.enterContext(patch.dict(self.booker._execute_book_job.__func__.__globals__,
             VSCloudApi=SimpleNamespace(Instance=lambda: self.cloud),
-            ThreadPool=SimpleNamespace(getInstance=lambda: self.executor),
-        ))
-        self.enterContext(flow.browser_navigation(self.page))
+            ThreadPool=SimpleNamespace(getInstance=lambda: self.executor)))
+
+    def dom(self, script, mode, *args):
+        self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
+        if mode == "context":
+            return {"path": "/BookingCalendar", "service": self.service, "day": self.date}
+        service, day_value, daily_id, _, _, click = args
+        if mode == "slot" and click:
+            self.selected = True
+        return {"contextReady": service == self.service,
+                "candidateCount": int(day_value == self.date and
+                    (mode == "date" or daily_id == str(self.daily_id))),
+                "candidateReady": True, "selected": mode == "date" or self.selected,
+                "clicked": click}
+
+    def response(self, page, method, path, **kwargs):
+        self.assertIs(page, self.page)
+        self.assertEqual(method, "POST")
+        status = 200
+        if path == ita.AVAILABILITY_PATH:
+            body = encoded([day("02/10/2026 00:00:00")])
+        elif path == ita.TIME_SLOTS_PATH:
+            body = encoded([slot("02/10/2026 00:00:00", daily_id=self.daily_id)])
+        elif path == ita.FINAL_PATH:
+            status = self.final_status
+            self.assertEqual(kwargs["data"]["idCalendarioGiornaliero"], str(self.daily_id))
+            body = json.dumps({"errorMessage": self.final_error,
+                               "url": "/Reservation" if not self.final_error else "/BookingCalendar"})
+        else:
+            self.fail("Unexpected request")
+        return Response(status, body, "https://prenotami.esteri.it" + path)
 
     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 final_calls(self):
+        return [call for call in self.fetch.call_args_list if call.args[2] == ita.FINAL_PATH]
 
     def test_explicit_site_success_uses_shared_success_reporting(self):
         self.run_booker()
-        self.assertEqual(self.page.final_count, 1)
+        self.assertEqual(len(self.final_calls()), 1)
         self.assertEqual(self.booker.m_tasks, [])
         self.booker._cleanup_task.assert_called_once_with(self.task, "booking success")
         self.assertEqual(len(self.queue), 1)
-        self.drain_reports()
+        self.queue.pop()()
         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"], "")
-        self.assertEqual(history["account"], self.inputs["username"].lower())
-        self.assertEqual(history["slot_date"], "2026-10-13")
-        self.assertEqual(history["slot_time"], "10:05 - 11:05")
+        self.assertEqual(payload["grabbed_history"]["account"], self.inputs["username"])
+        self.assertEqual(payload["grabbed_history"]["slot_date"], self.date)
+        self.assertEqual(payload["grabbed_history"]["slot_time"], "10:05 - 11:05")
         self.assertNotIn(self.inputs["password"], json.dumps(payload))
 
-    def test_site_rejection_stays_in_shared_retry_on_next_signal_branch(self):
-        self.page.response_error = "Synthetic slot no longer available"
+    def test_site_rejection_stays_in_shared_retry_branch(self):
+        self.final_error = "Synthetic rejection"
         self.run_booker()
-        self.assertEqual(self.page.final_count, 1)
+        self.assertEqual(len(self.final_calls()), 1)
         self.assertEqual(self.booker.m_tasks, [self.task])
         self.assertTrue(self.task.book_allowed)
         self.assertIsNone(self.plugin._prepared_calendar)
-        self.cloud.update_vas_task.assert_not_called()
         self.executor.enqueue.assert_not_called()
 
-    def test_later_signal_can_retry_after_fresh_calendar_preparation(self):
-        self.page.response_error = "Synthetic rejection"
+    def test_later_signal_rechecks_new_inventory_after_new_preparation(self):
+        self.final_error = "Synthetic rejection"
         self.run_booker()
+        self.assertIsNone(self.plugin._prepared_calendar)
+        # Simulate a newly prepared browser, not reuse the previous slot object.
+        self.daily_id, self.selected, self.final_error = 87654321, False, ""
         self.plugin._record_calendar_prepared_route(self.route, role="book")
-        self.page.response_error = ""
         self.run_booker()
-        self.assertEqual(self.page.final_count, 2)
+        self.assertEqual(len(self.final_calls()), 2)
+        self.assertEqual([call.kwargs["data"]["idCalendarioGiornaliero"]
+                          for call in self.final_calls()], ["12345678", "87654321"])
         self.assertEqual(self.booker.m_tasks, [])
-        self.assertTrue(any("Will retry on next signal" in str(call) for call in self.booker._log.call_args_list))
 
-    def test_unmatched_post_is_failure_not_pause(self):
-        self.page.wrong_request_day = True
+    def test_rate_limit_reaches_shared_retirement_branch(self):
+        self.final_status = 429
         self.run_booker()
-        self.assertEqual(self.page.final_count, 1)
-        self.assertEqual(self.booker.m_tasks, [self.task])
-        self.assertTrue(self.task.book_allowed)
-        self.cloud.update_vas_task.assert_not_called()
+        self.assertEqual(len(self.final_calls()), 1)
+        self.assertEqual(self.booker.m_tasks, [])
+        self.booker._cleanup_task.assert_called_once_with(self.task, "booking rate limited")
+        self.executor.enqueue.assert_not_called()
+        self.assertIsNone(self.plugin._prepared_calendar)
 
-    def test_prefinal_mode_never_calls_final_or_reports_success(self):
+    def test_prefinal_never_submits_or_reports_success(self):
         self.plugin.free_config["final_submit_enabled"] = False
         self.run_booker()
-        self.assertEqual(self.page.final_count, 0)
+        self.assertEqual(self.final_calls(), [])
         self.assertEqual(self.booker.m_tasks, [self.task])
         self.executor.enqueue.assert_not_called()
         self.cloud.update_vas_task.assert_not_called()

+ 147 - 216
test/ita/test_ita_booking_final.py

@@ -1,229 +1,160 @@
-"""Offline contracts for the thin Italy final-submit adapter."""
-
+"""Final POST contract through the current adapter; no browser or network."""
 import json
 import unittest
+from datetime import date, time
 from types import SimpleNamespace
-from unittest.mock import Mock
-
-from plugins import ita_plugin as final
-from plugins.ita_plugin import (
-    FINAL_ACCEPTED_LABEL,
-    FINAL_FAILED_LABEL,
-    FINAL_PATH,
-    NATIVE_FINAL_SCRIPT,
-    _final_packet_accepted,
-    _submit_final_once,
-)
-from test.ita.test_ita_calendar_book import FakePage, SERVICE, select
-from test.ita import test_ita_calendar_book_flow as flow
-
-
-def target():
-    """Small synthetic target retained for debug-tool fixtures."""
-    page = FakePage()
-    approval = select(page)
-    return SimpleNamespace(
-        applicant="applicant@example.test",
-        tab_id="applicant-tab",
-        routing_key="slot.fixture.it.tourist",
-        runtime_service=SERVICE,
-        approval=approval,
-    )
-
-
-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,
-            url="https://prenotami.esteri.it" + FINAL_PATH,
-            raw_body=json.dumps({"errorMessage": error, "url": destination}),
-        ),
-    )
-
-
-class Listener:
-    def __init__(self, page):
-        self.page = page
-        self.packet = None
-        self.started = self.stopped = 0
-
-    def start(self, target_path, method):
-        self.started += 1
-        if target_path != FINAL_PATH or method != "POST":
-            raise AssertionError("unexpected listener contract")
-
-    def wait(self, timeout):
-        return self.packet
-
-    def stop(self):
-        self.stopped += 1
-
-
-class NativePage(FakePage):
-    def __init__(self, booking_target=None):
-        super().__init__()
-        booking_target = booking_target or target()
-        self.tab_id = booking_target.tab_id
-        self.active = True
-        self.final_clicks = 0
-        self.final_packet = final_packet(booking_target)
-        self.listen = Listener(self)
-
-    def run_js(self, script, *args):
-        if script == NATIVE_FINAL_SCRIPT:
-            self.final_clicks += 1
-            self.listen.packet = self.final_packet
-            return {"clicked": True}
-        return super().run_js(script, *args)
-
-
-class PacketAcceptanceTests(unittest.TestCase):
+from unittest.mock import Mock, patch
+
+from plugins import ita_plugin as ita
+from test.ita.test_ita_compact import Response, route_config
+from vs_types import VSAccount
+
+
+class FinalSubmissionTests(unittest.TestCase):
     def setUp(self):
-        self.target = target()
-        self.packet = final_packet(self.target)
-
-    def accepted(self):
-        return _final_packet_accepted(
-            self.packet, self.target.approval, self.target.tab_id)
-
-    def test_exact_native_post_and_explicit_site_success_are_accepted(self):
-        self.assertTrue(self.accepted())
-        self.packet.request.postData = (
-            "idCalendarioGiornaliero=80001001&"
-            "selectedDay=2026-10-13&selectedHour=10%3A05+-+11%3A05%0A%281%29"
-        )
-        self.assertTrue(self.accepted())
-
-    def test_site_error_is_an_ordinary_rejection(self):
-        self.packet.response.raw_body = json.dumps(
-            {"errorMessage": "slot unavailable", "url": "/BookingCalendar"})
-        self.assertFalse(self.accepted())
-
-    def test_request_identity_must_match_current_selection(self):
-        mutations = (
-            ("url", "https://prenotami.esteri.it/Other"),
-            ("method", "GET"),
-            ("tab_id", "other-tab"),
-            ("is_failed", True),
-        )
-        for field, value in mutations:
-            with self.subTest(field=field):
-                packet = final_packet(self.target)
-                setattr(packet, field, value)
-                self.assertFalse(_final_packet_accepted(
-                    packet, self.target.approval, self.target.tab_id))
-
-    def test_body_requires_exact_unique_fields_and_current_runtime_id(self):
-        bodies = (
-            {},
-            {"idCalendarioGiornaliero": "80001001", "selectedDay": "2026-10-13"},
-            {"idCalendarioGiornaliero": "wrong", "selectedDay": "2026-10-13",
-             "selectedHour": "10:05 - 11:05\n(1)"},
-            "idCalendarioGiornaliero=80001001&idCalendarioGiornaliero=80001001&"
-            "selectedDay=2026-10-13&selectedHour=10%3A05+-+11%3A05%0A%281%29",
+        self.route = ita.resolve_route_config({"route": route_config()}, "route")
+        self.slot = ita.SlotCandidate(date(2026, 10, 2), 1, 0,
+                                      time(10, 5), time(11, 5), "12345678")
+        self.page = SimpleNamespace(tab_id="applicant-tab",
+                                    url="https://prenotami.esteri.it/BookingCalendar")
+        self.plugin = SimpleNamespace(
+            page=self.page,
+            config=SimpleNamespace(account=VSAccount(username="applicant@example.test")),
+            _require_calendar_context=Mock(return_value=SimpleNamespace(
+                tab_id=self.page.tab_id, runtime_service="4937")),
+            _reset_calendar_state=Mock(),
         )
-        for body in bodies:
-            with self.subTest(body=body):
-                packet = final_packet(self.target)
-                packet.request.postData = body
-                self.assertFalse(_final_packet_accepted(
-                    packet, self.target.approval, self.target.tab_id))
-
-    def test_response_must_be_bounded_same_origin_explicit_json_success(self):
-        values = (
-            (500, '{"errorMessage":"","url":"/Reservation"}'),
-            (200, "not-json"),
-            (200, '{"url":"/Reservation"}'),
-            (200, '{"errorMessage":null,"url":"/Reservation"}'),
-            (200, '{"errorMessage":"","url":"https://attacker.test"}'),
-        )
-        for status, raw in values:
-            with self.subTest(status=status, raw=raw):
-                packet = final_packet(self.target)
-                packet.response.status = status
-                packet.response.raw_body = raw
-                self.assertFalse(_final_packet_accepted(
-                    packet, self.target.approval, self.target.tab_id))
+        self.verify = self.enterContext(patch.object(ita, "verify_precommit_selection"))
+        self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch"))
+        self.respond()
 
+    def respond(self, *, status=200, body=None, url=None):
+        self.fetch.return_value = Response(
+            status, body if body is not None else json.dumps({
+                "errorMessage": "", "url": "/Reservation"}),
+            url or "https://prenotami.esteri.it" + ita.FINAL_PATH)
 
-class SubmitOnceTests(unittest.TestCase):
-    def setUp(self):
-        bootstrap = target()
-        self.page = NativePage(bootstrap)
-        self.plugin, self.route, _ = flow.prepared_plugin(
-            self.page, routing_key=bootstrap.routing_key)
-        self.plugin._log = Mock()
-        self.approval = bootstrap.approval
-
-    def test_success_uses_one_native_click_and_standard_result(self):
-        result = _submit_final_once(self.plugin, self.route, self.approval)
+    def submit(self):
+        return ita._submit_final_once(self.plugin, self.route, self.slot)
+
+    def test_one_form_post_uses_current_applicant_selection(self):
+        result = self.submit()
         self.assertTrue(result.success)
-        self.assertEqual(result.label, FINAL_ACCEPTED_LABEL)
         self.assertEqual(result.account, "applicant@example.test")
-        self.assertEqual(result.book_date, "2026-10-13")
+        self.assertEqual(result.book_date, "2026-10-02")
         self.assertEqual(result.book_time, "10:05 - 11:05")
-        self.assertEqual(self.page.final_clicks, 1)
-        self.assertEqual((self.page.listen.started, self.page.listen.stopped), (1, 1))
-        self.assertIsNotNone(self.plugin._prepared_calendar)
-
-    def test_site_rejection_returns_false_and_discards_attempt_context(self):
-        self.page.final_packet.response.raw_body = json.dumps(
-            {"errorMessage": "slot unavailable", "url": "/BookingCalendar"})
-        result = _submit_final_once(self.plugin, self.route, self.approval)
-        self.assertFalse(result.success)
-        self.assertEqual(result.label, FINAL_FAILED_LABEL)
-        self.assertEqual(self.page.final_clicks, 1)
-        self.assertIsNone(self.plugin._prepared_calendar)
-
-    def test_timeout_or_mismatched_packet_is_false_not_unknown_pause(self):
-        for mode in ("timeout", "wrong-day"):
-            with self.subTest(mode=mode):
-                self.setUp()
-                if mode == "timeout":
-                    self.page.final_packet = None
-                else:
-                    self.page.final_packet.request.postData["selectedDay"] = "2026-10-14"
-                result = _submit_final_once(self.plugin, self.route, self.approval)
-                self.assertFalse(result.success)
-                self.assertEqual(self.page.final_clicks, 1)
-                self.assertIsNone(self.plugin._prepared_calendar)
-
-    def test_changed_applicant_or_selection_never_clicks(self):
-        self.plugin.config.account.username = "other@example.test"
-        result = _submit_final_once(self.plugin, self.route, self.approval)
-        self.assertFalse(result.success)
-        self.assertEqual(self.page.final_clicks, 0)
-        self.assertIsNone(self.plugin._prepared_calendar)
-
-    def test_second_call_without_fresh_preparation_never_clicks_again(self):
-        self.page.final_packet = None
-        self.assertFalse(_submit_final_once(self.plugin, self.route, self.approval).success)
-        self.assertFalse(_submit_final_once(self.plugin, self.route, self.approval).success)
-        self.assertEqual(self.page.final_clicks, 1)
-
-
-class SourceContractTests(unittest.TestCase):
-    def test_old_unknown_and_receipt_state_machine_is_not_in_runtime(self):
-        for name in (
-            "FinalOutcomeUnknown", "FinalBookingAttempt", "NativeFinalSubmitter",
-            "SubmissionSignal", "ReservationSnapshot", "ReservationState",
-        ):
-            self.assertFalse(hasattr(final, name), name)
-
-    def test_query_and_selection_do_not_call_final_adapter(self):
-        self.assertNotIn("coordinate:ita-native-final-once", final.CALENDAR_GUARD_SCRIPT)
-        self.assertIn("coordinate:ita-native-final-once", NATIVE_FINAL_SCRIPT)
+        self.fetch.assert_called_once_with(self.page, "POST", ita.FINAL_PATH, timeout=30, data={
+            "idCalendarioGiornaliero": "12345678",
+            "selectedDay": "2026-10-02", "selectedHour": "10:05 - 11:05\n(1)",
+        })
+        self.verify.assert_called_once_with(self.page, runtime_service="4937", candidate=self.slot)
+        self.plugin._require_calendar_context.assert_called_once_with(
+            self.route, role="book", username="applicant@example.test")
+
+    def test_site_rejection_returns_false_and_discards_selection(self):
+        self.respond(body=json.dumps({"errorMessage": "No longer available", "url": "/BookingCalendar"}))
+        self.assertFalse(self.submit().success)
+        self.fetch.assert_called_once()
+        self.plugin._reset_calendar_state.assert_called_once()
+
+    def test_http_errors_keep_framework_categories_without_internal_retry(self):
+        for status, error in ((401, ita.SessionExpiredOrInvalidError),
+                              (403, ita.PermissionDeniedError), (404, ita.NotFoundError),
+                              (429, ita.RateLimiteddError), (0, ita.BizLogicError),
+                              (408, ita.BizLogicError), (500, ita.BizLogicError),
+                              (502, ita.BizLogicError), (503, ita.BizLogicError),
+                              (504, ita.BizLogicError)):
+            with self.subTest(status=status):
+                self.fetch.reset_mock()
+                self.plugin._reset_calendar_state.reset_mock()
+                self.respond(status=status)
+                with self.assertRaises(error):
+                    self.submit()
+                self.fetch.assert_called_once()
+                self.plugin._reset_calendar_state.assert_called_once()
+
+    def test_followed_iam_redirect_is_session_expiry(self):
+        self.respond(url="https://iam.esteri.it/signin/", body="<html>Login</html>")
+        with self.assertRaises(ita.SessionExpiredOrInvalidError):
+            self.submit()
+        self.plugin._reset_calendar_state.assert_called_once()
+
+    def test_network_exception_does_not_repost_or_keep_stale_ids(self):
+        self.fetch.side_effect = TimeoutError("synthetic timeout")
+        with self.assertRaises(ita.BizLogicError) as caught:
+            self.submit()
+        self.assertIsInstance(caught.exception.__cause__, TimeoutError)
+        self.fetch.assert_called_once()
+        self.plugin._reset_calendar_state.assert_called_once()
+
+    def test_existing_framework_exception_is_not_wrapped(self):
+        for error_type in (ita.SessionExpiredOrInvalidError, ita.PermissionDeniedError,
+                           ita.NotFoundError, ita.RateLimiteddError, ita.BizLogicError):
+            with self.subTest(error_type=error_type):
+                error = error_type("synthetic")
+                self.fetch.side_effect = error
+                with self.assertRaises(error_type) as caught:
+                    self.submit()
+                self.assertIs(caught.exception, error)
+
+    def test_malformed_or_incomplete_response_is_not_success(self):
+        for body in ("not json", "<html>error</html>", "null", "[]", "{}",
+                     '{"url":"/Reservation"}', '{"errorMessage":null,"url":"/Reservation"}',
+                     '{"errorMessage":false,"url":"/Reservation"}',
+                     '{"errorMessage":""}', '{"errorMessage":"","url":false}'):
+            with self.subTest(body=body):
+                self.fetch.reset_mock()
+                self.respond(body=body)
+                with self.assertRaises(ita.BizLogicError):
+                    self.submit()
+                self.fetch.assert_called_once()
+
+    def test_error_or_auth_pages_are_not_receipts(self):
+        for destination in ("", " ", "/", "/UserArea", "/Services", "/BookingCalendar",
+                            "/Error", "/ReservationDetail/Index/", "/Reservation/other",
+                            "https://attacker.test/Reservation", "//attacker.test/Reservation",
+                            "http://prenotami.esteri.it/Reservation",
+                            "https://prenotami.esteri.it:8443/Reservation",
+                            "https://user@prenotami.esteri.it/Reservation"):
+            with self.subTest(destination=destination):
+                self.respond(body=json.dumps({"errorMessage": "", "url": destination}))
+                with self.assertRaises(ita.BizLogicError):
+                    self.submit()
+
+    def test_known_receipt_paths_accept_relative_and_absolute_urls(self):
+        # Repository contract fixtures, not evidence of a live successful booking.
+        for destination in ("/Reservation", "/Reservation/",
+                            "https://prenotami.esteri.it/Reservation",
+                            "/ReservationDetail/Index/synthetic-receipt"):
+            with self.subTest(destination=destination):
+                self.respond(body=json.dumps({"errorMessage": "", "url": destination}))
+                self.assertTrue(self.submit().success)
+
+    def test_foreign_or_wrong_final_response_endpoint_is_rejected(self):
+        for url in ("https://attacker.test" + ita.FINAL_PATH,
+                    "https://prenotami.esteri.it/Reservation"):
+            with self.subTest(url=url):
+                self.respond(url=url)
+                with self.assertRaises(ita.BizLogicError):
+                    self.submit()
+
+    def test_changed_session_stops_before_post(self):
+        self.plugin._require_calendar_context.side_effect = ita.SessionExpiredOrInvalidError()
+        with self.assertRaises(ita.SessionExpiredOrInvalidError):
+            self.submit()
+        self.fetch.assert_not_called()
+        self.plugin._reset_calendar_state.assert_called_once()
+
+    def test_changed_tab_or_slot_stops_before_post(self):
+        self.page.tab_id = "different-tab"
+        with self.assertRaises(ita.BizLogicError):
+            self.submit()
+        self.fetch.assert_not_called()
+        self.page.tab_id = "applicant-tab"
+        self.verify.side_effect = ita.BizLogicError("Selection changed")
+        with self.assertRaises(ita.BizLogicError):
+            self.submit()
+        self.fetch.assert_not_called()
 
 
 if __name__ == "__main__":

+ 0 - 614
test/ita/test_ita_calendar_book.py

@@ -1,614 +0,0 @@
-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_plugin as book_calendar
-
-from plugins.ita_plugin import (
-    RUNTIME_SERVICE_SCRIPT,
-    SLOT_SELECTION_SCRIPT,
-    TIME_SLOTS_PATH,
-    CalendarBookError,
-    parse_book_time_slots,
-    select_slot_before_final,
-)
-from plugins.ita_plugin import AVAILABILITY_PATH, CALENDAR_GUARD_SCRIPT
-from test.ita.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 = {
-            "contextReady": service == self.service,
-            "candidateCount": 1,
-            "candidateReady": True,
-            "selected": self.active,
-            "clicked": click and self.click_ack,
-        }
-        raw.update(self.overrides)
-        if self.clicks:
-            raw.update(self.after_overrides)
-        return raw
-
-
-def select(page, pair=None):
-    availability, times = pair or packets()
-    service = SERVICE  # The caller's service binding at inventory capture time.
-    return select_slot_before_final(
-        page, target_day=DAY, runtime_service=service,
-        probe=book_calendar.parse_availability_packet(availability),
-        slots=book_calendar.parse_book_time_slots(times, target_day=DAY, runtime_service_id=service),
-    )
-
-
-class PrecommitReadbackTests(unittest.TestCase):
-    """Migrate the old pure-state checks to the actual read-only browser boundary."""
-
-    def setUp(self):
-        self.page = FakePage()
-        self.page.active = True
-        self.day = book_calendar.parse_calendar_availability(
-            double_json([availability_item("09/10/2026 00:00:00", 1, 0)])
-        )[0]
-        self.negative_candidate, self.candidate = book_calendar.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),
-        ]))
-
-    def readback(self, *, calendar_day=None, candidate=None):
-        approval = book_calendar.PrecommitApproval(calendar_day or self.day, candidate or self.candidate)
-        return book_calendar.verify_precommit_selection(
-            self.page, runtime_service=SERVICE, approval=approval,
-        )
-
-    def reject(self, **kwargs):
-        with self.assertRaises(CalendarBookError):
-            self.readback(**kwargs)
-        self.assertEqual(self.page.clicks, 0)
-
-    def test_e44_positive_selection_approves_precommit(self):
-        approval = self.readback()
-        self.assertIs(approval.calendar_day, self.day)
-        self.assertIs(approval.candidate, self.candidate)
-        self.assertNotIn(self.candidate.daily_calendar_id, repr(approval))
-        self.assertEqual(self.page.clicks, 0)
-
-    def test_readback_rejects_wrong_types_and_extra_fields(self):
-        for mutation in (
-            {"candidateCount": True}, {"candidateCount": 1.0},
-            {"contextReady": 1}, {"candidateReady": 1}, {"selected": 1},
-            {"clicked": 0}, {"extra": "unexpected"},
-        ):
-            with self.subTest(mutation=mutation):
-                self.page.overrides = mutation
-                self.reject()
-
-    def test_rejects_every_unsafe_control_semantic(self):
-        for mutation in (
-            {"contextReady": False}, {"candidateCount": 0}, {"candidateCount": 2},
-            {"candidateReady": False}, {"selected": False}, {"clicked": True},
-        ):
-            with self.subTest(mutation=mutation):
-                self.page.overrides = mutation
-                self.reject()
-
-    def test_rejects_negative_candidate_even_if_dom_marks_it_active(self):
-        self.reject(candidate=self.negative_candidate)
-
-    def test_rejects_negative_calendar_day(self):
-        negative = book_calendar.parse_calendar_availability(
-            double_json([availability_item("09/10/2026 00:00:00", 0, -1)])
-        )[0]
-        self.reject(calendar_day=negative)
-
-    def test_calendar_and_slot_must_belong_to_the_same_day(self):
-        other = book_calendar.parse_calendar_availability(
-            double_json([availability_item("10/10/2026 00:00:00", 1, 0)])
-        )[0]
-        self.reject(calendar_day=other)
-
-
-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_uses_earliest_time_even_if_later_slots_have_more_capacity(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, "09:00 - 10:00")
-        self.assertEqual(page.last_candidate, ("80001002", "09:00 - 10:00", 1))
-
-    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 = [
-            {"contextReady": False}, {"candidateCount": 2},
-            {"candidateReady": False}, {"clicked": True},
-            {"candidateCount": True}, {"candidateReady": 1},
-            {"extra": "unexpected"},
-        ]
-        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 = [
-            {"contextReady": False}, {"candidateCount": 2},
-            {"candidateReady": False}, {"selected": 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()
-                with self.assertRaises(CalendarBookError):
-                    select_slot_before_final(page, target_day=target, probe=None, slots=(), runtime_service=SERVICE)
-                self.assertEqual(page.events, [])
-
-    def test_adapter_has_no_query_tool_network_or_final_action(self):
-        from test.ita.ita_source_sections import section
-        source = section("calendar_book")
-        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"]["selected"])
-
-    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"]["selected"])
-
-    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"]["contextReady"])
-        self.assertFalse(result["after"]["selected"])
-        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"]["contextReady"])
-        self.assertEqual(result["finalClicks"], 0)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 949
test/ita/test_ita_calendar_book_flow.py

@@ -1,949 +0,0 @@
-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_plugin as book_calendar
-from plugins.ita_plugin import (
-    DATE_SELECTION_SCRIPT, SLOT_SELECTION_SCRIPT, TIME_SLOTS_PATH,
-    CalendarBookError, book_date_preferences, recheck_calendar_before_final,
-)
-from plugins.ita_plugin import AVAILABILITY_PATH, CalendarNextMonthUnavailableError
-from plugins.ita_plugin import (
-    BOOKING_CALENDAR_PREFINAL_STOP_LABEL, BOOKING_RECHECK_NONE_AVAILABLE_LABEL, ItaPlugin,
-)
-from test.ita.test_ita_calendar_book import FakePage, SERVICE, packet
-from test.ita import test_ita_plugin as plugin_fixtures
-from test.ita.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
-            context = self.date_runtime_matches and service == self.service
-            ready = context and count == 1 and self.date_enabled
-            clicked = bool(click and self.date_ack and ready and not selected)
-            raw = {"contextReady": context, "candidateCount": count,
-                   "candidateReady": ready, "selected": context and count == 1 and 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["contextReady"] = raw["contextReady"] and day == self.selected_day == self.content_day
-            raw["candidateCount"] = len(matching)
-            raw["candidateReady"] = (raw["contextReady"] and len(matching) == 1
-                                     and matching[0]["SlotLiberi"] == free)
-            raw["selected"] = raw["candidateReady"] and self.active
-            raw.update(self.after_overrides if self.clicks else {})
-        return raw
-
-
-@contextmanager
-def browser_navigation(page):
-    original_click = book_calendar.click_next_month
-    # Query and Book now share this function's module. Only intercept the
-    # synthetic Book page; concurrent Query keeps its own native adapter.
-    with patch.object(book_calendar, "click_next_month", side_effect=lambda actual:
-                      page.next_month() if actual is page else original_click(actual)), \
-            patch.object(book_calendar.time, "sleep"):
-        yield
-
-
-def book_with_approval(plugin, trigger, inputs, *, call=None):
-    captured = []
-    original = book_calendar.recheck_calendar_before_final
-
-    def observe(*args, **kwargs):
-        approval = original(*args, **kwargs)
-        captured.append(approval)
-        return approval
-
-    with patch.object(book_calendar, "recheck_calendar_before_final", side_effect=observe):
-        result = (call or plugin.book)(trigger, inputs)
-    return result, captured[0] if captured else None
-
-
-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_each_captured_inventory_response_is_parsed_once(self):
-        for inventory in ({13: 1}, {1: 0, 13: 1}):
-            with self.subTest(inventory=inventory):
-                page = FlowPage([month("2026-10", inventory)])
-                with patch.object(book_calendar, "parse_availability_packet",
-                                  wraps=book_calendar.parse_availability_packet) as availability_parser, \
-                        patch.object(book_calendar, "parse_book_time_slots",
-                                     wraps=book_calendar.parse_book_time_slots) as slots_parser:
-                    self.assertIsNotNone(run_flow(page))
-                self.assertEqual(availability_parser.call_count,
-                                 sum(p.url.endswith(AVAILABILITY_PATH) for p in page.requests))
-                self.assertEqual(slots_parser.call_count,
-                                 sum(p.url.endswith(TIME_SLOTS_PATH) for p in page.requests))
-                self.assertEqual(page.clicks, 1)
-                self.assert_stopped(page)
-
-    def test_candidate_is_filtered_once_while_waiting_for_delayed_dom(self):
-        page = FlowPage()
-        original = page.run_js
-        slot_reads = []
-        clock = [0.0]
-
-        def delayed(script, *args):
-            raw = original(script, *args)
-            if script == SLOT_SELECTION_SCRIPT:
-                slot_reads.append(args[-1])
-                if len(slot_reads) <= 2:
-                    raw.update(candidateReady=False, candidateCount=0)
-            return raw
-
-        page.run_js = delayed
-        with browser_navigation(page), \
-                patch.object(book_calendar.time, "monotonic", side_effect=lambda: clock[0]), \
-                patch.object(book_calendar.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)), \
-                patch.object(book_calendar, "available_slot_candidates", wraps=book_calendar.available_slot_candidates) as select_candidates:
-            result = recheck_calendar_before_final(
-                page, lookahead_months=1, start_day=date(2026, 10, 1), end_day=date(2026, 10, 31),
-                session_is_current=lambda: True, dom_timeout=0.5,
-            )
-        self.assertIsNotNone(result)
-        self.assertEqual(select_candidates.call_count, 1)
-        self.assertEqual(slot_reads, [False, False, False, True, False])
-        self.assertEqual(page.clicks, 1)
-        self.assertEqual(page.refreshes, 1)
-        self.assertEqual(len(page.requests), 2)
-        self.assert_stopped(page)
-
-    def test_delayed_slot_timeout_is_bounded_without_extra_request_or_click(self):
-        page = FlowPage()
-        original = page.run_js
-        clock = [0.0]
-
-        def missing_slot(script, *args):
-            raw = original(script, *args)
-            if script == SLOT_SELECTION_SCRIPT:
-                raw.update(candidateReady=False, candidateCount=0)
-            return raw
-
-        page.run_js = missing_slot
-        with browser_navigation(page), \
-                patch.object(book_calendar.time, "monotonic", side_effect=lambda: clock[0]), \
-                patch.object(book_calendar.time, "sleep", side_effect=lambda delay: clock.__setitem__(0, clock[0] + delay)), \
-                self.assertRaisesRegex(CalendarBookError, "slot DOM did not match"):
-            recheck_calendar_before_final(
-                page, lookahead_months=1, start_day=date(2026, 10, 1), end_day=date(2026, 10, 31),
-                session_is_current=lambda: True, dom_timeout=0.25,
-            )
-        self.assertAlmostEqual(clock[0], 0.25)
-        self.assertEqual(page.clicks, 0)
-        self.assertEqual(page.refreshes, 1)
-        self.assertEqual(len(page.requests), 2)
-        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_scans_applicant_inventory_once_in_chronological_order(self):
-        page = FlowPage([month("2026-09", {9: 2}), month("2026-10", {13: 1})])
-        result = run_flow(page)
-        self.assertEqual(result.candidate.day, date(2026, 9, 9))
-        self.assertEqual(page.refreshes, 1)
-        self.assertEqual(page.month_clicks, 0)
-
-    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_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 = {"selected": 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)},
-                       {"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.user_data_path = "/nonexistent/ita-book-flow-test"
-    plugin._reset_calendar_state()
-    route = plugin._resolve_route(AppointmentType(routing_key=routing_key))
-    plugin._record_calendar_prepared_route(route, role="book")
-    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_query_and_book_share_month_reader_but_not_account_inventory(self):
-        from test.ita.test_debug_ita_production_query_gate import FakeProductionPage, make_plugin
-
-        query_page = FakeProductionPage([[(2026, 9, ()), (2026, 10, (13,))]])
-        query, query_route = make_plugin(query_page)
-        query.free_config["query_mode"] = "calendar"
-        book_page = FlowPage([month("2026-10", {13: 0, 14: 1})])
-        applicant, _, _ = prepared_plugin(book_page, routing_key=query_route.routing_key)
-        with browser_navigation(book_page), patch.object(
-            book_calendar, "_capture_month", wraps=book_calendar._capture_month
-        ) as capture:
-            signal = query.query(query_route.appointment_type())
-            result, approval = book_with_approval(
-                applicant, signal, {"username": "applicant@example.test"},
-            )
-
-        self.assertTrue(signal.success)
-        self.assertEqual(signal.earliest_date, datetime(2026, 10, 13))
-        self.assertFalse(result.success)  # Pre-final selection is not a booking.
-        self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
-        self.assertEqual(approval.candidate.day, date(2026, 10, 14))
-        self.assertNotEqual(query.config.account.username, applicant.config.account.username)
-        self.assertEqual([call.args[0] for call in capture.call_args_list],
-                         [query_page, query_page, book_page])
-        self.assertTrue(all(call.kwargs.get("service") is None for call in capture.call_args_list[:2]))
-        self.assertEqual(capture.call_args_list[2].kwargs["service"], SERVICE)
-        self.assertEqual(query_page.final_requests, 0)
-        self.assertEqual(book_page.guard_final_count, 0)
-        self.assertEqual(book_page.clicks, 1)
-        self.assertEqual(query_page.listen.stops, len(query_page.listen.starts))
-        self.assertEqual(book_page.listen.stops, book_page.listen.starts)
-        applicant.query.assert_not_called()
-
-    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, approval = book_with_approval(plugin, 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(approval.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_signal_date_does_not_override_earlier_applicant_inventory(self):
-        page = FlowPage([month("2026-09", {1: 1}), month("2026-10", {13: 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, approval = book_with_approval(
-                plugin, trigger, {"username": "applicant@example.test"},
-            )
-        self.assertEqual(result.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
-        self.assertEqual(approval.candidate.day, date(2026, 9, 1))
-        self.assertEqual(approval.candidate.time_label, "10:05 - 11:05")
-        self.assertEqual(page.refreshes, 1)
-        self.assertEqual(page.month_clicks, 0)
-
-    def test_query_preparation_cannot_be_converted_into_book_preparation(self):
-        page = FlowPage()
-        plugin, route, trigger = prepared_plugin(page)
-        plugin._reset_calendar_state()
-        plugin._record_calendar_prepared_route(route, role="query")
-        with self.assertRaises(BizLogicError):
-            plugin._record_calendar_prepared_route(route, role="book")
-        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_state()
-        plugin._enter_service = Mock(side_effect=BizLogicError("fresh preparation required"))
-        with self.assertRaises(BizLogicError):
-            plugin.book(trigger, {"username": "applicant@example.test"})
-        plugin._enter_service.assert_called_once()
-        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_page_is_rejected(self):
-        first, _, _ = prepared_plugin(FlowPage())
-        second, _, trigger = prepared_plugin(FlowPage())
-        second._prepared_calendar = first._prepared_calendar
-        with self.assertRaises(BizLogicError):
-            second.book(trigger, {"username": "applicant@example.test"})
-
-    def test_second_book_call_rechecks_current_inventory(self):
-        page = FlowPage()
-        plugin, _, trigger = prepared_plugin(page)
-        with browser_navigation(page):
-            first, first_approval = book_with_approval(
-                plugin, trigger, {"username": "applicant@example.test"},
-            )
-            second, second_approval = book_with_approval(
-                plugin, trigger, {"username": "applicant@example.test"},
-            )
-        self.assertEqual(first.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
-        self.assertEqual(second.label, BOOKING_CALENDAR_PREFINAL_STOP_LABEL)
-        self.assertEqual(first_approval.candidate.day, second_approval.candidate.day)
-        self.assertEqual(first_approval.candidate.time_label, second_approval.candidate.time_label)
-        self.assertEqual(page.refreshes, 2)
-        self.assertEqual(page.clicks, 2)
-
-    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, approval = book_with_approval(
-                plugin, 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(approval)
-
-    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._prepared_calendar)
-        self.assertEqual(page.clicks, 0)
-
-    def test_account_change_during_candidate_dom_read_blocks_the_click(self):
-        page = FlowPage()
-        plugin, _, trigger = prepared_plugin(page)
-        original = page.run_js
-
-        def changed_account(script, *args):
-            raw = original(script, *args)
-            if script == SLOT_SELECTION_SCRIPT and args[-1] is False:
-                plugin.config.account.username = "other@example.test"
-            return raw
-
-        page.run_js = changed_account
-        with browser_navigation(page), self.assertRaises(BizLogicError):
-            plugin.book(trigger, {"username": "applicant@example.test"})
-        self.assertIsNone(plugin._prepared_calendar)
-        self.assertEqual(page.clicks, 0)
-        self.assertEqual(page.date_clicks, [])
-
-    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.init_chromium_options", side_effect=RuntimeError("offline stop")):
-                        with self.assertRaises(RuntimeError):
-                            plugin.create_session()
-                else:
-                    plugin.cleanup()
-                self.assertIsNone(plugin._prepared_calendar)
-                self.assertFalse(hasattr(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._prepared_calendar)
-                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._prepared_calendar)
-
-    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.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"]["selected"])
-        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"]["selected"])
-
-    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"]["candidateReady"])
-                self.assertEqual(result["clicks"], 1)
-                self.assertTrue(result["after"]["selected"])
-                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"]["selected"])
-        self.assertFalse(result["before"]["candidateReady"])
-        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()

+ 187 - 264
test/ita/test_ita_calendar_query.py

@@ -1,270 +1,193 @@
-import json
-import shutil
-import subprocess
+"""Query uses current browser-fetch and public plugin contracts; no live I/O."""
 import unittest
+from datetime import date
+from types import SimpleNamespace
 from unittest.mock import Mock, patch
 
-from plugins.ita_plugin import (
-    CalendarGateError,
-    CalendarNextMonthUnavailableError,
-    CalendarProbeResult,
-    NEXT_MONTH_CONTROL_SCRIPT,
-    scan_until_first_available_month,
-)
-from plugins.ita_plugin import parse_calendar_availability
-
-
-MONTH_CONTROL_HARNESS = r"""
-const vm = require('node:vm');
-const {source, mode} = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
-let clicks = 0;
-const node = {
-  isConnected: mode !== 'detached',
-  hasAttribute: name => name === 'disabled' && mode === 'disabled',
-  getAttribute: name => name === 'aria-disabled' && mode === 'aria_disabled' ? 'true' : null,
-  getBoundingClientRect: () => ({left: 20, right: mode === 'zero_size' ? 20 : 100,
-                                top: mode === 'offscreen' ? 2000 : 20, bottom: 100}),
-  contains: item => item === node,
-  click: () => clicks++,
-};
-const document = {
-  querySelectorAll: selector => {
-    if (selector !== '#datetimepicker th.dtpicker-next') throw Error('Unexpected selector');
-    return mode === 'missing' ? [] : mode === 'duplicate' ? [node, node] : [node];
-  },
-  elementFromPoint: () => mode === 'occluded' ? {} : node,
-};
-const window = {
-  location: {origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it',
-             pathname: mode === 'wrong_path' ? '/UserArea' : '/BookingCalendar'},
-  innerWidth: 1000, innerHeight: 800,
-  getComputedStyle: () => ({display: mode === 'hidden' ? 'none' : 'block',
-    visibility: mode === 'invisible' ? 'hidden' : 'visible',
-    pointerEvents: mode === 'pointer_blocked' ? 'none' : 'auto', opacity: mode === 'transparent' ? '0' : '1'}),
-};
-const run = click => vm.runInNewContext('(function(){' + source + '\n}).apply(null, args)',
-  {document, window, args: [click]}, {timeout: 1000});
-const before = run(false), acted = run(true);
-process.stdout.write(JSON.stringify({before, acted, clicks}));
-"""
-
-
-@unittest.skipUnless(shutil.which("node"), "Node is required for actual Calendar-control scripts")
-class MonthControlJavaScriptTests(unittest.TestCase):
-    def run_case(self, mode):
-        result = subprocess.run(
-            [shutil.which("node"), "-e", MONTH_CONTROL_HARNESS],
-            input=json.dumps({"source": NEXT_MONTH_CONTROL_SCRIPT, "mode": mode}),
-            text=True, capture_output=True, timeout=10, check=True,
-        )
-        return json.loads(result.stdout)
-
-    def test_shared_control_check_only_clicks_the_ready_month_control(self):
-        result = self.run_case("ready")
-        self.assertFalse(result["before"]["clicked"])
-        self.assertEqual(result["before"]["actionableCount"], 1)
-        self.assertTrue(result["acted"]["clicked"])
-        self.assertEqual(result["clicks"], 1)
-
-    def test_hidden_disabled_covered_duplicate_or_foreign_controls_are_not_clicked(self):
-        for mode in ("detached", "disabled", "aria_disabled", "zero_size", "offscreen", "occluded",
-                     "missing", "duplicate", "hidden", "invisible", "pointer_blocked", "transparent",
-                     "wrong_origin", "wrong_path"):
-            with self.subTest(mode=mode):
-                result = self.run_case(mode)
-                self.assertFalse(result["acted"]["clicked"])
-                self.assertEqual(result["clicks"], 0)
-
-
-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_selected_month_preserves_both_observed_date_formats(self):
-        for selected_day in ("01/09/2026", "2026-09-01", " 01/09/2026 00:00:00 "):
-            with self.subTest(selected_day=selected_day):
-                result = CalendarProbeResult(days=(), selected_day=selected_day)
-                self.assertEqual(result.selected_month, (2026, 9))
-        for selected_day in ("not-a-date", "2026-13-01"):
-            with self.subTest(selected_day=selected_day), self.assertRaises(CalendarGateError):
-                CalendarProbeResult(days=(), selected_day=selected_day)
-
-    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_plugin._capture_month", side_effect=[august]) as capture:
-            result = scan_until_first_available_month(
-                Mock(),
-                lookahead_months=12,
-                month_click_interval_seconds=0,
-            )
-
-        capture.assert_called_once()
-        self.assertEqual(len(result), 1)
-        self.assertEqual(
-            result[-1].available_days[0].day.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_plugin._capture_month",
-            side_effect=[august, september, october, november],
-        ) as capture:
-            result = scan_until_first_available_month(
-                Mock(),
-                lookahead_months=12,
-                log=log,
-                month_click_interval_seconds=0,
-            )
-
-        self.assertEqual(capture.call_count, 3)
-        self.assertEqual(len(result), 3)
-        self.assertEqual(
-            result[-1].available_days[0].day.isoformat(),
-            "2026-10-12",
-        )
-        self.assertEqual(
-            [item.day.isoformat() for item in result[-1].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_plugin._capture_month", side_effect=months) as capture:
-            result = scan_until_first_available_month(
-                Mock(),
-                lookahead_months=3,
-                month_click_interval_seconds=0,
-            )
-
-        self.assertEqual(capture.call_count, 3)
-        self.assertEqual(len(result), 3)
-        self.assertEqual(result[-1].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_plugin._capture_month", side_effect=[december, january]):
-            result = scan_until_first_available_month(
-                Mock(),
-                lookahead_months=2,
-                month_click_interval_seconds=0,
-            )
-
-        self.assertEqual(
-            result[-1].available_days[0].day.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_plugin._capture_month", side_effect=[august, 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_plugin._capture_month",
-            side_effect=[august, 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,
-                    )
-
-    def test_invalid_scan_interval_never_touches_the_browser(self):
-        for value in (True, None, "1", -1, float("nan"), float("inf")):
-            with self.subTest(value=value):
-                page = Mock()
-                with self.assertRaisesRegex(CalendarGateError, "interval"):
-                    scan_until_first_available_month(
-                        page, lookahead_months=3, month_click_interval_seconds=value
-                    )
-                self.assertEqual(page.mock_calls, [])
+from plugins import ita_plugin as ita
+from test.ita.test_ita_compact import Response, day, encoded, route_config
+from vs_types import AppointmentType, AvailabilityStatus, VSAccount, VSPlgConfig
+
+
+class CalendarQueryTests(unittest.TestCase):
+    def setUp(self):
+        self.context = {"path": ita.CALENDAR_PATH, "service": "7002", "day": "2026-08-31"}
+        self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar",
+                                    tab_id="query-tab", run_js=Mock(side_effect=self.dom))
+        self.months = {}
+        self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch", side_effect=self.response))
+        self.sleep = self.enterContext(patch.object(ita.time, "sleep"))
+
+    def dom(self, script, *args):
+        if script == "return 1;":
+            return 1
+        self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
+        self.assertEqual(args[0], "context")
+        return dict(self.context)
+
+    def response(self, page, method, path, **kwargs):
+        self.assertIs(page, self.page)
+        self.assertEqual((method, path), ("POST", ita.AVAILABILITY_PATH))
+        payload = kwargs["json_data"]
+        self.assertEqual(payload["_Servizio"], self.context["service"])
+        self.assertEqual(set(payload), {"_Servizio", "selectedDay"})
+        return Response(200, encoded(self.months.get(payload["selectedDay"], [])),
+                        "https://prenotami.esteri.it" + path)
+
+    def scan(self, count=12):
+        return ita.scan_until_first_available_month(self.page, lookahead_months=count,
+                                                    month_click_interval_seconds=0)
+
+    def requested_months(self):
+        return [call.kwargs["json_data"]["selectedDay"] for call in self.fetch.call_args_list]
+
+    def plugin(self, *, service=7002, horizon=12):
+        plugin = object.__new__(ita.ItaPlugin)
+        config = route_config(service)
+        config["calendar_scan"]["lookahead_months"] = horizon
+        plugin.config = VSPlgConfig(account=VSAccount(username="pool@example.test", password="fixture"),
+            session_max_life=0, free_config={"query_mode": "calendar", "otp_mode": "cloud",
+                                           "apt_configs": {"route": config}})
+        plugin.free_config = plugin.config.free_config
+        plugin.page, plugin.is_healthy = self.page, True
+        plugin._log = Mock()
+        plugin._prepared_calendar = None
+        route = plugin._resolve_route(AppointmentType(routing_key="route"))
+        plugin._record_calendar_prepared_route(route, role="query")
+        return plugin
+
+    def test_initial_positive_month_stops_and_sorts_last_slot_correctly(self):
+        self.months["01/08/2026"] = [day("20/08/2026 00:00:00", 8, 7), day("12/08/2026 00:00:00")]
+        scans = self.scan()
+        self.assertEqual(self.requested_months(), ["01/08/2026"])
+        self.assertEqual([item.day for item in ita.available_calendar_days(scans[0])],
+                         [date(2026, 8, 12), date(2026, 8, 20)])
+
+    def test_sequential_months_stop_before_later_inventory(self):
+        self.months.update({"01/08/2026": [day("31/08/2026 00:00:00", 0, -1)],
+                           "01/10/2026": [day("20/10/2026 00:00:00", 8, 7),
+                                          day("12/10/2026 00:00:00")],
+                           "01/11/2026": [day("02/11/2026 00:00:00", 10, 9)]})
+        scans = self.scan()
+        self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"])
+        self.assertEqual(ita.available_calendar_days(scans[-1])[0].day, date(2026, 10, 12))
+
+    def test_empty_requires_complete_configured_horizon(self):
+        self.assertEqual(self.scan(3), ((), (), ()))
+        self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026", "01/10/2026"])
+
+    def test_cross_year_requests_exact_next_month(self):
+        self.context["day"] = "2026-12-20"
+        self.months["01/01/2027"] = [day("04/01/2027 00:00:00")]
+        self.assertEqual(ita.available_calendar_days(self.scan(2)[-1])[0].day, date(2027, 1, 4))
+        self.assertEqual(self.requested_months(), ["01/12/2026", "01/01/2027"])
+
+    def test_response_for_skipped_or_previous_month_is_not_availability(self):
+        for wrong_day in ("01/10/2026 00:00:00", "01/08/2026 00:00:00"):
+            with self.subTest(wrong_day=wrong_day):
+                self.fetch.reset_mock()
+                self.months["01/09/2026"] = [day(wrong_day)]
+                with self.assertRaisesRegex(ita.BizLogicError, "another month"):
+                    self.scan(3)
+                self.assertEqual(len(self.fetch.call_args_list), 2)
+
+    def test_wrong_month_is_rejected_even_when_all_its_days_are_sold_out(self):
+        self.months["01/08/2026"] = [day("01/09/2026 00:00:00", 0, -1)]
+        with self.assertRaisesRegex(ita.BizLogicError, "another month"):
+            self.scan()
+        self.fetch.assert_called_once()
+
+    def test_transport_failure_mid_horizon_is_not_no_availability(self):
+        self.fetch.side_effect = [self.response(self.page, "POST", ita.AVAILABILITY_PATH,
+            json_data={"_Servizio": "7002", "selectedDay": "01/08/2026"}),
+            ita.RateLimiteddError("synthetic rate limit")]
+        with self.assertRaises(ita.RateLimiteddError):
+            self.scan(3)
+        self.assertEqual(len(self.fetch.call_args_list), 2)
+
+    def test_html_or_malformed_json_is_not_an_empty_month(self):
+        for body in ("<html>unavailable</html>", "[]", '"not-json"'):
+            with self.subTest(body=body):
+                self.fetch.side_effect = None
+                self.fetch.return_value = Response(200, body, "https://prenotami.esteri.it" + ita.AVAILABILITY_PATH)
+                with self.assertRaises(ita.BizLogicError):
+                    self.scan()
+
+    def test_invalid_scan_horizons_never_make_network_requests(self):
+        for value in (True, 0, -1, 121):
+            with self.subTest(value=value), self.assertRaises(ita.ItaProtocolError):
+                self.scan(value)
+        self.fetch.assert_not_called()
+
+    def test_interval_applies_between_months_only(self):
+        ita.scan_until_first_available_month(self.page, lookahead_months=3, month_click_interval_seconds=1.5)
+        self.assertEqual([call.args for call in self.sleep.call_args_list], [(1.5,), (1.5,)])
+
+    def test_wrong_calendar_path_or_runtime_id_prevents_requests(self):
+        for service in ("", None, True, "0"):
+            with self.subTest(service=service), self.assertRaises(ita.BizLogicError):
+                self.context["service"] = service
+                self.scan()
+        self.page.url = "https://prenotami.esteri.it/UserArea"
+        with self.assertRaises(ita.BizLogicError):
+            self.scan()
+        self.fetch.assert_not_called()
+
+    def test_public_query_returns_earliest_date_without_slot_ids_or_times(self):
+        self.months["01/09/2026"] = [day("20/09/2026 00:00:00", 8, 7), day("12/09/2026 00:00:00")]
+        result = self.plugin().query(AppointmentType(routing_key="route"))
+        self.assertTrue(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.Available)
+        self.assertEqual(result.earliest_date.date(), date(2026, 9, 12))
+        self.assertEqual(len(result.availability), 1)
+        self.assertEqual(result.availability[0].times, [])
+        self.assertEqual(self.requested_months(), ["01/08/2026", "01/09/2026"])
+
+    def test_repeated_public_query_reuses_calendar_but_reads_fresh_inventory(self):
+        plugin = self.plugin()
+        self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
+        first = plugin.query(AppointmentType(routing_key="route"))
+        self.months["01/08/2026"] = []
+        self.months["01/09/2026"] = [day("12/09/2026 00:00:00")]
+        second = plugin.query(AppointmentType(routing_key="route"))
+        self.assertNotEqual(first.earliest_date, second.earliest_date)
+        self.assertEqual(self.requested_months(), ["01/08/2026", "01/08/2026", "01/09/2026"])
+
+    def test_public_query_empty_horizon_returns_false_not_success(self):
+        result = self.plugin(horizon=3).query(AppointmentType(routing_key="route"))
+        self.assertFalse(result.success)
+        self.assertEqual(result.availability_status, AvailabilityStatus.NoneAvailable)
+        self.assertEqual(len(self.fetch.call_args_list), 3)
+
+    def test_region_uses_its_own_runtime_service(self):
+        self.context["service"] = "9012"
+        self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
+        result = self.plugin(service=9012).query(AppointmentType(routing_key="route"))
+        self.assertTrue(result.success)
+        self.assertEqual(self.fetch.call_args.kwargs["json_data"]["_Servizio"], "9012")
+
+    def test_identity_drift_during_request_never_publishes_a_result(self):
+        self.months["01/08/2026"] = [day("31/08/2026 00:00:00")]
+        for drift in ("account", "tab", "service", "unhealthy"):
+            with self.subTest(drift=drift):
+                self.context["service"], self.page.tab_id = "7002", "query-tab"
+                plugin = self.plugin()
+                self.fetch.reset_mock()
+                def response(*args, **kwargs):
+                    reply = self.response(*args, **kwargs)
+                    if drift == "account":
+                        plugin.config.account.username = "other@example.test"
+                    elif drift == "tab":
+                        self.page.tab_id = "other-tab"
+                    elif drift == "service":
+                        self.context["service"] = "9012"
+                    else:
+                        plugin.is_healthy = False
+                    return reply
+                self.fetch.side_effect = response
+                with self.assertRaises(ita.BizLogicError):
+                    plugin.query(AppointmentType(routing_key="route"))
+                self.fetch.assert_called_once()
 
 
 if __name__ == "__main__":

+ 0 - 446
test/ita/test_ita_calendar_soak.py

@@ -1,446 +0,0 @@
-"""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 dataclasses import fields, replace
-from pathlib import Path
-from unittest.mock import Mock, patch
-
-from DrissionPage.errors import BrowserConnectError
-
-from plugins.ita_plugin import ItaPlugin
-from test.ita.test_debug_ita_production_query_gate import gate_env
-from test.ita.test_debug_ita_soak import FakeClock
-from test.ita.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, checkpoint_mutator=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_plugin.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.user_data_path = str(profile)
-                plugin.free_config["persistent_browser_profile_path"] = str(profile)
-                plugin.tunnel = None
-                plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query")
-                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._reset_calendar_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._reset_calendar_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 checkpoint_mutator is not None:
-                checkpoint_mutator(context, initial, route)
-            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_soak_checkpoint_is_local_and_contains_no_credentials_or_inventory(self):
-        def inspect(context, plugin, _route):
-            self.assertEqual(
-                {item.name for item in fields(context.checkpoint)},
-                {"route", "username", "profile_path", "calendar_url", "runtime_service"},
-            )
-            body = repr(context.checkpoint)
-            self.assertNotIn(plugin.config.account.username, body)
-            self.assertNotIn(plugin.config.account.password, body)
-            self.assertNotIn("earliest", body.lower())
-            self.assertNotIn("slot", body.lower())
-
-        result = self.run_case(restart=1, checkpoint_mutator=inspect)
-        self.assertEqual(result.code, 0, result.output)
-        self.assertEqual(result.report["restores"], 1)
-
-    def test_soak_restore_rejects_changed_owner_profile_or_route_before_navigation(self):
-        def mutate(field_name):
-            def apply(context, _plugin, _route):
-                checkpoint = context.checkpoint
-                if field_name == "username":
-                    context.checkpoint = replace(checkpoint, username="other@example.test")
-                elif field_name == "profile":
-                    context.checkpoint = replace(checkpoint, profile_path="/offline/other-profile")
-                else:
-                    context.checkpoint = replace(
-                        checkpoint, route=replace(checkpoint.route, service_id=9002),
-                    )
-            return apply
-
-        for field_name in ("username", "profile", "route"):
-            with self.subTest(field=field_name):
-                result = self.run_case(restart=1, checkpoint_mutator=mutate(field_name))
-                self.assertNotEqual(result.code, 0, result.output)
-                self.assertEqual(result.pages[1].get_calls, [])
-                self.assertEqual(result.report["restores"], 0)
-
-    def test_soak_restore_rejects_foreign_or_unobserved_calendar_url_before_navigation(self):
-        for calendar_url in (
-            "https://foreign.example/BookingCalendar",
-            "https://prenotami.esteri.it/BookingCalendar?unknown=1",
-        ):
-            def mutate(context, _plugin, _route, value=calendar_url):
-                context.checkpoint = replace(context.checkpoint, calendar_url=value)
-
-            with self.subTest(calendar_url=calendar_url):
-                result = self.run_case(restart=1, checkpoint_mutator=mutate)
-                self.assertNotEqual(result.code, 0, result.output)
-                self.assertEqual(result.pages[1].get_calls, [])
-                self.assertEqual(result.report["restores"], 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.ita 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()

+ 127 - 10
test/ita/test_ita_compact.py

@@ -104,10 +104,11 @@ class CompactCalendarTests(unittest.TestCase):
         })
 
     def test_calendar_status_mapping(self):
-        cases = ((401, ita.CalendarAuthenticationExpiredError),
-                 (403, ita.CalendarAccessDeniedError),
-                 (429, ita.CalendarRateLimitedError),
-                 (504, ita.CalendarTransientError))
+        cases = ((401, ita.SessionExpiredOrInvalidError),
+                 (403, ita.PermissionDeniedError),
+                 (404, ita.NotFoundError),
+                 (429, ita.RateLimiteddError),
+                 (504, ita.BizLogicError))
         for status, error in cases:
             with self.subTest(status=status), patch.object(
                     ita, "perform_browser_fetch", return_value=Response(
@@ -136,7 +137,7 @@ class CompactCalendarTests(unittest.TestCase):
     def test_service_mismatch_fails_instead_of_timing_out(self):
         with patch.object(ita, "read_calendar_context",
                           return_value=("9999", date(2026, 8, 1))):
-            with self.assertRaisesRegex(ita.CalendarBookError, "service changed"):
+            with self.assertRaisesRegex(ita.BizLogicError, "service changed"):
                 ita.wait_for_calendar_service(
                     unittest.mock.ANY, session_is_current=lambda: True,
                     expected_service=4937, timeout=0.1)
@@ -175,7 +176,7 @@ class CompactPreflightTests(unittest.TestCase):
         with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
              patch.object(ita.time, "sleep"), \
              patch.object(ita, "CloudflareBypasser") as factory, \
-             self.assertRaisesRegex(ita.CalendarGateError, "form_pending"):
+             self.assertRaisesRegex(ita.BizLogicError, "form_pending"):
             ita.wait_for_booking_preflight(page, script="offline")
         factory.assert_not_called()
 
@@ -184,7 +185,7 @@ class CompactPreflightTests(unittest.TestCase):
             otpSendEnabled=False)))
         with patch.object(ita.time, "monotonic", side_effect=[0, 0, 121]), \
              patch.object(ita.time, "sleep"), \
-             self.assertRaisesRegex(ita.CalendarGateError, "otp_send_disabled"):
+             self.assertRaisesRegex(ita.BizLogicError, "otp_send_disabled"):
             ita.wait_for_booking_preflight(page, script="offline")
 
     def test_after_otp_accepts_the_expected_send_button_cooldown(self):
@@ -230,17 +231,109 @@ class CompactFinalTests(unittest.TestCase):
         self.assertEqual(fetch.call_args.kwargs["data"]["idCalendarioGiornaliero"], "12345678")
         self.plugin._reset_calendar_state.assert_not_called()
 
-    def test_ambiguous_final_response_is_retryable_failure(self):
+    def test_ambiguous_final_response_raises_framework_business_error(self):
         response = Response(200, "{}",
                             "https://prenotami.esteri.it/BookingCalendar/InsertNewBooking")
         with patch.object(ita, "verify_precommit_selection"), \
              patch.object(ita, "perform_browser_fetch", return_value=response) as fetch:
-            result = ita._submit_final_once(self.plugin, self.route, self.slot)
-        self.assertFalse(result.success)
+            with self.assertRaises(ita.BizLogicError):
+                ita._submit_final_once(self.plugin, self.route, self.slot)
         self.assertEqual(fetch.call_count, 1)
         self.plugin._reset_calendar_state.assert_called_once()
 
 
+class CalendarSelectionRegressionTests(unittest.TestCase):
+    def setUp(self):
+        self.day = date(2026, 10, 1)
+        self.candidate = ita.parse_time_slots(encoded([slot()]))[0]
+        self.days = ita.parse_calendar_availability(encoded([day()]))
+        self.selected, self.pending, self.clicks = False, 0, []
+        self.page = SimpleNamespace(url="https://prenotami.esteri.it/BookingCalendar",
+                                    run_js=Mock(side_effect=self.dom))
+        self.now = 0
+        self.enterContext(patch.object(ita.time, "monotonic", side_effect=lambda: self.now))
+        self.enterContext(patch.object(ita.time, "sleep", side_effect=self.advance))
+        self.fetch = self.enterContext(patch.object(ita, "perform_browser_fetch",
+            side_effect=AssertionError("Selection must not send business requests")))
+
+    def advance(self, seconds):
+        self.now += seconds
+
+    def dom(self, script, mode, service, selected_day, daily_id, label, capacity, click):
+        self.assertEqual(script, ita.CALENDAR_DOM_SCRIPT)
+        self.assertEqual((service, selected_day), ("4937", self.day.isoformat()))
+        count = 1
+        if mode == "slot":
+            self.assertEqual((daily_id, label, capacity),
+                             (self.candidate.daily_calendar_id, self.candidate.time_label, 1))
+            if self.pending:
+                self.pending -= 1
+                count = 0
+            if click:
+                self.assertEqual(count, 1)
+                self.clicks.append(mode)
+                self.selected = True
+        return {"contextReady": True, "candidateCount": count,
+                "candidateReady": count == 1, "selected": mode == "date" or self.selected,
+                "clicked": click and mode == "slot"}
+
+    def select(self, **kwargs):
+        return ita.select_slot_before_final(self.page, target_day=self.day, days=self.days,
+            slots=(self.candidate,), runtime_service="4937", dom_timeout=0.3, **kwargs)
+
+    def test_async_slots_are_waited_for_without_requery_or_extra_click(self):
+        self.pending = 2
+        self.assertEqual(self.select(), self.candidate)
+        self.assertEqual(self.clicks, ["slot"])
+        self.assertAlmostEqual(self.now, 0.2)
+        self.fetch.assert_not_called()
+
+    def test_missing_slots_timeout_without_click_or_submission(self):
+        self.pending = 100
+        with self.assertRaisesRegex(ita.BizLogicError, "did not finish loading"):
+            self.select()
+        self.assertEqual(self.clicks, [])
+        self.assertLessEqual(self.now, 0.4)
+        self.fetch.assert_not_called()
+
+    def test_changed_session_stops_before_the_first_date_action(self):
+        with self.assertRaises(ita.SessionExpiredOrInvalidError):
+            self.select(session_is_current=lambda: False)
+        self.page.run_js.assert_not_called()
+
+    def test_duplicate_slots_are_rejected_immediately(self):
+        self.page.run_js.side_effect = None
+        self.page.run_js.return_value = {"contextReady": True, "candidateCount": 2,
+            "candidateReady": True, "selected": True, "clicked": False}
+        with self.assertRaises(ita.BizLogicError):
+            self.select()
+        self.assertEqual(self.now, 0)
+
+    def test_readback_requires_real_boolean_and_integer_facts(self):
+        raw = {"contextReady": True, "candidateCount": 1, "candidateReady": True,
+               "selected": True, "clicked": False}
+        self.page.run_js.side_effect = None
+        for field, value in (("candidateCount", True), ("candidateCount", 1.0),
+                             ("contextReady", 1), ("candidateReady", "true"),
+                             ("selected", 1), ("clicked", 0)):
+            with self.subTest(field=field, value=value):
+                self.page.run_js.return_value = {**raw, field: value}
+                with self.assertRaises(ita.BizLogicError):
+                    ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
+
+    def test_readback_never_accepts_missing_or_negative_candidate(self):
+        self.selected = True
+        self.pending = 1
+        with self.assertRaises(ita.BizLogicError):
+            ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=self.candidate)
+        negative = ita.parse_time_slots(encoded([slot(free=0, remaining=-1)]))[0]
+        self.page.run_js.side_effect = None
+        self.page.run_js.return_value = {"contextReady": True, "candidateCount": 1,
+            "candidateReady": True, "selected": True, "clicked": False}
+        with self.assertRaises(ita.BizLogicError):
+            ita.verify_precommit_selection(self.page, runtime_service="4937", candidate=negative)
+
+
 class CompactPluginTests(unittest.TestCase):
     def plugin(self, *, query_mode="calendar", final=False):
         plugin = object.__new__(ita.ItaPlugin)
@@ -257,10 +350,34 @@ class CompactPluginTests(unittest.TestCase):
         plugin.page = SimpleNamespace(
             tab_id="tab", url="https://prenotami.esteri.it/BookingCalendar")
         plugin.is_healthy = True
+        plugin.instance_id = "compact-test"
+        plugin.session_create_time = 0
         plugin._prepared_calendar = object()
         plugin.logger = None
         return plugin
 
+    def test_bad_query_mode_is_not_misreported_as_an_expired_session(self):
+        plugin = self.plugin(query_mode="services_probe")
+        with patch.object(plugin, "health_check") as health, \
+             self.assertRaisesRegex(ita.BizLogicError, "query_mode=calendar"):
+            plugin.query(AppointmentType(routing_key="route"))
+        health.assert_not_called()
+
+    def test_status_reports_elapsed_session_age(self):
+        plugin = self.plugin()
+        plugin.session_create_time = 100
+        with patch.object(ita.time, "time", return_value=145.8):
+            self.assertEqual(plugin.get_plugin_status().session_age_sec, 45)
+        plugin.session_create_time = 0
+        self.assertEqual(plugin.get_plugin_status().session_age_sec, 0)
+
+    def test_disconnected_browser_does_not_break_status_reporting(self):
+        plugin = self.plugin()
+        page = Mock()
+        type(page).url = unittest.mock.PropertyMock(side_effect=RuntimeError("disconnected"))
+        plugin.page = page
+        self.assertEqual(plugin.get_plugin_status().current_url, "")
+
     def test_query_publishes_only_real_calendar_availability(self):
         plugin, apt = self.plugin(), AppointmentType(routing_key="route")
         positive = (ita.CalendarDay(date(2026, 10, 2), 1, 0),)

+ 0 - 16
test/ita/test_ita_final_attribution.py

@@ -1,16 +0,0 @@
-"""Italy no longer attributes final success through Reservation history."""
-
-import unittest
-
-from plugins import ita_plugin
-
-
-class FinalAttributionContractTests(unittest.TestCase):
-    def test_explicit_final_response_replaces_receipt_delta_attribution(self):
-        self.assertTrue(hasattr(ita_plugin, "_final_packet_accepted"))
-        for name in ("inspect_final_packet", "FinalBookingAttempt", "ReservationSnapshot"):
-            self.assertFalse(hasattr(ita_plugin, name), name)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 31
test/ita/test_ita_final_evidence.py

@@ -1,31 +0,0 @@
-"""Local final evidence delegates to the installed production adapter."""
-
-import unittest
-from types import SimpleNamespace
-from unittest.mock import Mock
-
-from tools.ita_final_evidence import FinalEvidenceRun
-
-
-class FinalEvidenceTests(unittest.TestCase):
-    def test_success_and_failure_are_standard_results(self):
-        for success, outcome in ((True, "confirmed"), (False, "failed_retryable")):
-            with self.subTest(success=success):
-                result = SimpleNamespace(
-                    success=success, book_date="2026-10-13", book_time="10:05 - 11:05")
-                submit = Mock(return_value=result)
-                # FinalEvidenceRun resolves through the instance runtime; a tiny
-                # stand-in object makes that boundary explicit.
-                class Plugin:
-                    def book(self):
-                        pass
-                plugin = Plugin()
-                Plugin.book.__globals__["submit_final"] = submit
-                run = FinalEvidenceRun(plugin, object())
-                self.assertEqual(run.execute()["outcome"], outcome)
-                self.assertIs(run.result, result)
-                submit.assert_called_once()
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 39
test/ita/test_ita_final_read_port.py

@@ -1,39 +0,0 @@
-"""Receipt read-port was removed from the Italy production contract."""
-
-import unittest
-from unittest.mock import Mock
-
-from plugins import ita_plugin
-
-
-class ReceiptTab:
-    def __init__(self, browser):
-        self.browser = browser
-        self.close = Mock(side_effect=lambda: browser.on_close(self))
-
-
-class Browser:
-    """Minimal synthetic browser retained for unrelated debug fixture imports."""
-
-    def __init__(self):
-        self.id = "synthetic-browser"
-        self.raw = {}
-        self.after = None
-        self.pages = []
-        self.on_close = lambda _page: None
-        self.new_tab = Mock(side_effect=self.open_tab)
-
-    def open_tab(self, **_kwargs):
-        tab = ReceiptTab(self)
-        self.pages.append(tab)
-        return tab
-
-
-class RetiredReadPortTests(unittest.TestCase):
-    def test_runtime_contains_no_reservation_read_port(self):
-        for name in ("FinalBookingAttempt", "ReservationSnapshot", "read_reservation_listing"):
-            self.assertFalse(hasattr(ita_plugin, name), name)
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 366
test/ita/test_ita_local_handoff.py

@@ -1,366 +0,0 @@
-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 Mock, 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.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._bind_query_profile",
-                    return_value=Mock(),
-                ),
-                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()

+ 38 - 1
test/ita/test_ita_login_flow.py

@@ -7,7 +7,10 @@ from unittest.mock import Mock, patch
 from plugins import ita_plugin as ita
 from test.ita.ita_test_fakes import FakeChromiumOptions, FakeKeyboard, FakeMouse, FakePage
 from utils.flow_engine import BaseFlow
-from vs_types import BizLogicError, VSAccount, VSPlgConfig
+from vs_types import (
+    BizLogicError, NotFoundError, PermissionDeniedError, RateLimiteddError,
+    SessionExpiredOrInvalidError, VSAccount, VSPlgConfig,
+)
 
 
 class DelayedFormPage(FakePage):
@@ -116,6 +119,40 @@ class LoginFlowTests(unittest.TestCase):
             plugin.create_session()
         self.assertFalse(plugin.is_healthy)
 
+    def test_framework_login_errors_keep_their_original_category(self):
+        for error_type in (SessionExpiredOrInvalidError, RateLimiteddError,
+                           PermissionDeniedError, NotFoundError, BizLogicError):
+            with self.subTest(error_type=error_type):
+                plugin = self.setup_plugin(FakePage())
+                error = error_type("synthetic failure")
+                with patch.object(ita.ItaLoginFlow, "run", side_effect=error), \
+                     self.assertRaises(error_type) as caught:
+                    plugin.create_session()
+                self.assertIs(caught.exception, error)
+                self.assertFalse(plugin.is_healthy)
+
+    def test_missing_credentials_fail_before_starting_browser(self):
+        for field, value in (("username", ""), ("username", "  "),
+                             ("username", None), ("password", ""), ("password", None)):
+            with self.subTest(field=field, value=value):
+                plugin = self.setup_plugin(FakePage())
+                setattr(plugin.config.account, field, value)
+                with patch.object(ita, "init_chromium_options") as options, \
+                     patch.object(ita, "ChromiumPage") as browser, \
+                     self.assertRaisesRegex(BizLogicError, "username and password"):
+                    plugin.create_session()
+                options.assert_not_called()
+                browser.assert_not_called()
+                self.assertFalse(plugin.is_healthy)
+
+    def test_login_preserves_the_configured_password_including_spaces(self):
+        page = FakePage()
+        plugin = self.setup_plugin(page)
+        plugin.config.account.password = " fixture password "
+        plugin.create_session()
+        self.assertEqual(plugin.config.account.password, " fixture password ")
+        self.assertIn(" fixture password ", [item["value"] for item in page.input_values.values()])
+
 
 if __name__ == "__main__":
     unittest.main()

+ 0 - 1292
test/ita/test_ita_plugin.py

@@ -1,1292 +0,0 @@
-import inspect
-import json
-import sys
-import threading
-import types
-import unittest
-from dataclasses import replace
-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,
-    SERVICE_LINK_WAIT_SECONDS,
-    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 = []
-        self.tab_id = "query-fixture-tab"
-
-    @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-book-runtime-service" in script:
-            return {"path": "/BookingCalendar", "count": 1, "value": str(self.service_id)}
-        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("utils.plugin_utils.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("Entering username", log_output)
-        self.assertIn("Successfully reached authenticated /UserArea", 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("utils.plugin_utils.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("utils.plugin_utils.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("utils.plugin_utils.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)
-        self.assertTrue(any("@radware" in call.args[0] for call in logger.call_args_list))
-
-
-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.is_healthy = True
-        plugin.session_create_time = 111.0
-        plugin.config = VSPlgConfig(account=VSAccount(username="query@example.test"), free_config=plugin.free_config)
-        plugin._reset_calendar_state()
-        if (page is not None and query_mode == "calendar" and capability == "single_schengen_tourism"
-                and page.url.startswith("https://prenotami.esteri.it/BookingCalendar")):
-            plugin._record_calendar_prepared_route(
-                plugin._resolve_route(AppointmentType(routing_key=routing_key)), role="query")
-        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._enter_service(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._enter_service(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._enter_service(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._enter_service(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._enter_service(apt_type)
-        second_result = plugin._enter_service(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._enter_service(self._appointment_type())
-
-        self.assertEqual(page.clicked, ["booking-1321"])
-
-    def test_internal_entry_reports_form_without_inventory(self):
-        page = FakeQueryPage(outcome="booking_form")
-        plugin = self._plugin(page)
-
-        result = plugin._enter_service(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_internal_entry_can_be_reprobed_without_publishing_inventory(self):
-        page = FakeQueryPage(outcome="booking_form")
-        plugin = self._plugin(page)
-        apt_type = self._appointment_type()
-
-        first_result = plugin._enter_service(apt_type)
-        second_result = plugin._enter_service(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._enter_service(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._enter_service(self._appointment_type())
-
-        self.assertEqual(page.clicked, [])
-        self.assertIn(
-            ("tag:a@@href=/Services/Booking/1321", SERVICE_LINK_WAIT_SECONDS),
-            page.looked_up,
-        )
-        self.assertFalse(any("service-list-structure" in script for script in page.run_js_calls))
-
-    def test_missing_link_with_page_notice_is_not_attributed_to_the_target(self):
-        page = FakeQueryPage(has_link=False, already_booked_notice_rows=1)
-        plugin = self._plugin(page)
-
-        with self.assertRaises(ItaTargetServiceLinkMissingError) as raised:
-            plugin._enter_service(self._appointment_type())
-
-        self.assertIn("target service link is missing", str(raised.exception))
-        self.assertNotIn("already-booked notice", str(raised.exception))
-        self.assertFalse(any("service-list-structure" in script for script in page.run_js_calls))
-        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._enter_service(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._enter_service(self._appointment_type())
-                self.assertNotIn("already-booked notice", str(raised.exception))
-                self.assertEqual(page.clicked, [])
-
-    def test_book_propagates_missing_link_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, "target service link is missing"):
-            plugin.book(trigger)
-
-        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._enter_service(self._appointment_type())
-
-        self.assertEqual(page.clicked, [])
-
-    def test_second_sede_uses_same_entry_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._enter_service(
-            self._appointment_type(routing_key, city="Hong Kong")
-        )
-
-        self.assertTrue(result.success)
-        self.assertEqual(page.clicked, ["booking-4937"])
-
-    def test_public_query_rejects_legacy_probe_before_browser_actions(self):
-        for mode in (None, "services_probe"):
-            for capability in ("services_probe_only", "single_schengen_tourism"):
-                with self.subTest(mode=mode, capability=capability):
-                    page = FakeQueryPage(outcome="booking_form")
-                    plugin = self._plugin(page, capability=capability)
-                    if mode is None:
-                        plugin.free_config.pop("query_mode")
-                    with self.assertRaisesRegex(BizLogicError, "diagnostic-only"):
-                        plugin.query(self._appointment_type())
-                    self.assertEqual(page.get_calls, [])
-                    self.assertEqual(page.clicked, [])
-                    self.assertEqual(page.run_js_calls, [])
-
-    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(
-            available_days=(types.SimpleNamespace(day=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.assertFalse(hasattr(plugin, "last_calendar_query_scan"))
-
-    def test_failed_query_does_not_create_diagnostic_state(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._prepared_calendar = None
-
-        with self.assertRaisesRegex(BizLogicError, "identity or route"):
-            plugin.query(self._appointment_type(routing_key, city="Sample City"))
-
-        self.assertFalse(hasattr(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(available_days=()),),
-        ):
-            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._prepared_calendar = 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._prepared_calendar = replace(plugin._prepared_calendar,
-            route=replace(plugin._prepared_calendar.route, routing_key="slot.other.it.tourist"))
-
-        with patch(
-            "plugins.ita_plugin.scan_until_first_available_month"
-        ) as scanner:
-            with self.assertRaisesRegex(
-                BizLogicError,
-                "identity or route",
-            ):
-                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, query_mode="calendar", capability="single_schengen_tourism")
-
-        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
-        plugin._reset_calendar_state()
-        plugin.query = Mock(side_effect=AssertionError("Book must not call public Query"))
-        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, [])
-        plugin.query.assert_not_called()
-
-    def test_book_diagnostic_mode_stops_before_avanti_without_collecting_metadata(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(page.run_js_calls, [])
-        plugin.query.assert_not_called()
-
-    def test_book_rejects_a_form_on_an_unexpected_actual_page(self):
-        page = FakeQueryPage(outcome="unknown", initial_state="user_area")
-        original_ele = page.ele
-        page.ele = lambda selector, timeout=None: (
-            FakeQueryElement(page, "wrong-form")
-            if selector == "#bookingForm" and page.state == "unknown"
-            else original_ele(selector, timeout))
-        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_calls, [])
-        plugin.query.assert_not_called()
-
-    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[2]
-        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()

+ 0 - 363
test/ita/test_ita_preflight.py

@@ -1,363 +0,0 @@
-"""Offline regression for Italy form readiness; never contact the real site."""
-import io
-import json
-import shutil
-import subprocess
-import unittest
-from contextlib import redirect_stdout
-from dataclasses import asdict
-from types import SimpleNamespace
-from unittest import TestCase
-from unittest.mock import Mock, patch
-
-from plugins import ita_plugin as session
-from plugins import ita_plugin as turnstile
-from test.ita.test_debug_ita_calendar_gate import booking_preflight_snapshot
-from test.ita.test_ita_protocol import live_route
-
-
-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, enabled, expected in (
-            (False, True, 'turnstile_token_pending'),
-            (True, False, 'avanti_disabled'),
-            (False, False, '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(
-                        turnstileReady=token, avantiEnabled=enabled))
-                self.assertIn(expected, str(raised.exception))
-
-    def test_production_wait_does_not_emit_private_snapshots_without_a_diagnostic(self):
-        raw = booking_preflight_snapshot(turnstileReady=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)
-        self.assertNotIn('ITA_BOOK_PREFLIGHT_DIAGNOSTIC=', output.getvalue())
-        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(formReady=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(turnstileReady=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 ('turnstileReady', 'avantiEnabled'):
-            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_pending_validation_does_not_rewrite_snapshot_or_relax_other_fields(self):
-        raw = booking_preflight_snapshot(turnstileReady=False, avantiEnabled=False)
-        original = dict(raw)
-        session.validate_booking_preflight(raw, allow_pending=True)
-        self.assertEqual(raw, original)
-        with self.assertRaises(session.CalendarGateError):
-            session.validate_booking_preflight(raw)
-        for key, value in (("formReady", False), ("otpValuePresent", True),
-                           ("otpSendEnabled", False)):
-            with self.subTest(key=key), self.assertRaisesRegex(session.CalendarGateError, key):
-                session.validate_booking_preflight({**raw, key: value}, allow_pending=True)
-
-    def test_pending_policy_requires_a_real_boolean(self):
-        for value in (None, 1, "true"):
-            with self.subTest(value=value), self.assertRaisesRegex(session.CalendarGateError, "policy"):
-                session.validate_booking_preflight(booking_preflight_snapshot(), allow_pending=value)
-
-    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(turnstileReady=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['turnstileReady'])
-        self.assertEqual(page.run_js.call_count, 2)
-        action.assert_called_once()
-
-    def test_contract_fields_are_plain_booleans(self):
-        for field in ('formReady', 'turnstileReady', 'otpValuePresent',
-                      'otpSendEnabled', 'avantiEnabled'):
-            for value in (1, 0, 1.0, 0.0, 'true', None):
-                with self.subTest(field=field, value=value), redirect_stdout(io.StringIO()), \
-                     self.assertRaisesRegex(session.CalendarGateError, field):
-                    self.run_wait(booking_preflight_snapshot(**{field: value}))
-
-
-FORM_JS_HARNESS = r"""
-const vm = require('node:vm');
-const input = JSON.parse(require('node:fs').readFileSync(0, 'utf8'));
-const cfg = input.config, mode = input.mode;
-const calls = [];
-const fields = {
-  hiddenTipoPrenotazione: {value: '0'}, numAccSelected: {value: '0'},
-  hiddenSelezionato_0: {value: '0'},
-  PrivacyCheck: {checked: false, click() {this.checked = true; calls.push('privacy');}},
-  'otp-input': {value: ''}, 'otp-send': {disabled: false}, btnAvanti: {disabled: false},
-};
-function control(spec, role) {
-  fields[spec.control_id] = {
-    value: '0', options: [{value: spec.value, textContent: mode === role + '_wrong_label'
-      ? 'Unrelated service' : '  ' + spec.labels[0].toUpperCase() + '  '}],
-    dispatchEvent(event) {
-      if (event.type !== 'change' || event.bubbles !== true) throw Error('Wrong change event');
-      calls.push(role);
-      if (role === 'booking' && mode !== 'hidden_unsynced') fields.hiddenTipoPrenotazione.value = this.value;
-      if (role === 'booking' && mode === 'navigated_during_change') location.pathname = '/Services';
-    },
-  };
-  if (mode === role + '_missing') delete fields[spec.control_id];
-}
-control(cfg.booking_type, 'booking');
-control(cfg.purpose, 'purpose');
-if (mode === 'companions') fields.numAccSelected.value = '1';
-if (mode === 'purpose_hidden') fields.hiddenSelezionato_0.value = '999';
-const token = {value: mode === 'pending' ? '' : 'synthetic-widget-token'};
-const location = {
-  origin: mode === 'wrong_origin' ? 'https://other.example.test' : 'https://prenotami.esteri.it',
-  pathname: mode === 'wrong_path' ? '/Services' : '/Services/Booking/' + cfg.service_id,
-};
-location.href = location.origin + location.pathname;
-const form = {
-  action: mode === 'wrong_action' ? 'https://other.example.test/submit' : location.href,
-  method: mode === 'wrong_method' ? 'GET' : 'POST',
-  enctype: mode === 'wrong_enctype' ? 'application/json' : 'multipart/form-data',
-  querySelectorAll(selector) {
-    if (selector === 'input[type="file"]') return mode === 'upload' ? [{}] : [];
-    if (selector === '[required]') return mode === 'unknown_required' ? [{id: 'new-mandatory-field'}] : [];
-    throw Error('Unexpected form selector: ' + selector);
-  },
-};
-const document = {
-  visibilityState: 'visible',
-  getElementById: id => fields[id] || null,
-  querySelector(selector) {
-    if (selector === '#bookingForm') return form;
-    if (selector.startsWith('script[')) return {};
-    throw Error('Unexpected selector: ' + selector);
-  },
-  querySelectorAll(selector) {
-    if (selector === '#bookingForm') return mode === 'duplicate_form' ? [form, form] : [form];
-    if (selector === 'input[name="cf-turnstile-response"]') return mode === 'duplicate_token' ? [token, token] : [token];
-    if (selector === '#otp-input' && mode === 'duplicate_otp') return [fields['otp-input'], fields['otp-input']];
-    if (selector === '#otp-send' && mode === 'duplicate_send') return [fields['otp-send'], fields['otp-send']];
-    if (selector === '#btnAvanti' && mode === 'duplicate_avanti') return [fields.btnAvanti, fields.btnAvanti];
-    const field = fields[selector.slice(1)];
-    if (field) return [field];
-    throw Error('Unexpected selector: ' + selector);
-  },
-};
-const context = {document, location, window: {location, turnstile: {}}, URL,
-  Event: class {constructor(type, options) {this.type = type; this.bubbles = options.bubbles;}}};
-const run = () => vm.runInNewContext('(function(){' + input.source + '\n})()', context, {timeout: 1000});
-const before = run(), second = run();
-fields['otp-input'].value = '001234';
-fields['otp-send'].disabled = true;
-const after = run();
-process.stdout.write(JSON.stringify({before, second, after, calls}));
-"""
-
-
-@unittest.skipUnless(shutil.which('node'), 'Node required for actual form JavaScript execution')
-class FormJavaScriptTests(TestCase):
-    def run_case(self, mode='ready', *, alternate=False, source_factory=None):
-        config = live_route()
-        if alternate:
-            config['service_id'] = 9012
-            config['form'].update(booking_type_control_id='other-booking', booking_type_value='31',
-                                  booking_type_labels=['Individual'], purpose_control_id='other-purpose',
-                                  purpose_value='67', purpose_labels=['Tourism'])
-        route = session.resolve_route_config({'sample': config}, 'sample')
-        source = (source_factory or session.guarded_preflight_script)(
-            route, f'/Services/Booking/{route.service_id}')
-        completed = subprocess.run([shutil.which('node'), '-e', FORM_JS_HARNESS],
-            input=json.dumps({'source': source, 'mode': mode, 'config': asdict(route)}),
-            capture_output=True, text=True, timeout=10)
-        self.assertEqual(completed.returncode, 0, completed.stderr)
-        return json.loads(completed.stdout)
-
-    def test_two_routes_configure_controls_once_and_preserve_post_otp_cooldown(self):
-        for alternate in (False, True):
-            with self.subTest(alternate=alternate):
-                result = self.run_case(alternate=alternate)
-                session.validate_booking_preflight(result['before'])
-                session.validate_booking_preflight(result['second'])
-                session.validate_booking_preflight(result['after'], after_otp=True)
-                self.assertEqual(result['calls'], ['booking', 'purpose', 'privacy'])
-                self.assertNotIn('001234', json.dumps(result))
-                self.assertNotIn('synthetic-widget-token', json.dumps(result))
-
-    def test_boundary_rejects_before_any_form_changes(self):
-        for mode in ('wrong_origin', 'wrong_path', 'wrong_action', 'wrong_method',
-                     'wrong_enctype', 'upload', 'duplicate_form'):
-            with self.subTest(mode=mode):
-                result = self.run_case(mode)
-                self.assertEqual(result['calls'], [])
-                with self.assertRaises(session.CalendarGateError):
-                    session.validate_booking_preflight(result['before'])
-
-    def test_unknown_controls_unsynced_values_and_duplicate_otp_remain_rejected(self):
-        for mode in ('booking_wrong_label', 'purpose_wrong_label', 'booking_missing',
-                     'purpose_missing', 'hidden_unsynced', 'companions', 'purpose_hidden',
-                     'unknown_required', 'duplicate_otp', 'pending'):
-            with self.subTest(mode=mode):
-                result = self.run_case(mode)
-                with self.assertRaises(session.CalendarGateError):
-                    session.validate_booking_preflight(result['before'])
-                if mode.startswith('booking_'):
-                    self.assertNotIn('booking', result['calls'])
-                if mode.startswith('purpose_') and mode != 'purpose_hidden':
-                    self.assertNotIn('purpose', result['calls'])
-
-    def test_existing_calendar_debug_entry_uses_the_same_guarded_form(self):
-        from tools import debug_ita_calendar_gate as gate
-        for alternate in (False, True):
-            for mode in ('ready', 'wrong_origin', 'wrong_action', 'upload'):
-                with self.subTest(alternate=alternate, mode=mode):
-                    result = self.run_case(mode, alternate=alternate,
-                                           source_factory=gate.guarded_preflight_script)
-                    if mode == 'ready':
-                        session.validate_booking_preflight(result['before'])
-                        session.validate_booking_preflight(result['after'],
-                            after_otp=True)
-                        self.assertEqual(result['calls'], ['booking', 'purpose', 'privacy'])
-                    else:
-                        self.assertEqual(result['calls'], [])
-                        with self.assertRaises(session.CalendarGateError):
-                            session.validate_booking_preflight(result['before'])
-
-    def test_duplicate_business_controls_cannot_pass_either_otp_stage(self):
-        for mode in ('duplicate_send', 'duplicate_avanti', 'duplicate_token'):
-            with self.subTest(mode=mode):
-                result = self.run_case(mode)
-                for snapshot, after_otp in (('before', False), ('after', True)):
-                    self.assertFalse(result[snapshot]['formReady'])
-                    with self.assertRaises(session.CalendarGateError):
-                        session.validate_booking_preflight(result[snapshot], after_otp=after_otp)
-
-    def test_native_change_navigation_is_not_reported_as_a_ready_form(self):
-        result = self.run_case('navigated_during_change')
-        self.assertFalse(result['before']['formReady'])
-        with self.assertRaisesRegex(session.CalendarGateError, 'formReady'):
-            session.validate_booking_preflight(result['before'])
-        self.assertEqual(result['second'], {
-            'formReady': False, 'turnstileReady': False, 'otpValuePresent': False,
-            'otpSendEnabled': False, 'avantiEnabled': False,
-        })
-
-
-class TurnstileRecoveryTests(TestCase):
-    def setUp(self):
-        self.page = SimpleNamespace(title='Booking - Prenot@Mi', refresh=Mock(), run_js=Mock())
-        self.guard = Mock()
-        self.recovery = turnstile.turnstile_recovery(self.page, 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, after_otp=False):
-        self.recovery(raw if raw is not None else booking_preflight_snapshot(turnstileReady=False),
-            after_otp=after_otp,
-            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(avantiEnabled=False))
-        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.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, after_otp=True)
-        self.assertEqual(self.helper.click_verification_button.call_count, 3)
-
-    def test_wrong_form_or_missing_field_cannot_interact(self):
-        for changes in ({'formReady': False}, {'turnstileReady': None}):
-            with self.subTest(changes=changes), self.assertRaises(session.CalendarGateError):
-                raw = booking_preflight_snapshot(turnstileReady=False)
-                raw.update(changes)
-                self.attempt(raw=raw)
-        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()
-        self.assertNotIn('PRIVATE_BROWSER_DATA', output.getvalue())
-        self.assertNotIn('ITA_BOOK_TURNSTILE_INTERACTION=', output.getvalue())
-        self.assertEqual(self.helper.click_verification_button.call_count, 1)
-
-    def test_interaction_success_alone_cannot_release_preflight(self):
-        page = SimpleNamespace(run_js=Mock(return_value=booking_preflight_snapshot(turnstileReady=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()

+ 0 - 330
test/ita/test_ita_query_recovery.py

@@ -1,330 +0,0 @@
-"""Offline recovery contracts; no browser, credentials, or website requests."""
-
-import json
-import sys
-import threading
-import time
-import types
-import unittest
-from pathlib import Path
-from types import SimpleNamespace
-from unittest.mock import Mock, patch
-
-from DrissionPage.errors import PageDisconnectedError
-
-from plugins.ita_plugin import RUNTIME_SERVICE_SCRIPT
-from plugins.ita_plugin import (
-    AVAILABILITY_PATH, CalendarAccessDeniedError, CalendarAuthenticationExpiredError,
-    CalendarGateError, CalendarRateLimitedError, CalendarTransientError,
-    parse_availability_packet,
-)
-from plugins.ita_plugin import (
-    ItaCalendarTransientError, ItaPlugin,
-)
-from test.ita.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._reset_calendar_state()
-    plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query")
-    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]))
-                with self.assertRaises(expected):
-                    plugin.query(route.appointment_type())
-                self.assertFalse(plugin.is_healthy)
-                self.assertFalse(plugin.health_check())
-                self.assertFalse(hasattr(plugin, "last_calendar_query_scan"))
-                self.assertIsNone(plugin._prepared_calendar)
-                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"]))
-        with self.assertRaises(ItaCalendarTransientError):
-            plugin.query(route.appointment_type())
-        self.assertTrue(plugin.is_healthy)
-        self.assertFalse(hasattr(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._prepared_calendar)
-
-    def test_configured_lifetime_and_health_probe_clear_preparation(self):
-        plugin, route = prepared_plugin()
-        plugin.session_create_time = 1
-        self.assertFalse(plugin.health_check())
-        self.assertFalse(plugin.is_healthy)
-        self.assertIsNone(plugin._prepared_calendar)
-
-    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 CalendarSessionOwnershipTests(unittest.TestCase):
-    def test_ordinary_query_checks_identity_without_exporting_a_checkpoint(self):
-        for mutation in ("account", "page", "generation", "service", "tab", "route"):
-            with self.subTest(mutation=mutation):
-                plugin, route = prepared_plugin()
-                original = plugin.page
-                if mutation == "account":
-                    plugin.config.account.username = "other@example.test"
-                elif mutation == "page":
-                    plugin.page = RecoveryPage()
-                elif mutation == "generation":
-                    plugin.session_create_time += 1
-                elif mutation == "service":
-                    plugin.page.runtime_service = "different-runtime"
-                elif mutation == "tab":
-                    plugin.page.tab_id = "different-tab"
-                elif mutation == "route":
-                    plugin.free_config["apt_configs"][route.routing_key]["service_id"] = 9002
-                with self.assertRaises(BizLogicError):
-                    plugin.query(route.appointment_type())
-                self.assertEqual(original.refresh_calls, 0)
-                self.assertEqual(plugin.page.refresh_calls, 0)
-
-    def test_query_proof_cannot_be_copied_to_another_page(self):
-        first, route = prepared_plugin()
-        second, _ = prepared_plugin()
-        second.session_create_time = first.session_create_time
-        second._prepared_calendar = first._prepared_calendar
-        with self.assertRaises(BizLogicError):
-            second.query(route.appointment_type())
-        self.assertEqual(second.page.refresh_calls, 0)
-
-    def test_preparation_cannot_attest_a_replaced_page_after_reading_the_old_one(self):
-        plugin, route = prepared_plugin()
-        old_page = plugin.page
-        read = old_page.run_js
-        def replace_page_during_read(script, *args):
-            result = read(script, *args)
-            plugin.page = RecoveryPage()
-            return result
-        old_page.run_js = replace_page_during_read
-        with self.assertRaises(BizLogicError):
-            plugin._record_calendar_prepared_route(plugin._resolve_route(route.appointment_type()), role="query")
-        self.assertIsNone(plugin._prepared_calendar)
-        self.assertEqual(old_page.refresh_calls, 0)
-        self.assertEqual(plugin.page.refresh_calls, 0)
-
-    def test_query_rechecks_ownership_before_publishing_inventory(self):
-        plugin, route = prepared_plugin()
-        publish = plugin.page._publish_month
-        def change_account_during_response():
-            publish()
-            plugin.config.account.username = "other@example.test"
-        plugin.page._publish_month = change_account_during_response
-        with self.assertRaises(BizLogicError):
-            plugin.query(route.appointment_type())
-        self.assertEqual(plugin.page.refresh_calls, 1)
-        self.assertFalse(hasattr(plugin, "last_calendar_query_scan"))
-        self.assertEqual(plugin.page.final_requests, 0)
-
-    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()
-                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_real_cleanup_uses_shared_best_effort_contract(self):
-        plugin, _route = prepared_plugin()
-        plugin.__dict__.pop("cleanup")
-        plugin.root_workspace = "/nonexistent/ita-offline-cleanup-test"
-        plugin.tunnel = SimpleNamespace(stop=Mock())
-        page = plugin.page
-        page.quit = Mock(side_effect=RuntimeError("private@example.test secret-token"))
-        plugin.cleanup()
-        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.ita.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()

+ 0 - 61
test/ita/test_ita_reservation.py

@@ -1,61 +0,0 @@
-"""Synthetic receipt shapes retained only for old debug-fixture compatibility."""
-
-import copy
-import unittest
-
-from plugins import ita_plugin
-from tools import debug_ita_reservation as diagnostic
-
-
-HEADERS = ["Codice Prenotazione", "Ufficio", "Servizio", "Data", "Ora", "Stato"]
-
-
-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,
-        "rows": [{"reference": "SYNTHETIC-REFERENCE", "office": "Visti",
-                  "service": "Visti Nazionali e Schengen", "date": "13 ottobre 2026",
-                  "time": "10:25", "status": "Annullata"}],
-    }, {"id": "dataTableReservationsWL", "structuralEmpty": True}]}
-
-
-def confirmed_detail():
-    raw = copy.deepcopy(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 = copy.deepcopy(listing())
-    raw["tables"][0]["rows"].append({
-        **raw["tables"][0]["rows"][0], "reference": "CONFIRMED-SYNTHETIC",
-        "date": "3 settembre 2026", "time": "09:26", "status": "Confermata",
-    })
-    raw["tables"][0]["count"] = 2
-    return raw
-
-
-class RetiredReservationTests(unittest.TestCase):
-    def test_runtime_has_no_receipt_attribution_state_machine(self):
-        for name in ("ReservationState", "ReservationRecord", "read_reservation_listing"):
-            self.assertFalse(hasattr(ita_plugin, name), name)
-
-    def test_diagnostic_reports_retirement_without_external_io(self):
-        self.assertEqual(diagnostic.main([]), 0)
-        with self.assertRaises(diagnostic.ReservationDiagnosticRetired):
-            diagnostic.parse_reservation_detail(detail())
-
-
-if __name__ == "__main__":
-    unittest.main()

+ 0 - 250
test/ita/test_ita_route_wiring.py

@@ -1,250 +0,0 @@
-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[2]
-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.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.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()

+ 39 - 27
test/ita/test_ita_single_file.py

@@ -3,6 +3,7 @@ import ast
 import builtins
 from contextlib import ExitStack, redirect_stdout
 import hashlib
+import json
 from io import StringIO
 import os
 from pathlib import Path
@@ -13,13 +14,11 @@ import unittest
 from unittest.mock import Mock, patch
 
 from plugins import ita_plugin  # Preload shared host dependencies, not a loader substitute.
-from test.ita.test_ita_calendar_book import FakePage
 from test.ita.test_ita_protocol import live_route
-from tools import ita_query_book_local as local
 from utils import plugin_updater
 from vs_plg_factory import VSPlgFactory
 from vs_plg import IVSPlg
-from vs_types import AppointmentType, VSBookResult, VSQueryResult
+from vs_types import AppointmentType, RateLimiteddError, VSBookResult, VSQueryResult
 
 ROOT = Path(__file__).resolve().parents[2]
 
@@ -80,7 +79,7 @@ class SingleFileInstallationTests(unittest.TestCase):
         self.stack.enter_context(patch.object(sys, "dont_write_bytecode", True))
         self.factory = VSPlgFactory()
         self.factory.register_plugin("ita_plugin", str(self.path), "ItaPlugin")
-        self.install(self.source, "1.0.1")
+        self.install(self.source, ita_plugin.ItaPlugin.version)
 
     def install(self, source, version):
         self.assertTrue(plugin_updater.download_and_install_plugin(
@@ -97,30 +96,35 @@ class SingleFileInstallationTests(unittest.TestCase):
         plugin = self.create()
         runtime = type(plugin).book.__globals__
         for name in ("ItaRouteConfig", "_submit_final_once",
-                     "parse_otp_body", "prepare_calendar", "recheck_calendar_before_final", "submit_final"):
+                     "parse_otp_body", "prepare_calendar", "recheck_calendar_before_final"):
             self.assertEqual(runtime[name].__module__, "ita_plugin", name)
         self.assertEqual(runtime["parse_otp_body"]("OTP Code:001234"), "001234")
-        self.assertEqual(plugin_updater.get_installed_plugins(str(self.directory))["ita_plugin"], "1.0.1")
+        self.assertEqual(plugin_updater.get_installed_plugins(str(self.directory))["ita_plugin"],
+                         ita_plugin.ItaPlugin.version)
         self.assertIsNot(runtime["ItaCapability"], ita_plugin.ItaCapability)
 
     def test_public_query_and_book_bind_the_loaded_file_not_canonical_import(self):
         plugin = self.create()
         plugin.page = SimpleNamespace(url="https://prenotami.esteri.it/UserArea", quit=Mock())
-        plugin.free_config = {"otp_mode": "cloud", "query_mode": "calendar"}
+        key = "slot.fixture.it.tourist"
+        plugin.free_config = {"otp_mode": "cloud", "query_mode": "calendar",
+                              "apt_configs": {key: live_route()}}
         negative = VSQueryResult(success=False)
         runtime = type(plugin).book.__globals__
-        with patch.dict(runtime, prepare_query_if_needed=Mock(return_value=negative)):
-            self.assertIs(plugin.query(AppointmentType(routing_key="fixture")), negative)
-            runtime["prepare_query_if_needed"].assert_called_once()
-        key = "slot.fixture.it.tourist"
+        with patch.object(plugin, "health_check", return_value=True), \
+             patch.object(plugin, "_enter_service", return_value=negative), \
+             patch.dict(runtime, prepare_calendar=Mock()):
+            self.assertIs(plugin.query(AppointmentType(routing_key=key)), negative)
+            runtime["prepare_calendar"].assert_not_called()
         plugin.free_config = {"otp_mode": "cloud", "query_mode": "services_probe",
                               "final_submit_enabled": False, "apt_configs": {key: live_route()}}
         plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test"))
         plugin.session_create_time = 1
-        plugin.page = FakePage()
-        plugin.page.tab_id = "fixture-tab"
-        plugin.page.quit = Mock()
         route = runtime["resolve_route_config"](plugin.free_config["apt_configs"], key)
+        plugin.page = SimpleNamespace(tab_id="fixture-tab", quit=Mock(),
+            url="https://prenotami.esteri.it/BookingCalendar",
+            run_js=Mock(return_value={"path": "/BookingCalendar", "service": str(route.service_id),
+                                      "day": "2026-10-02"}))
         plugin._record_calendar_prepared_route(route, role="book")
         trigger = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key))
         with patch.dict(runtime, recheck_calendar_before_final=Mock(return_value=None)), \
@@ -143,23 +147,31 @@ class SingleFileInstallationTests(unittest.TestCase):
         adapter = Mock(return_value=expected)
         self.create()  # The host overwrites sys.modules['ita_plugin'] for Query.
         self.assertIsNot(sys.modules["ita_plugin"].ItaPlugin, type(plugin))
-        approval = object()
-        with patch.dict(runtime, _submit_final_once=adapter):
-            self.assertIs(runtime["submit_final"](plugin, route, approval), expected)
-        adapter.assert_called_once_with(plugin, route, approval)
-
-    def test_local_observer_preserves_standard_false_book_result(self):
+        plugin.page = object()
+        plugin.config = SimpleNamespace(account=SimpleNamespace(username="fixture@example.test"))
+        plugin.free_config = {"apt_configs": config, "final_submit_enabled": True}
+        plugin._prepared_calendar = object()
+        candidate = SimpleNamespace(day="2026-10-02", time_label="10:05 - 11:05")
+        with patch.dict(runtime, _submit_final_once=adapter,
+                        recheck_calendar_before_final=Mock(return_value=candidate)), \
+             patch.object(plugin, "_log"):
+            signal = VSQueryResult(success=True, apt_type=AppointmentType(routing_key=key))
+            self.assertIs(plugin.book(signal, {"username": "fixture@example.test"}), expected)
+        adapter.assert_called_once_with(plugin, route, candidate)
+        plugin.page = None
+
+    def test_loaded_adapter_uses_the_host_exception_classes(self):
         plugin = self.create()
-        observer = local.ObservedPlugin(plugin, "book")
-        result = VSBookResult(success=False, label="retryable")
-        plugin.book = Mock(return_value=result)
-        self.assertIs(observer.book(VSQueryResult(), {}), result)
-        self.assertIsNone(observer.error)
+        runtime = type(plugin).book.__globals__
+        with patch.dict(runtime, perform_browser_fetch=Mock(return_value=SimpleNamespace(
+                status_code=429, url="https://prenotami.esteri.it/BookingCalendar/RetrieveTimeSlots"))), \
+             self.assertRaises(RateLimiteddError):
+            runtime["_calendar_post"](object(), runtime["TIME_SLOTS_PATH"], {}, json.loads)
 
     def test_real_reload_replaces_code_and_preserves_process_wide_otp_lock(self):
         first = self.create()
         old = type(first).book.__globals__
-        updated = self.source.replace('version = "1.0.1"', 'version = "1.0.200"')
+        updated = self.source.replace(f'version = "{ita_plugin.ItaPlugin.version}"', 'version = "1.0.200"')
         self.install(updated, "1.0.200")
         owner = self
         events = []
@@ -184,7 +196,7 @@ class SingleFileInstallationTests(unittest.TestCase):
         self.assertEqual(events, ["stop", "load", "start"])
         self.assertEqual(wrappers["fixture"].plugin.version, "1.0.200")
         for name in ("ItaPlugin", "ItaCapability", "OtpMailConfig", "_submit_final_once",
-                     "fetch_otp_from_cloud", "prepare_calendar", "submit_final"):
+                     "fetch_otp_from_cloud", "prepare_calendar"):
             self.assertIsNot(new[name], old[name], name)
         self.assertIsNot(new["ItaPlugin"].book, old["ItaPlugin"].book)
         self.assertIs(new["_OTP_INPUT_LOCK"], old["_OTP_INPUT_LOCK"])

+ 0 - 689
test/ita/test_ita_workflow.py

@@ -1,689 +0,0 @@
-"""Offline production-entry tests: no credentials, site calls, or cloud writes."""
-import ast
-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_plugin as workflow
-from plugins import ita_plugin as preparation
-from plugins.ita_plugin import ItaPlugin
-from plugins.ita_plugin import fetch_otp_from_cloud as real_fetch_otp_from_cloud
-from plugins import ita_plugin as ita_turnstile
-from plugins.ita_plugin import OtpMailConfig
-from test.ita import test_ita_calendar_book_flow as flow
-from test.ita.test_debug_ita_calendar_gate import booking_preflight_snapshot
-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, otpSendEnabled=not 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_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_prepared_route.assert_called_once_with(self.route, role="query")
-        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_prepared_route.assert_called_once_with(self.route, role="book")
-
-    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_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.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_prepared_route.assert_called_once_with(self.route, role="book")
-
-    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_stops_avanti(self):
-        self.page.ele("#otp-input").input.side_effect = RuntimeError("private typed 001234")
-        with self.assertRaisesRegex(preparation.CalendarGateError, "DOM write failed"):
-            workflow.prepare_calendar(self.plugin, self.route, role="book")
-        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_stops_before_any_site_action(self):
-        with self.assertRaises(preparation.CalendarGateError):
-            workflow.prepare_calendar(self.plugin, replace(self.route, mail=None), 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._prepared_calendar = None
-        self.plugin._resolve_route = Mock(return_value=self.route)
-        self.plugin._enter_service = Mock(return_value=results[0])
-        self.plugin._query_once = Mock(side_effect=results[1:])
-        self.plugin._reset_calendar_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: real_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()
-        plugin._enter_service.assert_called_once()
-        self.assertEqual(plugin._query_once.call_count, 2)
-        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_prepared_route.assert_called_once_with(self.route, role="query")
-        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: real_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_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: real_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(
-            turnstileReady=self.token_ready, otpValuePresent=self.otp_present,
-            otpSendEnabled=not 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.assertGreaterEqual(self.page.run_js.call_count, 3)
-        self.assertNotIn('ITA_BOOK_PREFLIGHT_DIAGNOSTIC=', 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_prepared_route.assert_called_once_with(self.route, role="book")
-
-    def test_query_reuses_book_recovery_then_records_only_query_preparation(self):
-        self.assert_preparation_recovers('query')
-        self.plugin._record_calendar_prepared_route.assert_called_once_with(self.route, role="query")
-
-    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_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_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, 'turnstile_recovery') 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_stops_before_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('ITA_BOOK_WAITING_FOR_FORM:', output.getvalue())
-        self.assertNotIn('ITA_BOOK_PREFLIGHT_DIAGNOSTIC=', 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, \
-             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()
-
-    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.assertEqual(result.label, "calendar-ready-before-final")
-        self.assertEqual(self.plugin.page.clicks, 1)
-        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.assertEqual(self.plugin.page.clicks, 1)
-        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.assertIs(submit.call_args.args[0], self.plugin)
-        self.assertEqual(submit.call_args.args[1], self.route)
-        self.assertIsNotNone(submit.call_args.args[2])
-
-    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_prepared_route(self.route, role="book")
-        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.assertIs(submit.call_args.args[0], self.plugin)
-        self.assertEqual(submit.call_args.args[1], self.route)
-        self.assertIsNotNone(submit.call_args.args[2])
-
-    def test_one_public_book_call_prepares_and_selects_from_dashboard(self):
-        plugin = self.plugin
-        plugin.page.url = "https://prenotami.esteri.it/UserArea"
-        plugin._prepared_calendar = None
-        def entry(apt, **kwargs):
-            plugin.page.url = "https://prenotami.esteri.it" + plugin._booking_path(self.route)
-            return VSQueryResult(success=True)
-        plugin._enter_service = Mock(side_effect=entry)
-        def prepare(p, route, *, role):
-            self.assertEqual(role, "book")
-            p.page.url = "https://prenotami.esteri.it/BookingCalendar"
-            p._record_calendar_prepared_route(route, role="book")
-        with patch.object(workflow, "prepare_calendar", side_effect=prepare) as prep:
-            result = plugin.book(self.trigger, self.inputs)
-        prep.assert_called_once()
-        plugin._enter_service.assert_called_once_with(self.trigger.apt_type, route=self.route)
-        plugin.query.assert_not_called()
-        self.assertEqual(result.label, "calendar-ready-before-final")
-        self.assertEqual(plugin.page.clicks, 1)
-
-    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_prepared_route(self.route, role="book")
-        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):
-        context = self.plugin._prepared_calendar
-        for query_key, username in ((self.route.routing_key, self.inputs["username"]), (None, "other@example.test")):
-            self.plugin._prepared_calendar = replace(context, role="query" if query_key else "book")
-            with self.assertRaises(BizLogicError), patch.object(workflow, "submit_final") as submit:
-                self.plugin.book(self.trigger, {"username": username})
-            submit.assert_not_called()
-
-    def test_cloud_final_rejects_query_session_and_other_applicant(self):
-        self.plugin.free_config.update(otp_mode="cloud", final_submit_enabled=True)
-        context = self.plugin._prepared_calendar
-        for query_key, username in ((self.route.routing_key, self.inputs["username"]), (None, "other@example.test")):
-            self.plugin._prepared_calendar = replace(context, role="query" if query_key else "book")
-            with patch.object(workflow, "submit_final") as submit, self.assertRaises(BizLogicError):
-                self.plugin.book(self.trigger, {"username": username})
-            submit.assert_not_called()
-
-    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._prepared_calendar = None
-        strong = VSQueryResult(success=True, availability_status=AvailabilityStatus.Available,
-                               earliest_date=datetime(2026, 10, 13), apt_type=self.trigger.apt_type)
-        plugin._enter_service = Mock(return_value=VSQueryResult(success=True))
-        plugin._query_once = Mock(return_value=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)
-        plugin._enter_service.assert_called_once()
-        self.assertEqual(plugin._query_once.call_count, 2)
-
-    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._enter_service = 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[2]
-        for filename in ("ita_plugin.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 BookerReuseTests(TestCase):
-    def setUp(self):
-        # Reuse existing offline Redis import fixture; never open Redis/cloud.
-        from test.ita.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_standard_failure_is_called_again_on_the_next_signal(self):
-        self.task.instance.book.return_value = VSBookResult(success=False)
-        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_not_called()
-        self.assertTrue(self.task.book_allowed)
-        self.assertEqual(self.task.instance.book.call_count, 2)
-        self.booker._push_success_notification.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.ita.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")), \
-                patch.object(cli, "_bind_query_profile", return_value=Mock()), \
-                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()

+ 21 - 104
test/ita/test_plugin_tester_ita_config.py

@@ -1,10 +1,7 @@
 """Offline checks for the Italy profile consumed by the existing public tester."""
 
 import copy
-from contextlib import redirect_stderr, redirect_stdout
-import io
 import json
-import logging
 from pathlib import Path
 from types import SimpleNamespace
 import unittest
@@ -12,7 +9,6 @@ from unittest.mock import Mock, patch
 
 from plugins.ita_plugin import ItaCapability, resolve_route_config
 from sentinel import SentinelGCO
-from tools import debug_ita_query_book as query_book_cli
 from tools.plugin_tester import PluginTester
 from vs_types import GroupConfig
 
@@ -84,6 +80,18 @@ class ItalyPublicTesterConfigTests(unittest.TestCase):
         for key in ("website", "query_mode", "otp_mode", "final_submit_enabled", "apt_configs"):
             self.assertEqual(group.free_config[key], config[key])
 
+    def test_original_configuration_path_keeps_its_account_binding(self):
+        path = Path(__file__).resolve().parents[2] / "config/test_conf.json"
+        data = json.loads(path.read_text())
+        profile = data.get("plugins", data)["ita_plugin"]
+        with patch("vs_plg_factory.VSC_INFO"):
+            tester = PluginTester.from_json_config("ita_plugin", str(path))
+        for field in ("username", "password"):
+            # Assert the binding without including credentials in failure output.
+            self.assertTrue(getattr(tester.config.account, field) == profile["account"][field],
+                            f"Italy {field} must come from the original configuration")
+        self.assertNotIn("capsolver_key", profile["free_config"])
+
 
 class ItalySingleAccountPoolConfigTests(unittest.TestCase):
     def setUp(self):
@@ -152,107 +160,16 @@ class ItalySingleAccountPoolConfigTests(unittest.TestCase):
         self.plugin.create_session.assert_not_called()
         self.assertEqual(self.sentinel.m_tasks, [])
 
+    def test_another_pool_account_uses_its_own_authorized_mailbox(self):
+        self.cloud.get_next_account.return_value["username"] = "another@example.test"
+        self.sentinel._spawn_sentinel_worker()
+        config = self.plugin.set_config.call_args.args[0]
+        route = resolve_route_config(config.free_config["apt_configs"],
+                                     self.group.appointment_types[0].routing_key)
+        self.assertEqual(config.account.username, "another@example.test")
+        self.assertEqual(route.mail.mailbox_for(config.account.username), "another@example.test")
+        self.plugin.book.assert_not_called()
 
-class ItalyPoolQueryCommandTests(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_pool_query(self):
-        output = io.StringIO()
-        with redirect_stdout(output):
-            code = query_book_cli.main(["--pool-query"])
-        return code, output.getvalue()
-
-    def test_supported_command_uses_existing_sdk_and_public_tester_query_only(self):
-        code, output = self.run_pool_query()
-        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-v3", 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_pool_query()
-                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_is_not_an_italy_allocation_gate(self):
-        with patch("vs_log_macros._active_logger", logging.Logger("unsafe-fixture", level=logging.DEBUG)):
-            code, output = self.run_pool_query()
-        self.assertEqual(code, 0)
-        self.assertIn("ITA_POOL_QUERY_SOURCE=cloud_pool", output)
-        self.cloud.get_next_account.assert_called_once()
-        self.pipeline.assert_called_once()
-
-    def test_test_account_override_stops_before_pool_allocation(self):
-        with patch("configure.TEST_ACCOUNT", {"username": "fixture@example.test"}):
-            code, output = self.run_pool_query()
-        self.assertEqual(code, 1)
-        self.assertIn("ITA_POOL_QUERY_ACCOUNT_REJECTED reason=test_account_override_enabled", output)
-        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_pool_query()
-        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, output = self.run_pool_query()
-                self.assertEqual(code, 1)
-                self.assertIn("ITA_POOL_QUERY_ACCOUNT_REJECTED", output)
-                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_pool_query()
-        self.assertEqual(code, 1)
-        self.assertIn("ITA_POOL_QUERY_MAIL_CONFIG_FAILED", output)
-        self.pipeline.assert_not_called()
-
-    def test_pool_query_rejects_final_submission_before_account_allocation(self):
-        with self.assertRaises(SystemExit) as raised, redirect_stderr(io.StringIO()):
-            query_book_cli.main(["--pool-query", "--submit-once"])
-        self.assertEqual(raised.exception.code, 2)
-        self.cloud.get_next_account.assert_not_called()
-        self.pipeline.assert_not_called()
 
 
 if __name__ == "__main__":