ofw-mcp 2.27.4 → 2.28.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.
@@ -402,6 +402,9 @@ export class OFWCacheCore {
402
402
  const r = this.db.get('SELECT value FROM meta WHERE key = ?', [key]);
403
403
  return r ? r.value : null;
404
404
  }
405
+ deleteMeta(key) {
406
+ this.db.run('DELETE FROM meta WHERE key = ?', [key]);
407
+ }
405
408
  setMeta(key, value) {
406
409
  this.db.run('INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value', [key, value]);
407
410
  }
@@ -548,6 +551,9 @@ export class LocalCacheStore {
548
551
  async getMeta(key) {
549
552
  return this.core.getMeta(key);
550
553
  }
554
+ async deleteMeta(key) {
555
+ this.core.deleteMeta(key);
556
+ }
551
557
  async setMeta(key, value) {
552
558
  this.core.setMeta(key, value);
553
559
  }
package/dist/read-days.js CHANGED
@@ -25,6 +25,12 @@
25
25
  // An unparseable token fails CLOSED (every day blocked) with a stderr warning:
26
26
  // someone who wrote "Thrusday" meant to restrict reading, and silently
27
27
  // ignoring the typo would keep reading on the day they meant to keep clear.
28
+ //
29
+ // `overrideNoReadDay` is the one way past this, per call, for when the user
30
+ // explicitly asks to read anyway. It lifts ONLY the day restriction: the
31
+ // mark-read gates (OFW_ALLOW_MARK_READ, OFW_CONFIRM_MARK_READ, sync's
32
+ // fetchUnreadBodies) apply exactly as on a reading day, and each use is logged
33
+ // through auditReadOverride.
28
34
  import { readEnvVar } from '@chrischall/mcp-utils';
29
35
  import { displayTimeZone } from './timestamps.js';
30
36
  const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
@@ -121,7 +127,22 @@ export function readingBlockedToday(now = new Date()) {
121
127
  today: today.date,
122
128
  weekday: WEEKDAY_LABELS[today.weekday],
123
129
  timeZone,
124
- reason: `${reason} You may see that messages arrived, who sent them, when, and their subjects — but message bodies and attachments are withheld, and nothing may be marked read on OurFamilyWizard. This is a deployment setting; no per-call argument can override it.`,
130
+ reason: `${reason} You may see that messages arrived, who sent them, when, and their subjects — but message bodies and attachments are withheld, and nothing may be marked read on OurFamilyWizard. This is a deployment setting: respect it. Only if the user has explicitly asked to read anyway today, pass overrideNoReadDay:true to ofw_get_message, ofw_list_messages or ofw_sync_messages. Attachments stay withheld either way.`,
125
131
  nextReadableDay,
126
132
  };
127
133
  }
134
+ /** What a response that used the override says about itself. */
135
+ export const READ_OVERRIDE_NOTE = 'Read on a no-read day via override.';
136
+ /**
137
+ * Record one use of overrideNoReadDay. stderr is this server's only log — on a
138
+ * hosted deployment it is what `mcp-host logs` tails — so the audit line goes
139
+ * there, in one greppable, parseable shape. Ids only: never subjects or bodies.
140
+ */
141
+ export function auditReadOverride(tool, messageIds, now = new Date()) {
142
+ console.error(`[ofw-mcp] AUDIT ${JSON.stringify({
143
+ event: 'no_read_day_override',
144
+ timestamp: now.toISOString(),
145
+ tool,
146
+ messageIds,
147
+ })}`);
148
+ }
package/dist/sync.js CHANGED
@@ -1,10 +1,11 @@
1
1
  import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
2
2
  import { z } from 'zod';
3
- import { ApiRecipientSchema, hasRealView, mapRecipients, scrapeSaysRead, threadedReplyTo } from './tools/_shared.js';
3
+ import { ApiRecipientSchema, draftReplyTarget, hasRealView, mapRecipients, scrapeSaysRead } from './tools/_shared.js';
4
+ import { clearReplyToSource, setReplyToSource } from './tools/reply-source.js';
4
5
  import { senderOf } from './tools/project.js';
5
6
  import { parseLenient } from '@chrischall/mcp-utils';
6
7
  import { displayTimeZone, nowNaiveWallClock, parseTimestampValue } from './timestamps.js';
7
- import { readingBlockedToday } from './read-days.js';
8
+ import { READ_OVERRIDE_NOTE, readingBlockedToday } from './read-days.js';
8
9
  // Each OFW message detail returns `files: [fileId, ...]`. We fetch the metadata
9
10
  // for each file id (cheap JSON call) so the model can see filenames/mime types
10
11
  // without downloading bytes. Bytes are pulled lazily by ofw_download_attachment.
@@ -230,6 +231,7 @@ async function walkPages(client, folder, folderId, opts, store) {
230
231
  break;
231
232
  }
232
233
  const detail = await fetchDetail(item, { subject: existing.subject, sentAt: existing.sentAt, from: senderOf(existing) }, 'GET /pub/v3/messages/{id} (body backfill)', false);
234
+ opts.onBodyFetched?.(item.id);
233
235
  toUpsert.push({
234
236
  ...existing,
235
237
  body: detail.body ?? '',
@@ -299,6 +301,7 @@ async function walkPages(client, folder, folderId, opts, store) {
299
301
  }
300
302
  // Reached for an unread inbox message only under fetchUnreadBodies.
301
303
  const detail = await fetchDetail(item, { subject: row.subject, sentAt: row.sentAt, from }, 'GET /pub/v3/messages/{id} (sync)', isInboxUnread);
304
+ opts.onBodyFetched?.(item.id);
302
305
  body = detail.body ?? '';
303
306
  fetchedBodyAt = new Date().toISOString();
304
307
  detailRecipients = detail.recipients;
@@ -380,6 +383,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
380
383
  stopAtCachedPage: true,
381
384
  fetchUnreadBodies: opts.fetchUnreadBodies,
382
385
  fetchBodies,
386
+ onBodyFetched: opts.onBodyFetched,
383
387
  budget,
384
388
  }, store);
385
389
  let synced = fwd.synced;
@@ -433,6 +437,7 @@ export async function syncMessageFolder(client, folder, folderId, opts, store) {
433
437
  stopAtCachedPage: false,
434
438
  fetchUnreadBodies: opts.fetchUnreadBodies,
435
439
  fetchBodies,
440
+ onBodyFetched: opts.onBodyFetched,
436
441
  budget,
437
442
  }, store);
438
443
  synced += bf.synced;
@@ -470,6 +475,14 @@ const DraftListResponseSchema = z.looseObject({ data: z.array(DraftListItemSchem
470
475
  const DraftDetailSchema = z.looseObject({
471
476
  body: z.string().optional(),
472
477
  subject: z.string().optional(),
478
+ // The reply linkage and recipients are read from the DETAIL, not the list
479
+ // item: the drafts list carries no replyToId/inReplyTo/showContext key at all
480
+ // (verified live 2026-11-08), so a row built from it hashed to a different
481
+ // revision than the save echo and lost the reply target.
482
+ replyToId: z.number().nullable().optional(),
483
+ inReplyTo: z.number().nullable().optional(),
484
+ showContext: z.boolean().optional(),
485
+ recipients: z.array(ApiRecipientSchema).optional(),
473
486
  });
474
487
  /**
475
488
  * Meta key holding whether the drafts cache has been compared against OFW.
@@ -594,26 +607,36 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
594
607
  // Fetch every draft's detail up front, still buffered. OFW's list
595
608
  // `date.dateTime` is NOT a reliable modification timestamp for drafts —
596
609
  // direct UI edits don't bump it — so we can't skip the detail fetch.
610
+ //
611
+ // Pre-sync state (S1 batch read) — for the synced-count comparison below,
612
+ // and as the reply-target fallback when a payload does not echo the linkage.
613
+ const ids = items.map((it) => it.id);
614
+ const existingById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
597
615
  const rows = [];
616
+ const replySources = [];
598
617
  for (const item of items) {
599
618
  if (!b.take())
600
619
  return defer();
601
620
  const detail = parseLenient(DraftDetailSchema, await client.request('GET', `/pub/v3/messages/${item.id}`), { label: 'ofw-mcp', context: 'GET /pub/v3/messages/{id} (drafts sync)' });
621
+ // The same rule ofw_save_draft and the freshness snapshot apply
622
+ // (draftReplyTarget), so the revision a read reports matches the one the
623
+ // save returned for the same server state.
624
+ const reply = draftReplyTarget([detail, item], existingById.get(item.id)?.replyToId ?? null);
602
625
  rows.push({
603
626
  id: item.id,
604
627
  subject: detail.subject ?? item.subject ?? '(no subject)',
605
628
  body: detail.body ?? '',
606
- recipients: mapRecipients(item.recipients),
607
- replyToId: threadedReplyTo(item),
629
+ recipients: mapRecipients(detail.recipients ?? item.recipients),
630
+ replyToId: reply.replyToId,
608
631
  modifiedAt: item.date?.dateTime ?? nowNaiveWallClock(),
609
632
  listData: item,
610
633
  });
634
+ replySources.push(reply.replyToSource);
611
635
  }
612
- // Budget funded the whole walk — apply atomically. Batch reads (S1) snapshot
613
- // pre-upsert state for the synced-count comparison and stale-row eviction.
614
- const ids = items.map((it) => it.id);
615
- const existingById = new Map((await store.getDrafts(ids)).map((d) => [d.id, d]));
636
+ // Budget funded the whole walk — apply atomically.
616
637
  await store.upsertDrafts(rows);
638
+ for (const [i, row] of rows.entries())
639
+ await setReplyToSource(store, row.id, replySources[i]);
617
640
  // If a stale `messages` row exists for a draft id (cached by a prior
618
641
  // ofw_get_message call before the drafts table knew about this id), evict it.
619
642
  // The drafts table is the source of truth for drafts.
@@ -633,8 +656,10 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
633
656
  const seenIds = new Set(ids);
634
657
  const vanished = (await store.listDraftIds()).filter((id) => !seenIds.has(id));
635
658
  await inferReplacedDraftLineage(store, vanished, rows.filter((r) => !existingById.has(r.id)));
636
- for (const id of vanished)
659
+ for (const id of vanished) {
637
660
  await store.deleteDraft(id);
661
+ await clearReplyToSource(store, id);
662
+ }
638
663
  // The complete walk fetched every draft's DETAIL and reconciled deletions, so
639
664
  // the cache is now known-equal to the server. Only here is `synced: 0`
640
665
  // truthful as "verified no changes" — and only here may reads report the
@@ -730,7 +755,11 @@ export async function syncAll(client, opts, store) {
730
755
  const budget = makeBudget(opts.maxRequests ?? Number.POSITIVE_INFINITY);
731
756
  // Decided HERE, not by each caller, so every path into a sync — the tool,
732
757
  // a read's autoRefresh, ofw_status — honours a no-read day (read-days.ts).
733
- const readingBlocked = readingBlockedToday() !== null;
758
+ const noReadDay = readingBlockedToday() !== null;
759
+ const overriding = noReadDay && opts.overrideNoReadDay === true;
760
+ const readingBlocked = noReadDay && !overriding;
761
+ const bodyFetchedIds = [];
762
+ const onBodyFetched = (id) => { bodyFetchedIds.push(id); };
734
763
  // resolveFolderIds always makes exactly one request; the tool guarantees
735
764
  // maxRequests >= 1, so this unit is always available (result intentionally
736
765
  // ignored — we account for it without a branch that can't be reached).
@@ -762,6 +791,7 @@ export async function syncAll(client, opts, store) {
762
791
  const r = await syncMessageFolder(client, 'inbox', ids.inbox, {
763
792
  fetchUnreadBodies: !readingBlocked && (opts.fetchUnreadBodies ?? false),
764
793
  fetchBodies: !readingBlocked,
794
+ onBodyFetched,
765
795
  deep: opts.deep ?? false,
766
796
  budget,
767
797
  }, store);
@@ -776,6 +806,7 @@ export async function syncAll(client, opts, store) {
776
806
  const r = await syncMessageFolder(client, 'sent', ids.sent, {
777
807
  fetchUnreadBodies: false,
778
808
  fetchBodies: !readingBlocked,
809
+ onBodyFetched,
779
810
  deep: opts.deep ?? false,
780
811
  budget,
781
812
  }, store);
@@ -828,6 +859,7 @@ export async function syncAll(client, opts, store) {
828
859
  refreshed,
829
860
  notRefreshed,
830
861
  ...(readingBlocked ? { bodiesWithheld: true } : {}),
862
+ ...(overriding ? { readOverride: true, readOverrideNote: READ_OVERRIDE_NOTE, readOverrideMessageIds: bodyFetchedIds } : {}),
831
863
  note,
832
864
  markedRead,
833
865
  newMessages: newMessages.slice(0, NEW_MESSAGES_CAP),
@@ -102,6 +102,35 @@ export function hasRealView(recipients) {
102
102
  export function threadedReplyTo(detail) {
103
103
  return detail.replyToId ?? detail.inReplyTo ?? null;
104
104
  }
105
+ /**
106
+ * The ONE rule for a draft's reply target, used by every path that builds a
107
+ * draft's content (save echo, drafts sync, the freshness snapshot, the
108
+ * destructive-draft guard), so the revision hashed from it cannot depend on
109
+ * which path produced it.
110
+ *
111
+ * The first echo that names a target wins (`server`). When none does, the
112
+ * `fallback` (the cached row's target, or the one just posted) is kept as
113
+ * `cache` — unless an echo POSITIVELY reports the draft unthreaded
114
+ * ({@link reportsUnthreaded}), in which case OFW's answer stands and nothing
115
+ * is resurrected.
116
+ *
117
+ * Why the fallback exists: the drafts LIST payload carries no `replyToId`,
118
+ * `inReplyTo` or `showContext` key at all (verified live 2026-11-08), so a
119
+ * cached row built from it read `replyToId: null` for a draft whose detail said
120
+ * `inReplyTo: 574607114` — and its revision disagreed with the one the save
121
+ * returned. Silence about the linkage is not evidence it is gone.
122
+ */
123
+ export function draftReplyTarget(echoes, fallback) {
124
+ for (const echo of echoes) {
125
+ const target = threadedReplyTo(echo);
126
+ if (target !== null)
127
+ return { replyToId: target, replyToSource: 'server' };
128
+ }
129
+ if (fallback !== null && !echoes.some(reportsUnthreaded)) {
130
+ return { replyToId: fallback, replyToSource: 'cache' };
131
+ }
132
+ return { replyToId: null, replyToSource: null };
133
+ }
105
134
  /** True when the payload positively reports the message as threaded. */
106
135
  export function reportsThreaded(detail) {
107
136
  return threadedReplyTo(detail) !== null || detail.showContext === true;
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { parseLenient } from '@chrischall/mcp-utils';
3
- import { ApiRecipientSchema, mapRecipients, threadedReplyTo } from './_shared.js';
3
+ import { ApiRecipientSchema, draftReplyTarget, mapRecipients } from './_shared.js';
4
4
  /** Thrown when the freshness check itself could not be completed. */
5
5
  export class DraftFreshnessError extends Error {
6
6
  }
@@ -52,6 +52,7 @@ const ServerDraftSchema = z.looseObject({
52
52
  // that disagreed about the same draft.
53
53
  replyToId: z.number().nullable().optional(),
54
54
  inReplyTo: z.number().nullable().optional(),
55
+ showContext: z.boolean().optional(),
55
56
  recipients: z.array(ApiRecipientSchema).optional(),
56
57
  // Attachment fileIds — read so send-by-draft carries the draft's
57
58
  // attachments onto the sent message (see DraftContent.files).
@@ -89,7 +90,7 @@ function isNotFound(e) {
89
90
  * the narrower type (the catch blocks read only `.message`, which every Error
90
91
  * carries).
91
92
  */
92
- export async function fetchMessageSnapshot(client, id) {
93
+ export async function fetchMessageSnapshot(client, id, fallbackReplyTo = null) {
93
94
  let raw;
94
95
  try {
95
96
  raw = await client.request('GET', `/pub/v3/messages/${id}`);
@@ -109,17 +110,22 @@ export async function fetchMessageSnapshot(client, id) {
109
110
  context: 'GET /pub/v3/messages/{id} (draft freshness check)',
110
111
  mode: 'strict',
111
112
  });
113
+ // The same reply-target rule as the save echo and the drafts sync
114
+ // (draftReplyTarget), with the cached target as the fallback, so a detail
115
+ // that does not echo the linkage hashes exactly like the cached row.
116
+ const reply = draftReplyTarget([detail], fallbackReplyTo);
112
117
  return {
113
118
  content: {
114
119
  subject: detail.subject ?? '',
115
120
  body: detail.body ?? '',
116
- replyToId: threadedReplyTo(detail),
121
+ replyToId: reply.replyToId,
117
122
  recipients: mapRecipients(detail.recipients),
118
123
  ...(detail.files !== undefined ? { files: detail.files } : {}),
119
124
  },
120
125
  folderId: detail.folder?.id === undefined ? null : String(detail.folder.id),
121
126
  folderName: detail.folder?.name ?? null,
122
127
  dateTime: detail.date?.dateTime ?? null,
128
+ replyToSource: reply.replyToSource,
123
129
  };
124
130
  }
125
131
  /**
@@ -130,8 +136,8 @@ export async function fetchMessageSnapshot(client, id) {
130
136
  * the callers in messages.ts abort on ALL of them: a freshness check that could
131
137
  * not run must never wave the write through.
132
138
  */
133
- export async function fetchServerDraft(client, id) {
134
- return (await fetchMessageSnapshot(client, id))?.content ?? null;
139
+ export async function fetchServerDraft(client, id, fallbackReplyTo = null) {
140
+ return (await fetchMessageSnapshot(client, id, fallbackReplyTo))?.content ?? null;
135
141
  }
136
142
  /**
137
143
  * The fields whose divergence constitutes a REAL conflict — the actual message
@@ -210,7 +210,10 @@ async function probeOne(client, prepared, map, draftKey, heldFiles) {
210
210
  const { id, cachedDraft } = prepared;
211
211
  let snapshot;
212
212
  try {
213
- snapshot = await fetchMessageSnapshot(client, id);
213
+ // The cached target is the fallback for a detail that does not echo the
214
+ // linkage, the same rule the drafts sync applies, so an unchanged draft
215
+ // reports cacheRevision === serverRevision.
216
+ snapshot = await fetchMessageSnapshot(client, id, cachedDraft?.replyToId ?? null);
214
217
  }
215
218
  catch (e) {
216
219
  return {