import * as p from "@clack/prompts"; import { listDuplicatedMemoryCopies, MemoryStore, resolveDbPath } from "@codemem/core"; import { Command } from "commander"; import { helpStyle } from "../help-style.js"; import { addDbOption, addJsonOption, emitJsonError, resolveDbOpt } from "../shared-options.js"; interface SyncDuplicatesOptions { db?: string; dbPath?: string; json?: boolean; } /** Prints the memories this device stores more than one copy of in one scope now. */ function runSyncDuplicates(opts: SyncDuplicatesOptions): void { let store: MemoryStore | null = null; try { store = new MemoryStore(resolveDbPath(resolveDbOpt(opts))); const duplicates = listDuplicatedMemoryCopies(store.db); if (opts.json) { console.log(JSON.stringify({ duplicates, count: duplicates.length })); return; } if (duplicates.length === 0) { p.log.success("No memory has more than one copy in a scope."); return; } const lines = duplicates.map( (group) => ` ${group.scope_id ?? "(no scope)"}: memories ${group.memory_ids.map((id) => `#${id}`).join(", ")}`, ); p.log.warn( `${duplicates.length} memories are stored more than once in a scope. Sync sends and applies none of their copies until all but one are removed:\n${lines.join("\n")}`, ); } catch (error) { const message = error instanceof Error ? error.message : "Listing duplicate copies failed"; if (opts.json) { emitJsonError("duplicates_failed", message); return; } p.log.error(message); process.exitCode = 1; } finally { store?.close(); } } export function buildSyncDuplicatesCommand(): Command { const cmd = new Command("duplicates") .configureHelp(helpStyle) .description("List memories stored more than once in a scope, which sync withholds"); addDbOption(cmd); addJsonOption(cmd); cmd.action((opts: SyncDuplicatesOptions) => runSyncDuplicates(opts)); return cmd; }