From 1a236f634420240f9647e8508ec02ccb920f9997 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Mon, 30 Nov 2026 23:54:11 -0800 Subject: [PATCH 1/4] fix(gitlab): keep merge request diffs within a source's code scope and search project commits on basic search --- .../lib/sim-search/live/gitlab-admin.test.ts | 30 ++++ apps/sim/lib/sim-search/live/gitlab-admin.ts | 58 +++---- apps/sim/lib/sim-search/live/gitlab.test.ts | 118 +++++++++++++-- apps/sim/lib/sim-search/live/gitlab.ts | 141 ++++++++++++++---- apps/sim/lib/sim-search/live/providers.ts | 4 +- 5 files changed, 279 insertions(+), 72 deletions(-) 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 51479e0f0d6..2cf738cb95a 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts @@ -198,6 +198,36 @@ describe('administrator-managed live GitLab authorization', () => { expect.any(Object) ) }) + it('trusts a ref-scoped search for a commit’s ref and checks any other commit once', async () => { + const sha = '4109c2d872d5fdb1ed057400d103766aaea97f98' + const current = await session({ ...source.config, ref: 'main' }) + client.json.mockResolvedValue({ id: sha }) + expect( + await current.verify({ id: sha, container: '42', kind: 'commits' }, { ref: 'main' }) + ).toBe(true) + expect(client.json).toHaveBeenCalledTimes(1) + expect(await current.verify({ id: sha.slice(0, 8), container: '42', kind: 'commits' })).toBe( + true + ) + expect(await current.verify({ id: sha, container: '42', kind: 'commits' })).toBe(true) + expect( + client.json.mock.calls.filter(([path]) => String(path).endsWith('/merge_base')) + ).toHaveLength(1) + }) + it('reads with no repository content from a source that does not serve code', async () => { + const current = await session({ ...source.config, contentTypes: 'merge_requests' }) + client.json.mockResolvedValue({ project_id: 42, iid: 9, author: { id: 8 }, assignees: [] }) + mocks.read.mockResolvedValue({ + id: '9', + container: '42', + kind: 'merge_requests', + title: '', + url: '', + content: '', + }) + await current.read({ id: '9', container: '42', kind: 'merge_requests' }) + expect(mocks.read.mock.calls[0]?.[5]).toBeNull() + }) 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) diff --git a/apps/sim/lib/sim-search/live/gitlab-admin.ts b/apps/sim/lib/sim-search/live/gitlab-admin.ts index 45607a59a61..ab3b7239594 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.ts @@ -20,6 +20,7 @@ import { searchIntegrationAccessCondition } from '@/lib/knowledge/search/integra import { dateSortDirection, hasDateBounds } from '@/lib/sim-search/live/dates' import { GITLAB_OPT_IN_KINDS, + type GitLabCodeScope, gitLabDocumentUrl, gitLabProjectPath, readGitLab, @@ -291,7 +292,7 @@ async function createProjectSession( if (grant) tokens.add(grant) } } - const current = object(await client.json(`/api/v4/projects/${segment(string(config.project))}`)) + const current = object(await client.json(gitLabProjectPath(string(config.project)))) project = string(current.id) projectPath = string(current.path_with_namespace) } @@ -308,15 +309,9 @@ async function createProjectSession( throw new NativeSearchError('unavailable', 'GitLab project identity could not be verified.') signal.throwIfAborted() const kinds = gitLabSourceKinds(config) - const permittedReference = (reference: Reference) => { - if ( - ![project, projectPath].includes(reference.container ?? '') || - !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 + const ref = string(config.ref) + /** The repository paths the source's code scope covers: its path prefix and file types. */ + const permittedPath = (path: string) => { if ( path.startsWith('/') || path.includes('\\') || @@ -329,22 +324,33 @@ async function createProjectSession( .split(',') .map((part) => part.trim().toLowerCase()) .filter(Boolean) - if ( - extensions.length && - !extensions.some((extension) => + return ( + !extensions.length || + extensions.some((extension) => path.toLowerCase().endsWith(extension.startsWith('.') ? extension : `.${extension}`) ) ) - return false - const branch = string(config.ref) - return !branch || reference.revision === branch + } + /** What of the repository a read may show: none unless the source serves code. */ + const codeScope: GitLabCodeScope | null = kinds.includes('code') + ? { allows: permittedPath, ...(ref ? { ref } : {}) } + : null + /** Commits a ref-scoped search returned, or a merge-base check placed, in the source's ref. */ + const onRef = new Set() + const permittedReference = (reference: Reference) => { + if (![project, projectPath].includes(reference.container ?? '')) return false + if (reference.kind === 'commits') return isCommitSha(reference.id) + if (reference.kind !== 'code') return true + if (!permittedPath(reference.id)) return false + return !ref || reference.revision === ref } const verify = async ( reference: Reference, evidence?: Record ): Promise => { signal.throwIfAborted() - if (!permittedReference(reference)) return false + const kind = kinds.find((candidate) => candidate === reference.kind) + if (!kind || !permittedReference(reference)) return false let metadata: Record = {} if (reference.kind === 'issues' || reference.kind === 'merge_requests') { if (!/^[1-9]\d*$/.test(reference.id)) return false @@ -371,12 +377,14 @@ async function createProjectSession( return false } } - if (reference.kind === 'commits' && string(config.ref)) { + const sha = reference.id.toLowerCase() + if (reference.kind === 'commits' && ref && evidence?.ref !== ref && !onRef.has(sha)) { // 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. + // a commit's merge base with that ref is the commit itself. Commits a ref-scoped search + // returned are on the ref already. const base = await client .json(`${gitLabProjectPath(project)}/repository/merge_base`, { - query: { 'refs[]': [reference.id, string(config.ref)] }, + query: { 'refs[]': [reference.id, ref] }, memo: true, }) .catch((error: unknown) => { @@ -385,11 +393,10 @@ async function createProjectSession( return undefined throw error }) - if (!string(object(base).id).toLowerCase().startsWith(reference.id.toLowerCase())) - return false + const full = string(object(base).id).toLowerCase() + if (!full.startsWith(sha)) return false + onRef.add(sha).add(full) } - 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, @@ -441,7 +448,8 @@ async function createProjectSession( reference.id, project, reference.kind, - string(config.ref) || reference.revision + ref || reference.revision, + codeScope ) if (!(await verify(document, document.accessMetadata))) throw new NativeSearchError( diff --git a/apps/sim/lib/sim-search/live/gitlab.test.ts b/apps/sim/lib/sim-search/live/gitlab.test.ts index 6adbaf027ec..ab9978c0adb 100644 --- a/apps/sim/lib/sim-search/live/gitlab.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab.test.ts @@ -45,19 +45,34 @@ const commitSearch = ( }) describe('GitLab commit search', () => { - it('lists and matches recent commits when the instance has no advanced search', async () => { + it('searches a project’s commits under basic search, whatever the instance’s 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'), - ], + '/api/v4/projects/42': () => PROJECT, + '/api/v4/projects/42/search': (query) => + query?.scope === 'commits' ? [commit('Fix the cache eviction race')] : [], }) 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') + expect(page.documents[0]?.url).toBe(`${PROJECT.web_url}/-/commit/${SHA}`) + expect(requests).not.toContain('/api/v4/application/settings') + expect(requests).not.toContain('/api/v4/projects/42/repository/commits') + }) + + it('lists a project’s commits for a dated search and dates them where they were committed', async () => { + const windows: unknown[] = [] + const { client } = gitlab({ + '/api/v4/projects/42/repository/commits': (query) => { + windows.push([query?.since, query?.until]) + return [{ ...commit('Fix cache'), committed_date: '2026-11-20T09:00:00Z' }] + }, + }) + const page = await searchGitLab( + client, + commitSearch('cache', { filters: { startDate: '2026-11-15T00:00:00Z' } }) + ) + expect(windows).toEqual([['2026-11-15T00:00:00.000Z', undefined]]) + expect(page.documents[0]?.modifiedAt).toBe('2026-11-20T09:00:00.000Z') }) it('continues a commit listing without skipping matches beyond one result page', async () => { @@ -75,7 +90,10 @@ describe('GitLab commit search', () => { const seen: string[] = [] let cursor: string | undefined do { - const input = commitSearch('cache', { limit: 4 }) + const input = commitSearch('cache', { + limit: 4, + filters: { startDate: '2026-01-01T00:00:00Z' }, + }) const page = await searchGitLab(client, { ...input, native: { provider: 'gitlab', query: 'cache', project: '42', kind: 'commits', cursor }, @@ -95,7 +113,10 @@ describe('GitLab commit search', () => { '/api/v4/projects/42/repository/commits': () => Array.from({ length: 4 }, () => commit('Bump version')), }) - const input = commitSearch('cache', { limit: 4 }) + const input = commitSearch('cache', { + limit: 4, + filters: { startDate: '2026-01-01T00:00:00Z' }, + }) const page = await searchGitLab(client, { ...input, native: { @@ -120,7 +141,7 @@ describe('GitLab commit search', () => { native: { provider: 'gitlab', query: 'cache', project: '..', kind: 'commits' }, }) ).rejects.toThrow('Invalid GitLab project reference') - expect(requests).toEqual(['/api/v4/application/settings']) + expect(requests).toEqual([]) }) it('falls back to the listing when GitLab rejects the commit search scope', async () => { @@ -146,8 +167,9 @@ describe('GitLab commit search', () => { return [commit('Fix the cache eviction race')] }, }) - await searchGitLab(client, commitSearch('cache'), { ref: 'release' }) + const page = await searchGitLab(client, commitSearch('cache'), { ref: 'release' }) expect(branches).toEqual(['release', 'release']) + expect(page.documents[0]?.accessMetadata).toEqual({ ref: 'release' }) }) it('refuses commit search across a group without advanced search, so the group searches its projects', async () => { @@ -210,6 +232,78 @@ describe('GitLab merge request reads', () => { ] const base = `/api/v4/projects/42/merge_requests/9` + it('shows a merge request’s diff and diff threads only within the source’s code scope', async () => { + const routes = { + [base]: () => MR, + [`${base}/discussions`]: () => [ + ...discussions, + { + id: 'd3', + notes: [ + { + id: 4, + type: 'DiffNote', + body: 'Rotate this key', + author: { username: 'eve' }, + position: { new_path: 'secrets/keys.ts', new_line: 3 }, + }, + ], + }, + ], + [`${base}/diffs`]: () => [ + { new_path: 'src/cache.ts', old_path: 'src/cache.ts', diff: '+cached' }, + { new_path: 'secrets/keys.ts', old_path: 'secrets/keys.ts', diff: '+key' }, + { new_path: 'src/moved.ts', old_path: 'secrets/old.ts', diff: '+moved' }, + ], + } + const scoped = gitlab(routes) + const inSrc = await readGitLab(scoped.client, '9', '42', 'merge_requests', undefined, { + allows: (path) => path.startsWith('src/'), + }) + expect(inSrc.content).toContain('+cached') + expect(inSrc.content).toContain('Use an LRU here') + for (const hidden of ['+key', '+moved', 'Rotate this key', 'secrets/']) + expect(inSrc.content).not.toContain(hidden) + + const noCode = gitlab(routes) + const withoutCode = await readGitLab( + noCode.client, + '9', + '42', + 'merge_requests', + undefined, + null + ) + expect(withoutCode.content).not.toContain('+cached') + expect(withoutCode.content).not.toContain('Use an LRU here') + expect(noCode.requests).not.toContain(`${base}/diffs`) + + const otherRef = gitlab(routes) + const release = await readGitLab(otherRef.client, '9', '42', 'merge_requests', undefined, { + allows: () => true, + ref: 'release', + }) + expect(release.content).not.toContain('+cached') + expect(otherRef.requests).not.toContain(`${base}/diffs`) + }) + + it('stops reading diffs when an instance repeats a page instead of advancing', async () => { + const files = Array.from({ length: 50 }, (_, index) => ({ + new_path: `src/file${index}.ts`, + old_path: `src/file${index}.ts`, + diff: `+line ${index}`, + })) + const { client, requests } = gitlab({ + [base]: () => MR, + [`${base}/discussions`]: () => [], + [`${base}/diffs`]: () => files, + }) + const document = await readGitLab(client, '9', '42', 'merge_requests') + expect(requests.filter((path) => path === `${base}/diffs`)).toHaveLength(2) + expect(document.content.split('### src/file0.ts')).toHaveLength(2) + expect(document.content).not.toContain('Coverage incomplete') + }) + it('returns the discussion and diff, leaving out internal and system notes', async () => { const { client } = gitlab({ '/api/v4/projects/42': () => PROJECT, diff --git a/apps/sim/lib/sim-search/live/gitlab.ts b/apps/sim/lib/sim-search/live/gitlab.ts index daf5f235aee..cdd2fab6da0 100644 --- a/apps/sim/lib/sim-search/live/gitlab.ts +++ b/apps/sim/lib/sim-search/live/gitlab.ts @@ -41,6 +41,16 @@ const GITLAB_SCOPES = { /** Scopes GitLab searches on one branch when given a `ref`. */ const GITLAB_REF_SCOPES = new Set(['blobs', 'wiki_blobs', 'commits']) +/** + * What of a repository a read may show: the paths a source's code scope covers and, for a source + * limited to one ref, that ref. Merge request diffs and diff comments outside it are left out; + * `null` shows no repository content at all, for a source that does not serve code. + */ +export interface GitLabCodeScope { + allows: (path: string) => boolean + ref?: string +} + /** Where a search runs: a group, and the one branch a source is limited to. */ export interface GitLabSearchScope { groupId?: number @@ -56,9 +66,9 @@ const GITLAB_DISCUSSION_PAGE_SIZE = 50 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." + "GitLab searches commits across a group only with advanced search. Set project to search one project's 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.' + "GitLab could not search this project's commits, so its recent commits 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 @@ -117,25 +127,35 @@ 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 { +/** + * A commit as a document: its message is the content and its commit date the timeline, the date + * GitLab's `since` and `until` filter on, so a rebased or cherry-picked commit dates where it + * landed. + */ +function commitDocument( + row: Record, + container: string, + ref?: string +): NativeDocument { const sha = string(row.id) const message = string(row.message) || string(row.title) - const authored = Date.parse(string(row.authored_date)) + const committed = Date.parse(string(row.committed_date) || string(row.authored_date)) return { + // A ref-scoped search or listing returns only commits in that ref's history. + ...(ref ? { accessMetadata: { ref } } : {}), 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() } : {}), + ...(Number.isFinite(committed) ? { modifiedAt: new Date(committed).toISOString() } : {}), author: string(row.author_name), } } /** - * Whether the instance runs advanced search, which commit search requires. An administrator + * Whether the instance runs advanced search, which group commit search requires. An administrator * token reads it from the application settings; any other token cannot, so the search itself * decides. */ @@ -190,7 +210,7 @@ async function listGitLabCommits( const rows = array(response) for (const row of rows) if (termCoverage(string(row.message), terms) === terms.length) - documents.push(commitDocument(row, project)) + documents.push(commitDocument(row, project, ref)) capped = rows.length === input.limit && next >= 10_000 next = rows.length === input.limit && !capped ? next + 1 : undefined } @@ -203,24 +223,25 @@ async function listGitLabCommits( } /** - * 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. + * The project whose commits a commit search lists instead of searching, if any. A project's + * commits are searchable under basic search, but GitLab's commit search filters neither by date + * nor oldest first, so dated searches list instead. Across a group, commit search needs advanced + * search: a group search that cannot run throws with a 400 status, which moves it on to its + * projects. */ -async function listsCommits( +async function commitListingProject( client: NativeClient, input: NativeSearchInput, project: string | undefined -): Promise { +): 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 + if (project) return dated ? project : undefined + if (!dated && (await gitLabAdvancedSearch(client)) !== false) return undefined throw new NativeSearchError( 'unavailable', dated @@ -313,8 +334,8 @@ export async function searchGitLab( '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 listed = kind === 'commits' ? await commitListingProject(client, input, project) : undefined + if (listed) return listGitLabCommits(client, input, listed, Number(page), ref) const groupPageLimit = Math.floor(10_000 / input.limit) if (groupId !== undefined && Number(page) > groupPageLimit) throw new NativeSearchError( @@ -381,7 +402,13 @@ export async function searchGitLab( throw new NativeSearchError('unavailable', 'GitLab returned an invalid search response.') const data = array(response) const documents = data.map((row) => - kind === 'commits' ? commitDocument(row, string(row.project_id)) : document(row, kind) + kind === 'commits' + ? commitDocument( + row, + string(row.project_id), + ref && GITLAB_REF_SCOPES.has(scope) ? ref : undefined + ) + : document(row, kind) ) const projects = new Map() for (const item of documents) { @@ -409,8 +436,16 @@ export async function searchGitLab( } /** 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) +function gitLabDiscussionEntry( + discussion: Record, + codeScope?: GitLabCodeScope | null +): string { + const notes = array(discussion.notes) + // A thread opened on a diff line discusses that code, so it follows the code's scope. + const anchor = object(notes[0]?.position) + const anchorPath = string(anchor.new_path) || string(anchor.old_path) + if (anchorPath && codeScope !== undefined && !codeScope?.allows(anchorPath)) return '' + return notes .filter((note) => note.system !== true && note.internal !== true && note.confidential !== true) .map((note, index) => { const position = object(note.position) @@ -442,7 +477,12 @@ function gitLabDiscussionEntry(discussion: Record): string { .join('\n\n') } -function readGitLabDiscussion(client: NativeClient, path: string, label: string) { +function readGitLabDiscussion( + client: NativeClient, + path: string, + label: string, + codeScope?: GitLabCodeScope | null +) { return readDiscussionSection(label, async (cursor) => { const page = cursor ?? '1' const response = await client.json(path, { @@ -452,7 +492,7 @@ function readGitLabDiscussion(client: NativeClient, path: string, label: string) throw new NativeSearchError('unavailable', 'returned an invalid discussion response') const rows = array(response) return { - entries: rows.map(gitLabDiscussionEntry), + entries: rows.map((row) => gitLabDiscussionEntry(row, codeScope)), ...(rows.length >= GITLAB_DISCUSSION_PAGE_SIZE ? { nextCursor: String(Number(page) + 1) } : {}), @@ -491,7 +531,25 @@ function gitLabDiffEntry(row: Record): string { * 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) { +function readGitLabDiffs( + client: NativeClient, + path: string, + legacyPath?: string, + codeScope?: GitLabCodeScope +) { + /** A diff shows a file only when every path it names is in scope. */ + const shown = (row: Record) => + !codeScope || + [string(row.new_path), string(row.old_path)].filter(Boolean).every(codeScope.allows) + const seen = new Set() + /** Files not listed before; an instance that ignores paging repeats them, ending the read. */ + const fresh = (rows: Record[]) => + rows.filter((row) => { + const key = `${string(row.old_path)}\u0000${string(row.new_path)}` + if (seen.has(key)) return false + seen.add(key) + return true + }) return readDiscussionSection('Changes', async (cursor) => { const page = cursor ?? '1' let rows: Record[] @@ -510,11 +568,18 @@ function readGitLabDiffs(client: NativeClient, path: string, legacyPath?: string error.httpStatus !== 404 ) throw error - return { entries: array(object(await client.json(legacyPath)).changes).map(gitLabDiffEntry) } + return { + entries: fresh(array(object(await client.json(legacyPath)).changes)) + .filter(shown) + .map(gitLabDiffEntry), + } } + const added = fresh(rows) return { - entries: rows.map(gitLabDiffEntry), - ...(rows.length >= GITLAB_DIFF_PAGE_SIZE ? { nextCursor: String(Number(page) + 1) } : {}), + entries: added.filter(shown).map(gitLabDiffEntry), + ...(rows.length >= GITLAB_DIFF_PAGE_SIZE && added.length + ? { nextCursor: String(Number(page) + 1) } + : {}), } }) } @@ -524,7 +589,8 @@ export async function readGitLab( id: string, project?: string, kind?: string, - revision?: string + revision?: string, + codeScope?: GitLabCodeScope | null ): Promise { if (!project) throw new NativeSearchError('unavailable', 'Missing GitLab project reference.') const path = gitLabProjectPath(project) @@ -570,7 +636,7 @@ export async function readGitLab( const commitPath = `${path}/repository/commits/${segment(id)}` const [row, changes] = await Promise.all([ client.json(commitPath).then(object), - readGitLabDiffs(client, `${commitPath}/diff`), + readGitLabDiffs(client, `${commitPath}/diff`, undefined, codeScope ?? undefined), ]) const commit = commitDocument(row, project) const stats = object(row.stats) @@ -593,15 +659,23 @@ export async function readGitLab( const mergeRequest = kind === 'merge_requests' const collection = mergeRequest ? 'merge_requests' : 'issues' const itemPath = `${path}/${collection}/${id}` - const [row, discussion, changes] = await Promise.all([ + const [row, discussion] = await Promise.all([ client.json(itemPath).then(object), readGitLabDiscussion( client, `${itemPath}/discussions`, - mergeRequest ? 'Merge request discussion' : 'Issue discussion' + mergeRequest ? 'Merge request discussion' : 'Issue discussion', + codeScope ), - mergeRequest ? readGitLabDiffs(client, `${itemPath}/diffs`, `${itemPath}/changes`) : undefined, ]) + /** A source limited to a ref shows only the diffs of merge requests into that ref. */ + const showsChanges = + mergeRequest && + codeScope !== null && + (!codeScope?.ref || string(row.target_branch) === codeScope.ref) + const changes = showsChanges + ? await readGitLabDiffs(client, `${itemPath}/diffs`, `${itemPath}/changes`, codeScope) + : undefined return { ...document(row, collection), content: [ @@ -614,7 +688,8 @@ export async function readGitLab( : '', string(row.description), discussion.content, - changes?.content, + changes?.content ?? + (mergeRequest ? 'Changes are not shown: they fall outside this source.' : ''), ] .filter(Boolean) .join('\n\n'), diff --git a/apps/sim/lib/sim-search/live/providers.ts b/apps/sim/lib/sim-search/live/providers.ts index 3012ae37103..cad462adf09 100644 --- a/apps/sim/lib/sim-search/live/providers.ts +++ b/apps/sim/lib/sim-search/live/providers.ts @@ -278,10 +278,10 @@ export const LIVE_SEARCH_PROVIDERS = { syntax: '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.', + 'accountId targets one configured source and project narrows it to one project. kind commits searches commit messages; dates filter commits by commit date, newest first, within a project.', example: 'connection timeout', avoid: - '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.', + '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 across a group needs advanced search; set project to search the commits of one project. Read a merge request for its discussion and diff, and a commit for its diff.', }, search: (client, input) => searchGitLab(client, input), read: (client, reference) => From a86b505783b1b5e6cfe9f322477c1577f699a9e0 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:07:49 -0800 Subject: [PATCH 2/4] fix(gitlab): scope diff threads by every path and the source ref, and say when diffs are withheld --- apps/sim/lib/sim-search/live/gitlab.test.ts | 18 ++++++- apps/sim/lib/sim-search/live/gitlab.ts | 58 ++++++++++++++------- 2 files changed, 55 insertions(+), 21 deletions(-) diff --git a/apps/sim/lib/sim-search/live/gitlab.test.ts b/apps/sim/lib/sim-search/live/gitlab.test.ts index ab9978c0adb..a791d49cba2 100644 --- a/apps/sim/lib/sim-search/live/gitlab.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab.test.ts @@ -249,6 +249,19 @@ describe('GitLab merge request reads', () => { }, ], }, + { + id: 'd4', + notes: [ + { + id: 5, + type: 'DiffNote', + body: 'Old secret moved here', + author: { username: 'eve' }, + position: { new_path: 'src/moved.ts', old_path: 'secrets/old.ts', new_line: 1 }, + }, + ], + }, + { id: 'd5', notes: [{ id: 6, body: 'Looks good to me', author: { username: 'ann' } }] }, ], [`${base}/diffs`]: () => [ { new_path: 'src/cache.ts', old_path: 'src/cache.ts', diff: '+cached' }, @@ -262,7 +275,8 @@ describe('GitLab merge request reads', () => { }) expect(inSrc.content).toContain('+cached') expect(inSrc.content).toContain('Use an LRU here') - for (const hidden of ['+key', '+moved', 'Rotate this key', 'secrets/']) + expect(inSrc.content).toContain('2 changed files fall outside this source') + for (const hidden of ['+key', '+moved', 'Rotate this key', 'Old secret', 'secrets/']) expect(inSrc.content).not.toContain(hidden) const noCode = gitlab(routes) @@ -284,6 +298,8 @@ describe('GitLab merge request reads', () => { ref: 'release', }) expect(release.content).not.toContain('+cached') + expect(release.content).not.toContain('Use an LRU here') + expect(release.content).toContain('Looks good to me') expect(otherRef.requests).not.toContain(`${base}/diffs`) }) diff --git a/apps/sim/lib/sim-search/live/gitlab.ts b/apps/sim/lib/sim-search/live/gitlab.ts index cdd2fab6da0..b0770be652e 100644 --- a/apps/sim/lib/sim-search/live/gitlab.ts +++ b/apps/sim/lib/sim-search/live/gitlab.ts @@ -443,8 +443,13 @@ function gitLabDiscussionEntry( const notes = array(discussion.notes) // A thread opened on a diff line discusses that code, so it follows the code's scope. const anchor = object(notes[0]?.position) - const anchorPath = string(anchor.new_path) || string(anchor.old_path) - if (anchorPath && codeScope !== undefined && !codeScope?.allows(anchorPath)) return '' + const anchorPaths = [string(anchor.new_path), string(anchor.old_path)].filter(Boolean) + if ( + anchorPaths.length && + codeScope !== undefined && + !anchorPaths.every((path) => codeScope?.allows(path)) + ) + return '' return notes .filter((note) => note.system !== true && note.internal !== true && note.confidential !== true) .map((note, index) => { @@ -531,17 +536,23 @@ function gitLabDiffEntry(row: Record): string { * Instances without the paginated merge request diffs endpoint answer it with 404 and serve * `legacyPath`'s `changes` instead. */ -function readGitLabDiffs( +async function readGitLabDiffs( client: NativeClient, path: string, legacyPath?: string, codeScope?: GitLabCodeScope -) { +): Promise<{ content: string; warning?: string }> { /** A diff shows a file only when every path it names is in scope. */ const shown = (row: Record) => !codeScope || [string(row.new_path), string(row.old_path)].filter(Boolean).every(codeScope.allows) const seen = new Set() + let hidden = 0 + const inScope = (rows: Record[]) => { + const kept = rows.filter(shown) + hidden += rows.length - kept.length + return kept + } /** Files not listed before; an instance that ignores paging repeats them, ending the read. */ const fresh = (rows: Record[]) => rows.filter((row) => { @@ -550,7 +561,7 @@ function readGitLabDiffs( seen.add(key) return true }) - return readDiscussionSection('Changes', async (cursor) => { + const section = await readDiscussionSection('Changes', async (cursor) => { const page = cursor ?? '1' let rows: Record[] try { @@ -569,19 +580,25 @@ function readGitLabDiffs( ) throw error return { - entries: fresh(array(object(await client.json(legacyPath)).changes)) - .filter(shown) - .map(gitLabDiffEntry), + entries: inScope(fresh(array(object(await client.json(legacyPath)).changes))).map( + gitLabDiffEntry + ), } } const added = fresh(rows) return { - entries: added.filter(shown).map(gitLabDiffEntry), + entries: inScope(added).map(gitLabDiffEntry), ...(rows.length >= GITLAB_DIFF_PAGE_SIZE && added.length ? { nextCursor: String(Number(page) + 1) } : {}), } }) + return hidden + ? { + ...section, + content: `${section.content}\n\n${hidden} changed ${hidden === 1 ? 'file falls' : 'files fall'} outside this source and ${hidden === 1 ? 'is' : 'are'} not shown.`, + } + : section } export async function readGitLab( @@ -659,23 +676,24 @@ export async function readGitLab( const mergeRequest = kind === 'merge_requests' const collection = mergeRequest ? 'merge_requests' : 'issues' const itemPath = `${path}/${collection}/${id}` - const [row, discussion] = await Promise.all([ - client.json(itemPath).then(object), + const row = object(await client.json(itemPath)) + /** + * A source limited to a ref shows the code of merge requests into that ref only: their diffs + * and diff-line threads. Ordinary comments are kept either way. + */ + const itemScope = + mergeRequest && codeScope?.ref && string(row.target_branch) !== codeScope.ref ? null : codeScope + const [discussion, changes] = await Promise.all([ readGitLabDiscussion( client, `${itemPath}/discussions`, mergeRequest ? 'Merge request discussion' : 'Issue discussion', - codeScope + itemScope ), + mergeRequest && itemScope !== null + ? readGitLabDiffs(client, `${itemPath}/diffs`, `${itemPath}/changes`, itemScope) + : undefined, ]) - /** A source limited to a ref shows only the diffs of merge requests into that ref. */ - const showsChanges = - mergeRequest && - codeScope !== null && - (!codeScope?.ref || string(row.target_branch) === codeScope.ref) - const changes = showsChanges - ? await readGitLabDiffs(client, `${itemPath}/diffs`, `${itemPath}/changes`, codeScope) - : undefined return { ...document(row, collection), content: [ From 0f782b637f4963fe78c08b2543fec74a63feefdf Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:37:49 -0800 Subject: [PATCH 3/4] fix(gitlab): read a commit without its diff for a source that does not serve code --- apps/sim/lib/sim-search/live/gitlab.test.ts | 12 ++++++++++++ apps/sim/lib/sim-search/live/gitlab.ts | 8 +++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/apps/sim/lib/sim-search/live/gitlab.test.ts b/apps/sim/lib/sim-search/live/gitlab.test.ts index a791d49cba2..2c9ac04f22f 100644 --- a/apps/sim/lib/sim-search/live/gitlab.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab.test.ts @@ -303,6 +303,18 @@ describe('GitLab merge request reads', () => { expect(otherRef.requests).not.toContain(`${base}/diffs`) }) + it('reads a commit without its diff for a source that does not serve code', async () => { + const commitPath = `/api/v4/projects/42/repository/commits/${SHA}` + const { client, requests } = gitlab({ + [commitPath]: () => commit('Fix the cache race'), + [`${commitPath}/diff`]: () => [{ new_path: 'src/cache.ts', diff: '+fixed' }], + }) + const document = await readGitLab(client, SHA, '42', 'commits', undefined, null) + expect(document.content).toContain('Fix the cache race') + expect(document.content).not.toContain('+fixed') + expect(requests).not.toContain(`${commitPath}/diff`) + }) + it('stops reading diffs when an instance repeats a page instead of advancing', async () => { const files = Array.from({ length: 50 }, (_, index) => ({ new_path: `src/file${index}.ts`, diff --git a/apps/sim/lib/sim-search/live/gitlab.ts b/apps/sim/lib/sim-search/live/gitlab.ts index b0770be652e..89ade10ce94 100644 --- a/apps/sim/lib/sim-search/live/gitlab.ts +++ b/apps/sim/lib/sim-search/live/gitlab.ts @@ -653,19 +653,21 @@ export async function readGitLab( const commitPath = `${path}/repository/commits/${segment(id)}` const [row, changes] = await Promise.all([ client.json(commitPath).then(object), - readGitLabDiffs(client, `${commitPath}/diff`, undefined, codeScope ?? undefined), + codeScope === null + ? undefined + : readGitLabDiffs(client, `${commitPath}/diff`, undefined, codeScope), ]) const commit = commitDocument(row, project) const stats = object(row.stats) return { ...commit, content: [ - changes.warning, + 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, + changes?.content ?? 'Changes are not shown: they fall outside this source.', ] .filter(Boolean) .join('\n\n'), From 77cc0d2d3b3822629721bf99dc50b52ccfc82c85 Mon Sep 17 00:00:00 2001 From: Waleed Latif Date: Tue, 1 Dec 2026 00:49:45 -0800 Subject: [PATCH 4/4] test(gitlab): read through the real reader when checking a no-code source --- .../lib/sim-search/live/gitlab-admin.test.ts | 33 +++++++++++++------ 1 file changed, 23 insertions(+), 10 deletions(-) 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 2cf738cb95a..73487bc0ccc 100644 --- a/apps/sim/lib/sim-search/live/gitlab-admin.test.ts +++ b/apps/sim/lib/sim-search/live/gitlab-admin.test.ts @@ -215,18 +215,31 @@ describe('administrator-managed live GitLab authorization', () => { ).toHaveLength(1) }) it('reads with no repository content from a source that does not serve code', async () => { + const actual = await vi.importActual( + '@/lib/sim-search/live/gitlab' + ) + mocks.read.mockImplementation(actual.readGitLab) const current = await session({ ...source.config, contentTypes: 'merge_requests' }) - client.json.mockResolvedValue({ project_id: 42, iid: 9, author: { id: 8 }, assignees: [] }) - mocks.read.mockResolvedValue({ - id: '9', - container: '42', - kind: 'merge_requests', - title: '', - url: '', - content: '', + const mergeRequest = { + project_id: 42, + iid: 9, + title: 'Add cache', + description: 'Adds the cache layer', + target_branch: 'main', + author: { id: 8 }, + assignees: [], + } + client.json.mockImplementation(async (path: string) => { + if (path.endsWith('/merge_requests/9')) return mergeRequest + if (path.endsWith('/merge_requests/9/discussions')) return [] + if (path.endsWith('/merge_requests/9/diffs')) + return [{ new_path: 'src/secret.ts', old_path: 'src/secret.ts', diff: '+const key = 1' }] + return project }) - await current.read({ id: '9', container: '42', kind: 'merge_requests' }) - expect(mocks.read.mock.calls[0]?.[5]).toBeNull() + const document = await current.read({ id: '9', container: '42', kind: 'merge_requests' }) + expect(document.content).toContain('Adds the cache layer') + expect(document.content).not.toContain('const key') + expect(document.content).toContain('Changes are not shown') }) 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' })