obsidian-sync-mcp 0.7.2 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -2,11 +2,13 @@
2
2
  // Node polyfills for livesync-commonlib browser globals
3
3
  if(!("navigator" in globalThis)){globalThis.navigator={language:"en"};}
4
4
  import {
5
- applyIndexChange
6
- } from "./chunk-SGLPTZJA.js";
5
+ applyIndexChange,
6
+ pruneGhosts
7
+ } from "./chunk-GSVMRHWP.js";
7
8
  import {
9
+ isValidNotePath,
8
10
  parseFrontmatterAndLinks
9
- } from "./chunk-43MP6CJE.js";
11
+ } from "./chunk-VR63UUCB.js";
10
12
 
11
13
  // src/main.ts
12
14
  import { FastMCP } from "fastmcp";
@@ -184,7 +186,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
184
186
  console.log(`Auth: /oauth/authorize accepted client_id=${clientId} redirect_uri=${JSON.stringify(redirectUri)}`);
185
187
  const csrf = randomBytes(32).toString("hex");
186
188
  csrfTokens.set(code, csrf);
187
- return c.html(renderPasswordPage(code, csrf));
189
+ return c.html(renderPasswordPage(code, csrf, hostOf(redirectUri), client.clientName));
188
190
  });
189
191
  app.post("/oauth/approve", async (c) => {
190
192
  const body = await c.req.parseBody();
@@ -204,7 +206,7 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
204
206
  console.warn(`Auth: locked out, ${waitSec}s remaining`);
205
207
  const newCsrf = randomBytes(32).toString("hex");
206
208
  csrfTokens.set(code, newCsrf);
207
- return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
209
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${waitSec} seconds.`), 429);
208
210
  }
209
211
  if (typeof submittedPassword !== "string" || !safeEqual(submittedPassword, password)) {
210
212
  failedAttempts++;
@@ -216,9 +218,9 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
216
218
  const lockoutMs = BASE_LOCKOUT_MS * Math.pow(2, lockoutCount - 1);
217
219
  lockedUntil = Date.now() + lockoutMs;
218
220
  console.warn(`Auth: lockout #${lockoutCount}, ${lockoutMs / 1e3}s`);
219
- return c.html(renderPasswordPage(code, newCsrf, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
221
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, `Too many attempts. Try again in ${Math.ceil(lockoutMs / 1e3)} seconds.`), 429);
220
222
  }
221
- return c.html(renderPasswordPage(code, newCsrf, "Wrong password."), 401);
223
+ return c.html(renderPasswordPage(code, newCsrf, hostOf(pending.redirectUri), clients.get(pending.clientId)?.clientName, "Wrong password."), 401);
222
224
  }
223
225
  failedAttempts = 0;
224
226
  lockoutCount = 0;
@@ -381,7 +383,16 @@ function mountPasswordAuth(app, baseUrl, password, persistPath) {
381
383
  }
382
384
  };
383
385
  }
384
- function renderPasswordPage(code, csrf, error) {
386
+ function hostOf(uri) {
387
+ try {
388
+ return new URL(uri).host;
389
+ } catch {
390
+ return uri;
391
+ }
392
+ }
393
+ function renderPasswordPage(code, csrf, redirectHost, clientName, error) {
394
+ const esc = (s) => s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
395
+ const who = clientName ? `<b>${esc(clientName)}</b> (name self-reported)` : "An application";
385
396
  return `<!DOCTYPE html>
386
397
  <html><head><title>Obsidian Sync MCP - Authorize</title>
387
398
  <meta http-equiv="Content-Security-Policy" content="default-src 'none'; style-src 'unsafe-inline'">
@@ -391,10 +402,15 @@ function renderPasswordPage(code, csrf, error) {
391
402
  input[type=password] { width: 100%; padding: 10px; margin: 10px 0; box-sizing: border-box; font-size: 1em; }
392
403
  button { padding: 10px 20px; font-size: 1em; cursor: pointer; }
393
404
  .error { color: red; }
405
+ .dest { background: #f3f3f3; padding: 8px 10px; border-radius: 6px; word-break: break-all; }
406
+ .warn { color: #a15c00; }
394
407
  </style></head>
395
408
  <body>
396
409
  <h1>Obsidian Sync MCP</h1>
397
- ${error ? `<p class="error">${error.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;")}</p>` : "<p>Enter the server password to authorize access to your vault.</p>"}
410
+ <p>${who} is requesting access to your vault. After you approve, your browser will be sent to:</p>
411
+ <p class="dest"><b>${esc(redirectHost)}</b></p>
412
+ <p class="warn">Only enter your password if you recognize this destination. If you did not start this sign-in, close this page.</p>
413
+ ${error ? `<p class="error">${esc(error)}</p>` : ""}
398
414
  <form method="POST" action="/oauth/approve" autocomplete="on">
399
415
  <input type="hidden" name="code" value="${code.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
400
416
  <input type="hidden" name="csrf" value="${csrf.replace(/&/g, "&amp;").replace(/"/g, "&quot;")}">
@@ -425,6 +441,12 @@ function decrypt(data, passphrase) {
425
441
  decipher.setAuthTag(Buffer.from(tagHex, "hex"));
426
442
  return Buffer.concat([decipher.update(Buffer.from(encryptedHex, "hex")), decipher.final()]).toString("utf-8");
427
443
  }
444
+ function snippetAround(text, idx, len, context = 80) {
445
+ const start = Math.max(0, idx - context);
446
+ const end = Math.min(text.length, idx + len + context);
447
+ const body = text.slice(start, end).replace(/\s+/g, " ").trim();
448
+ return (start > 0 ? "\u2026" : "") + body + (end < text.length ? "\u2026" : "");
449
+ }
428
450
  var SearchIndex = class {
429
451
  _state = "building";
430
452
  mtimes = /* @__PURE__ */ new Map();
@@ -432,8 +454,14 @@ var SearchIndex = class {
432
454
  links = /* @__PURE__ */ new Map();
433
455
  backlinks = /* @__PURE__ */ new Map();
434
456
  knownPaths = /* @__PURE__ */ new Set();
457
+ /** Decrypted note text, in memory only — one copy per note; term matching is case-insensitive via a regex per term. */
458
+ content = /* @__PURE__ */ new Map();
459
+ /** Frontmatter `title:` per path, when present — searched together with the path. */
460
+ titles = /* @__PURE__ */ new Map();
435
461
  saving = false;
436
462
  _since = "";
463
+ /** When `since` last advanced from a completed catch-up or a watcher change (ms), null before the first. */
464
+ _lastSyncAt = null;
437
465
  persistPath;
438
466
  passphrase;
439
467
  constructor(persistPath, passphrase) {
@@ -496,14 +524,28 @@ var SearchIndex = class {
496
524
  this.saving = false;
497
525
  }
498
526
  }
499
- /** Add or update a note in the index. */
527
+ /**
528
+ * Add or update a note in the index. The watcher and the pre-search
529
+ * catch-up both write here without coordinating, so a write whose mtime is
530
+ * not newer than the one recorded for text already held is skipped: a
531
+ * stale copy can never replace a newer one. Mtimes loaded from disk carry
532
+ * no text, so the startup rebuild still fills them in.
533
+ */
500
534
  update(path, content, mtime) {
535
+ if (mtime !== void 0 && this.content.has(path) && mtime <= (this.mtimes.get(path) ?? -Infinity)) return;
501
536
  if (this.knownPaths.has(path)) {
502
537
  this.clearBacklinks(path);
503
538
  }
504
539
  this.knownPaths.add(path);
505
540
  if (mtime !== void 0) this.mtimes.set(path, mtime);
541
+ this.content.set(path, content);
506
542
  const parsed = parseFrontmatterAndLinks(content);
543
+ const title = parsed.frontmatter["title"];
544
+ if (typeof title === "string" && title.trim().length > 0) {
545
+ this.titles.set(path, title.trim());
546
+ } else {
547
+ this.titles.delete(path);
548
+ }
507
549
  if (parsed.tags.length > 0) {
508
550
  this.tags.set(path, parsed.tags);
509
551
  } else {
@@ -526,9 +568,67 @@ var SearchIndex = class {
526
568
  this.knownPaths.delete(path);
527
569
  this.mtimes.delete(path);
528
570
  this.tags.delete(path);
571
+ this.content.delete(path);
572
+ this.titles.delete(path);
529
573
  this.clearBacklinks(path);
530
574
  }
531
575
  }
576
+ /** Decrypted text of a note, or null if the index holds no content for it. */
577
+ getContent(path) {
578
+ return this.content.get(path) ?? null;
579
+ }
580
+ /** Notes whose text is in memory. Below `size` means search cannot see every note. */
581
+ get contentCount() {
582
+ return this.content.size;
583
+ }
584
+ /**
585
+ * Search over path + frontmatter title first, then the in-memory text.
586
+ * Ranked: name hits first, then number of distinct terms matched, then
587
+ * newest first, then path. `limit` defaults to 20.
588
+ */
589
+ search(q) {
590
+ const prefix = q.folder ? q.folder.endsWith("/") ? q.folder : q.folder + "/" : void 0;
591
+ const terms = (q.terms ?? []).filter((t) => t.length > 0).map((t) => ({
592
+ text: t.toLowerCase(),
593
+ // Case-insensitive (Unicode) search over the note text without a lowercased copy of the vault in memory.
594
+ re: new RegExp(t.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"), "iu")
595
+ }));
596
+ const hits = [];
597
+ for (const [path, entry] of this.content) {
598
+ if (!isValidNotePath(path)) continue;
599
+ if (prefix && !path.startsWith(prefix)) continue;
600
+ if (q.tag && !this.getTags(path).includes(q.tag)) continue;
601
+ const mtime = this.mtimes.get(path) ?? 0;
602
+ if (q.modifiedAfter !== void 0 && mtime < q.modifiedAfter) continue;
603
+ const title = this.titles.get(path);
604
+ const name = title ? `${path} ${title}` : path;
605
+ const nameLower = name.toLowerCase();
606
+ let matched = 0;
607
+ let nameHit = false;
608
+ let anchor = -1;
609
+ let anchorLen = 1;
610
+ {
611
+ for (const t of terms) {
612
+ const inName = nameLower.includes(t.text);
613
+ const i = entry.search(t.re);
614
+ if (!inName && i === -1) continue;
615
+ matched++;
616
+ if (inName) nameHit = true;
617
+ if (i !== -1 && (anchor === -1 || i < anchor)) {
618
+ anchor = i;
619
+ anchorLen = t.text.length;
620
+ }
621
+ }
622
+ if (matched === 0) continue;
623
+ }
624
+ const snippet = anchor === -1 ? "" : snippetAround(entry, anchor, anchorLen);
625
+ hits.push({ path, mtime, matched, nameHit, snippet });
626
+ }
627
+ hits.sort(
628
+ (a, b) => Number(b.nameHit) - Number(a.nameHit) || b.matched - a.matched || b.mtime - a.mtime || a.path.localeCompare(b.path)
629
+ );
630
+ return { hits: hits.slice(0, q.limit ?? 20), total: hits.length };
631
+ }
532
632
  /** Remove all backlink entries where path is the source. */
533
633
  clearBacklinks(path) {
534
634
  const oldLinks = this.links.get(path);
@@ -548,7 +648,7 @@ var SearchIndex = class {
548
648
  /** List all indexed paths with mtimes, optionally filtered by folder prefix. */
549
649
  listWithMtime(folder) {
550
650
  const prefix = folder && !folder.endsWith("/") ? folder + "/" : folder;
551
- const entries = [...this.knownPaths].filter((p) => p.endsWith(".md")).filter((p) => !prefix || p.startsWith(prefix)).map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));
651
+ const entries = [...this.knownPaths].filter(isValidNotePath).filter((p) => !prefix || p.startsWith(prefix)).map((p) => ({ path: p, mtime: this.mtimes.get(p) ?? 0 }));
552
652
  return entries.sort((a, b) => a.path.localeCompare(b.path));
553
653
  }
554
654
  /** Get mtime for a path. */
@@ -606,6 +706,12 @@ var SearchIndex = class {
606
706
  set since(value) {
607
707
  this._since = value;
608
708
  }
709
+ get lastSyncAt() {
710
+ return this._lastSyncAt;
711
+ }
712
+ set lastSyncAt(value) {
713
+ this._lastSyncAt = value;
714
+ }
609
715
  get size() {
610
716
  return this.knownPaths.size;
611
717
  }
@@ -764,11 +870,97 @@ function describeListing(s) {
764
870
  return line + describeIndexState(s.index);
765
871
  }
766
872
 
873
+ // src/search-format.ts
874
+ function resolveDisplayZone(raw) {
875
+ const zone = raw?.trim() || Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";
876
+ try {
877
+ new Intl.DateTimeFormat("en-US", { timeZone: zone });
878
+ return zone;
879
+ } catch {
880
+ console.warn(`DISPLAY_TIMEZONE "${zone}" is not a valid IANA time zone; using UTC.`);
881
+ return "UTC";
882
+ }
883
+ }
884
+ var DISPLAY_TIMEZONE = resolveDisplayZone(process.env.DISPLAY_TIMEZONE);
885
+ function formatServerTime(ms, timeZone = DISPLAY_TIMEZONE) {
886
+ const d = new Date(ms);
887
+ const parts = new Intl.DateTimeFormat("sv-SE", {
888
+ timeZone,
889
+ year: "numeric",
890
+ month: "2-digit",
891
+ day: "2-digit",
892
+ hour: "2-digit",
893
+ minute: "2-digit",
894
+ hourCycle: "h23",
895
+ timeZoneName: "short"
896
+ }).formatToParts(d);
897
+ const get = (type) => parts.find((p) => p.type === type)?.value ?? "";
898
+ const utc = d.toISOString().slice(11, 16);
899
+ return `${get("year")}-${get("month")}-${get("day")} ${get("hour")}:${get("minute")} ${get("timeZoneName")} (${utc}Z)`;
900
+ }
901
+ function seqPrefix(seq) {
902
+ if (!seq) return "none";
903
+ const dash = seq.indexOf("-");
904
+ return dash === -1 ? seq : seq.slice(0, dash);
905
+ }
906
+ function minutesBetween(from, to) {
907
+ return Math.max(0, Math.round((to - from) / 6e4));
908
+ }
909
+ function plural2(n, word) {
910
+ return `${n} ${word}${n === 1 ? "" : "s"}`;
911
+ }
912
+ function describeSync(s, timeZone = DISPLAY_TIMEZONE) {
913
+ const now = formatServerTime(s.now, timeZone);
914
+ const coverage = `${s.withContent} of ${plural2(s.notes, "note")} with content`;
915
+ if (s.mode === "local") {
916
+ return `Index: local vault, no sequence \u2014 ${now}; ${coverage}.`;
917
+ }
918
+ if (s.state === "building") {
919
+ return `Index: still building (${plural2(s.notes, "note")} so far), not caught up \u2014 ${now}; results may be incomplete.`;
920
+ }
921
+ if (s.state === "failed") {
922
+ return `Index: rebuild failed at startup (see server log), not caught up \u2014 ${now}; results may be incomplete or stale.`;
923
+ }
924
+ if (s.error) {
925
+ const last = s.syncedAt === null ? "never" : `${formatServerTime(s.syncedAt, timeZone)}, ${minutesBetween(s.syncedAt, s.now)} min ago`;
926
+ return `Index: catch-up failed (${s.error}); last caught up with CouchDB seq ${seqPrefix(s.seq)} \u2014 ${last}; results may be stale.`;
927
+ }
928
+ const age = s.syncedAt === null ? 0 : minutesBetween(s.syncedAt, s.now);
929
+ let line = `Index caught up with CouchDB seq ${seqPrefix(s.seq)} \u2014 ${now}, ${age} min; ${coverage}`;
930
+ if (s.unreadable > 0) {
931
+ line += `; ${plural2(s.unreadable, "document")} could not be read`;
932
+ }
933
+ return line + ".";
934
+ }
935
+ function describeQuery(terms) {
936
+ return terms.map((t) => `"${t}"`).join(", ");
937
+ }
938
+ function describeHits(hits, total, query, deepLink) {
939
+ if (total === 0) return `No notes match ${query}.`;
940
+ const shown = hits.length < total ? ` (showing ${hits.length}; narrow with folder, tag or modified_after)` : "";
941
+ const nameHits = hits.filter((h) => h.nameHit).length;
942
+ const byName = nameHits > 0 ? ` ${plural2(nameHits, "hit")} by path or title listed first.` : "";
943
+ const header = `${plural2(total, "note")} ${total === 1 ? "matches" : "match"} ${query}${shown}.${byName} Call read_note on a hit before relying on it.`;
944
+ const lines = hits.map((h) => {
945
+ const date = h.mtime ? new Date(h.mtime).toISOString().slice(0, 16) : "";
946
+ const context = h.nameHit ? h.snippet ? `[path/title] ${h.snippet}` : "[path/title match]" : h.snippet;
947
+ return `- ${date} [${h.path}](${deepLink(h.path)})
948
+ ${context}`;
949
+ });
950
+ return [header, ...lines].join("\n");
951
+ }
952
+
767
953
  // src/tools.ts
768
954
  var debugLogging = process.env.LOG_LEVEL === "debug";
955
+ var SEARCH_MAX_HITS = 20;
956
+ var SEARCH_MAX_TERMS = 20;
957
+ var SEARCH_MAX_TERM_LENGTH = 200;
958
+ function cleanSearchTerms(terms) {
959
+ return (terms ?? []).map((t) => t.trim().slice(0, SEARCH_MAX_TERM_LENGTH)).filter((t) => t.length > 0).slice(0, SEARCH_MAX_TERMS);
960
+ }
769
961
  var WRITE_TOOLS = ["write_note", "edit_note", "delete_note", "move_note"];
770
962
  var READ_NOTE_MAX_RESULT_SIZE_CHARS = 1e5;
771
- function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = false, writeFolders = null) {
963
+ function registerTools(server2, vault2, searchIndex2, vaultName, readOnly = false, writeFolders = null, syncBeforeSearch2) {
772
964
  if (readOnly) {
773
965
  console.log(`READ_ONLY mode: write tools disabled (${WRITE_TOOLS.join(", ")}).`);
774
966
  } else if (writeFolders) {
@@ -895,6 +1087,45 @@ ${content}`;
895
1087
  return [header, ...lines].join("\n");
896
1088
  }
897
1089
  });
1090
+ server2.addTool({
1091
+ name: "search_notes",
1092
+ description: "Search note contents for terms, case-insensitive.\nPaths and frontmatter titles are searched first and such hits rank on top, marked [path/title]; content hits follow. Returns paths with one context line each, never the note body: call read_note on a hit before relying on it. Give `terms` (a note matches when ANY term occurs \u2014 OR, so list synonyms, field names and other-language wordings; a term may contain spaces; ranked by how many terms match) Filters: folder, tag, modified_after. The first line of every response is the index status: the CouchDB sequence the index is caught up with after a catch-up run just before the search, the server time (local zone and UTC), its age in minutes, how many notes carry content, and any documents that could not be read.",
1093
+ parameters: z.object({
1094
+ terms: z.array(z.string().max(SEARCH_MAX_TERM_LENGTH)).max(SEARCH_MAX_TERMS).optional().describe(`Case-insensitive substrings, at most ${SEARCH_MAX_TERMS} of at most ${SEARCH_MAX_TERM_LENGTH} characters each; a note matches when any of them occurs. E.g. ['drag i kanban', 'kanban', 'labels p\xE5 kategori'].`),
1095
+ folder: z.string().optional().describe("Folder to search in, e.g. 'projects'. Omit for the whole vault."),
1096
+ tag: z.string().optional().describe("Only notes carrying this tag, e.g. 'project'."),
1097
+ modified_after: z.string().optional().describe("Only notes modified after this ISO date, e.g. '2026-03-25' or '2026-03-25T10:00'."),
1098
+ limit: z.coerce.number().optional().describe(`Max hits to return, default and maximum ${SEARCH_MAX_HITS}.`)
1099
+ }),
1100
+ execute: async ({ terms, folder, tag, modified_after, limit }) => {
1101
+ const cleanTerms = cleanSearchTerms(terms);
1102
+ if (cleanTerms.length === 0) {
1103
+ return "Give at least one term.";
1104
+ }
1105
+ let modifiedAfter;
1106
+ if (modified_after) {
1107
+ modifiedAfter = new Date(modified_after).getTime();
1108
+ if (isNaN(modifiedAfter)) return `Invalid date format: ${modified_after}. Use ISO format like '2026-03-25'.`;
1109
+ }
1110
+ const cap = Math.max(1, Math.min(SEARCH_MAX_HITS, limit ?? SEARCH_MAX_HITS));
1111
+ const sync = syncBeforeSearch2 ? await syncBeforeSearch2() : { unreadable: 0 };
1112
+ const status = {
1113
+ mode: syncBeforeSearch2 ? "couchdb" : "local",
1114
+ state: searchIndex2.state,
1115
+ seq: searchIndex2.since,
1116
+ syncedAt: searchIndex2.lastSyncAt,
1117
+ now: Date.now(),
1118
+ notes: searchIndex2.size,
1119
+ withContent: searchIndex2.contentCount,
1120
+ unreadable: sync.unreadable,
1121
+ error: sync.error
1122
+ };
1123
+ const { hits, total } = searchIndex2.search({ terms: cleanTerms, folder, tag, modifiedAfter, limit: cap });
1124
+ const query = describeQuery(cleanTerms);
1125
+ return `${describeSync(status)}
1126
+ ${describeHits(hits, total, query, (p) => makeDeepLink(vaultName, p))}`;
1127
+ }
1128
+ });
898
1129
  server2.addTool({
899
1130
  name: "list_folders",
900
1131
  description: "List all folders in the vault. Use this to discover folder names before writing or listing notes. Returns the folder tree with note counts.",
@@ -1144,7 +1375,7 @@ if (MCP_INSTRUCTIONS_FILE) {
1144
1375
  }
1145
1376
  var vault;
1146
1377
  if (VAULT_PATH) {
1147
- const { LocalVault } = await import("./vault-local-S53KTNRT.js");
1378
+ const { LocalVault } = await import("./vault-local-OURGENR5.js");
1148
1379
  vault = new LocalVault(VAULT_PATH);
1149
1380
  console.log(`Local mode: ${VAULT_PATH}`);
1150
1381
  } else if (COUCHDB_URL) {
@@ -1152,7 +1383,7 @@ if (VAULT_PATH) {
1152
1383
  console.error("COUCHDB_PASSWORD is required in remote mode.");
1153
1384
  process.exit(1);
1154
1385
  }
1155
- const { Vault } = await import("./vault-YGHHZZZQ.js");
1386
+ const { Vault } = await import("./vault-IAH37QM4.js");
1156
1387
  vault = new Vault({
1157
1388
  couchdbUrl: COUCHDB_URL,
1158
1389
  couchdbUser: COUCHDB_USER,
@@ -1183,38 +1414,45 @@ await searchIndex.loadFromDisk();
1183
1414
  if (debugLogging2) {
1184
1415
  console.log(`[debug] Persisted metadata: ${searchIndex.size} notes, since: ${searchIndex.since || "(none)"}`);
1185
1416
  }
1417
+ if (searchIndex.size > 0 && searchIndex.contentCount < searchIndex.size) {
1418
+ console.log(`Persisted metadata for ${searchIndex.size} notes has no text; re-reading note bodies from the start so search_notes covers every note (metadata stays serveable meanwhile).`);
1419
+ searchIndex.since = "0";
1420
+ }
1186
1421
  async function rebuildIndex() {
1187
1422
  const start = performance.now();
1188
1423
  if (COUCHDB_URL && vault.catchUp) {
1189
- const changeCallback = (path, content, mtime) => {
1190
- applyIndexChange(searchIndex, path, content, mtime);
1191
- };
1192
- let since = searchIndex.since || "0";
1424
+ const since = searchIndex.since || "0";
1193
1425
  if (debugLogging2) console.log(`[debug] CouchDB catch-up from since: ${since}`);
1194
1426
  let changes = 0;
1427
+ const preexisting = new Set(searchIndex.listPaths());
1428
+ const seen = /* @__PURE__ */ new Set();
1429
+ let fromZero = since === "0";
1195
1430
  const onBatch = async (batchSince, processed) => {
1196
1431
  searchIndex.since = batchSince;
1197
1432
  await searchIndex.saveToDisk();
1198
1433
  console.log(` checkpoint: ${processed} changes processed, ${searchIndex.size} notes indexed.`);
1199
1434
  };
1435
+ const countingCallback = (path, content, mtime) => {
1436
+ changes++;
1437
+ if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
1438
+ if (content !== null) seen.add(path);
1439
+ else seen.delete(path);
1440
+ applyIndexChange(searchIndex, path, content, mtime);
1441
+ };
1200
1442
  try {
1201
- const countingCallback = (path, content, mtime) => {
1202
- changes++;
1203
- if (debugLogging2) console.log(`[debug] Change: ${path} ${content !== null ? "(update)" : "(delete)"}`);
1204
- changeCallback(path, content, mtime);
1205
- };
1206
1443
  const newSince = await vault.catchUp(since, countingCallback, onBatch);
1207
1444
  searchIndex.since = newSince;
1445
+ searchIndex.lastSyncAt = Date.now();
1208
1446
  } catch (err) {
1209
- console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), rebuilding index from scratch...`);
1210
- searchIndex.clear();
1447
+ console.warn(`Catch-up failed (${describeError(err, debugLogging2)}), re-reading from the start...`);
1211
1448
  changes = 0;
1212
- const newSince = await vault.catchUp("0", (path, content, mtime) => {
1213
- changes++;
1214
- changeCallback(path, content, mtime);
1215
- }, onBatch);
1449
+ seen.clear();
1450
+ fromZero = true;
1451
+ const newSince = await vault.catchUp("0", countingCallback, onBatch);
1216
1452
  searchIndex.since = newSince;
1453
+ searchIndex.lastSyncAt = Date.now();
1217
1454
  }
1455
+ if (fromZero) pruneGhosts(searchIndex, preexisting, seen);
1218
1456
  if (changes > 0) {
1219
1457
  console.log(`Search index synced: ${changes} changes in ${((performance.now() - start) / 1e3).toFixed(1)}s (${searchIndex.size} notes).`);
1220
1458
  } else {
@@ -1247,6 +1485,30 @@ rebuildIndex().catch((err) => {
1247
1485
  searchIndex.state = "failed";
1248
1486
  console.error(`Index rebuild failed: ${describeError(err, debugLogging2)}`);
1249
1487
  });
1488
+ var syncChain = Promise.resolve();
1489
+ async function syncBeforeSearch() {
1490
+ if (!(COUCHDB_URL && vault.catchUp) || searchIndex.state !== "ready") return { unreadable: 0 };
1491
+ const run = async () => {
1492
+ const stats = { unreadable: 0 };
1493
+ try {
1494
+ const newSince = await vault.catchUp(
1495
+ searchIndex.since || "0",
1496
+ (path, content, mtime) => applyIndexChange(searchIndex, path, content, mtime),
1497
+ void 0,
1498
+ stats
1499
+ );
1500
+ searchIndex.since = newSince;
1501
+ searchIndex.lastSyncAt = Date.now();
1502
+ return { unreadable: stats.unreadable };
1503
+ } catch (err) {
1504
+ console.warn(`Pre-search catch-up failed: ${describeError(err, debugLogging2)}`);
1505
+ return { unreadable: stats.unreadable, error: "CouchDB sync error" };
1506
+ }
1507
+ };
1508
+ const result = syncChain.then(run, run);
1509
+ syncChain = result.catch(() => void 0);
1510
+ return result;
1511
+ }
1250
1512
  var fsWatcher = null;
1251
1513
  if (VAULT_PATH) {
1252
1514
  const pending = /* @__PURE__ */ new Map();
@@ -1276,14 +1538,17 @@ if (VAULT_PATH) {
1276
1538
  vault.watchChanges((path, content, mtime, seq) => {
1277
1539
  if (debugLogging2) console.log(`[debug] CouchDB ${content === null ? "delete" : "change"}: ${path}`);
1278
1540
  applyIndexChange(searchIndex, path, content, mtime);
1279
- if (seq) searchIndex.since = String(seq);
1541
+ if (seq) {
1542
+ searchIndex.since = String(seq);
1543
+ searchIndex.lastSyncAt = Date.now();
1544
+ }
1280
1545
  });
1281
1546
  console.log("Watching CouchDB for LiveSync changes.");
1282
1547
  }
1283
1548
  var BASE_INSTRUCTIONS = "Access and manage an Obsidian vault. You can read, write, list, search, move, and delete markdown notes. Every tool response includes an Obsidian deep link. Always show this link to the user using the format [obsidian://open?vault=...&file=...](obsidian://open?vault=...&file=...) so it is both clickable and visible as a URL.";
1284
1549
  var serverOptions = {
1285
1550
  name: "obsidian-sync-mcp",
1286
- version: "0.7.2",
1551
+ version: "0.8.0",
1287
1552
  instructions: MCP_EXTRA_INSTRUCTIONS ? `${BASE_INSTRUCTIONS}
1288
1553
 
1289
1554
  ${MCP_EXTRA_INSTRUCTIONS}` : BASE_INSTRUCTIONS
@@ -1328,7 +1593,7 @@ if (AUTH_TOKEN) {
1328
1593
  auth = mountPasswordAuth(server.getApp(), BASE_URL, AUTH_TOKEN, tokenPath);
1329
1594
  await auth.loadTokens();
1330
1595
  }
1331
- registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS);
1596
+ registerTools(server, vault, searchIndex, VAULT_NAME, READ_ONLY, WRITE_FOLDERS, COUCHDB_URL ? syncBeforeSearch : void 0);
1332
1597
  async function shutdown() {
1333
1598
  console.log("Shutting down...");
1334
1599
  if (fsWatcher) fsWatcher.close();
@@ -1350,7 +1615,7 @@ server.start({
1350
1615
  transportType: "httpStream",
1351
1616
  httpStream: { port: PORT, endpoint: "/mcp", host: process.env.HOST ?? "0.0.0.0" }
1352
1617
  });
1353
- console.log(`obsidian-sync-mcp v${"0.7.2"} listening on port ${PORT}`);
1618
+ console.log(`obsidian-sync-mcp v${"0.8.0"} listening on port ${PORT}`);
1354
1619
  process.on("unhandledRejection", (err) => {
1355
1620
  console.error(`Unhandled rejection: ${describeError(err, debugLogging2)}`);
1356
1621
  });