@virtocommerce/test-automation-framework 0.0.0-stage → 0.1.0-alpha.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 (233) hide show
  1. package/.biome/formatter.json +11 -0
  2. package/.biome/imports.json +52 -0
  3. package/.biome/preset.json +4 -0
  4. package/.biome/rules.json +45 -0
  5. package/.claude/agents/qa-automation-expert.md +119 -0
  6. package/.claude/agents/qa-coverage.md +96 -0
  7. package/.claude/agents/qa-explorer.md +112 -0
  8. package/.claude/agents/qa-healer.md +88 -0
  9. package/.claude/agents/qa-judge.md +102 -0
  10. package/.claude/agents/qa-planner.md +104 -0
  11. package/.claude/agents/qa-reviewer.md +121 -0
  12. package/.claude/checks/browser-secrets.mts +107 -0
  13. package/.claude/checks/contract.mts +469 -0
  14. package/.claude/checks/expectation-guard.mts +665 -0
  15. package/.claude/checks/explore-extractors.mts +4 -0
  16. package/.claude/checks/judge-verdict.mts +165 -0
  17. package/.claude/checks/project-facts.mts +491 -0
  18. package/.claude/checks/prove-fails.mts +770 -0
  19. package/.claude/checks/rank-gaps.mts +177 -0
  20. package/.claude/checks/readonly-shell.mts +740 -0
  21. package/.claude/checks/reconcile-run.mts +270 -0
  22. package/.claude/checks/scan-prompts.mts +351 -0
  23. package/.claude/checks/stand.mts +45 -0
  24. package/.claude/checks/test-duration.mts +134 -0
  25. package/.claude/checks/test-shape.mts +224 -0
  26. package/.claude/checks/ticket-card.mts +195 -0
  27. package/.claude/commands/qa-coverage.md +13 -0
  28. package/.claude/commands/qa-explore.md +17 -0
  29. package/.claude/commands/qa-heal.md +44 -0
  30. package/.claude/commands/qa-implement.md +60 -0
  31. package/.claude/commands/qa-plan.md +55 -0
  32. package/.claude/commands/qa-review.md +90 -0
  33. package/.claude/commands/qa.md +156 -0
  34. package/.claude/hooks/readonly-shell.mts +65 -0
  35. package/.claude/settings.json +15 -0
  36. package/.claude/skills/coverage-analysis/SKILL.md +107 -0
  37. package/.claude/skills/create-graphql-layer/SKILL.md +159 -0
  38. package/.claude/skills/create-ui-layer/SKILL.md +189 -0
  39. package/.claude/skills/explore-api/SKILL.md +74 -0
  40. package/.claude/skills/explore-frontend/SKILL.md +85 -0
  41. package/.claude/skills/framework-rules/SKILL.md +189 -0
  42. package/.claude/skills/heal-tests/SKILL.md +197 -0
  43. package/.claude/skills/heal-tests/guard-recipe.md +53 -0
  44. package/.claude/skills/judge-criteria/SKILL.md +40 -0
  45. package/.claude/skills/judge-criteria/coverage.md +9 -0
  46. package/.claude/skills/judge-criteria/expert.md +23 -0
  47. package/.claude/skills/judge-criteria/explorer.md +9 -0
  48. package/.claude/skills/judge-criteria/healer.md +13 -0
  49. package/.claude/skills/judge-criteria/planner.md +12 -0
  50. package/.claude/skills/plan-implementation/SKILL.md +82 -0
  51. package/.claude/skills/plan-implementation/contract-template.md +72 -0
  52. package/.claude/skills/plan-test-strategy/SKILL.md +100 -0
  53. package/.claude/skills/project-facts/SKILL.md +130 -0
  54. package/.claude/skills/read-change/SKILL.md +64 -0
  55. package/.claude/skills/read-ticket/SKILL.md +63 -0
  56. package/.claude/skills/read-ticket/providers.md +58 -0
  57. package/.claude/skills/review-pr/SKILL.md +152 -0
  58. package/.claude/skills/review-test-code/SKILL.md +208 -0
  59. package/.claude/skills/write-e2e-test/SKILL.md +175 -0
  60. package/.claude/skills/write-graphql-test/SKILL.md +158 -0
  61. package/.claude/skills/write-rest-api-test/SKILL.md +182 -0
  62. package/.claude/skills/write-security-test/SKILL.md +253 -0
  63. package/.qa/project.example.json +71 -0
  64. package/CHANGELOG.md +1 -0
  65. package/LICENSE +12 -0
  66. package/README.md +53 -2
  67. package/bin/install-qa-agents.mjs +94 -0
  68. package/dist/auth/credentials.d.ts +10 -0
  69. package/dist/auth/credentials.js +2 -0
  70. package/dist/auth/credentials.js.map +1 -0
  71. package/dist/auth/frontend-browser-sessions.d.ts +71 -0
  72. package/dist/auth/frontend-browser-sessions.js +130 -0
  73. package/dist/auth/frontend-browser-sessions.js.map +1 -0
  74. package/dist/auth/index.d.ts +9 -0
  75. package/dist/auth/index.js +5 -0
  76. package/dist/auth/index.js.map +1 -0
  77. package/dist/auth/platform-browser-sessions.d.ts +47 -0
  78. package/dist/auth/platform-browser-sessions.js +92 -0
  79. package/dist/auth/platform-browser-sessions.js.map +1 -0
  80. package/dist/auth/sign-in-lock.d.ts +14 -0
  81. package/dist/auth/sign-in-lock.js +70 -0
  82. package/dist/auth/sign-in-lock.js.map +1 -0
  83. package/dist/auth/storage-state.d.ts +3 -0
  84. package/dist/auth/storage-state.js +2 -0
  85. package/dist/auth/storage-state.js.map +1 -0
  86. package/dist/auth/token-client.d.ts +82 -0
  87. package/dist/auth/token-client.js +111 -0
  88. package/dist/auth/token-client.js.map +1 -0
  89. package/dist/auth/token-manager.d.ts +67 -0
  90. package/dist/auth/token-manager.js +138 -0
  91. package/dist/auth/token-manager.js.map +1 -0
  92. package/dist/core/default-reporters.d.ts +31 -0
  93. package/dist/core/default-reporters.js +36 -0
  94. package/dist/core/default-reporters.js.map +1 -0
  95. package/dist/core/default-use.d.ts +28 -0
  96. package/dist/core/default-use.js +25 -0
  97. package/dist/core/default-use.js.map +1 -0
  98. package/dist/core/env.d.ts +24 -0
  99. package/dist/core/env.js +33 -0
  100. package/dist/core/env.js.map +1 -0
  101. package/dist/core/error-message.d.ts +10 -0
  102. package/dist/core/error-message.js +13 -0
  103. package/dist/core/error-message.js.map +1 -0
  104. package/dist/core/index.d.ts +16 -0
  105. package/dist/core/index.js +11 -0
  106. package/dist/core/index.js.map +1 -0
  107. package/dist/core/is-ci.d.ts +14 -0
  108. package/dist/core/is-ci.js +18 -0
  109. package/dist/core/is-ci.js.map +1 -0
  110. package/dist/core/parse-env.d.ts +13 -0
  111. package/dist/core/parse-env.js +21 -0
  112. package/dist/core/parse-env.js.map +1 -0
  113. package/dist/core/projects.d.ts +24 -0
  114. package/dist/core/projects.js +33 -0
  115. package/dist/core/projects.js.map +1 -0
  116. package/dist/core/run-options.d.ts +31 -0
  117. package/dist/core/run-options.js +43 -0
  118. package/dist/core/run-options.js.map +1 -0
  119. package/dist/core/secret.d.ts +105 -0
  120. package/dist/core/secret.js +167 -0
  121. package/dist/core/secret.js.map +1 -0
  122. package/dist/core/string-schemas.d.ts +39 -0
  123. package/dist/core/string-schemas.js +56 -0
  124. package/dist/core/string-schemas.js.map +1 -0
  125. package/dist/core/url-path.d.ts +7 -0
  126. package/dist/core/url-path.js +2 -0
  127. package/dist/core/url-path.js.map +1 -0
  128. package/dist/dataset/collection.d.ts +44 -0
  129. package/dist/dataset/collection.js +76 -0
  130. package/dist/dataset/collection.js.map +1 -0
  131. package/dist/dataset/index.d.ts +11 -0
  132. package/dist/dataset/index.js +6 -0
  133. package/dist/dataset/index.js.map +1 -0
  134. package/dist/dataset/load-dataset.d.ts +39 -0
  135. package/dist/dataset/load-dataset.js +62 -0
  136. package/dist/dataset/load-dataset.js.map +1 -0
  137. package/dist/dataset/manifest.d.ts +77 -0
  138. package/dist/dataset/manifest.js +10 -0
  139. package/dist/dataset/manifest.js.map +1 -0
  140. package/dist/dataset/placeholders.d.ts +66 -0
  141. package/dist/dataset/placeholders.js +87 -0
  142. package/dist/dataset/placeholders.js.map +1 -0
  143. package/dist/dataset/seed-collection.d.ts +53 -0
  144. package/dist/dataset/seed-collection.js +115 -0
  145. package/dist/dataset/seed-collection.js.map +1 -0
  146. package/dist/dataset/seed-dataset.d.ts +70 -0
  147. package/dist/dataset/seed-dataset.js +138 -0
  148. package/dist/dataset/seed-dataset.js.map +1 -0
  149. package/dist/dataset/seed-events.d.ts +81 -0
  150. package/dist/dataset/seed-events.js +2 -0
  151. package/dist/dataset/seed-events.js.map +1 -0
  152. package/dist/dataset/seed-requests.d.ts +102 -0
  153. package/dist/dataset/seed-requests.js +160 -0
  154. package/dist/dataset/seed-requests.js.map +1 -0
  155. package/dist/dataset/seed-scope.d.ts +39 -0
  156. package/dist/dataset/seed-scope.js +67 -0
  157. package/dist/dataset/seed-scope.js.map +1 -0
  158. package/dist/fixtures/default-fixtures.d.ts +93 -0
  159. package/dist/fixtures/default-fixtures.js +105 -0
  160. package/dist/fixtures/default-fixtures.js.map +1 -0
  161. package/dist/fixtures/index.d.ts +2 -0
  162. package/dist/fixtures/index.js +2 -0
  163. package/dist/fixtures/index.js.map +1 -0
  164. package/dist/graphql/graphql-client.d.ts +78 -0
  165. package/dist/graphql/graphql-client.js +83 -0
  166. package/dist/graphql/graphql-client.js.map +1 -0
  167. package/dist/graphql/graphql-codegen.d.ts +56 -0
  168. package/dist/graphql/graphql-codegen.js +42 -0
  169. package/dist/graphql/graphql-codegen.js.map +1 -0
  170. package/dist/graphql/graphql-error.d.ts +54 -0
  171. package/dist/graphql/graphql-error.js +74 -0
  172. package/dist/graphql/graphql-error.js.map +1 -0
  173. package/dist/graphql/index.d.ts +6 -0
  174. package/dist/graphql/index.js +4 -0
  175. package/dist/graphql/index.js.map +1 -0
  176. package/dist/http/authentication.d.ts +16 -0
  177. package/dist/http/authentication.js +2 -0
  178. package/dist/http/authentication.js.map +1 -0
  179. package/dist/http/http-client.d.ts +110 -0
  180. package/dist/http/http-client.js +237 -0
  181. package/dist/http/http-client.js.map +1 -0
  182. package/dist/http/http-error.d.ts +26 -0
  183. package/dist/http/http-error.js +34 -0
  184. package/dist/http/http-error.js.map +1 -0
  185. package/dist/http/http-method.d.ts +2 -0
  186. package/dist/http/http-method.js +2 -0
  187. package/dist/http/http-method.js.map +1 -0
  188. package/dist/http/http-response.d.ts +137 -0
  189. package/dist/http/http-response.js +166 -0
  190. package/dist/http/http-response.js.map +1 -0
  191. package/dist/http/index.d.ts +7 -0
  192. package/dist/http/index.js +4 -0
  193. package/dist/http/index.js.map +1 -0
  194. package/dist/http/request-options.d.ts +62 -0
  195. package/dist/http/request-options.js +2 -0
  196. package/dist/http/request-options.js.map +1 -0
  197. package/dist/modules/index.d.ts +2 -0
  198. package/dist/modules/index.js +2 -0
  199. package/dist/modules/index.js.map +1 -0
  200. package/dist/modules/installed-modules.d.ts +86 -0
  201. package/dist/modules/installed-modules.js +135 -0
  202. package/dist/modules/installed-modules.js.map +1 -0
  203. package/docs/README.md +43 -0
  204. package/docs/concepts/areas.md +38 -0
  205. package/docs/concepts/auth.md +92 -0
  206. package/docs/concepts/config.md +102 -0
  207. package/docs/concepts/dataset.md +183 -0
  208. package/docs/concepts/environment.md +54 -0
  209. package/docs/concepts/fixtures.md +109 -0
  210. package/docs/concepts/graphql.md +76 -0
  211. package/docs/concepts/http.md +88 -0
  212. package/docs/concepts/modules.md +63 -0
  213. package/docs/concepts/secrets.md +50 -0
  214. package/docs/contributing/architecture.md +67 -0
  215. package/docs/contributing/conventions.md +39 -0
  216. package/docs/contributing/documentation.md +37 -0
  217. package/docs/contributing/releasing.md +76 -0
  218. package/docs/examples/auth.ts +20 -0
  219. package/docs/examples/config.ts +36 -0
  220. package/docs/examples/dataset.ts +70 -0
  221. package/docs/examples/environment.ts +8 -0
  222. package/docs/examples/fixtures.ts +41 -0
  223. package/docs/examples/getting-started.ts +22 -0
  224. package/docs/examples/graphql-codegen.ts +9 -0
  225. package/docs/examples/graphql.ts +32 -0
  226. package/docs/examples/http.ts +18 -0
  227. package/docs/examples/modules.ts +19 -0
  228. package/docs/examples/secrets.ts +11 -0
  229. package/docs/examples/tsconfig.json +10 -0
  230. package/docs/getting-started.md +106 -0
  231. package/docs/guides/generating-types.md +75 -0
  232. package/docs/guides/qa-agents.md +66 -0
  233. package/package.json +156 -4
@@ -0,0 +1,740 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { lstatSync, realpathSync } from "node:fs";
3
+ import { dirname, isAbsolute, join, relative, resolve } from "node:path";
4
+
5
+ import { passwordNames, runVariables } from "./browser-secrets.mts";
6
+ import { EXTRACTORS } from "./explore-extractors.mts";
7
+ import { PROJECT_FACTS_PATH, playwrightConfigArgs, readProjectFactsIn, SHORT_NAME_SEGMENT } from "./project-facts.mts";
8
+ import { standOrigins } from "./stand.mts";
9
+
10
+ /** The suite's Playwright config arguments (`playwrightConfigArgs`), or undefined when the facts cannot be read. */
11
+ export type SuiteConfig = readonly string[] | undefined;
12
+
13
+ export const READ_ONLY_AGENTS = ["qa-reviewer", "qa-explorer", "qa-coverage", "qa-judge"] as const;
14
+
15
+ export const HEALER_AGENT = "qa-healer";
16
+
17
+ export const ALLOWED_QA_MODULES = [
18
+ "project-facts",
19
+ "ticket-card",
20
+ "contract",
21
+ "reconcile-run",
22
+ "rank-gaps",
23
+ "stand",
24
+ "test-shape",
25
+ "test-duration",
26
+ ] as const;
27
+
28
+ export const JUDGE_AGENT = "qa-judge";
29
+
30
+ export const JUDGE_QA_MODULES = ["judge-verdict", "prove-fails"] as const;
31
+
32
+ export const JUDGE_WRITE_DIR = ".qa/judge";
33
+
34
+ export const EXPLORER_AGENT = "qa-explorer";
35
+
36
+ export const COVERAGE_AGENT = "qa-coverage";
37
+
38
+ export const EXPLORER_WRITE_DIR = ".qa/reports";
39
+
40
+ export const HEALER_RUN_DIR = ".qa/runs";
41
+
42
+ export const BROWSER_TOOL_PREFIX = "mcp__playwright__browser_";
43
+
44
+ const BROWSER_TOOL_KEYS: Readonly<Record<string, readonly string[]>> = {
45
+ navigate: ["url"],
46
+ navigate_back: [],
47
+ snapshot: ["target", "depth", "boxes"],
48
+ take_screenshot: ["type", "fullPage", "element", "target"],
49
+ click: ["element", "target", "doubleClick", "button", "modifiers"],
50
+ hover: ["element", "target"],
51
+ type: ["element", "target", "text", "submit", "slowly"],
52
+ fill_form: ["fields"],
53
+ find: ["text", "regex"],
54
+ handle_dialog: ["accept", "promptText"],
55
+ select_option: ["element", "target", "values"],
56
+ press_key: ["key"],
57
+ wait_for: ["time", "text", "textGone"],
58
+ tabs: ["action", "index", "url"],
59
+ console_messages: ["level", "all"],
60
+ network_requests: ["includeStatic", "static", "filter"],
61
+ network_request: ["index", "part"],
62
+ evaluate: ["function", "element", "target"],
63
+ resize: ["width", "height"],
64
+ close: [],
65
+ };
66
+
67
+ const RESPONSE_BODY = "response-body";
68
+
69
+ export const BROWSER_TOOLS = Object.keys(BROWSER_TOOL_KEYS).map((name) => `${BROWSER_TOOL_PREFIX}${name}`);
70
+
71
+ export const WRITING_TOOLS = ["Edit", "MultiEdit", "NotebookEdit", "PowerShell"] as const;
72
+
73
+ const TOKEN = /^[A-Za-z0-9_./:=@,+^~-]+$/;
74
+ const GIT_SUBCOMMANDS = ["diff", "log", "show", "status"];
75
+ const GIT_FORBIDDEN_PREFIXES = ["--output", "--ext-diff", "--textconv", "--no-index", "--open-files", "--exec", "-O"];
76
+ const PLAYWRIGHT_FLAGS = [
77
+ /^--no-deps$/,
78
+ /^--list$/,
79
+ /^--reporter=(json|list|null)$/,
80
+ /^--project=[\w.-]+$/,
81
+ /^--grep(-invert)?=\S+$/,
82
+ /^--repeat-each=\d{1,2}$/,
83
+ ];
84
+ const PLAYWRIGHT_PATH = /^[\w./@-]+$/;
85
+ const CHECKS_DIR = ".claude/checks";
86
+ const CHECKS_DIR_PATTERN = CHECKS_DIR.replace(/[.]/g, "[.]");
87
+ const PROVE_FAILS_PATH = `${CHECKS_DIR}/prove-fails.mts`;
88
+ const TEST_SHAPE_PATH = `${CHECKS_DIR}/test-shape.mts`;
89
+ const TEST_DURATION_PATH = `${CHECKS_DIR}/test-duration.mts`;
90
+ const TEST_DURATION_ARGUMENTS = [2, 3];
91
+ const PROVE_FAILS_PROJECT = /^--project=[\w.-]+$/;
92
+ const REPORTER_FLAG = /^--reporter=/;
93
+ const OUTPUT_VARIABLE = "PLAYWRIGHT_JSON_OUTPUT_FILE=";
94
+ const REVIEWER_AGENT = "qa-reviewer";
95
+ const REVIEWER_OUTPUT =
96
+ /^PLAYWRIGHT_JSON_OUTPUT_FILE=\.qa\/runs\/(?![Hh][Ee][Aa][Ll]-)[\w-]+\/review-list\.[\w-]+\.json$/;
97
+ const HEALER_REVIEW_OUTPUT =
98
+ /^PLAYWRIGHT_JSON_OUTPUT_FILE=\.qa\/runs\/heal-[a-z0-9]+(-[a-z0-9]+)*\/review-list\.[\w-]+\.json$/;
99
+ const NPX = "npx";
100
+ const NPX_NO_INSTALL = "--no";
101
+ const END_OF_OPTIONS = "--";
102
+ const QA_MODULE_PATH = modulePattern(ALLOWED_QA_MODULES);
103
+ const JUDGE_QA_MODULE_PATH = modulePattern([...ALLOWED_QA_MODULES, ...JUDGE_QA_MODULES]);
104
+ const MAX_SHOWN_COMMAND = 80;
105
+
106
+ /**
107
+ * Text shaped like a credential: a JSON Web Token, an `access_token`, `refresh_token` or `id_token` field, a
108
+ * `"password"` field or a `Bearer` header. The explorer's report and an observed value in a contract never hold one.
109
+ */
110
+ export const CREDENTIAL_SHAPE =
111
+ /\beyJ[\w-]+\.[\w-]+\.[\w-]+|access_token|refresh_token|id_token|"password"|\bBearer\s/i;
112
+
113
+ const QA_DIR_TOKEN = /(^|\/)\.qa(\/|$)/i;
114
+ const REPORT_FILE = /^explore-[a-z0-9]+(-[a-z0-9]+)*\.md$/;
115
+ const COVERAGE_FILE = /^coverage-[0-9]{4}-[0-9]{2}-[0-9]{2}(-[a-z0-9-]+)?\.md$/;
116
+ const JUDGE_FILE = /\.json$/;
117
+ const PATH_SEPARATORS = /[\\/]/;
118
+ const WEB_PROTOCOLS = ["http:", "https:"];
119
+ const HEAL_SLUG = /^heal-[a-z0-9]+(-[a-z0-9]+)*$/;
120
+ const HEAL_REPORT = /^(heal-[a-z0-9]+(-[a-z0-9]+)*|flaky)\.md$/;
121
+ const HEAL_JSON_OUTPUT = /^PLAYWRIGHT_JSON_OUTPUT_FILE=\.qa\/runs\/heal-[a-z0-9]+(-[a-z0-9]+)*\/[\w.-]+\.json$/;
122
+ const HEALER_PLAYWRIGHT_FLAGS = [
123
+ /^--no-deps$/,
124
+ /^--project=[\w.-]+$/,
125
+ /^--repeat-each=\d{1,3}$/,
126
+ /^--retries=0$/,
127
+ /^--grep=[\w.+^~,:@/=][\w.+^~,:@/=-]*$/,
128
+ ];
129
+ const HEALER_REPORTER = /^--reporter=(list|json|null)(,(list|json))*$/;
130
+ const GREP_VALUE = /^[\w.+^~,:@/=][\w.+^~,:@/=-]*$/;
131
+ const GUARD_BASE = /^--base=[0-9a-f]{7,64}$/;
132
+ const GUARD_PATH = `${CHECKS_DIR}/expectation-guard.mts`;
133
+ const DRIVE_PATH = /^[A-Za-z]:/;
134
+ const CONFIG_FLAG = "--config";
135
+ const CONFIG_PREFIX = `${CONFIG_FLAG}=`;
136
+ const CONFIG_SHORT_FLAG = "-c";
137
+ const NO_EMIT = "--noEmit";
138
+ const ENV_FILE_NAME = /^\.env(\.|$)/;
139
+ const WINDOWS_TRAILING = /[. ]+$/;
140
+ const GIT_DIR = ".git";
141
+ const NO_HOOKS_DIR = "";
142
+ const GIT_HOOKS_DIR_ARGS = ["-c", "core.fsmonitor=false", "rev-parse", "--path-format=absolute", "--git-path", "hooks"];
143
+
144
+ function modulePattern(modules: readonly string[]): RegExp {
145
+ return new RegExp(`^${CHECKS_DIR_PATTERN}/(${modules.join("|")})[.]mts$`);
146
+ }
147
+
148
+ function bareName(agent: string | undefined): string | undefined {
149
+ return agent?.split(":").pop();
150
+ }
151
+
152
+ function isRecord(value: unknown): value is Record<string, unknown> {
153
+ return typeof value === "object" && value !== null && !Array.isArray(value);
154
+ }
155
+
156
+ function isGitRead(tokens: readonly string[]): boolean {
157
+ const [, subcommand, ...rest] = tokens;
158
+ if (subcommand === undefined || !GIT_SUBCOMMANDS.includes(subcommand)) {
159
+ return false;
160
+ }
161
+ return rest.every((token) => !GIT_FORBIDDEN_PREFIXES.some((prefix) => token.startsWith(prefix)));
162
+ }
163
+
164
+ function npxArgs(tokens: readonly string[]): readonly string[] | undefined {
165
+ if (tokens[0] !== NPX || tokens[1] !== NPX_NO_INSTALL) {
166
+ return undefined;
167
+ }
168
+ return tokens[2] === END_OF_OPTIONS ? tokens.slice(3) : tokens.slice(2);
169
+ }
170
+
171
+ function isConfigFlag(token: string): boolean {
172
+ return token === CONFIG_SHORT_FLAG || token.startsWith(CONFIG_FLAG);
173
+ }
174
+
175
+ /**
176
+ * True when `args` carry exactly the suite's config arguments (`playwrightConfigArgs`): `--config=<suiteDir>` once,
177
+ * or no config flag for a suite at the repository root. An unknown config (the facts could not be read) never passes.
178
+ */
179
+ function hasSuiteConfig(args: readonly string[], config: SuiteConfig): boolean {
180
+ if (config === undefined) {
181
+ return false;
182
+ }
183
+ const given = args.filter(isConfigFlag);
184
+ return given.length === config.length && given.every((token, index) => token === config[index]);
185
+ }
186
+
187
+ function namesEnvFile(path: string): boolean {
188
+ return path
189
+ .split(PATH_SEPARATORS)
190
+ .some((segment) => ENV_FILE_NAME.test(segment.toLowerCase().replace(WINDOWS_TRAILING, "")));
191
+ }
192
+
193
+ function isPlaywrightList(tokens: readonly string[], config: SuiteConfig): boolean {
194
+ const [tool, subcommand, ...rest] = npxArgs(tokens) ?? [];
195
+ if (tool !== "playwright" || subcommand !== "test" || !rest.includes("--list")) {
196
+ return false;
197
+ }
198
+ if (rest.some((token) => QA_DIR_TOKEN.test(token) || namesEnvFile(token)) || !hasSuiteConfig(rest, config)) {
199
+ return false;
200
+ }
201
+ if (rest.filter((token) => REPORTER_FLAG.test(token)).length !== 1) {
202
+ return false;
203
+ }
204
+ return rest
205
+ .filter((token) => !isConfigFlag(token))
206
+ .every((token) =>
207
+ token.startsWith("-") ? PLAYWRIGHT_FLAGS.some((flag) => flag.test(token)) : PLAYWRIGHT_PATH.test(token),
208
+ );
209
+ }
210
+
211
+ function isProveFailsCall(tokens: readonly string[]): boolean {
212
+ const [, , spec = "", line = "", ...rest] = tokens;
213
+ const flags = rest.filter((token) => token.startsWith("-"));
214
+ const words = rest.filter((token) => !token.startsWith("-"));
215
+ return (
216
+ PLAYWRIGHT_PATH.test(spec) &&
217
+ !spec.startsWith("-") &&
218
+ !spec.startsWith("/") &&
219
+ !spec.split("/").includes("..") &&
220
+ !namesEnvFile(spec) &&
221
+ /^\d+$/.test(line) &&
222
+ words.length > 0 &&
223
+ flags.length <= 1 &&
224
+ flags.every((flag) => PROVE_FAILS_PROJECT.test(flag))
225
+ );
226
+ }
227
+
228
+ function isQualityCall(tokens: readonly string[]): boolean {
229
+ const [, module, ...args] = tokens;
230
+ const count = module === TEST_SHAPE_PATH ? args.length > 0 : TEST_DURATION_ARGUMENTS.includes(args.length);
231
+ return count && args.every(isRepoPath);
232
+ }
233
+
234
+ function isQaModule(tokens: readonly string[], agent: string | undefined): boolean {
235
+ const pattern = bareName(agent) === JUDGE_AGENT ? JUDGE_QA_MODULE_PATH : QA_MODULE_PATH;
236
+ if (tokens[0] !== "node" || !pattern.test(tokens[1] ?? "")) {
237
+ return false;
238
+ }
239
+ if (tokens[1] === TEST_SHAPE_PATH || tokens[1] === TEST_DURATION_PATH) {
240
+ return isQualityCall(tokens);
241
+ }
242
+ return tokens[1] !== PROVE_FAILS_PATH || isProveFailsCall(tokens);
243
+ }
244
+
245
+ function outputPatternOf(agent: string | undefined): RegExp | undefined {
246
+ const bare = bareName(agent);
247
+ if (bare === REVIEWER_AGENT) {
248
+ return REVIEWER_OUTPUT;
249
+ }
250
+ return bare === HEALER_AGENT ? HEALER_REVIEW_OUTPUT : undefined;
251
+ }
252
+
253
+ function withoutOutputAssignment(tokens: readonly string[], agent: string | undefined): readonly string[] | undefined {
254
+ const [first = ""] = tokens;
255
+ if (!first.startsWith(OUTPUT_VARIABLE)) {
256
+ return tokens;
257
+ }
258
+ return outputPatternOf(agent)?.test(first) === true ? tokens.slice(1) : undefined;
259
+ }
260
+
261
+ /**
262
+ * True only for a single plain command on the allowlist: `npx --no playwright test --config=<suiteDir> --list
263
+ * --reporter=json|list|null …` (`--repeat-each=<1-2 digits>` allowed there, so a reviewer can list a series; the
264
+ * config flag exactly as `config` holds it, none for a suite at the repository root, and no path to a `.env` file),
265
+ * `git diff|log|show|status …`, `node .claude/checks/<module>.mts …` (`test-shape` and `test-duration` only with
266
+ * repository paths and a project name, as 1+ and 2-3 arguments); `qa-judge` also has `judge-verdict` and
267
+ * `prove-fails`. `npx` must carry `--no`, optionally then `--` (npm 12 needs it before a tool whose next word is a
268
+ * flag), so npm never fetches a package. Only `qa-reviewer` may lead the listing with
269
+ * `PLAYWRIGHT_JSON_OUTPUT_FILE=.qa/runs/<contract-name>/review-list.<project>.json`, `<contract-name>` not starting
270
+ * with `heal-`, and `qa-healer` only with the directory `heal-<slug>`. No chaining, substitution, redirection, quoting,
271
+ * globbing or variable expansion.
272
+ *
273
+ * @param config the suite's Playwright config arguments (`playwrightConfigArgs`); undefined blocks every Playwright
274
+ * command.
275
+ */
276
+ export function isReadOnlyCommand(command: string, agent: string | undefined, config: SuiteConfig): boolean {
277
+ const text = command.trim();
278
+ if (text === "") {
279
+ return false;
280
+ }
281
+ const tokens = text.split(" ");
282
+ if (!tokens.every((token) => TOKEN.test(token))) {
283
+ return false;
284
+ }
285
+ const bare = withoutOutputAssignment(tokens, agent);
286
+ if (bare === undefined) {
287
+ return false;
288
+ }
289
+ if (bare !== tokens) {
290
+ return isPlaywrightList(bare, config);
291
+ }
292
+ if (tokens[0] === "git") {
293
+ return isGitRead(tokens);
294
+ }
295
+ if (tokens[0] === NPX) {
296
+ return isPlaywrightList(tokens, config);
297
+ }
298
+ return isQaModule(tokens, agent);
299
+ }
300
+
301
+ function isRepoPath(token: string): boolean {
302
+ return (
303
+ PLAYWRIGHT_PATH.test(token) &&
304
+ !token.startsWith("-") &&
305
+ !token.startsWith("/") &&
306
+ !DRIVE_PATH.test(token) &&
307
+ !token.split("/").includes("..") &&
308
+ !namesEnvFile(token)
309
+ );
310
+ }
311
+
312
+ function isHealerPlaywright(tokens: readonly string[], config: SuiteConfig): boolean {
313
+ const [tool, subcommand, ...rest] = npxArgs(tokens) ?? [];
314
+ if (tool !== "playwright" || subcommand !== "test" || !hasSuiteConfig(rest, config)) {
315
+ return false;
316
+ }
317
+ let reporters = 0;
318
+ for (let index = 0; index < rest.length; index += 1) {
319
+ const token = rest[index] ?? "";
320
+ if (isConfigFlag(token)) {
321
+ } else if (token === "-g") {
322
+ index += 1;
323
+ if (!GREP_VALUE.test(rest[index] ?? "")) {
324
+ return false;
325
+ }
326
+ } else if (token === "--list") {
327
+ } else if (token.startsWith("--reporter=")) {
328
+ reporters += 1;
329
+ if (reporters > 1 || !HEALER_REPORTER.test(token)) {
330
+ return false;
331
+ }
332
+ } else if (token.startsWith("-")) {
333
+ if (!HEALER_PLAYWRIGHT_FLAGS.some((flag) => flag.test(token))) {
334
+ return false;
335
+ }
336
+ } else if (!isRepoPath(token)) {
337
+ return false;
338
+ }
339
+ }
340
+ return true;
341
+ }
342
+
343
+ function isTypecheck(args: readonly string[], config: SuiteConfig): boolean {
344
+ if (args.length === 1) {
345
+ return args[0] === NO_EMIT;
346
+ }
347
+ const suiteDir = config?.[0]?.slice(CONFIG_PREFIX.length);
348
+ return suiteDir !== undefined && args.length === 3 && args[0] === "-p" && args[1] === suiteDir && args[2] === NO_EMIT;
349
+ }
350
+
351
+ /**
352
+ * True only for a single plain command the healer may run besides the read-only ones: `npx --no playwright test
353
+ * --config=<suiteDir>` (the config flag exactly as `config` holds it) on repository paths with `--project`,
354
+ * `--repeat-each`, `--retries=0`, `--reporter=list|json|null`, `--grep` or `-g` and `--list`, optionally led by
355
+ * `PLAYWRIGHT_JSON_OUTPUT_FILE=.qa/runs/heal-<slug>/<name>.json`; `node .claude/checks/expectation-guard.mts
356
+ * --snapshot|--base=<sha>`; `npx --no tsc --noEmit` and, for a suite in a directory, `npx --no tsc -p <suiteDir>
357
+ * --noEmit`; `npx --no biome check <paths>` with no flag. No path names a `.env` file. Nothing that fetches a package,
358
+ * writes to git, updates snapshots, picks another config or an output directory, and not the main session's
359
+ * `--repo-fingerprint`.
360
+ */
361
+ export function isHealerCommand(command: string, config: SuiteConfig): boolean {
362
+ const text = command.trim();
363
+ const tokens = text.split(" ");
364
+ if (text === "" || !tokens.every((token) => TOKEN.test(token))) {
365
+ return false;
366
+ }
367
+ const [first = "", second, third, ...rest] = tokens;
368
+ if (first.startsWith(OUTPUT_VARIABLE)) {
369
+ return HEAL_JSON_OUTPUT.test(first) && isHealerPlaywright(tokens.slice(1), config);
370
+ }
371
+ if (first === "node") {
372
+ return (
373
+ second === GUARD_PATH &&
374
+ rest.length === 0 &&
375
+ third !== undefined &&
376
+ (third === "--snapshot" || GUARD_BASE.test(third))
377
+ );
378
+ }
379
+ const [tool, subcommand, ...args] = npxArgs(tokens) ?? [];
380
+ if (tool === "playwright") {
381
+ return isHealerPlaywright(tokens, config);
382
+ }
383
+ if (tool === "tsc") {
384
+ return isTypecheck([subcommand ?? "", ...args], config);
385
+ }
386
+ if (tool === "biome") {
387
+ return subcommand === "check" && args.length > 0 && args.every(isRepoPath);
388
+ }
389
+ return false;
390
+ }
391
+
392
+ export function isReadOnlyAgent(name: string | undefined): boolean {
393
+ const bare = bareName(name);
394
+ return READ_ONLY_AGENTS.some((agent) => agent === bare);
395
+ }
396
+
397
+ function realPathOf(path: string): string | undefined {
398
+ let existing = path;
399
+ while (!exists(existing)) {
400
+ const parent = dirname(existing);
401
+ if (parent === existing) {
402
+ return undefined;
403
+ }
404
+ existing = parent;
405
+ }
406
+ try {
407
+ return join(realpathSync(existing), relative(existing, path));
408
+ } catch {
409
+ return undefined;
410
+ }
411
+ }
412
+
413
+ function exists(path: string): boolean {
414
+ try {
415
+ lstatSync(path);
416
+ return true;
417
+ } catch {
418
+ return false;
419
+ }
420
+ }
421
+
422
+ function hasShortName(path: string): boolean {
423
+ return path.split(PATH_SEPARATORS).some((segment) => SHORT_NAME_SEGMENT.test(segment));
424
+ }
425
+
426
+ function pathInside(projectDir: string, dir: string, file: string): string[] | undefined {
427
+ const requested = resolve(projectDir, file);
428
+ const area = realPathOf(resolve(projectDir, dir));
429
+ const target = realPathOf(requested);
430
+ if (area === undefined || target === undefined || hasShortName(relative(projectDir, requested))) {
431
+ return undefined;
432
+ }
433
+ const path = relative(area, target);
434
+ if (path === "" || path.startsWith("..") || isAbsolute(path) || hasShortName(path)) {
435
+ return undefined;
436
+ }
437
+ return path.split(PATH_SEPARATORS);
438
+ }
439
+
440
+ function isReportFile(segments: readonly string[]): boolean {
441
+ return segments.length === 1 && REPORT_FILE.test(segments[0] ?? "");
442
+ }
443
+
444
+ function isCoverageFile(segments: readonly string[]): boolean {
445
+ return segments.length === 1 && COVERAGE_FILE.test(segments[0] ?? "");
446
+ }
447
+
448
+ function isJudgeFile(segments: readonly string[]): boolean {
449
+ return segments.length >= 2 && JUDGE_FILE.test(segments.at(-1) ?? "") && !segments.some((name) => name.includes(":"));
450
+ }
451
+
452
+ function writeRuleOf(
453
+ agent: string,
454
+ ): { dir: string; allows: (segments: readonly string[]) => boolean; shown: string } | undefined {
455
+ const bare = bareName(agent);
456
+ if (bare === JUDGE_AGENT) {
457
+ return {
458
+ dir: JUDGE_WRITE_DIR,
459
+ allows: isJudgeFile,
460
+ shown: `only .json files under ${JUDGE_WRITE_DIR}/<contract-name>/`,
461
+ };
462
+ }
463
+ if (bare === EXPLORER_AGENT) {
464
+ return { dir: EXPLORER_WRITE_DIR, allows: isReportFile, shown: `only ${EXPLORER_WRITE_DIR}/explore-<slug>.md` };
465
+ }
466
+ if (bare === COVERAGE_AGENT) {
467
+ return {
468
+ dir: EXPLORER_WRITE_DIR,
469
+ allows: isCoverageFile,
470
+ shown: `only ${EXPLORER_WRITE_DIR}/coverage-<yyyy-mm-dd>[-<slug>].md`,
471
+ };
472
+ }
473
+ return undefined;
474
+ }
475
+
476
+ function writeBlockReason(agent: string, toolInput: unknown, projectDir: string): string | undefined {
477
+ const rule = writeRuleOf(agent);
478
+ if (rule === undefined) {
479
+ return `${agent} is read-only and may not write files; blocked`;
480
+ }
481
+ const file = isRecord(toolInput) ? toolInput["file_path"] : undefined;
482
+ const segments = typeof file === "string" && file !== "" ? pathInside(projectDir, rule.dir, file) : undefined;
483
+ if (segments !== undefined && rule.allows(segments)) {
484
+ const content = isRecord(toolInput) ? toolInput["content"] : undefined;
485
+ return bareName(agent) === EXPLORER_AGENT && typeof content === "string" && CREDENTIAL_SHAPE.test(content)
486
+ ? `${agent} may not write a token, password or Bearer header into a report; blocked`
487
+ : undefined;
488
+ }
489
+ const shown = JSON.stringify(typeof file === "string" ? file.slice(0, MAX_SHOWN_COMMAND) : null);
490
+ return `${agent} may write ${rule.shown}; blocked: ${shown}`;
491
+ }
492
+
493
+ function cleanHealerSegments(segments: readonly string[] | undefined): readonly string[] | undefined {
494
+ const bad = segments?.some((name) => {
495
+ const lower = name.toLowerCase();
496
+ const windowsName = lower.replace(WINDOWS_TRAILING, "");
497
+ return (
498
+ name.includes(":") ||
499
+ lower.startsWith(".git") ||
500
+ windowsName === ".claude" ||
501
+ ENV_FILE_NAME.test(windowsName) ||
502
+ /~\d/.test(name)
503
+ );
504
+ });
505
+ return bad === false ? segments : undefined;
506
+ }
507
+
508
+ function healerPathsOf(projectDir: string): readonly string[] | undefined {
509
+ try {
510
+ return readProjectFactsIn(projectDir).healerPaths;
511
+ } catch {
512
+ return undefined;
513
+ }
514
+ }
515
+
516
+ function suiteConfigOf(projectDir: string): SuiteConfig {
517
+ try {
518
+ return playwrightConfigArgs(readProjectFactsIn(projectDir).suiteDir);
519
+ } catch {
520
+ return undefined;
521
+ }
522
+ }
523
+
524
+ function playwrightShown(config: SuiteConfig): string {
525
+ return config === undefined
526
+ ? `npx --no playwright test (not now: ${PROJECT_FACTS_PATH} could not be read)`
527
+ : ["npx --no playwright test", ...config].join(" ");
528
+ }
529
+
530
+ function typecheckShown(config: SuiteConfig): string {
531
+ const suiteDir = config?.[0]?.slice(CONFIG_PREFIX.length);
532
+ return suiteDir === undefined
533
+ ? `npx --no tsc ${NO_EMIT}`
534
+ : `npx --no tsc ${NO_EMIT}, npx --no tsc -p ${suiteDir} ${NO_EMIT}`;
535
+ }
536
+
537
+ function healerMayWrite(file: string, projectDir: string, healerPaths: readonly string[]): boolean {
538
+ if (healerPaths.some((dir) => cleanHealerSegments(pathInside(projectDir, dir, file)) !== undefined)) {
539
+ return true;
540
+ }
541
+ const report = cleanHealerSegments(pathInside(projectDir, EXPLORER_WRITE_DIR, file));
542
+ if (report?.length === 1 && HEAL_REPORT.test(report[0] ?? "")) {
543
+ return true;
544
+ }
545
+ const run = cleanHealerSegments(pathInside(projectDir, HEALER_RUN_DIR, file));
546
+ return run !== undefined && run.length >= 2 && HEAL_SLUG.test(run[0] ?? "");
547
+ }
548
+
549
+ /**
550
+ * The directory git runs hooks from (`core.hooksPath`, else `.git/hooks`), resolved by git itself. Outside a repository
551
+ * there is none (`NO_HOOKS_DIR`); a repository whose configuration git cannot read gives undefined, which blocks.
552
+ */
553
+ function hooksDirOf(projectDir: string): string | undefined {
554
+ try {
555
+ return execFileSync("git", GIT_HOOKS_DIR_ARGS, {
556
+ cwd: projectDir,
557
+ encoding: "utf8",
558
+ env: { ...process.env, GIT_OPTIONAL_LOCKS: "0" },
559
+ stdio: ["ignore", "pipe", "ignore"],
560
+ }).trim();
561
+ } catch {
562
+ return exists(join(projectDir, GIT_DIR)) ? undefined : NO_HOOKS_DIR;
563
+ }
564
+ }
565
+
566
+ function isInsideHooksDir(file: string, projectDir: string, hooksDir: string): boolean {
567
+ return hooksDir !== NO_HOOKS_DIR && pathInside(projectDir, hooksDir, file) !== undefined;
568
+ }
569
+
570
+ function healerWriteBlockReason(agent: string, toolInput: unknown, projectDir: string): string | undefined {
571
+ const file = isRecord(toolInput) ? toolInput["file_path"] : undefined;
572
+ const shown = JSON.stringify(typeof file === "string" ? file.slice(0, MAX_SHOWN_COMMAND) : null);
573
+ const healerPaths = healerPathsOf(projectDir);
574
+ if (healerPaths === undefined) {
575
+ return `${agent} may not write: ${PROJECT_FACTS_PATH} could not be read; blocked: ${shown}`;
576
+ }
577
+ const hooksDir = hooksDirOf(projectDir);
578
+ if (hooksDir === undefined) {
579
+ return `${agent} may not write: the git hooks directory could not be resolved; blocked: ${shown}`;
580
+ }
581
+ if (typeof file === "string" && file !== "" && isInsideHooksDir(file, projectDir, hooksDir)) {
582
+ return `${agent} may not write into the directory git runs hooks from; blocked: ${shown}`;
583
+ }
584
+ if (typeof file === "string" && file !== "" && healerMayWrite(file, projectDir, healerPaths)) {
585
+ return undefined;
586
+ }
587
+ return `${agent} may write only under its healer paths, ${EXPLORER_WRITE_DIR}/heal-<slug>.md, ${EXPLORER_WRITE_DIR}/flaky.md and ${HEALER_RUN_DIR}/heal-<slug>/; blocked: ${shown}`;
588
+ }
589
+
590
+ function healerBlockReason(agent: string, tool: unknown, toolInput: unknown, projectDir: string): string | undefined {
591
+ if (tool !== undefined && typeof tool !== "string") {
592
+ return `${agent} is restricted and its tool could not be identified; blocked`;
593
+ }
594
+ if (tool === "Write" || tool === "Edit" || tool === "MultiEdit") {
595
+ return healerWriteBlockReason(agent, toolInput, projectDir);
596
+ }
597
+ if (tool === "NotebookEdit" || tool === "PowerShell") {
598
+ return `${agent} may not use ${tool}; blocked`;
599
+ }
600
+ if (typeof tool === "string" && tool.startsWith("mcp__")) {
601
+ return browserBlockReason(agent, tool, toolInput, projectDir);
602
+ }
603
+ if (tool !== undefined && tool !== "Bash") {
604
+ return undefined;
605
+ }
606
+ const command = isRecord(toolInput) ? toolInput["command"] : undefined;
607
+ const config = suiteConfigOf(projectDir);
608
+ if (typeof command === "string" && (isReadOnlyCommand(command, agent, config) || isHealerCommand(command, config))) {
609
+ return undefined;
610
+ }
611
+ const shown = JSON.stringify(typeof command === "string" ? command.slice(0, MAX_SHOWN_COMMAND) : null);
612
+ return `${agent} may run only git diff|log|show|status, node ${CHECKS_DIR}/<module>.mts, ${playwrightShown(config)} <specs> with --project, --no-deps, --repeat-each, --retries=0, --reporter, -g and --list, node ${GUARD_PATH} --snapshot|--base=<sha>, ${typecheckShown(config)} and npx --no biome check <paths>, never on a .env file; blocked: ${shown}`;
613
+ }
614
+
615
+ function isWebUrl(value: unknown): boolean {
616
+ if (typeof value !== "string") {
617
+ return false;
618
+ }
619
+ try {
620
+ return WEB_PROTOCOLS.includes(new URL(value).protocol);
621
+ } catch {
622
+ return false;
623
+ }
624
+ }
625
+
626
+ function isShippedExtractor(script: unknown): boolean {
627
+ return typeof script === "string" && EXTRACTORS.includes(script.trim());
628
+ }
629
+
630
+ function standOriginList(projectDir: string): string[] | string {
631
+ try {
632
+ return Object.values(standOrigins(runVariables(projectDir)));
633
+ } catch (error) {
634
+ return error instanceof Error ? error.message : String(error);
635
+ }
636
+ }
637
+
638
+ function signInSecretNames(projectDir: string): string[] {
639
+ try {
640
+ return passwordNames(readProjectFactsIn(projectDir).passwordFor);
641
+ } catch {
642
+ return [];
643
+ }
644
+ }
645
+
646
+ function openBlockReason(agent: string, tool: string, url: unknown, projectDir: string): string | undefined {
647
+ if (!isWebUrl(url)) {
648
+ return `${agent} may open only http or https addresses in ${tool}; blocked`;
649
+ }
650
+ const origins = standOriginList(projectDir);
651
+ if (typeof origins === "string") {
652
+ return `${agent} may open only the stand, whose origins are unknown (${origins}); blocked`;
653
+ }
654
+ const origin = new URL(String(url)).origin;
655
+ return origins.includes(origin)
656
+ ? undefined
657
+ : `${agent} may open only the stand (${origins.join(", ")}), not ${origin}; blocked`;
658
+ }
659
+
660
+ function browserBlockReason(agent: string, tool: string, toolInput: unknown, projectDir: string): string | undefined {
661
+ if (!BROWSER_TOOLS.includes(tool)) {
662
+ return `${agent} is read-only and may not use ${tool}; blocked`;
663
+ }
664
+ if (toolInput !== undefined && toolInput !== null && !isRecord(toolInput)) {
665
+ return `${agent} may call ${tool} only with named arguments; blocked`;
666
+ }
667
+ const input = isRecord(toolInput) ? toolInput : {};
668
+ const name = tool.slice(BROWSER_TOOL_PREFIX.length);
669
+ const extra = Object.keys(input).find((key) => !(BROWSER_TOOL_KEYS[name] ?? []).includes(key));
670
+ if (extra !== undefined) {
671
+ return `${agent} may not pass ${JSON.stringify(extra.slice(0, MAX_SHOWN_COMMAND))} to ${tool}; blocked`;
672
+ }
673
+ if (name === "network_request" && (bareName(agent) !== EXPLORER_AGENT || input["part"] !== RESPONSE_BODY)) {
674
+ return `${agent} may read only part "${RESPONSE_BODY}" of a request in ${tool}, and only as ${EXPLORER_AGENT}; blocked`;
675
+ }
676
+ if (name === "evaluate" && !isShippedExtractor(input["function"])) {
677
+ return `${agent} may run only the shipped page extractor in ${tool}; blocked`;
678
+ }
679
+ if (name === "type" && input["submit"] !== undefined && input["submit"] !== false) {
680
+ const text = input["text"];
681
+ if (typeof text !== "string" || !signInSecretNames(projectDir).includes(text)) {
682
+ return `${agent} may type with submit in ${tool} only a password name from passwordFor, to sign in; blocked`;
683
+ }
684
+ }
685
+ if (name === "navigate" || (name === "tabs" && input["url"] !== undefined)) {
686
+ return openBlockReason(agent, tool, input["url"], projectDir);
687
+ }
688
+ return undefined;
689
+ }
690
+
691
+ /**
692
+ * Decides a PreToolUse hook call for the Bash, Write and Playwright browser tools: a one-line reason to block it, or
693
+ * undefined to let it pass. Only the read-only agents are limited; the main session and every other agent pass
694
+ * untouched. A read-only agent's Bash call must be on the allowlist, its Playwright commands with the suite's config
695
+ * arguments from the project facts (`suiteDir`). Its Write call is allowed for `qa-judge` only as a `.json` file under
696
+ * `.qa/judge/<contract-name>/`, for `qa-explorer` only as `.qa/reports/explore-<slug>.md` and for `qa-coverage` only
697
+ * as `.qa/reports/coverage-<yyyy-mm-dd>[-<slug>].md`, all under the
698
+ * real path of the project directory (a link that leaves it does not count). The other writing tools are blocked, and
699
+ * so is every `mcp__` tool but the fixed list of `mcp__playwright__browser_*` tools: `browser_evaluate` runs only the
700
+ * shipped page extractor, `browser_type` submits only a password name from `passwordFor` (a sign-in),
701
+ * `browser_navigate` and a new tab open only the stand's origins (`stand.mts`),
702
+ * `browser_network_request` is the explorer's only and reads only a response body. The tools that
703
+ * only read pass.
704
+ */
705
+ export function hookBlockReason(input: unknown, projectDir: string = process.cwd()): string | undefined {
706
+ if (!isRecord(input)) {
707
+ return undefined;
708
+ }
709
+ const agent = input["agent_type"];
710
+ if (typeof agent === "string" && bareName(agent) === HEALER_AGENT) {
711
+ return healerBlockReason(agent, input["tool_name"], input["tool_input"], projectDir);
712
+ }
713
+ if (typeof agent !== "string" || !isReadOnlyAgent(agent)) {
714
+ return undefined;
715
+ }
716
+ const tool = input["tool_name"];
717
+ const toolInput = input["tool_input"];
718
+ if (tool === "Write") {
719
+ return writeBlockReason(agent, toolInput, projectDir);
720
+ }
721
+ if (tool !== undefined && typeof tool !== "string") {
722
+ return `${agent} is read-only and its tool could not be identified; blocked`;
723
+ }
724
+ if (WRITING_TOOLS.some((writing) => writing === tool)) {
725
+ return `${agent} is read-only and may not use ${tool}; blocked`;
726
+ }
727
+ if (typeof tool === "string" && tool.startsWith("mcp__")) {
728
+ return browserBlockReason(agent, tool, toolInput, projectDir);
729
+ }
730
+ if (tool !== undefined && tool !== "Bash") {
731
+ return undefined;
732
+ }
733
+ const command = isRecord(toolInput) ? toolInput["command"] : undefined;
734
+ const config = suiteConfigOf(projectDir);
735
+ if (typeof command === "string" && isReadOnlyCommand(command, agent, config)) {
736
+ return undefined;
737
+ }
738
+ const shown = JSON.stringify(typeof command === "string" ? command.slice(0, MAX_SHOWN_COMMAND) : null);
739
+ return `${agent} is read-only and may run only git diff|log|show|status, ${playwrightShown(config)} --list [--no-deps] --reporter=json|list|null and node ${CHECKS_DIR}/<module>.mts, never on a .env file; blocked: ${shown}`;
740
+ }