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): github soup includes_me filter (#3944)
Will Hutchinsond05389640fd7
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.tsindex df9232695a..543ac1d8b9 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequest.ts@@ -9,6 +9,7 @@ import type { EnrichedGithubPullRequestChecks } from './enrichedGithubPullRequesimport type { EnrichedGithubPullRequestComments } from './enrichedGithubPullRequestComments';import type { EnrichedGithubPullRequestDeletions } from './enrichedGithubPullRequestDeletions';import type { EnrichedGithubPullRequestName } from './enrichedGithubPullRequestName';+import type { EnrichedGithubPullRequestParticipantGithubUserIds } from './enrichedGithubPullRequestParticipantGithubUserIds';import type { EnrichedGithubPullRequestStatus } from './enrichedGithubPullRequestStatus';/**@@ -42,6 +43,10 @@ export interface EnrichedGithubPullRequest {number: number;/** The GitHub repository owner or organization. */owner: string;+ /** Stable numeric GitHub user ids (as strings) for everyone involved in the pull request.+Queried by the foreign entity `includes_me` filter, so stored metadata merges this as a+union rather than replacing it (partial write paths must not drop known participants). */+ participantGithubUserIds?: EnrichedGithubPullRequestParticipantGithubUserIds;/** The GitHub repository name. */repo: string;status?: EnrichedGithubPullRequestStatus;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestParticipantGithubUserIds.ts b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestParticipantGithubUserIds.tsnew file mode 100644index 0000000000..3883cbae7f--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/enrichedGithubPullRequestParticipantGithubUserIds.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Stable numeric GitHub user ids (as strings) for everyone involved in the pull request.+Queried by the foreign entity `includes_me` filter, so stored metadata merges this as a+union rather than replacing it (partial write paths must not drop known participants).+ */+export type EnrichedGithubPullRequestParticipantGithubUserIds = string[] | null;diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestComment.ts b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestComment.tsindex 2cee3177d2..3398439214 100644--- a/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestComment.ts+++ b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestComment.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 0.1.0*/import type { GithubPullRequestCommentAuthorAssociation } from './githubPullRequestCommentAuthorAssociation';+import type { GithubPullRequestCommentAuthorId } from './githubPullRequestCommentAuthorId';import type { GithubPullRequestCommentAuthorLogin } from './githubPullRequestCommentAuthorLogin';import type { GithubPullRequestCommentCreatedAt } from './githubPullRequestCommentCreatedAt';import type { GithubPullRequestCommentUpdatedAt } from './githubPullRequestCommentUpdatedAt';@@ -16,6 +17,11 @@ import type { GithubPullRequestCommentUrl } from './githubPullRequestCommentUrl'export interface GithubPullRequestComment {/** GitHub's relationship label for the author, when available. */authorAssociation?: GithubPullRequestCommentAuthorAssociation;+ /**+ * The stable numeric GitHub user id for the comment author, when available.+ * @minimum 0+ */+ authorId?: GithubPullRequestCommentAuthorId;/** The GitHub login for the comment author, when available. */authorLogin?: GithubPullRequestCommentAuthorLogin;/** The comment or review body text. */diff --git a/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestCommentAuthorId.ts b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestCommentAuthorId.tsnew file mode 100644index 0000000000..82cc44f054--- /dev/null+++ b/js/app/packages/service-clients/service-auth/generated/schemas/githubPullRequestCommentAuthorId.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * authentication_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * The stable numeric GitHub user id for the comment author, when available.+ * @minimum 0+ */+export type GithubPullRequestCommentAuthorId = number | null;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 61c94e88f7..3406d8b1c3 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@@ -25,6 +25,7 @@ export * from './enrichedGithubPullRequestChecks';export * from './enrichedGithubPullRequestComments';export * from './enrichedGithubPullRequestDeletions';export * from './enrichedGithubPullRequestName';+export * from './enrichedGithubPullRequestParticipantGithubUserIds';export * from './enrichedGithubPullRequestStatus';export * from './enrichGithubPullRequestsProxyRequest';export * from './enrichGithubPullRequestsResponse';@@ -47,6 +48,7 @@ export * from './githubPullRequestCheckRunStartedAt';export * from './githubPullRequestCheckRunUrl';export * from './githubPullRequestComment';export * from './githubPullRequestCommentAuthorAssociation';+export * from './githubPullRequestCommentAuthorId';export * from './githubPullRequestCommentAuthorLogin';export * from './githubPullRequestCommentCreatedAt';export * from './githubPullRequestCommentUpdatedAt';diff --git a/js/app/packages/service-clients/service-auth/openapi.json b/js/app/packages/service-clients/service-auth/openapi.jsonindex b58372890a..c6f517f8b0 100644--- a/js/app/packages/service-clients/service-auth/openapi.json+++ b/js/app/packages/service-clients/service-auth/openapi.json@@ -3502,6 +3502,13 @@"type": "string","description": "The GitHub repository owner or organization."},+ "participantGithubUserIds": {+ "type": ["array", "null"],+ "items": {+ "type": "string"+ },+ "description": "Stable numeric GitHub user ids (as strings) for everyone involved in the pull request.\nQueried by the foreign entity `includes_me` filter, so stored metadata merges this as a\nunion rather than replacing it (partial write paths must not drop known participants)."+ },"repo": {"type": "string","description": "The GitHub repository name."@@ -3728,6 +3735,12 @@"type": ["string", "null"],"description": "GitHub's relationship label for the author, when available."},+ "authorId": {+ "type": ["integer", "null"],+ "format": "int64",+ "description": "The stable numeric GitHub user id for the comment author, when available.",+ "minimum": 0+ },"authorLogin": {"type": ["string", "null"],"description": "The GitHub login for the comment author, when available."diff --git a/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.ts b/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.tsindex 6d1bca274e..6bea6ed0a2 100644--- a/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/foreignEntityFilters.ts@@ -15,4 +15,8 @@ export interface ForeignEntityFilters {foreign_entity_sources?: string[];/** Internal foreign entity record IDs to filter by. Empty to include all records. */ids?: string[];+ /** When true, only return foreign entities whose metadata lists the requesting user as a+participant (GitHub `involves:me` semantics for `github_pull_request` records). False or+absent applies no filter. Serialized in filter ASTs as the `"me"` literal. */+ includes_me?: boolean;}diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex caf00c05aa..685aca25a1 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -2101,6 +2101,10 @@"type": "string"},"description": "Internal foreign entity record IDs to filter by. Empty to include all records."+ },+ "includes_me": {+ "type": "boolean",+ "description": "When true, only return foreign entities whose metadata lists the requesting user as a\nparticipant (GitHub `involves:me` semantics for `github_pull_request` records). False or\nabsent applies no filter. Serialized in filter ASTs as the `\"me\"` literal."}}},diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.tsindex 4af467c417..a6a64604bb 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/foreignEntityFilters.ts@@ -15,4 +15,8 @@ export interface ForeignEntityFilters {foreign_entity_sources?: string[];/** Internal foreign entity record IDs to filter by. Empty to include all records. */ids?: string[];+ /** When true, only return foreign entities whose metadata lists the requesting user as a+participant (GitHub `involves:me` semantics for `github_pull_request` records). False or+absent applies no filter. Serialized in filter ASTs as the `"me"` literal. */+ includes_me?: boolean;}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex cbc02a813d..ac26d3ee1f 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -7833,6 +7833,12 @@ export const postItemsSoupBody = zod.describe('Internal foreign entity record IDs to filter by. Empty to include all records.'),+ includes_me: zod+ .boolean()+ .optional()+ .describe(+ 'When true, only return foreign entities whose metadata lists the requesting user as a\nparticipant (GitHub `involves:me` semantics for `github_pull_request` records). False or\nabsent applies no filter. Serialized in filter ASTs as the `\"me\"` literal.'+ ),}).optional().describe('Filters for foreign entity records.'),diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 4ad4aff587..0b46ce6a78 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -13729,6 +13729,10 @@"type": "string"},"description": "Internal foreign entity record IDs to filter by. Empty to include all records."+ },+ "includes_me": {+ "type": "boolean",+ "description": "When true, only return foreign entities whose metadata lists the requesting user as a\nparticipant (GitHub `involves:me` semantics for `github_pull_request` records). False or\nabsent applies no filter. Serialized in filter ASTs as the `\"me\"` literal."}}},diff --git a/rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.json b/rust/cloud-storage/.sqlx/query-e4eb2173ecfc39987f998d5075237c0b8aaf00c3eae94c06f069591f72445e14.jsonsimilarity index 71%rename from rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.jsonrename to rust/cloud-storage/.sqlx/query-e4eb2173ecfc39987f998d5075237c0b8aaf00c3eae94c06f069591f72445e14.jsonindex e34e1c8fed..0c2c26e399 100644--- a/rust/cloud-storage/.sqlx/query-1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a.json+++ b/rust/cloud-storage/.sqlx/query-e4eb2173ecfc39987f998d5075237c0b8aaf00c3eae94c06f069591f72445e14.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ",+ "query": "\n WITH source_ids AS (\n SELECT DISTINCT stored_for_id, stored_for_auth_entity\n FROM UNNEST($1::text[], $2::text[])\n AS source_rows(stored_for_id, stored_for_auth_entity)\n ),\n deduped AS (\n SELECT DISTINCT ON (fe.foreign_entity_source, fe.foreign_entity_id)\n fe.id,\n fe.foreign_entity_id,\n fe.foreign_entity_source,\n fe.metadata,\n fe.stored_for_id,\n fe.stored_for_auth_entity,\n fe.created_at,\n fe.updated_at,\n CASE $3::text\n WHEN 'created_at' THEN fe.created_at\n ELSE fe.updated_at\n END AS sort_at\n FROM foreign_entity fe\n WHERE EXISTS (\n SELECT 1\n FROM source_ids s\n WHERE s.stored_for_id = fe.stored_for_id\n AND s.stored_for_auth_entity = fe.stored_for_auth_entity\n )\n AND (\n $4::text IS NULL\n OR jsonb_path_match(\n jsonb_build_object(\n 'id', fe.id::text,\n 'foreignEntityId', fe.foreign_entity_id,\n 'foreignEntitySource', fe.foreign_entity_source\n ),\n ($4::text)::jsonpath\n )\n )\n AND (\n $8::text IS NULL\n OR (fe.metadata -> 'participantGithubUserIds') ? $8::text\n )\n ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC\n )\n SELECT\n id as \"id!: Uuid\",\n foreign_entity_id as \"foreign_entity_id!: String\",\n foreign_entity_source as \"foreign_entity_source!: String\",\n metadata as \"metadata!: serde_json::Value\",\n stored_for_id as \"stored_for_id!: String\",\n stored_for_auth_entity as \"stored_for_auth_entity!: String\",\n created_at as \"created_at!: DateTime<Utc>\",\n updated_at as \"updated_at!: DateTime<Utc>\"\n FROM deduped\n WHERE $5::timestamptz IS NULL\n OR (sort_at, id) < ($5::timestamptz, $6::uuid)\n ORDER BY sort_at DESC, id DESC\n LIMIT $7\n ","describe": {"columns": [{@@ -52,7 +52,8 @@"Text","Timestamptz","Uuid",- "Int8"+ "Int8",+ "Text"]},"nullable": [@@ -66,5 +67,5 @@false]},- "hash": "1174bf6390d826cba31f55507174a5685ec293663d6c1418b3fad3a07d26c08a"+ "hash": "e4eb2173ecfc39987f998d5075237c0b8aaf00c3eae94c06f069591f72445e14"}diff --git a/rust/cloud-storage/.sqlx/query-f9e1032b35c2a8134372f0188b76dc5ca777fdfccf87f1760b3ff0f03d4515b2.json b/rust/cloud-storage/.sqlx/query-f9e1032b35c2a8134372f0188b76dc5ca777fdfccf87f1760b3ff0f03d4515b2.jsonnew file mode 100644index 0000000000..60443a4422--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-f9e1032b35c2a8134372f0188b76dc5ca777fdfccf87f1760b3ff0f03d4515b2.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT github_user_id\n FROM github_links\n WHERE macro_id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "github_user_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "f9e1032b35c2a8134372f0188b76dc5ca777fdfccf87f1760b3ff0f03d4515b2"+}diff --git a/rust/cloud-storage/authentication_service/src/api/swagger.rs b/rust/cloud-storage/authentication_service/src/api/swagger.rsindex 7e0c455850..150a447fc5 100644--- a/rust/cloud-storage/authentication_service/src/api/swagger.rs+++ b/rust/cloud-storage/authentication_service/src/api/swagger.rs@@ -297,5 +297,10 @@ mod tests {let response_properties = &schemas["EnrichedGithubPullRequest"]["properties"];assert!(response_properties.get("comments").is_some());assert!(response_properties.get("checks").is_some());+ assert!(+ response_properties+ .get("participantGithubUserIds")+ .is_some()+ );}}diff --git a/rust/cloud-storage/documents/src/domain/service/tests.rs b/rust/cloud-storage/documents/src/domain/service/tests.rsindex 06df40f49f..5ec6166361 100644--- a/rust/cloud-storage/documents/src/domain/service/tests.rs+++ b/rust/cloud-storage/documents/src/domain/service/tests.rs@@ -257,6 +257,7 @@ impl ForeignEntityService for TestForeignEntityService {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,_source_ids: Vec<SourceId>,_limit: u32,_query: ForeignEntityListQuery,diff --git a/rust/cloud-storage/foreign_entity/src/domain/ports.rs b/rust/cloud-storage/foreign_entity/src/domain/ports.rsindex 97e0b45bbe..daef7fa531 100644--- a/rust/cloud-storage/foreign_entity/src/domain/ports.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/ports.rs@@ -41,8 +41,12 @@ pub trait ForeignEntityRepository: Send + Sync + 'static {) -> impl Future<Output = Result<Vec<ForeignEntity>, Self::Err>> + Send;/// List foreign entities visible through the supplied source identifiers.+ ///+ /// `requesting_user` is the macro user id used to resolve participant filters such as+ /// [`ForeignEntityLiteral::IncludesMe`]; when `None`, participant filters match nothing.fn get_foreign_entities_for_user(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -101,8 +105,12 @@ pub trait ForeignEntityService: Send + Sync + 'static {) -> impl Future<Output = Result<Vec<ForeignEntity>, ForeignEntityError>> + Send;/// List foreign entities visible through the supplied source identifiers.+ ///+ /// `requesting_user` is the macro user id used to resolve participant filters such as+ /// [`ForeignEntityLiteral::IncludesMe`]; when `None`, participant filters match nothing.fn get_foreign_entities_for_user(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,diff --git a/rust/cloud-storage/foreign_entity/src/domain/service.rs b/rust/cloud-storage/foreign_entity/src/domain/service.rsindex eefc8e9dc6..61c5aae569 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service.rs@@ -82,6 +82,7 @@ where#[tracing::instrument(err, skip(self, source_ids, query))]async fn get_foreign_entities_for_user(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -95,7 +96,7 @@ where}self.repo- .get_foreign_entities_for_user(source_ids, limit, query)+ .get_foreign_entities_for_user(requesting_user, source_ids, limit, query).await.map_err(|error| ForeignEntityError::Internal(error.into()))}diff --git a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rsindex 35c6e65f37..a147c091a5 100644--- a/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/domain/service/tests.rs@@ -80,6 +80,7 @@ impl ForeignEntityRepository for FakeForeignEntityRepository {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -364,6 +365,7 @@ async fn get_foreign_entities_for_user_returns_matching_sources() {let service = ForeignEntityServiceImpl::new(repo);let entities = service.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]"),SourceId::new("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "team"),@@ -388,7 +390,12 @@ async fn get_foreign_entities_for_user_empty_sources_returns_empty_without_repo_let service = ForeignEntityServiceImpl::new(repo.clone());let entities = service- .get_foreign_entities_for_user(Vec::new(), 10, listing_query(SimpleSortMethod::UpdatedAt))+ .get_foreign_entities_for_user(+ None,+ Vec::new(),+ 10,+ listing_query(SimpleSortMethod::UpdatedAt),+ ).await.expect("empty source list should return an empty listing");@@ -405,6 +412,7 @@ async fn get_foreign_entities_for_user_forwards_limit_and_query() {service.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],37,Query::Cursor(models_pagination::Cursor {@@ -440,6 +448,7 @@ async fn get_foreign_entities_for_user_maps_repo_errors_to_internal() {let error = service.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],10,listing_query(SimpleSortMethod::UpdatedAt),diff --git a/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rsindex fe0d03909e..f594657d5b 100644--- a/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/inbound/axum_router/tests.rs@@ -111,6 +111,7 @@ impl ForeignEntityService for StubForeignEntityService {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,_source_ids: Vec<SourceId>,_limit: u32,_query: ForeignEntityListQuery,diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rsindex 4019b26e7b..5b9b0d28ba 100644--- a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo.rs@@ -5,7 +5,7 @@ mod tests;use chrono::{DateTime, Utc};use filter_ast::Expr;-use item_filters::ast::{LiteralTree, foreign_entity::ForeignEntityLiteral};+use item_filters::ast::foreign_entity::ForeignEntityLiteral;use models_pagination::SimpleSortMethod;use sqlx::PgPool;use uuid::Uuid;@@ -18,6 +18,7 @@ struct ForeignEntityBatchQuery<'a> {source_auth_entities: &'a [String],sort_method: SimpleSortMethod,filter_jsonpath: Option<&'a str>,+ participant_github_user_id: Option<&'a str>,cursor_id: Option<Uuid>,cursor_value: Option<DateTime<Utc>>,limit: i64,@@ -30,8 +31,46 @@ fn source_id_parts(source_ids: &[SourceId]) -> (Vec<String>, Vec<String>) {.unzip()}-fn foreign_entity_filter_jsonpath(filter: &LiteralTree<ForeignEntityLiteral>) -> Option<String> {- filter.as_deref().map(foreign_entity_expr_jsonpath)+/// Marker error for filters that place [`ForeignEntityLiteral::IncludesMe`] somewhere it cannot+/// be hoisted into the dedicated SQL predicate (under `Or`/`Not`).+struct UnsupportedIncludesMe;++fn contains_includes_me(expr: &Expr<ForeignEntityLiteral>) -> bool {+ match expr {+ Expr::And(left, right) | Expr::Or(left, right) => {+ contains_includes_me(left) || contains_includes_me(right)+ }+ Expr::Not(inner) => contains_includes_me(inner),+ Expr::Literal(literal) => matches!(literal, ForeignEntityLiteral::IncludesMe),+ }+}++/// Strip [`ForeignEntityLiteral::IncludesMe`] literals off the top-level AND spine of a filter+/// tree, returning the flag and the jsonpath for the residual filter. The literal cannot be+/// expressed in the jsonpath (it needs the indexed metadata containment predicate), so any+/// occurrence under `Or`/`Not` is an error.+fn extract_includes_me(+ expr: &Expr<ForeignEntityLiteral>,+) -> Result<(bool, Option<String>), UnsupportedIncludesMe> {+ match expr {+ Expr::And(left, right) => {+ let (left_me, left_jsonpath) = extract_includes_me(left)?;+ let (right_me, right_jsonpath) = extract_includes_me(right)?;+ let jsonpath = match (left_jsonpath, right_jsonpath) {+ (Some(left), Some(right)) => Some(format!("({left} && {right})")),+ (left, right) => left.or(right),+ };+ Ok((left_me || right_me, jsonpath))+ }+ Expr::Literal(ForeignEntityLiteral::IncludesMe) => Ok((true, None)),+ other => {+ if contains_includes_me(other) {+ Err(UnsupportedIncludesMe)+ } else {+ Ok((false, Some(foreign_entity_expr_jsonpath(other))))+ }+ }+ }}fn foreign_entity_expr_jsonpath(expr: &Expr<ForeignEntityLiteral>) -> String {@@ -58,6 +97,9 @@ fn foreign_entity_literal_jsonpath(literal: &ForeignEntityLiteral) -> String {ForeignEntityLiteral::ForeignEntitySource(source) => {jsonpath_text_eq("foreignEntitySource", source)}+ // IncludesMe is hoisted into a dedicated SQL predicate by extract_includes_me and never+ // reaches the jsonpath; if one slips through, match nothing rather than everything.+ ForeignEntityLiteral::IncludesMe => "(1 == 0)".to_string(),}}@@ -88,6 +130,7 @@ impl PgForeignEntityRepo {source_auth_entities,sort_method,filter_jsonpath,+ participant_github_user_id,cursor_id,cursor_value,limit,@@ -134,6 +177,10 @@ impl PgForeignEntityRepo {($4::text)::jsonpath))+ AND (+ $8::text IS NULL+ OR (fe.metadata -> 'participantGithubUserIds') ? $8::text+ )ORDER BY fe.foreign_entity_source, fe.foreign_entity_id, sort_at DESC, fe.id DESC)SELECT@@ -158,10 +205,27 @@ impl PgForeignEntityRepo {cursor_value,cursor_id,limit,+ participant_github_user_id,).fetch_all(&self.pool).await}++ async fn github_user_id_for_macro_user(+ &self,+ macro_user_id: &str,+ ) -> Result<Option<String>, sqlx::Error> {+ sqlx::query_scalar!(+ r#"+ SELECT github_user_id+ FROM github_links+ WHERE macro_id = $1+ "#,+ macro_user_id,+ )+ .fetch_optional(&self.pool)+ .await+ }}impl ForeignEntityRepository for PgForeignEntityRepo {@@ -224,6 +288,7 @@ impl ForeignEntityRepository for PgForeignEntityRepo {#[tracing::instrument(err, skip(self, source_ids, query))]async fn get_foreign_entities_for_user(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -232,8 +297,35 @@ impl ForeignEntityRepository for PgForeignEntityRepo {return Ok(Vec::new());}+ let (includes_me, filter_jsonpath) = match query+ .filter()+ .as_deref()+ .map(extract_includes_me)+ .transpose()+ {+ Ok(split) => split.unwrap_or((false, None)),+ Err(UnsupportedIncludesMe) => {+ tracing::warn!(+ "IncludesMe under Or/Not in a foreign entity filter is unsupported; returning no results"+ );+ return Ok(Vec::new());+ }+ };++ let participant_github_user_id = if includes_me {+ let Some(requesting_user) = requesting_user else {+ return Ok(Vec::new());+ };+ match self.github_user_id_for_macro_user(&requesting_user).await? {+ Some(github_user_id) => Some(github_user_id),+ // No linked GitHub identity: the user participates in nothing.+ None => return Ok(Vec::new()),+ }+ } else {+ None+ };+let (source_ids, source_auth_entities) = source_id_parts(&source_ids);- let filter_jsonpath = foreign_entity_filter_jsonpath(query.filter());let (cursor_id, cursor_value) = query.vals();self.get_foreign_entities_for_user_batch(ForeignEntityBatchQuery {@@ -241,6 +333,7 @@ impl ForeignEntityRepository for PgForeignEntityRepo {source_auth_entities: &source_auth_entities,sort_method: *query.sort_method(),filter_jsonpath: filter_jsonpath.as_deref(),+ participant_github_user_id: participant_github_user_id.as_deref(),cursor_id: cursor_id.copied(),cursor_value: cursor_value.copied(),limit: limit as i64,diff --git a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rsindex 0d4a55ee45..f5204bcdc8 100644--- a/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs+++ b/rust/cloud-storage/foreign_entity/src/outbound/pg_foreign_entity_repo/tests.rs@@ -245,6 +245,7 @@ async fn get_for_user_returns_matching_user_and_team_sources(pool: PgPool) {let entities = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]"),SourceId::team(team_id),@@ -276,7 +277,12 @@ async fn get_for_user_empty_sources_returns_empty(pool: PgPool) {.await;let entities = repo- .get_foreign_entities_for_user(Vec::new(), 10, list_query(SimpleSortMethod::UpdatedAt))+ .get_foreign_entities_for_user(+ None,+ Vec::new(),+ 10,+ list_query(SimpleSortMethod::UpdatedAt),+ ).await.expect("empty source list should succeed");@@ -324,6 +330,7 @@ async fn get_for_user_dedupes_duplicate_source_grants(pool: PgPool) {let entities = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]"),SourceId::team(team_id),@@ -393,6 +400,7 @@ async fn get_for_user_paginates_by_created_at(pool: PgPool) {let first_page = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],2,list_query(SimpleSortMethod::CreatedAt),@@ -401,6 +409,7 @@ async fn get_for_user_paginates_by_created_at(pool: PgPool) {.expect("first created_at page should be fetched");let second_page = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],2,cursor_query(&first_page[1], SimpleSortMethod::CreatedAt),@@ -467,6 +476,7 @@ async fn get_for_user_paginates_by_updated_at(pool: PgPool) {let first_page = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],2,list_query(SimpleSortMethod::UpdatedAt),@@ -475,6 +485,7 @@ async fn get_for_user_paginates_by_updated_at(pool: PgPool) {.expect("first updated_at page should be fetched");let second_page = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],2,cursor_query(&first_page[1], SimpleSortMethod::UpdatedAt),@@ -511,6 +522,7 @@ async fn get_for_user_applies_foreign_entity_filters(pool: PgPool) {)));let source_matches = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],10,filter_query(source_filter),@@ -523,6 +535,7 @@ async fn get_for_user_applies_foreign_entity_filters(pool: PgPool) {))));let not_linear_matches = repo.get_foreign_entities_for_user(+ None,vec![SourceId::user("macro|[email protected]")],10,filter_query(not_linear_filter),@@ -534,6 +547,198 @@ async fn get_for_user_applies_foreign_entity_filters(pool: PgPool) {assert_eq!(not_linear_matches, vec![github]);}+async fn insert_pr_with_participants(+ repo: &PgForeignEntityRepo,+ foreign_entity_id: &str,+ stored_for_id: &str,+ participant_github_user_ids: Option<&[&str]>,+) -> ForeignEntity {+ let mut metadata = json!({ "displayName": foreign_entity_id });+ if let Some(participants) = participant_github_user_ids {+ metadata["participantGithubUserIds"] = json!(participants);+ }++ repo.create_foreign_entity(+ Uuid::now_v7(),+ CreateForeignEntity {+ foreign_entity_id: foreign_entity_id.into(),+ foreign_entity_source: "github_pull_request".into(),+ metadata,+ stored_for_id: stored_for_id.into(),+ stored_for_auth_entity: "user".into(),+ },+ )+ .await+ .expect("pull request foreign entity should be inserted")+}++async fn insert_github_link(pool: &PgPool, macro_id: &str, github_user_id: &str) {+ let macro_user_id = Uuid::now_v7();+ let email = format!("{macro_user_id}@example.com");++ sqlx::query(+ r#"+ INSERT INTO public.macro_user (id, username, email, stripe_customer_id)+ VALUES ($1, $2, $3, $4)+ "#,+ )+ .bind(macro_user_id)+ .bind(macro_id)+ .bind(&email)+ .bind(format!("cus_{macro_user_id}"))+ .execute(pool)+ .await+ .expect("macro_user row should be inserted");++ sqlx::query(+ r#"+ INSERT INTO public."User" (id, email, macro_user_id)+ VALUES ($1, $2, $3)+ "#,+ )+ .bind(macro_id)+ .bind(&email)+ .bind(macro_user_id)+ .execute(pool)+ .await+ .expect("User row should be inserted");++ sqlx::query(+ r#"+ INSERT INTO github_links (id, macro_id, fusionauth_user_id, github_username, github_user_id)+ VALUES ($1, $2, $3, $4, $5)+ "#,+ )+ .bind(Uuid::now_v7())+ .bind(macro_id)+ .bind(Uuid::now_v7())+ .bind(format!("gh-{github_user_id}"))+ .bind(github_user_id)+ .execute(pool)+ .await+ .expect("github_links row should be inserted");+}++fn includes_me_filter() -> LiteralTree<ForeignEntityLiteral> {+ Some(Arc::new(Expr::val(ForeignEntityLiteral::IncludesMe)))+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_includes_me_filters_to_participant_metadata(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let macro_id = "macro|[email protected]";+ insert_github_link(&pool, macro_id, "42").await;++ let involved =+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["7", "42"])).await;+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;+ insert_pr_with_participants(&repo, "legacy-pr", macro_id, None).await;++ let entities = repo+ .get_foreign_entities_for_user(+ Some(macro_id.to_string()),+ vec![SourceId::user(macro_id)],+ 10,+ filter_query(includes_me_filter()),+ )+ .await+ .expect("includes_me filter should be applied");++ assert_eq!(entities, vec![involved]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_includes_me_without_github_link_returns_empty(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool);+ let macro_id = "macro|[email protected]";+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;++ let entities = repo+ .get_foreign_entities_for_user(+ Some(macro_id.to_string()),+ vec![SourceId::user(macro_id)],+ 10,+ filter_query(includes_me_filter()),+ )+ .await+ .expect("includes_me without a github link should succeed");++ assert!(entities.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_includes_me_without_requesting_user_returns_empty(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let macro_id = "macro|[email protected]";+ insert_github_link(&pool, macro_id, "42").await;+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;++ let entities = repo+ .get_foreign_entities_for_user(+ None,+ vec![SourceId::user(macro_id)],+ 10,+ filter_query(includes_me_filter()),+ )+ .await+ .expect("includes_me without a requesting user should succeed");++ assert!(entities.is_empty());+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_includes_me_composes_with_other_filters(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let macro_id = "macro|[email protected]";+ insert_github_link(&pool, macro_id, "42").await;++ let involved = insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;+ insert_foreign_entity_for_source(&repo, "linear-issue", "linear_issue", macro_id, "user").await;++ let filter = Some(Arc::new(Expr::and(+ Expr::val(ForeignEntityLiteral::ForeignEntitySource(+ "github_pull_request".to_string(),+ )),+ Expr::val(ForeignEntityLiteral::IncludesMe),+ )));+ let entities = repo+ .get_foreign_entities_for_user(+ Some(macro_id.to_string()),+ vec![SourceId::user(macro_id)],+ 10,+ filter_query(filter),+ )+ .await+ .expect("includes_me composed with a source filter should be applied");++ assert_eq!(entities, vec![involved]);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn get_for_user_includes_me_under_not_fails_closed(pool: PgPool) {+ let repo = PgForeignEntityRepo::new(pool.clone());+ let macro_id = "macro|[email protected]";+ insert_github_link(&pool, macro_id, "42").await;+ insert_pr_with_participants(&repo, "involved-pr", macro_id, Some(&["42"])).await;+ insert_pr_with_participants(&repo, "other-pr", macro_id, Some(&["7"])).await;++ let filter = Some(Arc::new(Expr::is_not(Expr::val(+ ForeignEntityLiteral::IncludesMe,+ ))));+ let entities = repo+ .get_foreign_entities_for_user(+ Some(macro_id.to_string()),+ vec![SourceId::user(macro_id)],+ 10,+ filter_query(filter),+ )+ .await+ .expect("unsupported includes_me placement should fail closed");++ assert!(entities.is_empty());+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]async fn patch_updates_selected_fields_preserves_others_and_refreshes_updated_at(pool: PgPool) {let repo = PgForeignEntityRepo::new(pool.clone());diff --git a/rust/cloud-storage/github/src/domain/models/pull_request.rs b/rust/cloud-storage/github/src/domain/models/pull_request.rsindex 2a3fdbdeb6..d49fbc64f7 100644--- a/rust/cloud-storage/github/src/domain/models/pull_request.rs+++ b/rust/cloud-storage/github/src/domain/models/pull_request.rs@@ -100,6 +100,9 @@ pub struct GithubPullRequestComment {pub body: String,/// The GitHub login for the comment author, when available.pub author_login: Option<String>,+ /// The stable numeric GitHub user id for the comment author, when available.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub author_id: Option<u64>,/// GitHub's relationship label for the author, when available.pub author_association: Option<String>,/// The public GitHub URL for the comment or review, when available.@@ -161,6 +164,14 @@ pub struct GithubPullRequestDetails {deserialize_with = "deserialize_optional_array")]pub checks: Option<Vec<GithubPullRequestCheckRun>>,+ /// Stable numeric GitHub user ids (as strings) for everyone involved in the pull request:+ /// author, requested reviewers, reviewers, assignees, and commenters.+ #[serde(+ default,+ skip_serializing_if = "Option::is_none",+ deserialize_with = "deserialize_optional_array"+ )]+ pub participant_github_user_ids: Option<Vec<String>>,}impl GithubPullRequestDetails {@@ -201,6 +212,11 @@ pub struct EnrichedGithubPullRequest {/// Check runs collected from the pull request head commit, when enrichment includes them.#[serde(default, skip_serializing_if = "Option::is_none")]pub checks: Option<Vec<GithubPullRequestCheckRun>>,+ /// Stable numeric GitHub user ids (as strings) for everyone involved in the pull request.+ /// Queried by the foreign entity `includes_me` filter, so stored metadata merges this as a+ /// union rather than replacing it (partial write paths must not drop known participants).+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub participant_github_user_ids: Option<Vec<String>>,}impl EnrichedGithubPullRequest {@@ -219,6 +235,7 @@ impl EnrichedGithubPullRequest {deletions: None,comments: None,checks: None,+ participant_github_user_ids: None,}}@@ -242,6 +259,7 @@ impl EnrichedGithubPullRequest {deletions: Some(details.deletions),comments: details.comments,checks: details.checks,+ participant_github_user_ids: details.participant_github_user_ids,}}@@ -273,6 +291,33 @@ impl EnrichedGithubPullRequest {}}+ // Participants are unioned rather than carried forward or replaced: write paths produce+ // partial sets (a webhook fallback knows the author/reviewers/assignees but not the+ // commenters), so replacing would drop participants a richer earlier write discovered.+ const PARTICIPANTS_FIELD: &str = "participantGithubUserIds";+ let mut participants: std::collections::BTreeSet<String> = [+ existing_object.get(PARTICIPANTS_FIELD),+ metadata_object.get(PARTICIPANTS_FIELD),+ ]+ .into_iter()+ .flatten()+ .filter_map(|value| value.as_array())+ .flatten()+ .filter_map(|value| value.as_str().map(str::to_string))+ .collect();++ if !participants.is_empty() {+ metadata_object.insert(+ PARTICIPANTS_FIELD.to_string(),+ serde_json::Value::Array(+ std::mem::take(&mut participants)+ .into_iter()+ .map(serde_json::Value::String)+ .collect(),+ ),+ );+ }+Ok(metadata)}}diff --git a/rust/cloud-storage/github/src/domain/models/test.rs b/rust/cloud-storage/github/src/domain/models/test.rsindex 7d44d0834e..3bef48ff45 100644--- a/rust/cloud-storage/github/src/domain/models/test.rs+++ b/rust/cloud-storage/github/src/domain/models/test.rs@@ -30,6 +30,7 @@ fn pull_request_details(deletions: 12,comments: None,checks: None,+ participant_github_user_ids: None,}}@@ -43,6 +44,7 @@ fn pull_request_comment() -> GithubPullRequestComment {GithubPullRequestComment {id: 101,body: "Looks good to me".to_string(),+ author_id: None,author_login: Some("octocat".to_string()),author_association: Some("MEMBER".to_string()),url: Some("https://github.com/macro/app/pull/7#issuecomment-101".to_string()),@@ -151,6 +153,7 @@ fn pull_request_response_serializes_with_camel_case_fields() {deletions: Some(12),comments: Some(vec![pull_request_comment()]),checks: Some(vec![pull_request_check_run()]),+ participant_github_user_ids: None,}],};@@ -267,6 +270,7 @@ fn pull_request_enrichment_copies_details_fields() {deletions: 12,comments: Some(comments.clone()),checks: Some(checks.clone()),+ participant_github_user_ids: Some(vec!["42".to_string(), "583231".to_string()]),};let enriched = EnrichedGithubPullRequest::from_details(reference.clone(), details);@@ -286,6 +290,10 @@ fn pull_request_enrichment_copies_details_fields() {assert_eq!(enriched.deletions, Some(12));assert_eq!(enriched.comments, Some(comments));assert_eq!(enriched.checks, Some(checks));+ assert_eq!(+ enriched.participant_github_user_ids,+ Some(vec!["42".to_string(), "583231".to_string()])+ );}#[test]@@ -304,6 +312,7 @@ fn pull_request_foreign_entity_metadata_serializes_enriched_pull_request() {deletions: 12,comments: Some(vec![pull_request_comment()]),checks: Some(vec![pull_request_check_run()]),+ participant_github_user_ids: None,};let enriched = EnrichedGithubPullRequest::from_details(reference, details);@@ -415,6 +424,7 @@ fn pull_request_foreign_entity_metadata_keeps_fresh_arrays() {deletions: 12,comments: Some(comments.clone()),checks: Some(checks.clone()),+ participant_github_user_ids: None,};let enriched = EnrichedGithubPullRequest::from_details(pull_request_reference(), details);let existing_metadata = serde_json::json!({@@ -432,6 +442,45 @@ fn pull_request_foreign_entity_metadata_keeps_fresh_arrays() {assert_eq!(metadata.get("checks"), Some(&fresh_checks));}+#[test]+fn pull_request_foreign_entity_metadata_unions_participants_with_existing() {+ let mut details = pull_request_details("open", None);+ details.participant_github_user_ids = Some(vec!["42".to_string(), "99".to_string()]);+ let enriched = EnrichedGithubPullRequest::from_details(pull_request_reference(), details);+ let existing_metadata = serde_json::json!({+ "participantGithubUserIds": ["7", "42"]+ });++ let metadata = enriched+ .foreign_entity_metadata(Some(&existing_metadata))+ .unwrap();++ assert_eq!(+ metadata.get("participantGithubUserIds"),+ Some(&serde_json::json!(["42", "7", "99"]))+ );+}++#[test]+fn pull_request_foreign_entity_metadata_carries_existing_participants_forward() {+ let enriched = EnrichedGithubPullRequest::from_details(+ pull_request_reference(),+ pull_request_details("open", None),+ );+ let existing_metadata = serde_json::json!({+ "participantGithubUserIds": ["7"]+ });++ let metadata = enriched+ .foreign_entity_metadata(Some(&existing_metadata))+ .unwrap();++ assert_eq!(+ metadata.get("participantGithubUserIds"),+ Some(&serde_json::json!(["7"]))+ );+}+// ---------------------------------------------------------------------------// MacroTaskId::from_short_uuid// ---------------------------------------------------------------------------diff --git a/rust/cloud-storage/github/src/domain/service/link_test.rs b/rust/cloud-storage/github/src/domain/service/link_test.rsindex 17590ba43c..6fb6dffd53 100644--- a/rust/cloud-storage/github/src/domain/service/link_test.rs+++ b/rust/cloud-storage/github/src/domain/service/link_test.rs@@ -132,6 +132,7 @@ fn default_pull_request_details() -> GithubPullRequestDetails {deletions: 3,comments: None,checks: None,+ participant_github_user_ids: None,}}@@ -360,6 +361,7 @@ impl ForeignEntityService for StubForeignEntityService {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,_source_ids: Vec<SourceId>,_limit: u32,_query: ForeignEntityListQuery,diff --git a/rust/cloud-storage/github/src/domain/service/sync/mod.rs b/rust/cloud-storage/github/src/domain/service/sync/mod.rsindex aa6bd42a2c..1fa688bef4 100644--- a/rust/cloud-storage/github/src/domain/service/sync/mod.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/mod.rs@@ -222,9 +222,38 @@ impl<.and_then(|value| value.as_u64()),comments: None,checks: None,+ participant_github_user_ids: Self::participant_ids_from_payload(pull_request),})}+ /// Collect the stable numeric ids of the author, requested reviewers, and assignees from a+ /// webhook `pull_request` payload. Commenters are not present in the payload; they are+ /// unioned in from existing metadata or a live fetch.+ fn participant_ids_from_payload(+ pull_request: Option<&serde_json::Value>,+ ) -> Option<Vec<String>> {+ let pull_request = pull_request?;+ let mut ids = std::collections::BTreeSet::new();++ ids.extend(+ pull_request+ .get("user")+ .and_then(|user| user.get("id"))+ .and_then(|value| value.as_u64()),+ );+ for field in ["requested_reviewers", "assignees"] {+ if let Some(users) = pull_request.get(field).and_then(|value| value.as_array()) {+ ids.extend(+ users+ .iter()+ .filter_map(|user| user.get("id").and_then(|value| value.as_u64())),+ );+ }+ }++ (!ids.is_empty()).then(|| ids.iter().map(u64::to_string).collect())+ }+/// Build pull request metadata from live GitHub details when possible,/// falling back to the webhook payload if the live request fails.async fn enriched_pull_request_metadata(@@ -291,6 +320,9 @@ impl<deletions: Some(details.deletions),comments: details.comments,checks: details.checks,+ participant_github_user_ids: details+ .participant_github_user_ids+ .or(fallback.participant_github_user_ids),}}diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex bf0fbde229..117470a197 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -741,6 +741,7 @@ impl ForeignEntityService for StubForeignEntityService {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,_query: ForeignEntityListQuery,@@ -967,6 +968,7 @@ fn expected_pull_request_metadata(deletions,comments: None,checks: None,+ participant_github_user_ids: None,}).unwrap()}@@ -1069,6 +1071,7 @@ fn backfilled_pull_request(title: &str) -> EnrichedGithubPullRequest {deletions: None,comments: None,checks: None,+ participant_github_user_ids: None,}}@@ -1088,6 +1091,7 @@ fn expected_pull_request_metadata_from_details(deletions: Some(details.deletions),comments: details.comments.clone(),checks: details.checks.clone(),+ participant_github_user_ids: details.participant_github_user_ids.clone(),}).unwrap()}@@ -1096,6 +1100,7 @@ fn pull_request_comment(id: u64, body: &str, source: &str) -> GithubPullRequestCGithubPullRequestComment {id,body: body.to_string(),+ author_id: None,author_login: Some("octocat".to_string()),author_association: Some("MEMBER".to_string()),url: Some(format!(@@ -1134,6 +1139,7 @@ fn pull_request_details(deletions,comments,checks,+ participant_github_user_ids: None,}}@@ -2350,6 +2356,47 @@ async fn pr_closed_upserts_merged_pull_request_metadata() {);}+#[tokio::test]+async fn pr_event_extracts_participants_from_webhook_payload() {+ let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();+ let event = ValidatedGithubWebhookEvent::new(+ "pull_request".to_string(),+ serde_json::json!({+ "action": "opened",+ "pull_request": {+ "number": 42,+ "title": "fixes MACRO-2BuyvtY3aeEvHx4uG8iD51",+ "body": null,+ "head": { "ref": "feature/some-branch" },+ "state": "open",+ "merged": false,+ "additions": 10,+ "deletions": 2,+ "user": { "login": "author", "id": 7 },+ "requested_reviewers": [+ { "login": "reviewer", "id": 42 },+ { "login": "author", "id": 7 }+ ],+ "assignees": [{ "login": "assignee", "id": 99 }]+ },+ "repository": {+ "name": "my-repo",+ "owner": { "login": "my-org" }+ },+ "installation": { "id": 12345 }+ }),+ );++ service.process_webhook_event(&event).await.unwrap();++ let foreign_entities = foreign_entity_service.foreign_entities();+ assert_eq!(foreign_entities.len(), 1);+ assert_eq!(+ foreign_entities[0].metadata.get("participantGithubUserIds"),+ Some(&serde_json::json!(["7", "42", "99"]))+ );+}+#[tokio::test]async fn pr_event_without_valid_tasks_still_upserts_foreign_entity() {let (service, foreign_entity_service) = make_sync_service_with_foreign_entity_service();diff --git a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rsindex eed0a600d7..9ee9024a36 100644--- a/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs+++ b/rust/cloud-storage/github/src/outbound/pull_request_metadata.rs@@ -1,5 +1,6 @@//! Shared GitHub pull request metadata fetcher.+use std::collections::BTreeSet;use std::time::Duration;use serde::de::DeserializeOwned;@@ -23,7 +24,7 @@ pub(crate) async fn fetch_pull_request_metadata(number: u64,) -> Result<GithubPullRequestDetails, anyhow::Error> {let pull_request = fetch_pull_request(client, access_token, owner, repo, number).await?;- let comments = fetch_comments(client, access_token, owner, repo, number).await;+ let discussion = fetch_comments(client, access_token, owner, repo, number).await;let checks = fetch_check_runs(client,access_token,@@ -33,6 +34,16 @@ pub(crate) async fn fetch_pull_request_metadata().await;+ let mut participant_ids = pull_request.participant_ids();+ let comments = discussion.map(|discussion| {+ participant_ids.extend(discussion.participant_ids);+ discussion.comments+ });+ // A failed comments fetch still yields the partial author/reviewer/assignee set; stored+ // metadata merges participants as a union, so partial sets are safe.+ let participant_github_user_ids =+ (!participant_ids.is_empty()).then(|| participant_ids.iter().map(u64::to_string).collect());+Ok(GithubPullRequestDetails {title: pull_request.title,state: pull_request.state,@@ -41,6 +52,7 @@ pub(crate) async fn fetch_pull_request_metadata(deletions: pull_request.deletions,comments,checks,+ participant_github_user_ids,})}@@ -134,6 +146,11 @@ struct GithubOpenPullRequestResponse {number: u64,title: String,html_url: String,+ user: Option<GithubUserResponse>,+ #[serde(default)]+ requested_reviewers: Vec<GithubUserResponse>,+ #[serde(default)]+ assignees: Vec<GithubUserResponse>,}#[derive(Debug, serde::Deserialize)]@@ -144,6 +161,35 @@ struct GithubPullRequestResponse {additions: u64,deletions: u64,head: GithubPullRequestHeadResponse,+ user: Option<GithubUserResponse>,+ #[serde(default)]+ requested_reviewers: Vec<GithubUserResponse>,+ #[serde(default)]+ assignees: Vec<GithubUserResponse>,+}++impl GithubPullRequestResponse {+ fn participant_ids(&self) -> BTreeSet<u64> {+ structural_participant_ids(+ self.user.as_ref(),+ &self.requested_reviewers,+ &self.assignees,+ )+ }+}++/// Collect the stable numeric ids of a pull request's author, requested reviewers, and assignees.+fn structural_participant_ids(+ user: Option<&GithubUserResponse>,+ requested_reviewers: &[GithubUserResponse],+ assignees: &[GithubUserResponse],+) -> BTreeSet<u64> {+ user.iter()+ .copied()+ .chain(requested_reviewers)+ .chain(assignees)+ .filter_map(|user| user.id)+ .collect()}#[derive(Debug, serde::Deserialize)]@@ -154,6 +200,7 @@ struct GithubPullRequestHeadResponse {#[derive(Debug, serde::Deserialize)]struct GithubUserResponse {login: Option<String>,+ id: Option<u64>,}#[derive(Debug, serde::Deserialize)]@@ -221,19 +268,35 @@ async fn fetch_pull_request(response.json().await.map_err(Into::into)}+/// The comments collected for a pull request plus every discussion author's stable numeric id.+///+/// The ids are collected separately because comment conversion drops some authors (reviews with+/// an empty body, such as a plain approval, never become comments).+struct FetchedDiscussion {+ comments: Vec<GithubPullRequestComment>,+ participant_ids: BTreeSet<u64>,+}+async fn fetch_comments(client: &reqwest::Client,access_token: &str,owner: &str,repo: &str,number: u64,-) -> Option<Vec<GithubPullRequestComment>> {- let mut comments = fetch_issue_comments(client, access_token, owner, repo, number).await?;+) -> Option<FetchedDiscussion> {+ let mut discussion = fetch_issue_comments(client, access_token, owner, repo, number).await?;++ let review_comments = fetch_review_comments(client, access_token, owner, repo, number).await?;+ discussion.comments.extend(review_comments.comments);+ discussion+ .participant_ids+ .extend(review_comments.participant_ids);- comments.extend(fetch_review_comments(client, access_token, owner, repo, number).await?);- comments.extend(fetch_reviews(client, access_token, owner, repo, number).await?);+ let reviews = fetch_reviews(client, access_token, owner, repo, number).await?;+ discussion.comments.extend(reviews.comments);+ discussion.participant_ids.extend(reviews.participant_ids);- Some(comments)+ Some(discussion)}async fn fetch_issue_comments(@@ -242,7 +305,7 @@ async fn fetch_issue_comments(owner: &str,repo: &str,number: u64,-) -> Option<Vec<GithubPullRequestComment>> {+) -> Option<FetchedDiscussion> {match fetch_paginated_github_items(client,access_token,@@ -256,12 +319,13 @@ async fn fetch_issue_comments().await{- Ok(comments) => Some(- comments+ Ok(comments) => Some(FetchedDiscussion {+ participant_ids: author_ids(&comments, |comment| comment.user.as_ref()),+ comments: comments.into_iter().map(|comment| comment.into_pull_request_comment("issue_comment")).collect(),- ),+ }),Err(error) => {tracing::warn!(error=?error,@@ -281,7 +345,7 @@ async fn fetch_review_comments(owner: &str,repo: &str,number: u64,-) -> Option<Vec<GithubPullRequestComment>> {+) -> Option<FetchedDiscussion> {match fetch_paginated_github_items(client,access_token,@@ -295,12 +359,13 @@ async fn fetch_review_comments().await{- Ok(comments) => Some(- comments+ Ok(comments) => Some(FetchedDiscussion {+ participant_ids: author_ids(&comments, |comment| comment.user.as_ref()),+ comments: comments.into_iter().map(|comment| comment.into_pull_request_comment("review_comment")).collect(),- ),+ }),Err(error) => {tracing::warn!(error=?error,@@ -320,7 +385,7 @@ async fn fetch_reviews(owner: &str,repo: &str,number: u64,-) -> Option<Vec<GithubPullRequestComment>> {+) -> Option<FetchedDiscussion> {match fetch_paginated_github_items(client,access_token,@@ -334,12 +399,15 @@ async fn fetch_reviews().await{- Ok(reviews) => Some(- reviews+ // Ids are collected before conversion: empty-body reviews (plain approvals) are dropped+ // from the comment list but their reviewers still count as participants.+ Ok(reviews) => Some(FetchedDiscussion {+ participant_ids: author_ids(&reviews, |review| review.user.as_ref()),+ comments: reviews.into_iter().filter_map(GithubReviewResponse::into_pull_request_comment).collect(),- ),+ }),Err(error) => {tracing::warn!(error=?error,@@ -353,6 +421,13 @@ async fn fetch_reviews(}}+fn author_ids<T>(+ items: &[T],+ user_of: impl Fn(&T) -> Option<&GithubUserResponse>,+) -> BTreeSet<u64> {+ items.iter().filter_map(|item| user_of(item)?.id).collect()+}+async fn fetch_check_runs(client: &reqwest::Client,access_token: &str,@@ -465,6 +540,14 @@ fn github_get(impl GithubOpenPullRequestResponse {fn into_enriched_pull_request(self, owner: &str, repo: &str) -> EnrichedGithubPullRequest {+ // The list endpoint does not include comments, so this is the partial structural+ // participant set; stored metadata merges participants as a union.+ let participant_ids = structural_participant_ids(+ self.user.as_ref(),+ &self.requested_reviewers,+ &self.assignees,+ );+EnrichedGithubPullRequest {github_key: GithubKey::new(owner, repo, self.number).to_string(),owner: owner.to_string(),@@ -478,6 +561,8 @@ impl GithubOpenPullRequestResponse {deletions: None,comments: None,checks: None,+ participant_github_user_ids: (!participant_ids.is_empty())+ .then(|| participant_ids.iter().map(u64::to_string).collect()),}}}@@ -487,6 +572,7 @@ impl GithubCommentResponse {GithubPullRequestComment {id: self.id,body: self.body.unwrap_or_default(),+ author_id: self.user.as_ref().and_then(|user| user.id),author_login: self.user.and_then(|user| user.login),author_association: self.author_association,url: self.html_url,@@ -508,6 +594,7 @@ impl GithubReviewResponse {Some(GithubPullRequestComment {id: self.id,body,+ author_id: self.user.as_ref().and_then(|user| user.id),author_login: self.user.and_then(|user| user.login),author_association: self.author_association,url: self.html_url,diff --git a/rust/cloud-storage/item_filters/src/ast/foreign_entity.rs b/rust/cloud-storage/item_filters/src/ast/foreign_entity.rsindex 00808f1d99..aca7ef0743 100644--- a/rust/cloud-storage/item_filters/src/ast/foreign_entity.rs+++ b/rust/cloud-storage/item_filters/src/ast/foreign_entity.rs@@ -16,6 +16,9 @@ pub enum ForeignEntityLiteral {/// Filter by the external source name.#[serde(rename = "fes")]ForeignEntitySource(String),+ /// Filter to entities whose metadata participant list contains the requesting user.+ #[serde(rename = "me")]+ IncludesMe,}impl ExpandFrame<ForeignEntityLiteral> for ForeignEntityFilters {@@ -28,6 +31,7 @@ impl ExpandFrame<ForeignEntityLiteral> for ForeignEntityFilters {ids,foreign_entity_ids,foreign_entity_sources,+ includes_me,} = filter_request;let ids = ids@@ -43,8 +47,12 @@ impl ExpandFrame<ForeignEntityLiteral> for ForeignEntityFilters {.into_iter().expand(ForeignEntityLiteral::ForeignEntitySource, Expr::or);- Ok([ids, foreign_entity_ids, foreign_entity_sources]- .into_iter()- .fold_with(Expr::and))+ let includes_me = includes_me.then_some(Expr::Literal(ForeignEntityLiteral::IncludesMe));++ Ok(+ [ids, foreign_entity_ids, foreign_entity_sources, includes_me]+ .into_iter()+ .fold_with(Expr::and),+ )}}diff --git a/rust/cloud-storage/item_filters/src/ast/tests.rs b/rust/cloud-storage/item_filters/src/ast/tests.rsindex 0b55040e3d..75f80c354e 100644--- a/rust/cloud-storage/item_filters/src/ast/tests.rs+++ b/rust/cloud-storage/item_filters/src/ast/tests.rs@@ -995,6 +995,62 @@ fn foreign_entity_sources_expand_as_or_tree() {assert_eq!(json, exp);}+#[test]+fn foreign_entity_includes_me_expands_as_me_literal() {+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ includes_me: true,+ ..Default::default()+ },+ ..Default::default()+ };++ let ast = Arc::into_inner(+ EntityFilterAst::new_from_filters(f)+ .unwrap()+ .unwrap()+ .foreign_entity_filter+ .unwrap(),+ )+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({ "l": "me" });++ assert_eq!(json, exp);+}++#[test]+fn foreign_entity_includes_me_ands_with_sources() {+ let f = EntityFilters {+ foreign_entity_filters: ForeignEntityFilters {+ foreign_entity_sources: vec!["github_pull_request".to_string()],+ includes_me: true,+ ..Default::default()+ },+ ..Default::default()+ };++ let ast = Arc::into_inner(+ EntityFilterAst::new_from_filters(f)+ .unwrap()+ .unwrap()+ .foreign_entity_filter+ .unwrap(),+ )+ .unwrap();++ let json = serde_json::to_value(ast).unwrap();+ let exp = json!({+ "&": [+ { "l": { "fes": "github_pull_request" } },+ { "l": "me" }+ ]+ });++ assert_eq!(json, exp);+}+#[test]fn foreign_entity_invalid_id_returns_uuid_error() {let f = EntityFilters {diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex bf8929a798..0bc5c50872 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -382,6 +382,11 @@ pub struct ForeignEntityFilters {/// External source names to filter by. Empty to include all sources.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub foreign_entity_sources: Vec<String>,+ /// When true, only return foreign entities whose metadata lists the requesting user as a+ /// participant (GitHub `involves:me` semantics for `github_pull_request` records). False or+ /// absent applies no filter. Serialized in filter ASTs as the `"me"` literal.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub includes_me: bool,}impl IsEmpty for ForeignEntityFilters {@@ -390,8 +395,12 @@ impl IsEmpty for ForeignEntityFilters {ids,foreign_entity_ids,foreign_entity_sources,+ includes_me,} = self;- ids.is_empty() && foreign_entity_ids.is_empty() && foreign_entity_sources.is_empty()+ ids.is_empty()+ && foreign_entity_ids.is_empty()+ && foreign_entity_sources.is_empty()+ && !*includes_me}}diff --git a/rust/cloud-storage/macro_db_client/migrations/20260610161951_add_foreign_entity_participant_index.sql b/rust/cloud-storage/macro_db_client/migrations/20260610161951_add_foreign_entity_participant_index.sqlnew file mode 100644index 0000000000..5179d21b8c--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260610161951_add_foreign_entity_participant_index.sql@@ -0,0 +1,8 @@+-- GIN expression index over the GitHub PR participant id array so the+-- foreign-entity includes_me filter (`metadata -> 'participantGithubUserIds' ? $id`)+-- is indexable. Expression form (not whole-column GIN) because metadata embeds+-- full comment bodies and check runs; default jsonb_ops because the `?` operator+-- is not supported by jsonb_path_ops.+CREATE INDEX IF NOT EXISTS idx_foreign_entity_metadata_participant_github_user_ids+ ON foreign_entity+ USING GIN ((metadata -> 'participantGithubUserIds'));diff --git a/rust/cloud-storage/soup/src/domain/service.rs b/rust/cloud-storage/soup/src/domain/service.rsindex 008cbe4d93..803771fe01 100644--- a/rust/cloud-storage/soup/src/domain/service.rs+++ b/rust/cloud-storage/soup/src/domain/service.rs@@ -470,6 +470,7 @@ where#[tracing::instrument(err, skip(self, source_ids, query))]async fn handle_foreign_entity_request(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: Option<ForeignEntityListQuery>,@@ -480,7 +481,7 @@ whereOk(Either::Right(self.foreign_entity_service- .get_foreign_entities_for_user(source_ids, limit, query)+ .get_foreign_entities_for_user(requesting_user, source_ids, limit, query).await?.into_iter().map(|entity| FrecencySoupItem {@@ -546,6 +547,7 @@ wherelet crm_company_soup_fut = self.handle_crm_company_request(crm_company_request);let foreign_entity_soup_fut = self.handle_foreign_entity_request(+ Some(req.user.to_string()),foreign_entity_source_ids,limit as u32,foreign_entity_query,diff --git a/rust/cloud-storage/soup/src/domain/service/tests.rs b/rust/cloud-storage/soup/src/domain/service/tests.rsindex c6c9402118..a4d105c78b 100644--- a/rust/cloud-storage/soup/src/domain/service/tests.rs+++ b/rust/cloud-storage/soup/src/domain/service/tests.rs@@ -132,6 +132,7 @@ impl ForeignEntityService for NoopForeignEntityService {async fn get_foreign_entities_for_user(&self,+ _requesting_user: Option<String>,_source_ids: Vec<SourceId>,_limit: u32,_query: ForeignEntityListQuery,@@ -171,6 +172,7 @@ struct RecordingForeignEntityState {#[derive(Clone)]struct RecordedForeignEntityCall {+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -208,6 +210,8 @@ fn foreign_entity_matches_literal(entity: &ForeignEntity, literal: &ForeignEntitForeignEntityLiteral::ForeignEntitySource(source) => {entity.foreign_entity_source.as_str() == source.as_str()}+ // "me" resolution happens in the repository; the fake cannot resolve it, so fail closed.+ ForeignEntityLiteral::IncludesMe => false,}}@@ -268,6 +272,7 @@ impl ForeignEntityService for RecordingForeignEntityService {async fn get_foreign_entities_for_user(&self,+ requesting_user: Option<String>,source_ids: Vec<SourceId>,limit: u32,query: ForeignEntityListQuery,@@ -279,6 +284,7 @@ impl ForeignEntityService for RecordingForeignEntityService {.lock().unwrap().push(RecordedForeignEntityCall {+ requesting_user,source_ids: source_ids.clone(),limit,query,@@ -586,6 +592,7 @@ async fn team_receipt_contributes_team_foreign_entity_source_id() {SourceId::new(team_id.to_string(), "team"),]);+ assert_eq!(calls[0].requesting_user, Some(user.to_string()));}#[tokio::test]