birdclaw 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1060 @@
1
+ import { getNativeDb } from "./db";
2
+ import {
3
+ ensureIdentitySearchIndexForDmProfiles,
4
+ syncIdentitySearchIndexForProfileIds,
5
+ } from "./identity-search-index";
6
+ import { fetchProfileBioEntities } from "./profile-bio-entities";
7
+ import { fetchProfileSnapshots } from "./profile-history";
8
+ import { expandUrlsFromTexts } from "./url-expansion";
9
+ import { resolveProfilesForIds } from "./profile-resolver";
10
+ import { listDmConversations, listTimelineItems } from "./queries";
11
+ import type {
12
+ DmConversationItem,
13
+ ProfileAffiliation,
14
+ ProfileBioEntity,
15
+ ProfileRecord,
16
+ ProfileSnapshot,
17
+ TimelineItem,
18
+ UrlExpansionItem,
19
+ } from "./types";
20
+
21
+ export interface WhoisOptions {
22
+ account?: string;
23
+ dms?: boolean;
24
+ tweets?: boolean;
25
+ resolveProfiles?: boolean;
26
+ expandUrls?: boolean;
27
+ refreshProfileCache?: boolean;
28
+ refreshUrlCache?: boolean;
29
+ xurlFallback?: boolean;
30
+ context?: number;
31
+ limit?: number;
32
+ affiliation?: string;
33
+ currentAffiliation?: string;
34
+ excludeDomainOnly?: boolean;
35
+ }
36
+
37
+ export interface WhoisCandidate {
38
+ conversation: DmConversationItem;
39
+ confidence: number;
40
+ category: WhoisCandidateCategory;
41
+ reasons: string[];
42
+ profileEvidence: WhoisEvidenceSignal[];
43
+ evidence: Array<{
44
+ messageId: string;
45
+ createdAt: string;
46
+ direction: string;
47
+ text: string;
48
+ urlExpansions?: UrlExpansionItem[];
49
+ }>;
50
+ }
51
+
52
+ export type WhoisCandidateCategory =
53
+ | "likely_affiliated"
54
+ | "ecosystem"
55
+ | "profile_or_link"
56
+ | "dm_context"
57
+ | "other";
58
+
59
+ export interface WhoisResult {
60
+ query: string;
61
+ candidates: WhoisCandidate[];
62
+ relatedTweets: TimelineItem[];
63
+ urlExpansions: UrlExpansionItem[];
64
+ profileResolution?: Awaited<ReturnType<typeof resolveProfilesForIds>>;
65
+ }
66
+
67
+ export interface WhoisEvidenceSignal {
68
+ kind:
69
+ | "profile_handle"
70
+ | "profile_name"
71
+ | "profile_bio"
72
+ | "profile_location"
73
+ | "profile_url"
74
+ | "profile_bio_url"
75
+ | "profile_verified_type"
76
+ | "affiliation"
77
+ | "bio_handle"
78
+ | "bio_domain"
79
+ | "bio_company"
80
+ | "profile_history"
81
+ | "dm_context"
82
+ | "expanded_url";
83
+ value: string;
84
+ source: "profile" | "affiliation" | "bio_entity" | "history" | "dm" | "url";
85
+ }
86
+
87
+ interface WhoisQueryIntent {
88
+ raw: string;
89
+ normalized: string;
90
+ terms: string[];
91
+ handles: string[];
92
+ domains: string[];
93
+ wantsPerson: boolean;
94
+ wantsAffiliation: boolean;
95
+ wantsDomain: boolean;
96
+ }
97
+
98
+ function normalizeQuery(query: string) {
99
+ return query.trim().toLowerCase();
100
+ }
101
+
102
+ function getSignificantQueryTerms(query: string) {
103
+ const stopwords = new Set([
104
+ "a",
105
+ "an",
106
+ "and",
107
+ "at",
108
+ "for",
109
+ "from",
110
+ "guy",
111
+ "is",
112
+ "of",
113
+ "person",
114
+ "the",
115
+ "who",
116
+ "with",
117
+ ]);
118
+ return Array.from(
119
+ new Set(
120
+ normalizeQuery(query)
121
+ .split(/[^a-z0-9_@.-]+/)
122
+ .map((term) => term.replace(/^@/, ""))
123
+ .filter((term) => term.length >= 3 && !stopwords.has(term)),
124
+ ),
125
+ );
126
+ }
127
+
128
+ function getQueryDomains(query: string) {
129
+ return Array.from(
130
+ new Set(
131
+ query
132
+ .toLowerCase()
133
+ .match(/\b(?:[a-z0-9-]+\.)+[a-z]{2,}\b/g)
134
+ ?.map((domain) => domain.replace(/^www\./, "")) ?? [],
135
+ ),
136
+ );
137
+ }
138
+
139
+ function getQueryHandles(query: string) {
140
+ return Array.from(
141
+ new Set(
142
+ query
143
+ .match(/@[A-Za-z0-9_]{1,15}\b/g)
144
+ ?.map((handle) => handle.toLowerCase()) ?? [],
145
+ ),
146
+ );
147
+ }
148
+
149
+ function getQueryIntent(query: string): WhoisQueryIntent {
150
+ const normalized = normalizeQuery(query);
151
+ const domains = getQueryDomains(query);
152
+ const handles = getQueryHandles(query);
153
+ const terms = getSignificantQueryTerms(query);
154
+ const wantsPerson =
155
+ /\b(guy|person|people|who|someone|staff|employee|devrel|founder|founders)\b/i.test(
156
+ query,
157
+ );
158
+ const wantsDomain =
159
+ domains.length > 0 ||
160
+ (/\b(link|url|domain|repo|repository|github\.com)\b/i.test(query) &&
161
+ !wantsPerson);
162
+ const wantsAffiliation =
163
+ handles.length > 0 ||
164
+ wantsPerson ||
165
+ /\b(at|from|works?|employee|staff|affiliation|company|org|devrel)\b/i.test(
166
+ query,
167
+ );
168
+ return {
169
+ raw: query,
170
+ normalized,
171
+ terms,
172
+ handles,
173
+ domains,
174
+ wantsPerson,
175
+ wantsAffiliation,
176
+ wantsDomain,
177
+ };
178
+ }
179
+
180
+ function matchesQueryText(query: string, value: string | undefined | null) {
181
+ if (!value) {
182
+ return false;
183
+ }
184
+ const normalizedValue = value.toLowerCase();
185
+ if (normalizedValue.includes(query)) {
186
+ return true;
187
+ }
188
+ return getSignificantQueryTerms(query).some((term) =>
189
+ normalizedValue.includes(term),
190
+ );
191
+ }
192
+
193
+ function getDmSearchQueries(query: string) {
194
+ const trimmed = query.trim();
195
+ const values = [trimmed, ...getSignificantQueryTerms(trimmed)];
196
+ return Array.from(new Set(values.filter((value) => value.length > 0)));
197
+ }
198
+
199
+ function getMessageTexts(conversation: DmConversationItem) {
200
+ return (conversation.matches ?? []).flatMap((match) => [
201
+ ...match.before.map((message) => message.text),
202
+ match.message.text,
203
+ ...match.after.map((message) => message.text),
204
+ ]);
205
+ }
206
+
207
+ function getUrlEntityExpandedUrl(entity: unknown) {
208
+ if (!entity || typeof entity !== "object") {
209
+ return undefined;
210
+ }
211
+ const record = entity as Record<string, unknown>;
212
+ const expanded = record.expandedUrl ?? record.expanded_url ?? record.url;
213
+ return typeof expanded === "string" && expanded.length > 0
214
+ ? expanded
215
+ : undefined;
216
+ }
217
+
218
+ function getProfileBioUrls(profile: ProfileRecord) {
219
+ const description = profile.entities?.description;
220
+ if (!description || typeof description !== "object") {
221
+ return [];
222
+ }
223
+ const urls = (description as { urls?: unknown }).urls;
224
+ if (!Array.isArray(urls)) {
225
+ return [];
226
+ }
227
+ return urls
228
+ .map(getUrlEntityExpandedUrl)
229
+ .filter((url): url is string => Boolean(url));
230
+ }
231
+
232
+ function getAffiliationTexts(affiliation: ProfileAffiliation) {
233
+ return [
234
+ affiliation.organizationName,
235
+ affiliation.organizationHandle,
236
+ affiliation.label,
237
+ affiliation.url,
238
+ affiliation.organizationProfileId,
239
+ ].filter((item): item is string => Boolean(item));
240
+ }
241
+
242
+ function pushMatchEvidence(
243
+ signals: WhoisEvidenceSignal[],
244
+ query: string,
245
+ kind: WhoisEvidenceSignal["kind"],
246
+ value: string | undefined | null,
247
+ source: WhoisEvidenceSignal["source"],
248
+ ) {
249
+ if (!matchesQueryText(query, value)) {
250
+ return;
251
+ }
252
+ signals.push({ kind, value: String(value), source });
253
+ }
254
+
255
+ function getSnapshotAffiliationTexts(snapshot: ProfileSnapshot) {
256
+ return snapshot.affiliations.flatMap((affiliation) => {
257
+ if (!affiliation || typeof affiliation !== "object") {
258
+ return [];
259
+ }
260
+ const record = affiliation as Record<string, unknown>;
261
+ return [
262
+ record.organizationName,
263
+ record.organizationHandle,
264
+ record.label,
265
+ record.url,
266
+ ].filter(
267
+ (item): item is string => typeof item === "string" && item.length > 0,
268
+ );
269
+ });
270
+ }
271
+
272
+ function getHistoricalSnapshotTexts(
273
+ snapshot: ProfileSnapshot,
274
+ profile: ProfileRecord,
275
+ ) {
276
+ const texts: string[] = [];
277
+ if (snapshot.handle !== profile.handle) {
278
+ texts.push(`previous handle: @${snapshot.handle}`);
279
+ }
280
+ if (snapshot.displayName !== profile.displayName) {
281
+ texts.push(`previous name: ${snapshot.displayName}`);
282
+ }
283
+ if (snapshot.bio !== profile.bio) {
284
+ texts.push(`previous bio: ${snapshot.bio}`);
285
+ }
286
+ if (snapshot.location && snapshot.location !== (profile.location ?? null)) {
287
+ texts.push(`previous location: ${snapshot.location}`);
288
+ }
289
+ if (snapshot.url && snapshot.url !== (profile.url ?? null)) {
290
+ texts.push(`previous url: ${snapshot.url}`);
291
+ }
292
+ if (
293
+ snapshot.verifiedType &&
294
+ snapshot.verifiedType !== (profile.verifiedType ?? null)
295
+ ) {
296
+ texts.push(`previous verified: ${snapshot.verifiedType}`);
297
+ }
298
+ const currentAffiliationTexts = new Set(
299
+ (profile.affiliations ?? [])
300
+ .flatMap((affiliation) => [
301
+ affiliation.organizationName,
302
+ affiliation.organizationHandle,
303
+ affiliation.label,
304
+ affiliation.url,
305
+ ])
306
+ .filter((item): item is string => Boolean(item))
307
+ .map((item) => item.toLowerCase()),
308
+ );
309
+ const previousAffiliationTexts = getSnapshotAffiliationTexts(snapshot);
310
+ if (
311
+ previousAffiliationTexts.some(
312
+ (text) => !currentAffiliationTexts.has(text.toLowerCase()),
313
+ )
314
+ ) {
315
+ texts.push(
316
+ `previous affiliations: ${JSON.stringify(snapshot.affiliations)}`,
317
+ );
318
+ }
319
+ return texts;
320
+ }
321
+
322
+ function collectProfileEvidence(
323
+ query: string,
324
+ profile: ProfileRecord,
325
+ bioEntities: ProfileBioEntity[] = [],
326
+ snapshots: ProfileSnapshot[] = [],
327
+ ) {
328
+ const signals: WhoisEvidenceSignal[] = [];
329
+ pushMatchEvidence(
330
+ signals,
331
+ query,
332
+ "profile_handle",
333
+ profile.handle,
334
+ "profile",
335
+ );
336
+ pushMatchEvidence(
337
+ signals,
338
+ query,
339
+ "profile_name",
340
+ profile.displayName,
341
+ "profile",
342
+ );
343
+ pushMatchEvidence(signals, query, "profile_bio", profile.bio, "profile");
344
+ pushMatchEvidence(
345
+ signals,
346
+ query,
347
+ "profile_location",
348
+ profile.location,
349
+ "profile",
350
+ );
351
+ pushMatchEvidence(signals, query, "profile_url", profile.url, "profile");
352
+ pushMatchEvidence(
353
+ signals,
354
+ query,
355
+ "profile_verified_type",
356
+ profile.verifiedType,
357
+ "profile",
358
+ );
359
+ for (const url of getProfileBioUrls(profile)) {
360
+ pushMatchEvidence(signals, query, "profile_bio_url", url, "profile");
361
+ }
362
+ for (const affiliation of profile.affiliations ?? []) {
363
+ for (const text of getAffiliationTexts(affiliation)) {
364
+ pushMatchEvidence(signals, query, "affiliation", text, "affiliation");
365
+ }
366
+ }
367
+ for (const entity of bioEntities) {
368
+ const kind =
369
+ entity.kind === "handle"
370
+ ? "bio_handle"
371
+ : entity.kind === "domain"
372
+ ? "bio_domain"
373
+ : "bio_company";
374
+ pushMatchEvidence(signals, query, kind, entity.value, "bio_entity");
375
+ }
376
+ for (const snapshot of snapshots) {
377
+ for (const text of getHistoricalSnapshotTexts(snapshot, profile)) {
378
+ pushMatchEvidence(
379
+ signals,
380
+ query,
381
+ "profile_history",
382
+ `${snapshot.lastSeenAt}: ${text}`,
383
+ "history",
384
+ );
385
+ }
386
+ }
387
+ return signals;
388
+ }
389
+
390
+ const DOMAIN_ONLY_EVIDENCE = new Set<WhoisEvidenceSignal["kind"]>([
391
+ "profile_url",
392
+ "profile_bio_url",
393
+ "bio_domain",
394
+ "expanded_url",
395
+ ]);
396
+
397
+ function getEvidenceWeight(
398
+ signal: WhoisEvidenceSignal,
399
+ intent: WhoisQueryIntent,
400
+ profile: ProfileRecord,
401
+ ) {
402
+ const bio = profile.bio.toLowerCase();
403
+ const ecosystemPenalty =
404
+ signal.kind === "bio_handle" || signal.kind === "bio_company"
405
+ ? isEcosystemMention(bio, intent)
406
+ : false;
407
+ switch (signal.kind) {
408
+ case "affiliation":
409
+ return 72;
410
+ case "bio_handle":
411
+ return ecosystemPenalty ? 20 : 56;
412
+ case "bio_company":
413
+ return ecosystemPenalty ? 16 : 46;
414
+ case "profile_history":
415
+ return 36;
416
+ case "profile_handle":
417
+ return intent.handles.length > 0 ? 44 : 24;
418
+ case "profile_name":
419
+ case "profile_bio":
420
+ return 24;
421
+ case "dm_context":
422
+ return intent.wantsAffiliation ? 12 : 22;
423
+ case "expanded_url":
424
+ return intent.wantsDomain ? 26 : 8;
425
+ case "profile_url":
426
+ case "profile_bio_url":
427
+ case "bio_domain":
428
+ return intent.wantsDomain ? 30 : 8;
429
+ case "profile_location":
430
+ case "profile_verified_type":
431
+ return 8;
432
+ }
433
+ }
434
+
435
+ function isEcosystemMention(bio: string, intent: WhoisQueryIntent) {
436
+ const terms = new Set([
437
+ ...intent.terms,
438
+ ...intent.handles.map((handle) => handle.replace(/^@/, "")),
439
+ ]);
440
+ for (const term of terms) {
441
+ const escaped = term.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
442
+ if (
443
+ new RegExp(
444
+ `\\b${escaped}\\s+(star|stars|sponsor|sponsors|campus expert|expert|partner|alumni)\\b`,
445
+ "i",
446
+ ).test(bio)
447
+ ) {
448
+ return true;
449
+ }
450
+ }
451
+ return false;
452
+ }
453
+
454
+ function hasCurrentAffiliationMatch(
455
+ profile: ProfileRecord,
456
+ affiliationQuery: string | undefined,
457
+ ) {
458
+ if (!affiliationQuery?.trim()) {
459
+ return true;
460
+ }
461
+ const normalized = normalizeQuery(affiliationQuery);
462
+ return (profile.affiliations ?? []).some((affiliation) =>
463
+ getAffiliationTexts(affiliation).some((text) =>
464
+ matchesQueryText(normalized, text),
465
+ ),
466
+ );
467
+ }
468
+
469
+ function hasAffiliationEvidenceMatch(
470
+ profile: ProfileRecord,
471
+ profileEvidence: WhoisEvidenceSignal[],
472
+ affiliationQuery: string | undefined,
473
+ ) {
474
+ if (!affiliationQuery?.trim()) {
475
+ return true;
476
+ }
477
+ const normalized = normalizeQuery(affiliationQuery);
478
+ if (hasCurrentAffiliationMatch(profile, affiliationQuery)) {
479
+ return true;
480
+ }
481
+ return profileEvidence.some(
482
+ (signal) =>
483
+ (signal.kind === "affiliation" ||
484
+ signal.kind === "bio_handle" ||
485
+ signal.kind === "bio_company" ||
486
+ signal.kind === "profile_history") &&
487
+ matchesQueryText(normalized, signal.value),
488
+ );
489
+ }
490
+
491
+ function hasNonDomainEvidence(profileEvidence: WhoisEvidenceSignal[]) {
492
+ return profileEvidence.some(
493
+ (signal) => !DOMAIN_ONLY_EVIDENCE.has(signal.kind),
494
+ );
495
+ }
496
+
497
+ function getCandidateCategory(
498
+ profile: ProfileRecord,
499
+ profileEvidence: WhoisEvidenceSignal[],
500
+ intent: WhoisQueryIntent,
501
+ messageMatched: boolean,
502
+ ): WhoisCandidateCategory {
503
+ if (profileEvidence.some((signal) => signal.kind === "affiliation")) {
504
+ return "likely_affiliated";
505
+ }
506
+ if (
507
+ profileEvidence.some(
508
+ (signal) =>
509
+ signal.kind === "bio_handle" ||
510
+ signal.kind === "bio_company" ||
511
+ signal.kind === "profile_history",
512
+ )
513
+ ) {
514
+ return isEcosystemMention(profile.bio.toLowerCase(), intent)
515
+ ? "ecosystem"
516
+ : "likely_affiliated";
517
+ }
518
+ if (profileEvidence.some((signal) => DOMAIN_ONLY_EVIDENCE.has(signal.kind))) {
519
+ return "profile_or_link";
520
+ }
521
+ return messageMatched ? "dm_context" : "other";
522
+ }
523
+
524
+ function scoreCandidate(
525
+ query: string,
526
+ conversation: DmConversationItem,
527
+ expansions: UrlExpansionItem[],
528
+ bioEntities: ProfileBioEntity[] = [],
529
+ snapshots: ProfileSnapshot[] = [],
530
+ ) {
531
+ const normalized = normalizeQuery(query);
532
+ const intent = getQueryIntent(query);
533
+ const profile = conversation.participant;
534
+ const profileEvidence = collectProfileEvidence(
535
+ normalized,
536
+ profile,
537
+ bioEntities,
538
+ snapshots,
539
+ );
540
+ const affiliationTexts = (profile.affiliations ?? []).flatMap(
541
+ getAffiliationTexts,
542
+ );
543
+ const profileBioUrls = getProfileBioUrls(profile);
544
+ const bioEntityTexts = bioEntities.map((entity) => entity.value);
545
+ const profileHistoryTexts = snapshots.flatMap((snapshot) =>
546
+ getHistoricalSnapshotTexts(snapshot, profile),
547
+ );
548
+ const messageTexts = getMessageTexts(conversation);
549
+ const haystack = [
550
+ conversation.title,
551
+ profile.handle,
552
+ profile.displayName,
553
+ profile.bio,
554
+ profile.location,
555
+ profile.url,
556
+ profile.verifiedType,
557
+ ...profileBioUrls,
558
+ ...affiliationTexts,
559
+ ...bioEntityTexts,
560
+ ...profileHistoryTexts,
561
+ ...messageTexts,
562
+ ]
563
+ .filter(Boolean)
564
+ .join("\n")
565
+ .toLowerCase();
566
+ const reasons: string[] = [];
567
+ let confidence = 0;
568
+
569
+ if (!/^id\d+$/.test(conversation.participant.handle)) {
570
+ confidence += 18;
571
+ reasons.push("resolved profile");
572
+ }
573
+ if (
574
+ matchesQueryText(normalized, profile.handle) ||
575
+ matchesQueryText(normalized, profile.displayName) ||
576
+ matchesQueryText(normalized, profile.bio)
577
+ ) {
578
+ confidence += 18;
579
+ reasons.push("profile matches query");
580
+ }
581
+ if (
582
+ matchesQueryText(normalized, profile.url) ||
583
+ profileBioUrls.some((url) => matchesQueryText(normalized, url))
584
+ ) {
585
+ confidence += intent.wantsDomain ? 28 : 8;
586
+ reasons.push("profile URL matches query");
587
+ }
588
+ if (profileEvidence.some((signal) => signal.kind === "affiliation")) {
589
+ confidence += 40;
590
+ reasons.push("affiliation matches query");
591
+ }
592
+ if (profileEvidence.some((signal) => signal.source === "bio_entity")) {
593
+ confidence += 24;
594
+ reasons.push("bio entity matches query");
595
+ }
596
+ if (profileEvidence.some((signal) => signal.source === "history")) {
597
+ confidence += 20;
598
+ reasons.push("profile history matches query");
599
+ }
600
+ if (haystack.includes("co-founder") || haystack.includes("cofounder")) {
601
+ confidence += 25;
602
+ reasons.push("cofounder language");
603
+ }
604
+ const messageMatched = messageTexts.some((text) =>
605
+ matchesQueryText(normalized, text),
606
+ );
607
+ if (messageMatched) {
608
+ confidence += intent.wantsAffiliation ? 10 : 18;
609
+ reasons.push("message text matches query");
610
+ profileEvidence.push({
611
+ kind: "dm_context",
612
+ value: query,
613
+ source: "dm",
614
+ });
615
+ }
616
+ if (expansions.some((item) => matchesQueryText(normalized, item.finalUrl))) {
617
+ confidence += intent.wantsDomain ? 20 : 8;
618
+ reasons.push("expanded URL matches query");
619
+ for (const item of expansions) {
620
+ pushMatchEvidence(
621
+ profileEvidence,
622
+ normalized,
623
+ "expanded_url",
624
+ item.finalUrl,
625
+ "url",
626
+ );
627
+ }
628
+ }
629
+
630
+ for (const signal of profileEvidence) {
631
+ confidence += getEvidenceWeight(signal, intent, profile);
632
+ }
633
+ const category = getCandidateCategory(
634
+ profile,
635
+ profileEvidence,
636
+ intent,
637
+ messageMatched,
638
+ );
639
+ if (category === "ecosystem") {
640
+ confidence -= 24;
641
+ reasons.push("ecosystem mention, not direct affiliation");
642
+ }
643
+ if (category === "profile_or_link" && intent.wantsAffiliation) {
644
+ confidence -= 18;
645
+ }
646
+
647
+ return {
648
+ confidence: Math.max(0, Math.min(100, confidence)),
649
+ category,
650
+ reasons: reasons.length > 0 ? reasons : ["local DM match"],
651
+ profileEvidence,
652
+ };
653
+ }
654
+
655
+ function attachExpansionsToMatches(
656
+ conversation: DmConversationItem,
657
+ expansions: UrlExpansionItem[],
658
+ ) {
659
+ for (const match of conversation.matches ?? []) {
660
+ const matchUrls = new Set(
661
+ [...match.before, match.message, ...match.after].flatMap((message) =>
662
+ expansions
663
+ .filter((item) => message.text.includes(item.url))
664
+ .map((item) => item.url),
665
+ ),
666
+ );
667
+ if (matchUrls.size > 0) {
668
+ match.urlExpansions = expansions.filter((item) =>
669
+ matchUrls.has(item.url),
670
+ );
671
+ }
672
+ }
673
+ }
674
+
675
+ function mergeConversations(
676
+ target: Map<string, DmConversationItem>,
677
+ conversations: DmConversationItem[],
678
+ ) {
679
+ for (const conversation of conversations) {
680
+ if (!target.has(conversation.id)) {
681
+ target.set(conversation.id, conversation);
682
+ }
683
+ }
684
+ }
685
+
686
+ function findProfileEvidenceConversationIds(
687
+ query: string,
688
+ account: string | undefined,
689
+ limit: number,
690
+ ) {
691
+ const terms = [normalizeQuery(query), ...getSignificantQueryTerms(query)]
692
+ .filter((term) => term.length > 0)
693
+ .filter((term, index, array) => array.indexOf(term) === index);
694
+ if (terms.length === 0) {
695
+ return [];
696
+ }
697
+ const db = getNativeDb();
698
+ ensureIdentitySearchIndexForDmProfiles(db, account);
699
+ const clauses: string[] = [];
700
+ const params: Array<string | number> = [];
701
+ for (const term of terms) {
702
+ const pattern = `%${term}%`;
703
+ clauses.push("isi.normalized_value like ?");
704
+ params.push(pattern);
705
+ }
706
+
707
+ let accountClause = "";
708
+ if (account && account !== "all") {
709
+ accountClause = "and c.account_id = ?";
710
+ params.push(account);
711
+ }
712
+ params.push(limit);
713
+
714
+ const rows = db
715
+ .prepare(
716
+ `
717
+ select c.id, max(isi.weight) as max_weight
718
+ from dm_conversations c
719
+ join identity_search_index isi on isi.profile_id = c.participant_profile_id
720
+ where (${clauses.map((clause) => `(${clause})`).join(" or ")})
721
+ ${accountClause}
722
+ group by c.id
723
+ order by max_weight desc, c.last_message_at desc
724
+ limit ?
725
+ `,
726
+ )
727
+ .all(...params) as Array<{ id: string }>;
728
+ return rows.map((row) => row.id);
729
+ }
730
+
731
+ function loadWhoisConversations(
732
+ query: string,
733
+ options: WhoisOptions,
734
+ includeDms: boolean,
735
+ context: number,
736
+ limit: number,
737
+ ) {
738
+ if (!includeDms) {
739
+ return [];
740
+ }
741
+ const merged = new Map<string, DmConversationItem>();
742
+ const batchLimit = Math.max(limit * 3, 20);
743
+ for (const search of getDmSearchQueries(query)) {
744
+ mergeConversations(
745
+ merged,
746
+ listDmConversations({
747
+ account: options.account,
748
+ search,
749
+ context,
750
+ limit: batchLimit,
751
+ }),
752
+ );
753
+ }
754
+
755
+ const profileEvidenceIds = findProfileEvidenceConversationIds(
756
+ query,
757
+ options.account,
758
+ Math.max(limit * 5, 50),
759
+ );
760
+ if (profileEvidenceIds.length > 0) {
761
+ mergeConversations(
762
+ merged,
763
+ listDmConversations({
764
+ account: options.account,
765
+ conversationIds: profileEvidenceIds,
766
+ limit: profileEvidenceIds.length,
767
+ }),
768
+ );
769
+ }
770
+
771
+ return [...merged.values()];
772
+ }
773
+
774
+ export async function runWhois(
775
+ query: string,
776
+ options: WhoisOptions = {},
777
+ ): Promise<WhoisResult> {
778
+ const includeDms = options.dms ?? true;
779
+ const includeTweets = options.tweets ?? false;
780
+ const limit = options.limit ?? 10;
781
+ const context = options.context ?? 4;
782
+ let conversations = loadWhoisConversations(
783
+ query,
784
+ options,
785
+ includeDms,
786
+ context,
787
+ limit,
788
+ );
789
+ let profileResolution: WhoisResult["profileResolution"];
790
+
791
+ if (options.resolveProfiles ?? true) {
792
+ profileResolution = await resolveProfilesForIds(
793
+ conversations.map((item) => item.participant.id),
794
+ {
795
+ refresh: options.refreshProfileCache,
796
+ xurlFallback: options.xurlFallback ?? true,
797
+ },
798
+ );
799
+ conversations = loadWhoisConversations(
800
+ query,
801
+ options,
802
+ includeDms,
803
+ context,
804
+ limit,
805
+ );
806
+ }
807
+ syncIdentitySearchIndexForProfileIds(
808
+ getNativeDb(),
809
+ conversations.map((item) => item.participant.id),
810
+ );
811
+
812
+ const relatedTweets = includeTweets
813
+ ? [
814
+ ...listTimelineItems({
815
+ resource: "home",
816
+ account: options.account,
817
+ search: query,
818
+ limit,
819
+ }),
820
+ ...listTimelineItems({
821
+ resource: "mentions",
822
+ account: options.account,
823
+ search: query,
824
+ limit,
825
+ }),
826
+ ]
827
+ : [];
828
+
829
+ const texts = [
830
+ ...conversations.flatMap(getMessageTexts),
831
+ ...conversations.flatMap((conversation) =>
832
+ [
833
+ conversation.participant.bio,
834
+ conversation.participant.url ?? "",
835
+ ...getProfileBioUrls(conversation.participant),
836
+ ].filter((text) => text.includes("https://t.co/")),
837
+ ),
838
+ ...relatedTweets.map((tweet) => tweet.text),
839
+ ];
840
+ const urlExpansions =
841
+ (options.expandUrls ?? true)
842
+ ? await expandUrlsFromTexts(texts, { refresh: options.refreshUrlCache })
843
+ : [];
844
+ for (const conversation of conversations) {
845
+ attachExpansionsToMatches(conversation, urlExpansions);
846
+ }
847
+
848
+ const profileIds = conversations.map(
849
+ (conversation) => conversation.participant.id,
850
+ );
851
+ const bioEntitiesByProfile = fetchProfileBioEntities(
852
+ getNativeDb(),
853
+ profileIds,
854
+ );
855
+ const snapshotsByProfile = fetchProfileSnapshots(getNativeDb(), profileIds);
856
+ const candidates = conversations
857
+ .map((conversation): WhoisCandidate | null => {
858
+ const conversationExpansions = urlExpansions.filter((item) =>
859
+ getMessageTexts(conversation).some((text) => text.includes(item.url)),
860
+ );
861
+ const profileId = conversation.participant.id;
862
+ const score = scoreCandidate(
863
+ query,
864
+ conversation,
865
+ conversationExpansions,
866
+ bioEntitiesByProfile.get(profileId) ?? [],
867
+ snapshotsByProfile.get(profileId) ?? [],
868
+ );
869
+ if (
870
+ !hasCurrentAffiliationMatch(
871
+ conversation.participant,
872
+ options.currentAffiliation,
873
+ )
874
+ ) {
875
+ return null;
876
+ }
877
+ if (
878
+ !hasAffiliationEvidenceMatch(
879
+ conversation.participant,
880
+ score.profileEvidence,
881
+ options.affiliation,
882
+ )
883
+ ) {
884
+ return null;
885
+ }
886
+ if (
887
+ options.excludeDomainOnly &&
888
+ !hasNonDomainEvidence(score.profileEvidence)
889
+ ) {
890
+ return null;
891
+ }
892
+ return {
893
+ conversation,
894
+ confidence: score.confidence,
895
+ category: score.category,
896
+ reasons: score.reasons,
897
+ profileEvidence: score.profileEvidence,
898
+ evidence: (conversation.matches ?? []).map((match) => ({
899
+ messageId: match.message.id,
900
+ createdAt: match.message.createdAt,
901
+ direction: match.message.direction,
902
+ text: match.message.text,
903
+ ...(match.urlExpansions
904
+ ? { urlExpansions: match.urlExpansions }
905
+ : {}),
906
+ })),
907
+ };
908
+ })
909
+ .filter((candidate): candidate is WhoisCandidate => candidate !== null)
910
+ .sort((left, right) => {
911
+ if (right.confidence !== left.confidence) {
912
+ return right.confidence - left.confidence;
913
+ }
914
+ return (
915
+ new Date(right.conversation.lastMessageAt).getTime() -
916
+ new Date(left.conversation.lastMessageAt).getTime()
917
+ );
918
+ })
919
+ .slice(0, limit);
920
+
921
+ return {
922
+ query,
923
+ candidates,
924
+ relatedTweets,
925
+ urlExpansions,
926
+ ...(profileResolution ? { profileResolution } : {}),
927
+ };
928
+ }
929
+
930
+ const CATEGORY_LABELS: Record<WhoisCandidateCategory, string> = {
931
+ likely_affiliated: "Likely affiliated",
932
+ ecosystem: "Ecosystem / role mentions",
933
+ profile_or_link: "Profile or link matches",
934
+ dm_context: "DM context matches",
935
+ other: "Other local matches",
936
+ };
937
+
938
+ function summarizeSignal(signal: WhoisEvidenceSignal) {
939
+ switch (signal.kind) {
940
+ case "affiliation":
941
+ return `current affiliation ${signal.value}`;
942
+ case "bio_handle":
943
+ return `bio handle ${signal.value}`;
944
+ case "bio_company":
945
+ return `bio company ${signal.value}`;
946
+ case "profile_history":
947
+ return `profile history ${signal.value}`;
948
+ case "profile_url":
949
+ case "profile_bio_url":
950
+ case "bio_domain":
951
+ return `domain/link ${signal.value}`;
952
+ case "dm_context":
953
+ return `DM context`;
954
+ case "expanded_url":
955
+ return `expanded URL ${signal.value}`;
956
+ default:
957
+ return `${signal.kind.replace(/^profile_/, "profile ")} ${signal.value}`;
958
+ }
959
+ }
960
+
961
+ function signalSummaryRank(signal: WhoisEvidenceSignal) {
962
+ switch (signal.kind) {
963
+ case "affiliation":
964
+ return 0;
965
+ case "bio_handle":
966
+ return 1;
967
+ case "bio_company":
968
+ return 2;
969
+ case "profile_history":
970
+ return 3;
971
+ case "dm_context":
972
+ return 4;
973
+ case "expanded_url":
974
+ return 5;
975
+ case "profile_url":
976
+ case "profile_bio_url":
977
+ case "bio_domain":
978
+ return 6;
979
+ default:
980
+ return 7;
981
+ }
982
+ }
983
+
984
+ function explainCandidate(candidate: WhoisCandidate) {
985
+ const evidence = candidate.profileEvidence
986
+ .slice()
987
+ .sort((left, right) => signalSummaryRank(left) - signalSummaryRank(right))
988
+ .slice(0, 4)
989
+ .map(summarizeSignal);
990
+ return evidence.length > 0
991
+ ? evidence.join(" + ")
992
+ : candidate.reasons.join(", ");
993
+ }
994
+
995
+ export function formatWhois(result: WhoisResult) {
996
+ const lines = [`Whois: ${result.query}`];
997
+ if (result.candidates.length === 0) {
998
+ lines.push("No matching DM candidates.");
999
+ } else {
1000
+ let activeCategory: WhoisCandidateCategory | undefined;
1001
+ for (const candidate of result.candidates) {
1002
+ const profile = candidate.conversation.participant;
1003
+ if (activeCategory !== candidate.category) {
1004
+ activeCategory = candidate.category;
1005
+ lines.push("");
1006
+ lines.push(CATEGORY_LABELS[candidate.category]);
1007
+ }
1008
+ lines.push("");
1009
+ lines.push(
1010
+ `${candidate.confidence}% @${profile.handle} (${profile.displayName})`,
1011
+ );
1012
+ lines.push(`Why: ${explainCandidate(candidate)}`);
1013
+ lines.push(`Reasons: ${candidate.reasons.join(", ")}`);
1014
+ lines.push(`Conversation: ${candidate.conversation.id}`);
1015
+ for (const signal of candidate.profileEvidence.slice(0, 5)) {
1016
+ lines.push(`Evidence: ${signal.kind}: ${signal.value}`);
1017
+ }
1018
+ for (const evidence of candidate.evidence.slice(0, 3)) {
1019
+ lines.push(
1020
+ `- ${evidence.createdAt} ${evidence.direction}: ${evidence.text}`,
1021
+ );
1022
+ for (const expansion of evidence.urlExpansions ?? []) {
1023
+ lines.push(` ${expansion.url} -> ${expansion.finalUrl}`);
1024
+ }
1025
+ }
1026
+ }
1027
+ }
1028
+
1029
+ if (result.relatedTweets.length > 0) {
1030
+ lines.push("");
1031
+ lines.push(`Related tweets: ${result.relatedTweets.length}`);
1032
+ for (const tweet of result.relatedTweets.slice(0, 5)) {
1033
+ lines.push(`- ${tweet.createdAt} @${tweet.author.handle}: ${tweet.text}`);
1034
+ }
1035
+ }
1036
+
1037
+ return lines.join("\n");
1038
+ }
1039
+
1040
+ export const __test__ = {
1041
+ getSignificantQueryTerms,
1042
+ getQueryDomains,
1043
+ getQueryHandles,
1044
+ getQueryIntent,
1045
+ matchesQueryText,
1046
+ getDmSearchQueries,
1047
+ getUrlEntityExpandedUrl,
1048
+ getProfileBioUrls,
1049
+ getAffiliationTexts,
1050
+ getSnapshotAffiliationTexts,
1051
+ getHistoricalSnapshotTexts,
1052
+ collectProfileEvidence,
1053
+ hasCurrentAffiliationMatch,
1054
+ hasAffiliationEvidenceMatch,
1055
+ hasNonDomainEvidence,
1056
+ scoreCandidate,
1057
+ explainCandidate,
1058
+ attachExpansionsToMatches,
1059
+ mergeConversations,
1060
+ };