From e7c57e548c4632cb222bb3ec200cd4f0519ef588 Mon Sep 17 00:00:00 2001 From: Fernando Fernandes Date: Thu, 19 Nov 2026 13:57:58 +0100 Subject: [PATCH] Resolve TestFlight builds from exact Xcode Cloud runs --- README.md | 18 +- package-lock.json | 4 +- package.json | 2 +- src/api/base-client.ts | 39 ++-- src/api/resources/builds.ts | 53 +++++ src/api/types.ts | 46 ++++- src/index.ts | 2 +- src/tools/build-runs.ts | 114 +++++++---- src/tools/results.ts | 2 +- src/tools/tests.ts | 6 +- src/utils/testflight-builds.ts | 299 ++++++++++++++++++++++++++++ tests/smoke.test.ts | 26 +++ tests/testflight-builds.test.ts | 336 ++++++++++++++++++++++++++++++++ tests/tools.test.ts | 5 + 14 files changed, 887 insertions(+), 65 deletions(-) create mode 100644 src/utils/testflight-builds.ts create mode 100644 tests/testflight-builds.test.ts diff --git a/README.md b/README.md index 20fc201..e4d358d 100644 --- a/README.md +++ b/README.md @@ -19,6 +19,7 @@ MCP server for discovering Xcode Cloud products, inspecting and editing workflow | Discover workflows | `list_workflows` | "List the workflows for product `def456`." | `Feature Branch`, `description`, `isEnabled: true`, `containerFilePath: Chauffeur.xcodeproj` | | Inspect workflow configuration | `get_workflow_details` | "Show me the full workflow details for `abc123`, including environment and actions." | `general`, `environment`, `startConditions`, `actions`, `postActions` | | Monitor running or recent builds | `list_build_runs` | "Show me the running builds for workflow `abc123` so I can monitor them." | `number: 93`, `executionProgress: RUNNING`, `completionStatus: null`, `startedDate: ...` | +| Resolve linked TestFlight build IDs | `get_build_run_testflight_builds` | "Verify this release run and find its iOS and tvOS builds for TestFlight." | verified run provenance and per-platform readiness | | Start an Xcode Cloud build | `start_build` | "Start one build for workflow `abc123`." | newly created build-run ID, number, and execution state | | Enable or disable a workflow | `set_workflow_enabled` | "Disable workflow `abc123` while we are testing new settings." | `operation.type: set_workflow_enabled`, `workflow.general.isEnabled: false` | | Update name, description, or clean mode | `update_workflow_general` | "Rename workflow `abc123` to `Feature Branch v2` and adjust its description." | `changedFields: [name, description]`, updated `workflow.general` | @@ -36,7 +37,7 @@ Build lookup is workflow-scoped. Retrieval tools accept a direct `buildRunId`, o `list_products` and `list_workflows` automatically paginate through all results. -`list_build_runs` supports `status: "all" | "failed" | "succeeded" | "running" | "pending"` and an optional `limit`, which defaults to `20`, so agents can poll active workflows without post-processing every run locally or inflating MCP response size. +`list_build_runs` supports `status: "all" | "failed" | "succeeded" | "running" | "pending"` and an optional exact `sourceCommitSha` filter. The limit (default 20, maximum 500) bounds the runs scanned before filtering. Each result includes the full source commit SHA, canonical source ref and its resource ID when available, the PR flag, and the start reason. For a SHA lookup with no results, check `scan.hasMore` for older runs and `scan.unverifiedSourceCount` for scanned runs whose SHA was unavailable. If several runs match, use the intended exact run ID for the handoff. ## Build Start Behavior @@ -92,7 +93,8 @@ codex mcp add xcode-cloud \ - `list_products()` - `list_workflows(productId)` - `get_workflow_details(workflowId)` -- `list_build_runs(workflowId, limit?, status?)` +- `list_build_runs(workflowId, limit?, status?, sourceCommitSha?)` +- `get_build_run_testflight_builds(buildRunId, workflowId, appId, platforms, expectedSourceRef?, expectedSourceCommitSha?)` - `start_build(workflowId, clean?, sourceBranchOrTagId?, pullRequestId?, buildRunId?)` - `set_workflow_enabled(workflowId, enabled)` - `update_workflow_general(workflowId, name?, description?, clean?)` @@ -247,4 +249,14 @@ Creating an archive, making it eligible for TestFlight, and assigning its proces Apple's [OpenAPI specification](https://developer.apple.com/sample-code/app-store-connect/app-store-connect-openapi-specification.zip), version 4.4.1, inspected on 2026-09-07, exposes no post-action field or relationship in `CiWorkflow`, `CiWorkflowCreateRequest`, or `CiWorkflowUpdateRequest`, and no workflow post-action endpoint. Consequently, workflow responses explicitly report `testFlightDistribution.status: "UNSUPPORTED_BY_APPLE_API"` and group assignment as `UNKNOWN`; the legacy empty `postActions` array is not evidence that no post-actions exist. See Apple's [BuildAudienceType](https://developer.apple.com/documentation/appstoreconnectapi/buildaudiencetype) and [TestFlight distribution guide](https://developer.apple.com/documentation/xcode/distributing-your-xcode-cloud-builds-through-testflight). -Waiting for completion, TestFlight processing, beta-group assignment, and broader release orchestration remain outside this server's current scope and would not be native Xcode Cloud post-actions. +### Read-only TestFlight handoff + +Call `get_build_run_testflight_builds` with an exact Xcode Cloud run ID, its expected workflow ID, the App Store Connect app resource ID, and one or more distinct Apple platform values (`IOS`, `TV_OS`, `MAC_OS`, `VISION_OS`). Run and workflow IDs may also use their `xcode-cloud://` URI forms. For automated handoff, provide both `expectedSourceRef` (for example, `refs/heads/main`) and `expectedSourceCommitSha` (the full Git SHA). With those inputs the tool verifies the branch and revision and rejects pull-request runs. + +The tool verifies the run and workflow, reads the run's linked builds, and verifies each build against its App Store Connect app and prerelease version. When the run returns a build ID without its metadata, the tool reads that exact build ID for the missing evidence. The response includes run provenance and the following statuses. + +- `ready` means the run succeeded and each requested platform has exactly one verified, valid, unexpired, externally eligible build. Each platform includes `build.id`, marketing version, build number, processing state, audience, and expiration state. +- `pending` means the run is still active, a requested platform has no linked build yet, or a relevant build is processing. Read again after the upload or processing progresses. +- `blocked` reports per-platform reasons such as a failed or canceled run, app mismatch, internal-only or expired build, missing or unknown evidence, or ambiguous eligible builds. A run, workflow, or requested source mismatch produces an MCP error. + +A successful archive can precede upload and processing in App Store Connect. When the overall status is `ready`, pass the exact `build.id` values to [app-store-connect-mcp](https://github.com/thatfactory/app-store-connect-mcp) or another consumer that rechecks eligibility before TestFlight distribution. Beta review and group assignment are separate App Store Connect operations. diff --git a/package-lock.json b/package-lock.json index a2067f7..54c4ee7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@thatfactory/xcode-cloud-mcp", - "version": "0.7.0", + "version": "0.8.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@thatfactory/xcode-cloud-mcp", - "version": "0.7.0", + "version": "0.8.0", "license": "MIT", "dependencies": { "@modelcontextprotocol/sdk": "^1.28.0", diff --git a/package.json b/package.json index d1e6c5e..423da2a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@thatfactory/xcode-cloud-mcp", - "version": "0.7.0", + "version": "0.8.0", "description": "MCP server for configuring Xcode Cloud workflows, starting builds, and retrieving build logs, issues, and test artifacts.", "license": "MIT", "type": "module", diff --git a/src/api/base-client.ts b/src/api/base-client.ts index 4809eed..5fe6c51 100644 --- a/src/api/base-client.ts +++ b/src/api/base-client.ts @@ -33,7 +33,7 @@ export class BaseAPIClient { url.searchParams.set(key, value); } - return this.request(url.toString()); + return this.request(url.toString()); } /** @@ -46,27 +46,40 @@ export class BaseAPIClient { params?: Record, maxItems?: number, ): Promise { + return (await this.listAllWithIncluded(path, params, maxItems)).data; + } + + /** Collect primary and included resources, preserving whether the scan hit its bound. */ + protected async listAllWithIncluded( + path: string, + params?: Record, + maxItems?: number, + ): Promise<{ data: TData[]; included: TIncluded[]; hasMore: boolean }> { const allData: TData[] = []; + const included: TIncluded[] = []; - let response = await this.get(path, params); - if (Array.isArray(response.data)) { - allData.push(...response.data); - } else { - return [response.data]; + let response = await this.get(path, params); + if (!Array.isArray(response.data)) { + return { data: [response.data], included: response.included ?? [], hasMore: false }; } - while (response.links?.next && (!maxItems || allData.length < maxItems)) { - response = await this.request(this.resolveNextPageUrl(response.links.next)); + while (true) { + included.push(...(response.included ?? [])); if (Array.isArray(response.data)) { allData.push(...response.data); } - } - if (maxItems && allData.length > maxItems) { - return allData.slice(0, maxItems); - } + const next = response.links?.next; + if (!next || (maxItems && allData.length >= maxItems)) { + return { + data: maxItems ? allData.slice(0, maxItems) : allData, + included, + hasMore: Boolean(next || (maxItems && allData.length > maxItems)), + }; + } - return allData; + response = await this.request(this.resolveNextPageUrl(next)); + } } /** diff --git a/src/api/resources/builds.ts b/src/api/resources/builds.ts index 1da654f..ae6ba08 100644 --- a/src/api/resources/builds.ts +++ b/src/api/resources/builds.ts @@ -1,11 +1,24 @@ import { BaseAPIClient } from '../base-client.js'; import type { + AppStoreBuild, CiBuildAction, CiBuildRun, CiBuildRunCreateRequest, CiBuildRunStartOptions, + CiWorkflow, + PrereleaseVersion, + ScmGitReference, } from '../types.js'; +type BuildIncludedResource = PrereleaseVersion | { type: 'apps'; id: string }; + +const testFlightBuildFields = { + include: 'app,preReleaseVersion', + 'fields[apps]': 'bundleId', + 'fields[builds]': 'version,expired,processingState,buildAudienceType,app,preReleaseVersion', + 'fields[preReleaseVersions]': 'platform,version', +}; + /** * Build run endpoints. */ @@ -80,6 +93,46 @@ export class BuildsClient extends BaseAPIClient { return response.data; } + /** Read the workflow and source linkage alongside the exact build run. */ + async getWithProvenance(buildRunId: string) { + return this.get( + `/v1/ciBuildRuns/${encodeURIComponent(buildRunId)}`, + { include: 'workflow,sourceBranchOrTag' }, + ); + } + + async getGitReference(referenceId: string): Promise { + const response = await this.get( + `/v1/scmGitReferences/${encodeURIComponent(referenceId)}`, + ); + return response.data; + } + + /** Scan a bounded number of runs with their source references. */ + async listWithProvenance(workflowId: string, scanLimit: number) { + return this.listAllWithIncluded( + `/v1/ciWorkflows/${encodeURIComponent(workflowId)}/buildRuns`, + { include: 'sourceBranchOrTag', sort: '-number', limit: String(Math.min(scanLimit, 200)) }, + scanLimit, + ); + } + + /** Read only the App Store Connect builds explicitly linked to this run. */ + async listLinkedBuilds(buildRunId: string) { + return this.listAllWithIncluded( + `/v1/ciBuildRuns/${encodeURIComponent(buildRunId)}/builds`, + { ...testFlightBuildFields, limit: '200' }, + ); + } + + /** Hydrate an exact linked build when the run endpoint omits build evidence. */ + async getLinkedBuildDetails(buildId: string) { + return this.get( + `/v1/builds/${encodeURIComponent(buildId)}`, + testFlightBuildFields, + ); + } + /** * List build runs for a workflow, paginating through all results. * Optionally limit the total number of build runs returned. diff --git a/src/api/types.ts b/src/api/types.ts index df5e969..0e3e6e5 100644 --- a/src/api/types.ts +++ b/src/api/types.ts @@ -171,21 +171,19 @@ export interface CiBuildRun { startedDate?: string; finishedDate?: string; executionProgress: 'PENDING' | 'RUNNING' | 'COMPLETE'; - completionStatus?: 'SUCCEEDED' | 'FAILED' | 'ERRORED' | 'CANCELED'; + completionStatus?: 'SUCCEEDED' | 'FAILED' | 'ERRORED' | 'CANCELED' | 'SKIPPED' | null; isPullRequestBuild: boolean; issueCounts?: CiIssueCounts; + startReason?: 'GIT_REF_CHANGE' | 'MANUAL' | 'MANUAL_REBUILD' | 'PULL_REQUEST_OPEN' | 'PULL_REQUEST_UPDATE' | 'SCHEDULE'; sourceCommit?: { commitSha: string; message?: string; }; }; relationships?: { - workflow?: { - data: { - type: 'ciWorkflows'; - id: string; - }; - }; + workflow?: ToOneRelationship<'ciWorkflows'>; + sourceBranchOrTag?: ToOneRelationship<'scmGitReferences'>; + pullRequest?: ToOneRelationship<'scmPullRequests'>; }; } @@ -194,6 +192,40 @@ interface ResourceIdentifier { id: string; } +interface ToOneRelationship { + data?: ResourceIdentifier | null; +} + +export interface ScmGitReference extends ResourceIdentifier<'scmGitReferences'> { + attributes?: { + canonicalName?: string; + kind?: 'BRANCH' | 'TAG'; + }; +} + +export const buildPlatforms = ['IOS', 'MAC_OS', 'TV_OS', 'VISION_OS'] as const; +export type BuildPlatform = (typeof buildPlatforms)[number]; + +export interface PrereleaseVersion extends ResourceIdentifier<'preReleaseVersions'> { + attributes?: { + platform?: BuildPlatform; + version?: string; + }; +} + +export interface AppStoreBuild extends ResourceIdentifier<'builds'> { + attributes?: { + version?: string | null; + expired?: boolean | null; + processingState?: 'PROCESSING' | 'FAILED' | 'INVALID' | 'VALID' | null; + buildAudienceType?: BuildAudienceType | null; + }; + relationships?: { + app?: ToOneRelationship<'apps'>; + preReleaseVersion?: ToOneRelationship<'preReleaseVersions'>; + }; +} + /** * Options for creating one Xcode Cloud build run. */ diff --git a/src/index.ts b/src/index.ts index 0005505..2bcbd7a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -23,7 +23,7 @@ export function createServer(): McpServer { const server = new McpServer({ name: 'Xcode Cloud MCP', - version: '0.7.0', + version: '0.8.0', }); registerDiscoveryTools(server, client); diff --git a/src/tools/build-runs.ts b/src/tools/build-runs.ts index b1ae670..d92904b 100644 --- a/src/tools/build-runs.ts +++ b/src/tools/build-runs.ts @@ -2,19 +2,28 @@ import { z } from 'zod'; import type { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'; import type { AppStoreConnectClient } from '../api/client.js'; import type { CiBuildRun } from '../api/types.js'; +import { buildPlatforms } from '../api/types.js'; import { parseIdentifier } from '../utils/identifiers.js'; import { isFailureStatus, sortBuildRuns, } from '../utils/build-locator.js'; import { errorResponse, jsonResponse } from '../utils/tool-response.js'; +import { + buildRunProvenance, + fullCommitSha, + getBuildRunTestFlightBuilds, + testFlightBuildLookupOutput, +} from '../utils/testflight-builds.js'; type BuildRunStatusFilter = 'all' | 'failed' | 'pending' | 'running' | 'succeeded'; const identifierSchema = z.string().trim().min(1); +const commitShaSchema = z.string().trim().regex(fullCommitSha, 'Provide a full Git commit SHA.'); +const readOnlyAnnotations = { readOnlyHint: true, idempotentHint: true, openWorldHint: true }; /** - * Register build run listing tools. + * Register build run tools. */ export function registerBuildRunTools( server: McpServer, @@ -89,7 +98,7 @@ export function registerBuildRunTools( buildRun: { id: buildRun.id, workflowId: - buildRun.relationships?.workflow?.data.id ?? parsedWorkflowId, + buildRun.relationships?.workflow?.data?.id ?? parsedWorkflowId, number: buildRun.attributes.number, executionProgress: buildRun.attributes.executionProgress, completionStatus: buildRun.attributes.completionStatus, @@ -110,47 +119,84 @@ export function registerBuildRunTools( 'list_build_runs', { description: - 'List recent build runs for a workflow, optionally filtered by outcome. Automatically paginates through build runs. Use limit to cap the number of results returned.', + 'Scan recent build runs for a workflow with source provenance. Optionally filter by outcome and full source commit SHA. The scan reports whether additional runs remain beyond the limit.', inputSchema: { workflowId: z.string(), status: z.enum(['all', 'failed', 'pending', 'running', 'succeeded']).optional(), - limit: z.number().int().min(1).max(500).optional().describe('Maximum number of build runs to return. Defaults to 20 if not specified.'), + limit: z.number().int().min(1).max(500).optional().describe('Maximum number of runs scanned before filtering. Defaults to 20.'), + sourceCommitSha: commitShaSchema.optional(), }, + annotations: readOnlyAnnotations, }, - async ({ - workflowId, - status, - limit, - }: { - workflowId: string; - status?: BuildRunStatusFilter; - limit?: number; - }) => { + async ({ workflowId, status, limit, sourceCommitSha }) => { try { - const buildRuns = sortBuildRuns( - await client.builds.listForWorkflow( - parseIdentifier(workflowId, 'workflow'), - limit ?? 20, - ), - ); + const parsedWorkflowId = parseIdentifier(workflowId, 'workflow'); + const { data, included, hasMore } = await client.builds.listWithProvenance(parsedWorkflowId, limit ?? 20); + const provenance = new Map(data.map((run) => [run.id, buildRunProvenance(run, included)])); + const expectedSha = sourceCommitSha?.toLowerCase(); + const buildRuns = filterBuildRuns(sortBuildRuns(data), status ?? 'all') + .filter((run) => !expectedSha || provenance.get(run.id)?.sourceCommitSha?.toLowerCase() === expectedSha); return jsonResponse({ - buildRuns: filterBuildRuns(buildRuns, status ?? 'all').map( - (buildRun) => ({ - id: buildRun.id, - workflowId: - buildRun.relationships?.workflow?.data.id ?? - parseIdentifier(workflowId, 'workflow'), - number: buildRun.attributes.number, - executionProgress: buildRun.attributes.executionProgress, - completionStatus: buildRun.attributes.completionStatus, - createdDate: buildRun.attributes.createdDate, - startedDate: buildRun.attributes.startedDate, - finishedDate: buildRun.attributes.finishedDate, - issueCounts: buildRun.attributes.issueCounts, - }), - ), + buildRuns: buildRuns.map((buildRun) => ({ + id: buildRun.id, + workflowId: buildRun.relationships?.workflow?.data?.id ?? parsedWorkflowId, + number: buildRun.attributes.number, + executionProgress: buildRun.attributes.executionProgress, + completionStatus: buildRun.attributes.completionStatus, + createdDate: buildRun.attributes.createdDate, + startedDate: buildRun.attributes.startedDate, + finishedDate: buildRun.attributes.finishedDate, + issueCounts: buildRun.attributes.issueCounts, + ...provenance.get(buildRun.id), + })), + scan: { + scannedCount: data.length, + hasMore, + unverifiedSourceCount: data.filter((run) => !provenance.get(run.id)?.sourceCommitSha).length, + }, + }); + } catch (error) { + return errorResponse(error); + } + }, + ); + + server.registerTool( + 'get_build_run_testflight_builds', + { + title: 'Resolve TestFlight Builds from an Xcode Cloud Run', + description: + 'Verify an exact run, workflow and App Store Connect app, then look up the externally eligible builds linked to the run. For automatic handoff, supply both the expected canonical branch ref and full source commit SHA. Use build IDs only when the overall status is ready.', + inputSchema: z.strictObject({ + buildRunId: identifierSchema.describe('Exact run ID or xcode-cloud://build-run URI.'), + workflowId: identifierSchema.describe('Expected workflow ID or xcode-cloud://workflow URI.'), + appId: identifierSchema.describe('Expected App Store Connect app resource ID.'), + platforms: z.array(z.enum(buildPlatforms)).min(1).max(buildPlatforms.length) + .refine((platforms) => new Set(platforms).size === platforms.length, 'Requested platforms must be distinct.'), + expectedSourceRef: z.string().trim().regex(/^refs\/heads\/.+$/).optional(), + expectedSourceCommitSha: commitShaSchema.optional(), + }).refine( + ({ expectedSourceRef, expectedSourceCommitSha }) => + (expectedSourceRef === undefined) === (expectedSourceCommitSha === undefined), + 'Provide both expectedSourceRef and expectedSourceCommitSha for branch verification.', + ), + outputSchema: testFlightBuildLookupOutput, + annotations: readOnlyAnnotations, + }, + async (input) => { + try { + const buildRunId = parseIdentifier(input.buildRunId, 'build-run'); + const workflowId = parseIdentifier(input.workflowId, 'workflow'); + if ([buildRunId, workflowId].some((id) => !id.trim() || id === '.' || id === '..')) { + throw new Error('Provide exact build run and workflow resource IDs.'); + } + const result = await getBuildRunTestFlightBuilds(client.builds, { + ...input, + buildRunId, + workflowId, }); + return { ...jsonResponse(result), structuredContent: result }; } catch (error) { return errorResponse(error); } diff --git a/src/tools/results.ts b/src/tools/results.ts index 8d3b5a5..0b57220 100644 --- a/src/tools/results.ts +++ b/src/tools/results.ts @@ -176,7 +176,7 @@ function defaultIssueCounts() { function formatBuildRun(buildRun: Awaited>) { return { id: buildRun.id, - workflowId: buildRun.relationships?.workflow?.data.id, + workflowId: buildRun.relationships?.workflow?.data?.id, number: buildRun.attributes.number, executionProgress: buildRun.attributes.executionProgress, completionStatus: buildRun.attributes.completionStatus, diff --git a/src/tools/tests.ts b/src/tools/tests.ts index 5b942f4..d61fff7 100644 --- a/src/tools/tests.ts +++ b/src/tools/tests.ts @@ -49,7 +49,7 @@ export function registerTestTools( buildRun: { id: buildRun.id, number: buildRun.attributes.number, - workflowId: buildRun.relationships?.workflow?.data.id, + workflowId: buildRun.relationships?.workflow?.data?.id, completionStatus: buildRun.attributes.completionStatus, }, issueCounts: buildRun.attributes.issueCounts ?? { @@ -97,7 +97,7 @@ export function registerTestTools( buildRun: { id: buildRun.id, number: buildRun.attributes.number, - workflowId: buildRun.relationships?.workflow?.data.id, + workflowId: buildRun.relationships?.workflow?.data?.id, completionStatus: buildRun.attributes.completionStatus, }, savedLogsDirectory: storedLogs.directoryPath, @@ -126,7 +126,7 @@ export function registerTestTools( buildRun: { id: buildRun.id, number: buildRun.attributes.number, - workflowId: buildRun.relationships?.workflow?.data.id, + workflowId: buildRun.relationships?.workflow?.data?.id, }, screenshots: groupedArtifacts.screenshots.map(formatArtifact), videos: groupedArtifacts.videos.map(formatArtifact), diff --git a/src/utils/testflight-builds.ts b/src/utils/testflight-builds.ts new file mode 100644 index 0000000..4c9bd33 --- /dev/null +++ b/src/utils/testflight-builds.ts @@ -0,0 +1,299 @@ +import { z } from 'zod'; +import type { BuildsClient } from '../api/resources/builds.js'; +import { buildPlatforms } from '../api/types.js'; +import type { + AppStoreBuild, + BuildPlatform, + CiBuildRun, + PrereleaseVersion, + ScmGitReference, +} from '../api/types.js'; + +export const fullCommitSha = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i; + +export function sourceRefId(run: CiBuildRun): string | null { + const reference = run.relationships?.sourceBranchOrTag?.data; + return reference?.type === 'scmGitReferences' && reference.id ? reference.id : null; +} + +export function buildRunProvenance( + run: CiBuildRun, + included: ReadonlyArray<{ type: string; id: string } | ScmGitReference>, +) { + const referenceId = sourceRefId(run); + const reference = included.find( + (resource): resource is ScmGitReference => + resource.type === 'scmGitReferences' && resource.id === referenceId, + ); + const { canonicalName, kind } = reference?.attributes ?? {}; + const prefix = kind === 'BRANCH' ? 'refs/heads/' : kind === 'TAG' ? 'refs/tags/' : null; + const sourceRef = prefix && canonicalName?.startsWith(prefix) && canonicalName.length > prefix.length + ? canonicalName + : null; + const sha = run.attributes?.sourceCommit?.commitSha; + + return { + sourceCommitSha: sha && fullCommitSha.test(sha) ? sha : null, + sourceRef, + sourceRefId: referenceId, + sourceRefKind: sourceRef ? kind ?? null : null, + isPullRequestBuild: run.attributes?.isPullRequestBuild ?? null, + startReason: run.attributes?.startReason ?? null, + }; +} + +interface LookupOptions { + buildRunId: string; + workflowId: string; + appId: string; + platforms: BuildPlatform[]; + expectedSourceRef?: string; + expectedSourceCommitSha?: string; +} + +const handoffStatus = z.enum(['ready', 'pending', 'blocked']); +const platformSchema = z.enum(buildPlatforms); + +export const testFlightBuildLookupOutput = z.object({ + status: handoffStatus, + buildRun: z.object({ + id: z.string(), + workflowId: z.string(), + executionProgress: z.string().nullable(), + completionStatus: z.string().nullable(), + sourceCommitSha: z.string().nullable(), + sourceRef: z.string().nullable(), + sourceRefId: z.string().nullable(), + sourceRefKind: z.enum(['BRANCH', 'TAG']).nullable(), + isPullRequestBuild: z.boolean().nullable(), + startReason: z.string().nullable(), + }), + appId: z.string(), + platforms: z.array(z.object({ + platform: platformSchema, + status: handoffStatus, + reasons: z.array(z.string()), + build: z.object({ + id: z.string(), + platform: platformSchema, + marketingVersion: z.string(), + buildNumber: z.string(), + processingState: z.literal('VALID'), + buildAudienceType: z.literal('APP_STORE_ELIGIBLE'), + expired: z.literal(false), + }).optional(), + })), +}); + +type TestFlightBuildLookup = z.infer; +type PlatformResult = TestFlightBuildLookup['platforms'][number]; +type BuildEvidence = NonNullable; + +type RunState = + | { status: 'ready' } + | { status: 'pending' | 'blocked'; reason: string }; + +type LinkedBuild = + | { status: 'eligible'; platform: BuildPlatform; build: BuildEvidence } + | { + status: 'pending' | 'unverified' | 'ineligible'; + platform?: BuildPlatform; + reason: string; + }; + +/** Resolve a TestFlight handoff using the run's own App Store Connect relationships. */ +export async function getBuildRunTestFlightBuilds( + client: BuildsClient, + options: LookupOptions, +): Promise { + const { buildRunId, workflowId, appId, platforms, expectedSourceRef, expectedSourceCommitSha } = options; + const { data: run, included = [] } = await client.getWithProvenance(buildRunId); + if (run.type !== 'ciBuildRuns' || run.id !== buildRunId) { + throw new Error('App Store Connect returned a different build run than requested.'); + } + const workflow = run.relationships?.workflow?.data; + if (workflow?.type !== 'ciWorkflows' || workflow.id !== workflowId) { + throw new Error('The build run does not link to the expected workflow.'); + } + + let provenance = buildRunProvenance(run, included); + if (expectedSourceRef !== undefined) { + const startReason = provenance.startReason; + const pullRequest = run.relationships?.pullRequest?.data; + if (provenance.isPullRequestBuild !== false || pullRequest || + startReason === 'PULL_REQUEST_OPEN' || startReason === 'PULL_REQUEST_UPDATE') { + throw new Error('Branch provenance requires a verified non-pull-request run.'); + } + if (provenance.sourceCommitSha?.toLowerCase() !== expectedSourceCommitSha?.toLowerCase() || + !provenance.sourceCommitSha) { + throw new Error('The build run does not have the expected source commit SHA.'); + } + } + if (!provenance.sourceRef && provenance.sourceRefId) { + const reference = await client.getGitReference(provenance.sourceRefId); + provenance = buildRunProvenance(run, [reference]); + } + if (expectedSourceRef !== undefined && + (provenance.sourceRefKind !== 'BRANCH' || provenance.sourceRef !== expectedSourceRef)) { + throw new Error('The build run does not have the expected canonical source branch.'); + } + + const executionProgress = run.attributes?.executionProgress ?? null; + const completionStatus = run.attributes?.completionStatus ?? null; + const runState = getRunState(executionProgress, completionStatus); + let results: PlatformResult[]; + if (runState.status === 'ready') { + const builds = await readLinkedBuilds(client, buildRunId, appId); + results = platforms.map((platform) => assessPlatform(platform, builds)); + } else { + const { status, reason } = runState; + results = platforms.map((platform) => ({ platform, status, reasons: [reason] })); + } + + const status = results.some((result) => result.status === 'blocked') ? 'blocked' + : results.some((result) => result.status === 'pending') ? 'pending' + : 'ready'; + return { + status, + buildRun: { id: buildRunId, workflowId, executionProgress, completionStatus, ...provenance }, + appId, + platforms: results, + }; +} + +async function readLinkedBuilds(client: BuildsClient, buildRunId: string, appId: string) { + const linked = await client.listLinkedBuilds(buildRunId); + const versions = prereleaseVersions(linked.included); + const fallbacks = new Map(); + const results: LinkedBuild[] = []; + for (const build of linked.data) { + let result = assessLinkedBuild(build, appId, versions); + if (result.status === 'unverified' && build.type === 'builds' && build.id) { + const existing = fallbacks.get(build.id); + if (existing) { + result = existing; + } else { + const detail = await client.getLinkedBuildDetails(build.id); + if (detail.data.type !== 'builds' || detail.data.id !== build.id) { + throw new Error('App Store Connect returned a different build than the run linked.'); + } + result = assessLinkedBuild(detail.data, appId, prereleaseVersions(detail.included ?? [])); + fallbacks.set(build.id, result); + } + } + results.push(result); + } + return results; +} + +function prereleaseVersions(included: ReadonlyArray<{ type: string; id: string }>) { + const versions = included.filter( + (resource): resource is PrereleaseVersion => resource.type === 'preReleaseVersions', + ); + return new Map(versions.map((version) => [version.id, version])); +} + +function getRunState( + progress: CiBuildRun['attributes']['executionProgress'] | null, + completion: CiBuildRun['attributes']['completionStatus'], +): RunState { + switch (completion) { + case 'FAILED': + case 'ERRORED': + return { status: 'blocked', reason: 'run_failed' }; + case 'CANCELED': + return { status: 'blocked', reason: 'run_canceled' }; + case 'SKIPPED': + return { status: 'blocked', reason: 'run_skipped' }; + case 'SUCCEEDED': + if (progress === 'COMPLETE') return { status: 'ready' }; + break; + case undefined: + case null: + if (progress === 'PENDING' || progress === 'RUNNING') { + return { status: 'pending', reason: 'run_in_progress' }; + } + } + return { status: 'blocked', reason: 'unknown_run_state' }; +} + +function assessLinkedBuild( + build: AppStoreBuild, + appId: string, + versions: ReadonlyMap, +): LinkedBuild { + if (build.type !== 'builds' || !build.id) { + return { status: 'unverified', reason: 'unverified_build' }; + } + const release = build.relationships?.preReleaseVersion?.data; + const version = release?.type === 'preReleaseVersions' ? versions.get(release.id)?.attributes : undefined; + const platform = version?.platform && buildPlatforms.includes(version.platform) + ? version.platform + : undefined; + const app = build.relationships?.app?.data; + if (app?.type !== 'apps' || !app.id) { + return { status: 'unverified', platform, reason: 'unverified_app' }; + } + if (app.id !== appId) { + return { status: 'ineligible', platform, reason: 'wrong_app' }; + } + if (!platform || !version?.version) { + return { status: 'unverified', platform, reason: 'unverified_prerelease_version' }; + } + + const { version: buildNumber, expired, processingState, buildAudienceType } = build.attributes ?? {}; + if (expired === true) return { status: 'ineligible', platform, reason: 'expired' }; + if (buildAudienceType === 'INTERNAL_ONLY') { + return { status: 'ineligible', platform, reason: 'internal_only' }; + } + if (processingState === 'PROCESSING') { + return { status: 'pending', platform, reason: 'build_processing' }; + } + if (processingState === 'FAILED' || processingState === 'INVALID') { + return { status: 'ineligible', platform, reason: 'build_processing_failed' }; + } + if (processingState !== 'VALID' || buildAudienceType !== 'APP_STORE_ELIGIBLE' || + expired !== false || !buildNumber) { + return { status: 'unverified', platform, reason: 'unknown_build_state' }; + } + return { + status: 'eligible', + platform, + build: { + id: build.id, + platform, + marketingVersion: version.version, + buildNumber, + processingState, + buildAudienceType, + expired, + }, + }; +} + +function assessPlatform(platform: BuildPlatform, builds: LinkedBuild[]): PlatformResult { + const eligible = new Map(); + const reasons = new Set(); + let pending = false; + let unverified = false; + for (const build of builds) { + if (build.platform !== undefined && build.platform !== platform) continue; + if (build.status === 'eligible') { + eligible.set(build.build.id, build.build); + } else { + reasons.add(build.reason); + pending ||= build.status === 'pending'; + unverified ||= build.status === 'unverified'; + } + } + + if (eligible.size > 1) reasons.add('ambiguous_builds'); + if (eligible.size > 1 || unverified) { + return { platform, status: 'blocked', reasons: [...reasons] }; + } + if (pending) return { platform, status: 'pending', reasons: [...reasons] }; + const build = eligible.values().next().value; + if (build) return { platform, status: 'ready', reasons: [...reasons], build }; + if (reasons.size) return { platform, status: 'blocked', reasons: [...reasons] }; + return { platform, status: 'pending', reasons: ['build_not_linked'] }; +} diff --git a/tests/smoke.test.ts b/tests/smoke.test.ts index 304ddb2..adf8635 100644 --- a/tests/smoke.test.ts +++ b/tests/smoke.test.ts @@ -36,6 +36,7 @@ test('server starts over stdio and exposes the expected tools', async () => { 'configure_manual_release_candidate', 'get_build_issues', 'get_build_logs', + 'get_build_run_testflight_builds', 'get_failed_tests', 'get_test_artifacts', 'get_test_results', @@ -72,5 +73,30 @@ test('server starts over stdio and exposes the expected tools', async () => { }); assert.equal(unexpectedStartInput.isError, true); + const lookupTool = tools.tools.find((tool) => tool.name === 'get_build_run_testflight_builds'); + assert.equal(lookupTool?.annotations?.readOnlyHint, true); + assert.equal(lookupTool?.outputSchema?.type, 'object'); + const lookupArguments = { + buildRunId: 'run-1', + workflowId: 'workflow-1', + appId: 'app-1', + platforms: ['IOS', 'TV_OS'], + }; + for (const invalidArguments of [ + { ...lookupArguments, expectedSourceRef: 'refs/heads/main' }, + { ...lookupArguments, expectedSourceCommitSha: 'deadbeef' }, + { ...lookupArguments, expectedSourceCommitSha: 'a'.repeat(40) }, + { ...lookupArguments, platforms: ['IOS', 'IOS'] }, + { ...lookupArguments, platforms: ['TVOS'] }, + { ...lookupArguments, platforms: [] }, + ]) { + const invalidLookup = await client.callTool({ + name: 'get_build_run_testflight_builds', + arguments: invalidArguments, + }); + assert.equal(invalidLookup.isError, true); + assert.match(JSON.stringify(invalidLookup.content), /Input validation error/); + } + await client.close(); }); diff --git a/tests/testflight-builds.test.ts b/tests/testflight-builds.test.ts new file mode 100644 index 0000000..19bf0e1 --- /dev/null +++ b/tests/testflight-builds.test.ts @@ -0,0 +1,336 @@ +import test, { type TestContext } from 'node:test'; +import assert from 'node:assert/strict'; +import type { AuthManager } from '../src/api/auth.js'; +import { AppStoreConnectClient } from '../src/api/client.js'; +import { registerBuildRunTools } from '../src/tools/build-runs.js'; + +const origin = 'https://api.appstoreconnect.apple.com'; +const workflowPath = '/v1/ciWorkflows/workflow-1/buildRuns'; +const runPath = '/v1/ciBuildRuns/run-1'; +const buildsPath = runPath + '/builds'; +const referencePath = '/v1/scmGitReferences/reference-1'; +const sha = 'a'.repeat(40); +const ref = 'refs/heads/release'; +const request = { + buildRunId: 'xcode-cloud://build-run/run-1', + workflowId: 'xcode-cloud://workflow/workflow-1', + appId: 'app-1', + platforms: ['IOS', 'TV_OS'], + expectedSourceRef: ref, + expectedSourceCommitSha: sha.toUpperCase(), +}; + +function buildRun() { + return { + type: 'ciBuildRuns', + id: 'run-1', + attributes: { + number: 73, + executionProgress: 'COMPLETE', + completionStatus: 'SUCCEEDED', + isPullRequestBuild: false, + startReason: 'GIT_REF_CHANGE', + sourceCommit: { commitSha: sha, message: 'Private commit message', webUrl: 'https://private.example' }, + }, + relationships: { + workflow: { data: { type: 'ciWorkflows', id: 'workflow-1' } }, + sourceBranchOrTag: { data: { type: 'scmGitReferences', id: 'reference-1' } }, + }, + }; +} + +const reference = { + type: 'scmGitReferences', + id: 'reference-1', + attributes: { canonicalName: ref, kind: 'BRANCH' }, +}; + +function prerelease(platform: string, id = platform) { + return { type: 'preReleaseVersions', id, attributes: { platform, version: '2.1' } }; +} + +function build(id: string, platform: string, attributes: Record = {}, appId = 'app-1') { + return { + type: 'builds', + id, + attributes: { version: '44', processingState: 'VALID', buildAudienceType: 'APP_STORE_ELIGIBLE', expired: false, ...attributes }, + relationships: { + app: { data: { type: 'apps', id: appId } }, + preReleaseVersion: { data: { type: 'preReleaseVersions', id: platform } }, + }, + }; +} + +test('resolves exact iOS and tvOS builds across Apple pages, safely repeating reads', async (t) => { + const { lookup, calls } = toolsFixture(t, (url) => { + if (url.pathname === runPath) return { data: buildRun(), included: [reference] }; + assert.equal(url.pathname, buildsPath); + if (url.searchParams.get('cursor')) { + return { + data: [build('tv-build', 'TV_OS'), build('ios-build', 'IOS')], + included: [prerelease('TV_OS')], + }; + } + return { + data: [build('ios-build', 'IOS')], + included: [{ type: 'apps', id: 'IOS', attributes: { version: 'wrong-type' } }, prerelease('IOS')], + links: { next: origin + buildsPath + '?cursor=2' }, + }; + }); + const result = await lookup(request); + assert.deepEqual(await lookup(request), result); + assert.equal(result.status, 'ready'); + assert.deepEqual(result.buildRun, { + id: 'run-1', workflowId: 'workflow-1', + executionProgress: 'COMPLETE', completionStatus: 'SUCCEEDED', + sourceCommitSha: sha, sourceRef: ref, sourceRefId: 'reference-1', + sourceRefKind: 'BRANCH', isPullRequestBuild: false, startReason: 'GIT_REF_CHANGE', + }); + assert.deepEqual(result.platforms, [ + { platform: 'IOS', status: 'ready', reasons: [], build: expectedBuild('ios-build', 'IOS') }, + { platform: 'TV_OS', status: 'ready', reasons: [], build: expectedBuild('tv-build', 'TV_OS') }, + ]); + assert.doesNotMatch(JSON.stringify(result), /Private commit message|private\.example/); + assert.deepEqual(calls.map((url) => url.pathname), [ + runPath, buildsPath, buildsPath, runPath, buildsPath, buildsPath, + ]); + assert.equal(calls[0]?.searchParams.get('include'), 'workflow,sourceBranchOrTag'); + assert.equal(calls[1]?.searchParams.get('include'), 'app,preReleaseVersion'); +}); + +test('reads the exact linked ref when its included attributes are unavailable', async (t) => { + const { lookup, calls } = toolsFixture(t, (url) => { + if (url.pathname === runPath) { + return { + data: buildRun(), + included: [ + { type: 'scmGitReferences', id: 'reference-1' }, + { ...reference, id: 'unrelated-reference' }, + ], + }; + } + if (url.pathname === referencePath) return { data: reference }; + assert.equal(url.pathname, buildsPath); + return { data: [], included: [] }; + }); + const result = await lookup(request); + assert.equal(result.buildRun.sourceRef, ref); + assert.equal(result.status, 'pending'); + assert.deepEqual(result.platforms.map((item: { reasons: string[] }) => item.reasons), [ + ['build_not_linked'], ['build_not_linked'], + ]); + assert.deepEqual(calls.map((url) => url.pathname), [runPath, referencePath, buildsPath]); +}); + +test('hydrates sparse linked builds by ID when Apple omits app and platform evidence', async (t) => { + const { lookup, calls } = toolsFixture(t, (url) => { + switch (url.pathname) { + case runPath: + return { data: buildRun(), included: [reference] }; + case buildsPath: + return { + data: ['ios-build', 'tv-build'].map((id) => ({ + type: 'builds', id, + attributes: { version: null, processingState: null, buildAudienceType: null, expired: null }, + relationships: { app: { data: null }, preReleaseVersion: { data: null } }, + })), + included: [], + }; + case '/v1/builds/ios-build': + return { data: build('ios-build', 'IOS'), included: [prerelease('IOS')] }; + case '/v1/builds/tv-build': + return { data: build('tv-build', 'TV_OS'), included: [prerelease('TV_OS')] }; + default: + assert.fail(`Unexpected read of ${url.pathname}`); + } + }); + const result = await lookup(request); + assert.equal(result.status, 'ready'); + assert.deepEqual(result.platforms.map((item: { build: unknown }) => item.build), [ + expectedBuild('ios-build', 'IOS'), expectedBuild('tv-build', 'TV_OS'), + ]); + assert.deepEqual(calls.map((url) => url.pathname), [ + runPath, buildsPath, '/v1/builds/ios-build', '/v1/builds/tv-build', + ]); +}); + +test('rejects fallback details for a build ID outside the run', async (t) => { + const { invoke } = toolsFixture(t, (url) => { + if (url.pathname === runPath) return { data: buildRun(), included: [reference] }; + if (url.pathname === buildsPath) { + return { data: [{ type: 'builds', id: 'linked-build' }] }; + } + assert.equal(url.pathname, '/v1/builds/linked-build'); + return { data: build('other-build', 'IOS'), included: [prerelease('IOS')] }; + }); + const result = await invoke('get_build_run_testflight_builds', request); + assert.equal(result.isError, true); + assert.match(result.content[0]!.text, /different build than the run linked/); +}); + +test('rejects a different run, workflow, SHA, branch, ref kind or PR before fetching builds', async (t) => { + const wrongRun = { ...buildRun(), id: 'run-2' }; + const wrongWorkflow = buildRun(); + wrongWorkflow.relationships.workflow.data.id = 'workflow-2'; + const wrongSha = buildRun(); + wrongSha.attributes.sourceCommit.commitSha = 'b'.repeat(40); + const isPullRequest = buildRun(); + isPullRequest.attributes.isPullRequestBuild = true; + const cases = [ + { run: wrongRun, error: /different build run/ }, + { run: wrongWorkflow, error: /expected workflow/ }, + { run: wrongSha, error: /expected source commit SHA/ }, + { included: { ...reference, attributes: { canonicalName: 'refs/heads/main', kind: 'BRANCH' } }, error: /expected canonical source branch/ }, + { included: { ...reference, attributes: { canonicalName: 'refs/tags/release', kind: 'TAG' } }, error: /expected canonical source branch/ }, + { run: isPullRequest, error: /non-pull-request run/ }, + ]; + for (const { run, included, error } of cases) { + await t.test(error.source, async (t) => { + const { invoke, calls } = toolsFixture(t, (url) => { + assert.equal(url.pathname, runPath); + return { data: run ?? buildRun(), included: [included ?? reference] }; + }); + const result = await invoke('get_build_run_testflight_builds', request); + assert.equal(result.isError, true); + assert.match(result.content[0]!.text, error); + assert.equal(calls.length, 1); + }); + } +}); + +test('distinguishes running or failed runs from a completed upload', async (t) => { + const cases = [ + ['RUNNING', null, 'pending', 'run_in_progress'], + ['COMPLETE', 'FAILED', 'blocked', 'run_failed'], + ['COMPLETE', 'CANCELED', 'blocked', 'run_canceled'], + ['COMPLETE', 'UNRECOGNIZED', 'blocked', 'unknown_run_state'], + ] as const; + for (const [executionProgress, completionStatus, status, reason] of cases) { + await t.test(reason, async (t) => { + const run = buildRun(); + const { lookup, calls } = toolsFixture(t, (url) => { + assert.equal(url.pathname, runPath); + return { data: { ...run, attributes: { ...run.attributes, executionProgress, completionStatus } }, included: [reference] }; + }); + const result = await lookup(request); + assert.equal(result.status, status); + assert.deepEqual(result.platforms, request.platforms.map((platform) => ({ platform, status, reasons: [reason] }))); + assert.equal(calls.length, 1); + }); + } +}); + +test('classifies delayed upload, ineligible builds, missing evidence and ambiguity without exposing their IDs', async (t) => { + const ios = build('ios-build', 'IOS'); + const tv = build('tv-build', 'TV_OS'); + const cases = [ + { builds: [ios], status: 'pending', reason: 'build_not_linked' }, + { builds: [ios, build(tv.id, 'TV_OS', { processingState: 'PROCESSING', buildAudienceType: undefined })], status: 'pending', reason: 'build_processing' }, + { builds: [ios, build(tv.id, 'TV_OS', { buildAudienceType: 'INTERNAL_ONLY' })], status: 'blocked', reason: 'internal_only' }, + { builds: [ios, build(tv.id, 'TV_OS', { expired: true })], status: 'blocked', reason: 'expired' }, + { builds: [ios, build(tv.id, 'TV_OS', { processingState: 'UNRECOGNIZED' })], status: 'blocked', reason: 'unknown_build_state' }, + { builds: [ios, build(tv.id, 'TV_OS', { buildAudienceType: undefined })], status: 'blocked', reason: 'unknown_build_state' }, + { builds: [ios, build(tv.id, 'TV_OS', {}, 'different-app')], status: 'blocked', reason: 'wrong_app' }, + { builds: [ios, build(tv.id, 'bad-version-id')], status: 'blocked', reason: 'unverified_prerelease_version' }, + { builds: [ios, tv, build('other-tv-build', 'TV_OS')], status: 'blocked', reason: 'ambiguous_builds' }, + ]; + for (const { builds, status, reason } of cases) { + await t.test(reason, async (t) => { + const included = [prerelease('IOS'), prerelease('TV_OS')]; + const { lookup } = toolsFixture(t, (url) => { + if (url.pathname === runPath) return { data: buildRun(), included: [reference] }; + if (url.pathname === buildsPath) return { data: builds, included }; + assert.equal(url.pathname, '/v1/builds/tv-build'); + return { data: builds.find((build) => build.id === 'tv-build'), included }; + }); + const result = await lookup(request); + assert.equal(result.status, status); + assert.deepEqual(result.platforms[1], { platform: 'TV_OS', status, reasons: [reason] }); + assert.doesNotMatch(JSON.stringify(result), /tv-build/); + }); + } +}); + +test('SHA scans distinguish more pages, unverified source commits and an exhaustive no-match', async (t) => { + const matchingRun = buildRun(); + const unverifiedRun = buildRun(); + unverifiedRun.id = 'unverified'; + unverifiedRun.attributes.sourceCommit.commitSha = 'a'; + const { list, calls } = toolsFixture(t, (url) => { + assert.equal(url.pathname, workflowPath); + if (url.searchParams.get('cursor')) return { data: [matchingRun], included: [reference] }; + assert.equal(url.searchParams.get('include'), 'sourceBranchOrTag'); + assert.equal(url.searchParams.get('sort'), '-number'); + return { data: [unverifiedRun], links: { next: origin + workflowPath + '?cursor=2' } }; + }); + assert.deepEqual(await list({ limit: 1, sourceCommitSha: sha }), { + buildRuns: [], scan: { scannedCount: 1, hasMore: true, unverifiedSourceCount: 1 }, + }); + assert.equal(calls.length, 1); + const match = await list({ limit: 2, sourceCommitSha: sha }); + assert.equal(match.buildRuns[0].sourceRef, ref); + assert.equal(match.buildRuns[0].sourceCommitSha, sha); + assert.equal(match.buildRuns[0].isPullRequestBuild, false); + assert.equal(match.buildRuns[0].startReason, 'GIT_REF_CHANGE'); + assert.deepEqual(match.scan, { scannedCount: 2, hasMore: false, unverifiedSourceCount: 1 }); + assert.doesNotMatch(JSON.stringify(match), /Private commit message|private\.example/); +}); + +test('a limit inside the final Apple page still marks the SHA scan incomplete', async (t) => { + const first = buildRun(); + first.attributes.sourceCommit.commitSha = 'b'.repeat(40); + const second = buildRun(); + second.id = 'run-2'; + const { list } = toolsFixture(t, () => ({ data: [first, second], included: [reference] })); + const truncated = await list({ limit: 1, sourceCommitSha: sha }); + assert.deepEqual(truncated, { buildRuns: [], scan: { scannedCount: 1, hasMore: true, unverifiedSourceCount: 0 } }); + const exhaustive = await list({ limit: 2, sourceCommitSha: 'c'.repeat(40) }); + assert.deepEqual(exhaustive, { buildRuns: [], scan: { scannedCount: 2, hasMore: false, unverifiedSourceCount: 0 } }); +}); + +function expectedBuild(id: string, platform: string) { + return { + id, platform, marketingVersion: '2.1', buildNumber: '44', + processingState: 'VALID', buildAudienceType: 'APP_STORE_ELIGIBLE', expired: false, + }; +} + +type Handler = (input: Record) => Promise<{ + isError?: boolean; + content: { text: string }[]; + structuredContent?: unknown; +}>; + +function toolsFixture(t: TestContext, respond: (url: URL) => unknown) { + const calls: URL[] = []; + const registry = new Map(); + const server = { + registerTool: (name: string, _config: unknown, callback: Handler) => registry.set(name, callback), + }; + t.mock.method(globalThis, 'fetch', async (input: string, init: RequestInit) => { + const url = new URL(input); + calls.push(url); + assert.equal(url.origin, origin); + assert.equal(init.method ?? 'GET', 'GET'); + assert.equal(init.body, undefined); + return Response.json(respond(url)); + }); + const auth = { getToken: () => 'mock-token' } as AuthManager; + registerBuildRunTools(server as never, new AppStoreConnectClient(auth)); + const invoke = (tool: string, args: Record) => registry.get(tool)!(args); + const payload = async (tool: string, args: Record) => { + const response = await invoke(tool, args); + assert.equal(response.isError, undefined, response.content[0]?.text); + const data = JSON.parse(response.content[0]!.text); + if (tool === 'get_build_run_testflight_builds') { + assert.deepEqual(response.structuredContent, data); + } + return data; + }; + return { + calls, + invoke, + lookup: (args: Record) => payload('get_build_run_testflight_builds', args), + list: (args: Record) => payload('list_build_runs', { workflowId: request.workflowId, ...args }), + }; +} diff --git a/tests/tools.test.ts b/tests/tools.test.ts index 5b46fae..37e0707 100644 --- a/tests/tools.test.ts +++ b/tests/tools.test.ts @@ -311,6 +311,11 @@ test('registered tools expose product, workflow, and build data', async () => { }, getById: async () => buildRun, listForWorkflow: async () => [buildRun, runningBuildRun, pendingBuildRun], + listWithProvenance: async () => ({ + data: [buildRun, runningBuildRun, pendingBuildRun], + included: [], + hasMore: false, + }), getActions: async () => [buildAction], }, artifacts: {