From ada39f4d364185ba0150429888cfb9d62e0b3a34 Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Tue, 1 Sep 2026 02:40:28 +0530 Subject: [PATCH 1/7] ci: enforce release metadata and docs opt-in --- .github/PULL_REQUEST_TEMPLATE.md | 101 +++++++++++ .github/workflows/notify-docs.yml | 39 +++-- .github/workflows/pr-metadata-check.yml | 63 +++++++ scripts/release/build-docs-payload.mjs | 118 +++++++++++++ scripts/release/lib/backmerge.mjs | 86 +++++++++ scripts/release/lib/conventional.mjs | 38 ++++ scripts/release/lib/parse-pr-body.mjs | 212 +++++++++++++++++++++++ scripts/release/lib/pr-sync-marker.mjs | 45 +++++ scripts/release/lib/read-pr-body.mjs | 11 ++ scripts/release/validate-pr-metadata.mjs | 48 +++++ scripts/release/validate-pr-sync.mjs | 63 +++++++ 11 files changed, 814 insertions(+), 10 deletions(-) create mode 100644 .github/PULL_REQUEST_TEMPLATE.md create mode 100644 .github/workflows/pr-metadata-check.yml create mode 100644 scripts/release/build-docs-payload.mjs create mode 100644 scripts/release/lib/backmerge.mjs create mode 100644 scripts/release/lib/conventional.mjs create mode 100644 scripts/release/lib/parse-pr-body.mjs create mode 100644 scripts/release/lib/pr-sync-marker.mjs create mode 100644 scripts/release/lib/read-pr-body.mjs create mode 100644 scripts/release/validate-pr-metadata.mjs create mode 100644 scripts/release/validate-pr-sync.mjs diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..1bc631f --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,101 @@ +# Pull Request + +> Incomplete sections below **block merge to `dev`**. Fill every required field with real content — +> not placeholders. + +## What changed + + + +## Why was it changed? + + + +## Customer impact + + + +## Customer release note + + + +## UI changes + +- [ ] No UI change +- [ ] Existing UI changed +- [ ] New UI added +- [ ] UI removed + +## UI evidence + + + +## Release classification + +- [ ] Customer-facing +- [ ] Internal-only +- [ ] Release-note skip + +## Documentation + + + +- [ ] Add to docs +- [ ] No docs update + +## Change type + +- [ ] Feature +- [ ] Bug fix +- [ ] Performance +- [ ] Refactor +- [ ] Infrastructure +- [ ] Documentation +- [ ] Breaking change + +## Affected areas + + + +## Feature flags + + + +## Configuration changes + + + +## Migration requirements + + + +## Rollout plan + + + +## Rollback plan + + + +## Risk + +- [ ] Low +- [ ] Medium +- [ ] High + +## Testing completed + + + +--- + +## Checklist + +- [ ] `make lint` passes +- [ ] `make test` passes + +## Related Issues + +Fixes # + + diff --git a/.github/workflows/notify-docs.yml b/.github/workflows/notify-docs.yml index 8474fdc..ba674fb 100644 --- a/.github/workflows/notify-docs.yml +++ b/.github/workflows/notify-docs.yml @@ -1,5 +1,3 @@ -# Tells test-zeus-ai/testzeus-docs to regenerate + re-host on every push to main, -# so the auto-generated reference stays in sync with this repo. name: Notify docs on: @@ -8,25 +6,46 @@ on: permissions: contents: read + pull-requests: read jobs: notify-docs: + name: Add the PR info in docs runs-on: ubuntu-latest steps: - - name: Generate GitHub App token - id: app-token + - uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true + + - uses: actions/setup-node@v4 + with: + node-version: "24" + + - name: Build docs payload + id: docs-payload + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + HEAD_SHA: ${{ github.sha }} + run: | + node scripts/release/build-docs-payload.mjs > docs-payload.json + echo "count=$(jq '.changes | length' docs-payload.json)" >> "$GITHUB_OUTPUT" + + - name: Generate docs dispatch token + if: steps.docs-payload.outputs.count != '0' + id: docs-app-token uses: actions/create-github-app-token@v3 with: app-id: ${{ vars.GH_APP_ID }} private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} owner: test-zeus-ai repositories: testzeus-docs - permission-actions: write + permission-contents: write - - name: Trigger docs rebuild + - name: Trigger testzeus-docs intake + if: steps.docs-payload.outputs.count != '0' env: - GH_TOKEN: ${{ steps.app-token.outputs.token }} + GH_TOKEN: ${{ steps.docs-app-token.outputs.token }} run: | - gh workflow run deploy.yml \ - --repo test-zeus-ai/testzeus-docs \ - --ref main + jq '{event_type: "source-updated", client_payload: .}' docs-payload.json > docs-dispatch.json + gh api repos/test-zeus-ai/testzeus-docs/dispatches --input docs-dispatch.json diff --git a/.github/workflows/pr-metadata-check.yml b/.github/workflows/pr-metadata-check.yml new file mode 100644 index 0000000..bd668bf --- /dev/null +++ b/.github/workflows/pr-metadata-check.yml @@ -0,0 +1,63 @@ +name: Release metadata check + +on: + pull_request: + types: [opened, edited, synchronize, reopened] + # Validate every PR targeting dev or main, including promotions and backmerges. + branches: [dev, main] + +permissions: + contents: read + pull-requests: read + +jobs: + validate: + name: release-metadata / validate + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + + - name: Write PR body to file + uses: actions/github-script@v7 + with: + script: | + const fs = require('node:fs'); + fs.writeFileSync('pr-body.txt', context.payload.pull_request.body ?? '', 'utf8'); + + - name: Validate PR metadata + env: + PR_TITLE: ${{ github.event.pull_request.title }} + PR_BODY_FILE: pr-body.txt + PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + PR_AUTHOR: ${{ github.event.pull_request.user.login }} + run: node scripts/release/validate-pr-metadata.mjs + + sync: + name: release-metadata / pr-sync + if: github.event.action == 'opened' || github.event.action == 'reopened' || github.event.action == 'synchronize' || github.event.action == 'edited' + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + with: + ref: ${{ github.event.pull_request.head.sha }} + fetch-depth: 0 + + - name: Write PR body to file + uses: actions/github-script@v7 + with: + script: | + const fs = require('node:fs'); + fs.writeFileSync('pr-body.txt', context.payload.pull_request.body ?? '', 'utf8'); + + - name: Validate PR description matches latest commits + env: + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + PR_BODY_FILE: pr-body.txt + PR_TITLE: ${{ github.event.pull_request.title }} + PR_HEAD_REF: ${{ github.event.pull_request.head.ref }} + PR_BASE_REF: ${{ github.event.pull_request.base.ref }} + PR_AUTHOR: ${{ github.event.pull_request.user.login }} + run: node scripts/release/validate-pr-sync.mjs diff --git a/scripts/release/build-docs-payload.mjs b/scripts/release/build-docs-payload.mjs new file mode 100644 index 0000000..36b7323 --- /dev/null +++ b/scripts/release/build-docs-payload.mjs @@ -0,0 +1,118 @@ +#!/usr/bin/env node +/* Builds the payload testzeus-docs consumes from the pull requests behind a + deploy. + + Only the author-written customer fields cross the boundary — no diffs, no + commit bodies, no internal description text. That is what lets the docs + repository treat the payload as publishable source material rather than + something to be sanitised after the fact. + + Usage: + node scripts/release/build-docs-payload.mjs > docs-payload.json + + Environment: + GITHUB_REPOSITORY owner/repo (set by Actions) + HEAD_SHA commit being deployed + SINCE_SHA optional; walk PRs for every commit in SINCE_SHA..HEAD_SHA + RELEASE optional release identifier, defaults to YYYY-MM + GH_TOKEN token with pull-request read access +*/ +import { execFileSync } from "node:child_process"; + +import { parsePrMetadata } from "./lib/parse-pr-body.mjs"; + +const SHA = /^[0-9a-f]{7,40}$/i; +const repository = process.env.GITHUB_REPOSITORY ?? ""; +const headSha = process.env.HEAD_SHA ?? ""; +const sinceSha = process.env.SINCE_SHA ?? ""; +const release = process.env.RELEASE || new Date().toISOString().slice(0, 7); + +if (!repository || !headSha) { + console.error("GITHUB_REPOSITORY and HEAD_SHA are required"); + process.exit(1); +} +if (!SHA.test(headSha)) { + console.error("HEAD_SHA must be a hex git SHA"); + process.exit(1); +} +if (sinceSha && !SHA.test(sinceSha)) { + console.error("SINCE_SHA must be a hex git SHA when set"); + process.exit(1); +} + +function gh(args) { + return execFileSync("gh", args, { encoding: "utf8" }); +} + +/** Commits to inspect. Defaults to the deployed commit alone, which is the + common case: one squash-merged pull request per deploy. */ +function commitsToInspect() { + if (!sinceSha || sinceSha === headSha) return [headSha]; + try { + const log = execFileSync("git", ["log", "--first-parent", "--pretty=format:%H", `${sinceSha}..${headSha}`], { + encoding: "utf8", + }).trim(); + const commits = log ? log.split("\n") : []; + /* Bound the walk: a deploy after a long gap should not fan out into + hundreds of API calls. */ + return commits.slice(0, 50).concat(commits.length ? [] : [headSha]); + } catch (error) { + console.error(`git log ${sinceSha}..${headSha} failed: ${error.message.split("\n")[0]}`); + process.exit(1); + } +} + +const seen = new Map(); +for (const sha of commitsToInspect()) { + let pulls; + try { + pulls = JSON.parse(gh(["api", `repos/${repository}/commits/${sha}/pulls`, "--jq", "."])); + } catch (error) { + console.error(`Failed to list PRs for ${sha.slice(0, 7)}: ${error.message.split("\n")[0]}`); + process.exit(1); + } + for (const pull of pulls ?? []) { + if ( + !pull.merged_at || + pull.base?.ref !== "main" || + pull.head?.ref !== "dev" || + seen.has(pull.number) + ) continue; + seen.set(pull.number, pull); + } +} + +const changes = []; +for (const pull of seen.values()) { + const parsed = parsePrMetadata(pull.body ?? ""); + const meta = parsed.metadata; + /* Allow-list: only valid, customer-facing PRs cross the docs boundary. + Unclassified and pre-kit bodies are dropped here rather than sent with + their titles. */ + if ( + !parsed.valid || + !meta.docsRequested || + meta.documentationSelectionCount !== 1 || + meta.audience !== "customer-facing" + ) continue; + + const change = { + pullRequest: pull.number, + title: pull.title, + url: pull.html_url, + audience: "customer-facing", + customerReleaseNote: meta.customerReleaseNote || undefined, + areas: meta.affectedAreas + ? meta.affectedAreas.split(/[,\n]/).map((area) => area.trim()).filter(Boolean) + : undefined, + changeTypes: meta.changeTypes?.length ? meta.changeTypes : undefined, + uiChanged: meta.uiChanged, + }; + if (meta.customerImpact) change.customerImpact = meta.customerImpact; + changes.push(change); +} + +process.stdout.write( + `${JSON.stringify({ repository: repository.split("/")[1], sha: headSha, release, changes }, null, 2)}\n`, +); +console.error(`Built docs payload: ${changes.length} customer-facing change(s) from ${seen.size} merged PR(s).`); diff --git a/scripts/release/lib/backmerge.mjs b/scripts/release/lib/backmerge.mjs new file mode 100644 index 0000000..6b7aee2 --- /dev/null +++ b/scripts/release/lib/backmerge.mjs @@ -0,0 +1,86 @@ +export const BACKMERGE_TITLE_PREFIX = "Backmerge main to dev"; + +export const BACKMERGE_COMMIT_REGEX = /^Backmerge main to dev(\s+\[skip ci\])?$/i; + +/** e.g. Merge branch 'dev' into feat/foo, Merge remote-tracking branch 'origin/dev' into ... */ +export const MERGE_BASE_INTO_FEATURE_REGEX = + /^Merge (?:branch|remote-tracking branch) ['"]?(?:origin\/)?dev['"]?(?: of \S+)? into .+/i; + +export function isBackmergeTitle(title) { + return String(title ?? "") + .trim() + .startsWith(BACKMERGE_TITLE_PREFIX); +} + +export function isBackmergeCommitMessage(message) { + const firstLine = String(message ?? "") + .trim() + .split("\n")[0] + ?.trim(); + return Boolean(firstLine && BACKMERGE_COMMIT_REGEX.test(firstLine)); +} + +export function isMergeBaseIntoFeatureCommit(message) { + const firstLine = String(message ?? "") + .trim() + .split("\n")[0] + ?.trim(); + return Boolean(firstLine && MERGE_BASE_INTO_FEATURE_REGEX.test(firstLine)); +} + +export function isBackmergePullRequest({ title, headRef, authorLogin } = {}) { + if (isBackmergeTitle(title)) { + return true; + } + + if (headRef === "main") { + return true; + } + + if (authorLogin === "github-actions[bot]") { + return true; + } + + return false; +} + +export function listCommitsBetween(baseSha, headSha, runGit) { + if (!(baseSha && headSha) || baseSha === headSha) { + return []; + } + + const output = runGit(["log", `${baseSha}..${headSha}`, "--pretty=format:%s"]); + if (!output) { + return []; + } + + return output.split("\n").filter(Boolean); +} + +/** First-parent only — ignores commits brought in by merging base into the feature branch. */ +export function listFirstParentCommitsBetween(baseSha, headSha, runGit) { + if (!(baseSha && headSha) || baseSha === headSha) { + return []; + } + + const output = runGit(["log", "--first-parent", `${baseSha}..${headSha}`, "--pretty=format:%s"]); + if (!output) { + return []; + } + + return output.split("\n").filter(Boolean); +} + +export function areBackmergeOnlyCommits(subjects) { + return subjects.length > 0 && subjects.every(isBackmergeCommitMessage); +} + +/** True when the only first-parent commits are base merges / backmerges (no feature work). */ +export function areSyncWaivableCommits(subjects) { + return ( + subjects.length > 0 && + subjects.every( + subject => isBackmergeCommitMessage(subject) || isMergeBaseIntoFeatureCommit(subject), + ) + ); +} diff --git a/scripts/release/lib/conventional.mjs b/scripts/release/lib/conventional.mjs new file mode 100644 index 0000000..9e81642 --- /dev/null +++ b/scripts/release/lib/conventional.mjs @@ -0,0 +1,38 @@ +/* Conventional-commit title rules. + + Kept self-contained so the release kit can be dropped into a repository that + has no semantic-release setup of its own. The type list matches + testzeus-hercules-uix's conventional-commit-config.cjs — if a repo adds its + own release tooling later, point this at that config instead of duplicating + the list. */ + +export const ALLOWED_COMMIT_TYPES = [ + "feat", + "enhancement", + "fix", + "perf", + "revert", + "security", + "docs", + "chore", + "refactor", + "style", + "test", + "build", + "ci", +]; + +const CONVENTIONAL_TITLE_REGEX = new RegExp( + `^(Merge (branch|remote-tracking branch|pull request)|(${ALLOWED_COMMIT_TYPES.join("|")})(\\([a-zA-Z0-9-]+\\))?!?:).+`, + "i", +); + +export function isConventionalTitle(title) { + return CONVENTIONAL_TITLE_REGEX.test(String(title ?? "").trim()); +} + +export function isConventionalCommitMessage(message) { + const firstLine = String(message ?? "").split("\n")[0]?.trim() ?? ""; + if (/^Merge (branch|remote-tracking branch|pull request)/i.test(firstLine)) return true; + return isConventionalTitle(firstLine); +} diff --git a/scripts/release/lib/parse-pr-body.mjs b/scripts/release/lib/parse-pr-body.mjs new file mode 100644 index 0000000..555f516 --- /dev/null +++ b/scripts/release/lib/parse-pr-body.mjs @@ -0,0 +1,212 @@ +const PLACEHOLDER_PATTERNS = [ + /^$/m, + /^TBD$/i, + /^TODO$/i, + /^-$/, + /^\.{3}$/, + /^Describe /i, + /^Provide /i, + /^Add /i, + /^List /i, + /^Link /i, + /^e\.g\./i, + /^Write /i, + /^Flag name/i, + /^Steps required/i, + /^How to revert/i, + /^What you tested/i, + /^Screenshot,/i, + /^One sentence customers/i, + /^Business or technical/i, + /^Who is affected/i, +]; + +export function isAllowedOptionalValue(text) { + return /^(none|n\/a)$/i.test(text.trim()); +} + +export function isPlaceholder(text, { allowOptionalValues = false } = {}) { + const trimmed = text.trim(); + if (trimmed.length === 0) { + return true; + } + if (allowOptionalValues && isAllowedOptionalValue(trimmed)) { + return false; + } + if (trimmed.includes("/i; + +export function buildSyncMarker(headSha) { + return ``; +} + +export function extractSyncHead(body) { + const match = body.match(PR_SYNC_MARKER_REGEX); + return match?.[1]?.toLowerCase() ?? null; +} + +export function upsertSyncMarker(body, headSha) { + const marker = buildSyncMarker(headSha); + if (PR_SYNC_MARKER_REGEX.test(body)) { + return body.replace(PR_SYNC_MARKER_REGEX, marker); + } + return `${body.trimEnd()}\n\n${marker}\n`; +} + +export function validatePrSync(body, headSha) { + const errors = []; + const normalizedHead = headSha?.trim().toLowerCase(); + + if (!normalizedHead) { + errors.push("HEAD_SHA is required for PR sync validation"); + return errors; + } + + const syncedSha = extractSyncHead(body); + + if (!syncedSha) { + errors.push( + `PR description must be updated for the latest commits. Refresh What changed, Testing completed, and related sections, then add ${buildSyncMarker(normalizedHead)} to the PR body (or run /sync-pr in Cursor).`, + ); + return errors; + } + + if (syncedSha !== normalizedHead) { + errors.push( + `PR description is out of date with the latest commits (synced: ${syncedSha.slice(0, 7)}, head: ${normalizedHead.slice(0, 7)}). Update the description accordingly and set ${buildSyncMarker(normalizedHead)}.`, + ); + } + + return errors; +} diff --git a/scripts/release/lib/read-pr-body.mjs b/scripts/release/lib/read-pr-body.mjs new file mode 100644 index 0000000..9962184 --- /dev/null +++ b/scripts/release/lib/read-pr-body.mjs @@ -0,0 +1,11 @@ +import { readFileSync } from "node:fs"; + +export function readPrBody(argvValue, env = process.env) { + if (typeof argvValue === "string" && argvValue.length > 0) { + return argvValue; + } + if (env.PR_BODY_FILE) { + return readFileSync(env.PR_BODY_FILE, "utf8"); + } + return env.PR_BODY ?? ""; +} diff --git a/scripts/release/validate-pr-metadata.mjs b/scripts/release/validate-pr-metadata.mjs new file mode 100644 index 0000000..1e7c339 --- /dev/null +++ b/scripts/release/validate-pr-metadata.mjs @@ -0,0 +1,48 @@ +#!/usr/bin/env node +import { isConventionalTitle } from "./lib/conventional.mjs"; +import { parsePrMetadata } from "./lib/parse-pr-body.mjs"; +import { readPrBody } from "./lib/read-pr-body.mjs"; + +const title = process.argv[2] ?? process.env.PR_TITLE ?? ""; +const body = readPrBody(process.argv[3]); +const warnOnly = process.env.RELEASE_METADATA_WARN_ONLY === "true"; +const headRef = process.env.PR_HEAD_REF ?? ""; +const baseRef = process.env.PR_BASE_REF ?? ""; + +const errors = []; + +if (!isConventionalTitle(title)) { + errors.push("PR title must follow Conventional Commits (e.g. feat(scope): description)"); +} + +const parsed = parsePrMetadata(body); +errors.push(...parsed.errors); + +if (baseRef === "main") { + if (headRef !== "dev") { + errors.push("Only dev -> main promotion pull requests are allowed"); + } else if (parsed.metadata.documentationSelectionCount !== 1) { + errors.push("Documentation: select exactly one of Add to docs or No docs update for dev -> main PRs"); + } +} + +if (parsed.metadata.docsRequested && parsed.metadata.audience !== "customer-facing") { + errors.push("Add to docs requires the release classification Customer-facing"); +} + +if (errors.length > 0) { + for (const error of errors) { + const prefix = warnOnly ? "::warning ::" : "::error ::"; + console.log(`${prefix}${error}`); + } + + if (warnOnly) { + console.log("::notice ::Release metadata validation failed (warn-only mode)"); + process.exit(0); + } + + console.error(`Release metadata validation failed (${errors.length} issue(s))`); + process.exit(1); +} + +console.log("Release metadata validation passed"); diff --git a/scripts/release/validate-pr-sync.mjs b/scripts/release/validate-pr-sync.mjs new file mode 100644 index 0000000..506b603 --- /dev/null +++ b/scripts/release/validate-pr-sync.mjs @@ -0,0 +1,63 @@ +#!/usr/bin/env node +import { execFileSync } from "node:child_process"; + +import { + areBackmergeOnlyCommits, + areSyncWaivableCommits, + listCommitsBetween, + listFirstParentCommitsBetween, +} from "./lib/backmerge.mjs"; +import { extractSyncHead, validatePrSync } from "./lib/pr-sync-marker.mjs"; +import { readPrBody } from "./lib/read-pr-body.mjs"; + +const headSha = process.argv[2] ?? process.env.HEAD_SHA ?? ""; +const body = readPrBody(process.argv[3]); +const warnOnly = process.env.RELEASE_METADATA_WARN_ONLY === "true"; + +const errors = validatePrSync(body, headSha); + +if (errors.length > 0) { + const syncedSha = extractSyncHead(body); + + if (syncedSha && headSha) { + try { + const runGit = args => execFileSync("git", args, { encoding: "utf8" }).trim(); + const subjects = listCommitsBetween(syncedSha, headSha, runGit); + const firstParentSubjects = listFirstParentCommitsBetween(syncedSha, headSha, runGit); + + if (areBackmergeOnlyCommits(subjects)) { + console.log( + "::notice ::PR sync waived — only backmerge commits since last description sync", + ); + process.exit(0); + } + + // Merging `dev` into a feature branch pulls many base commits into `A..B`, but + // first-parent history only shows the merge commit itself. Don't force a PR + // description rewrite for that. + if (areSyncWaivableCommits(firstParentSubjects)) { + console.log( + "::notice ::PR sync waived — only base-merge/backmerge commits on first-parent since last description sync", + ); + process.exit(0); + } + } catch { + // Git history unavailable — keep validation errors + } + } + + for (const error of errors) { + const prefix = warnOnly ? "::warning ::" : "::error ::"; + console.log(`${prefix}${error}`); + } + + if (warnOnly) { + console.log("::notice ::PR description sync validation failed (warn-only mode)"); + process.exit(0); + } + + console.error(`PR description sync validation failed (${errors.length} issue(s))`); + process.exit(1); +} + +console.log(`PR description sync validation passed (head ${headSha.slice(0, 7)})`); From 816b9336c46eaa4260cee181b89327e86fa00c1d Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Thu, 29 Oct 2026 17:02:57 +0530 Subject: [PATCH 2/7] feat(mcp): add Test Blocks authoring and live-run tools (#25) * feat(mcp): add Test Blocks authoring and live-run tools Expose create/add-step/verify/save/live-run tools and refuse to queue a Test Blocks test that is not ready. Co-authored-by: Cursor * fix(mcp): check tag-selected runs and compact Test Blocks replies Require SDK 0.0.28, apply the readiness guard when tests are selected by tags, and return a step summary instead of the full graph on mutations. Co-authored-by: Cursor --------- Co-authored-by: Cursor --- pyproject.toml | 4 +- tests/test_server.py | 8 + tests/test_test_blocks.py | 114 +++++++++++++ testzeus_mcp_server/server.py | 262 ++++++++++++++++++++++++++++- testzeus_mcp_server/test_blocks.py | 128 ++++++++++++++ uv.lock | 2 +- 6 files changed, 514 insertions(+), 4 deletions(-) create mode 100644 tests/test_test_blocks.py create mode 100644 testzeus_mcp_server/test_blocks.py diff --git a/pyproject.toml b/pyproject.toml index 4680f83..1ade3c3 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "testzeus-mcp-server" -version = "2.0.3" +version = "2.0.4" description = "FastMCP server for TestZeus SDK - enables Claude and other MCP clients to conduct intelligent testing activities" authors = [ {name = "TestZeus Team", email = "info@testzeus.com"} @@ -13,7 +13,7 @@ readme = "README.md" requires-python = ">=3.11,<4.0" dependencies = [ "fastmcp>=2.0.0", - "testzeus-sdk>=0.0.25,!=0.0.26", + "testzeus-sdk>=0.0.28,!=0.0.26", "aiohttp>=3.8.0", "python-dateutil>=2.9.0.post0", ] diff --git a/tests/test_server.py b/tests/test_server.py index 4e21d1a..1d34ec2 100644 --- a/tests/test_server.py +++ b/tests/test_server.py @@ -192,6 +192,9 @@ def test_server_defines_mcp_tools(self): assert "async def list_tests" in content assert "async def get_test" in content assert "async def create_test" in content + assert "async def create_test_blocks" in content + assert "async def verify_test_blocks" in content + assert "async def live_run_test_blocks" in content assert "async def list_test_suites" in content assert "async def create_test_suite" in content assert "async def list_test_suite_runs" in content @@ -240,6 +243,11 @@ def test_server_implements_test_management_tools(self): assert "delete_test" in content assert "get_test_input_params" in content assert "get_dependent_test_suites" in content + assert "create_test_blocks" in content + assert "add_test_blocks_step" in content + assert "verify_test_blocks" in content + assert "save_test_blocks" in content + assert "live_run_test_blocks" in content def test_server_implements_test_suite_management_tools(self): """Test that server implements suite management functionality.""" diff --git a/tests/test_test_blocks.py b/tests/test_test_blocks.py new file mode 100644 index 0000000..6354326 --- /dev/null +++ b/tests/test_test_blocks.py @@ -0,0 +1,114 @@ +"""Unit tests for Test Blocks helpers and the MCP tool surface.""" + +from types import SimpleNamespace + +from testzeus_mcp_server.test_blocks import ( + SDK_HINT, + builder_status, + is_test_blocks_test, + manager, + not_ready_run_error, + summarize_builder, + validate_step_type, + verify_summary, +) + + +class TestHelpers: + def test_is_test_blocks_test(self): + assert is_test_blocks_test(SimpleNamespace(is_test_blocks=True)) + assert is_test_blocks_test(SimpleNamespace(executor="test_blocks", data={})) + assert is_test_blocks_test( + SimpleNamespace(executor="hercules", authoring_mode="box_graph", data={}) + ) + assert not is_test_blocks_test( + SimpleNamespace(executor="hercules", authoring_mode="legacy", data={}) + ) + assert not is_test_blocks_test(None) + + def test_not_ready_run_error(self): + ready = SimpleNamespace( + id="readyid12345678", is_test_blocks=True, builder_status="ready", data={} + ) + draft = SimpleNamespace( + id="draftid12345678", is_test_blocks=True, builder_status="authoring", data={} + ) + gherkin = SimpleNamespace( + id="gherkin1234567", is_test_blocks=False, executor="hercules", data={} + ) + assert not_ready_run_error([ready, gherkin]) is None + message = not_ready_run_error([draft, gherkin]) + assert message.startswith("Error:") + assert "draftid12345678" in message + assert "verify_test_blocks" in message + + def test_builder_status_falls_back_to_data(self): + assert builder_status(SimpleNamespace(data={"builder_status": "invalid"})) == "invalid" + + def test_manager_requires_sdk_surface(self): + try: + manager(None) + raise AssertionError("expected error") + except ValueError as exc: + assert "authenticated" in str(exc) + try: + manager(SimpleNamespace()) + raise AssertionError("expected error") + except ValueError as exc: + assert SDK_HINT in str(exc) + tb = object() + assert manager(SimpleNamespace(test_blocks=tb)) is tb + + def test_validate_step_type(self): + assert validate_step_type(None) is None + assert validate_step_type("backend") == "backend" + assert validate_step_type("mobile") == "mobile" + try: + validate_step_type("gherkin") + raise AssertionError("expected error") + except ValueError as exc: + assert "step_type" in str(exc) + + def test_summarize_and_verify(self): + payload = { + "id": "t1", + "name": "n", + "builder_status": "authoring", + "block_graph_hash": "h", + "blocks": [ + { + "id": "a", + "kind": "intent", + "label": "one", + "step_type": "backend", + "implementation": {"verificationStatus": "verified"}, + "authoring": {}, + }, + { + "id": "b", + "kind": "intent", + "label": "two", + "implementation": {"verificationStatus": "failed"}, + "authoring": {"isAssert": True}, + }, + ], + "validation": {"errors": [{"code": "UNVERIFIED", "message": "fix"}]}, + } + summary = summarize_builder(payload) + assert summary["id"] == "t1" and len(summary["steps"]) == 2 + assert "UNVERIFIED" in summary["errors"][0] + assert verify_summary(payload)["status"] == "failed" + + +class TestServerSurface: + def test_create_test_points_at_test_blocks(self): + with open("testzeus_mcp_server/server.py") as f: + content = f.read() + assert "create_test_blocks instead" in content + assert "async def create_test_blocks" in content + assert "async def add_test_blocks_step" in content + assert "async def verify_test_blocks" in content + assert "async def save_test_blocks" in content + assert "async def live_run_test_blocks" in content + assert "async def get_test_blocks_run_status" in content + assert "builder_status" in content diff --git a/testzeus_mcp_server/server.py b/testzeus_mcp_server/server.py index 015e5e6..4b173e5 100644 --- a/testzeus_mcp_server/server.py +++ b/testzeus_mcp_server/server.py @@ -31,6 +31,8 @@ from mcp.server.fastmcp import Context, FastMCP from testzeus_sdk.client import TestZeusClient +from testzeus_mcp_server import test_blocks as test_blocks_ops + # Set up logging logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) @@ -129,6 +131,10 @@ async def list_tests( "name": test.name, "testing_type": test.testing_type, "execution_mode": test.execution_mode, + "executor": getattr(test, "executor", None), + "builder_status": getattr(test, "builder_status", None), + "origin": getattr(test, "origin", None), + "authoring_mode": getattr(test, "authoring_mode", None), "test_feature": test.test_feature, "tags": test.tags, "environment": test.environment, @@ -161,6 +167,11 @@ async def get_test(test_id_or_name: str, ctx: Context = None) -> str: "name": test.name, "testing_type": test.testing_type, "execution_mode": test.execution_mode, + "executor": getattr(test, "executor", None), + "builder_status": getattr(test, "builder_status", None), + "origin": getattr(test, "origin", None), + "authoring_mode": getattr(test, "authoring_mode", None), + "builder_validation": getattr(test, "builder_validation", None), "test_feature": test.test_feature, "tags": test.tags, "test_data": test.test_data, @@ -198,9 +209,10 @@ async def create_test( execution_mode: Literal["lenient", "strict"] = "lenient", ctx: Context = None, ) -> str: - """Create a new test in TestZeus. + """Create a Gherkin (Hercules) test in TestZeus. testing_type defaults to 'web'. When set to 'mobile', an environment reference is required. + For a step-based Test Blocks test (Playwright / tz Python), use create_test_blocks instead. """ if testing_type == "mobile" and not environment: return "Error: environment is required when testing_type is 'mobile'" @@ -375,6 +387,246 @@ async def delete_test(test_id_or_name: str, ctx: Context = None) -> str: return error_msg +def _tb(): + return test_blocks_ops.manager(testzeus_client) + + +async def _tb_call(ctx: Context, label: str, operation, compact: bool = True): + if not await ensure_authenticated(): + await authenticate_testzeus() + try: + result = await operation(_tb()) + if ctx: + await ctx.info(label) + if isinstance(result, str): + return result + if compact and isinstance(result, dict) and "blocks" in result: + result = test_blocks_ops.summarize_builder(result) + return json.dumps(result, cls=DateTimeEncoder) + except Exception as e: + error_msg = f"Error: {str(e)}" + if ctx: + await ctx.error(error_msg) + return error_msg + + +async def _tests_for_run(test_ids: list[str] | None, tags: list[str] | None) -> list: + loaded = [] + if test_ids: + for test_id in test_ids: + loaded.append(await testzeus_client.tests.get_one(test_id)) + return loaded + if not tags: + return loaded + listing = await testzeus_client.tests.get_list(filters={"tags": tags}, per_page=100) + items = listing.get("items") if isinstance(listing, dict) else getattr(listing, "items", []) + return list(items or []) + + +@mcp.tool() +async def create_test_blocks( + name: str, + testing_type: Literal["web", "mobile"] = "web", + environment: str | None = None, + test_data: list[str] | None = None, + knowledge_base_id: list[str] | None = None, + idempotency_key: str | None = None, + ctx: Context = None, +) -> str: + """Create an empty Test Blocks test (ordered Playwright / tz Python steps). + + Do not use create_test for this: that path requires a Gherkin feature. + After create, set environment_url_key via update_test_blocks_config, add steps, verify, save, then live_run_test_blocks. + """ + if testing_type == "mobile" and not environment: + return "Error: environment is required when testing_type is 'mobile'" + return await _tb_call( + ctx, + f"Created Test Blocks test '{name}'", + lambda tb: tb.create( + name, + testing_type=testing_type, + environment=environment, + test_data=test_data, + knowledge_base_id=knowledge_base_id, + idempotency_key=idempotency_key, + ), + ) + + +@mcp.tool() +async def get_test_blocks(test_id: str, ctx: Context = None) -> str: + """Get a Test Blocks test with its steps, validation, and builder_status.""" + return await _tb_call( + ctx, f"Retrieved Test Blocks test {test_id}", lambda tb: tb.get(test_id), compact=False + ) + + +@mcp.tool() +async def add_test_blocks_step( + test_id: str, + instruction: str = "", + step_type: Literal["browser", "mobile", "backend", "soql", "apex", "http"] | None = None, + source: str | None = None, + label: str | None = None, + after_step_id: str | None = None, + request: dict[str, Any] | None = None, + is_assert: bool = False, + target_org: str | None = None, + prepend: bool = False, + ctx: Context = None, +) -> str: + """Add one step. Without source, code is generated from instruction when the test is verified. + + request is the typed form for soql/apex/http, e.g. + {"query": "SELECT Id FROM Account", "outputName": "accounts"}. + """ + try: + test_blocks_ops.validate_step_type(step_type) + except ValueError as exc: + return f"Error: {exc}" + if not instruction.strip() and not (source or "").strip() and request is None: + return "Error: provide instruction, source, or a typed request" + return await _tb_call( + ctx, + f"Added step to {test_id}", + lambda tb: tb.add_step( + test_id, + instruction=instruction, + step_type=step_type, + source=source, + label=label, + after_step_id=after_step_id, + request=request, + is_assert=is_assert, + target_org=target_org, + prepend=prepend, + ), + ) + + +@mcp.tool() +async def update_test_blocks_step( + test_id: str, + step_id: str, + instruction: str | None = None, + source: str | None = None, + label: str | None = None, + step_type: Literal["browser", "mobile", "backend", "soql", "apex", "http"] | None = None, + request: dict[str, Any] | None = None, + is_assert: bool | None = None, + target_org: str | None = None, + ctx: Context = None, +) -> str: + """Edit a step. Changing source marks it unverified; verify again before saving.""" + try: + test_blocks_ops.validate_step_type(step_type) + except ValueError as exc: + return f"Error: {exc}" + return await _tb_call( + ctx, + f"Updated step {step_id}", + lambda tb: tb.update_step( + test_id, + step_id, + instruction=instruction, + source=source, + label=label, + step_type=step_type, + request=request, + is_assert=is_assert, + target_org=target_org, + ), + ) + + +@mcp.tool() +async def delete_test_blocks_steps(test_id: str, step_ids: list[str], ctx: Context = None) -> str: + """Delete steps; the remaining steps are reconnected in order.""" + if not step_ids: + return "Error: step_ids is required" + return await _tb_call( + ctx, f"Deleted {len(step_ids)} step(s)", lambda tb: tb.delete_steps(test_id, step_ids) + ) + + +@mcp.tool() +async def update_test_blocks_config( + test_id: str, + environment: str | None = None, + environment_url_key: str | None = None, + test_data: list[str] | None = None, + knowledge_base_id: list[str] | None = None, + step_retry_count: int | None = None, + ctx: Context = None, +) -> str: + """Change a Test Blocks test's environment, test data, knowledge bases, or step retry count.""" + return await _tb_call( + ctx, + f"Updated config for {test_id}", + lambda tb: tb.update_config( + test_id, + environment=environment, + environment_url_key=environment_url_key, + test_data=test_data, + knowledge_base_id=knowledge_base_id, + step_retry_count=step_retry_count, + ), + ) + + +@mcp.tool() +async def verify_test_blocks( + test_id: str, + through_step_id: str | None = None, + wait: bool = True, + timeout: int = 90, + ctx: Context = None, +) -> str: + """Run steps in order so they can be saved. + + The worker leases a browser when a browser step needs one. + Default wait is 90s; use wait=false and poll get_test_blocks if the client times out sooner. + """ + if timeout < 0: + return "Error: timeout must be >= 0" + + async def operation(tb): + started = await tb.verify(test_id, through_step_id=through_step_id) + if not wait or started.get("status") == "already_current": + return started + await tb.wait_for_verify(test_id, timeout=timeout) + payload = await tb.get(test_id) + return test_blocks_ops.verify_summary(payload) + + return await _tb_call(ctx, f"Verified Test Blocks test {test_id}", operation, compact=False) + + +@mcp.tool() +async def save_test_blocks(test_id: str, ctx: Context = None) -> str: + """Save the test. builder_status becomes ready only when every reachable step is verified.""" + return await _tb_call(ctx, f"Saved Test Blocks test {test_id}", lambda tb: tb.save(test_id)) + + +@mcp.tool() +async def live_run_test_blocks(test_id: str, key: str | None = None, ctx: Context = None) -> str: + """Start an official run of a saved, ready Test Blocks test. + + Prefer this over run_test for Test Blocks. Pass key to make retries idempotent. + """ + return await _tb_call( + ctx, f"Queued live run for {test_id}", lambda tb: tb.live_run(test_id, key=key) + ) + + +@mcp.tool() +async def get_test_blocks_run_status(test_run_id: str, ctx: Context = None) -> str: + """Aggregated status of a Test Blocks live run, including dash steps and attachments.""" + return await _tb_call( + ctx, f"Retrieved run status {test_run_id}", lambda tb: tb.get_run_status(test_run_id) + ) + + @mcp.tool() async def run_test( name: str, @@ -392,6 +644,10 @@ async def run_test( return "Error: test_ids and tags cannot be used together, provide one of them." try: + loaded = await _tests_for_run(test_ids, tags) + blocked = test_blocks_ops.not_ready_run_error(loaded) + if blocked: + return blocked group = await testzeus_client.test_run_groups.create_and_execute( name=name, test_ids=test_ids, @@ -2576,6 +2832,10 @@ async def create_test_run_group( return "Error: test_ids and tags cannot be used together, provide one of them." try: + loaded = await _tests_for_run(test_ids, tags) + blocked = test_blocks_ops.not_ready_run_error(loaded) + if blocked: + return blocked group = await testzeus_client.test_run_groups.create_and_execute( name=name, test_ids=test_ids, diff --git a/testzeus_mcp_server/test_blocks.py b/testzeus_mcp_server/test_blocks.py new file mode 100644 index 0000000..53d07cc --- /dev/null +++ b/testzeus_mcp_server/test_blocks.py @@ -0,0 +1,128 @@ +"""Test Blocks helpers for the MCP server. + +A Test Blocks test (``executor == "test_blocks"``) is an ordered list of steps. +Steps cannot be written through the tests collection: every change goes through +``client.test_blocks`` (SDK >= 0.0.28). A test only becomes ``ready`` after +verify then save. +""" + +from typing import Any + +SDK_HINT = "Test Blocks tools need testzeus-sdk>=0.0.28. Upgrade with: pip install -U testzeus-sdk" +STEP_TYPES = ("browser", "mobile", "backend", "soql", "apex", "http") +RUNNABLE_VERIFICATION = ("verified", "inferred", "transcribed") + + +def manager(client: Any) -> Any: + if client is None: + raise ValueError("Not authenticated") + tb = getattr(client, "test_blocks", None) + if tb is None: + raise ValueError(SDK_HINT) + return tb + + +def is_test_blocks_test(test: Any) -> bool: + if test is None: + return False + if getattr(test, "is_test_blocks", None) is True: + return True + data = getattr(test, "data", None) or {} + executor = str(getattr(test, "executor", None) or data.get("executor") or "").strip().lower() + mode = ( + str(getattr(test, "authoring_mode", None) or data.get("authoring_mode") or "") + .strip() + .lower() + ) + return executor in ("test_blocks", "test_builder") or mode == "box_graph" + + +def builder_status(test: Any) -> str: + data = getattr(test, "data", None) or {} + return str(getattr(test, "builder_status", None) or data.get("builder_status") or "") + + +def not_ready_run_error(tests: list[Any]) -> str | None: + """Error when run_test / create_test_run_group would queue an unverified Test Blocks test.""" + blocked = [ + test for test in tests if is_test_blocks_test(test) and builder_status(test) != "ready" + ] + if not blocked: + return None + ids = ", ".join(str(getattr(test, "id", "?")) for test in blocked) + return ( + f"Error: Test Blocks test(s) {ids} are not ready to run. " + "Verify every step, then save (verify_test_blocks + save_test_blocks), " + "or use live_run_test_blocks which enforces readiness." + ) + + +def test_identity(test: Any) -> dict[str, Any]: + return { + "id": getattr(test, "id", None), + "name": getattr(test, "name", None), + "executor": getattr(test, "executor", None), + "origin": getattr(test, "origin", None), + "authoring_mode": getattr(test, "authoring_mode", None), + "builder_status": getattr(test, "builder_status", None), + "testing_type": getattr(test, "testing_type", None), + "execution_mode": getattr(test, "execution_mode", None), + "test_feature": getattr(test, "test_feature", None), + "environment": getattr(test, "environment", None), + "test_data": getattr(test, "test_data", None), + "tags": getattr(test, "tags", None), + } + + +def summarize_builder(payload: dict[str, Any]) -> dict[str, Any]: + """Compact mutation response: ids, status, ordered steps, validation errors.""" + blocks = payload.get("blocks") or [] + steps = [] + for block in blocks: + if str(block.get("kind") or "intent") not in ("", "intent"): + continue + steps.append( + { + "id": block.get("id"), + "label": block.get("label"), + "step_type": block.get("step_type") or "browser", + "verification": (block.get("implementation") or {}).get("verificationStatus") + or "unverified", + "assert": bool((block.get("authoring") or {}).get("isAssert")), + } + ) + validation = payload.get("validation") or {} + return { + "id": payload.get("id"), + "name": payload.get("name"), + "builder_status": payload.get("builder_status"), + "block_graph_hash": payload.get("block_graph_hash"), + "environment": payload.get("environment"), + "environment_url_key": payload.get("environment_url_key"), + "steps": steps, + "errors": [ + f'{issue.get("code")}: {issue.get("message")}' for issue in validation.get("errors") or [] + ], + } + + +def verify_summary(payload: dict[str, Any]) -> dict[str, Any]: + summary = summarize_builder(payload) + failed = [ + step + for step in summary["steps"] + if step["verification"] not in RUNNABLE_VERIFICATION + ] + summary["status"] = "failed" if failed else "verified" + summary["failed_steps"] = failed + return summary + + +def validate_step_type(step_type: str | None) -> str | None: + if step_type is None: + return None + if step_type not in STEP_TYPES: + raise ValueError( + f"Invalid step_type '{step_type}'. Must be one of: {', '.join(STEP_TYPES)}" + ) + return step_type diff --git a/uv.lock b/uv.lock index a99f268..4cb6b86 100644 --- a/uv.lock +++ b/uv.lock @@ -1954,7 +1954,7 @@ wheels = [ [[package]] name = "testzeus-mcp-server" -version = "2.0.3" +version = "2.0.4" source = { editable = "." } dependencies = [ { name = "aiohttp" }, From 0fa3cba2757a2f6938995ba2cbc6e47d01f9d1cb Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Thu, 29 Oct 2026 17:28:22 +0530 Subject: [PATCH 3/7] ci: install unpublished testzeus-sdk from GitHub in promote CI uv cannot resolve testzeus-sdk>=0.0.28 from PyPI until that SDK is published, so fall back to a GitHub checkout. Co-authored-by: Cursor --- .github/workflows/ci.yml | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index aca3212..212f3a1 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,8 +26,36 @@ jobs: with: version: "latest" + - name: Generate testzeus-sdk checkout token + id: sdk-token + uses: actions/create-github-app-token@v3 + with: + app-id: ${{ vars.GH_APP_ID }} + private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} + owner: test-zeus-ai + repositories: testzeus-sdk + + - name: Checkout testzeus-sdk + uses: actions/checkout@v5 + with: + repository: test-zeus-ai/testzeus-sdk + ref: dev + path: .deps/testzeus-sdk + token: ${{ steps.sdk-token.outputs.token }} + - name: Install dependencies run: | + set +e + uv sync --dev + status=$? + set -e + if [ "$status" -eq 0 ]; then + echo "Installed dependencies from package indexes" + exit 0 + fi + echo "testzeus-sdk is unpublished; using GitHub checkout at .deps/testzeus-sdk" + printf '\n[tool.uv.sources]\ntestzeus-sdk = { path = ".deps/testzeus-sdk" }\n' >> pyproject.toml + uv lock --upgrade-package testzeus-sdk uv sync --dev - name: Run linting From 84aee1d4f193a5ab563a23b3250e89e1278bfb5d Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Thu, 29 Oct 2026 17:34:09 +0530 Subject: [PATCH 4/7] ci: fall back to published testzeus-sdk when 0.0.28 is missing This public repo cannot check out the private SDK, so lint/build uses the latest PyPI SDK until 0.0.28 is published. Co-authored-by: Cursor --- .github/workflows/ci.yml | 31 +------------------------------ scripts/ci/install-deps.sh | 29 +++++++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 30 deletions(-) create mode 100644 scripts/ci/install-deps.sh diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 212f3a1..63ef2ee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -26,37 +26,8 @@ jobs: with: version: "latest" - - name: Generate testzeus-sdk checkout token - id: sdk-token - uses: actions/create-github-app-token@v3 - with: - app-id: ${{ vars.GH_APP_ID }} - private-key: ${{ secrets.GH_APP_PRIVATE_KEY }} - owner: test-zeus-ai - repositories: testzeus-sdk - - - name: Checkout testzeus-sdk - uses: actions/checkout@v5 - with: - repository: test-zeus-ai/testzeus-sdk - ref: dev - path: .deps/testzeus-sdk - token: ${{ steps.sdk-token.outputs.token }} - - name: Install dependencies - run: | - set +e - uv sync --dev - status=$? - set -e - if [ "$status" -eq 0 ]; then - echo "Installed dependencies from package indexes" - exit 0 - fi - echo "testzeus-sdk is unpublished; using GitHub checkout at .deps/testzeus-sdk" - printf '\n[tool.uv.sources]\ntestzeus-sdk = { path = ".deps/testzeus-sdk" }\n' >> pyproject.toml - uv lock --upgrade-package testzeus-sdk - uv sync --dev + run: bash scripts/ci/install-deps.sh - name: Run linting run: | diff --git a/scripts/ci/install-deps.sh b/scripts/ci/install-deps.sh new file mode 100644 index 0000000..72a6aa2 --- /dev/null +++ b/scripts/ci/install-deps.sh @@ -0,0 +1,29 @@ +#!/usr/bin/env bash +# Install from PyPI. If testzeus-sdk>=0.0.28 is unpublished, use the latest +# published SDK so lint/build can run on this public repository. +set -euo pipefail + +set +e +uv sync --dev +status=$? +set -e +if [ "$status" -eq 0 ]; then + echo "Installed dependencies from package indexes" + exit 0 +fi + +echo "testzeus-sdk>=0.0.28 is not on PyPI yet; using the latest published SDK for lint/build" +python3 - <<'PY' +from pathlib import Path + +path = Path("pyproject.toml") +text = path.read_text() +old = '"testzeus-sdk>=0.0.28,!=0.0.26"' +new = '"testzeus-sdk>=0.0.27,!=0.0.26"' +if old not in text: + raise SystemExit("could not rewrite the testzeus-sdk pin in pyproject.toml") +path.write_text(text.replace(old, new, 1)) +PY + +uv lock --upgrade-package testzeus-sdk +uv sync --dev From f6fcc9adc6b463016b70248a9fb97036ae91ea5b Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Thu, 29 Oct 2026 17:36:01 +0530 Subject: [PATCH 5/7] fix(mcp): wrap Test Blocks lines that fail ruff E501 Promote CI runs ruff as a gate, and those two descriptions exceeded 100 characters. Co-authored-by: Cursor --- testzeus_mcp_server/server.py | 3 ++- testzeus_mcp_server/test_blocks.py | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/testzeus_mcp_server/server.py b/testzeus_mcp_server/server.py index 4b173e5..e8c1532 100644 --- a/testzeus_mcp_server/server.py +++ b/testzeus_mcp_server/server.py @@ -436,7 +436,8 @@ async def create_test_blocks( """Create an empty Test Blocks test (ordered Playwright / tz Python steps). Do not use create_test for this: that path requires a Gherkin feature. - After create, set environment_url_key via update_test_blocks_config, add steps, verify, save, then live_run_test_blocks. + After create, set environment_url_key via update_test_blocks_config, + add steps, verify, save, then live_run_test_blocks. """ if testing_type == "mobile" and not environment: return "Error: environment is required when testing_type is 'mobile'" diff --git a/testzeus_mcp_server/test_blocks.py b/testzeus_mcp_server/test_blocks.py index 53d07cc..3da883b 100644 --- a/testzeus_mcp_server/test_blocks.py +++ b/testzeus_mcp_server/test_blocks.py @@ -101,7 +101,8 @@ def summarize_builder(payload: dict[str, Any]) -> dict[str, Any]: "environment_url_key": payload.get("environment_url_key"), "steps": steps, "errors": [ - f'{issue.get("code")}: {issue.get("message")}' for issue in validation.get("errors") or [] + f'{issue.get("code")}: {issue.get("message")}' + for issue in validation.get("errors") or [] ], } From 7596dff5f6ea027b0a179e000c22b60002977928 Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Thu, 29 Oct 2026 17:38:24 +0530 Subject: [PATCH 6/7] style(mcp): apply ruff format to Test Blocks summary helper Co-authored-by: Cursor --- testzeus_mcp_server/test_blocks.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/testzeus_mcp_server/test_blocks.py b/testzeus_mcp_server/test_blocks.py index 3da883b..492424a 100644 --- a/testzeus_mcp_server/test_blocks.py +++ b/testzeus_mcp_server/test_blocks.py @@ -101,7 +101,7 @@ def summarize_builder(payload: dict[str, Any]) -> dict[str, Any]: "environment_url_key": payload.get("environment_url_key"), "steps": steps, "errors": [ - f'{issue.get("code")}: {issue.get("message")}' + f"{issue.get('code')}: {issue.get('message')}" for issue in validation.get("errors") or [] ], } @@ -110,9 +110,7 @@ def summarize_builder(payload: dict[str, Any]) -> dict[str, Any]: def verify_summary(payload: dict[str, Any]) -> dict[str, Any]: summary = summarize_builder(payload) failed = [ - step - for step in summary["steps"] - if step["verification"] not in RUNNABLE_VERIFICATION + step for step in summary["steps"] if step["verification"] not in RUNNABLE_VERIFICATION ] summary["status"] = "failed" if failed else "verified" summary["failed_steps"] = failed From 79933b8a6652ea7fa97fe4371bf3da5481431e86 Mon Sep 17 00:00:00 2001 From: rmudukanagoudra Date: Wed, 11 Nov 2026 13:49:24 +0530 Subject: [PATCH 7/7] fix(release): send the feature PRs a promotion ships to docs intake (#28) The docs payload only read the dev -> main promotion pull request. Authors tick "Add to docs" on the feature pull requests they merge into dev, and promotions almost always say "No docs update", so nothing reached testzeus-docs. Deploys that passed SINCE_SHA from the last tag also re-sent the same old promotions on every deploy. The payload now reads every pull request merged into dev between the previous promotion and this one, plus the promotion itself. SINCE_SHA is ignored. Co-authored-by: Claude Opus 5.5 --- scripts/release/build-docs-payload.mjs | 149 ++++++++++++++++++------- 1 file changed, 106 insertions(+), 43 deletions(-) diff --git a/scripts/release/build-docs-payload.mjs b/scripts/release/build-docs-payload.mjs index 36b7323..8db8fd3 100644 --- a/scripts/release/build-docs-payload.mjs +++ b/scripts/release/build-docs-payload.mjs @@ -7,15 +7,25 @@ repository treat the payload as publishable source material rather than something to be sanitised after the fact. + A deploy of `main` is a dev -> main promotion. The customer-facing metadata + ("Add to docs", the release note, affected areas) is written on the feature + pull requests that were merged into `dev`, not on the promotion itself, so + the payload is built from every feature pull request the promotion shipped: + those merged into `dev` after the previous promotion and up to this one. The + promotion pull request is still read too, for promotions whose own body asks + for docs. + Usage: node scripts/release/build-docs-payload.mjs > docs-payload.json Environment: GITHUB_REPOSITORY owner/repo (set by Actions) HEAD_SHA commit being deployed - SINCE_SHA optional; walk PRs for every commit in SINCE_SHA..HEAD_SHA RELEASE optional release identifier, defaults to YYYY-MM GH_TOKEN token with pull-request read access + SINCE_SHA ignored; kept so existing workflows keep working. Walking + a tag range re-sent every promotion since the last tag on + each deploy. */ import { execFileSync } from "node:child_process"; @@ -24,10 +34,13 @@ import { parsePrMetadata } from "./lib/parse-pr-body.mjs"; const SHA = /^[0-9a-f]{7,40}$/i; const repository = process.env.GITHUB_REPOSITORY ?? ""; const headSha = process.env.HEAD_SHA ?? ""; -const sinceSha = process.env.SINCE_SHA ?? ""; const release = process.env.RELEASE || new Date().toISOString().slice(0, 7); -if (!repository || !headSha) { +/* A promotion that ships more feature pull requests than this is not a normal + release; stop rather than fan out into an unbounded number of API calls. */ +const MAX_FEATURE_PRS = 300; + +if (!(repository && headSha)) { console.error("GITHUB_REPOSITORY and HEAD_SHA are required"); process.exit(1); } @@ -35,84 +48,134 @@ if (!SHA.test(headSha)) { console.error("HEAD_SHA must be a hex git SHA"); process.exit(1); } -if (sinceSha && !SHA.test(sinceSha)) { - console.error("SINCE_SHA must be a hex git SHA when set"); - process.exit(1); + +const [owner] = repository.split("/"); + +function ghJson(args) { + return JSON.parse(execFileSync("gh", ["api", ...args], { encoding: "utf8", maxBuffer: 64 * 1024 * 1024 })); } -function gh(args) { - return execFileSync("gh", args, { encoding: "utf8" }); +function isPromotion(pull) { + return Boolean(pull.merged_at) && pull.base?.ref === "main" && pull.head?.ref === "dev"; } -/** Commits to inspect. Defaults to the deployed commit alone, which is the - common case: one squash-merged pull request per deploy. */ -function commitsToInspect() { - if (!sinceSha || sinceSha === headSha) return [headSha]; +/** The dev -> main promotion pull request(s) that produced the deployed commit. */ +function promotionsForHead() { try { - const log = execFileSync("git", ["log", "--first-parent", "--pretty=format:%H", `${sinceSha}..${headSha}`], { - encoding: "utf8", - }).trim(); - const commits = log ? log.split("\n") : []; - /* Bound the walk: a deploy after a long gap should not fan out into - hundreds of API calls. */ - return commits.slice(0, 50).concat(commits.length ? [] : [headSha]); + return ghJson([`repos/${repository}/commits/${headSha}/pulls`]).filter(isPromotion); } catch (error) { - console.error(`git log ${sinceSha}..${headSha} failed: ${error.message.split("\n")[0]}`); + console.error(`Failed to list PRs for ${headSha.slice(0, 7)}: ${error.message.split("\n")[0]}`); process.exit(1); } } -const seen = new Map(); -for (const sha of commitsToInspect()) { - let pulls; - try { - pulls = JSON.parse(gh(["api", `repos/${repository}/commits/${sha}/pulls`, "--jq", "."])); - } catch (error) { - console.error(`Failed to list PRs for ${sha.slice(0, 7)}: ${error.message.split("\n")[0]}`); +/** The promotion merged most recently before `promotion`, if any. */ +function previousPromotion(promotion) { + const merged = []; + for (let page = 1; page <= 5; page += 1) { + const pulls = ghJson([ + `repos/${repository}/pulls?state=closed&base=main&head=${owner}:dev&sort=updated&direction=desc&per_page=100&page=${page}`, + ]); + merged.push(...pulls.filter((pull) => isPromotion(pull) && pull.merged_at < promotion.merged_at)); + if (pulls.length < 100) { + break; + } + } + merged.sort((a, b) => b.merged_at.localeCompare(a.merged_at)); + return merged[0]; +} + +/** Pull requests merged into dev in the window (previous promotion, this promotion]. */ +function featurePullsBetween(previous, promotion) { + const query = `repo:${repository} is:pr is:merged base:dev merged:${previous.merged_at}..${promotion.merged_at}`; + const found = []; + for (let page = 1; page <= 10; page += 1) { + const result = ghJson([ + "-X", + "GET", + "search/issues", + "-f", + `q=${query}`, + "-f", + "per_page=100", + "-f", + `page=${page}`, + ]); + found.push(...result.items); + if (result.items.length < 100 || found.length >= MAX_FEATURE_PRS) { + break; + } + } + if (found.length >= MAX_FEATURE_PRS) { + console.error(`More than ${MAX_FEATURE_PRS} feature PRs between promotions; refusing to build a payload.`); process.exit(1); } - for (const pull of pulls ?? []) { - if ( - !pull.merged_at || - pull.base?.ref !== "main" || - pull.head?.ref !== "dev" || - seen.has(pull.number) - ) continue; - seen.set(pull.number, pull); + /* The search bounds are inclusive; the previous promotion's own merge second + belongs to the earlier release. */ + return found.filter((item) => item.pull_request?.merged_at && item.pull_request.merged_at > previous.merged_at); +} + +const candidates = new Map(); +for (const promotion of promotionsForHead()) { + candidates.set(promotion.number, { + number: promotion.number, + title: promotion.title, + url: promotion.html_url, + body: promotion.body, + }); + + const previous = previousPromotion(promotion); + if (!previous) { + console.error(`#${promotion.number} is the first promotion; only its own body is read.`); + continue; + } + for (const item of featurePullsBetween(previous, promotion)) { + if (candidates.has(item.number)) { + continue; + } + candidates.set(item.number, { number: item.number, title: item.title, url: item.html_url, body: item.body }); } } const changes = []; -for (const pull of seen.values()) { +for (const pull of candidates.values()) { const parsed = parsePrMetadata(pull.body ?? ""); const meta = parsed.metadata; /* Allow-list: only valid, customer-facing PRs cross the docs boundary. Unclassified and pre-kit bodies are dropped here rather than sent with their titles. */ if ( - !parsed.valid || - !meta.docsRequested || + !(parsed.valid && meta.docsRequested) || meta.documentationSelectionCount !== 1 || meta.audience !== "customer-facing" - ) continue; + ) { + continue; + } const change = { pullRequest: pull.number, title: pull.title, - url: pull.html_url, + url: pull.url, audience: "customer-facing", customerReleaseNote: meta.customerReleaseNote || undefined, areas: meta.affectedAreas - ? meta.affectedAreas.split(/[,\n]/).map((area) => area.trim()).filter(Boolean) + ? meta.affectedAreas + .split(/[,\n]/) + .map((area) => area.trim()) + .filter(Boolean) : undefined, changeTypes: meta.changeTypes?.length ? meta.changeTypes : undefined, uiChanged: meta.uiChanged, }; - if (meta.customerImpact) change.customerImpact = meta.customerImpact; + if (meta.customerImpact) { + change.customerImpact = meta.customerImpact; + } changes.push(change); } process.stdout.write( `${JSON.stringify({ repository: repository.split("/")[1], sha: headSha, release, changes }, null, 2)}\n`, ); -console.error(`Built docs payload: ${changes.length} customer-facing change(s) from ${seen.size} merged PR(s).`); +console.error( + `Built docs payload: ${changes.length} customer-facing change(s) from ${candidates.size} merged PR(s).`, +);