Files
cbb-refresh-verify-795/docs/superpowers/plans/2026-09-20-adaptive-dialog-supervision.md
T
阿白叔 11a2b2e46e Import CBB refresh verify r4 stability baseline
Preserve tested Verify source, authoritative READY checks, bounded bridge retries, diagnostics and failure-only reporting. Include 336-test suite and packaging assets; exclude live Mentor samples, field logs, backups and distributions.
2026-09-29 15:05:20 +08:00

578 lines
29 KiB
Markdown

# Adaptive Dialog Supervision Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Make CBB Verify discover, classify, and safely handle Mentor dialogs across machines without touching the user's foreground desktop, while preserving authoritative Project Integration and READY validation.
**Architecture:** A private-desktop dialog agent captures Win32 and UI Automation metadata and serves versioned JSONL requests. The parent `DialogSupervisor` applies phase-aware declarative rules, dispatches interface/UIA/Win32 actions in a fixed order, and writes complete evidence before failing an unknown item. Existing PCB COM, dynamic timeout, Job Object cleanup, and status bridge remain authoritative.
**Tech Stack:** Python 3.12, pywin32, pywinauto 0.6.x UIA backend, JSONL IPC, pytest, PyInstaller onedir
**Spec:** `docs/superpowers/specs/2026-09-20-adaptive-dialog-supervision-design.md`
## Global Constraints
- Windows desktop target; Python `>=3.12,<3.13`.
- Do not move the real cursor, inject keyboard input, activate foreground windows, or call `SwitchDesktop`. The only mouse-like fallback allowed is a private-desktop `WM_LBUTTONDOWN/WM_LBUTTONUP` message for the explicitly identified EE7.9.5 license selector HWND.
- Do not use screen coordinates, colors, OCR, timestamps, or dialog disappearance as final success evidence.
- Unknown dialogs are evidence-first failures for the current CBB and never receive a guessed default action.
- A PASS still requires PCB/PRJ identity, four Project Integration `InSynch` values, Validate/Save/IsSaved/Close success, no fatal dialog, and final status bridge `READY`.
- Do not call private Library Manager write exports and do not run concurrent Verify writes against one LMC.
- The project directory is not a Git repository as of 2026-09-20. Do not initialize Git implicitly; each task ends with a test checkpoint instead of a commit.
## File Map
- Create `src/cbb_refresh_verify/dialog_models.py`: immutable phases, control/window snapshots, fingerprints, decisions, and JSON conversion.
- Create `src/cbb_refresh_verify/dialog_rules.py`: schema validation, semantic normalization, rule matching, conflict detection, and packaged rule loading.
- Create `src/cbb_refresh_verify/assets/dialog_rules.v1.json`: default known-dialog rules only.
- Create `src/cbb_refresh_verify/dialog_probe.py`: unrestricted private-desktop Win32 discovery plus UIA enrichment; no policy.
- Create `src/cbb_refresh_verify/dialog_agent.py`: JSONL IPC loop on the private desktop and action-channel execution.
- Modify `src/cbb_refresh_verify/desktop_worker.py`: launch the agent on the same desktop and bind it to the same Job Object.
- Modify `src/cbb_refresh_verify/application.py`: hidden `--dialog-agent` entry point for source and frozen execution.
- Modify `src/cbb_refresh_verify/dialog_supervisor.py`: consume agent snapshots, run rules, verify postconditions, and expose structured outcomes.
- Modify `src/cbb_refresh_verify/verify_runner.py`: maintain phase, synchronize the agent, preserve evidence, and stop only the current item.
- Modify `src/cbb_refresh_verify/mentor_adapter.py`: emit explicit phase events and remove legacy dialog handling from real Verify paths.
- Modify `packaging/CbbRefreshVerify.spec`: package the rule file and UIA dependencies.
- Create `tests/test_dialog_models.py`, `tests/test_dialog_rules.py`, `tests/test_dialog_probe.py`, and `tests/test_dialog_agent.py`.
- Modify `tests/test_dialog_supervisor.py`, `tests/test_verify_runner.py`, `tests/test_safety.py`, and `tests/test_packaging.py`.
---
### Task 1: Stable Window Model and Rule Engine (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_models.py`
- Create: `src/cbb_refresh_verify/dialog_rules.py`
- Create: `src/cbb_refresh_verify/assets/dialog_rules.v1.json`
- Create: `tests/test_dialog_models.py`
- Create: `tests/test_dialog_rules.py`
**Interfaces:**
- Produces: `DialogPhase`, `ControlSnapshot`, `WindowSnapshot`, `DialogRule`, `RuleDecision`.
- Produces: `normalize_text(value: str) -> str`, `stable_fingerprint(snapshot: WindowSnapshot) -> str`.
- Produces: `load_rules(default_path: Path, override_path: Path | None) -> tuple[DialogRule, ...]`.
- Produces: `decide(snapshot: WindowSnapshot, rules: Sequence[DialogRule]) -> RuleDecision`.
- [x] **Step 1: Write model tests for stable fingerprints**
```python
def test_fingerprint_ignores_handle_pid_paths_and_elapsed_numbers():
first = snapshot(hwnd=10, pid=20, text=r"Elapsed time 11 C:\A\x.pcb")
second = snapshot(hwnd=99, pid=77, text=r"Elapsed time 42 D:\B\y.pcb")
assert stable_fingerprint(first) == stable_fingerprint(second)
def test_fingerprint_changes_for_control_shape():
assert stable_fingerprint(snapshot(control_types=("Button",))) != stable_fingerprint(
snapshot(control_types=("Button", "List")))
```
- [x] **Step 2: Run the model tests and confirm the missing-module failure**
Run: `python -m pytest tests/test_dialog_models.py -q`
Expected: FAIL because `cbb_refresh_verify.dialog_models` does not exist.
- [x] **Step 3: Implement immutable models and normalization**
Define exactly these public fields:
```python
class DialogPhase(str, Enum):
PCB_STARTING = "PCB_STARTING"
LICENSE_ACQUISITION = "LICENSE_ACQUISITION"
DATABASE_RECOVERY = "DATABASE_RECOVERY"
DOCUMENT_ATTACH = "DOCUMENT_ATTACH"
IDENTITY_CHECK = "IDENTITY_CHECK"
PROJECT_INTEGRATION = "PROJECT_INTEGRATION"
VALIDATE = "VALIDATE"
SAVE = "SAVE"
CLOSE = "CLOSE"
POST_VERIFY_STATUS = "POST_VERIFY_STATUS"
@dataclass(frozen=True)
class ControlSnapshot:
handle: int
control_id: int
class_name: str
name: str
automation_id: str = ""
control_type: str = ""
enabled: bool = True
selected: bool = False
checked: bool = False
patterns: tuple[str, ...] = ()
@dataclass(frozen=True)
class WindowSnapshot:
hwnd: int
pid: int
process_name: str
process_role: str
window_class: str
title: str
phase: DialogPhase
controls: tuple[ControlSnapshot, ...]
```
Normalize case, whitespace, elapsed numbers, GUIDs, drive/UNC paths and numeric handles before hashing. Keep original values in `to_record()`.
- [x] **Step 4: Write rule tests for phase, conflict, negative evidence, and override merging**
```python
def test_save_rule_does_not_match_during_license_phase(default_rules):
decision = decide(save_prompt(phase=DialogPhase.LICENSE_ACQUISITION), default_rules)
assert decision.error_code == "DIALOG_OUT_OF_PHASE"
def test_equal_priority_matches_are_rejected():
decision = decide(progress_prompt(), (matching_rule("a", 10), matching_rule("b", 10)))
assert decision.error_code == "DIALOG_RULE_CONFLICT"
def test_override_replaces_rule_by_id(tmp_path, default_path):
override = write_rules(tmp_path, [{"rule_id": "tip-of-day", "enabled": False}])
assert rule_by_id(load_rules(default_path, override), "tip-of-day").enabled is False
```
- [x] **Step 5: Implement strict rule parsing and matching**
Reject unknown schema versions, duplicate rule IDs, missing phases, unknown action channels, and malformed control predicates with `RULE_CONFIG_ERROR`. Merge overrides by `rule_id`; do not permit arbitrary Python expressions or executable commands.
- [x] **Step 6: Add initial packaged rules**
The JSON file must contain phase-scoped rules for `license-selector`, `database-restoration`, `open-lock-confirm`, `reusable-block-save`, `integration-progress`, `integration-error`, `save-error`, `design-server-error`, `database-load-error`, and `tip-of-day`. Each action rule must define a postcondition such as `window_gone`, `control_selected`, or `next_phase`.
- [x] **Step 7: Run the task tests**
Run: `python -m pytest tests/test_dialog_models.py tests/test_dialog_rules.py -q`
Expected: PASS.
- [x] **Step 8: Record the checkpoint**
Record the passing command and changed files in `docs/superpowers/plans/2026-09-20-adaptive-dialog-supervision.md` under a dated execution note. Do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_models.py tests/test_dialog_rules.py -q` -> `8 passed`.
### Task 2: Complete Win32 and UIA Discovery (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_probe.py`
- Create: `tests/test_dialog_probe.py`
- Modify: `tests/test_safety.py`
**Interfaces:**
- Consumes: `ControlSnapshot`, `WindowSnapshot`, `DialogPhase`.
- Produces: `WindowProbe.capture(phase: DialogPhase) -> tuple[WindowSnapshot, ...]`.
- Produces: `WindowProbe.capture_one(hwnd: int, phase: DialogPhase) -> WindowSnapshot | None`.
- [x] **Step 1: Write discovery tests**
```python
def test_probe_keeps_visible_non_dialog_classes(fake_windows):
fake_windows.add(hwnd=10, class_name="GXWND", visible=True)
assert [item.window_class for item in make_probe(fake_windows).capture(PHASE)] == ["GXWND"]
def test_disappearing_window_is_skipped_without_hiding_other_windows(fake_windows):
fake_windows.raise_on_title(10)
fake_windows.add(hwnd=20, class_name="#32770", visible=True)
assert [item.hwnd for item in make_probe(fake_windows).capture(PHASE)] == [20]
def test_uia_enrichment_records_patterns(fake_windows, fake_uia):
fake_uia.element(10, automation_id="licenseList", patterns=("SelectionItem",))
control = make_probe(fake_windows, fake_uia).capture(PHASE)[0].controls[0]
assert control.automation_id == "licenseList"
assert control.patterns == ("SelectionItem",)
```
- [x] **Step 2: Run the probe tests and confirm failure**
Run: `python -m pytest tests/test_dialog_probe.py -q`
Expected: FAIL because `WindowProbe` is not implemented.
- [x] **Step 3: Implement class-agnostic Win32 capture**
Enumerate all visible top-level windows from the supplied private desktop. Preserve the current WinError `0/2` empty-desktop behavior, explicitly return `True` from every enumeration callback, and surface other errors as `WINDOW_ENUM_ERROR`. Record process executable name with `OpenProcess/QueryFullProcessImageName`; failure to read a process name must leave it empty rather than discard the window.
- [x] **Step 4: Add bounded UIA enrichment**
Use pywinauto's UIA backend only around already discovered HWND values. Each UIA lookup gets a bounded call wrapper; on timeout or unsupported Pattern, keep the Win32 snapshot and append a probe diagnostic instead of dropping the window. Capture `Invoke`, `SelectionItem`, `Toggle`, `Value`, and `Window` availability.
- [x] **Step 5: Tighten safety tests**
Keep all existing forbidden APIs. Permit UIA wrapper methods `invoke`, `select`, and `toggle`; continue forbidding `click_input`, `type_keys`, `set_focus`, foreground activation, cursor APIs, keyboard APIs, and absolute-coordinate code. The only exception is the explicit private-desktop license-selector `WM_LBUTTONDOWN/WM_LBUTTONUP` fallback, which must remain target-scoped and tested.
- [x] **Step 6: Run tests**
Run: `python -m pytest tests/test_dialog_probe.py tests/test_safety.py -q`
Expected: PASS.
- [x] **Step 7: Record the checkpoint**
Append the passing command and files to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_probe.py tests/test_dialog_models.py tests/test_dialog_rules.py tests/test_safety.py -q` -> `16 passed`.
### Task 3: Private-Desktop Dialog Agent and JSONL Protocol (Complete)
**Files:**
- Create: `src/cbb_refresh_verify/dialog_agent.py`
- Create: `tests/test_dialog_agent.py`
- Modify: `src/cbb_refresh_verify/desktop_worker.py`
- Modify: `src/cbb_refresh_verify/application.py`
- Modify: `tests/test_application.py`
**Interfaces:**
- Consumes: `WindowProbe` and snapshot JSON conversion.
- Produces: `dialog_agent_main(config_path: Path) -> int`.
- Produces: `DialogAgentClient.start(worker: DesktopWorker, root: Path) -> DialogAgentClient`.
- Produces: `DialogAgentClient.observe(phase: DialogPhase) -> tuple[WindowSnapshot, ...]`.
- Produces: `DialogAgentClient.perform(hwnd: int, fingerprint: str, action: dict) -> ActionResult`.
- [x] **Step 1: Write protocol tests**
```python
def test_agent_correlates_observe_response_by_request_id(tmp_path, fake_probe):
client, server = in_process_protocol(tmp_path, fake_probe)
reply = client.observe(DialogPhase.PCB_STARTING)
assert reply[0].window_class == "GXWND"
assert server.requests[0]["request_id"] == server.responses[0]["request_id"]
def test_agent_rejects_stale_action_fingerprint(tmp_path, changing_probe):
result = agent(tmp_path, changing_probe).perform(10, "old", invoke_action())
assert result.error_code == "STALE_DIALOG"
```
- [x] **Step 2: Run protocol tests and confirm failure**
Run: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q`
Expected: FAIL for missing agent entry point and protocol classes.
- [x] **Step 3: Implement versioned JSONL envelopes**
Every request contains `schema_version=1`, `request_id`, `op`, `phase`, and `sent_at`. Every response echoes `request_id`, has a monotonic `sequence`, and contains either `result` or structured `error_code/detail`. Parse only complete newline-terminated JSON records and reject mismatched IDs with `DIALOG_PROTOCOL_ERROR`.
- [x] **Step 4: Implement safe actions in the agent**
Support only these declarative operations: `uia_invoke`, `uia_select`, `uia_toggle`, `win32_button_click`, and `observe`. Re-capture the target HWND and compare its stable fingerprint before acting. `win32_button_click` may only target a discovered enabled `Button`; it sends `BM_CLICK` and never cursor input.
- [x] **Step 5: Launch the agent on the same desktop and Job Object**
Add `DesktopWorker.start_companion(command)` using `CreateProcess` with the same `startup.lpDesktop` and `AssignProcessToJobObject`. The agent receives its IPC directory through a config file. Closing or terminating `DesktopWorker` must reap worker, PCB, helper, and agent.
- [x] **Step 6: Add the hidden application route**
Parse `--dialog-agent <config-path>` before Qt creation and call `dialog_agent_main`. Source mode uses `python -m cbb_refresh_verify --dialog-agent ...`; frozen mode uses `CbbRefreshVerify.exe --dialog-agent ...`.
- [x] **Step 7: Run tests**
Run: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q`
Expected: PASS, including companion cleanup and frozen command construction fakes.
- [x] **Step 8: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_agent.py tests/test_application.py -q` -> `7 passed`.
### Task 4: Phase-Aware Supervisor and Postconditions (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/dialog_supervisor.py`
- Modify: `tests/test_dialog_supervisor.py`
**Interfaces:**
- Consumes: `DialogAgentClient`, `load_rules`, `decide`, and `DialogPhase`.
- Produces: `DialogSupervisor.poll(phase: DialogPhase) -> DialogPollResult`.
- Produces error codes: `UNKNOWN_DIALOG`, `DIALOG_OUT_OF_PHASE`, `DIALOG_RULE_CONFLICT`, `DIALOG_ACTION_STUCK`, `DIALOG_PROTOCOL_ERROR`.
- [x] **Step 1: Replace text-only classification tests with phase-aware rule tests**
```python
def test_unknown_dialog_fails_without_action(supervisor, backend):
backend.observe_result = (unknown_gxwnd(),)
result = supervisor.poll(DialogPhase.PCB_STARTING)
assert result.error_code == "UNKNOWN_DIALOG"
assert backend.actions == []
def test_sent_action_is_pending_until_postcondition(supervisor, backend):
backend.observe_result = (restore_prompt(selected=False),)
assert supervisor.poll(DialogPhase.DATABASE_RECOVERY).action_sent
backend.observe_result = (restore_prompt(selected=True),)
assert supervisor.poll(DialogPhase.DATABASE_RECOVERY).activity
```
- [x] **Step 2: Run the supervisor tests and confirm failure**
Run: `python -m pytest tests/test_dialog_supervisor.py -q`
Expected: FAIL because the existing supervisor accepts no phase and hardcodes text rules.
- [x] **Step 3: Rebuild supervisor state around rule IDs and postconditions**
Key pending actions by `(fingerprint, rule_id)` rather than HWND alone. Mark resolution only when `window_gone`, `control_selected`, `control_enabled`, `signature_changed`, or `next_phase` is observed. Reused HWND with a new fingerprint is a new window state.
- [x] **Step 4: Preserve fatal-result precedence**
For `FATAL_ACK`, perform the configured acknowledgement only to unblock cleanup, return the rule's fatal error immediately, and never allow later Save/Close events to overwrite it. For `OBSERVE_PROGRESS`, state changes count as activity but the Cancel control is never invoked.
- [x] **Step 5: Run tests**
Run: `python -m pytest tests/test_dialog_supervisor.py -q`
Expected: PASS for standard dialogs, GXWND, progress, fatal, unknown, phase mismatch, rule conflict, delayed initialization, reused handles, and bounded retries.
- [x] **Step 6: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_dialog_supervisor.py tests/test_dialog_agent.py tests/test_dialog_rules.py -q` -> `27 passed`.
### Task 5: Verify Runner Integration and Evidence Closure (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/verify_runner.py`
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Modify: `tests/test_verify_runner.py`
- Modify: `tests/test_integration.py`
**Interfaces:**
- Consumes: `DialogAgentClient`, phase-aware `DialogSupervisor`.
- Produces evidence: `window_snapshots.jsonl`, `dialogs.jsonl`, `process_tree.json`, `events.jsonl`, `worker.log`, `save.log`, `result.json`.
- Preserves: `run_verify(request, ...) -> VerifyResult` and batch skip-on-failure behavior.
- [x] **Step 1: Write integration tests for phase mapping and evidence**
```python
def test_worker_stage_advances_dialog_phase():
assert phase_for_event({"stage": "pcb_launch"}) is DialogPhase.PCB_STARTING
assert phase_for_event({"stage": "integration_status"}) is DialogPhase.PROJECT_INTEGRATION
assert phase_for_event({"stage": "save_start"}) is DialogPhase.SAVE
def test_unknown_dialog_writes_snapshot_before_current_item_fails(tmp_path, fake_worker):
result = run_verify(request(tmp_path), dialog_supervisor_factory=unknown_supervisor)
assert result.status == "FAIL"
assert "UNKNOWN_DIALOG" in result.stderr
assert (result.evidence_path.parent / "window_snapshots.jsonl").is_file()
```
- [x] **Step 2: Run focused integration tests and confirm failure**
Run: `python -m pytest tests/test_verify_runner.py tests/test_integration.py -q`
Expected: FAIL for missing phase mapping and evidence writer behavior.
- [x] **Step 3: Add deterministic worker-stage to dialog-phase mapping**
Map startup and `pcb_started` to `PCB_STARTING`, license evidence to `LICENSE_ACQUISITION`, attach polling to `DOCUMENT_ATTACH`, identity completion to `IDENTITY_CHECK`, integration events to `PROJECT_INTEGRATION`, `save_start/save_helper` to `SAVE`, `saved_and_closed` to `CLOSE`, and authoritative flag reread to `POST_VERIFY_STATUS`. Unknown worker stages retain the last phase and are logged.
- [x] **Step 4: Start and supervise the dialog agent**
Start the companion immediately after `DesktopWorker`, before PCB launch can create a modal. Poll the agent every existing 200 ms loop iteration. Write every new or changed snapshot to `window_snapshots.jsonl`; write decisions/actions/errors to `dialogs.jsonl`.
- [x] **Step 5: Make unknown/fatal handling fail only the current item**
On a dialog error, flush evidence, terminate the job tree, write a FAIL `result.json` with `safe_to_continue=true`, and let `run_batch` proceed. Do not wait for the inactivity timeout once an unknown snapshot has been saved.
- [x] **Step 6: Remove legacy Verify dialog handling**
Delete real Verify calls to `handle_known_dialogs()` and `choose_dialog_action()`. Retain any compatibility functions needed by historical read-only probes under explicit `legacy_` names, add deprecation comments, and assert in tests that `execute_job()` does not reference them.
- [x] **Step 7: Preserve the authoritative PASS gate**
Add regression coverage proving that dialog resolution cannot create PASS, a fatal dialog overrides later save markers, and final status bridge `PENDING/UNKNOWN` converts an otherwise successful run to FAIL.
- [x] **Step 8: Run focused tests**
Run: `python -m pytest tests/test_verify_runner.py tests/test_integration.py tests/test_pcb_bridge.py -q`
Expected: PASS.
- [x] **Step 9: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_verify_runner.py tests/test_integration.py tests/test_pcb_bridge.py -q` -> `52 passed`.
### Task 6: License Interface First, UIA Fallback Second (Complete)
**Files:**
- Modify: `src/cbb_refresh_verify/mentor_adapter.py`
- Modify: `src/cbb_refresh_verify/pcb_bridge.py`
- Modify: `src/cbb_refresh_verify/assets/dialog_rules.v1.json`
- Create: `tests/test_automation_license.py`
**Interfaces:**
- Produces: `validate_document(doc, license_factory, emit) -> None`.
- Uses official sequence: `key = doc.Validate(0)`, `token = license_factory().GetToken(key)`, `doc.Validate(token)`.
- Falls back to rule `license-selector` only for known COM unavailability HRESULTs.
- [x] **Step 1: Write official licensing tests**
```python
def test_validate_uses_official_automation_token():
doc = FakeDocument(validate_results=(1234, True))
license_app = FakeLicenseApp(token=5678)
validate_document(doc, lambda: license_app, emit=lambda **event: None)
assert doc.validate_calls == [0, 5678]
assert license_app.keys == [1234]
def test_validation_business_error_does_not_fall_back_to_ui():
with pytest.raises(AutomationLicenseError) as error:
validate_document(BusinessErrorDocument(), factory, emit=noop)
assert error.value.fallback_allowed is False
```
- [x] **Step 2: Run the licensing tests and confirm failure**
Run: `python -m pytest tests/test_automation_license.py -q`
Expected: FAIL because `validate_document` does not implement the official token flow.
- [x] **Step 3: Implement the official token flow**
Create `MGCPCBAutomationLicensing.Application` only after the target document identity is confirmed. Emit `license_key_requested`, `license_token_received` without logging the token value, and `document_validated`. Classify COM registration/server-unavailable errors as fallback-eligible; classify rejected token and document validation errors as fatal.
- [x] **Step 4: Restrict the UIA fallback**
Allow `license-selector` only during `LICENSE_ACQUISITION`, only when the window contains the known selector structure, and only after the COM event explicitly reports fallback eligibility. Require unique selectable license evidence, selected state, enabled OK, and window disappearance.
- [x] **Step 5: Run tests**
Run: `python -m pytest tests/test_automation_license.py tests/test_dialog_rules.py tests/test_dialog_supervisor.py -q`
Expected: PASS.
- [x] **Step 6: Record the checkpoint**
Append test evidence to the execution note; do not initialize Git.
Execution note 2026-09-20: `python -m pytest tests/test_automation_license.py tests/test_dialog_agent.py tests/test_pcb_bridge.py -q` -> `14 passed`.
### Task 7: Packaging, Safety, and Full Automated Regression
**Files:**
- Modify: `packaging/CbbRefreshVerify.spec`
- Modify: `tests/test_packaging.py`
- Modify: `tests/test_safety.py`
- Modify: `tests/test_application.py`
**Interfaces:**
- Packages: `cbb_refresh_verify/assets/dialog_rules.v1.json`, pywinauto UIA backend imports, and dialog-agent modules.
- Preserves executable name: `CbbRefreshVerify-Background/CbbRefreshVerify.exe`.
- [ ] **Step 1: Write packaging assertions**
```python
def test_spec_packages_dialog_rules_and_uia_backend():
text = Path("packaging/CbbRefreshVerify.spec").read_text(encoding="utf-8")
assert "dialog_rules.v1.json" in text
assert "pywinauto" in text
def test_frozen_dialog_agent_route_does_not_create_qt(monkeypatch, tmp_path):
assert application.main(["--dialog-agent", str(agent_config(tmp_path))]) == 0
assert not qt_was_imported()
```
- [ ] **Step 2: Run packaging and safety tests and confirm failure**
Run: `python -m pytest tests/test_packaging.py tests/test_safety.py tests/test_application.py -q`
Expected: FAIL until the spec and hidden route are complete.
- [ ] **Step 3: Update the PyInstaller spec**
Add the JSON rule file to `datas`; add only the pywinauto UIA modules required by the probe to hidden imports. Do not copy test evidence, historical screenshots, data archives, or build directories into the release.
- [ ] **Step 4: Run the entire automated suite**
Run: `python -m pip install -e .`
Run: `python -m pytest -q`
Expected: all tests PASS. The previous subprocess `ModuleNotFoundError: cbb_refresh_verify` must no longer occur after editable installation.
- [ ] **Step 5: Build into a new validation directory**
Run: `powershell -ExecutionPolicy Bypass -File packaging/Build-CbbRefreshVerify.ps1 -OutputDirectory dist-dialog-validation`
Expected: exit code 0, frozen smoke test PASS, and `dist-dialog-validation/CbbRefreshVerify-Background/CbbRefreshVerify.exe` exists. Do not overwrite `dist-optimized` yet.
- [ ] **Step 6: Inspect release contents**
Run: `Get-ChildItem -Recurse -LiteralPath dist-dialog-validation/CbbRefreshVerify-Background | Measure-Object -Property Length -Sum`
Expected: one application directory containing the executable, runtime dependencies, the green-check icon assets, status bridge, save script, and dialog rule file; no `data`, `evidence`, `build`, `.zip`, or `.rar` payloads.
- [ ] **Step 7: Record the checkpoint**
Append the full test count, build path, executable size, and directory size to the execution note; do not initialize Git.
### Task 8: Local Single-CBB Acceptance Before Release
**Files:**
- Runtime output only: `build/acceptance-dialog-<timestamp>/`
- Promote only after PASS: `dist-optimized/CbbRefreshVerify-Background/`
**Interfaces:**
- Uses LMC: `F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc`.
- Uses block: `2GPHY_ZX5201`.
- Uses Mentor root: `D:\Mentor\7.9.5EE\SDD_HOME`.
- [ ] **Step 1: Confirm the pre-run authoritative state and input files**
Run the authoritative read-only status bridge:
```powershell
$env:CBB_STATUS_BRIDGE_ALLOW_PRIVATE = '1'
python -c "from pathlib import Path; from cbb_refresh_verify.status_bridge import StatusBridgeClient; print(StatusBridgeClient().query(Path(r'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc'), '2GPHY_ZX5201'))"
```
Then require all three inputs:
```powershell
$block = 'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\ReusableBlocksLP\2GPHY_ZX5201\Work'
@(
"$block\2GPHY_ZX5201.prj",
"$block\PCB\2GPHY_ZX5201.pcb",
"$block\PCB\Layout\LayoutDB.lyt"
) | ForEach-Object { if (-not (Test-Path -LiteralPath $_)) { throw "Missing acceptance input: $_" } }
```
Record the pre-run status and paths in the acceptance directory. Do not alter the CBB when prerequisites are missing.
- [ ] **Step 2: Run exactly one CBB from the validation build**
Run:
```powershell
& 'dist-dialog-validation\CbbRefreshVerify-Background\CbbRefreshVerify.exe' `
--batch-lmc 'F:\Sync Tool Skyworth\Work Maps\Skyworth_CBB_Lib\Mentor_lib_EE7.9\mentor_lib.lmc' `
--block '2GPHY_ZX5201' `
--mentor-bin 'D:\Mentor\7.9.5EE\SDD_HOME'
```
Expected: the foreground desktop does not switch, cursor and keyboard remain untouched, and only one PCB job exists.
- [ ] **Step 3: Inspect the evidence before claiming success**
Require nonempty `events.jsonl`, `window_snapshots.jsonl`, `worker.log`, `save.log`, and `result.json`. `dialogs.jsonl` may be absent only when no dialog appeared; if present, every action must name its `rule_id`, phase, channel, target, and satisfied postcondition.
- [ ] **Step 4: Apply the acceptance gate**
PASS requires the exact target PCB/PRJ identity, all four Project Integration statuses `InSynch`, official validation completion, Save/IsSaved/Close completion, no fatal/unknown/conflict/out-of-phase dialog, process-tree cleanup, and post-run status bridge `READY`. Any missing condition is a failed acceptance, even if the GUI appears green.
- [ ] **Step 5: Test one controlled unknown window only after the normal run**
Use a test fixture window on a disposable private-desktop run, not a production Mentor prompt. Confirm `UNKNOWN_DIALOG`, zero actions, immediate current-item failure, complete snapshot/UIA evidence, and no effect on the foreground desktop.
- [ ] **Step 6: Promote the build only after acceptance**
Preserve the previous `dist-optimized` release as the one retained rollback artifact, copy the accepted validation build into the release location, and remove only superseded project-generated validation builds after verifying their resolved paths remain under the project directory. Never delete user-provided `data.zip`, `data.rar`, logs, or evidence.
- [ ] **Step 7: Record the final checkpoint**
Write the exact executable path, build timestamp, test count, single-CBB result, status-bridge before/after values, and evidence directory into the execution note. Because the directory has no Git metadata, explicitly state that no commit hash exists.