Skip to content

Commit fd24aa5

Browse files
committed
fix(search-experts): add up a person's work across sources, cite evidence, keep self-declared emails out of identity
- Contributors resolve to their directory person before ranking, so an email in one source and a unique name in another add up. - An item two connected accounts both return counts once. - GitHub people are named by login; git commit emails and GitLab public emails no longer identify anyone; Slack file authors count. - Linear emails and the Drive last editor are fetched only for expert searches. - A Slack ID that two workspaces give different people resolves to no one, and Slack emails are folded. - The Assistant's citation readers collect expert evidence; its summary mentions outside contributors. - Without directory access, department and location filters no longer hide every contributor; the note says they were not applied. - The workflow tool projects every filter a secret could fill, not only the query.
1 parent 6b6fb56 commit fd24aa5

14 files changed

Lines changed: 175 additions & 41 deletions

File tree

‎apps/sim/lib/internal/organization-search/search-experts.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,10 @@ export const searchOrganizationExperts: OrganizationSearchToolHandler = async (c
99
const parsed = parseInternalOperationInput({ body: searchExpertsInputSchema }, call.input)
1010
if (!parsed.success) return parsed.response
1111
const input = parsed.data.body
12-
return respondWithResultProvenance(call, input.query, (registry) =>
12+
const { query, source, startDate, endDate, department, location } = input
13+
// Every argument a run's secret could fill is projected out of what the sources return.
14+
const modelInput = [query, source, startDate, endDate, department, location].filter(Boolean)
15+
return respondWithResultProvenance(call, modelInput, (registry) =>
1316
searchExperts.execute({
1417
principal: call.principal,
1518
input: {

‎apps/sim/lib/knowledge/application/experts.integration.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -240,3 +240,36 @@ it('counts an item once per person at their strongest role, and caps chat messag
240240
expect(contributions[billingDev]).toEqual([{ source: 'jira', role: 'assignee', count: 1 }])
241241
expect(contributions[billingLead]).toEqual([{ source: 'slack', role: 'author', count: 5 }])
242242
})
243+
244+
it("adds up one person's work however each source names them", async () => {
245+
liveItems.value = [
246+
item('jira', 'ENG-8', [{ role: 'assignee', email: email(billingDev) }]),
247+
item('confluence', 'page-8', [{ role: 'author', name: 'Pat Developer' }]),
248+
]
249+
const result = await search()
250+
expect(result.experts.map((expert) => expert.personId)).toEqual([billingDev])
251+
expect(result.experts[0]?.contributions).toEqual(
252+
expect.arrayContaining([
253+
{ source: 'jira', role: 'assignee', count: 1 },
254+
{ source: 'confluence', role: 'author', count: 1 },
255+
])
256+
)
257+
})
258+
259+
it('counts an item two connected accounts both return once', async () => {
260+
liveItems.value = [
261+
item('jira', 'ENG-9', [{ role: 'assignee', email: email(billingDev) }]),
262+
item('jira', 'ENG-9', [{ role: 'assignee', email: email(billingDev) }]),
263+
]
264+
const result = await search()
265+
expect(result.experts[0]?.contributions).toEqual([{ source: 'jira', role: 'assignee', count: 1 }])
266+
expect(result.experts[0]?.evidence).toHaveLength(1)
267+
})
268+
269+
it('still names contributors when the directory is closed and a department is asked for', async () => {
270+
peopleOpen.value = false
271+
const result = await search({ department: 'platform' })
272+
expect(result.experts).toEqual([])
273+
expect(result.otherContributors?.length).toBeGreaterThan(0)
274+
expect(result.note).toMatch(/department and location filters were not applied/)
275+
})

‎apps/sim/lib/knowledge/application/experts.ts‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ import { resolveKnowledgeOrganizationContext } from '@/lib/knowledge/application
99
import { knowledgeOperations } from '@/lib/knowledge/application/operations'
1010
import { type RankedContributor, rankContributors } from '@/lib/knowledge/experts/rank'
1111
import { canLookUpPeople, personFacts } from '@/lib/people/directory-lookup'
12-
import { foldDirectoryName, resolveDirectoryIdentities } from '@/lib/people/repository'
12+
import {
13+
type DirectoryIdentity,
14+
foldDirectoryName,
15+
resolveDirectoryIdentities,
16+
} from '@/lib/people/repository'
1317
import { connectHint } from '@/lib/sim-search/live/activity'
1418
import { type LiveContributionItem, searchLiveKnowledge } from '@/lib/sim-search/live/application'
1519
import type { ResolvedSecretTraceRegistry } from '@/executor/utils/resolved-secret-trace-registry'
@@ -125,10 +129,21 @@ export const searchExperts = defineAuthorizedKnowledgeUseCase({
125129
})
126130
: undefined
127131
const slackEmails = directory?.slackEmails ?? new Map<string, string>()
132+
const people = new Map<string, DirectoryIdentity>()
128133
const identities = new Map<string, ContributorIdentity>()
134+
/** One key per directory person, however each source names them, so their work adds up. */
129135
const ranked = rankContributors(items, (contributor, provider) => {
130136
const identity = contributorIdentity(contributor, provider, slackEmails)
131137
if (!identity) return undefined
138+
const person =
139+
identity.email !== undefined
140+
? directory?.byEmail.get(identity.email)
141+
: directory?.byName.get(foldDirectoryName(identity.name))
142+
if (person) {
143+
const key = `person:${person.memberId}`
144+
people.set(key, person)
145+
return key
146+
}
132147
const key =
133148
identity.email !== undefined
134149
? `email:${identity.email}`
@@ -137,34 +152,29 @@ export const searchExperts = defineAuthorizedKnowledgeUseCase({
137152
return key
138153
})
139154

155+
const filtered = Boolean(input.department || input.location)
140156
const experts: Expert[] = []
141157
const others: OtherContributor[] = []
142-
const seen = new Set<string>()
143158
for (const { key, ...ranking } of ranked) {
144-
const identity = identities.get(key)
145-
const person = !identity
146-
? undefined
147-
: identity.email !== undefined
148-
? directory?.byEmail.get(identity.email)
149-
: directory?.byName.get(foldDirectoryName(identity.name))
159+
const person = people.get(key)
150160
if (person) {
151-
if (seen.has(person.memberId)) continue
152-
seen.add(person.memberId)
153161
if (
154-
!contains(person.department, input.department) ||
155-
!contains(person.location, input.location)
162+
experts.length < input.topK &&
163+
contains(person.department, input.department) &&
164+
contains(person.location, input.location)
156165
)
157-
continue
158-
if (experts.length < input.topK) experts.push({ ...personFacts(person), ...ranking })
159-
} else if (!input.department && !input.location && others.length < MAX_OTHER_CONTRIBUTORS) {
160-
others.push({ ...identity, ...ranking })
166+
experts.push({ ...personFacts(person), ...ranking })
167+
} else if ((!filtered || !directoryOpen) && others.length < MAX_OTHER_CONTRIBUTORS) {
168+
others.push({ ...identities.get(key), ...ranking })
161169
}
162170
}
163171

164172
const notes: string[] = []
165173
if (!directoryOpen)
166174
notes.push(
167-
'The People directory is not available to you here, so experts are named as their sources name them, without profiles.'
175+
filtered
176+
? 'The People directory is not available to you here, so experts are named as their sources name them, without profiles, and the department and location filters were not applied.'
177+
: 'The People directory is not available to you here, so experts are named as their sources name them, without profiles.'
168178
)
169179
if (!experts.length && !others.length)
170180
notes.push(

‎apps/sim/lib/knowledge/experts/rank.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,12 @@ export function rankContributors(
6868
now = Date.now()
6969
): RankedContributor[] {
7070
const people = new Map<string, Tally>()
71+
/** Two connected accounts can return the same item, at the same link; its work counts once. */
72+
const counted = new Set<string>()
7173
for (const item of items) {
74+
const itemKey = `${item.provider}\n${item.result.sourceUrl ?? item.result.documentId}`
75+
if (counted.has(itemKey)) continue
76+
counted.add(itemKey)
7277
const strongest = new Map<string, LiveContributionRole>()
7378
for (const contributor of item.contributors) {
7479
const key = keyOf(contributor, item.provider)

‎apps/sim/lib/mothership/chat/citation-evidence.ts‎

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { toRecordOrNull } from '@sim/utils/object'
1+
import { toArray, toRecordOrNull } from '@sim/utils/object'
22

33
export interface RetrievalCitationBlock {
44
toolCall?: { name: string; status: string; result?: { success: boolean; output?: unknown } }
@@ -20,6 +20,7 @@ const CITATION_TOOLS = new Set([
2020
'search_workspace',
2121
'read_document',
2222
'list_my_activity',
23+
'search_experts',
2324
...WEB_TOOLS,
2425
])
2526

@@ -51,6 +52,14 @@ export function toCitationResult(
5152
sourceDate: result.timestamp,
5253
content: result.snippet,
5354
}
55+
if (toolName === 'search_experts' && typeof result.documentName !== 'string')
56+
return {
57+
citationId: result.citationId,
58+
citationUrl: result.citationUrl,
59+
documentName: result.title,
60+
connectorType: result.source,
61+
sourceDate: result.date,
62+
}
5463
if (!isWebResearchTool(toolName) || typeof result.citationUrl === 'string') return result
5564
return {
5665
citationId: result.citationId,
@@ -74,10 +83,15 @@ export function parseCitationRecord(value: unknown): Record<string, unknown> | n
7483

7584
/**
7685
* The entries of one tool result that may each be a source. Activity lists its entries under
77-
* `items`; a saved result, once compacted, keeps them under `results` like every other tool.
86+
* `items`, and expert search its evidence under each expert and outside contributor; a saved
87+
* result, once compacted, keeps them under `results` like every other tool.
7888
*/
7989
export function citationResults(toolName: string, data: Record<string, unknown>): unknown[] {
8090
if (toolName === 'list_my_activity' && Array.isArray(data.items)) return data.items
91+
if (toolName === 'search_experts' && Array.isArray(data.experts))
92+
return [...data.experts, ...toArray(data.otherContributors)].flatMap((person) =>
93+
toArray(toRecordOrNull(person)?.evidence)
94+
)
8195
return Array.isArray(data.results) ? data.results : [data]
8296
}
8397

‎apps/sim/lib/mothership/chat/retrieval-citations.test.ts‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, expect, it } from 'vitest'
2+
import { collectRetrievalCitationEvidence } from '@/lib/mothership/chat/citation-evidence'
23
import { compactRetrievalCitations } from '@/lib/mothership/chat/retrieval-citations'
34

45
describe('persisted retrieval citations', () => {
@@ -73,4 +74,42 @@ describe('persisted retrieval citations', () => {
7374
).toBeUndefined()
7475
expect(compactRetrievalCitations('web_search', { error: 'Search failed' })).toBeUndefined()
7576
})
77+
78+
it("cites an expert search's evidence, from the full result and once compacted", () => {
79+
const evidence = (citationId: string) => ({
80+
documentId: citationId,
81+
title: `Item ${citationId}`,
82+
citationUrl: `https://example.test/${citationId}`,
83+
citationId,
84+
source: 'jira',
85+
role: 'assignee',
86+
date: '2026-11-02T00:00:00Z',
87+
})
88+
const output = {
89+
success: true,
90+
data: {
91+
experts: [{ personId: 'p1', evidence: [evidence('live:a')] }],
92+
otherContributors: [{ name: 'Outside', evidence: [evidence('live:b')] }],
93+
sources: [],
94+
},
95+
}
96+
const cited = (result: unknown) =>
97+
[
98+
...collectRetrievalCitationEvidence([
99+
{
100+
toolCall: {
101+
name: 'search_experts',
102+
status: 'success',
103+
result: { success: true, output: result },
104+
},
105+
},
106+
]).entries(),
107+
].map(([id, source]) => [id, source.url, source.title])
108+
const expected = [
109+
['live:a', 'https://example.test/live:a', 'Item live:a'],
110+
['live:b', 'https://example.test/live:b', 'Item live:b'],
111+
]
112+
expect(cited(output)).toEqual(expected)
113+
expect(cited(compactRetrievalCitations('search_experts', output))).toEqual(expected)
114+
})
76115
})

‎apps/sim/lib/mothership/tools/server/knowledge/experts.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,10 @@ export const searchExpertsServerTool: BaseServerTool = {
4848
return {
4949
success: true,
5050
message: [
51-
`Found ${data.experts.length} experts, highest score first.`,
51+
`Found ${data.experts.length} experts in the directory, highest score first.`,
52+
data.otherContributors?.length
53+
? `otherContributors lists ${data.otherContributors.length} more people the sources name who are not matched to the directory.`
54+
: '',
5255
reconnect.length
5356
? `Not read: ${reconnect.map((source) => source.source).join(', ')}. Offer to reconnect each with oauth_get_auth_link using its connect.providerId.`
5457
: '',

‎apps/sim/lib/people/repository.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,7 +344,16 @@ export async function resolveDirectoryIdentities(
344344
)
345345
)
346346
: []
347-
const slackEmails = new Map(slackRows.map((row) => [row.slackUserId, row.email]))
347+
/** A Slack ID two workspaces give different people resolves to no one; names stay the fallback. */
348+
const slackEmails = new Map<string, string>()
349+
const conflicting = new Set<string>()
350+
for (const row of slackRows) {
351+
const email = normalizeEmail(row.email)
352+
const held = slackEmails.get(row.slackUserId)
353+
if (held !== undefined && held !== email) conflicting.add(row.slackUserId)
354+
else slackEmails.set(row.slackUserId, email)
355+
}
356+
for (const slackUserId of conflicting) slackEmails.delete(slackUserId)
348357
const wantedEmails = [...new Set([...emails, ...slackEmails.values()].map(normalizeEmail))]
349358
const wantedNames = [...new Set(names.map(foldDirectoryName))]
350359
const rows =

‎apps/sim/lib/sim-search/live/github.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
} from '@/lib/sim-search/live/http'
1616
import { collectNativePages, joinMessages } from '@/lib/sim-search/live/pages'
1717
import {
18+
type LiveContributionRole,
1819
liveContributor,
1920
type NativeClient,
2021
type NativeDocument,
@@ -39,14 +40,20 @@ function commitDocument(
3940
content: message,
4041
...(Number.isFinite(authored) ? { modifiedAt: new Date(authored).toISOString() } : {}),
4142
author: string(object(row.author).login) || string(object(commit.author).name),
43+
// A commit's git author email is whatever the committer wrote, so it never names a person.
4244
contributors: liveContributor('author', {
43-
name: string(object(commit.author).name),
44-
email: string(object(commit.author).email),
45+
name: string(object(row.author).login) || string(object(commit.author).name),
4546
providerUserId: string(object(row.author).login),
4647
}),
4748
}
4849
}
4950

51+
/** A GitHub account, named by its login: GitHub shares no verified email in search results. */
52+
function githubPerson(role: LiveContributionRole, value: unknown) {
53+
const login = string(object(value).login)
54+
return liveContributor(role, { name: login, providerUserId: login })
55+
}
56+
5057
function githubDocument(row: Record<string, unknown>, kind: string): NativeDocument {
5158
if (kind === 'commits') return commitDocument(row)
5259
const repository = object(row.repository)
@@ -85,10 +92,8 @@ function githubDocument(row: Record<string, unknown>, kind: string): NativeDocum
8592
modifiedAt: string(row.updated_at),
8693
author: string(object(row.user).login) || string(object(row.owner).login),
8794
contributors: [
88-
...liveContributor('author', { providerUserId: string(object(row.user).login) }),
89-
...array(row.assignees).flatMap((person) =>
90-
liveContributor('assignee', { providerUserId: string(person.login) })
91-
),
95+
...githubPerson('author', row.user),
96+
...array(row.assignees).flatMap((person) => githubPerson('assignee', person)),
9297
],
9398
}
9499
}

‎apps/sim/lib/sim-search/live/gitlab.ts‎

Lines changed: 3 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -158,19 +158,16 @@ function commitDocument(
158158
content: message,
159159
...(Number.isFinite(committed) ? { modifiedAt: new Date(committed).toISOString() } : {}),
160160
author: string(row.author_name),
161-
contributors: liveContributor('author', {
162-
name: string(row.author_name),
163-
email: string(row.author_email),
164-
}),
161+
// A commit's author email is whatever the committer wrote, so it never names a person.
162+
contributors: liveContributor('author', { name: string(row.author_name) }),
165163
}
166164
}
167165

168-
/** A GitLab user object: a name and username, and an email only where the user made it public. */
166+
/** A GitLab account: its name and username. Its public email is self-declared, so it is not used. */
169167
function gitlabPerson(role: LiveContributionRole, value: unknown) {
170168
const person = object(value)
171169
return liveContributor(role, {
172170
name: string(person.name),
173-
email: string(person.public_email),
174171
providerUserId: string(person.username),
175172
})
176173
}

0 commit comments

Comments
 (0)