ofw-mcp 2.8.0 → 2.9.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/bundle.js CHANGED
@@ -38407,7 +38407,7 @@ async function loginWithPassword(username, password) {
38407
38407
  // package.json
38408
38408
  var package_default = {
38409
38409
  name: "ofw-mcp",
38410
- version: "2.8.0",
38410
+ version: "2.9.0",
38411
38411
  license: "MIT",
38412
38412
  mcpName: "io.github.chrischall/ofw-mcp",
38413
38413
  description: "OurFamilyWizard MCP server for Claude \u2014 developed and maintained by AI (Claude Code)",
@@ -38856,6 +38856,7 @@ async function resolveFolderIds(client2, store) {
38856
38856
  };
38857
38857
  await store.setMeta("drafts_folder_id", ids.drafts);
38858
38858
  await store.setMeta("sent_folder_id", ids.sent);
38859
+ await store.setMeta("inbox_folder_id", ids.inbox);
38859
38860
  return ids;
38860
38861
  }
38861
38862
  var ListItemSchema = external_exports.looseObject({
@@ -39249,6 +39250,9 @@ function getAllowMarkRead() {
39249
39250
  function getFetchUnreadBodies() {
39250
39251
  return parseBoolEnv("OFW_FETCH_UNREAD_BODIES");
39251
39252
  }
39253
+ function getAutoRefreshStaleReads() {
39254
+ return parseBoolEnv("OFW_AUTO_REFRESH");
39255
+ }
39252
39256
  function getDefaultInlineAttachments() {
39253
39257
  return parseBoolEnv("OFW_INLINE_ATTACHMENTS");
39254
39258
  }
@@ -39394,12 +39398,30 @@ var ServerDraftSchema = external_exports.looseObject({
39394
39398
  subject: external_exports.string().optional(),
39395
39399
  body: external_exports.string().optional(),
39396
39400
  replyToId: external_exports.number().nullable().optional(),
39397
- recipients: external_exports.array(ApiRecipientSchema).optional()
39401
+ recipients: external_exports.array(ApiRecipientSchema).optional(),
39402
+ // Read for the LIFECYCLE answer (see tools/lifecycle.ts): which folder OFW
39403
+ // itself says this id lives in right now. `existsOnServer` alone cannot
39404
+ // distinguish "still a draft" from "was sent" — a sent draft still exists.
39405
+ // `id` accepts BOTH spellings deliberately. This schema is parsed in
39406
+ // `mode: 'strict'` because it backs the destructive-draft guard, so a
39407
+ // present-but-mistyped field THROWS — and OFW is already inconsistent about
39408
+ // this exact field: the folders listing (`FoldersSchema` in sync.ts) types it
39409
+ // `z.string()`, while message detail has been observed returning a number.
39410
+ // Pinning one spelling here would turn a harmless representation change into
39411
+ // a hard failure of ofw_save_draft / ofw_delete_draft, which is the opposite
39412
+ // of what a strict boundary is for: it exists to stop us acting on a response
39413
+ // we cannot interpret, not to reject one we can. `folderId` is normalized to
39414
+ // a string below, so both spellings compare correctly downstream.
39415
+ folder: external_exports.looseObject({
39416
+ id: external_exports.union([external_exports.string(), external_exports.number()]).optional(),
39417
+ name: external_exports.string().optional()
39418
+ }).nullable().optional(),
39419
+ date: external_exports.looseObject({ dateTime: external_exports.string().optional() }).nullable().optional()
39398
39420
  });
39399
39421
  function isNotFound(e) {
39400
39422
  return e instanceof Error && /OFW API error: 404\b/.test(e.message);
39401
39423
  }
39402
- async function fetchServerDraft(client2, id) {
39424
+ async function fetchMessageSnapshot(client2, id) {
39403
39425
  let raw;
39404
39426
  try {
39405
39427
  raw = await client2.request("GET", `/pub/v3/messages/${id}`);
@@ -39416,12 +39438,20 @@ async function fetchServerDraft(client2, id) {
39416
39438
  mode: "strict"
39417
39439
  });
39418
39440
  return {
39419
- subject: detail.subject ?? "",
39420
- body: detail.body ?? "",
39421
- replyToId: detail.replyToId ?? null,
39422
- recipients: mapRecipients(detail.recipients)
39441
+ content: {
39442
+ subject: detail.subject ?? "",
39443
+ body: detail.body ?? "",
39444
+ replyToId: detail.replyToId ?? null,
39445
+ recipients: mapRecipients(detail.recipients)
39446
+ },
39447
+ folderId: detail.folder?.id === void 0 ? null : String(detail.folder.id),
39448
+ folderName: detail.folder?.name ?? null,
39449
+ dateTime: detail.date?.dateTime ?? null
39423
39450
  };
39424
39451
  }
39452
+ async function fetchServerDraft(client2, id) {
39453
+ return (await fetchMessageSnapshot(client2, id))?.content ?? null;
39454
+ }
39425
39455
  var SUBSTANTIVE_FIELDS = ["subject", "body", "recipients"];
39426
39456
  function substantiveChanges(changed) {
39427
39457
  return changed.filter((f) => SUBSTANTIVE_FIELDS.includes(f));
@@ -39505,6 +39535,171 @@ function staleDraftPayload(input) {
39505
39535
  };
39506
39536
  }
39507
39537
 
39538
+ // src/tools/lifecycle.ts
39539
+ var FOLDER_TYPE = {
39540
+ inbox: "INBOX",
39541
+ sent: "SENT_MESSAGES",
39542
+ drafts: "DRAFTS"
39543
+ };
39544
+ var FOLDER_ID_META_KEY = {
39545
+ inbox: "inbox_folder_id",
39546
+ sent: "sent_folder_id",
39547
+ drafts: "drafts_folder_id"
39548
+ };
39549
+ var FOLDERS = ["inbox", "sent", "drafts"];
39550
+ async function readFolderIdMap(store) {
39551
+ return {
39552
+ inbox: await store.getMeta(FOLDER_ID_META_KEY.inbox),
39553
+ sent: await store.getMeta(FOLDER_ID_META_KEY.sent),
39554
+ drafts: await store.getMeta(FOLDER_ID_META_KEY.drafts)
39555
+ };
39556
+ }
39557
+ async function persistFolderIds(store, systemFolders) {
39558
+ for (const folder of FOLDERS) {
39559
+ const entry = systemFolders.find((f) => f.folderType === FOLDER_TYPE[folder]);
39560
+ if (entry !== void 0) await store.setMeta(FOLDER_ID_META_KEY[folder], entry.id);
39561
+ }
39562
+ }
39563
+ async function ensureFolderIdMap(client2, store) {
39564
+ const cached2 = await readFolderIdMap(store);
39565
+ if (cached2.inbox !== null && cached2.sent !== null && cached2.drafts !== null) {
39566
+ return { map: cached2, requests: 0 };
39567
+ }
39568
+ try {
39569
+ const ids = await resolveFolderIds(client2, store);
39570
+ return { map: { inbox: ids.inbox, sent: ids.sent, drafts: ids.drafts }, requests: 1 };
39571
+ } catch {
39572
+ return { map: cached2, requests: 1 };
39573
+ }
39574
+ }
39575
+ function classifyState(snapshot, map2) {
39576
+ if (snapshot === null) return "deleted";
39577
+ const { folderId } = snapshot;
39578
+ if (folderId === null) return "unknown";
39579
+ if (map2.drafts !== null && folderId === map2.drafts) return "draft";
39580
+ if (map2.sent !== null && folderId === map2.sent) return "sent";
39581
+ if (map2.inbox !== null && folderId === map2.inbox) return "received";
39582
+ return "unknown";
39583
+ }
39584
+ function probeWouldStamp(cachedDraft, cachedMessage) {
39585
+ if (cachedDraft !== null) return false;
39586
+ if (cachedMessage === null) return true;
39587
+ if (cachedMessage.folder === "sent") return false;
39588
+ return !deriveRead(cachedMessage);
39589
+ }
39590
+ var SKIP_NOTE = 'Verifying this id requires fetching its detail from OurFamilyWizard, which would mark an unread inbox message as READ and stamp a co-parent-visible "First Viewed" time on the record. Ids already cached as drafts, as sent, or as already-read inbox messages are probed freely because none of those can stamp anything. Run ofw_sync_messages (it walks list pages, not bodies) or pass allowMarkRead:true.';
39591
+ function stateNote(state, cachedAsDraft, folderName) {
39592
+ if (state === "deleted") {
39593
+ return cachedAsDraft ? "This draft is in the local cache but NO LONGER EXISTS on OurFamilyWizard \u2014 it was sent or deleted elsewhere. Do not describe it as still unsent." : "Not found on OurFamilyWizard.";
39594
+ }
39595
+ if (state === "sent") {
39596
+ return cachedAsDraft ? "This id is cached as a DRAFT but OurFamilyWizard now has it in Sent \u2014 it was SENT (see sentAt). It is no longer a draft; saying it is still unsent would be false." : "This id is a sent message on OurFamilyWizard.";
39597
+ }
39598
+ if (state === "received") {
39599
+ return cachedAsDraft ? "This id is cached as a draft but OurFamilyWizard has it in the Inbox. Run ofw_sync_messages to reconcile." : "This id is an inbox message on OurFamilyWizard.";
39600
+ }
39601
+ if (state === "unknown") {
39602
+ return `OurFamilyWizard did not report a folder this tool can map${folderName === null ? "" : ` (it reported "${folderName}")`}, so what this id has become is NOT established. Treat it as unverified rather than assuming it is unchanged.`;
39603
+ }
39604
+ return void 0;
39605
+ }
39606
+ async function probeIds(client2, store, ids, opts) {
39607
+ const draftsById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
39608
+ const messagesById = new Map((await store.getMessages(ids)).map((m) => [m.id, m]));
39609
+ const prepared = ids.map((id) => {
39610
+ const cachedDraft = draftsById.get(id) ?? null;
39611
+ const cachedMessage = cachedDraft === null ? messagesById.get(id) ?? null : null;
39612
+ return {
39613
+ id,
39614
+ cachedDraft,
39615
+ cachedMessage,
39616
+ skip: !opts.allowMarkRead && probeWouldStamp(cachedDraft, cachedMessage)
39617
+ };
39618
+ });
39619
+ let requests = 0;
39620
+ let map2 = { inbox: null, sent: null, drafts: null };
39621
+ if (prepared.some((p) => !p.skip)) {
39622
+ const resolved = await ensureFolderIdMap(client2, store);
39623
+ map2 = resolved.map;
39624
+ requests += resolved.requests;
39625
+ }
39626
+ const keyById = new Map(
39627
+ (await store.getDraftLineageByIds(ids)).map((l) => [l.id, l.draftKey])
39628
+ );
39629
+ const items = [];
39630
+ for (const p of prepared) {
39631
+ if (p.skip) {
39632
+ items.push({ id: p.id, skipped: true, reason: "WOULD_MARK_READ", note: SKIP_NOTE });
39633
+ continue;
39634
+ }
39635
+ const probe = await probeOne(client2, p, map2, keyById.get(p.id) ?? null);
39636
+ requests += probe.requests;
39637
+ items.push(probe.item);
39638
+ }
39639
+ return { items, requests };
39640
+ }
39641
+ async function probeOne(client2, prepared, map2, draftKey) {
39642
+ const { id, cachedDraft } = prepared;
39643
+ let snapshot;
39644
+ try {
39645
+ snapshot = await fetchMessageSnapshot(client2, id);
39646
+ } catch (e) {
39647
+ return {
39648
+ requests: 1,
39649
+ item: {
39650
+ id,
39651
+ error: "FRESHNESS_CHECK_FAILED",
39652
+ message: e.message,
39653
+ inSync: null,
39654
+ note: "The freshness check itself failed, so nothing is confirmed either way."
39655
+ }
39656
+ };
39657
+ }
39658
+ const state = classifyState(snapshot, map2);
39659
+ const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft);
39660
+ const serverRevision = snapshot === null ? null : draftRevision(snapshot.content);
39661
+ const viewedAt = snapshot?.content.recipients.find((r) => r.viewedAt !== null)?.viewedAt ?? null;
39662
+ let inSync;
39663
+ if (cachedDraft === null) inSync = null;
39664
+ else if (snapshot === null) inSync = false;
39665
+ else if (cacheRevision !== serverRevision) inSync = false;
39666
+ else if (state === "draft") inSync = true;
39667
+ else if (state === "unknown") inSync = null;
39668
+ else inSync = false;
39669
+ const notes = [];
39670
+ const stateN = stateNote(state, cachedDraft !== null, snapshot?.folderName ?? null);
39671
+ if (stateN !== void 0) notes.push(stateN);
39672
+ if (snapshot !== null && cachedDraft === null) {
39673
+ notes.push("Not in the drafts cache, so there is no cached copy to compare its content against (inSync is null, not false).");
39674
+ } else if (snapshot !== null && cacheRevision !== serverRevision) {
39675
+ notes.push("Content differs from the cache \u2014 it was edited on OurFamilyWizard since the last sync. Run ofw_sync_messages before reading or writing it.");
39676
+ }
39677
+ return {
39678
+ requests: 1,
39679
+ item: {
39680
+ id,
39681
+ state,
39682
+ folder: snapshot?.folderName ?? null,
39683
+ sentAt: state === "sent" ? snapshot?.dateTime ?? null : null,
39684
+ viewedAt,
39685
+ existsOnServer: snapshot !== null,
39686
+ cacheRevision,
39687
+ serverRevision,
39688
+ inSync,
39689
+ ...draftKey !== null ? { draftKey } : {},
39690
+ ...notes.length > 0 ? { note: notes.join(" ") } : {}
39691
+ }
39692
+ };
39693
+ }
39694
+ async function resolveDraftKey(store, draftKey) {
39695
+ const chain = await store.getDraftLineage(draftKey);
39696
+ if (chain.length === 0) return null;
39697
+ return { currentId: chain[chain.length - 1].id, ids: chain.map((r) => r.id) };
39698
+ }
39699
+ function newDraftKey() {
39700
+ return `dk_${crypto.randomUUID()}`;
39701
+ }
39702
+
39508
39703
  // src/extract/inflate.ts
39509
39704
  var MAX_DECOMPRESSED_BYTES = 32 * 1024 * 1024;
39510
39705
  var DecompressionLimitError = class extends Error {
@@ -40547,7 +40742,10 @@ var MessageDetailSchema = external_exports.looseObject({
40547
40742
  // The detail payload carries its own owning folder ({id, name}). We read the
40548
40743
  // id to label a live-fetched message sent-vs-inbox instead of blindly
40549
40744
  // defaulting to inbox — see the folder derivation in ofw_get_message.
40550
- folder: external_exports.looseObject({ id: external_exports.number() }).optional()
40745
+ // Same union as ServerDraftSchema's, for the same reason — OFW types this id
40746
+ // as a string on the folders listing and a number on message detail. Lenient
40747
+ // here, so a mismatch only warns, but it would warn on EVERY live fetch.
40748
+ folder: external_exports.looseObject({ id: external_exports.union([external_exports.string(), external_exports.number()]) }).optional()
40551
40749
  });
40552
40750
  var DetailFilesSchema = external_exports.looseObject({ files: external_exports.array(external_exports.number()).optional() });
40553
40751
  var FolderCountsSchema = external_exports.looseObject({
@@ -40559,11 +40757,6 @@ var FolderCountsSchema = external_exports.looseObject({
40559
40757
  count: external_exports.number().optional()
40560
40758
  })).optional()
40561
40759
  });
40562
- var FOLDER_TYPE = {
40563
- inbox: "INBOX",
40564
- sent: "SENT_MESSAGES",
40565
- drafts: "DRAFTS"
40566
- };
40567
40760
  var MAX_FRESHNESS_IDS = 25;
40568
40761
  var UploadedFileSchema = external_exports.looseObject({
40569
40762
  fileId: external_exports.number(),
@@ -40586,6 +40779,37 @@ async function draftsFreshness(cache) {
40586
40779
  const cacheStatus = completed === "fresh" && freshness.staleness === "fresh" ? "fresh" : "unverified";
40587
40780
  return { freshness, serverConfirmed: cacheStatus === "fresh", cacheStatus };
40588
40781
  }
40782
+ var AUTO_REFRESH_DESC = 'If the result comes back EMPTY from a cache that is not verified-fresh, sync the backing folders first and answer from the refreshed cache instead of refusing. Defaults to the OFW_AUTO_REFRESH env var (false unless set), in which case the call refuses with result:"UNVERIFIED_EMPTY" and names the remedy. Costs OFW requests when it fires.';
40783
+ async function guardedCacheRead(o) {
40784
+ let value = await o.read();
40785
+ let refreshed = false;
40786
+ const unverifiable = (v) => o.isEmpty(v) && v.freshness.staleness !== "fresh";
40787
+ if (unverifiable(value) && o.autoRefresh) {
40788
+ await syncAll(o.client, {
40789
+ folders: o.folders,
40790
+ // Same ceiling ofw_sync_messages applies: an automatic refresh must never
40791
+ // stamp unread inbox messages as a side effect of a list read.
40792
+ fetchUnreadBodies: getAllowMarkRead() && getFetchUnreadBodies(),
40793
+ maxRequests: getSyncMaxRequests()
40794
+ }, o.cache);
40795
+ refreshed = true;
40796
+ value = await o.read();
40797
+ }
40798
+ return { value, refreshed, unverifiedEmpty: unverifiable(value) };
40799
+ }
40800
+ function unverifiedEmptyResponse(input) {
40801
+ const { freshness } = input;
40802
+ const age = freshness.ageSeconds === null ? "it has never been checked against OurFamilyWizard" : `it was last verified ${freshness.ageSeconds < 60 ? `${freshness.ageSeconds} sec` : `${Math.round(freshness.ageSeconds / 60)} min`} ago`;
40803
+ const refreshClause = input.refreshed ? " An automatic refresh ran on this call and did NOT make the result verifiable (the sync paused or skipped this folder), so the refusal stands." : "";
40804
+ return jsonErrorResponse({
40805
+ result: "UNVERIFIED_EMPTY",
40806
+ reason: `No ${input.what} were found, but the backing cache is "${freshness.staleness}" \u2014 ${age}. Refusing to report absence from unverified data: an empty result from a stale cache is indistinguishable from a verified "nothing there", and repeating it as one asserts a false negative about a legal record.${refreshClause}`,
40807
+ remedy: input.remedy,
40808
+ complete: false,
40809
+ freshness,
40810
+ ...input.extra
40811
+ });
40812
+ }
40589
40813
  function markReadVerdict(cached2, requested) {
40590
40814
  const ceiling = getAllowMarkRead();
40591
40815
  if (ceiling && (requested ?? true)) return null;
@@ -40613,15 +40837,16 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40613
40837
  return jsonResponse({ folders: data, freshness });
40614
40838
  });
40615
40839
  server.registerTool("ofw_list_messages", {
40616
- description: "List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based but if you know what you want (a date range, a topic), prefer the filters over walking pages \u2014 the cache may have 1000+ messages. Call ofw_sync_messages first if the cache is empty or stale.",
40617
- annotations: { readOnlyHint: true },
40840
+ description: 'List messages from the local OurFamilyWizard cache. Supports filtering by folder, date range, and a substring query on subject+body. Pagination is offset-based but if you know what you want (a date range, a topic), prefer the filters over walking pages \u2014 the cache may have 1000+ messages. Returns an explicit `complete` boolean describing the RESULT SET: true means "this is every message on OurFamilyWizard matching these filters as of freshness.asOf" \u2014 check it before asserting a count. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as an absence; pass autoRefresh:true to sync and answer instead.',
40841
+ annotations: { readOnlyHint: false },
40618
40842
  inputSchema: {
40619
40843
  folderId: external_exports.string().describe('Folder name: "inbox", "sent", or "both" (default "both")').optional(),
40620
40844
  page: external_exports.number().int().min(1).describe("Page number (default 1)").optional(),
40621
40845
  size: external_exports.number().int().min(1).describe("Messages per page (default 50)").optional(),
40622
40846
  since: external_exports.string().describe("ISO date or datetime \u2014 only messages with sent_at >= since (inclusive)").optional(),
40623
40847
  until: external_exports.string().describe("ISO date or datetime \u2014 only messages with sent_at < until (exclusive)").optional(),
40624
- q: external_exports.string().describe("Substring match on subject AND body (case-insensitive). Use to find messages on a specific topic.").optional()
40848
+ q: external_exports.string().describe("Substring match on subject AND body (case-insensitive). Use to find messages on a specific topic.").optional(),
40849
+ autoRefresh: external_exports.boolean().describe(AUTO_REFRESH_DESC).optional()
40625
40850
  }
40626
40851
  }, async (args) => {
40627
40852
  const page = args.page ?? 1;
@@ -40632,29 +40857,58 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40632
40857
  else if (folderArg === "sent") folder = "sent";
40633
40858
  else if (folderArg === "both") folder = void 0;
40634
40859
  else {
40635
- return jsonResponse({
40636
- messages: [],
40637
- freshness: await buildFreshness(cacheProvider(), {
40638
- source: "cache",
40639
- folders: ["inbox", "sent"]
40640
- }),
40641
- note: 'folderId must be "inbox", "sent", or "both". Numeric OFW folder IDs are not supported by the cache. No lookup was performed \u2014 this empty result says nothing about what is in the cache.'
40860
+ return jsonErrorResponse({
40861
+ result: "INVALID_FOLDER",
40862
+ reason: `folderId must be "inbox", "sent", or "both" (got ${JSON.stringify(folderArg)}). Numeric OFW folder IDs are not supported by the cache.`,
40863
+ remedy: "Re-call with folderId omitted (searches both) or set to one of the three accepted names.",
40864
+ complete: false,
40865
+ note: 'No lookup was performed. This says NOTHING about what is in the cache \u2014 do not read it as "no messages".'
40642
40866
  });
40643
40867
  }
40644
40868
  const cache = cacheProvider();
40869
+ const folders = folder === void 0 ? ["inbox", "sent"] : [folder];
40645
40870
  const filter = { folder, since: args.since, until: args.until, q: args.q };
40646
- const total = await cache.countMessages(filter);
40647
- const messages = (await cache.listMessages({ ...filter, page, size })).map((m) => withReadState(m));
40648
- const freshness = await buildFreshness(cache, {
40649
- source: "cache",
40650
- folders: folder === void 0 ? ["inbox", "sent"] : [folder]
40871
+ const { value, refreshed, unverifiedEmpty } = await guardedCacheRead({
40872
+ client: client2,
40873
+ cache,
40874
+ folders,
40875
+ autoRefresh: args.autoRefresh ?? getAutoRefreshStaleReads(),
40876
+ isEmpty: (v) => v.total === 0,
40877
+ read: async () => {
40878
+ const total2 = await cache.countMessages(filter);
40879
+ const messages2 = (await cache.listMessages({ ...filter, page, size })).map((m) => withReadState(m));
40880
+ const freshness2 = await buildFreshness(cache, { source: "cache", folders });
40881
+ return { messages: messages2, total: total2, freshness: freshness2 };
40882
+ }
40651
40883
  });
40652
- const payload = { messages, total, page, size, freshness };
40884
+ if (unverifiedEmpty) {
40885
+ return unverifiedEmptyResponse({
40886
+ what: "messages matching these filters",
40887
+ freshness: value.freshness,
40888
+ refreshed,
40889
+ remedy: `Call ofw_sync_messages(folders:${JSON.stringify(folders)}) and retry, or re-call this tool with autoRefresh:true. ofw_check_freshness is the cheap live alternative when you only need to confirm a specific message.`,
40890
+ extra: { page, size, filters: { folderId: folderArg, since: args.since, until: args.until, q: args.q } }
40891
+ });
40892
+ }
40893
+ const { messages, total, freshness } = value;
40894
+ const fullSlice = page === 1 && messages.length === total;
40895
+ const complete = fullSlice && freshness.staleness === "fresh" && freshness.historyComplete;
40896
+ const payload = { messages, total, page, size, complete, freshness };
40897
+ if (!complete) {
40898
+ payload.completeNote = [
40899
+ !fullSlice ? `this page holds ${messages.length} of ${total} matching cached messages` : null,
40900
+ freshness.staleness !== "fresh" ? `the cache is "${freshness.staleness}", so newer messages may exist on OurFamilyWizard` : null,
40901
+ !freshness.historyComplete ? "older history is still being backfilled, so the cache does not yet hold every message" : null
40902
+ ].filter((r) => r !== null).join("; ").concat(". Do not state a total or an absence from this result without resolving that first.");
40903
+ }
40653
40904
  if (total === 0) {
40654
- payload.note = "No messages match these filters. If you expected results, check ofw_sync_messages was run, or relax the filters.";
40905
+ payload.note = 'No messages match these filters, and the cache IS verified-fresh for these folders \u2014 so this is a real "nothing matched", not a stale-cache artefact. If you expected results, relax the filters.';
40655
40906
  } else if (page * size < total) {
40656
40907
  payload.note = `Showing ${(page - 1) * size + 1}\u2013${(page - 1) * size + messages.length} of ${total}. Increase 'page' to see more, or narrow with since/until/q.`;
40657
40908
  }
40909
+ if (refreshed) {
40910
+ payload.autoRefreshed = true;
40911
+ }
40658
40912
  return jsonResponse(payload);
40659
40913
  });
40660
40914
  server.registerTool("ofw_get_message", {
@@ -40689,6 +40943,11 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40689
40943
  // Concurrency token — pass as expectedRevision to ofw_save_draft /
40690
40944
  // ofw_delete_draft to assert you are editing THIS version.
40691
40945
  revision: draftRevision(draftRow),
40946
+ // Stable logical identity. Survives the create-then-delete id churn of
40947
+ // editing AND the transition to sent — pass it to ofw_status to ask
40948
+ // "what happened to the thing I was working on?". Null when this draft
40949
+ // was never written through this tool (e.g. authored in the web app).
40950
+ draftKey: (await cache.getDraftLineageById(draftRow.id))?.draftKey ?? null,
40692
40951
  cacheStatus,
40693
40952
  // False = this draft's existence and unsent status are remembered from
40694
40953
  // a cache, not confirmed on OFW. Call ofw_check_freshness before
@@ -40844,6 +41103,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40844
41103
  }, SentDetailSchema, "ofw_send_message");
40845
41104
  let persisted = null;
40846
41105
  let verifyNote = null;
41106
+ let sentDraftKey = null;
40847
41107
  if (newId !== null) {
40848
41108
  verifyNote = verifyWriteLanded("message", { subject, body }, detail);
40849
41109
  persisted = {
@@ -40860,6 +41120,16 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40860
41120
  listData: detail
40861
41121
  };
40862
41122
  await cache.upsertMessage(persisted);
41123
+ if (draftRef !== void 0) {
41124
+ const prior = await cache.getDraftLineageById(draftRef);
41125
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41126
+ const key = prior?.draftKey ?? newDraftKey();
41127
+ if (prior === null) {
41128
+ await cache.recordDraftLineage({ id: draftRef, draftKey: key, previousId: null, recordedAt: now });
41129
+ }
41130
+ await cache.recordDraftLineage({ id: newId, draftKey: key, previousId: draftRef, recordedAt: now });
41131
+ sentDraftKey = key;
41132
+ }
40863
41133
  for (const fileId of myFileIDs) {
40864
41134
  const existing = await cache.getAttachment(fileId);
40865
41135
  await cache.upsertAttachmentForMessage({
@@ -40881,7 +41151,7 @@ function registerMessageTools(server, client2, cacheProvider, attachmentIO) {
40881
41151
  await deleteOFWMessages(client2, [draftRef]);
40882
41152
  await cache.deleteDraft(draftRef);
40883
41153
  }
40884
- const responseObj = persisted ?? raw;
41154
+ const responseObj = persisted === null ? raw : { ...persisted, ...sentDraftKey !== null ? { draftKey: sentDraftKey, previousId: draftRef } : {} };
40885
41155
  const text = responseObj ? JSON.stringify(responseObj, null, 2) : "Message sent successfully.";
40886
41156
  const notes = [rewriteNote, verifyNote, unconfirmedNote].filter((n) => n !== null).join("\n\n");
40887
41157
  return textResponse(notes ? `${notes}
@@ -40946,35 +41216,65 @@ ${JSON.stringify(
40946
41216
  };
40947
41217
  }
40948
41218
  server.registerTool("ofw_list_drafts", {
40949
- description: "List draft messages from the local OurFamilyWizard cache. Call ofw_sync_messages first if the cache is empty.",
40950
- annotations: { readOnlyHint: true },
41219
+ description: 'List draft messages from the local OurFamilyWizard cache. Returns an explicit `complete` boolean describing the RESULT SET: true means "these are ALL the drafts on OurFamilyWizard as of freshness.asOf" \u2014 check it before saying "you have N drafts". Each draft carries its `draftKey` (stable across the create-then-delete churn of editing) when one is known. An empty result from a cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY"); pass autoRefresh:true to sync and answer instead. For a live, one-call answer prefer ofw_status(includeDraftInventory:true).',
41220
+ annotations: { readOnlyHint: false },
40951
41221
  inputSchema: {
40952
41222
  page: external_exports.number().int().min(1).describe("Page number (default 1)").optional(),
40953
- size: external_exports.number().int().min(1).describe("Drafts per page (default 50)").optional()
41223
+ size: external_exports.number().int().min(1).describe("Drafts per page (default 50)").optional(),
41224
+ autoRefresh: external_exports.boolean().describe(AUTO_REFRESH_DESC).optional()
40954
41225
  }
40955
41226
  }, async (args) => {
40956
41227
  const page = args.page ?? 1;
40957
41228
  const size = args.size ?? 50;
40958
41229
  const cache = cacheProvider();
40959
- const { freshness, serverConfirmed, cacheStatus } = await draftsFreshness(cache);
40960
- const rows = await cache.listDrafts({ page, size });
40961
- const drafts = rows.map((d) => ({
40962
- ...d,
40963
- revision: draftRevision(d),
40964
- cacheStatus,
40965
- serverConfirmed,
40966
- asOf: freshness.asOf
40967
- }));
40968
- if (drafts.length === 0) {
40969
- return jsonResponse({
40970
- drafts: [],
40971
- freshness,
40972
- note: "No drafts in the local cache. That is NOT proof there are no drafts on OurFamilyWizard \u2014 call ofw_sync_messages to populate, or ofw_check_freshness to confirm."
41230
+ const { value, refreshed, unverifiedEmpty } = await guardedCacheRead({
41231
+ client: client2,
41232
+ cache,
41233
+ folders: ["drafts"],
41234
+ autoRefresh: args.autoRefresh ?? getAutoRefreshStaleReads(),
41235
+ isEmpty: (v) => v.total === 0,
41236
+ read: async () => {
41237
+ const { freshness: freshness2, serverConfirmed: serverConfirmed2, cacheStatus } = await draftsFreshness(cache);
41238
+ const rows = await cache.listDrafts({ page, size });
41239
+ const total2 = await cache.countDrafts();
41240
+ const keyById = new Map(
41241
+ (await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey])
41242
+ );
41243
+ const drafts2 = rows.map((d) => ({
41244
+ ...d,
41245
+ revision: draftRevision(d),
41246
+ draftKey: keyById.get(d.id) ?? null,
41247
+ cacheStatus,
41248
+ serverConfirmed: serverConfirmed2,
41249
+ asOf: freshness2.asOf
41250
+ }));
41251
+ return { drafts: drafts2, total: total2, freshness: freshness2, serverConfirmed: serverConfirmed2 };
41252
+ }
41253
+ });
41254
+ if (unverifiedEmpty) {
41255
+ return unverifiedEmptyResponse({
41256
+ what: "drafts",
41257
+ freshness: value.freshness,
41258
+ refreshed,
41259
+ remedy: 'Call ofw_sync_messages(folders:["drafts"]) and retry, re-call with autoRefresh:true, or use ofw_status(includeDraftInventory:true) for a single live answer.',
41260
+ extra: { page, size }
40973
41261
  });
40974
41262
  }
40975
- const payload = { drafts, freshness };
41263
+ const { drafts, total, freshness, serverConfirmed } = value;
41264
+ const fullSlice = page === 1 && drafts.length === total;
41265
+ const complete = serverConfirmed && fullSlice;
41266
+ const payload = { drafts, total, page, size, complete, freshness };
41267
+ if (!complete) {
41268
+ payload.completeNote = [
41269
+ !fullSlice ? `this page holds ${drafts.length} of ${total} cached drafts` : null,
41270
+ !serverConfirmed ? "the drafts cache has not been confirmed against OurFamilyWizard inside the freshness window" : null
41271
+ ].filter((r) => r !== null).join("; ").concat(". Do NOT state a draft count from this result \u2014 call ofw_status(includeDraftInventory:true) for a live, complete one.");
41272
+ }
40976
41273
  if (!serverConfirmed) {
40977
- payload.note = 'serverConfirmed:false \u2014 these drafts are remembered from the local cache, NOT confirmed to still exist unsent on OurFamilyWizard right now, and their bodies may be behind the server. Do not state that a draft "is still sitting unsent" on this basis; drafts edited or deleted in the OFW web app bump no timestamp, so the cache cannot detect it on its own. Call ofw_check_freshness (cheap, live) or ofw_sync_messages first. Writes are guarded regardless \u2014 ofw_save_draft and ofw_delete_draft re-check the server and refuse a stale overwrite.';
41274
+ payload.note = 'serverConfirmed:false \u2014 these drafts are remembered from the local cache, NOT confirmed to still exist unsent on OurFamilyWizard right now, and their bodies may be behind the server. Do not state that a draft "is still sitting unsent" on this basis; drafts edited, deleted or SENT in the OFW web app bump no timestamp, so the cache cannot detect it on its own. Call ofw_status / ofw_check_freshness (cheap, live) or ofw_sync_messages first. Writes are guarded regardless \u2014 ofw_save_draft and ofw_delete_draft re-check the server and refuse a stale overwrite.';
41275
+ }
41276
+ if (refreshed) {
41277
+ payload.autoRefreshed = true;
40978
41278
  }
40979
41279
  return jsonResponse(payload);
40980
41280
  });
@@ -41034,6 +41334,7 @@ ${JSON.stringify(
41034
41334
  let replaceNote = null;
41035
41335
  let verifyNote = null;
41036
41336
  let newRevision = null;
41337
+ let draftKey = null;
41037
41338
  const warnings = [];
41038
41339
  if (newId !== null) {
41039
41340
  verifyNote = verifyWriteLanded("draft", { subject: args.subject, body: args.body }, detail);
@@ -41050,6 +41351,29 @@ ${JSON.stringify(
41050
41351
  };
41051
41352
  await cache.upsertDraft(persisted);
41052
41353
  newRevision = draftRevision(persisted);
41354
+ const now = (/* @__PURE__ */ new Date()).toISOString();
41355
+ if (args.messageId !== void 0) {
41356
+ const prior = await cache.getDraftLineageById(args.messageId);
41357
+ if (prior !== null) {
41358
+ draftKey = prior.draftKey;
41359
+ } else {
41360
+ draftKey = newDraftKey();
41361
+ await cache.recordDraftLineage({
41362
+ id: args.messageId,
41363
+ draftKey,
41364
+ previousId: null,
41365
+ recordedAt: now
41366
+ });
41367
+ }
41368
+ } else {
41369
+ draftKey = newDraftKey();
41370
+ }
41371
+ await cache.recordDraftLineage({
41372
+ id: newId,
41373
+ draftKey,
41374
+ previousId: args.messageId ?? null,
41375
+ recordedAt: now
41376
+ });
41053
41377
  if (resolvedReplyTo !== null && effectiveReplyTo !== resolvedReplyTo) {
41054
41378
  const rewrittenFrom = requestedReplyTo !== resolvedReplyTo ? ` (rewritten from ${requestedReplyTo})` : "";
41055
41379
  const outcome = effectiveReplyTo === null ? "OurFamilyWizard did not thread this draft (its inReplyTo/showContext will be empty). The subject and body were saved; only the reply linkage was dropped." : `OurFamilyWizard re-targeted the reply to message ${effectiveReplyTo} instead. The draft IS threaded \u2014 to that message, not the one requested \u2014 and the inReplyTo in this response reflects where it actually landed.`;
@@ -41089,6 +41413,11 @@ ${JSON.stringify(
41089
41413
  ...persisted,
41090
41414
  inReplyTo: persisted.replyToId,
41091
41415
  revision: newRevision,
41416
+ // The id above is volatile — it changes on every edit. `draftKey` is
41417
+ // not: pass it to ofw_status to resolve the chain's CURRENT id, or to
41418
+ // find out that the draft was sent and when.
41419
+ draftKey,
41420
+ previousId: args.messageId ?? null,
41092
41421
  cacheStatus: "fresh",
41093
41422
  serverConfirmed: true,
41094
41423
  ...warnings.length > 0 ? { warnings } : {}
@@ -41126,25 +41455,46 @@ ${text}` : text);
41126
41455
  ${text}` : text);
41127
41456
  });
41128
41457
  server.registerTool("ofw_get_unread_sent", {
41129
- description: "List sent messages that have not been read by one or more recipients. Reads from local cache; call ofw_sync_messages first if cache is stale.",
41130
- annotations: { readOnlyHint: true },
41458
+ description: 'List sent messages that have not been read by one or more recipients. Reads from local cache. Returns `complete` describing whether every sent message was scanned. An empty SENT cache that is not verified-fresh is REFUSED (result:"UNVERIFIED_EMPTY") rather than reported as "nothing sent"; pass autoRefresh:true to sync and answer instead.',
41459
+ annotations: { readOnlyHint: false },
41131
41460
  inputSchema: {
41132
41461
  page: external_exports.number().int().min(1).describe("Page (default 1)").optional(),
41133
- size: external_exports.number().int().min(1).describe("Per page (default 50)").optional()
41462
+ size: external_exports.number().int().min(1).describe("Per page (default 50)").optional(),
41463
+ autoRefresh: external_exports.boolean().describe(AUTO_REFRESH_DESC).optional()
41134
41464
  }
41135
41465
  }, async (args) => {
41136
41466
  const page = args.page ?? 1;
41137
41467
  const size = args.size ?? 50;
41138
41468
  const cache = cacheProvider();
41139
- const sent = await cache.listMessages({ folder: "sent", page, size });
41140
- const freshness = await buildFreshness(cache, { source: "cache", folders: ["sent"] });
41141
- if (sent.length === 0) {
41142
- return jsonResponse({
41143
- unread: [],
41144
- freshness,
41145
- note: "Sent cache is empty. Call ofw_sync_messages to populate. An empty cache is NOT evidence that no sent messages exist."
41469
+ const { value, refreshed, unverifiedEmpty } = await guardedCacheRead({
41470
+ client: client2,
41471
+ cache,
41472
+ folders: ["sent"],
41473
+ autoRefresh: args.autoRefresh ?? getAutoRefreshStaleReads(),
41474
+ // The guard is about the CACHE being empty, not the verdict. "You have
41475
+ // no sent messages" is an absence claim a stale cache cannot support;
41476
+ // "all of them are read" is a verdict over messages we did see, and it is
41477
+ // labelled by `freshness` and `complete` as before.
41478
+ isEmpty: (v) => v.total === 0,
41479
+ read: async () => {
41480
+ const sent2 = await cache.listMessages({ folder: "sent", page, size });
41481
+ const total2 = await cache.countMessages({ folder: "sent" });
41482
+ const freshness2 = await buildFreshness(cache, { source: "cache", folders: ["sent"] });
41483
+ return { sent: sent2, total: total2, freshness: freshness2 };
41484
+ }
41485
+ });
41486
+ if (unverifiedEmpty) {
41487
+ return unverifiedEmptyResponse({
41488
+ what: "sent messages in the local cache",
41489
+ freshness: value.freshness,
41490
+ refreshed,
41491
+ remedy: 'Call ofw_sync_messages(folders:["sent"]) and retry, or re-call with autoRefresh:true.',
41492
+ extra: { page, size }
41146
41493
  });
41147
41494
  }
41495
+ const { sent, total, freshness } = value;
41496
+ const fullSlice = page === 1 && sent.length === total;
41497
+ const complete = fullSlice && freshness.staleness === "fresh" && freshness.historyComplete;
41148
41498
  const unread = [];
41149
41499
  for (const msg of sent) {
41150
41500
  const unreadBy = msg.recipients.filter((r) => r.viewedAt === null).map((r) => r.name);
@@ -41152,14 +41502,17 @@ ${text}` : text);
41152
41502
  unread.push({ id: msg.id, subject: msg.subject, sentAt: msg.sentAt, unreadBy });
41153
41503
  }
41154
41504
  }
41505
+ const payload = { unread, scanned: sent.length, total, complete, freshness };
41506
+ if (!complete) {
41507
+ payload.completeNote = `This verdict covers the ${sent.length} of ${total} cached sent messages on this page${freshness.staleness === "fresh" ? "" : `, from a cache that is "${freshness.staleness}"`}. It is not a statement about every message you have sent.`;
41508
+ }
41155
41509
  if (unread.length === 0) {
41156
- return jsonResponse({
41157
- unread: [],
41158
- freshness,
41159
- message: "All scanned sent messages had been read as of the timestamp in `freshness.asOf`. A recipient may have read a message since without the cache hearing about it."
41160
- });
41510
+ payload.message = "Every sent message scanned had been read as of the timestamp in `freshness.asOf`. A recipient may have read \u2014 or not read \u2014 a message since without the cache hearing about it.";
41511
+ }
41512
+ if (refreshed) {
41513
+ payload.autoRefreshed = true;
41161
41514
  }
41162
- return jsonResponse({ unread, freshness });
41515
+ return jsonResponse(payload);
41163
41516
  });
41164
41517
  if (allowDrafts) server.registerTool("ofw_upload_attachment", {
41165
41518
  description: `Upload a local file to OurFamilyWizard's "My Files" so it can be attached to a message. Returns the fileId \u2014 pass that to ofw_send_message or ofw_save_draft in myFileIDs to attach it. The file is uploaded as PRIVATE (visible only to you) by default; pass shareClass:"SHARED" to share with co-parents directly via the My Files area.`,
@@ -41316,12 +41669,12 @@ ${text}` : text);
41316
41669
  return jsonResponse({ ...result, freshness });
41317
41670
  });
41318
41671
  server.registerTool("ofw_check_freshness", {
41319
- description: 'Cheaply confirm whether the local cache still matches OurFamilyWizard, WITHOUT running a full sync. Use this before asserting anything about current state \u2014 especially "draft X is still sitting unsent" \u2014 when a read returned serverConfirmed:false or freshness.staleness other than "fresh". Costs one OFW request for the folder check plus one per messageId. For each folder it returns the live server count next to the cached count; for each id, whether it still exists on OFW and whether its content matches the cache (compared by content revision, because OFW draft timestamps do NOT change when a draft is edited in the web app). Does not fetch bodies into the cache, does not touch attachments, and does not depend on sync state.',
41320
- annotations: { readOnlyHint: true },
41672
+ description: 'Cheaply confirm whether the local cache still matches OurFamilyWizard, WITHOUT running a full sync. Use this before asserting anything about current state \u2014 especially "draft X is still sitting unsent". Costs one OFW request for the folder check plus one per messageId. For each folder it returns the live server count next to the cached count. For each id it returns a LIVE lifecycle `state` \u2014 "draft" | "sent" | "received" | "deleted" | "unknown" \u2014 alongside `folder`, `sentAt`, `existsOnServer` and a content comparison. `state` is the field that answers "is this still a draft?": a draft that has been SENT still exists on the server, so existsOnServer:true never distinguished the two. A cached draft whose state is no longer "draft" reports inSync:false even when its text is byte-identical. Content is compared by revision hash, because OFW draft timestamps do NOT change when a draft is edited in the web app. Does not fetch bodies into the cache, does not touch attachments, and does not depend on sync state. For draftKeys, or a full live draft inventory, use ofw_status.',
41673
+ annotations: { readOnlyHint: false },
41321
41674
  inputSchema: {
41322
41675
  folders: external_exports.array(external_exports.enum(["inbox", "sent", "drafts"])).min(1).describe("Folders to compare cached vs live counts for. Defaults to all three when messageIds is not given. Must be non-empty if given.").optional(),
41323
- messageIds: external_exports.array(external_exports.number()).describe(`Specific ids to verify against OFW (max ${MAX_FRESHNESS_IDS}). By default only ids present in the drafts cache are probed \u2014 see allowMarkRead.`).optional(),
41324
- allowMarkRead: external_exports.boolean().describe("Default false. Probing an id that is NOT a cached draft requires fetching its detail, which marks an unread inbox message as READ on OurFamilyWizard \u2014 an irreversible change to the record. Such ids are skipped unless you set this to true.").optional()
41676
+ messageIds: external_exports.array(external_exports.number()).describe(`Specific ids to verify against OFW (max ${MAX_FRESHNESS_IDS}). Ids cached as drafts, as sent messages, or as already-read inbox messages are probed freely \u2014 none of those can stamp the record. Anything else is skipped \u2014 see allowMarkRead.`).optional(),
41677
+ allowMarkRead: external_exports.boolean().describe('Default false. Probing an id whose cached state cannot rule out an unread INBOX message requires fetching its detail, which marks it READ on OurFamilyWizard and stamps a co-parent-visible "First Viewed" time \u2014 irreversible. Such ids are skipped (reason:"WOULD_MARK_READ") unless you set this to true. The server-wide OFW_ALLOW_MARK_READ=false is a ceiling this cannot raise.').optional()
41325
41678
  }
41326
41679
  }, async (args) => {
41327
41680
  const cache = cacheProvider();
@@ -41339,6 +41692,7 @@ ${text}` : text);
41339
41692
  { label: "ofw-mcp", context: "GET /pub/v1/messageFolders (ofw_check_freshness)" }
41340
41693
  );
41341
41694
  const sys = data.systemFolders ?? [];
41695
+ await persistFolderIds(cache, sys);
41342
41696
  for (const folder of wantFolders) {
41343
41697
  const entry = sys.find((x) => x.folderType === FOLDER_TYPE[folder]);
41344
41698
  const serverCount = entry?.totalCount ?? entry?.messageCount ?? entry?.count ?? null;
@@ -41359,52 +41713,9 @@ ${text}` : text);
41359
41713
  });
41360
41714
  }
41361
41715
  }
41362
- const items = [];
41363
- for (const id of ids) {
41364
- const cachedDraft = await cache.getDraft(id);
41365
- if (cachedDraft === null && !allowMarkRead) {
41366
- items.push({
41367
- id,
41368
- skipped: true,
41369
- reason: "NOT_A_CACHED_DRAFT",
41370
- note: "Not in the drafts cache. Verifying it requires fetching its detail from OFW, which would mark an unread inbox message as READ on OurFamilyWizard. Pass allowMarkRead:true if that is acceptable."
41371
- });
41372
- continue;
41373
- }
41374
- requestsUsed++;
41375
- try {
41376
- const server2 = await fetchServerDraft(client2, id);
41377
- const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft);
41378
- if (server2 === null) {
41379
- items.push({
41380
- id,
41381
- existsOnServer: false,
41382
- inSync: false,
41383
- cacheRevision,
41384
- serverRevision: null,
41385
- note: cachedDraft === null ? "Not found on OurFamilyWizard." : "This draft is in the local cache but NO LONGER EXISTS on OurFamilyWizard \u2014 it was sent or deleted elsewhere. Do not describe it as still unsent."
41386
- });
41387
- continue;
41388
- }
41389
- const serverRevision = draftRevision(server2);
41390
- items.push({
41391
- id,
41392
- existsOnServer: true,
41393
- cacheRevision,
41394
- serverRevision,
41395
- inSync: cacheRevision !== null && cacheRevision === serverRevision,
41396
- ...cacheRevision === null ? { note: "Exists on OurFamilyWizard but is not in the local cache." } : cacheRevision !== serverRevision ? { note: "Content differs from the cache \u2014 it was edited on OurFamilyWizard since the last sync. Run ofw_sync_messages before reading or writing it." } : {}
41397
- });
41398
- } catch (e) {
41399
- items.push({
41400
- id,
41401
- error: "FRESHNESS_CHECK_FAILED",
41402
- message: e.message,
41403
- inSync: null,
41404
- note: "The freshness check itself failed, so nothing is confirmed either way."
41405
- });
41406
- }
41407
- }
41716
+ const probed = await probeIds(client2, cache, ids, { allowMarkRead });
41717
+ requestsUsed += probed.requests;
41718
+ const items = probed.items;
41408
41719
  const payload = {
41409
41720
  checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
41410
41721
  requestsUsed,
@@ -41416,6 +41727,132 @@ ${text}` : text);
41416
41727
  }
41417
41728
  return jsonResponse(payload);
41418
41729
  });
41730
+ server.registerTool("ofw_status", {
41731
+ description: 'ONE live call that answers "where does everything stand?". This is the call that should back any status summary about drafts or specific messages \u2014 never session memory, and never a cached read alone. With no arguments it returns the FULL current draft inventory, verified against OurFamilyWizard. Pass ids and/or draftKeys to get each one\'s live lifecycle `state` ("draft" | "sent" | "received" | "deleted" | "unknown") with `sentAt` and `viewedAt`. A draftKey is the stable identity ofw_save_draft returns: editing a draft mints a new OFW id every time (create-then-delete), so the key is the only way to ask "what happened to the thing I was working on?" \u2014 it resolves to the chain\'s current id and keeps resolving after the draft is SENT (state:"sent" with sentMessageId). The top-level `complete` is true ONLY when every part of this snapshot was verified live; if it is false, do not state a draft count or a lifecycle claim from this payload.',
41732
+ annotations: { readOnlyHint: false },
41733
+ inputSchema: {
41734
+ ids: external_exports.array(external_exports.number()).describe(`Message/draft ids to resolve to a live state (combined with draftKeys, max ${MAX_FRESHNESS_IDS} probes per call).`).optional(),
41735
+ draftKeys: external_exports.array(external_exports.string()).describe("Stable draft keys (from ofw_save_draft / ofw_list_drafts) to resolve to their CURRENT id and state.").optional(),
41736
+ includeDraftInventory: external_exports.boolean().describe("Return the full current draft list, verified against OurFamilyWizard first. Defaults to TRUE when neither ids nor draftKeys is given (so a bare ofw_status() is a complete status snapshot), otherwise false.").optional(),
41737
+ allowMarkRead: external_exports.boolean().describe("Default false. An id whose cached state cannot rule out an unread INBOX message can only be probed by fetching its detail, which marks it READ on OurFamilyWizard \u2014 irreversible and co-parent-visible. Those are skipped unless this is true. Cached drafts, sent messages and already-read messages are always probed. Capped by OFW_ALLOW_MARK_READ.").optional()
41738
+ }
41739
+ }, async (args) => {
41740
+ const cache = cacheProvider();
41741
+ const allowMarkRead = getAllowMarkRead() && (args.allowMarkRead ?? false);
41742
+ const requestedIds = args.ids ?? [];
41743
+ const requestedKeys = args.draftKeys ?? [];
41744
+ const wantInventory = args.includeDraftInventory ?? (requestedIds.length === 0 && requestedKeys.length === 0);
41745
+ const allTargets = [
41746
+ ...requestedIds.map((id) => ({ kind: "id", id })),
41747
+ ...requestedKeys.map((draftKey) => ({ kind: "draftKey", draftKey }))
41748
+ ];
41749
+ const targets = allTargets.slice(0, MAX_FRESHNESS_IDS);
41750
+ const truncated = allTargets.length - targets.length;
41751
+ if (!wantInventory && targets.length === 0) {
41752
+ return jsonErrorResponse({
41753
+ result: "NOTHING_REQUESTED",
41754
+ reason: "ofw_status was called with includeDraftInventory:false and no ids or draftKeys, so nothing was checked.",
41755
+ remedy: "Call ofw_status() with no arguments for the full draft inventory, or pass ids / draftKeys.",
41756
+ complete: false
41757
+ });
41758
+ }
41759
+ let probeRequests = 0;
41760
+ const incomplete = [];
41761
+ let drafts;
41762
+ let inventoryComplete = true;
41763
+ let inventoryFreshness;
41764
+ if (wantInventory) {
41765
+ const sync = await syncAll(client2, {
41766
+ folders: ["drafts"],
41767
+ maxRequests: getSyncMaxRequests()
41768
+ }, cache);
41769
+ inventoryComplete = sync.refreshed.includes("drafts");
41770
+ const { freshness, cacheStatus, serverConfirmed } = await draftsFreshness(cache);
41771
+ inventoryFreshness = freshness;
41772
+ if (!serverConfirmed) inventoryComplete = false;
41773
+ const total = await cache.countDrafts();
41774
+ const rows = await cache.listDrafts({ page: 1, size: Math.max(total, 1) });
41775
+ const keyById = new Map(
41776
+ (await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey])
41777
+ );
41778
+ drafts = rows.map((d) => ({
41779
+ id: d.id,
41780
+ draftKey: keyById.get(d.id) ?? null,
41781
+ subject: d.subject,
41782
+ revision: draftRevision(d),
41783
+ modifiedAt: d.modifiedAt,
41784
+ recipients: d.recipients,
41785
+ replyToId: d.replyToId,
41786
+ cacheStatus
41787
+ }));
41788
+ if (!inventoryComplete) {
41789
+ incomplete.push("the drafts folder was not fully verified against OurFamilyWizard on this call (the request budget paused the walk), so this inventory may be missing or misreporting drafts");
41790
+ }
41791
+ }
41792
+ const requested = [];
41793
+ if (targets.length > 0) {
41794
+ const resolved = /* @__PURE__ */ new Map();
41795
+ for (const t of targets) {
41796
+ if (t.kind === "draftKey" && !resolved.has(t.draftKey)) {
41797
+ resolved.set(t.draftKey, await resolveDraftKey(cache, t.draftKey));
41798
+ }
41799
+ }
41800
+ const toProbe = /* @__PURE__ */ new Set();
41801
+ for (const t of targets) {
41802
+ if (t.kind === "id") toProbe.add(t.id);
41803
+ else {
41804
+ const chain = resolved.get(t.draftKey);
41805
+ if (chain !== null && chain !== void 0) toProbe.add(chain.currentId);
41806
+ }
41807
+ }
41808
+ const probed = await probeIds(client2, cache, [...toProbe], { allowMarkRead });
41809
+ probeRequests += probed.requests;
41810
+ const probes = new Map(probed.items.map((item) => [item.id, item]));
41811
+ for (const t of targets) {
41812
+ if (t.kind === "id") {
41813
+ requested.push(decorate(probes.get(t.id)));
41814
+ continue;
41815
+ }
41816
+ const chain = resolved.get(t.draftKey);
41817
+ if (chain === null || chain === void 0) {
41818
+ requested.push({
41819
+ draftKey: t.draftKey,
41820
+ state: "unknown",
41821
+ error: "UNKNOWN_DRAFT_KEY",
41822
+ note: "This draftKey has never been recorded in the local cache, so it cannot be resolved to a message id. Draft keys are minted by ofw_save_draft; a cache rebuilt or opened on another machine will not know an older key."
41823
+ });
41824
+ continue;
41825
+ }
41826
+ requested.push({
41827
+ draftKey: t.draftKey,
41828
+ currentId: chain.currentId,
41829
+ previousIds: chain.ids.slice(0, -1),
41830
+ ...decorate(probes.get(chain.currentId))
41831
+ });
41832
+ }
41833
+ for (const entry of requested) {
41834
+ if (entry.skipped === true || entry.error !== void 0 || entry.state === "unknown") {
41835
+ incomplete.push(`id/key ${String(entry.draftKey ?? entry.id)} could not be resolved to a confirmed live state`);
41836
+ }
41837
+ }
41838
+ }
41839
+ if (truncated > 0) {
41840
+ incomplete.push(`${truncated} of ${allTargets.length} requested ids/draftKeys were not probed (per-call cap of ${MAX_FRESHNESS_IDS})`);
41841
+ }
41842
+ const complete = incomplete.length === 0;
41843
+ return jsonResponse({
41844
+ checkedAt: (/* @__PURE__ */ new Date()).toISOString(),
41845
+ probeRequests,
41846
+ ...drafts !== void 0 ? { drafts, draftCount: drafts.length, draftInventoryComplete: inventoryComplete } : {},
41847
+ ...requested.length > 0 ? { requested } : {},
41848
+ complete,
41849
+ ...complete ? {} : { incompleteReasons: incomplete, note: "complete:false \u2014 this snapshot is NOT a verified statement of current state. Do not report a draft count or say whether something was sent from it; resolve the reasons above (usually by calling ofw_sync_messages, or re-calling with allowMarkRead:true) and ask again." },
41850
+ ...inventoryFreshness !== void 0 ? { freshness: inventoryFreshness } : {}
41851
+ });
41852
+ });
41853
+ }
41854
+ function decorate(item) {
41855
+ return item.state === "sent" ? { ...item, sentMessageId: item.id } : { ...item };
41419
41856
  }
41420
41857
  async function deleteOFWMessages(client2, ids) {
41421
41858
  const form = new FormData();
@@ -41679,6 +42116,14 @@ function draftFromDb(r) {
41679
42116
  listData: JSON.parse(r.list_data_json)
41680
42117
  };
41681
42118
  }
42119
+ function lineageFromDb(r) {
42120
+ return {
42121
+ id: r.id,
42122
+ draftKey: r.draft_key,
42123
+ previousId: r.previous_id,
42124
+ recordedAt: r.recorded_at
42125
+ };
42126
+ }
41682
42127
  function attachmentFromDb(r) {
41683
42128
  return {
41684
42129
  fileId: r.file_id,
@@ -41734,6 +42179,17 @@ var SCHEMA_STATEMENTS = [
41734
42179
  key TEXT PRIMARY KEY,
41735
42180
  value TEXT NOT NULL
41736
42181
  )`,
42182
+ // v3: draft identity chain. One row per OFW id, all the ids of one logical
42183
+ // document sharing a `draft_key`. Survives ofw_save_draft's create-then-delete
42184
+ // replacement AND the transition to a sent message, so "what happened to the
42185
+ // draft I was editing?" is answerable without guessing which id is current.
42186
+ `CREATE TABLE IF NOT EXISTS draft_lineage (
42187
+ id INTEGER PRIMARY KEY,
42188
+ draft_key TEXT NOT NULL,
42189
+ previous_id INTEGER,
42190
+ recorded_at TEXT NOT NULL
42191
+ )`,
42192
+ `CREATE INDEX IF NOT EXISTS idx_draft_lineage_key ON draft_lineage(draft_key, recorded_at, id)`,
41737
42193
  // v2: attachments table. Idempotent — IF NOT EXISTS.
41738
42194
  `CREATE TABLE IF NOT EXISTS attachments (
41739
42195
  file_id INTEGER PRIMARY KEY,
@@ -41752,7 +42208,7 @@ var MIGRATIONS = [
41752
42208
  // Resumable deep-sync cursor. Absent/NULL → SyncState.resumePage null.
41753
42209
  "ALTER TABLE sync_state ADD COLUMN resume_page INTEGER"
41754
42210
  ];
41755
- var SCHEMA_VERSION = "2";
42211
+ var SCHEMA_VERSION = "3";
41756
42212
  function buildMessageFilter(opts) {
41757
42213
  const wheres = [];
41758
42214
  const params = [];
@@ -41937,6 +42393,10 @@ var OFWCacheCore = class {
41937
42393
  );
41938
42394
  return rows.map(draftFromDb);
41939
42395
  }
42396
+ countDrafts() {
42397
+ const r = this.db.get("SELECT COUNT(*) as n FROM drafts", []);
42398
+ return r?.n ?? 0;
42399
+ }
41940
42400
  deleteDraft(id) {
41941
42401
  this.db.run("DELETE FROM drafts WHERE id = ?", [id]);
41942
42402
  }
@@ -41944,6 +42404,57 @@ var OFWCacheCore = class {
41944
42404
  const rows = this.db.all("SELECT id FROM drafts", []);
41945
42405
  return rows.map((r) => r.id);
41946
42406
  }
42407
+ /**
42408
+ * Link an id into a draft's identity chain. Upserts on id: re-recording the
42409
+ * same id (e.g. a retried save) rewrites its link rather than duplicating it,
42410
+ * so `getDraftLineage` can never report one id twice.
42411
+ */
42412
+ recordDraftLineage(row) {
42413
+ this.db.run(
42414
+ `INSERT INTO draft_lineage (id, draft_key, previous_id, recorded_at) VALUES (?, ?, ?, ?)
42415
+ ON CONFLICT(id) DO UPDATE SET
42416
+ draft_key=excluded.draft_key,
42417
+ previous_id=excluded.previous_id,
42418
+ recorded_at=excluded.recorded_at`,
42419
+ [
42420
+ row.id,
42421
+ requireString("draft_lineage.draftKey", row.draftKey),
42422
+ nullish3(row.previousId),
42423
+ requireString("draft_lineage.recordedAt", row.recordedAt)
42424
+ ]
42425
+ );
42426
+ }
42427
+ getDraftLineageById(id) {
42428
+ const r = this.db.get("SELECT * FROM draft_lineage WHERE id = ?", [id]);
42429
+ return r ? lineageFromDb(r) : null;
42430
+ }
42431
+ /**
42432
+ * Batch read — one query for a whole page of drafts. On the Durable Object
42433
+ * backend each cache call is a subrequest, so a per-draft lookup would spend
42434
+ * the caller's sync budget on bookkeeping.
42435
+ */
42436
+ getDraftLineageByIds(ids) {
42437
+ if (ids.length === 0) return [];
42438
+ const placeholders = ids.map(() => "?").join(", ");
42439
+ const rows = this.db.all(
42440
+ `SELECT * FROM draft_lineage WHERE id IN (${placeholders})`,
42441
+ ids
42442
+ );
42443
+ return rows.map(lineageFromDb);
42444
+ }
42445
+ /**
42446
+ * Every link in one chain, OLDEST FIRST — so the last element is the chain's
42447
+ * current id. Ordered by recorded_at then id: two links written inside the
42448
+ * same millisecond tie-break on id, and OFW mints ids monotonically, so the
42449
+ * newer replacement always sorts last.
42450
+ */
42451
+ getDraftLineage(draftKey) {
42452
+ const rows = this.db.all(
42453
+ "SELECT * FROM draft_lineage WHERE draft_key = ? ORDER BY recorded_at ASC, id ASC",
42454
+ [draftKey]
42455
+ );
42456
+ return rows.map(lineageFromDb);
42457
+ }
41947
42458
  getSyncState(folder) {
41948
42459
  const r = this.db.get("SELECT last_sync_at, newest_id, resume_page FROM sync_state WHERE folder = ?", [folder]);
41949
42460
  if (!r) return null;
@@ -42079,12 +42590,27 @@ var LocalCacheStore = class {
42079
42590
  async listDrafts(opts) {
42080
42591
  return this.core.listDrafts(opts);
42081
42592
  }
42593
+ async countDrafts() {
42594
+ return this.core.countDrafts();
42595
+ }
42082
42596
  async deleteDraft(id) {
42083
42597
  this.core.deleteDraft(id);
42084
42598
  }
42085
42599
  async listDraftIds() {
42086
42600
  return this.core.listDraftIds();
42087
42601
  }
42602
+ async recordDraftLineage(row) {
42603
+ this.core.recordDraftLineage(row);
42604
+ }
42605
+ async getDraftLineageById(id) {
42606
+ return this.core.getDraftLineageById(id);
42607
+ }
42608
+ async getDraftLineageByIds(ids) {
42609
+ return this.core.getDraftLineageByIds(ids);
42610
+ }
42611
+ async getDraftLineage(draftKey) {
42612
+ return this.core.getDraftLineage(draftKey);
42613
+ }
42088
42614
  async getSyncState(folder) {
42089
42615
  return this.core.getSyncState(folder);
42090
42616
  }
@@ -42188,7 +42714,7 @@ var nodeCacheProvider = () => nodeCache ??= OFWCache.open(getCacheDbPath());
42188
42714
  var nodeAttachmentIO = new NodeAttachmentIO();
42189
42715
  await runMcp({
42190
42716
  name: "ofw",
42191
- version: "2.8.0",
42717
+ version: "2.9.0",
42192
42718
  // x-release-please-version
42193
42719
  deps: client,
42194
42720
  tools: [