qa-engineer 0.9.0

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 (232) hide show
  1. package/COMPATIBILITY.md +71 -0
  2. package/LICENSE +21 -0
  3. package/README.md +508 -0
  4. package/package.json +90 -0
  5. package/packages/installer/README.md +46 -0
  6. package/packages/installer/bin/qa.mjs +136 -0
  7. package/packages/installer/lib/agents/registry.mjs +209 -0
  8. package/packages/installer/lib/cli/commands.mjs +29 -0
  9. package/packages/installer/lib/cli/flags.mjs +64 -0
  10. package/packages/installer/lib/commands/doctor.mjs +190 -0
  11. package/packages/installer/lib/commands/install.mjs +291 -0
  12. package/packages/installer/lib/commands/onboard.mjs +163 -0
  13. package/packages/installer/lib/commands/repair.mjs +68 -0
  14. package/packages/installer/lib/commands/self-test.mjs +45 -0
  15. package/packages/installer/lib/commands/uninstall.mjs +167 -0
  16. package/packages/installer/lib/commands/update.mjs +69 -0
  17. package/packages/installer/lib/commands/verify.mjs +62 -0
  18. package/packages/installer/lib/constants.mjs +34 -0
  19. package/packages/installer/lib/core/bundle.mjs +124 -0
  20. package/packages/installer/lib/core/config.mjs +73 -0
  21. package/packages/installer/lib/core/conflict.mjs +29 -0
  22. package/packages/installer/lib/core/errors.mjs +29 -0
  23. package/packages/installer/lib/core/fs-safe.mjs +236 -0
  24. package/packages/installer/lib/core/hash.mjs +19 -0
  25. package/packages/installer/lib/core/lockfile.mjs +75 -0
  26. package/packages/installer/lib/core/logger.mjs +46 -0
  27. package/packages/installer/lib/core/manifest.mjs +89 -0
  28. package/packages/installer/lib/core/paths.mjs +74 -0
  29. package/packages/installer/lib/core/schema-validate.mjs +142 -0
  30. package/packages/installer/lib/core/skill-meta.mjs +75 -0
  31. package/packages/installer/lib/core/validate-install.mjs +152 -0
  32. package/packages/installer/lib/core/wrappers.mjs +91 -0
  33. package/packages/installer/lib/detect/environment.mjs +54 -0
  34. package/packages/installer/lib/detect/frameworks.mjs +94 -0
  35. package/packages/installer/lib/detect/project.mjs +126 -0
  36. package/packages/installer/lib/detect/recommend.mjs +85 -0
  37. package/packages/installer/lib/detect/scan.mjs +48 -0
  38. package/packages/installer/lib/ui/progress.mjs +32 -0
  39. package/packages/installer/lib/ui/theme.mjs +81 -0
  40. package/packages/installer/lib/version.mjs +47 -0
  41. package/packages/installer/package.json +28 -0
  42. package/packages/installer/schemas/qa-lock.schema.json +89 -0
  43. package/packages/installer/schemas/qa.config.schema.json +91 -0
  44. package/shared/analysis/lib/qa_analysis/__init__.py +11 -0
  45. package/shared/analysis/lib/qa_analysis/branding.json +9 -0
  46. package/shared/analysis/lib/qa_analysis/branding.py +175 -0
  47. package/shared/analysis/lib/qa_analysis/cli.py +129 -0
  48. package/shared/analysis/lib/qa_analysis/context.py +233 -0
  49. package/shared/analysis/lib/qa_analysis/contracts.py +158 -0
  50. package/shared/analysis/lib/qa_analysis/diff_guard.py +327 -0
  51. package/shared/analysis/lib/qa_analysis/discovery.py +113 -0
  52. package/shared/analysis/lib/qa_analysis/evidence.py +128 -0
  53. package/shared/analysis/lib/qa_analysis/har.py +58 -0
  54. package/shared/analysis/lib/qa_analysis/junit.py +80 -0
  55. package/shared/analysis/lib/qa_analysis/redaction.py +99 -0
  56. package/shared/analysis/lib/qa_analysis/taxonomy.py +98 -0
  57. package/shared/analysis/schemas/context.schema.json +82 -0
  58. package/shared/diagnostics/lib/qa_diagnostics/__init__.py +13 -0
  59. package/shared/diagnostics/lib/qa_diagnostics/cli.py +124 -0
  60. package/shared/diagnostics/lib/qa_diagnostics/engine.py +143 -0
  61. package/shared/diagnostics/lib/qa_diagnostics/internal_contracts.py +75 -0
  62. package/shared/diagnostics/lib/qa_diagnostics/prioritization.py +101 -0
  63. package/shared/diagnostics/lib/qa_diagnostics/repair.py +72 -0
  64. package/shared/diagnostics/lib/qa_diagnostics/root_cause.py +89 -0
  65. package/shared/diagnostics/lib/qa_diagnostics/timeline.py +71 -0
  66. package/shared/diagnostics/schemas/internal/analysis-result.schema.json +28 -0
  67. package/shared/diagnostics/schemas/internal/diagnosis.schema.json +55 -0
  68. package/shared/diagnostics/schemas/internal/execution-result-min.schema.json +34 -0
  69. package/shared/frameworks/cypress/lib/cypress_analysis.py +27 -0
  70. package/shared/frameworks/playwright/lib/playwright_analysis.py +167 -0
  71. package/shared/frameworks/registry.json +150 -0
  72. package/shared/frameworks/registry.mjs +37 -0
  73. package/shared/frameworks/registry.schema.json +74 -0
  74. package/shared/frameworks/selenium/lib/selenium_analysis.py +28 -0
  75. package/shared/frameworks/webdriverio/lib/webdriverio_analysis.py +24 -0
  76. package/shared/tooling/qa_tool.py +127 -0
  77. package/skills/README.md +31 -0
  78. package/skills/qa/README.md +19 -0
  79. package/skills/qa/SKILL.md +52 -0
  80. package/skills/qa/examples/routing.md +86 -0
  81. package/skills/qa/references/routing-map.md +33 -0
  82. package/skills/qa-api/README.md +19 -0
  83. package/skills/qa-api/SKILL.md +68 -0
  84. package/skills/qa-api/contracts/api-result.schema.json +51 -0
  85. package/skills/qa-api/examples/graphql-review.md +43 -0
  86. package/skills/qa-api/references/authentication.md +45 -0
  87. package/skills/qa-api/references/deterministic-tooling.md +128 -0
  88. package/skills/qa-api/references/evidence-and-reporting.md +66 -0
  89. package/skills/qa-api/references/graphql.md +44 -0
  90. package/skills/qa-api/references/rest.md +45 -0
  91. package/skills/qa-api/references/websocket.md +44 -0
  92. package/skills/qa-audit/README.md +19 -0
  93. package/skills/qa-audit/SKILL.md +70 -0
  94. package/skills/qa-audit/contracts/audit-result.schema.json +63 -0
  95. package/skills/qa-audit/examples/accessibility-audit.md +46 -0
  96. package/skills/qa-audit/references/accessibility.md +44 -0
  97. package/skills/qa-audit/references/deterministic-tooling.md +128 -0
  98. package/skills/qa-audit/references/evidence-and-reporting.md +66 -0
  99. package/skills/qa-audit/references/performance.md +44 -0
  100. package/skills/qa-audit/references/security.md +43 -0
  101. package/skills/qa-audit/references/visual-testing.md +44 -0
  102. package/skills/qa-debug/README.md +19 -0
  103. package/skills/qa-debug/SKILL.md +76 -0
  104. package/skills/qa-debug/contracts/debug-result.schema.json +121 -0
  105. package/skills/qa-debug/examples/failed-login.md +61 -0
  106. package/skills/qa-debug/examples/locator-break.md +59 -0
  107. package/skills/qa-debug/examples/network-timeout.md +61 -0
  108. package/skills/qa-debug/examples/successful-debug.md +62 -0
  109. package/skills/qa-debug/references/confidence-model.md +26 -0
  110. package/skills/qa-debug/references/deterministic-tooling.md +128 -0
  111. package/skills/qa-debug/references/diagnostic-engine.md +36 -0
  112. package/skills/qa-debug/references/evidence-and-reporting.md +66 -0
  113. package/skills/qa-debug/references/evidence-model.md +41 -0
  114. package/skills/qa-debug/references/failure-taxonomy.md +44 -0
  115. package/skills/qa-debug/references/finding-prioritization.md +43 -0
  116. package/skills/qa-debug/references/investigation-workflow.md +48 -0
  117. package/skills/qa-debug/references/recommendation-ranking.md +34 -0
  118. package/skills/qa-debug/references/root-cause-analysis.md +49 -0
  119. package/skills/qa-debug/references/timeline-builder.md +37 -0
  120. package/skills/qa-example/README.md +19 -0
  121. package/skills/qa-example/SKILL.md +60 -0
  122. package/skills/qa-example/contracts/self-check-report.schema.json +65 -0
  123. package/skills/qa-example/examples/self-check.md +53 -0
  124. package/skills/qa-example/references/example-domain.md +28 -0
  125. package/skills/qa-example/references/skill-format-notes.md +26 -0
  126. package/skills/qa-explore/README.md +22 -0
  127. package/skills/qa-explore/SKILL.md +87 -0
  128. package/skills/qa-explore/contracts/explore-result.schema.json +249 -0
  129. package/skills/qa-explore/examples/attached-test-cases.md +70 -0
  130. package/skills/qa-explore/examples/screenshot-proof-finding.md +50 -0
  131. package/skills/qa-explore/examples/url-smoke-explore.md +80 -0
  132. package/skills/qa-explore/references/accessibility.md +44 -0
  133. package/skills/qa-explore/references/api-replay.md +48 -0
  134. package/skills/qa-explore/references/browser-adapters.md +51 -0
  135. package/skills/qa-explore/references/evidence-and-reporting.md +66 -0
  136. package/skills/qa-explore/references/evidence-capture.md +54 -0
  137. package/skills/qa-explore/references/exploratory-qa.md +52 -0
  138. package/skills/qa-explore/references/finding-taxonomy.md +47 -0
  139. package/skills/qa-explore/references/performance.md +44 -0
  140. package/skills/qa-explore/references/pipeline.md +74 -0
  141. package/skills/qa-explore/references/report-pipeline.md +69 -0
  142. package/skills/qa-explore/references/security.md +43 -0
  143. package/skills/qa-explore/references/test-case-intake.md +44 -0
  144. package/skills/qa-fix/README.md +19 -0
  145. package/skills/qa-fix/SKILL.md +70 -0
  146. package/skills/qa-fix/contracts/fix-result.schema.json +132 -0
  147. package/skills/qa-fix/examples/repair-plan.md +56 -0
  148. package/skills/qa-fix/references/deterministic-tooling.md +128 -0
  149. package/skills/qa-fix/references/diagnostic-engine.md +36 -0
  150. package/skills/qa-fix/references/evidence-and-reporting.md +66 -0
  151. package/skills/qa-fix/references/repair-strategy.md +48 -0
  152. package/skills/qa-fix/references/root-cause-analysis.md +49 -0
  153. package/skills/qa-fix/references/suite-extension.md +73 -0
  154. package/skills/qa-flaky/README.md +19 -0
  155. package/skills/qa-flaky/SKILL.md +67 -0
  156. package/skills/qa-flaky/contracts/flaky-result.schema.json +62 -0
  157. package/skills/qa-flaky/examples/flaky-locator.md +46 -0
  158. package/skills/qa-flaky/references/deterministic-tooling.md +128 -0
  159. package/skills/qa-flaky/references/evidence-and-reporting.md +66 -0
  160. package/skills/qa-flaky/references/flakiness.md +48 -0
  161. package/skills/qa-flaky/references/retry.md +44 -0
  162. package/skills/qa-flaky/references/waiting-strategies.md +44 -0
  163. package/skills/qa-generate/README.md +42 -0
  164. package/skills/qa-generate/SKILL.md +83 -0
  165. package/skills/qa-generate/contracts/generation-result.schema.json +124 -0
  166. package/skills/qa-generate/examples/bootstrap-new-framework.md +24 -0
  167. package/skills/qa-generate/examples/extend-existing-suite.md +26 -0
  168. package/skills/qa-generate/references/code-style.md +29 -0
  169. package/skills/qa-generate/references/evidence-and-reporting.md +66 -0
  170. package/skills/qa-generate/references/framework-selection.md +88 -0
  171. package/skills/qa-generate/references/generation-strategy.md +48 -0
  172. package/skills/qa-generate/references/naming-conventions.md +27 -0
  173. package/skills/qa-generate/references/playwright-conventions.md +23 -0
  174. package/skills/qa-generate/references/playwright-generation.md +41 -0
  175. package/skills/qa-generate/references/playwright-project-discovery.md +42 -0
  176. package/skills/qa-generate/references/project-bootstrap.md +54 -0
  177. package/skills/qa-generate/references/repository-analysis.md +43 -0
  178. package/skills/qa-generate/references/suite-extension.md +73 -0
  179. package/skills/qa-generate/references/template-selection.md +48 -0
  180. package/skills/qa-generate/templates/playwright/api.ts +36 -0
  181. package/skills/qa-generate/templates/playwright/base-page.ts +14 -0
  182. package/skills/qa-generate/templates/playwright/data.ts +25 -0
  183. package/skills/qa-generate/templates/playwright/env.example +16 -0
  184. package/skills/qa-generate/templates/playwright/example.spec.ts +14 -0
  185. package/skills/qa-generate/templates/playwright/fixtures.ts +28 -0
  186. package/skills/qa-generate/templates/playwright/framework-readme.md +39 -0
  187. package/skills/qa-generate/templates/playwright/login.page.ts +26 -0
  188. package/skills/qa-generate/templates/playwright/playwright.config.ts +28 -0
  189. package/skills/qa-generate/templates/playwright/utils.ts +18 -0
  190. package/skills/qa-init/README.md +20 -0
  191. package/skills/qa-init/SKILL.md +72 -0
  192. package/skills/qa-init/examples/initialize-a-repo.md +91 -0
  193. package/skills/qa-init/references/detection-guide.md +76 -0
  194. package/skills/qa-init/references/deterministic-tooling.md +128 -0
  195. package/skills/qa-init/references/evidence-and-reporting.md +66 -0
  196. package/skills/qa-init/templates/context.md +68 -0
  197. package/skills/qa-report/README.md +19 -0
  198. package/skills/qa-report/SKILL.md +72 -0
  199. package/skills/qa-report/contracts/report-result.schema.json +186 -0
  200. package/skills/qa-report/examples/release-report.md +68 -0
  201. package/skills/qa-report/references/deterministic-tooling.md +128 -0
  202. package/skills/qa-report/references/diagnostic-engine.md +36 -0
  203. package/skills/qa-report/references/evidence-and-reporting.md +66 -0
  204. package/skills/qa-report/references/finding-prioritization.md +43 -0
  205. package/skills/qa-report/references/recommendation-ranking.md +34 -0
  206. package/skills/qa-report/references/report-aggregation.md +44 -0
  207. package/skills/qa-review/README.md +19 -0
  208. package/skills/qa-review/SKILL.md +58 -0
  209. package/skills/qa-review/contracts/review-result.schema.json +59 -0
  210. package/skills/qa-review/examples/suite-review.md +51 -0
  211. package/skills/qa-review/references/anti-patterns.md +49 -0
  212. package/skills/qa-review/references/assertion-patterns.md +45 -0
  213. package/skills/qa-review/references/evidence-and-reporting.md +66 -0
  214. package/skills/qa-review/references/fixtures.md +45 -0
  215. package/skills/qa-review/references/page-objects.md +45 -0
  216. package/skills/qa-run/README.md +22 -0
  217. package/skills/qa-run/SKILL.md +92 -0
  218. package/skills/qa-run/contracts/execution-plan.schema.json +132 -0
  219. package/skills/qa-run/contracts/execution-result.schema.json +204 -0
  220. package/skills/qa-run/examples/execute-playwright.md +89 -0
  221. package/skills/qa-run/examples/plan-a-run.md +83 -0
  222. package/skills/qa-run/references/artifact-collector.md +40 -0
  223. package/skills/qa-run/references/browser-launch.md +39 -0
  224. package/skills/qa-run/references/command-builder.md +39 -0
  225. package/skills/qa-run/references/deterministic-tooling.md +128 -0
  226. package/skills/qa-run/references/environment-detection.md +37 -0
  227. package/skills/qa-run/references/evidence-and-reporting.md +66 -0
  228. package/skills/qa-run/references/execution-strategy.md +54 -0
  229. package/skills/qa-run/references/playwright-artifacts.md +29 -0
  230. package/skills/qa-run/references/playwright-execution.md +48 -0
  231. package/skills/qa-run/references/playwright-project-discovery.md +42 -0
  232. package/skills/qa-run/references/report-normalization.md +49 -0
@@ -0,0 +1,158 @@
1
+ """Deterministic contract validation.
2
+
3
+ A dependency-free validator for the subset of JSON Schema the pack's contracts
4
+ use. It exists so no skill ever emits a result that violates its own contract,
5
+ and so CI can gate on it without a third-party dependency.
6
+
7
+ The supported subset is declared once, in `SUPPORTED_KEYWORDS`, and is the
8
+ **same** subset the JavaScript twin implements
9
+ (`packages/installer/lib/core/schema-validate.mjs`). Two rules keep that promise
10
+ honest:
11
+
12
+ 1. A keyword outside the subset is an **error**, never a silent no-op — a
13
+ contract author cannot accidentally write a constraint that looks enforced
14
+ and isn't.
15
+ 2. `tests/parity/validator-cases.json` runs through both validators and both
16
+ must agree on every case.
17
+
18
+ The subset includes `allOf` / `if` / `then` / `else` because the pack's safety
19
+ invariants are cross-field implications ("classification `passed` implies exit
20
+ code 0"). Those must be enforced at runtime by the contract itself, not only by
21
+ evaluation fixtures.
22
+
23
+ This validates the pack's own schemas; it is not a general-purpose JSON Schema
24
+ implementation, and it says so rather than pretending to be one.
25
+ """
26
+
27
+ import json
28
+ import re
29
+
30
+ _TYPES = {
31
+ "object": dict,
32
+ "array": list,
33
+ "string": str,
34
+ "number": (int, float),
35
+ "integer": int,
36
+ "boolean": bool,
37
+ "null": type(None),
38
+ }
39
+
40
+ # The complete supported subset. Anything else is reported as a schema error.
41
+ # Keep in sync with SUPPORTED in packages/installer/lib/core/schema-validate.mjs
42
+ # and the table in docs/skills/output-contracts.md (checked by
43
+ # scripts/check-spec-code-sync.mjs).
44
+ SUPPORTED_KEYWORDS = frozenset({
45
+ "$schema", "$id", "title", "description", "type", "properties", "required",
46
+ "additionalProperties", "items", "enum", "const", "pattern", "minimum",
47
+ "maximum", "minItems", "maxItems", "minLength", "maxLength", "default",
48
+ "examples", "format", "allOf", "if", "then", "else",
49
+ })
50
+
51
+ # RFC 3339 date-time. Defined here (rather than delegating to
52
+ # datetime.fromisoformat, which also accepts date-only strings and varies by
53
+ # interpreter version) so both validators accept exactly the same set.
54
+ _DATE_TIME = re.compile(
55
+ r"^\d{4}-\d{2}-\d{2}[Tt]\d{2}:\d{2}:\d{2}(\.\d+)?([Zz]|[+-]\d{2}:\d{2})$"
56
+ )
57
+
58
+
59
+ def load_schema(path):
60
+ with open(path, "r", encoding="utf-8") as handle:
61
+ return json.load(handle)
62
+
63
+
64
+ def validate(instance, schema, path="$"):
65
+ """Validate instance against schema. Returns (ok, errors) where errors is a
66
+ list of human-readable "path: problem" strings."""
67
+ errors = []
68
+ _validate(instance, schema, path, errors)
69
+ return (not errors, errors)
70
+
71
+
72
+ def _type_ok(value, expected):
73
+ types = expected if isinstance(expected, list) else [expected]
74
+ for name in types:
75
+ py = _TYPES.get(name)
76
+ if py is None:
77
+ continue
78
+ # bool is a subclass of int; keep them distinct.
79
+ if name == "integer" and isinstance(value, bool):
80
+ continue
81
+ if name == "number" and isinstance(value, bool):
82
+ continue
83
+ if isinstance(value, py):
84
+ return True
85
+ return False
86
+
87
+
88
+ def _matches(value, schema):
89
+ """True when value satisfies schema. Used for if/then branch selection, so
90
+ it must not leak errors into the caller's list."""
91
+ probe = []
92
+ _validate(value, schema, "$", probe)
93
+ return not probe
94
+
95
+
96
+ def _validate(value, schema, path, errors):
97
+ for keyword in schema:
98
+ if keyword not in SUPPORTED_KEYWORDS:
99
+ errors.append(f"{path}: schema uses unsupported keyword \"{keyword}\"")
100
+
101
+ if "type" in schema and not _type_ok(value, schema["type"]):
102
+ errors.append(f"{path}: expected type {schema['type']}, got {type(value).__name__}")
103
+ return # further checks assume the type held
104
+
105
+ if "const" in schema and value != schema["const"]:
106
+ errors.append(f"{path}: expected const {schema['const']!r}, got {value!r}")
107
+
108
+ if "enum" in schema and value not in schema["enum"]:
109
+ errors.append(f"{path}: {value!r} is not one of {schema['enum']}")
110
+
111
+ if isinstance(value, str):
112
+ if "pattern" in schema and not re.search(schema["pattern"], value):
113
+ errors.append(f"{path}: {value!r} does not match pattern {schema['pattern']}")
114
+ if schema.get("format") == "date-time" and not _DATE_TIME.match(value):
115
+ errors.append(f"{path}: {value!r} is not a valid date-time")
116
+ if "minLength" in schema and len(value) < schema["minLength"]:
117
+ errors.append(f"{path}: shorter than minLength {schema['minLength']}")
118
+ if "maxLength" in schema and len(value) > schema["maxLength"]:
119
+ errors.append(f"{path}: longer than maxLength {schema['maxLength']}")
120
+
121
+ if isinstance(value, (int, float)) and not isinstance(value, bool):
122
+ if "minimum" in schema and value < schema["minimum"]:
123
+ errors.append(f"{path}: {value} < minimum {schema['minimum']}")
124
+ if "maximum" in schema and value > schema["maximum"]:
125
+ errors.append(f"{path}: {value} > maximum {schema['maximum']}")
126
+
127
+ if isinstance(value, list):
128
+ if "minItems" in schema and len(value) < schema["minItems"]:
129
+ errors.append(f"{path}: fewer than minItems {schema['minItems']}")
130
+ if "maxItems" in schema and len(value) > schema["maxItems"]:
131
+ errors.append(f"{path}: more than maxItems {schema['maxItems']}")
132
+ if "items" in schema:
133
+ for i, item in enumerate(value):
134
+ _validate(item, schema["items"], f"{path}[{i}]", errors)
135
+
136
+ if isinstance(value, dict):
137
+ for key in schema.get("required", []):
138
+ if key not in value:
139
+ errors.append(f"{path}: missing required property '{key}'")
140
+ properties = schema.get("properties", {})
141
+ for key, sub in properties.items():
142
+ if key in value:
143
+ _validate(value[key], sub, f"{path}.{key}", errors)
144
+ if schema.get("additionalProperties") is False:
145
+ for key in value:
146
+ if key not in properties:
147
+ errors.append(f"{path}: additional property '{key}' is not allowed")
148
+
149
+ # Applicators last: the invariant layer. `additionalProperties` deliberately
150
+ # does not see properties introduced by these subschemas (same rule as
151
+ # JSON Schema 2020-12, and the same as the JavaScript twin).
152
+ for sub in schema.get("allOf", []):
153
+ _validate(value, sub, path, errors)
154
+
155
+ if "if" in schema:
156
+ branch = schema.get("then") if _matches(value, schema["if"]) else schema.get("else")
157
+ if branch is not None:
158
+ _validate(value, branch, path, errors)
@@ -0,0 +1,327 @@
1
+ """The diff guard: a deterministic protection layer against unsafe "fixes".
2
+
3
+ Given a unified diff of test code, it flags changes that make a suite pass
4
+ without proving the software works. Each flag explains why it is unsafe. It
5
+ never edits; it only judges.
6
+
7
+ The guard has two jobs, and they pull against each other:
8
+
9
+ 1. **Catch every way a suite is made to lie.** Deleting or weakening
10
+ assertions, skipping, forcing a pass, excluding specs from the run, making the
11
+ test command always exit zero, swallowing failures, inflating timeouts,
12
+ deleting test files.
13
+ 2. **Not cry wolf on real repairs.** Healing a stale locator *is* the job of
14
+ `/qa-fix`, and it necessarily rewrites an assertion line. A guard that flags
15
+ every legitimate repair as `high` trains the agent — and the human — to
16
+ override it, which is worse than having no guard.
17
+
18
+ Job 2 is why assertions are compared by **strength** rather than by presence. An
19
+ assertion replaced by one that is at least as strong, keeping the same expected
20
+ values, is a modification worth confirming (`low`) — not a removal (`high`). An
21
+ assertion replaced by a weaker one, or one that drops the expected value, is
22
+ `weakened-assertion` (`high`), because that is how a test quietly stops checking
23
+ anything.
24
+ """
25
+
26
+ import re
27
+
28
+ # --- assertion recognition ---------------------------------------------------
29
+
30
+ _ASSERTION = re.compile(r"(?i)\b(expect|assert|should|toBe|toEqual|toHaveText|toBeVisible|toContain|assertThat)\b")
31
+
32
+ # Matchers that pin a specific value or state. Replacing one of these with a
33
+ # weaker matcher means the test no longer checks what it used to.
34
+ _STRONG_MATCHERS = re.compile(
35
+ r"(?i)\b(toBe|toEqual|toStrictEqual|toHaveText|toContainText|toHaveValue|toHaveURL|"
36
+ r"toHaveTitle|toHaveCount|toHaveLength|toHaveAttribute|toHaveClass|toHaveScreenshot|"
37
+ r"toMatch|toMatchObject|toMatchSnapshot|toBeVisible|toBeChecked|toBeEnabled|toBeDisabled|"
38
+ r"toBeEmpty|toBeGreaterThan|toBeLessThan|toBeCloseTo|"
39
+ r"assertEqual|assertEquals|assertIn|assertTrue|assertFalse|isEqualTo|containsExactly)\b"
40
+ )
41
+
42
+ # Matchers that only prove something exists or is loosely truthy.
43
+ _WEAK_MATCHERS = re.compile(
44
+ r"(?i)\b(toBeDefined|toBeUndefined|toBeTruthy|toBeFalsy|toBeNull|toBeNaN|toBeAttached|"
45
+ r"toBeOk|assertIsNotNone|assertIsNone|isNotNull|isNotEmpty|notNull|toBeInstanceOf)\b"
46
+ )
47
+
48
+ # A soft assertion does not stop the test at the point of failure; swapping a
49
+ # hard assertion for a soft one weakens it.
50
+ _SOFT_ASSERTION = re.compile(r"(?i)\b(expect\.soft|softAssert|assertSoftly)\b")
51
+
52
+ # String and numeric literals — the expected values an assertion pins down.
53
+ _STRING_LITERAL = re.compile(r"""(['"])((?:(?!\1).){2,})\1""")
54
+ _NUMBER_LITERAL = re.compile(r"(?<![\w.])\d+(?:\.\d+)?(?![\w.])")
55
+
56
+ _IDENTIFIER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
57
+
58
+ # --- unsafe-change patterns --------------------------------------------------
59
+
60
+ _SKIP_ADDED = re.compile(
61
+ r"(?i)(\.skip\b|\.fixme\b|\bxit\b|\bxdescribe\b|test\.skip|it\.skip|describe\.skip|"
62
+ r"@pytest\.mark\.skip|@Ignore\b|@Disabled\b|\.only\b|this\.skip\(|t\.Skip\()"
63
+ )
64
+ _FORCED_PASS = re.compile(
65
+ r"(?i)(assert\s+True\b|expect\(true\)\.toBe\(true\)|expect\(1\)\.toBe\(1\)|"
66
+ r"return\s*;?\s*//\s*pass|assert\s+1\s*==\s*1|pass\s*#\s*(?:todo|skip|pass))"
67
+ )
68
+
69
+ # A bare early return inside a test body ends the test before it verifies
70
+ # anything — the quietest way to fake a pass. Only value-free returns count, so
71
+ # `return page.click(...)` and `return await expect(...)` stay clean.
72
+ _EARLY_RETURN = re.compile(r"^\s*(?:if\s*\(.*?\)\s*\{?\s*)?return\s*;?\s*\}?\s*$")
73
+
74
+ # Excluding specs from the run drops coverage without touching a test file.
75
+ _SUITE_EXCLUSION = re.compile(
76
+ r"(?i)(testIgnore|testPathIgnorePatterns|excludeSpecPattern|"
77
+ r"exclude\s*[:=]|ignorePatterns|--grep-invert|--ignore-pattern|"
78
+ r"specs?\s*:\s*\[\s*\]|testMatch\s*[:=]\s*\[\s*\])"
79
+ )
80
+
81
+ # Making the test command exit zero regardless of the result.
82
+ _FORCED_PASS_COMMAND = re.compile(
83
+ r"(?i)(\|\|\s*true\b|\|\|\s*exit\s+0\b|;\s*exit\s+0\b|--passWithNoTests\b|"
84
+ r"--pass-with-no-tests\b|continue-on-error\s*:\s*true|set\s+\+e\b|"
85
+ r"-DskipTests\b|--exit-zero\b|\|\|\s*:)"
86
+ )
87
+
88
+ # A catch block that discards the failure.
89
+ _SWALLOWED_FAILURE = re.compile(r"(?i)(catch\s*(?:\([^)]*\))?\s*\{\s*\}|except\s*[\w.]*\s*:\s*pass\b)")
90
+ _CATCH_ADDED = re.compile(r"(?i)(\bcatch\s*[({]|^\s*except\b)")
91
+
92
+ _TIMEOUT = re.compile(r"(?i)(timeout|setTimeout|wait_?for|implicitly_wait|setDefaultTimeout)\D{0,20}?(\d{3,})")
93
+ # Deliberately excludes `expect(`: an expectation is an assertion, not a wait,
94
+ # and including it made this rule unreachable.
95
+ _WAIT = re.compile(r"(?i)(waitFor\w*|wait_?for\w*|\.wait\(|awaitVisible|implicitly_wait)")
96
+ _LOCATOR = re.compile(r"""(?i)(getBy\w+|locator|find_element|\$\(|css=|xpath=|By\.\w+)""")
97
+ _EMPTY_BODY = re.compile(r"(?i)(async\s+)?(\([^)]*\)\s*=>\s*\{\s*\}|function[^{]*\{\s*\}|def\s+test\w*\([^)]*\):\s*pass)")
98
+ _RETRY = re.compile(r"(?i)(retries?\s*[:=]\s*(\d+)|\.retry\((\d+)\))")
99
+
100
+ _TEST_FILE = re.compile(r"(?i)(\.spec\.|\.test\.|_test\.|test_|/tests?/|/e2e/|\.feature$|Test\.java$|Tests\.cs$)")
101
+
102
+ MASS_DELETION_THRESHOLD = 15
103
+
104
+ # How much token overlap makes an added assertion the counterpart of a removed
105
+ # one. Tuned so a locator rewrite on the same expectation pairs up, while two
106
+ # unrelated assertions in the same file do not.
107
+ _COUNTERPART_THRESHOLD = 0.34
108
+
109
+
110
+ def _parse_diff(diff_text):
111
+ """Yield (hunk_file, sign, text) for each changed line. sign is '+' or '-'."""
112
+ current = "unknown"
113
+ for line in diff_text.splitlines():
114
+ if line.startswith("+++ ") or line.startswith("--- "):
115
+ path = line[4:].strip()
116
+ if path not in ("/dev/null", ""):
117
+ current = re.sub(r"^[ab]/", "", path)
118
+ continue
119
+ if line.startswith("@@"):
120
+ continue
121
+ if line.startswith("+") and not line.startswith("+++"):
122
+ yield (current, "+", line[1:])
123
+ elif line.startswith("-") and not line.startswith("---"):
124
+ yield (current, "-", line[1:])
125
+
126
+
127
+ def _deleted_files(diff_text):
128
+ """Files whose new side is /dev/null — deleted outright."""
129
+ deleted, pending = set(), None
130
+ for line in diff_text.splitlines():
131
+ if line.startswith("--- "):
132
+ path = line[4:].strip()
133
+ pending = re.sub(r"^[ab]/", "", path) if path != "/dev/null" else None
134
+ elif line.startswith("+++ "):
135
+ if line[4:].strip() == "/dev/null" and pending:
136
+ deleted.add(pending)
137
+ pending = None
138
+ return deleted
139
+
140
+
141
+ def _tokens(text):
142
+ return {t.lower() for t in _IDENTIFIER.findall(text)}
143
+
144
+
145
+ def _literals(text):
146
+ strings = {m.group(2) for m in _STRING_LITERAL.finditer(text)}
147
+ numbers = set(_NUMBER_LITERAL.findall(text))
148
+ return strings, numbers
149
+
150
+
151
+ def _strength(text):
152
+ """3 = pins a value/state, 2 = unclassified assertion, 1 = existence only."""
153
+ if _SOFT_ASSERTION.search(text):
154
+ return 1
155
+ if _WEAK_MATCHERS.search(text) and not _STRONG_MATCHERS.search(text):
156
+ return 1
157
+ if _STRONG_MATCHERS.search(text):
158
+ return 3
159
+ return 2
160
+
161
+
162
+ def _counterpart(removed_text, candidates):
163
+ """The added assertion line most plausibly replacing this removed one."""
164
+ removed_tokens = _tokens(removed_text)
165
+ if not removed_tokens:
166
+ return None
167
+ best, best_score = None, 0.0
168
+ for text in candidates:
169
+ overlap = removed_tokens & _tokens(text)
170
+ score = len(overlap) / max(len(removed_tokens), 1)
171
+ if score > best_score:
172
+ best, best_score = text, score
173
+ return best if best_score >= _COUNTERPART_THRESHOLD else None
174
+
175
+
176
+ def check_diff(diff_text):
177
+ """Analyze a unified diff. Returns a list of issue dicts:
178
+ {rule, severity, file, why, sample}. An empty list means no unsafe change
179
+ was detected (which is not a guarantee of correctness, only of safety)."""
180
+ issues = []
181
+ removed = [(f, t) for f, s, t in _parse_diff(diff_text) if s == "-"]
182
+ added = [(f, t) for f, s, t in _parse_diff(diff_text) if s == "+"]
183
+ deleted_files = _deleted_files(diff_text)
184
+
185
+ def flag(rule, severity, file, why, sample):
186
+ issues.append({"rule": rule, "severity": severity, "file": file,
187
+ "why": why, "sample": str(sample).strip()[:200]})
188
+
189
+ added_by_file = {}
190
+ for file, text in added:
191
+ added_by_file.setdefault(file, []).append(text)
192
+
193
+ # --- removed or weakened assertions --------------------------------------
194
+ for file, text in removed:
195
+ if _ASSERTION.search(text):
196
+ same_file_added = added_by_file.get(file, [])
197
+ # An identical line re-added is a move, not a change.
198
+ if any(a.strip() == text.strip() for a in same_file_added):
199
+ continue
200
+
201
+ assertion_candidates = [a for a in same_file_added if _ASSERTION.search(a)]
202
+ replacement = _counterpart(text, assertion_candidates)
203
+
204
+ if replacement is None:
205
+ if file in deleted_files:
206
+ continue # reported once as a deleted test file, below
207
+ flag("removed-assertion", "high", file,
208
+ "An assertion or expectation was removed with nothing replacing it; "
209
+ "a test that no longer asserts proves nothing.", text)
210
+ continue
211
+
212
+ old_strength, new_strength = _strength(text), _strength(replacement)
213
+ old_strings, old_numbers = _literals(text)
214
+ new_strings, new_numbers = _literals(replacement)
215
+ dropped_strings = old_strings - new_strings
216
+ dropped_numbers = old_numbers - new_numbers
217
+
218
+ if new_strength < old_strength:
219
+ flag("weakened-assertion", "high", file,
220
+ "An assertion was replaced by a weaker one (existence or truthiness "
221
+ "instead of a specific value or state); the test can now pass without "
222
+ "the behaviour being correct.", replacement)
223
+ elif dropped_strings or dropped_numbers:
224
+ dropped = sorted(dropped_strings | dropped_numbers)
225
+ flag("weakened-assertion", "high", file,
226
+ "An assertion kept its matcher but dropped the expected value(s) "
227
+ f"{dropped}; it no longer pins down what it used to.", replacement)
228
+ else:
229
+ flag("assertion-modified", "low", file,
230
+ "An assertion was rewritten with equal or greater strength and the same "
231
+ "expected values — consistent with a legitimate repair. Confirm it still "
232
+ "targets the same behaviour.", replacement)
233
+
234
+ if _WAIT.search(text) and not _ASSERTION.search(text):
235
+ flag("removed-wait", "medium", file,
236
+ "A wait/synchronization was removed, which can mask a real failure or "
237
+ "introduce flakiness.", text)
238
+
239
+ # --- added skips, forced passes, early returns, empty bodies -------------
240
+ for file, text in added:
241
+ if _SKIP_ADDED.search(text):
242
+ flag("added-skip-or-only", "high", file,
243
+ "A skip/ignore/only marker was added; skipping or narrowing hides failures "
244
+ "instead of fixing them.", text)
245
+ if _FORCED_PASS.search(text):
246
+ flag("forced-pass", "high", file,
247
+ "A tautological or forced-pass assertion was added; it makes the test pass "
248
+ "without checking behavior.", text)
249
+ if _EMPTY_BODY.search(text):
250
+ flag("empty-test-body", "high", file,
251
+ "A test body was emptied; an empty test passes vacuously.", text)
252
+ if _EARLY_RETURN.match(text) and _TEST_FILE.search(file):
253
+ flag("conditional-skip", "high", file,
254
+ "An unconditional or condition-guarded early return was added to a test; "
255
+ "the test exits before verifying anything, which is a skip in disguise.", text)
256
+ if _SUITE_EXCLUSION.search(text):
257
+ flag("suite-exclusion", "high", file,
258
+ "Specs were excluded from the run (ignore pattern, exclusion list, or empty "
259
+ "spec list); coverage is dropped without any test file changing.", text)
260
+ if _FORCED_PASS_COMMAND.search(text):
261
+ flag("forced-pass-command", "high", file,
262
+ "The test command was made to succeed regardless of the result "
263
+ "(`|| true`, `exit 0`, `--passWithNoTests`, `continue-on-error`); the suite "
264
+ "can no longer fail a pipeline.", text)
265
+ if _SWALLOWED_FAILURE.search(text):
266
+ flag("swallowed-failure", "high", file,
267
+ "A failure is caught and discarded; an assertion inside a swallowed catch "
268
+ "cannot fail the test.", text)
269
+ elif _CATCH_ADDED.search(text) and _TEST_FILE.search(file):
270
+ flag("added-error-handling", "medium", file,
271
+ "Error handling was added inside a test; confirm the failure still surfaces "
272
+ "rather than being caught and logged.", text)
273
+
274
+ # --- deleted test files --------------------------------------------------
275
+ for file in sorted(deleted_files):
276
+ if _TEST_FILE.search(file):
277
+ flag("test-file-deleted", "high", file,
278
+ "A test file was deleted outright; every case it held stops running, "
279
+ "regardless of the file's size.", file)
280
+
281
+ # --- timeout inflation and unsafe retry increases -------------------------
282
+ _flag_numeric_inflation(_TIMEOUT, removed, added, "timeout-inflation", "medium",
283
+ "A timeout was increased substantially, which can paper over a real slowness or hang.", flag)
284
+ _flag_numeric_inflation(_RETRY, removed, added, "unsafe-retry-increase", "medium",
285
+ "Retry count was increased, which can convert a real failure into an intermittent pass.", flag)
286
+
287
+ # --- suspicious locator changes ------------------------------------------
288
+ removed_locators = {f: t for f, t in removed if _LOCATOR.search(t)}
289
+ for file, text in added:
290
+ if _LOCATOR.search(text) and file in removed_locators and text.strip() != removed_locators[file].strip():
291
+ flag("suspicious-locator-change", "low", file,
292
+ "A locator was changed; confirm it targets the same element and was not "
293
+ "loosened to pass.", text)
294
+
295
+ # --- mass deletion per file ----------------------------------------------
296
+ per_file = {}
297
+ for file, _ in removed:
298
+ per_file[file] = per_file.get(file, 0) + 1
299
+ for file, count in per_file.items():
300
+ if count >= MASS_DELETION_THRESHOLD and file not in deleted_files:
301
+ flag("mass-deletion", "high", file,
302
+ f"{count} lines were deleted from a test file; large deletions can silently drop coverage.",
303
+ f"{count} lines removed")
304
+
305
+ return issues
306
+
307
+
308
+ def _flag_numeric_inflation(pattern, removed, added, rule, severity, why, flag):
309
+ def max_number(text):
310
+ nums = [int(n) for n in re.findall(r"\d{2,}", text)]
311
+ return max(nums) if nums else None
312
+
313
+ removed_by_file = {}
314
+ for file, text in removed:
315
+ if pattern.search(text):
316
+ value = max_number(text)
317
+ if value is not None:
318
+ removed_by_file.setdefault(file, []).append(value)
319
+ for file, text in added:
320
+ if pattern.search(text):
321
+ new_value = max_number(text)
322
+ if new_value is None:
323
+ continue
324
+ for old_value in removed_by_file.get(file, []):
325
+ if new_value >= old_value * 2 and new_value > old_value:
326
+ flag(rule, severity, file, why, text)
327
+ break
@@ -0,0 +1,113 @@
1
+ """Deterministic artifact discovery.
2
+
3
+ Locates the artifacts a run produced — automatically by convention or from
4
+ explicit paths — and classifies each as present, partial, or corrupted. It
5
+ handles multiple runs, parallel workers, and sharded output (many result files),
6
+ and it reports what is missing rather than inventing it.
7
+ """
8
+
9
+ import json
10
+ import os
11
+ import zipfile
12
+ from glob import glob
13
+
14
+ from .evidence import Artifact
15
+
16
+ # Convention globs for known artifact types, relative to a run root.
17
+ _PATTERNS = [
18
+ ("junit", ["**/results.xml", "**/junit*.xml", "**/*junit*.xml"]),
19
+ ("report", ["**/results.json", "**/report.json"]),
20
+ ("html-report", ["**/playwright-report/index.html", "**/*-report/index.html"]),
21
+ ("trace", ["**/trace.zip", "**/*-trace.zip"]),
22
+ ("har", ["**/*.har"]),
23
+ ("video", ["**/*.webm", "**/*.mp4"]),
24
+ ("screenshot", ["**/*.png", "**/*-actual.png"]),
25
+ ]
26
+
27
+
28
+ def _integrity(artifact_type, path):
29
+ """Classify an artifact as present, partial (empty), or corrupted."""
30
+ try:
31
+ size = os.path.getsize(path)
32
+ except OSError:
33
+ return "missing"
34
+ if size == 0:
35
+ return "partial"
36
+ # Structural spot-checks for formats we can cheaply verify.
37
+ if artifact_type == "trace":
38
+ if not zipfile.is_zipfile(path):
39
+ return "corrupted"
40
+ elif artifact_type in ("report", "har"):
41
+ try:
42
+ with open(path, "r", encoding="utf-8") as handle:
43
+ json.load(handle)
44
+ except (json.JSONDecodeError, OSError, UnicodeDecodeError):
45
+ return "corrupted"
46
+ return "present"
47
+
48
+
49
+ def discover(root=".", explicit=None, framework="unknown"):
50
+ """Discover artifacts under root, or validate explicit paths.
51
+
52
+ Returns {present: [Artifact...], partial: [...], corrupted: [...],
53
+ missing: [paths]}. Explicit paths that do not exist are reported as missing;
54
+ convention discovery never reports missing (absence is simply not found).
55
+ """
56
+ present, partial, corrupted, missing = [], [], [], []
57
+
58
+ def record(artifact_type, path):
59
+ state = _integrity(artifact_type, path)
60
+ artifact = Artifact(type=artifact_type, location=os.path.relpath(path, root)
61
+ if os.path.isabs(path) else path, framework=framework,
62
+ present=(state == "present"))
63
+ if state == "present":
64
+ present.append(artifact)
65
+ elif state == "partial":
66
+ partial.append(artifact)
67
+ elif state == "corrupted":
68
+ corrupted.append(artifact)
69
+ else:
70
+ missing.append(path)
71
+
72
+ if explicit:
73
+ for path in explicit:
74
+ if not os.path.exists(path):
75
+ missing.append(path)
76
+ continue
77
+ matched = next((t for t, _ in _PATTERNS if _matches_type(t, path)), "attachment")
78
+ record(matched, path)
79
+ else:
80
+ seen = set()
81
+ for artifact_type, patterns in _PATTERNS:
82
+ for pattern in patterns:
83
+ for path in sorted(glob(os.path.join(root, pattern), recursive=True)):
84
+ if path in seen:
85
+ continue
86
+ seen.add(path)
87
+ record(artifact_type, path)
88
+
89
+ return {
90
+ "present": present,
91
+ "partial": partial,
92
+ "corrupted": corrupted,
93
+ "missing": missing,
94
+ }
95
+
96
+
97
+ def _matches_type(artifact_type, path):
98
+ lower = path.lower()
99
+ if artifact_type == "junit":
100
+ return lower.endswith(".xml")
101
+ if artifact_type == "report":
102
+ return lower.endswith(".json")
103
+ if artifact_type == "trace":
104
+ return lower.endswith(".zip")
105
+ if artifact_type == "har":
106
+ return lower.endswith(".har")
107
+ if artifact_type == "video":
108
+ return lower.endswith((".webm", ".mp4"))
109
+ if artifact_type == "screenshot":
110
+ return lower.endswith(".png")
111
+ if artifact_type == "html-report":
112
+ return lower.endswith(".html")
113
+ return False