diff --git a/src/cli/dms-lists-contract.test.ts b/src/cli/dms-lists-contract.test.ts new file mode 100644 index 00000000..343833e8 --- /dev/null +++ b/src/cli/dms-lists-contract.test.ts @@ -0,0 +1,147 @@ +// @vitest-environment node +import { Command } from "commander"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { + createCommandContext, + configureOperationAccountSelection, + resetOperationAccountSelection, +} from "./command-context"; +import { configureNumericOptions, CliInputError } from "./numeric-options"; +import { registerDirectMessageCommands } from "./register-dms"; +import { registerListCommands } from "./register-lists"; + +const mocks = vi.hoisted(() => ({ + read: vi.fn(), + sync: vi.fn(), + update: vi.fn(), + members: vi.fn(), + lists: vi.fn(), + defaultAccount: vi.fn(), + resolveAccount: vi.fn(), +})); +vi.mock("./dm-command-helpers", async (original) => ({ + ...(await original()), + enrichDmItems: mocks.read, +})); +vi.mock("#/lib/dms-live", () => ({ + syncDirectMessagesViaCachedBird: mocks.sync, +})); +vi.mock("#/lib/x-lists", () => ({ + listStoredXListMembers: mocks.members, + listStoredXLists: mocks.lists, +})); +vi.mock("#/lib/account-selection", () => ({ + resolveOperationAccount: mocks.resolveAccount, +})); +vi.mock("#/lib/config", async (original) => ({ + ...(await original()), + getDefaultAccountSelector: mocks.defaultAccount, +})); + +function run(args: string[]) { + const program = new Command().option("--json").exitOverride(); + configureNumericOptions(program); + configureOperationAccountSelection(program); + const context = { + ...createCommandContext(program), + print: vi.fn(), + autoUpdateBeforeRead: mocks.update, + autoSyncAfterWrite: vi.fn(), + }; + registerDirectMessageCommands(context); + registerListCommands(context); + return program.parseAsync(["--json", ...args], { from: "user" }); +} +beforeEach(() => { + for (const mock of Object.values(mocks)) mock.mockReset(); + mocks.read.mockResolvedValue([]); + mocks.sync.mockResolvedValue({ ok: true }); + mocks.members.mockReturnValue({ items: [] }); + mocks.lists.mockReturnValue([]); + mocks.resolveAccount.mockReturnValue({ + id: "acct_studio", + username: "studio", + }); +}); +afterEach(resetOperationAccountSelection); + +describe("DM and List CLI contracts", () => { + it.each([false, true])( + "rejects conflicting DM reply filters before reads or refresh=%s", + async (refresh) => { + await expect( + run([ + "dms", + "list", + "--replied", + "--unreplied", + ...(refresh ? ["--refresh"] : []), + ]), + ).rejects.toThrow(CliInputError); + expect(mocks.update).not.toHaveBeenCalled(); + expect(mocks.sync).not.toHaveBeenCalled(); + expect(mocks.read).not.toHaveBeenCalled(); + }, + ); + it.each(["bogus", "", "FOLLOWER"])( + "rejects invalid DM sort %j before refresh", + async (sort) => { + await expect( + run(["dms", "list", "--sort", sort, "--refresh"]), + ).rejects.toThrow("--sort must be recent or followers"); + expect(mocks.sync).not.toHaveBeenCalled(); + expect(mocks.read).not.toHaveBeenCalled(); + }, + ); + it.each(["recent", "followers", "influence"])( + "preserves DM sort %s including the legacy alias", + async (sort) => { + await run(["dms", "list", "--sort", sort]); + expect(mocks.read).toHaveBeenCalledWith( + expect.objectContaining({ + sort: sort === "influence" ? "followers" : sort, + }), + expect.anything(), + ); + }, + ); + it.each(["0", "-1", "NaN", "1.5"])( + "rejects List member limit %s before backup auto-update", + async (limit) => { + await expect( + run(["lists", "members", "builders", "--limit", limit]), + ).rejects.toThrow(CliInputError); + expect(mocks.update).not.toHaveBeenCalled(); + expect(mocks.members).not.toHaveBeenCalled(); + }, + ); + it("preserves valid List member limit and selector", async () => { + await run(["lists", "members", "builders", "--limit", "1"]); + expect(mocks.members).toHaveBeenCalledWith( + expect.objectContaining({ name: "builders", limit: 1 }), + ); + }); + it("keeps zero additional DM pages valid", async () => { + await run(["dms", "sync", "--max-pages", "0", "--limit", "1"]); + expect(mocks.sync).toHaveBeenCalledWith( + expect.objectContaining({ limit: 1 }), + ); + expect(mocks.sync.mock.calls[0][0].maxPages).toBeUndefined(); + }); + it.each(["0", "-1", "NaN"])( + "rejects invalid live DM limit %s before invoking sync", + async (limit) => { + await expect( + run(["dms", "list", "--refresh", "--limit", limit]), + ).rejects.toThrow(CliInputError); + expect(mocks.sync).not.toHaveBeenCalled(); + }, + ); + it("preserves zero as an empty offline DM result limit", async () => { + await run(["dms", "list", "--limit", "0"]); + expect(mocks.read).toHaveBeenCalledWith( + expect.objectContaining({ limit: 0 }), + expect.anything(), + ); + }); +}); diff --git a/src/cli/register-dms.ts b/src/cli/register-dms.ts index 587e8c9f..a749d506 100644 --- a/src/cli/register-dms.ts +++ b/src/cli/register-dms.ts @@ -24,6 +24,7 @@ export function registerDirectMessageCommands({ autoUpdateBeforeRead, parseNonNegativeIntegerOption, parseFiniteNumberOption, + parsePositiveLimitOption, }: CliCommandContext) { const dmsCommand = program.command("dms").description("Direct messages"); @@ -58,6 +59,12 @@ export function registerDirectMessageCommands({ .option("--unreplied", "Only unreplied threads") .option("--limit ", "Limit results", "20") .action(async (options) => { + if (options.replied && options.unreplied) { + throw new CliInputError("Cannot combine --replied and --unreplied"); + } + if (!["recent", "followers", "influence"].includes(options.sort)) { + throw new CliInputError("--sort must be recent or followers"); + } const replyFilter = options.replied ? "replied" : options.unreplied @@ -86,7 +93,7 @@ export function registerDirectMessageCommands({ await syncDirectMessagesViaCachedBird({ account: options.account, mode, - limit: Number(options.limit), + limit: parsePositiveLimitOption(options.limit, "--limit"), ...(inbox !== "all" ? { inbox } : {}), ...(maxPages > 0 ? { maxPages } : {}), ...(options.allPages ? { allPages: true } : {}), @@ -156,7 +163,7 @@ export function registerDirectMessageCommands({ const result = await syncDirectMessagesViaCachedBird({ account: options.account, mode, - limit: Number(options.limit), + limit: parsePositiveLimitOption(options.limit, "--limit"), ...(inbox !== "all" ? { inbox } : {}), ...(maxPages > 0 ? { maxPages } : {}), ...(options.allPages ? { allPages: true } : {}), diff --git a/src/cli/register-lists.ts b/src/cli/register-lists.ts index 54cd93f8..0c1658c8 100644 --- a/src/cli/register-lists.ts +++ b/src/cli/register-lists.ts @@ -6,6 +6,7 @@ export function registerListCommands({ print, asJson, autoUpdateBeforeRead, + parsePositiveLimitOption, }: CliCommandContext) { const listsCommand = program .command("lists") @@ -40,13 +41,14 @@ export function registerListCommands({ .option("--include-ended", "Include members absent from a complete sync") .option("--limit ", "Limit results", "100") .action(async (name, options) => { + const limit = parsePositiveLimitOption(options.limit, "--limit"); await autoUpdateBeforeRead(); const result = listStoredXListMembers({ account: options.account, name, listId: options.listId, includeEnded: Boolean(options.includeEnded), - limit: Number(options.limit), + limit, }); if (asJson()) { print(result, true); diff --git a/src/lib/dms-live.test.ts b/src/lib/dms-live.test.ts index 6a7c8c50..a333bddb 100644 --- a/src/lib/dms-live.test.ts +++ b/src/lib/dms-live.test.ts @@ -96,6 +96,86 @@ describe("cached live DMs", () => { } }); + it.each(["bird", "xurl"])( + "enforces the xurl DM page maximum in auto mode with %s preferred", + async (preferred) => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = preferred; + listDirectMessagesViaBirdMock.mockRejectedValue( + new Error("Bird unavailable"), + ); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ + mode: "auto", + limit: 101, + refresh: true, + }), + ).rejects.toThrow("--limit must be between 1 and 100"); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }, + ); + + it("does not impose xurl's maximum on a successful Bird DM read", async () => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; + listDirectMessagesViaBirdMock.mockResolvedValue({ + success: true, + conversations: [], + events: [], + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit: 101 }), + ).resolves.toMatchObject({ source: "bird" }); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }); + + it("skips an oversized preferred xurl page and still succeeds via Bird", async () => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "xurl"; + listDirectMessagesViaBirdMock.mockResolvedValue({ + success: true, + conversations: [], + events: [], + }); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit: 101 }), + ).resolves.toMatchObject({ source: "bird" }); + expect(listDirectMessageEventsViaXurlMock).not.toHaveBeenCalled(); + }); + + it.each([1, 100])( + "allows xurl DM boundary limit %i after Bird failure", + async (limit) => { + makeTempHome(); + process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; + listDirectMessagesViaBirdMock.mockRejectedValue( + new Error("Bird unavailable"), + ); + listDirectMessageEventsViaXurlMock.mockResolvedValue({ + data: [], + meta: {}, + }); + const { syncDirectMessagesViaCachedBird } = await import("./dms-live"); + await expect( + syncDirectMessagesViaCachedBird({ mode: "auto", limit, maxPages: 0 }), + ).resolves.toMatchObject({ source: "xurl" }); + expect(listDirectMessageEventsViaXurlMock).toHaveBeenCalledWith( + expect.objectContaining({ maxResults: limit }), + ); + }, + ); + it("prefers Bird for auto DMs and falls back to xurl after a Bird failure", async () => { makeTempHome(); process.env.BIRDCLAW_PREFERRED_TRANSPORT = "bird"; diff --git a/src/lib/dms-live.ts b/src/lib/dms-live.ts index e24c0389..1bfbbba6 100644 --- a/src/lib/dms-live.ts +++ b/src/lib/dms-live.ts @@ -10,7 +10,7 @@ import { } from "./bird"; import { verifyBirdAccountMatchesEffect } from "./bird-account"; import { getNativeDb } from "./db"; -import { runEffectPromise, tryPromise } from "./effect-runtime"; +import { runEffectPromise, tryPromise, trySync } from "./effect-runtime"; import { getProvenSelectedAccountLegacyProfileIds } from "./profile-identity"; import { assertLiveAccountMatches, @@ -828,6 +828,9 @@ export function syncDirectMessagesViaCachedBirdEffect({ inbox !== "requests"; if (tryXurl) { const xurlResult = yield* Effect.gen(function* () { + yield* trySync(() => + parseLivePageSize(limit, { max: XURL_DMS_MAX_RESULTS }), + ); const authenticated = getAuthenticatedXurlAccount( yield* lookupAuthenticatedOAuth2UserEffect( resolvedAccount.username, diff --git a/src/lib/live-sync-engine.ts b/src/lib/live-sync-engine.ts index 4d608957..75696b08 100644 --- a/src/lib/live-sync-engine.ts +++ b/src/lib/live-sync-engine.ts @@ -1,5 +1,5 @@ import { Effect } from "effect"; -import { getPreferredTransport } from "./config"; +import { getPreferredTransport, isReadOnlyDeployment } from "./config"; import { findOperationAccount } from "./account-selection"; import { databaseWriteEffect } from "./database-writer"; import { toError } from "./effect-runtime"; @@ -257,11 +257,12 @@ export function runCachedLiveSyncEffect< }); const cached = cache.entry; if (!refresh && cached && cache.fresh) { - const persisted = persistCached - ? yield* databaseWriteEffect((writeDb) => - persistCached(writeDb, cached.value), - ) - : undefined; + const persisted = + persistCached && !isReadOnlyDeployment() + ? yield* databaseWriteEffect((writeDb) => + persistCached(writeDb, cached.value), + ) + : undefined; return { source: "cache", payload: cached.value, diff --git a/src/lib/timeline-live.test.ts b/src/lib/timeline-live.test.ts index b1d4de13..7bf5876f 100644 --- a/src/lib/timeline-live.test.ts +++ b/src/lib/timeline-live.test.ts @@ -46,6 +46,7 @@ function makeTempHome() { } afterEach(() => { + vi.unstubAllEnvs(); delete process.env.BIRDCLAW_PREFERRED_TRANSPORT; resetDatabaseForTests(); resetBirdclawPathsForTests(); @@ -60,6 +61,223 @@ afterEach(() => { }); describe("live home timeline sync", () => { + it.each(["bird", "xurl"] as const)( + "restores %s cached timeline rows, edges and FTS for a handle-selected account", + async (mode) => { + makeTempHome(); + const db = getNativeDb(); + const selected = birdAccountForTest(db, "acct_studio"); + getAuthenticatedBirdAccountMock.mockResolvedValue(selected); + const payload = { + data: [ + { + id: "cache_restore", + author_id: "42", + text: "restorationneedle", + created_at: "2026-04-26T13:43:34.000Z", + }, + ], + includes: { users: [{ id: "42", username: "sam", name: "Sam" }] }, + meta: {}, + }; + const transport = + mode === "bird" + ? listHomeTimelineViaBirdMock + : listHomeTimelineViaXurlMock; + transport.mockResolvedValue(payload); + const { syncHomeTimeline } = await import("./timeline-live"); + const options = { + mode, + account: "@" + selected.username.replace(/^@/, ""), + limit: 5, + cacheTtlMs: 60_000, + }; + await syncHomeTimeline(options); + const cacheBefore = db + .prepare("select * from sync_cache where cache_key like 'timeline:%'") + .all(); + for (const deletion of [ + "delete from tweet_account_edges where tweet_id = 'cache_restore'", + "delete from tweets where id = 'cache_restore'", + ]) { + db.prepare(deletion).run(); + const progress = vi.fn(); + await expect( + syncHomeTimeline({ ...options, onProgress: progress }), + ).resolves.toMatchObject({ + source: "cache", + count: 1, + accountId: "acct_studio", + }); + expect( + listTimelineItems({ + resource: "home", + account: "acct_studio", + search: "restorationneedle", + }).map((tweet) => tweet.id), + ).toEqual(["cache_restore"]); + expect( + listTimelineItems({ + resource: "home", + account: "acct_primary", + search: "restorationneedle", + }), + ).toEqual([]); + expect(progress).toHaveBeenLastCalledWith( + expect.objectContaining({ source: "cache", fetched: 1, done: true }), + ); + } + expect(transport).toHaveBeenCalledTimes(1); + expect( + db + .prepare("select * from sync_cache where cache_key like 'timeline:%'") + .all(), + ).toEqual(cacheBefore); + }, + ); + + it("preserves newer stored tweet metrics and profile metadata when replaying an older cached home timeline sync", async () => { + makeTempHome(); + const db = getNativeDb(); + listHomeTimelineViaXurlMock + .mockResolvedValueOnce({ + data: [ + { + id: "home_cache_freshness_1", + author_id: "42", + text: "home cache freshness item", + created_at: "2026-04-26T13:43:34.000Z", + public_metrics: { like_count: 1 }, + }, + ], + includes: { + users: [ + { + id: "42", + username: "sam", + name: "Old Sam", + public_metrics: { followers_count: 10 }, + }, + ], + }, + meta: {}, + }) + .mockResolvedValueOnce({ + data: [ + { + id: "home_cache_freshness_1", + author_id: "42", + text: "home cache freshness item", + created_at: "2026-04-26T13:43:34.000Z", + public_metrics: { like_count: 99 }, + }, + { + id: "home_cache_freshness_2", + author_id: "43", + text: "second home item", + created_at: "2026-04-26T13:44:34.000Z", + public_metrics: { like_count: 5 }, + }, + ], + includes: { + users: [ + { + id: "42", + username: "alice", + name: "New Sam", + public_metrics: { followers_count: 250 }, + }, + { + id: "43", + username: "sam", + name: "Current Sam", + public_metrics: { followers_count: 500 }, + }, + ], + }, + meta: {}, + }); + const { syncHomeTimeline } = await import("./timeline-live"); + await syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 5, + refresh: true, + cacheTtlMs: 60_000, + }); + await syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 20, + refresh: true, + cacheTtlMs: 60_000, + }); + + db.exec( + "delete from tweet_account_edges where tweet_id = 'home_cache_freshness_1' and kind = 'home'", + ); + await expect( + syncHomeTimeline({ + account: "acct_primary", + mode: "xurl", + limit: 5, + cacheTtlMs: 60_000, + }), + ).resolves.toMatchObject({ source: "cache", count: 1 }); + + expect( + db + .prepare( + "select account_id, tweet_id, kind from tweet_account_edges where tweet_id = 'home_cache_freshness_1' and kind = 'home'", + ) + .get(), + ).toEqual({ + account_id: "acct_primary", + tweet_id: "home_cache_freshness_1", + kind: "home", + }); + expect( + db + .prepare( + "select like_count from tweets where id = 'home_cache_freshness_1'", + ) + .get(), + ).toEqual({ like_count: 99 }); + expect( + db + .prepare( + "select id, handle, display_name, followers_count from profiles where id in ('profile_user_42', 'profile_user_43') order by id", + ) + .all(), + ).toEqual([ + { + id: "profile_user_42", + handle: "alice", + display_name: "New Sam", + followers_count: 250, + }, + { + id: "profile_user_43", + handle: "sam", + display_name: "Current Sam", + followers_count: 500, + }, + ]); + + resetDatabaseForTests(); + vi.stubEnv("BIRDCLAW_DEPLOYMENT_READ_ONLY", "1"); + const readOnlyCached = await syncHomeTimeline({ + mode: "xurl", + limit: 5, + refresh: false, + }); + expect(readOnlyCached).toMatchObject({ + ok: true, + source: "cache", + count: 1, + }); + }); + it("honors config preference and does not reuse another auto preference's cache", async () => { makeTempHome(); const { setPreferredTransport } = await import("./config"); diff --git a/src/lib/timeline-live.ts b/src/lib/timeline-live.ts index 39d8cde2..b4aeef29 100644 --- a/src/lib/timeline-live.ts +++ b/src/lib/timeline-live.ts @@ -70,7 +70,7 @@ function mergeHomeTimelineIntoLocalStore( db: Database, accountId: string, payload: XurlMentionsResponse, - source: "bird" | "xurl", + source: "bird" | "xurl" | "cache", ) { ingestTweetPayload(db, { accountId, @@ -212,6 +212,8 @@ export function syncHomeTimelineEffect({ livePayload, liveSource, ), + persistCached: (writeDb, payload) => + mergeHomeTimelineIntoLocalStore(writeDb, accountId, payload, "cache"), }); const { source, payload } = syncResult; if (source === "cache") { diff --git a/src/lib/tweet-account-edges.ts b/src/lib/tweet-account-edges.ts index dbe18248..3f57d9b5 100644 --- a/src/lib/tweet-account-edges.ts +++ b/src/lib/tweet-account-edges.ts @@ -33,16 +33,27 @@ export function upsertTweetAccountEdge( ) values (?, ?, ?, ?, ?, 1, ?, ?, ?) on conflict(account_id, tweet_id, kind) do update set first_seen_at = min(tweet_account_edges.first_seen_at, excluded.first_seen_at), - last_seen_at = max(tweet_account_edges.last_seen_at, excluded.last_seen_at), - seen_count = tweet_account_edges.seen_count + 1, + last_seen_at = case + when excluded.source = 'cache' then tweet_account_edges.last_seen_at + else max(tweet_account_edges.last_seen_at, excluded.last_seen_at) + end, + seen_count = case + when excluded.source = 'cache' then tweet_account_edges.seen_count + else tweet_account_edges.seen_count + 1 + end, source = case when tweet_account_edges.source = 'archive' then 'archive' + when excluded.source = 'cache' then tweet_account_edges.source else coalesce(nullif(excluded.source, ''), tweet_account_edges.source) end, raw_json = case + when excluded.source = 'cache' and tweet_account_edges.raw_json not in ('', '{}', 'null') then tweet_account_edges.raw_json when excluded.raw_json not in ('', '{}', 'null') then excluded.raw_json else tweet_account_edges.raw_json end, - updated_at = max(tweet_account_edges.updated_at, excluded.updated_at) + updated_at = case + when excluded.source = 'cache' then tweet_account_edges.updated_at + else max(tweet_account_edges.updated_at, excluded.updated_at) + end `).run(accountId, tweetId, kind, seenAt, seenAt, source, rawJson, seenAt); } diff --git a/src/lib/tweet-repository.ts b/src/lib/tweet-repository.ts index eaa530ca..c2f32c75 100644 --- a/src/lib/tweet-repository.ts +++ b/src/lib/tweet-repository.ts @@ -81,7 +81,11 @@ export function ingestTweetPayload( } handleOwners.set(handle, user.id); } + const isCacheSource = source === "cache"; const mediaByKey = indexMediaIncludes(payload.includes?.media); + const hasTweetRow = isCacheSource + ? db.prepare("select 1 from tweets where id = ? limit 1") + : undefined; const upsertTweet = db.prepare(` insert into tweets ( id, author_profile_id, text, created_at, is_replied, reply_to_id, @@ -89,22 +93,29 @@ export function ingestTweetPayload( quoted_tweet_id ) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) on conflict(id) do update set - author_profile_id = excluded.author_profile_id, + author_profile_id = case when ? then tweets.author_profile_id else excluded.author_profile_id end, text = case + when ? then tweets.text when excluded.note_tweet_json is null and tweets.note_tweet_json is not null then tweets.text else excluded.text end, - created_at = excluded.created_at, + created_at = case when ? then tweets.created_at else excluded.created_at end, is_replied = max(tweets.is_replied, excluded.is_replied), reply_to_id = coalesce(tweets.reply_to_id, excluded.reply_to_id), like_count = case when ? then tweets.like_count else excluded.like_count end, media_count = max(tweets.media_count, excluded.media_count), entities_json = case + when ? then tweets.entities_json when excluded.note_tweet_json is null and tweets.note_tweet_json is not null then tweets.entities_json else excluded.entities_json end, - note_tweet_json = coalesce(excluded.note_tweet_json, tweets.note_tweet_json), + note_tweet_json = coalesce( + case when ? then tweets.note_tweet_json else excluded.note_tweet_json end, + tweets.note_tweet_json, + excluded.note_tweet_json + ), media_json = case + when ? and tweets.media_json not in ('', '[]', 'null') then tweets.media_json when excluded.media_json not in ('', '[]', 'null') then excluded.media_json else tweets.media_json end, @@ -116,9 +127,18 @@ export function ingestTweetPayload( account_id, tweet_id, kind, collected_at, source, raw_json, updated_at ) values (?, ?, ?, null, ?, ?, ?) on conflict(account_id, tweet_id, kind) do update set - source = excluded.source, - raw_json = excluded.raw_json, - updated_at = excluded.updated_at + source = case + when excluded.source = 'cache' then tweet_collections.source + else excluded.source + end, + raw_json = case + when excluded.source = 'cache' and tweet_collections.raw_json not in ('', '{}', 'null') then tweet_collections.raw_json + else excluded.raw_json + end, + updated_at = case + when excluded.source = 'cache' then tweet_collections.updated_at + else excluded.updated_at + end `) : undefined; const tweetIds: string[] = []; @@ -140,11 +160,14 @@ export function ingestTweetPayload( for (const tweet of toCanonicalTweets(payload)) { touchedTweetIds.push(tweet.id); const isPrimaryTweet = primaryTweetIds.has(tweet.id); + const tweetAlreadyStored = Boolean(hasTweetRow?.get(tweet.id)); let profileId = profileIdsByAuthor.get(tweet.author_id); if (!profileId) { const author = usersById.get(tweet.author_id); const profile = author - ? upsertProfileFromXUser(db, author) + ? upsertProfileFromXUser(db, author, { + preserveExisting: isCacheSource, + }) : ensureStubProfileForXUser(db, tweet.author_id); profileId = profile.profile.id; // Keep order-dependent handle-collision reconciliation for ambiguous payloads. @@ -159,6 +182,7 @@ export function ingestTweetPayload( // Included tweets are reference data, not members of the caller's result set. const shouldMarkReplied = isPrimaryTweet && markRepliesAsReplied && Boolean(replyToId); + const preserveExistingTweet = isCacheSource ? 1 : 0; upsertTweet.run( tweet.id, profileId, @@ -172,17 +196,26 @@ export function ingestTweetPayload( serializeNoteTweet(tweet.note_tweet), media.json, quotedTweetId, - !isPrimaryTweet && tweet.public_metrics?.like_count === undefined + preserveExistingTweet, + preserveExistingTweet, + preserveExistingTweet, + isCacheSource || + (!isPrimaryTweet && tweet.public_metrics?.like_count === undefined) ? 1 : 0, + preserveExistingTweet, + preserveExistingTweet, + preserveExistingTweet, ); - recordTweetRevision(db, { - tweetId: tweet.id, - editHistoryIds: editHistoryIdsFromPayload(tweet.id, tweet), - payloadJson: JSON.stringify(tweet), - source, - observedAt, - }); + if (!isCacheSource || !tweetAlreadyStored) { + recordTweetRevision(db, { + tweetId: tweet.id, + editHistoryIds: editHistoryIdsFromPayload(tweet.id, tweet), + payloadJson: JSON.stringify(tweet), + source, + observedAt, + }); + } const sourceUrl = provenance?.sourceUrlByTweetId.get(tweet.id); if (sourceUrl) { upsertSource?.run(tweet.id, source, sourceUrl, observedAt); diff --git a/src/lib/x-profile.ts b/src/lib/x-profile.ts index a7f19167..5800b9d4 100644 --- a/src/lib/x-profile.ts +++ b/src/lib/x-profile.ts @@ -19,6 +19,7 @@ export interface ResolvedXProfile { export interface XProfileIdentityOptions { provenLegacyProfileIds?: ReadonlySet; + preserveExisting?: boolean; } export function buildExternalProfileId(externalUserId: string) { @@ -198,12 +199,42 @@ function upsertProfileFromXUserInTransaction( } const profileId = buildExternalProfileId(externalUserId); + if (options.preserveExisting) { + const existingCanonical = db + .prepare( + ` + select id, handle, display_name, bio, followers_count, following_count, avatar_hue, avatar_url, + location, url, verified_type, entities_json, created_at + from profiles + where id = ? + limit 1 + `, + ) + .get(profileId) as Record | undefined; + if (existingCanonical) { + const existingHandle = String(existingCanonical.handle ?? ""); + const existingDisplayName = String(existingCanonical.display_name ?? ""); + if ( + !existingHandle.startsWith("birdclaw_stub_") && + !existingDisplayName.startsWith("birdclaw_stub_") + ) { + return { + profile: profileFromDbRow(existingCanonical), + externalUserId: String(user.id), + }; + } + } + } + const reconciliation = reconcileCanonicalXProfileIdentity({ db, externalUserId, canonicalProfileId: profileId, incomingHandle: username, provenLegacyProfileIds: options.provenLegacyProfileIds, + ...(options.preserveExisting + ? { canReassignHandleCollision: () => false } + : {}), }); const storedHandle = reconciliation.blockedHandleProfileIds.length > 0