claude-code-pilot 3.2.0 → 3.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +14 -9
  3. package/bin/install.js +124 -16
  4. package/manifest.json +18 -3
  5. package/package.json +3 -2
  6. package/src/agents/django-build-resolver.md +252 -0
  7. package/src/agents/django-reviewer.md +169 -0
  8. package/src/agents/fastapi-reviewer.md +79 -0
  9. package/src/agents/fsharp-reviewer.md +109 -0
  10. package/src/agents/swift-build-resolver.md +170 -0
  11. package/src/agents/swift-reviewer.md +116 -0
  12. package/src/commands/ccp/cost-report.md +107 -0
  13. package/src/commands/ccp/intel.md +3 -3
  14. package/src/commands/ccp/mvp-phase.md +45 -0
  15. package/src/commands/ccp/plan-prd.md +160 -0
  16. package/src/commands/ccp/pr-ecc.md +184 -0
  17. package/src/commands/ccp/security-scan.md +74 -0
  18. package/src/hooks/ccp-bash-hook-dispatcher.js +96 -0
  19. package/src/hooks/ccp-context-monitor.js +23 -0
  20. package/src/hooks/ccp-doc-file-warning.js +93 -0
  21. package/src/hooks/ccp-pre-bash-dispatcher.js +24 -0
  22. package/src/hooks/ccp-write-gateguard.js +868 -0
  23. package/src/lib/project-detect.js +0 -2
  24. package/src/lib/shell-substitution.js +499 -0
  25. package/src/pilot/references/execute-mvp-tdd.md +81 -0
  26. package/src/pilot/references/mvp-concepts.md +49 -0
  27. package/src/pilot/references/planner-graphify-auto-update.md +67 -0
  28. package/src/pilot/references/planner-human-verify-mode.md +57 -0
  29. package/src/pilot/references/planner-mvp-mode.md +53 -0
  30. package/src/pilot/references/skeleton-template.md +48 -0
  31. package/src/pilot/references/spidr-splitting.md +69 -0
  32. package/src/pilot/references/user-story-template.md +58 -0
  33. package/src/pilot/references/verify-mvp-mode.md +85 -0
  34. package/src/pilot/references/worktree-path-safety.md +89 -0
  35. package/src/pilot/workflows/help.md +5 -0
  36. package/src/pilot/workflows/mvp-phase.md +199 -0
  37. package/src/skills/agent-architecture-audit/SKILL.md +256 -0
  38. package/src/skills/agent-harness-design/SKILL.md +73 -0
  39. package/src/skills/angular-developer/SKILL.md +154 -0
  40. package/src/skills/angular-developer/references/angular-animations.md +160 -0
  41. package/src/skills/angular-developer/references/angular-aria.md +410 -0
  42. package/src/skills/angular-developer/references/cli.md +86 -0
  43. package/src/skills/angular-developer/references/component-harnesses.md +59 -0
  44. package/src/skills/angular-developer/references/component-styling.md +91 -0
  45. package/src/skills/angular-developer/references/components.md +117 -0
  46. package/src/skills/angular-developer/references/creating-services.md +97 -0
  47. package/src/skills/angular-developer/references/data-resolvers.md +69 -0
  48. package/src/skills/angular-developer/references/define-routes.md +67 -0
  49. package/src/skills/angular-developer/references/defining-providers.md +72 -0
  50. package/src/skills/angular-developer/references/di-fundamentals.md +120 -0
  51. package/src/skills/angular-developer/references/e2e-testing.md +56 -0
  52. package/src/skills/angular-developer/references/effects.md +83 -0
  53. package/src/skills/angular-developer/references/hierarchical-injectors.md +43 -0
  54. package/src/skills/angular-developer/references/host-elements.md +80 -0
  55. package/src/skills/angular-developer/references/injection-context.md +63 -0
  56. package/src/skills/angular-developer/references/inputs.md +101 -0
  57. package/src/skills/angular-developer/references/linked-signal.md +59 -0
  58. package/src/skills/angular-developer/references/loading-strategies.md +61 -0
  59. package/src/skills/angular-developer/references/mcp.md +108 -0
  60. package/src/skills/angular-developer/references/navigate-to-routes.md +69 -0
  61. package/src/skills/angular-developer/references/outputs.md +86 -0
  62. package/src/skills/angular-developer/references/reactive-forms.md +122 -0
  63. package/src/skills/angular-developer/references/rendering-strategies.md +44 -0
  64. package/src/skills/angular-developer/references/resource.md +77 -0
  65. package/src/skills/angular-developer/references/route-animations.md +56 -0
  66. package/src/skills/angular-developer/references/route-guards.md +52 -0
  67. package/src/skills/angular-developer/references/router-lifecycle.md +45 -0
  68. package/src/skills/angular-developer/references/router-testing.md +87 -0
  69. package/src/skills/angular-developer/references/show-routes-with-outlets.md +68 -0
  70. package/src/skills/angular-developer/references/signal-forms.md +795 -0
  71. package/src/skills/angular-developer/references/signals-overview.md +94 -0
  72. package/src/skills/angular-developer/references/tailwind-css.md +69 -0
  73. package/src/skills/angular-developer/references/template-driven-forms.md +114 -0
  74. package/src/skills/angular-developer/references/testing-fundamentals.md +65 -0
  75. package/src/skills/error-handling/SKILL.md +376 -0
  76. package/src/skills/fastapi-patterns/SKILL.md +327 -0
  77. package/src/skills/flox-environments/SKILL.md +496 -0
  78. package/src/skills/fsharp-testing/SKILL.md +280 -0
  79. package/src/skills/ios-icon-gen/SKILL.md +157 -0
  80. package/src/skills/ios-icon-gen/scripts/generate_icons.swift +258 -0
  81. package/src/skills/ios-icon-gen/scripts/iconify_gen.sh +235 -0
  82. package/src/skills/make-interfaces-feel-better/SKILL.md +151 -0
  83. package/src/skills/mysql-patterns/SKILL.md +412 -0
  84. package/src/skills/plan-orchestrate/SKILL.md +220 -0
  85. package/src/skills/prisma-patterns/SKILL.md +371 -0
  86. package/src/skills/production-audit/SKILL.md +206 -0
  87. package/src/skills/security-scan/references/agentshield-policy-exception/candidate-playbook.md +49 -0
  88. package/src/skills/security-scan/references/agentshield-policy-exception/report.json +35 -0
  89. package/src/skills/security-scan/references/agentshield-policy-exception/scenario.json +62 -0
  90. package/src/skills/security-scan/references/agentshield-policy-exception/trace.json +45 -0
  91. package/src/skills/security-scan/references/agentshield-policy-exception/verifier-result.json +35 -0
  92. package/src/skills/vite-patterns/SKILL.md +449 -0
  93. package/src/skills/windows-desktop-e2e/SKILL.md +887 -0
@@ -0,0 +1,887 @@
1
+ ---
2
+ name: windows-desktop-e2e
3
+ description: E2E testing for Windows native desktop apps (WPF, WinForms, Win32/MFC, Qt) using pywinauto and Windows UI Automation.
4
+ origin: ECC
5
+ ---
6
+
7
+ # Windows Desktop E2E Testing
8
+
9
+ End-to-end testing for Windows native desktop applications using **pywinauto** backed by Windows UI Automation (UIA). Covers WPF, WinForms, Win32/MFC, and Qt (5.x / 6.x) — with Qt-specific guidance as a dedicated section.
10
+
11
+ ## When to Activate
12
+
13
+ - Writing or running E2E tests for a Windows native desktop application
14
+ - Setting up a desktop GUI test suite from scratch
15
+ - Diagnosing flaky or failing desktop automation tests
16
+ - Adding testability (AutomationId, accessible names) to an existing app
17
+ - Integrating desktop E2E into a CI/CD pipeline (GitHub Actions `windows-latest`)
18
+
19
+ ### When NOT to Use
20
+
21
+ - Web applications → use `e2e-testing` skill (Playwright)
22
+ - Electron / CEF / WebView2 apps → the HTML layer needs browser automation, not UIA
23
+ - Mobile apps → use platform-specific tools (UIAutomator, XCUITest)
24
+ - Pure unit or integration tests that don't need a running GUI
25
+
26
+ ## Core Concepts
27
+
28
+ All Windows desktop automation relies on **UI Automation (UIA)**, a Windows-built-in accessibility API. Every supported framework exposes a tree of UIA elements with properties Claude can read and act on:
29
+
30
+ ```
31
+ Your test (Python)
32
+ └── pywinauto (UIA backend)
33
+ └── Windows UI Automation API ← built into Windows, framework-agnostic
34
+ └── App's UIA provider ← each framework ships its own
35
+ └── Running .exe
36
+ ```
37
+
38
+ **UIA quality by framework:**
39
+
40
+ | Framework | AutomationId | Reliability | Notes |
41
+ |-----------|-------------|-------------|-------|
42
+ | WPF | ★★★★★ | Excellent | `x:Name` maps directly to AutomationId |
43
+ | WinForms | ★★★★☆ | Good | `AccessibleName` = AutomationId |
44
+ | UWP / WinUI 3 | ★★★★★ | Excellent | Full Microsoft support |
45
+ | Qt 6.x | ★★★★★ | Excellent | Accessibility enabled by default; class names change to `Qt6*` |
46
+ | Qt 5.15+ | ★★★★☆ | Good | Improved Accessibility module |
47
+ | Qt 5.7–5.14 | ★★★☆☆ | Fair | Needs `QT_ACCESSIBILITY=1`; objectName manual |
48
+ | Win32 / MFC | ★★★☆☆ | Fair | Control IDs accessible; text matching common |
49
+
50
+ ## Setup & Prerequisites
51
+
52
+ ```bash
53
+ # Python 3.8+, Windows only
54
+ pip install pywinauto pytest pytest-html Pillow pytest-timeout
55
+ # Optional: screen recording
56
+ # Install ffmpeg and add to PATH: https://ffmpeg.org/download.html
57
+ ```
58
+
59
+ Verify UIA is reachable:
60
+
61
+ ```python
62
+ from pywinauto import Desktop
63
+ Desktop(backend="uia").windows() # lists all top-level windows
64
+ ```
65
+
66
+ Install **Accessibility Insights for Windows** (free, from Microsoft) — your DevTools equivalent for inspecting the UIA element tree before writing any test.
67
+
68
+ ## Testability Setup (by Framework)
69
+
70
+ The single most impactful thing you can do is **give every interactive control a stable AutomationId** before writing tests.
71
+
72
+ ### WPF
73
+
74
+ ```xml
75
+ <!-- XAML: x:Name becomes AutomationId automatically -->
76
+ <TextBox x:Name="usernameInput" />
77
+ <PasswordBox x:Name="passwordInput" />
78
+ <Button x:Name="btnLogin" Content="Login" />
79
+ <TextBlock x:Name="lblError" />
80
+ ```
81
+
82
+ ### WinForms
83
+
84
+ ```csharp
85
+ // Set in designer or code
86
+ usernameInput.AccessibleName = "usernameInput";
87
+ passwordInput.AccessibleName = "passwordInput";
88
+ btnLogin.AccessibleName = "btnLogin";
89
+ lblError.AccessibleName = "lblError";
90
+ ```
91
+
92
+ ### Win32 / MFC
93
+
94
+ ```cpp
95
+ // Control resource IDs in .rc file are exposed as AutomationId strings
96
+ // IDC_EDIT_USERNAME -> AutomationId "1001"
97
+ // Prefer SetWindowText for Name; add IAccessible for richer support
98
+ ```
99
+
100
+ ### Qt — see dedicated section below
101
+
102
+ ---
103
+
104
+ ## Page Object Model
105
+
106
+ ```
107
+ tests/
108
+ ├── conftest.py # app launch fixture, failure screenshot
109
+ ├── pytest.ini
110
+ ├── config.py
111
+ ├── pages/
112
+ │ ├── __init__.py # required for imports
113
+ │ ├── base_page.py # locators, wait, screenshot helpers
114
+ │ ├── login_page.py
115
+ │ └── main_page.py
116
+ ├── tests/
117
+ │ ├── __init__.py
118
+ │ ├── test_login.py
119
+ │ └── test_main_flow.py
120
+ └── artifacts/ # screenshots, videos, logs
121
+ ```
122
+
123
+ ### base_page.py
124
+
125
+ ```python
126
+ import os, time
127
+ from pywinauto import Desktop
128
+ from config import ACTION_TIMEOUT, ARTIFACT_DIR
129
+
130
+ class BasePage:
131
+ def __init__(self, window):
132
+ self.window = window
133
+
134
+ # --- Locators (priority order) ---
135
+
136
+ def by_id(self, auto_id, **kw):
137
+ """AutomationId — most stable. Use as first choice."""
138
+ return self.window.child_window(auto_id=auto_id, **kw)
139
+
140
+ def by_name(self, name, **kw):
141
+ """Visible text / accessible name."""
142
+ return self.window.child_window(title=name, **kw)
143
+
144
+ def by_class(self, cls, index=0, **kw):
145
+ """Control class + index — fragile, avoid if possible."""
146
+ return self.window.child_window(class_name=cls, found_index=index, **kw)
147
+
148
+ # --- Waits ---
149
+
150
+ def wait_visible(self, spec, timeout=ACTION_TIMEOUT):
151
+ spec.wait("visible", timeout=timeout)
152
+ return spec
153
+
154
+ def wait_gone(self, spec, timeout=ACTION_TIMEOUT):
155
+ spec.wait_not("visible", timeout=timeout)
156
+ return spec
157
+
158
+ def wait_window(self, title, timeout=ACTION_TIMEOUT):
159
+ """Wait for a new top-level window (dialogs, child windows)."""
160
+ dlg = Desktop(backend="uia").window(title=title)
161
+ dlg.wait("visible", timeout=timeout)
162
+ return dlg
163
+
164
+ def wait_until(self, fn, timeout=ACTION_TIMEOUT, interval=0.3):
165
+ """Poll an arbitrary condition — use when UIA events are unreliable."""
166
+ deadline = time.time() + timeout
167
+ while time.time() < deadline:
168
+ try:
169
+ if fn():
170
+ return True
171
+ except Exception:
172
+ pass
173
+ time.sleep(interval)
174
+ raise TimeoutError(f"Condition not met within {timeout}s")
175
+
176
+ # --- Actions ---
177
+
178
+ def click(self, spec):
179
+ self.wait_visible(spec)
180
+ spec.click_input()
181
+
182
+ def type_text(self, spec, text):
183
+ self.wait_visible(spec)
184
+ ctrl = spec.wrapper_object()
185
+ try:
186
+ ctrl.set_edit_text(text)
187
+ except Exception as e:
188
+ # Qt 5.x fallback: UIA Value Pattern may be incomplete
189
+ import sys, pywinauto.keyboard as kb
190
+ print(f"[windows-desktop-e2e] set_edit_text failed ({e}), using keyboard fallback", file=sys.stderr)
191
+ ctrl.click_input()
192
+ kb.send_keys("^a")
193
+ kb.send_keys(text, with_spaces=True)
194
+
195
+ def get_text(self, spec):
196
+ ctrl = spec.wrapper_object()
197
+ for attr in ("window_text", "get_value"):
198
+ try:
199
+ v = getattr(ctrl, attr)()
200
+ if v:
201
+ return v
202
+ except Exception:
203
+ pass
204
+ return ""
205
+
206
+ # --- Artifacts ---
207
+
208
+ def screenshot(self, name):
209
+ os.makedirs(ARTIFACT_DIR, exist_ok=True)
210
+ path = os.path.join(ARTIFACT_DIR, f"{name}.png")
211
+ self.window.capture_as_image().save(path)
212
+ return path
213
+ ```
214
+
215
+ ### login_page.py
216
+
217
+ ```python
218
+ from pages.base_page import BasePage
219
+
220
+ class LoginPage(BasePage):
221
+ @property
222
+ def username(self): return self.by_id("usernameInput")
223
+
224
+ @property
225
+ def password(self): return self.by_id("passwordInput")
226
+
227
+ @property
228
+ def btn_login(self): return self.by_id("btnLogin")
229
+
230
+ @property
231
+ def error_label(self): return self.by_id("lblError")
232
+
233
+ def login(self, user, pwd):
234
+ self.type_text(self.username, user)
235
+ self.type_text(self.password, pwd)
236
+ self.click(self.btn_login)
237
+
238
+ def login_ok(self, user, pwd, main_title="Main Window"):
239
+ self.login(user, pwd)
240
+ return self.wait_window(main_title)
241
+
242
+ def login_fail(self, user, pwd):
243
+ self.login(user, pwd)
244
+ self.wait_visible(self.error_label)
245
+ return self.get_text(self.error_label)
246
+ ```
247
+
248
+ ### conftest.py
249
+
250
+ > For new projects prefer the **Tier 1 sandbox fixture** (see below) — it adds filesystem isolation at zero extra cost. This basic fixture is for minimal/legacy setups only.
251
+
252
+ ```python
253
+ import os, pytest
254
+ os.environ["QT_ACCESSIBILITY"] = "1" # Required for Qt 5.x UIA support
255
+
256
+ from pywinauto import Application
257
+ from config import APP_PATH, MAIN_WINDOW_TITLE, LAUNCH_TIMEOUT, ARTIFACT_DIR
258
+
259
+ @pytest.fixture
260
+ def app(request):
261
+ if not APP_PATH:
262
+ pytest.exit("APP_PATH environment variable is not set", returncode=1)
263
+ proc = Application(backend="uia").start(APP_PATH, timeout=LAUNCH_TIMEOUT)
264
+ win = proc.window(title=MAIN_WINDOW_TITLE)
265
+ win.wait("visible", timeout=LAUNCH_TIMEOUT)
266
+ yield win
267
+ # Screenshot on failure
268
+ if getattr(getattr(request.node, "rep_call", None), "failed", False):
269
+ os.makedirs(ARTIFACT_DIR, exist_ok=True)
270
+ try:
271
+ win.capture_as_image().save(
272
+ os.path.join(ARTIFACT_DIR, f"FAIL_{request.node.name}.png")
273
+ )
274
+ except Exception:
275
+ pass
276
+ # Graceful exit first, force-kill as fallback
277
+ # proc is a pywinauto Application — use wait_for_process_exit(), not wait_for_process()
278
+ try:
279
+ win.close()
280
+ proc.wait_for_process_exit(timeout=5)
281
+ except Exception:
282
+ proc.kill()
283
+
284
+ @pytest.hookimpl(tryfirst=True, hookwrapper=True)
285
+ def pytest_runtest_makereport(item, call):
286
+ outcome = yield
287
+ setattr(item, f"rep_{outcome.get_result().when}", outcome.get_result())
288
+ ```
289
+
290
+ ### config.py
291
+
292
+ ```python
293
+ import os
294
+ APP_PATH = os.environ.get("APP_PATH", "") # set via env — no default path
295
+ MAIN_WINDOW_TITLE = os.environ.get("APP_TITLE", "")
296
+ LAUNCH_TIMEOUT = int(os.environ.get("LAUNCH_TIMEOUT", "15"))
297
+ ACTION_TIMEOUT = int(os.environ.get("ACTION_TIMEOUT", "10"))
298
+ ARTIFACT_DIR = os.path.join(os.path.dirname(__file__), "artifacts")
299
+ ```
300
+
301
+ ### pytest.ini
302
+
303
+ ```ini
304
+ [pytest]
305
+ testpaths = tests
306
+ markers =
307
+ smoke: fast smoke tests for critical paths
308
+ flaky: known-unstable tests
309
+ addopts = -v --tb=short --html=artifacts/report.html --self-contained-html
310
+ ```
311
+
312
+ ## Locator Strategy
313
+
314
+ ```
315
+ AutomationId > Name (text) > ClassName + index > XPath
316
+ (stable) (readable) (fragile) (last resort)
317
+ ```
318
+
319
+ Inspect with Accessibility Insights → **Properties** pane → look for `AutomationId` first.
320
+
321
+ ```python
322
+ # Inspect at runtime — paste into a REPL to explore the tree
323
+ win.print_control_identifiers()
324
+ # or narrow scope:
325
+ win.child_window(auto_id="groupBox1").print_control_identifiers()
326
+ ```
327
+
328
+ ## Wait Patterns
329
+
330
+ ```python
331
+ # Wait for control to appear
332
+ page.wait_visible(page.by_id("statusLabel"))
333
+
334
+ # Wait for control to disappear (e.g. loading spinner)
335
+ page.wait_gone(page.by_id("spinnerOverlay"))
336
+
337
+ # Wait for a dialog to pop up
338
+ dlg = page.wait_window("Confirm Delete")
339
+
340
+ # Custom condition (e.g. text changes)
341
+ page.wait_until(lambda: page.get_text(page.by_id("lblStatus")) == "Ready")
342
+ ```
343
+
344
+ **Never use `time.sleep()` as primary synchronization** — use `wait()` or `wait_until()`.
345
+
346
+ ## Artifact Management
347
+
348
+ ```python
349
+ # Screenshot on demand
350
+ page.screenshot("after_login")
351
+
352
+ # Full-screen capture (when window is off-screen or minimised)
353
+ import pyautogui
354
+ pyautogui.screenshot("artifacts/fullscreen.png")
355
+
356
+ # Screen recording with ffmpeg (start before test, stop after)
357
+ import subprocess
358
+
359
+ def start_recording(name):
360
+ return subprocess.Popen([
361
+ "ffmpeg", "-f", "gdigrab", "-framerate", "10",
362
+ "-i", "desktop", "-y", f"artifacts/videos/{name}.mp4"
363
+ ], stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
364
+
365
+ def stop_recording(proc):
366
+ proc.stdin.write(b"q"); proc.stdin.flush(); proc.wait(timeout=10)
367
+ ```
368
+
369
+ ## Per-Step Trace (opt-in)
370
+
371
+ The default failure screenshot is often too thin for diagnosing flaky tests. The step-level trace below is **off by default** — enable it only when reproducing a flaky case.
372
+
373
+ ### Enable
374
+
375
+ ```bash
376
+ E2E_TRACE=1 pytest tests/test_login.py -v
377
+ # Include typed text in the JSONL log (DO NOT use on tests that type credentials/PII):
378
+ E2E_TRACE=1 E2E_TRACE_INCLUDE_TEXT=1 pytest ...
379
+ ```
380
+
381
+ ### Patch into BasePage
382
+
383
+ ```python
384
+ import os, json, time
385
+ TRACE_ENABLED = os.environ.get("E2E_TRACE") == "1"
386
+ TRACE_INCLUDE_TEXT = os.environ.get("E2E_TRACE_INCLUDE_TEXT") == "1"
387
+
388
+ class BasePage:
389
+ _step = 0
390
+
391
+ def _trace(self, action, spec=None, text=None):
392
+ if not TRACE_ENABLED:
393
+ return
394
+ BasePage._step += 1
395
+ idx = f"{BasePage._step:03d}"
396
+ os.makedirs(ARTIFACT_DIR, exist_ok=True)
397
+ try:
398
+ self.window.capture_as_image().save(
399
+ os.path.join(ARTIFACT_DIR, f"step_{idx}_{action}.png"))
400
+ except Exception:
401
+ pass # capture failure must not break the test
402
+ rec = {
403
+ "ts": time.time(), "step": BasePage._step, "action": action,
404
+ "locator": getattr(spec, "criteria", None),
405
+ "text": text if TRACE_INCLUDE_TEXT else ("<redacted>" if text else None),
406
+ }
407
+ with open(os.path.join(ARTIFACT_DIR, "trace.jsonl"), "a") as f:
408
+ f.write(json.dumps(rec) + "\n")
409
+
410
+ def click(self, spec):
411
+ self.wait_visible(spec); self._trace("click_before", spec)
412
+ spec.click_input(); self._trace("click_after", spec)
413
+
414
+ def type_text(self, spec, text):
415
+ self.wait_visible(spec); self._trace("type_before", spec, text)
416
+ # ... existing set_edit_text / keyboard fallback ...
417
+ self._trace("type_after", spec)
418
+ ```
419
+
420
+ ### Caveats
421
+
422
+ - **PII / credentials**: `type_text` content is `<redacted>` by default. Never set `E2E_TRACE_INCLUDE_TEXT=1` on login or payment flows.
423
+ - **Overhead**: ~50–200ms per action + one PNG per step on disk. Don't enable on the default CI matrix — only on a dedicated flake-repro job.
424
+ - **Artifact bloat**: a long flow produces tens of MB; tune `retention-days` accordingly.
425
+ - **Parallel/rerun hygiene**: this simple example appends to `trace.jsonl` and uses a class-level counter. Clear the artifact directory before reruns, and use per-worker artifact dirs for parallel tests.
426
+ - **Coverage gap**: actions performed outside `BasePage` (raw `pywinauto` calls in test code) are not traced.
427
+
428
+ ## Flaky Test Handling
429
+
430
+ ```python
431
+ # Quarantine — equivalent to Playwright's test.fixme()
432
+ @pytest.mark.skip(reason="Flaky: animation race on slow CI. Issue #42")
433
+ def test_animated_transition(self, app): ...
434
+
435
+ # Skip in CI only
436
+ @pytest.mark.skipif(os.environ.get("CI") == "true", reason="Flaky in CI #43")
437
+ def test_heavy_load(self, app): ...
438
+ ```
439
+
440
+ Common causes and fixes:
441
+
442
+ | Cause | Fix |
443
+ |-------|-----|
444
+ | Control not ready | Replace `time.sleep` with `wait_visible` |
445
+ | Window not focused | Add `win.set_focus()` before interactions |
446
+ | Animation in progress | `wait_until(lambda: not loading_indicator.exists())` |
447
+ | Dialog timing | `wait_window(title, timeout=15)` |
448
+ | CI display not ready | Set `DISPLAY` or use virtual desktop in CI |
449
+ | `set_edit_text` raises NotImplementedError | UIA ValuePattern missing (common on Qt 5.x) — `BasePage.type_text` already falls back to `keyboard.send_keys` |
450
+ | Control exists but `wait_visible` times out | Window minimised or off-screen — call `win.restore()` + `win.set_focus()` before waiting |
451
+
452
+ ## Test Isolation & Sandbox
453
+
454
+ Three tiers of isolation — use the lightest tier that satisfies your needs.
455
+
456
+ ### Tier 1 — Filesystem Isolation (default, always use)
457
+
458
+ Each test gets its own `APPDATA` / `LOCALAPPDATA` / `TEMP` via `subprocess.Popen` and `Application.connect()`. pytest's `tmp_path` fixture handles cleanup automatically.
459
+
460
+ ```python
461
+ # conftest.py — replace the basic `app` fixture with this
462
+ import os, subprocess, pytest
463
+ from pywinauto import Application
464
+ from config import APP_PATH, APP_ARGS, APP_TITLE, LAUNCH_TIMEOUT, ACTION_TIMEOUT, ARTIFACT_DIR
465
+
466
+ @pytest.fixture(scope="function")
467
+ def app(request, tmp_path):
468
+ """Fresh process + isolated user-data dirs per test."""
469
+ if not APP_PATH:
470
+ pytest.exit("APP_PATH not set", returncode=1)
471
+
472
+ # Redirect all per-user storage to an isolated tmp directory
473
+ sandbox_env = os.environ.copy()
474
+ sandbox_env["QT_ACCESSIBILITY"] = "1"
475
+ sandbox_env["APPDATA"] = str(tmp_path / "AppData" / "Roaming")
476
+ sandbox_env["LOCALAPPDATA"] = str(tmp_path / "AppData" / "Local")
477
+ sandbox_env["TEMP"] = sandbox_env["TMP"] = str(tmp_path / "Temp")
478
+ for p in (sandbox_env["APPDATA"], sandbox_env["LOCALAPPDATA"], sandbox_env["TEMP"]):
479
+ os.makedirs(p, exist_ok=True)
480
+
481
+ if not APP_TITLE:
482
+ pytest.exit("APP_TITLE environment variable is not set", returncode=1)
483
+
484
+ # shlex.split handles quoted args with spaces; plain split() breaks on them
485
+ import shlex
486
+ # Launch via subprocess so we can pass env; connect pywinauto by PID
487
+ proc = subprocess.Popen(
488
+ [APP_PATH] + shlex.split(APP_ARGS),
489
+ env=sandbox_env,
490
+ )
491
+ pw_app = Application(backend="uia").connect(process=proc.pid, timeout=LAUNCH_TIMEOUT)
492
+ win = pw_app.window(title=APP_TITLE)
493
+ win.wait("visible", timeout=LAUNCH_TIMEOUT)
494
+ yield win
495
+
496
+ if getattr(getattr(request.node, "rep_call", None), "failed", False):
497
+ os.makedirs(ARTIFACT_DIR, exist_ok=True)
498
+ try:
499
+ win.capture_as_image().save(
500
+ os.path.join(ARTIFACT_DIR, f"FAIL_{request.node.name}.png")
501
+ )
502
+ except Exception:
503
+ pass
504
+ try:
505
+ win.close()
506
+ proc.wait(timeout=5)
507
+ except Exception:
508
+ proc.kill()
509
+ # tmp_path is cleaned up automatically by pytest
510
+
511
+ @pytest.hookimpl(tryfirst=True, hookwrapper=True)
512
+ def pytest_runtest_makereport(item, call):
513
+ outcome = yield
514
+ setattr(item, f"rep_{outcome.get_result().when}", outcome.get_result())
515
+ ```
516
+
517
+ ### Tier 2 — Windows Job Object (optional: process-lifetime containment)
518
+
519
+ Attach the process to a Job Object so it is **automatically terminated** when
520
+ the test fixture's job handle is GC'd. Also prevents the app from spawning
521
+ child processes that escape fixture cleanup.
522
+
523
+ > **Scope of isolation:** Job Objects do NOT virtualize filesystem access or
524
+ > block network traffic. File-write and network isolation require AppContainer,
525
+ > Windows Firewall rules, or Tier 3 (Windows Sandbox). Use Tier 2 only for
526
+ > process-lifetime and child-process containment.
527
+
528
+ Requires no extra dependencies.
529
+
530
+ ```python
531
+ import ctypes, ctypes.wintypes as wt
532
+
533
+ def restrict_process(pid: int):
534
+ """
535
+ Attach the process to a Job Object that prevents it from:
536
+ - spawning processes outside the job (LIMIT_KILL_ON_JOB_CLOSE)
537
+ Does NOT block network — use Windows Firewall rules for that.
538
+ """
539
+ JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000
540
+ # Minimal rights: SET_QUOTA (0x0100) | TERMINATE (0x0001)
541
+ PROCESS_SET_QUOTA_AND_TERMINATE = 0x0101
542
+
543
+ kernel32 = ctypes.windll.kernel32
544
+ job = kernel32.CreateJobObjectW(None, None)
545
+ hproc = kernel32.OpenProcess(PROCESS_SET_QUOTA_AND_TERMINATE, False, pid)
546
+
547
+ # Correct struct layout — LimitFlags is at offset +16, not +44
548
+ class JOBOBJECT_BASIC_LIMIT_INFORMATION(ctypes.Structure):
549
+ _fields_ = [
550
+ ("PerProcessUserTimeLimit", wt.LARGE_INTEGER),
551
+ ("PerJobUserTimeLimit", wt.LARGE_INTEGER),
552
+ ("LimitFlags", wt.DWORD),
553
+ ("MinimumWorkingSetSize", ctypes.c_size_t),
554
+ ("MaximumWorkingSetSize", ctypes.c_size_t),
555
+ ("ActiveProcessLimit", wt.DWORD),
556
+ ("Affinity", ctypes.c_size_t),
557
+ ("PriorityClass", wt.DWORD),
558
+ ("SchedulingClass", wt.DWORD),
559
+ ]
560
+
561
+ info = JOBOBJECT_BASIC_LIMIT_INFORMATION()
562
+ info.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE
563
+ ok = kernel32.SetInformationJobObject(job, 2, ctypes.byref(info), ctypes.sizeof(info))
564
+ if not ok:
565
+ raise ctypes.WinError()
566
+ kernel32.AssignProcessToJobObject(job, hproc)
567
+ kernel32.CloseHandle(hproc)
568
+ return job # keep alive — job closes (kills proc) when GC'd
569
+
570
+ # After proc = subprocess.Popen(...): job = restrict_process(proc.pid)
571
+ ```
572
+
573
+ ### Tier 3 — Windows Sandbox (CI full-OS isolation)
574
+
575
+ When you need a clean Windows image per run (no leftover registry keys, no
576
+ shared GPU state, true isolation), run the **entire test suite** inside
577
+ [Windows Sandbox](https://learn.microsoft.com/windows/security/application-security/application-isolation/windows-sandbox/windows-sandbox-overview).
578
+
579
+ **Requirement:** Windows 10/11 Pro or Enterprise, Virtualization enabled.
580
+
581
+ Create `e2e-sandbox.wsb` in your project root:
582
+
583
+ ```xml
584
+ <Configuration>
585
+ <MappedFolders>
586
+ <!-- App binary (read-only) -->
587
+ <MappedFolder>
588
+ <HostFolder>C:\path\to\your\build\Release</HostFolder>
589
+ <SandboxFolder>C:\app</SandboxFolder>
590
+ <ReadOnly>true</ReadOnly>
591
+ </MappedFolder>
592
+ <!-- Test suite (read-write for artifacts) -->
593
+ <MappedFolder>
594
+ <HostFolder>C:\path\to\your\e2e_test</HostFolder>
595
+ <SandboxFolder>C:\e2e_test</SandboxFolder>
596
+ <ReadOnly>false</ReadOnly>
597
+ </MappedFolder>
598
+ </MappedFolders>
599
+ <LogonCommand>
600
+ <!--
601
+ Windows Sandbox starts with no Python. Install it silently first,
602
+ then install deps and run tests. Artifacts are written back to the
603
+ host via the MappedFolder above.
604
+ -->
605
+ <Command>powershell -Command "
606
+ winget install --id Python.Python.3.11 --silent --accept-package-agreements;
607
+ $env:PATH += ';' + $env:LOCALAPPDATA + '\Programs\Python\Python311\Scripts';
608
+ cd C:\e2e_test;
609
+ pip install -r requirements.txt;
610
+ pytest tests\ -v
611
+ "</Command>
612
+ </LogonCommand>
613
+ </Configuration>
614
+ ```
615
+
616
+ Launch: `WindowsSandbox.exe e2e-sandbox.wsb`
617
+
618
+ > pywinauto and the app both run **inside** the sandbox (same session required).
619
+ > Artifacts are written back to the host via the mapped folder.
620
+
621
+ ### Tier comparison
622
+
623
+ | Tier | Isolation | Setup cost | Works on CI | Use when |
624
+ |------|-----------|-----------|-------------|----------|
625
+ | 1 — `tmp_path` env redirect | Filesystem | Zero | Always | Default for all tests |
626
+ | 2 — Job Object | Process tree | Low | Always | Prevent child-process escape |
627
+ | 3 — Windows Sandbox | Full OS | Medium | Needs Pro/Enterprise image | Nightly clean-room runs |
628
+
629
+ ### Prevent hanging tests
630
+
631
+ Add `pytest-timeout` to cap any single test. In `pytest.ini` set `timeout = 60` and `timeout_method = thread`. Note: `thread` method cannot kill Qt app subprocesses on Windows — add `atexit.register(lambda: [p.kill() for p in psutil.Process().children(recursive=True)])` in `conftest.py` to reap orphans.
632
+
633
+ ## CI/CD Integration
634
+
635
+ ```yaml
636
+ # .github/workflows/e2e-desktop.yml
637
+ name: Desktop E2E
638
+ on: [push, pull_request]
639
+
640
+ jobs:
641
+ e2e:
642
+ runs-on: windows-latest # real GUI environment, no Xvfb needed
643
+ steps:
644
+ - uses: actions/checkout@v4
645
+
646
+ - uses: actions/setup-python@v5
647
+ with: { python-version: "3.11" }
648
+
649
+ - name: Install deps
650
+ run: pip install pywinauto pytest pytest-html Pillow
651
+
652
+ - name: Build app
653
+ run: cmake --build build --config Release # adjust to your build system
654
+
655
+ - name: Run E2E
656
+ env:
657
+ APP_PATH: ${{ github.workspace }}\build\Release\MyApp.exe
658
+ APP_TITLE: "My Application"
659
+ CI: "true"
660
+ run: pytest tests/ --html=artifacts/report.html --self-contained-html --junitxml=artifacts/results.xml -v
661
+
662
+ - uses: actions/upload-artifact@v4
663
+ if: always()
664
+ with:
665
+ name: e2e-artifacts
666
+ path: artifacts/
667
+ retention-days: 14
668
+ ```
669
+
670
+ ## Qt Specific
671
+
672
+ ### Enable UIA in Qt 5.x
673
+
674
+ Qt 5.x accessibility is disabled by default in some builds (especially 5.7–5.14). Set the environment variable **before** launching. Qt 6.x enables accessibility by default — skip this step for Qt 6.
675
+
676
+ ```python
677
+ # conftest.py — add at module top
678
+ import os
679
+ os.environ["QT_ACCESSIBILITY"] = "1"
680
+ ```
681
+
682
+ Or export it in CI:
683
+
684
+ ```yaml
685
+ env:
686
+ QT_ACCESSIBILITY: "1"
687
+ ```
688
+
689
+ ### Add Stable Identifiers to Qt Widgets
690
+
691
+ ```cpp
692
+ // Preferred: both objectName and accessibleName
693
+ void setTestId(QWidget* w, const char* id) {
694
+ w->setObjectName(id);
695
+ w->setAccessibleName(id); // becomes UIA Name property
696
+ }
697
+
698
+ // In your dialog constructor:
699
+ setTestId(ui->usernameEdit, "usernameInput");
700
+ setTestId(ui->passwordEdit, "passwordInput");
701
+ setTestId(ui->loginButton, "btnLogin");
702
+ setTestId(ui->errorLabel, "lblError");
703
+ ```
704
+
705
+ Centralise all IDs in a header to avoid typos:
706
+
707
+ ```cpp
708
+ // test_ids.h
709
+ #define TID_USERNAME "usernameInput"
710
+ #define TID_PASSWORD "passwordInput"
711
+ #define TID_BTN_LOGIN "btnLogin"
712
+ #define TID_LBL_ERROR "lblError"
713
+ ```
714
+
715
+ ### Qt-Specific Quirks
716
+
717
+ **QComboBox** — the dropdown is a separate top-level window:
718
+
719
+ ```python
720
+ from pywinauto import Desktop
721
+
722
+ def select_combo_item(page, combo_spec, item_text):
723
+ page.click(combo_spec)
724
+ # Dropdown appears as a new root-level window
725
+ # class_name varies by Qt version — verify with Accessibility Insights
726
+ # Qt 5.x: "Qt5QWindowIcon" | Qt 6.x: "Qt6QWindowIcon" — verify with Accessibility Insights
727
+ popup = Desktop(backend="uia").window(class_name_re="Qt[56]QWindowIcon")
728
+ popup.wait("visible", timeout=5)
729
+ popup.child_window(title=item_text).click_input()
730
+ ```
731
+
732
+ **QMessageBox / QDialog** — also separate top-level windows:
733
+
734
+ ```python
735
+ dlg = page.wait_window("Confirm") # wait for dialog title
736
+ dlg.child_window(title="OK").click_input() # click button inside it
737
+ ```
738
+
739
+ **QTableWidget / QTableView** — row/cell access:
740
+
741
+ ```python
742
+ table = page.by_id("tblUsers").wrapper_object()
743
+ cell = table.cell(row=0, column=1)
744
+ print(cell.window_text())
745
+ ```
746
+
747
+ **Self-drawn controls** (`paintEvent`-only, `QGraphicsView`, `QOpenGLWidget`) — UIA cannot see their internals. Use the Fallback section below.
748
+
749
+ ## Fallback: Screenshot Mode
750
+
751
+ When a control is not reachable via UIA (self-drawn, third-party, game engine):
752
+
753
+ ```bash
754
+ pip install pyautogui Pillow opencv-python
755
+ ```
756
+
757
+ ```python
758
+ import pyautogui, cv2, numpy as np
759
+ from PIL import Image
760
+
761
+ def find_image_on_screen(template_path, confidence=0.85):
762
+ """Locate a template image on screen. Returns (x, y) center or None."""
763
+ screen = np.array(pyautogui.screenshot())
764
+ template = np.array(Image.open(template_path))
765
+ result = cv2.matchTemplate(
766
+ cv2.cvtColor(screen, cv2.COLOR_RGB2BGR),
767
+ cv2.cvtColor(template, cv2.COLOR_RGB2BGR),
768
+ cv2.TM_CCOEFF_NORMED,
769
+ )
770
+ _, max_val, _, max_loc = cv2.minMaxLoc(result)
771
+ if max_val >= confidence:
772
+ h, w = template.shape[:2]
773
+ return max_loc[0] + w // 2, max_loc[1] + h // 2
774
+ return None
775
+
776
+ def click_image(template_path, confidence=0.85):
777
+ pos = find_image_on_screen(template_path, confidence)
778
+ if pos is None:
779
+ raise RuntimeError(f"Image not found on screen: {template_path}")
780
+ pyautogui.click(*pos)
781
+ ```
782
+
783
+ ### DPI / Scaling Rules (screenshot mode only)
784
+
785
+ Screenshot matching is brutally sensitive to Windows display scaling (100% / 125% / 150%). Three hard rules:
786
+
787
+ 1. **Capture templates at the same scale as the target machine.** Don't try to rescue a mismatch with `PIL.Image.resize` — `cv2.matchTemplate` is very fragile against resampling artefacts.
788
+ 2. **Pin the CI display scaling.** On `windows-latest` add a step like `Set-DisplayResolution 1920 1080 -Force` and disable per-monitor DPI scaling, so screenshot dimensions are reproducible.
789
+ 3. **Record the scale alongside each artefact.** On capture, write `GetDpiForWindow(hwnd) / 96` to `artifacts/<test>/metadata.json` — postmortems become obvious instead of guess-work.
790
+
791
+ > Process-level DPI awareness (`SetProcessDpiAwarenessContext`) **can conflict with Qt's own DPI handling** when the app under test is Qt-based. Prefer "same-scale templates + CI pin" over flipping process-wide DPI mode in fixtures.
792
+
793
+ ### Debugging Match Confidence
794
+
795
+ When tuning the `confidence` threshold, the only sane workflow is to **see** where the match landed. The helper below is diagnosis-only — do not call it from test code.
796
+
797
+ ```python
798
+ def debug_match(template_path, out="artifacts/match_debug.png", confidence=0.85):
799
+ """Diagnosis-only. Draw the best-match rectangle + score back on the current screen.
800
+
801
+ NOT for production tests — use when calibrating confidence or chasing false matches.
802
+ """
803
+ import os, cv2, pyautogui, numpy as np
804
+ screen = np.array(pyautogui.screenshot())[:, :, ::-1]
805
+ tpl = cv2.imread(template_path)
806
+ if tpl is None:
807
+ raise RuntimeError(f"Template unreadable: {template_path}")
808
+ res = cv2.matchTemplate(screen, tpl, cv2.TM_CCOEFF_NORMED)
809
+ _, mv, _, ml = cv2.minMaxLoc(res)
810
+ h, w = tpl.shape[:2]
811
+ colour = (0, 255, 0) if mv >= confidence else (0, 0, 255) # green pass / red fail
812
+ cv2.rectangle(screen, ml, (ml[0]+w, ml[1]+h), colour, 2)
813
+ cv2.putText(screen, f"score={mv:.3f} thr={confidence}",
814
+ (ml[0], max(20, ml[1]-6)),
815
+ cv2.FONT_HERSHEY_SIMPLEX, 0.7, colour, 2)
816
+ os.makedirs(os.path.dirname(out) or ".", exist_ok=True)
817
+ cv2.imwrite(out, screen)
818
+ return mv
819
+ ```
820
+
821
+ **Use sparingly** — image matching breaks on DPI changes, theme switches, and partial occlusion.
822
+ Always try UIA first; fall back to screenshots only for genuinely unreachable controls.
823
+
824
+ ## Anti-Patterns
825
+
826
+ ```python
827
+ # BAD: fixed sleep
828
+ time.sleep(3)
829
+ page.click(page.by_id("btnSubmit"))
830
+
831
+ # GOOD: condition wait
832
+ page.wait_visible(page.by_id("btnSubmit"))
833
+ page.click(page.by_id("btnSubmit"))
834
+ ```
835
+
836
+ ```python
837
+ # BAD: brittle class+index locator as primary strategy
838
+ page.by_class("Edit", index=2).type_keys("hello")
839
+
840
+ # GOOD: AutomationId
841
+ page.by_id("usernameInput").set_edit_text("hello")
842
+ ```
843
+
844
+ ```python
845
+ # BAD: assert on pixel coordinates
846
+ assert btn.rectangle().left == 120
847
+
848
+ # GOOD: assert on content / state
849
+ assert page.get_text(page.by_id("lblStatus")) == "Logged in"
850
+ assert page.by_id("btnLogout").is_enabled()
851
+ ```
852
+
853
+ ```python
854
+ # BAD: share app instance across all tests (state leaks)
855
+ @pytest.fixture(scope="session")
856
+ def app(): ...
857
+
858
+ # GOOD: fresh process per test (or per class at most)
859
+ @pytest.fixture(scope="function")
860
+ def app(): ...
861
+ ```
862
+
863
+ ## Running Tests
864
+
865
+ ```bash
866
+ # All tests
867
+ pytest tests/ -v
868
+
869
+ # Smoke only
870
+ pytest tests/ -m smoke -v
871
+
872
+ # Specific file
873
+ pytest tests/test_login.py -v
874
+
875
+ # With custom app path
876
+ APP_PATH="C:\build\Release\MyApp.exe" APP_TITLE="MyApp" pytest tests/ -v
877
+
878
+ # Detect flaky tests (repeat each 5 times)
879
+ pip install pytest-repeat
880
+ pytest tests/test_login.py --count=5 -v
881
+ ```
882
+
883
+ ## Related Skills
884
+
885
+ - `e2e-testing` — Playwright E2E for web applications
886
+ - `cpp-testing` — C++ unit/integration testing with GoogleTest
887
+ - `cpp-coding-standards` — C++ code style and patterns