@capagents/forgeqe 3.0.2 → 3.0.4

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 (155) hide show
  1. package/HOW_TO_USE.md +190 -189
  2. package/README.md +12 -12
  3. package/THIRD_PARTY_NOTICES.md +2 -2
  4. package/dist/docs-site/architecture-map/index.html +6 -6
  5. package/dist/docs-site/docs/architecture/index.html +31 -31
  6. package/dist/docs-site/docs/containers/index.html +9 -10
  7. package/dist/docs-site/docs/custom-agents-first-run/index.html +5 -5
  8. package/dist/docs-site/docs/desktop/index.html +8 -10
  9. package/dist/docs-site/docs/feature-test-prompts/index.html +4 -4
  10. package/dist/docs-site/docs/graphify/index.html +1 -1
  11. package/dist/docs-site/docs/index.html +214 -165
  12. package/dist/docs-site/docs/mobile/index.html +6 -6
  13. package/dist/docs-site/docs/model-routing/index.html +58 -10
  14. package/dist/docs-site/docs/product-graph/index.html +3 -3
  15. package/dist/docs-site/docs/product-views/index.html +1 -1
  16. package/dist/docs-site/docs/search.js +1 -1
  17. package/dist/docs-site/docs/web-app/index.html +6 -6
  18. package/dist/forgeqe.js +1854 -1823
  19. package/dist/template.html +69 -69
  20. package/dist/web/assets/Agent-CKlqZ4Eq.js +8 -0
  21. package/dist/web/assets/ApiTests-MARHrxdT.js +10 -0
  22. package/dist/web/assets/Browse-B2QYflth.js +2 -0
  23. package/dist/web/assets/Chat-DRkmiF4r.js +5 -0
  24. package/dist/web/assets/{CommandPalette-Dkb2OOQX.js → CommandPalette-DMpA8mBk.js} +1 -1
  25. package/dist/web/assets/{Compare-Esy5n-kR.js → Compare-DD1mmRB4.js} +1 -1
  26. package/dist/web/assets/Cost-B6BCZIxQ.js +1 -0
  27. package/dist/web/assets/Data-CpKR98gM.js +6 -0
  28. package/dist/web/assets/{Desktop-CsEWht_F.js → Desktop-xUqFsJPz.js} +1 -1
  29. package/dist/web/assets/{DesktopReview-BUfM70Ju.js → DesktopReview-CnLC9yMR.js} +1 -1
  30. package/dist/web/assets/{Evidence-DEDtYoZr.js → Evidence-CWcZvoOu.js} +1 -1
  31. package/dist/web/assets/{Explore-AXLdkUHT.js → Explore-DuDQqmEn.js} +2 -2
  32. package/dist/web/assets/{Features-DcDbE20H.js → Features-BJTX7utr.js} +1 -1
  33. package/dist/web/assets/{Flags-CSKvhaye.js → Flags-BeG_gA9O.js} +2 -2
  34. package/dist/web/assets/{Flaky-B48EUqK0.js → Flaky-DulQuBGi.js} +1 -1
  35. package/dist/web/assets/Impact-BvGp2rYG.js +3 -0
  36. package/dist/web/assets/Jobs-BXqBtH8C.js +5 -0
  37. package/dist/web/assets/KindPage-BGEobnS3.js +6 -0
  38. package/dist/web/assets/Migration-D1JVUQM0.js +2 -0
  39. package/dist/web/assets/{Product-CDAzt1hG.js → Product-Y1dUpFfW.js} +2 -2
  40. package/dist/web/assets/{Production-sUNlZeSF.js → Production-DY9Gddm8.js} +1 -1
  41. package/dist/web/assets/{Quality-C9Z0FYjK.js → Quality-B7M1Zna2.js} +1 -1
  42. package/dist/web/assets/{Readiness-Qse6Oxo-.js → Readiness-BtQ8RbJh.js} +1 -1
  43. package/dist/web/assets/Record-W7ojjKNu.js +2 -0
  44. package/dist/web/assets/Regression-eV2N8m2P.js +5 -0
  45. package/dist/web/assets/{RelationGraph-CV8NXesZ.js → RelationGraph-C7K_BfEF.js} +1 -1
  46. package/dist/web/assets/{Reports-C4U0fIue.js → Reports-D4v66mJR.js} +2 -2
  47. package/dist/web/assets/Response-B_2R4FjH.js +4 -0
  48. package/dist/web/assets/{RunDiff-DUREV_nk.js → RunDiff-Br5uN0Gu.js} +1 -1
  49. package/dist/web/assets/Runs-DvjM0xfG.js +2 -0
  50. package/dist/web/assets/{Steps-Bt1rmBc3.js → Steps-DULf0k5w.js} +1 -1
  51. package/dist/web/assets/{TestCases-CVSJIPFl.js → TestCases-Dc6bjNO5.js} +1 -1
  52. package/dist/web/assets/TestData-DWPcmhz4.js +2 -0
  53. package/dist/web/assets/{TestDebt-D5NgM75J.js → TestDebt-BpYav19x.js} +1 -1
  54. package/dist/web/assets/Tosca-Bw-j_W-Q.js +3 -0
  55. package/dist/web/assets/{WhatsNew-BtwiaM4Q.js → WhatsNew-CRaJjaut.js} +1 -1
  56. package/dist/web/assets/agentLink-Dxy-IYQv.js +1 -0
  57. package/dist/web/assets/{dataParts-CxOVAp8R.js → dataParts-Bwh_DOs0.js} +1 -1
  58. package/dist/web/assets/{families-BLmK1isi.js → families-C47Nrp6j.js} +1 -1
  59. package/dist/web/assets/filters-Ca7by1u0.js +1 -0
  60. package/dist/web/assets/{fold-GeY4MiIu.js → fold-Bd5-4sjR.js} +1 -1
  61. package/dist/web/assets/frame-BliO67Wd.js +18 -0
  62. package/dist/web/assets/index-B1U2Jkz_.js +67 -0
  63. package/dist/web/assets/index-Ce2EYROA.css +2 -0
  64. package/dist/web/assets/{logos-COH9UQgY.js → logos-CgYEz85j.js} +1 -1
  65. package/dist/web/assets/{markdown-DoF5NaZz.js → markdown-DSp3tP8i.js} +5 -5
  66. package/dist/web/assets/{paletteCommands-BlCwQKjX.js → paletteCommands-CGFwmBxN.js} +1 -1
  67. package/dist/web/assets/{parts-Bx4MyFXM.js → parts-DlmbVDzO.js} +1 -1
  68. package/dist/web/assets/{productParts-DTtbe-g-.js → productParts-CL2tDIGF.js} +1 -1
  69. package/dist/web/assets/{qualityParts-DbH_PNDs.js → qualityParts-Bs34Dzva.js} +1 -1
  70. package/dist/web/assets/recordTest-DHsT3pOe.js +1 -0
  71. package/dist/web/assets/{rows-vliRYT-Z.js → rows-Baid_ASt.js} +1 -1
  72. package/dist/web/assets/{segmented-Bisag9SK.js → segmented-D0PvwMW_.js} +1 -1
  73. package/dist/web/assets/{usePageChat-B-4sWqvn.js → usePageChat-lmgkgnb4.js} +1 -1
  74. package/dist/web/index.html +5 -5
  75. package/docs/ARCHITECTURE.md +30 -30
  76. package/docs/BUSINESS_ASSURANCE.md +7 -7
  77. package/docs/CONTAINERS.md +8 -10
  78. package/docs/CUSTOM_AGENTS_FIRST_RUN.md +4 -4
  79. package/docs/DESKTOP.md +8 -10
  80. package/docs/GRAPHIFY.md +1 -1
  81. package/docs/MOBILE.md +6 -6
  82. package/docs/MODEL_ROUTING.md +57 -9
  83. package/docs/PRODUCT_KNOWLEDGE.md +3 -3
  84. package/docs/PRODUCT_VIEWS.md +1 -1
  85. package/docs/WEB_APP.md +6 -6
  86. package/docs/demo-qi-commerce.md +30 -30
  87. package/docs/feature-test-prompts.md +3 -3
  88. package/docs/prompts/graphify-evidence.md +3 -3
  89. package/docs/security-data-flow.html +23 -23
  90. package/docs/user-guide.html +214 -165
  91. package/docs/walkthrough/hotfix-narration.md +19 -19
  92. package/docs/walkthrough/index.html +26 -26
  93. package/env.example.yaml +1 -1
  94. package/evals/evidence/records/forgeqe-test-writing/source.jsonl +1 -1
  95. package/forgeqe-architecture.html +48 -48
  96. package/forgeqe.example.yaml +16 -10
  97. package/package.json +1 -1
  98. package/prompts/README.md +7 -7
  99. package/prompts/agent-builder.md +1 -1
  100. package/prompts/api-tests.md +1 -1
  101. package/prompts/brain.md +10 -4
  102. package/prompts/business-interview.md +3 -3
  103. package/prompts/business-persona.md +3 -3
  104. package/prompts/business-strategist.md +1 -1
  105. package/prompts/db-agent.md +3 -3
  106. package/prompts/doc-reader.md +2 -2
  107. package/prompts/heal.md +1 -1
  108. package/prompts/knowledge-agent.md +3 -3
  109. package/prompts/model-profile.md +1 -1
  110. package/prompts/page-differs.md +1 -1
  111. package/prompts/persona-own.md +3 -3
  112. package/prompts/talk.md +5 -4
  113. package/prompts/test-agent.md +2 -2
  114. package/prompts/test-plan.md +2 -2
  115. package/prompts/tosca-assistant.md +1 -1
  116. package/py/forgeqe_engine/copilot_gateway.py +1 -1
  117. package/py/forgeqe_engine/memory.py +48 -2
  118. package/py/forgeqe_engine/recordsession.py +31 -1
  119. package/py/forgeqe_engine/video.py +104 -20
  120. package/py/forgeqe_engine/webrecord_page.py +88 -7
  121. package/py/forgeqe_tosca/__init__.py +2 -2
  122. package/py/forgeqe_tosca/render.py +1 -1
  123. package/py/forgeqe_tosca/tsu.py +2 -2
  124. package/py/forgeqe_voice/worker.py +10 -2
  125. package/skills/playwright-automation/SKILL.md +102 -0
  126. package/skills/playwright-automation/references/dotnet.md +90 -0
  127. package/skills/playwright-automation/references/java.md +41 -0
  128. package/skills/playwright-automation/references/python.md +42 -0
  129. package/skills/playwright-automation/references/typescript.md +54 -0
  130. package/skills/test-data/SKILL.md +1 -1
  131. package/skills/writing-skills/SKILL.md +2 -2
  132. package/dist/web/assets/Agent-CNIwgz9P.js +0 -8
  133. package/dist/web/assets/ApiTests-CuflKFaz.js +0 -10
  134. package/dist/web/assets/Browse-D6cvDJW3.js +0 -2
  135. package/dist/web/assets/Chat-BwlScUXP.js +0 -5
  136. package/dist/web/assets/Cost-BIoJmbfg.js +0 -1
  137. package/dist/web/assets/Data-3Q5bGxT5.js +0 -6
  138. package/dist/web/assets/Impact-BTLqgWf6.js +0 -3
  139. package/dist/web/assets/Jobs-C2UViADN.js +0 -5
  140. package/dist/web/assets/KindPage-DBWC-d0o.js +0 -6
  141. package/dist/web/assets/Migration-TR5UJVZD.js +0 -2
  142. package/dist/web/assets/Record-BPd38INk.js +0 -2
  143. package/dist/web/assets/Regression-Brk_1yqk.js +0 -5
  144. package/dist/web/assets/Response-B1iCzkHo.js +0 -4
  145. package/dist/web/assets/Runs-B--vjy7q.js +0 -2
  146. package/dist/web/assets/TestData-_sZDpddH.js +0 -2
  147. package/dist/web/assets/Tosca-BcfNYUdZ.js +0 -3
  148. package/dist/web/assets/agentLink-BD93RYQ0.js +0 -1
  149. package/dist/web/assets/filters-YzD0tZES.js +0 -1
  150. package/dist/web/assets/frame-CaTNV7DF.js +0 -18
  151. package/dist/web/assets/index-9ELkRoKH.js +0 -67
  152. package/dist/web/assets/index-B_mKjNAi.css +0 -2
  153. package/dist/web/assets/recordTest-Brs1Sw9O.js +0 -1
  154. package/skills/dotnet-nunit-playwright/SKILL.md +0 -36
  155. package/skills/playwright-typescript/SKILL.md +0 -36
@@ -6,7 +6,10 @@ and a desktop run (the screen).
6
6
  Every video is ``video.mp4`` (H.264), made by the ffmpeg that the pinned ``imageio-ffmpeg`` package ships inside
7
7
  itself: found in the package's own ``binaries`` folder, never on PATH and never through ``IMAGEIO_FFMPEG_EXE``, started
8
8
  with an argument list and system settings only. Frames reach it on stdin as raw RGB pixels of a fixed size, so nothing
9
- a page or an app shows ever reaches its command line. A video runs in real time at ``FPS`` frames a second (the
9
+ a page or an app shows ever reaches its command line. A replay's video can carry a narration track
10
+ (``browser.narrate_video``): one WAV that ForgeQE made itself (src/voice/narration.ts lays the spoken lines into it),
11
+ given to ffmpeg as a second input by its path only -- never a clip of its own, never a filter graph built from a
12
+ page's words. A video runs in real time at ``FPS`` frames a second (the
10
13
  latest picture is repeated while nothing changes), stops growing after ``MAX_SECONDS``, and a video that could not be
11
14
  finished is removed rather than kept half written.
12
15
  """
@@ -20,6 +23,7 @@ import subprocess
20
23
  import sys
21
24
  import threading
22
25
  import time
26
+ import wave
23
27
  from pathlib import Path
24
28
  from typing import Any, Callable, Dict, List, Optional, Tuple
25
29
 
@@ -56,14 +60,6 @@ def ffmpeg_exe() -> Optional[str]:
56
60
  return None
57
61
 
58
62
 
59
- def video_ready() -> bool:
60
- try:
61
- import PIL # noqa: F401
62
- except Exception:
63
- return False
64
- return ffmpeg_exe() is not None
65
-
66
-
67
63
  def _even(n: int) -> int:
68
64
  return max(2, n - (n % 2))
69
65
 
@@ -75,14 +71,43 @@ def fit_size(width: int, height: int, max_width: int = MAX_WIDTH, max_height: in
75
71
  return _even(round(width * scale)), _even(round(height * scale))
76
72
 
77
73
 
78
- def ffmpeg_args(exe: str, size: Tuple[int, int], fps: int, out: Path) -> List[str]:
74
+ def ffmpeg_args(exe: str, size: Tuple[int, int], fps: int, out: Path, audio: Optional[Path] = None) -> List[str]:
75
+ """ffmpeg's arguments: pictures on stdin, and with ``audio`` that one WAV as a second input, by its path alone."""
79
76
  w, h = size
80
- return [
77
+ args = [
81
78
  exe, "-hide_banner", "-loglevel", "error", "-y",
82
79
  "-f", "rawvideo", "-pix_fmt", "rgb24", "-s", f"{w}x{h}", "-r", str(fps), "-i", "-",
83
- "-an", "-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart",
84
- str(out),
85
80
  ]
81
+ if audio is not None:
82
+ # One more input, and only a WAV ForgeQE wrote: the video still ends when its pictures do (-shortest).
83
+ args += ["-f", "wav", "-i", str(audio), "-c:a", "aac", "-b:a", "96k", "-shortest"]
84
+ else:
85
+ args += ["-an"]
86
+ args += ["-c:v", "libx264", "-preset", "veryfast", "-crf", "28", "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(out)]
87
+ return args
88
+
89
+
90
+ def wav_ms(file: Path) -> int:
91
+ """How long a WAV ForgeQE wrote lasts, in milliseconds, from its own header; 0 when it cannot be read."""
92
+ try:
93
+ with wave.open(str(file), "rb") as w:
94
+ rate = w.getframerate()
95
+ return int(w.getnframes() * 1000 / rate) if rate else 0
96
+ except (OSError, wave.Error, EOFError):
97
+ return 0
98
+
99
+
100
+ def narration_file(raw: Any) -> Optional[Path]:
101
+ """The narration track to lay under the video: a regular ``.wav`` file that is really there, else None."""
102
+ if not raw:
103
+ return None
104
+ try:
105
+ p = Path(str(raw))
106
+ if p.suffix.lower() != ".wav" or p.is_symlink() or not p.is_file() or not p.stat().st_size:
107
+ return None
108
+ return p
109
+ except OSError:
110
+ return None
86
111
 
87
112
 
88
113
  def _child_env() -> Dict[str, str]:
@@ -174,6 +199,13 @@ class FrameVideo:
174
199
  self._latest = data
175
200
  self._fresh = True
176
201
 
202
+ def where_ms(self) -> int:
203
+ """
204
+ Where the video is now, in milliseconds: the frames written at ``fps``, so the time held is not counted (it is
205
+ not in the video either). This is what times a step for the narration (browser.narrate_video).
206
+ """
207
+ return int(self.written * 1000 / self.fps)
208
+
177
209
  def hold(self, held: bool) -> None:
178
210
  with self._lock:
179
211
  if held == self._held:
@@ -292,10 +324,45 @@ def frames_in(folder: Path) -> List[Tuple[int, Path]]:
292
324
  return out[:MAX_FRAMES]
293
325
 
294
326
 
295
- def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float = MAX_SECONDS, exe: Optional[str] = None) -> Tuple[Optional[Path], str]:
327
+ def add_narration(video: Any, track: Any, out: Path, *, exe: Optional[str] = None) -> Tuple[Optional[Path], str]:
328
+ """
329
+ A video already made (a recording's own, written as it happened) with the narration laid under it: its pictures are
330
+ copied, not made again, and ffmpeg is given the two files ForgeQE wrote, by their paths alone.
331
+ """
332
+ src = Path(str(video))
333
+ if src.suffix.lower() != ".mp4" or src.is_symlink() or not src.is_file() or not src.stat().st_size:
334
+ return None, "there is no video to narrate"
335
+ laid = narration_file(track)
336
+ if laid is None:
337
+ return None, "there is no narration to lay under it"
338
+ exe = exe or ffmpeg_exe()
339
+ if not exe:
340
+ return None, "the engine's video packages are missing (run forgeqe setup)"
341
+ out = Path(out)
342
+ out.parent.mkdir(parents=True, exist_ok=True)
343
+ args = [
344
+ exe, "-hide_banner", "-loglevel", "error", "-y",
345
+ "-i", str(src), "-f", "wav", "-i", str(laid),
346
+ "-map", "0:v:0", "-map", "1:a:0", "-c:v", "copy", "-c:a", "aac", "-b:a", "96k", "-shortest",
347
+ str(out),
348
+ ]
349
+ try:
350
+ proc = subprocess.run(args, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False, timeout=FINISH_SECONDS)
351
+ except (OSError, subprocess.TimeoutExpired) as ex:
352
+ return None, f"ffmpeg did not finish ({ex.__class__.__name__})"
353
+ if proc.returncode != 0 or not out.is_file() or not out.stat().st_size:
354
+ try:
355
+ out.unlink()
356
+ except OSError:
357
+ pass
358
+ return None, f"ffmpeg ended with {proc.returncode}"
359
+ return out, ""
360
+
361
+
362
+ def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float = MAX_SECONDS, exe: Optional[str] = None, audio: Any = None) -> Tuple[Optional[Path], str]:
296
363
  """
297
364
  A video of frames kept with their times (a replay's): each moment shows the latest frame taken by then. (path, "")
298
- or (None, why not).
365
+ or (None, why not). ``audio``: a WAV ForgeQE made (the narration), laid under it when it is really a .wav file.
299
366
  """
300
367
  frames = frames_in(folder)
301
368
  if not frames:
@@ -307,14 +374,18 @@ def encode_frames(folder: Path, out: Path, *, fps: int = FPS, max_seconds: float
307
374
  if first is None:
308
375
  return None, "the first frame is not a picture"
309
376
  size = fit_size(first.width, first.height)
377
+ track = narration_file(audio)
310
378
  out = Path(out)
311
379
  out.parent.mkdir(parents=True, exist_ok=True)
312
380
  try:
313
- proc = subprocess.Popen(ffmpeg_args(exe, size, fps, out), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False)
381
+ proc = subprocess.Popen(ffmpeg_args(exe, size, fps, out, track), stdin=subprocess.PIPE, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_child_env(), shell=False)
314
382
  except OSError as ex:
315
383
  return None, f"ffmpeg did not start ({ex.__class__.__name__})"
316
384
  start = frames[0][0]
317
385
  end = min(frames[-1][0] - start, int(max_seconds * 1000))
386
+ # With a narration, the video lasts as long as it does: the last frame is held, so its closing line is never cut.
387
+ if track is not None:
388
+ end = min(max(end, wav_ms(track)), int(max_seconds * 1000))
318
389
  count = end * fps // 1000 + 1
319
390
  i, pixels, ok = 0, _letterbox(first, size), True
320
391
  assert proc.stdin is not None
@@ -413,11 +484,24 @@ class ScreenVideo:
413
484
 
414
485
 
415
486
  def main(args: List[str], out: Any) -> int:
416
- """``python -m forgeqe_engine video <frames folder> <file.mp4>``: a replay's frames as a video (src/code/replay.ts)."""
417
- if len(args) != 2 or not args[1].endswith(".mp4"):
418
- result: Dict[str, Any] = {"success": False, "error": "usage: video <frames folder> <file.mp4>"}
487
+ """
488
+ ``python -m forgeqe_engine video <frames folder> <file.mp4> [narration.wav]``: a replay's frames as a video
489
+ (src/code/replay.ts), with the narration track under it when one is given (src/voice/narration.ts).
490
+ ``video narrate <made.mp4> <narration.wav> <out.mp4>``: a recording's own video, written as it happened, with that
491
+ track laid under it afterwards (its pictures copied, not made again).
492
+ """
493
+ if args and args[0] == "narrate":
494
+ if len(args) != 4 or not args[1].endswith(".mp4") or not args[2].endswith(".wav") or not args[3].endswith(".mp4"):
495
+ result: Dict[str, Any] = {"success": False, "error": "usage: video narrate <made.mp4> <narration.wav> <out.mp4>"}
496
+ else:
497
+ path, why = add_narration(args[1], args[2], Path(args[3]))
498
+ result = {"success": True, "video": str(path)} if path else {"success": False, "error": why}
499
+ out.write(json.dumps({"type": "done", "result": result}) + "\n")
500
+ return 0 if result["success"] else 1
501
+ if len(args) not in (2, 3) or not args[1].endswith(".mp4") or (len(args) == 3 and not args[2].endswith(".wav")):
502
+ result = {"success": False, "error": "usage: video <frames folder> <file.mp4> [narration.wav]"}
419
503
  else:
420
- path, why = encode_frames(Path(args[0]), Path(args[1]))
504
+ path, why = encode_frames(Path(args[0]), Path(args[1]), audio=args[2] if len(args) == 3 else None)
421
505
  result = {"success": True, "video": str(path)} if path else {"success": False, "error": why}
422
506
  out.write(json.dumps({"type": "done", "result": result}) + "\n")
423
507
  return 0 if result["success"] else 1
@@ -14,7 +14,7 @@ from __future__ import annotations
14
14
  import json
15
15
  from typing import Any, Dict, Optional
16
16
 
17
- from .memory import STATE_CLASS
17
+ from .memory import SHAKY_TEXT, STATE_CLASS, TEXT_GEN
18
18
 
19
19
  # The leader key, then one letter: what each letter does, as the key bar and the panel's hint show it.
20
20
  COMMAND_KEYS = (
@@ -147,13 +147,62 @@ RECORDER_JS = r"""(() => {
147
147
  // No XPath for an element inside a shadow root: an XPath cannot reach into one, so it would find nothing on replay.
148
148
  const xpath = (e) => inShadow(e) ? '' : xpathOf(e);
149
149
  const xpathOf = (e) => { const parts = []; for (; e && e.nodeType === 1; e = e.parentElement) { let i = 1; for (let s = e.previousElementSibling; s; s = s.previousElementSibling) if (s.tagName === e.tagName) i++; parts.unshift(e.tagName.toLowerCase() + '[' + i + ']'); } return parts.join('/'); };
150
+ // ---- a relative XPath: anchored on what the page says, never on where the element sits ------------------------
151
+ // An absolute path (/html[1]/body[1]/div[1]/…) breaks when anything above the element moves. These are built from
152
+ // the element's own identifying attribute or its text, and where that is not unique, from a text that identifies an
153
+ // ancestor, so the path survives a re-ordered page. Page text goes in as an XPath string literal only (xpLit), so a
154
+ // quote in it can never end the literal and add a step of its own.
155
+ const XP_TEXT_MAX = 60;
156
+ // A framework's own attribute value (ember1423, :r3:, a hash): it changes on the next load, so it is never put in
157
+ // a path. A long run of digits counts here, where an attribute is concerned.
158
+ const XP_GEN = /\d{4,}|^(?=[0-9a-f]*\d)(?=[0-9a-f]*[a-f])[0-9a-f]{8,}$|:[rR][0-9a-zA-Z]*:|^(?:ember|mui-|react-select-|headlessui-|radix-|yui_|j_id|__)/i;
159
+ // Text the page shows is judged more narrowly (memory.py TEXT_GEN): an order or invoice number ("INV-1042") is the
160
+ // steadiest anchor a row has, so digits alone never rule a text out. Only an opaque token does.
161
+ const XP_GEN_TEXT = new RegExp(CFG.textGen, 'i');
162
+ const XP_ATTRS = ['data-testid', 'data-test-id', 'data-test', 'data-qa', 'data-cy', 'id', 'name', 'aria-label', 'placeholder', 'title', 'alt'];
163
+ const xpLit = (s) => s.indexOf("'") < 0 ? "'" + s + "'" : s.indexOf('"') < 0 ? '"' + s + '"'
164
+ : 'concat(' + s.split("'").map((p) => "'" + p + "'").join(', "\'", ') + ')';
165
+ const xpCount = (xp) => { try { return document.evaluate('count(' + xp + ')', document, null, XPathResult.NUMBER_TYPE, null).numberValue; } catch (err) { return -1; } };
166
+ // What identifies the element itself: a stable attribute, else its own text.
167
+ const xpOwn = (f) => {
168
+ for (const k of XP_ATTRS) { const v = f.attributes[k]; if (v && v.length <= 120 && !XP_GEN.test(v)) return '[@' + k + '=' + xpLit(v) + ']'; }
169
+ const t = norm(f.text || f.name);
170
+ return t && t.length <= XP_TEXT_MAX && !XP_GEN_TEXT.test(t) ? '[normalize-space()=' + xpLit(t) + ']' : '';
171
+ };
172
+ const relXpath = (e, f) => {
173
+ // An XPath cannot reach into a shadow root, so there is nothing to build (xpathOf does the same).
174
+ if (inShadow(e)) return '';
175
+ const own = xpOwn(f);
176
+ const self = '//' + f.tag + own;
177
+ // Its own attribute or text is enough, where that finds only it. With neither, only the anchored form below can
178
+ // tell it from the other elements of its tag, so a bare "//input" is never the answer.
179
+ if (own && xpCount(self) === 1) return self;
180
+ // Not unique on its own: the item that holds it (a card, a row), reached from a text only that item has. The
181
+ // ancestor axis takes the nearest one, so a wrapper that holds every card does not match as well.
182
+ const mine = norm(f.text || f.name);
183
+ const tail = '//' + f.tag + own;
184
+ for (let box = up(e), i = 0; box && i < 6 && box !== document.body && box !== document.documentElement; box = up(box), i++) {
185
+ if (box.nodeType !== 1 || inShadow(box)) continue;
186
+ const btag = box.tagName.toLowerCase();
187
+ for (const t of anchorTexts(box, mine, [box], e)) {
188
+ if (!t || t.length > XP_TEXT_MAX || XP_GEN_TEXT.test(t)) continue;
189
+ const xp = '//*[normalize-space()=' + xpLit(t) + ']/ancestor::' + btag + '[1]' + tail;
190
+ if (xpCount(xp) === 1) return xp;
191
+ }
192
+ }
193
+ return '';
194
+ };
195
+
150
196
  const facts = (e) => {
151
197
  const attrs = {};
152
198
  for (const k of CFG.kept) { const v = e.getAttribute(k); if (v) attrs[k] = v; }
153
199
  const name = accName(e);
154
200
  // Never a state class (active, selected, is-open): it moves to another element (memory.py STATE_CLASS).
155
201
  const classes = [...e.classList].filter((c) => /^[A-Za-z_-][\w-]*$/.test(c) && !STATE_CLASS.test(c)).slice(0, 4);
156
- return { tag: e.tagName.toLowerCase(), attributes: attrs, classes, xpath: xpath(e), role: e.getAttribute('role') || implicitRole(e), name: name.slice(0, 120), text: name ? '' : textOf(e).slice(0, 120) };
202
+ const f = { tag: e.tagName.toLowerCase(), attributes: attrs, classes, xpath: xpath(e), role: e.getAttribute('role') || implicitRole(e), name: name.slice(0, 120), text: name ? '' : textOf(e).slice(0, 120) };
203
+ const rel = relXpath(e, f);
204
+ if (rel) f.rel_xpath = rel;
205
+ return f;
157
206
  };
158
207
  // How many elements each kind of locator for `e` matches right now, counted at the event: ForgeQE checks locators
159
208
  // through the DevTools protocol, but a click that opens another page can take the element away before it looks.
@@ -178,6 +227,8 @@ RECORDER_JS = r"""(() => {
178
227
  if (/\d/.test(f.name) || f.name.length > 80) out.role_names = same.slice(0, 400).map((x) => accName(x).slice(0, 160));
179
228
  }
180
229
  if (f.name) out.label = deepAll('input, select, textarea, [aria-label]', rs).filter((x) => labelText(x) === f.name).length;
230
+ // The relative path is counted here too: it is built to find one element, and a page can still hold a second.
231
+ if (f.rel_xpath) out.rel_xpath = xpCount(f.rel_xpath);
181
232
  return out;
182
233
  };
183
234
  const shown = (e) => {
@@ -190,7 +241,11 @@ RECORDER_JS = r"""(() => {
190
241
  // Nine cards with the same "Book online now" button: the card that holds it, by a text only that card has ("FABIA
191
242
  // Auto"), then the button inside it, as Playwright writes it: getByRole('listitem').filter({ hasText }).getByRole(…).
192
243
  // A field with no label of its own is found the same way, by the text beside it in the group that holds it.
193
- const CONTAINER_ROLES = new Set(['listitem', 'row', 'article', 'dialog', 'group', 'tabpanel', 'gridcell', 'cell']);
244
+ // Roles a thing that holds other things has. Only roles Playwright matches without an accessible name: `region` and
245
+ // `form` need one, so a <section> or a <form> is addressed by its tag below instead.
246
+ const CONTAINER_ROLES = new Set(['listitem', 'row', 'article', 'dialog', 'alertdialog', 'group', 'tabpanel', 'gridcell',
247
+ 'cell', 'status', 'alert', 'list', 'table', 'grid', 'rowgroup', 'menu', 'menubar', 'toolbar', 'tablist', 'figure',
248
+ 'note', 'tooltip', 'log', 'banner', 'main', 'navigation', 'complementary', 'contentinfo', 'treegrid', 'tree']);
194
249
  const containerRole = (x) => {
195
250
  const r = x.getAttribute('role');
196
251
  if (r) return CONTAINER_ROLES.has(r) ? r : '';
@@ -201,13 +256,31 @@ RECORDER_JS = r"""(() => {
201
256
  if (x.tagName === 'FIELDSET') return 'group';
202
257
  return '';
203
258
  };
259
+ // Tags that hold other things and are worth addressing by the tag alone: which one is meant is settled by the text
260
+ // filter, and the count below proves only one of them has that text.
261
+ const CONTAINER_TAGS = new Set(['section', 'article', 'aside', 'nav', 'header', 'footer', 'main', 'form', 'fieldset',
262
+ 'figure', 'details', 'dialog', 'table', 'thead', 'tbody', 'tr', 'td', 'th', 'li', 'dl', 'dd', 'blockquote']);
263
+ // An attribute that names a container and carries no value of its own making. The value is put in a selector, so a
264
+ // quote or an angle bracket in it rules it out rather than being escaped away.
265
+ const CONTAINER_ATTRS = ['data-testid', 'data-test-id', 'data-test', 'data-qa', 'data-cy', 'aria-label'];
266
+ const plainAttr = (v) => !!v && v.length <= 80 && !/["'\\<>\u0000-\u001f]/.test(v) && !XP_GEN.test(v);
204
267
  const stableClass = (c) => /^[A-Za-z][\w-]{2,40}$/.test(c) && !/\d{3,}|__|^(?:css|sc|jsx|svelte|emotion)-/i.test(c) && !STATE_CLASS.test(c);
205
268
  // A class a page sets for a state (the item under the pointer, the one chosen, a menu open): it moves between elements.
206
269
  const STATE_CLASS = new RegExp(CFG.stateClass, 'i');
207
270
  // A web component by its tag alone (memory.py _COMPONENT_TAG): <promo-card>, whose controls are in its shadow root.
208
271
  const COMPONENT_TAG = /^[a-z][a-z0-9]{0,30}(?:-[a-z0-9]{1,30}){1,4}$/;
209
272
  const componentTag = (x) => { const t = x.tagName.toLowerCase(); return COMPONENT_TAG.test(t) ? t : ''; };
210
- const containerCss = (x) => { const c = [...x.classList].find(stableClass); return c ? x.tagName.toLowerCase() + '.' + c : componentTag(x); };
273
+ const containerCss = (x) => {
274
+ const tag = x.tagName.toLowerCase();
275
+ // Its own test id or label first: a card a repository marked is the steadiest container there is.
276
+ for (const k of CONTAINER_ATTRS) { const v = x.getAttribute(k); if (plainAttr(v)) return '[' + k + '="' + v + '"]'; }
277
+ const c = [...x.classList].find(stableClass);
278
+ if (c) return tag + '.' + c;
279
+ const comp = componentTag(x);
280
+ if (comp) return comp;
281
+ // A tag that holds things, with nothing else to go on (a <section> whose classes a build makes up).
282
+ return CONTAINER_TAGS.has(tag) ? tag : '';
283
+ };
211
284
  const lowText = (x) => norm(x.textContent).toLowerCase();
212
285
  // A component's own roots: it, its open shadow roots, and the one the element is in (a closed root is reached only
213
286
  // from inside it), so what it holds is searched where it is, not only in its light DOM.
@@ -219,7 +292,12 @@ RECORDER_JS = r"""(() => {
219
292
  return out;
220
293
  };
221
294
  const boxText = (box, e) => norm(boxRoots(box, e).map((r) => (r === box ? flatText(box) : r === box.shadowRoot ? '' : flatText(r))).join(' ')).toLowerCase();
222
- // The texts that could tell this container from the others: its headings, then its labels, then short texts of its own.
295
+ // A text that reports a state or a running total rather than naming the thing: a status ("Overdue", "Active"), an
296
+ // amount, a time, a date, a count. It is a poor anchor — it changes while the thing it sits in stays the same — so
297
+ // it is kept, but only after every steadier text.
298
+ const SHAKY_TEXT = new RegExp(CFG.shakyText, 'i');
299
+ // The texts that could tell this container from the others: its headings, then its labels, then short texts of its
300
+ // own — each group with the texts that name a thing before the ones that report its state.
223
301
  const anchorTexts = (box, own, rs = [box], self = null) => {
224
302
  const out = [];
225
303
  const add = (t, at) => { t = norm(t); if (t && t.length <= 80 && t !== own && !(self && at && deepContains(self, at)) && !out.includes(t)) out.push(t); };
@@ -231,7 +309,10 @@ RECORDER_JS = r"""(() => {
231
309
  // Never the control's own text (a "×" of a Close): it tells nothing of which container this is.
232
310
  for (let n = walker.nextNode(); n && k < 40; n = walker.nextNode(), k++) if (!['STYLE', 'SCRIPT', 'TEMPLATE'].includes(n.parentNode && n.parentNode.nodeName)) add(n.data, n.parentNode);
233
311
  }
234
- return out.slice(0, 12);
312
+ // A steady text first, in the order it was found; a state or an amount only after them.
313
+ const steady = out.filter((t) => !SHAKY_TEXT.test(t.trim()));
314
+ const shaky = out.filter((t) => SHAKY_TEXT.test(t.trim()));
315
+ return [...steady, ...shaky].slice(0, 12);
235
316
  };
236
317
  const innerOf = (e, f, box, rs = [box]) => {
237
318
  const inBox = (sel) => rs.flatMap((r) => [...r.querySelectorAll(sel)]).filter(visible);
@@ -1065,5 +1146,5 @@ def recorder_js(binding: str, kept: Any, *, leader: Dict[str, Any], badge: bool
1065
1146
  The page script; ``badge``: no panel, only a badge that says it records (a recording started from the web app);
1066
1147
  ``pw``: the saved logins' password fingerprints for this recording (recordsession.password_prints), never a password.
1067
1148
  """
1068
- config = {"binding": binding, "kept": list(kept), "leader": leader, "commands": [list(c) for c in COMMAND_KEYS], "badge": bool(badge), "stateClass": STATE_CLASS, **({"pw": pw} if pw else {})}
1149
+ config = {"binding": binding, "kept": list(kept), "leader": leader, "commands": [list(c) for c in COMMAND_KEYS], "badge": bool(badge), "stateClass": STATE_CLASS, "textGen": TEXT_GEN, "shakyText": SHAKY_TEXT, **({"pw": pw} if pw else {})}
1069
1150
  return RECORDER_JS.replace("__CONFIG__", json.dumps(config))
@@ -1,7 +1,7 @@
1
1
  """ForgeQE's Tosca reader: Tricentis Tosca .tsu exports → NTIR (neutral test JSON) and a readable view per test case.
2
2
 
3
- The .tsu graph is read by ToscaTSU's parser (vendor/toscatsu, MIT, unchanged); this package wraps it, adds what the
4
- Tosca agent needs (routes by engine, tool-neutral locators, secrets as variable names, fidelity anchors), and never
3
+ The .tsu graph is read by ToscaTSU's parser (vendor/toscatsu, MIT, unchanged); this package wraps it, adds what
4
+ Bridge needs (routes by engine, tool-neutral locators, secrets as variable names, fidelity anchors), and never
5
5
  runs or trusts anything inside the export.
6
6
  """
7
7
  from __future__ import annotations
@@ -1,4 +1,4 @@
1
- """A test case's NTIR as plain text: what the Tosca agent and a person read in place of the binary .tsu.
1
+ """A test case's NTIR as plain text: what Bridge and a person read in place of the binary .tsu.
2
2
 
3
3
  Every action line carries its node id ([n12]) so the converted test can name the Tosca step it implements, and the
4
4
  fidelity check can match them. Values from the .tsu are quoted as data; secrets show only their variable's name.
@@ -1,4 +1,4 @@
1
- """Read a Tosca .tsu export safely, and index what the Tosca agent needs that ToscaTSU's manifest does not carry.
1
+ """Read a Tosca .tsu export safely, and index what Bridge needs that ToscaTSU's manifest does not carry.
2
2
 
3
3
  A .tsu is gzip-compressed JSON: {"Entities": [{Surrogate, ObjectClass, Attributes, Assocs}, ...]}. It comes from
4
4
  someone else's workspace, so it is untrusted: its size is capped before and after unpacking, nothing in it is run, and
@@ -19,7 +19,7 @@ _CHUNK = 1024 * 1024
19
19
 
20
20
 
21
21
  class TsuError(Exception):
22
- """The file is not a .tsu the Tosca agent can read; the message says why in plain words."""
22
+ """The file is not a .tsu Bridge can read; the message says why in plain words."""
23
23
 
24
24
 
25
25
  def load(path: Path) -> Dict[str, Any]:
@@ -32,6 +32,9 @@ FORMAT = 1
32
32
  RATE_IN = 16_000
33
33
  MAX_SECONDS = 30
34
34
  MAX_TEXT = 600
35
+ # A hint of the project's names for Whisper: words, spaces and . _ ' - , only.
36
+ MAX_HINT = 300
37
+ HINT = re.compile(r"^[\w][\w .'\-,]*$")
35
38
  VOICE = re.compile(r"^[abh][fm]_[a-z]{2,12}$")
36
39
  # The voice fingerprint: 13 cepstral coefficients, their mean and spread over the voiced frames, as one unit vector.
37
40
  PRINT_COEFFS = 13
@@ -50,7 +53,8 @@ LANGUAGES = {"en", "de", "es", "fr", "it", "nl", "pt", "pl", "hi", "ja", "zh"}
50
53
  # never what anyone typed, so it only leans what is heard toward these spellings.
51
54
  PROMPT = (
52
55
  "ForgeQE, ADO, Azure DevOps, Jira, ACs, acceptance criteria, work item, user story, test case, test plan, "
53
- "TestMu, BrowserStack, Playwright, Cypress, Selenium, Appium, Maestro, Tosca, regression pack, staging, Record, runs."
56
+ "TestMu, BrowserStack, Playwright, Cypress, Selenium, Appium, Maestro, Tosca, regression pack, staging, Record, runs, "
57
+ "the last failed run."
54
58
  )
55
59
  # Hindi as people say it to ForgeQE: Hindi with its English terms ("मॉडल सेटिंग्स खोलो", "ADO से 256 के ACs"). Fixed.
56
60
  HI_PROMPT = "ForgeQE, ADO, Azure DevOps, Jira, ACs, TestMu, Playwright. मॉडल सेटिंग्स खोलो। मेरे फेल हुए रन दिखाओ। टेस्ट केस।"
@@ -125,7 +129,7 @@ class Voice:
125
129
  self.whisper = WhisperModel(str(models / "whisper-base"), device="cpu", compute_type="int8")
126
130
  # Hindi's listening model (whisper-small), loaded the first time Hindi is heard, when it was downloaded.
127
131
  self.whisper_hi = None
128
- self.kokoro = Kokoro(str(models / "kokoro" / "kokoro-v1.0.int8.onnx"), str(models / "kokoro" / "voices-v1.0.bin"))
132
+ self.kokoro = Kokoro(str(models / "kokoro" / "kokoro-v1.0.onnx"), str(models / "kokoro" / "voices-v1.0.bin"))
129
133
  self.voices = set(self.kokoro.get_voices())
130
134
 
131
135
  def transcribe(self, req: dict) -> dict:
@@ -147,6 +151,10 @@ class Voice:
147
151
  self.whisper_hi = WhisperModel(str(small), device="cpu", compute_type="int8")
148
152
  if self.whisper_hi is not None:
149
153
  model, prompt = self.whisper_hi, HI_PROMPT
154
+ # The project's own names (checked by the gateway's cleanHint, and again here): words only, short.
155
+ hint = req.get("hint")
156
+ if isinstance(hint, str) and 0 < len(hint) <= MAX_HINT and HINT.match(hint):
157
+ prompt = f"{prompt} {hint}."
150
158
  segments, _ = model.transcribe(audio, language=language, beam_size=1, vad_filter=True, initial_prompt=prompt, condition_on_previous_text=False)
151
159
  out = {"text": " ".join(s.text.strip() for s in segments).strip()}
152
160
  # The voice's fingerprint, only when the page asked for it (Talk's wake word is on).
@@ -0,0 +1,102 @@
1
+ ---
2
+ name: playwright-automation
3
+ description: "Use when the repository's browser tests are Playwright in any language — TypeScript or JavaScript (@playwright/test, playwright.config.ts), Python (pytest-playwright), Java (JUnit/TestNG) or .NET (MSTest/NUnit/xUnit): where its settings and fixtures live, narrowing a locator instead of indexing, strict mode, sign-in state, frames and shadow DOM, reading a ForgeQE recording handoff, and the command that runs one test."
4
+ agents: [scribe]
5
+ ---
6
+
7
+ # Playwright
8
+
9
+ This adds Playwright's own mechanics to the test rules you already have; it never replaces them. Where a rule
10
+ says what to do (locator order, retrying assertions, overlays, test data, repository conventions), that rule
11
+ stands — what follows is how Playwright does it.
12
+
13
+ The browser API is the same in every language; the names and the runner differ. Read the reference for the
14
+ repository's language before writing code:
15
+
16
+ - `references/typescript.md` — TypeScript / JavaScript (`@playwright/test`, the full runner)
17
+ - `references/python.md` — Python (`pytest-playwright`)
18
+ - `references/java.md` — Java (JUnit 5 / TestNG, Maven or Gradle)
19
+ - `references/dotnet.md` — .NET (NUnit, MSTest, xUnit)
20
+
21
+ ## Read the setup first
22
+ - Find the runner's config and note base URL, browser, headless, timeouts, retries and trace. Each reference
23
+ names the file for its language and which settings belong in it.
24
+ - Find the base class or fixture the repository's tests use, and its page objects. New tests use them; never
25
+ build a browser by hand when the repository hands one out.
26
+ - Find how sign-in is done and reuse the saved storage state. Sign in inside a test only when sign-in is the
27
+ thing under test.
28
+
29
+ ## Never install anything
30
+ - Do not run `npm install`, `pip install`, `playwright install`, `playwright.ps1 install`, `mvn dependency:get`,
31
+ `dotnet add package`, or any other installer. Packages and browsers are installed by ForgeQE. If something is
32
+ missing, name the package or browser and the version and stop.
33
+ - Do not edit a manifest or lockfile (`package.json`, `package-lock.json`, `pyproject.toml`,
34
+ `requirements.txt`, `pom.xml`, `build.gradle`, `*.csproj`). Ask through your request tools instead.
35
+
36
+ ## Making a locator unique
37
+ - Narrow, do not index: `filter({ hasText, hasNotText, has, hasNot, visible })`, chaining,
38
+ `and()`, `or()`, `within(other)` (v1.64+: `saveButton.within(dialog)`), `visible()` (v1.63+).
39
+ - Strict mode is a signal, not an obstacle. When a one-element action throws because the locator matched
40
+ several, the locator is ambiguous: scope it to the container holding the one you mean.
41
+ - `getByTestId` reads `data-testid` by default. A repository can point it elsewhere (`testIdAttribute` in the
42
+ config, or `selectors.setTestIdAttribute()`), so check before using it; when unsure, use an attribute
43
+ selector.
44
+ - An accessible name comes from `aria-label`, `aria-labelledby`, a wired `<label>`, or the element's own text —
45
+ in that order. If a role locator will not match, the name you expect is probably not the computed one.
46
+ - `describe()` (v1.53+) names a locator in the trace and the report. Use it where an expression is unavoidably
47
+ opaque.
48
+
49
+ ## From ForgeQE's handoff
50
+ - A locator marked ✓ was verified against the live page during the run. Use it.
51
+ - A locator carrying a warning ("a framework made this value", "the page gave this element another value",
52
+ "this name holds data that changes") passes the run it was recorded on and fails the next. Never reach for it
53
+ first; use the steadier one listed beside it.
54
+ - A `within` locator is already the scoped form
55
+ (`getByRole('listitem').filter({ hasText: … }).getByRole(…)`). Keep it; do not flatten it to a path.
56
+ - A `role_pattern` or `text_pattern` locator matches the part of the name that holds. Keep the pattern; do not
57
+ spell out this run's value.
58
+ - A step shown with only an XPath means every semantic locator was checked and none was unique. Read the page
59
+ snapshot under that step and build a scoped locator from what it shows before falling back to the path.
60
+
61
+ ## The retrying assertions
62
+ These are the ones that retry, so these are the ones to use:
63
+ `toBeVisible`, `toBeHidden`, `toBeAttached`, `toHaveText`, `toContainText`, `toHaveValue`, `toHaveValues`,
64
+ `toHaveCount`, `toHaveAttribute`, `toHaveClass`, `toContainClass`, `toHaveCSS`, `toHaveId`, `toHaveJSProperty`,
65
+ `toBeChecked`, `toBeEnabled`, `toBeDisabled`, `toBeEditable`, `toBeEmpty`, `toBeFocused`, `toBeInViewport`,
66
+ `toHaveRole`, `toHaveAccessibleName`, `toHaveAccessibleDescription`, `toHaveAccessibleErrorMessage`,
67
+ `toMatchAriaSnapshot`, `toHaveScreenshot`; on the page, `toHaveTitle`, `toHaveURL`; on a response, `toBeOK`.
68
+
69
+ - A plain assertion on a value you read yourself (`isVisible()`, `textContent()`) does not retry, whatever it
70
+ is wrapped in.
71
+ - To wait for a request, create the response promise *before* the click that triggers it
72
+ (`waitForResponse` / `RunAndWaitForResponseAsync`), not after.
73
+ - `expect.soft`, `expect.poll` and `toPass` are the Node runner's only. In Python, Java and .NET use the test
74
+ framework's own retry.
75
+
76
+ ## Isolation and sign-in
77
+ - One context per test. Playwright gives a fresh context by default; state shared through a static field or a
78
+ module-level variable defeats it.
79
+ - Save sign-in once and load it. That file holds live session credentials: it belongs in `.gitignore`, never in
80
+ a commit. Read secret values from the environment and fail with a clear message when one is missing; add new
81
+ names to the repository's example file without values.
82
+ - Session storage is not saved with storage state; restore it by hand if the app needs it. For an app keeping
83
+ tokens in IndexedDB, enable the IndexedDB option when saving.
84
+ - If tests write server-side data, give each worker its own account.
85
+
86
+ ## Frames and shadow DOM
87
+ - A control in an iframe needs `frameLocator` / `frame_locator`; an ordinary locator will not cross into it.
88
+ The handoff names the frame chain for the step.
89
+ - Locators pierce **open** shadow roots; XPath does not. A closed root is unreachable — when the handoff says
90
+ the recording opened closed roots, do the same once in the fixture or base-class setup with the init script
91
+ the handoff gives, before the site loads.
92
+
93
+ ## Overlay handlers
94
+ The test rules say when to use a handler and when to use a helper. Playwright's part: the handler exists from
95
+ 1.42 (`addLocatorHandler` / `AddLocatorHandlerAsync`), takes the overlay's own container as its locator, and
96
+ its body runs on every action that the overlay blocks. Each reference gives the call for its language.
97
+
98
+ ## Running and finishing
99
+ - Run only the test you wrote, with the repository's own command, and read the failure before changing
100
+ anything. Record a trace on failure and read it rather than re-running blind.
101
+ - Never commit a focus marker, a headed flag, or a pause (`test.only`, `--headed`, `page.pause()`, `PWDEBUG`).
102
+ - Mock third parties you do not control (`route` / `RouteAsync`) rather than testing their live site.
@@ -0,0 +1,90 @@
1
+ # Playwright in .NET (C#)
2
+
3
+ Official statement: "Playwright is distributed as a .NET Standard 2.0 library. We recommend .NET 8"
4
+ (playwright.dev/dotnet/docs/intro). Match the `TargetFramework` in the repository's `.csproj`.
5
+
6
+ ## Read the setup first
7
+ - The test project: the `.csproj` referencing `Microsoft.Playwright.NUnit` (or `.MSTest`, `.Xunit`,
8
+ `.Xunit.v3`). Note its target framework, `Nullable`, `TreatWarningsAsErrors`, analyzers, and anything set in
9
+ `Directory.Build.props` and `.editorconfig`.
10
+ - Base classes: tests inherit `PageTest` (giving `Page`, `Context`, `Browser` and `Expect`), or `ContextTest` /
11
+ `BrowserTest`. Repositories usually add their own (`BaseTest : PageTest`) that signs in, sets context options
12
+ or starts tracing. Inherit the repository's base, never `PageTest` directly when one exists.
13
+ - Page objects: classes taking `IPage`, exposing `ILocator` properties, with `async Task` methods.
14
+
15
+ ## Shape of a test
16
+ ```csharp
17
+ using Microsoft.Playwright;
18
+ using Microsoft.Playwright.NUnit;
19
+
20
+ public class CheckoutTests : PageTest
21
+ {
22
+ [Test]
23
+ public async Task PlacesOrder()
24
+ {
25
+ await Page.GotoAsync("/cart");
26
+ await Page.GetByRole(AriaRole.Button, new() { Name = "Checkout" }).ClickAsync();
27
+ await Expect(Page.GetByRole(AriaRole.Heading, new() { Name = "Payment" })).ToBeVisibleAsync();
28
+ }
29
+ }
30
+ ```
31
+ Attributes by framework: NUnit `[TestFixture]`/`[Test]` with `[Parallelizable(ParallelScope.Self)]`;
32
+ MSTest `[TestClass]`/`[TestMethod]`; xUnit `[Fact]`.
33
+
34
+ ## Browser and context settings
35
+ - Launch settings live in the `.runsettings` file's `<Playwright>` section:
36
+ `<BrowserName>chromium</BrowserName>` and
37
+ `<LaunchOptions><Channel>chrome</Channel><Headless>true</Headless></LaunchOptions>`. It is used through
38
+ `dotnet test --settings <file>` or `<RunSettingsFilePath>` in the `.csproj`. `BROWSER` and `HEADED=1`
39
+ override it.
40
+ - Context settings (viewport, locale, time zone, base URL, storage state) go in an override of
41
+ `public override BrowserNewContextOptions ContextOptions()` in the base class.
42
+
43
+ ## Naming and style
44
+ - PascalCase with an `Async` suffix and `new() { ... }` option objects: `GotoAsync`, `FillAsync`,
45
+ `ToHaveTextAsync`, `FrameLocator`, `Context.StorageStateAsync(new() { Path = ... })`,
46
+ `.Filter(new() { HasText = "FABIA Auto" })`.
47
+ - Tests are `public async Task` methods that await every call. Never `.Result`, `.Wait()`, `Thread.Sleep` or
48
+ `Task.Delay`.
49
+ - Use `ConfigureAwait(false)` exactly where the repository does (an analyzer such as CA2007 asks for it).
50
+ Follow the analyzers so the build gains no warnings.
51
+ - Retrying assertions: `await Expect(locator).ToBeVisibleAsync()`, `ToHaveTextAsync`, `ToHaveValueAsync`,
52
+ `await Expect(Page).ToHaveURLAsync(...)`. Use `Assert.That` for plain values only, never on
53
+ `await locator.IsVisibleAsync()`.
54
+ - Wait for outcomes with `Page.WaitForURLAsync`, `Page.RunAndWaitForResponseAsync`, or an assertion.
55
+
56
+ ## The overlay handler's call
57
+ The test rules say when a handler is right and when a helper is. Playwright's call, from 1.42, registered in
58
+ `[SetUp]` of the base class:
59
+ ```csharp
60
+ await Page.AddLocatorHandlerAsync(banner, async () => {
61
+ await banner.GetByRole(AriaRole.Button, new() { Name = "Accept all", Exact = true }).ClickAsync();
62
+ await Expect(banner).ToBeHiddenAsync();
63
+ });
64
+ ```
65
+ In .NET terms, the rule that an "if present" helper may ignore only the overlay not showing means catching
66
+ `TimeoutException` alone — never `PlaywrightException`.
67
+
68
+ ## Run one test
69
+ ```bash
70
+ dotnet build <Tests.csproj>
71
+ dotnet test <Tests.csproj> --no-build --settings <file>.runsettings \
72
+ --filter "FullyQualifiedName~MyTests.CheckoutTests.PlacesOrder" --logger "console;verbosity=normal"
73
+ ```
74
+ `--filter "Category=Smoke"` runs a category. `HEADED=1` runs headed, `BROWSER=firefox` switches browser,
75
+ `PWDEBUG=1` opens the Inspector. Trace: `pwsh bin/Debug/<tfm>/playwright.ps1 show-trace trace.zip`.
76
+
77
+ Browsers are installed by ForgeQE, not by you. If one is missing, name it and stop; do not run
78
+ `playwright.ps1 install` or `dotnet tool install`.
79
+
80
+ ## Data, secrets, attributes
81
+ - Data: `[TestCase(...)]`, `[TestCaseSource(nameof(Cases))]`, or the repository's data files and builders.
82
+ - Secrets:
83
+ `Environment.GetEnvironmentVariable("SHOP_USER") ?? throw new InvalidOperationException("Set SHOP_USER")`.
84
+ If the repository reads `TestContext.Parameters` from `.runsettings`, follow that, without committing values.
85
+ - Match the repository's `[Category]`, `[Parallelizable]`, `[Description]` and naming. `PageTest` gives each
86
+ test its own context, so tests must not share state through static fields.
87
+
88
+ ## Gaps against the Node runner
89
+ No projects, sharding or HTML reporter. Isolation comes from the `PageTest` / `ContextTest` base classes;
90
+ parallelism from NUnit, MSTest or xUnit settings the repository already has.