From a4030ecaafed4be7def85e987a98b2f96678e468 Mon Sep 17 00:00:00 2001 From: sm0ky Date: Sun, 8 Nov 2026 18:27:45 -0500 Subject: [PATCH 1/2] fix(sync,mcp,search): resolve account selectors, filter tombstoned FTS rows, and harden search/sync contracts --- src/cli/register-sync.ts | 89 +++++++++++++------ src/cli/sync-contract.test.ts | 111 ++++++++++++++++++++++++ src/lib/link-insights.test.ts | 65 ++++++++++++++ src/lib/link-insights.ts | 9 +- src/lib/mcp-tools.test.ts | 138 ++++++++++++++++++++++++++++++ src/lib/mcp-tools.ts | 2 +- src/lib/search-discussion.test.ts | 59 +++++++++++++ src/lib/search-discussion.ts | 10 ++- src/lib/web-sync.test.ts | 77 ++++++++++++++++- src/lib/web-sync.ts | 43 +++++++++- 10 files changed, 567 insertions(+), 36 deletions(-) create mode 100644 src/cli/sync-contract.test.ts create mode 100644 src/lib/mcp-tools.test.ts diff --git a/src/cli/register-sync.ts b/src/cli/register-sync.ts index 44af7f38..7018bd6b 100644 --- a/src/cli/register-sync.ts +++ b/src/cli/register-sync.ts @@ -14,6 +14,15 @@ import { syncHomeTimeline } from "#/lib/timeline-live"; import { syncXLists, type XListSyncMode } from "#/lib/x-lists"; import { errorMessage, type CliCommandContext } from "./command-context"; +function parseCacheTtlMs(value: string | undefined): number | undefined { + if (value === undefined) return undefined; + const milliseconds = Number(value) * 1000; + if (!value.trim() || !Number.isFinite(milliseconds) || milliseconds < 0) { + throw new Error("--cache-ttl must be a non-negative number"); + } + return milliseconds; +} + export function registerSyncCommands({ program, print, @@ -70,17 +79,30 @@ export function registerSyncCommands({ .option("--cache-ttl ", "Live-cache freshness window", "120") .option("--refresh", "Bypass live-cache freshness window") .action(async (options) => { - const result = await syncHomeTimeline({ - account: options.account, - mode: options.mode, - limit: Number(options.limit), - maxPages: Number(options.maxPages), - following: !options.forYou, - refresh: Boolean(options.refresh), - cacheTtlMs: Number(options.cacheTtl) * 1000, - }); - await autoSyncAfterWrite(); - print(result, true); + try { + const result = await syncHomeTimeline({ + account: options.account, + mode: options.mode, + limit: Number(options.limit), + maxPages: Number(options.maxPages), + following: !options.forYou, + refresh: Boolean(options.refresh), + cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + }); + await autoSyncAfterWrite(); + print(result, true); + } catch (error) { + print( + { + ok: false, + kind: "timeline", + mode: options.mode, + error: errorMessage(error), + }, + true, + ); + process.exitCode = 1; + } }); syncCommand @@ -119,7 +141,7 @@ export function registerSyncCommands({ sinceId: options.sinceId, startTime: options.startTime, refresh: Boolean(options.refresh), - cacheTtlMs: Number(options.cacheTtl) * 1000, + cacheTtlMs: parseCacheTtlMs(options.cacheTtl), }); await autoSyncAfterWrite(); print(result, true); @@ -238,20 +260,33 @@ export function registerSyncCommands({ .option("--cache-ttl ", "Live-cache freshness window", "120") .option("--refresh", "Bypass live-cache freshness window") .action(async (options) => { - const result = await syncTimelineCollection({ - kind, - account: options.account, - mode: options.mode as TimelineCollectionMode, - limit: Number(options.limit), - all: Boolean(options.all) || options.maxPages !== undefined, - maxPages: options.maxPages ? Number(options.maxPages) : undefined, - paginationToken: options.paginationToken, - refresh: Boolean(options.refresh), - cacheTtlMs: Number(options.cacheTtl) * 1000, - earlyStop: Boolean(options.earlyStop), - }); - await autoSyncAfterWrite(); - print(result, true); + try { + const result = await syncTimelineCollection({ + kind, + account: options.account, + mode: options.mode as TimelineCollectionMode, + limit: Number(options.limit), + all: Boolean(options.all) || options.maxPages !== undefined, + maxPages: options.maxPages ? Number(options.maxPages) : undefined, + paginationToken: options.paginationToken, + refresh: Boolean(options.refresh), + cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + earlyStop: Boolean(options.earlyStop), + }); + await autoSyncAfterWrite(); + print(result, true); + } catch (error) { + print( + { + ok: false, + kind, + mode: options.mode, + error: errorMessage(error), + }, + true, + ); + process.exitCode = 1; + } }); } @@ -281,7 +316,7 @@ export function registerSyncCommands({ maxResources: options.maxResources ? Number(options.maxResources) : undefined, - cacheTtlMs: Number(options.cacheTtl) * 1000, + cacheTtlMs: parseCacheTtlMs(options.cacheTtl), refresh: Boolean(options.refresh), allowPartial: Boolean(options.allowPartial), yes: Boolean(options.yes), diff --git a/src/cli/sync-contract.test.ts b/src/cli/sync-contract.test.ts new file mode 100644 index 00000000..55a9f19d --- /dev/null +++ b/src/cli/sync-contract.test.ts @@ -0,0 +1,111 @@ +// @vitest-environment node +import { Command } from "commander"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +import { registerSyncCommands } from "./register-sync"; +import { createCommandContext } from "./command-context"; +const mocks = vi.hoisted(() => ({ + timeline: vi.fn(), + collection: vi.fn(), + mentions: vi.fn(), + graph: vi.fn(), +})); +vi.mock("#/lib/timeline-live", () => ({ syncHomeTimeline: mocks.timeline })); +vi.mock("#/lib/timeline-collections-live", () => ({ + syncTimelineCollection: mocks.collection, +})); +vi.mock("#/lib/mentions-live", () => ({ syncMentions: mocks.mentions })); +vi.mock("#/lib/follow-graph", () => ({ syncFollowGraph: mocks.graph })); +function fixture() { + const program = new Command().exitOverride(); + const print = vi.fn(); + const backup = vi.fn().mockResolvedValue(undefined); + registerSyncCommands({ + ...createCommandContext(program), + print, + autoSyncAfterWrite: backup, + }); + return { + run: (args: string[]) => + program.parseAsync(["sync", ...args], { from: "user" }), + print, + backup, + }; +} +const initialExitCode = process.exitCode; +beforeEach(() => { + process.exitCode = 0; + for (const mock of Object.values(mocks)) + mock.mockReset().mockResolvedValue({ ok: true, count: 1 }); +}); +afterEach(() => { + process.exitCode = initialExitCode; +}); +describe("Pass 11 sync registration contracts", () => { + for (const kind of ["timeline", "likes", "bookmarks"] as const) { + it( + "prints structured " + kind + " transport failures without backup writes", + async () => { + const f = fixture(); + const mock = kind === "timeline" ? mocks.timeline : mocks.collection; + mock.mockRejectedValue(new Error("transport unavailable")); + await expect(f.run([kind, "--mode", "bird"])).resolves.toBeInstanceOf( + Command, + ); + expect(f.print).toHaveBeenCalledWith( + { ok: false, kind, mode: "bird", error: "transport unavailable" }, + true, + ); + expect(process.exitCode).toBe(1); + expect(f.backup).not.toHaveBeenCalled(); + process.exitCode = 0; + mock.mockResolvedValue({ ok: true }); + await fixture().run([kind]); + expect(process.exitCode).toBe(0); + }, + ); + } + for (const kind of [ + "timeline", + "mentions", + "likes", + "bookmarks", + "followers", + "following", + ]) { + it.each(["-1", "NaN", "not-a-number", "Infinity", "1e308"])( + "rejects " + kind + " cache TTL %j before sync or backup", + async (ttl) => { + const f = fixture(); + await f.run([kind, "--cache-ttl", ttl]); + expect(f.print).toHaveBeenCalledWith( + expect.objectContaining({ + ok: false, + error: "--cache-ttl must be a non-negative number", + }), + true, + ); + expect(process.exitCode).toBe(1); + for (const mock of Object.values(mocks)) + expect(mock).not.toHaveBeenCalled(); + expect(f.backup).not.toHaveBeenCalled(); + process.exitCode = 0; + await fixture().run([kind, "--cache-ttl", "0"]); + const mock = + kind === "timeline" + ? mocks.timeline + : kind === "mentions" + ? mocks.mentions + : kind === "likes" || kind === "bookmarks" + ? mocks.collection + : mocks.graph; + expect(mock).toHaveBeenLastCalledWith( + expect.objectContaining({ cacheTtlMs: 0 }), + ); + await fixture().run([kind, "--cache-ttl", "0.25"]); + expect(mock).toHaveBeenLastCalledWith( + expect.objectContaining({ cacheTtlMs: 250 }), + ); + }, + ); + } +}); diff --git a/src/lib/link-insights.test.ts b/src/lib/link-insights.test.ts index 25e353ff..df5cd73d 100644 --- a/src/lib/link-insights.test.ts +++ b/src/lib/link-insights.test.ts @@ -237,6 +237,71 @@ describe("link insights", () => { rmSync(homeDir, { recursive: true, force: true }); }); + it.each(["@steipete", "steipete", " STEIPETE ", " acct_primary "])( + "Pass 11 resolves link insight selector %j across every membership path", + (account) => { + const db = insertAccountFixture(); + db.prepare( + "update accounts set handle = '@steipete' where id = 'acct_primary'", + ).run(); + for (const id of ["direct", "edge", "collection", "other"]) { + insertTweet(db, { + id, + accountId: "acct_secondary", + authorProfileId: "profile_a", + text: id, + createdAt: localIso(), + }); + insertExpansion(db, { + shortUrl: "https://t.co/" + id, + finalUrl: "https://example.com/" + id, + }); + insertOccurrence(db, { + sourceKind: "tweet", + sourceId: id, + shortUrl: "https://t.co/" + id, + accountId: id === "direct" ? "acct_primary" : "acct_secondary", + createdAt: localIso(), + }); + } + insertTweetAccountEdge(db, { + accountId: "acct_primary", + tweetId: "edge", + }); + db.prepare( + "insert into tweet_collections (account_id, tweet_id, kind, collected_at, source, raw_json, updated_at) values ('acct_primary', 'collection', 'bookmarks', ?, 'test', '{}', ?)", + ).run(localIso(), localIso()); + insertDmMessage(db, { + id: "dm_link", + senderProfileId: "profile_b", + text: "https://t.co/dm", + createdAt: localIso(), + }); + insertExpansion(db, { + shortUrl: "https://t.co/dm", + finalUrl: "https://example.com/dm", + }); + insertOccurrence(db, { + sourceKind: "dm", + sourceId: "dm_link", + shortUrl: "https://t.co/dm", + createdAt: localIso(), + }); + const query = { now: localDate(), range: "all" as const }; + const expected = getLinkInsights({ ...query, account: "acct_primary" }); + expect(expected.stats.occurrences).toBe(4); + expect(getLinkInsights({ ...query, account })).toEqual(expected); + expect( + getLinkInsights({ ...query, account: "all" }).stats.occurrences, + ).toBe(5); + expect(getLinkInsights(query).stats.occurrences).toBe(5); + expect( + getLinkInsights({ ...query, account: "acct_secondary" }).stats + .occurrences, + ).toBe(4); + }, + ); + it("keeps every video host form while rejecting URLs that only contain a host hint", () => { const db = insertAccountFixture(); const suffixes = [ diff --git a/src/lib/link-insights.ts b/src/lib/link-insights.ts index 28c3330b..8e7d57a7 100644 --- a/src/lib/link-insights.ts +++ b/src/lib/link-insights.ts @@ -1,6 +1,7 @@ import { profileSelect, type ProfileSqlRow } from "./profile-row"; import { parseJsonField } from "./json-codec"; import { getNativeDb } from "./db"; +import { findOperationAccount } from "./account-selection"; import { isReadOnlyDeployment } from "./config"; import { ReadOnlyQueryCache } from "./read-only-query-cache"; import type { Database } from "./sqlite"; @@ -716,7 +717,11 @@ function buildLinkInsights( conditions.push("o.source_kind = ?"); params.push(source); } - if (query.account && query.account !== "all") { + const accountId = + query.account && query.account !== "all" + ? (findOperationAccount(db, query.account)?.id ?? query.account) + : undefined; + if (accountId) { conditions.push(`( (o.source_kind = 'dm' and o.account_id = ?) or ( @@ -738,7 +743,7 @@ function buildLinkInsights( ) ) )`); - params.push(query.account, query.account, query.account, query.account); + params.push(accountId, accountId, accountId, accountId); } if (kind === "videos") { addVideoUrlPrefilter(conditions); diff --git a/src/lib/mcp-tools.test.ts b/src/lib/mcp-tools.test.ts new file mode 100644 index 00000000..3695e329 --- /dev/null +++ b/src/lib/mcp-tools.test.ts @@ -0,0 +1,138 @@ +// @vitest-environment node +import { describe, expect, it } from "vitest"; +import { + useTestHome, + insertTestAccount, + insertTestProfile, + insertTestTweet, +} from "../test/test-home"; +import { __test__, MCP_MAX_FTS_MATCHES } from "./mcp-tools"; +import { handleBirdclawMcpRequest } from "./mcp-http"; +import { listTimelineItems } from "./timeline-read-model"; +const home = useTestHome({ + seedDemoData: false, + prefix: "birdclaw-mcp-pass11-", +}); +const now = "2026-07-01T12:00:00.000Z"; +function fixture(hidden: "deleted_at" | "superseded_at", count: number) { + const db = home().db; + insertTestAccount(db, { id: "acct_primary", handle: "@steipete" }); + insertTestProfile(db); + db.transaction(() => { + for (let i = 0; i <= count; i++) { + const id = "p11_" + i; + insertTestTweet(db, { id, text: "pass11needle", createdAt: now }); + db.prepare( + "insert into tweets_fts(tweet_id, text) values (?, 'pass11needle')", + ).run(id); + db.prepare( + "insert into tweet_account_edges(account_id,tweet_id,kind,first_seen_at,last_seen_at,source,updated_at) values ('acct_primary',?,'home',?,?,'test',?)", + ).run(id, now, now, now); + for (const kind of ["likes", "bookmarks"]) + db.prepare( + "insert into tweet_collections(account_id,tweet_id,kind,collected_at,source,raw_json,updated_at) values ('acct_primary',?,?,?,'test','{}',?)", + ).run(id, kind, now, now); + if (i > 0) + db.prepare("update tweets set " + hidden + " = ? where id = ?").run( + now, + id, + ); + } + })(); + return db; +} +async function search() { + const token = "birdclaw-pass11-test-token-0123456789abcdef"; + const response = await handleBirdclawMcpRequest( + new Request("http://mcp.birdclaw.test/mcp", { + method: "POST", + headers: { + host: "mcp.birdclaw.test", + authorization: "Bearer " + token, + accept: "application/json, text/event-stream", + "content-type": "application/json", + "mcp-protocol-version": "2025-06-18", + }, + body: JSON.stringify({ + jsonrpc: "2.0", + id: 1, + method: "tools/call", + params: { + name: "search_tweets", + arguments: { query: "pass11needle", limit: 1 }, + }, + }), + }), + { + config: { + token, + publicUrl: new URL("https://mcp.birdclaw.test/mcp"), + reserveHost: true, + }, + account: { id: "acct_primary", handle: "@steipete" }, + serverVersion: "test", + }, + { isLoopbackPeer: true }, + ); + expect(response.status).toBe(200); + return (await response.json()) as { + result: { + isError?: boolean; + structuredContent?: { count: number; items: Array<{ id: string }> }; + }; + }; +} +describe("Pass 11 MCP visible FTS scope", () => { + for (const hidden of ["deleted_at", "superseded_at"] as const) { + it.each([ + { likedOnly: false, bookmarkedOnly: false }, + { likedOnly: true, bookmarkedOnly: false }, + { likedOnly: false, bookmarkedOnly: true }, + { likedOnly: true, bookmarkedOnly: true }, + ])("excludes " + hidden + " from scoped FTS counts with %j", (filters) => { + const db = fixture(hidden, 2); + const preflight = __test__.preflightFtsSearch(db, { + query: "pass11needle", + accountId: "acct_primary", + resource: "home", + includeReplies: true, + ...filters, + }); + expect(preflight).toMatchObject({ + rawCandidateCount: 3, + candidateCount: 3, + scopedCount: 1, + }); + expect( + listTimelineItems( + { + account: "acct_primary", + resource: "home", + search: "pass11needle", + qualityFilter: "all", + ...filters, + }, + db, + ).map((t) => t.id), + ).toEqual(["p11_0"]); + }); + it( + "does not reject an otherwise small result because of " + + hidden + + " matches", + async () => { + const db = fixture(hidden, MCP_MAX_FTS_MATCHES); + const accepted = await search(); + expect(accepted.result.isError).not.toBe(true); + expect(accepted.result.structuredContent).toMatchObject({ + count: 1, + items: [{ id: "p11_0" }], + }); + db.prepare("update tweets set " + hidden + " = null").run(); + const rejected = await search(); + expect(rejected.result.isError).toBe(true); + expect(JSON.stringify(rejected)).toContain("more than 1000"); + }, + ); + } +}); diff --git a/src/lib/mcp-tools.ts b/src/lib/mcp-tools.ts index 39a62fcd..80fa54df 100644 --- a/src/lib/mcp-tools.ts +++ b/src/lib/mcp-tools.ts @@ -185,7 +185,7 @@ function preflightFtsSearch( const { ftsSearch: normalizedQuery, authorHandle } = parseTimelineSearch({ search: query, }); - const filters: string[] = []; + const filters: string[] = ["t.deleted_at is null", "t.superseded_at is null"]; const params: Array = [ normalizedQuery, MCP_MAX_FTS_CANDIDATES + 1, diff --git a/src/lib/search-discussion.test.ts b/src/lib/search-discussion.test.ts index 1abbe92f..15ad511c 100644 --- a/src/lib/search-discussion.test.ts +++ b/src/lib/search-discussion.test.ts @@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { Effect } from "effect"; +import * as tweetSearch from "./tweet-search-live"; import { processOpenAIResponseSseChunk } from "./openai-response-runtime"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { resetBirdclawPathsForTests } from "./config"; @@ -53,12 +54,70 @@ afterEach(() => { delete process.env.BIRDCLAW_OPENAI_REASONING_EFFORT; delete process.env.BIRDCLAW_OPENAI_SERVICE_TIER; vi.unstubAllGlobals(); + vi.restoreAllMocks(); for (const tempRoot of tempRoots.splice(0)) { rmSync(tempRoot, { recursive: true, force: true }); } }); describe("search discussion", () => { + for (const mode of ["auto", "bird", "xurl"] as const) { + it.each(["", " ", "\t\n"])( + "Pass 11 rejects blank " + mode + " query %j before live search", + async (query) => { + const live = vi + .spyOn(tweetSearch, "syncTweetSearchEffect") + .mockReturnValue( + Effect.fail(new Error("Live transport was invoked")), + ); + const effect = streamSearchDiscussionEffect({ query, mode }); + expect(live).not.toHaveBeenCalled(); + await expect(Effect.runPromise(effect)).rejects.toThrow( + "Search query is required", + ); + expect(live).not.toHaveBeenCalled(); + }, + ); + } + it.each(["Thanks for the detail", " Thanks for the detail"])( + "Pass 11 excludes metadata replies without a leading mention: %j", + (text) => { + const db = getNativeDb(); + db.prepare( + "update tweets set text = ?, reply_to_id = 'tweet_002' where id = 'tweet_001'", + ).run(text); + db.prepare( + "update tweets set text = 'Original standalone post', reply_to_id = null where id = 'tweet_003'", + ).run(); + const options = { + query: "detail", + source: "search" as const, + limit: 20, + liveSearch: { + ok: true as const, + source: "xurl" as const, + accountId: "acct_primary", + query: "detail", + count: 2, + pageCount: 1, + tweetIds: ["tweet_001", "tweet_003"], + }, + }; + expect( + collectSearchDiscussionContext({ + ...options, + originalsOnly: true, + }).tweets.map((t) => t.id), + ).toEqual(["tweet_003"]); + expect( + collectSearchDiscussionContext({ + ...options, + originalsOnly: false, + }).tweets.map((t) => t.id), + ).toEqual(["tweet_001", "tweet_003"]); + }, + ); + it("collects keyword matches from tweets and optional DMs", () => { const context = collectSearchDiscussionContext({ query: "local-first", diff --git a/src/lib/search-discussion.ts b/src/lib/search-discussion.ts index 547496b4..ea049c24 100644 --- a/src/lib/search-discussion.ts +++ b/src/lib/search-discussion.ts @@ -215,6 +215,7 @@ function collectLiveSearchTweets( t.text, t.created_at, t.is_replied, + t.reply_to_id, t.like_count, t.media_count, t.entities_json, @@ -291,7 +292,11 @@ function liveSearchRowPassesFilters( ) { const text = String(row.text); const createdAt = String(row.created_at); - if (options.originalsOnly && text.startsWith("@")) return false; + if ( + options.originalsOnly && + (Boolean(row.reply_to_id) || text.startsWith("@")) + ) + return false; if (options.since?.trim() && createdAt < options.since.trim()) return false; if (options.until?.trim() && createdAt >= options.until.trim()) return false; if (!options.hideLowQuality) return true; @@ -561,6 +566,9 @@ export function streamSearchDiscussionEffect( handlers: SearchDiscussionStreamHandlers = {}, ): Effect.Effect { return Effect.gen(function* () { + if (!options.query.trim()) { + return yield* Effect.fail(new Error("Search query is required")); + } const mode = options.mode ?? defaultLiveSyncMode("xurl"); const liveSearch = mode === "local" diff --git a/src/lib/web-sync.test.ts b/src/lib/web-sync.test.ts index 1610e948..1fa81a95 100644 --- a/src/lib/web-sync.test.ts +++ b/src/lib/web-sync.test.ts @@ -103,7 +103,14 @@ function setupDefaultAccount(accountId: string) { values (?, ?, ?, ?, ?, ?) `, ) - .run(accountId, "Studio", "@studio", "bird", 1, "2026-01-01T00:00:00.000Z"); + .run( + accountId, + "Studio workspace", + "@studio", + "bird", + 1, + "2026-01-01T00:00:00.000Z", + ); } describe("web sync dispatcher", () => { @@ -136,6 +143,74 @@ describe("web sync dispatcher", () => { } }); + for (const kind of ["timeline", "likes", "bookmarks"] as const) { + it.each([ + "@studio", + "studio", + "Studio", + "Studio workspace", + " acct_studio ", + " ", + ])( + "Pass 11 keeps auto mode for " + kind + " default selector %j", + async (account) => { + setupDefaultAccount("acct_studio"); + const mock = + kind === "timeline" + ? syncHomeTimelineMock + : syncTimelineCollectionMock; + mock.mockResolvedValue({ ok: true, source: "bird", count: 1 }); + const response = await runWebSync(kind, account); + expect(response.ok).toBe(true); + expect(mock).toHaveBeenCalledWith( + expect.objectContaining({ account, mode: "auto" }), + ); + expect(response.accountId).toBe(account); + await runWebSync(kind, "acct_other"); + expect(mock).toHaveBeenLastCalledWith( + expect.objectContaining({ account: "acct_other", mode: "xurl" }), + ); + }, + ); + } + it.each([ + "@studio", + "studio", + "Studio", + "Studio workspace", + " acct_studio ", + " ", + ])( + "Pass 11 coalesces default aliases %j without changing the caller account", + async (account) => { + setupDefaultAccount("acct_studio"); + const pending = deferred<{ + ok: boolean; + source: string; + count: number; + }>(); + syncHomeTimelineMock.mockReturnValue(pending.promise); + const first = startWebSync("timeline", account); + const omitted = startWebSync("timeline"); + const canonical = startWebSync("timeline", "acct_studio"); + const other = startWebSync("timeline", "acct_other"); + pending.resolve({ ok: true, source: "bird", count: 1 }); + await vi.waitFor(() => { + for (const job of [first, omitted, canonical, other]) + expect(getWebSyncJob(job.id)?.status).toBe("succeeded"); + }); + expect(omitted.id).toBe(first.id); + expect(canonical.id).toBe(first.id); + expect(other.id).not.toBe(first.id); + expect(first.accountId).toBe(account); + expect(syncHomeTimelineMock).toHaveBeenCalledTimes(2); + expect(syncHomeTimelineMock).toHaveBeenNthCalledWith( + 1, + expect.objectContaining({ account }), + ); + }, + ); + it("syncs the home timeline with a live refresh and backup pass", async () => { syncHomeTimelineMock.mockResolvedValue({ ok: true, diff --git a/src/lib/web-sync.ts b/src/lib/web-sync.ts index f035e9a3..fefaf2e7 100644 --- a/src/lib/web-sync.ts +++ b/src/lib/web-sync.ts @@ -114,8 +114,8 @@ const WEB_SYNC_PLANS: Record = { account, mode: getPreferredTransport() || - !account || - account === resolveDefaultSyncAccountId(runtime) + resolveSyncAccountId(account, runtime) === + resolveDefaultSyncAccountId(runtime) ? "auto" : "xurl", limit: 100, @@ -223,7 +223,8 @@ function syncSavedCollection( ): Effect.Effect { return Effect.gen(function* () { const isNonDefaultAccount = - account !== undefined && account !== resolveDefaultSyncAccountId(runtime); + resolveSyncAccountId(account, runtime) !== + resolveDefaultSyncAccountId(runtime); const result = yield* syncTimelineCollectionEffect({ kind, account, @@ -300,6 +301,40 @@ function resolveDefaultSyncAccountId(runtime: ServerRuntimeServices) { } } +function resolveSyncAccountId( + account: string | undefined, + runtime: ServerRuntimeServices, +): string { + const selector = account?.trim(); + if (!selector) return resolveDefaultSyncAccountId(runtime); + const dbPath = runtime.getPaths().dbPath; + if (!existsSync(dbPath)) return selector; + let db: NativeSqliteDatabase | undefined; + try { + db = new NativeSqliteDatabase(dbPath, { readonly: true }); + const row = db + .prepare(` + select id from accounts + where id = ? + or lower(ltrim(handle, '@')) = lower(ltrim(?, '@')) + or lower(name) = lower(?) + order by case + when id = ? then 0 + when lower(ltrim(handle, '@')) = lower(ltrim(?, '@')) then 1 + else 2 end, is_default desc, created_at asc + limit 1 + `) + .get(selector, selector, selector, selector, selector) as + | { id: string } + | undefined; + return row?.id ?? selector; + } catch { + return selector; + } finally { + db?.close(); + } +} + function serializeSyncOptions(kind: WebSyncKind, options: WebSyncOptions) { if (kind !== "dms") return ""; const parts = [ @@ -318,7 +353,7 @@ function getRunningSyncKey( runtime: ServerRuntimeServices = defaultServerRuntimeServices, ) { const optionKey = serializeSyncOptions(kind, options); - return `${kind}:${accountId ?? resolveDefaultSyncAccountId(runtime)}${optionKey ? `:${optionKey}` : ""}`; + return `${kind}:${resolveSyncAccountId(accountId, runtime)}${optionKey ? `:${optionKey}` : ""}`; } function setJobSnapshot(snapshot: WebSyncJobSnapshot) { From 678e6061ce4a1344e299c264ac1a9df87f2aac9f Mon Sep 17 00:00:00 2001 From: Bobby Bones Date: Sun, 8 Nov 2026 18:56:13 -0500 Subject: [PATCH 2/2] fix(sync,cli): reuse findOperationAccount in web-sync and bound cache-ttl ms in numeric-options --- src/cli/numeric-options.ts | 7 +++- src/cli/register-sync.ts | 17 +++------- src/cli/sync-contract.test.ts | 61 +++++++++-------------------------- src/lib/web-sync.test.ts | 18 ++--------- src/lib/web-sync.ts | 25 +++----------- 5 files changed, 33 insertions(+), 95 deletions(-) diff --git a/src/cli/numeric-options.ts b/src/cli/numeric-options.ts index f6ac9085..7c0b4523 100644 --- a/src/cli/numeric-options.ts +++ b/src/cli/numeric-options.ts @@ -24,7 +24,12 @@ export function configureNumericOptions(program: Command) { throw new CliInputError(`${option.long} must be a finite number`); } } else if (name === "cacheTtl") { - if (!text || !Number.isFinite(number) || number < 0) { + if ( + !text || + !Number.isFinite(number) || + !Number.isFinite(number * 1000) || + number < 0 + ) { throw new CliInputError( `${option.long} must be a non-negative finite number`, ); diff --git a/src/cli/register-sync.ts b/src/cli/register-sync.ts index 7018bd6b..bc3e9ff6 100644 --- a/src/cli/register-sync.ts +++ b/src/cli/register-sync.ts @@ -14,15 +14,6 @@ import { syncHomeTimeline } from "#/lib/timeline-live"; import { syncXLists, type XListSyncMode } from "#/lib/x-lists"; import { errorMessage, type CliCommandContext } from "./command-context"; -function parseCacheTtlMs(value: string | undefined): number | undefined { - if (value === undefined) return undefined; - const milliseconds = Number(value) * 1000; - if (!value.trim() || !Number.isFinite(milliseconds) || milliseconds < 0) { - throw new Error("--cache-ttl must be a non-negative number"); - } - return milliseconds; -} - export function registerSyncCommands({ program, print, @@ -87,7 +78,7 @@ export function registerSyncCommands({ maxPages: Number(options.maxPages), following: !options.forYou, refresh: Boolean(options.refresh), - cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + cacheTtlMs: Number(options.cacheTtl) * 1000, }); await autoSyncAfterWrite(); print(result, true); @@ -141,7 +132,7 @@ export function registerSyncCommands({ sinceId: options.sinceId, startTime: options.startTime, refresh: Boolean(options.refresh), - cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + cacheTtlMs: Number(options.cacheTtl) * 1000, }); await autoSyncAfterWrite(); print(result, true); @@ -270,7 +261,7 @@ export function registerSyncCommands({ maxPages: options.maxPages ? Number(options.maxPages) : undefined, paginationToken: options.paginationToken, refresh: Boolean(options.refresh), - cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + cacheTtlMs: Number(options.cacheTtl) * 1000, earlyStop: Boolean(options.earlyStop), }); await autoSyncAfterWrite(); @@ -316,7 +307,7 @@ export function registerSyncCommands({ maxResources: options.maxResources ? Number(options.maxResources) : undefined, - cacheTtlMs: parseCacheTtlMs(options.cacheTtl), + cacheTtlMs: Number(options.cacheTtl) * 1000, refresh: Boolean(options.refresh), allowPartial: Boolean(options.allowPartial), yes: Boolean(options.yes), diff --git a/src/cli/sync-contract.test.ts b/src/cli/sync-contract.test.ts index 55a9f19d..4e0db153 100644 --- a/src/cli/sync-contract.test.ts +++ b/src/cli/sync-contract.test.ts @@ -1,8 +1,10 @@ // @vitest-environment node import { Command } from "commander"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { registerSyncCommands } from "./register-sync"; import { createCommandContext } from "./command-context"; +import { CliInputError, configureNumericOptions } from "./numeric-options"; +import { registerSyncCommands } from "./register-sync"; + const mocks = vi.hoisted(() => ({ timeline: vi.fn(), collection: vi.fn(), @@ -15,10 +17,12 @@ vi.mock("#/lib/timeline-collections-live", () => ({ })); vi.mock("#/lib/mentions-live", () => ({ syncMentions: mocks.mentions })); vi.mock("#/lib/follow-graph", () => ({ syncFollowGraph: mocks.graph })); + function fixture() { const program = new Command().exitOverride(); const print = vi.fn(); const backup = vi.fn().mockResolvedValue(undefined); + configureNumericOptions(program); registerSyncCommands({ ...createCommandContext(program), print, @@ -31,6 +35,7 @@ function fixture() { backup, }; } + const initialExitCode = process.exitCode; beforeEach(() => { process.exitCode = 0; @@ -40,7 +45,8 @@ beforeEach(() => { afterEach(() => { process.exitCode = initialExitCode; }); -describe("Pass 11 sync registration contracts", () => { + +describe("sync registration contracts", () => { for (const kind of ["timeline", "likes", "bookmarks"] as const) { it( "prints structured " + kind + " transport failures without backup writes", @@ -64,48 +70,13 @@ describe("Pass 11 sync registration contracts", () => { }, ); } - for (const kind of [ - "timeline", - "mentions", - "likes", - "bookmarks", - "followers", - "following", - ]) { - it.each(["-1", "NaN", "not-a-number", "Infinity", "1e308"])( - "rejects " + kind + " cache TTL %j before sync or backup", - async (ttl) => { - const f = fixture(); - await f.run([kind, "--cache-ttl", ttl]); - expect(f.print).toHaveBeenCalledWith( - expect.objectContaining({ - ok: false, - error: "--cache-ttl must be a non-negative number", - }), - true, - ); - expect(process.exitCode).toBe(1); - for (const mock of Object.values(mocks)) - expect(mock).not.toHaveBeenCalled(); - expect(f.backup).not.toHaveBeenCalled(); - process.exitCode = 0; - await fixture().run([kind, "--cache-ttl", "0"]); - const mock = - kind === "timeline" - ? mocks.timeline - : kind === "mentions" - ? mocks.mentions - : kind === "likes" || kind === "bookmarks" - ? mocks.collection - : mocks.graph; - expect(mock).toHaveBeenLastCalledWith( - expect.objectContaining({ cacheTtlMs: 0 }), - ); - await fixture().run([kind, "--cache-ttl", "0.25"]); - expect(mock).toHaveBeenLastCalledWith( - expect.objectContaining({ cacheTtlMs: 250 }), - ); - }, + + it("rejects overflowing --cache-ttl seconds in the shared numeric hook before sync or backup", async () => { + const f = fixture(); + await expect(f.run(["timeline", "--cache-ttl", "1e308"])).rejects.toThrow( + new CliInputError("--cache-ttl must be a non-negative finite number"), ); - } + expect(mocks.timeline).not.toHaveBeenCalled(); + expect(f.backup).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/web-sync.test.ts b/src/lib/web-sync.test.ts index 1fa81a95..1a2a6ec5 100644 --- a/src/lib/web-sync.test.ts +++ b/src/lib/web-sync.test.ts @@ -144,14 +144,7 @@ describe("web sync dispatcher", () => { }); for (const kind of ["timeline", "likes", "bookmarks"] as const) { - it.each([ - "@studio", - "studio", - "Studio", - "Studio workspace", - " acct_studio ", - " ", - ])( + it.each(["@studio", "studio", "Studio", " acct_studio "])( "Pass 11 keeps auto mode for " + kind + " default selector %j", async (account) => { setupDefaultAccount("acct_studio"); @@ -173,14 +166,7 @@ describe("web sync dispatcher", () => { }, ); } - it.each([ - "@studio", - "studio", - "Studio", - "Studio workspace", - " acct_studio ", - " ", - ])( + it.each(["@studio", "studio", "Studio", " acct_studio "])( "Pass 11 coalesces default aliases %j without changing the caller account", async (account) => { setupDefaultAccount("acct_studio"); diff --git a/src/lib/web-sync.ts b/src/lib/web-sync.ts index fefaf2e7..2d0ed967 100644 --- a/src/lib/web-sync.ts +++ b/src/lib/web-sync.ts @@ -1,3 +1,4 @@ +import { findOperationAccount } from "./account-selection"; import type { z } from "zod"; import type * as contracts from "./api-contracts"; import { existsSync } from "node:fs"; @@ -305,31 +306,15 @@ function resolveSyncAccountId( account: string | undefined, runtime: ServerRuntimeServices, ): string { - const selector = account?.trim(); - if (!selector) return resolveDefaultSyncAccountId(runtime); + if (account === undefined) return resolveDefaultSyncAccountId(runtime); const dbPath = runtime.getPaths().dbPath; - if (!existsSync(dbPath)) return selector; + if (!existsSync(dbPath)) return account; let db: NativeSqliteDatabase | undefined; try { db = new NativeSqliteDatabase(dbPath, { readonly: true }); - const row = db - .prepare(` - select id from accounts - where id = ? - or lower(ltrim(handle, '@')) = lower(ltrim(?, '@')) - or lower(name) = lower(?) - order by case - when id = ? then 0 - when lower(ltrim(handle, '@')) = lower(ltrim(?, '@')) then 1 - else 2 end, is_default desc, created_at asc - limit 1 - `) - .get(selector, selector, selector, selector, selector) as - | { id: string } - | undefined; - return row?.id ?? selector; + return findOperationAccount(db, account)?.id ?? account; } catch { - return selector; + return account; } finally { db?.close(); }