Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

perf: reuse Beeper sweep roster for touchpoints (#9877)

Adam Eivy3742792951ba
diff --git a/server/services/beeperSync.js b/server/services/beeperSync.js
index 22e2cd8b18..70d057a3fb 100644
--- a/server/services/beeperSync.js
+++ b/server/services/beeperSync.js
@@ -659,7 +659,7 @@ async function sweepChat({
senderId: message.senderId,
sentAt: message.sentAt,
network: normalized.network,
- })));
+ })), { personIndex });
await commitMessages({
conversationId,
diff --git a/server/services/beeperSync.test.js b/server/services/beeperSync.test.js
index f700854227..c38d151513 100644
--- a/server/services/beeperSync.test.js
+++ b/server/services/beeperSync.test.js
@@ -457,6 +457,29 @@ describe('watermark-bounded sweep', () => {
expect(params.get('direction')).toBe('before');
});
+ it('shares one roster across chats and touchpoints, then refreshes it for the next sweep', async () => {
+ installFetch({
+ chatPages: [{ items: CHAT_PAGE.items.slice(0, 2), hasMore: false }],
+ messagePages: Object.fromEntries(['chat-1', 'chat-2'].map((chatId) => [chatId, {
+ items: [{ id: 'msg-1', senderID: 'user-1', timestamp: '2026-09-02T10:00:00.000Z', sortKey: '1', text: 'hi' }],
+ hasMore: false,
+ }])),
+ });
+
+ await runBeeperSweep({ reason: 'manual' });
+ expect(loadRosterIndexMock).toHaveBeenCalledTimes(1);
+ const firstIndex = await loadRosterIndexMock.mock.results[0].value;
+ expect(logSenderTouchpointsMock).toHaveBeenCalledTimes(2);
+ expect(logSenderTouchpointsMock.mock.calls.every(([, options]) => options.personIndex === firstIndex)).toBe(true);
+ expect(upsertParticipantMock.mock.calls.every(([input]) => input.personIndex === firstIndex)).toBe(true);
+
+ await runBeeperSweep({ reason: 'manual' });
+ expect(loadRosterIndexMock).toHaveBeenCalledTimes(2);
+ const nextIndex = await loadRosterIndexMock.mock.results[1].value;
+ expect(nextIndex).not.toBe(firstIndex);
+ expect(logSenderTouchpointsMock.mock.calls.slice(2).every(([, options]) => options.personIndex === nextIndex)).toBe(true);
+ });
+
it('relates senders and participants through beeperTribe rather than writing identity rows itself', async () => {
installFetch({
chatPages: [{ items: [CHAT_PAGE.items[0]], hasMore: false }],
diff --git a/server/services/beeperTribe.js b/server/services/beeperTribe.js
index 939df321e6..775992590e 100644
--- a/server/services/beeperTribe.js
+++ b/server/services/beeperTribe.js
@@ -221,9 +221,8 @@ export async function resolveParticipantPerson({ conversationId, sourceUserId },
/**
* Load and index the Tribe roster ONCE, for a caller (a sweep pass in
* `beeperSync.js`) about to resolve MANY participants and wants to hand the
- * same `personIndex` to every `upsertParticipant` call rather than let each
- * one reload and reindex every Tribe person for itself. Mirrors the batching
- * `logSenderTouchpoints` already does internally for its own candidate list.
+ * same `personIndex` to participant upserts and touchpoint batches rather than
+ * let each reload and reindex every Tribe person for itself.
*/
export async function loadRosterIndex() {
return buildPersonMatchIndex(await tribe.listPeople());
@@ -564,16 +563,16 @@ export async function createPersonAndLinkParticipant({
* candidate is `{ conversationId, senderId, sentAt, network, channel }`.
* Dedupe key is `beeper:<YYYY-MM-DD>`, matching #10 decision "daily Tribe
* touchpoints are written; there is no per-message activity event."
- * Returns `{ created, matched }` (mirrors `tribe.autoLogTouchpoints`'s shape).
+ * Accepts an optional sweep-scoped `personIndex`; standalone calls load one
+ * for the batch. Returns `{ created, matched }` (mirrors `tribe.autoLogTouchpoints`'s shape).
*/
-export async function logSenderTouchpoints(candidates = []) {
+export async function logSenderTouchpoints(candidates = [], { personIndex = null } = {}) {
if (!Array.isArray(candidates) || candidates.length === 0) return { created: 0, matched: 0 };
await ensureReady();
- // Built ONCE for the whole batch and threaded through resolveParticipantPerson's
- // phone fallback (mirrors tribe.autoLogTouchpoints), rather than every
- // resolution reloading and reindexing every Tribe person from scratch.
- const personIndex = buildPersonMatchIndex(await tribe.listPeople());
+ // Reuse the sweep snapshot, or load once for a standalone batch. Identity
+ // resolution still runs against current authoritative records.
+ const index = personIndex || await loadRosterIndex();
// Memoize the participant -> person resolution per (conversationId,
// senderId) within this batch, so a burst of messages from the same sender
@@ -591,7 +590,7 @@ export async function logSenderTouchpoints(candidates = []) {
// eslint-disable-next-line no-await-in-loop -- resolving one sender at a time; batch sizes here are one sync sweep, not a bulk import
personCache.set(cacheKey, await resolveParticipantPerson(
{ conversationId: c.conversationId, sourceUserId: c.senderId },
- personIndex,
+ index,
));
}
const personId = personCache.get(cacheKey);
diff --git a/server/services/beeperTribe.test.js b/server/services/beeperTribe.test.js
index f418f343e9..45b8252f6c 100644
--- a/server/services/beeperTribe.test.js
+++ b/server/services/beeperTribe.test.js
@@ -865,3 +865,72 @@ describe('logSenderTouchpoints batch deduplication', () => {
expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledTimes(20);
});
});
+
+describe('touchpoint roster reuse', () => {
+ const candidate = (conversationId = CONVERSATION) => ({
+ conversationId, senderId: 'user-1', sentAt: '2026-09-02T10:00:00.000Z', network: 'whatsapp',
+ });
+
+ beforeEach(() => {
+ tribeService.autoCreateTouchpoint.mockReset();
+ tribeService.autoCreateTouchpoint.mockResolvedValue({ id: 'example-touchpoint' });
+ });
+
+ it('reuses a sweep index while preserving authoritative claims and deleted cache handling', async () => {
+ listPeople.mockResolvedValue([{ id: LEGACY_PHONE_PERSON, name: 'Example', phones: [PHONE_NORMALIZED] }]);
+ seedParticipant({ handle: PHONE_RAW, tribePersonId: CACHED_PERSON, network: 'whatsapp' });
+ seedParticipant({ conversationId: OTHER_CONVERSATION, handle: '', tribePersonId: CACHED_PERSON });
+ db.identities.set(iKey('phone', '', PHONE_NORMALIZED), CLAIMING_PERSON);
+ db.people.get(CACHED_PERSON).deleted = true;
+ const personIndex = await beeperTribe.loadRosterIndex();
+
+ expect(await beeperTribe.logSenderTouchpoints([candidate(), candidate(OTHER_CONVERSATION)], { personIndex }))
+ .toEqual({ created: 1, matched: 1 });
+ expect(tribeService.autoCreateTouchpoint).toHaveBeenCalledWith(CLAIMING_PERSON, expect.objectContaining({ dedupeKey: 'beeper:2026-09-02' }));
+ expect(listPeople).toHaveBeenCalledTimes(1);
+ });
+
+ it('loads phone fallbacks afresh for standalone calls', async () => {
+ seedParticipant({ handle: PHONE_RAW, network: 'whatsapp' });
+ listPeople.mockResolvedValueOnce([{ id: LEGACY_PHONE_PERSON, name: 'Example', phones: [PHONE_NORMALIZED] }])
+ .mockResolvedValueOnce([]);
+ expect(await beeperTribe.logSenderTouchpoints([candidate()])).toEqual({ created: 1, matched: 1 });
+ expect(await beeperTribe.logSenderTouchpoints([candidate()])).toEqual({ created: 0, matched: 0 });
+ expect(listPeople).toHaveBeenCalledTimes(2);
+ });
+
+ it('reduces a synthetic 1000-person, 20-chat pass from 21 roster loads to one with identical outcomes', async () => {
+ const roster = Array.from({ length: 1000 }, (_, i) => ({
+ id: i === 0 ? LEGACY_PHONE_PERSON : `example-person-${i}`, name: `Example ${i}`, notes: 'x'.repeat(8192),
+ phones: i === 0 ? [PHONE_NORMALIZED] : [],
+ }));
+ listPeople.mockResolvedValue(roster);
+ const batches = Array.from({ length: 20 }, (_, i) => {
+ const conversationId = `example-chat-${i}`;
+ seedParticipant({ conversationId, handle: PHONE_RAW, network: 'whatsapp' });
+ return Array.from({ length: 25 }, () => candidate(conversationId));
+ });
+ const run = async (reuse) => {
+ listPeople.mockClear();
+ tribeService.autoCreateTouchpoint.mockClear();
+ const touched = new Set();
+ tribeService.autoCreateTouchpoint.mockImplementation(async (personId, { dedupeKey }) => {
+ const key = `${personId}:${dedupeKey}`;
+ if (touched.has(key)) return null;
+ touched.add(key);
+ return { id: 'example-touchpoint' };
+ });
+ const personIndex = await beeperTribe.loadRosterIndex();
+ let created = 0, matched = 0;
+ for (const batch of batches) {
+ // eslint-disable-next-line no-await-in-loop -- mirrors sequential sweep batches
+ const result = await beeperTribe.logSenderTouchpoints(batch, reuse ? { personIndex } : {});
+ created += result.created;
+ matched += result.matched;
+ }
+ return { created, matched, reads: listPeople.mock.calls.length, attempts: tribeService.autoCreateTouchpoint.mock.calls.length };
+ };
+ expect(await run(false)).toEqual({ created: 1, matched: 500, reads: 21, attempts: 20 });
+ expect(await run(true)).toEqual({ created: 1, matched: 500, reads: 1, attempts: 20 });
+ });
+});