@capagents/forgeqe 2.9.0 → 2.9.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 (123) hide show
  1. package/HOW_TO_USE.md +250 -22
  2. package/dist/docs-site/docs/desktop/index.html +45 -1
  3. package/dist/docs-site/docs/index.html +261 -4
  4. package/dist/docs-site/docs/search.js +1 -1
  5. package/dist/forgeqe.js +1671 -1623
  6. package/dist/web/assets/Agent-BNWcLTrm.js +4 -0
  7. package/dist/web/assets/ApiTests-CZFzjMKc.js +10 -0
  8. package/dist/web/assets/Browse-CeiK4X_V.js +2 -0
  9. package/dist/web/assets/{Chat-BcFP0BbA.js → Chat-BqXSNxV2.js} +3 -3
  10. package/dist/web/assets/CommandPalette-VSEzjRS1.js +1 -0
  11. package/dist/web/assets/Compare-Bjh-qB8C.js +1 -0
  12. package/dist/web/assets/Cost-BRtni21m.js +1 -0
  13. package/dist/web/assets/Data-Bzn351xU.js +6 -0
  14. package/dist/web/assets/Evidence-eM1ZsFF-.js +1 -0
  15. package/dist/web/assets/{Explore-Dw8S6DG1.js → Explore-D07Qbzyq.js} +2 -2
  16. package/dist/web/assets/Features-DFwuL5cN.js +1 -0
  17. package/dist/web/assets/Flags-pxSAu21R.js +2 -0
  18. package/dist/web/assets/Flaky-BdfqCR6j.js +1 -0
  19. package/dist/web/assets/ForceGraph-DC7NzeR4.js +1 -0
  20. package/dist/web/assets/Impact-CfnvrPzq.js +3 -0
  21. package/dist/web/assets/Jobs-CIKpgvcv.js +5 -0
  22. package/dist/web/assets/KindPage-OyYE9NU7.js +6 -0
  23. package/dist/web/assets/Migration-BQA6MOPN.js +2 -0
  24. package/dist/web/assets/Product-DNe8RV_H.js +7 -0
  25. package/dist/web/assets/Production-ClEiFS1u.js +1 -0
  26. package/dist/web/assets/Quality-BZnQcbb2.js +1 -0
  27. package/dist/web/assets/Readiness-Dk2KZZm4.js +1 -0
  28. package/dist/web/assets/Record-CSapdwkr.js +2 -0
  29. package/dist/web/assets/Regression-C7bZ5sSE.js +5 -0
  30. package/dist/web/assets/Reports-BWtgbiVp.js +2 -0
  31. package/dist/web/assets/{Response-DGl2R0A-.js → Response-DyvlQXek.js} +2 -2
  32. package/dist/web/assets/RunDiff-DWV5qdHx.js +1 -0
  33. package/dist/web/assets/{Runs-CkNWhAhe.js → Runs-CET6zwQu.js} +2 -2
  34. package/dist/web/assets/Steps-DUG1BKJb.js +2 -0
  35. package/dist/web/assets/TestCases-DyicRSqL.js +1 -0
  36. package/dist/web/assets/TestData-D2aWG3dq.js +2 -0
  37. package/dist/web/assets/TestDebt-DobUiGTz.js +1 -0
  38. package/dist/web/assets/Tosca-DvTni6va.js +3 -0
  39. package/dist/web/assets/WhatsNew-B3xewvk5.js +1 -0
  40. package/dist/web/assets/dataParts-rU9wRwfo.js +3 -0
  41. package/dist/web/assets/families-DWrv-fcS.js +1 -0
  42. package/dist/web/assets/filters-BDJYWuRV.js +1 -0
  43. package/dist/web/assets/fold-BgITvJex.js +1 -0
  44. package/dist/web/assets/frame-Dn34zQXO.js +4 -0
  45. package/dist/web/assets/index-BiMUTOBo.js +45 -0
  46. package/dist/web/assets/index-CGfii-zv.css +2 -0
  47. package/dist/web/assets/logos-C067hMmF.js +1 -0
  48. package/dist/web/assets/palette-Br50dJuQ.js +1 -0
  49. package/dist/web/assets/parts-CbA0h_uO.js +1 -0
  50. package/dist/web/assets/productParts-BxQnjrHo.js +1 -0
  51. package/dist/web/assets/qualityParts-Cn74cNyX.js +1 -0
  52. package/dist/web/assets/rows-X8lfgK8j.js +1 -0
  53. package/dist/web/assets/segmented-mcjXGwLg.js +1 -0
  54. package/dist/web/assets/{thread-BeaLQ_f4.js → thread-Bamx8xqR.js} +2 -2
  55. package/dist/web/assets/usePageChat-B-vpiXQ6.js +1 -0
  56. package/dist/web/index.html +4 -3
  57. package/docs/DESKTOP.md +48 -1
  58. package/docs/user-guide.html +261 -4
  59. package/package.json +1 -1
  60. package/prompts/README.md +1 -0
  61. package/prompts/impact-reader.md +8 -9
  62. package/prompts/tosca-assistant.md +47 -0
  63. package/prompts/tosca.md +3 -1
  64. package/py/forgeqe_desktop/agentdesktop_driver.py +57 -7
  65. package/py/forgeqe_desktop/handhooks.py +71 -22
  66. package/py/forgeqe_desktop/handrecord.py +7 -1
  67. package/py/forgeqe_desktop/heal.py +24 -2
  68. package/py/forgeqe_desktop/memory.py +54 -4
  69. package/py/forgeqe_desktop/pywinauto_driver.py +210 -12
  70. package/py/forgeqe_desktop/replay.py +10 -2
  71. package/py/forgeqe_desktop/service.py +9 -2
  72. package/py/forgeqe_desktop/ufo_runner.py +101 -1
  73. package/py/forgeqe_mobile/service.py +4 -1
  74. package/py/forgeqe_tosca/__init__.py +11 -1
  75. package/py/forgeqe_tosca/app.py +168 -0
  76. package/py/forgeqe_tosca/db.py +131 -0
  77. package/py/forgeqe_tosca/files.py +74 -0
  78. package/py/forgeqe_tosca/ntir.py +357 -5
  79. package/py/forgeqe_tosca/render.py +38 -0
  80. package/py/forgeqe_tosca/tsu.py +110 -0
  81. package/skills/tosca-knowledge/SKILL.md +14 -3
  82. package/skills/tosca-knowledge/references/api.md +54 -0
  83. package/dist/web/assets/Agent-BGwHbXbc.js +0 -4
  84. package/dist/web/assets/ApiTests-DSnZHRlF.js +0 -10
  85. package/dist/web/assets/Browse-Dx3pHGuG.js +0 -2
  86. package/dist/web/assets/CommandPalette-v6mqHZnU.js +0 -1
  87. package/dist/web/assets/Cost-C9LZdx1p.js +0 -1
  88. package/dist/web/assets/Data-DvbaOc9e.js +0 -6
  89. package/dist/web/assets/Evidence-Y1AeSzh5.js +0 -1
  90. package/dist/web/assets/Features-CjrVraBE.js +0 -1
  91. package/dist/web/assets/Flags-C_Qm0078.js +0 -2
  92. package/dist/web/assets/Flaky-DYgN586D.js +0 -1
  93. package/dist/web/assets/ForceGraph-CEH86-Z0.js +0 -1
  94. package/dist/web/assets/Impact-dBPp7aM2.js +0 -3
  95. package/dist/web/assets/Jobs-CSyN6YRx.js +0 -5
  96. package/dist/web/assets/KindPage-BQl-5bcd.js +0 -6
  97. package/dist/web/assets/Migration-COly7O-T.js +0 -2
  98. package/dist/web/assets/Product-7mM8tcxH.js +0 -7
  99. package/dist/web/assets/Production-De5CCUoP.js +0 -1
  100. package/dist/web/assets/Quality-Q_iqj3fk.js +0 -1
  101. package/dist/web/assets/Readiness-kU9kum_I.js +0 -1
  102. package/dist/web/assets/Record-CIhINuEz.js +0 -2
  103. package/dist/web/assets/Regression-CMQnH7dN.js +0 -5
  104. package/dist/web/assets/Reports-dUOe6_vN.js +0 -2
  105. package/dist/web/assets/RunDiff-BVRRIz3m.js +0 -1
  106. package/dist/web/assets/TestCases-exR7hRWd.js +0 -1
  107. package/dist/web/assets/TestData-yVPMg9kw.js +0 -2
  108. package/dist/web/assets/TestDebt-C3sM6cH0.js +0 -1
  109. package/dist/web/assets/Tosca-Bcalg1JU.js +0 -2
  110. package/dist/web/assets/WhatsNew-EFSt6xx2.js +0 -1
  111. package/dist/web/assets/dataParts-D33u08WR.js +0 -3
  112. package/dist/web/assets/families-Btjss8bN.js +0 -1
  113. package/dist/web/assets/frame-D3IhgCFt.js +0 -4
  114. package/dist/web/assets/index-D5sya6FK.css +0 -2
  115. package/dist/web/assets/index-v-k_CVn7.js +0 -45
  116. package/dist/web/assets/logos-CfpaNwbY.js +0 -1
  117. package/dist/web/assets/palette-X7hU78Wy.js +0 -1
  118. package/dist/web/assets/parts-B7YrlR3a.js +0 -1
  119. package/dist/web/assets/productParts-CAxyMnWJ.js +0 -1
  120. package/dist/web/assets/qualityParts-CN9JVKZN.js +0 -1
  121. package/dist/web/assets/rows-IEP4Jvfi.js +0 -1
  122. package/dist/web/assets/segmented-DBqHvZW3.js +0 -1
  123. package/dist/web/assets/usePageChat-D_3KsqBU.js +0 -1
@@ -10,9 +10,12 @@ Secrets: a Tosca-encrypted value is never kept. It becomes an environment variab
10
10
  """
11
11
  from __future__ import annotations
12
12
 
13
+ import json
13
14
  import re
14
15
  from typing import Any, Dict, List, Optional, Tuple
15
16
 
17
+ from . import app, db, files
18
+
16
19
  NTIR_VERSION = "1.0"
17
20
 
18
21
  ENCRYPTED_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}[A-Za-z0-9+/=]{20,}$")
@@ -61,9 +64,36 @@ def env_name(raw: str) -> str:
61
64
  return "TOSCA_" + s if s in RESERVED_ENV else s
62
65
 
63
66
 
67
+ SCHEME_RE = re.compile(r"^\s*([A-Za-z][A-Za-z0-9+.-]*):")
68
+
69
+
70
+ def url_problem(val: Dict[str, Any]) -> Optional[str]:
71
+ """Why an OpenUrl value cannot become a navigation: a literal start with a scheme other than http(s).
72
+
73
+ A value from the environment, a buffer or a parameter is checked by the test at run time; a literal
74
+ `javascript:`, `file:` or `data:` address is never turned into code.
75
+ """
76
+ first = val
77
+ if isinstance(val.get("concat"), list) and val["concat"]:
78
+ first = val["concat"][0]
79
+ lit = first.get("literal") if isinstance(first, dict) else None
80
+ if not isinstance(lit, str):
81
+ return None
82
+ m = SCHEME_RE.match(lit)
83
+ if m and m.group(1).lower() not in ("http", "https"):
84
+ return f"OpenUrl opens only http(s) addresses, not '{m.group(1).lower()}:'"
85
+ return None
86
+
87
+
88
+ # Engines whose steps the web and API conversion leaves for a person, by route.
89
+ OTHER_ENGINES = {"desktop": "A desktop", "mobile": "A mobile", "data": "A database or file"}
90
+
91
+
64
92
  class Builder:
65
- def __init__(self, manifest: Dict[str, Any], engines: Dict[str, str], route_of) -> None:
93
+ def __init__(self, manifest: Dict[str, Any], engines: Dict[str, str], route_of, api: Optional[Dict[str, Any]] = None) -> None:
66
94
  self.m = manifest
95
+ self.api = api or {}
96
+ self.controls: Dict[str, Dict[str, Dict[str, str]]] = {}
67
97
  self.meta = manifest.get("meta", {})
68
98
  self.engines = engines
69
99
  self.route_of = route_of
@@ -86,12 +116,23 @@ class Builder:
86
116
 
87
117
  def value(self, raw: str, resolved: Optional[str], element: str) -> Tuple[Dict[str, Any], Optional[str]]:
88
118
  """The NTIR value of a Tosca value, and a warning when it needs a person."""
119
+ # ToscaTSU resolves a {CP[...]} inside a longer value to "$CONFIG:Name" text: the raw value keeps the reference,
120
+ # so it becomes a variable's name (a token in "Bearer {CP[ApiToken]}" is never a literal).
121
+ if resolved and "$CONFIG:" in resolved and not resolved.startswith("$CONFIG:") and raw and "{CP[" in raw:
122
+ resolved = None
123
+ # It resolves a test-data reference {XL[Name]} to "$XL:Name" text, alone or inside a longer value: the raw value
124
+ # keeps the reference, so it is Tosca's test data (never a literal "$XL:..." typed into the app).
125
+ if resolved and "$XL:" in resolved and raw and "{XL[" in raw:
126
+ resolved = None
89
127
  v = resolved if resolved not in (None, "") else raw
90
128
  if v is None:
91
129
  v = ""
92
130
  if ENCRYPTED_RE.match(v):
93
131
  hint = raw[4:-2] if raw.startswith("{PL[") else element
94
132
  return self.secret_env(hint, f"Tosca-encrypted value for '{element}'"), None
133
+ m_xl = re.fullmatch(r"\$XL:([^\s{}$]{1,200})", v)
134
+ if m_xl:
135
+ return {"data": m_xl.group(1)}, f"{{XL[{m_xl.group(1)}]}} reads a TestCaseDesign / Excel value; map it to the target's test data"
95
136
  if v.startswith("$CONFIG:"):
96
137
  key = v[len("$CONFIG:"):]
97
138
  name = env_name(key)
@@ -128,6 +169,9 @@ class Builder:
128
169
 
129
170
  def pick(self, raw: str, resolved: Optional[str]) -> str:
130
171
  """The raw value when its buffer references name variables this test sets (keeps the link), else the resolved one."""
172
+ # ToscaTSU's "$XL:Name" / "$CONFIG:Name" text for a reference: the raw value keeps it (test data, a variable).
173
+ if resolved and raw and (("$XL:" in resolved and "{XL[" in raw) or ("$CONFIG:" in resolved and not resolved.startswith("$CONFIG:") and "{CP[" in raw)):
174
+ return raw
131
175
  refs = re.findall(r"\{B\[([^\]]+)\]\}", raw or "")
132
176
  if refs and all(r in self.vars for r in refs) and not re.search(r"\{(PL|CP)\[", raw):
133
177
  return raw
@@ -374,6 +418,10 @@ class Builder:
374
418
  out.append(self.unsupported(step, a, f"unknown ActionMode '{a.get('mode', '')}' on OpenUrl", module))
375
419
  continue
376
420
  val, warn = self.value(a.get("value") or "", a.get("value_resolved"), "Url")
421
+ bad = url_problem(val)
422
+ if bad:
423
+ out.append(self.unsupported(step, a, bad, module))
424
+ continue
377
425
  if warn:
378
426
  self.warnings.append(f"{step} / Url: {warn}")
379
427
  out.append({"kind": "action", "id": self.node_id(), "op": "navigate", "value": val, "tosca": self.anchor(step, a, "secret" in val)})
@@ -386,12 +434,32 @@ class Builder:
386
434
  out.append({"kind": "action", "id": self.node_id(), "op": "close", "tosca": self.anchor(step, a, False)})
387
435
  self.counts["actions"] += 1
388
436
  return out
437
+ # A file or Excel step that reads: a check the test makes on the file (files.py); TBox file modules too.
438
+ if files.is_file_step(module, self.engines.get(module, "")):
439
+ self.routes["data"] = self.routes.get("data", 0) + 1
440
+ return [files.file_node(self, step, s, module)]
389
441
  if module.startswith("TBox "):
390
442
  for a in s.get("actions", []):
391
- out.append(self.unsupported(step, a, f"Tosca TBox module '{module}' has no web equivalent; route it to the desktop agent or code it by hand", module))
443
+ out.append(self.unsupported(step, a, f"Tosca TBox module '{module}' has no equivalent in a converted test or workflow; a person codes it", module))
392
444
  return out
393
445
  route = self.route_of(self.engines.get(module, ""), module)
394
446
  self.routes[route] = self.routes.get(route, 0) + 1
447
+ if route == "api":
448
+ return self.api_nodes(step, s, module)
449
+ # A desktop or mobile step: read as any step, its control a workflow target (app.py) instead of a page's
450
+ # element. A case of such steps alone becomes a workflow (build); beside web or API steps each is a marked spot.
451
+ if route in ("desktop", "mobile"):
452
+ return self.app_nodes(step, s, module, route)
453
+ # A database step: a read-only query and its checks, which the target's own database client runs (db.py).
454
+ if route == "data" and db.is_database(self.engines.get(module, "")):
455
+ return [db.query_node(self, step, s, module)]
456
+ # A file or Excel step: never a web step, but a marked spot in the test for a person, with what it does.
457
+ if route in OTHER_ENGINES:
458
+ for a in s.get("actions", []):
459
+ node = self.unsupported(step, a, f"{OTHER_ENGINES[route]} step (module '{module}'): the web and API conversion cannot do it; a person codes it here", module)
460
+ node["engine"] = route
461
+ out.append(node)
462
+ return out
395
463
  for a in s.get("actions", []):
396
464
  mode = a.get("mode", "")
397
465
  raw = (a.get("locator") or {}).get("raw") or {}
@@ -414,6 +482,222 @@ class Builder:
414
482
  out.append(self.unsupported(step, a, f"unknown ActionMode '{mode}'"))
415
483
  return out
416
484
 
485
+ def split_app_steps(self, nodes: List[Dict[str, Any]], parts: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
486
+ """Runs of consecutive desktop or mobile nodes (one engine) as parts: an {kind: app_run} node in their place."""
487
+ out: List[Dict[str, Any]] = []
488
+ run: List[Dict[str, Any]] = []
489
+
490
+ def flush() -> None:
491
+ if not run:
492
+ return
493
+ engine = run[0]["engine"]
494
+ wf = app.workflow_of(engine, run)
495
+ if len(wf["steps"]) <= 2:
496
+ out.extend(self.mark_app_steps(list(run)))
497
+ else:
498
+ for n in run:
499
+ if n["kind"] in ("action", "assert"):
500
+ self.counts["actions" if n["kind"] == "action" else "asserts"] -= 1
501
+ self.counts["actions"] += 1
502
+ self.counts["app_runs"] = self.counts.get("app_runs", 0) + 1
503
+ k = len(parts) + 1
504
+ parts.append({"index": k, "engine": engine, "covers": [n.get("id", "") for n in run], **wf})
505
+ out.append({"kind": "app_run", "id": self.node_id(), "engine": engine, "part": k, "covers": [n.get("id", "") for n in run],
506
+ "tosca": run[0].get("tosca") or {}})
507
+ run.clear()
508
+
509
+ for n in nodes:
510
+ for key in ("body", "then", "else", "loop"):
511
+ if isinstance(n.get(key), list):
512
+ n[key] = self.split_app_steps(n[key], parts)
513
+ if n.get("engine") in ("desktop", "mobile") and (not run or run[0]["engine"] == n["engine"]):
514
+ run.append(n)
515
+ continue
516
+ flush()
517
+ if n.get("engine") in ("desktop", "mobile"):
518
+ run.append(n)
519
+ continue
520
+ out.append(n)
521
+ flush()
522
+ return out
523
+
524
+ def mark_app_steps(self, nodes: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
525
+ """Desktop and mobile nodes as marked spots (a case that also drives the web or an API)."""
526
+ out = []
527
+ for n in nodes:
528
+ for key in ("body", "then", "else"):
529
+ if isinstance(n.get(key), list):
530
+ n[key] = self.mark_app_steps(n[key])
531
+ if n.get("engine") in ("desktop", "mobile") and n.get("kind") in ("action", "assert"):
532
+ self.counts["actions" if n["kind"] == "action" else "asserts"] -= 1
533
+ t = n.get("tosca") or {}
534
+ a = {"element": t.get("element", ""), "mode": t.get("mode", ""), "property": "", "value": ""}
535
+ m = OTHER_ENGINES[n["engine"]]
536
+ u = self.unsupported(t.get("step", ""), a, f"{m} step: the web and API conversion cannot do it; a person codes it here")
537
+ u["id"], u["engine"], u["tosca"] = n["id"], n["engine"], t
538
+ out.append(u)
539
+ continue
540
+ out.append(n)
541
+ return out
542
+
543
+ def app_nodes(self, step: str, s: Dict[str, Any], module: str, route: str) -> List[Dict[str, Any]]:
544
+ """A desktop or mobile step's nodes: as a web step's, with the control's workflow target (app.app_target)."""
545
+ out: List[Dict[str, Any]] = []
546
+ engine = self.engines.get(module, "")
547
+ for a in s.get("actions", []):
548
+ mode = a.get("mode", "")
549
+ # The control's own properties from the export, then what the vendored reader kept.
550
+ raw = {**((self.controls.get(module) or {}).get(a.get("element", "")) or {}), **((a.get("locator") or {}).get("raw") or {})}
551
+ ref = f"app:{slug(module)}.{slug(a.get('element', ''))}"
552
+ tgt, why = app.app_target(route, engine, raw)
553
+ if mode in ("set", "input", "optionalSet"):
554
+ nodes = self.set_action(step, a, ref, mode == "optionalSet")
555
+ self.counts["actions"] += sum(1 for n in nodes if n["kind"] == "action")
556
+ elif mode in ("verify", "waitFor"):
557
+ self.counts["asserts"] += 1
558
+ nodes = [self.assert_action(step, a, ref, mode == "waitFor")]
559
+ else:
560
+ nodes = [self.unsupported(step, a, f"unknown ActionMode '{mode}'", module)]
561
+ for n in nodes:
562
+ n["engine"] = route
563
+ if n["kind"] in ("action", "assert"):
564
+ n["app_target"] = tgt
565
+ if not tgt:
566
+ n["app_reason"] = why
567
+ out += nodes
568
+ return out
569
+
570
+ # API steps ----------------------------------------------------------------------------------------------------
571
+ def api_path(self, module: str, element: str, mode: str) -> Optional[List[str]]:
572
+ """The attribute's path in its API module; for a name in both the request and the response, the side the
573
+ step's action is on (set: request; verify or buffer: response). None when that still leaves two."""
574
+ paths = ((self.api.get(module) or {}).get("paths") or {}).get(element) or []
575
+ if len(paths) == 1:
576
+ return list(paths[0])
577
+ if not paths:
578
+ return [element]
579
+ side = "response" if mode in ("verify", "waitFor", "bufferRead") else "request"
580
+ on_side = [p for p in paths if any(api_seg(x) == side for x in p)]
581
+ return list(on_side[0]) if len(on_side) == 1 else None
582
+
583
+ def api_expect(self, a: Dict[str, Any]) -> Tuple[str, Dict[str, Any]]:
584
+ """How a verify compares, and the value: Tosca's operators (==, !=, <, <=, >, >=) and * for "contains"."""
585
+ if (a.get("property") or "").strip().lower() == "exists":
586
+ truth = (a.get("value_resolved") or a.get("value") or "").strip().lower()
587
+ return ("exists" if truth != "false" else "absent"), {"literal": ""}
588
+ v = self.pick(a.get("value") or "", a.get("value_resolved")).strip()
589
+ match = "exact"
590
+ for op, m in ((">=", "gte"), ("<=", "lte"), ("!=", "not"), ("==", "exact"), (">", "gt"), ("<", "lt"), ("=", "exact")):
591
+ if v.startswith(op):
592
+ match, v = m, v[len(op):].strip()
593
+ break
594
+ else:
595
+ if v.startswith("*") or v.endswith("*"):
596
+ match, v = "contains", v.strip("*")
597
+ expected, warn = self.value(v, None, a.get("element", ""))
598
+ if warn:
599
+ self.warnings.append(f"{a.get('element', '')}: {warn}")
600
+ return match, expected
601
+
602
+ def api_nodes(self, step: str, s: Dict[str, Any], module: str) -> List[Dict[str, Any]]:
603
+ """One API step as a request (method, address, query, headers, path parameters, body), then a check for each
604
+ verify (status, header, a JSON value or the body) and a stored value for each buffer, all on the response of
605
+ the step's request, or of the last request when the step only checks (Tosca's response modules). An
606
+ attribute ForgeQE cannot place stays a marked note for a person."""
607
+ params = {api_seg(k): v for k, v in ((self.api.get(module) or {}).get("params") or {}).items()}
608
+ req: Dict[str, Any] = {}
609
+ for key, names in (("method", ("method", "httpmethod", "verb")), ("endpoint", ("endpoint", "baseurl", "url", "host", "server")), ("resource", ("resource", "resourcepath", "path", "uri"))):
610
+ raw = next((params[n] for n in names if params.get(n)), "")
611
+ if raw:
612
+ req[key] = self.value(raw, None, key)[0]
613
+ query: Dict[str, Any] = {}
614
+ headers: Dict[str, Any] = {}
615
+ path_params: Dict[str, Any] = {}
616
+ fields: List[Dict[str, Any]] = []
617
+ raw_body: Optional[Dict[str, Any]] = None
618
+ first: Optional[Dict[str, Any]] = None
619
+ after: List[Dict[str, Any]] = []
620
+ out: List[Dict[str, Any]] = []
621
+ for a in s.get("actions", []):
622
+ mode = a.get("mode", "")
623
+ element = a.get("element", "")
624
+ path = self.api_path(module, element, mode)
625
+ if path is None:
626
+ after.append(self.unsupported(step, a, f"'{element}' is in both the request and the response of API module '{module}'; a person places it", module))
627
+ continue
628
+ role, rest = api_role(path)
629
+ if mode in ("set", "input", "optionalSet"):
630
+ val, warn = self.value(a.get("value") or "", a.get("value_resolved"), element)
631
+ if warn:
632
+ self.warnings.append(f"{step} / {element}: {warn}")
633
+ if role in ("method", "endpoint", "resource"):
634
+ req[role] = val
635
+ elif role == "header" and rest:
636
+ headers[rest[0]] = val
637
+ elif role == "query" and rest:
638
+ query[rest[0]] = val
639
+ elif role == "pathparam" and rest:
640
+ path_params[rest[0]] = val
641
+ elif role == "body" and rest:
642
+ fields.append({"path": json_path(rest), "value": val})
643
+ elif role == "body":
644
+ raw_body = val
645
+ else:
646
+ after.append(self.unsupported(step, a, f"API attribute '{' / '.join(path)}' is not a part of a request ForgeQE knows (method, address, query, header, path parameter, body)", module))
647
+ continue
648
+ first = first or a
649
+ elif mode in ("verify", "waitFor"):
650
+ match, expected = self.api_expect(a)
651
+ base = {"kind": "assert", "id": "", "match": match, "expected": expected, "tosca": self.anchor(step, a, False)}
652
+ if role == "status":
653
+ node = {**base, "op": "api_status", "target": "status"}
654
+ elif role == "header" and rest:
655
+ node = {**base, "op": "api_header", "target": rest[0]}
656
+ elif role == "body" and rest:
657
+ node = {**base, "op": "api_json", "target": json_path(rest)}
658
+ elif role == "body":
659
+ node = {**base, "op": "api_body", "target": "body"}
660
+ else:
661
+ after.append(self.unsupported(step, a, f"API attribute '{' / '.join(path)}' is not a part of a response ForgeQE can check (status, header, body)", module))
662
+ continue
663
+ self.counts["asserts"] += 1
664
+ after.append(node)
665
+ elif mode == "bufferRead":
666
+ var = a.get("value") or a.get("explicit_name") or "value"
667
+ if role in ("status", "header", "body"):
668
+ target = "status" if role == "status" else rest[0] if role == "header" and rest else json_path(rest) if rest else "body"
669
+ self.counts["stores"] += 1
670
+ after.append({"kind": "store", "id": "", "op": "api_store", "var": var, "target": target, "property": {"status": "status", "header": "header", "body": "json" if rest else "body"}[role], "tosca": self.anchor(step, a, False)})
671
+ else:
672
+ after.append(self.unsupported(step, a, f"API attribute '{' / '.join(path)}' cannot be stored from a response", module))
673
+ else:
674
+ after.append(self.unsupported(step, a, f"unknown ActionMode '{mode}'", module))
675
+ has_checks = any(n["kind"] != "unsupported" for n in after)
676
+ if first is not None or (not has_checks and (req.get("method") or req.get("resource"))):
677
+ anchor = self.anchor(step, first or {"element": module, "mode": "set", "value": ""}, False)
678
+ node: Dict[str, Any] = {"kind": "action", "id": self.node_id(), "op": "api_request", "target": module, "tosca": anchor}
679
+ for k in ("method", "endpoint", "resource"):
680
+ if k in req:
681
+ node[k] = req[k]
682
+ for k, v in (("query", query), ("headers", headers), ("pathParams", path_params)):
683
+ if v:
684
+ node[k] = v
685
+ if fields:
686
+ node["payload"] = {"fields": fields}
687
+ elif raw_body is not None:
688
+ node["payload"] = {"raw": raw_body}
689
+ self.counts["actions"] += 1
690
+ out.append(node)
691
+ for n in after:
692
+ if n["id"] == "":
693
+ n["id"] = self.node_id()
694
+ out.append(n)
695
+ # A note made while reading the step took its id first: the step's ids go in the order its nodes are done.
696
+ ids = sorted((n["id"] for n in out), key=lambda i: int(i[1:]))
697
+ for n, i in zip(out, ids):
698
+ n["id"] = i
699
+ return out
700
+
417
701
  # Structure ----------------------------------------------------------------------------------------------------
418
702
  def body(self, steps: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
419
703
  root: List[Dict[str, Any]] = []
@@ -491,16 +775,27 @@ def chord(arg: str) -> str:
491
775
  return "+".join(out)
492
776
 
493
777
 
494
- def build(manifest: Dict[str, Any], case: Dict[str, Any], engines: Dict[str, str], route_of) -> Dict[str, Any]:
778
+ def build(manifest: Dict[str, Any], case: Dict[str, Any], engines: Dict[str, str], route_of, api: Optional[Dict[str, Any]] = None,
779
+ controls: Optional[Dict[str, Dict[str, Dict[str, str]]]] = None) -> Dict[str, Any]:
495
780
  """One test case's NTIR document."""
496
- b = Builder(manifest, engines, route_of)
781
+ b = Builder(manifest, engines, route_of, api)
782
+ b.controls = controls or {}
497
783
  body = b.body(manifest.get("steps") or [])
498
784
  meta = manifest.get("meta", {})
499
785
  for item in meta.get("unmapped") or []: # what ToscaTSU itself could not map stays visible even if NTIR could
500
786
  if not any(u["step"] == item.get("step") and u["element"] == item.get("element") and u["value"] == item.get("value") for u in b.unmapped):
501
787
  b.warnings.append(f"ToscaTSU: {item.get('step', '')} / {item.get('element', '')}: {item.get('reason', '')}")
502
788
  routes = sorted(r for r in b.routes)
503
- return {
789
+ apps = [r for r in routes if r in ("desktop", "mobile")]
790
+ workflow = None
791
+ parts: List[Dict[str, Any]] = []
792
+ if apps and any(r in ("web", "api") for r in routes):
793
+ # Beside web or API steps: each run of desktop or mobile steps becomes a small ForgeQE workflow the test replays
794
+ # at that point (a part); a run of which no step can be a workflow step stays a marked spot for a person.
795
+ body = b.split_app_steps(body, parts)
796
+ elif len(apps) == 1 and all(r in (apps[0], "unsupported") for r in routes):
797
+ workflow = app.workflow_of(apps[0], body)
798
+ doc = {
504
799
  "ntir_version": NTIR_VERSION,
505
800
  "source": {"tool": "tosca", "file": meta.get("source_file", ""), "project": meta.get("project", ""),
506
801
  "test_case": {"name": case.get("name") or meta.get("test_name", ""), "surrogate": case.get("surrogate") or meta.get("surrogate", ""),
@@ -514,3 +809,60 @@ def build(manifest: Dict[str, Any], case: Dict[str, Any], engines: Dict[str, str
514
809
  "body": body,
515
810
  "report": {"counts": b.counts, "unmapped": b.unmapped, "warnings": sorted(set(b.warnings))},
516
811
  }
812
+ if workflow is not None:
813
+ doc["workflow"] = workflow
814
+ if parts:
815
+ doc["parts"] = parts
816
+ return doc
817
+
818
+
819
+ def api_seg(s: str) -> str:
820
+ """A name compared without case, spaces, - or _ (Tosca writes "Status Code", "statusCode", "Query-Parameters")."""
821
+ return re.sub(r"[\s_\-]+", "", (s or "").lower())
822
+
823
+
824
+ API_ROLES = {
825
+ "method": ("method", "httpmethod", "verb"),
826
+ "endpoint": ("endpoint", "baseurl", "url", "host", "server"),
827
+ "resource": ("resource", "resourcepath", "path", "uri"),
828
+ "status": ("statuscode", "status", "httpstatus", "httpstatuscode", "responsecode"),
829
+ "header": ("headers", "header", "httpheaders"),
830
+ "query": ("queryparameters", "queryparams", "queryparameter", "query", "parameters"),
831
+ "pathparam": ("pathparameters", "pathparams", "pathparameter", "uriparameters", "resourceparameters", "templateparameters"),
832
+ "body": ("payload", "body", "content", "requestbody", "responsebody", "message"),
833
+ }
834
+
835
+
836
+ def api_role(path: List[str]) -> Tuple[str, List[str]]:
837
+ """What an API attribute is, by its path (Request / Response markers left out), and the path below it."""
838
+ rest = list(path)
839
+ while rest and api_seg(rest[0]) in ("request", "response", "httprequest", "httpresponse"):
840
+ rest = rest[1:]
841
+ if not rest:
842
+ return "unknown", []
843
+ head = api_seg(rest[0])
844
+ for role, names in API_ROLES.items():
845
+ if head in names:
846
+ below = rest[1:]
847
+ if role == "body":
848
+ # Tosca puts a JSON or XML root under the payload: it is the body itself.
849
+ while below and api_seg(below[0]) in ("json", "xml", "root", "object"):
850
+ below = below[1:]
851
+ if role in ("resource", "method", "endpoint", "status") and below:
852
+ return "unknown", rest
853
+ return role, below
854
+ return "unknown", rest
855
+
856
+
857
+ def json_path(parts: List[str]) -> str:
858
+ """A JSONPath from attribute names: an index ("0", "[0]", "Item 0") as [n], a name as .name or ['name']."""
859
+ out = "$"
860
+ for p in parts:
861
+ m = re.fullmatch(r"\[?(\d+)\]?|item\s*(\d+)", p.strip(), re.I)
862
+ if m:
863
+ out += f"[{m.group(1) or m.group(2)}]"
864
+ elif re.fullmatch(r"[A-Za-z_][A-Za-z0-9_]*", p):
865
+ out += f".{p}"
866
+ else:
867
+ out += "[" + json.dumps(p) + "]"
868
+ return out
@@ -65,6 +65,20 @@ def node_lines(n: Dict[str, Any], depth: int) -> List[str]:
65
65
  return out
66
66
  t = n.get("tosca", {})
67
67
  where = f" (Tosca step \"{t.get('step', '')}\", {t.get('mode', '')})" if t else ""
68
+ if k == "action" and n.get("op") == "api_request":
69
+ parts = [f"{pad}- {tag}API request {value_text(n['method']) if 'method' in n else '(method not set)'}"]
70
+ addr = [value_text(n[x]) for x in ("endpoint", "resource") if x in n]
71
+ parts.append(f"{pad} address: {' + '.join(addr) if addr else '(none: the module has no endpoint or resource)'}")
72
+ for key, label in (("pathParams", "path parameter"), ("query", "query parameter"), ("headers", "header")):
73
+ for name, v in (n.get(key) or {}).items():
74
+ parts.append(f"{pad} {label} {json.dumps(name, ensure_ascii=False)} = {value_text(v)}")
75
+ body = n.get("payload") or {}
76
+ for f in body.get("fields") or []:
77
+ parts.append(f"{pad} body {f['path']} = {value_text(f['value'])}")
78
+ if "raw" in body:
79
+ parts.append(f"{pad} body (as is) = {value_text(body['raw'])}")
80
+ parts[0] += where
81
+ return parts
68
82
  if k == "action":
69
83
  extra = ""
70
84
  if "value" in n:
@@ -89,6 +103,30 @@ def node_lines(n: Dict[str, Any], depth: int) -> List[str]:
89
103
  return [f"{pad}- {tag}set variable {n['var']} = {value_text(n['value'])}{where}"]
90
104
  if k == "wait":
91
105
  return [f"{pad}- {tag}wait {n['ms']} ms{where}"]
106
+ if k == "db":
107
+ # The statement and every value are data, quoted; the connection is never in the brief (TOSCA_DB_URL).
108
+ out = [f"{pad}- {tag}Database query (read only), with the target's database client on the connection string in the environment variable TOSCA_DB_URL{where}",
109
+ f"{pad} sql: {json.dumps(n['sql'], ensure_ascii=False)}"]
110
+ for prm in n.get("params") or []:
111
+ out.append(f"{pad} bind :{prm['name']} = {value_text(prm['value'])} (a bound parameter with the client's own placeholder, never pasted into the statement)")
112
+ for c in n.get("checks") or []:
113
+ out.append(f"{pad} check row {c['row']} column {json.dumps(c['column'], ensure_ascii=False)} {c.get('match', 'exact')} {value_text(c['expected'])}")
114
+ for st in n.get("stores") or []:
115
+ out.append(f"{pad} read row {st['row']} column {json.dumps(st['column'], ensure_ascii=False)} into variable {st['var']}")
116
+ return out
117
+ if k == "app_run":
118
+ return [f"{pad}- {tag}{n['engine'].capitalize()} steps {', '.join(n.get('covers') or [])}: ForgeQE's {n['engine']} workflow part {n['part']} does them; the test replays it here (see how below){where}"]
119
+ if k == "file":
120
+ # Read only: what Tosca set says where the file is and how to read it, quoted; the checks follow.
121
+ out = [f"{pad}- {tag}{'Excel' if n.get('op') == 'excel' else 'File'} check (read only), Tosca module {json.dumps(n.get('module', ''), ensure_ascii=False)}: find the file by its name among the files the test downloaded, else in the folder of the environment variable TOSCA_FILES_DIR{where}"]
122
+ for w in n.get("where") or []:
123
+ out.append(f"{pad} {json.dumps(w['name'], ensure_ascii=False)} = {value_text(w['value'])}")
124
+ for c in n.get("checks") or []:
125
+ prop = f" {json.dumps(c['property'], ensure_ascii=False)}" if c.get("property") else ""
126
+ out.append(f"{pad} check {json.dumps(c['name'], ensure_ascii=False)}{prop} {c.get('match', 'exact')} {value_text(c['expected'])}")
127
+ for st in n.get("stores") or []:
128
+ out.append(f"{pad} read {json.dumps(st['name'], ensure_ascii=False)} into variable {st['var']}")
129
+ return out
92
130
  if k == "unsupported":
93
131
  return [f"{pad}- {tag}NOT CONVERTIBLE: {n['reason']}{where}"]
94
132
  return [f"{pad}- {tag}{k}"]
@@ -211,6 +211,12 @@ class Index:
211
211
  engines: Dict[str, str] = field(default_factory=dict) # module name → engine
212
212
  entity_count: int = 0
213
213
  suites: List[Dict[str, Any]] = field(default_factory=list) # execution lists: name, folders, test case surrogates
214
+ # API modules (route "api"): their own settings (Method, Endpoint, Resource, ...) and each attribute's path from the
215
+ # module down, by the attribute's name, so a step value's place in the request or response is known.
216
+ api: Dict[str, Dict[str, Any]] = field(default_factory=dict)
217
+ # Desktop and mobile modules' controls: module name -> attribute name -> its technical properties (AutomationId,
218
+ # Name, ControlType, resource-id, ...), which the vendored reader keeps only when it can make a web locator of them.
219
+ controls: Dict[str, Dict[str, Dict[str, str]]] = field(default_factory=dict)
214
220
 
215
221
 
216
222
  # Tosca's own workspace folders: they say nothing about what a test is about, so they never become a folder of the suite.
@@ -288,6 +294,8 @@ def index(data: Dict[str, Any]) -> Index:
288
294
  if p and name_of(p) == "Engine" and isinstance(_attrs(p).get("Value"), str):
289
295
  engine = _attrs(p)["Value"]
290
296
  idx.engines[name_of(e)] = engine
297
+ idx.api = api_modules(data, ents, idx.engines)
298
+ idx.controls = app_controls(data, ents, idx.engines)
291
299
  for e in data["Entities"]:
292
300
  if e.get("ObjectClass") != "TestCase":
293
301
  continue
@@ -297,3 +305,105 @@ def index(data: Dict[str, Any]) -> Index:
297
305
  tc["area"] = area_of(tc["folders"])
298
306
  tc["suites"] = [s["name"] for s in idx.suites if tc["surrogate"] in s["cases"] and s["name"]]
299
307
  return idx
308
+
309
+
310
+ MAX_API_ATTRS = 5000
311
+
312
+
313
+ MAX_CONTROLS = 20000
314
+
315
+
316
+ def app_controls(data: Dict[str, Any], ents: Dict[str, Dict[str, Any]], engines: Dict[str, str]) -> Dict[str, Dict[str, Dict[str, str]]]:
317
+ """Each desktop or mobile module's controls by name, with their technical properties as text (sizes capped)."""
318
+ names = {name for name, engine in engines.items() if route_of(engine, name) in ("desktop", "mobile")}
319
+ if not names:
320
+ return {}
321
+ module_by_sur = {e["Surrogate"]: name_of(e) for e in data["Entities"] if e.get("ObjectClass") == "XModule" and name_of(e) in names}
322
+ params_of: Dict[str, Dict[str, str]] = {}
323
+ for p in data["Entities"]:
324
+ if p.get("ObjectClass") != "XParam" or not name_of(p):
325
+ continue
326
+ v = _attrs(p).get("Value")
327
+ if isinstance(v, str) and len(v) <= 1000:
328
+ for owner in _assocs(p, "ExtendableObject"):
329
+ params_of.setdefault(owner, {})[name_of(p)[:80]] = v
330
+ out: Dict[str, Dict[str, Dict[str, str]]] = {}
331
+ count = 0
332
+ for a in data["Entities"]:
333
+ if a.get("ObjectClass") != "XModuleAttribute":
334
+ continue
335
+ module = next((module_by_sur[m] for m in _assocs(a, "Module") if m in module_by_sur), None)
336
+ if not module:
337
+ # A nested control: its module is its top attribute's.
338
+ cur, seen = a, set()
339
+ while _assocs(cur, "ParentAttribute") and len(seen) < 40:
340
+ nxt = ents.get(_assocs(cur, "ParentAttribute")[0])
341
+ if not nxt or nxt["Surrogate"] in seen:
342
+ break
343
+ seen.add(nxt["Surrogate"])
344
+ cur = nxt
345
+ module = next((module_by_sur[m] for m in _assocs(cur, "Module") if m in module_by_sur), None)
346
+ if not module:
347
+ continue
348
+ count += 1
349
+ if count > MAX_CONTROLS:
350
+ break
351
+ props = dict(params_of.get(a["Surrogate"], {}))
352
+ for p in (ents.get(x) for x in _assocs(a, "Properties")):
353
+ if p and p.get("ObjectClass") == "XParam" and name_of(p) and isinstance(_attrs(p).get("Value"), str) and len(_attrs(p)["Value"]) <= 1000:
354
+ props[name_of(p)[:80]] = _attrs(p)["Value"]
355
+ out.setdefault(module, {}).setdefault(name_of(a)[:200], props)
356
+ return out
357
+
358
+
359
+ def api_modules(data: Dict[str, Any], ents: Dict[str, Dict[str, Any]], engines: Dict[str, str]) -> Dict[str, Dict[str, Any]]:
360
+ """Each API module's settings and attribute paths, read as data: names and values as text, sizes capped.
361
+
362
+ params: the module's XParams but its Engine (Method, Endpoint, Resource, ...), as Tosca's API Scan writes them.
363
+ paths: attribute name -> every path to an attribute of that name, from the module's top attribute down (a name
364
+ such as "id" can be in both the request's and the response's payload; the step's action tells them apart).
365
+ """
366
+ out: Dict[str, Dict[str, Any]] = {}
367
+ api_names = {name for name, engine in engines.items() if route_of(engine, name) == "api"}
368
+ if not api_names:
369
+ return out
370
+ module_by_sur = {e["Surrogate"]: name_of(e) for e in data["Entities"] if e.get("ObjectClass") == "XModule" and name_of(e) in api_names}
371
+ for sur, name in module_by_sur.items():
372
+ params: Dict[str, str] = {}
373
+ for p in (ents.get(x) for x in _assocs(ents[sur], "Properties")):
374
+ if p and p.get("ObjectClass") == "XParam" and name_of(p) and name_of(p) != "Engine":
375
+ v = _attrs(p).get("Value")
376
+ if isinstance(v, str) and len(v) <= 4000:
377
+ params[name_of(p)[:120]] = v
378
+ out[name] = {"params": params, "paths": {}}
379
+ parent: Dict[str, str] = {}
380
+ top: Dict[str, str] = {}
381
+ attrs = [e for e in data["Entities"] if e.get("ObjectClass") == "XModuleAttribute"]
382
+ for a in attrs:
383
+ ps = _assocs(a, "ParentAttribute")
384
+ if ps:
385
+ parent[a["Surrogate"]] = ps[0]
386
+ for m in _assocs(a, "Module"):
387
+ if m in module_by_sur:
388
+ top[a["Surrogate"]] = module_by_sur[m]
389
+ count = 0
390
+ for a in attrs:
391
+ chain = [a]
392
+ seen = {a["Surrogate"]}
393
+ cur = a["Surrogate"]
394
+ while cur in parent and parent[cur] not in seen and len(chain) < 40:
395
+ cur = parent[cur]
396
+ seen.add(cur)
397
+ if cur in ents:
398
+ chain.append(ents[cur])
399
+ module = top.get(chain[-1]["Surrogate"])
400
+ if not module:
401
+ continue
402
+ count += 1
403
+ if count > MAX_API_ATTRS:
404
+ break
405
+ path = [name_of(x)[:200] for x in reversed(chain)]
406
+ out[module]["paths"].setdefault(path[-1], [])
407
+ if path not in out[module]["paths"][path[-1]]:
408
+ out[module]["paths"][path[-1]].append(path)
409
+ return out
@@ -48,9 +48,20 @@ More in `references/locators.md`.
48
48
  - Contains checks (`*text*` in Tosca) assert containment; exact checks assert equality.
49
49
  - Secrets and configuration parameters are read from the environment at run time; `.env.example` lists them.
50
50
  - Mapping cookbooks per target: `references/mapping-playwright.md`, `references/mapping-cypress.md`,
51
- `references/mapping-selenium-webdriverio.md`. The NTIR format: `references/ntir.md`.
51
+ `references/mapping-selenium-webdriverio.md`. The NTIR format: `references/ntir.md`. API steps, per target:
52
+ `references/api.md`.
53
+
54
+ ## Tosca test data ({XL[...]})
55
+ A template test case reads its values from a TestCaseDesign test sheet, which a .tsu does not hold. When a person names
56
+ a data file for the plan, ForgeQE writes the case's rows to `tosca-data/<case>.json` in the target folder
57
+ (`{"rows": [{"Name": "value"}, ...]}`, keyed by the `{XL[Name]}` names). The test reads that file at run time and runs
58
+ once per row, the target's way: Playwright `for (const row of rows) test(...)` or `test.describe` per row; pytest
59
+ `@pytest.mark.parametrize`; JUnit 5 `@ParameterizedTest` with `@MethodSource`; NUnit `[TestCaseSource]`; Cypress
60
+ `rows.forEach((row) => it(...))`; WebdriverIO the same with `it`. Never copy the values into the code. A name like a
61
+ password is an environment variable (`TOSCA_DATA_PASSWORD`), read at run time and the same for every row.
52
62
 
53
63
  ## What cannot be converted as it is
54
- Desktop, SAP and mobile steps (other ForgeQE agents, later), TBox Window Operation / Start Program / Dialog, unknown
55
- ActionModes or tokens, and Tosca expressions or `{XL[]}` test data that need the target's own code. These stay in the
64
+ Desktop, SAP and mobile steps (other ForgeQE agents, later), API attributes that are not a part of a request or a
65
+ response ForgeQE knows (a timeout, a certificate), TBox Window Operation / Start Program / Dialog, unknown
66
+ ActionModes or tokens, and Tosca expressions that need the target's own code. `{XL[]}` test data with no data file named for it stays a TODO too; with one, the test is data-driven (see above). These stay in the
56
67
  test as `tosca: nX TODO <why>` comments; the test still runs.