Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(github): pr enricher (#3522)
Will Hutchinsonb6a4bb8d4689
diff --git a/infra/stacks/cloud-storage-service/index.ts b/infra/stacks/cloud-storage-service/index.tsindex 07686fe716..a810717396 100644--- a/infra/stacks/cloud-storage-service/index.ts+++ b/infra/stacks/cloud-storage-service/index.ts@@ -85,14 +85,6 @@ const syncServiceAuthKeyArn: pulumi.Output<string> =const syncServiceAuthKeyValue: pulumi.Output<string> =syncServiceAuthSecret.apply((secret) => secret.secretString);-const AUTHENTICATION_SERVICE_SECRET_KEY = config.require(- `authentication_service_secret_key`-);-const authenticationServiceSecretKeyArn: pulumi.Output<string> =- aws.secretsmanager- .getSecretVersionOutput({ secretId: AUTHENTICATION_SERVICE_SECRET_KEY })- .apply((secret) => secret.arn);-const fusionauthClientIdSecretKey = config.require(`fusionauth_client_id`);const FUSIONAUTH_CLIENT_ID = aws.secretsmanager@@ -392,7 +384,6 @@ const cloudStorageService = new CloudStorageService(cloudfrontPrivateKeySecretArn,internalApiKeyArn,syncServiceAuthKeyArn,- authenticationServiceSecretKeyArn,MACRO_API_TOKENS.macroApiTokenPublicKeyArn,opensearchPasswordArn,githubWebhookSecretKeyArn,@@ -588,14 +579,6 @@ const cloudStorageService = new CloudStorageService(name: ServiceUrl.LEXICAL_SERVICE_URL,value: getServiceUrl(ServiceUrl.LEXICAL_SERVICE_URL),},- {- name: 'AUTHENTICATION_SERVICE_SECRET_KEY',- value: pulumi.interpolate`${AUTHENTICATION_SERVICE_SECRET_KEY}`,- },- {- name: ServiceUrl.AUTHENTICATION_SERVICE_URL,- value: getServiceUrl(ServiceUrl.AUTHENTICATION_SERVICE_URL),- },{name: 'MACRO_API_TOKEN_ISSUER',value: pulumi.interpolate`${MACRO_API_TOKENS.macroApiTokenIssuer}`,diff --git a/js/app/packages/queries/storage/github-pull-requests.ts b/js/app/packages/queries/storage/github-pull-requests.tsindex cf8ccc04ea..8e89b80894 100644--- a/js/app/packages/queries/storage/github-pull-requests.ts+++ b/js/app/packages/queries/storage/github-pull-requests.ts@@ -1,6 +1,14 @@import { throwOnErr } from '@core/util/result';+import { authServiceClient } from '@service-auth/client';+import type {+ EnrichedGithubPullRequest,+ GithubPullRequestRef,+} from '@service-auth/generated/schemas';import { storageServiceClient } from '@service-storage/client';-import type { GithubPullRequestsResponse } from '@service-storage/generated/schemas';+import type {+ GithubPullRequest,+ GithubPullRequestsResponse,+} from '@service-storage/generated/schemas';import { useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import { documentGithubPullRequestsKeys } from './keys';@@ -25,12 +33,60 @@ function readEnabled(enabled: EnabledInput | undefined): boolean {return typeof enabled === 'function' ? enabled() : enabled;}+function toGithubPullRequestRef(+ pullRequest: GithubPullRequest+): GithubPullRequestRef {+ return {+ displayName: pullRequest.displayName,+ githubKey: pullRequest.githubKey,+ number: pullRequest.number,+ owner: pullRequest.owner,+ repo: pullRequest.repo,+ url: pullRequest.url,+ };+}++function toStorageGithubPullRequest(+ pullRequest: EnrichedGithubPullRequest+): GithubPullRequest {+ return {+ additions: pullRequest.additions,+ deletions: pullRequest.deletions,+ displayName: pullRequest.displayName,+ githubKey: pullRequest.githubKey,+ name: pullRequest.name,+ number: pullRequest.number,+ owner: pullRequest.owner,+ repo: pullRequest.repo,+ status: pullRequest.status,+ url: pullRequest.url,+ };+}+async function fetchDocumentGithubPullRequests(documentId: string): Promise<GithubPullRequestsResponse> {- return await throwOnErr(() =>+ const rawResponse = await throwOnErr(() =>storageServiceClient.getDocumentGithubPullRequests({ documentId }));++ if (rawResponse.pullRequests.length === 0) {+ return rawResponse;+ }++ const enrichedResponse = await authServiceClient.enrichGithubPullRequests({+ pullRequests: rawResponse.pullRequests.map(toGithubPullRequestRef),+ });++ if (enrichedResponse.isErr()) {+ return rawResponse;+ }++ return {+ pullRequests: enrichedResponse.value.pullRequests.map(+ toStorageGithubPullRequest+ ),+ };}export function useDocumentGithubPullRequestsQuery(diff --git a/js/app/packages/service-clients/service-auth/client.ts b/js/app/packages/service-clients/service-auth/client.tsindex 821982cca6..2bf0f013b4 100644--- a/js/app/packages/service-clients/service-auth/client.ts+++ b/js/app/packages/service-clients/service-auth/client.ts@@ -10,6 +10,8 @@ import { ok } from 'neverthrow';import { createSignal } from 'solid-js';import { fetchWithAuth as _fetchWithAuth } from './fetch';import type {+ EnrichGithubPullRequestsProxyRequest,+ EnrichGithubPullRequestsResponse,InitGithubLinkResponse,PatchSubscriptionTierRequest,PatchUserTutorialRequest,@@ -317,6 +319,18 @@ export const authServiceClient = {return result;},++ async enrichGithubPullRequests(args: EnrichGithubPullRequestsProxyRequest) {+ return (+ await fetchWithAuth<EnrichGithubPullRequestsResponse>(+ `${authHost}/github_pull_requests/enrich`,+ {+ method: 'POST',+ body: JSON.stringify(args),+ }+ )+ ).map((result) => result);+ },async patchUserTutorial(args: PatchUserTutorialRequest) {return (await fetchWithAuth<EmptyResponse>(`${authHost}/user/tutorial`, {diff --git a/js/app/packages/service-clients/service-auth/generated/client.ts b/js/app/packages/service-clients/service-auth/generated/client.tsindex 799f1e7868..67cb3ec225 100644--- a/js/app/packages/service-clients/service-auth/generated/client.ts+++ b/js/app/packages/service-clients/service-auth/generated/client.ts@@ -14,6 +14,8 @@ import type {CreateTeamRequest,CreateUserRequest,EmptyResponse,+ EnrichGithubPullRequestsProxyRequest,+ EnrichGithubPullRequestsResponse,ErrorResponse,GenerateEmailLinkRequest,GenericSuccessResponse,@@ -270,6 +272,72 @@ export const verifyEmailLink = async (} as verifyEmailLinkResponse;};+/**+ * @summary Enriches GitHub pull request references with live GitHub data for the authenticated user.+ */+export type enrichGithubPullRequestsResponse200 = {+ data: EnrichGithubPullRequestsResponse;+ status: 200;+};++export type enrichGithubPullRequestsResponse401 = {+ data: ErrorResponse;+ status: 401;+};++export type enrichGithubPullRequestsResponse404 = {+ data: ErrorResponse;+ status: 404;+};++export type enrichGithubPullRequestsResponse500 = {+ data: ErrorResponse;+ status: 500;+};++export type enrichGithubPullRequestsResponseSuccess =+ enrichGithubPullRequestsResponse200 & {+ headers: Headers;+ };+export type enrichGithubPullRequestsResponseError = (+ | enrichGithubPullRequestsResponse401+ | enrichGithubPullRequestsResponse404+ | enrichGithubPullRequestsResponse500+) & {+ headers: Headers;+};++export type enrichGithubPullRequestsResponse =+ | enrichGithubPullRequestsResponseSuccess+ | enrichGithubPullRequestsResponseError;++export const getEnrichGithubPullRequestsUrl = () => {+ return `/github_pull_requests/enrich`;+};++export const enrichGithubPullRequests = async (+ enrichGithubPullRequestsProxyRequest: EnrichGithubPullRequestsProxyRequest,+ options?: RequestInit+): Promise<enrichGithubPullRequestsResponse> => {+ const res = await fetch(getEnrichGithubPullRequestsUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(enrichGithubPullRequestsProxyRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: enrichGithubPullRequestsResponse['data'] = body+ ? JSON.parse(body)+ : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as enrichGithubPullRequestsResponse;+};+/*** @summary Health check*/diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsProxyRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsProxyRequest.tsnew file mode 100644index 0000000000..09c8f370b9--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsProxyRequest.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPullRequestRef } from './githubPullRequestRef';++/**+ * Request body for the authenticated pull request enrichment proxy.+ */+export interface EnrichGithubPullRequestsProxyRequest {+ /** The pull requests to enrich for the authenticated user. */+ pullRequests: GithubPullRequestRef[];+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsResponse.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsResponse.tsnew file mode 100644index 0000000000..f0b131967c--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichGithubPullRequestsResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { EnrichedGithubPullRequest } from './enrichedGithubPullRequest';++/**+ * Response body for pull request enrichment.+ */+export interface EnrichGithubPullRequestsResponse {+ /** Pull requests with enrichment fields populated when GitHub data was available. */+ pullRequests: EnrichedGithubPullRequest[];+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.tsnew file mode 100644index 0000000000..f94266c97a--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts@@ -0,0 +1,44 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { EnrichedGithubPullRequestAdditions } from './enrichedGithubPullRequestAdditions';+import type { EnrichedGithubPullRequestDeletions } from './enrichedGithubPullRequestDeletions';+import type { EnrichedGithubPullRequestName } from './enrichedGithubPullRequestName';+import type { EnrichedGithubPullRequestStatus } from './enrichedGithubPullRequestStatus';++/**+ * A pull request reference enriched with live GitHub details when available.+ */+export interface EnrichedGithubPullRequest {+ /**+ * The number of added lines reported by GitHub, when enrichment succeeds.+ * @minimum 0+ */+ additions?: EnrichedGithubPullRequestAdditions;+ /**+ * The number of deleted lines reported by GitHub, when enrichment succeeds.+ * @minimum 0+ */+ deletions?: EnrichedGithubPullRequestDeletions;+ /** A compact label suitable for display in the UI. */+ displayName: string;+ /** The stored GitHub association key, in `owner/repo/pull/number` format. */+ githubKey: string;+ /** The GitHub pull request title, when enrichment succeeds. */+ name?: EnrichedGithubPullRequestName;+ /**+ * The GitHub pull request number.+ * @minimum 0+ */+ number: number;+ /** The GitHub repository owner or organization. */+ owner: string;+ /** The GitHub repository name. */+ repo: string;+ status?: EnrichedGithubPullRequestStatus;+ /** The public GitHub URL for the pull request. */+ url: string;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAdditions.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAdditions.tsnew file mode 100644index 0000000000..c7007a97bd--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestAdditions.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The number of added lines reported by GitHub, when enrichment succeeds.+ * @minimum 0+ */+export type EnrichedGithubPullRequestAdditions = number | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestDeletions.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestDeletions.tsnew file mode 100644index 0000000000..06bd58fb52--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestDeletions.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The number of deleted lines reported by GitHub, when enrichment succeeds.+ * @minimum 0+ */+export type EnrichedGithubPullRequestDeletions = number | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestName.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestName.tsnew file mode 100644index 0000000000..b18ab09269--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The GitHub pull request title, when enrichment succeeds.+ */+export type EnrichedGithubPullRequestName = string | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestStatus.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestStatus.tsnew file mode 100644index 0000000000..2d15257ada--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestStatus.ts@@ -0,0 +1,9 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */+import type { GithubPullRequestStatus } from './githubPullRequestStatus';++export type EnrichedGithubPullRequestStatus = null | GithubPullRequestStatus;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestRef.ts b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestRef.tsnew file mode 100644index 0000000000..3ac9614b32--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestRef.ts@@ -0,0 +1,27 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * A pull request reference that can be enriched with live GitHub data.+ */+export interface GithubPullRequestRef {+ /** A compact label suitable for display in the UI. */+ displayName: string;+ /** The stored GitHub association key, in `owner/repo/pull/number` format. */+ githubKey: string;+ /**+ * The GitHub pull request number.+ * @minimum 0+ */+ number: number;+ /** The GitHub repository owner or organization. */+ owner: string;+ /** The GitHub repository name. */+ repo: string;+ /** The public GitHub URL for the pull request. */+ url: string;+}diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestStatus.ts b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestStatus.tsnew file mode 100644index 0000000000..c0fb03e687--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestStatus.ts@@ -0,0 +1,19 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The normalized lifecycle status for a GitHub pull request.+ */+export type GithubPullRequestStatus =+ (typeof GithubPullRequestStatus)[keyof typeof GithubPullRequestStatus];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const GithubPullRequestStatus = {+ open: 'open',+ closed: 'closed',+ merged: 'merged',+} as const;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts b/js/app/packages/service-clients/service-auth/generated/schemas/index.tsindex e8dd88e67e..0ca6ed983a 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/index.ts@@ -21,6 +21,13 @@ export * from './createPortalSessionRequest';export * from './createTeamRequest';export * from './createUserRequest';export * from './emptyResponse';+export * from './enrichedGithubPullRequest';+export * from './enrichedGithubPullRequestAdditions';+export * from './enrichedGithubPullRequestDeletions';+export * from './enrichedGithubPullRequestName';+export * from './enrichedGithubPullRequestStatus';+export * from './enrichGithubPullRequestsProxyRequest';+export * from './enrichGithubPullRequestsResponse';export * from './errorResponse';export * from './generateEmailLinkRequest';export * from './genericSuccessResponse';@@ -32,6 +39,8 @@ export * from './getProfilePicturesRequestBody';export * from './getUserInfo';export * from './getUserInfoOrganizationId';export * from './getUserLinkExistsParams';+export * from './githubPullRequestRef';+export * from './githubPullRequestStatus';export * from './initGithubLinkParams';export * from './initGithubLinkResponse';export * from './initGmailLinkParams';diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex 130b57c7c3..0119569159 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -178,6 +178,65 @@}}},+ "/github_pull_requests/enrich": {+ "post": {+ "tags": ["github_pull_requests"],+ "summary": "Enriches GitHub pull request references with live GitHub data for the authenticated user.",+ "operationId": "enrich_github_pull_requests",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EnrichGithubPullRequestsProxyRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/EnrichGithubPullRequestsResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/health": {"get": {"tags": ["health"],@@ -3395,6 +3454,101 @@"type": "object","description": "Empty response is required due to custom fetch forcing `response.json()`"},+ "EnrichGithubPullRequestsProxyRequest": {+ "type": "object",+ "description": "Request body for the authenticated pull request enrichment proxy.",+ "required": ["pullRequests"],+ "properties": {+ "pullRequests": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/GithubPullRequestRef"+ },+ "description": "The pull requests to enrich for the authenticated user."+ }+ }+ },+ "EnrichGithubPullRequestsResponse": {+ "type": "object",+ "description": "Response body for pull request enrichment.",+ "required": ["pullRequests"],+ "properties": {+ "pullRequests": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/EnrichedGithubPullRequest"+ },+ "description": "Pull requests with enrichment fields populated when GitHub data was available."+ }+ }+ },+ "EnrichedGithubPullRequest": {+ "type": "object",+ "description": "A pull request reference enriched with live GitHub details when available.",+ "required": [+ "githubKey",+ "owner",+ "repo",+ "number",+ "url",+ "displayName"+ ],+ "properties": {+ "additions": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "The number of added lines reported by GitHub, when enrichment succeeds.",+ "minimum": 0+ },+ "deletions": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "The number of deleted lines reported by GitHub, when enrichment succeeds.",+ "minimum": 0+ },+ "displayName": {+ "type": "string",+ "description": "A compact label suitable for display in the UI."+ },+ "githubKey": {+ "type": "string",+ "description": "The stored GitHub association key, in `owner/repo/pull/number` format."+ },+ "name": {+ "type": ["string", "null"],+ "description": "The GitHub pull request title, when enrichment succeeds."+ },+ "number": {+ "type": "integer",+ "format": "int64",+ "description": "The GitHub pull request number.",+ "minimum": 0+ },+ "owner": {+ "type": "string",+ "description": "The GitHub repository owner or organization."+ },+ "repo": {+ "type": "string",+ "description": "The GitHub repository name."+ },+ "status": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/GithubPullRequestStatus",+ "description": "The normalized GitHub pull request status, when enrichment succeeds."+ }+ ]+ },+ "url": {+ "type": "string",+ "description": "The public GitHub URL for the pull request."+ }+ }+ },"ErrorResponse": {"type": "object","description": "A plain old json error response for use with axum.\nyup, thats it.",@@ -3542,6 +3696,51 @@}}},+ "GithubPullRequestRef": {+ "type": "object",+ "description": "A pull request reference that can be enriched with live GitHub data.",+ "required": [+ "githubKey",+ "owner",+ "repo",+ "number",+ "url",+ "displayName"+ ],+ "properties": {+ "displayName": {+ "type": "string",+ "description": "A compact label suitable for display in the UI."+ },+ "githubKey": {+ "type": "string",+ "description": "The stored GitHub association key, in `owner/repo/pull/number` format."+ },+ "number": {+ "type": "integer",+ "format": "int64",+ "description": "The GitHub pull request number.",+ "minimum": 0+ },+ "owner": {+ "type": "string",+ "description": "The GitHub repository owner or organization."+ },+ "repo": {+ "type": "string",+ "description": "The GitHub repository name."+ },+ "url": {+ "type": "string",+ "description": "The public GitHub URL for the pull request."+ }+ }+ },+ "GithubPullRequestStatus": {+ "type": "string",+ "description": "The normalized lifecycle status for a GitHub pull request.",+ "enum": ["open", "closed", "merged"]+ },"InitGithubLinkResponse": {"type": "object","required": ["authorization_url", "link_id"],diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.tsindex 3cf1483726..6a4c1a29f3 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequest.ts@@ -4,15 +4,31 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { GithubPullRequestAdditions } from './githubPullRequestAdditions';+import type { GithubPullRequestDeletions } from './githubPullRequestDeletions';+import type { GithubPullRequestName } from './githubPullRequestName';+import type { GithubPullRequestStatus } from './githubPullRequestStatus';/*** Display-ready data for a GitHub pull request associated with a task.*/export interface GithubPullRequest {+ /**+ * The number of added lines in the pull request, when enrichment data is available.+ * @minimum 0+ */+ additions?: GithubPullRequestAdditions;+ /**+ * The number of deleted lines in the pull request, when enrichment data is available.+ * @minimum 0+ */+ deletions?: GithubPullRequestDeletions;/** A compact label suitable for display in the UI. */displayName: string;/** The stored GitHub association key, in `owner/repo/pull/number` format. */githubKey: string;+ /** The GitHub pull request title, when enrichment data is available. */+ name?: GithubPullRequestName;/*** The GitHub pull request number.* @minimum 0@@ -22,6 +38,8 @@ export interface GithubPullRequest {owner: string;/** The GitHub repository name. */repo: string;+ /** The GitHub pull request status, when enrichment data is available. */+ status?: GithubPullRequestStatus;/** The public GitHub URL for the pull request. */url: string;}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestAdditions.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestAdditions.tsnew file mode 100644index 0000000000..4a913a7a89--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestAdditions.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The number of added lines in the pull request, when enrichment data is available.+ * @minimum 0+ */+export type GithubPullRequestAdditions = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestDeletions.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestDeletions.tsnew file mode 100644index 0000000000..96dd207532--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestDeletions.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The number of deleted lines in the pull request, when enrichment data is available.+ * @minimum 0+ */+export type GithubPullRequestDeletions = number | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestName.tsnew file mode 100644index 0000000000..8cf20ef1a3--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The GitHub pull request title, when enrichment data is available.+ */+export type GithubPullRequestName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestStatus.ts b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestStatus.tsnew file mode 100644index 0000000000..4050196afe--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/githubPullRequestStatus.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The GitHub pull request status, when enrichment data is available.+ */+export type GithubPullRequestStatus = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 1f91fd7097..1d36403e5f 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -438,6 +438,10 @@ export * from './getRecentActivityHandlerParams';export * from './getUserDocumentsHandlerParams';export * from './getUserHistoryResponse';export * from './githubPullRequest';+export * from './githubPullRequestAdditions';+export * from './githubPullRequestDeletions';+export * from './githubPullRequestName';+export * from './githubPullRequestStatus';export * from './githubPullRequestsResponse';export * from './hashMap';export * from './hashMapOneOf';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex e2f148c14b..8a43770885 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -3626,6 +3626,10 @@ export const getDocumentGithubPullRequestsParams = zod.object({document_id: zod.string().describe('Document ID'),});+export const getDocumentGithubPullRequestsResponsePullRequestsItemAdditionsMin = 0;++export const getDocumentGithubPullRequestsResponsePullRequestsItemDeletionsMin = 0;+export const getDocumentGithubPullRequestsResponsePullRequestsItemNumberMin = 0;export const getDocumentGithubPullRequestsResponse = zod@@ -3634,6 +3638,24 @@ export const getDocumentGithubPullRequestsResponse = zod.array(zod.object({+ additions: zod+ .number()+ .min(+ getDocumentGithubPullRequestsResponsePullRequestsItemAdditionsMin+ )+ .nullish()+ .describe(+ 'The number of added lines in the pull request, when enrichment data is available.'+ ),+ deletions: zod+ .number()+ .min(+ getDocumentGithubPullRequestsResponsePullRequestsItemDeletionsMin+ )+ .nullish()+ .describe(+ 'The number of deleted lines in the pull request, when enrichment data is available.'+ ),displayName: zod.string().describe('A compact label suitable for display in the UI.'),@@ -3642,6 +3664,12 @@ export const getDocumentGithubPullRequestsResponse = zod.describe('The stored GitHub association key, in `owner\/repo\/pull\/number` format.'),+ name: zod+ .string()+ .nullish()+ .describe(+ 'The GitHub pull request title, when enrichment data is available.'+ ),number: zod.number().min(@@ -3652,6 +3680,12 @@ export const getDocumentGithubPullRequestsResponse = zod.string().describe('The GitHub repository owner or organization.'),repo: zod.string().describe('The GitHub repository name.'),+ status: zod+ .string()+ .nullish()+ .describe(+ 'The GitHub pull request status, when enrichment data is available.'+ ),url: zod.string().describe('The public GitHub URL for the pull request.'),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex efbd56a08e..a8e6b02b16 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -10327,6 +10327,18 @@"displayName"],"properties": {+ "additions": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "The number of added lines in the pull request, when enrichment data is available.",+ "minimum": 0+ },+ "deletions": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "The number of deleted lines in the pull request, when enrichment data is available.",+ "minimum": 0+ },"displayName": {"type": "string","description": "A compact label suitable for display in the UI."@@ -10335,6 +10347,10 @@"type": "string","description": "The stored GitHub association key, in `owner/repo/pull/number` format."},+ "name": {+ "type": ["string", "null"],+ "description": "The GitHub pull request title, when enrichment data is available."+ },"number": {"type": "integer","format": "int64",@@ -10349,6 +10365,10 @@"type": "string","description": "The GitHub repository name."},+ "status": {+ "type": ["string", "null"],+ "description": "The GitHub pull request status, when enrichment data is available."+ },"url": {"type": "string","description": "The public GitHub URL for the pull request."diff --git a/rust/cloud-storage/ai_tools/src/build_context.rs b/rust/cloud-storage/ai_tools/src/build_context.rsindex ad31a7aed8..fd32855e5d 100644--- a/rust/cloud-storage/ai_tools/src/build_context.rs+++ b/rust/cloud-storage/ai_tools/src/build_context.rs@@ -193,17 +193,19 @@ pub async fn build_tool_service_context_from_env(presigned_url_expiry_seconds: 3600,browser_cache_expiry_seconds: 86400,};- let document_service = documents::domain::service::DocumentServiceImpl::new(- document_repo,+ let document_service = documents::domain::service::DocumentServiceImpl {+ repo: document_repo,cloudfront_config,- sync_client.as_ref().clone(),- s3_upload_adapter,- NoOpTaskProperties,- NoOpConnectionService,- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(- entity_access_management::outbound::PgRepository::new(pool.clone()),- ),- );+ sync_service_client: sync_client.as_ref().clone(),+ upload_url_service: s3_upload_adapter,+ task_properties_service: NoOpTaskProperties,+ connection_service: NoOpConnectionService,+ entity_access_management_service:+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(+ entity_access_management::outbound::PgRepository::new(pool.clone()),+ ),+ };+let entity_access_service = Arc::new(EntityAccessServiceImpl::new(PgAccessRepository::new(pool.clone(),)));diff --git a/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs b/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rsnew file mode 100644index 0000000000..ed67042540--- /dev/null+++ b/rust/cloud-storage/authentication_service/src/api/github_pull_requests.rs@@ -0,0 +1,79 @@+use axum::{+ Json, Router,+ extract::{self, State},+ http::StatusCode,+ response::{IntoResponse, Response},+ routing::post,+};+use github::domain::{+ models::{EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse, GithubError},+ ports::GithubLinkService,+};+use model::response::ErrorResponse;+use model_user::axum_extractor::MacroUserExtractor;++use crate::api::context::ApiContext;++#[derive(thiserror::Error, Debug)]+pub enum EnrichGithubPullRequestsProxyError {+ #[error(transparent)]+ Github(#[from] GithubError),+}++impl IntoResponse for EnrichGithubPullRequestsProxyError {+ fn into_response(self) -> Response {+ let status_code = match &self {+ Self::Github(GithubError::NoLinkFound) => StatusCode::NOT_FOUND,+ Self::Github(error) => {+ tracing::error!(error=?error, "failed to enrich GitHub pull requests");+ StatusCode::INTERNAL_SERVER_ERROR+ }+ };++ let message = match &self {+ Self::Github(GithubError::NoLinkFound) => "no github link found",+ Self::Github(_) => "internal error",+ };++ (+ status_code,+ Json(ErrorResponse {+ message: message.into(),+ }),+ )+ .into_response()+ }+}++pub fn router() -> Router<ApiContext> {+ Router::new().route("/enrich", post(handler))+}++/// Enriches GitHub pull request references with live GitHub data for the authenticated user.+#[utoipa::path(+ post,+ path = "/github_pull_requests/enrich",+ operation_id = "enrich_github_pull_requests",+ request_body = EnrichGithubPullRequestsProxyRequest,+ responses(+ (status = 200, body = EnrichGithubPullRequestsResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(skip(ctx, user_context, request), fields(user_id = %user_context.macro_user_id), err)]+pub async fn handler(+ State(ctx): State<ApiContext>,+ user_context: MacroUserExtractor,+ extract::Json(request): extract::Json<EnrichGithubPullRequestsProxyRequest>,+) -> Result<Json<EnrichGithubPullRequestsResponse>, EnrichGithubPullRequestsProxyError> {+ tracing::info!("enrich_github_pull_requests");++ let pull_requests = ctx+ .github_link_service+ .enrich_pull_requests(&user_context.macro_user_id, request.pull_requests)+ .await?;++ Ok(Json(EnrichGithubPullRequestsResponse { pull_requests }))+}diff --git a/rust/cloud-storage/authentication_service/src/api/mod.rs b/rust/cloud-storage/authentication_service/src/api/mod.rsindex 92d82f83d0..97a7f5f3c5 100644--- a/rust/cloud-storage/authentication_service/src/api/mod.rs+++ b/rust/cloud-storage/authentication_service/src/api/mod.rs@@ -22,6 +22,7 @@ mod link;mod merge;mod mobile_welcome_email;+mod github_pull_requests;mod health;mod internal;mod jwt;@@ -93,6 +94,15 @@ fn api_router(state: ApiContext) -> Router<ApiContext> {),)),)+ .nest(+ "/github_pull_requests",+ github_pull_requests::router().layer(ServiceBuilder::new().layer(+ axum::middleware::from_fn_with_state(+ state.jwt_args.clone(),+ macro_middleware::auth::decode_jwt::handler,+ ),+ )),+ ).nest("/team",teams::inbound::axum_router::teams_router(diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 55c8343dd2..45bfacbd38 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -1,3 +1,7 @@+use github::domain::models::{+ EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,+ EnrichedGithubPullRequest, GithubPullRequestRef, GithubPullRequestStatus,+};use model::authentication::login::request::{AppleLoginRequest, PasswordRequest};use teams::domain::model::{PatchTeamCrmSettingsRequest, PatchTeamCrmSettingsResponse, PatchTeamRequest, PatchTeamUserRole,@@ -33,8 +37,8 @@ use crate::api::user::stripe::create_portal_session::CreatePortalSessionRequest;use crate::api::user::stripe::patch_subscription_tier::PatchSubscriptionTierRequest;use crate::api::user::stripe::{StripeProductTier, StripeSessionResponse};use crate::api::{- email, health, jwt, link, login, logout, merge, mobile_welcome_email, oauth, oauth2,- permissions, session, user,+ email, github_pull_requests, health, jwt, link, login, logout, merge, mobile_welcome_email,+ oauth, oauth2, permissions, session, user,};use model::authentication::login::response::SsoRequiredResponse;use model::authentication::{@@ -74,6 +78,9 @@ use model::user::{link::github::delete_github_link_handler,link::gmail::init_gmail_link_handler,+ /// /github_pull_requests+ github_pull_requests::handler,+/// /oauthoauth::oauth_redirect::handler,oauth::passwordless_callback::handler,@@ -169,6 +176,14 @@ use model::user::{CreateInProgressLinkResponse,InitGithubLinkResponse,InitGmailLinkResponse,++ // GitHub pull requests+ EnrichGithubPullRequestsProxyRequest,+ EnrichGithubPullRequestsResponse,+ EnrichedGithubPullRequest,+ GithubPullRequestRef,+ GithubPullRequestStatus,+UserQuota,UserOrganizationResponse,GetLegacyUserPermissionsResponse,@@ -215,3 +230,47 @@ use model::user::{))]pub struct ApiDoc;++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn github_pull_requests_openapi_includes_enrich_path() {+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();+ let operation = &openapi["paths"]["/github_pull_requests/enrich"]["post"];++ assert_eq!(operation["operationId"], "enrich_github_pull_requests");+ assert_eq!(+ operation["requestBody"]["content"]["application/json"]["schema"]["$ref"].as_str(),+ Some("#/components/schemas/EnrichGithubPullRequestsProxyRequest")+ );+ assert_eq!(+ operation["responses"]["200"]["content"]["application/json"]["schema"]["$ref"].as_str(),+ Some("#/components/schemas/EnrichGithubPullRequestsResponse")+ );+ }++ #[test]+ fn github_pull_requests_openapi_includes_components() {+ let openapi = serde_json::to_value(ApiDoc::openapi()).unwrap();+ let schemas = &openapi["components"]["schemas"];++ for schema_name in [+ "EnrichGithubPullRequestsProxyRequest",+ "EnrichGithubPullRequestsResponse",+ "EnrichedGithubPullRequest",+ "GithubPullRequestRef",+ "GithubPullRequestStatus",+ ] {+ assert!(+ schemas.get(schema_name).is_some(),+ "missing schema component {schema_name}"+ );+ }++ let request_properties = &schemas["EnrichGithubPullRequestsProxyRequest"]["properties"];+ assert!(request_properties.get("pullRequests").is_some());+ assert!(request_properties.get("macroUserId").is_none());+ }+}diff --git a/rust/cloud-storage/authentication_service_client/src/lib.rs b/rust/cloud-storage/authentication_service_client/src/lib.rsindex 376e30fbed..70afd6fcfa 100644--- a/rust/cloud-storage/authentication_service_client/src/lib.rs+++ b/rust/cloud-storage/authentication_service_client/src/lib.rs@@ -11,6 +11,8 @@ pub struct AuthServiceClient {pub static INTERNAL_AUTH_HEADER_KEY: &str = "x-internal-auth-key";+const REQUEST_TIMEOUT_SECONDS: u64 = 15;+impl AuthServiceClient {pub fn new(internal_auth_key: String, url: String) -> Self {let mut headers = reqwest::header::HeaderMap::new();@@ -18,6 +20,7 @@ impl AuthServiceClient {let client = reqwest::Client::builder().default_headers(headers)+ .timeout(std::time::Duration::from_secs(REQUEST_TIMEOUT_SECONDS)).build().unwrap();diff --git a/rust/cloud-storage/document_storage_service/src/config.rs b/rust/cloud-storage/document_storage_service/src/config.rsindex 805849dedb..ea76eefc44 100644--- a/rust/cloud-storage/document_storage_service/src/config.rs+++ b/rust/cloud-storage/document_storage_service/src/config.rs@@ -54,8 +54,6 @@ env_var! {pub SyncServiceUrl,pub SyncServiceAuthKey,pub LexicalServiceUrl,- pub AuthenticationServiceUrl,- pub AuthenticationServiceSecretKey,pub OpensearchUrl,pub OpensearchUsername,pub OpensearchPassword,diff --git a/rust/cloud-storage/documents/src/domain/models.rs b/rust/cloud-storage/documents/src/domain/models.rsindex 49546c77e9..553037f30f 100644--- a/rust/cloud-storage/documents/src/domain/models.rs+++ b/rust/cloud-storage/documents/src/domain/models.rs@@ -120,6 +120,18 @@ pub struct GithubPullRequest {pub url: String,/// A compact label suitable for display in the UI.pub display_name: String,+ /// The GitHub pull request title, when enrichment data is available.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,+ /// The GitHub pull request status, when enrichment data is available.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub status: Option<String>,+ /// The number of added lines in the pull request, when enrichment data is available.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub additions: Option<u64>,+ /// The number of deleted lines in the pull request, when enrichment data is available.+ #[serde(skip_serializing_if = "Option::is_none")]+ pub deletions: Option<u64>,}impl GithubPullRequest {@@ -151,6 +163,10 @@ impl GithubPullRequest {number,url,display_name,+ name: None,+ status: None,+ additions: None,+ deletions: None,})}}diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex 2a6fb5057d..374aa63904 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -58,14 +58,20 @@ pub struct DocumentServiceImpl<C: ConnectionService,Eam: EntityAccessManagementService,> {- repo: R,- cloudfront_config: CloudFrontConfig,- sync_service_client: sync_service_client::SyncServiceClient,- upload_url_service: U,- task_properties_service: T,- connection_service: C,- #[allow(dead_code)]- entity_access_management_service: Eam,+ /// Document repository+ pub repo: R,+ /// Cloudfront config+ pub cloudfront_config: CloudFrontConfig,+ /// Sync service client+ pub sync_service_client: sync_service_client::SyncServiceClient,+ /// Upload service+ pub upload_url_service: U,+ /// Task properties service+ pub task_properties_service: T,+ /// Connection service+ pub connection_service: C,+ /// entity access management service+ pub entity_access_management_service: Eam,}fn ready_content_for_file_type(file_type: Option<FileType>) -> DocumentContent {@@ -121,7 +127,7 @@ impl<Eam: EntityAccessManagementService,> DocumentServiceImpl<R, U, T, C, Eam>{- /// Create a new document service.+ /// Create a document service with its repository and external service ports.pub fn new(repo: R,cloudfront_config: CloudFrontConfig,diff --git a/rust/cloud-storage/documents/src/domain/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rsindex 836ecc2c0b..5c3365d7ba 100644--- a/rust/cloud-storage/documents/src/domain/service/tests.rs+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs@@ -1,6 +1,7 @@use macro_user_id::cowlike::CowLike;use model::document::DocumentMetadata;+use crate::domain::models::GithubPullRequest;use crate::domain::ports::MockDocumentRepo;use super::*;@@ -33,6 +34,205 @@ fn make_mock_repo() -> MockDocumentRepo {MockDocumentRepo::new()}+fn test_cloudfront_config() -> CloudFrontConfig {+ CloudFrontConfig {+ distribution_url: "https://cdn.example.test".to_string(),+ signer_public_key_id: "test-key-id".to_string(),+ signer_private_key: "test-private-key".to_string(),+ presigned_url_expiry_seconds: 60,+ browser_cache_expiry_seconds: 60,+ }+}++fn task_document_context(document_id: &str) -> DocumentBasic {+ DocumentBasic {+ document_id: document_id.to_string(),+ document_name: "Test task".to_string(),+ owner: macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ file_type: Some("md".to_string()),+ sub_type: Some(DocumentSubType::Task),+ branched_from_id: None,+ branched_from_version_id: None,+ document_family_id: None,+ project_id: None,+ deleted_at: None,+ }+}++fn authenticated_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {+ let user_id = macro_user_id::user_id::MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ EntityAccessReceipt::dangerously_assert_authenticated_user(+ user_id,+ document_id,+ EntityType::Document,+ )+}++fn internal_receipt(document_id: &str) -> EntityAccessReceipt<ViewAccessLevel> {+ EntityAccessReceipt::dangerously_assert_internal_user(document_id, EntityType::Document)+}++struct TestUploadUrlPort;++impl PresignedUploadUrlPort for TestUploadUrlPort {+ async fn put_document_storage_presigned_url(+ &self,+ _key: &str,+ _sha: &str,+ _content_type: ContentType,+ ) -> anyhow::Result<String> {+ Ok(String::new())+ }++ async fn put_docx_upload_presigned_url(+ &self,+ _key: &str,+ _sha: &str,+ _content_type: ContentType,+ ) -> anyhow::Result<String> {+ Ok(String::new())+ }++ async fn copy_object(&self, _source_key: &str, _destination_key: &str) -> anyhow::Result<()> {+ Ok(())+ }+}++struct TestTaskPropertiesPort;++impl TaskPropertiesPort for TestTaskPropertiesPort {+ async fn attach_task_properties(&self, _entity_ids: Vec<String>) -> anyhow::Result<()> {+ Ok(())+ }++ async fn update_task_status(&self, _entity_id: &str, _status: &str) -> anyhow::Result<()> {+ Ok(())+ }++ async fn set_entity_property(+ &self,+ _user_id: &str,+ _entity_id: &str,+ _property_definition_id: uuid::Uuid,+ _value: Option<models_properties::api::requests::SetPropertyValue>,+ ) -> anyhow::Result<()> {+ Ok(())+ }++ async fn copy_task_properties(+ &self,+ _from_task_id: &str,+ _to_task_id: &str,+ ) -> anyhow::Result<()> {+ Ok(())+ }+}++struct TestConnectionService;++impl ConnectionService for TestConnectionService {+ async fn send_invalidation_event<'a, T: std::fmt::Debug + serde::Serialize + Send>(+ &self,+ _invalidation_event: InvalidationEvent<'a, T>,+ ) -> Result<(), connection::domain::models::ConnectionError> {+ Ok(())+ }++ async fn send_channel_message<'a>(+ &self,+ _users: &[macro_user_id::user_id::MacroUserIdStr<'a>],+ _message_type: &str,+ _message: serde_json::Value,+ ) -> Result<(), connection::domain::models::ConnectionError> {+ Ok(())+ }+}++#[derive(Clone)]+struct TestEntityAccessManagementService;++impl EntityAccessManagementService for TestEntityAccessManagementService {+ async fn add_entity_to_project(+ &self,+ _entity_id: &uuid::Uuid,+ _entity_type: EntityType,+ _project_id: &uuid::Uuid,+ ) -> Result<(), entity_access_management::domain::models::EntityAccessManagementError> {+ Ok(())+ }++ async fn remove_entity_from_project(+ &self,+ _entity_id: &uuid::Uuid,+ _entity_type: EntityType,+ _old_project_id: &uuid::Uuid,+ ) -> Result<(), entity_access_management::domain::models::EntityAccessManagementError> {+ Ok(())+ }++ async fn move_project(+ &self,+ _project_id: &uuid::Uuid,+ _old_project_id: Option<&uuid::Uuid>,+ _new_project_id: Option<&uuid::Uuid>,+ ) -> Result<(), entity_access_management::domain::models::EntityAccessManagementError> {+ Ok(())+ }+}++fn make_test_service(+ repo: MockDocumentRepo,+) -> DocumentServiceImpl<+ MockDocumentRepo,+ TestUploadUrlPort,+ TestTaskPropertiesPort,+ TestConnectionService,+ TestEntityAccessManagementService,+> {+ DocumentServiceImpl::new(+ repo,+ test_cloudfront_config(),+ sync_service_client::SyncServiceClient::new(+ "test-sync-key".to_string(),+ "http://sync-service.test".to_string(),+ ),+ TestUploadUrlPort,+ TestTaskPropertiesPort,+ TestConnectionService,+ TestEntityAccessManagementService,+ )+}++fn assert_raw_pull_request(+ pull_request: &GithubPullRequest,+ github_key: &str,+ owner: &str,+ repo: &str,+ number: u64,+) {+ let expected_url = format!("https://github.com/{owner}/{repo}/pull/{number}");+ let expected_display_name = format!("{owner}/{repo}#{number}");++ assert_eq!(pull_request.github_key.as_str(), github_key);+ assert_eq!(pull_request.owner.as_str(), owner);+ assert_eq!(pull_request.repo.as_str(), repo);+ assert_eq!(pull_request.number, number);+ assert_eq!(pull_request.url.as_str(), expected_url.as_str());+ assert_eq!(+ pull_request.display_name.as_str(),+ expected_display_name.as_str()+ );+ assert!(pull_request.name.is_none());+ assert!(pull_request.status.is_none());+ assert!(pull_request.additions.is_none());+ assert!(pull_request.deletions.is_none());+}+#[tokio::test]async fn test_get_document_happy_path() {let mut repo = make_mock_repo();@@ -88,3 +288,71 @@ async fn test_soft_delete_document() {let result = repo.soft_delete_document("doc-1").await;assert!(result.is_ok());}++#[tokio::test]+async fn test_get_task_github_pull_requests_returns_raw_refs_for_authenticated_user() {+ let document_id = "00000000-0000-0000-0000-000000000001";+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();+ let mut repo = make_mock_repo();++ repo.expect_get_task_github_pull_request_keys()+ .withf(move |task_short_id| task_short_id == expected_short_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(vec![+ "macro/repo/pull/7".to_string(),+ ])))+ });++ let service = make_test_service(repo);++ let response = service+ .get_task_github_pull_requests(+ authenticated_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(response.pull_requests.len(), 1);+ assert_raw_pull_request(+ &response.pull_requests[0],+ "macro/repo/pull/7",+ "macro",+ "repo",+ 7,+ );+}++#[tokio::test]+async fn test_get_task_github_pull_requests_returns_raw_refs_for_internal_access() {+ let document_id = "00000000-0000-0000-0000-000000000002";+ let expected_short_id = short_id_for_entity_id(document_id).unwrap();+ let mut repo = make_mock_repo();++ repo.expect_get_task_github_pull_request_keys()+ .withf(move |task_short_id| task_short_id == expected_short_id)+ .return_once(|_| {+ Box::pin(std::future::ready(Ok(vec![+ "macro/repo/pull/8".to_string(),+ ])))+ });++ let service = make_test_service(repo);++ let response = service+ .get_task_github_pull_requests(+ internal_receipt(document_id),+ &task_document_context(document_id),+ )+ .await+ .unwrap();++ assert_eq!(response.pull_requests.len(), 1);+ assert_raw_pull_request(+ &response.pull_requests[0],+ "macro/repo/pull/8",+ "macro",+ "repo",+ 8,+ );+}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rsindex 8f05e12491..b4473a5eac 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs@@ -1003,6 +1003,10 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgresnumber: 5,url: "https://github.com/macro/api/pull/5".to_string(),display_name: "macro/api#5".to_string(),+ name: None,+ status: None,+ additions: None,+ deletions: None,},GithubPullRequest {github_key: "macro/macro/pull/10".to_string(),@@ -1011,6 +1015,10 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgresnumber: 10,url: "https://github.com/macro/macro/pull/10".to_string(),display_name: "macro/macro#10".to_string(),+ name: None,+ status: None,+ additions: None,+ deletions: None,},GithubPullRequest {github_key: "macro/macro/pull/20".to_string(),@@ -1019,6 +1027,10 @@ async fn test_get_github_pull_request_keys_orders_and_parses(pool: Pool<Postgresnumber: 20,url: "https://github.com/macro/macro/pull/20".to_string(),display_name: "macro/macro#20".to_string(),+ name: None,+ status: None,+ additions: None,+ deletions: None,},]);diff --git a/rust/cloud-storage/github/src/domain/models/link.rs b/rust/cloud-storage/github/src/domain/models/link.rsindex e1c0e08a29..b72b54f663 100644--- a/rust/cloud-storage/github/src/domain/models/link.rs+++ b/rust/cloud-storage/github/src/domain/models/link.rs@@ -13,6 +13,17 @@ impl GithubAccessToken {pub fn new(token: String) -> Self {Self(token)}++ /// Returns the token string without exposing ownership of the secret.+ pub fn as_str(&self) -> &str {+ &self.0+ }+}++impl AsRef<str> for GithubAccessToken {+ fn as_ref(&self) -> &str {+ self.as_str()+ }}/// A GitHub link record (as stored in the database)diff --git a/rust/cloud-storage/github/src/domain/models/mod.rs b/rust/cloud-storage/github/src/domain/models/mod.rsindex 74e11145ce..b1f125c560 100644--- a/rust/cloud-storage/github/src/domain/models/mod.rs+++ b/rust/cloud-storage/github/src/domain/models/mod.rs@@ -4,9 +4,15 @@mod test;mod link;+mod pull_request;mod sync;pub use link::{GithubAccessToken, GithubExchangeTokenResponse, GithubLink, GithubUserInfo};+pub use pull_request::{+ EnrichGithubPullRequestsProxyRequest, EnrichGithubPullRequestsResponse,+ EnrichedGithubPullRequest, GithubPullRequestDetails, GithubPullRequestRef,+ GithubPullRequestStatus,+};pub use sync::{GithubInstallationAccessToken, GithubKey, GithubWebhookEventType, MacroTaskId,TeamTaskReference, ValidatedGithubWebhookEvent,diff --git a/rust/cloud-storage/github/src/domain/models/pull_request.rs b/rust/cloud-storage/github/src/domain/models/pull_request.rsnew file mode 100644index 0000000000..3fe6c5005b--- /dev/null+++ b/rust/cloud-storage/github/src/domain/models/pull_request.rs@@ -0,0 +1,174 @@+//! Domain models for GitHub pull request enrichment.++use std::fmt;++use serde::{Deserialize, Serialize};++/// A pull request reference that can be enriched with live GitHub data.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct GithubPullRequestRef {+ /// The stored GitHub association key, in `owner/repo/pull/number` format.+ pub github_key: String,+ /// The GitHub repository owner or organization.+ pub owner: String,+ /// The GitHub repository name.+ pub repo: String,+ /// The GitHub pull request number.+ pub number: u64,+ /// The public GitHub URL for the pull request.+ pub url: String,+ /// A compact label suitable for display in the UI.+ pub display_name: String,+}++/// The normalized lifecycle status for a GitHub pull request.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "lowercase")]+pub enum GithubPullRequestStatus {+ /// The pull request is open.+ Open,+ /// The pull request is closed without being merged.+ Closed,+ /// The pull request is closed and merged.+ Merged,+}++impl GithubPullRequestStatus {+ /// Derive the normalized status from GitHub API pull request details.+ pub fn from_details(details: &GithubPullRequestDetails) -> Self {+ if details.state == "closed" {+ if details.merged_at.is_some() {+ return Self::Merged;+ }++ return Self::Closed;+ }++ Self::Open+ }++ /// Return the status as the API string representation.+ pub fn as_str(self) -> &'static str {+ match self {+ Self::Open => "open",+ Self::Closed => "closed",+ Self::Merged => "merged",+ }+ }+}++impl fmt::Display for GithubPullRequestStatus {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.as_str())+ }+}++/// GitHub API pull request details used to enrich a pull request reference.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+pub struct GithubPullRequestDetails {+ /// The GitHub pull request title.+ pub title: String,+ /// The raw GitHub pull request state, usually `open` or `closed`.+ pub state: String,+ /// The merge timestamp returned by GitHub, when the pull request was merged.+ pub merged_at: Option<chrono::DateTime<chrono::Utc>>,+ /// The number of added lines reported by GitHub.+ pub additions: u64,+ /// The number of deleted lines reported by GitHub.+ pub deletions: u64,+}++impl GithubPullRequestDetails {+ /// Derive the normalized status for these GitHub API details.+ pub fn status(&self) -> GithubPullRequestStatus {+ GithubPullRequestStatus::from_details(self)+ }+}++/// A pull request reference enriched with live GitHub details when available.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct EnrichedGithubPullRequest {+ /// The stored GitHub association key, in `owner/repo/pull/number` format.+ pub github_key: String,+ /// The GitHub repository owner or organization.+ pub owner: String,+ /// The GitHub repository name.+ pub repo: String,+ /// The GitHub pull request number.+ pub number: u64,+ /// The public GitHub URL for the pull request.+ pub url: String,+ /// A compact label suitable for display in the UI.+ pub display_name: String,+ /// The GitHub pull request title, when enrichment succeeds.+ pub name: Option<String>,+ /// The normalized GitHub pull request status, when enrichment succeeds.+ pub status: Option<GithubPullRequestStatus>,+ /// The number of added lines reported by GitHub, when enrichment succeeds.+ pub additions: Option<u64>,+ /// The number of deleted lines reported by GitHub, when enrichment succeeds.+ pub deletions: Option<u64>,+}++impl EnrichedGithubPullRequest {+ /// Create an unenriched response that preserves the base pull request reference.+ pub fn from_reference(reference: GithubPullRequestRef) -> Self {+ Self {+ github_key: reference.github_key,+ owner: reference.owner,+ repo: reference.repo,+ number: reference.number,+ url: reference.url,+ display_name: reference.display_name,+ name: None,+ status: None,+ additions: None,+ deletions: None,+ }+ }++ /// Create an enriched response from a base pull request reference and GitHub details.+ pub fn from_details(+ reference: GithubPullRequestRef,+ details: GithubPullRequestDetails,+ ) -> Self {+ let status = details.status();++ Self {+ github_key: reference.github_key,+ owner: reference.owner,+ repo: reference.repo,+ number: reference.number,+ url: reference.url,+ display_name: reference.display_name,+ name: Some(details.title),+ status: Some(status),+ additions: Some(details.additions),+ deletions: Some(details.deletions),+ }+ }+}++/// Request body for the authenticated pull request enrichment proxy.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct EnrichGithubPullRequestsProxyRequest {+ /// The pull requests to enrich for the authenticated user.+ pub pull_requests: Vec<GithubPullRequestRef>,+}++/// Response body for pull request enrichment.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[cfg_attr(feature = "axum", derive(utoipa::ToSchema))]+#[serde(rename_all = "camelCase")]+pub struct EnrichGithubPullRequestsResponse {+ /// Pull requests with enrichment fields populated when GitHub data was available.+ pub pull_requests: Vec<EnrichedGithubPullRequest>,+}diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rsindex a15f471955..90f2d27958 100644--- a/rust/cloud-storage/github/src/domain/models/test.rs+++ b/rust/cloud-storage/github/src/domain/models/test.rs@@ -7,6 +7,147 @@ fn test_github_key() {assert_eq!(key.to_string(), "rust-lang/rust/pull/12345");}+fn pull_request_reference() -> GithubPullRequestRef {+ GithubPullRequestRef {+ github_key: "macro/app/pull/7".to_string(),+ owner: "macro".to_string(),+ repo: "app".to_string(),+ number: 7,+ url: "https://github.com/macro/app/pull/7".to_string(),+ display_name: "macro/app#7".to_string(),+ }+}++fn pull_request_details(+ state: &str,+ merged_at: Option<chrono::DateTime<chrono::Utc>>,+) -> GithubPullRequestDetails {+ GithubPullRequestDetails {+ title: "Add pull request enrichment".to_string(),+ state: state.to_string(),+ merged_at,+ additions: 42,+ deletions: 12,+ }+}++#[test]+fn pull_request_status_maps_open_pr() {+ let details = pull_request_details("open", None);++ assert_eq!(details.status(), GithubPullRequestStatus::Open);+}++#[test]+fn pull_request_status_maps_closed_unmerged_pr() {+ let details = pull_request_details("closed", None);++ assert_eq!(details.status(), GithubPullRequestStatus::Closed);+}++#[test]+fn pull_request_status_maps_closed_merged_pr() {+ let merged_at = chrono::DateTime::parse_from_rfc3339("2026-05-25T18:54:21Z")+ .unwrap()+ .with_timezone(&chrono::Utc);+ let details = pull_request_details("closed", Some(merged_at));++ assert_eq!(details.status(), GithubPullRequestStatus::Merged);+}++#[test]+fn pull_request_proxy_request_serializes_with_only_pull_requests() {+ let reference = pull_request_reference();+ let request = EnrichGithubPullRequestsProxyRequest {+ pull_requests: vec![reference],+ };++ let request_json = serde_json::to_value(&request).unwrap();++ assert_eq!(+ request_json,+ serde_json::json!({+ "pullRequests": [+ {+ "githubKey": "macro/app/pull/7",+ "owner": "macro",+ "repo": "app",+ "number": 7,+ "url": "https://github.com/macro/app/pull/7",+ "displayName": "macro/app#7"+ }+ ]+ })+ );+ assert!(request_json.get("macroUserId").is_none());++ let decoded_request: EnrichGithubPullRequestsProxyRequest =+ serde_json::from_value(request_json).unwrap();+ assert_eq!(decoded_request, request);+}++#[test]+fn pull_request_response_serializes_with_camel_case_fields() {+ let reference = pull_request_reference();+ let response = EnrichGithubPullRequestsResponse {+ pull_requests: vec![EnrichedGithubPullRequest {+ github_key: reference.github_key,+ owner: reference.owner,+ repo: reference.repo,+ number: reference.number,+ url: reference.url,+ display_name: reference.display_name,+ name: Some("Add pull request enrichment".to_string()),+ status: Some(GithubPullRequestStatus::Merged),+ additions: Some(42),+ deletions: Some(12),+ }],+ };++ let response_json = serde_json::to_value(&response).unwrap();++ assert_eq!(+ response_json,+ serde_json::json!({+ "pullRequests": [+ {+ "githubKey": "macro/app/pull/7",+ "owner": "macro",+ "repo": "app",+ "number": 7,+ "url": "https://github.com/macro/app/pull/7",+ "displayName": "macro/app#7",+ "name": "Add pull request enrichment",+ "status": "merged",+ "additions": 42,+ "deletions": 12+ }+ ]+ })+ );++ let decoded_response: EnrichGithubPullRequestsResponse =+ serde_json::from_value(response_json).unwrap();+ assert_eq!(decoded_response, response);+}++#[test]+fn pull_request_enrichment_preserves_reference_fields() {+ let reference = pull_request_reference();+ let enriched = EnrichedGithubPullRequest::from_reference(reference.clone());++ assert_eq!(enriched.github_key, reference.github_key);+ assert_eq!(enriched.owner, reference.owner);+ assert_eq!(enriched.repo, reference.repo);+ assert_eq!(enriched.number, reference.number);+ assert_eq!(enriched.url, reference.url);+ assert_eq!(enriched.display_name, reference.display_name);+ assert_eq!(enriched.name, None);+ assert_eq!(enriched.status, None);+ assert_eq!(enriched.additions, None);+ assert_eq!(enriched.deletions, None);+}+// ---------------------------------------------------------------------------// MacroTaskId::from_short_uuid// ---------------------------------------------------------------------------diff --git a/rust/cloud-storage/github/src/domain/ports/link.rs b/rust/cloud-storage/github/src/domain/ports/link.rsindex 64add1a24e..d71e4de24b 100644--- a/rust/cloud-storage/github/src/domain/ports/link.rs+++ b/rust/cloud-storage/github/src/domain/ports/link.rs@@ -3,7 +3,8 @@use std::future::Future;use crate::domain::models::{- GithubAccessToken, GithubError, GithubExchangeTokenResponse, GithubLink, GithubUserInfo,+ EnrichedGithubPullRequest, GithubAccessToken, GithubError, GithubExchangeTokenResponse,+ GithubLink, GithubPullRequestDetails, GithubPullRequestRef, GithubUserInfo,};use macro_user_id::{lowercased::Lowercase, user_id::MacroUserId};@@ -81,6 +82,15 @@ pub trait GithubOauth: Send + Sync + 'static {&self,access_token: &str,) -> impl Future<Output = Result<GithubUserInfo, Self::Err>> + Send;++ /// Gets pull request details using the user's access token.+ fn get_pull_request_details(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ number: u64,+ ) -> impl Future<Output = Result<GithubPullRequestDetails, Self::Err>> + Send;}/// Repository for handling auth related actions.@@ -111,7 +121,7 @@ pub trait Auth: Send + Sync + 'static {&self,fusionauth_user_id: &uuid::Uuid,github_idp_id: &str,- ) -> impl Future<Output = Result<GithubAccessToken, Self::Err>>;+ ) -> impl Future<Output = Result<GithubAccessToken, Self::Err>> + Send;}/// Service interface for github link operations (OAuth and account linking).@@ -146,4 +156,11 @@ pub trait GithubLinkService: Send + Sync + 'static {&self,user_id: &MacroUserId<Lowercase<'static>>,) -> impl Future<Output = Result<(), GithubError>> + Send;++ /// Enriches GitHub pull request references with details from the GitHub API.+ fn enrich_pull_requests(+ &self,+ user_id: &MacroUserId<Lowercase<'static>>,+ pull_requests: Vec<GithubPullRequestRef>,+ ) -> impl Future<Output = Result<Vec<EnrichedGithubPullRequest>, GithubError>> + Send;}diff --git a/rust/cloud-storage/github/src/domain/service/link.rs b/rust/cloud-storage/github/src/domain/service/link.rsindex bfc04534a7..8b90aeb2db 100644--- a/rust/cloud-storage/github/src/domain/service/link.rs+++ b/rust/cloud-storage/github/src/domain/service/link.rs@@ -7,7 +7,7 @@ use macro_user_id::{};use crate::domain::{- models::{GithubError, GithubLink},+ models::{EnrichedGithubPullRequest, GithubError, GithubLink, GithubPullRequestRef},ports::{Auth, GithubLinkService, GithubOauth, GithubRepo},};@@ -65,6 +65,74 @@ impl<R: GithubRepo, U: GithubOauth, F: Auth> GithubLinkService for GithubLinkSer.map_err(|e| GithubError::Internal(e.into()))}+ #[tracing::instrument(skip(self, pull_requests), err)]+ async fn enrich_pull_requests(+ &self,+ macro_user_id: &MacroUserId<Lowercase<'static>>,+ pull_requests: Vec<GithubPullRequestRef>,+ ) -> Result<Vec<EnrichedGithubPullRequest>, GithubError> {+ if pull_requests.is_empty() {+ return Ok(Vec::new());+ }++ let link = match self.repo.get_github_link_by_user_id(macro_user_id).await {+ Ok(link) => link,+ Err(e) => {+ let e: anyhow::Error = e.into();+ if let Some(db_err) = e.downcast_ref::<sqlx::Error>()+ && matches!(db_err, sqlx::Error::RowNotFound)+ {+ return Err(GithubError::NoLinkFound);+ }++ if e.to_string().contains("no rows returned") {+ return Err(GithubError::NoLinkFound);+ }++ return Err(GithubError::Internal(e));+ }+ };++ let access_token = self+ .auth+ .retreive_access_token(&link.fusionauth_user_id, &self.config.idp_id)+ .await+ .map_err(|e| GithubError::Internal(e.into()))?;++ let mut enriched_pull_requests = Vec::with_capacity(pull_requests.len());++ for pull_request in pull_requests {+ let details = self+ .oauth+ .get_pull_request_details(+ access_token.as_str(),+ pull_request.owner.as_str(),+ pull_request.repo.as_str(),+ pull_request.number,+ )+ .await;++ let enriched_pull_request = match details {+ Ok(details) => EnrichedGithubPullRequest::from_details(pull_request, details),+ Err(e) => {+ tracing::warn!(+ error=?e,+ owner=%pull_request.owner,+ repo=%pull_request.repo,+ number=pull_request.number,+ "failed to enrich GitHub pull request"+ );++ EnrichedGithubPullRequest::from_reference(pull_request)+ }+ };++ enriched_pull_requests.push(enriched_pull_request);+ }++ Ok(enriched_pull_requests)+ }+#[tracing::instrument(skip(self), err)]async fn delete_user_link(&self,diff --git a/rust/cloud-storage/github/src/outbound/github_oauth_client.rs b/rust/cloud-storage/github/src/outbound/github_oauth_client.rsindex cd428de6ee..6d9f64be61 100644--- a/rust/cloud-storage/github/src/outbound/github_oauth_client.rs+++ b/rust/cloud-storage/github/src/outbound/github_oauth_client.rs@@ -3,7 +3,7 @@use std::time::Duration;use crate::domain::{- models::{GithubExchangeTokenResponse, GithubUserInfo},+ models::{GithubExchangeTokenResponse, GithubPullRequestDetails, GithubUserInfo},ports::GithubOauth,};@@ -180,4 +180,46 @@ impl GithubOauth for GithubOauthImpl {Ok(user_info)}++ #[tracing::instrument(skip(self, access_token), err)]+ async fn get_pull_request_details(+ &self,+ access_token: &str,+ owner: &str,+ repo: &str,+ number: u64,+ ) -> Result<GithubPullRequestDetails, Self::Err> {+ let response = self+ .client+ .get(format!(+ "https://api.github.com/repos/{owner}/{repo}/pulls/{number}"+ ))+ .header("Authorization", format!("Bearer {}", access_token))+ .header("Accept", "application/vnd.github+json")+ .header("User-Agent", "Macro-Auth-Service")+ .header("X-GitHub-Api-Version", "2022-11-28")+ .timeout(Duration::from_secs(15))+ .send()+ .await?;++ let status = response.status();++ if !status.is_success() {+ let error_body = response+ .text()+ .await+ .unwrap_or_else(|_| "unknown error".to_string());++ if status.as_u16() == 401 {+ tracing::warn!(error_body=%error_body, "GitHub token expired or invalid");+ anyhow::bail!("unauthorized access")+ }++ anyhow::bail!("failed to get pull request details {}", error_body)+ }++ let details: GithubPullRequestDetails = response.json().await?;++ Ok(details)+ }}diff --git a/rust/cloud-storage/mcp_service/src/context.rs b/rust/cloud-storage/mcp_service/src/context.rsindex 650cf711f4..ba55d0c417 100644--- a/rust/cloud-storage/mcp_service/src/context.rs+++ b/rust/cloud-storage/mcp_service/src/context.rs@@ -10,7 +10,7 @@ use comms::domain::service::ChannelServiceImpl;use comms::outbound::postgres::comms_repo::PgCommsRepo;use comms::outbound::postgres::user_repo::PgUserRepo;use documents::{- domain::{models::CloudFrontConfig, service::DocumentServiceImpl},+ domain::models::CloudFrontConfig,inbound::toolset::DocumentToolContext,outbound::{pg_document_repo::PgDocumentRepo, s3_upload_url::S3UploadUrlAdapter},};@@ -216,17 +216,18 @@ async fn build_tool_context(};let sync_service_client =SyncServiceClient::new(sync_service_auth_key.clone(), sync_service_url.clone());- let document_service = DocumentServiceImpl::new(- document_repo,+ let document_service = documents::domain::service::DocumentServiceImpl {+ repo: document_repo,cloudfront_config,- sync_service_client.clone(),- s3_upload_adapter,- NoOpTaskProperties,- NoOpConnectionService,- entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(- entity_access_management::outbound::PgRepository::new(db.clone()),- ),- );+ sync_service_client: sync_service_client.clone(),+ upload_url_service: s3_upload_adapter,+ task_properties_service: NoOpTaskProperties,+ connection_service: NoOpConnectionService,+ entity_access_management_service:+ entity_access_management::domain::service::EntityAccessManagementServiceImpl::new(+ entity_access_management::outbound::PgRepository::new(db.clone()),+ ),+ };let entity_access_service = EntityAccessServiceImpl::new(PgAccessRepository::new(db.clone()));let lexical_client_for_tools = (*lexical_client).clone();let document_tool_context = DocumentToolContext::new(