@skyramp/mcp 0.2.7 → 0.2.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/build/index.js +5 -2
  2. package/build/prompts/enhance-assertions/uiAssertionsPrompt.js +24 -5
  3. package/build/prompts/sut-setup/modes/adaptWorkflowPrompt.d.ts +2 -0
  4. package/build/prompts/sut-setup/modes/adaptWorkflowPrompt.js +114 -0
  5. package/build/prompts/sut-setup/modes/dockerComposePrompt.d.ts +2 -0
  6. package/build/prompts/sut-setup/modes/dockerComposePrompt.js +292 -0
  7. package/build/prompts/sut-setup/shared.d.ts +39 -0
  8. package/build/prompts/sut-setup/shared.js +132 -0
  9. package/build/prompts/test-maintenance/driftAnalysisSections.js +9 -3
  10. package/build/prompts/test-recommendation/analysisOutputPrompt.js +1 -1
  11. package/build/prompts/test-recommendation/diffExecutionPlan.js +76 -2
  12. package/build/prompts/test-recommendation/test-recommendation-prompt.test.js +91 -0
  13. package/build/prompts/testbot/testbot-prompts.d.ts +16 -1
  14. package/build/prompts/testbot/testbot-prompts.js +113 -22
  15. package/build/prompts/testbot/testbot-prompts.test.js +95 -45
  16. package/build/resources/sutSetupResource.d.ts +2 -0
  17. package/build/resources/sutSetupResource.js +45 -0
  18. package/build/resources/testbotResource.js +2 -2
  19. package/build/services/TestDiscoveryService.d.ts +2 -2
  20. package/build/services/TestDiscoveryService.js +22 -12
  21. package/build/services/TestExecutionService.d.ts +10 -1
  22. package/build/services/TestExecutionService.js +158 -26
  23. package/build/services/TestExecutionService.test.js +306 -0
  24. package/build/tools/executeSkyrampTestTool.js +26 -7
  25. package/build/tools/generate-tests/generateBatchScenarioRestTool.js +1 -1
  26. package/build/tools/submitReportTool.d.ts +10 -0
  27. package/build/tools/submitReportTool.js +106 -39
  28. package/build/tools/submitReportTool.test.js +296 -50
  29. package/build/tools/test-management/actionsTool.js +21 -7
  30. package/build/tools/test-management/analyzeChangesTool.d.ts +1 -1
  31. package/build/tools/test-management/analyzeChangesTool.js +106 -41
  32. package/build/tools/test-management/analyzeChangesTool.test.js +21 -41
  33. package/build/tools/test-management/analyzeTestHealthTool.js +16 -9
  34. package/build/tools/workspace/initializeWorkspaceTool.js +39 -22
  35. package/build/tools/workspace/serviceUpsert.d.ts +12 -0
  36. package/build/tools/workspace/serviceUpsert.js +23 -0
  37. package/build/tools/workspace/serviceUpsert.test.d.ts +1 -0
  38. package/build/tools/workspace/serviceUpsert.test.js +50 -0
  39. package/build/types/TestAnalysis.d.ts +2 -1
  40. package/build/types/TestExecution.d.ts +12 -2
  41. package/build/types/TestExecution.js +11 -1
  42. package/build/types/TestbotReport.d.ts +68 -0
  43. package/build/types/TestbotReport.js +1 -0
  44. package/build/types/index.d.ts +4 -0
  45. package/build/types/index.js +3 -0
  46. package/build/utils/AnalysisStateManager.d.ts +61 -1
  47. package/build/utils/AnalysisStateManager.js +144 -3
  48. package/build/utils/AnalysisStateManager.test.js +98 -0
  49. package/build/utils/docker.test.js +1 -1
  50. package/build/utils/routeParsers.d.ts +0 -10
  51. package/build/utils/routeParsers.js +31 -38
  52. package/build/utils/scenarioDrafting.d.ts +1 -1
  53. package/build/utils/scenarioDrafting.js +23 -1
  54. package/build/utils/utils.d.ts +7 -1
  55. package/build/utils/utils.js +10 -0
  56. package/build/utils/versions.d.ts +3 -3
  57. package/build/utils/versions.js +1 -1
  58. package/build/workspace/workspace.d.ts +10 -10
  59. package/build/workspace/workspace.js +7 -7
  60. package/build/workspace/workspace.test.js +6 -6
  61. package/node_modules/playwright/lib/mcp/skyramp/loadTraceTool.js +31 -13
  62. package/node_modules/playwright/lib/mcp/skyramp/traceRecordingBackend.js +88 -15
  63. package/node_modules/playwright/lib/mcp/test/skyRampExport.js +4 -3
  64. package/node_modules/playwright/node_modules/playwright-core/ThirdPartyNotices.txt +23 -126
  65. package/node_modules/playwright/node_modules/playwright-core/lib/generated/injectedScriptSource.js +1 -1
  66. package/node_modules/playwright/node_modules/playwright-core/lib/server/recorder/recorderApp.js +79 -19
  67. package/node_modules/playwright/node_modules/playwright-core/lib/server/recorder/skyramp/aliasRemapper.js +84 -0
  68. package/node_modules/playwright/node_modules/playwright-core/lib/server/recorder/skyramp/replayEngine.js +15 -4
  69. package/node_modules/playwright/node_modules/playwright-core/lib/vite/recorder/assets/{codeMirrorModule-CPZKmjFR.js → codeMirrorModule-D0BjbCb7.js} +1 -1
  70. package/node_modules/playwright/node_modules/playwright-core/lib/vite/recorder/assets/index-lvTRGFx-.js +193 -0
  71. package/node_modules/playwright/node_modules/playwright-core/lib/vite/recorder/index.html +1 -1
  72. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/assets/{codeMirrorModule-B0JOjboO.js → codeMirrorModule-Cqp3cwEJ.js} +1 -1
  73. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/assets/{defaultSettingsView-1anWeyDf.js → defaultSettingsView-CYf9adZh.js} +79 -79
  74. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/{index.Cc5029a3.js → index.B_7ywgmr.js} +1 -1
  75. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/index.html +2 -2
  76. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/uiMode.html +2 -2
  77. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/{uiMode.Wo5yvvVh.js → uiMode.u4_8VnCV.js} +1 -1
  78. package/node_modules/playwright/node_modules/playwright-core/package.json +1 -1
  79. package/node_modules/playwright/node_modules/playwright-core/src/generated/injectedScriptSource.ts +1 -1
  80. package/node_modules/playwright/node_modules/playwright-core/src/server/recorder/recorderApp.ts +129 -43
  81. package/node_modules/playwright/node_modules/playwright-core/src/server/recorder/skyramp/aliasRemapper.ts +119 -0
  82. package/node_modules/playwright/node_modules/playwright-core/src/server/recorder/skyramp/replayEngine.ts +33 -10
  83. package/node_modules/playwright/package.json +1 -1
  84. package/package.json +10 -3
  85. package/node_modules/playwright/node_modules/playwright-core/bundles/mcp/node_modules/.bin/node-which +0 -52
  86. package/node_modules/playwright/node_modules/playwright-core/bundles/utils/node_modules/.bin/is-docker +0 -5
  87. package/node_modules/playwright/node_modules/playwright-core/bundles/utils/node_modules/.bin/mime +0 -46
  88. package/node_modules/playwright/node_modules/playwright-core/bundles/utils/node_modules/.bin/yaml +0 -11
  89. package/node_modules/playwright/node_modules/playwright-core/lib/vite/recorder/assets/index-CsgPR2wy.js +0 -193
  90. package/node_modules/playwright/node_modules/playwright-core/lib/vite/traceViewer/index.CP3Y8Zsb.js +0 -2
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Path of the Testbot workflow file relative to the repo root. Created by the
3
+ * Testbot installer and edited in-place by every SUT setup mode.
4
+ */
5
+ export const TESTBOT_WORKFLOW_PATH = ".github/workflows/skyramp-testbot.yml";
6
+ export var SutSetupMode;
7
+ (function (SutSetupMode) {
8
+ SutSetupMode["None"] = "none";
9
+ SutSetupMode["AdaptWorkflow"] = "adapt_workflow";
10
+ SutSetupMode["DockerCompose"] = "docker_compose";
11
+ })(SutSetupMode || (SutSetupMode = {}));
12
+ /**
13
+ * Glossary block rendered right after the first mention of "SUT" in each
14
+ * setup prompt. Shared across modes so the LLM gets a single explicit
15
+ * definition rather than inferring it from context.
16
+ */
17
+ export function buildSutDefinitionBlock() {
18
+ return `**System Under Test (SUT)** — the application services this workflow brings up so Testbot can exercise them end-to-end. The SUT is what runs the PR's source code: backend services (REST/gRPC APIs), their supporting infrastructure (databases, queues, caches), and any frontend UI under test. The SUT does NOT include the test runner itself or Testbot. Bringing up the SUT means building from PR source, starting all required services, seeding any data tests rely on, and exposing a health check that proves the system is ready for traffic.
19
+
20
+ `;
21
+ }
22
+ export function buildContextBlock(args) {
23
+ const lines = [];
24
+ lines.push(`<context>`);
25
+ lines.push(`Repository path: ${args.repositoryPath}`);
26
+ lines.push(`Setup mode: ${args.sutSetupMode}`);
27
+ if (args.sutSourceWorkflowFile)
28
+ lines.push(`Source workflow file: ${args.sutSourceWorkflowFile}`);
29
+ if (args.sutSourceDockerComposeFile)
30
+ lines.push(`Source docker-compose file: ${args.sutSourceDockerComposeFile}`);
31
+ lines.push(`</context>`);
32
+ return lines.join("\n");
33
+ }
34
+ export function buildLocalValidationSection() {
35
+ return `Before reporting success, exercise the adapted workflow locally. Testbot's external fix loop only retries when SUT lifecycle commands are set on the Testbot action. When the SUT is brought up by surrounding GHA steps (skipTargetSetup: 'true'), the fix loop is skipped — so the local check below is the only safety net before the workflow is committed.
36
+ Run commands one at a time in your shell — individual execution pinpoints failures far faster than running the whole workflow at once. Any non-zero exit is a fix-needed signal: adjust the workflow, re-run the failing command, and do not proceed until it passes.
37
+ 1. Validate build scripts and helper programs first — run these before anything else so build and auth failures surface cheaply:
38
+ a. Every helper script the workflow calls (e.g., \`./scripts/*.sh\`, \`make <target>\`, \`./gradlew <task>\`) — run each and confirm exit 0.
39
+ b. \`.skyramp/sut/get-auth-token.sh\` if present — run it and confirm it prints a non-empty token to stdout.
40
+ c. Validate any standalone Dockerfile referenced by GHA \`steps:\` (not by a compose service) with \`docker build\`. Do NOT also run \`docker build\` on Dockerfiles that belong to a compose service — \`docker compose build\` (next step) already builds them in one BuildKit graph; doubling up wastes ~5-10 GB of cache per service.
41
+ d. Every docker-compose file the workflow references — run \`docker compose -f <path> config\` to validate the YAML, then \`docker compose -f <path> build\`.
42
+ e. **Disk hygiene between heavy builds.** Between any two build commands (Dockerfile, compose, helper scripts that build), if the runner is under ~5 GB free or you see \`no space left on device\`, run \`docker builder prune -af -f && docker image prune -af\` before the next build. This frees BuildKit cache + dangling images without losing the running stack. Skipping this on heavy SUTs (medusa, calcom, mattermost, supabase) exhausts the ~14 GB \`ubuntu-latest\` disk mid-validation.
43
+ 2. Validate the SUT lifecycle — choose the branch that matches the chosen pattern:
44
+ a. If lifecycle commands are set on the Testbot action (skipTargetSetup is unset):
45
+ i. Run \`targetSetupCommand\` — confirm exit 0.
46
+ ii. Poll \`targetReadyCheckCommand\` until it exits 0 within \`targetReadyCheckTimeout\` seconds.
47
+ iii. Run \`targetTeardownCommand\` — confirm cleanup and exit 0.
48
+ b. If GHA steps wrap the Testbot action (skipTargetSetup: 'true'):
49
+ i. Extract the shell body of each SETUP step and run them in order. If a step depends entirely on a \${{ secrets.* }} value your shell cannot resolve, note it in <thinking> and skip — do not fabricate a value.
50
+ ii. Poll \`targetReadyCheckCommand\` until it exits 0.
51
+ iii. Extract and run each TEARDOWN step's body in order so the next iteration starts clean.
52
+ Only proceed to the success report once setup → health check → teardown all pass.`;
53
+ }
54
+ /**
55
+ * Returns the canonical "add to the Testbot workflow" block: every input that
56
+ * controls the SUT lifecycle, auth, and workflow-level setup, followed by the
57
+ * shared What to do / What not to do guidance (including the sutSetupMode
58
+ * bootstrap guard). Shared by every SUT setup mode (adapt_workflow and
59
+ * docker_compose) so the input semantics and rules never drift between prompts.
60
+ */
61
+ export function buildAddToTestbotWorkflowSection() {
62
+ return `#### Testbot action inputs - Add target lifecycle commands and auth to Testbot Workflow
63
+ For the full Testbot action input reference (defaults, edge cases, advanced options beyond the ones called out below), see the Testbot README: https://github.com/letsramp/testbot#inputs
64
+
65
+ Target lifecycle inputs (control how Testbot starts, validates, and stops the SUT):
66
+ 1. \`targetSetupCommand\` — shell command that builds and starts all SUT services. Testbot runs this before tests.
67
+ a. Default when unset: \`docker compose up -d\` (starts existing images, does NOT build).
68
+ b. For PR-source builds use \`docker compose up -d --build\` or the equivalent for helm/script-based SUTs.
69
+ c. With a dedicated compose file (reused or generated), point at it explicitly: \`docker compose -f .skyramp/sut/docker-compose.testbot.yml --project-directory . up -d --build\`.
70
+ d. Override whenever the source workflow's start sequence differs from the default.
71
+ 2. \`targetReadyCheckCommand\` — polling command (e.g., \`curl -sf http://localhost:8080/health\`) that Testbot runs repeatedly after setup until it exits 0 (service is ready) or the timeout is reached.
72
+ a. **CRITICAL: Always set this to a valid target readiness check command.** Required in every pattern: when \`targetSetupCommand\` is explicit, when relying on the \`docker compose up -d\` default, AND when surrounding GHA steps bring the SUT up before the Testbot action (\`skipTargetSetup: 'true'\`). Testbot's fail-early gate throws \`Unable to verify service readiness\` when no readiness signal is available (neither this nor a workspace service \`baseUrl\`) and the action exits non-zero. It is also what gates a backgrounded \`targetSetupCommand\` — without it Testbot can't tell when the service is actually listening.
73
+ 3. \`targetReadyCheckTimeout\` — seconds to wait for \`targetReadyCheckCommand\` to succeed.
74
+ a. Default: \`1800\` (30 min) — sized for cold \`docker compose --build\` runs on multi-service stacks. The loop exits on the first success, so fast services pay no extra cost. Override only if you want to fail faster on stuck setups (e.g. \`'300'\` for a small single-service SUT).
75
+ 4. \`targetTeardownCommand\` — shell command that stops and cleans up the SUT after tests (e.g., \`docker compose down -v\`, or \`docker compose -f .skyramp/sut/docker-compose.testbot.yml --project-directory . down -v\` for a dedicated compose file).
76
+ a. Always set this so each run starts from a clean state.
77
+ b. Omit only when teardown is handled by surrounding GHA steps with \`if: always()\`.
78
+ 5. \`skipTargetSetup\` — when \`'true'\`, Testbot skips running \`targetSetupCommand\` entirely.
79
+ a. Set this only when GHA steps surrounding the Testbot action already bring the SUT up.
80
+ b. Leave it unset (or \`'false'\`) when Testbot should run the full lifecycle via the inputs above.
81
+ Auth inputs (used by Testbot to authenticate against the running SUT during test recording and execution):
82
+ 6. \`authTokenCommand\` — shell command whose stdout is the auth credential for REST/gRPC API testing (e.g., a Bearer token, API key, or session cookie). Testbot captures the output and injects it as the \`Authorization\` header.
83
+ a. Set this when the SUT requires authentication for API calls.
84
+ b. If the source workflow exports a token via a step output or script, wire that same script here (e.g., \`bash .skyramp/sut/get-auth-token.sh\`).
85
+ c. If the workflow seeds a test user during setup, create \`.skyramp/sut/get-auth-token.sh\` that logs in with those credentials and prints the token.
86
+ d. Omit when the SUT APIs are unauthenticated.
87
+ 7. \`uiCredentials\` — \`username:password\` pair typed into the browser login form during UI test recording (format: \`myuser:mypassword\`).
88
+ a. Set for any frontend service that requires browser-based login.
89
+ b. Use \`\${{ secrets.SKYRAMP_UI_CREDENTIALS }}\` if the secret exists, otherwise use credentials seeded during SUT setup.
90
+ Workflow / job level settings (set on the workflow or job, not as \`skyramp/testbot\` action inputs):
91
+ 8. Secrets / environment variables — pass every secret/env var the setup needs into the workflow via an \`env:\` block or \`secrets: inherit\`, and add any dependency-resolution steps/jobs the SUT requires.
92
+ 9. \`runs-on\` runner label — switch to a larger runner when the SUT needs more disk or memory: heavy Docker builds, large dependency installs, or a multi-service (3+) compose stack. Standard runners run out of disk and crash with \`No space left on device\`. Runner names vary by org — do not hardcode \`large-ubuntu\`. Pick the label by (a) preserving whatever larger label the source workflow already uses (never downgrade to \`ubuntu-latest\`), (b) reusing the label adjacent heavy or integration jobs in \`.github/workflows/\` already use, or (c) falling back to a known GitHub-hosted large label such as \`ubuntu-latest-large\`.
93
+
94
+ #### What to do
95
+ Edit \`${TESTBOT_WORKFLOW_PATH}\` in place (already created by the Testbot installer) — do NOT recreate it. Add only what the SUT needs onto the existing \`skyramp/testbot\` action step, alongside the inputs the installer already added:
96
+ 1. The 4 target lifecycle inputs — \`targetSetupCommand\`, \`targetReadyCheckCommand\`, \`targetReadyCheckTimeout\`, \`targetTeardownCommand\`.
97
+ 2. The 2 auth inputs when the SUT needs them — \`authTokenCommand\` and/or \`uiCredentials\`.
98
+ 3. Any secrets / environment variables and dependency-resolution steps/jobs the setup needs (input 8).
99
+ 4. The \`runs-on\` runner label, if a larger runner is needed (input 9).
100
+ 5. Use a daemon/detached form for \`targetSetupCommand\` — \`docker compose up -d --build\`, \`nohup npm start &\`, \`./server &\`, \`pnpm --prefix ./apps/studio start &\`. The command should launch the service and exit; \`targetReadyCheckCommand\` is what gates readiness. Testbot backgrounds foreground-blocking commands (\`npm start\`, \`python app.py\`, \`./server\`) automatically after a 5-minute timeout as a safety net, so they will eventually work — but daemon mode is faster (no 5-minute wait) and surfaces startup crashes clearly via the command's exit code. If no daemon form is available and the repo has no \`docker-compose.yml\`, wrap the foreground command in compose (a \`Dockerfile\` + \`docker-compose.yml\` running \`npm start\`) so it can be launched with \`docker compose up -d --build\`. Only fall back to a GHA pre-step with \`&\` (e.g. \`run: npm start &\`) if Docker is not feasible.
101
+
102
+ #### What not to do
103
+ 1. IMPORTANT — do NOT remove or change the existing \`sutSetupMode\` input (nor \`sutSourceWorkflowFile\` / \`sutSourceDockerComposeFile\`). Leave \`sutSetupMode\` exactly as provided: Testbot flips it to \`none\` automatically after validation succeeds, and the committed \`sutSetupMode\` value is the signal that tells the next CI run to validate this adapted workflow rather than run tests. Deleting it or setting it to \`none\` breaks the bootstrap/validation cycle.
104
+ 2. Do not point the SUT at a prebuilt upstream image (e.g. \`image: org/app:latest\` or a fixed commit SHA from \`main\`) for any application service under test. The image will lag the PR and Testbot will validate stale code.
105
+ 3. Do not point the SUT at a remote staging or production environment for application services under test. Staging code drifts from PR source and turns Testbot's results into noise. External infra is acceptable only for sidecar dependencies the PR does not change (e.g. a managed test database).
106
+ 4. Do not use a foreground-blocking command as \`targetSetupCommand\` (e.g. \`npm start\`, \`pnpm --prefix ./apps/studio start\`, \`python app.py\`, \`prefect server start\`, \`./server\`) — see input 5 in "What to do" above for daemon forms and the compose-wrap fallback.
107
+ 5. Do not leave server processes running between fix-loop retries. If \`targetSetupCommand\` starts a direct process (not \`docker compose\`), always set \`targetTeardownCommand\` to kill it (e.g. \`pkill -f "node dist/index.js"\` or \`docker compose down\`). Without teardown, retried setup attempts will fail with \`EADDRINUSE\` because the previous process still holds the port.
108
+ `;
109
+ }
110
+ /**
111
+ * `buildAddToTestbotWorkflowSection()` output with its leading
112
+ * `#### Testbot action inputs ...` header stripped — for use as a PromptPlan
113
+ * step body where the PromptPlan step header replaces the inline `####`.
114
+ */
115
+ export function buildInputsBody() {
116
+ const text = buildAddToTestbotWorkflowSection();
117
+ const firstNewline = text.indexOf("\n");
118
+ return text.slice(firstNewline + 1);
119
+ }
120
+ export function buildCommonSutErrorsSection() {
121
+ return `Before finishing, verify the adapted Testbot workflow setup against common errors seen during SUT setup:
122
+ 1. port_conflict — another container is already using the port. Pick a free host port or stop the conflicting container.
123
+ 2. image_not_found / build_failed — the referenced image does not exist for this SHA, or the build step has the wrong context/Dockerfile path. Build from PR source, do not rely on upstream commit-SHA tags.
124
+ 3. healthcheck_timeout — the service is slow to come up. Use \`targetReadyCheckTimeout >= 120\` and ensure the health endpoint actually exists.
125
+ 4. connection_refused — the service is not listening on the expected host/port (often binding to 127.0.0.1 inside the container; bind to 0.0.0.0).
126
+ 5. dependency_error — required service (DB, cache, queue) is missing from compose or not healthy before the app starts. Add \`depends_on\` with \`condition: service_healthy\`.
127
+ 6. permission_denied — script is not executable (\`chmod +x\`) or volume mount has wrong ownership.
128
+ 7. auth_endpoint_404 / auth_credentials_invalid — the auth script hits a wrong path, or the database has no seeded user. The auth script must create the user before login when starting from a fresh DB.
129
+ 8. missing env vars / secrets — required env vars are unset on the runner. Either default them in the script or pass them through workflow \`env:\`.
130
+ 9. no_space_left — the runner ran out of disk space (\`No space left on device\`). This happens on standard runners when the SUT involves large Docker builds, many npm packages, or multiple compose services that pull large images. Switch \`runs-on\` to a larger runner — runner names vary by org, do not hardcode \`large-ubuntu\`. Pick the label by (a) preserving whatever larger label the source workflow already uses, (b) reusing the label adjacent heavy or integration jobs in \`.github/workflows/\` already use, or (c) falling back to a known GitHub-hosted large label such as \`ubuntu-latest-large\`. Indicator: source workflow already specifies a large runner, or the SUT has multi-stage Docker builds / a compose file with 3+ services.
131
+ Do not add an in-prompt fix loop — Testbot's external validator will retry with concrete error context if any of these occur.`;
132
+ }
@@ -136,7 +136,9 @@ Actions:
136
136
  **UPDATE vs REGENERATE — the deciding question is whether the root response wrapper changed:**
137
137
  - **REGENERATE** only when a new top-level envelope object wraps the entire payload or the root key is renamed so that essentially every existing assertion must change.
138
138
  - **UPDATE** for everything else. If you can describe the fix as "patch these N assertion paths", it is UPDATE regardless of how many paths there are.
139
- - When every assertion in the file is invalid, it is REGENERATE. When you can still patch individual paths, it is UPDATE.`;
139
+ - When every assertion in the file is invalid, it is REGENERATE. When you can still patch individual paths, it is UPDATE.
140
+
141
+ **Non-test consumer check:** When the diff removes or renames response fields, also grep the repository for non-test source files that import or reference the changed schema type (e.g. \`grep -r "WorkQueueStatusDetail" src/\`). If any client model, SDK class, or serializer references the old field names, add a VERIFY entry for each such file in your recommendations so the developer is alerted — these are not test files but they will break at runtime.`;
140
142
  }
141
143
  export function buildCheckAuthAndAuthorization() {
142
144
  return `Has the authentication or authorization for this endpoint changed?
@@ -180,7 +182,7 @@ export function buildCheckAssignAction() {
180
182
  **Every action requires a specific rationale — including IGNORE:**
181
183
  - UPDATE / REGENERATE / DELETE: quote the specific diff line that triggered it.
182
184
  - VERIFY: name the uncertain element (e.g. "model-only change, cannot confirm field is exposed without checking the output layer").
183
- - IGNORE: name the specific reason the changed code cannot reach this test's endpoint (e.g. "diff only touches \`auth/session-service.js\` — this test targets \`/api/v1/orders\` which has no session dependency"). Generic "unrelated endpoint" or "service boundary" without a diff reference is not sufficient.
185
+ - IGNORE: name the changed file(s) from the diff AND explain why they cannot reach this test's endpoint (e.g. "diff only touches \`auth/session-service.js\` — this test targets \`/api/v1/orders\` which has no session dependency"). You must reference at least one specific changed file from the diff. Generic "unrelated endpoint" or "service boundary" without naming the changed file is not sufficient.
184
186
 
185
187
  - If the Additive Fields check flagged a new field with output layer signal confirmed in the diff → action is UPDATE. If the Additive Fields check returned VERIFY (model-only signal, no output layer change) → action remains VERIFY.
186
188
  - **Scope gate:** If the changed code is clearly not reachable through the service or base URL this test targets, assign IGNORE.
@@ -222,12 +224,16 @@ export function buildDriftOutputChecklist(stateFile, existingTests) {
222
224
  const noTestsNote = !hasTests
223
225
  ? `\nNo existing tests were found. Call \`skyramp_actions\` with \`recommendations: []\` and explain in your report why no maintenance was needed (e.g. "no existing tests cover the changed endpoints" or "PR adds a new endpoint with no prior coverage").\n`
224
226
  : "";
227
+ const symbolDiscoveryStep = hasTests
228
+ ? `**Symbol import discovery (before assessing tests):** If the diff adds or modifies class, function, or type definitions, grep the repository for test files that import those symbol names. Add any matched test files not already in the list below to your assessment — these files may need updating even if their path doesn't match the changed resource name. Include all discovered files in the \`recommendations[]\` passed to \`skyramp_actions\` — do NOT edit them directly without going through \`skyramp_actions\` first.`
229
+ : "";
225
230
  const existingTestSection = `**Existing tests (${existingTests?.length ?? 0} total) — assess ALL of the following:**
226
231
  ${testList}
227
232
  ${noTestsNote}
228
233
  **UPDATE scope notes:**
229
234
  - UPDATE is an in-place edit — do not recommend creating a new file for an already-tested endpoint.
230
235
  - If a new HTTP method is added to a resource, emit a separate UPDATE entry for every existing test file that covers that resource (contract, integration, UI).
236
+ - **When multiple test files cover the same changed resource, prefer the most resource-specific file** (e.g. a file whose name directly reflects the changed resource) over a generic shared test file. Only UPDATE both if the change affects base types shared across both files.
231
237
 
232
238
  For each test above, output one entry:
233
239
  - **IGNORE**: \`{testFile} — IGNORE: {reason the diff cannot reach this test's endpoint}\`
@@ -253,7 +259,7 @@ Rationale: DELETE because {quoted diff signal}; all covered endpoints removed
253
259
  \`\`\`
254
260
  Include ALL actions — IGNORE, VERIFY, UPDATE, REGENERATE, DELETE — in the \`recommendations[]\` passed to \`skyramp_actions\`. For \`[external]\` tests: \`skyramp_actions\` will apply UPDATE edits and surface REGENERATE/DELETE as report-only findings.
255
261
  Be concise — one line per IGNORE/VERIFY entry.`;
256
- const sections = [existingTestSection, finalStep];
262
+ const sections = [symbolDiscoveryStep, existingTestSection, finalStep].filter(Boolean);
257
263
  return `<output_format>
258
264
  Complete ALL of the following:
259
265
 
@@ -127,7 +127,7 @@ An unintegrated non-route component has no DOM node in the running app and canno
127
127
  return `${canInline ? "Read the \`<diff>\` above" : `Read the diff file at \`${p.diffFilePath}\``} and identify every new or modified API endpoint — route registrations, handler methods, controller annotations. Then use the **Router Mounting / Nesting** section above to reconstruct the full URL path for each endpoint by chaining all parent router prefixes down to the handler (e.g. a handler in a file with \`prefix="/reviews"\` that is mounted at \`/{product_id}\` under a router mounted at \`/api/v1/products\` → full path \`/api/v1/products/{product_id}/reviews\`).
128
128
  ${diffHasJavaFiles ? JAVA_SPRING_NOTE : ""}
129
129
  For each endpoint found: note the HTTP method, full path, and source file.
130
- ${preDetectedEndpoints ? "The endpoint catalog above already lists some changed endpoints — verify and augment with anything it missed." : "No endpoints were pre-detected in the changed files — extract them from the diff."}
130
+ ${preDetectedEndpoints ? "The endpoint catalog above already lists some changed endpoints — verify and augment with anything it missed. **If a changed file contains many endpoints (hub/routing files like api.go, routes.py, router.ts), cross-reference against the diff hunks to identify only the endpoints whose handler code actually changed — do not include neighboring routes whose code was untouched.**" : "No endpoints were pre-detected in the changed files — extract them from the diff."}
131
131
  **Also identify removed endpoints**: Look for deleted route annotations (lines starting with \`-\` in the diff) in modified files (files that still exist but had routes deleted). A removed endpoint is a route definition present in the base branch but absent in the current branch. Cross-reference against the scanned endpoint listing below — if a deleted route annotation's endpoint still appears there (e.g. moved to another file), it is NOT removed. Only flag endpoints that are truly gone from the codebase.
132
132
  **CRITICAL — Query params vs body:** For GET endpoints (especially search/filter/list),
133
133
  identify which parameters are URL query params vs request body. Look at framework-specific
@@ -154,6 +154,69 @@ function prioritizeAttackSurfaceBundles(items) {
154
154
  }
155
155
  return reordered;
156
156
  }
157
+ /**
158
+ * Select `count` items from a rank-ordered list, distributing GENERATE slots
159
+ * EVENLY across the test types present, with spillover.
160
+ *
161
+ * Policy (kept identical to the multi-repo prose in testbot-prompts.ts's
162
+ * "Cross-repo test generation" block — change both together):
163
+ * - Protected items first: CRITICAL-priority and attack-surface security_boundary
164
+ * scenarios always take a slot before round-robin (they must stay in GENERATE).
165
+ * - Bucket the rest by inferred test type (contract vs integration — the same
166
+ * inference used when rendering: `testType ?? (steps===1 ? contract : integration)`).
167
+ * - Round-robin one item per non-empty bucket per round, in the buckets' order of
168
+ * first appearance in the rank-ordered list (so the highest-ranked type wins
169
+ * round 1), preserving rank order within each bucket.
170
+ * - Spillover: an exhausted bucket is skipped on later rounds, so its freed slots
171
+ * go to the next type's next-highest item.
172
+ *
173
+ * Degenerate cases match the previous pure rank-order slice exactly: a single type
174
+ * present, or `count >= items.length`, returns the same items in the same order —
175
+ * so backend-only / single-type runs are unchanged (no regression).
176
+ */
177
+ function roundRobinByType(rankOrdered, count) {
178
+ if (count <= 0)
179
+ return [];
180
+ // Everything fits → no need to bucket; identical to the old slice.
181
+ if (count >= rankOrdered.length)
182
+ return rankOrdered.slice(0, count);
183
+ const inferType = (s) => s.testType ?? (s.steps.length === 1 ? "contract" : "integration");
184
+ // Protected items occupy GENERATE slots first, in rank order.
185
+ const selected = [];
186
+ const remaining = [];
187
+ for (const item of rankOrdered) {
188
+ if (selected.length < count &&
189
+ (item.priority === "CRITICAL" || isAttackSurfaceSecurityBoundary(item.scenario))) {
190
+ selected.push(item);
191
+ }
192
+ else {
193
+ remaining.push(item);
194
+ }
195
+ }
196
+ // Bucket the remainder by inferred type, preserving rank order and first-appearance
197
+ // bucket order.
198
+ const order = [];
199
+ const buckets = new Map();
200
+ for (const item of remaining) {
201
+ const t = inferType(item.scenario);
202
+ if (!buckets.has(t)) {
203
+ buckets.set(t, []);
204
+ order.push(t);
205
+ }
206
+ buckets.get(t).push(item);
207
+ }
208
+ // Round-robin one per non-empty bucket per round until full.
209
+ while (selected.length < count && order.some((t) => buckets.get(t).length > 0)) {
210
+ for (const t of order) {
211
+ if (selected.length >= count)
212
+ break;
213
+ const bucket = buckets.get(t);
214
+ if (bucket.length > 0)
215
+ selected.push(bucket.shift());
216
+ }
217
+ }
218
+ return selected;
219
+ }
157
220
  export function buildExecutionPlan(scored, maxGen, topN, baseUrl, authHeaderValue, authSchemeSnippet, authTypeValue, seed, endpointCount, isUIOnlyPR, hasFrontendChanges = false, hasTraces = false, externalCoverage = new Set(), relevantExternalTestPaths = []) {
158
221
  const frontendUrl = "<frontend_url>";
159
222
  // Slot allocation:
@@ -183,8 +246,19 @@ export function buildExecutionPlan(scored, maxGen, topN, baseUrl, authHeaderValu
183
246
  })
184
247
  : scored;
185
248
  const slotOrderedItems = prioritizeAttackSurfaceBundles(scoredAfterExternalDedup);
186
- const generateItems = slotOrderedItems.slice(0, Math.min(backendGenerateCount, slotOrderedItems.length));
187
- const rawAdditionalItems = slotOrderedItems.slice(backendGenerateCount, topN);
249
+ // Distribute the backend GENERATE slots evenly across the test types present
250
+ // (contract vs integration) with spillover, instead of a pure top-N rank slice —
251
+ // so a backend change isn't starved of (say) integration coverage just because
252
+ // contract scenarios out-ranked it. See roundRobinByType.
253
+ const generateItems = roundRobinByType(slotOrderedItems, Math.min(backendGenerateCount, slotOrderedItems.length));
254
+ // ADDITIONAL = everything not chosen for GENERATE, in original rank order, capped
255
+ // at the remaining budget. Computed by set-difference (not a positional slice)
256
+ // because round-robin may pick items that aren't the first backendGenerateCount by
257
+ // rank — a positional slice would double-list a generated item or drop one.
258
+ const generateSet = new Set(generateItems);
259
+ const rawAdditionalItems = slotOrderedItems
260
+ .filter((it) => !generateSet.has(it))
261
+ .slice(0, Math.max(0, topN - backendGenerateCount));
188
262
  // Filter additional items whose primary resource + test type already appear in GENERATE
189
263
  const generatedCoverage = new Set(generateItems.map((item) => scenarioCoverageKey(item.scenario)));
190
264
  const additionalItems = rawAdditionalItems.filter((item) => !generatedCoverage.has(scenarioCoverageKey(item.scenario)));
@@ -910,6 +910,97 @@ describe("buildRecommendationPrompt — GENERATE slot allocation", () => {
910
910
  expect(additionalBlock).toContain("DELETE /api/gadgets/{id} → 401");
911
911
  });
912
912
  });
913
+ describe("buildExecutionPlan — even-with-spillover test-type distribution", () => {
914
+ // Backend-only PR (hasFrontendChanges=false) so every GENERATE slot is a backend
915
+ // scenario drawn from `scored` — this is where contract-vs-integration distribution
916
+ // applies. baseUrl/auth args mirror the existing buildExecutionPlan tests above.
917
+ const contract = (name, path, priority = "HIGH") => ({
918
+ scenario: minimalScenario({
919
+ scenarioName: name,
920
+ category: "crud",
921
+ testType: TestType.CONTRACT,
922
+ steps: [{ order: 1, method: "POST", path, description: `POST ${path}`, interactionType: "success", expectedStatusCode: 201 }],
923
+ }),
924
+ priority: priority,
925
+ novelty: "new",
926
+ });
927
+ const integration = (name, p1, p2, priority = "HIGH") => ({
928
+ scenario: minimalScenario({
929
+ scenarioName: name,
930
+ category: "data_integrity",
931
+ testType: TestType.INTEGRATION,
932
+ steps: [
933
+ { order: 1, method: "POST", path: p1, description: `POST ${p1}`, interactionType: "success", expectedStatusCode: 201 },
934
+ { order: 2, method: "PATCH", path: p2, description: `PATCH ${p2}`, interactionType: "success", expectedStatusCode: 200 },
935
+ ],
936
+ }),
937
+ priority: priority,
938
+ novelty: "new",
939
+ });
940
+ const plan = (items, maxGen, topN) => buildExecutionPlan(items, maxGen, topN, "http://localhost:3000", "Authorization", ", authScheme: \"Bearer\"", "", "seed", items.length, false);
941
+ it("distributes GENERATE slots across contract AND integration when budget < candidates", () => {
942
+ // 4 contract out-rank 4 integration; pure top-3 rank slice would be all contract.
943
+ const items = [
944
+ contract("c1", "/api/a"), contract("c2", "/api/b"), contract("c3", "/api/c"), contract("c4", "/api/d"),
945
+ integration("i1", "/api/x", "/api/x/{id}"), integration("i2", "/api/y", "/api/y/{id}"),
946
+ ];
947
+ const prompt = plan(items, 3, 6);
948
+ const generated = prompt.slice(0, prompt.indexOf("[ADDITIONAL]") >= 0 ? prompt.indexOf("[ADDITIONAL]") : prompt.length);
949
+ expect(generated).toMatch(/GENERATE\*\* \| contract/);
950
+ expect(generated).toMatch(/GENERATE\*\* \| integration/);
951
+ });
952
+ it("single backend type → unchanged top-N rank slice (no regression)", () => {
953
+ const items = [contract("c1", "/api/a"), contract("c2", "/api/b"), contract("c3", "/api/c"), contract("c4", "/api/d")];
954
+ const prompt = plan(items, 3, 6);
955
+ const generated = prompt.slice(0, prompt.indexOf("[ADDITIONAL]") >= 0 ? prompt.indexOf("[ADDITIONAL]") : prompt.length);
956
+ // Top 3 contract by rank are generated; the 4th is not.
957
+ expect(generated).toContain("POST /api/a → 201");
958
+ expect(generated).toContain("POST /api/b → 201");
959
+ expect(generated).toContain("POST /api/c → 201");
960
+ expect(generated).not.toContain("POST /api/d → 201");
961
+ expect(generated).not.toMatch(/GENERATE\*\* \| integration/);
962
+ });
963
+ it("keeps a CRITICAL item in GENERATE even when lower-ranked than other-type candidates", () => {
964
+ // A CRITICAL integration sits after several HIGH contracts in rank order.
965
+ const items = [
966
+ contract("c1", "/api/a"), contract("c2", "/api/b"), contract("c3", "/api/c"),
967
+ integration("crit", "/api/orders", "/api/orders/{id}", "CRITICAL"),
968
+ ];
969
+ const prompt = plan(items, 3, 6);
970
+ const generated = prompt.slice(0, prompt.indexOf("[ADDITIONAL]") >= 0 ? prompt.indexOf("[ADDITIONAL]") : prompt.length);
971
+ // The CRITICAL integration must occupy a GENERATE slot (protected-first).
972
+ expect(generated).toContain("PATCH /api/orders/{id}");
973
+ });
974
+ it("spills freed slots to the remaining type when one type runs dry", () => {
975
+ // 1 integration + 4 contract, budget 3: round 1 = 1 integration + 1 contract,
976
+ // integration bucket now empty → remaining 1 slot spills to contract → 2 contract total.
977
+ const items = [
978
+ integration("i1", "/api/x", "/api/x/{id}"),
979
+ contract("c1", "/api/a"), contract("c2", "/api/b"), contract("c3", "/api/c"), contract("c4", "/api/d"),
980
+ ];
981
+ const prompt = plan(items, 3, 6);
982
+ const generated = prompt.slice(0, prompt.indexOf("[ADDITIONAL]") >= 0 ? prompt.indexOf("[ADDITIONAL]") : prompt.length);
983
+ const contractSlots = (generated.match(/GENERATE\*\* \| contract/g) || []).length;
984
+ const integrationSlots = (generated.match(/GENERATE\*\* \| integration/g) || []).length;
985
+ expect(integrationSlots).toBe(1);
986
+ expect(contractSlots).toBe(2);
987
+ });
988
+ it("never lists a GENERATE item again under ADDITIONAL (set-difference recompute)", () => {
989
+ const items = [
990
+ contract("c1", "/api/a"), contract("c2", "/api/b"), contract("c3", "/api/c"), contract("c4", "/api/d"),
991
+ integration("i1", "/api/x", "/api/x/{id}"), integration("i2", "/api/y", "/api/y/{id}"),
992
+ ];
993
+ const prompt = plan(items, 3, 6);
994
+ const splitIdx = prompt.indexOf("[ADDITIONAL]");
995
+ expect(splitIdx).toBeGreaterThan(0);
996
+ const generated = prompt.slice(0, splitIdx);
997
+ const additional = prompt.slice(splitIdx);
998
+ // Each generated endpoint must not reappear in the ADDITIONAL section.
999
+ for (const m of generated.matchAll(/(POST|PATCH) (\/api\/[^\s]+)/g)) {
1000
+ expect(additional).not.toContain(`${m[1]} ${m[2]}`);
1001
+ }
1002
+ });
1003
+ });
913
1004
  // ---------------------------------------------------------------------------
914
1005
  // Tests — buildTestQualityCriteria contract-test guidance (regression guard)
915
1006
  // ---------------------------------------------------------------------------
@@ -1,7 +1,22 @@
1
1
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
2
2
  import { type Service } from "../../workspace/workspace.js";
3
+ /** One related repository to analyze as shared context in multi-repo mode. */
4
+ export interface RelatedRepository {
5
+ repositoryPath: string;
6
+ baseBranch?: string;
7
+ /** `owner/repo` slug, resolved by the action from the checkout's git remote.
8
+ * Used verbatim as the `repository` argument/attribution for this repo so the
9
+ * agent never has to infer it. */
10
+ repo: string;
11
+ }
12
+ /**
13
+ * Parse the JSON-encoded `relatedRepositories` argument passed via the testbot
14
+ * prompt/resource. Returns undefined for missing/blank input or malformed JSON so the
15
+ * caller cleanly falls back to single-repo behavior.
16
+ */
17
+ export declare function parseRelatedRepositories(raw: string | undefined): RelatedRepository[] | undefined;
3
18
  export declare function getTestbotPrompt(prTitle: string, prDescription: string, summaryOutputFile: string, repositoryPath: string, baseBranch?: string, maxRecommendations?: number, maxGenerate?: number, _maxCritical?: number, // Reserved — accepted for API compat but not yet wired into prompt
4
- prNumber?: number, userPrompt?: string, services?: Service[], stateOutputFile?: string, uiCredentials?: string, testsRepoDir?: string): string;
19
+ prNumber?: number, userPrompt?: string, services?: Service[], uiCredentials?: string, testsRepoDir?: string, relatedRepositories?: RelatedRepository[], primaryRepo?: string): string;
5
20
  /**
6
21
  * Read services from .skyramp/workspace.yml. Returns empty array if
7
22
  * the workspace file doesn't exist or can't be parsed.