#!/usr/bin/env node import { atlasDataDir, databasePath, openDatabase, pruneOrphanResources, refreshResourceFts } from "./db.ts"; import { syncGitHubStars } from "./github.ts"; import { getResource, searchResources } from "./search.ts"; import { recall, relatedResources } from "./recall.ts"; import { collectStage } from "./stage.ts"; import { enrichGitHubReadmes, enrichWebPages } from "./enrich.ts"; import { importXJsonFile, repairXPosts } from "./x.ts"; import { collectXBookmarks } from "./collector.ts"; import { BROWSER_PROVIDERS, browserContributions, discoverBrowserSources, distinctBookmarkPages, isBrowserInstalled, readBrowserSource, syncBrowserBookmarks } from "./browsers.ts"; import { atlasConfigPath, readConfig, writeConfig } from "./config.ts"; import { startXCaptureServer } from "./receiver.ts"; import { startMcpServer } from "./mcp.ts"; function optionValue(args: string[], name: string): string | undefined { const index = args.indexOf(name); return index >= 0 ? args[index + 1] : undefined; } // Only these flags consume the next argument. Boolean flags (--stage, --fast, // --clear, ...) must not swallow the positional text that follows. const VALUE_FLAGS = new Set([ "--limit", "--repo", "--account", "--concurrency", "--port", "--browser", "--profile", "--enable", ]); function positional(args: string[]): string[] { const result: string[] = []; for (let index = 0; index < args.length; index += 1) { const argument = args[index]; if (argument === undefined) break; if (argument.startsWith("--")) { if (VALUE_FLAGS.has(argument)) index += 1; continue; } result.push(argument); } return result; } function printHelp(): void { console.log(`Bookmark Atlas — read your starred bookmarks and their content Usage: bookmark-atlas sync github [--limit N] [--account NAME] bookmark-atlas sync browsers [--browser NAME] [--profile NAME] [--limit N] bookmark-atlas browsers bookmark-atlas browsers --enable NAME,NAME | --enable all | --enable none bookmark-atlas enrich github-readmes [--limit N] [--concurrency N] [--refresh] bookmark-atlas enrich web-pages [--limit N] [--concurrency N] [--refresh] bookmark-atlas enrich x-posts bookmark-atlas import x-json [--account NAME] [--reconcile] bookmark-atlas collect x [--account NAME] [--full] [--fast] [--keep-export] bookmark-atlas capture x [--port N] bookmark-atlas search [--limit N] bookmark-atlas recall [--repo PATH] [--limit N] [--stage] bookmark-atlas related [--limit N] bookmark-atlas get [--content] bookmark-atlas note [--clear] bookmark-atlas status bookmark-atlas prune [--dry-run] bookmark-atlas mcp Environment: BOOKMARK_ATLAS_DB SQLite path (default: ${databasePath()}) BOOKMARK_ATLAS_DATA_DIR Data directory (default: ${atlasDataDir()}) BOOKMARK_ATLAS_GITHUB_TOKEN GitHub token (falls back to GH_TOKEN or gh auth token) BOOKMARK_ATLAS_TWEETXVAULT_BIN TweetXVault executable (default: tweetxvault) BOOKMARK_ATLAS_X_CAPTURE_TOKEN Required token for the local browser capture receiver `); } async function main(): Promise { const args = process.argv.slice(2); const command = args[0]; if (!command || command === "help" || command === "--help") { printHelp(); return; } const db = openDatabase(databasePath()); try { if (command === "collect" && args[1] === "x") { const account = optionValue(args, "--account"); const result = collectXBookmarks(db, { ...(account ? { account } : {}), full: args.includes("--full"), fast: args.includes("--fast"), keepExport: args.includes("--keep-export"), }); console.log(JSON.stringify(result, null, 2)); return; } if (command === "capture" && args[1] === "x") { const token = process.env.BOOKMARK_ATLAS_X_CAPTURE_TOKEN; if (!token) throw new Error("Set BOOKMARK_ATLAS_X_CAPTURE_TOKEN before starting capture x"); const rawPort = optionValue(args, "--port"); const port = rawPort ? Number.parseInt(rawPort, 10) : 41009; if (!Number.isSafeInteger(port) || port < 1 || port > 65535) throw new Error("--port must be between 1 and 65535"); const capture = await startXCaptureServer({ db, token, port }); console.log(JSON.stringify({ listening: capture.address, endpoints: ["/session/start", "/session/batch", "/session/complete"] }, null, 2)); await new Promise((resolve, reject) => { const stop = () => capture.close().then(resolve, reject); process.once("SIGINT", stop); process.once("SIGTERM", stop); }); return; } if (command === "mcp") { await startMcpServer(db); return; } if (command === "sync" && args[1] === "github") { const rawLimit = optionValue(args, "--limit"); const limit = rawLimit ? Number.parseInt(rawLimit, 10) : undefined; if (rawLimit && (!Number.isFinite(limit) || (limit ?? 0) < 1)) { throw new Error("--limit must be a positive integer"); } const account = optionValue(args, "--account"); const result = await syncGitHubStars(db, { ...(account ? { account } : {}), ...(limit ? { limit } : {}), }); console.log(JSON.stringify(result, null, 2)); return; } if (command === "sync" && args[1] === "browsers") { const rawLimit = optionValue(args, "--limit"); const limit = rawLimit ? Number.parseInt(rawLimit, 10) : undefined; if (rawLimit && (!Number.isFinite(limit) || (limit ?? 0) < 1)) { throw new Error("--limit must be a positive integer"); } const provider = optionValue(args, "--browser"); const profile = optionValue(args, "--profile"); const result = syncBrowserBookmarks(db, { ...(provider ? { provider } : {}), ...(profile ? { profile } : {}), ...(limit ? { limit } : {}), }); console.log(JSON.stringify(result, null, 2)); return; } if (command === "browsers") { const configured = readConfig().browsers; // With nothing recorded, "all" means every browser that is installed. A // leftover profile of an uninstalled browser stays off until asked for. const isEnabled = (provider: string): boolean => configured === null ? isBrowserInstalled(provider) : configured.includes(provider); const known = [...BROWSER_PROVIDERS].sort((a, b) => a.localeCompare(b)); // --enable is the only writer of the browser selection, so the palette // shells out to it rather than reimplementing the config file format. const request = optionValue(args, "--enable"); if (request !== undefined) { const requested = request.trim().toLowerCase(); let next: string[] | null; if (requested === "all" || requested === "") next = null; else if (requested === "none") next = []; else next = [...new Set(requested.split(",").map((name) => name.trim()).filter(Boolean))]; const unknown = (next ?? []).filter((name) => !BROWSER_PROVIDERS.has(name)); if (unknown.length > 0) { throw new Error( `unknown browser${unknown.length > 1 ? "s" : ""}: ${unknown.join(", ")}. ` + `Known browsers: ${known.join(", ")}`, ); } writeConfig({ browsers: next }); console.log(JSON.stringify({ config: atlasConfigPath(), browsers: next ?? "all" }, null, 2)); return; } // The diagnostic for "why is Safari empty?": it reports the permission // error per source instead of failing the whole run. // Every source is read once here, and the pages it holds are kept, so the // per-browser totals come from the browser files rather than from what // happens to be synced. A browser that is switched off has its saves marked // removed, so a database view reports nothing for exactly the browsers // someone opens this list to decide about. const pagesByProvider = new Map>(); const sources = discoverBrowserSources().map((source) => { const base = { provider: source.provider, profile: source.profile, kind: source.kind, path: source.path, installed: isBrowserInstalled(source.provider), enabled: isEnabled(source.provider), }; try { const bookmarks = readBrowserSource(source); const pages = pagesByProvider.get(source.provider) ?? new Set(); for (const page of distinctBookmarkPages(bookmarks)) pages.add(page); pagesByProvider.set(source.provider, pages); return { ...base, bookmarks: bookmarks.length }; } catch (error) { return { ...base, error: error instanceof Error ? error.message : String(error) }; } }); console.log( JSON.stringify( { config: atlasConfigPath(), enabled: configured ?? "all", known, found: sources.length, // Per browser, not per profile: pages is what it holds and unique is // what nothing else holds, so a browser with a thousand bookmarks // and four unique pages reads as what it is. contributions: browserContributions(pagesByProvider), sources, }, null, 2, ), ); return; } if (command === "search") { const query = positional(args.slice(1)).join(" ").trim(); if (!query) throw new Error("search requires a query"); const limit = Number.parseInt(optionValue(args, "--limit") ?? "10", 10); console.log(JSON.stringify(searchResources(db, query, limit), null, 2)); return; } if (command === "recall") { const focus = positional(args.slice(1)).join(" ").trim(); const useStage = args.includes("--stage"); if (!focus && !useStage) throw new Error("recall requires a task description"); const explicitRepo = optionValue(args, "--repo"); const repoPath = explicitRepo ?? (useStage ? process.cwd() : undefined); // --stage derives "where the project is now" from git so the caller does // not have to describe the current state by hand. const stage = useStage && repoPath ? collectStage(repoPath, focus) : null; if (!focus && !stage) throw new Error("recall found nothing to work with; pass a task description"); const limit = Number.parseInt(optionValue(args, "--limit") ?? "5", 10); if (stage) process.stderr.write(`stage: branch=${stage.branch ?? "?"} · ${stage.commits.length} commits · ${stage.files.length} files\n`); console.log( JSON.stringify( recall(db, { task: focus, ...(repoPath ? { repoPath } : {}), ...(stage ? { stage: stage.description } : {}), limit, }), null, 2, ), ); return; } if (command === "related") { const id = Number.parseInt(args[1] ?? "", 10); if (!Number.isFinite(id) || id < 1) throw new Error("related requires a numeric resource id"); const limit = Number.parseInt(optionValue(args, "--limit") ?? "10", 10); console.log(JSON.stringify(relatedResources(db, id, { limit }), null, 2)); return; } if (command === "import" && args[1] === "x-json") { const file = args[2]; if (!file || file.startsWith("--")) throw new Error("import x-json requires a file path"); const account = optionValue(args, "--account"); console.log( JSON.stringify( importXJsonFile(db, file, { ...(account ? { account } : {}), reconcile: args.includes("--reconcile"), }), null, 2, ), ); return; } if (command === "enrich" && args[1] === "x-posts") { console.log(JSON.stringify(repairXPosts(db), null, 2)); return; } if (command === "enrich" && args[1] === "web-pages") { const limit = Number.parseInt(optionValue(args, "--limit") ?? "25", 10); const concurrency = Number.parseInt(optionValue(args, "--concurrency") ?? "4", 10); if (!Number.isFinite(limit) || limit < 1) throw new Error("--limit must be a positive integer"); if (!Number.isFinite(concurrency) || concurrency < 1) { throw new Error("--concurrency must be a positive integer"); } console.log( JSON.stringify( await enrichWebPages(db, { limit, concurrency, refresh: args.includes("--refresh") }), null, 2, ), ); return; } if (command === "enrich" && args[1] === "github-readmes") { const limit = Number.parseInt(optionValue(args, "--limit") ?? "25", 10); const concurrency = Number.parseInt(optionValue(args, "--concurrency") ?? "4", 10); if (!Number.isFinite(limit) || limit < 1) throw new Error("--limit must be a positive integer"); if (!Number.isFinite(concurrency) || concurrency < 1) { throw new Error("--concurrency must be a positive integer"); } console.log( JSON.stringify( await enrichGitHubReadmes(db, { limit, concurrency, refresh: args.includes("--refresh") }), null, 2, ), ); return; } if (command === "get") { const id = Number.parseInt(args[1] ?? "", 10); if (!Number.isFinite(id) || id < 1) throw new Error("get requires a numeric resource id"); const resource = getResource(db, id, args.includes("--content")); if (!resource) throw new Error(`resource ${id} not found`); console.log(JSON.stringify(resource, null, 2)); return; } if (command === "note") { const id = Number.parseInt(args[1] ?? "", 10); if (!Number.isFinite(id) || id < 1) throw new Error("note requires a numeric resource id"); const text = positional(args.slice(2)).join(" ").trim(); if (!text || args.includes("--clear")) { db.prepare("DELETE FROM resource_notes WHERE resource_id = ?").run(id); } else { db.prepare(` INSERT INTO resource_notes (resource_id, context, updated_at) VALUES (?, ?, ?) ON CONFLICT(resource_id) DO UPDATE SET context = excluded.context, updated_at = excluded.updated_at `).run(id, text, new Date().toISOString()); } refreshResourceFts(db, id); const row = db.prepare("SELECT context FROM resource_notes WHERE resource_id = ?").get(id) as | { context: string } | undefined; console.log(JSON.stringify({ id, context: row?.context ?? null }, null, 2)); return; } if (command === "prune") { console.log(JSON.stringify(pruneOrphanResources(db, { dryRun: args.includes("--dry-run") }), null, 2)); return; } if (command === "status") { const counts = db.prepare(` SELECT (SELECT COUNT(*) FROM resources) AS resources, (SELECT COUNT(*) FROM saves WHERE unsaved_at IS NULL) AS activeSaves, (SELECT COUNT(*) FROM resources_fts) AS indexedResources, (SELECT COUNT(*) FROM captures WHERE kind = 'github_readme') AS readmeCaptures, (SELECT COUNT(*) FROM x_posts) AS xPosts, (SELECT COUNT(*) FROM chunks) AS chunks, (SELECT COUNT(*) FROM resources r JOIN saves s ON s.resource_id = r.id AND s.unsaved_at IS NULL LEFT JOIN resource_fetch_state f ON f.resource_id = r.id AND f.kind = 'web_page' WHERE r.resource_type = 'web_page' AND f.resource_id IS NULL) AS webPagesPending `).get(); const fetchState = db.prepare(` SELECT kind, status, COUNT(*) AS count FROM resource_fetch_state GROUP BY kind, status ORDER BY kind, status `).all(); const sync = db.prepare(` SELECT i.provider, i.account, c.high_watermark AS highWatermark, c.last_success_at AS lastSuccessAt, c.last_reconciled_at AS lastReconciledAt, c.last_error AS lastError FROM integrations i LEFT JOIN sync_checkpoints c ON c.integration_id = i.id ORDER BY i.provider, i.account `).all(); console.log( JSON.stringify( { database: databasePath(), counts, fetchState, sync, }, null, 2, ), ); return; } throw new Error(`Unknown command: ${args.join(" ")}`); } finally { db.close(); } } main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exitCode = 1; });