diff --git a/apps/sim/connectors/gitlab/permissions.test.ts b/apps/sim/connectors/gitlab/permissions.test.ts index 52897ea50a4..2f3e6b6f08d 100644 --- a/apps/sim/connectors/gitlab/permissions.test.ts +++ b/apps/sim/connectors/gitlab/permissions.test.ts @@ -227,6 +227,18 @@ describe('GitLab source permission audiences', () => { ]) }) + it('grants a commit to the repository audience only, withdrawn with repository access', async () => { + const commit = document('commit:4109c2d8', {}) + const acls = await getGitLabDocumentAcls('test-token', config, [commit]) + expect(acls['commit:4109c2d8']).toEqual([ + 'g:gitlab:gitlab.example.com%3A8443/42:project:42:repository', + ]) + sourceProject = { ...project, repository_access_level: 'disabled' } + expect( + (await getGitLabDocumentAcls('test-token', config, [commit]))['commit:4109c2d8'] + ).toEqual([]) + }) + it('rejects a project path reassigned between directory identity and permission reads', async () => { const directory = await openGitLabDirectory('test-token', config, {}) sourceProject = { ...project, id: 43 } diff --git a/apps/sim/connectors/gitlab/permissions.ts b/apps/sim/connectors/gitlab/permissions.ts index cfac3172edd..d9de62c27f8 100644 --- a/apps/sim/connectors/gitlab/permissions.ts +++ b/apps/sim/connectors/gitlab/permissions.ts @@ -594,6 +594,24 @@ export async function openGitLabDirectory( } } +/** + * The project feature that governs each document ID prefix. Commits are live Search references the + * crawl never lists; they belong to the repository like files. + */ +const DOCUMENT_FEATURES: Record = { + file: 'repository', + commit: 'repository', + merge_request: 'merge_requests', + wiki: 'wiki', + issue: 'issues', +} + +function documentFeature(externalId: string): Feature | null { + const separator = externalId.indexOf(':') + const prefix = separator > 0 ? externalId.slice(0, separator) : '' + return Object.hasOwn(DOCUMENT_FEATURES, prefix) ? (DOCUMENT_FEATURES[prefix] ?? null) : null +} + /** Permissions are fetched independently from content hashes, including unchanged confidential issues. */ export async function getGitLabDocumentAcls( token: string, @@ -605,7 +623,7 @@ export async function getGitLabDocumentAcls( if (csv) { const result: Record = {} for (const doc of documents) { - const known = /^(file|wiki|issue|merge_request):/.test(doc.externalId) + const known = documentFeature(doc.externalId) !== null const excluded = doc.skippedReason || (doc.externalId.startsWith('issue:') && doc.metadata?.confidential !== false) @@ -628,15 +646,7 @@ export async function getGitLabDocumentAcls( ) const result: Record = {} for (const doc of documents) { - const feature = doc.externalId.startsWith('file:') - ? 'repository' - : doc.externalId.startsWith('merge_request:') - ? 'merge_requests' - : doc.externalId.startsWith('wiki:') - ? 'wiki' - : doc.externalId.startsWith('issue:') - ? 'issues' - : null + const feature = documentFeature(doc.externalId) if ( !feature || !['enabled', 'private'].includes(accessLevel(state.project, feature) ?? '') || diff --git a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts index 3c3e5b9d99b..3f5dd1370d9 100644 --- a/apps/sim/lib/api/contracts/mothership-assistant-tools.ts +++ b/apps/sim/lib/api/contracts/mothership-assistant-tools.ts @@ -19,13 +19,16 @@ export const MAX_NATIVE_QUERIES_PER_ACCOUNT = 4 */ const PROVIDER_KIND_SCHEMAS = { github: z.enum(['issues', 'code', 'repositories', 'commits']), - gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki']), + gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki', 'commits']), hubspot: z.enum(['contacts', 'companies', 'deals', 'tickets']), lucid: z.enum(['lucidchart', 'lucidspark']), google_meet: z.enum(['transcript', 'smart_notes']), zoom: z.enum(['meeting']), } as const +/** A collection one GitLab search selects. */ +export type GitLabSearchKind = z.output + function hasSearchKinds( provider: LiveSearchProvider ): provider is keyof typeof PROVIDER_KIND_SCHEMAS { diff --git a/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts b/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts index c5ecb8894b3..35d1dfff5fa 100644 --- a/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts +++ b/apps/sim/lib/knowledge/__integration__/gitlab-federated.integration.ts @@ -60,6 +60,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { let connectorId: string let issueIid: number let confidentialIid: number + let mergeRequestIid: number let sourceRevision: number const people: Record = {} const providerUserIds: number[] = [] @@ -100,7 +101,10 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { throw new Error('Disposable GitLab membership did not converge') } - function search(person: FixturePerson, kind: 'issues' | 'code' | 'wiki' | 'merge_requests') { + function search( + person: FixturePerson, + kind: 'issues' | 'code' | 'wiki' | 'merge_requests' | 'commits' + ) { return searchLiveKnowledge.execute({ principal: principal(person), input: { @@ -226,7 +230,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { await api(`/projects/${projectId}/repository/files/fixture.md`, 'POST', { branch: 'main', content: `${QUERY} repository content.`, - commit_message: 'Create disposable federated fixture', + commit_message: `${QUERY} create disposable federated fixture`, }) await api(`/projects/${projectId}/wikis`, 'POST', { title: `${QUERY} wiki`, @@ -255,11 +259,20 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { content: `${QUERY} proposed content.`, commit_message: 'Update disposable federated fixture', }) - await api(`/projects/${projectId}/merge_requests`, 'POST', { - source_branch: 'fixture-change', - target_branch: 'main', - title: `${QUERY} merge request`, - description: `${QUERY} proposed content.`, + mergeRequestIid = ( + await api<{ iid: number }>(`/projects/${projectId}/merge_requests`, 'POST', { + source_branch: 'fixture-change', + target_branch: 'main', + title: `${QUERY} merge request`, + description: `${QUERY} proposed content.`, + }) + ).iid + await api(`/projects/${projectId}/merge_requests/${mergeRequestIid}/notes`, 'POST', { + body: 'Reviewed: ship it', + }) + await api(`/projects/${projectId}/merge_requests/${mergeRequestIid}/notes`, 'POST', { + body: 'Internal: hold for the security review', + internal: true, }) await db.insert(organizationSearchIntegration).values({ organizationId: ids.organizationId, @@ -300,7 +313,7 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { for (const result of cleanup) if (result.status === 'rejected') throw result.reason }, 120_000) - it.each(['issues', 'code', 'wiki', 'merge_requests'] as const)( + it.each(['issues', 'code', 'wiki', 'merge_requests', 'commits'] as const)( 'searches and reads %s from the configured HTTPS instance with current permissions', async (kind) => { const result = await search(people.reporter!, kind) @@ -324,6 +337,22 @@ describe.skipIf(!fixtureFile)('federated self-hosted GitLab Search', () => { 120_000 ) + it('reads a merge request with its review discussion and diff, without internal notes', async () => { + const reporter = people.reporter + if (!reporter) throw new Error('Expected the reporter fixture') + const row = (await search(reporter, 'merge_requests')).results.find( + (result) => decodeLiveReference(result.documentId).id === String(mergeRequestIid) + ) + if (!row) throw new Error('Expected the fixture merge request') + const content = (await read(reporter, row.documentId)).chunks + .map((chunk) => chunk.content) + .join('\n') + expect(content).toContain('Reviewed: ship it') + expect(content).toContain('### fixture.md (modified)') + expect(content).toContain(`+${QUERY} proposed content.`) + expect(content).not.toContain('security review') + }, 120_000) + it('keeps references reader-bound and rechecks confidentiality before reads', async () => { const reporter = await search(people.reporter!, 'code') const file = reporter.results[0]! diff --git a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts index 9089689412d..ab69d7932ee 100644 --- a/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts +++ b/apps/sim/lib/mothership/generated/sim-assistant-tools.generated.ts @@ -42,7 +42,7 @@ export const MAX_NATIVE_QUERIES_PER_ACCOUNT = 4 */ const PROVIDER_KIND_SCHEMAS = { github: z.enum(['issues', 'code', 'repositories', 'commits']), - gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki']), + gitlab: z.enum(['issues', 'code', 'merge_requests', 'wiki', 'commits']), hubspot: z.enum(['contacts', 'companies', 'deals', 'tickets']), lucid: z.enum(['lucidchart', 'lucidspark']), google_meet: z.enum(['transcript', 'smart_notes']), diff --git a/apps/sim/lib/sim-search/live/github.ts b/apps/sim/lib/sim-search/live/github.ts index 8b9eb05bb19..043dcc15d9d 100644 --- a/apps/sim/lib/sim-search/live/github.ts +++ b/apps/sim/lib/sim-search/live/github.ts @@ -5,7 +5,14 @@ import { nativeText, } from '@/lib/sim-search/live/dates' import { readDiscussionSection } from '@/lib/sim-search/live/discussion' -import { array, NativeSearchError, object, segment, string } from '@/lib/sim-search/live/http' +import { + array, + isCommitSha, + NativeSearchError, + object, + segment, + string, +} from '@/lib/sim-search/live/http' import { collectNativePages, joinMessages } from '@/lib/sim-search/live/pages' import type { NativeClient, @@ -460,7 +467,7 @@ export async function readGitHub( return githubDocument(row, 'repositories') } if (kind === 'commits') { - if (!/^[0-9a-f]{7,40}$/i.test(id)) + if (!isCommitSha(id)) throw new NativeSearchError('unavailable', 'Invalid GitHub commit reference.') /** Each changed file carries its patch, so the page bounds the response size. */ const row = object( diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts index 6fda990842d..51479e0f0d6 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts @@ -9,6 +9,7 @@ import { createAdminGitLabSession, listAdminGitLabAccounts, } from '@/lib/sim-search/live/gitlab-admin' +import { NativeSearchError } from '@/lib/sim-search/live/http' import { gitLabCsvGroupToken, setGitLabCsvContext, @@ -38,7 +39,8 @@ vi.mock('@/connectors/gitlab/permissions', () => ({ getGitLabDocumentAcls: mocks.acl, validateGitLabCsvToken: mocks.csv, })) -vi.mock('@/lib/sim-search/live/gitlab', () => ({ +vi.mock('@/lib/sim-search/live/gitlab', async (importOriginal) => ({ + ...(await importOriginal()), searchGitLab: mocks.search, readGitLab: mocks.read, })) @@ -55,7 +57,7 @@ const grant = groupToken({ groupId: 'repository', })! const client = { json: vi.fn(), text: vi.fn(), bytes: vi.fn() } -const session = (config = source.config) => +const session = (config: Record = source.config) => createAdminGitLabSession({ owner: { organizationId: 'org' }, userId: 'reader', @@ -171,6 +173,56 @@ describe('administrator-managed live GitLab authorization', () => { ) expect(mocks.acl).toHaveBeenCalledTimes(2) }) + it('serves a commit only from the history of the ref a source is limited to, under the repository ACL', async () => { + const sha = '4109c2d872d5fdb1ed057400d103766aaea97f98' + const commit = { id: sha, container: '42', kind: 'commits' } + const current = await session({ ...source.config, ref: 'v1.2.0' }) + client.json.mockResolvedValue({ id: 'aaaaaaa1aaaaaaa1aaaaaaa1aaaaaaa1aaaaaaa1' }) + expect(await current.verify(commit)).toBe(false) + client.json.mockRejectedValue(new NativeSearchError('unavailable', 'Unrelated', undefined, 400)) + expect(await current.verify(commit)).toBe(false) + expect(mocks.acl).not.toHaveBeenCalled() + client.json.mockResolvedValue({ id: sha }) + expect(await current.verify(commit)).toBe(true) + await current.search({ + query: 'fix', + limit: 10, + scopes: [], + native: { provider: 'gitlab', query: 'fix', kind: 'commits' }, + }) + expect(mocks.search).toHaveBeenCalledWith(client, expect.any(Object), { ref: 'v1.2.0' }) + expect(mocks.acl).toHaveBeenCalledWith( + 'admin-token', + expect.any(Object), + [expect.objectContaining({ externalId: `commit:${sha}` })], + expect.any(Object) + ) + }) + it('leaves commits out of a source that limits code to a path, whose commits span other files', async () => { + const current = await session({ ...source.config, pathPrefix: 'docs' }) + expect(await current.verify({ id: '4109c2d8', container: '42', kind: 'commits' })).toBe(false) + await current.search({ + query: 'fix', + limit: 10, + scopes: [], + native: { provider: 'gitlab', query: 'fix', kind: 'commits' }, + }) + expect(mocks.search).not.toHaveBeenCalled() + }) + it('searches commits only when asked, as a search without a source does', async () => { + mocks.search.mockImplementation(async (_client, input) => ({ + documents: [ + { id: '1', container: '42', kind: input.native.kind, title: '', url: '', content: '' }, + ], + })) + const page = await (await session()).search({ query: 'fix', limit: 10, scopes: [] }) + expect(page.documents.map((document) => document.kind).sort()).toEqual([ + 'code', + 'issues', + 'merge_requests', + 'wiki', + ]) + }) it('propagates the caller deadline into the canonical permission directory', async () => { await session() expect(mocks.directory).toHaveBeenCalledWith( diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.ts b/apps/sim/lib/sim-search/live/gitlab-admin.ts index 067a180c07a..45607a59a61 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.ts @@ -4,6 +4,7 @@ import { createLogger } from '@sim/logger' import { describeError } from '@sim/utils/errors' import { and, eq, inArray, isNull } from 'drizzle-orm' import { z } from 'zod' +import type { GitLabSearchKind } from '@/lib/api/contracts/mothership-assistant-tools' import { decryptApiKey } from '@/lib/api-key/crypto' import { type ResourceOwner, resourceScopeFromOwner } from '@/lib/core/resource-scope' import { resourceScopeCondition } from '@/lib/core/resource-scope.server' @@ -17,8 +18,21 @@ import { } from '@/lib/knowledge/connectors/permission-store' import { searchIntegrationAccessCondition } from '@/lib/knowledge/search/integration-policy' import { dateSortDirection, hasDateBounds } from '@/lib/sim-search/live/dates' -import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' -import { array, NativeSearchError, object, segment, string } from '@/lib/sim-search/live/http' +import { + GITLAB_OPT_IN_KINDS, + gitLabDocumentUrl, + gitLabProjectPath, + readGitLab, + searchGitLab, +} from '@/lib/sim-search/live/gitlab' +import { + array, + isCommitSha, + NativeSearchError, + object, + segment, + string, +} from '@/lib/sim-search/live/http' import { collectNativePages, joinMessages } from '@/lib/sim-search/live/pages' import type { LiveAccount, @@ -159,12 +173,34 @@ export async function resolveAdminGitLabAccount(owner: ResourceOwner, account: L type Reference = Pick type AdminSource = { id: string; config: Record } -export function gitLabSourceKinds(config: Record): string[] { +/** The source's kinds a search covers: the one it names, or all but the opt-in kinds. */ +function defaultKinds(kinds: GitLabSearchKind[], requested?: string): GitLabSearchKind[] { + return kinds.filter((kind) => + requested ? kind === requested : !GITLAB_OPT_IN_KINDS.includes(kind) + ) +} + +/** The connector document ID prefix each kind's permissions are evaluated under. */ +const GITLAB_DOCUMENT_PREFIXES = { + code: 'file', + commits: 'commit', + issues: 'issue', + merge_requests: 'merge_request', + wiki: 'wiki', +} satisfies Record + +/** + * The collections a source serves. Commits come with code, except where the source limits code to + * a path or file types: a commit's message and diff span files outside that limit. + */ +export function gitLabSourceKinds(config: Record): GitLabSearchKind[] { + const commits: GitLabSearchKind[] = + string(config.pathPrefix).trim() || string(config.fileExtensions).trim() ? [] : ['commits'] switch (config.contentTypes || 'both') { case 'all': - return ['code', 'wiki', 'issues', 'merge_requests'] + return ['code', 'wiki', 'issues', 'merge_requests', ...commits] case 'repo': - return ['code'] + return ['code', ...commits] case 'wiki': return ['wiki'] case 'issues': @@ -275,9 +311,10 @@ async function createProjectSession( const permittedReference = (reference: Reference) => { if ( ![project, projectPath].includes(reference.container ?? '') || - !kinds.includes(reference.kind ?? '') + !kinds.some((kind) => kind === reference.kind) ) return false + if (reference.kind === 'commits') return isCommitSha(reference.id) if (reference.kind !== 'code') return true const path = reference.id if ( @@ -313,11 +350,7 @@ async function createProjectSession( if (!/^[1-9]\d*$/.test(reference.id)) return false const row = evidence ?? - object( - await client.json( - `/api/v4/projects/${segment(project)}/${reference.kind}/${reference.id}` - ) - ) + object(await client.json(`${gitLabProjectPath(project)}/${reference.kind}/${reference.id}`)) if (!evidence && (string(row.project_id) !== project || string(row.iid) !== reference.id)) return false metadata = evidence ?? { @@ -338,15 +371,26 @@ async function createProjectSession( return false } } - const prefix = - reference.kind === 'code' - ? 'file' - : reference.kind === 'issues' - ? 'issue' - : reference.kind === 'merge_requests' - ? 'merge_request' - : 'wiki' - const externalId = `${prefix}:${reference.id}` + if (reference.kind === 'commits' && string(config.ref)) { + // A source limited to one ref (branch, tag or commit) serves only the commits in its history: + // a commit's merge base with that ref is the commit itself. + const base = await client + .json(`${gitLabProjectPath(project)}/repository/merge_base`, { + query: { 'refs[]': [reference.id, string(config.ref)] }, + memo: true, + }) + .catch((error: unknown) => { + // GitLab answers an unknown commit or unrelated histories with 400 or 404. + if (error instanceof NativeSearchError && [400, 404].includes(error.httpStatus ?? 0)) + return undefined + throw error + }) + if (!string(object(base).id).toLowerCase().startsWith(reference.id.toLowerCase())) + return false + } + const kind = kinds.find((candidate) => candidate === reference.kind) + if (!kind) return false + const externalId = `${GITLAB_DOCUMENT_PREFIXES[kind]}:${reference.id}` const acl = await getGitLabDocumentAcls( token, config, @@ -361,32 +405,22 @@ async function createProjectSession( async search(search: NativeSearchInput) { if (search.native?.project && ![project, projectPath].includes(search.native.project)) return { documents: [] } - const selected = search.native?.kind - ? kinds.filter((kind) => kind === search.native?.kind) - : kinds - const scopedClient: NativeClient = { - ...client, - json: (path, options) => - client.json(path, { - ...options, - ...(path.endsWith('/search') && - string(config.ref) && - ['blobs', 'wiki_blobs'].includes(options?.query?.scope as string) - ? { query: { ...options?.query, ref: string(config.ref) } } - : {}), - }), - } - const request = (kind: string) => - searchGitLab(scopedClient, { - ...search, - native: { - provider: 'gitlab', - query: search.query, - ...search.native, - project, - kind: kind as 'code' | 'wiki' | 'issues' | 'merge_requests', + const selected = defaultKinds(kinds, search.native?.kind) + const request = (kind: GitLabSearchKind) => + searchGitLab( + client, + { + ...search, + native: { + provider: 'gitlab', + query: search.query, + ...search.native, + project, + kind, + }, }, - }) + { ref: string(config.ref) || undefined } + ) const page = selected.length === 1 ? await request(selected[0]!) @@ -519,12 +553,13 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { } const searchGroup = async ( search: NativeSearchInput, - kinds: string[], + kinds: GitLabSearchKind[], raw?: string ): Promise => { + /** Group search takes no branch, so a source limited to one searches its projects instead. */ const fallback = (kind: string) => Boolean( - (['code', 'wiki'].includes(kind) && string(source.config.ref)) || + (['code', 'wiki', 'commits'].includes(kind) && string(source.config.ref)) || hasDateBounds(search.filters) || dateSortDirection(search.filters) ) @@ -585,7 +620,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { provider: 'gitlab', query: search.query, ...search.native, - kind: kind as 'code' | 'wiki' | 'issues' | 'merge_requests', + kind, cursor: String(position.page), }, } @@ -593,7 +628,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { try { let result: NativePage if (position.mode === 'group') { - result = await searchGitLab(client, query, metadata.group.id) + result = await searchGitLab(client, query, { groupId: metadata.group.id }) const byId = new Set(result.documents.map((document) => document.container)) const candidates = projects.filter((project) => byId.has(String(project.id))) const allowed = new Map( @@ -605,13 +640,12 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { for (const document of result.documents) { const project = allowed.get(document.container ?? '') if (!document.url && project) { - const base = `https://${metadata.host}/${project.path.split('/').map(segment).join('/')}` - document.url = - kind === 'code' - ? `${base}/-/blob/${segment(document.revision || 'HEAD')}/${document.id.split('/').map(segment).join('/')}` - : kind === 'wiki' - ? `${base}/-/wikis/${document.id.split('/').map(segment).join('/')}` - : `${base}/-/${kind}/${segment(document.id)}` + document.url = gitLabDocumentUrl( + `https://${metadata.host}/${project.path.split('/').map(segment).join('/')}`, + kind, + document.id, + document.revision + ) } } } else { @@ -710,9 +744,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { const project = await referencedProject(search.native.project) return project ? (await session(project)).search(search) : { documents: [] } } - const kinds = gitLabSourceKinds(source.config).filter( - (kind) => !search.native?.kind || kind === search.native.kind - ) + const kinds = defaultKinds(gitLabSourceKinds(source.config), search.native?.kind) if (!kinds.length) return { documents: [] } const raw = search.native?.cursor if (metadata.mode === 'csv' && (!raw || raw.startsWith('g1.'))) @@ -753,7 +785,7 @@ async function createGroupSession(input: GitLabSessionInput, own: string) { query: search.query, ...search.native, project: String(project.id), - kind: kind as 'code' | 'wiki' | 'issues' | 'merge_requests', + kind, cursor: String(page), }, }) diff --git a/apps/sim/lib/sim-search/live/gitlab.test.ts b/apps/sim/lib/sim-search/live/gitlab.test.ts new file mode 100644 index 00000000000..6adbaf027ec --- /dev/null +++ b/apps/sim/lib/sim-search/live/gitlab.test.ts @@ -0,0 +1,270 @@ +import { describe, expect, it } from 'vitest' +import { readGitLab, searchGitLab } from '@/lib/sim-search/live/gitlab' +import { NativeSearchError } from '@/lib/sim-search/live/http' +import type { NativeClient, NativeSearchInput } from '@/lib/sim-search/live/types' + +const PROJECT = { id: 42, web_url: 'https://git.example.com/team/repo', default_branch: 'main' } +const SHA = '4109c2d872d5fdb1ed057400d103766aaea97f98' + +type Route = (query: Record | undefined) => unknown + +/** A GitLab API that answers each path it knows and fails like GitLab on any other. */ +function gitlab(routes: Record) { + const requests: string[] = [] + const client: NativeClient = { + text: async () => '', + bytes: async () => Buffer.alloc(0), + async json(path, options) { + requests.push(path) + const route = routes[path] + if (!route) throw new NativeSearchError('unavailable', 'Not found', undefined, 404) + return route(options?.query) + }, + } + return { client, requests } +} + +const commit = (message: string, id = SHA) => ({ + id, + title: message.split('\n')[0], + message, + author_name: 'Ada', + authored_date: '2026-11-02T10:00:00Z', + project_id: 42, +}) + +const commitSearch = ( + query: string, + extra: Partial = {} +): NativeSearchInput => ({ + query, + limit: 10, + scopes: [], + native: { provider: 'gitlab', query, project: '42', kind: 'commits' }, + ...extra, +}) + +describe('GitLab commit search', () => { + it('lists and matches recent commits when the instance has no advanced search', async () => { + const { client, requests } = gitlab({ + '/api/v4/application/settings': () => ({ elasticsearch_search: false }), + '/api/v4/projects/42/repository/commits': () => [ + commit('Fix the cache eviction race'), + commit('Bump version', 'aaaaaaa1'), + ], + }) + const page = await searchGitLab(client, commitSearch('cache race')) + expect(page.documents.map((document) => document.id)).toEqual([SHA]) + expect(page.documents[0]?.kind).toBe('commits') + expect(page.message).toContain('advanced search') + expect(requests).not.toContain('/api/v4/projects/42/search') + }) + + it('continues a commit listing without skipping matches beyond one result page', async () => { + const history = Array.from({ length: 9 }, (_, index) => + commit(index % 3 === 1 ? `Bump version ${index}` : `Fix cache ${index}`, `${index}`.repeat(7)) + ) + const { client } = gitlab({ + '/api/v4/application/settings': () => ({ elasticsearch_search: false }), + '/api/v4/projects/42/repository/commits': (query) => { + const size = Number(query?.per_page) + const start = (Number(query?.page) - 1) * size + return history.slice(start, start + size) + }, + }) + const seen: string[] = [] + let cursor: string | undefined + do { + const input = commitSearch('cache', { limit: 4 }) + const page = await searchGitLab(client, { + ...input, + native: { provider: 'gitlab', query: 'cache', project: '42', kind: 'commits', cursor }, + }) + expect(page.documents.length).toBeLessThanOrEqual(4) + seen.push(...page.documents.map((document) => document.id)) + cursor = page.nextCursor + } while (cursor) + expect(seen).toEqual( + history.filter((row) => row.message.startsWith('Fix')).map((row) => row.id) + ) + }) + + it('reports a commit listing that reaches GitLab’s last page as incomplete, not finished', async () => { + const { client } = gitlab({ + '/api/v4/application/settings': () => ({ elasticsearch_search: false }), + '/api/v4/projects/42/repository/commits': () => + Array.from({ length: 4 }, () => commit('Bump version')), + }) + const input = commitSearch('cache', { limit: 4 }) + const page = await searchGitLab(client, { + ...input, + native: { + provider: 'gitlab', + query: 'cache', + project: '42', + kind: 'commits', + cursor: '10000', + }, + }) + expect(page).toMatchObject({ partial: true, hasMore: true }) + expect(page.nextCursor).toBeUndefined() + }) + + it('refuses a project reference that would resolve away from the project endpoint', async () => { + const { client, requests } = gitlab({ + '/api/v4/application/settings': () => ({ elasticsearch_search: false }), + }) + await expect( + searchGitLab(client, { + ...commitSearch('cache'), + native: { provider: 'gitlab', query: 'cache', project: '..', kind: 'commits' }, + }) + ).rejects.toThrow('Invalid GitLab project reference') + expect(requests).toEqual(['/api/v4/application/settings']) + }) + + it('falls back to the listing when GitLab rejects the commit search scope', async () => { + const { client } = gitlab({ + '/api/v4/projects/42/search': () => { + throw new NativeSearchError('unavailable', 'Bad scope', undefined, 400) + }, + '/api/v4/projects/42/repository/commits': () => [commit('Fix the cache eviction race')], + }) + const page = await searchGitLab(client, commitSearch('cache')) + expect(page.documents.map((document) => document.id)).toEqual([SHA]) + }) + + it('keeps commit search and listing on the branch a source is limited to', async () => { + const branches: unknown[] = [] + const { client } = gitlab({ + '/api/v4/projects/42/search': (query) => { + branches.push(query?.ref) + throw new NativeSearchError('unavailable', 'Bad scope', undefined, 400) + }, + '/api/v4/projects/42/repository/commits': (query) => { + branches.push(query?.ref_name) + return [commit('Fix the cache eviction race')] + }, + }) + await searchGitLab(client, commitSearch('cache'), { ref: 'release' }) + expect(branches).toEqual(['release', 'release']) + }) + + it('refuses commit search across a group without advanced search, so the group searches its projects', async () => { + const { client } = gitlab({ + '/api/v4/application/settings': () => ({ elasticsearch_search: false }), + }) + const failure = await searchGitLab(client, commitSearch('cache'), { groupId: 7 }).catch( + (error: unknown) => error + ) + expect(failure).toBeInstanceOf(NativeSearchError) + expect(failure).toMatchObject({ httpStatus: 400, message: expect.stringContaining('project') }) + }) + + it('refuses oldest-first commit order, which GitLab cannot list', async () => { + const { client } = gitlab({}) + await expect( + searchGitLab(client, commitSearch('', { filters: { sortBy: 'oldest' } })) + ).rejects.toThrow('newest first') + }) +}) + +describe('GitLab merge request reads', () => { + const MR = { + iid: 9, + project_id: 42, + title: 'Add cache', + description: 'Adds the cache layer', + state: 'opened', + source_branch: 'cache', + target_branch: 'main', + author: { id: 1, name: 'Ada' }, + } + const discussions = [ + { + id: 'd1', + notes: [ + { + id: 1, + type: 'DiffNote', + body: 'Use an LRU here', + author: { username: 'bob' }, + created_at: '2026-11-03T10:00:00Z', + position: { new_path: 'src/cache.ts', new_line: 12 }, + resolvable: true, + resolved: false, + }, + { + id: 2, + body: 'Security reviewers only: the token is logged', + internal: true, + author: { username: 'sec' }, + created_at: '2026-11-03T11:00:00Z', + }, + ], + }, + { + id: 'd2', + notes: [{ id: 3, body: 'added 1 commit', system: true, author: { username: 'ada' } }], + }, + ] + const base = `/api/v4/projects/42/merge_requests/9` + + it('returns the discussion and diff, leaving out internal and system notes', async () => { + const { client } = gitlab({ + '/api/v4/projects/42': () => PROJECT, + [base]: () => MR, + [`${base}/discussions`]: () => discussions, + [`${base}/diffs`]: () => [ + { new_path: 'src/cache.ts', old_path: 'src/cache.ts', diff: '@@ -1 +1 @@\n-a\n+b' }, + { new_path: 'dist/bundle.js', old_path: 'dist/bundle.js', diff: '', too_large: true }, + ], + }) + const document = await readGitLab(client, '9', '42', 'merge_requests') + expect(document.content).toContain('Use an LRU here') + expect(document.content).toContain('src/cache.ts · line 12') + expect(document.content).toContain('+b') + expect(document.content).toContain('Diff withheld: dist/bundle.js (modified), too large') + expect(document.content).not.toContain('token is logged') + expect(document.content).not.toContain('added 1 commit') + expect(document.accessMetadata).toMatchObject({ authorId: 1 }) + }) + + it('warns first when the diff exceeds its text budget', async () => { + const { client } = gitlab({ + '/api/v4/projects/42': () => PROJECT, + [base]: () => MR, + [`${base}/discussions`]: () => [], + [`${base}/diffs`]: () => [ + { new_path: 'a.txt', diff: `+${'x'.repeat(130_000)}` }, + { new_path: 'b.txt', diff: '+never shown' }, + ], + }) + const document = await readGitLab(client, '9', '42', 'merge_requests') + expect(document.content.startsWith('Coverage incomplete: Changes exceeded')).toBe(true) + expect(document.content).not.toContain('never shown') + expect(document.content.length).toBeLessThan(125_000) + }) + + it('reads changes from the older endpoint on instances without paginated diffs', async () => { + const { client } = gitlab({ + '/api/v4/projects/42': () => PROJECT, + [base]: () => MR, + [`${base}/discussions`]: () => [], + [`${base}/changes`]: () => ({ changes: [{ new_path: 'old.ts', diff: '+legacy' }] }), + }) + const document = await readGitLab(client, '9', '42', 'merge_requests') + expect(document.content).toContain('+legacy') + expect(document.content).not.toContain('Coverage incomplete') + }) +}) + +describe('GitLab commit reads', () => { + it('rejects a reference that is not a commit SHA before any request', async () => { + const { client, requests } = gitlab({ '/api/v4/projects/42': () => PROJECT }) + await expect(readGitLab(client, '../../users', '42', 'commits')).rejects.toThrow( + 'Invalid GitLab commit reference' + ) + expect(requests).toEqual([]) + }) +}) diff --git a/apps/sim/lib/sim-search/live/gitlab.ts b/apps/sim/lib/sim-search/live/gitlab.ts index 3a42451a3c0..daf5f235aee 100644 --- a/apps/sim/lib/sim-search/live/gitlab.ts +++ b/apps/sim/lib/sim-search/live/gitlab.ts @@ -1,17 +1,96 @@ +import type { GitLabSearchKind } from '@/lib/api/contracts/mothership-assistant-tools' import { dateSortDirection, hasDateBounds, nativeDateBounds, nativeText, } from '@/lib/sim-search/live/dates' -import { array, NativeSearchError, object, segment, string } from '@/lib/sim-search/live/http' +import { readDiscussionSection } from '@/lib/sim-search/live/discussion' +import { + array, + isCommitSha, + NativeSearchError, + object, + segment, + string, +} from '@/lib/sim-search/live/http' import { collectNativePages } from '@/lib/sim-search/live/pages' +import { significantTerms, termCoverage } from '@/lib/sim-search/live/text-match' import type { NativeClient, NativeDocument, NativePage, NativeSearchInput, } from '@/lib/sim-search/live/types' +import { encodeGitLabResourceId } from '@/tools/gitlab/utils' + +/** Collections a search without a kind covers; commits must be asked for, as on GitHub. */ +const GITLAB_DEFAULT_KINDS = ['issues', 'code', 'merge_requests'] as const + +/** Collections searched only when a search names them, whatever else a source serves. */ +export const GITLAB_OPT_IN_KINDS: readonly GitLabSearchKind[] = ['commits'] + +const GITLAB_SCOPES = { + issues: 'issues', + code: 'blobs', + merge_requests: 'merge_requests', + wiki: 'wiki_blobs', + commits: 'commits', +} satisfies Record + +/** Scopes GitLab searches on one branch when given a `ref`. */ +const GITLAB_REF_SCOPES = new Set(['blobs', 'wiki_blobs', 'commits']) + +/** Where a search runs: a group, and the one branch a source is limited to. */ +export interface GitLabSearchScope { + groupId?: number + ref?: string +} + +/** Listing pages one commit search scans for a match when it matches messages itself. */ +const GITLAB_COMMIT_LIST_MAX_PAGES = 5 + +/** Small pages keep long Markdown comments below the provider response byte ceiling. */ +const GITLAB_DISCUSSION_PAGE_SIZE = 50 +/** Changed files per diff page; each carries its patch, so the page bounds the response. */ +const GITLAB_DIFF_PAGE_SIZE = 50 + +const GITLAB_COMMITS_NEED_ADVANCED_SEARCH = + "GitLab commit search requires advanced search on this instance. Set project to search a project's recent commits." +const GITLAB_COMMITS_LISTED = + 'GitLab commit search needs advanced search (Premium) on this instance, so recent commits in this project were listed and matched against their messages.' + +/** + * The API path of a project named by ID or full path. A dot segment would let URL parsing resolve + * the request away from the project, so it is refused. + */ +export function gitLabProjectPath(project: string): string { + try { + return `/api/v4/projects/${encodeGitLabResourceId(project)}` + } catch { + throw new NativeSearchError('unavailable', 'Invalid GitLab project reference.') + } +} + +/** Where a GitLab document opens in the browser, from its project's web URL. */ +export function gitLabDocumentUrl( + projectUrl: string, + kind: string | undefined, + id: string, + revision?: string +): string { + const path = id.split('/').map(segment).join('/') + switch (kind) { + case 'code': + return `${projectUrl}/-/blob/${segment(revision || 'HEAD')}/${path}` + case 'wiki': + return `${projectUrl}/-/wikis/${path}` + case 'commits': + return `${projectUrl}/-/commit/${segment(id)}` + default: + return `${projectUrl}/-/${kind}/${segment(id)}` + } +} function document(row: Record, kind: string): NativeDocument { return { @@ -38,10 +117,124 @@ function document(row: Record, kind: string): NativeDocument { } } +/** A commit as a document: its message is the content and its author date the timeline. */ +function commitDocument(row: Record, container: string): NativeDocument { + const sha = string(row.id) + const message = string(row.message) || string(row.title) + const authored = Date.parse(string(row.authored_date)) + return { + id: sha, + container, + kind: 'commits', + title: string(row.title) || message.split('\n')[0] || sha.slice(0, 8), + url: string(row.web_url), + content: message, + ...(Number.isFinite(authored) ? { modifiedAt: new Date(authored).toISOString() } : {}), + author: string(row.author_name), + } +} + +/** + * Whether the instance runs advanced search, which commit search requires. An administrator + * token reads it from the application settings; any other token cannot, so the search itself + * decides. + */ +async function gitLabAdvancedSearch(client: NativeClient): Promise { + try { + const enabled = object( + await client.json('/api/v4/application/settings', { memo: true }) + ).elasticsearch_search + return typeof enabled === 'boolean' ? enabled : undefined + } catch (error) { + if (error instanceof NativeSearchError && [403, 404].includes(error.httpStatus ?? 0)) + return undefined + throw error + } +} + +/** + * Lists a project's commits newest first and keeps those whose message holds every query term, + * for instances without advanced search and for date-bounded commit searches. Pages are the + * size of one result page, and scanning stops at the first page with a match, so a page's matches + * always fit the results and the cursor never skips one. + */ +async function listGitLabCommits( + client: NativeClient, + input: NativeSearchInput, + project: string, + page: number, + ref?: string +): Promise { + const dates = nativeDateBounds(input) + const dated = hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters)) + const terms = significantTerms(nativeText(input)) + const documents: NativeDocument[] = [] + let next: number | undefined = page + let capped = false + for ( + let scanned = 0; + next !== undefined && scanned < GITLAB_COMMIT_LIST_MAX_PAGES && documents.length === 0; + scanned++ + ) { + const response = await client.json(`${gitLabProjectPath(project)}/repository/commits`, { + query: { + per_page: String(input.limit), + page: String(next), + ...(ref ? { ref_name: ref } : {}), + ...(dates.start ? { since: dates.start } : {}), + ...(dates.end ? { until: dates.end } : {}), + }, + }) + if (!Array.isArray(response) || response.length > input.limit) + throw new NativeSearchError('unavailable', 'GitLab returned an invalid commit listing.') + const rows = array(response) + for (const row of rows) + if (termCoverage(string(row.message), terms) === terms.length) + documents.push(commitDocument(row, project)) + capped = rows.length === input.limit && next >= 10_000 + next = rows.length === input.limit && !capped ? next + 1 : undefined + } + return { + documents, + ...(next !== undefined ? { nextCursor: String(next) } : {}), + ...(capped ? { partial: true, hasMore: true } : {}), + ...(dated ? {} : { message: GITLAB_COMMITS_LISTED }), + } +} + +/** + * Whether a commit search lists its project's commits instead of searching: GitLab's commit + * search needs advanced search and filters neither by date nor oldest first, while the listing + * does dates. A search without a project that cannot be served throws with a 400 status, which + * moves a group search on to its projects. + */ +async function listsCommits( + client: NativeClient, + input: NativeSearchInput, + project: string | undefined +): Promise { + if (dateSortDirection(input.filters) === 'asc') + throw new NativeSearchError( + 'unavailable', + 'GitLab lists commits newest first; sort by newest or omit the sort.' + ) + const dated = hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters)) + if (!dated && (await gitLabAdvancedSearch(client)) !== false) return false + if (project) return true + throw new NativeSearchError( + 'unavailable', + dated + ? 'GitLab filters commits by date only within a project. Set project to list its commits in that window.' + : GITLAB_COMMITS_NEED_ADVANCED_SEARCH, + undefined, + 400 + ) +} + export async function searchGitLab( client: NativeClient, input: NativeSearchInput, - groupId?: number + { groupId, ref }: GitLabSearchScope = {} ): Promise { if (!input.native?.project && groupId === undefined) { const projects = array( @@ -60,15 +253,19 @@ export async function searchGitLab( const pages: Promise[] = [] for (const project of selected) { pages.push( - searchGitLab(client, { - ...input, - native: { - provider: 'gitlab', - query: input.query, - ...input.native, - project: string(project.id), + searchGitLab( + client, + { + ...input, + native: { + provider: 'gitlab', + query: input.query, + ...input.native, + project: string(project.id), + }, }, - }) + { ref } + ) ) } const result = await collectNativePages( @@ -86,35 +283,26 @@ export async function searchGitLab( } if (!input.native?.kind) return collectNativePages( - ['issues', 'code', 'merge_requests'].map((kind) => + GITLAB_DEFAULT_KINDS.map((kind) => searchGitLab( client, { ...input, - native: { - provider: 'gitlab', - query: input.query, - ...input.native, - kind: kind as 'issues' | 'code' | 'merge_requests', - }, + native: { provider: 'gitlab', query: input.query, ...input.native, kind }, }, - groupId + { groupId, ref } ) ), 'Searched GitLab issues, merge requests, and code.' ) const kind = input.native?.kind ?? 'issues' - const scopes: Record = { - issues: 'issues', - code: 'blobs', - merge_requests: 'merge_requests', - wiki: 'wiki_blobs', - } - const scope = scopes[kind] + const scope = Object.hasOwn(GITLAB_SCOPES, kind) + ? GITLAB_SCOPES[kind as GitLabSearchKind] + : undefined if (!scope) throw new NativeSearchError( 'unavailable', - 'GitLab supports issues, code, merge_requests, or wiki search.' + `GitLab supports ${Object.keys(GITLAB_SCOPES).join(', ')} search.` ) const page = input.native?.cursor ?? '1' if (!/^\d{1,5}$/.test(page) || Number(page) < 1 || Number(page) > 10_000) @@ -124,6 +312,9 @@ export async function searchGitLab( 'unavailable', 'GitLab code/wiki search does not provide modification dates. Use issues or merge_requests for date-filtered search.' ) + const project = groupId === undefined ? input.native?.project : undefined + if (kind === 'commits' && (await listsCommits(client, input, project)) && project) + return listGitLabCommits(client, input, project, Number(page), ref) const groupPageLimit = Math.floor(10_000 / input.limit) if (groupId !== undefined && Number(page) > groupPageLimit) throw new NativeSearchError( @@ -132,7 +323,7 @@ export async function searchGitLab( ) const dates = nativeDateBounds(input) const listing = Boolean( - input.native?.project && + project && ['issues', 'merge_requests'].includes(kind) && (hasDateBounds(input.filters) || Boolean(dateSortDirection(input.filters))) ) @@ -142,13 +333,14 @@ export async function searchGitLab( groupId !== undefined ? `/api/v4/groups/${groupId}/search` : listing - ? `/api/v4/projects/${segment(input.native!.project!)}/${kind}` - : input.native?.project - ? `/api/v4/projects/${segment(input.native.project)}/search` + ? `${gitLabProjectPath(project ?? '')}/${kind}` + : project + ? `${gitLabProjectPath(project)}/search` : '/api/v4/search', { query: { scope: listing ? 'all' : scope, + ...(ref && !listing && GITLAB_REF_SCOPES.has(scope) ? { ref } : {}), ...(groupId !== undefined ? { exclude_forks: 'false', include_archived: 'true' } : {}), ...(nativeText(input) ? { search: nativeText(input) } : {}), ...(listing && dates.start ? { updated_after: dates.start } : {}), @@ -162,6 +354,19 @@ export async function searchGitLab( } ) } catch (error) { + if ( + kind === 'commits' && + error instanceof NativeSearchError && + (error.httpStatus === 400 || error.httpStatus === 422) + ) { + if (project) return listGitLabCommits(client, input, project, Number(page), ref) + throw new NativeSearchError( + 'unavailable', + GITLAB_COMMITS_NEED_ADVANCED_SEARCH, + undefined, + error.httpStatus + ) + } if (error instanceof NativeSearchError) throw new NativeSearchError( error.status, @@ -175,23 +380,18 @@ export async function searchGitLab( if (!Array.isArray(response) || response.length > input.limit) throw new NativeSearchError('unavailable', 'GitLab returned an invalid search response.') const data = array(response) - const documents = data.map((row) => document(row, kind)) + const documents = data.map((row) => + kind === 'commits' ? commitDocument(row, string(row.project_id)) : document(row, kind) + ) const projects = new Map() for (const item of documents) { if (groupId === undefined && !item.url && item.container) { let url = projects.get(item.container) if (!url) { - url = string( - object(await client.json(`/api/v4/projects/${segment(item.container)}`)).web_url - ) + url = string(object(await client.json(gitLabProjectPath(item.container))).web_url) projects.set(item.container, url) } - item.url = - kind === 'code' - ? `${url}/-/blob/${segment(item.revision || 'HEAD')}/${item.id.split('/').map(segment).join('/')}` - : kind === 'wiki' - ? `${url}/-/wikis/${item.id.split('/').map(segment).join('/')}` - : `${url}/-/${kind}/${segment(item.id)}` + item.url = gitLabDocumentUrl(url, kind, item.id, item.revision) } } const capped = @@ -204,10 +404,121 @@ export async function searchGitLab( ? { nextCursor: String(Number(page) + 1) } : {}), message: - 'GitLab code/wiki/global search availability depends on the instance plan and enabled search backend. Set project to narrow to a project ID or path.', + 'GitLab code/wiki/commits/global search availability depends on the instance plan and enabled search backend. Set project to narrow to a project ID or path.', } } +/** One discussion thread: its first note, then each reply. System and internal notes are left out. */ +function gitLabDiscussionEntry(discussion: Record): string { + return array(discussion.notes) + .filter((note) => note.system !== true && note.internal !== true && note.confidential !== true) + .map((note, index) => { + const position = object(note.position) + const path = string(position.new_path) || string(position.old_path) + const line = string(position.new_line) || string(position.old_line) + return [ + [ + index > 0 ? 'Reply' : note.type === 'DiffNote' ? 'Diff comment' : 'Comment', + string(note.id), + string(object(note.author).username) || 'Unknown author', + string(note.created_at), + ] + .filter(Boolean) + .join(' · '), + string(note.updated_at) && note.updated_at !== note.created_at + ? `Updated: ${string(note.updated_at)}` + : '', + path ? [path, line ? `line ${line}` : ''].filter(Boolean).join(' · ') : '', + index === 0 && note.resolvable === true + ? note.resolved === true + ? 'Resolved' + : 'Unresolved' + : '', + string(note.body), + ] + .filter(Boolean) + .join('\n') + }) + .join('\n\n') +} + +function readGitLabDiscussion(client: NativeClient, path: string, label: string) { + return readDiscussionSection(label, async (cursor) => { + const page = cursor ?? '1' + const response = await client.json(path, { + query: { per_page: String(GITLAB_DISCUSSION_PAGE_SIZE), page }, + }) + if (!Array.isArray(response)) + throw new NativeSearchError('unavailable', 'returned an invalid discussion response') + const rows = array(response) + return { + entries: rows.map(gitLabDiscussionEntry), + ...(rows.length >= GITLAB_DISCUSSION_PAGE_SIZE + ? { nextCursor: String(Number(page) + 1) } + : {}), + } + }) +} + +/** One changed file's patch, or a line naming a diff GitLab withheld (too large, collapsed, generated). */ +function gitLabDiffEntry(row: Record): string { + const name = string(row.new_path) || string(row.old_path) + const change = + row.new_file === true + ? 'added' + : row.deleted_file === true + ? 'deleted' + : row.renamed_file === true + ? `renamed from ${string(row.old_path)}` + : 'modified' + const withheld = + row.too_large === true + ? 'too large' + : row.collapsed === true + ? 'collapsed' + : row.generated_file === true + ? 'generated' + : string(row.diff) + ? undefined + : 'no text diff' + return withheld + ? `Diff withheld: ${name} (${change}), ${withheld}` + : `### ${name} (${change})\n${string(row.diff)}` +} + +/** + * The changed files with their patches, within the shared discussion page and text budget. + * Instances without the paginated merge request diffs endpoint answer it with 404 and serve + * `legacyPath`'s `changes` instead. + */ +function readGitLabDiffs(client: NativeClient, path: string, legacyPath?: string) { + return readDiscussionSection('Changes', async (cursor) => { + const page = cursor ?? '1' + let rows: Record[] + try { + const response = await client.json(path, { + query: { per_page: String(GITLAB_DIFF_PAGE_SIZE), page }, + }) + if (!Array.isArray(response)) + throw new NativeSearchError('unavailable', 'returned an invalid diff response') + rows = array(response) + } catch (error) { + if ( + !legacyPath || + cursor || + !(error instanceof NativeSearchError) || + error.httpStatus !== 404 + ) + throw error + return { entries: array(object(await client.json(legacyPath)).changes).map(gitLabDiffEntry) } + } + return { + entries: rows.map(gitLabDiffEntry), + ...(rows.length >= GITLAB_DIFF_PAGE_SIZE ? { nextCursor: String(Number(page) + 1) } : {}), + } + }) +} + export async function readGitLab( client: NativeClient, id: string, @@ -216,26 +527,34 @@ export async function readGitLab( revision?: string ): Promise { if (!project) throw new NativeSearchError('unavailable', 'Missing GitLab project reference.') - const path = `/api/v4/projects/${segment(project)}` - const metadata = object(await client.json(path)) + const path = gitLabProjectPath(project) if (kind === 'code') { - const row = object( - await client.json(`${path}/repository/files/${segment(id)}`, { - query: { ref: revision || 'HEAD' }, - }) - ) + const [metadata, row] = await Promise.all([ + client.json(path).then(object), + client + .json(`${path}/repository/files/${segment(id)}`, { query: { ref: revision || 'HEAD' } }) + .then(object), + ]) return { id, container: project, kind, revision, title: string(row.file_name), - url: `${string(metadata.web_url)}/-/blob/${segment(revision || string(metadata.default_branch))}/${id.split('/').map(segment).join('/')}`, + url: gitLabDocumentUrl( + string(metadata.web_url), + 'code', + id, + revision || string(metadata.default_branch) + ), content: Buffer.from(string(row.content), 'base64').toString('utf8'), } } if (kind === 'wiki') { - const row = object(await client.json(`${path}/wikis/${segment(id.replace(/\.md$/, ''))}`)) + const [metadata, row] = await Promise.all([ + client.json(path).then(object), + client.json(`${path}/wikis/${segment(id.replace(/\.md$/, ''))}`).then(object), + ]) return { id, container: project, @@ -245,12 +564,59 @@ export async function readGitLab( content: string(row.content), } } + if (kind === 'commits') { + if (!isCommitSha(id)) + throw new NativeSearchError('unavailable', 'Invalid GitLab commit reference.') + const commitPath = `${path}/repository/commits/${segment(id)}` + const [row, changes] = await Promise.all([ + client.json(commitPath).then(object), + readGitLabDiffs(client, `${commitPath}/diff`), + ]) + const commit = commitDocument(row, project) + const stats = object(row.stats) + return { + ...commit, + content: [ + changes.warning, + `Commit ${string(row.id)}`, + [string(row.author_name), string(row.authored_date)].filter(Boolean).join(' · '), + string(stats.total) ? `+${string(stats.additions)} -${string(stats.deletions)}` : '', + commit.content, + changes.content, + ] + .filter(Boolean) + .join('\n\n'), + } + } if (!/^\d+$/.test(id)) throw new NativeSearchError('unavailable', 'Invalid GitLab issue reference.') - return document( - object( - await client.json(`${path}/${kind === 'merge_requests' ? 'merge_requests' : 'issues'}/${id}`) + const mergeRequest = kind === 'merge_requests' + const collection = mergeRequest ? 'merge_requests' : 'issues' + const itemPath = `${path}/${collection}/${id}` + const [row, discussion, changes] = await Promise.all([ + client.json(itemPath).then(object), + readGitLabDiscussion( + client, + `${itemPath}/discussions`, + mergeRequest ? 'Merge request discussion' : 'Issue discussion' ), - kind ?? 'issues' - ) + mergeRequest ? readGitLabDiffs(client, `${itemPath}/diffs`, `${itemPath}/changes`) : undefined, + ]) + return { + ...document(row, collection), + content: [ + discussion.warning, + changes?.warning, + `${mergeRequest ? `Merge request !${id}` : `Issue #${id}`}: ${string(row.title)}`, + string(row.state) ? `State: ${string(row.state)}` : '', + mergeRequest && string(row.source_branch) + ? `Branches: ${string(row.source_branch)} → ${string(row.target_branch)}` + : '', + string(row.description), + discussion.content, + changes?.content, + ] + .filter(Boolean) + .join('\n\n'), + } } diff --git a/apps/sim/lib/sim-search/live/http.ts b/apps/sim/lib/sim-search/live/http.ts index 175de822e63..9ae9d7b5bcd 100644 --- a/apps/sim/lib/sim-search/live/http.ts +++ b/apps/sim/lib/sim-search/live/http.ts @@ -287,3 +287,6 @@ export function textContent(value: unknown): string { return string(node.text) || textContent(node.content) } export const segment = (value: string) => encodeURIComponent(value) + +/** Whether a reference names a git commit by its full or abbreviated SHA. */ +export const isCommitSha = (value: string) => /^[\da-f]{7,40}$/i.test(value) diff --git a/apps/sim/lib/sim-search/live/links.test.ts b/apps/sim/lib/sim-search/live/links.test.ts index ca1ca9e2a27..dab08d5dc94 100644 --- a/apps/sim/lib/sim-search/live/links.test.ts +++ b/apps/sim/lib/sim-search/live/links.test.ts @@ -138,6 +138,21 @@ describe('parseDocumentLinks', () => { }, ], ], + [ + 'a commit on a self-hosted GitLab', + 'https://git.acme.dev/platform/api/-/commit/4109c2d872d5fdb1ed057400d103766aaea97f98', + [ + { + provider: 'gitlab', + host: 'git.acme.dev', + reference: { + container: 'platform/api', + id: '4109c2d872d5fdb1ed057400d103766aaea97f98', + kind: 'commits', + }, + }, + ], + ], ])('reads %s on any host, for the account on that host', (_case, link, expected) => { expect(parseDocumentLinks(link)).toEqual(expected) }) @@ -158,6 +173,7 @@ describe('parseDocumentLinks', () => { 'https://mail.google.com/mail/u/0/#inbox/FMfcgzQXJ', ], ['an unrelated site', 'https://example.com/about'], + ['a GitLab commit link naming a branch', 'https://git.acme.dev/platform/api/-/commit/main'], ])('names nothing for %s', (_case, link) => { expect(parseDocumentLinks(link)).toEqual([]) }) diff --git a/apps/sim/lib/sim-search/live/links.ts b/apps/sim/lib/sim-search/live/links.ts index f36f5e8e422..86f3a41b0ac 100644 --- a/apps/sim/lib/sim-search/live/links.ts +++ b/apps/sim/lib/sim-search/live/links.ts @@ -1,6 +1,6 @@ import { parseGitHubRepository } from '@/lib/oauth/github-repository' import { atlassianSiteId } from '@/lib/sim-search/live/atlassian' -import { NativeSearchError, object, string } from '@/lib/sim-search/live/http' +import { isCommitSha, NativeSearchError, object, string } from '@/lib/sim-search/live/http' import { linearIssueReference } from '@/lib/sim-search/live/linear' import { notionResource } from '@/lib/sim-search/live/notion-mcp' import type { NativeClient, NativeDocument } from '@/lib/sim-search/live/types' @@ -200,7 +200,7 @@ function githubCommit( sha: string | undefined, link: (reference: LinkedReference) => DocumentLink ): DocumentLink | undefined { - return sha && /^[\da-f]{7,40}$/i.test(sha) ? link({ id: sha, kind: 'commits' }) : undefined + return sha && isCommitSha(sha) ? link({ id: sha, kind: 'commits' }) : undefined } /** GitLab separates a project's path from its pages with `/-/`, on gitlab.com and self-hosted. */ @@ -221,6 +221,8 @@ function gitlabLink(url: URL): DocumentLink | undefined { return iid && NUMERIC_ID.test(iid) ? link({ id: iid, kind: section === 'merge_requests' ? 'merge_requests' : 'issues' }) : undefined + if (section === 'commit') + return iid && isCommitSha(iid) ? link({ id: iid, kind: 'commits' }) : undefined if (section === 'blob') return { provider: 'gitlab', host: url.host, repository: project, blob: rest } if (section === 'wikis' && rest.length) return link({ id: rest.join('/'), kind: 'wiki' }) diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 16f372d2f94..3012ae37103 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -276,11 +276,12 @@ export const LIVE_SEARCH_PROVIDERS = { gitlab: { guide: { syntax: - 'Plain search terms with kind issues, merge_requests, code or wiki, on administrator-configured projects only. Under basic or advanced search, code and wiki accept filename:, path: and extension: filters (-filename: or -extension: excludes files); where exact code search handles code, use file: and lang: instead. Advanced search also accepts "exact phrase", | for OR and -word to exclude.', - scope: 'accountId targets one configured source and project narrows it to one project.', + 'Plain search terms with kind issues, merge_requests, code, wiki or commits, on administrator-configured projects only; no kind searches issues, merge requests and code. Under basic or advanced search, code and wiki accept filename:, path: and extension: filters (-filename: or -extension: excludes files); where exact code search handles code, use file: and lang: instead. Advanced search also accepts "exact phrase", | for OR and -word to exclude.', + scope: + 'accountId targets one configured source and project narrows it to one project. kind commits searches commit messages; dates filter commits by author date, newest first, within a project.', example: 'connection timeout', avoid: - 'expecting date filters or sorting on code or wiki results, and relying on advanced-search operators (quotes, |, -) on instances that may only have basic search.', + 'expecting date filters or sorting on code or wiki results, oldest-first commits, and relying on advanced-search operators (quotes, |, -) on instances that may only have basic search. Commit search needs advanced search; without it a project-scoped commit search lists recent commits and matches their messages. Read a merge request for its discussion and diff, and a commit for its diff.', }, search: (client, input) => searchGitLab(client, input), read: (client, reference) => diff --git a/scripts/check-explicit-any.baseline.json b/scripts/check-explicit-any.baseline.json index 828d79de638..11918ff975a 100644 --- a/scripts/check-explicit-any.baseline.json +++ b/scripts/check-explicit-any.baseline.json @@ -1541,7 +1541,6 @@ "apps/sim/lib/sim-search/live/github.ts": 1, "apps/sim/lib/sim-search/live/gitlab-admin.test.ts": 1, "apps/sim/lib/sim-search/live/gitlab-admin.ts": 1, - "apps/sim/lib/sim-search/live/gitlab.ts": 2, "apps/sim/lib/sim-search/live/google-meet.ts": 1, "apps/sim/lib/sim-search/live/granola-mcp.ts": 2, "apps/sim/lib/sim-search/live/hubspot-mcp.test.ts": 1,