@taodigital/crawler 0.0.0-stage → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/Dockerfile +82 -0
- package/README.md +10 -2
- package/dist/accessibility-auditor.d.ts +29 -0
- package/dist/accessibility-auditor.js +57 -0
- package/dist/accessibility-auditor.js.map +7 -0
- package/dist/accessibility-tree-crawler.d.ts +44 -0
- package/dist/accessibility-tree-crawler.js +156 -0
- package/dist/accessibility-tree-crawler.js.map +7 -0
- package/dist/advanced-ui-probes.d.ts +47 -0
- package/dist/advanced-ui-probes.js +310 -0
- package/dist/advanced-ui-probes.js.map +7 -0
- package/dist/ai-login.d.ts +32 -0
- package/dist/ai-login.js +250 -0
- package/dist/ai-login.js.map +7 -0
- package/dist/auth-token-rotator.d.ts +47 -0
- package/dist/auth-token-rotator.js +58 -0
- package/dist/auth-token-rotator.js.map +7 -0
- package/dist/auth.d.ts +20 -0
- package/dist/auth.js +348 -0
- package/dist/auth.js.map +7 -0
- package/dist/browser-extension.d.ts +37 -0
- package/dist/browser-extension.js +113 -0
- package/dist/browser-extension.js.map +7 -0
- package/dist/captcha-solver.d.ts +16 -0
- package/dist/captcha-solver.js +105 -0
- package/dist/captcha-solver.js.map +7 -0
- package/dist/color-contrast.d.ts +30 -0
- package/dist/color-contrast.js +78 -0
- package/dist/color-contrast.js.map +7 -0
- package/dist/content-chunker.d.ts +18 -0
- package/dist/content-chunker.js +152 -0
- package/dist/content-chunker.js.map +7 -0
- package/dist/content-dedup.d.ts +23 -0
- package/dist/content-dedup.js +60 -0
- package/dist/content-dedup.js.map +7 -0
- package/dist/cookie-consent.d.ts +25 -0
- package/dist/cookie-consent.js +78 -0
- package/dist/cookie-consent.js.map +7 -0
- package/dist/cookie-jar.d.ts +20 -0
- package/dist/cookie-jar.js +61 -0
- package/dist/cookie-jar.js.map +7 -0
- package/dist/crawl-session-manager.d.ts +44 -0
- package/dist/crawl-session-manager.js +145 -0
- package/dist/crawl-session-manager.js.map +7 -0
- package/dist/crawler.d.ts +233 -0
- package/dist/crawler.js +6239 -0
- package/dist/crawler.js.map +7 -0
- package/dist/crud-interaction.d.ts +31 -0
- package/dist/crud-interaction.js +264 -0
- package/dist/crud-interaction.js.map +7 -0
- package/dist/custom-js-injector.d.ts +42 -0
- package/dist/custom-js-injector.js +50 -0
- package/dist/custom-js-injector.js.map +7 -0
- package/dist/dark-mode-capture.d.ts +23 -0
- package/dist/dark-mode-capture.js +75 -0
- package/dist/dark-mode-capture.js.map +7 -0
- package/dist/dead-link-detector.d.ts +37 -0
- package/dist/dead-link-detector.js +50 -0
- package/dist/dead-link-detector.js.map +7 -0
- package/dist/dropdown-enumerator.d.ts +20 -0
- package/dist/dropdown-enumerator.js +230 -0
- package/dist/dropdown-enumerator.js.map +7 -0
- package/dist/element-hash.d.ts +9 -0
- package/dist/element-hash.js +9 -0
- package/dist/element-hash.js.map +7 -0
- package/dist/email-otp.d.ts +42 -0
- package/dist/email-otp.js +177 -0
- package/dist/email-otp.js.map +7 -0
- package/dist/engine-router.d.ts +47 -0
- package/dist/engine-router.js +94 -0
- package/dist/engine-router.js.map +7 -0
- package/dist/export/bulk-export.d.ts +26 -0
- package/dist/export/bulk-export.js +76 -0
- package/dist/export/bulk-export.js.map +7 -0
- package/dist/export/vector-export.d.ts +76 -0
- package/dist/export/vector-export.js +85 -0
- package/dist/export/vector-export.js.map +7 -0
- package/dist/extractors/advanced.d.ts +64 -0
- package/dist/extractors/advanced.js +265 -0
- package/dist/extractors/advanced.js.map +7 -0
- package/dist/extractors/artifact-envelope.d.ts +63 -0
- package/dist/extractors/artifact-envelope.js +63 -0
- package/dist/extractors/artifact-envelope.js.map +7 -0
- package/dist/extractors/branding-extractor.d.ts +46 -0
- package/dist/extractors/branding-extractor.js +104 -0
- package/dist/extractors/branding-extractor.js.map +7 -0
- package/dist/extractors/summary-extractor.d.ts +10 -0
- package/dist/extractors/summary-extractor.js +36 -0
- package/dist/extractors/summary-extractor.js.map +7 -0
- package/dist/failure-analysis-agent.d.ts +16 -0
- package/dist/failure-analysis-agent.js +42 -0
- package/dist/failure-analysis-agent.js.map +7 -0
- package/dist/feature-flag-detector.d.ts +30 -0
- package/dist/feature-flag-detector.js +55 -0
- package/dist/feature-flag-detector.js.map +7 -0
- package/dist/filter-pagination-crawler.d.ts +52 -0
- package/dist/filter-pagination-crawler.js +299 -0
- package/dist/filter-pagination-crawler.js.map +7 -0
- package/dist/form-detector.d.ts +34 -0
- package/dist/form-detector.js +58 -0
- package/dist/form-detector.js.map +7 -0
- package/dist/frontier.d.ts +40 -0
- package/dist/frontier.js +103 -0
- package/dist/frontier.js.map +7 -0
- package/dist/gap-pass.d.ts +36 -0
- package/dist/gap-pass.js +115 -0
- package/dist/gap-pass.js.map +7 -0
- package/dist/graphql-detector.d.ts +39 -0
- package/dist/graphql-detector.js +86 -0
- package/dist/graphql-detector.js.map +7 -0
- package/dist/http-engine.d.ts +80 -0
- package/dist/http-engine.js +318 -0
- package/dist/http-engine.js.map +7 -0
- package/dist/incremental-diff.d.ts +116 -0
- package/dist/incremental-diff.js +137 -0
- package/dist/incremental-diff.js.map +7 -0
- package/dist/index.d.ts +52 -0
- package/dist/index.js +83 -0
- package/dist/index.js.map +7 -0
- package/dist/input-fuzzer.d.ts +30 -0
- package/dist/input-fuzzer.js +105 -0
- package/dist/input-fuzzer.js.map +7 -0
- package/dist/interactive-probe.d.ts +144 -0
- package/dist/interactive-probe.js +865 -0
- package/dist/interactive-probe.js.map +7 -0
- package/dist/job-queue.d.ts +297 -0
- package/dist/job-queue.js +3812 -0
- package/dist/job-queue.js.map +7 -0
- package/dist/js-coverage.d.ts +29 -0
- package/dist/js-coverage.js +56 -0
- package/dist/js-coverage.js.map +7 -0
- package/dist/js-router-detector.d.ts +17 -0
- package/dist/js-router-detector.js +90 -0
- package/dist/js-router-detector.js.map +7 -0
- package/dist/language-detector.d.ts +22 -0
- package/dist/language-detector.js +57 -0
- package/dist/language-detector.js.map +7 -0
- package/dist/link-classifier.d.ts +23 -0
- package/dist/link-classifier.js +40 -0
- package/dist/link-classifier.js.map +7 -0
- package/dist/live-view.d.ts +36 -0
- package/dist/live-view.js +105 -0
- package/dist/live-view.js.map +7 -0
- package/dist/locator-extractor.d.ts +46 -0
- package/dist/locator-extractor.js +220 -0
- package/dist/locator-extractor.js.map +7 -0
- package/dist/logger.d.ts +2 -0
- package/dist/logger.js +10 -0
- package/dist/logger.js.map +7 -0
- package/dist/markdown-extract.d.ts +8 -0
- package/dist/markdown-extract.js +54 -0
- package/dist/markdown-extract.js.map +7 -0
- package/dist/multi-context-handler.d.ts +55 -0
- package/dist/multi-context-handler.js +182 -0
- package/dist/multi-context-handler.js.map +7 -0
- package/dist/native-crawler.d.ts +69 -0
- package/dist/native-crawler.js +839 -0
- package/dist/native-crawler.js.map +7 -0
- package/dist/nested-window-crawler.d.ts +41 -0
- package/dist/nested-window-crawler.js +172 -0
- package/dist/nested-window-crawler.js.map +7 -0
- package/dist/network-action-correlator.d.ts +47 -0
- package/dist/network-action-correlator.js +209 -0
- package/dist/network-action-correlator.js.map +7 -0
- package/dist/network-observer.d.ts +49 -0
- package/dist/network-observer.js +149 -0
- package/dist/network-observer.js.map +7 -0
- package/dist/network-throttle.d.ts +25 -0
- package/dist/network-throttle.js +34 -0
- package/dist/network-throttle.js.map +7 -0
- package/dist/openapi-generator.d.ts +49 -0
- package/dist/openapi-generator.js +89 -0
- package/dist/openapi-generator.js.map +7 -0
- package/dist/pdf-extractor.d.ts +28 -0
- package/dist/pdf-extractor.js +81 -0
- package/dist/pdf-extractor.js.map +7 -0
- package/dist/performance-metrics-collector.d.ts +50 -0
- package/dist/performance-metrics-collector.js +155 -0
- package/dist/performance-metrics-collector.js.map +7 -0
- package/dist/performance-metrics.d.ts +52 -0
- package/dist/performance-metrics.js +83 -0
- package/dist/performance-metrics.js.map +7 -0
- package/dist/phash.d.ts +50 -0
- package/dist/phash.js +136 -0
- package/dist/phash.js.map +7 -0
- package/dist/pii-scrubber.d.ts +21 -0
- package/dist/pii-scrubber.js +75 -0
- package/dist/pii-scrubber.js.map +7 -0
- package/dist/playwright-recorder.d.ts +39 -0
- package/dist/playwright-recorder.js +123 -0
- package/dist/playwright-recorder.js.map +7 -0
- package/dist/policies/crawl-safety.d.ts +9 -0
- package/dist/policies/crawl-safety.js +41 -0
- package/dist/policies/crawl-safety.js.map +7 -0
- package/dist/profiles/domain-profile.d.ts +19 -0
- package/dist/profiles/domain-profile.js +160 -0
- package/dist/profiles/domain-profile.js.map +7 -0
- package/dist/proxy.d.ts +50 -0
- package/dist/proxy.js +165 -0
- package/dist/proxy.js.map +7 -0
- package/dist/rate-limiter.d.ts +31 -0
- package/dist/rate-limiter.js +64 -0
- package/dist/rate-limiter.js.map +7 -0
- package/dist/redirect-tracker.d.ts +37 -0
- package/dist/redirect-tracker.js +65 -0
- package/dist/redirect-tracker.js.map +7 -0
- package/dist/redis-frontier.d.ts +48 -0
- package/dist/redis-frontier.js +126 -0
- package/dist/redis-frontier.js.map +7 -0
- package/dist/redis-queue.d.ts +48 -0
- package/dist/redis-queue.js +165 -0
- package/dist/redis-queue.js.map +7 -0
- package/dist/response-cache.d.ts +38 -0
- package/dist/response-cache.js +140 -0
- package/dist/response-cache.js.map +7 -0
- package/dist/responsive-detector.d.ts +29 -0
- package/dist/responsive-detector.js +46 -0
- package/dist/responsive-detector.js.map +7 -0
- package/dist/retry-policy.d.ts +20 -0
- package/dist/retry-policy.js +54 -0
- package/dist/retry-policy.js.map +7 -0
- package/dist/robots-txt.d.ts +9 -0
- package/dist/robots-txt.js +77 -0
- package/dist/robots-txt.js.map +7 -0
- package/dist/screen-reader.d.ts +15 -0
- package/dist/screen-reader.js +48 -0
- package/dist/screen-reader.js.map +7 -0
- package/dist/screenshot-masker.d.ts +28 -0
- package/dist/screenshot-masker.js +62 -0
- package/dist/screenshot-masker.js.map +7 -0
- package/dist/seo-checker.d.ts +33 -0
- package/dist/seo-checker.js +91 -0
- package/dist/seo-checker.js.map +7 -0
- package/dist/service-worker-interceptor.d.ts +36 -0
- package/dist/service-worker-interceptor.js +136 -0
- package/dist/service-worker-interceptor.js.map +7 -0
- package/dist/session-capture.d.ts +39 -0
- package/dist/session-capture.js +274 -0
- package/dist/session-capture.js.map +7 -0
- package/dist/session-export.d.ts +49 -0
- package/dist/session-export.js +117 -0
- package/dist/session-export.js.map +7 -0
- package/dist/shadow-dom-crawler.d.ts +35 -0
- package/dist/shadow-dom-crawler.js +132 -0
- package/dist/shadow-dom-crawler.js.map +7 -0
- package/dist/sitemap-writer.d.ts +21 -0
- package/dist/sitemap-writer.js +47 -0
- package/dist/sitemap-writer.js.map +7 -0
- package/dist/sitemap.d.ts +51 -0
- package/dist/sitemap.js +160 -0
- package/dist/sitemap.js.map +7 -0
- package/dist/skyvern.d.ts +56 -0
- package/dist/skyvern.js +129 -0
- package/dist/skyvern.js.map +7 -0
- package/dist/sqs-queue.d.ts +13 -0
- package/dist/sqs-queue.js +115 -0
- package/dist/sqs-queue.js.map +7 -0
- package/dist/sso-token.d.ts +29 -0
- package/dist/sso-token.js +76 -0
- package/dist/sso-token.js.map +7 -0
- package/dist/state-graph.d.ts +59 -0
- package/dist/state-graph.js +193 -0
- package/dist/state-graph.js.map +7 -0
- package/dist/stealth/human-behavior.d.ts +20 -0
- package/dist/stealth/human-behavior.js +202 -0
- package/dist/stealth/human-behavior.js.map +7 -0
- package/dist/telemetry.d.ts +34 -0
- package/dist/telemetry.js +77 -0
- package/dist/telemetry.js.map +7 -0
- package/dist/test-executor.d.ts +81 -0
- package/dist/test-executor.js +443 -0
- package/dist/test-executor.js.map +7 -0
- package/dist/tls-fingerprint.d.ts +50 -0
- package/dist/tls-fingerprint.js +81 -0
- package/dist/tls-fingerprint.js.map +7 -0
- package/dist/url-pattern-completer.d.ts +28 -0
- package/dist/url-pattern-completer.js +122 -0
- package/dist/url-pattern-completer.js.map +7 -0
- package/dist/visual-diff-verdict.d.ts +40 -0
- package/dist/visual-diff-verdict.js +27 -0
- package/dist/visual-diff-verdict.js.map +7 -0
- package/dist/webhook-notifier.d.ts +30 -0
- package/dist/webhook-notifier.js +76 -0
- package/dist/webhook-notifier.js.map +7 -0
- package/dist/websocket-detector.d.ts +24 -0
- package/dist/websocket-detector.js +60 -0
- package/dist/websocket-detector.js.map +7 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +33 -0
- package/dist/worker.js.map +7 -0
- package/package.json +49 -4
- package/src/accessibility-auditor.ts +102 -0
- package/src/accessibility-tree-crawler.ts +246 -0
- package/src/advanced-ui-probes.ts +470 -0
- package/src/ai-login.ts +298 -0
- package/src/auth-token-rotator.ts +89 -0
- package/src/auth.ts +418 -0
- package/src/browser-extension.ts +186 -0
- package/src/captcha-solver.ts +143 -0
- package/src/color-contrast.ts +116 -0
- package/src/content-chunker.ts +170 -0
- package/src/content-dedup.ts +99 -0
- package/src/cookie-consent.ts +106 -0
- package/src/cookie-jar.ts +91 -0
- package/src/crawl-session-manager.ts +231 -0
- package/src/crawler.ts +7123 -0
- package/src/crawler.ts.rej +12 -0
- package/src/crud-interaction.ts +386 -0
- package/src/custom-js-injector.ts +93 -0
- package/src/dark-mode-capture.ts +110 -0
- package/src/dead-link-detector.ts +76 -0
- package/src/dropdown-enumerator.ts +312 -0
- package/src/element-hash.ts +16 -0
- package/src/email-otp.ts +252 -0
- package/src/engine-router.ts +141 -0
- package/src/export/bulk-export.ts +85 -0
- package/src/export/vector-export.ts +160 -0
- package/src/extractors/advanced.ts +309 -0
- package/src/extractors/artifact-envelope.ts +111 -0
- package/src/extractors/branding-extractor.ts +159 -0
- package/src/extractors/summary-extractor.ts +49 -0
- package/src/failure-analysis-agent.ts +51 -0
- package/src/feature-flag-detector.ts +97 -0
- package/src/filter-pagination-crawler.ts +500 -0
- package/src/form-detector.ts +103 -0
- package/src/frontier.test.ts +64 -0
- package/src/frontier.ts +144 -0
- package/src/gap-pass.ts +165 -0
- package/src/graphql-detector.ts +129 -0
- package/src/http-engine.ts +453 -0
- package/src/incremental-diff.ts +259 -0
- package/src/index.ts +52 -0
- package/src/input-fuzzer.ts +129 -0
- package/src/interactive-probe.ts +1136 -0
- package/src/job-queue.test.ts +187 -0
- package/src/job-queue.ts +4504 -0
- package/src/js-coverage.ts +87 -0
- package/src/js-router-detector.ts +112 -0
- package/src/language-detector.ts +82 -0
- package/src/link-classifier.ts +65 -0
- package/src/live-view.ts +146 -0
- package/src/locator-extractor.ts +309 -0
- package/src/logger.ts +9 -0
- package/src/markdown-extract.test.ts +73 -0
- package/src/markdown-extract.ts +76 -0
- package/src/multi-context-handler.ts +296 -0
- package/src/native-crawler.ts +1108 -0
- package/src/nested-window-crawler.ts +310 -0
- package/src/network-action-correlator.ts +320 -0
- package/src/network-observer.ts +204 -0
- package/src/network-throttle.ts +69 -0
- package/src/openapi-generator.ts +135 -0
- package/src/pdf-extractor.ts +123 -0
- package/src/performance-metrics-collector.ts +243 -0
- package/src/performance-metrics.ts +134 -0
- package/src/phash.ts +184 -0
- package/src/pii-scrubber.ts +99 -0
- package/src/playwright-recorder.ts +170 -0
- package/src/policies/crawl-safety.ts +52 -0
- package/src/profiles/domain-profile.ts +190 -0
- package/src/proxy.ts +238 -0
- package/src/rate-limiter.ts +87 -0
- package/src/redirect-tracker.ts +97 -0
- package/src/redis-frontier.ts +143 -0
- package/src/redis-queue.ts +208 -0
- package/src/response-cache.ts +150 -0
- package/src/responsive-detector.ts +92 -0
- package/src/retry-policy.ts +87 -0
- package/src/robots-txt.ts +96 -0
- package/src/screen-reader.ts +98 -0
- package/src/screenshot-masker.ts +98 -0
- package/src/seo-checker.ts +134 -0
- package/src/service-worker-interceptor.ts +185 -0
- package/src/session-capture.ts +335 -0
- package/src/session-export.test.ts +75 -0
- package/src/session-export.ts +172 -0
- package/src/shadow-dom-crawler.ts +198 -0
- package/src/sitemap-writer.ts +65 -0
- package/src/sitemap.test.ts +127 -0
- package/src/sitemap.ts +233 -0
- package/src/skyvern.ts +199 -0
- package/src/sqs-queue.ts +129 -0
- package/src/sso-token.ts +120 -0
- package/src/state-graph.ts +280 -0
- package/src/stealth/human-behavior.ts +227 -0
- package/src/telemetry.ts +122 -0
- package/src/test-executor.test.ts +72 -0
- package/src/test-executor.ts +578 -0
- package/src/tls-fingerprint.ts +111 -0
- package/src/url-pattern-completer.ts +161 -0
- package/src/vendor.d.ts +20 -0
- package/src/visual-diff-verdict.test.ts +80 -0
- package/src/visual-diff-verdict.ts +59 -0
- package/src/webhook-notifier.ts +109 -0
- package/src/websocket-detector.ts +83 -0
- package/src/worker.ts +50 -0
- package/tsconfig.json +13 -0
- package/types/accessibility-auditor.d.ts +29 -0
- package/types/accessibility-tree-crawler.d.ts +44 -0
- package/types/advanced-ui-probes.d.ts +47 -0
- package/types/ai-login.d.ts +32 -0
- package/types/auth-token-rotator.d.ts +47 -0
- package/types/auth.d.ts +20 -0
- package/types/browser-extension.d.ts +37 -0
- package/types/bull-worker.d.ts +6 -0
- package/types/captcha-solver.d.ts +16 -0
- package/types/color-contrast.d.ts +30 -0
- package/types/content-chunker.d.ts +18 -0
- package/types/content-dedup.d.ts +23 -0
- package/types/cookie-consent.d.ts +25 -0
- package/types/cookie-jar.d.ts +20 -0
- package/types/crawl-session-manager.d.ts +44 -0
- package/types/crawler.d.ts +233 -0
- package/types/crud-interaction.d.ts +31 -0
- package/types/custom-js-injector.d.ts +42 -0
- package/types/dark-mode-capture.d.ts +23 -0
- package/types/dead-link-detector.d.ts +37 -0
- package/types/dropdown-enumerator.d.ts +20 -0
- package/types/element-hash.d.ts +9 -0
- package/types/email-otp.d.ts +42 -0
- package/types/engine-router.d.ts +47 -0
- package/types/export/bulk-export.d.ts +26 -0
- package/types/export/vector-export.d.ts +76 -0
- package/types/extractors/advanced.d.ts +64 -0
- package/types/extractors/artifact-envelope.d.ts +63 -0
- package/types/extractors/branding-extractor.d.ts +46 -0
- package/types/extractors/summary-extractor.d.ts +10 -0
- package/types/failure-analysis-agent.d.ts +16 -0
- package/types/feature-flag-detector.d.ts +30 -0
- package/types/filter-pagination-crawler.d.ts +52 -0
- package/types/form-detector.d.ts +34 -0
- package/types/frontier.d.ts +40 -0
- package/types/gap-pass.d.ts +36 -0
- package/types/graphql-detector.d.ts +39 -0
- package/types/http-engine.d.ts +80 -0
- package/types/incremental-diff.d.ts +116 -0
- package/types/index.d.ts +52 -0
- package/types/input-fuzzer.d.ts +30 -0
- package/types/interactive-probe.d.ts +144 -0
- package/types/job-queue.d.ts +308 -0
- package/types/js-coverage.d.ts +29 -0
- package/types/js-router-detector.d.ts +17 -0
- package/types/language-detector.d.ts +22 -0
- package/types/link-classifier.d.ts +23 -0
- package/types/live-view.d.ts +36 -0
- package/types/locator-extractor.d.ts +46 -0
- package/types/logger.d.ts +2 -0
- package/types/markdown-extract.d.ts +8 -0
- package/types/multi-context-handler.d.ts +55 -0
- package/types/native-crawler.d.ts +69 -0
- package/types/nested-window-crawler.d.ts +41 -0
- package/types/network-action-correlator.d.ts +47 -0
- package/types/network-observer.d.ts +49 -0
- package/types/network-throttle.d.ts +25 -0
- package/types/openapi-generator.d.ts +49 -0
- package/types/pdf-extractor.d.ts +28 -0
- package/types/performance-metrics-collector.d.ts +50 -0
- package/types/performance-metrics.d.ts +52 -0
- package/types/phash.d.ts +50 -0
- package/types/pii-scrubber.d.ts +21 -0
- package/types/playwright-recorder.d.ts +39 -0
- package/types/policies/crawl-safety.d.ts +9 -0
- package/types/profiles/domain-profile.d.ts +19 -0
- package/types/proxy.d.ts +50 -0
- package/types/rate-limiter.d.ts +31 -0
- package/types/redirect-tracker.d.ts +37 -0
- package/types/redis-frontier.d.ts +48 -0
- package/types/redis-queue.d.ts +48 -0
- package/types/response-cache.d.ts +38 -0
- package/types/responsive-detector.d.ts +29 -0
- package/types/retry-policy.d.ts +20 -0
- package/types/robots-txt.d.ts +9 -0
- package/types/screen-reader.d.ts +15 -0
- package/types/screenshot-masker.d.ts +28 -0
- package/types/seo-checker.d.ts +33 -0
- package/types/service-worker-interceptor.d.ts +36 -0
- package/types/session-capture.d.ts +39 -0
- package/types/session-export.d.ts +49 -0
- package/types/shadow-dom-crawler.d.ts +35 -0
- package/types/sitemap-writer.d.ts +21 -0
- package/types/sitemap.d.ts +51 -0
- package/types/skyvern.d.ts +56 -0
- package/types/sqs-queue.d.ts +13 -0
- package/types/sso-token.d.ts +29 -0
- package/types/state-graph.d.ts +59 -0
- package/types/stealth/human-behavior.d.ts +20 -0
- package/types/telemetry.d.ts +34 -0
- package/types/test-executor.d.ts +84 -0
- package/types/tls-fingerprint.d.ts +50 -0
- package/types/url-pattern-completer.d.ts +28 -0
- package/types/visual-diff-verdict.d.ts +40 -0
- package/types/webhook-notifier.d.ts +30 -0
- package/types/websocket-detector.d.ts +24 -0
- package/types/worker.d.ts +1 -0
package/src/job-queue.ts
ADDED
|
@@ -0,0 +1,4504 @@
|
|
|
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 '@taodigital/database';
|
|
19
|
+
import { crawlJobsTotal, crawlJobDurationSeconds } from '@taodigital/core';
|
|
20
|
+
import { logger } from './logger.js';
|
|
21
|
+
import { AppBrain, getProjectStorageConfig, buildArtifactKey, uploadArtifact, getTenantStorageConfig, uploadScreenshotToTenantStorage, uploadFileToTenantStorage, notifyRunCompletion, recordLLMCall, downloadBufferFromTenantStorage, dispatchToTenantAdmins } from '@taodigital/app-brain';
|
|
22
|
+
|
|
23
|
+
async function notifyAdmins(tenantId: string, data: {
|
|
24
|
+
type: string; title: string; body: string; metadata?: Record<string, unknown>
|
|
25
|
+
}) {
|
|
26
|
+
try {
|
|
27
|
+
await dispatchToTenantAdmins(tenantId, data as any);
|
|
28
|
+
} catch (e) {
|
|
29
|
+
console.error('[notify] failed:', e);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
import { generateTaxonomySkillFiles, groupScreensWithAI, generateExecutionPlan, refreshTestCasesSkillFile, refreshTestDataSkillFile, refreshTestScriptSkillFile, refreshRequirementsCoverageSkillFile, refreshTestExecutionHistorySkillFile, refreshVisualRegressionHistorySkillFile, refreshLocatorStrategyWithHealingData, refreshFieldCatalogSkillFile, detectFieldsFromHtml, mergeIntoCatalog, generateArtifactIntelligence } from '@taodigital/agents';
|
|
33
|
+
import type { ExecutionStep } from '@taodigital/agents';
|
|
34
|
+
import { crawlProject, domFallbackElements, getNonHeadlessUserAgent } from './crawler.js';
|
|
35
|
+
import { httpCrawl } from './http-engine.js';
|
|
36
|
+
import { hashContent, normalizeText } from './incremental-diff.js';
|
|
37
|
+
import { discoverProjectUrls } from './sitemap.js';
|
|
38
|
+
import { executeExecutionStep, executeTestPlan } from './test-executor.js';
|
|
39
|
+
import { runNativeCrawl } from './native-crawler.js';
|
|
40
|
+
import { elementsToPlaywrightLocators } from './locator-extractor.js';
|
|
41
|
+
import { jira, confluence, figma } from '@taodigital/connectors';
|
|
42
|
+
import { decrypt, config as platformConfig, dispatchWebhook, isFeatureEnabled, interpolatePlaceholders } from '@taodigital/core';
|
|
43
|
+
import { createHmac } from 'node:crypto';
|
|
44
|
+
import fs from 'node:fs/promises';
|
|
45
|
+
import path from 'node:path';
|
|
46
|
+
import os from 'node:os';
|
|
47
|
+
import { spawn } from 'node:child_process';
|
|
48
|
+
|
|
49
|
+
// ── GAP-14/15: Structured failure classification with per-type backoff ────────────────
|
|
50
|
+
|
|
51
|
+
export enum FailureType {
|
|
52
|
+
TRANSIENT = 'TRANSIENT', // network timeout, rate limit, 429, 503
|
|
53
|
+
INFRASTRUCTURE = 'INFRASTRUCTURE', // DB connection, OOM, worker crash
|
|
54
|
+
LOGICAL = 'LOGICAL', // bad input, business rule violation, 400/422
|
|
55
|
+
FATAL = 'FATAL', // unrecoverable — bad config, missing secrets
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface BackoffConfig {
|
|
59
|
+
maxRetries: number;
|
|
60
|
+
baseDelayMs: number;
|
|
61
|
+
multiplier: number;
|
|
62
|
+
maxDelayMs: number;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const BACKOFF_BY_TYPE: Record<FailureType, BackoffConfig> = {
|
|
66
|
+
[FailureType.TRANSIENT]: { maxRetries: 5, baseDelayMs: 30_000, multiplier: 2, maxDelayMs: 300_000 },
|
|
67
|
+
[FailureType.INFRASTRUCTURE]: { maxRetries: 3, baseDelayMs: 60_000, multiplier: 3, maxDelayMs: 600_000 },
|
|
68
|
+
[FailureType.LOGICAL]: { maxRetries: 1, baseDelayMs: 120_000, multiplier: 1, maxDelayMs: 120_000 },
|
|
69
|
+
[FailureType.FATAL]: { maxRetries: 0, baseDelayMs: 0, multiplier: 1, maxDelayMs: 0 },
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export function classifyFailure(error: string | Error | unknown): FailureType {
|
|
73
|
+
const msg = (error instanceof Error ? error.message : String(error)).toLowerCase();
|
|
74
|
+
|
|
75
|
+
// Fatal — bad configuration, missing secrets
|
|
76
|
+
if (msg.includes('master_enc_key') || msg.includes('missing secret') || msg.includes('invalid configuration')) {
|
|
77
|
+
return FailureType.FATAL;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Infrastructure — OOM, DB, worker crashes
|
|
81
|
+
if (
|
|
82
|
+
msg.includes('out of memory') || msg.includes('heap out') ||
|
|
83
|
+
msg.includes('connection refused') || msg.includes('econnrefused') ||
|
|
84
|
+
msg.includes('prisma') || msg.includes('database') ||
|
|
85
|
+
msg.includes('worker exited') || msg.includes('sigkill')
|
|
86
|
+
) {
|
|
87
|
+
return FailureType.INFRASTRUCTURE;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
// Logical — validation, auth, bad input
|
|
91
|
+
if (
|
|
92
|
+
msg.includes('validation') || msg.includes('invalid input') ||
|
|
93
|
+
msg.includes('not found') || msg.includes('unauthorized') ||
|
|
94
|
+
msg.includes('bad request') || msg.includes('400') || msg.includes('422') ||
|
|
95
|
+
msg.includes('403')
|
|
96
|
+
) {
|
|
97
|
+
return FailureType.LOGICAL;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Default: TRANSIENT (network, timeout, rate limit, 429, 503)
|
|
101
|
+
return FailureType.TRANSIENT;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function computeNextRetryAt(failureType: FailureType, retryCount: number): Date | null {
|
|
105
|
+
const config = BACKOFF_BY_TYPE[failureType];
|
|
106
|
+
if (retryCount >= config.maxRetries) return null; // exceeded max — go to DLQ
|
|
107
|
+
const delayMs = Math.min(config.baseDelayMs * Math.pow(config.multiplier, retryCount), config.maxDelayMs);
|
|
108
|
+
return new Date(Date.now() + delayMs);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Centralized failure recorder for all PlatformJobs.
|
|
113
|
+
* - Classifies error into FailureType (TRANSIENT, INFRASTRUCTURE, LOGICAL, FATAL)
|
|
114
|
+
* - Computes exponential backoff per failure classification
|
|
115
|
+
* - If FATAL or retries exhausted: marks status='FAILED', dlq=true, dlqAt=NOW(), dlqReason=error
|
|
116
|
+
* - If retryable: marks status='RETRY_WAIT', nextRetryAt=NOW() + backoff, retryCount=retryCount+1
|
|
117
|
+
* - Persists checkpoint and checkpointAt if checkpointData provided
|
|
118
|
+
* - Updates failureType on the row and in result.failureType
|
|
119
|
+
*/
|
|
120
|
+
export async function recordJobFailure(
|
|
121
|
+
tenantId: string | null | undefined,
|
|
122
|
+
jobId: string,
|
|
123
|
+
err: unknown,
|
|
124
|
+
checkpointData?: any,
|
|
125
|
+
options?: { isAborted?: boolean }
|
|
126
|
+
): Promise<void> {
|
|
127
|
+
const errorMessage = err instanceof Error ? err.message : String(err);
|
|
128
|
+
const aborted = options?.isAborted ?? (errorMessage.includes('CRAWL_ABORTED') || errorMessage.includes('Stopped by user'));
|
|
129
|
+
|
|
130
|
+
if (aborted) {
|
|
131
|
+
await prismaAdmin.platformJob.update({
|
|
132
|
+
where: { id: jobId },
|
|
133
|
+
data: {
|
|
134
|
+
status: 'CANCELLED',
|
|
135
|
+
error: 'Stopped by user',
|
|
136
|
+
finishedAt: new Date(),
|
|
137
|
+
heartbeatAt: null,
|
|
138
|
+
workerId: null,
|
|
139
|
+
...(checkpointData ? { checkpoint: checkpointData, checkpointAt: new Date() } : {}),
|
|
140
|
+
},
|
|
141
|
+
}).catch(() => {});
|
|
142
|
+
return;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const failureType = classifyFailure(err);
|
|
146
|
+
const jobRow = await prismaAdmin.platformJob.findUnique({
|
|
147
|
+
where: { id: jobId },
|
|
148
|
+
select: { retryCount: true, result: true }
|
|
149
|
+
}).catch(() => null);
|
|
150
|
+
|
|
151
|
+
const currentRetry = jobRow?.retryCount ?? 0;
|
|
152
|
+
const nextRetryAt = computeNextRetryAt(failureType, currentRetry);
|
|
153
|
+
const isFatal = !nextRetryAt || failureType === FailureType.FATAL;
|
|
154
|
+
|
|
155
|
+
await prismaAdmin.platformJob.update({
|
|
156
|
+
where: { id: jobId },
|
|
157
|
+
data: {
|
|
158
|
+
status: isFatal ? 'FAILED' : 'RETRY_WAIT',
|
|
159
|
+
error: errorMessage.slice(0, 2000),
|
|
160
|
+
finishedAt: new Date(),
|
|
161
|
+
heartbeatAt: null,
|
|
162
|
+
workerId: null,
|
|
163
|
+
nextRetryAt,
|
|
164
|
+
retryCount: { increment: 1 },
|
|
165
|
+
failureType,
|
|
166
|
+
dlq: isFatal,
|
|
167
|
+
dlqAt: isFatal ? new Date() : null,
|
|
168
|
+
dlqReason: isFatal ? errorMessage.slice(0, 1000) : null,
|
|
169
|
+
...(checkpointData ? { checkpoint: checkpointData, checkpointAt: new Date() } : {}),
|
|
170
|
+
result: {
|
|
171
|
+
...(jobRow?.result as any ?? {}),
|
|
172
|
+
failureType,
|
|
173
|
+
...(checkpointData ? { checkpoint: checkpointData } : {})
|
|
174
|
+
} as any,
|
|
175
|
+
},
|
|
176
|
+
}).catch((e) => logger.error({ err: e, jobId }, '[job-queue] failed to record job failure'));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ────────────────────────────────────────────────────────────────────────────────
|
|
180
|
+
|
|
181
|
+
// RFC 6238 TOTP — no external dependency, uses Node built-in crypto.
|
|
182
|
+
export function generateTOTP(secret: string): string {
|
|
183
|
+
const BASE32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
184
|
+
const clean = secret.toUpperCase().replace(/\s/g, '').replace(/=/g, '');
|
|
185
|
+
let bits = 0, value = 0;
|
|
186
|
+
const bytes: number[] = [];
|
|
187
|
+
for (const ch of clean) {
|
|
188
|
+
const idx = BASE32.indexOf(ch);
|
|
189
|
+
if (idx === -1) continue;
|
|
190
|
+
value = (value << 5) | idx;
|
|
191
|
+
bits += 5;
|
|
192
|
+
if (bits >= 8) { bits -= 8; bytes.push((value >> bits) & 0xff); }
|
|
193
|
+
}
|
|
194
|
+
const counter = Math.floor(Date.now() / 30000);
|
|
195
|
+
const buf = Buffer.alloc(8);
|
|
196
|
+
buf.writeBigInt64BE(BigInt(counter));
|
|
197
|
+
const hmac = createHmac('sha1', Buffer.from(bytes)).update(buf).digest();
|
|
198
|
+
const offset = hmac[hmac.length - 1] & 0xf;
|
|
199
|
+
const code = ((hmac[offset] & 0x7f) << 24) | ((hmac[offset + 1] & 0xff) << 16) |
|
|
200
|
+
((hmac[offset + 2] & 0xff) << 8) | (hmac[offset + 3] & 0xff);
|
|
201
|
+
return String(code % 1_000_000).padStart(6, '0');
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function deriveFallbackTargetPath(ref: string, framework: string): string {
|
|
205
|
+
const slug = (ref ?? 'test').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '') || 'test';
|
|
206
|
+
const base = framework.startsWith('cypress') ? 'cypress/e2e/'
|
|
207
|
+
: (framework === 'playwright-py' || framework === 'pytest' || framework === 'selenium-py') ? 'tests/'
|
|
208
|
+
: (framework === 'playwright-java' || framework === 'selenium-java' || framework === 'junit') ? 'src/test/java/'
|
|
209
|
+
: 'tests/';
|
|
210
|
+
const ext = (framework === 'playwright-py' || framework === 'pytest' || framework === 'selenium-py') ? '_test.py'
|
|
211
|
+
: (framework === 'playwright-java' || framework === 'selenium-java' || framework === 'junit') ? 'Test.java'
|
|
212
|
+
: framework.includes('ts') ? '.spec.ts'
|
|
213
|
+
: '.spec.js';
|
|
214
|
+
return `${base}${slug}${ext}`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
function makeJobName(type: string): string {
|
|
218
|
+
const now = new Date();
|
|
219
|
+
const date = now.toISOString().slice(0, 10); // YYYY-MM-DD
|
|
220
|
+
const ts = now.getTime();
|
|
221
|
+
const label = type === 'CRAWL' ? 'Crawl'
|
|
222
|
+
: type === 'CAPTURE_STEPS' ? 'CaptureSteps'
|
|
223
|
+
: type === 'NATIVE_CRAWL' ? 'NativeCrawl'
|
|
224
|
+
: type === 'GENERATE_TESTS' ? 'GenerateTests'
|
|
225
|
+
: type === 'VISUAL_REGRESSION' ? 'VisualRegression'
|
|
226
|
+
: type === 'AI_EDIT' ? 'AIEdit'
|
|
227
|
+
: type === 'API_TESTS' ? 'ApiTests'
|
|
228
|
+
: type === 'SECURITY_TESTS' ? 'SecurityTests'
|
|
229
|
+
: type === 'INTEGRATION_TESTS' ? 'IntegrationTests'
|
|
230
|
+
: type === 'GENERATE_TESTS_FROM_REQS' ? 'GenerateTestsFromReqs'
|
|
231
|
+
: type === 'GENERATE_DATA' ? 'GenerateData'
|
|
232
|
+
: type === 'GENERATE_SCRIPT' ? 'GenerateScript'
|
|
233
|
+
: type === 'GENERATE_TEST_PLAN' ? 'GenerateTestPlan'
|
|
234
|
+
: type === 'IMPORT_TESTS' ? 'ImportTests'
|
|
235
|
+
: type === 'GENERATE_SCREEN_TESTS' ? 'GenerateScreenTests'
|
|
236
|
+
: type === 'BATCH_GENERATE_ALIGNED' ? 'BatchGenerateAligned'
|
|
237
|
+
: type === 'CREATE_PR' ? 'CreatePR'
|
|
238
|
+
: type === 'NEW_PAGES_PIPELINE' ? 'NewPagesPipeline'
|
|
239
|
+
: type.charAt(0) + type.slice(1).toLowerCase().replace(/_([a-z])/g, (_, c) => c.toUpperCase());
|
|
240
|
+
return `${label}_${date}_${ts}`;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export interface PlatformJobConfig {
|
|
244
|
+
tenantId: string;
|
|
245
|
+
projectId: string;
|
|
246
|
+
appUrl?: string; // Optional since generate jobs don't strictly need it
|
|
247
|
+
credentials?: { username: string; password: string; oneTimeCode?: string };
|
|
248
|
+
/** Decrypted Playwright storageState JSON — if present, session is restored without AI login. */
|
|
249
|
+
storageState?: string;
|
|
250
|
+
screenshotDir?: string;
|
|
251
|
+
maxScreens?: number;
|
|
252
|
+
/** Seed URLs added to the initial crawl queue — link discovery still runs from each page. */
|
|
253
|
+
startUrls?: string[];
|
|
254
|
+
/** When provided, crawl ONLY these exact URLs (no link-following). Used for selected-screen recrawl. */
|
|
255
|
+
selectiveUrls?: string[];
|
|
256
|
+
/** Device profiles for multi-viewport screenshot pass after main DESKTOP crawl. */
|
|
257
|
+
deviceProfiles?: string[];
|
|
258
|
+
/** HTTP Basic Auth credentials — injected as Authorization header on same-origin requests. */
|
|
259
|
+
httpBasicUsername?: string;
|
|
260
|
+
httpBasicPassword?: string;
|
|
261
|
+
/** Bearer/API token — injected as a request header and into localStorage. Skips AI login. */
|
|
262
|
+
authToken?: string;
|
|
263
|
+
/** Header name for authToken (default: 'Authorization'). */
|
|
264
|
+
authTokenHeader?: string;
|
|
265
|
+
/** Prefix for authToken value (default: 'Bearer '). */
|
|
266
|
+
authTokenPrefix?: string;
|
|
267
|
+
/** CAPTCHA solving API key (2captcha or CapSolver). */
|
|
268
|
+
captchaSolverApiKey?: string;
|
|
269
|
+
/** CAPTCHA solving service provider (default: '2captcha'). */
|
|
270
|
+
captchaSolverProvider?: '2captcha' | 'capsolver';
|
|
271
|
+
/**
|
|
272
|
+
* Path to a Chrome user data directory for profile inheritance (local deployments only).
|
|
273
|
+
* When set, the crawler exports the existing session from this profile and injects it.
|
|
274
|
+
*/
|
|
275
|
+
chromeProfilePath?: string;
|
|
276
|
+
/** MailSlurp API key for email OTP auto-retrieval. */
|
|
277
|
+
mailslurpApiKey?: string;
|
|
278
|
+
/** MailSlurp inbox ID to poll for OTP emails. */
|
|
279
|
+
mailslurpInboxId?: string;
|
|
280
|
+
/** SSO provider ('okta' | 'azure_ad' | 'generic_oidc'). */
|
|
281
|
+
ssoProvider?: string;
|
|
282
|
+
/** SSO domain or tenant ID. */
|
|
283
|
+
ssoDomain?: string;
|
|
284
|
+
/** SSO OAuth2 client ID. */
|
|
285
|
+
ssoClientId?: string;
|
|
286
|
+
/** SSO OAuth2 client secret (decrypted). */
|
|
287
|
+
ssoClientSecret?: string;
|
|
288
|
+
/** SSO scopes (space-separated). Default: 'openid profile'. */
|
|
289
|
+
ssoScope?: string;
|
|
290
|
+
/** HTTP/HTTPS/SOCKS5 proxy URL — routes browser through this proxy for bot-protected sites. */
|
|
291
|
+
proxyUrl?: string;
|
|
292
|
+
// ─── scrapegraph gap fields ──────────────────────────────────────────────
|
|
293
|
+
/** HTML extraction mode. 'normal'=raw, 'reader'=Readability article, 'prune'=strip nav/ads. Default: 'normal'. */
|
|
294
|
+
htmlMode?: 'normal' | 'reader' | 'prune';
|
|
295
|
+
/** Per-request screenshot dimensions and quality. Defaults: 1440×900, quality 80. */
|
|
296
|
+
screenshotConfig?: {
|
|
297
|
+
fullPage?: boolean;
|
|
298
|
+
width?: number;
|
|
299
|
+
height?: number;
|
|
300
|
+
quality?: number;
|
|
301
|
+
};
|
|
302
|
+
/** Enable/disable Playwright stealth plugin. Default: true (existing behaviour). */
|
|
303
|
+
stealth?: boolean;
|
|
304
|
+
/** Mock mode — intercept all navigation and return synthetic content. Good for CI. */
|
|
305
|
+
mock?: boolean | { minKb?: number; maxKb?: number; minSleep?: number; maxSleep?: number };
|
|
306
|
+
/** MIME type allowlist — crawler skips URLs returning disallowed content types. */
|
|
307
|
+
allowedTypes?: string[];
|
|
308
|
+
/** Glob-style include patterns for URL paths (e.g. '/blog/*'). Only matching paths crawled. */
|
|
309
|
+
includePatterns?: string[];
|
|
310
|
+
/** Glob-style exclude patterns for URL paths (e.g. '/admin/*'). Matching paths skipped. */
|
|
311
|
+
excludePatterns?: string[];
|
|
312
|
+
/** Allow crawler to follow links to external domains. Default: false. */
|
|
313
|
+
allowExternal?: boolean;
|
|
314
|
+
/** Requested output formats for a single-pass multi-format extraction. */
|
|
315
|
+
requestedFormats?: Array<'markdown' | 'html' | 'links' | 'images' | 'summary' | 'json' | 'branding' | 'screenshot'>;
|
|
316
|
+
/** LLM chunker configuration for AI extraction passes. */
|
|
317
|
+
chunkerConfig?: { size?: number | 'dynamic'; overlap?: number };
|
|
318
|
+
/** ISO-3166-1 alpha-2 country code for geo-targeted proxy routing (e.g. 'us', 'gb'). */
|
|
319
|
+
proxyCountry?: string;
|
|
320
|
+
/** When true, after the primary crawl auto-enqueue one CRAWL job per credentialProfile. */
|
|
321
|
+
crawlAllRoles?: boolean;
|
|
322
|
+
/** Decrypted credential profiles used when crawlAllRoles is true. */
|
|
323
|
+
credentialProfiles?: Array<{ id: string; name: string; username: string; password: string }>;
|
|
324
|
+
/** Set on role-crawl sub-jobs — profile name tagged on discovered screens via roleAccess column. */
|
|
325
|
+
roleProfileName?: string;
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** In-memory map of jobId → AbortController for RUNNING jobs. */
|
|
329
|
+
const runningControllers = new Map<string, AbortController>();
|
|
330
|
+
|
|
331
|
+
// ─── Durable job worker ──────────────────────────────────────────────────────
|
|
332
|
+
//
|
|
333
|
+
// A minimal Postgres-backed work queue: atomic claim via `FOR UPDATE SKIP
|
|
334
|
+
// LOCKED` (safe for any number of concurrent pollers, in-process or across
|
|
335
|
+
// containers), plus a stale-job sweep keyed off a liveness heartbeat rather
|
|
336
|
+
// than wall-clock job age, so a slow-but-alive job is never requeued and
|
|
337
|
+
// double-processed. See startJobWorkerLoop() below.
|
|
338
|
+
|
|
339
|
+
const WORKER_ID = `${os.hostname()}:${process.pid}`;
|
|
340
|
+
const STALE_JOB_TIMEOUT_MINUTES = Number(process.env.JOB_STALE_TIMEOUT_MINUTES) || 30;
|
|
341
|
+
const MAX_CONCURRENT_PER_TENANT = Number(process.env.MAX_CONCURRENT_PER_TENANT) || 4;
|
|
342
|
+
const WORKER_POLL_INTERVAL_MS = Number(process.env.JOB_WORKER_POLL_INTERVAL_MS) || 15_000;
|
|
343
|
+
const WORKER_CONCURRENCY = Number(process.env.JOB_WORKER_CONCURRENCY) || 8;
|
|
344
|
+
|
|
345
|
+
// GAP-12: true active-execution semaphore — counts jobs currently executing
|
|
346
|
+
// (claim→finish), not poll slots. A single poll loop checks this before every
|
|
347
|
+
// claim so the cap is never exceeded even across overlapping ticks.
|
|
348
|
+
let activeExecutions = 0;
|
|
349
|
+
|
|
350
|
+
function withSemaphore<T>(fn: () => Promise<T>): Promise<T> {
|
|
351
|
+
activeExecutions++;
|
|
352
|
+
return fn().finally(() => { activeExecutions--; });
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
export function getActiveExecutionCount(): number {
|
|
356
|
+
return activeExecutions;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
// Max simultaneous DISCOVER jobs — each launches a Playwright browser and holds
|
|
360
|
+
// DB connections, so running many concurrently exhausts resources. Default 2.
|
|
361
|
+
const MAX_CONCURRENT_DISCOVER = Number(process.env.MAX_CONCURRENT_DISCOVER) || 2;
|
|
362
|
+
const JOB_HEARTBEAT_INTERVAL_MS = Number(process.env.JOB_HEARTBEAT_INTERVAL_MS) || 15_000;
|
|
363
|
+
// How many headless browsers a single RUN_TEST_SUITE job launches at once —
|
|
364
|
+
// distinct from WORKER_CONCURRENCY (how many *jobs* the poll loop claims at
|
|
365
|
+
// once). Bounded by default to avoid exhausting a container's memory; the
|
|
366
|
+
// primary scale-out path for running more tests at once is still horizontal
|
|
367
|
+
// (more worker containers / SQS), not raising this past what one container
|
|
368
|
+
// can safely hold — see startJobWorkerLoop's doc comment.
|
|
369
|
+
const TEST_EXEC_CONCURRENCY = Number(process.env.TEST_EXEC_CONCURRENCY) || 5;
|
|
370
|
+
|
|
371
|
+
type ClaimedJob = { id: string; tenantId: string; projectId: string; type: string; config: any };
|
|
372
|
+
|
|
373
|
+
/** Dispatch table populated at module bottom, once every process*Job function is declared. */
|
|
374
|
+
let jobDispatchTable: Record<string, (jobId: string, config: any) => Promise<void>> | null = null;
|
|
375
|
+
|
|
376
|
+
/** Atomically claims one specific QUEUED job for this worker. Returns null if it was already claimed. */
|
|
377
|
+
export async function claimSpecificJob(jobId: string): Promise<ClaimedJob | null> {
|
|
378
|
+
const rows = await prismaAdmin.$queryRaw<ClaimedJob[]>`
|
|
379
|
+
UPDATE "PlatformJob"
|
|
380
|
+
SET status = 'RUNNING', "startedAt" = NOW(), "heartbeatAt" = NOW(), "workerId" = ${WORKER_ID}
|
|
381
|
+
WHERE id = ${jobId} AND status = 'QUEUED'
|
|
382
|
+
AND ("nextRetryAt" IS NULL OR "nextRetryAt" <= NOW())
|
|
383
|
+
RETURNING id, "tenantId" AS "tenantId", "projectId" AS "projectId", type, config
|
|
384
|
+
`;
|
|
385
|
+
return rows[0] ?? null;
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
/** Atomically claims the oldest QUEUED job across all tenants. SKIP LOCKED makes this
|
|
389
|
+
* race-safe against any number of other pollers doing the same thing concurrently.
|
|
390
|
+
* DISCOVER jobs are subject to MAX_CONCURRENT_DISCOVER — skipped when that many are
|
|
391
|
+
* already RUNNING to prevent Playwright/DB pool exhaustion from simultaneous crawls. */
|
|
392
|
+
export async function claimNextQueuedJob(): Promise<ClaimedJob | null> {
|
|
393
|
+
const maxDiscover = MAX_CONCURRENT_DISCOVER;
|
|
394
|
+
const rows = await prismaAdmin.$queryRaw<ClaimedJob[]>`
|
|
395
|
+
UPDATE "PlatformJob"
|
|
396
|
+
SET status = 'RUNNING', "startedAt" = NOW(), "heartbeatAt" = NOW(), "workerId" = ${WORKER_ID}
|
|
397
|
+
WHERE id = (
|
|
398
|
+
SELECT id FROM "PlatformJob" p
|
|
399
|
+
WHERE status = 'QUEUED'
|
|
400
|
+
AND ("nextRetryAt" IS NULL OR "nextRetryAt" <= NOW())
|
|
401
|
+
AND (
|
|
402
|
+
type != 'DISCOVER'
|
|
403
|
+
OR (SELECT COUNT(*) FROM "PlatformJob" WHERE status = 'RUNNING' AND type = 'DISCOVER') < ${maxDiscover}
|
|
404
|
+
)
|
|
405
|
+
AND (
|
|
406
|
+
SELECT COUNT(*) FROM "PlatformJob" p2
|
|
407
|
+
WHERE p2.status = 'RUNNING'
|
|
408
|
+
AND p2."tenantId" = p."tenantId"
|
|
409
|
+
AND p2.inline = false
|
|
410
|
+
) < ${MAX_CONCURRENT_PER_TENANT}
|
|
411
|
+
ORDER BY p."priority" DESC, p."queuedAt" ASC
|
|
412
|
+
FOR UPDATE SKIP LOCKED
|
|
413
|
+
LIMIT 1
|
|
414
|
+
)
|
|
415
|
+
RETURNING id, "tenantId" AS "tenantId", "projectId" AS "projectId", type, config
|
|
416
|
+
`;
|
|
417
|
+
return rows[0] ?? null;
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Requeues RUNNING jobs whose heartbeat has gone stale — the worker that claimed them
|
|
421
|
+
* died (crash, restart, OOM) without ever marking them DONE/FAILED. Idempotent and
|
|
422
|
+
* safe to run from every worker process; only affects rows past the timeout.
|
|
423
|
+
* API-in-process job types (GENERATE_SCRIPT etc.) are failed directly — requeueing them
|
|
424
|
+
* would cause the worker to claim and fail them with a confusing "claimed by worker" error. */
|
|
425
|
+
export async function requeueStaleRunningJobs(): Promise<void> {
|
|
426
|
+
// Directly fail stale API-in-process jobs — worker cannot process these types.
|
|
427
|
+
const failedRows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
428
|
+
UPDATE "PlatformJob"
|
|
429
|
+
SET status = 'FAILED',
|
|
430
|
+
"finishedAt" = NOW(),
|
|
431
|
+
error = 'API process was restarted while this job was running — please retry from the UI.'
|
|
432
|
+
WHERE status = 'RUNNING'
|
|
433
|
+
AND type IN ('GENERATE_SCRIPT', 'GENERATE_DATA', 'GENERATE_TESTS', 'GENERATE_TEST_PLAN')
|
|
434
|
+
AND COALESCE("heartbeatAt", "startedAt") < (NOW() AT TIME ZONE 'UTC') - (${STALE_JOB_TIMEOUT_MINUTES} * interval '1 minute')
|
|
435
|
+
RETURNING id
|
|
436
|
+
`;
|
|
437
|
+
if (failedRows.length > 0) {
|
|
438
|
+
logger.warn({ jobIds: failedRows.map((r: any) => r.id), staleTimeoutMinutes: STALE_JOB_TIMEOUT_MINUTES }, '[job-worker] failed stale API-in-process job(s) — API restarted while running');
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
const rows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
442
|
+
UPDATE "PlatformJob"
|
|
443
|
+
SET status = 'QUEUED',
|
|
444
|
+
"workerId" = NULL,
|
|
445
|
+
result = jsonb_set(
|
|
446
|
+
COALESCE(result::jsonb, '{}'::jsonb),
|
|
447
|
+
'{step}',
|
|
448
|
+
to_jsonb('Worker heartbeat lost — queued for recovery'::text),
|
|
449
|
+
true
|
|
450
|
+
)
|
|
451
|
+
WHERE status = 'RUNNING'
|
|
452
|
+
AND type NOT IN ('GENERATE_SCRIPT', 'GENERATE_DATA', 'GENERATE_TESTS', 'GENERATE_TEST_PLAN')
|
|
453
|
+
AND COALESCE("heartbeatAt", "startedAt") < (NOW() AT TIME ZONE 'UTC') - (${STALE_JOB_TIMEOUT_MINUTES} * interval '1 minute')
|
|
454
|
+
RETURNING id
|
|
455
|
+
`;
|
|
456
|
+
if (rows.length > 0) {
|
|
457
|
+
logger.warn({ jobIds: rows.map((r: any) => r.id), staleTimeoutMinutes: STALE_JOB_TIMEOUT_MINUTES }, '[job-worker] requeued stale RUNNING job(s)');
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
/**
|
|
462
|
+
* Requeues any RUNNING jobs claimed by a different worker (i.e., a previous
|
|
463
|
+
* process instance). Call once at startup before the poll loop begins — this
|
|
464
|
+
* provides immediate recovery instead of waiting the full STALE_JOB_TIMEOUT_MINUTES.
|
|
465
|
+
* Safe to call from multiple replicas simultaneously (each uses its own WORKER_ID).
|
|
466
|
+
*/
|
|
467
|
+
export async function requeueOrphanedJobs(): Promise<void> {
|
|
468
|
+
const rows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
469
|
+
UPDATE "PlatformJob"
|
|
470
|
+
SET status = 'QUEUED',
|
|
471
|
+
"workerId" = NULL,
|
|
472
|
+
result = jsonb_set(
|
|
473
|
+
COALESCE(result::jsonb, '{}'::jsonb),
|
|
474
|
+
'{step}',
|
|
475
|
+
to_jsonb('Worker restarted — queued for recovery'::text),
|
|
476
|
+
true
|
|
477
|
+
)
|
|
478
|
+
WHERE status = 'RUNNING'
|
|
479
|
+
AND "workerId" IS NOT NULL
|
|
480
|
+
AND "workerId" != ${WORKER_ID}
|
|
481
|
+
RETURNING id
|
|
482
|
+
`;
|
|
483
|
+
if (rows.length > 0) {
|
|
484
|
+
logger.warn({ jobIds: rows.map((r: any) => r.id), workerId: WORKER_ID }, '[job-worker] requeued orphaned RUNNING job(s) from dead worker');
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
/** Dispatches a claimed job to its type's processor. Last-resort safety net — every
|
|
489
|
+
* process*Job function already catches and records its own failures. */
|
|
490
|
+
export async function dispatchClaimedJob(job: ClaimedJob): Promise<void> {
|
|
491
|
+
const dispatcher = jobDispatchTable?.[job.type];
|
|
492
|
+
if (!dispatcher) {
|
|
493
|
+
logger.error({ jobId: job.id, type: job.type }, '[job-worker] no dispatcher registered for job type');
|
|
494
|
+
await prismaAdmin.platformJob.update({
|
|
495
|
+
where: { id: job.id },
|
|
496
|
+
data: { status: 'FAILED', error: `Unknown job type: ${job.type}`, finishedAt: new Date() },
|
|
497
|
+
}).catch(() => { });
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
const stopTimer = crawlJobDurationSeconds.startTimer({ type: job.type });
|
|
501
|
+
try {
|
|
502
|
+
await dispatcher(job.id, job.config);
|
|
503
|
+
stopTimer();
|
|
504
|
+
// dispatcher() resolving doesn't mean the job succeeded — every process*Job
|
|
505
|
+
// function catches and records its own failures internally without
|
|
506
|
+
// rethrowing (see this function's doc comment). Read back the actual
|
|
507
|
+
// final status so the metric reflects reality, not just "didn't throw".
|
|
508
|
+
const finished = await prismaAdmin.platformJob.findUnique({ where: { id: job.id }, select: { status: true } }).catch(() => null);
|
|
509
|
+
crawlJobsTotal.inc({ type: job.type, status: (finished?.status === 'FAILED' || finished?.status === 'RETRY_WAIT') ? 'failed' : 'success' });
|
|
510
|
+
} catch (err: any) {
|
|
511
|
+
stopTimer();
|
|
512
|
+
crawlJobsTotal.inc({ type: job.type, status: 'failed' });
|
|
513
|
+
logger.error({ jobId: job.id, type: job.type, err: String(err?.message ?? err) }, '[job-worker] job threw uncaught error');
|
|
514
|
+
await recordJobFailure(job.tenantId, job.id, err);
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
let workerLoopTimer: ReturnType<typeof setInterval> | null = null;
|
|
519
|
+
// GAP-12: signals the semaphore-based poll loop to exit gracefully.
|
|
520
|
+
let workerShuttingDown = false;
|
|
521
|
+
|
|
522
|
+
/** Re-promotes FAILED jobs to RETRY_WAIT if they are eligible for retry based on per-type limits.
|
|
523
|
+
* RETRY_WAIT makes the waiting period visible in the UI. A separate sweep then promotes
|
|
524
|
+
* RETRY_WAIT → QUEUED once nextRetryAt <= NOW(). */
|
|
525
|
+
export async function retryEligibleFailedJobs(): Promise<void> {
|
|
526
|
+
// Legacy path: jobs that failed before failure-type classification was added.
|
|
527
|
+
// New failures go FAILED→RETRY_WAIT directly in the job error handler (dispatchClaimedJob).
|
|
528
|
+
// This only picks up old FAILED rows that have no nextRetryAt set yet.
|
|
529
|
+
// Phase 1: FAILED → RETRY_WAIT (GAP-07: visible waiting state)
|
|
530
|
+
const rows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
531
|
+
UPDATE "PlatformJob"
|
|
532
|
+
SET status = 'RETRY_WAIT',
|
|
533
|
+
"retryCount" = "retryCount" + 1,
|
|
534
|
+
"nextRetryAt" = NOW() + (INTERVAL '1 minute' * POWER(2, "retryCount")),
|
|
535
|
+
"workerId" = NULL
|
|
536
|
+
WHERE status = 'FAILED'
|
|
537
|
+
AND dlq = false
|
|
538
|
+
AND "nextRetryAt" IS NULL
|
|
539
|
+
AND "retryCount" < 5
|
|
540
|
+
RETURNING id
|
|
541
|
+
`;
|
|
542
|
+
if (rows.length > 0) {
|
|
543
|
+
logger.info({ jobIds: rows.map((r: any) => r.id) }, '[job-worker] moved failed job(s) to RETRY_WAIT');
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
// Phase 2: RETRY_WAIT → QUEUED when the wait period has elapsed (GAP-07)
|
|
547
|
+
const readyRows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
548
|
+
UPDATE "PlatformJob"
|
|
549
|
+
SET status = 'QUEUED',
|
|
550
|
+
"requeuedAt" = NOW()
|
|
551
|
+
WHERE status = 'RETRY_WAIT'
|
|
552
|
+
AND "nextRetryAt" <= (NOW() AT TIME ZONE 'UTC')
|
|
553
|
+
AND dlq = false
|
|
554
|
+
RETURNING id
|
|
555
|
+
`;
|
|
556
|
+
if (readyRows.length > 0) {
|
|
557
|
+
logger.info({ jobIds: readyRows.map((r: any) => r.id) }, '[job-worker] promoted RETRY_WAIT job(s) to QUEUED');
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** Promotes FAILED jobs to DLQ if they exceed their per-type retry limits. */
|
|
562
|
+
export async function promoteToDeadLetterQueue(): Promise<void> {
|
|
563
|
+
const rows = await prismaAdmin.$queryRaw<Array<{ id: string }>>`
|
|
564
|
+
UPDATE "PlatformJob"
|
|
565
|
+
SET dlq = true,
|
|
566
|
+
"dlqAt" = NOW(),
|
|
567
|
+
"dlqReason" = error
|
|
568
|
+
WHERE status = 'FAILED'
|
|
569
|
+
AND dlq = false
|
|
570
|
+
AND "retryCount" >= CASE
|
|
571
|
+
WHEN type IN ('CRAWL', 'NATIVE_CRAWL') THEN 3
|
|
572
|
+
WHEN type IN ('GENERATE_TESTS', 'IMPORT_TESTS', 'RUN_TEST_SUITE', 'VISUAL_REGRESSION') THEN 2
|
|
573
|
+
WHEN type IN ('GENERATE_SCRIPT', 'GENERATE_DATA', 'GENERATE_TEST_PLAN') THEN 0
|
|
574
|
+
ELSE 1
|
|
575
|
+
END
|
|
576
|
+
RETURNING id
|
|
577
|
+
`;
|
|
578
|
+
if (rows.length > 0) {
|
|
579
|
+
logger.error({ jobIds: rows.map((r: any) => r.id) }, '[job-worker] promoted failed job(s) to DLQ');
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/**
|
|
584
|
+
* Starts the durable job worker poll loop. This is what makes job processing
|
|
585
|
+
* survive a restart — enqueueJob()'s immediate same-process claim attempt is
|
|
586
|
+
* only a latency optimization; if the process dies before that fires (or
|
|
587
|
+
* mid-job), this loop's next tick claims/requeues it. Call once at process
|
|
588
|
+
* startup (API server and/or a dedicated crawler worker process — safe to
|
|
589
|
+
* run in both, and safe to run in many container replicas at once).
|
|
590
|
+
*/
|
|
591
|
+
export function startJobWorkerLoop(opts?: { pollIntervalMs?: number; concurrency?: number }): void {
|
|
592
|
+
if (workerLoopTimer) return; // already running in this process
|
|
593
|
+
const pollIntervalMs = opts?.pollIntervalMs ?? WORKER_POLL_INTERVAL_MS;
|
|
594
|
+
const concurrency = opts?.concurrency ?? WORKER_CONCURRENCY;
|
|
595
|
+
logger.info({ workerId: WORKER_ID, pollIntervalMs, concurrency }, '[job-worker] starting');
|
|
596
|
+
|
|
597
|
+
// GAP-12: maintenance sweep stays on a fixed interval (unchanged).
|
|
598
|
+
const sweepTick = async () => {
|
|
599
|
+
try {
|
|
600
|
+
await retryEligibleFailedJobs();
|
|
601
|
+
await promoteToDeadLetterQueue();
|
|
602
|
+
await requeueStaleRunningJobs();
|
|
603
|
+
} catch (err) {
|
|
604
|
+
logger.error({ err: String(err) }, '[job-worker] stale/retry job sweep failed');
|
|
605
|
+
}
|
|
606
|
+
};
|
|
607
|
+
workerLoopTimer = setInterval(sweepTick, pollIntervalMs);
|
|
608
|
+
|
|
609
|
+
// GAP-12: single continuous poll loop — checks the semaphore before every
|
|
610
|
+
// claim so activeExecutions never exceeds WORKER_CONCURRENCY regardless of
|
|
611
|
+
// how long individual jobs take. Jobs are non-blocking: withSemaphore(...)
|
|
612
|
+
// is NOT awaited here, so the loop immediately loops back and can claim the
|
|
613
|
+
// next job while previous ones are still running.
|
|
614
|
+
//
|
|
615
|
+
// NOTE (GAP-20): requeueOrphanedJobs() is intentionally NOT called at startup here.
|
|
616
|
+
// Calling it at startup is unsafe in multi-replica deployments — replica A would steal
|
|
617
|
+
// RUNNING jobs from replica B (which is still alive and processing them), causing
|
|
618
|
+
// double-execution. The stale-job sweep (requeueStaleRunningJobs) handles recovery
|
|
619
|
+
// safely via heartbeat timeout. requeueOrphanedJobs() remains available for admin use.
|
|
620
|
+
workerShuttingDown = false;
|
|
621
|
+
|
|
622
|
+
const pollLoop = async () => {
|
|
623
|
+
void sweepTick(); // run one sweep immediately on startup
|
|
624
|
+
while (!workerShuttingDown) {
|
|
625
|
+
if (activeExecutions >= concurrency) {
|
|
626
|
+
// All slots busy — wait before checking again without hammering the DB.
|
|
627
|
+
await new Promise(resolve => setTimeout(resolve, 500));
|
|
628
|
+
continue;
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
let paused = false;
|
|
632
|
+
try {
|
|
633
|
+
const pauseRow = await prismaAdmin.systemConfig.findUnique({ where: { key: 'queue.paused' } });
|
|
634
|
+
paused = pauseRow?.value === 'true';
|
|
635
|
+
} catch {
|
|
636
|
+
// ignore — treat as unpaused
|
|
637
|
+
}
|
|
638
|
+
|
|
639
|
+
if (paused) {
|
|
640
|
+
logger.info('[job-worker] queue is paused — skipping claim');
|
|
641
|
+
await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
|
|
642
|
+
continue;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
let job: ClaimedJob | null = null;
|
|
646
|
+
try {
|
|
647
|
+
job = await claimNextQueuedJob();
|
|
648
|
+
} catch (err) {
|
|
649
|
+
logger.error({ err: String(err) }, '[job-worker] claim failed');
|
|
650
|
+
}
|
|
651
|
+
|
|
652
|
+
if (!job) {
|
|
653
|
+
// Nothing queued — back off before polling again.
|
|
654
|
+
await new Promise(resolve => setTimeout(resolve, pollIntervalMs));
|
|
655
|
+
continue;
|
|
656
|
+
}
|
|
657
|
+
|
|
658
|
+
// Non-blocking: fire and forget into semaphore — poll loop continues immediately.
|
|
659
|
+
withSemaphore(() => dispatchClaimedJob(job!)).catch(err => {
|
|
660
|
+
logger.error({ err, jobId: job!.id }, '[worker] unhandled job error');
|
|
661
|
+
});
|
|
662
|
+
}
|
|
663
|
+
};
|
|
664
|
+
|
|
665
|
+
void pollLoop();
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Stops the poll loop. Mainly for tests. */
|
|
669
|
+
export function stopJobWorkerLoop(): void {
|
|
670
|
+
workerShuttingDown = true; // GAP-12: signal continuous poll loop to exit
|
|
671
|
+
if (workerLoopTimer) clearInterval(workerLoopTimer);
|
|
672
|
+
workerLoopTimer = null;
|
|
673
|
+
}
|
|
674
|
+
|
|
675
|
+
/** Create a job record that tracks a synchronous operation (telemetry only, no background processor). */
|
|
676
|
+
export async function createTrackedJob(
|
|
677
|
+
type: string,
|
|
678
|
+
config: { tenantId: string; projectId: string;[k: string]: any }
|
|
679
|
+
): Promise<string> {
|
|
680
|
+
const name = makeJobName(type);
|
|
681
|
+
const job = await withTenant(config.tenantId, (tx) =>
|
|
682
|
+
tx.platformJob.create({
|
|
683
|
+
data: { tenantId: config.tenantId, projectId: config.projectId, type, name, status: 'RUNNING', startedAt: new Date(), inline: true, config: config as any },
|
|
684
|
+
})
|
|
685
|
+
) as { id: string };
|
|
686
|
+
return job.id;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** Mark a tracked job DONE or FAILED. Safe to call in finally — swallows errors.
|
|
690
|
+
* GAP-14/15: Uses failure-type classification for per-type backoff on FAILED. */
|
|
691
|
+
export async function finishTrackedJob(tenantId: string, jobId: string, error?: string): Promise<void> {
|
|
692
|
+
if (!error) {
|
|
693
|
+
await withTenant(tenantId, (tx) =>
|
|
694
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), progress: 100 } })
|
|
695
|
+
).catch(() => { });
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
const failureType = classifyFailure(error);
|
|
699
|
+
const jobRow = await prismaAdmin.platformJob.findUnique({ where: { id: jobId }, select: { retryCount: true, result: true } }).catch(() => null);
|
|
700
|
+
const currentRetry = jobRow?.retryCount ?? 0;
|
|
701
|
+
const nextRetryAt = computeNextRetryAt(failureType, currentRetry);
|
|
702
|
+
await withTenant(tenantId, (tx) =>
|
|
703
|
+
tx.platformJob.update({
|
|
704
|
+
where: { id: jobId },
|
|
705
|
+
data: {
|
|
706
|
+
status: nextRetryAt ? 'RETRY_WAIT' : 'FAILED',
|
|
707
|
+
finishedAt: new Date(),
|
|
708
|
+
error,
|
|
709
|
+
nextRetryAt,
|
|
710
|
+
retryCount: { increment: 1 },
|
|
711
|
+
failureType,
|
|
712
|
+
result: { ...(jobRow?.result as any ?? {}), failureType } as any,
|
|
713
|
+
},
|
|
714
|
+
})
|
|
715
|
+
).catch(() => { });
|
|
716
|
+
if (!nextRetryAt || failureType === FailureType.FATAL) {
|
|
717
|
+
await prismaAdmin.platformJob.update({
|
|
718
|
+
where: { id: jobId },
|
|
719
|
+
data: { dlq: true, dlqAt: new Date(), dlqReason: error },
|
|
720
|
+
}).catch(() => { });
|
|
721
|
+
}
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/** Enqueue a generic platform job — returns the job ID immediately. */
|
|
725
|
+
export async function enqueueJob(type: string, config: any): Promise<string> {
|
|
726
|
+
const { tenantId, projectId, submittedBy } = config;
|
|
727
|
+
|
|
728
|
+
const name = makeJobName(type);
|
|
729
|
+
const job = await withTenant(tenantId, (tx) =>
|
|
730
|
+
tx.platformJob.create({
|
|
731
|
+
data: {
|
|
732
|
+
tenantId,
|
|
733
|
+
projectId,
|
|
734
|
+
type,
|
|
735
|
+
name,
|
|
736
|
+
status: 'QUEUED',
|
|
737
|
+
config: config as any,
|
|
738
|
+
...(submittedBy ? { submittedBy } : {}),
|
|
739
|
+
},
|
|
740
|
+
})
|
|
741
|
+
) as { id: string };
|
|
742
|
+
|
|
743
|
+
// Durability comes from startJobWorkerLoop()'s poll — this is only a same-process
|
|
744
|
+
// latency optimization so a job doesn't sit idle until the next poll tick. The
|
|
745
|
+
// claim is atomic (WHERE status='QUEUED'), so it's safe even if the poll loop's
|
|
746
|
+
// own tick fires concurrently and claims this same job first.
|
|
747
|
+
if (process.env.JOB_QUEUE_BACKEND === 'sqs') {
|
|
748
|
+
const { sendJobToSqs } = await import('./sqs-queue.js');
|
|
749
|
+
await sendJobToSqs(job.id);
|
|
750
|
+
} else if (process.env.DISABLE_WORKER !== 'true') {
|
|
751
|
+
// Skip inline dispatch when DISABLE_WORKER=true — the dedicated crawler process
|
|
752
|
+
// will pick this up via its poll loop. Inline dispatch in the API container
|
|
753
|
+
// would launch Playwright browsers and crash the API.
|
|
754
|
+
setImmediate(() => claimSpecificJob(job.id).then((claimed) => claimed && dispatchClaimedJob(claimed)));
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
return job.id;
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Get the current state of a platform job. */
|
|
761
|
+
export async function getJob(tenantId: string, jobId: string) {
|
|
762
|
+
return withTenant(tenantId, (tx) =>
|
|
763
|
+
tx.platformJob.findFirst({ where: { id: jobId, tenantId } })
|
|
764
|
+
);
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** List recent jobs for a project. */
|
|
768
|
+
export async function listJobs(tenantId: string, projectId: string) {
|
|
769
|
+
return withTenant(tenantId, async (tx) => {
|
|
770
|
+
const jobs = await tx.platformJob.findMany({
|
|
771
|
+
where: { tenantId, projectId },
|
|
772
|
+
orderBy: { queuedAt: 'desc' },
|
|
773
|
+
take: 50,
|
|
774
|
+
});
|
|
775
|
+
// Attach the most-recently-used model for each job from LLMCallLog
|
|
776
|
+
const jobIds = jobs.map((j) => j.id);
|
|
777
|
+
if (jobIds.length === 0) return jobs;
|
|
778
|
+
const modelRows = await (tx as any).lLMCallLog.groupBy({
|
|
779
|
+
by: ['jobId'],
|
|
780
|
+
where: { tenantId, jobId: { in: jobIds } },
|
|
781
|
+
_max: { model: true, calledAt: true },
|
|
782
|
+
});
|
|
783
|
+
const modelByJobId = new Map<string, string>(
|
|
784
|
+
modelRows
|
|
785
|
+
.filter((r: any) => r.jobId && r._max?.model)
|
|
786
|
+
.map((r: any) => [r.jobId as string, r._max.model as string])
|
|
787
|
+
);
|
|
788
|
+
return jobs.map((j) => ({ ...j, llmModel: modelByJobId.get(j.id) ?? null }));
|
|
789
|
+
});
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
/** Cancel a RUNNING or QUEUED job.
|
|
793
|
+
* Sets status to CANCEL_REQUESTED (GAP-08) so the worker's abort handler can
|
|
794
|
+
* detect the request and set CANCELLED + finishedAt after the underlying work stops.
|
|
795
|
+
* The in-process AbortController is also triggered for same-process jobs. */
|
|
796
|
+
export async function cancelJob(tenantId: string, jobId: string): Promise<void> {
|
|
797
|
+
// Abort in-memory controller if job is running in the same process
|
|
798
|
+
const controller = runningControllers.get(jobId);
|
|
799
|
+
if (controller) {
|
|
800
|
+
controller.abort();
|
|
801
|
+
runningControllers.delete(jobId);
|
|
802
|
+
}
|
|
803
|
+
await withTenant(tenantId, (tx) =>
|
|
804
|
+
tx.platformJob.update({
|
|
805
|
+
where: { id: jobId },
|
|
806
|
+
data: { status: 'CANCEL_REQUESTED' },
|
|
807
|
+
})
|
|
808
|
+
);
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
/** Re-enqueue a job using the same config as a previous job. */
|
|
812
|
+
export async function rerunJob(tenantId: string, jobId: string): Promise<string> {
|
|
813
|
+
const job = await withTenant(tenantId, (tx) =>
|
|
814
|
+
tx.platformJob.findUnique({ where: { id: jobId } })
|
|
815
|
+
) as { type: string; config: any } | null;
|
|
816
|
+
if (!job) throw new Error('Job not found');
|
|
817
|
+
return enqueueJob(job.type, { ...(job.config as any), tenantId });
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// In-memory checkpoint store: updated every 10 screens, saved to DB result on failure.
|
|
821
|
+
const jobCheckpoints = new Map<string, { visitedUrls: string[]; pendingQueue: string[] }>();
|
|
822
|
+
|
|
823
|
+
export async function resumeJob(tenantId: string, jobId: string): Promise<string> {
|
|
824
|
+
const job = await withTenant(tenantId, (tx) =>
|
|
825
|
+
tx.platformJob.findUnique({ where: { id: jobId } })
|
|
826
|
+
) as { type: string; config: any; result: any; checkpoint?: any } | null;
|
|
827
|
+
if (!job) throw new Error('Job not found');
|
|
828
|
+
|
|
829
|
+
const checkpoint = (job as any).checkpoint ?? (job.result as any)?.checkpoint;
|
|
830
|
+
const visitedUrls: string[] = checkpoint?.visitedUrls ?? [];
|
|
831
|
+
const pendingQueue: string[] = checkpoint?.pendingQueue ?? [];
|
|
832
|
+
|
|
833
|
+
if (pendingQueue.length === 0 && visitedUrls.length === 0) {
|
|
834
|
+
// No checkpoint saved — full rerun
|
|
835
|
+
return enqueueJob(job.type, { ...(job.config as any), tenantId });
|
|
836
|
+
}
|
|
837
|
+
|
|
838
|
+
return enqueueJob(job.type, {
|
|
839
|
+
...(job.config as any),
|
|
840
|
+
tenantId,
|
|
841
|
+
skipUrls: [...((job.config as any)?.skipUrls ?? []), ...visitedUrls],
|
|
842
|
+
startUrls: pendingQueue.length > 0 ? pendingQueue : (job.config as any)?.startUrls,
|
|
843
|
+
});
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
/** Update progress percentage and current step label on a running job (non-fatal). */
|
|
847
|
+
export async function updateJobProgress(tenantId: string, jobId: string, progress: number, step: string) {
|
|
848
|
+
try {
|
|
849
|
+
await withTenant(tenantId, async (tx) => {
|
|
850
|
+
// DB-flag cancellation: works for both inline and SQS backends.
|
|
851
|
+
// When a user cancels, status is set to CANCEL_REQUESTED (GAP-08).
|
|
852
|
+
// This check fires at each progress update (every few seconds during crawl).
|
|
853
|
+
const current = await tx.platformJob.findUnique({
|
|
854
|
+
where: { id: jobId },
|
|
855
|
+
select: { status: true },
|
|
856
|
+
});
|
|
857
|
+
if (current?.status === 'CANCELLED' || current?.status === 'CANCEL_REQUESTED') {
|
|
858
|
+
runningControllers.get(jobId)?.abort();
|
|
859
|
+
runningControllers.delete(jobId);
|
|
860
|
+
return; // abort signal propagates; crawlProject exits on next signal check
|
|
861
|
+
}
|
|
862
|
+
await tx.platformJob.update({
|
|
863
|
+
where: { id: jobId },
|
|
864
|
+
// GAP-09: write currentStep as a proper column in addition to result.step (backward compat)
|
|
865
|
+
data: { progress, currentStep: step, result: { step } as any, heartbeatAt: new Date() },
|
|
866
|
+
});
|
|
867
|
+
});
|
|
868
|
+
} catch { /* non-fatal — progress updates best-effort */ }
|
|
869
|
+
}
|
|
870
|
+
|
|
871
|
+
/** Bump only worker liveness. This intentionally does not touch progress/result. */
|
|
872
|
+
async function heartbeatJob(tenantId: string, jobId: string) {
|
|
873
|
+
try {
|
|
874
|
+
await withTenant(tenantId, async (tx) => {
|
|
875
|
+
const current = await tx.platformJob.findUnique({
|
|
876
|
+
where: { id: jobId },
|
|
877
|
+
select: { status: true },
|
|
878
|
+
});
|
|
879
|
+
if (current?.status === 'CANCELLED' || current?.status === 'CANCEL_REQUESTED') {
|
|
880
|
+
runningControllers.get(jobId)?.abort();
|
|
881
|
+
runningControllers.delete(jobId);
|
|
882
|
+
return;
|
|
883
|
+
}
|
|
884
|
+
if (current?.status !== 'RUNNING') return;
|
|
885
|
+
await tx.platformJob.update({
|
|
886
|
+
where: { id: jobId },
|
|
887
|
+
data: { heartbeatAt: new Date(), workerId: WORKER_ID },
|
|
888
|
+
});
|
|
889
|
+
});
|
|
890
|
+
} catch { /* non-fatal — heartbeat updates best-effort */ }
|
|
891
|
+
}
|
|
892
|
+
|
|
893
|
+
/** Background: for each changed screen, search Jira + Confluence for related tickets/pages. */
|
|
894
|
+
async function investigateScreenChanges(
|
|
895
|
+
tenantId: string,
|
|
896
|
+
projectId: string,
|
|
897
|
+
changedScreens: Array<{ id: string; name: string; url?: string; addedElements: string[]; removedElements: string[] }>
|
|
898
|
+
) {
|
|
899
|
+
const [jiraCfg, confluenceCfg] = await Promise.all([
|
|
900
|
+
AppBrain.getConnectorConfig(tenantId, projectId, 'JIRA'),
|
|
901
|
+
AppBrain.getConnectorConfig(tenantId, projectId, 'CONFLUENCE'),
|
|
902
|
+
]);
|
|
903
|
+
|
|
904
|
+
for (const screen of changedScreens) {
|
|
905
|
+
const searchTerm = screen.url ?? screen.name;
|
|
906
|
+
const changeSummary = `Screen "${screen.name}" changed: +${screen.addedElements.length} elements, -${screen.removedElements.length} elements`;
|
|
907
|
+
|
|
908
|
+
const detail: Record<string, any> = {
|
|
909
|
+
screenId: screen.id,
|
|
910
|
+
screenName: screen.name,
|
|
911
|
+
url: screen.url,
|
|
912
|
+
addedElements: screen.addedElements,
|
|
913
|
+
removedElements: screen.removedElements,
|
|
914
|
+
jiraTickets: [],
|
|
915
|
+
confluencePages: [],
|
|
916
|
+
};
|
|
917
|
+
|
|
918
|
+
if (jiraCfg?.baseUrl && jiraCfg?.email && jiraCfg?.apiToken) {
|
|
919
|
+
try {
|
|
920
|
+
detail.jiraTickets = await jira.searchIssues(
|
|
921
|
+
{ baseUrl: jiraCfg.baseUrl, email: jiraCfg.email, apiToken: jiraCfg.apiToken, projectKey: jiraCfg.projectKey },
|
|
922
|
+
searchTerm
|
|
923
|
+
);
|
|
924
|
+
} catch (e) {
|
|
925
|
+
logger.warn({ searchTerm, err: e }, 'Jira search failed');
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
if (confluenceCfg?.baseUrl && confluenceCfg?.email && confluenceCfg?.apiToken) {
|
|
930
|
+
try {
|
|
931
|
+
detail.confluencePages = await confluence.searchPages(
|
|
932
|
+
{ baseUrl: confluenceCfg.baseUrl, email: confluenceCfg.email, apiToken: confluenceCfg.apiToken, spaceKey: confluenceCfg.spaceKey },
|
|
933
|
+
searchTerm
|
|
934
|
+
);
|
|
935
|
+
} catch (e) {
|
|
936
|
+
logger.warn({ searchTerm, err: e }, 'Confluence search failed');
|
|
937
|
+
}
|
|
938
|
+
}
|
|
939
|
+
|
|
940
|
+
await AppBrain.logChange(tenantId, projectId, 'MODIFIED', changeSummary, detail);
|
|
941
|
+
logger.info({ screen: screen.name, jiraTickets: detail.jiraTickets.length, confluencePages: detail.confluencePages.length }, 'Logged screen change investigation');
|
|
942
|
+
}
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
export interface ProcessJobOpts {
|
|
946
|
+
onProgress?: (pct: number) => Promise<void>;
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
export async function processJob(jobId: string, config: any, opts?: ProcessJobOpts) {
|
|
950
|
+
const { tenantId, projectId } = config;
|
|
951
|
+
|
|
952
|
+
// Mark as RUNNING — skip if already CANCELLED (race: user cancelled before worker picked it up).
|
|
953
|
+
const jobStartedAt = new Date();
|
|
954
|
+
const claimed = await withTenant(tenantId, (tx) =>
|
|
955
|
+
tx.platformJob.updateMany({
|
|
956
|
+
where: { id: jobId, status: { not: 'CANCELLED' } },
|
|
957
|
+
data: { status: 'RUNNING', startedAt: jobStartedAt, heartbeatAt: jobStartedAt, workerId: WORKER_ID },
|
|
958
|
+
})
|
|
959
|
+
);
|
|
960
|
+
if (claimed.count === 0) return;
|
|
961
|
+
|
|
962
|
+
const controller = new AbortController();
|
|
963
|
+
runningControllers.set(jobId, controller);
|
|
964
|
+
const heartbeatTimer = setInterval(() => {
|
|
965
|
+
void heartbeatJob(tenantId, jobId);
|
|
966
|
+
}, JOB_HEARTBEAT_INTERVAL_MS);
|
|
967
|
+
|
|
968
|
+
const onProgress = async (pct: number, step: string) => {
|
|
969
|
+
await updateJobProgress(tenantId, jobId, pct, step);
|
|
970
|
+
await opts?.onProgress?.(pct);
|
|
971
|
+
};
|
|
972
|
+
|
|
973
|
+
const DEFAULT_MAX_SCREENS = parseInt(process.env.CRAWL_DEFAULT_MAX_SCREENS ?? '') || 150;
|
|
974
|
+
|
|
975
|
+
try {
|
|
976
|
+
// Per-project maxScreens + deviceProfiles + seedUrls + interactive probing + sitemap seeding + traversal strategy from crawlConfig override job config defaults.
|
|
977
|
+
if (!config.maxScreens || !config.deviceProfiles || config.interactive === undefined || config.useSitemap === undefined || !config.traversalStrategy) {
|
|
978
|
+
const proj: any = await withTenant(tenantId, (tx) =>
|
|
979
|
+
(tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
|
|
980
|
+
);
|
|
981
|
+
const perProject = proj?.crawlConfig?.maxScreens;
|
|
982
|
+
if (!config.maxScreens) config.maxScreens = perProject || DEFAULT_MAX_SCREENS;
|
|
983
|
+
if (!config.deviceProfiles) config.deviceProfiles = proj?.crawlConfig?.deviceProfiles ?? ['DESKTOP'];
|
|
984
|
+
if (config.interactive === undefined) config.interactive = proj?.crawlConfig?.interactive ?? false;
|
|
985
|
+
if (config.useSitemap === undefined) config.useSitemap = proj?.crawlConfig?.useSitemap ?? false;
|
|
986
|
+
if (!config.sitemapUrl) config.sitemapUrl = proj?.crawlConfig?.sitemapUrl ?? undefined;
|
|
987
|
+
if (!config.traversalStrategy) config.traversalStrategy = proj?.crawlConfig?.traversalStrategy ?? 'BFS';
|
|
988
|
+
if (!config.bestFirstKeywords) config.bestFirstKeywords = proj?.crawlConfig?.bestFirstKeywords ?? undefined;
|
|
989
|
+
// segmentSize from crawl config — default unlimited (9_999_999) so normal sites run in one job;
|
|
990
|
+
// only segment if the project explicitly sets a segmentSize in its crawl config.
|
|
991
|
+
if (!config.segmentSize) config.segmentSize = proj?.crawlConfig?.segmentSize ?? 9_999_999;
|
|
992
|
+
// Load saved seedUrls as non-selective seeds (link discovery still runs from them).
|
|
993
|
+
// Skip when a selective recrawl is requested (selectiveUrls set) or seeds already provided.
|
|
994
|
+
if (!config.selectiveUrls?.length && (!config.startUrls || config.startUrls.length === 0)) {
|
|
995
|
+
const saved: string[] = proj?.crawlConfig?.seedUrls ?? [];
|
|
996
|
+
if (saved.length > 0) config.startUrls = saved;
|
|
997
|
+
}
|
|
998
|
+
if (config.interactive === undefined) config.interactive = proj?.crawlConfig?.interactive ?? false;
|
|
999
|
+
}
|
|
1000
|
+
// Build runtime credentials: convert stored totpSecret → getOneTimeCode function
|
|
1001
|
+
const runtimeCreds = config.credentials
|
|
1002
|
+
? {
|
|
1003
|
+
...config.credentials,
|
|
1004
|
+
...(config.credentials.totpSecret
|
|
1005
|
+
? { getOneTimeCode: async () => generateTOTP(config.credentials.totpSecret) }
|
|
1006
|
+
: {}),
|
|
1007
|
+
}
|
|
1008
|
+
: undefined;
|
|
1009
|
+
|
|
1010
|
+
const storageConfigForCrawl = await getTenantStorageConfig(tenantId).catch(() => null);
|
|
1011
|
+
const result = await crawlProject({
|
|
1012
|
+
...config, credentials: runtimeCreds, abortSignal: controller.signal, jobId,
|
|
1013
|
+
storageConfig: storageConfigForCrawl,
|
|
1014
|
+
onCheckpoint: async (visitedUrls, pendingQueue) => {
|
|
1015
|
+
jobCheckpoints.set(jobId, { visitedUrls, pendingQueue });
|
|
1016
|
+
// GAP-19: configurable checkpoint interval; GAP-04: persist to DB for crash recovery
|
|
1017
|
+
const CHECKPOINT_INTERVAL = parseInt(process.env.CRAWL_CHECKPOINT_INTERVAL ?? '10');
|
|
1018
|
+
if (visitedUrls.length % CHECKPOINT_INTERVAL === 0) {
|
|
1019
|
+
try {
|
|
1020
|
+
await prismaAdmin.platformJob.update({
|
|
1021
|
+
where: { id: jobId },
|
|
1022
|
+
data: {
|
|
1023
|
+
checkpoint: { visitedUrls, pendingQueue } as any,
|
|
1024
|
+
checkpointAt: new Date(),
|
|
1025
|
+
},
|
|
1026
|
+
});
|
|
1027
|
+
} catch { /* non-fatal */ }
|
|
1028
|
+
}
|
|
1029
|
+
},
|
|
1030
|
+
}, onProgress);
|
|
1031
|
+
jobCheckpoints.delete(jobId);
|
|
1032
|
+
|
|
1033
|
+
const pendingUrls: string[] = (result as any)?.pendingUrls ?? [];
|
|
1034
|
+
let nextJobId: string | undefined;
|
|
1035
|
+
if (pendingUrls.length > 0) {
|
|
1036
|
+
// visitedUrls includes all attempted URLs (screens, soft-404s, API paths) — more complete than
|
|
1037
|
+
// discovered-with-screenId only, preventing the continuation job from re-attempting dead ends.
|
|
1038
|
+
const visitedForSkip: string[] = (result as any).visitedUrls ?? ((result as any).discovered ?? [])
|
|
1039
|
+
.filter((d: any) => !!d.screenId && !!d.url)
|
|
1040
|
+
.map((d: any) => { try { const _u = new URL(d.url as string); _u.hash = ''; return _u.href; } catch { return d.url as string; } });
|
|
1041
|
+
const reason = (result as any).wasTimeout ? 'timeout' : 'segment-limit';
|
|
1042
|
+
logger.info({ pendingUrls: pendingUrls.length, visited: visitedForSkip.length, reason }, '[crawl] auto-enqueuing continuation job');
|
|
1043
|
+
nextJobId = await enqueueJob('CRAWL', {
|
|
1044
|
+
...config,
|
|
1045
|
+
startUrls: pendingUrls,
|
|
1046
|
+
skipUrls: [...(config.skipUrls ?? []), ...visitedForSkip],
|
|
1047
|
+
}).catch((autoErr: any) => { logger.warn({ err: autoErr?.message }, '[crawl] auto-segment enqueue failed (non-fatal)'); return undefined; });
|
|
1048
|
+
}
|
|
1049
|
+
|
|
1050
|
+
await withTenant(tenantId, (tx) =>
|
|
1051
|
+
tx.platformJob.update({
|
|
1052
|
+
where: { id: jobId },
|
|
1053
|
+
data: {
|
|
1054
|
+
status: 'DONE',
|
|
1055
|
+
result: { ...(result as any), ...(nextJobId ? { nextJobId } : {}) } as any,
|
|
1056
|
+
progress: 100,
|
|
1057
|
+
finishedAt: new Date(),
|
|
1058
|
+
},
|
|
1059
|
+
})
|
|
1060
|
+
);
|
|
1061
|
+
|
|
1062
|
+
// Auto-enqueue CRAWL_DIFF when a prior baseline exists
|
|
1063
|
+
try {
|
|
1064
|
+
const priorJob = await prismaAdmin.platformJob.findFirst({
|
|
1065
|
+
where: { tenantId, projectId, type: 'CRAWL', status: 'DONE', id: { not: jobId } },
|
|
1066
|
+
orderBy: { finishedAt: 'desc' },
|
|
1067
|
+
});
|
|
1068
|
+
if (priorJob) {
|
|
1069
|
+
await prismaAdmin.platformJob.create({
|
|
1070
|
+
data: { tenantId, projectId, type: 'CRAWL_DIFF', name: `crawl-diff-${priorJob.id.slice(-6)}-${jobId.slice(-6)}`, status: 'QUEUED', config: { fromJobId: priorJob.id, toJobId: jobId } as any },
|
|
1071
|
+
});
|
|
1072
|
+
}
|
|
1073
|
+
} catch (_) {}
|
|
1074
|
+
|
|
1075
|
+
clearInterval(heartbeatTimer);
|
|
1076
|
+
runningControllers.delete(jobId);
|
|
1077
|
+
|
|
1078
|
+
{
|
|
1079
|
+
// Auto-seed: merge all successfully crawled URLs into crawlConfig.seedUrls so future
|
|
1080
|
+
// crawls and discovery agents start from a complete picture of the app.
|
|
1081
|
+
const crawledUrls: string[] = ((result as any).discovered ?? [])
|
|
1082
|
+
.filter((d: any) => !!d.screenId && !!d.url)
|
|
1083
|
+
.map((d: any) => d.url as string);
|
|
1084
|
+
if (crawledUrls.length > 0) {
|
|
1085
|
+
(async () => {
|
|
1086
|
+
const cfg = await AppBrain.getCrawlConfig(tenantId, projectId);
|
|
1087
|
+
const existing: string[] = cfg?.seedUrls ?? [];
|
|
1088
|
+
const merged = Array.from(new Set([...existing, ...crawledUrls]));
|
|
1089
|
+
if (merged.length > existing.length) {
|
|
1090
|
+
await AppBrain.saveCrawlConfig(tenantId, projectId, { seedUrls: merged });
|
|
1091
|
+
logger.info({ added: merged.length - existing.length, total: merged.length }, '[crawl] auto-seeded crawled URLs into crawlConfig.seedUrls');
|
|
1092
|
+
}
|
|
1093
|
+
})().catch((err: any) => logger.warn({ err: err?.message }, '[crawl] auto-seed seedUrls failed (non-fatal)'));
|
|
1094
|
+
}
|
|
1095
|
+
|
|
1096
|
+
notifyAdmins(tenantId, {
|
|
1097
|
+
type: 'crawl.done',
|
|
1098
|
+
title: 'Crawl completed',
|
|
1099
|
+
body: `Crawl for project finished successfully.`,
|
|
1100
|
+
metadata: { projectId, jobId },
|
|
1101
|
+
}).catch(console.error);
|
|
1102
|
+
|
|
1103
|
+
dispatchWebhook(tenantId, projectId, 'crawl.done', {
|
|
1104
|
+
jobId,
|
|
1105
|
+
screensFound: (result as any)?.screensFound ?? (result as any)?.screens?.length ?? 0,
|
|
1106
|
+
}).catch(console.error);
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
// Aggregate token usage from LLM calls made during this job.
|
|
1110
|
+
// Delay 8s to let concurrent recordLLMCall writes settle before querying LLMCallLog.
|
|
1111
|
+
setTimeout(() => {
|
|
1112
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
|
|
1113
|
+
}, 8000);
|
|
1114
|
+
|
|
1115
|
+
// Post-crawl: generate / refresh all taxonomy skill files + investigate changes.
|
|
1116
|
+
setImmediate(async () => {
|
|
1117
|
+
try {
|
|
1118
|
+
const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
|
|
1119
|
+
if (projectMap?.screens?.length) {
|
|
1120
|
+
// Mark project oversized when > 300 screens — activates VectorSearchGrounding
|
|
1121
|
+
const screenCount = (projectMap.screens as any[]).length;
|
|
1122
|
+
if (screenCount > 300) {
|
|
1123
|
+
await withTenant(tenantId, (tx) =>
|
|
1124
|
+
(tx as any).project.update({ where: { id: projectId }, data: { oversized: true } })
|
|
1125
|
+
);
|
|
1126
|
+
}
|
|
1127
|
+
await generateTaxonomySkillFiles(tenantId, projectId, projectMap.screens as any, result.apiEndpoints, result.performanceMetrics);
|
|
1128
|
+
|
|
1129
|
+
// Auto-detect AppField catalog from crawled DOM snapshots.
|
|
1130
|
+
// Runs before test generation so getFieldsForCase() returns typed fields (FORM mode).
|
|
1131
|
+
// Capped at 20 screens and only where domSnapshotPath exists to bound LLM cost.
|
|
1132
|
+
try {
|
|
1133
|
+
const { readFile } = await import('node:fs/promises');
|
|
1134
|
+
const { existsSync } = await import('node:fs');
|
|
1135
|
+
const screensWithDom = (projectMap.screens as any[]).filter((s: any) => s.domSnapshotPath);
|
|
1136
|
+
const detectLimit = Math.min(screensWithDom.length, 20);
|
|
1137
|
+
let fieldDetectAdded = 0;
|
|
1138
|
+
for (let si = 0; si < detectLimit; si++) {
|
|
1139
|
+
const screen = screensWithDom[si];
|
|
1140
|
+
try {
|
|
1141
|
+
let htmlContent: string | null = null;
|
|
1142
|
+
const domPath: string = screen.domSnapshotPath;
|
|
1143
|
+
if (domPath.startsWith('https://') || domPath.startsWith('http://')) {
|
|
1144
|
+
const res = await fetch(domPath);
|
|
1145
|
+
if (res.ok) htmlContent = await res.text();
|
|
1146
|
+
} else if (existsSync(domPath)) {
|
|
1147
|
+
htmlContent = await readFile(domPath, 'utf8');
|
|
1148
|
+
}
|
|
1149
|
+
if (!htmlContent) continue;
|
|
1150
|
+
const detected = await detectFieldsFromHtml({ tenantId, projectId, html: htmlContent });
|
|
1151
|
+
if (detected.length > 0) {
|
|
1152
|
+
const merged = await mergeIntoCatalog({ tenantId, projectId, detected });
|
|
1153
|
+
fieldDetectAdded += merged.added;
|
|
1154
|
+
}
|
|
1155
|
+
} catch (sErr) {
|
|
1156
|
+
logger.warn({ screenId: screen.id, err: sErr }, '[field-detect] skipped screen');
|
|
1157
|
+
}
|
|
1158
|
+
}
|
|
1159
|
+
if (fieldDetectAdded > 0 || detectLimit > 0) {
|
|
1160
|
+
logger.info({ screens: detectLimit, added: fieldDetectAdded, projectId }, '[field-detect] catalog populated from crawl');
|
|
1161
|
+
// Refresh FIELD_CATALOG skill file after catalog is populated (GAP-SF-20)
|
|
1162
|
+
refreshFieldCatalogSkillFile(tenantId, projectId).catch(console.error);
|
|
1163
|
+
}
|
|
1164
|
+
} catch (fdErr) {
|
|
1165
|
+
logger.warn({ err: fdErr }, '[field-detect] post-crawl field detection failed');
|
|
1166
|
+
}
|
|
1167
|
+
|
|
1168
|
+
// Cloud storage: upload screenshots to tenant S3/R2 if configured
|
|
1169
|
+
const tenantStorageCfg = await getTenantStorageConfig(tenantId).catch(() => null);
|
|
1170
|
+
if (tenantStorageCfg) {
|
|
1171
|
+
let uploaded = 0;
|
|
1172
|
+
for (const screen of projectMap.screens as any[]) {
|
|
1173
|
+
for (const shot of (screen.screenshots ?? []) as any[]) {
|
|
1174
|
+
if (!shot.storagePath || shot.cloudUrl) continue;
|
|
1175
|
+
try {
|
|
1176
|
+
const filename = `${screen.id}-v${shot.version}.png`;
|
|
1177
|
+
const key = buildArtifactKey(tenantId, projectId, 'screenshots', filename, tenantStorageCfg.prefix);
|
|
1178
|
+
const cloudUrl = await uploadScreenshotToTenantStorage(tenantStorageCfg, shot.storagePath, key);
|
|
1179
|
+
await AppBrain.updateScreenshotCloudUrl(tenantId, shot.id, cloudUrl);
|
|
1180
|
+
uploaded++;
|
|
1181
|
+
} catch (uploadErr) {
|
|
1182
|
+
logger.warn({ screenId: screen.id, err: uploadErr }, 'Failed to upload screenshot to cloud storage');
|
|
1183
|
+
}
|
|
1184
|
+
}
|
|
1185
|
+
}
|
|
1186
|
+
if (uploaded > 0) logger.info({ uploaded, provider: tenantStorageCfg.provider }, 'Uploaded screenshots to cloud storage');
|
|
1187
|
+
|
|
1188
|
+
// Upload DOM snapshots and markdown to tenant storage
|
|
1189
|
+
const { existsSync } = await import('node:fs');
|
|
1190
|
+
let domUploaded = 0;
|
|
1191
|
+
let mdUploaded = 0;
|
|
1192
|
+
for (const screen of projectMap.screens as any[]) {
|
|
1193
|
+
// DOM snapshot
|
|
1194
|
+
const domPath = screen.domSnapshotPath;
|
|
1195
|
+
if (domPath && !domPath.startsWith('https://') && existsSync(domPath)) {
|
|
1196
|
+
try {
|
|
1197
|
+
const key = buildArtifactKey(tenantId, projectId, 'dom-snapshots', `${screen.id}.json`, tenantStorageCfg.prefix);
|
|
1198
|
+
const cloudUrl = await uploadFileToTenantStorage(tenantStorageCfg, domPath, key, 'application/json');
|
|
1199
|
+
await AppBrain.updateScreenDomSnapshot(tenantId, screen.id, domPath, cloudUrl);
|
|
1200
|
+
domUploaded++;
|
|
1201
|
+
} catch (err) {
|
|
1202
|
+
logger.warn({ screenId: screen.id, err }, 'Failed to upload DOM snapshot to cloud storage');
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
// Markdown extract
|
|
1206
|
+
const mdPath = screen.markdownPath;
|
|
1207
|
+
if (mdPath && !mdPath.startsWith('https://') && existsSync(mdPath)) {
|
|
1208
|
+
try {
|
|
1209
|
+
const key = buildArtifactKey(tenantId, projectId, 'markdown', `${screen.id}.md`, tenantStorageCfg.prefix);
|
|
1210
|
+
const cloudUrl = await uploadFileToTenantStorage(tenantStorageCfg, mdPath, key, 'text/markdown');
|
|
1211
|
+
await AppBrain.updateScreenMarkdownPath(tenantId, screen.id, cloudUrl);
|
|
1212
|
+
mdUploaded++;
|
|
1213
|
+
} catch (err) {
|
|
1214
|
+
logger.warn({ screenId: screen.id, err }, 'Failed to upload markdown to cloud storage');
|
|
1215
|
+
}
|
|
1216
|
+
}
|
|
1217
|
+
}
|
|
1218
|
+
if (domUploaded > 0) logger.info({ domUploaded, provider: tenantStorageCfg.provider }, 'Uploaded DOM snapshots to cloud storage');
|
|
1219
|
+
if (mdUploaded > 0) logger.info({ mdUploaded, provider: tenantStorageCfg.provider }, 'Uploaded markdown to cloud storage');
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
// AI screen grouping — clusters screens into semantic feature areas
|
|
1223
|
+
await groupScreensWithAI(tenantId, projectId, projectMap.screens as any, jobId, jobStartedAt);
|
|
1224
|
+
|
|
1225
|
+
// Auto-flag stale tests: mark PENDING_REVIEW when screen elements changed since test was generated
|
|
1226
|
+
try {
|
|
1227
|
+
await withTenant(tenantId, async (tx) => {
|
|
1228
|
+
const staleTests = await tx.$queryRaw<{ id: string }[]>`
|
|
1229
|
+
SELECT tc.id
|
|
1230
|
+
FROM "TestCase" tc
|
|
1231
|
+
JOIN "Screen" s ON tc."screenId" = s.id
|
|
1232
|
+
WHERE tc."tenantId" = ${tenantId}
|
|
1233
|
+
AND s."projectId" = ${projectId}
|
|
1234
|
+
AND s."elementHashChangedAt" IS NOT NULL
|
|
1235
|
+
AND tc."createdAt" IS NOT NULL
|
|
1236
|
+
AND s."elementHashChangedAt" > tc."createdAt"
|
|
1237
|
+
AND tc.status != 'PENDING_REVIEW'
|
|
1238
|
+
AND tc.status != 'RETIRED'
|
|
1239
|
+
`;
|
|
1240
|
+
if (staleTests.length > 0) {
|
|
1241
|
+
const ids = staleTests.map((t: { id: string }) => t.id);
|
|
1242
|
+
await tx.testCase.updateMany({
|
|
1243
|
+
where: { id: { in: ids } },
|
|
1244
|
+
data: { status: 'PENDING_REVIEW' },
|
|
1245
|
+
});
|
|
1246
|
+
logger.info({ count: staleTests.length, projectId }, 'Auto-flagged stale test cases as PENDING_REVIEW');
|
|
1247
|
+
}
|
|
1248
|
+
});
|
|
1249
|
+
} catch (staleErr) {
|
|
1250
|
+
logger.warn({ err: staleErr }, 'Failed to auto-flag stale tests');
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
const changed = (projectMap.screens as any[]).filter((s: any) => s.hasChange);
|
|
1254
|
+
if (changed.length > 0) {
|
|
1255
|
+
await investigateScreenChanges(tenantId, projectId, changed);
|
|
1256
|
+
}
|
|
1257
|
+
}
|
|
1258
|
+
} catch (skillErr) {
|
|
1259
|
+
logger.error({ projectId, err: skillErr }, 'Taxonomy generation failed');
|
|
1260
|
+
}
|
|
1261
|
+
});
|
|
1262
|
+
|
|
1263
|
+
} catch (err: any) {
|
|
1264
|
+
clearInterval(heartbeatTimer);
|
|
1265
|
+
runningControllers.delete(jobId);
|
|
1266
|
+
const aborted = String(err).includes('CRAWL_ABORTED');
|
|
1267
|
+
const authFailure = !aborted && (String(err).includes('AUTH_FAILURE') || String(err).includes('SESSION_EXPIRED'));
|
|
1268
|
+
const checkpoint = jobCheckpoints.get(jobId);
|
|
1269
|
+
jobCheckpoints.delete(jobId);
|
|
1270
|
+
|
|
1271
|
+
// Auth failed mid-crawl with work still pending — auto-requeue continuation job.
|
|
1272
|
+
// The crawler checkpoints the remaining queue before throwing, so checkpoint.pendingQueue
|
|
1273
|
+
// holds URLs not yet visited. skipUrls prevents re-crawling already-done pages.
|
|
1274
|
+
if (authFailure && (checkpoint?.pendingQueue?.length ?? 0) > 0) {
|
|
1275
|
+
const pendingAfterAuth: string[] = checkpoint!.pendingQueue!;
|
|
1276
|
+
logger.info({ pending: pendingAfterAuth.length }, '[crawl] auth failure mid-crawl — auto-enqueuing continuation with pending URLs');
|
|
1277
|
+
enqueueJob('CRAWL', {
|
|
1278
|
+
...config,
|
|
1279
|
+
startUrls: pendingAfterAuth,
|
|
1280
|
+
skipUrls: [...(config.skipUrls ?? []), ...(checkpoint!.visitedUrls ?? [])],
|
|
1281
|
+
}).catch((enqErr: any) => logger.warn({ err: enqErr?.message }, '[crawl] auth-failure auto-segment enqueue failed (non-fatal)'));
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
await recordJobFailure(tenantId, jobId, err, checkpoint, { isAborted: aborted });
|
|
1285
|
+
|
|
1286
|
+
// Notify on crawl failure (fire-and-forget)
|
|
1287
|
+
if (!aborted) {
|
|
1288
|
+
notifyAdmins(tenantId, {
|
|
1289
|
+
type: 'crawl.failed',
|
|
1290
|
+
title: 'Crawl failed',
|
|
1291
|
+
body: `Crawl for project failed: ${String(err)}`,
|
|
1292
|
+
metadata: { projectId, jobId, error: String(err) },
|
|
1293
|
+
}).catch(console.error);
|
|
1294
|
+
|
|
1295
|
+
// Dispatch outbound webhooks (fire-and-forget)
|
|
1296
|
+
dispatchWebhook(tenantId, projectId, 'crawl.failed', {
|
|
1297
|
+
jobId,
|
|
1298
|
+
error: String(err),
|
|
1299
|
+
}).catch(console.error);
|
|
1300
|
+
}
|
|
1301
|
+
} finally {
|
|
1302
|
+
runningControllers.delete(jobId);
|
|
1303
|
+
}
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
/** After a job finishes, sum LLMCallLog entries for that project during the job window. */
|
|
1307
|
+
export async function aggregateJobTokens(tenantId: string, jobId: string, projectId: string, startedAt: Date) {
|
|
1308
|
+
try {
|
|
1309
|
+
await withTenant(tenantId, async (tx) => {
|
|
1310
|
+
const rows = await tx.$queryRaw<any[]>`
|
|
1311
|
+
SELECT
|
|
1312
|
+
COALESCE(SUM("promptTokens"), 0)::INT AS "totalPromptTokens",
|
|
1313
|
+
COALESCE(SUM("completionTokens"), 0)::INT AS "totalCompletionTokens",
|
|
1314
|
+
COALESCE(SUM("cacheReadTokens"), 0)::INT AS "totalCacheReadTokens",
|
|
1315
|
+
COALESCE(SUM("estimatedCostUsd"), 0.0) AS "totalEstimatedCostUsd",
|
|
1316
|
+
COUNT(*)::INT AS "llmCallCount"
|
|
1317
|
+
FROM "LLMCallLog"
|
|
1318
|
+
WHERE "tenantId" = ${tenantId}
|
|
1319
|
+
AND "jobId" = ${jobId}
|
|
1320
|
+
`;
|
|
1321
|
+
const row = rows[0];
|
|
1322
|
+
if (!row || !row.llmCallCount) return;
|
|
1323
|
+
await tx.platformJob.update({
|
|
1324
|
+
where: { id: jobId },
|
|
1325
|
+
data: {
|
|
1326
|
+
totalPromptTokens: row.totalPromptTokens,
|
|
1327
|
+
totalCompletionTokens: row.totalCompletionTokens,
|
|
1328
|
+
totalCacheReadTokens: row.totalCacheReadTokens,
|
|
1329
|
+
totalEstimatedCostUsd: Number(row.totalEstimatedCostUsd),
|
|
1330
|
+
llmCallCount: row.llmCallCount,
|
|
1331
|
+
},
|
|
1332
|
+
});
|
|
1333
|
+
});
|
|
1334
|
+
} catch (err) {
|
|
1335
|
+
console.warn('[job-tokens] aggregation failed:', err);
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
async function processApiTestsJob(jobId: string, config: any) {
|
|
1340
|
+
const { tenantId, projectId } = config;
|
|
1341
|
+
const jobStartedAt = new Date();
|
|
1342
|
+
await withTenant(tenantId, (tx) =>
|
|
1343
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
|
|
1344
|
+
);
|
|
1345
|
+
try {
|
|
1346
|
+
const { generateApiTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@taodigital/agents');
|
|
1347
|
+
await updateJobProgress(tenantId, jobId, 20, 'Loading API contracts and endpoints…');
|
|
1348
|
+
const result = await generateApiTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
|
|
1349
|
+
await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} API test cases`);
|
|
1350
|
+
refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
|
|
1351
|
+
refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
|
|
1352
|
+
refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
|
|
1353
|
+
// GAP-007: auto-trigger script generation after API test cases are saved
|
|
1354
|
+
enqueueJob('GENERATE_SCRIPT', { tenantId, projectId, source: 'api_tests' }).catch((e) =>
|
|
1355
|
+
console.warn('[GAP-007] GENERATE_SCRIPT enqueue failed (non-fatal):', e?.message ?? e)
|
|
1356
|
+
);
|
|
1357
|
+
await withTenant(tenantId, (tx) =>
|
|
1358
|
+
tx.platformJob.update({
|
|
1359
|
+
where: { id: jobId },
|
|
1360
|
+
data: {
|
|
1361
|
+
status: 'DONE', progress: 100, finishedAt: new Date(),
|
|
1362
|
+
result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
|
|
1363
|
+
},
|
|
1364
|
+
})
|
|
1365
|
+
);
|
|
1366
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
|
|
1367
|
+
} catch (err: any) {
|
|
1368
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1369
|
+
}
|
|
1370
|
+
}
|
|
1371
|
+
|
|
1372
|
+
async function processSecurityTestsJob(jobId: string, config: any) {
|
|
1373
|
+
const { tenantId, projectId } = config;
|
|
1374
|
+
const jobStartedAt = new Date();
|
|
1375
|
+
await withTenant(tenantId, (tx) =>
|
|
1376
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
|
|
1377
|
+
);
|
|
1378
|
+
try {
|
|
1379
|
+
const { generateSecurityTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@taodigital/agents');
|
|
1380
|
+
await updateJobProgress(tenantId, jobId, 20, 'Mapping OWASP attack surface…');
|
|
1381
|
+
const result = await generateSecurityTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
|
|
1382
|
+
await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} security test cases`);
|
|
1383
|
+
refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
|
|
1384
|
+
refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
|
|
1385
|
+
refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
|
|
1386
|
+
await withTenant(tenantId, (tx) =>
|
|
1387
|
+
tx.platformJob.update({
|
|
1388
|
+
where: { id: jobId },
|
|
1389
|
+
data: {
|
|
1390
|
+
status: 'DONE', progress: 100, finishedAt: new Date(),
|
|
1391
|
+
result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
|
|
1392
|
+
},
|
|
1393
|
+
})
|
|
1394
|
+
);
|
|
1395
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
|
|
1396
|
+
} catch (err: any) {
|
|
1397
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
|
|
1401
|
+
async function processIntegrationTestsJob(jobId: string, config: any) {
|
|
1402
|
+
const { tenantId, projectId } = config;
|
|
1403
|
+
const jobStartedAt = new Date();
|
|
1404
|
+
await withTenant(tenantId, (tx) =>
|
|
1405
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
|
|
1406
|
+
);
|
|
1407
|
+
try {
|
|
1408
|
+
const { generateIntegrationTests, refreshCoverageMatrix, refreshTestCaseInventory } = await import('@taodigital/agents');
|
|
1409
|
+
await updateJobProgress(tenantId, jobId, 20, 'Analysing API contracts and data models…');
|
|
1410
|
+
const result = await generateIntegrationTests({ tenantId, projectId, apiEndpoints: config.apiEndpoints });
|
|
1411
|
+
await updateJobProgress(tenantId, jobId, 90, `Generated ${result.cases?.length ?? 0} integration test cases`);
|
|
1412
|
+
refreshCoverageMatrix(tenantId, projectId).catch((e) => console.warn('[coverage-matrix]', e));
|
|
1413
|
+
refreshTestCaseInventory(tenantId, projectId).catch((e) => console.warn('[tc-inventory]', e));
|
|
1414
|
+
refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
|
|
1415
|
+
await withTenant(tenantId, (tx) =>
|
|
1416
|
+
tx.platformJob.update({
|
|
1417
|
+
where: { id: jobId },
|
|
1418
|
+
data: {
|
|
1419
|
+
status: 'DONE', progress: 100, finishedAt: new Date(),
|
|
1420
|
+
result: { cases: result.cases?.length ?? 0, suiteName: result.suiteName } as any,
|
|
1421
|
+
},
|
|
1422
|
+
})
|
|
1423
|
+
);
|
|
1424
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
|
|
1425
|
+
} catch (err: any) {
|
|
1426
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
async function processFigmaImportJob(jobId: string, config: any) {
|
|
1431
|
+
const { tenantId, projectId, fileKey } = config;
|
|
1432
|
+
await withTenant(tenantId, (tx) =>
|
|
1433
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
1434
|
+
);
|
|
1435
|
+
try {
|
|
1436
|
+
// Prefer OAuth token (connected via Figma OAuth flow), fall back to PAT connector.
|
|
1437
|
+
const oauthConn = await AppBrain.getOAuthConnection(tenantId, projectId, 'FIGMA');
|
|
1438
|
+
let creds: figma.FigmaCredentials;
|
|
1439
|
+
const resolvedFileKey = fileKey ?? '';
|
|
1440
|
+
if (!resolvedFileKey) throw new Error('No Figma file key. Paste the full Figma file URL as the App URL.');
|
|
1441
|
+
|
|
1442
|
+
if (oauthConn?.accessToken && oauthConn.status === 'CONNECTED') {
|
|
1443
|
+
// OAuth token must use Authorization: Bearer header (oauthToken field), not X-Figma-Token
|
|
1444
|
+
creds = { accessToken: '', oauthToken: oauthConn.accessToken, fileKey: resolvedFileKey };
|
|
1445
|
+
} else {
|
|
1446
|
+
const connector = await withTenant(tenantId, (tx) =>
|
|
1447
|
+
(tx as any).connector.findFirst({ where: { projectId, kind: 'FIGMA', tenantId } })
|
|
1448
|
+
) as any;
|
|
1449
|
+
if (!connector) throw new Error('Figma connector not configured. Add your Figma token in Project Settings → Integrations.');
|
|
1450
|
+
const cfg = connector.config as Record<string, string>;
|
|
1451
|
+
const pat = cfg.accessToken_enc ? decrypt(cfg.accessToken_enc) : '';
|
|
1452
|
+
if (!pat) throw new Error('Figma access token missing. Edit the Figma connector and add your Personal Access Token.');
|
|
1453
|
+
creds = { accessToken: pat, fileKey: resolvedFileKey };
|
|
1454
|
+
}
|
|
1455
|
+
|
|
1456
|
+
await updateJobProgress(tenantId, jobId, 5, 'Listing frames from Figma file…');
|
|
1457
|
+
const frames = await figma.listScreens(creds, resolvedFileKey);
|
|
1458
|
+
if (frames.length === 0) {
|
|
1459
|
+
await withTenant(tenantId, (tx) =>
|
|
1460
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, result: { screensImported: 0 } as any, finishedAt: new Date() } })
|
|
1461
|
+
);
|
|
1462
|
+
return;
|
|
1463
|
+
}
|
|
1464
|
+
|
|
1465
|
+
await updateJobProgress(tenantId, jobId, 15, `Fetching images for ${frames.length} frames…`);
|
|
1466
|
+
const nodeIds = frames.map((f: any) => f.id);
|
|
1467
|
+
const imageUrls = await figma.getScreenImages(creds, resolvedFileKey, nodeIds, 1);
|
|
1468
|
+
|
|
1469
|
+
const screenshotDir = path.join(platformConfig.screenshotDir, projectId);
|
|
1470
|
+
await fs.mkdir(screenshotDir, { recursive: true });
|
|
1471
|
+
const tenantStorageCfg = await getTenantStorageConfig(tenantId).catch(() => null);
|
|
1472
|
+
|
|
1473
|
+
let saved = 0;
|
|
1474
|
+
for (const frame of frames) {
|
|
1475
|
+
try {
|
|
1476
|
+
const pct = Math.round(15 + ((saved / frames.length) * 80));
|
|
1477
|
+
await updateJobProgress(tenantId, jobId, pct, `Saving frame ${saved + 1}/${frames.length}: ${(frame as any).name}`);
|
|
1478
|
+
const screen = await AppBrain.saveScreen(tenantId, projectId, (frame as any).name, `figma://file/${resolvedFileKey}/node/${(frame as any).id}`);
|
|
1479
|
+
const imgUrl = (imageUrls as any)[(frame as any).id];
|
|
1480
|
+
if (imgUrl) {
|
|
1481
|
+
const imgRes = await fetch(imgUrl);
|
|
1482
|
+
if (imgRes.ok) {
|
|
1483
|
+
const buf = Buffer.from(await imgRes.arrayBuffer());
|
|
1484
|
+
const filename = `${screen.id}-v1.png`;
|
|
1485
|
+
const storagePath = path.join(screenshotDir, filename);
|
|
1486
|
+
await fs.writeFile(storagePath, buf);
|
|
1487
|
+
let cloudUrl: string | undefined;
|
|
1488
|
+
if (tenantStorageCfg) {
|
|
1489
|
+
try {
|
|
1490
|
+
const key = buildArtifactKey(tenantId, projectId, 'screenshots', filename, tenantStorageCfg.prefix);
|
|
1491
|
+
cloudUrl = (await uploadScreenshotToTenantStorage(tenantStorageCfg, storagePath, key)) ?? undefined;
|
|
1492
|
+
} catch (e) {
|
|
1493
|
+
console.warn('[figma-import] cloud upload failed:', e);
|
|
1494
|
+
}
|
|
1495
|
+
}
|
|
1496
|
+
const w = (frame as any).boundingBox?.width ?? 1440;
|
|
1497
|
+
const viewport = w <= 480 ? 'MOBILE_PORTRAIT' : w <= 1024 ? 'TABLET' : 'DESKTOP';
|
|
1498
|
+
await AppBrain.saveScreenshot(tenantId, projectId, screen.id, storagePath, 1, viewport, cloudUrl);
|
|
1499
|
+
}
|
|
1500
|
+
}
|
|
1501
|
+
|
|
1502
|
+
// Extract elements from Figma frame node → save for grounding + test generation
|
|
1503
|
+
if ((frame as any).node) {
|
|
1504
|
+
const figmaElements = figma.extractElements((frame as any).node);
|
|
1505
|
+
for (const el of figmaElements) {
|
|
1506
|
+
const role = el.type === 'COMPONENT' || el.type === 'COMPONENT_SET' ? 'COMPONENT'
|
|
1507
|
+
: el.type === 'INSTANCE' ? 'COMPONENT'
|
|
1508
|
+
: el.type === 'TEXT' ? 'TEXT'
|
|
1509
|
+
: el.type === 'FRAME' || el.type === 'GROUP' ? 'REGION'
|
|
1510
|
+
: el.type;
|
|
1511
|
+
const boundingRect = el.boundingBox
|
|
1512
|
+
? { x: Math.round(el.boundingBox.x), y: Math.round(el.boundingBox.y), width: Math.round(el.boundingBox.width), height: Math.round(el.boundingBox.height) }
|
|
1513
|
+
: undefined;
|
|
1514
|
+
await AppBrain.saveElement(
|
|
1515
|
+
tenantId, projectId, screen.id,
|
|
1516
|
+
el.name, role, undefined,
|
|
1517
|
+
el.description ?? undefined, undefined,
|
|
1518
|
+
el.isInteractive,
|
|
1519
|
+
boundingRect, undefined, undefined,
|
|
1520
|
+
);
|
|
1521
|
+
}
|
|
1522
|
+
}
|
|
1523
|
+
|
|
1524
|
+
saved++;
|
|
1525
|
+
} catch (err) {
|
|
1526
|
+
console.warn(`[figma-import] Failed to save frame:`, err);
|
|
1527
|
+
}
|
|
1528
|
+
}
|
|
1529
|
+
|
|
1530
|
+
await withTenant(tenantId, (tx) =>
|
|
1531
|
+
tx.platformJob.update({
|
|
1532
|
+
where: { id: jobId },
|
|
1533
|
+
data: { status: 'DONE', progress: 100, result: { screensImported: saved, totalFrames: frames.length } as any, finishedAt: new Date() },
|
|
1534
|
+
})
|
|
1535
|
+
);
|
|
1536
|
+
|
|
1537
|
+
// Post-import: run AI grouping + taxonomy skill files (same as post-crawl)
|
|
1538
|
+
setImmediate(async () => {
|
|
1539
|
+
try {
|
|
1540
|
+
const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
|
|
1541
|
+
if (projectMap?.screens?.length) {
|
|
1542
|
+
await generateTaxonomySkillFiles(tenantId, projectId, projectMap.screens as any);
|
|
1543
|
+
await groupScreensWithAI(tenantId, projectId, projectMap.screens as any, jobId, new Date());
|
|
1544
|
+
}
|
|
1545
|
+
} catch (err) {
|
|
1546
|
+
console.error('[figma-import] post-import grouping failed:', err);
|
|
1547
|
+
}
|
|
1548
|
+
});
|
|
1549
|
+
|
|
1550
|
+
} catch (err: any) {
|
|
1551
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1552
|
+
}
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
async function processNativeCrawlJob(jobId: string, config: any) {
|
|
1556
|
+
const { tenantId, projectId } = config;
|
|
1557
|
+
const jobStartedAt = new Date();
|
|
1558
|
+
try {
|
|
1559
|
+
const platform = config.nativePlatform as 'android' | 'ios' | 'windows' | 'macos' | undefined;
|
|
1560
|
+
if (!platform) throw new Error('Native crawl blocked: nativePlatform is required.');
|
|
1561
|
+
|
|
1562
|
+
const build = await withTenant(tenantId, (tx) =>
|
|
1563
|
+
(tx as any).nativeAppBuild.findFirst({
|
|
1564
|
+
where: { tenantId, projectId, platform },
|
|
1565
|
+
orderBy: { uploadedAt: 'desc' },
|
|
1566
|
+
})
|
|
1567
|
+
) as { platform: string; fileFormat: string; s3Path: string; packageName: string | null } | null;
|
|
1568
|
+
|
|
1569
|
+
if (!build) throw new Error(`Native crawl blocked: no ${platform} app build found for project.`);
|
|
1570
|
+
|
|
1571
|
+
// AAB requires bundletool conversion — fail early with a clear message
|
|
1572
|
+
if (build.fileFormat === 'aab') {
|
|
1573
|
+
throw new Error(
|
|
1574
|
+
'AAB format cannot be installed directly by Appium. Convert to APK using bundletool first, then re-upload the APK.'
|
|
1575
|
+
);
|
|
1576
|
+
}
|
|
1577
|
+
|
|
1578
|
+
// Persist device targeting info on the job record
|
|
1579
|
+
const deviceFarm = (config.deviceFarm ?? 'local_emulator') as 'local_emulator' | 'aws_device_farm' | 'browserstack';
|
|
1580
|
+
await withTenant(tenantId, (tx) =>
|
|
1581
|
+
(tx as any).platformJob.update({
|
|
1582
|
+
where: { id: jobId },
|
|
1583
|
+
data: {
|
|
1584
|
+
deviceModel: config.deviceModel ?? null,
|
|
1585
|
+
osVersion: config.osVersion ?? null,
|
|
1586
|
+
deviceFarm,
|
|
1587
|
+
},
|
|
1588
|
+
})
|
|
1589
|
+
).catch(() => { });
|
|
1590
|
+
|
|
1591
|
+
const workspaceDeviceFarm = await AppBrain.getTenantDeviceFarmConfig(tenantId).catch(() => null);
|
|
1592
|
+
if (deviceFarm === 'browserstack' && (!workspaceDeviceFarm?.browserstackUsername || !workspaceDeviceFarm?.browserstackAccessKey)) {
|
|
1593
|
+
throw new Error('Native crawl blocked: BrowserStack device farm is not configured for this workspace.');
|
|
1594
|
+
}
|
|
1595
|
+
if (deviceFarm === 'aws_device_farm') {
|
|
1596
|
+
throw new Error('Native crawl blocked: AWS Device Farm execution is not implemented yet. Use Local / Emulator or BrowserStack.');
|
|
1597
|
+
}
|
|
1598
|
+
|
|
1599
|
+
await runNativeCrawl({
|
|
1600
|
+
tenantId,
|
|
1601
|
+
projectId,
|
|
1602
|
+
jobId,
|
|
1603
|
+
platform,
|
|
1604
|
+
appS3Path: build.s3Path,
|
|
1605
|
+
packageName: build.packageName ?? undefined,
|
|
1606
|
+
deviceModel: config.deviceModel,
|
|
1607
|
+
osVersion: config.osVersion,
|
|
1608
|
+
deviceFarm,
|
|
1609
|
+
appiumServerUrl: workspaceDeviceFarm?.appiumServerUrl,
|
|
1610
|
+
browserstackUsername: workspaceDeviceFarm?.browserstackUsername,
|
|
1611
|
+
browserstackAccessKey: workspaceDeviceFarm?.browserstackAccessKey,
|
|
1612
|
+
awsAccessKeyId: workspaceDeviceFarm?.awsAccessKeyId,
|
|
1613
|
+
awsSecretAccessKey: workspaceDeviceFarm?.awsSecretAccessKey,
|
|
1614
|
+
awsRegion: workspaceDeviceFarm?.awsRegion,
|
|
1615
|
+
awsDeviceFarmProjectArn: workspaceDeviceFarm?.awsDeviceFarmProjectArn,
|
|
1616
|
+
});
|
|
1617
|
+
|
|
1618
|
+
// Post-crawl: generate taxonomy skill files + AI screen grouping (mirrors web crawl processJob)
|
|
1619
|
+
setImmediate(async () => {
|
|
1620
|
+
try {
|
|
1621
|
+
const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
|
|
1622
|
+
const screens = (projectMap?.screens ?? []) as any[];
|
|
1623
|
+
if (screens.length > 0) {
|
|
1624
|
+
await generateTaxonomySkillFiles(tenantId, projectId, screens);
|
|
1625
|
+
await groupScreensWithAI(tenantId, projectId, screens, jobId, jobStartedAt);
|
|
1626
|
+
|
|
1627
|
+
// Auto-flag stale tests: mark PENDING_REVIEW when screen elements changed since test was generated
|
|
1628
|
+
try {
|
|
1629
|
+
await withTenant(tenantId, async (tx) => {
|
|
1630
|
+
const staleTests = await tx.$queryRaw<{ id: string }[]>`
|
|
1631
|
+
SELECT tc.id
|
|
1632
|
+
FROM "TestCase" tc
|
|
1633
|
+
JOIN "Screen" s ON tc."screenId" = s.id
|
|
1634
|
+
WHERE tc."tenantId" = ${tenantId}
|
|
1635
|
+
AND s."projectId" = ${projectId}
|
|
1636
|
+
AND s."elementHashChangedAt" IS NOT NULL
|
|
1637
|
+
AND tc."createdAt" IS NOT NULL
|
|
1638
|
+
AND s."elementHashChangedAt" > tc."createdAt"
|
|
1639
|
+
AND tc.status != 'PENDING_REVIEW'
|
|
1640
|
+
AND tc.status != 'RETIRED'
|
|
1641
|
+
`;
|
|
1642
|
+
if (staleTests.length > 0) {
|
|
1643
|
+
const ids = staleTests.map((t: { id: string }) => t.id);
|
|
1644
|
+
await tx.testCase.updateMany({
|
|
1645
|
+
where: { id: { in: ids } },
|
|
1646
|
+
data: { status: 'PENDING_REVIEW' },
|
|
1647
|
+
});
|
|
1648
|
+
logger.info({ count: staleTests.length, projectId }, 'Auto-flagged stale test cases as PENDING_REVIEW');
|
|
1649
|
+
}
|
|
1650
|
+
});
|
|
1651
|
+
} catch (staleErr) {
|
|
1652
|
+
logger.warn({ err: staleErr }, 'Failed to auto-flag stale tests');
|
|
1653
|
+
}
|
|
1654
|
+
}
|
|
1655
|
+
} catch (e) {
|
|
1656
|
+
logger.error({ err: e }, 'post-native-crawl processing failed');
|
|
1657
|
+
}
|
|
1658
|
+
});
|
|
1659
|
+
} catch (err: any) {
|
|
1660
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
async function processGenerateTestsFromReqsJob(jobId: string, config: any) {
|
|
1665
|
+
const { tenantId, projectId, reqIds, suiteId, suiteName } = config;
|
|
1666
|
+
try {
|
|
1667
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading requirements');
|
|
1668
|
+
|
|
1669
|
+
const { askTracked, deterministicSeed, getTaskAgentLLMConfig } = await import('@taodigital/agents');
|
|
1670
|
+
const llmCfg = await getTaskAgentLLMConfig(tenantId, 'testGeneration');
|
|
1671
|
+
|
|
1672
|
+
const all = await AppBrain.listRequirements(tenantId, projectId, {}) as any[];
|
|
1673
|
+
let reqs = reqIds?.length
|
|
1674
|
+
? all.filter((r: any) => reqIds.includes(r.reqId))
|
|
1675
|
+
: all.filter((r: any) => r.status === 'unbuilt' || r.status === 'pending');
|
|
1676
|
+
|
|
1677
|
+
if (reqs.length === 0) {
|
|
1678
|
+
await updateJobProgress(tenantId, jobId, 100, 'No pending requirements found');
|
|
1679
|
+
await withTenant(tenantId, (tx) =>
|
|
1680
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { created: 0, skipped: 0 } as any } })
|
|
1681
|
+
);
|
|
1682
|
+
return;
|
|
1683
|
+
}
|
|
1684
|
+
|
|
1685
|
+
// Resolve or create suite
|
|
1686
|
+
let resolvedSuiteId = suiteId;
|
|
1687
|
+
if (!resolvedSuiteId) {
|
|
1688
|
+
const name = suiteName?.trim() || 'Requirements Tests';
|
|
1689
|
+
const suite = await withTenant(tenantId, async (tx) => {
|
|
1690
|
+
const existing = await (tx as any).testSuite.findFirst({ where: { tenantId, projectId, name } });
|
|
1691
|
+
if (existing) return existing;
|
|
1692
|
+
return (tx as any).testSuite.create({ data: { tenantId, projectId, name } });
|
|
1693
|
+
}) as any;
|
|
1694
|
+
resolvedSuiteId = suite.id;
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
// Resume from checkpoint if present
|
|
1698
|
+
const existingJob = await prismaAdmin.platformJob.findUnique({
|
|
1699
|
+
where: { id: jobId },
|
|
1700
|
+
select: { checkpoint: true },
|
|
1701
|
+
}).catch(() => null);
|
|
1702
|
+
const completedReqIds = new Set<string>((existingJob?.checkpoint as any)?.completedReqIds ?? []);
|
|
1703
|
+
if (completedReqIds.size > 0) {
|
|
1704
|
+
reqs = reqs.filter((r: any) => !completedReqIds.has(r.reqId));
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
await updateJobProgress(tenantId, jobId, 20, `Generating tests for ${reqs.length} requirements`);
|
|
1708
|
+
|
|
1709
|
+
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']);
|
|
1710
|
+
const VALID_PRIORITIES = new Set(['CRITICAL', 'HIGH', 'MEDIUM', 'LOW']);
|
|
1711
|
+
|
|
1712
|
+
// Process requirements in chunks of 5 with checkpointing
|
|
1713
|
+
const CHUNK_SIZE = 5;
|
|
1714
|
+
let totalCreated = (existingJob?.checkpoint as any)?.createdCount ?? 0;
|
|
1715
|
+
let totalSkipped = (existingJob?.checkpoint as any)?.skippedCount ?? 0;
|
|
1716
|
+
const finishedReqIds: string[] = Array.from(completedReqIds);
|
|
1717
|
+
|
|
1718
|
+
for (let i = 0; i < reqs.length; i += CHUNK_SIZE) {
|
|
1719
|
+
const chunk = reqs.slice(i, i + CHUNK_SIZE);
|
|
1720
|
+
const reqBlock = chunk.map((r: any) => [
|
|
1721
|
+
`## ${r.reqId}: ${r.title}`,
|
|
1722
|
+
`Priority: ${r.priority} | Type: ${r.type}`,
|
|
1723
|
+
r.acceptanceCriteria?.length ? `Acceptance Criteria:\n${r.acceptanceCriteria.map((c: string) => `- ${c}`).join('\n')}` : '',
|
|
1724
|
+
r.businessRules?.length ? `Business Rules:\n${r.businessRules.map((b: string) => `- ${b}`).join('\n')}` : '',
|
|
1725
|
+
].filter(Boolean).join('\n')).join('\n\n');
|
|
1726
|
+
|
|
1727
|
+
const system = `You are ZeTa-AI's test case generator. Convert requirements into structured test cases.
|
|
1728
|
+
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 } ] }
|
|
1729
|
+
Kind must be one of: POSITIVE, NEGATIVE, EDGE, SECURITY, ACCESSIBILITY, INTEGRATION, E2E, SMOKE, REGRESSION.
|
|
1730
|
+
Priority must be one of: CRITICAL, HIGH, MEDIUM, LOW.
|
|
1731
|
+
Generate 1-3 test cases per requirement (positive + negative + edge if applicable).
|
|
1732
|
+
Each test case must reference its reqRef (the requirement ID like REQ-001).`;
|
|
1733
|
+
|
|
1734
|
+
const user = `Generate test cases for these requirements:\n\n${reqBlock}`;
|
|
1735
|
+
|
|
1736
|
+
let parsed: { cases: any[] } = { cases: [] };
|
|
1737
|
+
try {
|
|
1738
|
+
const reqSeed = deterministicSeed(`req-cases:${chunk.map((r: any) => r.reqId).sort().join('|').slice(0, 300)}`);
|
|
1739
|
+
const { text, usage } = await askTracked(system, user, llmCfg, undefined, undefined, { temperature: 0, seed: reqSeed });
|
|
1740
|
+
if (usage) recordLLMCall({ tenantId, projectId, jobId, agentType: 'generate_tests_from_reqs', label: 'test_case_generation', usage }).catch(() => { });
|
|
1741
|
+
const json = text.match(/\{[\s\S]*\}/)?.[0];
|
|
1742
|
+
if (json) parsed = JSON.parse(json);
|
|
1743
|
+
} catch (e: any) {
|
|
1744
|
+
throw new Error('AI failed to generate test cases: ' + (e.message ?? 'unknown'));
|
|
1745
|
+
}
|
|
1746
|
+
|
|
1747
|
+
const normalized = (parsed.cases ?? []).map((c: any) => ({
|
|
1748
|
+
ref: c.reqRef ?? null,
|
|
1749
|
+
traceTo: c.reqRef ?? null,
|
|
1750
|
+
title: c.title || 'Untitled',
|
|
1751
|
+
kind: VALID_KINDS.has((c.kind ?? '').toUpperCase()) ? c.kind.toUpperCase() : 'POSITIVE',
|
|
1752
|
+
priority: VALID_PRIORITIES.has((c.priority ?? '').toUpperCase()) ? c.priority.toUpperCase() : 'MEDIUM',
|
|
1753
|
+
preconditions: c.preconditions ?? '',
|
|
1754
|
+
steps: Array.isArray(c.steps) ? c.steps : [],
|
|
1755
|
+
expectedResult: c.expectedResult ?? '',
|
|
1756
|
+
tags: Array.isArray(c.tags) ? c.tags : [],
|
|
1757
|
+
}));
|
|
1758
|
+
|
|
1759
|
+
const { created, skipped } = await AppBrain.importTestCasesFromArtifact(
|
|
1760
|
+
tenantId, projectId, resolvedSuiteId, normalized, { duplicateMode: 'skip' }
|
|
1761
|
+
);
|
|
1762
|
+
totalCreated += created.length;
|
|
1763
|
+
totalSkipped += (skipped ?? 0);
|
|
1764
|
+
|
|
1765
|
+
// Mark processed requirements as covered
|
|
1766
|
+
const coveredReqIds = new Set(normalized.map((c: any) => c.ref).filter(Boolean));
|
|
1767
|
+
await Promise.all(
|
|
1768
|
+
chunk
|
|
1769
|
+
.filter((r: any) => coveredReqIds.has(r.reqId))
|
|
1770
|
+
.map((r: any) => AppBrain.updateRequirement(tenantId, projectId, r.reqId, { status: 'covered' }).catch(() => { }))
|
|
1771
|
+
);
|
|
1772
|
+
|
|
1773
|
+
for (const r of chunk) finishedReqIds.push(r.reqId);
|
|
1774
|
+
|
|
1775
|
+
// Save checkpoint after chunk
|
|
1776
|
+
await prismaAdmin.platformJob.update({
|
|
1777
|
+
where: { id: jobId },
|
|
1778
|
+
data: {
|
|
1779
|
+
checkpoint: { completedReqIds: finishedReqIds, createdCount: totalCreated, skippedCount: totalSkipped } as any,
|
|
1780
|
+
checkpointAt: new Date(),
|
|
1781
|
+
},
|
|
1782
|
+
}).catch(() => {});
|
|
1783
|
+
|
|
1784
|
+
const progressPct = Math.round(20 + ((i + chunk.length) / reqs.length) * 75);
|
|
1785
|
+
await updateJobProgress(tenantId, jobId, progressPct, `Processed ${finishedReqIds.length}/${reqs.length} requirements (${totalCreated} cases generated)`);
|
|
1786
|
+
}
|
|
1787
|
+
|
|
1788
|
+
await withTenant(tenantId, (tx) =>
|
|
1789
|
+
tx.platformJob.update({
|
|
1790
|
+
where: { id: jobId },
|
|
1791
|
+
data: { status: 'DONE', finishedAt: new Date(), result: { created: totalCreated, skipped: totalSkipped, suiteId: resolvedSuiteId } as any, progress: 100 },
|
|
1792
|
+
})
|
|
1793
|
+
);
|
|
1794
|
+
} catch (e: any) {
|
|
1795
|
+
const msg = e?.message ?? 'Unknown error';
|
|
1796
|
+
logger.error({ jobId, err: msg }, 'processGenerateTestsFromReqsJob failed');
|
|
1797
|
+
await recordJobFailure(tenantId, jobId, e);
|
|
1798
|
+
}
|
|
1799
|
+
}
|
|
1800
|
+
|
|
1801
|
+
/**
|
|
1802
|
+
* Runs every APPROVED test case in a project (optionally scoped to one suite)
|
|
1803
|
+
* against the agent-free Playwright executor (test-executor.ts) and aggregates
|
|
1804
|
+
* the results into the TestRun row created synchronously by POST /run-tests
|
|
1805
|
+
* (see ci.ts) — this is what makes the CI gate (GET /test-results/latest)
|
|
1806
|
+
* finally reflect what CI itself triggered, instead of a stale or nonexistent
|
|
1807
|
+
* result from an unrelated, manually-triggered, agent-connected suite run.
|
|
1808
|
+
*/
|
|
1809
|
+
async function processRunTestSuiteJob(jobId: string, config: any) {
|
|
1810
|
+
const { tenantId, projectId, testRunId, suiteId, storageState, browser, shardIndex, totalShards } = config as any;
|
|
1811
|
+
const runStart = Date.now();
|
|
1812
|
+
|
|
1813
|
+
await withTenant(tenantId, (tx) =>
|
|
1814
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
1815
|
+
);
|
|
1816
|
+
|
|
1817
|
+
try {
|
|
1818
|
+
let testCases = await AppBrain.listTestCases(tenantId, projectId, {
|
|
1819
|
+
status: 'APPROVED',
|
|
1820
|
+
...(suiteId ? { suiteId } : {}),
|
|
1821
|
+
}) as Array<{ id: string }>;
|
|
1822
|
+
|
|
1823
|
+
// Shard filtering: when running a distributed matrix (CI-triggered multi-browser/shard),
|
|
1824
|
+
// each worker only executes its own slice — testCases[shardIndex::totalShards].
|
|
1825
|
+
if (typeof totalShards === 'number' && totalShards > 1 && typeof shardIndex === 'number') {
|
|
1826
|
+
testCases = testCases.filter((_, i) => i % totalShards === shardIndex);
|
|
1827
|
+
}
|
|
1828
|
+
|
|
1829
|
+
if (testCases.length === 0) {
|
|
1830
|
+
// Nothing approved to run isn't a CI failure — same as any test runner
|
|
1831
|
+
// reporting "0 tests, 0 failures" when a suite is empty.
|
|
1832
|
+
await AppBrain.completeTestRun(tenantId, testRunId, { total: 0, passed: 0, failed: 0, skipped: 0, duration: 0 });
|
|
1833
|
+
await withTenant(tenantId, (tx) =>
|
|
1834
|
+
tx.platformJob.update({
|
|
1835
|
+
where: { id: jobId },
|
|
1836
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { total: 0 } as any },
|
|
1837
|
+
})
|
|
1838
|
+
);
|
|
1839
|
+
return;
|
|
1840
|
+
}
|
|
1841
|
+
|
|
1842
|
+
const aiHealingEnabled = await isFeatureEnabled(tenantId, 'AI_SELF_HEALING');
|
|
1843
|
+
const SCREENSHOT_DIR = process.env.SCREENSHOT_DIR ?? '/tmp/zeta-screenshots';
|
|
1844
|
+
const screenshotDir = config.screenshotDir || platformConfig.screenshotDir || SCREENSHOT_DIR;
|
|
1845
|
+
const VALID_BROWSERS = ['chromium', 'firefox', 'webkit'];
|
|
1846
|
+
const validBrowser = VALID_BROWSERS.includes(browser) ? browser : 'chromium';
|
|
1847
|
+
|
|
1848
|
+
let passed = 0;
|
|
1849
|
+
let failed = 0;
|
|
1850
|
+
const runResults: Array<{ testCaseId: string; status: string }> = [];
|
|
1851
|
+
|
|
1852
|
+
// Resume from checkpoint if present
|
|
1853
|
+
const existingJob = await prismaAdmin.platformJob.findUnique({
|
|
1854
|
+
where: { id: jobId },
|
|
1855
|
+
select: { checkpoint: true },
|
|
1856
|
+
}).catch(() => null);
|
|
1857
|
+
const completedCaseIds = new Set<string>((existingJob?.checkpoint as any)?.completedCaseIds ?? []);
|
|
1858
|
+
if (completedCaseIds.size > 0) {
|
|
1859
|
+
testCases = testCases.filter((tc) => !completedCaseIds.has(tc.id));
|
|
1860
|
+
passed = (existingJob?.checkpoint as any)?.passed ?? 0;
|
|
1861
|
+
failed = (existingJob?.checkpoint as any)?.failed ?? 0;
|
|
1862
|
+
}
|
|
1863
|
+
|
|
1864
|
+
const allFinishedCaseIds: string[] = Array.from(completedCaseIds);
|
|
1865
|
+
|
|
1866
|
+
for (let i = 0; i < testCases.length; i += TEST_EXEC_CONCURRENCY) {
|
|
1867
|
+
const batch = testCases.slice(i, i + TEST_EXEC_CONCURRENCY);
|
|
1868
|
+
await Promise.all(batch.map(async (tc) => {
|
|
1869
|
+
try {
|
|
1870
|
+
const full = await AppBrain.getTestCaseForExecution(tenantId, tc.id) as any;
|
|
1871
|
+
const baseUrl = full?.screen?.project?.appUrl ?? '';
|
|
1872
|
+
const execProjectId = full?.screen?.project?.id ?? projectId;
|
|
1873
|
+
const dataRows: Array<{ id: string; rowIndex: number; data: Record<string, string> }> =
|
|
1874
|
+
full?.dataSet?.rows ?? [];
|
|
1875
|
+
|
|
1876
|
+
// Data-driven: run once per row (substituting placeholders). If no data set, run once with no substitution.
|
|
1877
|
+
const runs = dataRows.length > 0 ? dataRows : [null];
|
|
1878
|
+
|
|
1879
|
+
for (const row of runs) {
|
|
1880
|
+
let tcForPlan = full ?? tc;
|
|
1881
|
+
if (row !== null) {
|
|
1882
|
+
// Clone the test case with interpolated steps and title
|
|
1883
|
+
const rawSteps = Array.isArray(tcForPlan.steps) ? tcForPlan.steps as string[] : [];
|
|
1884
|
+
tcForPlan = {
|
|
1885
|
+
...tcForPlan,
|
|
1886
|
+
steps: rawSteps.map((s: string) => interpolatePlaceholders(s, row.data)),
|
|
1887
|
+
title: interpolatePlaceholders(tcForPlan.title ?? '', row.data),
|
|
1888
|
+
preconditions: tcForPlan.preconditions
|
|
1889
|
+
? interpolatePlaceholders(tcForPlan.preconditions, row.data)
|
|
1890
|
+
: tcForPlan.preconditions,
|
|
1891
|
+
};
|
|
1892
|
+
}
|
|
1893
|
+
|
|
1894
|
+
const plan = await generateExecutionPlan(tenantId, tcForPlan, baseUrl);
|
|
1895
|
+
const result = await executeTestPlan(plan, {
|
|
1896
|
+
screenshotDir,
|
|
1897
|
+
testRunId,
|
|
1898
|
+
maxRuns: 1,
|
|
1899
|
+
browser: validBrowser as 'chromium' | 'firefox' | 'webkit',
|
|
1900
|
+
storageState,
|
|
1901
|
+
healCtx: aiHealingEnabled ? { tenantId, projectId: execProjectId } : undefined,
|
|
1902
|
+
});
|
|
1903
|
+
const status = result.status === 'PASSED' ? 'PASSED' : result.status === 'ERROR' ? 'ERROR' : 'FAILED';
|
|
1904
|
+
if (status === 'PASSED') passed++; else failed++;
|
|
1905
|
+
runResults.push({ testCaseId: tc.id, status });
|
|
1906
|
+
await AppBrain.saveTestResult(tenantId, {
|
|
1907
|
+
runId: testRunId,
|
|
1908
|
+
testCaseId: tc.id,
|
|
1909
|
+
status,
|
|
1910
|
+
duration: result.totalDuration,
|
|
1911
|
+
...(result.rootCauseSummary
|
|
1912
|
+
? { failureAnalysis: result.rootCauseSummary, failureAnalysisAt: new Date() }
|
|
1913
|
+
: {}),
|
|
1914
|
+
...(row !== null ? { dataRowId: row.id, dataRowIndex: row.rowIndex } : {}),
|
|
1915
|
+
...((result.consoleLogs?.length || result.networkErrors?.length) ? {
|
|
1916
|
+
logs: {
|
|
1917
|
+
consoleLogs: result.consoleLogs ?? [],
|
|
1918
|
+
networkErrors: result.networkErrors ?? [],
|
|
1919
|
+
},
|
|
1920
|
+
} : {}),
|
|
1921
|
+
});
|
|
1922
|
+
}
|
|
1923
|
+
await AppBrain.recordFlakinessOutcome(tenantId, tc.id).catch(() => { });
|
|
1924
|
+
} catch (err: any) {
|
|
1925
|
+
failed++;
|
|
1926
|
+
runResults.push({ testCaseId: tc.id, status: 'ERROR' });
|
|
1927
|
+
await AppBrain.saveTestResult(tenantId, {
|
|
1928
|
+
runId: testRunId,
|
|
1929
|
+
testCaseId: tc.id,
|
|
1930
|
+
status: 'ERROR',
|
|
1931
|
+
error: String(err?.message ?? err).slice(0, 500),
|
|
1932
|
+
}).catch(() => { });
|
|
1933
|
+
}
|
|
1934
|
+
}));
|
|
1935
|
+
|
|
1936
|
+
for (const tc of batch) allFinishedCaseIds.push(tc.id);
|
|
1937
|
+
|
|
1938
|
+
// Save durable checkpoint after each batch
|
|
1939
|
+
await prismaAdmin.platformJob.update({
|
|
1940
|
+
where: { id: jobId },
|
|
1941
|
+
data: {
|
|
1942
|
+
checkpoint: { completedCaseIds: allFinishedCaseIds, passed, failed } as any,
|
|
1943
|
+
checkpointAt: new Date(),
|
|
1944
|
+
},
|
|
1945
|
+
}).catch(() => {});
|
|
1946
|
+
|
|
1947
|
+
await updateJobProgress(
|
|
1948
|
+
tenantId, jobId,
|
|
1949
|
+
Math.round((Math.min(i + TEST_EXEC_CONCURRENCY, testCases.length) / testCases.length) * 100),
|
|
1950
|
+
`Ran ${Math.min(i + TEST_EXEC_CONCURRENCY, testCases.length)}/${testCases.length} test cases`,
|
|
1951
|
+
);
|
|
1952
|
+
}
|
|
1953
|
+
|
|
1954
|
+
await AppBrain.completeTestRun(tenantId, testRunId, {
|
|
1955
|
+
total: testCases.length,
|
|
1956
|
+
passed,
|
|
1957
|
+
failed,
|
|
1958
|
+
skipped: 0,
|
|
1959
|
+
duration: Date.now() - runStart,
|
|
1960
|
+
});
|
|
1961
|
+
|
|
1962
|
+
await withTenant(tenantId, (tx) =>
|
|
1963
|
+
tx.platformJob.update({
|
|
1964
|
+
where: { id: jobId },
|
|
1965
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { total: testCases.length, passed, failed } as any },
|
|
1966
|
+
})
|
|
1967
|
+
);
|
|
1968
|
+
|
|
1969
|
+
// Same full fan-out as the interactive web-driven run path (in-app,
|
|
1970
|
+
// generic webhook, suite-owner failure emails, GitHub check-run, Slack,
|
|
1971
|
+
// Teams, alert emails on failure) — a CI-triggered run has nobody
|
|
1972
|
+
// watching the SSE stream, so this is the only place these fire from.
|
|
1973
|
+
notifyRunCompletion(
|
|
1974
|
+
tenantId, projectId, testRunId,
|
|
1975
|
+
failed === 0 ? 'COMPLETED' : 'FAILED',
|
|
1976
|
+
{ passed, failed, total: testCases.length },
|
|
1977
|
+
runResults,
|
|
1978
|
+
).catch(console.error);
|
|
1979
|
+
refreshTestExecutionHistorySkillFile(tenantId, projectId).catch(console.error);
|
|
1980
|
+
} catch (err: any) {
|
|
1981
|
+
const msg = String(err?.message ?? err).slice(0, 500);
|
|
1982
|
+
logger.error({ jobId, testRunId, err: msg }, 'processRunTestSuiteJob failed');
|
|
1983
|
+
await AppBrain.failTestRun(tenantId, testRunId, msg).catch(() => { });
|
|
1984
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
1985
|
+
}
|
|
1986
|
+
}
|
|
1987
|
+
|
|
1988
|
+
async function processGenerateSkillFilesJob(jobId: string, config: any) {
|
|
1989
|
+
const { tenantId, projectId } = config;
|
|
1990
|
+
await withTenant(tenantId, (tx) =>
|
|
1991
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
1992
|
+
);
|
|
1993
|
+
try {
|
|
1994
|
+
await updateJobProgress(tenantId, jobId, 10, 'Loading project data…');
|
|
1995
|
+
const projectMap = await AppBrain.getProjectMap(tenantId, projectId);
|
|
1996
|
+
if (!projectMap) throw new Error('Project not found.');
|
|
1997
|
+
const screens = (projectMap.screens ?? []) as any[];
|
|
1998
|
+
// Manual regeneration has no fresh crawl result — reuse the metrics and
|
|
1999
|
+
// endpoints persisted on the last completed crawl job so the Performance
|
|
2000
|
+
// Baseline and API Contract aren't wiped to "no data captured".
|
|
2001
|
+
const lastCrawl = await withTenant(tenantId, (tx) =>
|
|
2002
|
+
tx.platformJob.findFirst({
|
|
2003
|
+
where: { projectId, type: 'CRAWL', status: 'DONE' },
|
|
2004
|
+
orderBy: { finishedAt: 'desc' },
|
|
2005
|
+
select: { result: true },
|
|
2006
|
+
})
|
|
2007
|
+
);
|
|
2008
|
+
const lastResult = ((lastCrawl as any)?.result ?? {}) as any;
|
|
2009
|
+
await updateJobProgress(tenantId, jobId, 25, `Generating ${screens.length} app intelligence skill files…`);
|
|
2010
|
+
await generateTaxonomySkillFiles(tenantId, projectId, screens, lastResult.apiEndpoints, lastResult.performanceMetrics);
|
|
2011
|
+
await updateJobProgress(tenantId, jobId, 85, 'Refreshing testing intelligence skill files…');
|
|
2012
|
+
await Promise.allSettled([
|
|
2013
|
+
refreshTestCasesSkillFile(tenantId, projectId),
|
|
2014
|
+
refreshTestDataSkillFile(tenantId, projectId),
|
|
2015
|
+
refreshTestScriptSkillFile(tenantId, projectId),
|
|
2016
|
+
refreshRequirementsCoverageSkillFile(tenantId, projectId),
|
|
2017
|
+
refreshTestExecutionHistorySkillFile(tenantId, projectId),
|
|
2018
|
+
refreshVisualRegressionHistorySkillFile(tenantId, projectId),
|
|
2019
|
+
refreshLocatorStrategyWithHealingData(tenantId, projectId),
|
|
2020
|
+
refreshFieldCatalogSkillFile(tenantId, projectId),
|
|
2021
|
+
]);
|
|
2022
|
+
await withTenant(tenantId, (tx) =>
|
|
2023
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, finishedAt: new Date() } })
|
|
2024
|
+
);
|
|
2025
|
+
} catch (err: any) {
|
|
2026
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
|
|
2030
|
+
// DATA_RETENTION_PURGE — deletes AuditLog rows older than each tenant's
|
|
2031
|
+
// dataRetentionDays setting (default 365), and LLMCallLog rows older than 90
|
|
2032
|
+
// days (fixed, no per-tenant override). Runs once daily via the cron in
|
|
2033
|
+
// worker.ts. The job has no tenantId/projectId — it sweeps all tenants so
|
|
2034
|
+
// enqueueJob() is not used; the worker.ts cron calls this directly.
|
|
2035
|
+
export async function processDataRetentionPurge(): Promise<void> {
|
|
2036
|
+
logger.info('[data-retention] starting purge run');
|
|
2037
|
+
|
|
2038
|
+
// LLMCallLog: fixed 90-day retention across all tenants (uses calledAt, not createdAt)
|
|
2039
|
+
const llmCutoff = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
|
|
2040
|
+
const llmResult = await prismaAdmin.lLMCallLog.deleteMany({
|
|
2041
|
+
where: { calledAt: { lt: llmCutoff } },
|
|
2042
|
+
});
|
|
2043
|
+
logger.info({ deleted: llmResult.count }, '[data-retention] LLMCallLog purged');
|
|
2044
|
+
|
|
2045
|
+
// AuditLog: per-tenant retention via TenantSetting.dataRetentionDays
|
|
2046
|
+
const tenants = await prismaAdmin.tenant.findMany({ select: { id: true } });
|
|
2047
|
+
let auditTotal = 0;
|
|
2048
|
+
|
|
2049
|
+
for (const { id: tenantId } of tenants) {
|
|
2050
|
+
// Find the most restrictive (lowest) dataRetentionDays across this tenant's
|
|
2051
|
+
// settings rows, falling back to 365 if no setting row exists.
|
|
2052
|
+
const setting = await prismaAdmin.tenantSetting.findFirst({
|
|
2053
|
+
where: { tenantId },
|
|
2054
|
+
orderBy: { dataRetentionDays: 'asc' },
|
|
2055
|
+
select: { dataRetentionDays: true },
|
|
2056
|
+
});
|
|
2057
|
+
const retentionDays = setting?.dataRetentionDays ?? (parseInt(process.env.DEFAULT_DATA_RETENTION_DAYS ?? '') || 365);
|
|
2058
|
+
const cutoff = new Date(Date.now() - retentionDays * 24 * 60 * 60 * 1000);
|
|
2059
|
+
|
|
2060
|
+
const result = await prismaAdmin.auditLog.deleteMany({
|
|
2061
|
+
where: { tenantId, createdAt: { lt: cutoff } },
|
|
2062
|
+
});
|
|
2063
|
+
auditTotal += result.count;
|
|
2064
|
+
}
|
|
2065
|
+
|
|
2066
|
+
logger.info({ deleted: auditTotal, tenants: tenants.length }, '[data-retention] AuditLog purged');
|
|
2067
|
+
|
|
2068
|
+
// AuthSession: fixed 12-month retention — IP addresses are PII under GDPR.
|
|
2069
|
+
// Only purge revoked sessions; active (non-revoked) sessions are kept.
|
|
2070
|
+
const SESSION_RETENTION_DAYS = 365;
|
|
2071
|
+
const sessionCutoff = new Date(Date.now() - SESSION_RETENTION_DAYS * 24 * 60 * 60_000);
|
|
2072
|
+
const sessionResult = await prismaAdmin.authSession.deleteMany({
|
|
2073
|
+
where: {
|
|
2074
|
+
createdAt: { lt: sessionCutoff },
|
|
2075
|
+
revokedAt: { not: null },
|
|
2076
|
+
},
|
|
2077
|
+
});
|
|
2078
|
+
logger.info({ deleted: sessionResult.count }, '[data-retention] AuthSession purged');
|
|
2079
|
+
|
|
2080
|
+
// PlatformJob: delete completed jobs older than 90 days (GAP-24)
|
|
2081
|
+
const ninetyDaysAgo = new Date(Date.now() - 90 * 24 * 60 * 60 * 1000);
|
|
2082
|
+
const deletedJobs = await prismaAdmin.platformJob.deleteMany({
|
|
2083
|
+
where: {
|
|
2084
|
+
status: { in: ['DONE', 'FAILED'] },
|
|
2085
|
+
dlq: false,
|
|
2086
|
+
inline: false,
|
|
2087
|
+
finishedAt: { lt: ninetyDaysAgo },
|
|
2088
|
+
},
|
|
2089
|
+
});
|
|
2090
|
+
if (deletedJobs.count > 0) {
|
|
2091
|
+
logger.info({ count: deletedJobs.count }, '[data-retention] deleted old completed jobs');
|
|
2092
|
+
}
|
|
2093
|
+
}
|
|
2094
|
+
|
|
2095
|
+
// ── URL Discovery Job ─────────────────────────────────────────────────────────
|
|
2096
|
+
// Three-phase URL discovery: sitemap seed → unauthenticated BFS spider → authenticated BFS
|
|
2097
|
+
// spider (when crawl credentials exist). Persists discovered URLs to crawlConfig and marks the
|
|
2098
|
+
// job DONE with the full URL list so the UI can poll for results.
|
|
2099
|
+
|
|
2100
|
+
async function processDiscoverJob(jobId: string, config: any, opts?: ProcessJobOpts) {
|
|
2101
|
+
const { tenantId, projectId } = config;
|
|
2102
|
+
|
|
2103
|
+
const controller = new AbortController();
|
|
2104
|
+
runningControllers.set(jobId, controller);
|
|
2105
|
+
|
|
2106
|
+
// Independent heartbeat timer — keeps heartbeatAt fresh even when no URLs are
|
|
2107
|
+
// arriving (e.g. during auth login, page-load waits, 2FA handling).
|
|
2108
|
+
const heartbeatTimer = setInterval(() => {
|
|
2109
|
+
void heartbeatJob(tenantId, jobId);
|
|
2110
|
+
}, JOB_HEARTBEAT_INTERVAL_MS);
|
|
2111
|
+
|
|
2112
|
+
// Shared accumulator — updated by onUrlsDiscovered callback as each page is visited.
|
|
2113
|
+
// This lets the frontend poll and see a growing list before the job finishes.
|
|
2114
|
+
const allUrls = new Set<string>();
|
|
2115
|
+
let lastPartialFlush = 0;
|
|
2116
|
+
let lastFlushedPct = 0; // high-water mark — progress never decreases
|
|
2117
|
+
|
|
2118
|
+
const flushPartialUrls = async (pct: number, step: string) => {
|
|
2119
|
+
const now = Date.now();
|
|
2120
|
+
// Flush to DB at most every 5 seconds to avoid excessive writes
|
|
2121
|
+
if (now - lastPartialFlush < 5_000 && allUrls.size < 5) return;
|
|
2122
|
+
const monotonic = Math.max(pct, lastFlushedPct);
|
|
2123
|
+
lastFlushedPct = monotonic;
|
|
2124
|
+
lastPartialFlush = now;
|
|
2125
|
+
try {
|
|
2126
|
+
await withTenant(tenantId, (tx) =>
|
|
2127
|
+
tx.platformJob.update({
|
|
2128
|
+
where: { id: jobId },
|
|
2129
|
+
data: { progress: monotonic, result: { step, partialUrls: Array.from(allUrls) } as any, heartbeatAt: new Date() },
|
|
2130
|
+
})
|
|
2131
|
+
);
|
|
2132
|
+
} catch { /* non-fatal */ }
|
|
2133
|
+
await opts?.onProgress?.(monotonic);
|
|
2134
|
+
};
|
|
2135
|
+
|
|
2136
|
+
const onProgress = async (pct: number, step: string) => {
|
|
2137
|
+
await updateJobProgress(tenantId, jobId, pct, step);
|
|
2138
|
+
await opts?.onProgress?.(pct);
|
|
2139
|
+
};
|
|
2140
|
+
|
|
2141
|
+
try {
|
|
2142
|
+
// Mark RUNNING inside the try block so any DB error is caught by the internal
|
|
2143
|
+
// handler below (which writes result.error). If this were before the try block,
|
|
2144
|
+
// a DB failure would bubble up to dispatchClaimedJob's catch, which writes to
|
|
2145
|
+
// the `error` column instead of `result.error` — the frontend would then show
|
|
2146
|
+
// "Unknown error" rather than the actual message.
|
|
2147
|
+
await withTenant(tenantId, (tx) =>
|
|
2148
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
2149
|
+
);
|
|
2150
|
+
// Load decrypted project crawl config for credentials/proxy/sitemap settings.
|
|
2151
|
+
// Reading Project.crawlConfig directly leaves encrypted fields as *_enc, so
|
|
2152
|
+
// discovery would see username but miss password/storageState/authToken.
|
|
2153
|
+
const crawlCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => null) ?? {};
|
|
2154
|
+
const appUrl: string = config.appUrl ?? crawlCfg.appUrl;
|
|
2155
|
+
if (!appUrl) throw new Error('No app URL configured. Save the crawl settings first.');
|
|
2156
|
+
|
|
2157
|
+
const { getSystemConfig } = await import('@taodigital/core');
|
|
2158
|
+
const crawlTuning = await getSystemConfig('crawl_tuning');
|
|
2159
|
+
const maxDiscoverUrls: number = config.maxDiscoverUrls ?? parseInt(String(crawlTuning?.maxDiscoverUrls ?? '2000'), 10);
|
|
2160
|
+
const proxyUrl: string | undefined = config.proxyUrl ?? crawlCfg.proxyUrl;
|
|
2161
|
+
const screenshotDir = os.tmpdir();
|
|
2162
|
+
const discoverStorageConfig = await getTenantStorageConfig(tenantId).catch(() => null);
|
|
2163
|
+
|
|
2164
|
+
await onProgress(3, 'Seeding from sitemap/robots.txt…');
|
|
2165
|
+
|
|
2166
|
+
// Phase 1 — sitemap + robots.txt seed (fast, no browser)
|
|
2167
|
+
const sitemapResult = await discoverProjectUrls(appUrl, {
|
|
2168
|
+
sitemapUrl: config.sitemapUrl ?? crawlCfg.sitemapUrl,
|
|
2169
|
+
proxyUrl,
|
|
2170
|
+
}).catch(() => ({ candidates: [] as Array<{ url: string; source: string }>, sitemapFound: false }));
|
|
2171
|
+
const sitemapUrls = sitemapResult.candidates.map((c: any) => c.url as string);
|
|
2172
|
+
// Seed accumulator with sitemap URLs so they show immediately
|
|
2173
|
+
for (const u of sitemapUrls) allUrls.add(u);
|
|
2174
|
+
logger.info({ count: sitemapUrls.length, sitemapFound: sitemapResult.sitemapFound }, '[discover] Phase 1 sitemap done');
|
|
2175
|
+
|
|
2176
|
+
// Phase 2 — unauthenticated BFS spider
|
|
2177
|
+
await onProgress(8, `Unauthenticated spider from ${appUrl}…`);
|
|
2178
|
+
const unauthResult = await crawlProject({
|
|
2179
|
+
tenantId,
|
|
2180
|
+
projectId,
|
|
2181
|
+
appUrl,
|
|
2182
|
+
discoveryMode: true,
|
|
2183
|
+
startUrls: sitemapUrls.length > 0 ? sitemapUrls : undefined,
|
|
2184
|
+
screenshotDir,
|
|
2185
|
+
maxScreens: maxDiscoverUrls,
|
|
2186
|
+
proxyUrl,
|
|
2187
|
+
useFirefox: crawlCfg.useFirefox,
|
|
2188
|
+
storageConfig: discoverStorageConfig,
|
|
2189
|
+
abortSignal: controller.signal,
|
|
2190
|
+
jobId,
|
|
2191
|
+
onUrlsDiscovered: async (urls: string[]) => {
|
|
2192
|
+
for (const u of urls) allUrls.add(u);
|
|
2193
|
+
const pct = 8 + Math.round((allUrls.size / Math.max(1, maxDiscoverUrls)) * 42);
|
|
2194
|
+
await flushPartialUrls(Math.min(pct, 49), `Discovered ${allUrls.size} URLs…`);
|
|
2195
|
+
},
|
|
2196
|
+
}, async (pct: number, step: string) => {
|
|
2197
|
+
await flushPartialUrls(8 + Math.round(pct * 0.42), `Unauthenticated: ${step}`);
|
|
2198
|
+
}).catch((err: any) => {
|
|
2199
|
+
if (err?.message === 'CRAWL_ABORTED') throw err;
|
|
2200
|
+
logger.warn({ err: err?.message }, '[discover] Phase 2 unauthenticated spider failed — continuing with partial results');
|
|
2201
|
+
return { discoveredUrls: [] as string[] };
|
|
2202
|
+
});
|
|
2203
|
+
|
|
2204
|
+
for (const u of ((unauthResult as any).discoveredUrls ?? [] as string[])) allUrls.add(u);
|
|
2205
|
+
logger.info({ count: allUrls.size }, '[discover] Phase 2 unauth spider done');
|
|
2206
|
+
|
|
2207
|
+
// Phase 3 — authenticated BFS spider (only when credentials configured)
|
|
2208
|
+
// getCrawlConfig returns flat fields (username/password/totpSecret) — NOT nested under .credentials
|
|
2209
|
+
let resolvedSso: {
|
|
2210
|
+
ssoProvider?: string;
|
|
2211
|
+
ssoDomain?: string;
|
|
2212
|
+
ssoClientId?: string;
|
|
2213
|
+
ssoClientSecret?: string;
|
|
2214
|
+
ssoScope?: string;
|
|
2215
|
+
} = {};
|
|
2216
|
+
if (crawlCfg.ssoProviderId) {
|
|
2217
|
+
const ssoProviders = await AppBrain.getWorkspaceSsoProviders(tenantId).catch(() => []);
|
|
2218
|
+
const ssoProvider = ssoProviders.find((p: any) => p.id === crawlCfg.ssoProviderId);
|
|
2219
|
+
if (ssoProvider) {
|
|
2220
|
+
resolvedSso = {
|
|
2221
|
+
ssoProvider: ssoProvider.provider,
|
|
2222
|
+
ssoDomain: ssoProvider.domain,
|
|
2223
|
+
ssoClientId: ssoProvider.clientId,
|
|
2224
|
+
ssoClientSecret: ssoProvider.clientSecret,
|
|
2225
|
+
ssoScope: ssoProvider.scope,
|
|
2226
|
+
};
|
|
2227
|
+
}
|
|
2228
|
+
}
|
|
2229
|
+
|
|
2230
|
+
const hasCreds = !!(
|
|
2231
|
+
crawlCfg.username ||
|
|
2232
|
+
crawlCfg.storageState ||
|
|
2233
|
+
crawlCfg.authToken ||
|
|
2234
|
+
crawlCfg.chromeProfilePath ||
|
|
2235
|
+
(crawlCfg.httpBasicUsername && crawlCfg.httpBasicPassword)
|
|
2236
|
+
);
|
|
2237
|
+
if (hasCreds && !controller.signal.aborted) {
|
|
2238
|
+
await onProgress(52, 'Authenticated spider…');
|
|
2239
|
+
const runtimeCreds = crawlCfg.username
|
|
2240
|
+
? {
|
|
2241
|
+
username: crawlCfg.username,
|
|
2242
|
+
password: crawlCfg.password ?? '',
|
|
2243
|
+
...(crawlCfg.totpSecret
|
|
2244
|
+
? { getOneTimeCode: async () => generateTOTP(crawlCfg.totpSecret!) }
|
|
2245
|
+
: {}),
|
|
2246
|
+
}
|
|
2247
|
+
: undefined;
|
|
2248
|
+
|
|
2249
|
+
const PHASE3_TIMEOUT_MS = 20 * 60_000; // 20-minute cap on authenticated spider
|
|
2250
|
+
const authResult = await Promise.race([
|
|
2251
|
+
crawlProject({
|
|
2252
|
+
tenantId,
|
|
2253
|
+
projectId,
|
|
2254
|
+
appUrl,
|
|
2255
|
+
discoveryMode: true,
|
|
2256
|
+
credentials: runtimeCreds,
|
|
2257
|
+
storageState: crawlCfg.storageState,
|
|
2258
|
+
httpBasicUsername: crawlCfg.httpBasicUsername,
|
|
2259
|
+
httpBasicPassword: crawlCfg.httpBasicPassword,
|
|
2260
|
+
authToken: crawlCfg.authToken,
|
|
2261
|
+
authTokenHeader: crawlCfg.authTokenHeader,
|
|
2262
|
+
authTokenPrefix: crawlCfg.authTokenPrefix,
|
|
2263
|
+
startUrls: crawlCfg.postLoginUrl
|
|
2264
|
+
? [crawlCfg.postLoginUrl, ...(sitemapUrls.length > 0 ? sitemapUrls : [])]
|
|
2265
|
+
: (sitemapUrls.length > 0 ? sitemapUrls : undefined),
|
|
2266
|
+
screenshotDir,
|
|
2267
|
+
maxScreens: maxDiscoverUrls,
|
|
2268
|
+
proxyUrl,
|
|
2269
|
+
chromeProfilePath: crawlCfg.chromeProfilePath,
|
|
2270
|
+
useFirefox: crawlCfg.useFirefox,
|
|
2271
|
+
storageConfig: discoverStorageConfig,
|
|
2272
|
+
captchaSolverApiKey: crawlCfg.captchaSolverApiKey,
|
|
2273
|
+
captchaSolverProvider: crawlCfg.captchaSolverProvider,
|
|
2274
|
+
mailslurpApiKey: crawlCfg.mailslurpApiKey,
|
|
2275
|
+
mailslurpInboxId: crawlCfg.mailslurpInboxId,
|
|
2276
|
+
loginInstructions: crawlCfg.loginInstructions,
|
|
2277
|
+
...resolvedSso,
|
|
2278
|
+
abortSignal: controller.signal,
|
|
2279
|
+
jobId,
|
|
2280
|
+
onUrlsDiscovered: async (urls: string[]) => {
|
|
2281
|
+
for (const u of urls) allUrls.add(u);
|
|
2282
|
+
const pct = 52 + Math.round((allUrls.size / Math.max(1, maxDiscoverUrls)) * 38);
|
|
2283
|
+
await flushPartialUrls(Math.min(pct, 89), `Discovered ${allUrls.size} URLs (authenticated)…`);
|
|
2284
|
+
},
|
|
2285
|
+
}, async (pct: number, step: string) => {
|
|
2286
|
+
await flushPartialUrls(52 + Math.round(pct * 0.38), `Authenticated: ${step}`);
|
|
2287
|
+
}),
|
|
2288
|
+
new Promise<never>((_, rej) => setTimeout(() => rej(new Error('AUTH_PHASE_TIMEOUT')), PHASE3_TIMEOUT_MS)),
|
|
2289
|
+
]).catch((err: any) => {
|
|
2290
|
+
if (err?.message === 'CRAWL_ABORTED') throw err;
|
|
2291
|
+
const reason = err?.message === 'AUTH_PHASE_TIMEOUT'
|
|
2292
|
+
? 'Authenticated spider timed out after 20 minutes'
|
|
2293
|
+
: err?.message;
|
|
2294
|
+
logger.warn({ reason }, '[discover] Phase 3 authenticated spider failed — using unauthenticated results');
|
|
2295
|
+
return { discoveredUrls: [] as string[] };
|
|
2296
|
+
});
|
|
2297
|
+
|
|
2298
|
+
for (const u of (((authResult as any).discoveredUrls) ?? [] as string[])) {
|
|
2299
|
+
allUrls.add(u);
|
|
2300
|
+
}
|
|
2301
|
+
logger.info({ count: allUrls.size }, '[discover] Phase 3 auth spider done');
|
|
2302
|
+
}
|
|
2303
|
+
|
|
2304
|
+
// Persist discovered URLs to project crawl config
|
|
2305
|
+
// Filter sentinel strings (_pending_, _auth_wall_, etc.) that may have leaked in
|
|
2306
|
+
// via onUrlsDiscovered callbacks fired before visited-map entries were updated.
|
|
2307
|
+
const discoveredUrls = Array.from(allUrls).filter(u => u.startsWith('http'));
|
|
2308
|
+
const existingCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => ({}));
|
|
2309
|
+
await AppBrain.saveCrawlConfig(tenantId, projectId, {
|
|
2310
|
+
...(existingCfg as any),
|
|
2311
|
+
discoveredUrls,
|
|
2312
|
+
discoveredAt: new Date().toISOString(),
|
|
2313
|
+
});
|
|
2314
|
+
|
|
2315
|
+
await onProgress(100, `Done — ${discoveredUrls.length} URLs discovered`);
|
|
2316
|
+
|
|
2317
|
+
await withTenant(tenantId, (tx) =>
|
|
2318
|
+
tx.platformJob.update({
|
|
2319
|
+
where: { id: jobId },
|
|
2320
|
+
data: {
|
|
2321
|
+
status: 'DONE',
|
|
2322
|
+
result: {
|
|
2323
|
+
discoveredUrls,
|
|
2324
|
+
count: discoveredUrls.length,
|
|
2325
|
+
sitemapFound: sitemapResult.sitemapFound,
|
|
2326
|
+
} as any,
|
|
2327
|
+
progress: 100,
|
|
2328
|
+
finishedAt: new Date(),
|
|
2329
|
+
},
|
|
2330
|
+
})
|
|
2331
|
+
);
|
|
2332
|
+
|
|
2333
|
+
notifyAdmins(tenantId, {
|
|
2334
|
+
type: 'discovery.done',
|
|
2335
|
+
title: 'URL Discovery completed',
|
|
2336
|
+
body: `Found ${discoveredUrls.length} URLs for the project.`,
|
|
2337
|
+
metadata: { projectId, jobId },
|
|
2338
|
+
}).catch(console.error);
|
|
2339
|
+
|
|
2340
|
+
} catch (err: any) {
|
|
2341
|
+
logger.error({ err: err?.message, jobId }, '[discover] Job failed');
|
|
2342
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
2343
|
+
} finally {
|
|
2344
|
+
clearInterval(heartbeatTimer);
|
|
2345
|
+
runningControllers.delete(jobId);
|
|
2346
|
+
}
|
|
2347
|
+
}
|
|
2348
|
+
|
|
2349
|
+
// ── Site Monitor Job ─────────────────────────────────────────────────────────
|
|
2350
|
+
// Lightweight scheduled content check: fetches configured URLs, diffs content
|
|
2351
|
+
// hashes against stored baselines, fires content.changed webhooks on drift.
|
|
2352
|
+
// Baselines are stored in project.crawlConfig.monitorBaselines (url→hash map).
|
|
2353
|
+
|
|
2354
|
+
async function processMonitorJob(jobId: string, config: any, opts?: ProcessJobOpts) {
|
|
2355
|
+
const { tenantId, projectId } = config;
|
|
2356
|
+
const controller = new AbortController();
|
|
2357
|
+
runningControllers.set(jobId, controller);
|
|
2358
|
+
|
|
2359
|
+
try {
|
|
2360
|
+
await withTenant(tenantId, (tx) =>
|
|
2361
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
2362
|
+
);
|
|
2363
|
+
|
|
2364
|
+
const proj: any = await withTenant(tenantId, (tx) =>
|
|
2365
|
+
(tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
|
|
2366
|
+
);
|
|
2367
|
+
const crawlCfg = proj?.crawlConfig ?? {};
|
|
2368
|
+
const monitorUrls: string[] = config.monitorUrls ?? crawlCfg.monitorUrls ?? [];
|
|
2369
|
+
|
|
2370
|
+
if (monitorUrls.length === 0) {
|
|
2371
|
+
throw new Error('No monitor URLs configured. Add monitorUrls to crawl config or job config.');
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
await updateJobProgress(tenantId, jobId, 10, `Monitoring ${monitorUrls.length} URL(s)...`);
|
|
2375
|
+
|
|
2376
|
+
// Baseline: stored baselines from previous monitor run take priority;
|
|
2377
|
+
// project screens' elementHash is the fallback for first-run.
|
|
2378
|
+
const storedBaselines: Record<string, string> = crawlCfg.monitorBaselines ?? {};
|
|
2379
|
+
const projectScreens: Array<{ url: string | null; elementHash: string | null }> =
|
|
2380
|
+
await withTenant(tenantId, (tx) =>
|
|
2381
|
+
tx.screen.findMany({ where: { projectId }, select: { url: true, elementHash: true } })
|
|
2382
|
+
).catch(() => []) as any;
|
|
2383
|
+
const screenHashMap: Record<string, string> = {};
|
|
2384
|
+
for (const s of projectScreens) {
|
|
2385
|
+
if (s.url && s.elementHash) screenHashMap[s.url] = s.elementHash;
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
const results: Array<{
|
|
2389
|
+
url: string; changed: boolean; reason: string;
|
|
2390
|
+
currentHash: string; previousHash: string | null;
|
|
2391
|
+
}> = [];
|
|
2392
|
+
const newBaselines: Record<string, string> = { ...storedBaselines };
|
|
2393
|
+
|
|
2394
|
+
for (let i = 0; i < monitorUrls.length; i++) {
|
|
2395
|
+
if (controller.signal.aborted) break;
|
|
2396
|
+
const url = monitorUrls[i];
|
|
2397
|
+
const pct = 10 + Math.floor((i / monitorUrls.length) * 80);
|
|
2398
|
+
await updateJobProgress(tenantId, jobId, pct, `Checking ${url}...`);
|
|
2399
|
+
opts?.onProgress?.(pct);
|
|
2400
|
+
|
|
2401
|
+
try {
|
|
2402
|
+
const crawlResult = await httpCrawl({ appUrl: url, maxScreens: 1, respectRobotsTxt: false, timeoutMs: parseInt(process.env.CRAWL_TIMEOUT_MS ?? '20000', 10) });
|
|
2403
|
+
const screen = crawlResult.screens[0];
|
|
2404
|
+
if (!screen) {
|
|
2405
|
+
results.push({ url, changed: false, reason: 'fetch_empty', currentHash: '', previousHash: null });
|
|
2406
|
+
continue;
|
|
2407
|
+
}
|
|
2408
|
+
const currentHash = hashContent(normalizeText(screen.markdown));
|
|
2409
|
+
const previousHash = storedBaselines[url] ?? screenHashMap[url] ?? null;
|
|
2410
|
+
newBaselines[url] = currentHash;
|
|
2411
|
+
|
|
2412
|
+
if (!previousHash) {
|
|
2413
|
+
results.push({ url, changed: false, reason: 'new_baseline', currentHash, previousHash: null });
|
|
2414
|
+
} else if (previousHash === currentHash) {
|
|
2415
|
+
results.push({ url, changed: false, reason: 'unchanged', currentHash, previousHash });
|
|
2416
|
+
} else {
|
|
2417
|
+
results.push({ url, changed: true, reason: 'content_changed', currentHash, previousHash });
|
|
2418
|
+
}
|
|
2419
|
+
} catch (fetchErr: any) {
|
|
2420
|
+
results.push({ url, changed: false, reason: `error:${fetchErr?.message ?? String(fetchErr)}`, currentHash: '', previousHash: null });
|
|
2421
|
+
}
|
|
2422
|
+
}
|
|
2423
|
+
|
|
2424
|
+
// Persist updated baselines so next run has fresh reference points.
|
|
2425
|
+
await withTenant(tenantId, (tx) =>
|
|
2426
|
+
(tx as any).project.update({
|
|
2427
|
+
where: { id: projectId },
|
|
2428
|
+
data: { crawlConfig: { ...crawlCfg, monitorBaselines: newBaselines } as any },
|
|
2429
|
+
})
|
|
2430
|
+
).catch((e: any) => logger.warn({ err: e }, '[monitor] baseline persist failed'));
|
|
2431
|
+
|
|
2432
|
+
const changedUrls = results.filter(r => r.changed);
|
|
2433
|
+
|
|
2434
|
+
if (changedUrls.length > 0) {
|
|
2435
|
+
dispatchWebhook(tenantId, projectId, 'content.changed', {
|
|
2436
|
+
jobId,
|
|
2437
|
+
changedUrls: changedUrls.map(r => ({ url: r.url, previousHash: r.previousHash, currentHash: r.currentHash })),
|
|
2438
|
+
totalChecked: results.length,
|
|
2439
|
+
changedCount: changedUrls.length,
|
|
2440
|
+
}).catch(console.error);
|
|
2441
|
+
}
|
|
2442
|
+
|
|
2443
|
+
await updateJobProgress(tenantId, jobId, 100, 'Monitor check complete');
|
|
2444
|
+
await withTenant(tenantId, (tx) =>
|
|
2445
|
+
tx.platformJob.update({
|
|
2446
|
+
where: { id: jobId },
|
|
2447
|
+
data: {
|
|
2448
|
+
status: 'DONE',
|
|
2449
|
+
progress: 100,
|
|
2450
|
+
finishedAt: new Date(),
|
|
2451
|
+
result: { results, changedCount: changedUrls.length, totalChecked: results.length } as any,
|
|
2452
|
+
},
|
|
2453
|
+
})
|
|
2454
|
+
);
|
|
2455
|
+
} catch (err: any) {
|
|
2456
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
2457
|
+
} finally {
|
|
2458
|
+
runningControllers.delete(jobId);
|
|
2459
|
+
}
|
|
2460
|
+
}
|
|
2461
|
+
|
|
2462
|
+
// ─── IMPORT_TESTS job processor ──────────────────────────────────────────────
|
|
2463
|
+
// Async counterpart to the synchronous POST /artifacts/:id/import-tests route.
|
|
2464
|
+
// Enqueued by POST /modernization/bulk-import for each artifact in a batch.
|
|
2465
|
+
// Config: { tenantId, projectId, artifactId, suiteId?, autoLabel?, sessionId? }
|
|
2466
|
+
|
|
2467
|
+
async function processImportTestsJob(jobId: string, config: any) {
|
|
2468
|
+
const { tenantId, projectId, artifactId, autoLabel, sourcePlatform } = config;
|
|
2469
|
+
const jobStart = new Date();
|
|
2470
|
+
let suiteId: string = config.suiteId ?? 'new';
|
|
2471
|
+
|
|
2472
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading artifact');
|
|
2473
|
+
|
|
2474
|
+
const artifact = await withTenant(tenantId, (tx) =>
|
|
2475
|
+
(tx as any).projectArtifact.findUnique({ where: { id: artifactId } })
|
|
2476
|
+
);
|
|
2477
|
+
if (!artifact || (artifact as any).tenantId !== tenantId) {
|
|
2478
|
+
throw new Error(`Artifact ${artifactId} not found`);
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
const content: string = (artifact as any).content ?? '';
|
|
2482
|
+
const filename: string = (artifact as any).originalName ?? (artifact as any).name ?? '';
|
|
2483
|
+
const kind: string = (artifact as any).kind ?? '';
|
|
2484
|
+
|
|
2485
|
+
// Detect format using same logic as the synchronous route
|
|
2486
|
+
function detectFormat(fn: string, k: string, c: string): string {
|
|
2487
|
+
if (fn.endsWith('.feature')) return 'GHERKIN';
|
|
2488
|
+
if (fn.match(/\.(xlsx|xls|csv)$/i) || k === 'SPREADSHEET') return 'EXCEL';
|
|
2489
|
+
if (fn.endsWith('.txt') && c && c.split('\n').some((l) => l.trim().startsWith('|'))) return 'EXCEL';
|
|
2490
|
+
return 'AI_EXTRACT';
|
|
2491
|
+
}
|
|
2492
|
+
const format = detectFormat(filename, kind, content);
|
|
2493
|
+
|
|
2494
|
+
await updateJobProgress(tenantId, jobId, 15, `Parsing ${filename}`);
|
|
2495
|
+
|
|
2496
|
+
const { parseTestCases, labelTestCasesBatch } = await import('@taodigital/agents');
|
|
2497
|
+
let res = await parseTestCases(content, format, tenantId, (artifact as any).columnMapping ?? undefined, undefined, undefined, sourcePlatform);
|
|
2498
|
+
if (res.cases.length === 0 && format !== 'AI_EXTRACT') {
|
|
2499
|
+
await updateJobProgress(tenantId, jobId, 25, 'Retrying with AI extraction');
|
|
2500
|
+
try {
|
|
2501
|
+
res = await parseTestCases(content, 'AI_EXTRACT', tenantId, undefined, undefined, undefined, sourcePlatform);
|
|
2502
|
+
} catch {
|
|
2503
|
+
// AI unavailable (no LLM configured) — proceed with 0 cases
|
|
2504
|
+
}
|
|
2505
|
+
}
|
|
2506
|
+
|
|
2507
|
+
const parsedCases = res.cases;
|
|
2508
|
+
if (parsedCases.length === 0) {
|
|
2509
|
+
await withTenant(tenantId, (tx) =>
|
|
2510
|
+
tx.platformJob.update({
|
|
2511
|
+
where: { id: jobId },
|
|
2512
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: { imported: 0, skipped: 0, labeled: 0 } as any },
|
|
2513
|
+
})
|
|
2514
|
+
);
|
|
2515
|
+
return;
|
|
2516
|
+
}
|
|
2517
|
+
|
|
2518
|
+
await updateJobProgress(tenantId, jobId, 35, `Parsed ${parsedCases.length} cases — creating suite`);
|
|
2519
|
+
|
|
2520
|
+
// Auto-create suite from filename when suiteId === 'new'
|
|
2521
|
+
if (!suiteId || suiteId === 'new') {
|
|
2522
|
+
const suiteName = filename.replace(/\.[^/.]+$/, '') || 'Imported Tests';
|
|
2523
|
+
const suite = await withTenant(tenantId, (tx) =>
|
|
2524
|
+
(tx as any).testSuite.create({
|
|
2525
|
+
data: { tenantId, projectId, name: suiteName },
|
|
2526
|
+
})
|
|
2527
|
+
);
|
|
2528
|
+
suiteId = (suite as any).id;
|
|
2529
|
+
}
|
|
2530
|
+
|
|
2531
|
+
await updateJobProgress(tenantId, jobId, 50, `Importing ${parsedCases.length} cases`);
|
|
2532
|
+
|
|
2533
|
+
const { created, skipped } = await AppBrain.importTestCasesFromArtifact(
|
|
2534
|
+
tenantId, projectId, suiteId, parsedCases, { duplicateMode: 'skip', artifactId }
|
|
2535
|
+
);
|
|
2536
|
+
|
|
2537
|
+
let labeled = 0;
|
|
2538
|
+
if (autoLabel && created.length > 0) {
|
|
2539
|
+
await updateJobProgress(tenantId, jobId, 75, `AI labeling ${created.length} cases`);
|
|
2540
|
+
try {
|
|
2541
|
+
const labelInput = created.map((c: any) => ({
|
|
2542
|
+
id: c.id, title: c.title,
|
|
2543
|
+
description: c.description ?? '',
|
|
2544
|
+
stepsText: (Array.isArray(c.steps) ? c.steps.join(' ') : String(c.steps ?? '')).slice(0, 200),
|
|
2545
|
+
}));
|
|
2546
|
+
const labelResults = await labelTestCasesBatch(labelInput, tenantId);
|
|
2547
|
+
// Persist labels back to each test case
|
|
2548
|
+
await Promise.all(
|
|
2549
|
+
labelResults.map((lr: any) =>
|
|
2550
|
+
withTenant(tenantId, (tx) =>
|
|
2551
|
+
tx.testCase.update({
|
|
2552
|
+
where: { id: lr.id },
|
|
2553
|
+
data: {
|
|
2554
|
+
priority: lr.priority ?? undefined,
|
|
2555
|
+
kind: lr.kind ?? undefined,
|
|
2556
|
+
tags: lr.tags ?? undefined,
|
|
2557
|
+
status: lr.needsReview ? 'PENDING_REVIEW' : undefined,
|
|
2558
|
+
},
|
|
2559
|
+
})
|
|
2560
|
+
).catch(() => { }) // non-fatal per-case
|
|
2561
|
+
)
|
|
2562
|
+
);
|
|
2563
|
+
labeled = labelResults.length;
|
|
2564
|
+
} catch {
|
|
2565
|
+
// non-fatal — import succeeded even if labeling fails
|
|
2566
|
+
}
|
|
2567
|
+
}
|
|
2568
|
+
|
|
2569
|
+
// Auto-generate AI test data for imported cases that have recorded form fields (testDataInline)
|
|
2570
|
+
const casesNeedingData = created.filter((c: any) => {
|
|
2571
|
+
const inline = (c as any).testDataInline;
|
|
2572
|
+
return inline && typeof inline === 'object' && Object.keys(inline).length > 0;
|
|
2573
|
+
});
|
|
2574
|
+
if (casesNeedingData.length > 0) {
|
|
2575
|
+
const cap = Math.min(casesNeedingData.length, 20);
|
|
2576
|
+
await updateJobProgress(tenantId, jobId, 90, `Generating test data for ${cap} cases`);
|
|
2577
|
+
const { generateTestData, refreshTestDataSkillFile } = await import('@taodigital/agents');
|
|
2578
|
+
for (let i = 0; i < cap; i++) {
|
|
2579
|
+
const c = casesNeedingData[i];
|
|
2580
|
+
await generateTestData({ tenantId, projectId, testCaseId: c.id, jobId }).catch((e: any) => {
|
|
2581
|
+
logger.warn({ err: e?.message, testCaseId: c.id }, '[import] test data generation failed');
|
|
2582
|
+
});
|
|
2583
|
+
}
|
|
2584
|
+
refreshTestDataSkillFile(tenantId, projectId).catch(console.error);
|
|
2585
|
+
}
|
|
2586
|
+
|
|
2587
|
+
if (created.length > 0) {
|
|
2588
|
+
refreshTestCasesSkillFile(tenantId, projectId).catch(console.error);
|
|
2589
|
+
}
|
|
2590
|
+
|
|
2591
|
+
await updateJobProgress(tenantId, jobId, 98, `Done — ${created.length} imported`);
|
|
2592
|
+
|
|
2593
|
+
// Write final result and mark job DONE
|
|
2594
|
+
await withTenant(tenantId, (tx) =>
|
|
2595
|
+
tx.platformJob.update({
|
|
2596
|
+
where: { id: jobId },
|
|
2597
|
+
data: {
|
|
2598
|
+
status: 'DONE',
|
|
2599
|
+
progress: 100,
|
|
2600
|
+
finishedAt: new Date(),
|
|
2601
|
+
result: {
|
|
2602
|
+
imported: created.length,
|
|
2603
|
+
skipped: skipped ?? 0,
|
|
2604
|
+
labeled,
|
|
2605
|
+
suiteId,
|
|
2606
|
+
artifactId,
|
|
2607
|
+
artifactName: filename,
|
|
2608
|
+
} as any,
|
|
2609
|
+
},
|
|
2610
|
+
})
|
|
2611
|
+
);
|
|
2612
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStart).catch(console.error);
|
|
2613
|
+
}
|
|
2614
|
+
|
|
2615
|
+
// Generate test cases for a single screen, enqueued by NEW_PAGES_PIPELINE.
|
|
2616
|
+
// Uses the same DualContextOrchestrator path as the in-process GENERATE_TESTS route.
|
|
2617
|
+
async function processGenerateScreenTestsJob(jobId: string, config: any) {
|
|
2618
|
+
const { tenantId, projectId, screenId, repoConnectionId, triggerAlignedScripts } = config;
|
|
2619
|
+
const jobStartedAt = new Date();
|
|
2620
|
+
try {
|
|
2621
|
+
await withTenant(tenantId, (tx: any) =>
|
|
2622
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } })
|
|
2623
|
+
);
|
|
2624
|
+
|
|
2625
|
+
const { DualContextOrchestrator } = await import('@taodigital/agents');
|
|
2626
|
+
await updateJobProgress(tenantId, jobId, 10, 'Generating test cases for screen');
|
|
2627
|
+
|
|
2628
|
+
const crawlCfg = await AppBrain.getCrawlConfig(tenantId, projectId).catch(() => null);
|
|
2629
|
+
const deviceProfiles: string[] = (crawlCfg as any)?.deviceProfiles ?? ['DESKTOP'];
|
|
2630
|
+
|
|
2631
|
+
const existingAiCases: number = await withTenant(tenantId, (tx) =>
|
|
2632
|
+
(tx as any).testCase.count({ where: { tenantId, screenId, source: 'AI_GENERATED' } })
|
|
2633
|
+
);
|
|
2634
|
+
const generationMode = existingAiCases > 0 ? 'replace' : undefined;
|
|
2635
|
+
|
|
2636
|
+
for (const viewport of deviceProfiles) {
|
|
2637
|
+
await DualContextOrchestrator.execute({ tenantId, projectId, targetScreenId: screenId, jobId, viewport, ...(generationMode ? { mode: generationMode } : {}) });
|
|
2638
|
+
}
|
|
2639
|
+
|
|
2640
|
+
await updateJobProgress(tenantId, jobId, 80, 'Test cases generated');
|
|
2641
|
+
|
|
2642
|
+
// Optionally kick framework-aligned script generation for this screen's test cases
|
|
2643
|
+
if (triggerAlignedScripts && repoConnectionId) {
|
|
2644
|
+
const conn: any = await withTenant(tenantId, (tx: any) =>
|
|
2645
|
+
tx.gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
|
|
2646
|
+
);
|
|
2647
|
+
if (conn?.styleProfile) {
|
|
2648
|
+
const { generateScriptAligned, mapWithConcurrency, SCRIPT_GEN_CONCURRENCY } = await import('@taodigital/agents');
|
|
2649
|
+
const cases = await withTenant(tenantId, (tx: any) =>
|
|
2650
|
+
tx.testCase.findMany({ where: { tenantId, projectId, screenId, status: 'APPROVED' }, select: { id: true }, take: 50 })
|
|
2651
|
+
);
|
|
2652
|
+
await mapWithConcurrency(cases as any[], SCRIPT_GEN_CONCURRENCY, (tc: any) =>
|
|
2653
|
+
generateScriptAligned({
|
|
2654
|
+
tenantId,
|
|
2655
|
+
projectId,
|
|
2656
|
+
testCaseId: tc.id,
|
|
2657
|
+
styleProfile: conn.styleProfile,
|
|
2658
|
+
pageObjectInventory: conn.pageObjectInventory ?? undefined,
|
|
2659
|
+
}).catch(() => { })
|
|
2660
|
+
);
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
|
|
2664
|
+
await withTenant(tenantId, (tx: any) =>
|
|
2665
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', progress: 100, finishedAt: new Date() } })
|
|
2666
|
+
);
|
|
2667
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStartedAt).catch(console.error);
|
|
2668
|
+
} catch (err: any) {
|
|
2669
|
+
const msg = err?.message ?? String(err);
|
|
2670
|
+
logger.error({ jobId, screenId, err: msg }, 'processGenerateScreenTestsJob failed');
|
|
2671
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
2672
|
+
}
|
|
2673
|
+
}
|
|
2674
|
+
|
|
2675
|
+
type CaptureStepStatus = 'PASSED' | 'FAILED' | 'HEALED' | 'SKIPPED';
|
|
2676
|
+
type CaptureStepResult = {
|
|
2677
|
+
stepNumber: number;
|
|
2678
|
+
description: string;
|
|
2679
|
+
status: CaptureStepStatus;
|
|
2680
|
+
screenshotPath?: string;
|
|
2681
|
+
screenshotUrl?: string;
|
|
2682
|
+
screenId?: string;
|
|
2683
|
+
url?: string;
|
|
2684
|
+
elementsCount?: number;
|
|
2685
|
+
healed?: boolean;
|
|
2686
|
+
healTier?: 'mechanical' | 'ai';
|
|
2687
|
+
healReasoning?: string;
|
|
2688
|
+
error?: string;
|
|
2689
|
+
};
|
|
2690
|
+
|
|
2691
|
+
function captureStepText(step: unknown): string {
|
|
2692
|
+
if (typeof step === 'string') return step;
|
|
2693
|
+
if (!step || typeof step !== 'object') return '';
|
|
2694
|
+
const obj = step as Record<string, unknown>;
|
|
2695
|
+
return [obj.action, obj.text, obj.label, obj.data, obj.expected]
|
|
2696
|
+
.filter((v): v is string => typeof v === 'string' && v.trim().length > 0)
|
|
2697
|
+
.join(' -> ');
|
|
2698
|
+
}
|
|
2699
|
+
|
|
2700
|
+
function firstQuoted(text: string): string | undefined {
|
|
2701
|
+
return (text.match(/"([^"]+)"/)?.[1] ?? text.match(/'([^']+)'/)?.[1])?.trim();
|
|
2702
|
+
}
|
|
2703
|
+
|
|
2704
|
+
function fallbackExecutionPlan(rawSteps: unknown[]): ExecutionStep[] {
|
|
2705
|
+
const plan: ExecutionStep[] = [];
|
|
2706
|
+
for (const raw of rawSteps) {
|
|
2707
|
+
const text = captureStepText(raw).trim();
|
|
2708
|
+
if (!text) continue;
|
|
2709
|
+
const stepNumber = plan.length + 1;
|
|
2710
|
+
const url = text.match(/https?:\/\/[^\s"']+/)?.[0];
|
|
2711
|
+
|
|
2712
|
+
if (/^navigate\b|^go to\b|^open\b/i.test(text) && url) {
|
|
2713
|
+
plan.push({ stepNumber, description: text, action: 'navigate', url });
|
|
2714
|
+
continue;
|
|
2715
|
+
}
|
|
2716
|
+
|
|
2717
|
+
const urlContains = text.match(/verify url contains:\s*["']?([^"']+)["']?/i);
|
|
2718
|
+
if (urlContains) {
|
|
2719
|
+
plan.push({ stepNumber, description: text, action: 'assert_url', value: urlContains[1].trim() });
|
|
2720
|
+
continue;
|
|
2721
|
+
}
|
|
2722
|
+
|
|
2723
|
+
const inputMatch = text.match(/(?:enter|type|fill)\s+["']([^"']+)["']\s+(?:in|into)\s+(.+?)(?:\s+field|\s+input|\s+box|\s+area)?(?:\s*→.*)?$/i);
|
|
2724
|
+
if (inputMatch) {
|
|
2725
|
+
const selector = inputMatch[2].replace(/^(the\s+)?/i, '').replace(/\s+(field|input|box|area)$/i, '').trim();
|
|
2726
|
+
plan.push({ stepNumber, description: text, action: 'fill', selectorStrategy: 'label', selector, value: inputMatch[1].trim() });
|
|
2727
|
+
continue;
|
|
2728
|
+
}
|
|
2729
|
+
|
|
2730
|
+
const quoted = firstQuoted(text);
|
|
2731
|
+
if (/^(click|tap|navigate menu|check|select)\b/i.test(text) && quoted) {
|
|
2732
|
+
plan.push({ stepNumber, description: text, action: 'click', selectorStrategy: 'text', selector: quoted });
|
|
2733
|
+
continue;
|
|
2734
|
+
}
|
|
2735
|
+
if (/^(verify|assert|expect)\b/i.test(text) && quoted) {
|
|
2736
|
+
plan.push({ stepNumber, description: text, action: 'assert_visible', selectorStrategy: 'text', selector: quoted });
|
|
2737
|
+
continue;
|
|
2738
|
+
}
|
|
2739
|
+
if (/execute script/i.test(text)) {
|
|
2740
|
+
const script = text.split(':').slice(1).join(':').replace(/\s*→.*$/, '').trim();
|
|
2741
|
+
if (script) plan.push({ stepNumber, description: text, action: 'script', value: script });
|
|
2742
|
+
}
|
|
2743
|
+
}
|
|
2744
|
+
return plan;
|
|
2745
|
+
}
|
|
2746
|
+
|
|
2747
|
+
function screenNameFromUrl(url: string, fallback: string): string {
|
|
2748
|
+
try {
|
|
2749
|
+
const u = new URL(url);
|
|
2750
|
+
return u.pathname.replace(/\/+$/, '').split('/').filter(Boolean).pop() || u.hostname || fallback;
|
|
2751
|
+
} catch {
|
|
2752
|
+
return fallback;
|
|
2753
|
+
}
|
|
2754
|
+
}
|
|
2755
|
+
|
|
2756
|
+
async function processCaptureStepsJob(jobId: string, config: any) {
|
|
2757
|
+
const { tenantId, projectId, testCaseId } = config as { tenantId: string; projectId: string; testCaseId: string };
|
|
2758
|
+
const screenshotDir = config.screenshotDir || platformConfig.screenshotDir || process.env.SCREENSHOT_DIR || '/tmp/zeta-screenshots';
|
|
2759
|
+
await fs.mkdir(screenshotDir, { recursive: true });
|
|
2760
|
+
|
|
2761
|
+
await withTenant(tenantId, (tx) =>
|
|
2762
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date(), progress: 2 } })
|
|
2763
|
+
);
|
|
2764
|
+
|
|
2765
|
+
let browser: any;
|
|
2766
|
+
try {
|
|
2767
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading test case');
|
|
2768
|
+
const [tc, crawlCfg, tenantStorageCfg] = await Promise.all([
|
|
2769
|
+
AppBrain.getTestCaseForExecution(tenantId, testCaseId) as Promise<any>,
|
|
2770
|
+
AppBrain.getCrawlConfig(tenantId, projectId).catch(() => null),
|
|
2771
|
+
getTenantStorageConfig(tenantId).catch(() => null),
|
|
2772
|
+
]);
|
|
2773
|
+
if (!tc) throw new Error('Test case not found');
|
|
2774
|
+
|
|
2775
|
+
const rawSteps = Array.isArray(tc.steps) ? tc.steps : [];
|
|
2776
|
+
if (rawSteps.length === 0) throw new Error('Test case has no steps to capture');
|
|
2777
|
+
|
|
2778
|
+
// Resolve env tokens from testDataInline so {{fze.env.URL}} → concrete URL before execution plan
|
|
2779
|
+
const _tdi = ((tc as any).testDataInline ?? {}) as Record<string, unknown>;
|
|
2780
|
+
const _tdiStartUrl = typeof _tdi['startUrl'] === 'string' && (_tdi['startUrl'] as string).startsWith('http')
|
|
2781
|
+
? (_tdi['startUrl'] as string) : '';
|
|
2782
|
+
const _recordedUrls = Array.isArray(_tdi['recordedUrls']) ? (_tdi['recordedUrls'] as unknown[]).map(String) : [];
|
|
2783
|
+
const _recordedStartUrl = _recordedUrls.find((u) => u.startsWith('http')) ?? '';
|
|
2784
|
+
|
|
2785
|
+
const baseUrl = config.baseUrl || _tdiStartUrl || _recordedStartUrl || tc?.screen?.project?.appUrl || crawlCfg?.appUrl || '';
|
|
2786
|
+
|
|
2787
|
+
// Build env token → concrete value map from testDataInline for step text substitution
|
|
2788
|
+
const _envTokenMap: Record<string, string> = {};
|
|
2789
|
+
for (const [k, v] of Object.entries(_tdi)) {
|
|
2790
|
+
if (typeof v === 'string' && v.startsWith('http')) _envTokenMap[k] = v;
|
|
2791
|
+
}
|
|
2792
|
+
if (_recordedStartUrl && !_envTokenMap['startUrl']) _envTokenMap['startUrl'] = _recordedStartUrl;
|
|
2793
|
+
|
|
2794
|
+
// Replace {{fze.env.X}} and [env:X] tokens in step texts with concrete values from testDataInline.
|
|
2795
|
+
// IMPORTANT: only substitute if we have a concrete value for that key.
|
|
2796
|
+
// Fall back to [key] placeholder — never fall back to baseUrl (would inject URL into credential fields).
|
|
2797
|
+
const resolveStepText = (text: string): string =>
|
|
2798
|
+
text
|
|
2799
|
+
.replace(/\{\{\s*fze\.env\.([A-Za-z_][A-Za-z0-9_]*)\s*\}\}/g, (_m, k) => _envTokenMap[k] ?? `[${k}]`)
|
|
2800
|
+
.replace(/\[env:([A-Za-z_][A-Za-z0-9_]*)\]/g, (_m, k) => _envTokenMap[k] ?? `[${k}]`);
|
|
2801
|
+
|
|
2802
|
+
const stepTexts = rawSteps.map(captureStepText).filter(Boolean).map(resolveStepText);
|
|
2803
|
+
if (stepTexts.length === 0) throw new Error('Test case has no steps to capture');
|
|
2804
|
+
|
|
2805
|
+
let plan = await generateExecutionPlan(tenantId, { ...tc, steps: stepTexts }, baseUrl).catch(() => []);
|
|
2806
|
+
plan = Array.isArray(plan)
|
|
2807
|
+
? plan.filter(Boolean).map((step: any, idx: number) => ({ ...step, stepNumber: idx + 1 }))
|
|
2808
|
+
: [];
|
|
2809
|
+
if (plan.length === 0) plan = fallbackExecutionPlan(rawSteps);
|
|
2810
|
+
if (plan.length === 0) throw new Error('Could not generate execution plan from steps');
|
|
2811
|
+
|
|
2812
|
+
const { chromium } = await import('playwright');
|
|
2813
|
+
browser = await chromium.launch({
|
|
2814
|
+
headless: true,
|
|
2815
|
+
...(process.env.PLAYWRIGHT_EXECUTABLE_PATH ? { executablePath: process.env.PLAYWRIGHT_EXECUTABLE_PATH } : {}),
|
|
2816
|
+
});
|
|
2817
|
+
let parsedStorageState: any;
|
|
2818
|
+
try {
|
|
2819
|
+
parsedStorageState = config.storageState ? JSON.parse(config.storageState) : crawlCfg?.storageState ? JSON.parse(crawlCfg.storageState) : undefined;
|
|
2820
|
+
} catch {
|
|
2821
|
+
parsedStorageState = undefined;
|
|
2822
|
+
}
|
|
2823
|
+
const context = await browser.newContext({
|
|
2824
|
+
viewport: { width: 1280, height: 800 },
|
|
2825
|
+
userAgent: await getNonHeadlessUserAgent(process.env.PLAYWRIGHT_EXECUTABLE_PATH || chromium.executablePath()),
|
|
2826
|
+
...(parsedStorageState ? { storageState: parsedStorageState } : {}),
|
|
2827
|
+
});
|
|
2828
|
+
const page = await context.newPage();
|
|
2829
|
+
const aiHealingEnabled = await isFeatureEnabled(tenantId, 'AI_SELF_HEALING').catch(() => false);
|
|
2830
|
+
|
|
2831
|
+
const stepResults: CaptureStepResult[] = [];
|
|
2832
|
+
const screens: Array<{ stepNumber: number; screenId: string; url: string; screenshotPath?: string; screenshotUrl?: string; isNewScreen: boolean }> = [];
|
|
2833
|
+
const locators: any[] = [];
|
|
2834
|
+
const seenLocatorExpressions = new Set<string>();
|
|
2835
|
+
const seenScreenKeys = new Set<string>();
|
|
2836
|
+
let lastStateKey = '';
|
|
2837
|
+
|
|
2838
|
+
for (let i = 0; i < plan.length; i++) {
|
|
2839
|
+
const step = plan[i];
|
|
2840
|
+
const description = step.description || stepTexts[i] || `Step ${i + 1}`;
|
|
2841
|
+
const stepNumber = i + 1;
|
|
2842
|
+
const result: CaptureStepResult = { stepNumber, description, status: 'FAILED' };
|
|
2843
|
+
await withTenant(tenantId, (tx) =>
|
|
2844
|
+
tx.platformJob.update({
|
|
2845
|
+
where: { id: jobId },
|
|
2846
|
+
data: {
|
|
2847
|
+
progress: Math.min(90, Math.round((i / Math.max(plan.length, 1)) * 90)),
|
|
2848
|
+
result: { currentStep: { stepNumber, description } } as any,
|
|
2849
|
+
heartbeatAt: new Date(),
|
|
2850
|
+
},
|
|
2851
|
+
})
|
|
2852
|
+
).catch(() => { });
|
|
2853
|
+
|
|
2854
|
+
try {
|
|
2855
|
+
const heal = await executeExecutionStep(page, step, aiHealingEnabled ? { healCtx: { tenantId, projectId } } : {});
|
|
2856
|
+
if (heal.healed) {
|
|
2857
|
+
result.healed = true;
|
|
2858
|
+
result.healTier = heal.healedVia;
|
|
2859
|
+
result.healReasoning = heal.healReasoning;
|
|
2860
|
+
}
|
|
2861
|
+
await page.waitForLoadState('networkidle', { timeout: parseInt(process.env.TEST_NETWORK_IDLE_TIMEOUT_MS ?? '2000', 10) }).catch(() => { });
|
|
2862
|
+
result.status = result.healed ? 'HEALED' : 'PASSED';
|
|
2863
|
+
} catch (err: any) {
|
|
2864
|
+
result.status = step.optional ? 'SKIPPED' : 'FAILED';
|
|
2865
|
+
result.error = String(err?.message ?? err).slice(0, 300);
|
|
2866
|
+
}
|
|
2867
|
+
|
|
2868
|
+
const currentUrl = page.url();
|
|
2869
|
+
result.url = currentUrl;
|
|
2870
|
+
const ssFilename = `${testCaseId}-capture-step-${stepNumber}${result.status === 'FAILED' ? '-err' : ''}.png`;
|
|
2871
|
+
const ssPath = path.join(screenshotDir, ssFilename);
|
|
2872
|
+
await page.screenshot({ path: ssPath, fullPage: false }).catch(() => { });
|
|
2873
|
+
result.screenshotPath = ssPath;
|
|
2874
|
+
|
|
2875
|
+
let cloudUrl: string | undefined;
|
|
2876
|
+
if (tenantStorageCfg) {
|
|
2877
|
+
const key = buildArtifactKey(tenantId, projectId, 'screenshots', ssFilename, tenantStorageCfg.prefix);
|
|
2878
|
+
cloudUrl = (await uploadScreenshotToTenantStorage(tenantStorageCfg, ssPath, key).catch(() => undefined)) ?? undefined;
|
|
2879
|
+
if (cloudUrl) result.screenshotUrl = cloudUrl;
|
|
2880
|
+
}
|
|
2881
|
+
|
|
2882
|
+
const elements = await domFallbackElements(page).catch(() => []);
|
|
2883
|
+
result.elementsCount = elements.length;
|
|
2884
|
+
const stateHash = hashContent(elements.map((el) => `${el.role}:${el.meaning}:${el.notes ?? ''}`).join('|'));
|
|
2885
|
+
const screenKey = `${currentUrl || 'about:blank'}:${stateHash}`;
|
|
2886
|
+
const shouldPersistScreen = currentUrl && currentUrl !== 'about:blank' && (i === 0 || screenKey !== lastStateKey || !seenScreenKeys.has(screenKey));
|
|
2887
|
+
lastStateKey = screenKey;
|
|
2888
|
+
|
|
2889
|
+
if (shouldPersistScreen) {
|
|
2890
|
+
const screenName = screenNameFromUrl(currentUrl, tc.title ?? `Step ${stepNumber}`);
|
|
2891
|
+
const screen = await AppBrain.saveScreen(tenantId, projectId, screenName, currentUrl, jobId, i === 0 ? 'ENTRY_POINT' : 'LINK_FOLLOW').catch(() => null) as any;
|
|
2892
|
+
if (screen?.id) {
|
|
2893
|
+
result.screenId = screen.id;
|
|
2894
|
+
await AppBrain.saveScreenshot(tenantId, projectId, screen.id, ssPath, screen.version ?? 1, 'DESKTOP', cloudUrl).catch(() => { });
|
|
2895
|
+
for (const el of elements) {
|
|
2896
|
+
await AppBrain.saveElement(
|
|
2897
|
+
tenantId, projectId, screen.id,
|
|
2898
|
+
el.meaning, el.role, el.expectedData, el.notes,
|
|
2899
|
+
undefined, true, el.boundingRect, el.ariaState, el.parentLandmark,
|
|
2900
|
+
).catch(() => { });
|
|
2901
|
+
}
|
|
2902
|
+
for (const loc of elementsToPlaywrightLocators(elements as any)) {
|
|
2903
|
+
if (seenLocatorExpressions.has(loc.expression)) continue;
|
|
2904
|
+
seenLocatorExpressions.add(loc.expression);
|
|
2905
|
+
locators.push(loc);
|
|
2906
|
+
}
|
|
2907
|
+
if (!seenScreenKeys.has(screenKey)) {
|
|
2908
|
+
screens.push({ stepNumber, screenId: screen.id, url: currentUrl, screenshotPath: ssPath, screenshotUrl: cloudUrl, isNewScreen: true });
|
|
2909
|
+
seenScreenKeys.add(screenKey);
|
|
2910
|
+
}
|
|
2911
|
+
}
|
|
2912
|
+
}
|
|
2913
|
+
|
|
2914
|
+
stepResults.push(result);
|
|
2915
|
+
if (result.status === 'FAILED') break;
|
|
2916
|
+
}
|
|
2917
|
+
|
|
2918
|
+
if (locators.length > 0) {
|
|
2919
|
+
await AppBrain.saveLocatorsJson(tenantId, testCaseId, locators as any).catch(() => { });
|
|
2920
|
+
}
|
|
2921
|
+
|
|
2922
|
+
const firstScreen = screens[0];
|
|
2923
|
+
await withTenant(tenantId, (tx) =>
|
|
2924
|
+
(tx as any).testCase.update({
|
|
2925
|
+
where: { id: testCaseId },
|
|
2926
|
+
data: {
|
|
2927
|
+
...(firstScreen?.screenId ? { screenId: firstScreen.screenId } : {}),
|
|
2928
|
+
captureStepScreenshots: stepResults as any,
|
|
2929
|
+
},
|
|
2930
|
+
})
|
|
2931
|
+
).catch(() => { });
|
|
2932
|
+
|
|
2933
|
+
const finalResult = {
|
|
2934
|
+
stepResults,
|
|
2935
|
+
screens,
|
|
2936
|
+
locators,
|
|
2937
|
+
totalSteps: plan.length,
|
|
2938
|
+
capturedScreens: screens.length,
|
|
2939
|
+
};
|
|
2940
|
+
await withTenant(tenantId, (tx) =>
|
|
2941
|
+
tx.platformJob.update({
|
|
2942
|
+
where: { id: jobId },
|
|
2943
|
+
data: { status: 'DONE', progress: 100, result: finalResult as any, finishedAt: new Date(), heartbeatAt: new Date() },
|
|
2944
|
+
})
|
|
2945
|
+
);
|
|
2946
|
+
} catch (err: any) {
|
|
2947
|
+
const error = String(err?.message ?? err);
|
|
2948
|
+
logger.error({ jobId, testCaseId, err: error }, 'processCaptureStepsJob failed');
|
|
2949
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
2950
|
+
} finally {
|
|
2951
|
+
await browser?.close?.().catch(() => { });
|
|
2952
|
+
}
|
|
2953
|
+
}
|
|
2954
|
+
|
|
2955
|
+
// ── Multi-role crawl orchestrator ────────────────────────────────────────────
|
|
2956
|
+
// Runs a primary CRAWL to discover all screens, then fans out one ROLE_CRAWL
|
|
2957
|
+
// job per credential profile. Role jobs run concurrently via the worker pool.
|
|
2958
|
+
|
|
2959
|
+
async function processMultiRoleCrawlJob(jobId: string, config: any) {
|
|
2960
|
+
const { tenantId, projectId } = config;
|
|
2961
|
+
try {
|
|
2962
|
+
await withTenant(tenantId, (tx) =>
|
|
2963
|
+
tx.platformJob.updateMany({
|
|
2964
|
+
where: { id: jobId, status: { not: 'CANCELLED' } },
|
|
2965
|
+
data: { status: 'RUNNING', startedAt: new Date(), heartbeatAt: new Date(), workerId: WORKER_ID },
|
|
2966
|
+
})
|
|
2967
|
+
);
|
|
2968
|
+
|
|
2969
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading project crawl config…');
|
|
2970
|
+
|
|
2971
|
+
// Load saved project crawlConfig for primary crawl parameters
|
|
2972
|
+
const proj = await withTenant(tenantId, (tx) =>
|
|
2973
|
+
(tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
|
|
2974
|
+
) as { crawlConfig: any } | null;
|
|
2975
|
+
const savedCrawlConfig = proj?.crawlConfig ?? {};
|
|
2976
|
+
|
|
2977
|
+
const credentialProfiles: Array<{ id: string; name: string; username: string; password: string }> =
|
|
2978
|
+
config.credentialProfiles ?? [];
|
|
2979
|
+
|
|
2980
|
+
// ── Step 1: enqueue primary CRAWL ────────────────────────────────────────
|
|
2981
|
+
await updateJobProgress(tenantId, jobId, 10, 'Enqueuing primary crawl…');
|
|
2982
|
+
const primaryJobId = await enqueueJob('CRAWL', {
|
|
2983
|
+
tenantId,
|
|
2984
|
+
projectId,
|
|
2985
|
+
appUrl: config.appUrl || savedCrawlConfig.appUrl,
|
|
2986
|
+
credentials: savedCrawlConfig.username && savedCrawlConfig.password
|
|
2987
|
+
? { username: savedCrawlConfig.username, password: savedCrawlConfig.password, ...(savedCrawlConfig.totpSecret ? { totpSecret: savedCrawlConfig.totpSecret } : {}) }
|
|
2988
|
+
: undefined,
|
|
2989
|
+
storageState: savedCrawlConfig.storageState,
|
|
2990
|
+
screenshotDir: platformConfig.screenshotDir,
|
|
2991
|
+
startUrls: savedCrawlConfig.seedUrls?.length ? savedCrawlConfig.seedUrls : undefined,
|
|
2992
|
+
deviceProfiles: savedCrawlConfig.deviceProfiles ?? ['DESKTOP'],
|
|
2993
|
+
loginInstructions: savedCrawlConfig.loginInstructions,
|
|
2994
|
+
proxyUrl: savedCrawlConfig.proxyUrl,
|
|
2995
|
+
useSitemap: true,
|
|
2996
|
+
sitemapUrl: savedCrawlConfig.sitemapUrl,
|
|
2997
|
+
});
|
|
2998
|
+
logger.info({ primaryJobId, projectId }, '[multi-role-crawl] primary CRAWL enqueued');
|
|
2999
|
+
|
|
3000
|
+
// ── Step 2: poll until primary CRAWL is done (2-hour timeout) ────────────
|
|
3001
|
+
const PRIMARY_TIMEOUT_MS = 2 * 60 * 60 * 1000;
|
|
3002
|
+
const POLL_INTERVAL_MS = 10_000;
|
|
3003
|
+
const deadline = Date.now() + PRIMARY_TIMEOUT_MS;
|
|
3004
|
+
let primaryStatus = 'QUEUED';
|
|
3005
|
+
while (Date.now() < deadline) {
|
|
3006
|
+
const primaryJob = await prismaAdmin.platformJob.findUnique({
|
|
3007
|
+
where: { id: primaryJobId },
|
|
3008
|
+
select: { status: true },
|
|
3009
|
+
}).catch(() => null);
|
|
3010
|
+
primaryStatus = primaryJob?.status ?? 'UNKNOWN';
|
|
3011
|
+
if (primaryStatus === 'DONE' || primaryStatus === 'FAILED' || primaryStatus === 'CANCELLED') break;
|
|
3012
|
+
await updateJobProgress(tenantId, jobId, 20, `Waiting for primary crawl (${primaryStatus})…`);
|
|
3013
|
+
await new Promise((res) => setTimeout(res, POLL_INTERVAL_MS));
|
|
3014
|
+
}
|
|
3015
|
+
|
|
3016
|
+
if (primaryStatus !== 'DONE') {
|
|
3017
|
+
throw new Error(`Primary crawl ${primaryJobId} ended with status ${primaryStatus} — aborting role crawls`);
|
|
3018
|
+
}
|
|
3019
|
+
|
|
3020
|
+
// ── Step 3: collect all known screen URLs ────────────────────────────────
|
|
3021
|
+
await updateJobProgress(tenantId, jobId, 50, 'Collecting screen URLs for role crawls…');
|
|
3022
|
+
const screens = await prismaAdmin.screen.findMany({
|
|
3023
|
+
where: { tenantId, projectId, status: 'ACTIVE' },
|
|
3024
|
+
select: { id: true, url: true },
|
|
3025
|
+
}).catch(() => [] as Array<{ id: string; url: string | null }>);
|
|
3026
|
+
const screenUrls = screens.filter((s) => s.url).map((s) => s.url as string);
|
|
3027
|
+
logger.info({ screenCount: screenUrls.length, projectId }, '[multi-role-crawl] screen URLs collected');
|
|
3028
|
+
|
|
3029
|
+
// ── Step 4: enqueue one ROLE_CRAWL per credential profile ────────────────
|
|
3030
|
+
if (credentialProfiles.length === 0) {
|
|
3031
|
+
logger.warn({ projectId, jobId }, '[multi-role-crawl] no credential profiles — nothing to role-crawl');
|
|
3032
|
+
}
|
|
3033
|
+
|
|
3034
|
+
const roleJobs: Array<{ roleName: string; jobId: string }> = [];
|
|
3035
|
+
for (const profile of credentialProfiles) {
|
|
3036
|
+
if (!profile.username || !profile.password) continue;
|
|
3037
|
+
const roleJobId = await enqueueJob('ROLE_CRAWL', {
|
|
3038
|
+
tenantId,
|
|
3039
|
+
projectId,
|
|
3040
|
+
appUrl: config.appUrl || savedCrawlConfig.appUrl,
|
|
3041
|
+
credentials: { username: profile.username, password: profile.password },
|
|
3042
|
+
roleProfileName: profile.name,
|
|
3043
|
+
parentJobId: jobId,
|
|
3044
|
+
selectiveUrls: config.fullReCrawl ? undefined : (screenUrls.length > 0 ? screenUrls : undefined),
|
|
3045
|
+
startUrls: config.fullReCrawl ? (savedCrawlConfig.seedUrls ?? []) : undefined,
|
|
3046
|
+
maxScreens: config.fullReCrawl ? undefined : screenUrls.length + 10,
|
|
3047
|
+
screenshotDir: platformConfig.screenshotDir,
|
|
3048
|
+
storageState: savedCrawlConfig.storageState,
|
|
3049
|
+
deviceProfiles: savedCrawlConfig.deviceProfiles ?? ['DESKTOP'],
|
|
3050
|
+
loginInstructions: savedCrawlConfig.loginInstructions,
|
|
3051
|
+
proxyUrl: savedCrawlConfig.proxyUrl,
|
|
3052
|
+
});
|
|
3053
|
+
roleJobs.push({ roleName: profile.name, jobId: roleJobId });
|
|
3054
|
+
logger.info({ roleJobId, roleName: profile.name, projectId }, '[multi-role-crawl] ROLE_CRAWL enqueued');
|
|
3055
|
+
}
|
|
3056
|
+
|
|
3057
|
+
// ── Step 5: poll until ALL role crawls complete ───────────────────────────
|
|
3058
|
+
const ROLE_TIMEOUT_MS = 2 * 60 * 60 * 1000;
|
|
3059
|
+
const roleDeadline = Date.now() + ROLE_TIMEOUT_MS;
|
|
3060
|
+
const roleResults: Array<{ roleName: string; jobId: string; status: string; screensTagged?: number }> = [];
|
|
3061
|
+
|
|
3062
|
+
while (Date.now() < roleDeadline && roleJobs.length > 0) {
|
|
3063
|
+
const pending: typeof roleJobs = [];
|
|
3064
|
+
for (const rj of roleJobs) {
|
|
3065
|
+
const rJob = await prismaAdmin.platformJob.findUnique({
|
|
3066
|
+
where: { id: rj.jobId },
|
|
3067
|
+
select: { status: true, result: true },
|
|
3068
|
+
}).catch(() => null);
|
|
3069
|
+
const st = rJob?.status ?? 'UNKNOWN';
|
|
3070
|
+
if (st === 'DONE' || st === 'FAILED' || st === 'CANCELLED') {
|
|
3071
|
+
roleResults.push({
|
|
3072
|
+
roleName: rj.roleName,
|
|
3073
|
+
jobId: rj.jobId,
|
|
3074
|
+
status: st,
|
|
3075
|
+
screensTagged: (rJob?.result as any)?.screensTagged,
|
|
3076
|
+
});
|
|
3077
|
+
} else {
|
|
3078
|
+
pending.push(rj);
|
|
3079
|
+
}
|
|
3080
|
+
}
|
|
3081
|
+
roleJobs.length = 0;
|
|
3082
|
+
roleJobs.push(...pending);
|
|
3083
|
+
if (roleJobs.length === 0) break;
|
|
3084
|
+
const pct = Math.round(60 + ((roleResults.length / (roleResults.length + roleJobs.length)) * 35));
|
|
3085
|
+
await updateJobProgress(tenantId, jobId, pct, `Role crawls: ${roleResults.length} done, ${roleJobs.length} pending…`);
|
|
3086
|
+
await new Promise((res) => setTimeout(res, POLL_INTERVAL_MS));
|
|
3087
|
+
}
|
|
3088
|
+
|
|
3089
|
+
// Any still-pending jobs timed out — record them as timed out
|
|
3090
|
+
for (const rj of roleJobs) {
|
|
3091
|
+
roleResults.push({ roleName: rj.roleName, jobId: rj.jobId, status: 'TIMEOUT' });
|
|
3092
|
+
}
|
|
3093
|
+
|
|
3094
|
+
await withTenant(tenantId, (tx) =>
|
|
3095
|
+
tx.platformJob.update({
|
|
3096
|
+
where: { id: jobId },
|
|
3097
|
+
data: {
|
|
3098
|
+
status: 'DONE',
|
|
3099
|
+
progress: 100,
|
|
3100
|
+
finishedAt: new Date(),
|
|
3101
|
+
result: { primaryJobId, roleJobs: roleResults } as any,
|
|
3102
|
+
},
|
|
3103
|
+
})
|
|
3104
|
+
);
|
|
3105
|
+
logger.info({ jobId, primaryJobId, roleCount: roleResults.length, projectId }, '[multi-role-crawl] completed');
|
|
3106
|
+
} catch (err: any) {
|
|
3107
|
+
const msg = String(err?.message ?? err);
|
|
3108
|
+
logger.error({ jobId, err: msg }, '[multi-role-crawl] failed');
|
|
3109
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3110
|
+
}
|
|
3111
|
+
}
|
|
3112
|
+
|
|
3113
|
+
// ── Role-specific sub-crawl ───────────────────────────────────────────────────
|
|
3114
|
+
// Crawls the app as a specific credential profile and tags all discovered
|
|
3115
|
+
// screens with the role name in the roleAccess array column.
|
|
3116
|
+
|
|
3117
|
+
async function processRoleCrawlJob(jobId: string, config: any) {
|
|
3118
|
+
const { tenantId, projectId } = config;
|
|
3119
|
+
try {
|
|
3120
|
+
const claimed = await withTenant(tenantId, (tx) =>
|
|
3121
|
+
tx.platformJob.updateMany({
|
|
3122
|
+
where: { id: jobId, status: { not: 'CANCELLED' } },
|
|
3123
|
+
data: { status: 'RUNNING', startedAt: new Date(), heartbeatAt: new Date(), workerId: WORKER_ID },
|
|
3124
|
+
})
|
|
3125
|
+
);
|
|
3126
|
+
if (claimed.count === 0) return;
|
|
3127
|
+
|
|
3128
|
+
const controller = new AbortController();
|
|
3129
|
+
runningControllers.set(jobId, controller);
|
|
3130
|
+
const heartbeatTimer = setInterval(() => void heartbeatJob(tenantId, jobId), JOB_HEARTBEAT_INTERVAL_MS);
|
|
3131
|
+
|
|
3132
|
+
const onProgress = async (pct: number, step: string) => {
|
|
3133
|
+
await updateJobProgress(tenantId, jobId, pct, step);
|
|
3134
|
+
};
|
|
3135
|
+
|
|
3136
|
+
try {
|
|
3137
|
+
// Load project crawlConfig for proxy, storageState overrides
|
|
3138
|
+
const proj = await withTenant(tenantId, (tx) =>
|
|
3139
|
+
(tx as any).project.findUnique({ where: { id: projectId }, select: { crawlConfig: true } })
|
|
3140
|
+
) as { crawlConfig: any } | null;
|
|
3141
|
+
const savedCrawlConfig = proj?.crawlConfig ?? {};
|
|
3142
|
+
|
|
3143
|
+
// Build runtime credentials with TOTP support
|
|
3144
|
+
const runtimeCreds = config.credentials
|
|
3145
|
+
? {
|
|
3146
|
+
...config.credentials,
|
|
3147
|
+
...(config.credentials.totpSecret
|
|
3148
|
+
? { getOneTimeCode: async () => generateTOTP(config.credentials.totpSecret) }
|
|
3149
|
+
: {}),
|
|
3150
|
+
}
|
|
3151
|
+
: undefined;
|
|
3152
|
+
|
|
3153
|
+
const storageConfigForCrawl = await getTenantStorageConfig(tenantId).catch(() => null);
|
|
3154
|
+
|
|
3155
|
+
const result = await crawlProject({
|
|
3156
|
+
...config,
|
|
3157
|
+
credentials: runtimeCreds,
|
|
3158
|
+
storageState: config.storageState ?? savedCrawlConfig.storageState,
|
|
3159
|
+
proxyUrl: config.proxyUrl ?? savedCrawlConfig.proxyUrl,
|
|
3160
|
+
loginInstructions: config.loginInstructions ?? savedCrawlConfig.loginInstructions,
|
|
3161
|
+
abortSignal: controller.signal,
|
|
3162
|
+
jobId,
|
|
3163
|
+
storageConfig: storageConfigForCrawl,
|
|
3164
|
+
}, onProgress);
|
|
3165
|
+
|
|
3166
|
+
clearInterval(heartbeatTimer);
|
|
3167
|
+
runningControllers.delete(jobId);
|
|
3168
|
+
|
|
3169
|
+
// Tag discovered screens with this role
|
|
3170
|
+
const roleName = config.roleProfileName as string;
|
|
3171
|
+
const discovered: any[] = (result as any).discovered ?? [];
|
|
3172
|
+
const roleScreenIds = discovered.filter((d: any) => d.screenId).map((d: any) => d.screenId as string);
|
|
3173
|
+
|
|
3174
|
+
if (roleScreenIds.length > 0 && roleName) {
|
|
3175
|
+
await prismaAdmin.$executeRaw`
|
|
3176
|
+
UPDATE "Screen"
|
|
3177
|
+
SET "roleAccess" = array(SELECT DISTINCT unnest(array_append("roleAccess", ${roleName}::text)))
|
|
3178
|
+
WHERE id = ANY(${roleScreenIds}::text[])
|
|
3179
|
+
AND "tenantId" = ${tenantId}
|
|
3180
|
+
`.catch((e: any) => logger.warn({ err: e?.message, roleName, count: roleScreenIds.length }, '[role-crawl] roleAccess tag failed (non-fatal)'));
|
|
3181
|
+
}
|
|
3182
|
+
|
|
3183
|
+
await withTenant(tenantId, (tx) =>
|
|
3184
|
+
tx.platformJob.update({
|
|
3185
|
+
where: { id: jobId },
|
|
3186
|
+
data: {
|
|
3187
|
+
status: 'DONE',
|
|
3188
|
+
progress: 100,
|
|
3189
|
+
finishedAt: new Date(),
|
|
3190
|
+
result: { screensTagged: roleScreenIds.length, roleName } as any,
|
|
3191
|
+
},
|
|
3192
|
+
})
|
|
3193
|
+
);
|
|
3194
|
+
logger.info({ jobId, roleName, screensTagged: roleScreenIds.length, projectId }, '[role-crawl] completed');
|
|
3195
|
+
} catch (err: any) {
|
|
3196
|
+
clearInterval(heartbeatTimer);
|
|
3197
|
+
runningControllers.delete(jobId);
|
|
3198
|
+
const aborted = String(err).includes('CRAWL_ABORTED');
|
|
3199
|
+
await withTenant(tenantId, (tx) =>
|
|
3200
|
+
tx.platformJob.update({
|
|
3201
|
+
where: { id: jobId },
|
|
3202
|
+
data: {
|
|
3203
|
+
status: aborted ? 'CANCELLED' : 'FAILED',
|
|
3204
|
+
error: aborted ? 'Stopped by user' : String(err),
|
|
3205
|
+
finishedAt: new Date(),
|
|
3206
|
+
},
|
|
3207
|
+
})
|
|
3208
|
+
);
|
|
3209
|
+
} finally {
|
|
3210
|
+
runningControllers.delete(jobId);
|
|
3211
|
+
}
|
|
3212
|
+
} catch (err: any) {
|
|
3213
|
+
const msg = String(err?.message ?? err);
|
|
3214
|
+
logger.error({ jobId, err: msg }, '[role-crawl] outer failure');
|
|
3215
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3216
|
+
}
|
|
3217
|
+
}
|
|
3218
|
+
|
|
3219
|
+
async function processGenerateScriptJob(jobId: string, config: any): Promise<void> {
|
|
3220
|
+
const { tenantId, projectId, language } = config;
|
|
3221
|
+
try {
|
|
3222
|
+
await updateJobProgress(tenantId, jobId, 1, 'Loading test cases…').catch(() => {});
|
|
3223
|
+
|
|
3224
|
+
if (config.packId) {
|
|
3225
|
+
// Pack script (regression / smoke / sanity / etc.)
|
|
3226
|
+
const { assertScriptGenerationReady, generatePackScript } = await import('@taodigital/agents');
|
|
3227
|
+
await assertScriptGenerationReady({ tenantId, projectId, packType: config.packId });
|
|
3228
|
+
const result = await generatePackScript({ tenantId, projectId, packType: config.packId, language });
|
|
3229
|
+
await withTenant(tenantId, (tx) =>
|
|
3230
|
+
tx.platformJob.update({
|
|
3231
|
+
where: { id: jobId },
|
|
3232
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: result as any },
|
|
3233
|
+
})
|
|
3234
|
+
);
|
|
3235
|
+
} else {
|
|
3236
|
+
// Suite script
|
|
3237
|
+
const { assertScriptGenerationReady, generateSuiteScript } = await import('@taodigital/agents');
|
|
3238
|
+
await assertScriptGenerationReady({ tenantId, projectId, suiteId: config.suiteId, caseIds: config.caseIds ?? undefined });
|
|
3239
|
+
let progressChain: Promise<void> = Promise.resolve();
|
|
3240
|
+
const result = await generateSuiteScript({
|
|
3241
|
+
tenantId, projectId, suiteId: config.suiteId, language,
|
|
3242
|
+
caseIds: config.caseIds ?? undefined,
|
|
3243
|
+
useV2: config.useV2,
|
|
3244
|
+
styleProfile: config.repoStyleProfile ?? undefined,
|
|
3245
|
+
pageObjectInventory: config.repoPageObjects ?? undefined,
|
|
3246
|
+
jobId,
|
|
3247
|
+
onProgress: (done: number, total: number) => {
|
|
3248
|
+
progressChain = progressChain
|
|
3249
|
+
.then(() => updateJobProgress(tenantId, jobId, Math.floor((done / total) * 95), `Generated ${done}/${total} scripts`))
|
|
3250
|
+
.catch(() => {});
|
|
3251
|
+
},
|
|
3252
|
+
});
|
|
3253
|
+
await progressChain.catch(() => {});
|
|
3254
|
+
await import('@taodigital/agents')
|
|
3255
|
+
.then(({ refreshScriptInventory }) => refreshScriptInventory(tenantId, projectId))
|
|
3256
|
+
.catch((e: any) => logger.warn({ err: e?.message }, '[generate-script] refreshScriptInventory failed'));
|
|
3257
|
+
await withTenant(tenantId, (tx) =>
|
|
3258
|
+
tx.platformJob.update({
|
|
3259
|
+
where: { id: jobId },
|
|
3260
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: result as any },
|
|
3261
|
+
})
|
|
3262
|
+
);
|
|
3263
|
+
}
|
|
3264
|
+
} catch (e: any) {
|
|
3265
|
+
await finishTrackedJob(tenantId, jobId, e?.message ?? 'generate-script failed');
|
|
3266
|
+
}
|
|
3267
|
+
}
|
|
3268
|
+
|
|
3269
|
+
function queueImportedArtifactSkillRefresh(tenantId: string, projectId: string, reason: string): void {
|
|
3270
|
+
setImmediate(() => {
|
|
3271
|
+
import('@taodigital/agents')
|
|
3272
|
+
.then((agentsModule) => {
|
|
3273
|
+
const agents = agentsModule as any;
|
|
3274
|
+
return Promise.allSettled([
|
|
3275
|
+
agents.refreshArtifactKnowledgeSkillFile(tenantId, projectId),
|
|
3276
|
+
agents.refreshRequirementsCoverageSkillFile(tenantId, projectId),
|
|
3277
|
+
]);
|
|
3278
|
+
})
|
|
3279
|
+
.then((results) => {
|
|
3280
|
+
results?.forEach((result) => {
|
|
3281
|
+
if (result.status === 'rejected') {
|
|
3282
|
+
console.warn(`[artifacts] skill refresh failed after ${reason}:`, result.reason?.message ?? result.reason);
|
|
3283
|
+
}
|
|
3284
|
+
});
|
|
3285
|
+
})
|
|
3286
|
+
.catch((e) => console.warn(`[artifacts] skill refresh failed after ${reason}:`, e?.message ?? e));
|
|
3287
|
+
});
|
|
3288
|
+
}
|
|
3289
|
+
|
|
3290
|
+
// Registers the type→processor dispatch table used by the durable worker (both the
|
|
3291
|
+
// enqueueJob() fast-path kick and startJobWorkerLoop()'s poll). Declared at module
|
|
3292
|
+
// bottom so it can reference every process*Job function by name; function
|
|
3293
|
+
// declarations are hoisted, so this could technically live anywhere in the file,
|
|
3294
|
+
// but keeping it here alongside the last definition keeps the mapping easy to audit
|
|
3295
|
+
// against the actual functions above.
|
|
3296
|
+
const CONTENT_DETECTED_DOC_TYPES = new Set(['FUNCTIONIZE_TC', 'SELENIUM_SCRIPT', 'ENV_CONFIG']);
|
|
3297
|
+
const AI_DOC_TYPES = new Set([
|
|
3298
|
+
'REQUIREMENTS', 'USER_STORY', 'TEST_CASES', 'TEST_DATA', 'AUTOMATION_SCRIPT', 'API_SPEC', 'ARCHITECTURE', 'REPORT', 'OTHER',
|
|
3299
|
+
'SPREADSHEET', 'DATASHEET',
|
|
3300
|
+
]);
|
|
3301
|
+
const AI_DOC_TYPE_ALIASES: Record<string, string> = {
|
|
3302
|
+
REQUIREMENT: 'REQUIREMENTS', SPEC: 'REQUIREMENTS', SPECIFICATION: 'REQUIREMENTS',
|
|
3303
|
+
USER_STORIES: 'USER_STORY', STORY: 'USER_STORY',
|
|
3304
|
+
TEST_CASE: 'TEST_CASES', TESTCASES: 'TEST_CASES',
|
|
3305
|
+
TESTDATA: 'TEST_DATA', SCRIPT: 'AUTOMATION_SCRIPT', AUTOMATION: 'AUTOMATION_SCRIPT',
|
|
3306
|
+
};
|
|
3307
|
+
function normalizeAiDocType(raw: unknown): string {
|
|
3308
|
+
const key = String(raw ?? '').trim().toUpperCase().replace(/[\s-]+/g, '_');
|
|
3309
|
+
const mapped = AI_DOC_TYPE_ALIASES[key] ?? key;
|
|
3310
|
+
return AI_DOC_TYPES.has(mapped) ? mapped : 'OTHER';
|
|
3311
|
+
}
|
|
3312
|
+
|
|
3313
|
+
async function processArtifactIntelJob(jobId: string, config: any) {
|
|
3314
|
+
const { tenantId, projectId, artifactId, artifactName, isReprocess } = config;
|
|
3315
|
+
try {
|
|
3316
|
+
await updateJobProgress(tenantId, jobId, 10, 'Downloading artifact content');
|
|
3317
|
+
|
|
3318
|
+
const artifact = await withTenant(tenantId, (tx) =>
|
|
3319
|
+
(tx as any).projectArtifact.findUnique({ where: { id: artifactId }, select: { storageKey: true, docType: true } })
|
|
3320
|
+
) as any;
|
|
3321
|
+
|
|
3322
|
+
if (!artifact || !artifact.storageKey) {
|
|
3323
|
+
await updateJobProgress(tenantId, jobId, 100, 'Artifact deleted or missing content, skipping.');
|
|
3324
|
+
await withTenant(tenantId, (tx) =>
|
|
3325
|
+
(tx as any).platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date() } })
|
|
3326
|
+
);
|
|
3327
|
+
return;
|
|
3328
|
+
}
|
|
3329
|
+
|
|
3330
|
+
const storageCfg = await getTenantStorageConfig(tenantId);
|
|
3331
|
+
if (!storageCfg) {
|
|
3332
|
+
throw new Error('Tenant storage configuration missing.');
|
|
3333
|
+
}
|
|
3334
|
+
const contentBuffer = await downloadBufferFromTenantStorage(storageCfg, artifact.storageKey);
|
|
3335
|
+
const content = contentBuffer.toString('utf8');
|
|
3336
|
+
|
|
3337
|
+
await updateJobProgress(tenantId, jobId, 40, 'Generating intelligence');
|
|
3338
|
+
|
|
3339
|
+
const intel = await generateArtifactIntelligence(tenantId, projectId, artifactId, content, artifactName, jobId);
|
|
3340
|
+
|
|
3341
|
+
const finalDocType = artifact.docType && CONTENT_DETECTED_DOC_TYPES.has(artifact.docType)
|
|
3342
|
+
? artifact.docType
|
|
3343
|
+
: normalizeAiDocType(intel.docType);
|
|
3344
|
+
|
|
3345
|
+
if (finalDocType !== intel.docType) {
|
|
3346
|
+
await withTenant(tenantId, (tx) =>
|
|
3347
|
+
(tx as any).projectArtifact.update({ where: { id: artifactId }, data: { docType: finalDocType } })
|
|
3348
|
+
).catch((err: any) => console.warn(`[artifact-intel] docType fix-up failed for "${artifactName}":`, err?.message));
|
|
3349
|
+
intel.docType = finalDocType;
|
|
3350
|
+
}
|
|
3351
|
+
|
|
3352
|
+
await updateJobProgress(tenantId, jobId, 90, 'Saving results');
|
|
3353
|
+
|
|
3354
|
+
await withTenant(tenantId, (tx) =>
|
|
3355
|
+
(tx as any).platformJob.update({ where: { id: jobId }, data: { result: { artifactId, artifactName, summary: intel.summary, keywords: intel.keywords, docType: intel.docType }, status: 'DONE', finishedAt: new Date(), progress: 100 } })
|
|
3356
|
+
);
|
|
3357
|
+
|
|
3358
|
+
queueImportedArtifactSkillRefresh(tenantId, projectId, isReprocess ? 'artifact-reprocess' : 'artifact-intel');
|
|
3359
|
+
} catch (err: any) {
|
|
3360
|
+
const msg = String(err?.message ?? err);
|
|
3361
|
+
logger.error({ jobId, err: msg }, '[artifact-intel] failed');
|
|
3362
|
+
await withTenant(tenantId, (tx) =>
|
|
3363
|
+
(tx as any).projectArtifact.update({ where: { id: artifactId }, data: { status: 'ERROR', summary: 'AI analysis failed' } })
|
|
3364
|
+
).catch(() => { });
|
|
3365
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3366
|
+
queueImportedArtifactSkillRefresh(tenantId, projectId, 'artifact-intel-failed');
|
|
3367
|
+
}
|
|
3368
|
+
}
|
|
3369
|
+
|
|
3370
|
+
// ── GAP-001: Newman server-side execution ────────────────────────────────────
|
|
3371
|
+
|
|
3372
|
+
async function processPostmanRunJob(jobId: string, config: any): Promise<void> {
|
|
3373
|
+
const { tenantId, projectId, runId, collection, environment, timeoutMs = 300_000 } = config;
|
|
3374
|
+
await withTenant(tenantId, (tx) =>
|
|
3375
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: new Date() } })
|
|
3376
|
+
);
|
|
3377
|
+
// GAP-003: historyId declared outside try so catch can reference it
|
|
3378
|
+
let historyId: string | null = null;
|
|
3379
|
+
try {
|
|
3380
|
+
await updateJobProgress(tenantId, jobId, 10, 'Preparing Newman run');
|
|
3381
|
+
|
|
3382
|
+
const tmpDir = path.join(os.tmpdir(), 'zeta-newman', String(runId ?? jobId));
|
|
3383
|
+
await fs.mkdir(tmpDir, { recursive: true });
|
|
3384
|
+
|
|
3385
|
+
// GAP-003: create run history record
|
|
3386
|
+
try {
|
|
3387
|
+
const hist = await prismaAdmin.apiTestRunHistory.create({
|
|
3388
|
+
data: { tenantId, projectId, status: 'running', source: 'newman' },
|
|
3389
|
+
select: { id: true },
|
|
3390
|
+
});
|
|
3391
|
+
historyId = hist.id;
|
|
3392
|
+
} catch { /* non-fatal — history tracking is best-effort */ }
|
|
3393
|
+
|
|
3394
|
+
const collectionPath = path.join(tmpDir, 'collection.json');
|
|
3395
|
+
const envPath = path.join(tmpDir, 'environment.json');
|
|
3396
|
+
const resultsPath = path.join(tmpDir, 'results.json');
|
|
3397
|
+
|
|
3398
|
+
await fs.writeFile(collectionPath, JSON.stringify(collection ?? {}));
|
|
3399
|
+
if (environment) await fs.writeFile(envPath, JSON.stringify(environment));
|
|
3400
|
+
|
|
3401
|
+
// GAP-017: data-driven iteration — write iteration data if provided
|
|
3402
|
+
const iterationDataPath = path.join(tmpDir, 'iteration-data.json');
|
|
3403
|
+
if (config.iterationDataJson) {
|
|
3404
|
+
await fs.writeFile(iterationDataPath, config.iterationDataJson);
|
|
3405
|
+
}
|
|
3406
|
+
|
|
3407
|
+
const newmanArgs = [
|
|
3408
|
+
'--yes', 'newman', 'run', collectionPath,
|
|
3409
|
+
...(environment ? ['-e', envPath] : []),
|
|
3410
|
+
...(config.iterationDataJson ? ['--iteration-data', iterationDataPath] : []),
|
|
3411
|
+
'--reporters', 'json',
|
|
3412
|
+
'--reporter-json-export', resultsPath,
|
|
3413
|
+
'--timeout', String(timeoutMs),
|
|
3414
|
+
'--suppress-exit-code',
|
|
3415
|
+
'--disable-unicode',
|
|
3416
|
+
];
|
|
3417
|
+
|
|
3418
|
+
await updateJobProgress(tenantId, jobId, 30, 'Running Newman');
|
|
3419
|
+
|
|
3420
|
+
await new Promise<void>((resolve, reject) => {
|
|
3421
|
+
const proc = spawn('npx', newmanArgs, {
|
|
3422
|
+
cwd: tmpDir,
|
|
3423
|
+
timeout: timeoutMs + 10_000,
|
|
3424
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
3425
|
+
});
|
|
3426
|
+
proc.on('close', () => resolve());
|
|
3427
|
+
proc.on('error', reject);
|
|
3428
|
+
});
|
|
3429
|
+
|
|
3430
|
+
await updateJobProgress(tenantId, jobId, 80, 'Parsing Newman results');
|
|
3431
|
+
|
|
3432
|
+
let summary = { total: 0, passed: 0, failed: 0, skipped: 0, durationMs: 0 };
|
|
3433
|
+
|
|
3434
|
+
try {
|
|
3435
|
+
const raw = await fs.readFile(resultsPath, 'utf-8');
|
|
3436
|
+
const results = JSON.parse(raw) as any;
|
|
3437
|
+
const executions: any[] = results.run?.executions ?? [];
|
|
3438
|
+
|
|
3439
|
+
for (const exec of executions) {
|
|
3440
|
+
const assertions: any[] = exec.assertions ?? [];
|
|
3441
|
+
const failed = assertions.filter((a: any) => !!a.error).length;
|
|
3442
|
+
const status = failed === 0 ? 'passed' : 'failed';
|
|
3443
|
+
summary.total++;
|
|
3444
|
+
if (status === 'passed') summary.passed++; else summary.failed++;
|
|
3445
|
+
}
|
|
3446
|
+
|
|
3447
|
+
const timings = results.run?.timings ?? {};
|
|
3448
|
+
summary.durationMs = (timings.completed ?? 0) - (timings.started ?? 0);
|
|
3449
|
+
|
|
3450
|
+
logger.info({ tenantId, projectId, runId, jobId, ...summary }, '[newman] run complete');
|
|
3451
|
+
|
|
3452
|
+
// GAP-003: persist per-request results
|
|
3453
|
+
if (historyId) {
|
|
3454
|
+
const requestRows = executions.map((exec: any) => {
|
|
3455
|
+
const assertions = exec.assertions ?? [];
|
|
3456
|
+
const failed = assertions.filter((a: any) => !!a.error).length;
|
|
3457
|
+
return {
|
|
3458
|
+
runHistoryId: historyId!,
|
|
3459
|
+
requestName: exec.item?.name ?? exec.item?.id ?? 'Unknown',
|
|
3460
|
+
status: failed === 0 ? 'passed' : 'failed',
|
|
3461
|
+
statusCode: exec.response?.code ?? null,
|
|
3462
|
+
durationMs: exec.response?.responseTime ?? null,
|
|
3463
|
+
assertions: assertions.length > 0 ? assertions : undefined,
|
|
3464
|
+
requestUrl: exec.request?.url?.raw ?? null,
|
|
3465
|
+
error: failed > 0 ? (assertions.find((a: any) => a.error)?.error?.message ?? 'Assertion failed') : null,
|
|
3466
|
+
};
|
|
3467
|
+
});
|
|
3468
|
+
try {
|
|
3469
|
+
await prismaAdmin.apiTestRunRequest.createMany({ data: requestRows });
|
|
3470
|
+
await prismaAdmin.apiTestRunHistory.update({
|
|
3471
|
+
where: { id: historyId },
|
|
3472
|
+
data: {
|
|
3473
|
+
status: summary.failed > 0 ? 'failed' : 'passed',
|
|
3474
|
+
summary: summary as any,
|
|
3475
|
+
completedAt: new Date(),
|
|
3476
|
+
},
|
|
3477
|
+
});
|
|
3478
|
+
} catch (e) { /* best-effort */ }
|
|
3479
|
+
}
|
|
3480
|
+
} catch (err) {
|
|
3481
|
+
logger.error({ err, jobId }, '[newman] failed to parse results');
|
|
3482
|
+
}
|
|
3483
|
+
|
|
3484
|
+
await fs.rm(tmpDir, { recursive: true, force: true }).catch(() => {});
|
|
3485
|
+
|
|
3486
|
+
await withTenant(tenantId, (tx) =>
|
|
3487
|
+
tx.platformJob.update({
|
|
3488
|
+
where: { id: jobId },
|
|
3489
|
+
data: { status: 'DONE', progress: 100, finishedAt: new Date(), result: summary as any },
|
|
3490
|
+
})
|
|
3491
|
+
);
|
|
3492
|
+
} catch (err: any) {
|
|
3493
|
+
logger.error({ jobId, err: String(err?.message ?? err) }, '[newman] job failed');
|
|
3494
|
+
if (historyId) {
|
|
3495
|
+
await prismaAdmin.apiTestRunHistory.update({
|
|
3496
|
+
where: { id: historyId },
|
|
3497
|
+
data: { status: 'error', completedAt: new Date() },
|
|
3498
|
+
}).catch(() => {});
|
|
3499
|
+
}
|
|
3500
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3501
|
+
}
|
|
3502
|
+
}
|
|
3503
|
+
|
|
3504
|
+
jobDispatchTable = {
|
|
3505
|
+
ARTIFACT_INTEL: processArtifactIntelJob,
|
|
3506
|
+
CRAWL: processJob,
|
|
3507
|
+
CAPTURE_STEPS: processCaptureStepsJob,
|
|
3508
|
+
DISCOVER: processDiscoverJob,
|
|
3509
|
+
MONITOR: processMonitorJob,
|
|
3510
|
+
NATIVE_CRAWL: processNativeCrawlJob,
|
|
3511
|
+
API_TESTS: processApiTestsJob,
|
|
3512
|
+
SECURITY_TESTS: processSecurityTestsJob,
|
|
3513
|
+
INTEGRATION_TESTS: processIntegrationTestsJob,
|
|
3514
|
+
FIGMA_IMPORT: processFigmaImportJob,
|
|
3515
|
+
GENERATE_SKILL_FILES: processGenerateSkillFilesJob,
|
|
3516
|
+
GENERATE_TESTS_FROM_REQS: processGenerateTestsFromReqsJob,
|
|
3517
|
+
GENERATE_SCREEN_TESTS: processGenerateScreenTestsJob,
|
|
3518
|
+
RUN_TEST_SUITE: processRunTestSuiteJob,
|
|
3519
|
+
REPO_SCAN: processRepoScanJob,
|
|
3520
|
+
IMPORT_TESTS: processImportTestsJob,
|
|
3521
|
+
BATCH_GENERATE_ALIGNED: processBatchGenerateAlignedJob,
|
|
3522
|
+
CREATE_PR: processCreatePRJob,
|
|
3523
|
+
NEW_PAGES_PIPELINE: processNewPagesPipelineJob,
|
|
3524
|
+
MULTI_ROLE_CRAWL: processMultiRoleCrawlJob,
|
|
3525
|
+
ROLE_CRAWL: processRoleCrawlJob,
|
|
3526
|
+
GENERATE_SCRIPT: processGenerateScriptJob,
|
|
3527
|
+
POSTMAN_RUN: processPostmanRunJob,
|
|
3528
|
+
// The following job types are still processed in-process by the API.
|
|
3529
|
+
// If the worker claims one, the API crashed after creating it — mark failed so it's visible.
|
|
3530
|
+
GENERATE_TESTS: async (jobId: string, _config: any) => {
|
|
3531
|
+
logger.error({ jobId }, '[job-worker] GENERATE_TESTS claimed by worker — API did not process it in-process');
|
|
3532
|
+
await prismaAdmin.platformJob.update({
|
|
3533
|
+
where: { id: jobId },
|
|
3534
|
+
data: { status: 'FAILED', error: 'Test generation was not completed by the API — please retry from the UI.', finishedAt: new Date() },
|
|
3535
|
+
}).catch(() => { });
|
|
3536
|
+
},
|
|
3537
|
+
GENERATE_DATA: async (jobId: string, _config: any) => {
|
|
3538
|
+
logger.error({ jobId }, '[job-worker] GENERATE_DATA claimed by worker — API did not process it in-process');
|
|
3539
|
+
await prismaAdmin.platformJob.update({
|
|
3540
|
+
where: { id: jobId },
|
|
3541
|
+
data: { status: 'FAILED', error: 'Data generation was not completed by the API — please retry from the UI.', finishedAt: new Date() },
|
|
3542
|
+
}).catch(() => { });
|
|
3543
|
+
},
|
|
3544
|
+
GENERATE_TEST_PLAN: async (jobId: string, _config: any) => {
|
|
3545
|
+
logger.error({ jobId }, '[job-worker] GENERATE_TEST_PLAN claimed by worker — API did not process it in-process');
|
|
3546
|
+
await prismaAdmin.platformJob.update({
|
|
3547
|
+
where: { id: jobId },
|
|
3548
|
+
data: { status: 'FAILED', error: 'Test plan generation was not completed by the API — please retry from the UI.', finishedAt: new Date() },
|
|
3549
|
+
}).catch(() => { });
|
|
3550
|
+
},
|
|
3551
|
+
SCREENSHOT_ENHANCE: async (jobId: string, config: any) => {
|
|
3552
|
+
const { tenantId, projectId } = config as { tenantId: string; projectId: string };
|
|
3553
|
+
const jobStartedAt = new Date();
|
|
3554
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } }).catch(() => {});
|
|
3555
|
+
try {
|
|
3556
|
+
const cfg = config as { artifactId: string; projectId: string };
|
|
3557
|
+
const { analyzeScreenshotForEnhancement, diffScreenshotElementsAgainstTestCases, updateProjectContextSources } = await import('@taodigital/agents');
|
|
3558
|
+
const artifact = await (prismaAdmin as any).projectArtifact?.findFirst({ where: { id: cfg.artifactId, tenantId } })
|
|
3559
|
+
?? await (prismaAdmin as any).artifact?.findFirst({ where: { id: cfg.artifactId, tenantId } });
|
|
3560
|
+
if (!artifact) {
|
|
3561
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { skipped: true, reason: 'artifact not found' } as any } }).catch(() => {});
|
|
3562
|
+
return;
|
|
3563
|
+
}
|
|
3564
|
+
let imageBase64 = '';
|
|
3565
|
+
if (artifact.cloudUrl) {
|
|
3566
|
+
try {
|
|
3567
|
+
const res = await fetch(artifact.cloudUrl);
|
|
3568
|
+
const buf = await res.arrayBuffer();
|
|
3569
|
+
imageBase64 = Buffer.from(buf).toString('base64');
|
|
3570
|
+
} catch (_) {}
|
|
3571
|
+
}
|
|
3572
|
+
const analysisResult = await analyzeScreenshotForEnhancement(tenantId, projectId, cfg.artifactId, imageBase64);
|
|
3573
|
+
const testCases = await (prismaAdmin as any).testCase.findMany({ where: { tenantId, projectId }, take: 100 });
|
|
3574
|
+
const payload = await diffScreenshotElementsAgainstTestCases(tenantId, projectId, analysisResult.elements, testCases);
|
|
3575
|
+
const enhancement = await (prismaAdmin as any).contextEnhancement.create({
|
|
3576
|
+
data: { tenantId, projectId, sourceType: 'SCREENSHOT', sourceRef: cfg.artifactId, status: payload.proposedChanges.length > 0 ? 'DIFF_READY' : 'APPROVED', proposedChanges: payload.proposedChanges },
|
|
3577
|
+
});
|
|
3578
|
+
if (analysisResult.elements.length > 0) {
|
|
3579
|
+
await (prismaAdmin as any).extractedElement.createMany({ data: analysisResult.elements.map((el: any) => ({ tenantId, projectId, sourceEnhancementId: enhancement.id, ...el })) }).catch(() => {});
|
|
3580
|
+
}
|
|
3581
|
+
await updateProjectContextSources(tenantId, projectId, 'SCREENSHOT', { count: 1 });
|
|
3582
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), progress: 100, result: { enhancementId: enhancement.id, elementsFound: analysisResult.elements.length, changesProposed: payload.proposedChanges.length } as any } }).catch(() => {});
|
|
3583
|
+
} catch (err: any) {
|
|
3584
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3585
|
+
}
|
|
3586
|
+
},
|
|
3587
|
+
FIGMA_ENHANCE: async (jobId: string, config: any) => {
|
|
3588
|
+
const { tenantId, projectId } = config as { tenantId: string; projectId: string };
|
|
3589
|
+
const jobStartedAt = new Date();
|
|
3590
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } }).catch(() => {});
|
|
3591
|
+
try {
|
|
3592
|
+
const { analyzeFigmaComponentsForEnhancement, updateProjectContextSources } = await import('@taodigital/agents');
|
|
3593
|
+
const figmaComponents = await (prismaAdmin as any).figmaComponent.findMany({ where: { tenantId, projectId } });
|
|
3594
|
+
const testCases = await (prismaAdmin as any).testCase.findMany({ where: { tenantId, projectId }, take: 100 });
|
|
3595
|
+
const payload = await analyzeFigmaComponentsForEnhancement(tenantId, projectId, figmaComponents, testCases);
|
|
3596
|
+
const enhancement = await (prismaAdmin as any).contextEnhancement.create({
|
|
3597
|
+
data: { tenantId, projectId, sourceType: 'FIGMA', status: payload.proposedChanges.length > 0 ? 'DIFF_READY' : 'APPROVED', proposedChanges: payload.proposedChanges },
|
|
3598
|
+
});
|
|
3599
|
+
await updateProjectContextSources(tenantId, projectId, 'FIGMA', { importedAt: new Date().toISOString() });
|
|
3600
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), progress: 100, result: { enhancementId: enhancement.id, changesProposed: payload.proposedChanges.length } as any } }).catch(() => {});
|
|
3601
|
+
} catch (err: any) {
|
|
3602
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3603
|
+
}
|
|
3604
|
+
},
|
|
3605
|
+
CRAWL_DIFF: async (jobId: string, config: any) => {
|
|
3606
|
+
const { tenantId, projectId } = config as { tenantId: string; projectId: string };
|
|
3607
|
+
const jobStartedAt = new Date();
|
|
3608
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } }).catch(() => {});
|
|
3609
|
+
try {
|
|
3610
|
+
const { computeCrawlDiffs } = await import('@taodigital/agents');
|
|
3611
|
+
const { fromJobId, toJobId } = config as { fromJobId: string; toJobId: string };
|
|
3612
|
+
const result = await computeCrawlDiffs(tenantId, projectId, fromJobId, toJobId);
|
|
3613
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), progress: 100, result: result as any } }).catch(() => {});
|
|
3614
|
+
} catch (err: any) {
|
|
3615
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3616
|
+
}
|
|
3617
|
+
},
|
|
3618
|
+
ANALYZE_FAILURES: async (jobId: string, config: any) => {
|
|
3619
|
+
const { tenantId, projectId } = config as { tenantId: string; projectId: string };
|
|
3620
|
+
const jobStartedAt = new Date();
|
|
3621
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'RUNNING', startedAt: jobStartedAt } }).catch(() => {});
|
|
3622
|
+
try {
|
|
3623
|
+
const { analyzeTestRunFailures, computeRequirementCoverage, computeCoverageGaps } = await import('@taodigital/agents');
|
|
3624
|
+
const { runId } = config as { runId: string };
|
|
3625
|
+
const [failures, coverage, gaps] = await Promise.all([
|
|
3626
|
+
analyzeTestRunFailures(tenantId, projectId, runId),
|
|
3627
|
+
computeRequirementCoverage(tenantId, projectId),
|
|
3628
|
+
computeCoverageGaps(tenantId, projectId),
|
|
3629
|
+
]);
|
|
3630
|
+
await prismaAdmin.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), progress: 100, result: { failures, coverage, gaps } as any } }).catch(() => {});
|
|
3631
|
+
} catch (err: any) {
|
|
3632
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
3633
|
+
}
|
|
3634
|
+
},
|
|
3635
|
+
};
|
|
3636
|
+
|
|
3637
|
+
async function processRepoScanJob(jobId: string, config: any) {
|
|
3638
|
+
const { repoConnectionId, tenantId, projectId } = config;
|
|
3639
|
+
const jobStart = new Date();
|
|
3640
|
+
try {
|
|
3641
|
+
await updateJobProgress(tenantId, jobId, 5, 'Starting repo scan');
|
|
3642
|
+
|
|
3643
|
+
const {
|
|
3644
|
+
fetchRepoTree, fetchFileContent, detectFramework,
|
|
3645
|
+
extractTestIds, extractStyleProfile,
|
|
3646
|
+
buildPageObjectInventory, resolveFixtureAliasesFromImports,
|
|
3647
|
+
} = await import('@taodigital/agents');
|
|
3648
|
+
|
|
3649
|
+
const conn = await withTenant(tenantId, (tx) =>
|
|
3650
|
+
tx.gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
|
|
3651
|
+
) as any;
|
|
3652
|
+
if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
|
|
3653
|
+
|
|
3654
|
+
// Decrypt token
|
|
3655
|
+
const { decrypt } = await import('@taodigital/core');
|
|
3656
|
+
const token = decrypt(conn.tokenEnc);
|
|
3657
|
+
|
|
3658
|
+
// Mark scanning
|
|
3659
|
+
await withTenant(tenantId, (tx) =>
|
|
3660
|
+
tx.gitHubRepoConnection.update({ where: { id: repoConnectionId }, data: { scanStatus: 'SCANNING', scanError: null } })
|
|
3661
|
+
);
|
|
3662
|
+
|
|
3663
|
+
await updateJobProgress(tenantId, jobId, 15, 'Fetching repo tree');
|
|
3664
|
+
// Use HEAD so it always resolves to the actual default branch regardless of stored value
|
|
3665
|
+
const treeResult = await fetchRepoTree(token, conn.repoFullName, 'HEAD');
|
|
3666
|
+
if (treeResult.truncated) {
|
|
3667
|
+
console.warn(`[repo-scan] ${conn.repoFullName}: tree truncated (>100k blobs) — detection may be incomplete`);
|
|
3668
|
+
await withTenant(tenantId, (tx) =>
|
|
3669
|
+
tx.gitHubRepoConnection.update({
|
|
3670
|
+
where: { id: repoConnectionId },
|
|
3671
|
+
data: { scanError: 'Repository tree was truncated by GitHub (>100k files) — some test files in deep subdirectories may be missing from this scan.' },
|
|
3672
|
+
})
|
|
3673
|
+
);
|
|
3674
|
+
}
|
|
3675
|
+
|
|
3676
|
+
const frameworks = detectFramework(treeResult.paths);
|
|
3677
|
+
const primary = frameworks[0];
|
|
3678
|
+
await updateJobProgress(tenantId, jobId, 30, `Detected framework: ${primary?.framework ?? 'unknown'}`);
|
|
3679
|
+
|
|
3680
|
+
// Prefer framework-detected glob when stored glob is the TS default (never explicitly set)
|
|
3681
|
+
const storedGlob = conn.testGlob || '';
|
|
3682
|
+
const testGlob = (storedGlob && storedGlob !== '**/*.spec.ts')
|
|
3683
|
+
? storedGlob
|
|
3684
|
+
: (primary?.testGlob || storedGlob || '**/*.spec.ts');
|
|
3685
|
+
const framework = primary?.framework ?? 'unknown';
|
|
3686
|
+
const language = primary?.language ?? 'typescript';
|
|
3687
|
+
|
|
3688
|
+
// Filter test files
|
|
3689
|
+
const { minimatch } = await import('minimatch').catch(() => ({ minimatch: null }));
|
|
3690
|
+
const isPythonTestFile = (p: string) =>
|
|
3691
|
+
p.endsWith('.py') && !p.endsWith('__init__.py') && !p.endsWith('conftest.py') &&
|
|
3692
|
+
(p.endsWith('_test.py') || /\/test_[^/]+\.py$/.test(p) || /^test_[^/]+\.py$/.test(p) ||
|
|
3693
|
+
p.includes('/tests/') || p.includes('/test/'));
|
|
3694
|
+
// Java: testGlob matches all *.java — further filter to actual test classes only
|
|
3695
|
+
// (excludes helpers, base classes, utilities that don't follow *Test.java/*Tests.java naming)
|
|
3696
|
+
const isJavaTestFile = (p: string) =>
|
|
3697
|
+
p.endsWith('.java') && (
|
|
3698
|
+
/[A-Z]\w*Tests?\.java$/.test(p) ||
|
|
3699
|
+
(/\/tests?\//.test(p) && /[A-Z][a-z]/.test(p.split('/').pop() ?? ''))
|
|
3700
|
+
);
|
|
3701
|
+
// Build list of globs to try — primary + common variants so we don't miss .test.ts alongside .spec.ts
|
|
3702
|
+
const testGlobs = minimatch
|
|
3703
|
+
? Array.from(new Set([
|
|
3704
|
+
testGlob,
|
|
3705
|
+
...(testGlob === '**/*.spec.ts' ? ['**/*.test.ts', '**/*.cy.ts'] : []),
|
|
3706
|
+
...(testGlob === '**/*.spec.js' ? ['**/*.test.js', '**/*.cy.js'] : []),
|
|
3707
|
+
]))
|
|
3708
|
+
: [];
|
|
3709
|
+
const testPaths = treeResult.paths.filter((p) => {
|
|
3710
|
+
if (language === 'java') return isJavaTestFile(p);
|
|
3711
|
+
if (language === 'python') return isPythonTestFile(p);
|
|
3712
|
+
if (testGlobs.length) return testGlobs.some(g => (minimatch as any)(p, g, { matchBase: true }));
|
|
3713
|
+
return p.endsWith('.spec.ts') || p.endsWith('.spec.js') || p.endsWith('.test.ts') || p.endsWith('.test.js') || p.endsWith('.cy.ts') || p.endsWith('.cy.js') || p.endsWith('_test.py') || p.includes('/test_');
|
|
3714
|
+
}).slice(0, 2000); // cap at 2000 test files
|
|
3715
|
+
|
|
3716
|
+
await updateJobProgress(tenantId, jobId, 40, `Found ${testPaths.length} test files`);
|
|
3717
|
+
|
|
3718
|
+
if (testPaths.length === 0) {
|
|
3719
|
+
logger.warn({ jobId, repoConnectionId, framework }, '[repo-scan] no test files matched glob — scan complete with 0 results');
|
|
3720
|
+
await withTenant(tenantId, (tx) =>
|
|
3721
|
+
tx.gitHubRepoConnection.update({
|
|
3722
|
+
where: { id: repoConnectionId },
|
|
3723
|
+
data: { scanStatus: 'DONE', testFileCount: 0, extractedIdCount: 0, lastScannedAt: new Date(), lastSyncAt: new Date() },
|
|
3724
|
+
})
|
|
3725
|
+
);
|
|
3726
|
+
await updateJobProgress(tenantId, jobId, 100, 'Done: 0 test files found');
|
|
3727
|
+
await withTenant(tenantId, (tx) =>
|
|
3728
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { testFileCount: 0, extractedIdCount: 0 } as any } })
|
|
3729
|
+
);
|
|
3730
|
+
return;
|
|
3731
|
+
}
|
|
3732
|
+
|
|
3733
|
+
// Extract test IDs from each file
|
|
3734
|
+
const allExtracted: any[] = [];
|
|
3735
|
+
const styleSampleFiles: Array<{ path: string; content: string }> = [];
|
|
3736
|
+
let processed = 0;
|
|
3737
|
+
|
|
3738
|
+
// Delete old test files for this connection
|
|
3739
|
+
await withTenant(tenantId, (tx) => tx.repoTestFile.deleteMany({ where: { repoConnectionId } }));
|
|
3740
|
+
|
|
3741
|
+
for (const filePath of testPaths) {
|
|
3742
|
+
const content = await fetchFileContent(token, conn.repoFullName, filePath);
|
|
3743
|
+
if (!content) continue;
|
|
3744
|
+
|
|
3745
|
+
// G-07: multi-file fixture tracing — resolve non-obvious aliases before extraction
|
|
3746
|
+
const extraAliases = await resolveFixtureAliasesFromImports(
|
|
3747
|
+
content, token, conn.repoFullName, filePath,
|
|
3748
|
+
).catch(() => new Set<string>());
|
|
3749
|
+
const extracted = extractTestIds(content, filePath, framework, extraAliases);
|
|
3750
|
+
allExtracted.push(...extracted);
|
|
3751
|
+
|
|
3752
|
+
await withTenant(tenantId, (tx) =>
|
|
3753
|
+
tx.repoTestFile.create({
|
|
3754
|
+
data: {
|
|
3755
|
+
tenantId,
|
|
3756
|
+
projectId,
|
|
3757
|
+
repoConnectionId,
|
|
3758
|
+
filePath,
|
|
3759
|
+
framework,
|
|
3760
|
+
extractedIds: extracted.map((e) => ({ name: e.name, normalizedName: e.normalizedName, lineNumber: e.lineNumber })) as any,
|
|
3761
|
+
rawSample: content.slice(0, 2000),
|
|
3762
|
+
lastScannedAt: new Date(),
|
|
3763
|
+
},
|
|
3764
|
+
})
|
|
3765
|
+
);
|
|
3766
|
+
|
|
3767
|
+
if (styleSampleFiles.length < 5) styleSampleFiles.push({ path: filePath, content: content.slice(0, 3000) });
|
|
3768
|
+
processed++;
|
|
3769
|
+
|
|
3770
|
+
if (processed % 10 === 0) {
|
|
3771
|
+
await updateJobProgress(tenantId, jobId, 40 + Math.floor((processed / testPaths.length) * 40), `Processed ${processed}/${testPaths.length} files`);
|
|
3772
|
+
}
|
|
3773
|
+
}
|
|
3774
|
+
|
|
3775
|
+
// Fetch and parse framework config files (playwright.config.ts, cypress.config.ts, tsconfig.json)
|
|
3776
|
+
// Fetch and parse framework config files for all supported frameworks.
|
|
3777
|
+
// Pure regex/JSON — no LLM. Results override LLM inference for path detection.
|
|
3778
|
+
// Covers: playwright, cypress, jest, pytest, junit/maven/gradle, selenium-java/py,
|
|
3779
|
+
// webdriverio, cucumber — all frameworks in DetectedFramework.
|
|
3780
|
+
const configPaths: {
|
|
3781
|
+
testDir?: string; fixturesFolder?: string; baseURL?: string;
|
|
3782
|
+
tsconfigPaths?: Record<string, string[]>; tsconfigBaseUrl?: string;
|
|
3783
|
+
javaTestSourceDir?: string; jestModuleNameMapper?: Record<string, string>;
|
|
3784
|
+
} = {};
|
|
3785
|
+
try {
|
|
3786
|
+
const pathSet = new Set(treeResult.paths as string[]);
|
|
3787
|
+
const lang = framework.includes('java') ? 'java'
|
|
3788
|
+
: (framework.includes('py') || framework === 'pytest') ? 'python' : 'js';
|
|
3789
|
+
|
|
3790
|
+
const configFilesToFetch: Array<{ path: string; type: string; dirPrefix: string }> = [];
|
|
3791
|
+
const tryAdd = (candidates: string[], type: string) => {
|
|
3792
|
+
for (const c of candidates) { if (pathSet.has(c)) { configFilesToFetch.push({ path: c, type, dirPrefix: '' }); break; } }
|
|
3793
|
+
};
|
|
3794
|
+
// Monorepo fallback: when root-level config is absent, find shallowest match anywhere in tree.
|
|
3795
|
+
// The dirPrefix (e.g. 'packages/e2e/') is prepended to testDir so paths are repo-root-relative.
|
|
3796
|
+
const scanTree = (pattern: RegExp, type: string) => {
|
|
3797
|
+
if (configFilesToFetch.some(f => f.type === type)) return;
|
|
3798
|
+
const all = (treeResult.paths as string[]).filter(p => pattern.test(p)).sort((a, b) => a.split('/').length - b.split('/').length);
|
|
3799
|
+
if (all[0]) {
|
|
3800
|
+
const lastSlash = all[0].lastIndexOf('/');
|
|
3801
|
+
const dirPrefix = lastSlash > 0 ? all[0].slice(0, lastSlash + 1) : '';
|
|
3802
|
+
configFilesToFetch.push({ path: all[0], type, dirPrefix });
|
|
3803
|
+
}
|
|
3804
|
+
};
|
|
3805
|
+
|
|
3806
|
+
if (lang === 'js') {
|
|
3807
|
+
if (framework.startsWith('playwright')) {
|
|
3808
|
+
tryAdd(['playwright.config.ts', 'playwright.config.js'], 'playwright');
|
|
3809
|
+
scanTree(/(?:^|\/)playwright\.config\.(ts|js|mts)$/, 'playwright');
|
|
3810
|
+
}
|
|
3811
|
+
if (framework.startsWith('cypress')) {
|
|
3812
|
+
tryAdd(['cypress.config.ts', 'cypress.config.js'], 'cypress');
|
|
3813
|
+
scanTree(/(?:^|\/)cypress\.config\.(ts|js)$/, 'cypress');
|
|
3814
|
+
}
|
|
3815
|
+
if (framework === 'jest-ts' || framework === 'jest-js') {
|
|
3816
|
+
tryAdd(['jest.config.ts', 'jest.config.js', 'jest.config.mjs'], 'jest');
|
|
3817
|
+
scanTree(/(?:^|\/)jest\.config\.(ts|js|mjs|cjs)$/, 'jest');
|
|
3818
|
+
tryAdd(['package.json'], 'package-json');
|
|
3819
|
+
}
|
|
3820
|
+
if (framework === 'webdriverio') {
|
|
3821
|
+
tryAdd(['wdio.conf.ts', 'wdio.conf.js', 'wdio.config.ts', 'wdio.config.js'], 'wdio');
|
|
3822
|
+
scanTree(/(?:^|\/)wdio\.(?:conf|config)\.(ts|js|mjs)$/, 'wdio');
|
|
3823
|
+
}
|
|
3824
|
+
if (framework === 'cucumber' || framework === 'gherkin') {
|
|
3825
|
+
tryAdd(['.cucumber.js', '.cucumber.cjs', 'cucumber.json', '.cucumber.yaml', '.cucumber.yml'], 'cucumber');
|
|
3826
|
+
tryAdd(['package.json'], 'package-json');
|
|
3827
|
+
}
|
|
3828
|
+
tryAdd(['tsconfig.json'], 'tsconfig');
|
|
3829
|
+
scanTree(/(?:^|\/)tsconfig(?:\.base)?\.json$/, 'tsconfig');
|
|
3830
|
+
} else if (lang === 'python') {
|
|
3831
|
+
tryAdd(['pytest.ini'], 'pytest-ini');
|
|
3832
|
+
scanTree(/(?:^|\/)pytest\.ini$/, 'pytest-ini');
|
|
3833
|
+
tryAdd(['pyproject.toml'], 'pyproject-toml');
|
|
3834
|
+
scanTree(/(?:^|\/)pyproject\.toml$/, 'pyproject-toml');
|
|
3835
|
+
tryAdd(['setup.cfg'], 'setup-cfg');
|
|
3836
|
+
} else if (lang === 'java') {
|
|
3837
|
+
tryAdd(['pom.xml'], 'pom-xml');
|
|
3838
|
+
scanTree(/(?:^|\/)pom\.xml$/, 'pom-xml');
|
|
3839
|
+
tryAdd(['build.gradle.kts', 'build.gradle'], 'build-gradle');
|
|
3840
|
+
scanTree(/(?:^|\/)build\.gradle(?:\.kts)?$/, 'build-gradle');
|
|
3841
|
+
tryAdd(['testng.xml', 'src/test/resources/testng.xml'], 'testng-xml');
|
|
3842
|
+
}
|
|
3843
|
+
|
|
3844
|
+
// Inline parsers — mirror parseFrameworkConfig from @taodigital/agents (kept inline to avoid build dep)
|
|
3845
|
+
const normDir = (s: string) => s.replace(/^\.\//, '').replace(/\/$/, '');
|
|
3846
|
+
const globRoot = (pattern: string): string | null => {
|
|
3847
|
+
const root = pattern.replace(/\/\*\*.*$/, '').replace(/\/\*[^*].*$/, '');
|
|
3848
|
+
return (root && !root.startsWith('*') && !root.startsWith('{')) ? normDir(root) : null;
|
|
3849
|
+
};
|
|
3850
|
+
|
|
3851
|
+
const fetched = await Promise.all(
|
|
3852
|
+
configFilesToFetch.map(async ({ path: cfgPath, type, dirPrefix }) => {
|
|
3853
|
+
const content = await fetchFileContent(token, conn.repoFullName, cfgPath).catch(() => null);
|
|
3854
|
+
if (!content) return null;
|
|
3855
|
+
const r: typeof configPaths = {};
|
|
3856
|
+
|
|
3857
|
+
if (type === 'playwright') {
|
|
3858
|
+
const m = content.match(/\btestDir\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3859
|
+
if (m) r.testDir = normDir(m[1]);
|
|
3860
|
+
const bm = content.match(/\bbaseURL\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3861
|
+
if (bm) r.baseURL = bm[1];
|
|
3862
|
+
} else if (type === 'cypress') {
|
|
3863
|
+
const sm = content.match(/\bspecPattern\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3864
|
+
if (sm) { const gr = globRoot(sm[1]); if (gr) r.testDir = gr; }
|
|
3865
|
+
const fm = content.match(/\bfixturesFolder\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3866
|
+
if (fm) r.fixturesFolder = normDir(fm[1]);
|
|
3867
|
+
const bm = content.match(/\bbaseUrl\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3868
|
+
if (bm) r.baseURL = bm[1];
|
|
3869
|
+
} else if (type === 'jest') {
|
|
3870
|
+
const rm = content.match(/\broots\s*:\s*\[([^\]]+)\]/);
|
|
3871
|
+
if (rm) { const fr = rm[1].match(/['"`]([^'"`]+)['"`]/)?.[1]; if (fr) r.testDir = fr.replace(/<rootDir>\/?/, '').replace(/\/$/, '') || 'src'; }
|
|
3872
|
+
if (!r.testDir) { const tm = content.match(/\btestMatch\s*:\s*\[([^\]]+)\]/); if (tm) { const fp = tm[1].match(/['"`]([^'"`]+)['"`]/)?.[1]; if (fp) { const gr = globRoot(fp.replace(/<rootDir>\/?/, '')); if (gr) r.testDir = gr; } } }
|
|
3873
|
+
const mm = content.match(/\bmoduleNameMapper\s*:\s*\{([^}]+)\}/s);
|
|
3874
|
+
if (mm) { const map: Record<string, string> = {}; for (const [, k, v] of mm[1].matchAll(/['"`]([^'"`]+)['"`]\s*:\s*['"`]([^'"`]+)['"`]/g)) map[k] = v; if (Object.keys(map).length) r.jestModuleNameMapper = map; }
|
|
3875
|
+
} else if (type === 'package-json') {
|
|
3876
|
+
try { const p = JSON.parse(content) as any; const j = p?.jest ?? {}; if (Array.isArray(j.roots) && j.roots[0]) r.testDir = String(j.roots[0]).replace(/<rootDir>\/?/, '').replace(/\/$/, '') || 'src'; if (!r.testDir && Array.isArray(j.testMatch) && j.testMatch[0]) { const gr = globRoot(String(j.testMatch[0]).replace(/<rootDir>\/?/, '')); if (gr) r.testDir = gr; } if (j.moduleNameMapper && typeof j.moduleNameMapper === 'object') r.jestModuleNameMapper = j.moduleNameMapper; } catch { /* ignore */ }
|
|
3877
|
+
} else if (type === 'tsconfig') {
|
|
3878
|
+
try { const stripped = content.replace(/\/\/[^\n]*/g, '').replace(/,(\s*[}\]])/g, '$1'); const p = JSON.parse(stripped) as any; const opts = p?.compilerOptions ?? {}; if (opts.paths && typeof opts.paths === 'object') r.tsconfigPaths = opts.paths; if (typeof opts.baseUrl === 'string') r.tsconfigBaseUrl = opts.baseUrl; } catch { /* ignore */ }
|
|
3879
|
+
} else if (type === 'pytest-ini') {
|
|
3880
|
+
const m = content.match(/^\s*testpaths\s*=\s*(.+)$/m);
|
|
3881
|
+
if (m) { const first = m[1].trim().split(/\s+/)[0]; if (first) r.testDir = normDir(first); }
|
|
3882
|
+
} else if (type === 'pyproject-toml') {
|
|
3883
|
+
const m = content.match(/testpaths\s*=\s*\[([^\]]+)\]/);
|
|
3884
|
+
if (m) { const first = m[1].match(/['"]([^'"]+)['"]/)?.[1]; if (first) r.testDir = normDir(first); }
|
|
3885
|
+
if (!r.testDir) { const m2 = content.match(/testpaths\s*=\s*['"]([^'"]+)['"]/); if (m2) r.testDir = normDir(m2[1]); }
|
|
3886
|
+
} else if (type === 'setup-cfg') {
|
|
3887
|
+
const m = content.match(/^\s*testpaths\s*=\s*(.+)$/m);
|
|
3888
|
+
if (m) { const first = m[1].trim().split(/[\s,]+/)[0]; if (first) r.testDir = normDir(first); }
|
|
3889
|
+
} else if (type === 'pom-xml') {
|
|
3890
|
+
const m = content.match(/<testSourceDirectory>\s*([^<]+)\s*<\/testSourceDirectory>/);
|
|
3891
|
+
if (m) r.javaTestSourceDir = normDir(m[1].trim());
|
|
3892
|
+
} else if (type === 'build-gradle') {
|
|
3893
|
+
const m = content.match(/srcDir[s]?\s*[=([]?\s*['"`]([^'"`]+)['"`]/) ?? content.match(/srcDir\s*\(\s*['"`]([^'"`]+)['"`]\s*\)/);
|
|
3894
|
+
if (m) r.javaTestSourceDir = normDir(m[1]);
|
|
3895
|
+
} else if (type === 'wdio') {
|
|
3896
|
+
const sm = content.match(/\bspecs\s*:\s*\[([^\]]+)\]/);
|
|
3897
|
+
if (sm) { const fp = sm[1].match(/['"`]([^'"`]+)['"`]/)?.[1]; if (fp) { const gr = globRoot(fp); if (gr) r.testDir = gr; } }
|
|
3898
|
+
const bm = content.match(/\bbaseUrl\s*:\s*['"`]([^'"`]+)['"`]/);
|
|
3899
|
+
if (bm) r.baseURL = bm[1];
|
|
3900
|
+
} else if (type === 'cucumber') {
|
|
3901
|
+
const pm = content.match(/\bpaths\s*:\s*\[([^\]]+)\]/);
|
|
3902
|
+
if (pm) { const fp = pm[1].match(/['"`]([^'"`]+)['"`]/)?.[1]; if (fp) { const gr = globRoot(fp); if (gr) r.testDir = gr; } }
|
|
3903
|
+
if (!r.testDir) { try { const p = JSON.parse(content) as any; const paths = p?.default?.paths ?? p?.paths; if (Array.isArray(paths) && paths[0]) { const gr = globRoot(String(paths[0])); if (gr) r.testDir = gr; } } catch { /* not JSON */ } }
|
|
3904
|
+
}
|
|
3905
|
+
// Monorepo workspace prefix: config found at e.g. packages/frontend/playwright.config.ts.
|
|
3906
|
+
// testDir from config is relative to that file ('tests' or 'e2e'). Prepend the directory
|
|
3907
|
+
// so the final path is repo-root-relative ('packages/frontend/tests').
|
|
3908
|
+
if (dirPrefix && r.testDir && !r.testDir.startsWith(dirPrefix)) {
|
|
3909
|
+
r.testDir = dirPrefix + r.testDir;
|
|
3910
|
+
}
|
|
3911
|
+
if (dirPrefix && r.javaTestSourceDir && !r.javaTestSourceDir.startsWith(dirPrefix)) {
|
|
3912
|
+
r.javaTestSourceDir = dirPrefix + r.javaTestSourceDir;
|
|
3913
|
+
}
|
|
3914
|
+
return r;
|
|
3915
|
+
})
|
|
3916
|
+
);
|
|
3917
|
+
|
|
3918
|
+
for (const parsed of fetched) {
|
|
3919
|
+
if (!parsed) continue;
|
|
3920
|
+
if (parsed.testDir && !configPaths.testDir) configPaths.testDir = parsed.testDir;
|
|
3921
|
+
if (parsed.fixturesFolder && !configPaths.fixturesFolder) configPaths.fixturesFolder = parsed.fixturesFolder;
|
|
3922
|
+
if (parsed.baseURL && !configPaths.baseURL) configPaths.baseURL = parsed.baseURL;
|
|
3923
|
+
if (parsed.tsconfigPaths && !configPaths.tsconfigPaths) configPaths.tsconfigPaths = parsed.tsconfigPaths;
|
|
3924
|
+
if (parsed.tsconfigBaseUrl && !configPaths.tsconfigBaseUrl) configPaths.tsconfigBaseUrl = parsed.tsconfigBaseUrl;
|
|
3925
|
+
if (parsed.javaTestSourceDir && !configPaths.javaTestSourceDir) configPaths.javaTestSourceDir = parsed.javaTestSourceDir;
|
|
3926
|
+
if (parsed.jestModuleNameMapper && !configPaths.jestModuleNameMapper) configPaths.jestModuleNameMapper = parsed.jestModuleNameMapper;
|
|
3927
|
+
}
|
|
3928
|
+
} catch { /* non-fatal */ }
|
|
3929
|
+
|
|
3930
|
+
// Extract style profile for aligned generation
|
|
3931
|
+
// For Java, include main source paths so LLM can detect page object location in src/main/java/
|
|
3932
|
+
// Fall back to existing styleProfile from DB if extraction fails or returns null.
|
|
3933
|
+
let styleProfile: any = conn.styleProfile ?? null;
|
|
3934
|
+
if (styleSampleFiles.length > 0) {
|
|
3935
|
+
try {
|
|
3936
|
+
const mainSourcePaths = language === 'java'
|
|
3937
|
+
? treeResult.paths.filter((p: string) => /^src\/main\/java\//.test(p)).slice(0, 50)
|
|
3938
|
+
: [];
|
|
3939
|
+
// For TS/JS, also include non-test source files so LLM can detect pageObjectLocation
|
|
3940
|
+
// (e.g. src/advantage/pages/ in playwright-sample-project)
|
|
3941
|
+
const testPathSet = new Set(testPaths);
|
|
3942
|
+
const sourceFilePaths = (language === 'typescript' || language === 'javascript')
|
|
3943
|
+
? treeResult.paths
|
|
3944
|
+
.filter((p: string) =>
|
|
3945
|
+
(p.endsWith('.ts') || p.endsWith('.js')) &&
|
|
3946
|
+
!testPathSet.has(p) &&
|
|
3947
|
+
!p.endsWith('.d.ts') &&
|
|
3948
|
+
!p.includes('node_modules/') &&
|
|
3949
|
+
!p.includes('dist/') &&
|
|
3950
|
+
!p.includes('.config.'))
|
|
3951
|
+
.slice(0, 60)
|
|
3952
|
+
: [];
|
|
3953
|
+
const allPathsForProfile = [...testPaths, ...mainSourcePaths, ...sourceFilePaths].slice(0, 200);
|
|
3954
|
+
// Pass full tree paths separately so detectDataDirs can find testdata/*.json, fixtures/*.yaml etc.
|
|
3955
|
+
const freshProfile = await extractStyleProfile(styleSampleFiles, framework, language, tenantId, projectId, jobId, allPathsForProfile, treeResult.paths);
|
|
3956
|
+
if (freshProfile) styleProfile = freshProfile;
|
|
3957
|
+
} catch { /* non-fatal */ }
|
|
3958
|
+
}
|
|
3959
|
+
|
|
3960
|
+
// Merge config file ground-truth into styleProfile (Priority 0 — highest, no LLM inference needed).
|
|
3961
|
+
// Java: javaTestSourceDir also sets testLocation (equivalent field for Java).
|
|
3962
|
+
if (styleProfile && Object.keys(configPaths).length > 0) {
|
|
3963
|
+
if (configPaths.testDir) styleProfile.configTestDir = configPaths.testDir;
|
|
3964
|
+
if (configPaths.javaTestSourceDir) {
|
|
3965
|
+
styleProfile.configTestDir = configPaths.javaTestSourceDir;
|
|
3966
|
+
// Also set testLocation if not already present from LLM scan
|
|
3967
|
+
if (!styleProfile.testLocation) styleProfile.testLocation = configPaths.javaTestSourceDir;
|
|
3968
|
+
}
|
|
3969
|
+
if (configPaths.fixturesFolder) styleProfile.configFixturesFolder = configPaths.fixturesFolder;
|
|
3970
|
+
if (configPaths.baseURL) styleProfile.configBaseURL = configPaths.baseURL;
|
|
3971
|
+
if (configPaths.tsconfigPaths) styleProfile.tsconfigPaths = configPaths.tsconfigPaths;
|
|
3972
|
+
if (configPaths.tsconfigBaseUrl) styleProfile.tsconfigBaseUrl = configPaths.tsconfigBaseUrl;
|
|
3973
|
+
if (configPaths.jestModuleNameMapper) styleProfile.jestModuleNameMapper = configPaths.jestModuleNameMapper;
|
|
3974
|
+
}
|
|
3975
|
+
|
|
3976
|
+
// Extract page object inventory — finds POM/page classes in non-test files
|
|
3977
|
+
// Fall back to existing inventory from DB if fetch fails.
|
|
3978
|
+
let pageObjectInventory: any[] = (conn.pageObjectInventory as any[]) ?? [];
|
|
3979
|
+
try {
|
|
3980
|
+
const freshInventory = await buildPageObjectInventory(token, conn.repoFullName, treeResult.paths, framework);
|
|
3981
|
+
if (freshInventory.length > 0) {
|
|
3982
|
+
pageObjectInventory = freshInventory;
|
|
3983
|
+
await updateJobProgress(tenantId, jobId, 82, `Found ${pageObjectInventory.length} page objects`);
|
|
3984
|
+
}
|
|
3985
|
+
} catch { /* non-fatal */ }
|
|
3986
|
+
|
|
3987
|
+
// Run coverage mapping
|
|
3988
|
+
await updateJobProgress(tenantId, jobId, 85, 'Running coverage mapping');
|
|
3989
|
+
const { buildCoverageMap } = await import('@taodigital/agents');
|
|
3990
|
+
const testCases = await withTenant(tenantId, (tx) =>
|
|
3991
|
+
tx.testCase.findMany({ where: { projectId, tenantId, status: { not: 'RETIRED' } }, select: { id: true, title: true, ref: true } })
|
|
3992
|
+
) as any[];
|
|
3993
|
+
|
|
3994
|
+
const mappings = await buildCoverageMap(testCases, allExtracted, tenantId);
|
|
3995
|
+
|
|
3996
|
+
// Upsert CoverageMapping records (skip manualOverride=true)
|
|
3997
|
+
for (const m of mappings) {
|
|
3998
|
+
const existing = await withTenant(tenantId, (tx) =>
|
|
3999
|
+
tx.coverageMapping.findUnique({ where: { testCaseId: m.testCaseId } })
|
|
4000
|
+
) as any;
|
|
4001
|
+
if (existing?.manualOverride) continue;
|
|
4002
|
+
|
|
4003
|
+
await withTenant(tenantId, (tx) =>
|
|
4004
|
+
tx.coverageMapping.upsert({
|
|
4005
|
+
where: { testCaseId: m.testCaseId },
|
|
4006
|
+
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 },
|
|
4007
|
+
update: { status: m.status, matchedFilePath: m.matchedFilePath ?? null, scriptTestName: m.scriptTestName ?? null, lineNumber: m.lineNumber ?? null, confidence: m.confidence, matchMethod: m.matchMethod },
|
|
4008
|
+
})
|
|
4009
|
+
);
|
|
4010
|
+
}
|
|
4011
|
+
|
|
4012
|
+
const mapped = mappings.filter((m) => m.status === 'MAPPED').length;
|
|
4013
|
+
const unmapped = mappings.filter((m) => m.status === 'UNMAPPED').length;
|
|
4014
|
+
const ambiguous = mappings.filter((m) => m.status === 'AMBIGUOUS').length;
|
|
4015
|
+
const coveragePercent = testCases.length > 0 ? (mapped / testCases.length) * 100 : 0;
|
|
4016
|
+
|
|
4017
|
+
// Write coverage snapshot
|
|
4018
|
+
await withTenant(tenantId, (tx) =>
|
|
4019
|
+
tx.coverageSnapshot.create({
|
|
4020
|
+
data: { tenantId, projectId, totalCases: testCases.length, mappedCases: mapped, unmappedCases: unmapped, ambiguousCases: ambiguous, coveragePercent },
|
|
4021
|
+
})
|
|
4022
|
+
);
|
|
4023
|
+
|
|
4024
|
+
// For Java, if styleProfile still missing testStructurePattern, infer two-tier from tree paths.
|
|
4025
|
+
// This covers the case where both extractStyleProfile and buildPageObjectInventory failed.
|
|
4026
|
+
const resolvedStyleProfile: any = (() => {
|
|
4027
|
+
const sp = styleProfile ?? {};
|
|
4028
|
+
if (framework === 'selenium-java' && !sp.testStructurePattern) {
|
|
4029
|
+
const hasMavenMain = treeResult.paths.some((p: string) => /^src\/main\/java\//.test(p));
|
|
4030
|
+
if (hasMavenMain) return { ...sp, testStructurePattern: 'two-tier' };
|
|
4031
|
+
}
|
|
4032
|
+
return sp;
|
|
4033
|
+
})();
|
|
4034
|
+
|
|
4035
|
+
// Update repo connection with results
|
|
4036
|
+
await withTenant(tenantId, (tx) =>
|
|
4037
|
+
tx.gitHubRepoConnection.update({
|
|
4038
|
+
where: { id: repoConnectionId },
|
|
4039
|
+
data: {
|
|
4040
|
+
scanStatus: 'DONE',
|
|
4041
|
+
detectedFramework: framework,
|
|
4042
|
+
configFilePath: primary?.configPath ?? null,
|
|
4043
|
+
testGlob: testGlob,
|
|
4044
|
+
testFileCount: testPaths.length,
|
|
4045
|
+
extractedIdCount: allExtracted.length,
|
|
4046
|
+
styleProfile: resolvedStyleProfile as any,
|
|
4047
|
+
pageObjectInventory: pageObjectInventory.length > 0 ? pageObjectInventory as any : undefined,
|
|
4048
|
+
treeSnapshot: JSON.stringify(treeResult.paths).slice(0, 100000),
|
|
4049
|
+
lastScannedAt: new Date(),
|
|
4050
|
+
lastSyncAt: new Date(),
|
|
4051
|
+
},
|
|
4052
|
+
})
|
|
4053
|
+
);
|
|
4054
|
+
try {
|
|
4055
|
+
const { generateRepoSkillFiles } = await import('@taodigital/agents');
|
|
4056
|
+
await generateRepoSkillFiles(tenantId, projectId, {
|
|
4057
|
+
repoFullName: conn.repoFullName,
|
|
4058
|
+
framework,
|
|
4059
|
+
language,
|
|
4060
|
+
testGlob,
|
|
4061
|
+
styleProfile: resolvedStyleProfile,
|
|
4062
|
+
pageObjectInventory,
|
|
4063
|
+
testPaths,
|
|
4064
|
+
extractedTestCount: allExtracted.length,
|
|
4065
|
+
treeWasTruncated: treeResult.truncated,
|
|
4066
|
+
extractedTests: allExtracted,
|
|
4067
|
+
});
|
|
4068
|
+
} catch (e: any) {
|
|
4069
|
+
logger.warn({ jobId, repoConnectionId, err: e?.message }, '[repo-scan] repo skill files generation failed (non-fatal)');
|
|
4070
|
+
}
|
|
4071
|
+
try {
|
|
4072
|
+
const { alignSkillFile } = await import('@taodigital/agents');
|
|
4073
|
+
await alignSkillFile(tenantId, projectId, {
|
|
4074
|
+
framework,
|
|
4075
|
+
language,
|
|
4076
|
+
styleProfile: resolvedStyleProfile,
|
|
4077
|
+
repoFullName: conn.repoFullName,
|
|
4078
|
+
});
|
|
4079
|
+
} catch (e: any) {
|
|
4080
|
+
logger.warn({ jobId, repoConnectionId, err: e?.message }, '[repo-scan] alignSkillFile failed (non-fatal)');
|
|
4081
|
+
}
|
|
4082
|
+
|
|
4083
|
+
await updateJobProgress(tenantId, jobId, 100, `Done: ${mapped} mapped, ${unmapped} unmapped`);
|
|
4084
|
+
await withTenant(tenantId, (tx) =>
|
|
4085
|
+
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 } })
|
|
4086
|
+
);
|
|
4087
|
+
aggregateJobTokens(tenantId, jobId, projectId, jobStart).catch(console.error);
|
|
4088
|
+
} catch (err: any) {
|
|
4089
|
+
const cause = err?.cause?.message ?? (typeof err?.cause === 'string' ? err.cause : '');
|
|
4090
|
+
const msg = `${String(err?.message ?? err)}${cause ? ` — ${cause}` : ''}`;
|
|
4091
|
+
logger.error({ jobId, repoConnectionId, err: msg }, '[repo-scan] failed');
|
|
4092
|
+
await withTenant(tenantId, (tx) =>
|
|
4093
|
+
tx.gitHubRepoConnection.update({ where: { id: repoConnectionId }, data: { scanStatus: 'FAILED', scanError: msg.slice(0, 500) } })
|
|
4094
|
+
).catch(() => { });
|
|
4095
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
4096
|
+
}
|
|
4097
|
+
}
|
|
4098
|
+
|
|
4099
|
+
// ── BATCH_GENERATE_ALIGNED — generate framework-aligned scripts for UNMAPPED cases ──
|
|
4100
|
+
|
|
4101
|
+
async function processBatchGenerateAlignedJob(jobId: string, config: any) {
|
|
4102
|
+
const { tenantId, projectId, repoConnectionId, scope = 'UNMAPPED', testCaseIds, force = false } = config;
|
|
4103
|
+
try {
|
|
4104
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading repo connection');
|
|
4105
|
+
|
|
4106
|
+
const conn = await withTenant(tenantId, (tx) =>
|
|
4107
|
+
(tx as any).gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
|
|
4108
|
+
) as any;
|
|
4109
|
+
if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
|
|
4110
|
+
|
|
4111
|
+
const {
|
|
4112
|
+
generateScriptAligned, deriveRepoTargetPath, validateGeneratedScript,
|
|
4113
|
+
mapWithConcurrency, SCRIPT_GEN_CONCURRENCY,
|
|
4114
|
+
} = await import('@taodigital/agents');
|
|
4115
|
+
|
|
4116
|
+
const styleProfile = conn.styleProfile as any;
|
|
4117
|
+
const pageObjectInventory = (conn.pageObjectInventory as any[]) ?? [];
|
|
4118
|
+
const framework = conn.detectedFramework ?? 'playwright-ts';
|
|
4119
|
+
const language = styleProfile?.language ?? 'typescript';
|
|
4120
|
+
|
|
4121
|
+
// Resolve which test cases to process
|
|
4122
|
+
let caseIds: string[];
|
|
4123
|
+
if (testCaseIds && testCaseIds.length > 0) {
|
|
4124
|
+
caseIds = testCaseIds;
|
|
4125
|
+
} else if (scope === 'UNMAPPED') {
|
|
4126
|
+
const mappings = await withTenant(tenantId, (tx) =>
|
|
4127
|
+
(tx as any).coverageMapping.findMany({
|
|
4128
|
+
where: { tenantId, projectId, repoConnectionId, status: 'UNMAPPED' },
|
|
4129
|
+
select: { testCaseId: true },
|
|
4130
|
+
})
|
|
4131
|
+
) as any[];
|
|
4132
|
+
caseIds = mappings.map((m: any) => m.testCaseId);
|
|
4133
|
+
} else {
|
|
4134
|
+
const cases = await withTenant(tenantId, (tx) =>
|
|
4135
|
+
tx.testCase.findMany({
|
|
4136
|
+
where: { tenantId, projectId, status: { not: 'RETIRED' } },
|
|
4137
|
+
select: { id: true },
|
|
4138
|
+
})
|
|
4139
|
+
) as any[];
|
|
4140
|
+
caseIds = cases.map((c: any) => c.id);
|
|
4141
|
+
}
|
|
4142
|
+
|
|
4143
|
+
await updateJobProgress(tenantId, jobId, 15, `Generating scripts for ${caseIds.length} test cases`);
|
|
4144
|
+
|
|
4145
|
+
let done = 0;
|
|
4146
|
+
const errors: string[] = [];
|
|
4147
|
+
|
|
4148
|
+
// One LLM call per case — bounded worker pool instead of a strictly serial loop,
|
|
4149
|
+
// which made large batches take an hour or more.
|
|
4150
|
+
await mapWithConcurrency(caseIds, SCRIPT_GEN_CONCURRENCY, async (tcId: string) => {
|
|
4151
|
+
try {
|
|
4152
|
+
// Skip if script already exists and not forcing
|
|
4153
|
+
if (!force) {
|
|
4154
|
+
const existing = await withTenant(tenantId, (tx) =>
|
|
4155
|
+
(tx as any).testScript.findFirst({ where: { testCaseId: tcId } })
|
|
4156
|
+
);
|
|
4157
|
+
if (existing) { done++; return; }
|
|
4158
|
+
}
|
|
4159
|
+
|
|
4160
|
+
// Get screen URL and ref for target path derivation
|
|
4161
|
+
const tc = await withTenant(tenantId, (tx) =>
|
|
4162
|
+
tx.testCase.findUnique({
|
|
4163
|
+
where: { id: tcId },
|
|
4164
|
+
select: { id: true, ref: true, title: true, screen: { select: { url: true } } },
|
|
4165
|
+
})
|
|
4166
|
+
);
|
|
4167
|
+
|
|
4168
|
+
const screenUrl = (tc as any)?.screen?.url ?? '';
|
|
4169
|
+
const repoTargetPath = styleProfile
|
|
4170
|
+
? deriveRepoTargetPath(screenUrl, styleProfile, framework)
|
|
4171
|
+
: deriveFallbackTargetPath((tc as any)?.ref ?? (tc as any)?.title ?? tcId, framework);
|
|
4172
|
+
|
|
4173
|
+
const result = await generateScriptAligned({
|
|
4174
|
+
tenantId, projectId, testCaseId: tcId,
|
|
4175
|
+
styleProfile,
|
|
4176
|
+
pageObjectInventory,
|
|
4177
|
+
repoTargetPath,
|
|
4178
|
+
save: true,
|
|
4179
|
+
});
|
|
4180
|
+
|
|
4181
|
+
// Validate the generated script
|
|
4182
|
+
if (result.code) {
|
|
4183
|
+
const validation = await validateGeneratedScript(result.code, framework, language);
|
|
4184
|
+
await withTenant(tenantId, (tx) =>
|
|
4185
|
+
(tx as any).testScript.updateMany({
|
|
4186
|
+
where: { testCaseId: tcId },
|
|
4187
|
+
data: {
|
|
4188
|
+
validationStatus: validation.ok ? 'PASS' : 'FAIL',
|
|
4189
|
+
validationErrors: validation.ok ? null : validation.errors.slice(0, 2000),
|
|
4190
|
+
},
|
|
4191
|
+
})
|
|
4192
|
+
);
|
|
4193
|
+
}
|
|
4194
|
+
|
|
4195
|
+
done++;
|
|
4196
|
+
} catch (e: any) {
|
|
4197
|
+
errors.push(`${tcId}: ${String(e.message).slice(0, 100)}`);
|
|
4198
|
+
}
|
|
4199
|
+
|
|
4200
|
+
if (done % 5 === 0) {
|
|
4201
|
+
await updateJobProgress(tenantId, jobId, 15 + Math.floor((done / caseIds.length) * 80), `Generated ${done}/${caseIds.length}`);
|
|
4202
|
+
}
|
|
4203
|
+
});
|
|
4204
|
+
|
|
4205
|
+
refreshTestScriptSkillFile(tenantId, projectId).catch(console.error);
|
|
4206
|
+
|
|
4207
|
+
await withTenant(tenantId, (tx) =>
|
|
4208
|
+
tx.platformJob.update({
|
|
4209
|
+
where: { id: jobId },
|
|
4210
|
+
data: { status: 'DONE', finishedAt: new Date(), result: { done, errors: errors.slice(0, 20), total: caseIds.length } as any },
|
|
4211
|
+
})
|
|
4212
|
+
);
|
|
4213
|
+
} catch (err: any) {
|
|
4214
|
+
const msg = String(err?.message ?? err);
|
|
4215
|
+
logger.error({ jobId, err: msg }, '[batch-generate-aligned] failed');
|
|
4216
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
4217
|
+
}
|
|
4218
|
+
}
|
|
4219
|
+
|
|
4220
|
+
// ── CREATE_PR — push generated scripts to GitHub as a PR ─────────────────────
|
|
4221
|
+
|
|
4222
|
+
async function processCreatePRJob(jobId: string, config: any) {
|
|
4223
|
+
const { tenantId, projectId, repoConnectionId, testScriptIds, crawlJobId } = config;
|
|
4224
|
+
try {
|
|
4225
|
+
await updateJobProgress(tenantId, jobId, 5, 'Loading connection');
|
|
4226
|
+
|
|
4227
|
+
const conn = await withTenant(tenantId, (tx) =>
|
|
4228
|
+
(tx as any).gitHubRepoConnection.findFirst({ where: { id: repoConnectionId, tenantId } })
|
|
4229
|
+
) as any;
|
|
4230
|
+
if (!conn) throw new Error(`RepoConnection ${repoConnectionId} not found`);
|
|
4231
|
+
|
|
4232
|
+
const { decrypt } = await import('@taodigital/core');
|
|
4233
|
+
const token = decrypt(conn.tokenEnc);
|
|
4234
|
+
|
|
4235
|
+
const { pushScriptsAsPR, getFileContent, mergeSpecContent } = await import('@taodigital/agents');
|
|
4236
|
+
|
|
4237
|
+
const framework = conn.detectedFramework ?? 'playwright-ts';
|
|
4238
|
+
|
|
4239
|
+
// Collect scripts + their target paths
|
|
4240
|
+
let scripts: any[];
|
|
4241
|
+
if (testScriptIds && testScriptIds.length > 0) {
|
|
4242
|
+
scripts = await withTenant(tenantId, (tx) =>
|
|
4243
|
+
(tx as any).testScript.findMany({
|
|
4244
|
+
where: { id: { in: testScriptIds }, tenantId, code: { not: null } },
|
|
4245
|
+
include: { testCase: { select: { title: true, ref: true, repoTargetPath: true } } },
|
|
4246
|
+
})
|
|
4247
|
+
);
|
|
4248
|
+
} else {
|
|
4249
|
+
// All scripts that haven't been pushed yet
|
|
4250
|
+
scripts = await withTenant(tenantId, (tx) =>
|
|
4251
|
+
(tx as any).testScript.findMany({
|
|
4252
|
+
where: { tenantId, projectId, pushedToPR: false, validationStatus: { in: ['PASS', 'PENDING'] }, code: { not: null } },
|
|
4253
|
+
include: { testCase: { select: { title: true, ref: true, repoTargetPath: true } } },
|
|
4254
|
+
})
|
|
4255
|
+
);
|
|
4256
|
+
}
|
|
4257
|
+
|
|
4258
|
+
if (scripts.length === 0) throw new Error('No generated scripts found to push.');
|
|
4259
|
+
|
|
4260
|
+
// For each file, check if it already exists in the repo and merge if so
|
|
4261
|
+
const files = await Promise.all(scripts.map(async (s: any) => {
|
|
4262
|
+
const path = s.testCase?.repoTargetPath
|
|
4263
|
+
?? deriveFallbackTargetPath(s.testCase?.ref ?? s.testCase?.title ?? s.id, framework);
|
|
4264
|
+
let content = s.code;
|
|
4265
|
+
|
|
4266
|
+
// Spec files: attempt to merge with existing content
|
|
4267
|
+
const isSpecFile = /\.(spec|test|cy)\.(ts|js|py|java)$/.test(path) || /_test\.py$/.test(path);
|
|
4268
|
+
if (isSpecFile) {
|
|
4269
|
+
const existing = await getFileContent(token, conn.repoFullName, path, conn.defaultBranch).catch(() => null);
|
|
4270
|
+
if (existing && existing.trim().length > 0) {
|
|
4271
|
+
logger.info({ path }, '[create-pr] merging new tests into existing spec file');
|
|
4272
|
+
content = mergeSpecContent(existing, s.code);
|
|
4273
|
+
}
|
|
4274
|
+
}
|
|
4275
|
+
|
|
4276
|
+
return { path, content };
|
|
4277
|
+
}));
|
|
4278
|
+
|
|
4279
|
+
if (files.length === 0) throw new Error('No scripts to push.');
|
|
4280
|
+
|
|
4281
|
+
await updateJobProgress(tenantId, jobId, 20, `Pushing ${files.length} scripts to GitHub`);
|
|
4282
|
+
|
|
4283
|
+
const now = new Date().toISOString().slice(0, 10);
|
|
4284
|
+
const branchName = `zeta/new-coverage-${now}-${jobId.slice(0, 8)}`;
|
|
4285
|
+
|
|
4286
|
+
const prBody = buildPRBody(scripts, projectId);
|
|
4287
|
+
|
|
4288
|
+
const prResult = await pushScriptsAsPR({
|
|
4289
|
+
token,
|
|
4290
|
+
repo: conn.repoFullName,
|
|
4291
|
+
baseBranch: conn.defaultBranch,
|
|
4292
|
+
branchName,
|
|
4293
|
+
files,
|
|
4294
|
+
prTitle: `ZeTa: Add test coverage for ${files.length} new scenario${files.length === 1 ? '' : 's'}`,
|
|
4295
|
+
prBody,
|
|
4296
|
+
draft: false,
|
|
4297
|
+
});
|
|
4298
|
+
|
|
4299
|
+
// Record the PR
|
|
4300
|
+
const pr = await withTenant(tenantId, (tx) =>
|
|
4301
|
+
(tx as any).gitHubPR.create({
|
|
4302
|
+
data: {
|
|
4303
|
+
tenantId, projectId,
|
|
4304
|
+
repoConnectionId,
|
|
4305
|
+
prNumber: prResult.prNumber,
|
|
4306
|
+
prUrl: prResult.prUrl,
|
|
4307
|
+
branch: prResult.branch,
|
|
4308
|
+
headSha: prResult.headSha,
|
|
4309
|
+
status: 'OPEN',
|
|
4310
|
+
crawlJobId: crawlJobId ?? null,
|
|
4311
|
+
scriptCount: files.length,
|
|
4312
|
+
prBody: prBody.slice(0, 10000),
|
|
4313
|
+
},
|
|
4314
|
+
})
|
|
4315
|
+
) as any;
|
|
4316
|
+
|
|
4317
|
+
// Mark scripts as pushed
|
|
4318
|
+
const scriptIds = scripts.map((s: any) => s.id);
|
|
4319
|
+
await withTenant(tenantId, (tx) =>
|
|
4320
|
+
(tx as any).testScript.updateMany({
|
|
4321
|
+
where: { id: { in: scriptIds } },
|
|
4322
|
+
data: { pushedToPR: true, pushedPRId: pr.id },
|
|
4323
|
+
})
|
|
4324
|
+
);
|
|
4325
|
+
|
|
4326
|
+
await notifyAdmins(tenantId, {
|
|
4327
|
+
type: 'GITHUB_PR_CREATED',
|
|
4328
|
+
title: 'ZeTa created a GitHub PR',
|
|
4329
|
+
body: `${files.length} new test script${files.length === 1 ? '' : 's'} pushed. PR #${prResult.prNumber}: ${prResult.prUrl}`,
|
|
4330
|
+
metadata: { prUrl: prResult.prUrl, prNumber: prResult.prNumber, scriptCount: files.length },
|
|
4331
|
+
});
|
|
4332
|
+
|
|
4333
|
+
await updateJobProgress(tenantId, jobId, 100, `PR #${prResult.prNumber} created`);
|
|
4334
|
+
await withTenant(tenantId, (tx) =>
|
|
4335
|
+
tx.platformJob.update({
|
|
4336
|
+
where: { id: jobId },
|
|
4337
|
+
data: { status: 'DONE', finishedAt: new Date(), result: { prUrl: prResult.prUrl, prNumber: prResult.prNumber, scriptCount: files.length } as any },
|
|
4338
|
+
})
|
|
4339
|
+
);
|
|
4340
|
+
} catch (err: any) {
|
|
4341
|
+
const msg = String(err?.message ?? err);
|
|
4342
|
+
logger.error({ jobId, err: msg }, '[create-pr] failed');
|
|
4343
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
4344
|
+
}
|
|
4345
|
+
}
|
|
4346
|
+
|
|
4347
|
+
function buildPRBody(scripts: any[], projectId: string): string {
|
|
4348
|
+
const lines = [
|
|
4349
|
+
'## ZeTa — Automated Test Coverage',
|
|
4350
|
+
'',
|
|
4351
|
+
`Generated by ZeTa Quality Intelligence Platform for project \`${projectId}\`.`,
|
|
4352
|
+
'',
|
|
4353
|
+
'### Scripts Added',
|
|
4354
|
+
'',
|
|
4355
|
+
'| Test Case | Target Path |',
|
|
4356
|
+
'|---|---|',
|
|
4357
|
+
];
|
|
4358
|
+
for (const s of scripts.slice(0, 30)) {
|
|
4359
|
+
const title = s.testCase?.title ?? s.id;
|
|
4360
|
+
const path = s.testCase?.repoTargetPath ?? '(unknown)';
|
|
4361
|
+
lines.push(`| ${title.replace(/\|/g, '\\|').slice(0, 60)} | \`${path}\` |`);
|
|
4362
|
+
}
|
|
4363
|
+
if (scripts.length > 30) lines.push(`| ... and ${scripts.length - 30} more | |`);
|
|
4364
|
+
lines.push('', '---', '_Review each test carefully before merging. ZeTa generates scripts aligned to your existing framework conventions._');
|
|
4365
|
+
return lines.join('\n');
|
|
4366
|
+
}
|
|
4367
|
+
|
|
4368
|
+
// ── NEW_PAGES_PIPELINE — post-crawl: detect new screens, generate tests + scripts ──
|
|
4369
|
+
|
|
4370
|
+
// ── GAP-019: k6 load test script generation ──────────────────────────────────
|
|
4371
|
+
|
|
4372
|
+
export function generateK6Script(params: {
|
|
4373
|
+
endpoints: Array<{ method: string; path: string; summary?: string }>;
|
|
4374
|
+
baseUrl: string;
|
|
4375
|
+
vus?: number;
|
|
4376
|
+
duration?: string;
|
|
4377
|
+
thinkTimeSeconds?: number;
|
|
4378
|
+
}): string {
|
|
4379
|
+
const { endpoints, baseUrl, vus = 10, duration = '30s', thinkTimeSeconds = 1 } = params;
|
|
4380
|
+
|
|
4381
|
+
const checks = endpoints
|
|
4382
|
+
.filter((ep) => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'].includes(ep.method.toUpperCase()))
|
|
4383
|
+
.map((ep) => {
|
|
4384
|
+
const method = ep.method.toUpperCase();
|
|
4385
|
+
const url = `\${__ENV.BASE_URL || '${baseUrl}'}${ep.path}`;
|
|
4386
|
+
const checkKey = `${method} ${ep.path} is 2xx`;
|
|
4387
|
+
const callExpr =
|
|
4388
|
+
method === 'GET' || method === 'DELETE'
|
|
4389
|
+
? `http.${method.toLowerCase()}(\`${url}\`, params)`
|
|
4390
|
+
: `http.${method.toLowerCase()}(\`${url}\`, JSON.stringify({}), params)`;
|
|
4391
|
+
return `
|
|
4392
|
+
// ${ep.summary ?? `${method} ${ep.path}`}
|
|
4393
|
+
{
|
|
4394
|
+
const res = ${callExpr};
|
|
4395
|
+
check(res, { '${checkKey}': (r) => r.status >= 200 && r.status < 300 });
|
|
4396
|
+
errorRate.add(res.status >= 400);
|
|
4397
|
+
}`;
|
|
4398
|
+
})
|
|
4399
|
+
.join('\n');
|
|
4400
|
+
|
|
4401
|
+
return `import http from 'k6/http';
|
|
4402
|
+
import { check, sleep } from 'k6';
|
|
4403
|
+
import { Rate } from 'k6/metrics';
|
|
4404
|
+
|
|
4405
|
+
const errorRate = new Rate('errors');
|
|
4406
|
+
|
|
4407
|
+
export const options = {
|
|
4408
|
+
vus: ${vus},
|
|
4409
|
+
duration: '${duration}',
|
|
4410
|
+
thresholds: {
|
|
4411
|
+
http_req_duration: ['p(95)<2000'],
|
|
4412
|
+
errors: ['rate<0.1'],
|
|
4413
|
+
},
|
|
4414
|
+
};
|
|
4415
|
+
|
|
4416
|
+
const params = {
|
|
4417
|
+
headers: { 'Content-Type': 'application/json' },
|
|
4418
|
+
};
|
|
4419
|
+
|
|
4420
|
+
export default function () {
|
|
4421
|
+
${checks}
|
|
4422
|
+
sleep(${thinkTimeSeconds});
|
|
4423
|
+
}
|
|
4424
|
+
`;
|
|
4425
|
+
}
|
|
4426
|
+
|
|
4427
|
+
async function processNewPagesPipelineJob(jobId: string, config: any) {
|
|
4428
|
+
const { tenantId, projectId, crawlJobId: _crawlJobId, repoConnectionId, autoPR = false } = config;
|
|
4429
|
+
try {
|
|
4430
|
+
await updateJobProgress(tenantId, jobId, 5, 'Detecting new screens');
|
|
4431
|
+
|
|
4432
|
+
// Find repo connection (use provided or find first active)
|
|
4433
|
+
const conn = await withTenant(tenantId, (tx) =>
|
|
4434
|
+
(tx as any).gitHubRepoConnection.findFirst({
|
|
4435
|
+
where: repoConnectionId
|
|
4436
|
+
? { id: repoConnectionId, tenantId }
|
|
4437
|
+
: { tenantId, projectId, status: 'ACTIVE' },
|
|
4438
|
+
})
|
|
4439
|
+
) as any;
|
|
4440
|
+
|
|
4441
|
+
// Get all screens last seen after the lastSyncAt of the repo connection
|
|
4442
|
+
const sinceDate = conn?.lastSyncAt ?? new Date(0);
|
|
4443
|
+
const newScreens = await withTenant(tenantId, (tx) =>
|
|
4444
|
+
tx.screen.findMany({
|
|
4445
|
+
where: {
|
|
4446
|
+
tenantId,
|
|
4447
|
+
projectId,
|
|
4448
|
+
lastSeenAt: { gt: sinceDate },
|
|
4449
|
+
status: { not: 'DELETED' },
|
|
4450
|
+
},
|
|
4451
|
+
select: { id: true, url: true, name: true },
|
|
4452
|
+
take: 100,
|
|
4453
|
+
})
|
|
4454
|
+
) as any[];
|
|
4455
|
+
|
|
4456
|
+
if (newScreens.length === 0) {
|
|
4457
|
+
await updateJobProgress(tenantId, jobId, 100, 'No new screens to process');
|
|
4458
|
+
await withTenant(tenantId, (tx) =>
|
|
4459
|
+
tx.platformJob.update({ where: { id: jobId }, data: { status: 'DONE', finishedAt: new Date(), result: { newScreens: 0 } as any } })
|
|
4460
|
+
);
|
|
4461
|
+
return;
|
|
4462
|
+
}
|
|
4463
|
+
|
|
4464
|
+
await updateJobProgress(tenantId, jobId, 15, `Found ${newScreens.length} new screens`);
|
|
4465
|
+
|
|
4466
|
+
// For each new screen, enqueue GENERATE_TESTS if no test cases exist
|
|
4467
|
+
const generationJobs: string[] = [];
|
|
4468
|
+
for (const screen of newScreens) {
|
|
4469
|
+
const caseCount = await withTenant(tenantId, (tx) =>
|
|
4470
|
+
tx.testCase.count({ where: { tenantId, screenId: screen.id } })
|
|
4471
|
+
);
|
|
4472
|
+
if (caseCount === 0) {
|
|
4473
|
+
const jid = await enqueueJob('GENERATE_SCREEN_TESTS', {
|
|
4474
|
+
tenantId, projectId, screenId: screen.id,
|
|
4475
|
+
triggerAlignedScripts: conn != null,
|
|
4476
|
+
repoConnectionId: (conn as any)?.id ?? null,
|
|
4477
|
+
});
|
|
4478
|
+
generationJobs.push(jid);
|
|
4479
|
+
}
|
|
4480
|
+
}
|
|
4481
|
+
|
|
4482
|
+
await updateJobProgress(tenantId, jobId, 60, `Queued ${generationJobs.length} test generation jobs`);
|
|
4483
|
+
|
|
4484
|
+
// If repo connected and autoPR enabled, schedule BATCH_GENERATE_ALIGNED after generation
|
|
4485
|
+
if (conn && autoPR) {
|
|
4486
|
+
await enqueueJob('BATCH_GENERATE_ALIGNED', {
|
|
4487
|
+
tenantId, projectId,
|
|
4488
|
+
repoConnectionId: conn.id,
|
|
4489
|
+
scope: 'UNMAPPED',
|
|
4490
|
+
});
|
|
4491
|
+
}
|
|
4492
|
+
|
|
4493
|
+
await withTenant(tenantId, (tx) =>
|
|
4494
|
+
tx.platformJob.update({
|
|
4495
|
+
where: { id: jobId },
|
|
4496
|
+
data: { status: 'DONE', finishedAt: new Date(), result: { newScreens: newScreens.length, generationJobs: generationJobs.length } as any },
|
|
4497
|
+
})
|
|
4498
|
+
);
|
|
4499
|
+
} catch (err: any) {
|
|
4500
|
+
const msg = String(err?.message ?? err);
|
|
4501
|
+
logger.error({ jobId, err: msg }, '[new-pages-pipeline] failed');
|
|
4502
|
+
await recordJobFailure(tenantId, jobId, err);
|
|
4503
|
+
}
|
|
4504
|
+
}
|