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 44af7f38..bc3e9ff6 100644 --- a/src/cli/register-sync.ts +++ b/src/cli/register-sync.ts @@ -70,17 +70,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: Number(options.cacheTtl) * 1000, + }); + await autoSyncAfterWrite(); + print(result, true); + } catch (error) { + print( + { + ok: false, + kind: "timeline", + mode: options.mode, + error: errorMessage(error), + }, + true, + ); + process.exitCode = 1; + } }); syncCommand @@ -238,20 +251,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: Number(options.cacheTtl) * 1000, + 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; + } }); } diff --git a/src/cli/sync-contract.test.ts b/src/cli/sync-contract.test.ts new file mode 100644 index 00000000..4e0db153 --- /dev/null +++ b/src/cli/sync-contract.test.ts @@ -0,0 +1,82 @@ +// @vitest-environment node +import { Command } from "commander"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; +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(), + 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); + configureNumericOptions(program); + 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("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); + }, + ); + } + + 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/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..1a2a6ec5 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,60 @@ describe("web sync dispatcher", () => { } }); + for (const kind of ["timeline", "likes", "bookmarks"] as const) { + it.each(["@studio", "studio", "Studio", " 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", " 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..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"; @@ -114,8 +115,8 @@ const WEB_SYNC_PLANS: Record = { account, mode: getPreferredTransport() || - !account || - account === resolveDefaultSyncAccountId(runtime) + resolveSyncAccountId(account, runtime) === + resolveDefaultSyncAccountId(runtime) ? "auto" : "xurl", limit: 100, @@ -223,7 +224,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 +302,24 @@ function resolveDefaultSyncAccountId(runtime: ServerRuntimeServices) { } } +function resolveSyncAccountId( + account: string | undefined, + runtime: ServerRuntimeServices, +): string { + if (account === undefined) return resolveDefaultSyncAccountId(runtime); + const dbPath = runtime.getPaths().dbPath; + if (!existsSync(dbPath)) return account; + let db: NativeSqliteDatabase | undefined; + try { + db = new NativeSqliteDatabase(dbPath, { readonly: true }); + return findOperationAccount(db, account)?.id ?? account; + } catch { + return account; + } finally { + db?.close(); + } +} + function serializeSyncOptions(kind: WebSyncKind, options: WebSyncOptions) { if (kind !== "dms") return ""; const parts = [ @@ -318,7 +338,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) {