ofw-mcp 2.27.3 → 2.27.5

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.
@@ -1,5 +1,5 @@
1
1
  import { z } from 'zod';
2
- import { syncAll, unreadInboxNote, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus } from '../sync.js';
2
+ import { syncAll, fetchAttachmentMeta, fetchAttachmentMetaForMessage, getDraftsCacheStatus, latestViewedAt, NEW_MESSAGES_CAP, refreshReadReporting } from '../sync.js';
3
3
  import { buildFreshness } from './freshness.js';
4
4
  import { briefDate, briefLine, briefPage, briefResult, familyMeta } from './hints.js';
5
5
  import { checkDraftFreshness, draftRevision, fetchServerDraft, staleDraftPayload, } from './draft-freshness.js';
@@ -10,15 +10,20 @@ import { MAX_UPLOAD_BYTES } from './attachments.js';
10
10
  import { blobStoreFromEnv } from '@chrischall/mcp-utils/export';
11
11
  import { blobKeysParam, blobObjectToUpload, checkFileCount, describePending, fileNameFromBlobKey, inlineAttachmentsParam, inlineFileSchema, MAX_FILES_PER_CALL, mintUploadSlot, planAttachments, requireBlobStore, resolveInlineUpload, sha256Hex, uploadPending, uploadSlotRequestSchema, uploadToMyFiles, } from './uploads.js';
12
12
  import { clearHeldFiles, getHeldFiles, heldFilesFor, HELD_NOTE, setHeldFiles, uniqueIds } from './held-attachments.js';
13
+ import { replyToSourceField, setReplyToSource } from './reply-source.js';
13
14
  import { buildInlineDelivery, MAX_INLINE_BYTES, tryExtract } from './delivery.js';
14
15
  import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
15
16
  import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
16
17
  import { basename, resolve } from 'node:path';
17
18
  import { randomUUID } from 'node:crypto';
18
- import { ApiRecipientSchema, deriveRead, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
19
+ import { ApiRecipientSchema, deriveRead, draftReplyTarget, hasRealView, jsonErrorResponse, jsonResponse, jsonText, mapRecipients, notedJsonResponse, postMessageAndRefetch, reportsThreaded, UnconfirmedWriteError, reportsUnthreaded, threadedReplyTo, verifyWriteLanded, withReadState } from './_shared.js';
19
20
  import { parseLenient } from '@chrischall/mcp-utils';
20
21
  import { pageState } from './pagination.js';
21
- import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
22
+ import { compactSentMessage, compactWrittenDraft, MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './project.js';
23
+ // The `view` note on the two write tools. Their echo is what the caller just
24
+ // wrote, so compact replaces the body with its length + hash rather than
25
+ // repeating it, and drops OFW's raw `listData` echo.
26
+ const WRITE_VIEW_NOTE = 'compact omits OurFamilyWizard\'s raw `listData` echo (which repeats the body, subject, recipients and a date block) and replaces the body you just wrote with `bodyLength` + `bodySha256` (the first 16 hex characters of its SHA-256) to confirm what landed. Pass "full" for both.';
22
27
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
23
28
  import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
24
29
  import { readingBlockedToday } from '../read-days.js';
@@ -286,6 +291,7 @@ async function unreadCandidates(cache) {
286
291
  /**
287
292
  * Fetch one unread inbox body and cache it — the request that marks it read.
288
293
  * Only ever called after the confirmation gate approved this exact message.
294
+ * Returns the `markedRead` entry the sync response reports for it.
289
295
  */
290
296
  async function openUnreadBody(client, cache, cached) {
291
297
  const detail = parseLenient(MessageDetailSchema, await client.request('GET', `/pub/v3/messages/${cached.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (sync, confirmed mark-read)' });
@@ -298,6 +304,10 @@ async function openUnreadBody(client, cache, cached) {
298
304
  if (Array.isArray(detail.files) && detail.files.length > 0) {
299
305
  await fetchAttachmentMetaForMessage(client, cached.id, detail.files, cache);
300
306
  }
307
+ return {
308
+ id: cached.id, subject: cached.subject, from: senderOf(cached), sentAt: cached.sentAt,
309
+ viewedAt: latestViewedAt(detail.recipients), reason: 'fetchUnreadBodies',
310
+ };
301
311
  }
302
312
  /**
303
313
  * OFW_CONFIRM_MARK_READ: before `ofw_get_message` fetches a body that would
@@ -685,6 +695,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
685
695
  // ofw_delete_draft / ofw_send_message to assert you are acting on
686
696
  // THIS version.
687
697
  revision: draftRevision(draftRow, held),
698
+ // Whether the reply target is OFW's own echo or this server's record of
699
+ // it (OFW's payload omitted the linkage) — see reply-source.ts.
700
+ ...(await replyToSourceField(cache, draftRow.id, draftRow.replyToId)),
688
701
  cacheStatus,
689
702
  // False = this draft's existence and unsent status are remembered from
690
703
  // a cache, not confirmed on OFW. Call ofw_check_freshness before
@@ -834,6 +847,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
834
847
  inlineAttachments: inlineAttachmentsParam,
835
848
  blobKeys: blobKeysParam,
836
849
  confirmToken: confirmTokenParam,
850
+ view: viewParam(MESSAGE_VIEWS, { note: WRITE_VIEW_NOTE }),
837
851
  }),
838
852
  }, async (args, ctx) => {
839
853
  if (args.messageId !== undefined && args.draftId !== undefined && args.messageId !== args.draftId) {
@@ -1201,7 +1215,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1201
1215
  previousId: draftRef,
1202
1216
  }
1203
1217
  : {}),
1204
- ...persisted,
1218
+ ...(resolveView(args.view, MESSAGE_VIEWS) === 'full' ? persisted : compactSentMessage(persisted)),
1205
1219
  ...(attachmentCheck !== null ? { attachments: attachmentCheck } : {}),
1206
1220
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1207
1221
  ...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
@@ -1220,7 +1234,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1220
1234
  };
1221
1235
  let server;
1222
1236
  try {
1223
- server = await fetchServerDraft(client, draftId);
1237
+ server = await fetchServerDraft(client, draftId, cachedRow?.replyToId ?? null);
1224
1238
  }
1225
1239
  catch (e) {
1226
1240
  // Anything landing here means the check could not RUN. Most failures
@@ -1339,8 +1353,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1339
1353
  // compared this cache against OFW.
1340
1354
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
1341
1355
  const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
1342
- const drafts = rows.map((d) => ({
1356
+ const drafts = await Promise.all(rows.map(async (d) => ({
1343
1357
  ...d,
1358
+ ...(await replyToSourceField(cache, d.id, d.replyToId)),
1344
1359
  revision: draftRevision(d, held.get(d.id)),
1345
1360
  ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
1346
1361
  draftKey: keyById.get(d.id) ?? null,
@@ -1348,7 +1363,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1348
1363
  cacheStatus,
1349
1364
  serverConfirmed,
1350
1365
  asOf: freshness.asOf,
1351
- }));
1366
+ })));
1352
1367
  return { drafts, total, freshness, serverConfirmed };
1353
1368
  },
1354
1369
  });
@@ -1405,7 +1420,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1405
1420
  if (allowDrafts)
1406
1421
  server.registerTool('ofw_save_draft', {
1407
1422
  _meta: familyMeta('change'),
1408
- description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard has not reliably kept recipients on drafts (when the saved draft comes back with none it is noted once, not warned about) — supply recipientIds at send time as well. ATTACHMENTS: OurFamilyWizard does not store files on drafts, so myFileIDs / inlineAttachments / blobKeys are HELD with the draft by this server (carried across edits, de-duplicated; removeFileIDs drops one), shown under attachments.held, folded into `revision`, and attached when the draft is sent with ofw_send_message(draftId). They are not visible on the draft in the OurFamilyWizard web app. IDENTITY: the response leads with `draftKey`, the stable identity that survives editing — key off it, because the `id` changes on EVERY edit (replacing a draft creates a NEW draft and deletes the old one; OFW\'s update-in-place endpoint silently no-ops, so we never use it). Pass messageId to replace an existing draft; the response.id will be the NEW id, and a transparency NOTE documents the swap and which fields were carried over. THREADING: if replyToId is provided, the cache may rewrite it to the latest reply in the thread (note included). The threading verdict is read from OFW\'s full echo (replyToId/inReplyTo/showContext) — a warning appears ONLY when the reply linkage was genuinely dropped or re-targeted, and the response\'s top-level replyToId/inReplyTo always agree with its listData. After saving, the tool re-fetches the draft from OFW, and the returned `revision` reflects that authoritative state (so it will match on your next edit). SAFETY: because replacing DESTROYS the old draft rather than merging, passing messageId first re-reads that draft from OFW and REFUSES the write if its subject/body/recipients changed since you read it (drafts edited in the OFW web app do not bump any timestamp, so the local cache can be silently behind). A pure replyToId normalization by OFW is NOT treated as a conflict. The refusal returns the current server body under serverBody — merge your edit into it and retry with expectedRevision.',
1423
+ description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard has not reliably kept recipients on drafts (when the saved draft comes back with none it is noted once, not warned about) — supply recipientIds at send time as well. ATTACHMENTS: OurFamilyWizard does not store files on drafts, so myFileIDs / inlineAttachments / blobKeys are HELD with the draft by this server (carried across edits, de-duplicated; removeFileIDs drops one), shown under attachments.held, folded into `revision`, and attached when the draft is sent with ofw_send_message(draftId). They are not visible on the draft in the OurFamilyWizard web app. IDENTITY: the response leads with `draftKey`, the stable identity that survives editing — key off it, because the `id` changes on EVERY edit (replacing a draft creates a NEW draft and deletes the old one; OFW\'s update-in-place endpoint silently no-ops, so we never use it). Pass messageId to replace an existing draft; the response.id will be the NEW id, and a transparency NOTE documents the swap and which fields were carried over. THREADING: if replyToId is provided, the cache may rewrite it to the latest reply in the thread (note included). The threading verdict is read from OFW\'s full echo (replyToId/inReplyTo/showContext) — a warning appears ONLY when the reply linkage was genuinely dropped or re-targeted. When OFW\'s echo omits the linkage entirely, the posted target is kept and marked replyToSource:"cache". Replacing a draft (messageId) without replyToId keeps the draft\'s own reply target. RESPONSE: compact by default — no listData echo, and the body you wrote is returned as bodyLength + bodySha256; view:"full" returns both. After saving, the tool re-fetches the draft from OFW, and the returned `revision` reflects that authoritative state (so it will match on your next edit). SAFETY: because replacing DESTROYS the old draft rather than merging, passing messageId first re-reads that draft from OFW and REFUSES the write if its subject/body/recipients changed since you read it (drafts edited in the OFW web app do not bump any timestamp, so the local cache can be silently behind). A pure replyToId normalization by OFW is NOT treated as a conflict. The refusal returns the current server body under serverBody — merge your edit into it and retry with expectedRevision.',
1409
1424
  // Destructive: with messageId, saving REPLACES the draft by creating a new
1410
1425
  // one and deleting the old (OFW has no draft update), so the old draft's
1411
1426
  // server content is gone. Not idempotent: every call mints a new draft id.
@@ -1422,9 +1437,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1422
1437
  blobKeys: blobKeysParam,
1423
1438
  expectedRevision: z.string().describe('With messageId: the `revision` you got from ofw_list_drafts/ofw_get_message for that draft. Asserts you are replacing THAT version. If the draft changed on OFW since, the write is refused and the current server body is returned. Omit and the tool compares the server against the local cache instead — omitting never means "overwrite anyway".').optional(),
1424
1439
  force: z.boolean().describe('Default false. Overwrite even when the draft changed on OurFamilyWizard since you read it. The discarded server version is echoed back in the response. Only use after showing the user the conflict.').optional(),
1440
+ view: viewParam(MESSAGE_VIEWS, { note: WRITE_VIEW_NOTE }),
1425
1441
  }),
1426
1442
  }, async (args) => {
1427
1443
  const cache = cacheProvider();
1444
+ const view = resolveView(args.view, MESSAGE_VIEWS);
1428
1445
  // New attachments are validated before ANYTHING happens, so a bad entry
1429
1446
  // fails the call with nothing uploaded and nothing saved.
1430
1447
  const blobStore = args.blobKeys?.length ? blobStoreFromEnv() : undefined;
@@ -1435,6 +1452,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1435
1452
  let serverFiles;
1436
1453
  let priorHeld = [];
1437
1454
  let serverRecipientIds;
1455
+ let serverReplyTo = null;
1438
1456
  if (args.messageId !== undefined) {
1439
1457
  const guard = await guardDestructiveDraftOp({
1440
1458
  cache,
@@ -1453,8 +1471,12 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1453
1471
  const kept = (guard.server?.recipients ?? []).map((r) => r.userId).filter((id) => id !== 0);
1454
1472
  if (kept.length > 0)
1455
1473
  serverRecipientIds = [...new Set(kept)];
1474
+ // Likewise the reply target: a replace that names no replyToId keeps the
1475
+ // draft's own thread. Posting without one turned an edit of a reply into
1476
+ // a new top-level conversation.
1477
+ serverReplyTo = guard.server?.replyToId ?? null;
1456
1478
  }
1457
- const requestedReplyTo = args.replyToId ?? null;
1479
+ const requestedReplyTo = args.replyToId ?? serverReplyTo;
1458
1480
  let resolvedReplyTo = requestedReplyTo;
1459
1481
  let rewriteNote = null;
1460
1482
  if (requestedReplyTo !== null) {
@@ -1497,6 +1519,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1497
1519
  let verifyNote = null;
1498
1520
  let recipientsNote = null;
1499
1521
  let newRevision = null;
1522
+ let replyToSource = null;
1500
1523
  let onDraft = [];
1501
1524
  let held = [];
1502
1525
  let draftKey = null;
@@ -1515,7 +1538,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1515
1538
  // null — reading only `replyToId` fired a false "did not thread" warning
1516
1539
  // on nearly every threaded save while the same response's listData
1517
1540
  // showed inReplyTo populated.
1518
- const effectiveReplyTo = threadedReplyTo(detail);
1541
+ //
1542
+ // The shared rule (draftReplyTarget) keeps the posted target when the
1543
+ // detail does not echo the linkage at all, exactly as the drafts sync and
1544
+ // the freshness snapshot do — so the revision returned here is the one
1545
+ // every later read reports. A POSITIVELY unthreaded echo still stores
1546
+ // null (the drop is not masked) and is warned about below.
1547
+ const reply = draftReplyTarget([detail], resolvedReplyTo);
1548
+ const effectiveReplyTo = reply.replyToId;
1549
+ replyToSource = reply.replyToSource;
1519
1550
  const storedRecipients = mapRecipients(detail.recipients);
1520
1551
  persisted = {
1521
1552
  id: newId,
@@ -1527,6 +1558,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1527
1558
  listData: detail,
1528
1559
  };
1529
1560
  await cache.upsertDraft(persisted);
1561
+ await setReplyToSource(cache, newId, replyToSource);
1530
1562
  // What OFW actually kept on the draft (in practice none), and what is
1531
1563
  // therefore held here for the send.
1532
1564
  onDraft = Array.isArray(detail.files) ? detail.files : [];
@@ -1572,9 +1604,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1572
1604
  // trained callers to skim warnings. The "dropped" warning demands
1573
1605
  // POSITIVE evidence (reportsUnthreaded): a bare `replyToId: null` or a
1574
1606
  // detail omitting every echo field is "not echoed", never "dropped".
1575
- // The stored replyToId is still the server echo (null when unreported) —
1576
- // masking it with intent was Defect 1, and the revision must hash what
1577
- // the next sync will read.
1607
+ // The stored replyToId is the server echo, or the posted target when OFW
1608
+ // echoed no linkage at all (replyToSource "cache"). Masking a POSITIVE
1609
+ // drop with intent was Defect 1; filling silence is not, because the
1610
+ // drafts sync and the freshness snapshot apply the same fallback, so the
1611
+ // revision still hashes what the next read reports.
1578
1612
  if (resolvedReplyTo !== null && effectiveReplyTo !== resolvedReplyTo && reportsUnthreaded(detail)) {
1579
1613
  const rewrittenFrom = requestedReplyTo !== resolvedReplyTo ? ` (rewritten from ${requestedReplyTo})` : '';
1580
1614
  warnings.push(`replyToId was requested as ${resolvedReplyTo}${rewrittenFrom} but the saved draft came back with replyToId null — OurFamilyWizard did not thread this draft (its inReplyTo/showContext are empty). The subject and body were saved; only the reply linkage was dropped. If threading matters, verify on ourfamilywizard.com.`);
@@ -1627,12 +1661,18 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1627
1661
  // `revision` concurrency token; the volatile `id` is carried further down
1628
1662
  // as an implementation detail. `inReplyTo` echoes the effective threading,
1629
1663
  // and `warnings` names any requested field that did not land.
1664
+ //
1665
+ // compact (the default) drops the OFW echo (`listData`, which repeats the
1666
+ // body, subject, recipients and an eleven-rendering date block) and the
1667
+ // body itself — the caller just wrote it — leaving its length and hash to
1668
+ // confirm what landed. `view: "full"` keeps both.
1630
1669
  const responseObj = persisted !== null
1631
1670
  ? {
1632
1671
  draftKey,
1633
1672
  revision: newRevision,
1634
- ...persisted,
1673
+ ...(view === 'full' ? persisted : compactWrittenDraft(persisted)),
1635
1674
  inReplyTo: persisted.replyToId,
1675
+ ...(replyToSource !== null ? { replyToSource } : {}),
1636
1676
  previousId: args.messageId ?? null,
1637
1677
  cacheStatus: 'fresh',
1638
1678
  serverConfirmed: true,
@@ -2090,7 +2130,7 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2090
2130
  _meta: familyMeta('other'),
2091
2131
  // Destructive: fetchUnreadBodies:true stamps a co-parent-visible "First
2092
2132
  // Viewed" time on every unread inbox message it touches — irreversible.
2093
- description: 'Sync messages from OurFamilyWizard into the local cache. Returns counts per folder and a list of unread inbox messages whose bodies were NOT fetched (to avoid mark-as-read on OFW). Call ofw_get_message(id) on those to read them. EVERY call re-checks the newest page first, so new messages are picked up promptly even while an old-history backfill is still running; only then does it spend what is left of its budget advancing that backfill. Pass deep:true to walk all OFW pages instead of stopping at the first all-cached page (use to backfill suspected gaps). Sync is BOUNDED and RESUMABLE: on hosted deployments a per-call OFW-request budget (env OFW_SYNC_MAX_REQUESTS, or the maxRequests argument) caps how far one call walks; when the budget is hit the response reports done:false with a note — call again with the SAME arguments to resume. done:false means older history is still being backfilled; it does NOT mean recent messages are missing. Local installs are unbounded by default (done is always true). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) no inbox or sent message body is downloaded at all — new messages are cached from the list (sender, date, subject) and the response carries bodiesWithheld:true; the first sync on a reading day fills in those bodies, except unread inbox ones.',
2133
+ description: 'Sync messages from OurFamilyWizard into the local cache. A sync NEVER marks a message read unless fetchUnreadBodies is set: a new inbox message that OFW does not list as read is cached from the list (sender, date, subject) WITHOUT its body, because fetching the body is what stamps a co-parent-visible "First Viewed" time. Every response says what arrived: newMessages lists each message first cached by THIS call — inbox and sent, newest first, with read (its state before the sync) and bodyFetched; newMessagesTotal and newMessagesTruncated give the full count when more than ' + NEW_MESSAGES_CAP + ' arrived (ofw_list_messages pages through the rest). unreadInbox lists the new inbox messages that were unread when the sync began; bodyFetched:false means still unread on OFW — call ofw_get_message(id) to read one, which marks it read. If this call DID mark anything read (fetchUnreadBodies, or a stamp it detected but did not intend), the response LEADS with a warning and lists each in markedRead with reason "fetchUnreadBodies" or "unexpected"; markedRead is omitted when nothing was marked, and markedReadCount is always present. Returns counts per folder too. EVERY call re-checks the newest page first, so new messages are picked up promptly even while an old-history backfill is still running; only then does it spend what is left of its budget advancing that backfill. Pass deep:true to walk all OFW pages instead of stopping at the first all-cached page (use to backfill suspected gaps). Sync is BOUNDED and RESUMABLE: on hosted deployments a per-call OFW-request budget (env OFW_SYNC_MAX_REQUESTS, or the maxRequests argument) caps how far one call walks; when the budget is hit the response reports done:false with a note — call again with the SAME arguments to resume. done:false means older history is still being backfilled; it does NOT mean recent messages are missing. Local installs are unbounded by default (done is always true). On a server-configured no-read day (OFW_READ_DAYS / OFW_NO_READ_DAYS) no inbox or sent message body is downloaded at all — new messages are cached from the list (sender, date, subject) and the response carries bodiesWithheld:true; the first sync on a reading day fills in those bodies, except unread inbox ones.',
2094
2134
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
2095
2135
  inputSchema: z.object({
2096
2136
  folders: z.array(z.enum(['inbox', 'sent', 'drafts'])).min(1).describe('Folders to sync (default: all three). Must be non-empty if given — an empty list would sync nothing while reporting success.').optional(),
@@ -2159,21 +2199,19 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2159
2199
  });
2160
2200
  if (gate)
2161
2201
  return gate;
2202
+ const markedRead = result.markedRead ?? [];
2162
2203
  for (const row of rows)
2163
- await openUnreadBody(client, cache, row);
2204
+ markedRead.push(await openUnreadBody(client, cache, row));
2205
+ result.markedRead = markedRead;
2164
2206
  }
2165
2207
  const opened = new Set(rows.map((row) => row.id));
2166
- const before = result.unreadInbox.length;
2167
- result.unreadInbox = result.unreadInbox.filter((hint) => !opened.has(hint.id));
2168
- if (result.unreadInbox.length !== before) {
2169
- // Keep the note in step with unreadInbox: one payload, one count.
2170
- // syncAll always writes a note when it reports unread hints, and the
2171
- // count only moved because there were some, so the note is present.
2172
- const notes = result.note.split('\n\n').filter((n) => n !== unreadInboxNote(before));
2173
- if (result.unreadInbox.length > 0)
2174
- notes.push(unreadInboxNote(result.unreadInbox.length));
2175
- result.note = notes.length > 0 ? notes.join('\n\n') : undefined;
2176
- }
2208
+ // unreadInbox keeps its PRE-sync meaning (these were unread when this
2209
+ // call began), so an opened message stays listed — now bodyFetched.
2210
+ // newMessages agrees, and the warning, markedReadCount and both note
2211
+ // lines are recomputed so one payload never carries two counts.
2212
+ result.unreadInbox = result.unreadInbox.map((hint) => (opened.has(hint.id) ? { ...hint, bodyFetched: true } : hint));
2213
+ result.newMessages = result.newMessages.map((m) => (opened.has(m.id) ? { ...m, bodyFetched: true } : m));
2214
+ refreshReadReporting(result);
2177
2215
  unreadBodies = { requested: true, fetched: true, opened: [...opened], ...(remaining > 0 ? { remaining } : {}) };
2178
2216
  }
2179
2217
  // Freshness of the cache AS OF this sync completing — so a paused call
@@ -2182,7 +2220,19 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2182
2220
  source: 'cache',
2183
2221
  folders: args.folders ?? ['inbox', 'sent', 'drafts'],
2184
2222
  });
2185
- return jsonResponse({ ...result, ...(unreadBodies ? { unreadBodies } : {}), freshness });
2223
+ // Emitted order is load-bearing (see "Paging state is emitted BEFORE the
2224
+ // data array" in CLAUDE.md): the warning first, so even a truncated read
2225
+ // learns that this sync marked messages read; the counts
2226
+ // (newMessagesTotal / newMessagesTruncated / markedReadCount) next; the
2227
+ // newMessages array LAST.
2228
+ const { warning, newMessages, ...rest } = result;
2229
+ return jsonResponse({
2230
+ ...(warning ? { warning } : {}),
2231
+ ...rest,
2232
+ ...(unreadBodies ? { unreadBodies } : {}),
2233
+ freshness,
2234
+ newMessages,
2235
+ });
2186
2236
  });
2187
2237
  server.registerTool('ofw_check_freshness', {
2188
2238
  _meta: familyMeta('other'),
@@ -2339,7 +2389,7 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2339
2389
  const keyById = new Map((await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey]));
2340
2390
  const held = await heldFilesFor(cache, rows.map((d) => d.id));
2341
2391
  const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
2342
- drafts = rows.map((d) => ({
2392
+ drafts = await Promise.all(rows.map(async (d) => ({
2343
2393
  id: d.id,
2344
2394
  draftKey: keyById.get(d.id) ?? null,
2345
2395
  ...(inferred.has(d.id) ? { draftKeyInferred: true } : {}),
@@ -2349,8 +2399,9 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2349
2399
  modifiedAt: d.modifiedAt,
2350
2400
  recipients: d.recipients,
2351
2401
  replyToId: d.replyToId,
2402
+ ...(await replyToSourceField(cache, d.id, d.replyToId)),
2352
2403
  cacheStatus,
2353
- }));
2404
+ })));
2354
2405
  if (!inventoryComplete) {
2355
2406
  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');
2356
2407
  }
@@ -1,3 +1,4 @@
1
+ import { createHash } from 'node:crypto';
1
2
  import { projectOrRaw, pruneUndefined } from '@chrischall/mcp-utils';
2
3
  /**
3
4
  * The compact projection (`docs` — fleet convention "Response shape", and
@@ -155,6 +156,45 @@ export function compactDraft(row) {
155
156
  ...omitKnown(rest, DRAFT_ROW_KEYS),
156
157
  });
157
158
  }
159
+ export function bodyDigest(body) {
160
+ if (body === null)
161
+ return { bodyLength: null, bodySha256: null };
162
+ return { bodyLength: body.length, bodySha256: createHash('sha256').update(body).digest('hex').slice(0, 16) };
163
+ }
164
+ /**
165
+ * The compact echo of a draft `ofw_save_draft` just wrote. Unlike
166
+ * {@link compactDraft} (a READ, where the body is the payload), the caller
167
+ * already holds this body, so it is replaced by {@link bodyDigest} — and the
168
+ * OFW `listData` echo, which repeats body, subject, recipients and an
169
+ * eleven-rendering date block, is dropped.
170
+ */
171
+ export function compactWrittenDraft(row) {
172
+ return {
173
+ id: row.id,
174
+ subject: row.subject,
175
+ ...bodyDigest(row.body),
176
+ recipients: row.recipients,
177
+ replyToId: row.replyToId,
178
+ modifiedAt: row.modifiedAt,
179
+ };
180
+ }
181
+ /**
182
+ * The compact echo of a message `ofw_send_message` just sent: the body becomes
183
+ * {@link bodyDigest}, and `listData`, `fromUser` (the account holder) and
184
+ * `fetchedBodyAt` (the moment of this very call) are dropped.
185
+ */
186
+ export function compactSentMessage(row) {
187
+ return {
188
+ id: row.id,
189
+ folder: row.folder,
190
+ subject: row.subject,
191
+ ...bodyDigest(row.body),
192
+ sentAt: row.sentAt,
193
+ recipients: row.recipients,
194
+ replyToId: row.replyToId,
195
+ chainRootId: row.chainRootId,
196
+ };
197
+ }
158
198
  /**
159
199
  * Project a page of messages, or hand it back whole.
160
200
  *
@@ -0,0 +1,28 @@
1
+ // Where each cached draft's reply target came from.
2
+ //
3
+ // The drafts table holds the target itself; this records whether it is
4
+ // OurFamilyWizard's own echo (`server`) or this server's record of it, kept
5
+ // because OFW's payload did not report the linkage (`cache` — see
6
+ // draftReplyTarget in _shared.ts). It lives in the cache's `meta` table, keyed
7
+ // by draft id like the held files, so it needed no schema migration. A row
8
+ // written before this existed has no entry and reads as `server`: every such
9
+ // row's target was taken from an OFW payload.
10
+ const key = (draftId) => `draft_reply_source:${draftId}`;
11
+ /** Record how a draft's reply target was established (null: it has none). */
12
+ export async function setReplyToSource(cache, draftId, source) {
13
+ await cache.setMeta(key(draftId), source ?? '');
14
+ }
15
+ /**
16
+ * The source of a draft's reply target, or null when it has no target.
17
+ * Anything but an explicit `cache` reads as `server` (see the header).
18
+ */
19
+ export async function getReplyToSource(cache, draftId, replyToId) {
20
+ if (replyToId === null)
21
+ return null;
22
+ return (await cache.getMeta(key(draftId))) === 'cache' ? 'cache' : 'server';
23
+ }
24
+ /** `{ replyToSource }` for a draft with a reply target, `{}` otherwise. */
25
+ export async function replyToSourceField(cache, draftId, replyToId) {
26
+ const source = await getReplyToSource(cache, draftId, replyToId);
27
+ return source === null ? {} : { replyToSource: source };
28
+ }
package/dist/version.js CHANGED
@@ -4,4 +4,4 @@
4
4
  // package.json drift. Importing these instead of package.json keeps the whole
5
5
  // manifest — npm scripts included — out of dist/bundle.js.
6
6
  export const SERVER_NAME = 'ofw-mcp';
7
- export const VERSION = '2.27.3'; // x-release-please-version
7
+ export const VERSION = '2.27.5'; // x-release-please-version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.27.3",
3
+ "version": "2.27.5",
4
4
  "license": "MIT",
5
5
  "mcpName": "io.github.chrischall/ofw-mcp",
6
6
  "description": "OurFamilyWizard MCP server for Claude — developed and maintained by AI (Claude Code)",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/ofw-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "2.27.3",
9
+ "version": "2.27.5",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.27.3",
14
+ "version": "2.27.5",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -90,7 +90,7 @@ Always pass `--config ~/.mcporter/mcporter.json` unless a local `config/mcporter
90
90
  ### Messages
91
91
  | Tool | Notes |
92
92
  |------|-------|
93
- | `ofw_sync_messages(folders?, deep?, fetchUnreadBodies?)` | Sync OFW → local cache. **Call first if the cache might be stale.** Returns unread inbox hints (bodies not fetched, to avoid mark-as-read). With `fetchUnreadBodies` it may instead return a confirmation preview listing the unread messages it would open (server `OFW_CONFIRM_MARK_READ`): show the user that list and repeat with the `confirmToken` only on their yes. `unreadBodies.gate` names a server ceiling that refused. |
93
+ | `ofw_sync_messages(folders?, deep?, fetchUnreadBodies?)` | Sync OFW → local cache. **Call first if the cache might be stale.** Never marks anything read unless `fetchUnreadBodies` is set. `newMessages` lists every message this call cached for the first time (newest first, with `read` and `bodyFetched`; `newMessagesTotal`/`newMessagesTruncated` when more than 50 arrived), so tell the user what arrived from that list. `unreadInbox` lists the new inbox messages that were unread when the sync began (`bodyFetched:false` = still unread). If the response leads with a `warning` and a `markedRead` list, the sync marked those messages read on OFW; tell the user, and stress any with `reason: "unexpected"`. With `fetchUnreadBodies` it may instead return a confirmation preview listing the unread messages it would open (server `OFW_CONFIRM_MARK_READ`): show the user that list and repeat with the `confirmToken` only on their yes. `unreadBodies.gate` names a server ceiling that refused. |
94
94
  | `ofw_list_message_folders` | List OFW folders with unread counts. Most reads use the cache; this is mainly for folder IDs and live unread counts. |
95
95
  | `ofw_list_messages(folderId?, since?, until?, q?, sort?, page?, size?, autoRefresh?, view?)` | Cache-backed list. Supports folder ("inbox"/"sent"/"both"), date range, and substring search. `sort:"oldest"` starts at the old end of a range instead of paging to it (default `"newest"`). Returns `complete` for the RESULT SET plus **`nextPage`** (null when done) — and the paging keys come FIRST in the JSON, before `messages`. `returned` carries the record count as a scalar, beside `total`. An **empty** result from a non-fresh cache is refused (`UNVERIFIED_EMPTY`) — pass `autoRefresh:true` to sync and answer instead. |
96
96
  | `ofw_get_message(messageId, allowMarkRead?, view?)` | Read a message OR draft body. Cache-first. Ids in the drafts cache return `folder: "drafts"`. ⚠️ Falls through to OFW for unread inbox messages, which marks them read AND stamps a "First Viewed" time the co-parent can see — irreversible. Pass `allowMarkRead:false` to refuse that fetch instead; cached, sent and already-read messages are unaffected. If the server runs with `OFW_CONFIRM_MARK_READ`, the first call returns a preview (subject, sender, sent time) instead of the body: show it to the user and repeat the call with its `confirmToken` only after they say yes. On a server-configured no-read day (`readingBlocked` / `READING_BLOCKED` in the response) the body is withheld (`bodyWithheld: true`) — report the sender, date and subject, say when `nextReadableDay` is, and do not try to work around it. |
@@ -177,6 +177,21 @@ eight fields per recipient beside the three the row already normalised, and a
177
177
  - **On a draft, `ofw_get_message` returns `from: null`** — a draft is unsent, so
178
178
  there is no sender, and `""` would read as one we failed to find.
179
179
 
180
+ **The two write tools default to compact too.** `ofw_save_draft` and
181
+ `ofw_send_message` drop the `listData` echo and replace the body you just wrote
182
+ with `bodyLength` + `bodySha256` (the first 16 hex characters of its SHA-256),
183
+ which is enough to confirm what landed. They keep `draftKey`, `id`, `revision`,
184
+ `replyToId`, `recipients`, the attachments block, `modifiedAt`/`sentAt`, notes
185
+ and warnings. `view: "full"` returns the body and the echo.
186
+
187
+ **`replyToSource` says where a draft's reply target came from.** `"server"`
188
+ means OFW reported it. `"cache"` means OFW's payload left the linkage out, so
189
+ the target this server recorded was kept (a payload that *positively* reports
190
+ the draft as unthreaded is never overridden). The target, and the `revision`
191
+ built from it, are the same on every path — save, list, get and
192
+ `ofw_check_freshness` — so a revision from any of them works as
193
+ `expectedRevision`, and sending by `draftId` threads to it.
194
+
180
195
  Pass `view: "full"` when you need a field compact dropped — `listData` and
181
196
  everything in it. There is deliberately **no `raw` rung**: a message here is
182
197
  assembled from a list item, a detail GET and derived fields, so there is no
@@ -40,14 +40,18 @@ curl -s 'https://ofw.ourfamilywizard.com/pub/v1/messageFolders?includeFolderCoun
40
40
  ```
41
41
 
42
42
  **List messages in a folder** (date-desc, 50/page is what the MCP's sync
43
- uses; unread inbox items carry `showNeverViewed: true` — the reliable
44
- unread signal, per CLAUDE.md):
43
+ uses). On the INBOX list, an item is read only when it carries
44
+ `read: true`; anything else (`read: false`, or no `read` at all) means
45
+ unread. Do NOT use `showNeverViewed` for the inbox: it is the sender-side
46
+ "recipient never viewed" badge and is `false` on a brand-new message you
47
+ have never opened. For SENT items, `showNeverViewed: false` means the
48
+ recipient has viewed it:
45
49
 
46
50
  ```sh
47
51
  FOLDER_ID=<id from above>
48
52
  curl -s "https://ofw.ourfamilywizard.com/pub/v3/messages?folders=${FOLDER_ID}&page=1&size=50&sort=date&sortDirection=desc" \
49
53
  "${AUTH_HEADERS[@]}" \
50
- | jq '.data[] | {id, subject, sentAt: .date.dateTime, from: .from.name, showNeverViewed}'
54
+ | jq '.data[] | {id, subject, sentAt: .date.dateTime, from: (.author.name // .from.name), read, showNeverViewed}'
51
55
  ```
52
56
 
53
57
  **Message/draft detail by id** (GETting an unread inbox message marks it