ofw-mcp 2.27.2 → 2.27.4

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/sync.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
2
2
  import { z } from 'zod';
3
- import { ApiRecipientSchema, hasRealView, mapRecipients, threadedReplyTo } from './tools/_shared.js';
3
+ import { ApiRecipientSchema, hasRealView, mapRecipients, scrapeSaysRead, threadedReplyTo } from './tools/_shared.js';
4
+ import { senderOf } from './tools/project.js';
4
5
  import { parseLenient } from '@chrischall/mcp-utils';
5
- import { nowNaiveWallClock } from './timestamps.js';
6
+ import { displayTimeZone, nowNaiveWallClock, parseTimestampValue } from './timestamps.js';
6
7
  import { readingBlockedToday } from './read-days.js';
7
8
  // Each OFW message detail returns `files: [fileId, ...]`. We fetch the metadata
8
9
  // for each file id (cheap JSON call) so the model can see filenames/mime types
@@ -104,14 +105,18 @@ export async function resolveFolderIds(client, store) {
104
105
  return ids;
105
106
  }
106
107
  // Required fields are the ones the sync loop reads unguarded (id keys the
107
- // cache; showNeverViewed drives unread semantics — per CLAUDE.md it's the
108
- // only reliable unread indicator, so its disappearance must warn loudly).
108
+ // cache; showNeverViewed is the SENT folder's read signal, so its
109
+ // disappearance must warn loudly). `read` is the INBOX list's own read flag —
110
+ // the only inbox read evidence (see scrapeSaysRead). It stays optional because
111
+ // sent items need not carry it, and a missing inbox `read` already fails
112
+ // closed to "unread", which is the safe answer.
109
113
  const ListItemSchema = z.looseObject({
110
114
  id: z.number(),
111
115
  subject: z.string(),
112
116
  date: z.looseObject({ dateTime: z.string() }),
113
117
  from: z.looseObject({ name: z.string().optional() }).optional(),
114
118
  showNeverViewed: z.boolean(),
119
+ read: z.boolean().optional(),
115
120
  recipients: z.array(ApiRecipientSchema).optional(),
116
121
  });
117
122
  const ListResponseSchema = z.looseObject({ data: z.array(ListItemSchema).optional() });
@@ -122,6 +127,32 @@ const DetailResponseSchema = z.looseObject({
122
127
  // endpoint only has an epoch placeholder) — used by the view-status refresh.
123
128
  recipients: z.array(ApiRecipientSchema).optional(),
124
129
  });
130
+ /**
131
+ * How far BEFORE the request start a detail's view time may fall and still
132
+ * count as stamped by that request. OFW reports view times to the second
133
+ * (truncation costs up to 1 s) and its clock is not ours; 2 s absorbs both
134
+ * without blaming us for a view that genuinely happened earlier.
135
+ */
136
+ export const STAMP_TOLERANCE_MS = 2000;
137
+ /**
138
+ * True when `viewedAt` (OFW's naive wall clock, read in DISPLAY_TZ like every
139
+ * other OFW time) is at or after `startedAtMs` less STAMP_TOLERANCE_MS — i.e.
140
+ * the fetch that began at `startedAtMs` is what stamped it. A missing or
141
+ * unparseable time is not evidence. If DISPLAY_TZ does not match the
142
+ * account's zone the comparison is off by the offset; this check is a
143
+ * backstop for the read-state rule, never a substitute for it.
144
+ */
145
+ export function stampedByFetch(viewedAt, startedAtMs) {
146
+ if (viewedAt === null)
147
+ return false;
148
+ const at = parseTimestampValue('viewedAt', viewedAt, displayTimeZone());
149
+ return at !== null && at.getTime() >= startedAtMs - STAMP_TOLERANCE_MS;
150
+ }
151
+ /** The latest real (non-placeholder) view time on a detail's recipients. */
152
+ export function latestViewedAt(recipients) {
153
+ const times = mapRecipients(recipients).map((r) => r.viewedAt).filter((t) => t !== null);
154
+ return times.length === 0 ? null : times.sort().at(-1);
155
+ }
125
156
  const maxId = (a, b) => a === null ? b : b === null ? a : Math.max(a, b);
126
157
  /**
127
158
  * Walk one folder's list pages from `startPage` toward older messages, caching
@@ -135,17 +166,41 @@ async function walkPages(client, folder, folderId, opts, store) {
135
166
  let synced = 0;
136
167
  let pagesFetched = 0;
137
168
  const unread = [];
169
+ const newMessages = [];
170
+ const markedRead = [];
171
+ const totals = () => ({ synced, unread, newMessages, markedRead, newestId, pagesFetched });
172
+ /**
173
+ * GET one message's detail. For an INBOX message, compare the view time OFW
174
+ * now reports with when the request began: a view at/after it means this
175
+ * fetch stamped "First Viewed", and that is reported, never silent.
176
+ * `deliberate` = the caller asked for unread bodies, so it is reported
177
+ * whatever the echo says.
178
+ */
179
+ const fetchDetail = async (item, row, context, deliberate) => {
180
+ const startedAt = Date.now();
181
+ const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context });
182
+ if (folder === 'inbox') {
183
+ const viewedAt = latestViewedAt(detail.recipients);
184
+ if (deliberate || stampedByFetch(viewedAt, startedAt)) {
185
+ markedRead.push({
186
+ id: item.id, subject: row.subject, from: row.from, sentAt: row.sentAt, viewedAt,
187
+ reason: deliberate ? 'fetchUnreadBodies' : 'unexpected',
188
+ });
189
+ }
190
+ }
191
+ return detail;
192
+ };
138
193
  while (true) {
139
194
  // One unit per list-page fetch. Out of budget → pause and resume at `page`.
140
195
  if (!budget.take()) {
141
- return { synced, unread, newestId, pagesFetched, done: false, nextPage: page };
196
+ return { ...totals(), done: false, nextPage: page };
142
197
  }
143
198
  const path = `/pub/v3/messages?folders=${encodeURIComponent(folderId)}&page=${page}&size=50&sort=date&sortDirection=desc`;
144
199
  const list = parseLenient(ListResponseSchema, await client.request('GET', path), { label: 'ofw-mcp', context: `GET /pub/v3/messages?folders={${folder}}` });
145
200
  pagesFetched++;
146
201
  const items = list.data ?? [];
147
202
  if (items.length === 0) {
148
- return { synced, unread, newestId, pagesFetched, done: true, nextPage: null };
203
+ return { ...totals(), done: true, nextPage: null };
149
204
  }
150
205
  // One batch read of this page's ids (S1) instead of a per-item getMessage.
151
206
  const existingById = new Map((await store.getMessages(items.map((it) => it.id))).map((row) => [row.id, row]));
@@ -157,18 +212,24 @@ async function walkPages(client, folder, folderId, opts, store) {
157
212
  if (newestId === null || item.id > newestId)
158
213
  newestId = item.id;
159
214
  const existing = existingById.get(item.id);
160
- const isInboxUnread = folder === 'inbox' && item.showNeverViewed === true;
215
+ // Read per the LIST, before we touch anything. For inbox that is the
216
+ // list's own `read === true` and nothing else: `showNeverViewed` on the
217
+ // inbox list is the sender-side badge and reads false on a message we
218
+ // never opened, so trusting it fetched — and stamped — unread bodies.
219
+ // Missing/non-boolean `read` fails closed to unread (scrapeSaysRead).
220
+ const listRead = scrapeSaysRead(folder, item);
221
+ const isInboxUnread = folder === 'inbox' && !listRead;
161
222
  if (existing) {
162
223
  // Heal a row cached without its body — typically one listed on a
163
224
  // no-read day — once fetching it can stamp nothing: a sent message, or
164
- // an inbox message OFW already reports as read. An unread inbox body
225
+ // an inbox message OFW's list reports as read. An unread inbox body
165
226
  // stays the caller's explicit choice (ofw_get_message), as before.
166
227
  if (opts.fetchBodies && existing.body === null && !isInboxUnread) {
167
228
  if (!budget.take()) {
168
229
  pageBudgetHit = true;
169
230
  break;
170
231
  }
171
- const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (body backfill)' });
232
+ const detail = await fetchDetail(item, { subject: existing.subject, sentAt: existing.sentAt, from: senderOf(existing) }, 'GET /pub/v3/messages/{id} (body backfill)', false);
172
233
  toUpsert.push({
173
234
  ...existing,
174
235
  body: detail.body ?? '',
@@ -215,12 +276,29 @@ async function walkPages(client, folder, folderId, opts, store) {
215
276
  // already read by the time we first saw it — reporting "never viewed" for
216
277
  // a message OFW shows as read, until a later sync's refresh healed it.
217
278
  let detailRecipients;
279
+ // The row as the list describes it; the detail (if fetched) fills in
280
+ // body and real view times below.
281
+ const row = {
282
+ id: item.id,
283
+ folder,
284
+ subject: item.subject ?? '(no subject)',
285
+ fromUser: item.from?.name ?? '',
286
+ sentAt: item.date?.dateTime ?? nowNaiveWallClock(),
287
+ recipients: mapRecipients(item.recipients),
288
+ body: null,
289
+ fetchedBodyAt: null,
290
+ replyToId: null,
291
+ chainRootId: null,
292
+ listData: item,
293
+ };
294
+ const from = senderOf(row);
218
295
  if (shouldFetchBody) {
219
296
  if (!budget.take()) {
220
297
  pageBudgetHit = true;
221
298
  break;
222
299
  }
223
- const detail = parseLenient(DetailResponseSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (sync)' });
300
+ // Reached for an unread inbox message only under fetchUnreadBodies.
301
+ const detail = await fetchDetail(item, { subject: row.subject, sentAt: row.sentAt, from }, 'GET /pub/v3/messages/{id} (sync)', isInboxUnread);
224
302
  body = detail.body ?? '';
225
303
  fetchedBodyAt = new Date().toISOString();
226
304
  detailRecipients = detail.recipients;
@@ -228,27 +306,24 @@ async function walkPages(client, folder, folderId, opts, store) {
228
306
  detailFileIds = detail.files;
229
307
  }
230
308
  }
231
- else if (isInboxUnread) {
309
+ if (isInboxUnread) {
310
+ // Pre-sync state: listed even when fetchUnreadBodies then opened it.
232
311
  unread.push({
233
312
  id: item.id,
234
313
  subject: item.subject,
235
- from: item.from?.name ?? '',
314
+ from: from ?? '',
236
315
  sentAt: item.date.dateTime,
316
+ bodyFetched: shouldFetchBody,
237
317
  });
238
318
  }
239
- const row = {
240
- id: item.id,
241
- folder,
242
- subject: item.subject ?? '(no subject)',
243
- fromUser: item.from?.name ?? '',
244
- sentAt: item.date?.dateTime ?? nowNaiveWallClock(),
245
- recipients: mapRecipients(detailRecipients ?? item.recipients),
246
- body,
247
- fetchedBodyAt,
248
- replyToId: null,
249
- chainRootId: null,
250
- listData: item,
251
- };
319
+ newMessages.push({
320
+ id: item.id, folder, from, subject: row.subject, sentAt: row.sentAt,
321
+ read: listRead, bodyFetched: shouldFetchBody,
322
+ });
323
+ row.body = body;
324
+ row.fetchedBodyAt = fetchedBodyAt;
325
+ if (detailRecipients)
326
+ row.recipients = mapRecipients(detailRecipients);
252
327
  toUpsert.push(row);
253
328
  synced++;
254
329
  if (detailFileIds.length > 0) {
@@ -265,14 +340,14 @@ async function walkPages(client, folder, folderId, opts, store) {
265
340
  if (pageBudgetHit) {
266
341
  // Paused mid-page. Resume at THIS page: the partial rows are cached, so
267
342
  // getMessages skips them next time and upserts are idempotent.
268
- return { synced, unread, newestId, pagesFetched, done: false, nextPage: page };
343
+ return { ...totals(), done: false, nextPage: page };
269
344
  }
270
345
  // Reached cached history (see `stopAtCachedPage`). Report THIS page as the
271
346
  // resume point rather than the next one: it costs one redundant (cheap,
272
347
  // all-cached) fetch if a backfill later starts here, and it cannot skip a
273
348
  // message the way an off-by-one `page + 1` could.
274
349
  if (opts.stopAtCachedPage && !pageHadNewItem) {
275
- return { synced, unread, newestId, pagesFetched, done: true, nextPage: page };
350
+ return { ...totals(), done: true, nextPage: page };
276
351
  }
277
352
  page++;
278
353
  }
@@ -309,6 +384,8 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
309
384
  }, store);
310
385
  let synced = fwd.synced;
311
386
  const unread = [...fwd.unread];
387
+ const newMessages = [...fwd.newMessages];
388
+ const markedRead = [...fwd.markedRead];
312
389
  // Never regress the folder's newest id: a pass that only walked cached pages
313
390
  // still saw page 1, but a paused one may not have.
314
391
  let newestId = maxId(saved?.newestId ?? null, fwd.newestId);
@@ -360,6 +437,8 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
360
437
  }, store);
361
438
  synced += bf.synced;
362
439
  unread.push(...bf.unread);
440
+ newMessages.push(...bf.newMessages);
441
+ markedRead.push(...bf.markedRead);
363
442
  newestId = maxId(newestId, bf.newestId);
364
443
  done = bf.done;
365
444
  resumePage = bf.done ? null : bf.nextPage;
@@ -373,7 +452,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
373
452
  // sync (buildFreshness downgrades when lastSyncAt runs ahead of verifiedAt).
374
453
  if (fwd.done)
375
454
  await markFolderVerified(store, folder, now);
376
- return { synced, unread, done, verified: fwd.done };
455
+ return { synced, unread, newMessages, markedRead, done, verified: fwd.done };
377
456
  }
378
457
  const DraftListItemSchema = z.looseObject({
379
458
  id: z.number(),
@@ -566,6 +645,21 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
566
645
  await markFolderVerified(store, 'drafts', now);
567
646
  return { synced, done: true };
568
647
  }
648
+ /**
649
+ * The most new messages one sync response lists. A first sync of a large
650
+ * account caches thousands of rows; echoing them all would make the response
651
+ * the problem (see "Response shape" in CLAUDE.md). The newest are the ones a
652
+ * caller acts on, `newMessagesTotal` keeps the real count, and
653
+ * `newMessagesTruncated` says the array is a slice — ofw_list_messages pages
654
+ * through the rest.
655
+ */
656
+ export const NEW_MESSAGES_CAP = 50;
657
+ /** Newest first: by sentAt (OFW's uniform naive format sorts as text), then id. */
658
+ function newestFirst(a, b) {
659
+ if (a.sentAt !== b.sentAt)
660
+ return a.sentAt < b.sentAt ? 1 : -1;
661
+ return b.id - a.id;
662
+ }
569
663
  /**
570
664
  * The sync note for unread inbox messages cached without bodies. Exported so
571
665
  * ofw_sync_messages can rewrite it after a confirmed open of some of them —
@@ -575,6 +669,49 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
575
669
  export function unreadInboxNote(count) {
576
670
  return `${count} unread inbox messages cached without bodies. Call ofw_get_message(id) to read them — this will mark them as read on OFW.`;
577
671
  }
672
+ const MARKED_READ_LEAD = 'MARKED READ on OurFamilyWizard by this sync:';
673
+ /**
674
+ * The note line for messages this sync marked read. Exported, like
675
+ * unreadInboxNote, so ofw_sync_messages can rewrite it after a confirmed open.
676
+ */
677
+ export function markedReadNote(markedRead) {
678
+ const unexpected = markedRead.filter((m) => m.reason === 'unexpected').length;
679
+ return `${MARKED_READ_LEAD} ${markedRead.length} inbox message${markedRead.length === 1 ? '' : 's'} (ids ${markedRead.map((m) => m.id).join(', ')}). Each now carries a "First Viewed" time your co-parent can see; it cannot be undone.${unexpected > 0 ? ` ${unexpected} of them ${unexpected === 1 ? 'was' : 'were'} NOT requested (reason "unexpected").` : ''}`;
680
+ }
681
+ /** The top-level `warning` for messages this sync marked read. */
682
+ export function markedReadWarning(markedRead) {
683
+ const unexpected = markedRead.filter((m) => m.reason === 'unexpected').length;
684
+ return `WARNING: this sync marked ${markedRead.length} inbox message${markedRead.length === 1 ? '' : 's'} READ on OurFamilyWizard (see markedRead). Your co-parent can see the "First Viewed" time, and it cannot be undone.${unexpected > 0 ? ` ${unexpected} of them ${unexpected === 1 ? 'was' : 'were'} NOT requested: the list reported ${unexpected === 1 ? 'it' : 'them'} as already read, but the fetch stamped ${unexpected === 1 ? 'it' : 'them'}. Tell the user, and report this as a bug.` : ''}`;
685
+ }
686
+ /**
687
+ * Recompute everything in a sync result DERIVED from `markedRead` and
688
+ * `unreadInbox` — `warning`, `markedReadCount`, and their two note lines —
689
+ * from the arrays as they now stand. syncAll calls it once; ofw_sync_messages
690
+ * calls it again after a confirmed open adds to them, so one payload never
691
+ * carries two counts for the same thing. Other note lines keep their order.
692
+ */
693
+ export function refreshReadReporting(result) {
694
+ const markedRead = result.markedRead ?? [];
695
+ const notes = (result.note === undefined ? [] : result.note.split('\n\n'))
696
+ .filter((n) => !n.startsWith(MARKED_READ_LEAD) && !/^\d+ unread inbox messages cached without bodies\./.test(n));
697
+ const bodiless = result.unreadInbox.filter((h) => !h.bodyFetched).length;
698
+ if (bodiless > 0)
699
+ notes.push(unreadInboxNote(bodiless));
700
+ if (markedRead.length > 0)
701
+ notes.unshift(markedReadNote(markedRead));
702
+ result.note = notes.length > 0 ? notes.join('\n\n') : undefined;
703
+ if (result.note === undefined)
704
+ delete result.note;
705
+ result.markedReadCount = markedRead.length;
706
+ if (markedRead.length > 0) {
707
+ result.warning = markedReadWarning(markedRead);
708
+ result.markedRead = markedRead;
709
+ }
710
+ else {
711
+ delete result.warning;
712
+ delete result.markedRead;
713
+ }
714
+ }
578
715
  export async function syncAll(client, opts, store) {
579
716
  const requested = opts.folders ?? ['inbox', 'sent', 'drafts'];
580
717
  // Drafts go FIRST. They are the only folder a destructive tool
@@ -601,6 +738,8 @@ export async function syncAll(client, opts, store) {
601
738
  const ids = await resolveFolderIds(client, store);
602
739
  const synced = {};
603
740
  let unreadInbox = [];
741
+ const newMessages = [];
742
+ const markedRead = [];
604
743
  let done = true;
605
744
  let draftsUnverified = false;
606
745
  const refreshed = [];
@@ -628,6 +767,8 @@ export async function syncAll(client, opts, store) {
628
767
  }, store);
629
768
  record('inbox', r.verified, r.synced);
630
769
  unreadInbox = r.unread;
770
+ newMessages.push(...r.newMessages);
771
+ markedRead.push(...r.markedRead);
631
772
  if (!r.done)
632
773
  done = false;
633
774
  }
@@ -639,6 +780,8 @@ export async function syncAll(client, opts, store) {
639
780
  budget,
640
781
  }, store);
641
782
  record('sent', r.verified, r.synced);
783
+ // A sent detail never stamps OUR read state, so it adds no markedRead.
784
+ newMessages.push(...r.newMessages);
642
785
  if (!r.done)
643
786
  done = false;
644
787
  }
@@ -662,9 +805,6 @@ export async function syncAll(client, opts, store) {
662
805
  if (draftsUnverified) {
663
806
  notes.push('The drafts folder was NOT checked against OurFamilyWizard on this call (the request budget ran out first), so no drafts count is reported and the cached drafts are marked "unverified". Cached draft bodies may be behind the server. Call ofw_sync_messages again — or ofw_sync_messages with folders:["drafts"] — before editing or deleting a draft.');
664
807
  }
665
- if (unreadInbox.length > 0) {
666
- notes.push(unreadInboxNote(unreadInbox.length));
667
- }
668
808
  if (notRefreshed.length > 0) {
669
809
  notes.push(`NOT checked against OurFamilyWizard on this call: ${notRefreshed.join(', ')}. No count is reported for ${notRefreshed.length > 1 ? 'those folders' : 'that folder'} — absence of a count means "not looked at", not "no changes". Cached contents may be behind the server; call ofw_sync_messages again to finish, or ofw_check_freshness for a cheap live confirmation.`);
670
810
  }
@@ -672,14 +812,26 @@ export async function syncAll(client, opts, store) {
672
812
  notes.push('Paused after the request budget to stay within the hosting limit; more pages remain — call ofw_sync_messages again with the same arguments to resume where it left off and continue the backfill.');
673
813
  }
674
814
  const note = notes.length > 0 ? notes.join('\n\n') : undefined;
675
- return {
815
+ newMessages.sort(newestFirst);
816
+ // Key order is the emitted order: the warning first (a truncated read must
817
+ // hit it), counts before arrays, newMessages last. `warning` is declared
818
+ // here as a placeholder so refreshReadReporting fills it IN PLACE.
819
+ const result = {
820
+ warning: undefined,
676
821
  synced,
822
+ markedReadCount: 0,
823
+ newMessagesTotal: newMessages.length,
824
+ newMessagesTruncated: newMessages.length > NEW_MESSAGES_CAP,
677
825
  unreadInbox,
678
826
  done,
679
827
  syncComplete: done,
680
828
  refreshed,
681
829
  notRefreshed,
682
830
  ...(readingBlocked ? { bodiesWithheld: true } : {}),
683
- ...(note ? { note } : {}),
831
+ note,
832
+ markedRead,
833
+ newMessages: newMessages.slice(0, NEW_MESSAGES_CAP),
684
834
  };
835
+ refreshReadReporting(result);
836
+ return result;
685
837
  }
@@ -78,7 +78,8 @@ export const ApiRecipientSchema = z.looseObject({
78
78
  // viewed. Only the DETAIL endpoint (/pub/v3/messages/{id}) carries a real
79
79
  // timestamp; the LIST endpoint returns an epoch-zero PLACEHOLDER
80
80
  // ("1970-01-01T00:00:00") in the SAME field even for read messages (on the
81
- // list, read status lives in `showNeverViewed`, not the timestamp). So treat
81
+ // list, read status lives in the flags — `read` for inbox, `showNeverViewed`
82
+ // for sent; see scrapeSaysRead — not the timestamp). So treat
82
83
  // the epoch placeholder as "no real view time" — otherwise a list-sourced row
83
84
  // reports a bogus 1970 read time. A detail re-fetch is what fills in the truth.
84
85
  export function mapRecipients(items) {
@@ -122,15 +123,31 @@ export function reportsUnthreaded(detail) {
122
123
  return false;
123
124
  return detail.inReplyTo !== undefined || detail.showContext !== undefined;
124
125
  }
125
- // True when the once-scraped list flags themselves say the message is read.
126
- // `showNeverViewed === false` is OFW's reliable "has been viewed" signal (per
127
- // CLAUDE.md); `read === true` is the inbox list's own flag. Both are only ever
128
- // captured at first sight, so they can go stale — they raise `read` but never
129
- // lower it (see deriveRead).
130
- function scrapeSaysRead(listData) {
126
+ /**
127
+ * True when the once-scraped LIST flags themselves say the message is read.
128
+ * Both are only ever captured at first sight, so they can go stale — they
129
+ * raise `read` but never lower it (see deriveRead).
130
+ *
131
+ * - INBOX: only the inbox list's own `read === true` counts. Anything else —
132
+ * `read: false`, a missing `read`, a non-boolean — is UNREAD. On the inbox
133
+ * list `showNeverViewed` is NOT our read state: it is the sender-side
134
+ * "recipient never viewed" badge flag, and it comes back `false` on a
135
+ * brand-new message we have never opened. Treating it as read evidence
136
+ * once let a routine sync fetch an unread body, which stamped a
137
+ * co-parent-visible "First Viewed" time. Unknown must fail closed: a false
138
+ * "unread" costs a confirmation, a false "read" stamps the record.
139
+ * - SENT: `showNeverViewed === false` is the reliable "a recipient has viewed
140
+ * it" signal (or `read === true`) — unchanged.
141
+ *
142
+ * Exported for sync.ts, which applies the same rule to a list item before
143
+ * deciding whether a body fetch could stamp it.
144
+ */
145
+ export function scrapeSaysRead(folder, listData) {
131
146
  if (typeof listData !== 'object' || listData === null)
132
147
  return false;
133
148
  const ld = listData;
149
+ if (folder === 'inbox')
150
+ return ld.read === true;
134
151
  return ld.read === true || ld.showNeverViewed === false;
135
152
  }
136
153
  /**
@@ -150,7 +167,10 @@ function scrapeSaysRead(listData) {
150
167
  * counts. OFW co-parent threads are 1:1 — the sole inbox recipient is us —
151
168
  * so this is exact, not an approximation. Fetching the body marks the message
152
169
  * read on OFW, so a non-null `fetchedBodyAt` is also read=true. The stale
153
- * scrape flag is only a last-resort fallback.
170
+ * scrape flag is only a last-resort fallback, and for inbox it is the list's
171
+ * `read === true` ONLY — never `showNeverViewed`, which on the inbox list is
172
+ * the sender-side badge and reads `false` on a message we never opened
173
+ * (see scrapeSaysRead).
154
174
  * - SENT: "read" means a *recipient* has opened it — tracked via their
155
175
  * `viewedAt` (the detail endpoint's real timestamp) — never our own body
156
176
  * fetch, which is always set for sent messages.
@@ -172,9 +192,9 @@ function scrapeSaysRead(listData) {
172
192
  export function deriveRead(row) {
173
193
  const viewedByAnyone = row.recipients.some((r) => r.viewedAt !== null);
174
194
  if (row.folder === 'inbox') {
175
- return viewedByAnyone || row.fetchedBodyAt !== null || scrapeSaysRead(row.listData);
195
+ return viewedByAnyone || row.fetchedBodyAt !== null || scrapeSaysRead('inbox', row.listData);
176
196
  }
177
- return viewedByAnyone || scrapeSaysRead(row.listData);
197
+ return viewedByAnyone || scrapeSaysRead(row.folder, row.listData);
178
198
  }
179
199
  /**
180
200
  * Return the row augmented with an authoritative top-level `read` boolean and a
@@ -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';
@@ -286,6 +286,7 @@ async function unreadCandidates(cache) {
286
286
  /**
287
287
  * Fetch one unread inbox body and cache it — the request that marks it read.
288
288
  * Only ever called after the confirmation gate approved this exact message.
289
+ * Returns the `markedRead` entry the sync response reports for it.
289
290
  */
290
291
  async function openUnreadBody(client, cache, cached) {
291
292
  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 +299,10 @@ async function openUnreadBody(client, cache, cached) {
298
299
  if (Array.isArray(detail.files) && detail.files.length > 0) {
299
300
  await fetchAttachmentMetaForMessage(client, cached.id, detail.files, cache);
300
301
  }
302
+ return {
303
+ id: cached.id, subject: cached.subject, from: senderOf(cached), sentAt: cached.sentAt,
304
+ viewedAt: latestViewedAt(detail.recipients), reason: 'fetchUnreadBodies',
305
+ };
301
306
  }
302
307
  /**
303
308
  * OFW_CONFIRM_MARK_READ: before `ofw_get_message` fetches a body that would
@@ -2090,7 +2095,7 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2090
2095
  _meta: familyMeta('other'),
2091
2096
  // Destructive: fetchUnreadBodies:true stamps a co-parent-visible "First
2092
2097
  // 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.',
2098
+ 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
2099
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
2095
2100
  inputSchema: z.object({
2096
2101
  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 +2164,19 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2159
2164
  });
2160
2165
  if (gate)
2161
2166
  return gate;
2167
+ const markedRead = result.markedRead ?? [];
2162
2168
  for (const row of rows)
2163
- await openUnreadBody(client, cache, row);
2169
+ markedRead.push(await openUnreadBody(client, cache, row));
2170
+ result.markedRead = markedRead;
2164
2171
  }
2165
2172
  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
- }
2173
+ // unreadInbox keeps its PRE-sync meaning (these were unread when this
2174
+ // call began), so an opened message stays listed — now bodyFetched.
2175
+ // newMessages agrees, and the warning, markedReadCount and both note
2176
+ // lines are recomputed so one payload never carries two counts.
2177
+ result.unreadInbox = result.unreadInbox.map((hint) => (opened.has(hint.id) ? { ...hint, bodyFetched: true } : hint));
2178
+ result.newMessages = result.newMessages.map((m) => (opened.has(m.id) ? { ...m, bodyFetched: true } : m));
2179
+ refreshReadReporting(result);
2177
2180
  unreadBodies = { requested: true, fetched: true, opened: [...opened], ...(remaining > 0 ? { remaining } : {}) };
2178
2181
  }
2179
2182
  // Freshness of the cache AS OF this sync completing — so a paused call
@@ -2182,7 +2185,19 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2182
2185
  source: 'cache',
2183
2186
  folders: args.folders ?? ['inbox', 'sent', 'drafts'],
2184
2187
  });
2185
- return jsonResponse({ ...result, ...(unreadBodies ? { unreadBodies } : {}), freshness });
2188
+ // Emitted order is load-bearing (see "Paging state is emitted BEFORE the
2189
+ // data array" in CLAUDE.md): the warning first, so even a truncated read
2190
+ // learns that this sync marked messages read; the counts
2191
+ // (newMessagesTotal / newMessagesTruncated / markedReadCount) next; the
2192
+ // newMessages array LAST.
2193
+ const { warning, newMessages, ...rest } = result;
2194
+ return jsonResponse({
2195
+ ...(warning ? { warning } : {}),
2196
+ ...rest,
2197
+ ...(unreadBodies ? { unreadBodies } : {}),
2198
+ freshness,
2199
+ newMessages,
2200
+ });
2186
2201
  });
2187
2202
  server.registerTool('ofw_check_freshness', {
2188
2203
  _meta: familyMeta('other'),
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.2'; // x-release-please-version
7
+ export const VERSION = '2.27.4'; // x-release-please-version
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ofw-mcp",
3
- "version": "2.27.2",
3
+ "version": "2.27.4",
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)",
@@ -34,7 +34,7 @@
34
34
  "typecheck": "tsc -p tsconfig.json --noEmit"
35
35
  },
36
36
  "dependencies": {
37
- "@chrischall/mcp-utils": "^3.6.0",
37
+ "@chrischall/mcp-utils": "^3.7.2",
38
38
  "@fetchproxy/bootstrap": "^3.6.2",
39
39
  "@modelcontextprotocol/server": "^2.3.0",
40
40
  "dotenv": "^18.0.0",
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.2",
9
+ "version": "2.27.4",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "ofw-mcp",
14
- "version": "2.27.2",
14
+ "version": "2.27.4",
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. |
@@ -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