@detiq/crawler 0.1.3

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 (412) hide show
  1. package/Dockerfile +49 -0
  2. package/README.md +11 -0
  3. package/dist/accessibility-auditor.d.ts +29 -0
  4. package/dist/accessibility-auditor.js +57 -0
  5. package/dist/accessibility-auditor.js.map +7 -0
  6. package/dist/ai-login.d.ts +32 -0
  7. package/dist/ai-login.js +177 -0
  8. package/dist/ai-login.js.map +7 -0
  9. package/dist/auth-token-rotator.d.ts +47 -0
  10. package/dist/auth-token-rotator.js +58 -0
  11. package/dist/auth-token-rotator.js.map +7 -0
  12. package/dist/auth.d.ts +20 -0
  13. package/dist/auth.js +329 -0
  14. package/dist/auth.js.map +7 -0
  15. package/dist/browser-extension.d.ts +37 -0
  16. package/dist/browser-extension.js +113 -0
  17. package/dist/browser-extension.js.map +7 -0
  18. package/dist/captcha-solver.d.ts +16 -0
  19. package/dist/captcha-solver.js +105 -0
  20. package/dist/captcha-solver.js.map +7 -0
  21. package/dist/color-contrast.d.ts +30 -0
  22. package/dist/color-contrast.js +78 -0
  23. package/dist/color-contrast.js.map +7 -0
  24. package/dist/content-chunker.d.ts +18 -0
  25. package/dist/content-chunker.js +152 -0
  26. package/dist/content-chunker.js.map +7 -0
  27. package/dist/content-dedup.d.ts +23 -0
  28. package/dist/content-dedup.js +60 -0
  29. package/dist/content-dedup.js.map +7 -0
  30. package/dist/cookie-consent.d.ts +25 -0
  31. package/dist/cookie-consent.js +78 -0
  32. package/dist/cookie-consent.js.map +7 -0
  33. package/dist/cookie-jar.d.ts +20 -0
  34. package/dist/cookie-jar.js +61 -0
  35. package/dist/cookie-jar.js.map +7 -0
  36. package/dist/crawler.d.ts +179 -0
  37. package/dist/crawler.js +3672 -0
  38. package/dist/crawler.js.map +7 -0
  39. package/dist/custom-js-injector.d.ts +42 -0
  40. package/dist/custom-js-injector.js +50 -0
  41. package/dist/custom-js-injector.js.map +7 -0
  42. package/dist/dark-mode-capture.d.ts +23 -0
  43. package/dist/dark-mode-capture.js +75 -0
  44. package/dist/dark-mode-capture.js.map +7 -0
  45. package/dist/dead-link-detector.d.ts +37 -0
  46. package/dist/dead-link-detector.js +50 -0
  47. package/dist/dead-link-detector.js.map +7 -0
  48. package/dist/element-hash.d.ts +9 -0
  49. package/dist/element-hash.js +9 -0
  50. package/dist/element-hash.js.map +7 -0
  51. package/dist/email-otp.d.ts +42 -0
  52. package/dist/email-otp.js +177 -0
  53. package/dist/email-otp.js.map +7 -0
  54. package/dist/engine-router.d.ts +47 -0
  55. package/dist/engine-router.js +94 -0
  56. package/dist/engine-router.js.map +7 -0
  57. package/dist/export/bulk-export.d.ts +26 -0
  58. package/dist/export/bulk-export.js +76 -0
  59. package/dist/export/bulk-export.js.map +7 -0
  60. package/dist/export/vector-export.d.ts +76 -0
  61. package/dist/export/vector-export.js +85 -0
  62. package/dist/export/vector-export.js.map +7 -0
  63. package/dist/extractors/advanced.d.ts +54 -0
  64. package/dist/extractors/advanced.js +245 -0
  65. package/dist/extractors/advanced.js.map +7 -0
  66. package/dist/extractors/artifact-envelope.d.ts +63 -0
  67. package/dist/extractors/artifact-envelope.js +63 -0
  68. package/dist/extractors/artifact-envelope.js.map +7 -0
  69. package/dist/failure-analysis-agent.d.ts +16 -0
  70. package/dist/failure-analysis-agent.js +40 -0
  71. package/dist/failure-analysis-agent.js.map +7 -0
  72. package/dist/feature-flag-detector.d.ts +30 -0
  73. package/dist/feature-flag-detector.js +55 -0
  74. package/dist/feature-flag-detector.js.map +7 -0
  75. package/dist/form-detector.d.ts +34 -0
  76. package/dist/form-detector.js +58 -0
  77. package/dist/form-detector.js.map +7 -0
  78. package/dist/frontier.d.ts +32 -0
  79. package/dist/frontier.js +83 -0
  80. package/dist/frontier.js.map +7 -0
  81. package/dist/gap-pass.d.ts +35 -0
  82. package/dist/gap-pass.js +81 -0
  83. package/dist/gap-pass.js.map +7 -0
  84. package/dist/graphql-detector.d.ts +39 -0
  85. package/dist/graphql-detector.js +86 -0
  86. package/dist/graphql-detector.js.map +7 -0
  87. package/dist/http-engine.d.ts +80 -0
  88. package/dist/http-engine.js +304 -0
  89. package/dist/http-engine.js.map +7 -0
  90. package/dist/incremental-diff.d.ts +59 -0
  91. package/dist/incremental-diff.js +61 -0
  92. package/dist/incremental-diff.js.map +7 -0
  93. package/dist/index.d.ts +35 -0
  94. package/dist/index.js +61 -0
  95. package/dist/index.js.map +7 -0
  96. package/dist/input-fuzzer.d.ts +30 -0
  97. package/dist/input-fuzzer.js +105 -0
  98. package/dist/input-fuzzer.js.map +7 -0
  99. package/dist/interactive-probe.d.ts +104 -0
  100. package/dist/interactive-probe.js +442 -0
  101. package/dist/interactive-probe.js.map +7 -0
  102. package/dist/job-queue.d.ts +171 -0
  103. package/dist/job-queue.js +2256 -0
  104. package/dist/job-queue.js.map +7 -0
  105. package/dist/js-coverage.d.ts +29 -0
  106. package/dist/js-coverage.js +56 -0
  107. package/dist/js-coverage.js.map +7 -0
  108. package/dist/js-router-detector.d.ts +17 -0
  109. package/dist/js-router-detector.js +90 -0
  110. package/dist/js-router-detector.js.map +7 -0
  111. package/dist/language-detector.d.ts +22 -0
  112. package/dist/language-detector.js +57 -0
  113. package/dist/language-detector.js.map +7 -0
  114. package/dist/link-classifier.d.ts +23 -0
  115. package/dist/link-classifier.js +40 -0
  116. package/dist/link-classifier.js.map +7 -0
  117. package/dist/live-view.d.ts +36 -0
  118. package/dist/live-view.js +100 -0
  119. package/dist/live-view.js.map +7 -0
  120. package/dist/logger.d.ts +2 -0
  121. package/dist/logger.js +10 -0
  122. package/dist/logger.js.map +7 -0
  123. package/dist/markdown-extract.d.ts +8 -0
  124. package/dist/markdown-extract.js +54 -0
  125. package/dist/markdown-extract.js.map +7 -0
  126. package/dist/native-crawler.d.ts +69 -0
  127. package/dist/native-crawler.js +839 -0
  128. package/dist/native-crawler.js.map +7 -0
  129. package/dist/network-observer.d.ts +49 -0
  130. package/dist/network-observer.js +149 -0
  131. package/dist/network-observer.js.map +7 -0
  132. package/dist/network-throttle.d.ts +25 -0
  133. package/dist/network-throttle.js +34 -0
  134. package/dist/network-throttle.js.map +7 -0
  135. package/dist/openapi-generator.d.ts +49 -0
  136. package/dist/openapi-generator.js +89 -0
  137. package/dist/openapi-generator.js.map +7 -0
  138. package/dist/pdf-extractor.d.ts +28 -0
  139. package/dist/pdf-extractor.js +81 -0
  140. package/dist/pdf-extractor.js.map +7 -0
  141. package/dist/performance-metrics.d.ts +53 -0
  142. package/dist/performance-metrics.js +83 -0
  143. package/dist/performance-metrics.js.map +7 -0
  144. package/dist/phash.d.ts +38 -0
  145. package/dist/phash.js +115 -0
  146. package/dist/phash.js.map +7 -0
  147. package/dist/pii-scrubber.d.ts +21 -0
  148. package/dist/pii-scrubber.js +75 -0
  149. package/dist/pii-scrubber.js.map +7 -0
  150. package/dist/playwright-recorder.d.ts +39 -0
  151. package/dist/playwright-recorder.js +123 -0
  152. package/dist/playwright-recorder.js.map +7 -0
  153. package/dist/policies/crawl-safety.d.ts +9 -0
  154. package/dist/policies/crawl-safety.js +37 -0
  155. package/dist/policies/crawl-safety.js.map +7 -0
  156. package/dist/profiles/domain-profile.d.ts +19 -0
  157. package/dist/profiles/domain-profile.js +140 -0
  158. package/dist/profiles/domain-profile.js.map +7 -0
  159. package/dist/proxy.d.ts +50 -0
  160. package/dist/proxy.js +165 -0
  161. package/dist/proxy.js.map +7 -0
  162. package/dist/rate-limiter.d.ts +31 -0
  163. package/dist/rate-limiter.js +64 -0
  164. package/dist/rate-limiter.js.map +7 -0
  165. package/dist/redirect-tracker.d.ts +37 -0
  166. package/dist/redirect-tracker.js +65 -0
  167. package/dist/redirect-tracker.js.map +7 -0
  168. package/dist/redis-frontier.d.ts +48 -0
  169. package/dist/redis-frontier.js +126 -0
  170. package/dist/redis-frontier.js.map +7 -0
  171. package/dist/redis-queue.d.ts +48 -0
  172. package/dist/redis-queue.js +165 -0
  173. package/dist/redis-queue.js.map +7 -0
  174. package/dist/response-cache.d.ts +38 -0
  175. package/dist/response-cache.js +140 -0
  176. package/dist/response-cache.js.map +7 -0
  177. package/dist/responsive-detector.d.ts +29 -0
  178. package/dist/responsive-detector.js +46 -0
  179. package/dist/responsive-detector.js.map +7 -0
  180. package/dist/retry-policy.d.ts +20 -0
  181. package/dist/retry-policy.js +54 -0
  182. package/dist/retry-policy.js.map +7 -0
  183. package/dist/robots-txt.d.ts +9 -0
  184. package/dist/robots-txt.js +77 -0
  185. package/dist/robots-txt.js.map +7 -0
  186. package/dist/screen-reader.d.ts +16 -0
  187. package/dist/screen-reader.js +46 -0
  188. package/dist/screen-reader.js.map +7 -0
  189. package/dist/screenshot-masker.d.ts +28 -0
  190. package/dist/screenshot-masker.js +62 -0
  191. package/dist/screenshot-masker.js.map +7 -0
  192. package/dist/seo-checker.d.ts +33 -0
  193. package/dist/seo-checker.js +91 -0
  194. package/dist/seo-checker.js.map +7 -0
  195. package/dist/session-capture.d.ts +35 -0
  196. package/dist/session-capture.js +267 -0
  197. package/dist/session-capture.js.map +7 -0
  198. package/dist/session-export.d.ts +49 -0
  199. package/dist/session-export.js +117 -0
  200. package/dist/session-export.js.map +7 -0
  201. package/dist/sitemap-writer.d.ts +21 -0
  202. package/dist/sitemap-writer.js +47 -0
  203. package/dist/sitemap-writer.js.map +7 -0
  204. package/dist/sitemap.d.ts +51 -0
  205. package/dist/sitemap.js +152 -0
  206. package/dist/sitemap.js.map +7 -0
  207. package/dist/skyvern.d.ts +56 -0
  208. package/dist/skyvern.js +129 -0
  209. package/dist/skyvern.js.map +7 -0
  210. package/dist/sqs-queue.d.ts +2 -0
  211. package/dist/sqs-queue.js +47 -0
  212. package/dist/sqs-queue.js.map +7 -0
  213. package/dist/sso-token.d.ts +29 -0
  214. package/dist/sso-token.js +76 -0
  215. package/dist/sso-token.js.map +7 -0
  216. package/dist/stealth/human-behavior.d.ts +20 -0
  217. package/dist/stealth/human-behavior.js +168 -0
  218. package/dist/stealth/human-behavior.js.map +7 -0
  219. package/dist/telemetry.d.ts +34 -0
  220. package/dist/telemetry.js +77 -0
  221. package/dist/telemetry.js.map +7 -0
  222. package/dist/test-executor.d.ts +67 -0
  223. package/dist/test-executor.js +311 -0
  224. package/dist/test-executor.js.map +7 -0
  225. package/dist/tls-fingerprint.d.ts +50 -0
  226. package/dist/tls-fingerprint.js +81 -0
  227. package/dist/tls-fingerprint.js.map +7 -0
  228. package/dist/url-pattern-completer.d.ts +28 -0
  229. package/dist/url-pattern-completer.js +87 -0
  230. package/dist/url-pattern-completer.js.map +7 -0
  231. package/dist/visual-diff-verdict.d.ts +40 -0
  232. package/dist/visual-diff-verdict.js +25 -0
  233. package/dist/visual-diff-verdict.js.map +7 -0
  234. package/dist/webhook-notifier.d.ts +30 -0
  235. package/dist/webhook-notifier.js +76 -0
  236. package/dist/webhook-notifier.js.map +7 -0
  237. package/dist/websocket-detector.d.ts +24 -0
  238. package/dist/websocket-detector.js +60 -0
  239. package/dist/websocket-detector.js.map +7 -0
  240. package/dist/worker.d.ts +1 -0
  241. package/dist/worker.js +33 -0
  242. package/dist/worker.js.map +7 -0
  243. package/package.json +45 -0
  244. package/src/accessibility-auditor.ts +102 -0
  245. package/src/ai-login.ts +218 -0
  246. package/src/auth-token-rotator.ts +89 -0
  247. package/src/auth.ts +396 -0
  248. package/src/browser-extension.ts +186 -0
  249. package/src/captcha-solver.ts +143 -0
  250. package/src/color-contrast.ts +116 -0
  251. package/src/content-chunker.ts +170 -0
  252. package/src/content-dedup.ts +99 -0
  253. package/src/cookie-consent.ts +106 -0
  254. package/src/cookie-jar.ts +91 -0
  255. package/src/crawler.ts +4305 -0
  256. package/src/custom-js-injector.ts +93 -0
  257. package/src/dark-mode-capture.ts +110 -0
  258. package/src/dead-link-detector.ts +76 -0
  259. package/src/element-hash.ts +16 -0
  260. package/src/email-otp.ts +252 -0
  261. package/src/engine-router.ts +141 -0
  262. package/src/export/bulk-export.ts +85 -0
  263. package/src/export/vector-export.ts +160 -0
  264. package/src/extractors/advanced.ts +283 -0
  265. package/src/extractors/artifact-envelope.ts +111 -0
  266. package/src/failure-analysis-agent.ts +49 -0
  267. package/src/feature-flag-detector.ts +97 -0
  268. package/src/form-detector.ts +103 -0
  269. package/src/frontier.test.ts +64 -0
  270. package/src/frontier.ts +112 -0
  271. package/src/gap-pass.ts +122 -0
  272. package/src/graphql-detector.ts +129 -0
  273. package/src/http-engine.ts +433 -0
  274. package/src/incremental-diff.ts +121 -0
  275. package/src/index.ts +35 -0
  276. package/src/input-fuzzer.ts +129 -0
  277. package/src/interactive-probe.ts +623 -0
  278. package/src/job-queue.test.ts +120 -0
  279. package/src/job-queue.ts +2701 -0
  280. package/src/js-coverage.ts +87 -0
  281. package/src/js-router-detector.ts +112 -0
  282. package/src/language-detector.ts +82 -0
  283. package/src/link-classifier.ts +65 -0
  284. package/src/live-view.ts +141 -0
  285. package/src/logger.ts +9 -0
  286. package/src/markdown-extract.test.ts +73 -0
  287. package/src/markdown-extract.ts +76 -0
  288. package/src/native-crawler.ts +1106 -0
  289. package/src/network-observer.ts +204 -0
  290. package/src/network-throttle.ts +69 -0
  291. package/src/openapi-generator.ts +135 -0
  292. package/src/pdf-extractor.ts +123 -0
  293. package/src/performance-metrics.ts +134 -0
  294. package/src/phash.ts +151 -0
  295. package/src/pii-scrubber.ts +99 -0
  296. package/src/playwright-recorder.ts +170 -0
  297. package/src/policies/crawl-safety.ts +46 -0
  298. package/src/profiles/domain-profile.ts +167 -0
  299. package/src/proxy.ts +238 -0
  300. package/src/rate-limiter.ts +87 -0
  301. package/src/redirect-tracker.ts +97 -0
  302. package/src/redis-frontier.ts +143 -0
  303. package/src/redis-queue.ts +208 -0
  304. package/src/response-cache.ts +150 -0
  305. package/src/responsive-detector.ts +92 -0
  306. package/src/retry-policy.ts +87 -0
  307. package/src/robots-txt.ts +96 -0
  308. package/src/screen-reader.ts +89 -0
  309. package/src/screenshot-masker.ts +98 -0
  310. package/src/seo-checker.ts +134 -0
  311. package/src/session-capture.ts +325 -0
  312. package/src/session-export.test.ts +75 -0
  313. package/src/session-export.ts +172 -0
  314. package/src/sitemap-writer.ts +65 -0
  315. package/src/sitemap.test.ts +131 -0
  316. package/src/sitemap.ts +224 -0
  317. package/src/skyvern.ts +199 -0
  318. package/src/sqs-queue.ts +49 -0
  319. package/src/sso-token.ts +120 -0
  320. package/src/stealth/human-behavior.ts +191 -0
  321. package/src/telemetry.ts +122 -0
  322. package/src/test-executor.test.ts +72 -0
  323. package/src/test-executor.ts +424 -0
  324. package/src/tls-fingerprint.ts +111 -0
  325. package/src/url-pattern-completer.ts +114 -0
  326. package/src/visual-diff-verdict.test.ts +80 -0
  327. package/src/visual-diff-verdict.ts +57 -0
  328. package/src/webhook-notifier.ts +109 -0
  329. package/src/websocket-detector.ts +83 -0
  330. package/src/worker.ts +48 -0
  331. package/tsconfig.json +13 -0
  332. package/types/accessibility-auditor.d.ts +29 -0
  333. package/types/ai-login.d.ts +32 -0
  334. package/types/auth-token-rotator.d.ts +47 -0
  335. package/types/auth.d.ts +20 -0
  336. package/types/browser-extension.d.ts +37 -0
  337. package/types/bull-worker.d.ts +6 -0
  338. package/types/captcha-solver.d.ts +16 -0
  339. package/types/color-contrast.d.ts +30 -0
  340. package/types/content-chunker.d.ts +18 -0
  341. package/types/content-dedup.d.ts +23 -0
  342. package/types/cookie-consent.d.ts +25 -0
  343. package/types/cookie-jar.d.ts +20 -0
  344. package/types/crawler.d.ts +179 -0
  345. package/types/custom-js-injector.d.ts +42 -0
  346. package/types/dark-mode-capture.d.ts +23 -0
  347. package/types/dead-link-detector.d.ts +37 -0
  348. package/types/element-hash.d.ts +9 -0
  349. package/types/email-otp.d.ts +42 -0
  350. package/types/engine-router.d.ts +47 -0
  351. package/types/export/bulk-export.d.ts +26 -0
  352. package/types/export/vector-export.d.ts +76 -0
  353. package/types/extractors/advanced.d.ts +54 -0
  354. package/types/extractors/artifact-envelope.d.ts +63 -0
  355. package/types/failure-analysis-agent.d.ts +16 -0
  356. package/types/feature-flag-detector.d.ts +30 -0
  357. package/types/form-detector.d.ts +34 -0
  358. package/types/frontier.d.ts +32 -0
  359. package/types/gap-pass.d.ts +35 -0
  360. package/types/graphql-detector.d.ts +39 -0
  361. package/types/http-engine.d.ts +80 -0
  362. package/types/incremental-diff.d.ts +59 -0
  363. package/types/index.d.ts +35 -0
  364. package/types/input-fuzzer.d.ts +30 -0
  365. package/types/interactive-probe.d.ts +104 -0
  366. package/types/job-queue.d.ts +171 -0
  367. package/types/js-coverage.d.ts +29 -0
  368. package/types/js-router-detector.d.ts +17 -0
  369. package/types/language-detector.d.ts +22 -0
  370. package/types/link-classifier.d.ts +23 -0
  371. package/types/live-view.d.ts +36 -0
  372. package/types/logger.d.ts +2 -0
  373. package/types/markdown-extract.d.ts +8 -0
  374. package/types/native-crawler.d.ts +69 -0
  375. package/types/network-observer.d.ts +49 -0
  376. package/types/network-throttle.d.ts +25 -0
  377. package/types/openapi-generator.d.ts +49 -0
  378. package/types/pdf-extractor.d.ts +28 -0
  379. package/types/performance-metrics.d.ts +53 -0
  380. package/types/phash.d.ts +38 -0
  381. package/types/pii-scrubber.d.ts +21 -0
  382. package/types/playwright-recorder.d.ts +39 -0
  383. package/types/policies/crawl-safety.d.ts +9 -0
  384. package/types/profiles/domain-profile.d.ts +19 -0
  385. package/types/proxy.d.ts +50 -0
  386. package/types/rate-limiter.d.ts +31 -0
  387. package/types/redirect-tracker.d.ts +37 -0
  388. package/types/redis-frontier.d.ts +48 -0
  389. package/types/redis-queue.d.ts +48 -0
  390. package/types/response-cache.d.ts +38 -0
  391. package/types/responsive-detector.d.ts +29 -0
  392. package/types/retry-policy.d.ts +20 -0
  393. package/types/robots-txt.d.ts +9 -0
  394. package/types/screen-reader.d.ts +16 -0
  395. package/types/screenshot-masker.d.ts +28 -0
  396. package/types/seo-checker.d.ts +33 -0
  397. package/types/session-capture.d.ts +38 -0
  398. package/types/session-export.d.ts +49 -0
  399. package/types/sitemap-writer.d.ts +21 -0
  400. package/types/sitemap.d.ts +51 -0
  401. package/types/skyvern.d.ts +56 -0
  402. package/types/sqs-queue.d.ts +2 -0
  403. package/types/sso-token.d.ts +29 -0
  404. package/types/stealth/human-behavior.d.ts +20 -0
  405. package/types/telemetry.d.ts +34 -0
  406. package/types/test-executor.d.ts +67 -0
  407. package/types/tls-fingerprint.d.ts +50 -0
  408. package/types/url-pattern-completer.d.ts +28 -0
  409. package/types/visual-diff-verdict.d.ts +40 -0
  410. package/types/webhook-notifier.d.ts +30 -0
  411. package/types/websocket-detector.d.ts +24 -0
  412. package/types/worker.d.ts +1 -0
@@ -0,0 +1,2701 @@
1
+ /**
2
+ * ZeTa-AI Background Job Queue
3
+ *
4
+ * Postgres-backed durable queue. Each job becomes a PlatformJob record.
5
+ * enqueueJob() writes it QUEUED and, for same-process responsiveness, kicks
6
+ * an immediate best-effort claim attempt — but durability comes from
7
+ * startJobWorkerLoop()'s poll: it atomically claims QUEUED jobs (Postgres
8
+ * `FOR UPDATE SKIP LOCKED`, safe across any number of concurrent worker
9
+ * processes/containers) and requeues jobs whose heartbeat went stale,
10
+ * so a crashed/restarted worker never silently loses a job.
11
+ *
12
+ * CRAWL-type jobs additionally support AWS SQS as an alternate transport
13
+ * (JOB_QUEUE_BACKEND=sqs, see sqs-queue.ts) for horizontally-scaled crawler
14
+ * fleets; every other job type always goes through the DB-backed queue.
15
+ */
16
+
17
+ import crypto from 'node:crypto';
18
+ import { withTenant, prismaAdmin } from '@detiq/database';
19
+ import { crawlJobsTotal, crawlJobDurationSeconds } from '@detiq/core';
20
+ import { logger } from './logger.js';
21
+
22
+ async function notifyAdmins(tenantId: string, data: {
23
+ type: string; title: string; body: string; metadata?: Record<string, unknown>
24
+ }) {
25
+ try {
26
+ // Notification/Membership both have FORCE ROW LEVEL SECURITY — a bare
27
+ // prisma call with no app.current_tenant set gets silently filtered to
28
+ // zero rows (SELECT) or rejected (INSERT), not an error, so this call
29
+ // site had been a complete no-op with no visible failure until fixed.
30
+ const members = await withTenant(tenantId, (tx) =>
31
+ tx.membership.findMany({
32
+ where: { tenantId, role: { in: ['OWNER', 'ADMIN'] } },
33
+ select: { userId: true },
34
+ })
35
+ );
36
+ await withTenant(tenantId, (tx) =>
37
+ tx.notification.createMany({
38
+ data: members.map((m: { userId: string }) => ({
39
+ id: `notif_${crypto.randomUUID()}`,
40
+ tenantId,
41
+ userId: m.userId,
42
+ type: data.type,
43
+ title: data.title,
44
+ body: data.body,
45
+ metadata: data.metadata as any,
46
+ })),
47
+ })
48
+ );
49
+ } catch (e) {
50
+ console.error('[notify] failed:', e);
51
+ }
52
+ }
53
+ import { AppBrain, getProjectStorageConfig, buildArtifactKey, uploadArtifact, getTenantStorageConfig, uploadScreenshotToTenantStorage, uploadFileToTenantStorage, notifyRunCompletion, recordLLMCall } from '@detiq/app-brain';
54
+ import { generateTaxonomySkillFiles, groupScreensWithAI, generateExecutionPlan, refreshTestCasesSkillFile, refreshTestDataSkillFile, refreshTestScriptSkillFile, refreshRequirementsCoverageSkillFile } from '@detiq/agents';
55
+ import { crawlProject } from './crawler.js';
56
+ import { httpCrawl } from './http-engine.js';
57
+ import { hashContent, normalizeText } from './incremental-diff.js';
58
+ import { discoverProjectUrls } from './sitemap.js';
59
+ import { executeTestPlan } from './test-executor.js';
60
+ import { runNativeCrawl } from './native-crawler.js';
61
+ import { jira, confluence, figma } from '@detiq/connectors';
62
+ import { decrypt, config as platformConfig, dispatchWebhook, isFeatureEnabled, interpolatePlaceholders } from '@detiq/core';
63
+ import { createHmac } from 'node:crypto';
64
+ import fs from 'node:fs/promises';
65
+ import path from 'node:path';
66
+ import os from 'node:os';
67
+
68
+ // RFC 6238 TOTP — no external dependency, uses Node built-in crypto.
69
+ export function generateTOTP(secret: string): string {
70
+ const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
71
+ const clean = secret.toUpperCase().replace(/\s/g, '').replace(/=/g, '');
72
+ let bits = 0, value = 0;
73
+ const bytes: number[] = [];
74
+ for (const ch of clean) {
75
+ const idx = BASE32.indexOf(ch);
76
+ if (idx === -1) continue;
77
+ value = (value << 5) | idx;
78
+ bits += 5;
79
+ if (bits >= 8) { bits -= 8; bytes.push((value >> bits) & 0xff); }
80
+ }
81
+ const counter = Math.floor(Date.now() / 30000);
82
+ const buf = Buffer.alloc(8);
83
+ buf.writeBigInt64BE(BigInt(counter));
84
+ const hmac = createHmac('sha1', Buffer.from(bytes)).update(buf).digest();
85
+ const offset = hmac[hmac.length - 1] & 0xf;
86
+ const code = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) |
87
+ ((hmac[offset + 2] & 0xff) << 8) | (hmac[offset + 3] & 0xff);
88
+ return String(code % 1_000_000).padStart(6, '0');
89
+ }
90
+
91
+ function deriveFallbackTargetPath(ref: string, framework: string): string {
92
+ const slug = (ref ?? 'test').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'test';
93
+ const base = framework.startsWith('cypress') ? 'cypress/e2e/'
94
+ : (framework === 'playwright-py' || framework === 'pytest' || framework === 'selenium-py') ? 'tests/'
95
+ : (framework === 'playwright-java' || framework === 'selenium-java' || framework === 'junit') ? 'src/test/java/'
96
+ : 'tests/';
97
+ const ext = (framework === 'playwright-py' || framework === 'pytest' || framework === 'selenium-py') ? '_test.py'
98
+ : (framework === 'playwright-java' || framework === 'selenium-java' || framework === 'junit') ? 'Test.java'
99
+ : framework.includes('ts') ? '.spec.ts'
100
+ : '.spec.js';
101
+ return `${base}${slug}${ext}`;
102
+ }
103
+
104
+ function makeJobName(type: string): string {
105
+ const now = new Date();
106
+ const date = now.toISOString().slice(0, 10); // YYYY-MM-DD
107
+ const ts = now.getTime();
108
+ const label = type === 'CRAWL' ? 'Crawl'
109
+ : type === 'NATIVE_CRAWL' ? 'NativeCrawl'
110
+ : type === 'GENERATE_TESTS' ? 'GenerateTests'
111
+ : type === 'VISUAL_REGRESSION' ? 'VisualRegression'
112
+ : type === 'AI_EDIT' ? 'AIEdit'
113
+ : type === 'API_TESTS' ? 'ApiTests'
114
+ : type === 'SECURITY_TESTS' ? 'SecurityTests'
115
+ : type === 'INTEGRATION_TESTS' ? 'IntegrationTests'
116
+ : type === 'GENERATE_TESTS_FROM_REQS' ? 'GenerateTestsFromReqs'
117
+ : type === 'GENERATE_DATA' ? 'GenerateData'
118
+ : type === 'GENERATE_SCRIPT' ? 'GenerateScript'
119
+ : type === 'GENERATE_TEST_PLAN' ? 'GenerateTestPlan'
120
+ : type === 'IMPORT_TESTS' ? 'ImportTests'
121
+ : type === 'GENERATE_SCREEN_TESTS' ? 'GenerateScreenTests'
122
+ : type === 'BATCH_GENERATE_ALIGNED' ? 'BatchGenerateAligned'
123
+ : type === 'CREATE_PR' ? 'CreatePR'
124
+ : type === 'NEW_PAGES_PIPELINE' ? 'NewPagesPipeline'
125
+ : type.charAt(0) + type.slice(1).toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
126
+ return `${label}_${date}_${ts}`;
127
+ }
128
+
129
+ export interface PlatformJobConfig {
130
+ tenantId: string;
131
+ projectId: string;
132
+ appUrl?: string; // Optional since generate jobs don't strictly need it
133
+ credentials?: { username: string; password: string; oneTimeCode?: string };
134
+ /** Decrypted Playwright storageState JSON — if present, session is restored without AI login. */
135
+ storageState?: string;
136
+ screenshotDir?: string;
137
+ maxScreens?: number;
138
+ /** Seed URLs added to the initial crawl queue — link discovery still runs from each page. */
139
+ startUrls?: string[];
140
+ /** When provided, crawl ONLY these exact URLs (no link-following). Used for selected-screen recrawl. */
141
+ selectiveUrls?: string[];
142
+ /** Device profiles for multi-viewport screenshot pass after main DESKTOP crawl. */
143
+ deviceProfiles?: string[];
144
+ /** HTTP Basic Auth credentials — injected as Authorization header on same-origin requests. */
145
+ httpBasicUsername?: string;
146
+ httpBasicPassword?: string;
147
+ /** Bearer/API token — injected as a request header and into localStorage. Skips AI login. */
148
+ authToken?: string;
149
+ /** Header name for authToken (default: 'Authorization'). */
150
+ authTokenHeader?: string;
151
+ /** Prefix for authToken value (default: 'Bearer '). */
152
+ authTokenPrefix?: string;
153
+ /** CAPTCHA solving API key (2captcha or CapSolver). */
154
+ captchaSolverApiKey?: string;
155
+ /** CAPTCHA solving service provider (default: '2captcha'). */
156
+ captchaSolverProvider?: '2captcha' | 'capsolver';
157
+ /**
158
+ * Path to a Chrome user data directory for profile inheritance (local deployments only).
159
+ * When set, the crawler exports the existing session from this profile and injects it.
160
+ */
161
+ chromeProfilePath?: string;
162
+ /** MailSlurp API key for email OTP auto-retrieval. */
163
+ mailslurpApiKey?: string;
164
+ /** MailSlurp inbox ID to poll for OTP emails. */
165
+ mailslurpInboxId?: string;
166
+ /** SSO provider ('okta' | 'azure_ad' | 'generic_oidc'). */
167
+ ssoProvider?: string;
168
+ /** SSO domain or tenant ID. */
169
+ ssoDomain?: string;
170
+ /** SSO OAuth2 client ID. */
171
+ ssoClientId?: string;
172
+ /** SSO OAuth2 client secret (decrypted). */
173
+ ssoClientSecret?: string;
174
+ /** SSO scopes (space-separated). Default: 'openid profile'. */
175
+ ssoScope?: string;
176
+ /** HTTP/HTTPS/SOCKS5 proxy URL — routes browser through this proxy for bot-protected sites. */
177
+ proxyUrl?: string;
178
+ }
179
+
180
+ /** In-memory map of jobId → AbortController for RUNNING jobs. */
181
+ const runningControllers = new Map<string, AbortController>();
182
+
183
+ // ─── Durable job worker ──────────────────────────────────────────────────────
184
+ //
185
+ // A minimal Postgres-backed work queue: atomic claim via `FOR UPDATE SKIP
186
+ // LOCKED` (safe for any number of concurrent pollers, in-process or across
187
+ // containers), plus a stale-job sweep keyed off a liveness heartbeat rather
188
+ // than wall-clock job age, so a slow-but-alive job is never requeued and
189
+ // double-processed. See startJobWorkerLoop() below.
190
+
191
+ const WORKER_ID = `${os.hostname()}:${process.pid}`;
192
+ const STALE_JOB_TIMEOUT_MINUTES = Number(process.env.JOB_STALE_TIMEOUT_MINUTES ?? 30);
193
+ const WORKER_POLL_INTERVAL_MS = Number(process.env.JOB_WORKER_POLL_INTERVAL_MS ?? 15_000);
194
+ const WORKER_CONCURRENCY = Number(process.env.JOB_WORKER_CONCURRENCY ?? 3);
195
+ const JOB_HEARTBEAT_INTERVAL_MS = Number(process.env.JOB_HEARTBEAT_INTERVAL_MS ?? 15_000);
196
+ // How many headless browsers a single RUN_TEST_SUITE job launches at once —
197
+ // distinct from WORKER_CONCURRENCY (how many *jobs* the poll loop claims at
198
+ // once). Bounded by default to avoid exhausting a container's memory; the
199
+ // primary scale-out path for running more tests at once is still horizontal
200
+ // (more worker containers / SQS), not raising this past what one container
201
+ // can safely hold — see startJobWorkerLoop's doc comment.
202
+ const TEST_EXEC_CONCURRENCY = Number(process.env.TEST_EXEC_CONCURRENCY ?? 3);
203
+
204
+ type ClaimedJob = { id: string; tenantId: string; projectId: string; type: string; config: any };
205
+
206
+ /** Dispatch table populated at module bottom, once every process*Job function is declared. */
207
+ let jobDispatchTable: Record<string, (jobId: string, config: any) => Promise<void>> | null = null;
208
+
209
+ /** Atomically claims one specific QUEUED job for this worker. Returns null if it was already claimed. */
210
+ export async function claimSpecificJob(jobId: string): Promise<ClaimedJob | null> {
211
+ const rows = await prismaAdmin.$queryRaw<ClaimedJob[]>`
212
+ UPDATE "PlatformJob"
213
+ SET status = 'RUNNING', "startedAt" = NOW(), "heartbeatAt" = NOW(), "workerId" = ${WORKER_ID}
214
+ WHERE id = ${jobId} AND status = 'QUEUED'
215
+ RETURNING id, "tenantId" AS "tenantId", "projectId" AS "projectId", type, config
216
+ `;
217
+ return rows[0] ?? null;
218
+ }
219
+
220
+ /** Atomically claims the oldest QUEUED job across all tenants. SKIP LOCKED makes this
221
+ * race-safe against any number of other pollers doing the same thing concurrently. */
222
+ export async function claimNextQueuedJob(): Promise<ClaimedJob | null> {
223
+ const rows = await prismaAdmin.$queryRaw<ClaimedJob[]>`
224
+ UPDATE "PlatformJob"
225
+ SET status = 'RUNNING', "startedAt" = NOW(), "heartbeatAt" = NOW(), "workerId" = ${WORKER_ID}
226
+ WHERE id = (
227
+ SELECT id FROM "PlatformJob"
228
+ WHERE status = 'QUEUED'
229
+ ORDER BY "queuedAt" ASC
230
+ FOR UPDATE SKIP LOCKED
231
+ LIMIT 1
232
+ )
233
+ RETURNING id, "tenantId" AS "tenantId", "projectId" AS "projectId", type, config
234
+ `;
235
+ return rows[0] ?? null;
236
+ }
237
+
238
+ /** Requeues RUNNING jobs whose heartbeat has gone stale — the worker that claimed them
239
+ * died (crash, restart, OOM) without ever marking them DONE/FAILED. Idempotent and
240
+ * safe to run from every worker process; only affects rows past the timeout. */
241
+ export async function requeueStaleRunningJobs(): Promise<void> {
242
+ const rows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
243
+ UPDATE "PlatformJob"
244
+ SET status = 'QUEUED',
245
+ "workerId" = NULL,
246
+ result = jsonb_set(
247
+ COALESCE(result::jsonb, '{}'::jsonb),
248
+ '{step}',
249
+ to_jsonb('Worker heartbeat lost — queued for recovery'::text),
250
+ true
251
+ )
252
+ WHERE status = 'RUNNING'
253
+ AND COALESCE("heartbeatAt", "startedAt") < NOW() - (${STALE_JOB_TIMEOUT_MINUTES} * interval '1 minute')
254
+ RETURNING id
255
+ `;
256
+ if (rows.length > 0) {
257
+ logger.warn({ jobIds: rows.map((r) => r.id), staleTimeoutMinutes: STALE_JOB_TIMEOUT_MINUTES }, '[job-worker] requeued stale RUNNING job(s)');
258
+ }
259
+ }
260
+
261
+ /** Dispatches a claimed job to its type's processor. Last-resort safety net — every
262
+ * process*Job function already catches and records its own failures. */
263
+ async function dispatchClaimedJob(job: ClaimedJob): Promise<void> {
264
+ const dispatcher = jobDispatchTable?.[job.type];
265
+ if (!dispatcher) {
266
+ logger.error({ jobId: job.id, type: job.type }, '[job-worker] no dispatcher registered for job type');
267
+ await prismaAdmin.platformJob.update({
268
+ where: { id: job.id },
269
+ data: { status: 'FAILED', error: `Unknown job type: ${job.type}`, finishedAt: new Date() },
270
+ }).catch(() => {});
271
+ return;
272
+ }
273
+ const stopTimer = crawlJobDurationSeconds.startTimer({ type: job.type });
274
+ try {
275
+ await dispatcher(job.id, job.config);
276
+ stopTimer();
277
+ // dispatcher() resolving doesn't mean the job succeeded — every process*Job
278
+ // function catches and records its own failures internally without
279
+ // rethrowing (see this function's doc comment). Read back the actual
280
+ // final status so the metric reflects reality, not just "didn't throw".
281
+ const finished = await prismaAdmin.platformJob.findUnique({ where: { id: job.id }, select: { status: true } }).catch(() => null);
282
+ crawlJobsTotal.inc({ type: job.type, status: finished?.status === 'FAILED' ? 'failed' : 'success' });
283
+ } catch (err: any) {
284
+ stopTimer();
285
+ crawlJobsTotal.inc({ type: job.type, status: 'failed' });
286
+ logger.error({ jobId: job.id, type: job.type, err: String(err?.message ?? err) }, '[job-worker] job threw uncaught error');
287
+ await prismaAdmin.platformJob.update({
288
+ where: { id: job.id },
289
+ data: { status: 'FAILED', error: String(err?.message ?? err), finishedAt: new Date() },
290
+ }).catch(() => {});
291
+ }
292
+ }
293
+
294
+ let workerLoopTimer: ReturnType<typeof setInterval> | null = null;
295
+
296
+ /**
297
+ * Starts the durable job worker poll loop. This is what makes job processing
298
+ * survive a restart — enqueueJob()'s immediate same-process claim attempt is
299
+ * only a latency optimization; if the process dies before that fires (or
300
+ * mid-job), this loop's next tick claims/requeues it. Call once at process
301
+ * startup (API server and/or a dedicated crawler worker process — safe to
302
+ * run in both, and safe to run in many container replicas at once).
303
+ */
304
+ export function startJobWorkerLoop(opts?: { pollIntervalMs?: number; concurrency?: number }): void {
305
+ if (workerLoopTimer) return; // already running in this process
306
+ const pollIntervalMs = opts?.pollIntervalMs ?? WORKER_POLL_INTERVAL_MS;
307
+ const concurrency = opts?.concurrency ?? WORKER_CONCURRENCY;
308
+ logger.info({ workerId: WORKER_ID, pollIntervalMs, concurrency }, '[job-worker] starting');
309
+
310
+ const tick = async () => {
311
+ try {
312
+ await requeueStaleRunningJobs();
313
+ } catch (err) {
314
+ logger.error({ err: String(err) }, '[job-worker] stale-job sweep failed');
315
+ }
316
+ try {
317
+ for (let i = 0; i < concurrency; i++) {
318
+ const job = await claimNextQueuedJob();
319
+ if (!job) break;
320
+ void dispatchClaimedJob(job); // not awaited — runs concurrently while the loop keeps polling
321
+ }
322
+ } catch (err) {
323
+ logger.error({ err: String(err) }, '[job-worker] claim loop failed');
324
+ }
325
+ };
326
+
327
+ workerLoopTimer = setInterval(tick, pollIntervalMs);
328
+ void tick();
329
+ }
330
+
331
+ /** Stops the poll loop. Mainly for tests. */
332
+ export function stopJobWorkerLoop(): void {
333
+ if (workerLoopTimer) clearInterval(workerLoopTimer);
334
+ workerLoopTimer = null;
335
+ }
336
+
337
+ /** Create a job record that tracks a synchronous operation (telemetry only, no background processor). */
338
+ export async function createTrackedJob(
339
+ type: string,
340
+ config: { tenantId: string; projectId: string; [k: string]: any }
341
+ ): Promise<string> {
342
+ const name = makeJobName(type);
343
+ const job = await withTenant(config.tenantId, (tx) =>
344
+ tx.platformJob.create({
345
+ data: { tenantId: config.tenantId, projectId: config.projectId, type, name, status: 'RUNNING', startedAt: new Date(), config: config as any },
346
+ })
347
+ ) as { id: string };
348
+ return job.id;
349
+ }
350
+
351
+ /** Mark a tracked job DONE or FAILED. Safe to call in finally — swallows errors. */
352
+ export async function finishTrackedJob(tenantId: string, jobId: string, error?: string): Promise<void> {
353
+ await withTenant(tenantId, (tx) =>
354
+ tx.platformJob.update({
355
+ where: { id: jobId },
356
+ data: { status: error ? 'FAILED' : 'DONE', finishedAt: new Date(), ...(error ? { error } : { progress: 100 }) },
357
+ })
358
+ ).catch(() => {});
359
+ }
360
+
361
+ /** Enqueue a generic platform job — returns the job ID immediately. */
362
+ export async function enqueueJob(type: string, config: any): Promise<string> {
363
+ const { tenantId, projectId } = config;
364
+
365
+ const name = makeJobName(type);
366
+ const job = await withTenant(tenantId, (tx) =>
367
+ tx.platformJob.create({
368
+ data: {
369
+ tenantId,
370
+ projectId,
371
+ type,
372
+ name,
373
+ status: 'QUEUED',
374
+ config: config as any,
375
+ },
376
+ })
377
+ ) as { id: string };
378
+
379
+ // Durability comes from startJobWorkerLoop()'s poll — this is only a same-process
380
+ // latency optimization so a job doesn't sit idle until the next poll tick. The
381
+ // claim is atomic (WHERE status='QUEUED'), so it's safe even if the poll loop's
382
+ // own tick fires concurrently and claims this same job first.
383
+ if (type === 'CRAWL' && process.env.JOB_QUEUE_BACKEND === 'sqs') {
384
+ const { sendJobToSqs } = await import('./sqs-queue.js');
385
+ await sendJobToSqs(job.id, tenantId, config);
386
+ } else {
387
+ setImmediate(() => claimSpecificJob(job.id).then((claimed) => claimed && dispatchClaimedJob(claimed)));
388
+ }
389
+
390
+ return job.id;
391
+ }
392
+
393
+ /** Get the current state of a platform job. */
394
+ export async function getJob(tenantId: string, jobId: string) {
395
+ return withTenant(tenantId, (tx) =>
396
+ tx.platformJob.findUnique({ where: { id: jobId } })
397
+ );
398
+ }
399
+
400
+ /** List recent jobs for a project. */
401
+ export async function listJobs(tenantId: string, projectId: string) {
402
+ return withTenant(tenantId, (tx) =>
403
+ tx.platformJob.findMany({
404
+ where: { tenantId, projectId },
405
+ orderBy: { queuedAt: 'desc' },
406
+ take: 50,
407
+ })
408
+ );
409
+ }
410
+
411
+ /** Cancel a RUNNING or QUEUED job. Aborts the in-process crawl and marks DB CANCELLED. */
412
+ export async function cancelJob(tenantId: string, jobId: string): Promise<void> {
413
+ // Abort in-memory controller if job is running in the same process
414
+ const controller = runningControllers.get(jobId);
415
+ if (controller) {
416
+ controller.abort();
417
+ runningControllers.delete(jobId);
418
+ }
419
+ await withTenant(tenantId, (tx) =>
420
+ tx.platformJob.update({
421
+ where: { id: jobId },
422
+ data: { status: 'CANCELLED', finishedAt: new Date() },
423
+ })
424
+ );
425
+ }
426
+
427
+ /** Re-enqueue a job using the same config as a previous job. */
428
+ export async function rerunJob(tenantId: string, jobId: string): Promise<string> {
429
+ const job = await withTenant(tenantId, (tx) =>
430
+ tx.platformJob.findUnique({ where: { id: jobId } })
431
+ ) as { type: string; config: any } | null;
432
+ if (!job) throw new Error('Job not found');
433
+ return enqueueJob(job.type, { ...(job.config as any), tenantId });
434
+ }
435
+
436
+ // In-memory checkpoint store: updated every 10 screens, saved to DB result on failure.
437
+ const jobCheckpoints = new Map<string, { visitedUrls: string[]; pendingQueue: string[] }>();
438
+
439
+ export async function resumeJob(tenantId: string, jobId: string): Promise<string> {
440
+ const job = await withTenant(tenantId, (tx) =>
441
+ tx.platformJob.findUnique({ where: { id: jobId } })
442
+ ) as { type: string; config: any; result: any } | null;
443
+ if (!job) throw new Error('Job not found');
444
+
445
+ const checkpoint = (job.result as any)?.checkpoint;
446
+ const visitedUrls: string[] = checkpoint?.visitedUrls ?? [];
447
+ const pendingQueue: string[] = checkpoint?.pendingQueue ?? [];
448
+
449
+ if (pendingQueue.length === 0 && visitedUrls.length === 0) {
450
+ // No checkpoint saved — full rerun
451
+ return enqueueJob(job.type, { ...(job.config as any), tenantId });
452
+ }
453
+
454
+ return enqueueJob(job.type, {
455
+ ...(job.config as any),
456
+ tenantId,
457
+ skipUrls: visitedUrls.length > 0 ? visitedUrls : undefined,
458
+ resumeUrls: pendingQueue.length > 0 ? pendingQueue : undefined,
459
+ });
460
+ }
461
+
462
+ /** Update progress percentage and current step label on a running job (non-fatal). */
463
+ export async function updateJobProgress(tenantId: string, jobId: string, progress: number, step: string) {
464
+ try {
465
+ await withTenant(tenantId, async (tx) => {
466
+ // DB-flag cancellation: works for both inline and SQS backends.
467
+ // When a user cancels, status is set to 'CANCELLED' in DB.
468
+ // This check fires at each progress update (every few seconds during crawl).
469
+ const current = await tx.platformJob.findUnique({
470
+ where: { id: jobId },
471
+ select: { status: true },
472
+ });
473
+ if (current?.status === 'CANCELLED') {
474
+ runningControllers.get(jobId)?.abort();
475
+ runningControllers.delete(jobId);
476
+ return; // abort signal propagates; crawlProject exits on next signal check
477
+ }
478
+ await tx.platformJob.update({
479
+ where: { id: jobId },
480
+ data: { progress, result: { step } as any, heartbeatAt: new Date() },
481
+ });
482
+ });
483
+ } catch { /* non-fatal — progress updates best-effort */ }
484
+ }
485
+
486
+ /** Bump only worker liveness. This intentionally does not touch progress/result. */
487
+ async function heartbeatJob(tenantId: string, jobId: string) {
488
+ try {
489
+ await withTenant(tenantId, async (tx) => {
490
+ const current = await tx.platformJob.findUnique({
491
+ where: { id: jobId },
492
+ select: { status: true },
493
+ });
494
+ if (current?.status === 'CANCELLED') {
495
+ runningControllers.get(jobId)?.abort();
496
+ runningControllers.delete(jobId);
497
+ return;
498
+ }
499
+ if (current?.status !== 'RUNNING') return;
500
+ await tx.platformJob.update({
501
+ where: { id: jobId },
502
+ data: { heartbeatAt: new Date(), workerId: WORKER_ID },
503
+ });
504
+ });
505
+ } catch { /* non-fatal — heartbeat updates best-effort */ }
506
+ }
507
+
508
+ /** Background: for each changed screen, search Jira + Confluence for related tickets/pages. */
509
+ async function investigateScreenChanges(
510
+ tenantId: string,
511
+ projectId: string,
512
+ changedScreens: Array<{ id: string; name: string; url?: string; addedElements: string[]; removedElements: string[] }>
513
+ ) {
514
+ const [jiraCfg, confluenceCfg] = await Promise.all([
515
+ AppBrain.getConnectorConfig(tenantId, projectId, 'JIRA'),
516
+ AppBrain.getConnectorConfig(tenantId, projectId, 'CONFLUENCE'),
517
+ ]);
518
+
519
+ for (const screen of changedScreens) {
520
+ const searchTerm = screen.url ?? screen.name;
521
+ const changeSummary = `Screen "${screen.name}" changed: +${screen.addedElements.length} elements, -${screen.removedElements.length} elements`;
522
+
523
+ const detail: Record<string, any> = {
524
+ screenId: screen.id,
525
+ screenName: screen.name,
526
+ url: screen.url,
527
+ addedElements: screen.addedElements,
528
+ removedElements: screen.removedElements,
529
+ jiraTickets: [],
530
+ confluencePages: [],
531
+ };
532
+
533
+ if (jiraCfg?.baseUrl && jiraCfg?.email && jiraCfg?.apiToken) {
534
+ try {
535
+ detail.jiraTickets = await jira.searchIssues(
536
+ { baseUrl: jiraCfg.baseUrl, email: jiraCfg.email, apiToken: jiraCfg.apiToken, projectKey: jiraCfg.projectKey },
537
+ searchTerm
538
+ );
539
+ } catch (e) {
540
+ logger.warn({ searchTerm, err: e }, 'Jira search failed');
541
+ }
542
+ }
543
+
544
+ if (confluenceCfg?.baseUrl && confluenceCfg?.email && confluenceCfg?.apiToken) {
545
+ try {
546
+ detail.confluencePages = await confluence.searchPages(
547
+ { baseUrl: confluenceCfg.baseUrl, email: confluenceCfg.email, apiToken: confluenceCfg.apiToken, spaceKey: confluenceCfg.spaceKey },
548
+ searchTerm
549
+ );
550
+ } catch (e) {
551
+ logger.warn({ searchTerm, err: e }, 'Confluence search failed');
552
+ }
553
+ }
554
+
555
+ await AppBrain.logChange(tenantId, projectId, 'MODIFIED', changeSummary, detail);
556
+ logger.info({ screen: screen.name, jiraTickets: detail.jiraTickets.length, confluencePages: detail.confluencePages.length }, 'Logged screen change investigation');
557
+ }
558
+ }
559
+
560
+ export interface ProcessJobOpts {
561
+ onProgress?: (pct: number) => Promise<void>;
562
+ }
563
+
564
+ export async function processJob(jobId: string, config: any, opts?: ProcessJobOpts) {
565
+ const { tenantId, projectId } = config;
566
+
567
+ // Mark as RUNNING.
568
+ const jobStartedAt = new Date();
569
+ await withTenant(tenantId, (tx) =>
570
+ tx.platformJob.update({
571
+ where: { id: jobId },
572
+ data: { status: 'RUNNING', startedAt: jobStartedAt, heartbeatAt: jobStartedAt, workerId: WORKER_ID },
573
+ })
574
+ );
575
+
576
+ const controller = new AbortController();
577
+ runningControllers.set(jobId, controller);
578
+ const heartbeatTimer = setInterval(() => {
579
+ void heartbeatJob(tenantId, jobId);
580
+ }, JOB_HEARTBEAT_INTERVAL_MS);
581
+
582
+ const onProgress = async (pct: number, step: string) => {
583
+ await updateJobProgress(tenantId, jobId, pct, step);
584
+ await opts?.onProgress?.(pct);
585
+ };
586
+
587
+ const DEFAULT_MAX_SCREENS = 150;
588
+
589
+ try {
590
+ // Per-project maxScreens + deviceProfiles + seedUrls + interactive probing + sitemap seeding + traversal strategy from crawlConfig override job config defaults.
591
+ if (!config.maxScreens || !config.deviceProfiles || config.interactive === undefined || config.useSitemap === undefined || !config.traversalStrategy) {
592
+ const proj: any = await withTenant(tenantId, (tx) =>
593
+ (tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
594
+ );
595
+ const perProject = proj?.crawlConfig?.maxScreens;
596
+ if (!config.maxScreens) config.maxScreens = perProject || DEFAULT_MAX_SCREENS;
597
+ if (!config.deviceProfiles) config.deviceProfiles = proj?.crawlConfig?.deviceProfiles ?? ['DESKTOP'];
598
+ if (config.interactive === undefined) config.interactive = proj?.crawlConfig?.interactive ?? false;
599
+ if (config.useSitemap === undefined) config.useSitemap = proj?.crawlConfig?.useSitemap ?? false;
600
+ if (!config.sitemapUrl) config.sitemapUrl = proj?.crawlConfig?.sitemapUrl ?? undefined;
601
+ if (!config.traversalStrategy) config.traversalStrategy = proj?.crawlConfig?.traversalStrategy ?? 'BFS';
602
+ if (!config.bestFirstKeywords) config.bestFirstKeywords = proj?.crawlConfig?.bestFirstKeywords ?? undefined;
603
+ // segmentSize from crawl config — default unlimited (9_999_999) so normal sites run in one job;
604
+ // only segment if the project explicitly sets a segmentSize in its crawl config.
605
+ if (!config.segmentSize) config.segmentSize = proj?.crawlConfig?.segmentSize ?? 9_999_999;
606
+ // Load saved seedUrls as non-selective seeds (link discovery still runs from them).
607
+ // Skip when a selective recrawl is requested (selectiveUrls set) or seeds already provided.
608
+ if (!config.selectiveUrls?.length && (!config.startUrls || config.startUrls.length === 0)) {
609
+ const saved: string[] = proj?.crawlConfig?.seedUrls ?? [];
610
+ if (saved.length > 0) config.startUrls = saved;
611
+ }
612
+ if (config.interactive === undefined) config.interactive = proj?.crawlConfig?.interactive ?? false;
613
+ }
614
+ // Build runtime credentials: convert stored totpSecret → getOneTimeCode function
615
+ const runtimeCreds = config.credentials
616
+ ? {
617
+ ...config.credentials,
618
+ ...(config.credentials.totpSecret
619
+ ? { getOneTimeCode: async () => generateTOTP(config.credentials.totpSecret) }
620
+ : {}),
621
+ }
622
+ : undefined;
623
+
624
+ const result = await crawlProject({
625
+ ...config, credentials: runtimeCreds, abortSignal: controller.signal, jobId,
626
+ onCheckpoint: async (visitedUrls, pendingQueue) => {
627
+ jobCheckpoints.set(jobId, { visitedUrls, pendingQueue });
628
+ },
629
+ }, onProgress);
630
+ jobCheckpoints.delete(jobId);
631
+
632
+ const pendingUrls: string[] = (result as any)?.pendingUrls ?? [];
633
+ if (pendingUrls.length > 0) {
634
+ logger.info({ pendingUrls: pendingUrls.length }, 'Crawl finished with pending URLs — not auto-queuing (segmented crawls disabled)');
635
+ }
636
+
637
+ await withTenant(tenantId, (tx) =>
638
+ tx.platformJob.update({
639
+ where: { id: jobId },
640
+ data: {
641
+ status: 'DONE',
642
+ result: { ...(result as any) } as any,
643
+ progress: 100,
644
+ finishedAt: new Date(),
645
+ },
646
+ })
647
+ );
648
+ clearInterval(heartbeatTimer);
649
+ runningControllers.delete(jobId);
650
+
651
+ {
652
+ // Auto-seed: merge all successfully crawled URLs into crawlConfig.seedUrls so future
653
+ // crawls and discovery agents start from a complete picture of the app.
654
+ const crawledUrls: string[] = ((result as any).discovered ?? [])
655
+ .filter((d: any) => !!d.screenId && !!d.url)
656
+ .map((d: any) => d.url as string);
657
+ if (crawledUrls.length > 0) {
658
+ (async () => {
659
+ const cfg = await AppBrain.getCrawlConfig(tenantId, projectId);
660
+ const existing: string[] = cfg?.seedUrls ?? [];
661
+ const merged = Array.from(new Set([...existing, ...crawledUrls]));
662
+ if (merged.length > existing.length) {
663
+ await AppBrain.saveCrawlConfig(tenantId, projectId, { seedUrls: merged });
664
+ logger.info({ added: merged.length - existing.length, total: merged.length }, '[crawl] auto-seeded crawled URLs into crawlConfig.seedUrls');
665
+ }
666
+ })().catch((err: any) => logger.warn({ err: err?.message }, '[crawl] auto-seed seedUrls failed (non-fatal)'));
667
+ }
668
+
669
+ notifyAdmins(tenantId, {
670
+ type: 'crawl.done',
671
+ title: 'Crawl completed',
672
+ body: `Crawl for project finished successfully.`,
673
+ metadata: { projectId, jobId },
674
+ }).catch(console.error);
675
+
676
+ dispatchWebhook(tenantId, projectId, 'crawl.done', {
677
+ jobId,
678
+ screensFound: (result as any)?.screensFound ?? (result as any)?.screens?.length ?? 0,
679
+ }).catch(console.error);
680
+ }
681
+
682
+ // Aggregate token usage from LLM calls made during this job.
683
+ // Delay 8s to let concurrent recordLLMCall writes settle before querying LLMCallLog.
684
+ setTimeout(() => {
685
+ aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
686
+ }, 8000);
687
+
688
+ // Post-crawl: generate / refresh all taxonomy skill files + investigate changes.
689
+ setImmediate(async () => {
690
+ try {
691
+ const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
692
+ if (projectMap?.screens?.length) {
693
+ // Mark project oversized when > 300 screens — activates VectorSearchGrounding
694
+ const screenCount = (projectMap.screens as any[]).length;
695
+ if (screenCount > 300) {
696
+ await withTenant(tenantId, (tx) =>
697
+ (tx as any).project.update({ where: { id: projectId }, data: { oversized: true } })
698
+ );
699
+ }
700
+ await generateTaxonomySkillFiles(tenantId, projectId, projectMap.screens as any, result.apiEndpoints, result.performanceMetrics);
701
+
702
+ // Cloud storage: upload screenshots to tenant S3/R2 if configured
703
+ const tenantStorageCfg = await getTenantStorageConfig(tenantId).catch(() => null);
704
+ if (tenantStorageCfg) {
705
+ let uploaded = 0;
706
+ for (const screen of projectMap.screens as any[]) {
707
+ for (const shot of (screen.screenshots ?? []) as any[]) {
708
+ if (!shot.storagePath || shot.cloudUrl) continue;
709
+ try {
710
+ const filename = `${screen.id}-v${shot.version}.png`;
711
+ const key = buildArtifactKey(tenantId, projectId, 'screenshots', filename, tenantStorageCfg.prefix);
712
+ const cloudUrl = await uploadScreenshotToTenantStorage(tenantStorageCfg, shot.storagePath, key);
713
+ await AppBrain.updateScreenshotCloudUrl(tenantId, shot.id, cloudUrl);
714
+ uploaded++;
715
+ } catch (uploadErr) {
716
+ logger.warn({ screenId: screen.id, err: uploadErr }, 'Failed to upload screenshot to cloud storage');
717
+ }
718
+ }
719
+ }
720
+ if (uploaded > 0) logger.info({ uploaded, provider: tenantStorageCfg.provider }, 'Uploaded screenshots to cloud storage');
721
+
722
+ // Upload DOM snapshots and markdown to tenant storage
723
+ const { existsSync } = await import('node:fs');
724
+ let domUploaded = 0;
725
+ let mdUploaded = 0;
726
+ for (const screen of projectMap.screens as any[]) {
727
+ // DOM snapshot
728
+ const domPath = screen.domSnapshotPath;
729
+ if (domPath && !domPath.startsWith('https://') && existsSync(domPath)) {
730
+ try {
731
+ const key = buildArtifactKey(tenantId, projectId, 'dom-snapshots', `${screen.id}.json`, tenantStorageCfg.prefix);
732
+ const cloudUrl = await uploadFileToTenantStorage(tenantStorageCfg, domPath, key, 'application/json');
733
+ await AppBrain.updateScreenDomSnapshot(tenantId, screen.id, cloudUrl);
734
+ domUploaded++;
735
+ } catch (err) {
736
+ logger.warn({ screenId: screen.id, err }, 'Failed to upload DOM snapshot to cloud storage');
737
+ }
738
+ }
739
+ // Markdown extract
740
+ const mdPath = screen.markdownPath;
741
+ if (mdPath && !mdPath.startsWith('https://') && existsSync(mdPath)) {
742
+ try {
743
+ const key = buildArtifactKey(tenantId, projectId, 'markdown', `${screen.id}.md`, tenantStorageCfg.prefix);
744
+ const cloudUrl = await uploadFileToTenantStorage(tenantStorageCfg, mdPath, key, 'text/markdown');
745
+ await AppBrain.updateScreenMarkdownPath(tenantId, screen.id, cloudUrl);
746
+ mdUploaded++;
747
+ } catch (err) {
748
+ logger.warn({ screenId: screen.id, err }, 'Failed to upload markdown to cloud storage');
749
+ }
750
+ }
751
+ }
752
+ if (domUploaded > 0) logger.info({ domUploaded, provider: tenantStorageCfg.provider }, 'Uploaded DOM snapshots to cloud storage');
753
+ if (mdUploaded > 0) logger.info({ mdUploaded, provider: tenantStorageCfg.provider }, 'Uploaded markdown to cloud storage');
754
+ }
755
+
756
+ // AI screen grouping — clusters screens into semantic feature areas
757
+ await groupScreensWithAI(tenantId, projectId, projectMap.screens as any, jobId, jobStartedAt);
758
+
759
+ // Auto-flag stale tests: mark PENDING_REVIEW when screen elements changed since test was generated
760
+ try {
761
+ await withTenant(tenantId, async (tx) => {
762
+ const staleTests = await tx.$queryRaw<{ id: string }[]>`
763
+ SELECT tc.id
764
+ FROM "TestCase" tc
765
+ JOIN "Screen" s ON tc."screenId" = s.id
766
+ WHERE tc."tenantId" = ${tenantId}
767
+ AND s."projectId" = ${projectId}
768
+ AND s."elementHashChangedAt" IS NOT NULL
769
+ AND tc."genAt" IS NOT NULL
770
+ AND s."elementHashChangedAt" > tc."genAt"
771
+ AND tc.status != 'PENDING_REVIEW'
772
+ AND tc.status != 'RETIRED'
773
+ `;
774
+ if (staleTests.length > 0) {
775
+ const ids = staleTests.map((t: { id: string }) => t.id);
776
+ await tx.testCase.updateMany({
777
+ where: { id: { in: ids } },
778
+ data: { status: 'PENDING_REVIEW' },
779
+ });
780
+ logger.info({ count: staleTests.length, projectId }, 'Auto-flagged stale test cases as PENDING_REVIEW');
781
+ }
782
+ });
783
+ } catch (staleErr) {
784
+ logger.warn({ err: staleErr }, 'Failed to auto-flag stale tests');
785
+ }
786
+
787
+ const changed = (projectMap.screens as any[]).filter((s: any) => s.hasChange);
788
+ if (changed.length > 0) {
789
+ await investigateScreenChanges(tenantId, projectId, changed);
790
+ }
791
+ }
792
+ } catch (skillErr) {
793
+ logger.error({ projectId, err: skillErr }, 'Taxonomy generation failed');
794
+ }
795
+ });
796
+
797
+ } catch (err: any) {
798
+ clearInterval(heartbeatTimer);
799
+ runningControllers.delete(jobId);
800
+ const aborted = String(err).includes('CRAWL_ABORTED');
801
+ const checkpoint = jobCheckpoints.get(jobId);
802
+ jobCheckpoints.delete(jobId);
803
+ await withTenant(tenantId, (tx) =>
804
+ tx.platformJob.update({
805
+ where: { id: jobId },
806
+ data: {
807
+ status: aborted ? 'CANCELLED' : 'FAILED',
808
+ error: aborted ? 'Stopped by user' : String(err),
809
+ finishedAt: new Date(),
810
+ ...(checkpoint ? { result: { checkpoint } as any } : {}),
811
+ },
812
+ })
813
+ );
814
+
815
+ // Notify on crawl failure (fire-and-forget)
816
+ if (!aborted) {
817
+ notifyAdmins(tenantId, {
818
+ type: 'crawl.failed',
819
+ title: 'Crawl failed',
820
+ body: `Crawl for project failed: ${String(err)}`,
821
+ metadata: { projectId, jobId, error: String(err) },
822
+ }).catch(console.error);
823
+
824
+ // Dispatch outbound webhooks (fire-and-forget)
825
+ dispatchWebhook(tenantId, projectId, 'crawl.failed', {
826
+ jobId,
827
+ error: String(err),
828
+ }).catch(console.error);
829
+ }
830
+ } finally {
831
+ runningControllers.delete(jobId);
832
+ }
833
+ }
834
+
835
+ /** After a job finishes, sum LLMCallLog entries for that project during the job window. */
836
+ export async function aggregateJobTokens(tenantId: string, jobId: string, projectId: string, startedAt: Date) {
837
+ try {
838
+ await withTenant(tenantId, async (tx) => {
839
+ const rows = await tx.$queryRaw<any[]>`
840
+ SELECT
841
+ COALESCE(SUM("promptTokens"), 0)::INT AS "totalPromptTokens",
842
+ COALESCE(SUM("completionTokens"), 0)::INT AS "totalCompletionTokens",
843
+ COALESCE(SUM("cacheReadTokens"), 0)::INT AS "totalCacheReadTokens",
844
+ COALESCE(SUM("estimatedCostUsd"), 0.0) AS "totalEstimatedCostUsd",
845
+ COUNT(*)::INT AS "llmCallCount"
846
+ FROM "LLMCallLog"
847
+ WHERE "tenantId" = ${tenantId}
848
+ AND "jobId" = ${jobId}
849
+ `;
850
+ const row = rows[0];
851
+ if (!row || !row.llmCallCount) return;
852
+ await tx.platformJob.update({
853
+ where: { id: jobId },
854
+ data: {
855
+ totalPromptTokens: row.totalPromptTokens,
856
+ totalCompletionTokens: row.totalCompletionTokens,
857
+ totalCacheReadTokens: row.totalCacheReadTokens,
858
+ totalEstimatedCostUsd: Number(row.totalEstimatedCostUsd),
859
+ llmCallCount: row.llmCallCount,
860
+ },
861
+ });
862
+ });
863
+ } catch (err) {
864
+ console.warn('[job-tokens] aggregation failed:', err);
865
+ }
866
+ }
867
+
868
+ async function processApiTestsJob(jobId: string, config: any) {
869
+ const { tenantId, projectId } = config;
870
+ const jobStartedAt = new Date();
871
+ await withTenant(tenantId, (tx) =>
872
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
873
+ );
874
+ try {
875
+ const { generateApiTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@detiq/agents');
876
+ await updateJobProgress(tenantId, jobId, 20, 'Loading API contracts and endpoints…');
877
+ const result = await generateApiTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
878
+ await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} API test cases`);
879
+ refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
880
+ refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
881
+ refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
882
+ await withTenant(tenantId, (tx) =>
883
+ tx.platformJob.update({
884
+ where: { id: jobId },
885
+ data: {
886
+ status: 'DONE', progress: 100, finishedAt: new Date(),
887
+ result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
888
+ },
889
+ })
890
+ );
891
+ aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
892
+ } catch (err: any) {
893
+ await withTenant(tenantId, (tx) =>
894
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err), finishedAt: new Date() } })
895
+ );
896
+ }
897
+ }
898
+
899
+ async function processSecurityTestsJob(jobId: string, config: any) {
900
+ const { tenantId, projectId } = config;
901
+ const jobStartedAt = new Date();
902
+ await withTenant(tenantId, (tx) =>
903
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
904
+ );
905
+ try {
906
+ const { generateSecurityTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@detiq/agents');
907
+ await updateJobProgress(tenantId, jobId, 20, 'Mapping OWASP attack surface…');
908
+ const result = await generateSecurityTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
909
+ await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} security test cases`);
910
+ refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
911
+ refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
912
+ refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
913
+ await withTenant(tenantId, (tx) =>
914
+ tx.platformJob.update({
915
+ where: { id: jobId },
916
+ data: {
917
+ status: 'DONE', progress: 100, finishedAt: new Date(),
918
+ result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
919
+ },
920
+ })
921
+ );
922
+ aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
923
+ } catch (err: any) {
924
+ await withTenant(tenantId, (tx) =>
925
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err), finishedAt: new Date() } })
926
+ );
927
+ }
928
+ }
929
+
930
+ async function processIntegrationTestsJob(jobId: string, config: any) {
931
+ const { tenantId, projectId } = config;
932
+ const jobStartedAt = new Date();
933
+ await withTenant(tenantId, (tx) =>
934
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
935
+ );
936
+ try {
937
+ const { generateIntegrationTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@detiq/agents');
938
+ await updateJobProgress(tenantId, jobId, 20, 'Analysing API contracts and data models…');
939
+ const result = await generateIntegrationTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
940
+ await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} integration test cases`);
941
+ refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
942
+ refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
943
+ refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
944
+ await withTenant(tenantId, (tx) =>
945
+ tx.platformJob.update({
946
+ where: { id: jobId },
947
+ data: {
948
+ status: 'DONE', progress: 100, finishedAt: new Date(),
949
+ result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
950
+ },
951
+ })
952
+ );
953
+ aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
954
+ } catch (err: any) {
955
+ await withTenant(tenantId, (tx) =>
956
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err), finishedAt: new Date() } })
957
+ );
958
+ }
959
+ }
960
+
961
+ async function processFigmaImportJob(jobId: string, config: any) {
962
+ const { tenantId, projectId, fileKey } = config;
963
+ await withTenant(tenantId, (tx) =>
964
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
965
+ );
966
+ try {
967
+ const connector = await withTenant(tenantId, (tx) =>
968
+ (tx as any).connector.findFirst({ where: { projectId, kind: 'FIGMA', tenantId } })
969
+ ) as any;
970
+ if (!connector) throw new Error('Figma connector not configured. Add your Figma token in Project Settings → Integrations.');
971
+
972
+ const cfg = connector.config as Record<string, string>;
973
+ const accessToken = cfg.accessToken_enc ? decrypt(cfg.accessToken_enc) : '';
974
+ if (!accessToken) throw new Error('Figma access token missing. Edit the Figma connector and add your Personal Access Token.');
975
+
976
+ const resolvedFileKey = fileKey ?? cfg.fileKey ?? '';
977
+ if (!resolvedFileKey) throw new Error('No Figma file key. Paste the full Figma file URL as the App URL.');
978
+
979
+ const creds: figma.FigmaCredentials = { accessToken, fileKey: resolvedFileKey };
980
+
981
+ await updateJobProgress(tenantId, jobId, 5, 'Listing frames from Figma file…');
982
+ const frames = await figma.listScreens(creds, resolvedFileKey);
983
+ if (frames.length === 0) {
984
+ await withTenant(tenantId, (tx) =>
985
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, result: { screensImported: 0 } as any, finishedAt: new Date() } })
986
+ );
987
+ return;
988
+ }
989
+
990
+ await updateJobProgress(tenantId, jobId, 15, `Fetching images for ${frames.length} frames…`);
991
+ const nodeIds = frames.map((f: any) => f.id);
992
+ const imageUrls = await figma.getScreenImages(creds, resolvedFileKey, nodeIds, 1);
993
+
994
+ const screenshotDir = path.join(platformConfig.screenshotDir, projectId);
995
+ await fs.mkdir(screenshotDir, { recursive: true });
996
+ const tenantStorageCfg = await getTenantStorageConfig(tenantId).catch(() => null);
997
+
998
+ let saved = 0;
999
+ for (const frame of frames) {
1000
+ try {
1001
+ const pct = Math.round(15 + ((saved / frames.length) * 80));
1002
+ await updateJobProgress(tenantId, jobId, pct, `Saving frame ${saved + 1}/${frames.length}: ${(frame as any).name}`);
1003
+ const screen = await AppBrain.saveScreen(tenantId, projectId, (frame as any).name, `figma://file/${resolvedFileKey}/node/${(frame as any).id}`);
1004
+ const imgUrl = (imageUrls as any)[(frame as any).id];
1005
+ if (imgUrl) {
1006
+ const imgRes = await fetch(imgUrl);
1007
+ if (imgRes.ok) {
1008
+ const buf = Buffer.from(await imgRes.arrayBuffer());
1009
+ const filename = `${screen.id}-v1.png`;
1010
+ const storagePath = path.join(screenshotDir, filename);
1011
+ await fs.writeFile(storagePath, buf);
1012
+ let cloudUrl: string | undefined;
1013
+ if (tenantStorageCfg) {
1014
+ try {
1015
+ const key = buildArtifactKey(tenantId, projectId, 'screenshots', filename, tenantStorageCfg.prefix);
1016
+ cloudUrl = (await uploadScreenshotToTenantStorage(tenantStorageCfg, storagePath, key)) ?? undefined;
1017
+ } catch (e) {
1018
+ console.warn('[figma-import] cloud upload failed:', e);
1019
+ }
1020
+ }
1021
+ await AppBrain.saveScreenshot(tenantId, projectId, screen.id, storagePath, 1, 'DESKTOP', cloudUrl);
1022
+ }
1023
+ }
1024
+
1025
+ // Extract elements from Figma frame node → save for grounding + test generation
1026
+ if ((frame as any).node) {
1027
+ const figmaElements = figma.extractElements((frame as any).node);
1028
+ for (const el of figmaElements) {
1029
+ const role = el.type === 'COMPONENT' || el.type === 'COMPONENT_SET' ? 'COMPONENT'
1030
+ : el.type === 'INSTANCE' ? 'COMPONENT'
1031
+ : el.type === 'TEXT' ? 'TEXT'
1032
+ : el.type === 'FRAME' || el.type === 'GROUP' ? 'REGION'
1033
+ : el.type;
1034
+ const boundingRect = el.boundingBox
1035
+ ? { x: Math.round(el.boundingBox.x), y: Math.round(el.boundingBox.y), width: Math.round(el.boundingBox.width), height: Math.round(el.boundingBox.height) }
1036
+ : undefined;
1037
+ await AppBrain.saveElement(
1038
+ tenantId, projectId, screen.id,
1039
+ el.name, role, undefined,
1040
+ el.description ?? undefined, undefined,
1041
+ el.isInteractive,
1042
+ boundingRect, undefined, undefined,
1043
+ );
1044
+ }
1045
+ }
1046
+
1047
+ saved++;
1048
+ } catch (err) {
1049
+ console.warn(`[figma-import] Failed to save frame:`, err);
1050
+ }
1051
+ }
1052
+
1053
+ await withTenant(tenantId, (tx) =>
1054
+ tx.platformJob.update({
1055
+ where: { id: jobId },
1056
+ data: { status: 'DONE', progress: 100, result: { screensImported: saved, totalFrames: frames.length } as any, finishedAt: new Date() },
1057
+ })
1058
+ );
1059
+
1060
+ // Post-import: run AI grouping + taxonomy skill files (same as post-crawl)
1061
+ setImmediate(async () => {
1062
+ try {
1063
+ const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
1064
+ if (projectMap?.screens?.length) {
1065
+ await generateTaxonomySkillFiles(tenantId, projectId, projectMap.screens as any);
1066
+ await groupScreensWithAI(tenantId, projectId, projectMap.screens as any, jobId, new Date());
1067
+ }
1068
+ } catch (err) {
1069
+ console.error('[figma-import] post-import grouping failed:', err);
1070
+ }
1071
+ });
1072
+
1073
+ } catch (err: any) {
1074
+ await withTenant(tenantId, (tx) =>
1075
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err?.message ?? err), finishedAt: new Date() } })
1076
+ );
1077
+ }
1078
+ }
1079
+
1080
+ async function processNativeCrawlJob(jobId: string, config: any) {
1081
+ const { tenantId, projectId } = config;
1082
+ const jobStartedAt = new Date();
1083
+ try {
1084
+ const build = await withTenant(tenantId, (tx) =>
1085
+ (tx as any).nativeAppBuild.findFirst({
1086
+ where: { tenantId, projectId },
1087
+ orderBy: { uploadedAt: 'desc' },
1088
+ })
1089
+ ) as { platform: string; fileFormat: string; s3Path: string; packageName: string | null } | null;
1090
+
1091
+ if (!build) throw new Error('No native app build found for project');
1092
+
1093
+ // AAB requires bundletool conversion — fail early with a clear message
1094
+ if (build.fileFormat === 'aab') {
1095
+ throw new Error(
1096
+ 'AAB format cannot be installed directly by Appium. Convert to APK using bundletool first, then re-upload the APK.'
1097
+ );
1098
+ }
1099
+
1100
+ // Persist device targeting info on the job record
1101
+ const deviceFarm = (config.deviceFarm ?? 'local_emulator') as 'local_emulator' | 'aws_device_farm' | 'browserstack';
1102
+ await withTenant(tenantId, (tx) =>
1103
+ (tx as any).platformJob.update({
1104
+ where: { id: jobId },
1105
+ data: {
1106
+ deviceModel: config.deviceModel ?? null,
1107
+ osVersion: config.osVersion ?? null,
1108
+ deviceFarm,
1109
+ },
1110
+ })
1111
+ ).catch(() => {});
1112
+
1113
+ const workspaceDeviceFarm = await AppBrain.getTenantDeviceFarmConfig(tenantId).catch(() => null);
1114
+
1115
+ await runNativeCrawl({
1116
+ tenantId,
1117
+ projectId,
1118
+ jobId,
1119
+ platform: build.platform as 'android' | 'ios' | 'windows' | 'macos',
1120
+ appS3Path: build.s3Path,
1121
+ packageName: build.packageName ?? undefined,
1122
+ deviceModel: config.deviceModel,
1123
+ osVersion: config.osVersion,
1124
+ deviceFarm,
1125
+ appiumServerUrl: workspaceDeviceFarm?.appiumServerUrl,
1126
+ browserstackUsername: workspaceDeviceFarm?.browserstackUsername,
1127
+ browserstackAccessKey: workspaceDeviceFarm?.browserstackAccessKey,
1128
+ awsAccessKeyId: workspaceDeviceFarm?.awsAccessKeyId,
1129
+ awsSecretAccessKey: workspaceDeviceFarm?.awsSecretAccessKey,
1130
+ awsRegion: workspaceDeviceFarm?.awsRegion,
1131
+ awsDeviceFarmProjectArn: workspaceDeviceFarm?.awsDeviceFarmProjectArn,
1132
+ });
1133
+
1134
+ // Post-crawl: generate taxonomy skill files + AI screen grouping (mirrors web crawl processJob)
1135
+ setImmediate(async () => {
1136
+ try {
1137
+ const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
1138
+ const screens = (projectMap?.screens ?? []) as any[];
1139
+ if (screens.length > 0) {
1140
+ await generateTaxonomySkillFiles(tenantId, projectId, screens);
1141
+ await groupScreensWithAI(tenantId, projectId, screens, jobId, jobStartedAt);
1142
+
1143
+ // Auto-flag stale tests: mark PENDING_REVIEW when screen elements changed since test was generated
1144
+ try {
1145
+ await withTenant(tenantId, async (tx) => {
1146
+ const staleTests = await tx.$queryRaw<{ id: string }[]>`
1147
+ SELECT tc.id
1148
+ FROM "TestCase" tc
1149
+ JOIN "Screen" s ON tc."screenId" = s.id
1150
+ WHERE tc."tenantId" = ${tenantId}
1151
+ AND s."projectId" = ${projectId}
1152
+ AND s."elementHashChangedAt" IS NOT NULL
1153
+ AND tc."genAt" IS NOT NULL
1154
+ AND s."elementHashChangedAt" > tc."genAt"
1155
+ AND tc.status != 'PENDING_REVIEW'
1156
+ AND tc.status != 'RETIRED'
1157
+ `;
1158
+ if (staleTests.length > 0) {
1159
+ const ids = staleTests.map((t: { id: string }) => t.id);
1160
+ await tx.testCase.updateMany({
1161
+ where: { id: { in: ids } },
1162
+ data: { status: 'PENDING_REVIEW' },
1163
+ });
1164
+ logger.info({ count: staleTests.length, projectId }, 'Auto-flagged stale test cases as PENDING_REVIEW');
1165
+ }
1166
+ });
1167
+ } catch (staleErr) {
1168
+ logger.warn({ err: staleErr }, 'Failed to auto-flag stale tests');
1169
+ }
1170
+ }
1171
+ } catch (e) {
1172
+ logger.error({ err: e }, 'post-native-crawl processing failed');
1173
+ }
1174
+ });
1175
+ } catch (err: any) {
1176
+ await withTenant(tenantId, (tx) =>
1177
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err?.message ?? err), finishedAt: new Date() } })
1178
+ ).catch(() => {});
1179
+ }
1180
+ }
1181
+
1182
+ async function processGenerateTestsFromReqsJob(jobId: string, config: any) {
1183
+ const { tenantId, projectId, reqIds, suiteId, suiteName } = config;
1184
+ try {
1185
+ await updateJobProgress(tenantId, jobId, 5, 'Loading requirements');
1186
+
1187
+ const { askTracked, getTaskAgentLLMConfig } = await import('@detiq/agents');
1188
+ const llmCfg = await getTaskAgentLLMConfig(tenantId, 'testGeneration');
1189
+
1190
+ const all = await AppBrain.listRequirements(tenantId, projectId, {}) as any[];
1191
+ const reqs = reqIds?.length
1192
+ ? all.filter((r: any) => reqIds.includes(r.reqId))
1193
+ : all.filter((r: any) => r.status === 'unbuilt' || r.status === 'pending');
1194
+
1195
+ if (reqs.length === 0) {
1196
+ await updateJobProgress(tenantId, jobId, 100, 'No pending requirements found');
1197
+ await withTenant(tenantId, (tx) =>
1198
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { created: 0, skipped: 0 } as any } })
1199
+ );
1200
+ return;
1201
+ }
1202
+
1203
+ // Resolve or create suite
1204
+ let resolvedSuiteId = suiteId;
1205
+ if (!resolvedSuiteId) {
1206
+ const name = suiteName?.trim() || 'Requirements Tests';
1207
+ const suite = await withTenant(tenantId, async (tx) => {
1208
+ const existing = await (tx as any).testSuite.findFirst({ where: { tenantId, projectId, name } });
1209
+ if (existing) return existing;
1210
+ return (tx as any).testSuite.create({ data: { tenantId, projectId, name } });
1211
+ }) as any;
1212
+ resolvedSuiteId = suite.id;
1213
+ }
1214
+
1215
+ await updateJobProgress(tenantId, jobId, 20, `Generating tests for ${reqs.length} requirements`);
1216
+
1217
+ const reqBlock = reqs.map((r: any) => [
1218
+ `## ${r.reqId}: ${r.title}`,
1219
+ `Priority: ${r.priority} | Type: ${r.type}`,
1220
+ r.acceptanceCriteria?.length ? `Acceptance Criteria:\n${r.acceptanceCriteria.map((c: string) => `- ${c}`).join('\n')}` : '',
1221
+ r.businessRules?.length ? `Business Rules:\n${r.businessRules.map((b: string) => `- ${b}`).join('\n')}` : '',
1222
+ ].filter(Boolean).join('\n')).join('\n\n');
1223
+
1224
+ const system = `You are ZeTa-AI's test case generator. Convert requirements into structured test cases.
1225
+ Return ONLY valid JSON: { "cases": [ { "title": string, "kind": string, "priority": string, "preconditions": string, "steps": [{"action": string, "data": string, "expected": string}], "expectedResult": string, "tags": string[], "reqRef": string } ] }
1226
+ Kind must be one of: POSITIVE, NEGATIVE, EDGE, SECURITY, ACCESSIBILITY, INTEGRATION, E2E, SMOKE, REGRESSION.
1227
+ Priority must be one of: CRITICAL, HIGH, MEDIUM, LOW.
1228
+ Generate 1-3 test cases per requirement (positive + negative + edge if applicable).
1229
+ Each test case must reference its reqRef (the requirement ID like REQ-001).`;
1230
+
1231
+ const user = `Generate test cases for these requirements:\n\n${reqBlock}`;
1232
+
1233
+ let parsed: { cases: any[] } = { cases: [] };
1234
+ try {
1235
+ const { text, usage } = await askTracked(system, user, llmCfg);
1236
+ if (usage) recordLLMCall({ tenantId, projectId, jobId, agentType: 'generate_tests_from_reqs', label: 'test_case_generation', usage }).catch(() => {});
1237
+ const json = text.match(/\{[\s\S]*\}/)?.[0];
1238
+ if (json) parsed = JSON.parse(json);
1239
+ } catch (e: any) {
1240
+ throw new Error('AI failed to generate test cases: ' + (e.message ?? 'unknown'));
1241
+ }
1242
+
1243
+ await updateJobProgress(tenantId, jobId, 70, `Saving ${parsed.cases?.length ?? 0} test cases`);
1244
+
1245
+ const VALID_KINDS = new Set(['POSITIVE','NEGATIVE','EDGE','STATE_TRANSITION','ACCESSIBILITY','SECURITY','INTEGRATION','E2E','API','EXPLORATORY','UAT','PERFORMANCE','COMPATIBILITY','L10N','USABILITY','LOAD','UNIT','MUTATION','AB_TEST','ALPHA_BETA','SYSTEM','SMOKE','REGRESSION','SANITY']);
1246
+ const VALID_PRIORITIES = new Set(['CRITICAL','HIGH','MEDIUM','LOW']);
1247
+ const normalized = (parsed.cases ?? []).map((c: any) => ({
1248
+ ref: c.reqRef ?? null,
1249
+ traceTo: c.reqRef ?? null,
1250
+ title: c.title || 'Untitled',
1251
+ kind: VALID_KINDS.has((c.kind ?? '').toUpperCase()) ? c.kind.toUpperCase() : 'POSITIVE',
1252
+ priority: VALID_PRIORITIES.has((c.priority ?? '').toUpperCase()) ? c.priority.toUpperCase() : 'MEDIUM',
1253
+ preconditions: c.preconditions ?? '',
1254
+ steps: Array.isArray(c.steps) ? c.steps : [],
1255
+ expectedResult: c.expectedResult ?? '',
1256
+ tags: Array.isArray(c.tags) ? c.tags : [],
1257
+ }));
1258
+
1259
+ const { created, skipped } = await AppBrain.importTestCasesFromArtifact(
1260
+ tenantId, projectId, resolvedSuiteId, normalized, { duplicateMode: 'skip' }
1261
+ );
1262
+
1263
+ // Mark requirements as covered
1264
+ const coveredReqIds = new Set(normalized.map((c: any) => c.ref).filter(Boolean));
1265
+ await Promise.all(
1266
+ reqs
1267
+ .filter((r: any) => coveredReqIds.has(r.reqId))
1268
+ .map((r: any) => AppBrain.updateRequirement(tenantId, projectId, r.reqId, { status: 'covered' }).catch(() => {}))
1269
+ );
1270
+
1271
+ await withTenant(tenantId, (tx) =>
1272
+ tx.platformJob.update({
1273
+ where: { id: jobId },
1274
+ data: { status: 'DONE', finishedAt: new Date(), result: { created: created.length, skipped, suiteId: resolvedSuiteId } as any, progress: 100 },
1275
+ })
1276
+ );
1277
+ } catch (e: any) {
1278
+ const msg = e?.message ?? 'Unknown error';
1279
+ logger.error({ jobId, err: msg }, 'processGenerateTestsFromReqsJob failed');
1280
+ await withTenant(tenantId, (tx) =>
1281
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg } })
1282
+ ).catch(() => {});
1283
+ }
1284
+ }
1285
+
1286
+ /**
1287
+ * Runs every APPROVED test case in a project (optionally scoped to one suite)
1288
+ * against the agent-free Playwright executor (test-executor.ts) and aggregates
1289
+ * the results into the TestRun row created synchronously by POST /run-tests
1290
+ * (see ci.ts) — this is what makes the CI gate (GET /test-results/latest)
1291
+ * finally reflect what CI itself triggered, instead of a stale or nonexistent
1292
+ * result from an unrelated, manually-triggered, agent-connected suite run.
1293
+ */
1294
+ async function processRunTestSuiteJob(jobId: string, config: any) {
1295
+ const { tenantId, projectId, testRunId, suiteId, storageState, browser, shardIndex, totalShards } = config as any;
1296
+ const runStart = Date.now();
1297
+
1298
+ await withTenant(tenantId, (tx) =>
1299
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
1300
+ );
1301
+
1302
+ try {
1303
+ let testCases = await AppBrain.listTestCases(tenantId, projectId, {
1304
+ status: 'APPROVED',
1305
+ ...(suiteId ? { suiteId } : {}),
1306
+ }) as Array<{ id: string }>;
1307
+
1308
+ // Shard filtering: when running a distributed matrix (CI-triggered multi-browser/shard),
1309
+ // each worker only executes its own slice — testCases[shardIndex::totalShards].
1310
+ if (typeof totalShards === 'number' && totalShards > 1 && typeof shardIndex === 'number') {
1311
+ testCases = testCases.filter((_, i) => i % totalShards === shardIndex);
1312
+ }
1313
+
1314
+ if (testCases.length === 0) {
1315
+ // Nothing approved to run isn't a CI failure — same as any test runner
1316
+ // reporting "0 tests, 0 failures" when a suite is empty.
1317
+ await AppBrain.completeTestRun(tenantId, testRunId, { total: 0, passed: 0, failed: 0, skipped: 0, duration: 0 });
1318
+ await withTenant(tenantId, (tx) =>
1319
+ tx.platformJob.update({
1320
+ where: { id: jobId },
1321
+ data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { total: 0 } as any },
1322
+ })
1323
+ );
1324
+ return;
1325
+ }
1326
+
1327
+ const aiHealingEnabled = await isFeatureEnabled(tenantId, 'AI_SELF_HEALING');
1328
+ const screenshotDir = config.screenshotDir || platformConfig.screenshotDir || '/tmp/zeta-screenshots';
1329
+ const VALID_BROWSERS = ['chromium', 'firefox', 'webkit'];
1330
+ const validBrowser = VALID_BROWSERS.includes(browser) ? browser : 'chromium';
1331
+
1332
+ let passed = 0;
1333
+ let failed = 0;
1334
+ const runResults: Array<{ testCaseId: string; status: string }> = [];
1335
+ for (let i = 0; i < testCases.length; i += TEST_EXEC_CONCURRENCY) {
1336
+ const batch = testCases.slice(i, i + TEST_EXEC_CONCURRENCY);
1337
+ await Promise.all(batch.map(async (tc) => {
1338
+ try {
1339
+ const full = await AppBrain.getTestCaseForExecution(tenantId, tc.id) as any;
1340
+ const baseUrl = full?.screen?.project?.appUrl ?? '';
1341
+ const execProjectId = full?.screen?.project?.id ?? projectId;
1342
+ const dataRows: Array<{ id: string; rowIndex: number; data: Record<string, string> }> =
1343
+ full?.dataSet?.rows ?? [];
1344
+
1345
+ // Data-driven: run once per row (substituting placeholders). If no data set, run once with no substitution.
1346
+ const runs = dataRows.length > 0 ? dataRows : [null];
1347
+
1348
+ for (const row of runs) {
1349
+ let tcForPlan = full ?? tc;
1350
+ if (row !== null) {
1351
+ // Clone the test case with interpolated steps and title
1352
+ const rawSteps = Array.isArray(tcForPlan.steps) ? tcForPlan.steps as string[] : [];
1353
+ tcForPlan = {
1354
+ ...tcForPlan,
1355
+ steps: rawSteps.map((s: string) => interpolatePlaceholders(s, row.data)),
1356
+ title: interpolatePlaceholders(tcForPlan.title ?? '', row.data),
1357
+ preconditions: tcForPlan.preconditions
1358
+ ? interpolatePlaceholders(tcForPlan.preconditions, row.data)
1359
+ : tcForPlan.preconditions,
1360
+ };
1361
+ }
1362
+
1363
+ const plan = await generateExecutionPlan(tenantId, tcForPlan, baseUrl);
1364
+ const result = await executeTestPlan(plan, {
1365
+ screenshotDir,
1366
+ testRunId,
1367
+ maxRuns: 1,
1368
+ browser: validBrowser as 'chromium' | 'firefox' | 'webkit',
1369
+ storageState,
1370
+ healCtx: aiHealingEnabled ? { tenantId, projectId: execProjectId } : undefined,
1371
+ });
1372
+ const status = result.status === 'PASSED' ? 'PASSED' : result.status === 'ERROR' ? 'ERROR' : 'FAILED';
1373
+ if (status === 'PASSED') passed++; else failed++;
1374
+ runResults.push({ testCaseId: tc.id, status });
1375
+ await AppBrain.saveTestResult(tenantId, {
1376
+ runId: testRunId,
1377
+ testCaseId: tc.id,
1378
+ status,
1379
+ duration: result.totalDuration,
1380
+ ...(result.rootCauseSummary
1381
+ ? { failureAnalysis: result.rootCauseSummary, failureAnalysisAt: new Date() }
1382
+ : {}),
1383
+ ...(row !== null ? { dataRowId: row.id, dataRowIndex: row.rowIndex } : {}),
1384
+ ...((result.consoleLogs?.length || result.networkErrors?.length) ? {
1385
+ logs: {
1386
+ consoleLogs: result.consoleLogs ?? [],
1387
+ networkErrors: result.networkErrors ?? [],
1388
+ },
1389
+ } : {}),
1390
+ });
1391
+ }
1392
+ await AppBrain.recordFlakinessOutcome(tenantId, tc.id).catch(() => {});
1393
+ } catch (err: any) {
1394
+ failed++;
1395
+ runResults.push({ testCaseId: tc.id, status: 'ERROR' });
1396
+ await AppBrain.saveTestResult(tenantId, {
1397
+ runId: testRunId,
1398
+ testCaseId: tc.id,
1399
+ status: 'ERROR',
1400
+ error: String(err?.message ?? err).slice(0, 500),
1401
+ }).catch(() => {});
1402
+ }
1403
+ }));
1404
+ await updateJobProgress(
1405
+ tenantId, jobId,
1406
+ Math.round((Math.min(i + TEST_EXEC_CONCURRENCY, testCases.length) / testCases.length) * 100),
1407
+ `Ran ${Math.min(i + TEST_EXEC_CONCURRENCY, testCases.length)}/${testCases.length} test cases`,
1408
+ );
1409
+ }
1410
+
1411
+ await AppBrain.completeTestRun(tenantId, testRunId, {
1412
+ total: testCases.length,
1413
+ passed,
1414
+ failed,
1415
+ skipped: 0,
1416
+ duration: Date.now() - runStart,
1417
+ });
1418
+
1419
+ await withTenant(tenantId, (tx) =>
1420
+ tx.platformJob.update({
1421
+ where: { id: jobId },
1422
+ data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { total: testCases.length, passed, failed } as any },
1423
+ })
1424
+ );
1425
+
1426
+ // Same full fan-out as the interactive web-driven run path (in-app,
1427
+ // generic webhook, suite-owner failure emails, GitHub check-run, Slack,
1428
+ // Teams, alert emails on failure) — a CI-triggered run has nobody
1429
+ // watching the SSE stream, so this is the only place these fire from.
1430
+ notifyRunCompletion(
1431
+ tenantId, projectId, testRunId,
1432
+ failed === 0 ? 'COMPLETED' : 'FAILED',
1433
+ { passed, failed, total: testCases.length },
1434
+ runResults,
1435
+ ).catch(console.error);
1436
+ } catch (err: any) {
1437
+ const msg = String(err?.message ?? err).slice(0, 500);
1438
+ logger.error({ jobId, testRunId, err: msg }, 'processRunTestSuiteJob failed');
1439
+ await AppBrain.failTestRun(tenantId, testRunId, msg).catch(() => {});
1440
+ await withTenant(tenantId, (tx) =>
1441
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg } })
1442
+ ).catch(() => {});
1443
+ }
1444
+ }
1445
+
1446
+ async function processGenerateSkillFilesJob(jobId: string, config: any) {
1447
+ const { tenantId, projectId } = config;
1448
+ await withTenant(tenantId, (tx) =>
1449
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
1450
+ );
1451
+ try {
1452
+ await updateJobProgress(tenantId, jobId, 10, 'Loading project data…');
1453
+ const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
1454
+ if (!projectMap) throw new Error('Project not found.');
1455
+ const screens = (projectMap.screens ?? []) as any[];
1456
+ // Manual regeneration has no fresh crawl result — reuse the metrics and
1457
+ // endpoints persisted on the last completed crawl job so the Performance
1458
+ // Baseline and API Contract aren't wiped to "no data captured".
1459
+ const lastCrawl = await withTenant(tenantId, (tx) =>
1460
+ tx.platformJob.findFirst({
1461
+ where: { projectId, type: 'CRAWL', status: 'DONE' },
1462
+ orderBy: { finishedAt: 'desc' },
1463
+ select: { result: true },
1464
+ })
1465
+ );
1466
+ const lastResult = (lastCrawl?.result ?? {}) as any;
1467
+ await updateJobProgress(tenantId, jobId, 25, `Generating ${screens.length} app intelligence skill files…`);
1468
+ await generateTaxonomySkillFiles(tenantId, projectId, screens, lastResult.apiEndpoints, lastResult.performanceMetrics);
1469
+ await updateJobProgress(tenantId, jobId, 85, 'Refreshing testing intelligence skill files…');
1470
+ await Promise.allSettled([
1471
+ refreshTestCasesSkillFile(tenantId, projectId),
1472
+ refreshTestDataSkillFile(tenantId, projectId),
1473
+ refreshTestScriptSkillFile(tenantId, projectId),
1474
+ refreshRequirementsCoverageSkillFile(tenantId, projectId),
1475
+ ]);
1476
+ await withTenant(tenantId, (tx) =>
1477
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, finishedAt: new Date() } })
1478
+ );
1479
+ } catch (err: any) {
1480
+ await withTenant(tenantId, (tx) =>
1481
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: String(err?.message ?? err), finishedAt: new Date() } })
1482
+ );
1483
+ }
1484
+ }
1485
+
1486
+ // DATA_RETENTION_PURGE — deletes AuditLog rows older than each tenant's
1487
+ // dataRetentionDays setting (default 365), and LLMCallLog rows older than 90
1488
+ // days (fixed, no per-tenant override). Runs once daily via the cron in
1489
+ // worker.ts. The job has no tenantId/projectId — it sweeps all tenants so
1490
+ // enqueueJob() is not used; the worker.ts cron calls this directly.
1491
+ export async function processDataRetentionPurge(): Promise<void> {
1492
+ logger.info('[data-retention] starting purge run');
1493
+
1494
+ // LLMCallLog: fixed 90-day retention across all tenants (uses calledAt, not createdAt)
1495
+ const llmCutoff = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
1496
+ const llmResult = await prismaAdmin.lLMCallLog.deleteMany({
1497
+ where: { calledAt: { lt: llmCutoff } },
1498
+ });
1499
+ logger.info({ deleted: llmResult.count }, '[data-retention] LLMCallLog purged');
1500
+
1501
+ // AuditLog: per-tenant retention via TenantSetting.dataRetentionDays
1502
+ const tenants = await prismaAdmin.tenant.findMany({ select: { id: true } });
1503
+ let auditTotal = 0;
1504
+
1505
+ for (const { id: tenantId } of tenants) {
1506
+ // Find the most restrictive (lowest) dataRetentionDays across this tenant's
1507
+ // settings rows, falling back to 365 if no setting row exists.
1508
+ const setting = await prismaAdmin.tenantSetting.findFirst({
1509
+ where: { tenantId },
1510
+ orderBy: { dataRetentionDays: 'asc' },
1511
+ select: { dataRetentionDays: true },
1512
+ });
1513
+ const retentionDays = setting?.dataRetentionDays ?? 365;
1514
+ const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000);
1515
+
1516
+ const result = await prismaAdmin.auditLog.deleteMany({
1517
+ where: { tenantId, createdAt: { lt: cutoff } },
1518
+ });
1519
+ auditTotal += result.count;
1520
+ }
1521
+
1522
+ logger.info({ deleted: auditTotal, tenants: tenants.length }, '[data-retention] AuditLog purged');
1523
+ }
1524
+
1525
+ // ── URL Discovery Job ─────────────────────────────────────────────────────────
1526
+ // Three-phase URL discovery: sitemap seed → unauthenticated BFS spider → authenticated BFS
1527
+ // spider (when crawl credentials exist). Persists discovered URLs to crawlConfig and marks the
1528
+ // job DONE with the full URL list so the UI can poll for results.
1529
+
1530
+ async function processDiscoverJob(jobId: string, config: any, opts?: ProcessJobOpts) {
1531
+ const { tenantId, projectId } = config;
1532
+
1533
+ const controller = new AbortController();
1534
+ runningControllers.set(jobId, controller);
1535
+
1536
+ // Shared accumulator — updated by onUrlsDiscovered callback as each page is visited.
1537
+ // This lets the frontend poll and see a growing list before the job finishes.
1538
+ const allUrls = new Set<string>();
1539
+ let lastPartialFlush = 0;
1540
+
1541
+ const flushPartialUrls = async (pct: number, step: string) => {
1542
+ const now = Date.now();
1543
+ // Flush to DB at most every 5 seconds to avoid excessive writes
1544
+ if (now - lastPartialFlush < 5_000 && allUrls.size < 5) return;
1545
+ lastPartialFlush = now;
1546
+ try {
1547
+ await withTenant(tenantId, (tx) =>
1548
+ tx.platformJob.update({
1549
+ where: { id: jobId },
1550
+ data: { progress: pct, result: { step, partialUrls: Array.from(allUrls) } as any, heartbeatAt: new Date() },
1551
+ })
1552
+ );
1553
+ } catch { /* non-fatal */ }
1554
+ await opts?.onProgress?.(pct);
1555
+ };
1556
+
1557
+ const onProgress = async (pct: number, step: string) => {
1558
+ await updateJobProgress(tenantId, jobId, pct, step);
1559
+ await opts?.onProgress?.(pct);
1560
+ };
1561
+
1562
+ try {
1563
+ // Mark RUNNING inside the try block so any DB error is caught by the internal
1564
+ // handler below (which writes result.error). If this were before the try block,
1565
+ // a DB failure would bubble up to dispatchClaimedJob's catch, which writes to
1566
+ // the `error` column instead of `result.error` — the frontend would then show
1567
+ // "Unknown error" rather than the actual message.
1568
+ await withTenant(tenantId, (tx) =>
1569
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
1570
+ );
1571
+ // Load decrypted project crawl config for credentials/proxy/sitemap settings.
1572
+ // Reading Project.crawlConfig directly leaves encrypted fields as *_enc, so
1573
+ // discovery would see username but miss password/storageState/authToken.
1574
+ const crawlCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => null) ?? {};
1575
+ const appUrl: string = config.appUrl ?? crawlCfg.appUrl;
1576
+ if (!appUrl) throw new Error('No app URL configured. Save the crawl settings first.');
1577
+
1578
+ const maxDiscoverUrls: number = config.maxDiscoverUrls ?? 2000;
1579
+ const proxyUrl: string | undefined = config.proxyUrl ?? crawlCfg.proxyUrl;
1580
+ const screenshotDir = os.tmpdir();
1581
+
1582
+ await onProgress(3, 'Seeding from sitemap/robots.txt…');
1583
+
1584
+ // Phase 1 — sitemap + robots.txt seed (fast, no browser)
1585
+ const sitemapResult = await discoverProjectUrls(appUrl, {
1586
+ sitemapUrl: config.sitemapUrl ?? crawlCfg.sitemapUrl,
1587
+ proxyUrl,
1588
+ }).catch(() => ({ candidates: [] as Array<{ url: string; source: string }>, sitemapFound: false }));
1589
+ const sitemapUrls = sitemapResult.candidates.map((c: any) => c.url as string);
1590
+ // Seed accumulator with sitemap URLs so they show immediately
1591
+ for (const u of sitemapUrls) allUrls.add(u);
1592
+ logger.info({ count: sitemapUrls.length, sitemapFound: sitemapResult.sitemapFound }, '[discover] Phase 1 sitemap done');
1593
+
1594
+ // Phase 2 — unauthenticated BFS spider
1595
+ await onProgress(8, `Unauthenticated spider from ${appUrl}…`);
1596
+ const unauthResult = await crawlProject({
1597
+ tenantId,
1598
+ projectId,
1599
+ appUrl,
1600
+ discoveryMode: true,
1601
+ startUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
1602
+ screenshotDir,
1603
+ maxScreens: maxDiscoverUrls,
1604
+ proxyUrl,
1605
+ useFirefox: crawlCfg.useFirefox,
1606
+ abortSignal: controller.signal,
1607
+ jobId,
1608
+ onUrlsDiscovered: async (urls: string[]) => {
1609
+ for (const u of urls) allUrls.add(u);
1610
+ const pct = 8 + Math.round((allUrls.size / Math.max(1, maxDiscoverUrls)) * 42);
1611
+ await flushPartialUrls(Math.min(pct, 49), `Discovered ${allUrls.size} URLs…`);
1612
+ },
1613
+ }, async (pct: number, step: string) => {
1614
+ await flushPartialUrls(8 + Math.round(pct * 0.42), `Unauthenticated: ${step}`);
1615
+ }).catch((err: any) => {
1616
+ if (err?.message === 'CRAWL_ABORTED') throw err;
1617
+ logger.warn({ err: err?.message }, '[discover] Phase 2 unauthenticated spider failed — continuing with partial results');
1618
+ return { discoveredUrls: [] as string[] };
1619
+ });
1620
+
1621
+ for (const u of ((unauthResult as any).discoveredUrls ?? [] as string[])) allUrls.add(u);
1622
+ logger.info({ count: allUrls.size }, '[discover] Phase 2 unauth spider done');
1623
+
1624
+ // Phase 3 — authenticated BFS spider (only when credentials configured)
1625
+ // getCrawlConfig returns flat fields (username/password/totpSecret) — NOT nested under .credentials
1626
+ let resolvedSso: {
1627
+ ssoProvider?: string;
1628
+ ssoDomain?: string;
1629
+ ssoClientId?: string;
1630
+ ssoClientSecret?: string;
1631
+ ssoScope?: string;
1632
+ } = {};
1633
+ if (crawlCfg.ssoProviderId) {
1634
+ const ssoProviders = await AppBrain.getWorkspaceSsoProviders(tenantId).catch(() => []);
1635
+ const ssoProvider = ssoProviders.find((p: any) => p.id === crawlCfg.ssoProviderId);
1636
+ if (ssoProvider) {
1637
+ resolvedSso = {
1638
+ ssoProvider: ssoProvider.provider,
1639
+ ssoDomain: ssoProvider.domain,
1640
+ ssoClientId: ssoProvider.clientId,
1641
+ ssoClientSecret: ssoProvider.clientSecret,
1642
+ ssoScope: ssoProvider.scope,
1643
+ };
1644
+ }
1645
+ }
1646
+
1647
+ const hasCreds = !!(
1648
+ crawlCfg.username ||
1649
+ crawlCfg.storageState ||
1650
+ crawlCfg.authToken ||
1651
+ crawlCfg.chromeProfilePath ||
1652
+ (crawlCfg.httpBasicUsername && crawlCfg.httpBasicPassword)
1653
+ );
1654
+ if (hasCreds && !controller.signal.aborted) {
1655
+ await onProgress(52, 'Authenticated spider…');
1656
+ const runtimeCreds = crawlCfg.username
1657
+ ? {
1658
+ username: crawlCfg.username,
1659
+ password: crawlCfg.password ?? '',
1660
+ ...(crawlCfg.totpSecret
1661
+ ? { getOneTimeCode: async () => generateTOTP(crawlCfg.totpSecret!) }
1662
+ : {}),
1663
+ }
1664
+ : undefined;
1665
+
1666
+ const authResult = await crawlProject({
1667
+ tenantId,
1668
+ projectId,
1669
+ appUrl,
1670
+ discoveryMode: true,
1671
+ credentials: runtimeCreds,
1672
+ storageState: crawlCfg.storageState,
1673
+ httpBasicUsername: crawlCfg.httpBasicUsername,
1674
+ httpBasicPassword: crawlCfg.httpBasicPassword,
1675
+ authToken: crawlCfg.authToken,
1676
+ authTokenHeader: crawlCfg.authTokenHeader,
1677
+ authTokenPrefix: crawlCfg.authTokenPrefix,
1678
+ startUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
1679
+ screenshotDir,
1680
+ maxScreens: maxDiscoverUrls,
1681
+ proxyUrl,
1682
+ chromeProfilePath: crawlCfg.chromeProfilePath,
1683
+ useFirefox: crawlCfg.useFirefox,
1684
+ captchaSolverApiKey: crawlCfg.captchaSolverApiKey,
1685
+ captchaSolverProvider: crawlCfg.captchaSolverProvider,
1686
+ mailslurpApiKey: crawlCfg.mailslurpApiKey,
1687
+ mailslurpInboxId: crawlCfg.mailslurpInboxId,
1688
+ loginInstructions: crawlCfg.loginInstructions,
1689
+ ...resolvedSso,
1690
+ abortSignal: controller.signal,
1691
+ jobId,
1692
+ onUrlsDiscovered: async (urls: string[]) => {
1693
+ for (const u of urls) allUrls.add(u);
1694
+ const pct = 52 + Math.round((allUrls.size / Math.max(1, maxDiscoverUrls)) * 38);
1695
+ await flushPartialUrls(Math.min(pct, 89), `Discovered ${allUrls.size} URLs (authenticated)…`);
1696
+ },
1697
+ }, async (pct: number, step: string) => {
1698
+ await flushPartialUrls(52 + Math.round(pct * 0.38), `Authenticated: ${step}`);
1699
+ }).catch((err: any) => {
1700
+ if (err?.message === 'CRAWL_ABORTED') throw err;
1701
+ logger.warn({ err: err?.message }, '[discover] Phase 3 authenticated spider failed — using unauthenticated results');
1702
+ return { discoveredUrls: [] as string[] };
1703
+ });
1704
+
1705
+ for (const u of (((authResult as any).discoveredUrls) ?? [] as string[])) {
1706
+ allUrls.add(u);
1707
+ }
1708
+ logger.info({ count: allUrls.size }, '[discover] Phase 3 auth spider done');
1709
+ }
1710
+
1711
+ // Persist discovered URLs to project crawl config
1712
+ const discoveredUrls = Array.from(allUrls);
1713
+ const existingCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => ({}));
1714
+ await AppBrain.saveCrawlConfig(tenantId, projectId, {
1715
+ ...(existingCfg as any),
1716
+ discoveredUrls,
1717
+ discoveredAt: new Date().toISOString(),
1718
+ });
1719
+
1720
+ await onProgress(100, `Done — ${discoveredUrls.length} URLs discovered`);
1721
+
1722
+ await withTenant(tenantId, (tx) =>
1723
+ tx.platformJob.update({
1724
+ where: { id: jobId },
1725
+ data: {
1726
+ status: 'DONE',
1727
+ result: {
1728
+ discoveredUrls,
1729
+ count: discoveredUrls.length,
1730
+ sitemapFound: sitemapResult.sitemapFound,
1731
+ } as any,
1732
+ progress: 100,
1733
+ finishedAt: new Date(),
1734
+ },
1735
+ })
1736
+ );
1737
+
1738
+ notifyAdmins(tenantId, {
1739
+ type: 'discovery.done',
1740
+ title: 'URL Discovery completed',
1741
+ body: `Found ${discoveredUrls.length} URLs for the project.`,
1742
+ metadata: { projectId, jobId },
1743
+ }).catch(console.error);
1744
+
1745
+ } catch (err: any) {
1746
+ logger.error({ err: err?.message, jobId }, '[discover] Job failed');
1747
+ await withTenant(tenantId, (tx) =>
1748
+ tx.platformJob.update({
1749
+ where: { id: jobId },
1750
+ data: {
1751
+ status: err?.message === 'CRAWL_ABORTED' ? 'CANCELLED' : 'FAILED',
1752
+ result: { error: err?.message ?? String(err) } as any,
1753
+ finishedAt: new Date(),
1754
+ },
1755
+ })
1756
+ ).catch(console.error);
1757
+ } finally {
1758
+ runningControllers.delete(jobId);
1759
+ }
1760
+ }
1761
+
1762
+ // ── Site Monitor Job ─────────────────────────────────────────────────────────
1763
+ // Lightweight scheduled content check: fetches configured URLs, diffs content
1764
+ // hashes against stored baselines, fires content.changed webhooks on drift.
1765
+ // Baselines are stored in project.crawlConfig.monitorBaselines (url→hash map).
1766
+
1767
+ async function processMonitorJob(jobId: string, config: any, opts?: ProcessJobOpts) {
1768
+ const { tenantId, projectId } = config;
1769
+ const controller = new AbortController();
1770
+ runningControllers.set(jobId, controller);
1771
+
1772
+ try {
1773
+ await withTenant(tenantId, (tx) =>
1774
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
1775
+ );
1776
+
1777
+ const proj: any = await withTenant(tenantId, (tx) =>
1778
+ (tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
1779
+ );
1780
+ const crawlCfg = proj?.crawlConfig ?? {};
1781
+ const monitorUrls: string[] = config.monitorUrls ?? crawlCfg.monitorUrls ?? [];
1782
+
1783
+ if (monitorUrls.length === 0) {
1784
+ throw new Error('No monitor URLs configured. Add monitorUrls to crawl config or job config.');
1785
+ }
1786
+
1787
+ await updateJobProgress(tenantId, jobId, 10, `Monitoring ${monitorUrls.length} URL(s)...`);
1788
+
1789
+ // Baseline: stored baselines from previous monitor run take priority;
1790
+ // project screens' elementHash is the fallback for first-run.
1791
+ const storedBaselines: Record<string, string> = crawlCfg.monitorBaselines ?? {};
1792
+ const projectScreens: Array<{ url: string | null; elementHash: string | null }> =
1793
+ await withTenant(tenantId, (tx) =>
1794
+ tx.screen.findMany({ where: { projectId }, select: { url: true, elementHash: true } })
1795
+ ).catch(() => []);
1796
+ const screenHashMap: Record<string, string> = {};
1797
+ for (const s of projectScreens) {
1798
+ if (s.url && s.elementHash) screenHashMap[s.url] = s.elementHash;
1799
+ }
1800
+
1801
+ const results: Array<{
1802
+ url: string; changed: boolean; reason: string;
1803
+ currentHash: string; previousHash: string | null;
1804
+ }> = [];
1805
+ const newBaselines: Record<string, string> = { ...storedBaselines };
1806
+
1807
+ for (let i = 0; i < monitorUrls.length; i++) {
1808
+ if (controller.signal.aborted) break;
1809
+ const url = monitorUrls[i];
1810
+ const pct = 10 + Math.floor((i / monitorUrls.length) * 80);
1811
+ await updateJobProgress(tenantId, jobId, pct, `Checking ${url}...`);
1812
+ opts?.onProgress?.(pct);
1813
+
1814
+ try {
1815
+ const crawlResult = await httpCrawl({ appUrl: url, maxScreens: 1, respectRobotsTxt: false, timeoutMs: 20_000 });
1816
+ const screen = crawlResult.screens[0];
1817
+ if (!screen) {
1818
+ results.push({ url, changed: false, reason: 'fetch_empty', currentHash: '', previousHash: null });
1819
+ continue;
1820
+ }
1821
+ const currentHash = hashContent(normalizeText(screen.markdown));
1822
+ const previousHash = storedBaselines[url] ?? screenHashMap[url] ?? null;
1823
+ newBaselines[url] = currentHash;
1824
+
1825
+ if (!previousHash) {
1826
+ results.push({ url, changed: false, reason: 'new_baseline', currentHash, previousHash: null });
1827
+ } else if (previousHash === currentHash) {
1828
+ results.push({ url, changed: false, reason: 'unchanged', currentHash, previousHash });
1829
+ } else {
1830
+ results.push({ url, changed: true, reason: 'content_changed', currentHash, previousHash });
1831
+ }
1832
+ } catch (fetchErr: any) {
1833
+ results.push({ url, changed: false, reason: `error:${fetchErr?.message ?? String(fetchErr)}`, currentHash: '', previousHash: null });
1834
+ }
1835
+ }
1836
+
1837
+ // Persist updated baselines so next run has fresh reference points.
1838
+ await withTenant(tenantId, (tx) =>
1839
+ (tx as any).project.update({
1840
+ where: { id: projectId },
1841
+ data: { crawlConfig: { ...crawlCfg, monitorBaselines: newBaselines } as any },
1842
+ })
1843
+ ).catch((e: any) => logger.warn({ err: e }, '[monitor] baseline persist failed'));
1844
+
1845
+ const changedUrls = results.filter(r => r.changed);
1846
+
1847
+ if (changedUrls.length > 0) {
1848
+ dispatchWebhook(tenantId, projectId, 'content.changed', {
1849
+ jobId,
1850
+ changedUrls: changedUrls.map(r => ({ url: r.url, previousHash: r.previousHash, currentHash: r.currentHash })),
1851
+ totalChecked: results.length,
1852
+ changedCount: changedUrls.length,
1853
+ }).catch(console.error);
1854
+ }
1855
+
1856
+ await updateJobProgress(tenantId, jobId, 100, 'Monitor check complete');
1857
+ await withTenant(tenantId, (tx) =>
1858
+ tx.platformJob.update({
1859
+ where: { id: jobId },
1860
+ data: {
1861
+ status: 'DONE',
1862
+ progress: 100,
1863
+ finishedAt: new Date(),
1864
+ result: { results, changedCount: changedUrls.length, totalChecked: results.length } as any,
1865
+ },
1866
+ })
1867
+ );
1868
+ } catch (err: any) {
1869
+ await withTenant(tenantId, (tx) =>
1870
+ tx.platformJob.update({
1871
+ where: { id: jobId },
1872
+ data: { status: 'FAILED', error: String(err?.message ?? err), finishedAt: new Date() },
1873
+ })
1874
+ );
1875
+ } finally {
1876
+ runningControllers.delete(jobId);
1877
+ }
1878
+ }
1879
+
1880
+ // ─── IMPORT_TESTS job processor ──────────────────────────────────────────────
1881
+ // Async counterpart to the synchronous POST /artifacts/:id/import-tests route.
1882
+ // Enqueued by POST /modernization/bulk-import for each artifact in a batch.
1883
+ // Config: { tenantId, projectId, artifactId, suiteId?, autoLabel?, sessionId? }
1884
+
1885
+ async function processImportTestsJob(jobId: string, config: any) {
1886
+ const { tenantId, projectId, artifactId, autoLabel, sourcePlatform } = config;
1887
+ const jobStart = new Date();
1888
+ let suiteId: string = config.suiteId ?? 'new';
1889
+
1890
+ await updateJobProgress(tenantId, jobId, 5, 'Loading artifact');
1891
+
1892
+ const artifact = await withTenant(tenantId, (tx) =>
1893
+ (tx as any).projectArtifact.findUnique({ where: { id: artifactId } })
1894
+ );
1895
+ if (!artifact || (artifact as any).tenantId !== tenantId) {
1896
+ throw new Error(`Artifact ${artifactId} not found`);
1897
+ }
1898
+
1899
+ const content: string = (artifact as any).content ?? '';
1900
+ const filename: string = (artifact as any).originalName ?? (artifact as any).name ?? '';
1901
+ const kind: string = (artifact as any).kind ?? '';
1902
+
1903
+ // Detect format using same logic as the synchronous route
1904
+ function detectFormat(fn: string, k: string, c: string): string {
1905
+ if (fn.endsWith('.feature')) return 'GHERKIN';
1906
+ if (fn.match(/\.(xlsx|xls|csv)$/i) || k === 'SPREADSHEET') return 'EXCEL';
1907
+ if (fn.endsWith('.txt') && c && c.split('\n').some((l) => l.trim().startsWith('|'))) return 'EXCEL';
1908
+ return 'AI_EXTRACT';
1909
+ }
1910
+ const format = detectFormat(filename, kind, content);
1911
+
1912
+ await updateJobProgress(tenantId, jobId, 15, `Parsing ${filename}`);
1913
+
1914
+ const { parseTestCases, labelTestCasesBatch } = await import('@detiq/agents');
1915
+ let res = await parseTestCases(content, format, tenantId, (artifact as any).columnMapping ?? undefined, undefined, undefined, sourcePlatform);
1916
+ if (res.cases.length === 0 && format !== 'AI_EXTRACT') {
1917
+ await updateJobProgress(tenantId, jobId, 25, 'Retrying with AI extraction');
1918
+ try {
1919
+ res = await parseTestCases(content, 'AI_EXTRACT', tenantId, undefined, undefined, undefined, sourcePlatform);
1920
+ } catch {
1921
+ // AI unavailable (no LLM configured) — proceed with 0 cases
1922
+ }
1923
+ }
1924
+
1925
+ const parsedCases = res.cases;
1926
+ if (parsedCases.length === 0) {
1927
+ await withTenant(tenantId, (tx) =>
1928
+ tx.platformJob.update({
1929
+ where: { id: jobId },
1930
+ data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { imported: 0, skipped: 0, labeled: 0 } as any },
1931
+ })
1932
+ );
1933
+ return;
1934
+ }
1935
+
1936
+ await updateJobProgress(tenantId, jobId, 35, `Parsed ${parsedCases.length} cases — creating suite`);
1937
+
1938
+ // Auto-create suite from filename when suiteId === 'new'
1939
+ if (!suiteId || suiteId === 'new') {
1940
+ const suiteName = filename.replace(/\.[^/.]+$/, '') || 'Imported Tests';
1941
+ const suite = await withTenant(tenantId, (tx) =>
1942
+ (tx as any).testSuite.create({
1943
+ data: { tenantId, projectId, name: suiteName },
1944
+ })
1945
+ );
1946
+ suiteId = (suite as any).id;
1947
+ }
1948
+
1949
+ await updateJobProgress(tenantId, jobId, 50, `Importing ${parsedCases.length} cases`);
1950
+
1951
+ const { created, skipped } = await AppBrain.importTestCasesFromArtifact(
1952
+ tenantId, projectId, suiteId, parsedCases, { duplicateMode: 'skip', artifactId }
1953
+ );
1954
+
1955
+ let labeled = 0;
1956
+ if (autoLabel && created.length > 0) {
1957
+ await updateJobProgress(tenantId, jobId, 75, `AI labeling ${created.length} cases`);
1958
+ try {
1959
+ const labelInput = created.map((c: any) => ({
1960
+ id: c.id, title: c.title,
1961
+ description: c.description ?? '',
1962
+ stepsText: (Array.isArray(c.steps) ? c.steps.join(' ') : String(c.steps ?? '')).slice(0, 200),
1963
+ }));
1964
+ const labelResults = await labelTestCasesBatch(labelInput, tenantId);
1965
+ // Persist labels back to each test case
1966
+ await Promise.all(
1967
+ labelResults.map((lr: any) =>
1968
+ withTenant(tenantId, (tx) =>
1969
+ tx.testCase.update({
1970
+ where: { id: lr.id },
1971
+ data: {
1972
+ priority: lr.priority ?? undefined,
1973
+ kind: lr.kind ?? undefined,
1974
+ tags: lr.tags ?? undefined,
1975
+ status: lr.needsReview ? 'PENDING_REVIEW' : undefined,
1976
+ },
1977
+ })
1978
+ ).catch(() => {}) // non-fatal per-case
1979
+ )
1980
+ );
1981
+ labeled = labelResults.length;
1982
+ } catch {
1983
+ // non-fatal — import succeeded even if labeling fails
1984
+ }
1985
+ }
1986
+
1987
+ // Auto-generate AI test data for imported cases that have recorded form fields (testDataInline)
1988
+ const casesNeedingData = created.filter((c: any) => {
1989
+ const inline = (c as any).testDataInline;
1990
+ return inline && typeof inline === 'object' && Object.keys(inline).length > 0;
1991
+ });
1992
+ if (casesNeedingData.length > 0) {
1993
+ const cap = Math.min(casesNeedingData.length, 20);
1994
+ await updateJobProgress(tenantId, jobId, 90, `Generating test data for ${cap} cases`);
1995
+ const { generateTestData, refreshTestDataSkillFile } = await import('@detiq/agents');
1996
+ for (let i = 0; i < cap; i++) {
1997
+ const c = casesNeedingData[i];
1998
+ await generateTestData({ tenantId, projectId, testCaseId: c.id, jobId }).catch((e: any) => {
1999
+ logger.warn({ err: e?.message, testCaseId: c.id }, '[import] test data generation failed');
2000
+ });
2001
+ }
2002
+ refreshTestDataSkillFile(tenantId, projectId).catch(console.error);
2003
+ }
2004
+
2005
+ if (created.length > 0) {
2006
+ refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
2007
+ }
2008
+
2009
+ await updateJobProgress(tenantId, jobId, 98, `Done — ${created.length} imported`);
2010
+
2011
+ // Write final result and mark job DONE
2012
+ await withTenant(tenantId, (tx) =>
2013
+ tx.platformJob.update({
2014
+ where: { id: jobId },
2015
+ data: {
2016
+ status: 'DONE',
2017
+ progress: 100,
2018
+ finishedAt: new Date(),
2019
+ result: {
2020
+ imported: created.length,
2021
+ skipped: skipped ?? 0,
2022
+ labeled,
2023
+ suiteId,
2024
+ artifactId,
2025
+ artifactName: filename,
2026
+ } as any,
2027
+ },
2028
+ })
2029
+ );
2030
+ aggregateJobTokens(tenantId, jobId, projectId, jobStart).catch(console.error);
2031
+ }
2032
+
2033
+ // Generate test cases for a single screen, enqueued by NEW_PAGES_PIPELINE.
2034
+ // Uses the same DualContextOrchestrator path as the in-process GENERATE_TESTS route.
2035
+ async function processGenerateScreenTestsJob(jobId: string, config: any) {
2036
+ const { tenantId, projectId, screenId, repoConnectionId, triggerAlignedScripts } = config;
2037
+ const jobStartedAt = new Date();
2038
+ try {
2039
+ await withTenant(tenantId, (tx: any) =>
2040
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
2041
+ );
2042
+
2043
+ const { DualContextOrchestrator } = await import('@detiq/agents');
2044
+ await updateJobProgress(tenantId, jobId, 10, 'Generating test cases for screen');
2045
+
2046
+ const crawlCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => null);
2047
+ const deviceProfiles: string[] = (crawlCfg as any)?.deviceProfiles ?? ['DESKTOP'];
2048
+
2049
+ for (const viewport of deviceProfiles) {
2050
+ await DualContextOrchestrator.execute({ tenantId, projectId, targetScreenId: screenId, jobId, viewport });
2051
+ }
2052
+
2053
+ await updateJobProgress(tenantId, jobId, 80, 'Test cases generated');
2054
+
2055
+ // Optionally kick framework-aligned script generation for this screen's test cases
2056
+ if (triggerAlignedScripts && repoConnectionId) {
2057
+ const conn: any = await withTenant(tenantId, (tx: any) =>
2058
+ tx.gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
2059
+ );
2060
+ if (conn?.styleProfile) {
2061
+ const { generateScriptAligned, mapWithConcurrency, SCRIPT_GEN_CONCURRENCY } = await import('@detiq/agents');
2062
+ const cases = await withTenant(tenantId, (tx: any) =>
2063
+ tx.testCase.findMany({ where: { tenantId, projectId, screenId, status: 'APPROVED' }, select: { id: true }, take: 50 })
2064
+ );
2065
+ await mapWithConcurrency(cases as any[], SCRIPT_GEN_CONCURRENCY, (tc: any) =>
2066
+ generateScriptAligned({
2067
+ tenantId,
2068
+ projectId,
2069
+ testCaseId: tc.id,
2070
+ styleProfile: conn.styleProfile,
2071
+ pageObjectInventory: conn.pageObjectInventory ?? undefined,
2072
+ }).catch(() => {})
2073
+ );
2074
+ }
2075
+ }
2076
+
2077
+ await withTenant(tenantId, (tx: any) =>
2078
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, finishedAt: new Date() } })
2079
+ );
2080
+ aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
2081
+ } catch (err: any) {
2082
+ const msg = err?.message ?? String(err);
2083
+ logger.error({ jobId, screenId, err: msg }, 'processGenerateScreenTestsJob failed');
2084
+ await withTenant(tenantId, (tx: any) =>
2085
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', error: msg.slice(0, 500), finishedAt: new Date() } })
2086
+ ).catch(() => {});
2087
+ }
2088
+ }
2089
+
2090
+ // Registers the type→processor dispatch table used by the durable worker (both the
2091
+ // enqueueJob() fast-path kick and startJobWorkerLoop()'s poll). Declared at module
2092
+ // bottom so it can reference every process*Job function by name; function
2093
+ // declarations are hoisted, so this could technically live anywhere in the file,
2094
+ // but keeping it here alongside the last definition keeps the mapping easy to audit
2095
+ // against the actual functions above.
2096
+ jobDispatchTable = {
2097
+ CRAWL: processJob,
2098
+ DISCOVER: processDiscoverJob,
2099
+ MONITOR: processMonitorJob,
2100
+ NATIVE_CRAWL: processNativeCrawlJob,
2101
+ API_TESTS: processApiTestsJob,
2102
+ SECURITY_TESTS: processSecurityTestsJob,
2103
+ INTEGRATION_TESTS: processIntegrationTestsJob,
2104
+ FIGMA_IMPORT: processFigmaImportJob,
2105
+ GENERATE_SKILL_FILES: processGenerateSkillFilesJob,
2106
+ GENERATE_TESTS_FROM_REQS: processGenerateTestsFromReqsJob,
2107
+ GENERATE_SCREEN_TESTS: processGenerateScreenTestsJob,
2108
+ RUN_TEST_SUITE: processRunTestSuiteJob,
2109
+ REPO_SCAN: processRepoScanJob,
2110
+ IMPORT_TESTS: processImportTestsJob,
2111
+ BATCH_GENERATE_ALIGNED: processBatchGenerateAlignedJob,
2112
+ CREATE_PR: processCreatePRJob,
2113
+ NEW_PAGES_PIPELINE: processNewPagesPipelineJob,
2114
+ };
2115
+
2116
+ async function processRepoScanJob(jobId: string, config: any) {
2117
+ const { repoConnectionId, tenantId, projectId } = config;
2118
+ const jobStart = new Date();
2119
+ try {
2120
+ await updateJobProgress(tenantId, jobId, 5, 'Starting repo scan');
2121
+
2122
+ const {
2123
+ fetchRepoTree, fetchFileContent, detectFramework,
2124
+ extractTestIds, extractStyleProfile,
2125
+ buildPageObjectInventory,
2126
+ } = await import('@detiq/agents');
2127
+
2128
+ const conn = await withTenant(tenantId, (tx) =>
2129
+ tx.gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
2130
+ );
2131
+ if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
2132
+
2133
+ // Decrypt token
2134
+ const { decrypt } = await import('@detiq/core');
2135
+ const token = decrypt(conn.tokenEnc);
2136
+
2137
+ // Mark scanning
2138
+ await withTenant(tenantId, (tx) =>
2139
+ tx.gitHubRepoConnection.update({ where: { id: repoConnectionId }, data: { scanStatus: 'SCANNING', scanError: null } })
2140
+ );
2141
+
2142
+ await updateJobProgress(tenantId, jobId, 15, 'Fetching repo tree');
2143
+ // Use HEAD so it always resolves to the actual default branch regardless of stored value
2144
+ const treeResult = await fetchRepoTree(token, conn.repoFullName, 'HEAD');
2145
+
2146
+ const frameworks = detectFramework(treeResult.paths);
2147
+ const primary = frameworks[0];
2148
+ await updateJobProgress(tenantId, jobId, 30, `Detected framework: ${primary?.framework ?? 'unknown'}`);
2149
+
2150
+ // Prefer framework-detected glob when stored glob is the TS default (never explicitly set)
2151
+ const storedGlob = conn.testGlob || '';
2152
+ const testGlob = (storedGlob && storedGlob !== '**/*.spec.ts')
2153
+ ? storedGlob
2154
+ : (primary?.testGlob || storedGlob || '**/*.spec.ts');
2155
+ const framework = primary?.framework ?? 'unknown';
2156
+ const language = primary?.language ?? 'typescript';
2157
+
2158
+ // Filter test files
2159
+ const { minimatch } = await import('minimatch').catch(() => ({ minimatch: null }));
2160
+ const isPythonTestFile = (p: string) =>
2161
+ p.endsWith('.py') && !p.endsWith('__init__.py') && !p.endsWith('conftest.py') &&
2162
+ (p.endsWith('_test.py') || /\/test_[^/]+\.py$/.test(p) || /^test_[^/]+\.py$/.test(p) ||
2163
+ p.includes('/tests/') || p.includes('/test/'));
2164
+ // Java: testGlob matches all *.java — further filter to actual test classes only
2165
+ // (excludes helpers, base classes, utilities that don't follow *Test.java/*Tests.java naming)
2166
+ const isJavaTestFile = (p: string) =>
2167
+ p.endsWith('.java') && (
2168
+ /[A-Z]\w*Tests?\.java$/.test(p) ||
2169
+ (/\/tests?\//.test(p) && /[A-Z][a-z]/.test(p.split('/').pop() ?? ''))
2170
+ );
2171
+ const testPaths = treeResult.paths.filter((p) => {
2172
+ if (language === 'java') return isJavaTestFile(p);
2173
+ if (language === 'python') return isPythonTestFile(p);
2174
+ if (minimatch) return minimatch(p, testGlob, { matchBase: true });
2175
+ return p.endsWith('.spec.ts') || p.endsWith('.spec.js') || p.endsWith('.test.ts') || p.endsWith('.test.js') || p.endsWith('_test.py') || p.includes('/test_');
2176
+ }).slice(0, 500); // cap at 500 files
2177
+
2178
+ await updateJobProgress(tenantId, jobId, 40, `Found ${testPaths.length} test files`);
2179
+
2180
+ // Extract test IDs from each file
2181
+ const allExtracted: any[] = [];
2182
+ const styleSampleFiles: Array<{ path: string; content: string }> = [];
2183
+ let processed = 0;
2184
+
2185
+ // Delete old test files for this connection
2186
+ await withTenant(tenantId, (tx) => tx.repoTestFile.deleteMany({ where: { repoConnectionId } }));
2187
+
2188
+ for (const filePath of testPaths) {
2189
+ const content = await fetchFileContent(token, conn.repoFullName, filePath);
2190
+ if (!content) continue;
2191
+
2192
+ const extracted = extractTestIds(content, filePath, framework);
2193
+ allExtracted.push(...extracted);
2194
+
2195
+ await withTenant(tenantId, (tx) =>
2196
+ tx.repoTestFile.create({
2197
+ data: {
2198
+ tenantId,
2199
+ projectId,
2200
+ repoConnectionId,
2201
+ filePath,
2202
+ framework,
2203
+ extractedIds: extracted.map((e) => ({ name: e.name, normalizedName: e.normalizedName, lineNumber: e.lineNumber })) as any,
2204
+ rawSample: content.slice(0, 2000),
2205
+ lastScannedAt: new Date(),
2206
+ },
2207
+ })
2208
+ );
2209
+
2210
+ if (styleSampleFiles.length < 5) styleSampleFiles.push({ path: filePath, content: content.slice(0, 3000) });
2211
+ processed++;
2212
+
2213
+ if (processed % 10 === 0) {
2214
+ await updateJobProgress(tenantId, jobId, 40 + Math.floor((processed / testPaths.length) * 40), `Processed ${processed}/${testPaths.length} files`);
2215
+ }
2216
+ }
2217
+
2218
+ // Extract style profile for aligned generation
2219
+ // For Java, include main source paths so LLM can detect page object location in src/main/java/
2220
+ // Fall back to existing styleProfile from DB if extraction fails or returns null.
2221
+ let styleProfile: any = conn.styleProfile ?? null;
2222
+ if (styleSampleFiles.length > 0) {
2223
+ try {
2224
+ const mainSourcePaths = language === 'java'
2225
+ ? treeResult.paths.filter((p: string) => /^src\/main\/java\//.test(p)).slice(0, 50)
2226
+ : [];
2227
+ // For TS/JS, also include non-test source files so LLM can detect pageObjectLocation
2228
+ // (e.g. src/advantage/pages/ in playwright-sample-project)
2229
+ const testPathSet = new Set(testPaths);
2230
+ const sourceFilePaths = (language === 'typescript' || language === 'javascript')
2231
+ ? treeResult.paths
2232
+ .filter((p: string) =>
2233
+ (p.endsWith('.ts') || p.endsWith('.js')) &&
2234
+ !testPathSet.has(p) &&
2235
+ !p.endsWith('.d.ts') &&
2236
+ !p.includes('node_modules/') &&
2237
+ !p.includes('dist/') &&
2238
+ !p.includes('.config.'))
2239
+ .slice(0, 60)
2240
+ : [];
2241
+ const allPathsForProfile = [...testPaths, ...mainSourcePaths, ...sourceFilePaths].slice(0, 200);
2242
+ const freshProfile = await extractStyleProfile(styleSampleFiles, framework, language, tenantId, projectId, jobId, allPathsForProfile);
2243
+ if (freshProfile) styleProfile = freshProfile;
2244
+ } catch { /* non-fatal */ }
2245
+ }
2246
+
2247
+ // Extract page object inventory — finds POM/page classes in non-test files
2248
+ // Fall back to existing inventory from DB if fetch fails.
2249
+ let pageObjectInventory: any[] = (conn.pageObjectInventory as any[]) ?? [];
2250
+ try {
2251
+ const freshInventory = await buildPageObjectInventory(token, conn.repoFullName, treeResult.paths, framework);
2252
+ if (freshInventory.length > 0) {
2253
+ pageObjectInventory = freshInventory;
2254
+ await updateJobProgress(tenantId, jobId, 82, `Found ${pageObjectInventory.length} page objects`);
2255
+ }
2256
+ } catch { /* non-fatal */ }
2257
+
2258
+ // Run coverage mapping
2259
+ await updateJobProgress(tenantId, jobId, 85, 'Running coverage mapping');
2260
+ const { buildCoverageMap } = await import('@detiq/agents');
2261
+ const testCases = await withTenant(tenantId, (tx) =>
2262
+ tx.testCase.findMany({ where: { projectId, tenantId, status: { not: 'RETIRED' } }, select: { id: true, title: true, ref: true } })
2263
+ );
2264
+
2265
+ const mappings = await buildCoverageMap(testCases, allExtracted, tenantId);
2266
+
2267
+ // Upsert CoverageMapping records (skip manualOverride=true)
2268
+ for (const m of mappings) {
2269
+ const existing = await withTenant(tenantId, (tx) =>
2270
+ tx.coverageMapping.findUnique({ where: { testCaseId: m.testCaseId } })
2271
+ );
2272
+ if (existing?.manualOverride) continue;
2273
+
2274
+ await withTenant(tenantId, (tx) =>
2275
+ tx.coverageMapping.upsert({
2276
+ where: { testCaseId: m.testCaseId },
2277
+ create: { tenantId, projectId, testCaseId: m.testCaseId, repoConnectionId, status: m.status, matchedFilePath: m.matchedFilePath ?? null, scriptTestName: m.scriptTestName ?? null, lineNumber: m.lineNumber ?? null, confidence: m.confidence, matchMethod: m.matchMethod },
2278
+ update: { status: m.status, matchedFilePath: m.matchedFilePath ?? null, scriptTestName: m.scriptTestName ?? null, lineNumber: m.lineNumber ?? null, confidence: m.confidence, matchMethod: m.matchMethod },
2279
+ })
2280
+ );
2281
+ }
2282
+
2283
+ const mapped = mappings.filter((m) => m.status === 'MAPPED').length;
2284
+ const unmapped = mappings.filter((m) => m.status === 'UNMAPPED').length;
2285
+ const ambiguous = mappings.filter((m) => m.status === 'AMBIGUOUS').length;
2286
+ const coveragePercent = testCases.length > 0 ? (mapped / testCases.length) * 100 : 0;
2287
+
2288
+ // Write coverage snapshot
2289
+ await withTenant(tenantId, (tx) =>
2290
+ tx.coverageSnapshot.create({
2291
+ data: { tenantId, projectId, totalCases: testCases.length, mappedCases: mapped, unmappedCases: unmapped, ambiguousCases: ambiguous, coveragePercent },
2292
+ })
2293
+ );
2294
+
2295
+ // For Java, if styleProfile still missing testStructurePattern, infer two-tier from tree paths.
2296
+ // This covers the case where both extractStyleProfile and buildPageObjectInventory failed.
2297
+ const resolvedStyleProfile: any = (() => {
2298
+ const sp = styleProfile ?? {};
2299
+ if (framework === 'selenium-java' && !sp.testStructurePattern) {
2300
+ const hasMavenMain = treeResult.paths.some((p: string) => /^src\/main\/java\//.test(p));
2301
+ if (hasMavenMain) return { ...sp, testStructurePattern: 'two-tier' };
2302
+ }
2303
+ return sp;
2304
+ })();
2305
+
2306
+ // Update repo connection with results
2307
+ await withTenant(tenantId, (tx) =>
2308
+ tx.gitHubRepoConnection.update({
2309
+ where: { id: repoConnectionId },
2310
+ data: {
2311
+ scanStatus: 'DONE',
2312
+ detectedFramework: framework,
2313
+ configFilePath: primary?.configPath ?? null,
2314
+ testGlob: testGlob,
2315
+ testFileCount: testPaths.length,
2316
+ extractedIdCount: allExtracted.length,
2317
+ styleProfile: resolvedStyleProfile as any,
2318
+ pageObjectInventory: pageObjectInventory.length > 0 ? pageObjectInventory as any : undefined,
2319
+ treeSnapshot: JSON.stringify(treeResult.paths).slice(0, 100000),
2320
+ lastScannedAt: new Date(),
2321
+ lastSyncAt: new Date(),
2322
+ },
2323
+ })
2324
+ );
2325
+ try {
2326
+ const { generateRepoSkillFiles } = await import('@detiq/agents');
2327
+ await generateRepoSkillFiles(tenantId, projectId, {
2328
+ repoFullName: conn.repoFullName,
2329
+ framework,
2330
+ language,
2331
+ testGlob,
2332
+ styleProfile: resolvedStyleProfile,
2333
+ pageObjectInventory,
2334
+ testPaths,
2335
+ extractedTestCount: allExtracted.length,
2336
+ });
2337
+ } catch (e: any) {
2338
+ logger.warn({ jobId, repoConnectionId, err: e?.message }, '[repo-scan] repo skill files generation failed (non-fatal)');
2339
+ }
2340
+
2341
+ await updateJobProgress(tenantId, jobId, 100, `Done: ${mapped} mapped, ${unmapped} unmapped`);
2342
+ await withTenant(tenantId, (tx) =>
2343
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { testFileCount: testPaths.length, extractedIdCount: allExtracted.length, mapped, unmapped, ambiguous, coveragePercent } as any } })
2344
+ );
2345
+ aggregateJobTokens(tenantId, jobId, projectId, jobStart).catch(console.error);
2346
+ } catch (err: any) {
2347
+ const msg = String(err?.message ?? err);
2348
+ logger.error({ jobId, repoConnectionId, err: msg }, '[repo-scan] failed');
2349
+ await withTenant(tenantId, (tx) =>
2350
+ tx.gitHubRepoConnection.update({ where: { id: repoConnectionId }, data: { scanStatus: 'FAILED', scanError: msg.slice(0, 500) } })
2351
+ ).catch(() => {});
2352
+ await withTenant(tenantId, (tx) =>
2353
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg.slice(0, 1000) } })
2354
+ ).catch(() => {});
2355
+ }
2356
+ }
2357
+
2358
+ // ── BATCH_GENERATE_ALIGNED — generate framework-aligned scripts for UNMAPPED cases ──
2359
+
2360
+ async function processBatchGenerateAlignedJob(jobId: string, config: any) {
2361
+ const { tenantId, projectId, repoConnectionId, scope = 'UNMAPPED', testCaseIds, force = false } = config;
2362
+ try {
2363
+ await updateJobProgress(tenantId, jobId, 5, 'Loading repo connection');
2364
+
2365
+ const conn = await withTenant(tenantId, (tx) =>
2366
+ (tx as any).gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
2367
+ ) as any;
2368
+ if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
2369
+
2370
+ const { decrypt } = await import('@detiq/core');
2371
+
2372
+ const {
2373
+ generateScriptAligned, deriveRepoTargetPath, validateGeneratedScript,
2374
+ mapWithConcurrency, SCRIPT_GEN_CONCURRENCY,
2375
+ } = await import('@detiq/agents');
2376
+
2377
+ const styleProfile = conn.styleProfile as any;
2378
+ const pageObjectInventory = (conn.pageObjectInventory as any[]) ?? [];
2379
+ const framework = conn.detectedFramework ?? 'playwright-ts';
2380
+ const language = styleProfile?.language ?? 'typescript';
2381
+
2382
+ // Resolve which test cases to process
2383
+ let caseIds: string[];
2384
+ if (testCaseIds && testCaseIds.length > 0) {
2385
+ caseIds = testCaseIds;
2386
+ } else if (scope === 'UNMAPPED') {
2387
+ const mappings = await withTenant(tenantId, (tx) =>
2388
+ (tx as any).coverageMapping.findMany({
2389
+ where: { tenantId, projectId, repoConnectionId, status: 'UNMAPPED' },
2390
+ select: { testCaseId: true },
2391
+ })
2392
+ ) as any[];
2393
+ caseIds = mappings.map((m: any) => m.testCaseId);
2394
+ } else {
2395
+ const cases = await withTenant(tenantId, (tx) =>
2396
+ tx.testCase.findMany({
2397
+ where: { tenantId, projectId, status: { not: 'RETIRED' } },
2398
+ select: { id: true },
2399
+ })
2400
+ );
2401
+ caseIds = cases.map((c) => c.id);
2402
+ }
2403
+
2404
+ await updateJobProgress(tenantId, jobId, 15, `Generating scripts for ${caseIds.length} test cases`);
2405
+
2406
+ let done = 0;
2407
+ const errors: string[] = [];
2408
+
2409
+ // One LLM call per case — bounded worker pool instead of a strictly serial loop,
2410
+ // which made large batches take an hour or more.
2411
+ await mapWithConcurrency(caseIds, SCRIPT_GEN_CONCURRENCY, async (tcId: string) => {
2412
+ try {
2413
+ // Skip if script already exists and not forcing
2414
+ if (!force) {
2415
+ const existing = await withTenant(tenantId, (tx) =>
2416
+ (tx as any).testScript.findFirst({ where: { testCaseId: tcId } })
2417
+ );
2418
+ if (existing) { done++; return; }
2419
+ }
2420
+
2421
+ // Get screen URL and ref for target path derivation
2422
+ const tc = await withTenant(tenantId, (tx) =>
2423
+ tx.testCase.findUnique({
2424
+ where: { id: tcId },
2425
+ select: { id: true, ref: true, title: true, screen: { select: { url: true } } },
2426
+ })
2427
+ );
2428
+
2429
+ const screenUrl = (tc as any)?.screen?.url ?? '';
2430
+ const repoTargetPath = styleProfile
2431
+ ? deriveRepoTargetPath(screenUrl, styleProfile, framework)
2432
+ : deriveFallbackTargetPath((tc as any)?.ref ?? (tc as any)?.title ?? tcId, framework);
2433
+
2434
+ const result = await generateScriptAligned({
2435
+ tenantId, projectId, testCaseId: tcId,
2436
+ styleProfile,
2437
+ pageObjectInventory,
2438
+ repoTargetPath,
2439
+ save: true,
2440
+ });
2441
+
2442
+ // Validate the generated script
2443
+ if (result.code) {
2444
+ const validation = await validateGeneratedScript(result.code, framework, language);
2445
+ await withTenant(tenantId, (tx) =>
2446
+ (tx as any).testScript.updateMany({
2447
+ where: { testCaseId: tcId },
2448
+ data: {
2449
+ validationStatus: validation.ok ? 'PASS' : 'FAIL',
2450
+ validationErrors: validation.ok ? null : validation.errors.slice(0, 2000),
2451
+ },
2452
+ })
2453
+ );
2454
+ }
2455
+
2456
+ done++;
2457
+ } catch (e: any) {
2458
+ errors.push(`${tcId}: ${String(e.message).slice(0, 100)}`);
2459
+ }
2460
+
2461
+ if (done % 5 === 0) {
2462
+ await updateJobProgress(tenantId, jobId, 15 + Math.floor((done / caseIds.length) * 80), `Generated ${done}/${caseIds.length}`);
2463
+ }
2464
+ });
2465
+
2466
+ refreshTestScriptSkillFile(tenantId, projectId).catch(console.error);
2467
+
2468
+ await withTenant(tenantId, (tx) =>
2469
+ tx.platformJob.update({
2470
+ where: { id: jobId },
2471
+ data: { status: 'DONE', finishedAt: new Date(), result: { done, errors: errors.slice(0, 20), total: caseIds.length } as any },
2472
+ })
2473
+ );
2474
+ } catch (err: any) {
2475
+ const msg = String(err?.message ?? err);
2476
+ logger.error({ jobId, err: msg }, '[batch-generate-aligned] failed');
2477
+ await withTenant(tenantId, (tx) =>
2478
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg.slice(0, 1000) } })
2479
+ ).catch(() => {});
2480
+ }
2481
+ }
2482
+
2483
+ // ── CREATE_PR — push generated scripts to GitHub as a PR ─────────────────────
2484
+
2485
+ async function processCreatePRJob(jobId: string, config: any) {
2486
+ const { tenantId, projectId, repoConnectionId, testScriptIds, crawlJobId } = config;
2487
+ try {
2488
+ await updateJobProgress(tenantId, jobId, 5, 'Loading connection');
2489
+
2490
+ const conn = await withTenant(tenantId, (tx) =>
2491
+ (tx as any).gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
2492
+ ) as any;
2493
+ if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
2494
+
2495
+ const { decrypt } = await import('@detiq/core');
2496
+ const token = decrypt(conn.tokenEnc);
2497
+
2498
+ const { pushScriptsAsPR } = await import('@detiq/agents');
2499
+
2500
+ const framework = conn.detectedFramework ?? 'playwright-ts';
2501
+
2502
+ // Collect scripts + their target paths
2503
+ let scripts: any[];
2504
+ if (testScriptIds && testScriptIds.length > 0) {
2505
+ scripts = await withTenant(tenantId, (tx) =>
2506
+ (tx as any).testScript.findMany({
2507
+ where: { id: { in: testScriptIds }, tenantId },
2508
+ include: { testCase: { select: { title: true, ref: true, repoTargetPath: true } } },
2509
+ })
2510
+ );
2511
+ } else {
2512
+ // All scripts that haven't been pushed yet
2513
+ scripts = await withTenant(tenantId, (tx) =>
2514
+ (tx as any).testScript.findMany({
2515
+ where: { tenantId, projectId, pushedToPR: false, validationStatus: { in: ['PASS', 'PENDING'] } },
2516
+ include: { testCase: { select: { title: true, ref: true, repoTargetPath: true } } },
2517
+ })
2518
+ );
2519
+ }
2520
+
2521
+ if (scripts.length === 0) throw new Error('No generated scripts found to push.');
2522
+
2523
+ const files = scripts.map((s: any) => {
2524
+ const path = s.testCase?.repoTargetPath
2525
+ ?? deriveFallbackTargetPath(s.testCase?.ref ?? s.testCase?.title ?? s.id, framework);
2526
+ return { path, content: s.code };
2527
+ });
2528
+
2529
+ if (files.length === 0) throw new Error('No scripts to push.');
2530
+
2531
+ await updateJobProgress(tenantId, jobId, 20, `Pushing ${files.length} scripts to GitHub`);
2532
+
2533
+ const now = new Date().toISOString().slice(0, 10);
2534
+ const branchName = `zeta/new-coverage-${now}-${jobId.slice(0, 8)}`;
2535
+
2536
+ const prBody = buildPRBody(scripts, projectId);
2537
+
2538
+ const prResult = await pushScriptsAsPR({
2539
+ token,
2540
+ repo: conn.repoFullName,
2541
+ baseBranch: conn.defaultBranch,
2542
+ branchName,
2543
+ files,
2544
+ prTitle: `ZeTa: Add test coverage for ${files.length} new scenario${files.length === 1 ? '' : 's'}`,
2545
+ prBody,
2546
+ draft: false,
2547
+ });
2548
+
2549
+ // Record the PR
2550
+ const pr = await withTenant(tenantId, (tx) =>
2551
+ (tx as any).gitHubPR.create({
2552
+ data: {
2553
+ tenantId, projectId,
2554
+ repoConnectionId,
2555
+ prNumber: prResult.prNumber,
2556
+ prUrl: prResult.prUrl,
2557
+ branch: prResult.branch,
2558
+ headSha: prResult.headSha,
2559
+ status: 'OPEN',
2560
+ crawlJobId: crawlJobId ?? null,
2561
+ scriptCount: files.length,
2562
+ prBody: prBody.slice(0, 10000),
2563
+ },
2564
+ })
2565
+ ) as any;
2566
+
2567
+ // Mark scripts as pushed
2568
+ const scriptIds = scripts.map((s: any) => s.id);
2569
+ await withTenant(tenantId, (tx) =>
2570
+ (tx as any).testScript.updateMany({
2571
+ where: { id: { in: scriptIds } },
2572
+ data: { pushedToPR: true, pushedPRId: pr.id },
2573
+ })
2574
+ );
2575
+
2576
+ await notifyAdmins(tenantId, {
2577
+ type: 'GITHUB_PR_CREATED',
2578
+ title: 'ZeTa created a GitHub PR',
2579
+ body: `${files.length} new test script${files.length === 1 ? '' : 's'} pushed. PR #${prResult.prNumber}: ${prResult.prUrl}`,
2580
+ metadata: { prUrl: prResult.prUrl, prNumber: prResult.prNumber, scriptCount: files.length },
2581
+ });
2582
+
2583
+ await updateJobProgress(tenantId, jobId, 100, `PR #${prResult.prNumber} created`);
2584
+ await withTenant(tenantId, (tx) =>
2585
+ tx.platformJob.update({
2586
+ where: { id: jobId },
2587
+ data: { status: 'DONE', finishedAt: new Date(), result: { prUrl: prResult.prUrl, prNumber: prResult.prNumber, scriptCount: files.length } as any },
2588
+ })
2589
+ );
2590
+ } catch (err: any) {
2591
+ const msg = String(err?.message ?? err);
2592
+ logger.error({ jobId, err: msg }, '[create-pr] failed');
2593
+ await withTenant(tenantId, (tx) =>
2594
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg.slice(0, 1000) } })
2595
+ ).catch(() => {});
2596
+ }
2597
+ }
2598
+
2599
+ function buildPRBody(scripts: any[], projectId: string): string {
2600
+ const lines = [
2601
+ '## ZeTa — Automated Test Coverage',
2602
+ '',
2603
+ `Generated by ZeTa Quality Intelligence Platform for project \`${projectId}\`.`,
2604
+ '',
2605
+ '### Scripts Added',
2606
+ '',
2607
+ '| Test Case | Target Path |',
2608
+ '|---|---|',
2609
+ ];
2610
+ for (const s of scripts.slice(0, 30)) {
2611
+ const title = s.testCase?.title ?? s.id;
2612
+ const path = s.testCase?.repoTargetPath ?? '(unknown)';
2613
+ lines.push(`| ${title.replace(/\|/g, '\\|').slice(0, 60)} | \`${path}\` |`);
2614
+ }
2615
+ if (scripts.length > 30) lines.push(`| ... and ${scripts.length - 30} more | |`);
2616
+ lines.push('', '---', '_Review each test carefully before merging. ZeTa generates scripts aligned to your existing framework conventions._');
2617
+ return lines.join('\n');
2618
+ }
2619
+
2620
+ // ── NEW_PAGES_PIPELINE — post-crawl: detect new screens, generate tests + scripts ──
2621
+
2622
+ async function processNewPagesPipelineJob(jobId: string, config: any) {
2623
+ const { tenantId, projectId, crawlJobId, repoConnectionId, autoPR = false } = config;
2624
+ try {
2625
+ await updateJobProgress(tenantId, jobId, 5, 'Detecting new screens');
2626
+
2627
+ // Find repo connection (use provided or find first active)
2628
+ const conn = await withTenant(tenantId, (tx) =>
2629
+ (tx as any).gitHubRepoConnection.findFirst({
2630
+ where: repoConnectionId
2631
+ ? { id: repoConnectionId, tenantId }
2632
+ : { tenantId, projectId, status: 'ACTIVE' },
2633
+ })
2634
+ ) as any;
2635
+
2636
+ // Get all screens last seen after the lastSyncAt of the repo connection
2637
+ const sinceDate = conn?.lastSyncAt ?? new Date(0);
2638
+ const newScreens = await withTenant(tenantId, (tx) =>
2639
+ tx.screen.findMany({
2640
+ where: {
2641
+ tenantId,
2642
+ projectId,
2643
+ lastSeenAt: { gt: sinceDate },
2644
+ status: { not: 'DELETED' },
2645
+ },
2646
+ select: { id: true, url: true, name: true },
2647
+ take: 100,
2648
+ })
2649
+ );
2650
+
2651
+ if (newScreens.length === 0) {
2652
+ await updateJobProgress(tenantId, jobId, 100, 'No new screens to process');
2653
+ await withTenant(tenantId, (tx) =>
2654
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { newScreens: 0 } as any } })
2655
+ );
2656
+ return;
2657
+ }
2658
+
2659
+ await updateJobProgress(tenantId, jobId, 15, `Found ${newScreens.length} new screens`);
2660
+
2661
+ // For each new screen, enqueue GENERATE_TESTS if no test cases exist
2662
+ const generationJobs: string[] = [];
2663
+ for (const screen of newScreens) {
2664
+ const caseCount = await withTenant(tenantId, (tx) =>
2665
+ tx.testCase.count({ where: { tenantId, screenId: screen.id } })
2666
+ );
2667
+ if (caseCount === 0) {
2668
+ const jid = await enqueueJob('GENERATE_SCREEN_TESTS', {
2669
+ tenantId, projectId, screenId: screen.id,
2670
+ triggerAlignedScripts: conn != null,
2671
+ repoConnectionId: (conn as any)?.id ?? null,
2672
+ });
2673
+ generationJobs.push(jid);
2674
+ }
2675
+ }
2676
+
2677
+ await updateJobProgress(tenantId, jobId, 60, `Queued ${generationJobs.length} test generation jobs`);
2678
+
2679
+ // If repo connected and autoPR enabled, schedule BATCH_GENERATE_ALIGNED after generation
2680
+ if (conn && autoPR) {
2681
+ await enqueueJob('BATCH_GENERATE_ALIGNED', {
2682
+ tenantId, projectId,
2683
+ repoConnectionId: conn.id,
2684
+ scope: 'UNMAPPED',
2685
+ });
2686
+ }
2687
+
2688
+ await withTenant(tenantId, (tx) =>
2689
+ tx.platformJob.update({
2690
+ where: { id: jobId },
2691
+ data: { status: 'DONE', finishedAt: new Date(), result: { newScreens: newScreens.length, generationJobs: generationJobs.length } as any },
2692
+ })
2693
+ );
2694
+ } catch (err: any) {
2695
+ const msg = String(err?.message ?? err);
2696
+ logger.error({ jobId, err: msg }, '[new-pages-pipeline] failed');
2697
+ await withTenant(tenantId, (tx) =>
2698
+ tx.platformJob.update({ where: { id: jobId }, data: { status: 'FAILED', finishedAt: new Date(), error: msg.slice(0, 1000) } })
2699
+ ).catch(() => {});
2700
+ }
2701
+ }