ofw-mcp 2.27.0 → 2.27.2

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,3 +1,4 @@
1
+ import { clearHeldFiles, getHeldFiles, setHeldFiles } from './tools/held-attachments.js';
1
2
  import { z } from 'zod';
2
3
  import { ApiRecipientSchema, hasRealView, mapRecipients, threadedReplyTo } from './tools/_shared.js';
3
4
  import { parseLenient } from '@chrischall/mcp-utils';
@@ -434,6 +435,43 @@ export async function getFolderVerifiedAt(store, folder) {
434
435
  export async function markFolderVerified(store, folder, at = new Date().toISOString()) {
435
436
  await store.setMeta(folderVerifiedAtKey(folder), at);
436
437
  }
438
+ /**
439
+ * A draft replaced OUTSIDE this cache — by another session or deployment
440
+ * (create-then-delete there), or in the web app — vanishes here while a new
441
+ * id appears, and the stable `draftKey` plus the attachments held for it would
442
+ * be lost with the old id. When EXACTLY ONE new draft carries the vanished
443
+ * draft's subject, body and reply target, it is the same message: move the
444
+ * key and the held files across, marked `draft_key_inferred:<id>`. Anything
445
+ * ambiguous (two candidates, changed content, a new draft that already has a
446
+ * lineage) is left unlinked — a wrong guess would hand one message's
447
+ * identity and attachments to another, which is worse than none.
448
+ */
449
+ async function inferReplacedDraftLineage(store, vanishedIds, newRows) {
450
+ if (vanishedIds.length === 0 || newRows.length === 0)
451
+ return;
452
+ for (const goneId of vanishedIds) {
453
+ // A vanished id came from this cache's own draft list, so its row exists.
454
+ const gone = (await store.getDraft(goneId));
455
+ const key = (await store.getDraftLineageById(goneId))?.draftKey;
456
+ const held = await getHeldFiles(store, goneId);
457
+ if (!key && held.length === 0)
458
+ continue;
459
+ const matches = newRows.filter((r) => r.subject === gone.subject && r.body === gone.body && r.replyToId === gone.replyToId);
460
+ if (matches.length !== 1)
461
+ continue;
462
+ const target = matches[0];
463
+ if (await store.getDraftLineageById(target.id))
464
+ continue;
465
+ if (key) {
466
+ await store.recordDraftLineage({ id: target.id, draftKey: key, previousId: goneId, recordedAt: new Date().toISOString() });
467
+ await store.setMeta(`draft_key_inferred:${target.id}`, '1');
468
+ }
469
+ if (held.length > 0) {
470
+ await setHeldFiles(store, target.id, [...held, ...(await getHeldFiles(store, target.id))]);
471
+ await clearHeldFiles(store, goneId);
472
+ }
473
+ }
474
+ }
437
475
  export async function syncDrafts(client, draftsFolderId, store, budget) {
438
476
  // No budget → unbounded (local stdio): identical to the original walk.
439
477
  const b = budget ?? makeBudget(Number.POSITIVE_INFINITY);
@@ -514,10 +552,10 @@ export async function syncDrafts(client, draftsFolderId, store, budget) {
514
552
  }
515
553
  }
516
554
  const seenIds = new Set(ids);
517
- for (const id of await store.listDraftIds()) {
518
- if (!seenIds.has(id))
519
- await store.deleteDraft(id);
520
- }
555
+ const vanished = (await store.listDraftIds()).filter((id) => !seenIds.has(id));
556
+ await inferReplacedDraftLineage(store, vanished, rows.filter((r) => !existingById.has(r.id)));
557
+ for (const id of vanished)
558
+ await store.deleteDraft(id);
521
559
  // The complete walk fetched every draft's DETAIL and reconciled deletions, so
522
560
  // the cache is now known-equal to the server. Only here is `synced: 0`
523
561
  // truthful as "verified no changes" — and only here may reads report the
@@ -58,7 +58,7 @@ export function jsonErrorResponse(data) {
58
58
  // call. Loose: unknown keys pass through (and survive into cached listData).
59
59
  export const ApiRecipientSchema = z.looseObject({
60
60
  // Live OFW payloads key the recipient's id as `userId` (verified against a
61
- // real /pub/v3/messages record: `recipients[].user.userId === 3039201`). An
61
+ // real /pub/v3/messages record: `recipients[].user.userId === 2000001`). An
62
62
  // earlier guess read `id`, which is absent — so every normalized recipient
63
63
  // came out with `userId: 0`, breaking any "find my own recipient" match. Both
64
64
  // are accepted (userId first, id fallback) so a backend that ever returns `id`
@@ -29,9 +29,16 @@ export function fnv1a64(s) {
29
29
  * STALE. Fields are length-prefixed so content cannot shift across a field
30
30
  * boundary without changing the hash.
31
31
  */
32
- export function draftRevision(d) {
32
+ export function draftRevision(d, heldFiles = []) {
33
33
  const ids = [...new Set(d.recipients.map((r) => r.userId))].sort((a, b) => a - b);
34
34
  const parts = [d.subject, d.body, String(d.replyToId ?? ''), ids.join(',')];
35
+ // Files OFW will not keep on a draft are HELD by this server (see
36
+ // held-attachments.ts) and are part of what the caller is editing, so they
37
+ // move the revision. Only when there are some: a draft with none hashes
38
+ // exactly as it always has, so tokens already in callers' hands stay valid.
39
+ const held = [...new Set(heldFiles)].sort((a, b) => a - b);
40
+ if (held.length > 0)
41
+ parts.push(`files:${held.join(',')}`);
35
42
  return `r1:${fnv1a64(parts.map((p) => `${p.length}:${p}`).join('|'))}`;
36
43
  }
37
44
  const ServerDraftSchema = z.looseObject({
@@ -181,6 +188,7 @@ function diffFields(a, b) {
181
188
  */
182
189
  export function checkDraftFreshness(input) {
183
190
  const { server, cached, expectedRevision } = input;
191
+ const held = input.heldFiles ?? [];
184
192
  if (server === null) {
185
193
  return {
186
194
  verdict: 'MISSING',
@@ -189,14 +197,18 @@ export function checkDraftFreshness(input) {
189
197
  };
190
198
  }
191
199
  if (expectedRevision !== undefined) {
192
- const actual = draftRevision(server);
193
- if (expectedRevision === actual) {
200
+ const actual = draftRevision(server, held);
201
+ // A token with or without the held files both name this server state:
202
+ // the guard protects what is ON OurFamilyWizard, and the held set is this
203
+ // server's own bookkeeping — a token minted before a file was held must
204
+ // not read as a conflict.
205
+ if (expectedRevision === actual || expectedRevision === draftRevision(server)) {
194
206
  return { verdict: 'FRESH', reason: 'expectedRevision matches the live server draft.', changedFields: [] };
195
207
  }
196
208
  // Token mismatch. When the caller's token is the one WE cached, we can name
197
209
  // exactly what drifted — and if that is metadata alone, it is our own
198
210
  // post-save normalization, not a conflict.
199
- if (cached !== null && draftRevision(cached) === expectedRevision) {
211
+ if (cached !== null && (draftRevision(cached, held) === expectedRevision || draftRevision(cached) === expectedRevision)) {
200
212
  const changedFields = diffFields(server, cached);
201
213
  if (substantiveChanges(changedFields).length === 0) {
202
214
  return {
@@ -252,7 +264,7 @@ export function staleDraftPayload(input) {
252
264
  reason: verdict.reason,
253
265
  ...(verdict.changedFields.length > 0 ? { changedFields: verdict.changedFields } : {}),
254
266
  ...(server !== null
255
- ? { serverBody: server.body, serverSubject: server.subject, serverRevision: draftRevision(server) }
267
+ ? { serverBody: server.body, serverSubject: server.subject, serverRevision: draftRevision(server, input.heldFiles ?? []) }
256
268
  : {}),
257
269
  ...(cached !== null ? { cachedBody: cached.body } : {}),
258
270
  recovery: server === null
@@ -0,0 +1,50 @@
1
+ // Attachments HELD against a draft, because OurFamilyWizard will not keep
2
+ // them on one.
3
+ //
4
+ // Verified live 2026-11-06: a draft saved with fileIds — PRIVATE or SHARED,
5
+ // by create OR by the web app's own in-place update — always comes back
6
+ // `files: []`, and the web app's compose screen never loads files from a
7
+ // draft (its attachment list starts empty and only ever holds what was added
8
+ // in that session; they go out with the final send). Before this module,
9
+ // ofw_save_draft posted the ids, OFW discarded them, and the response both
10
+ // warned that they were missing AND claimed "attachments (N)" were carried
11
+ // over — while the next edit posted `[]` and lost them for good.
12
+ //
13
+ // So the ids live here, in the cache's `meta` table keyed by draft id, moved
14
+ // to the new id on every create-then-delete replace, folded into the draft's
15
+ // `revision`, and attached by ofw_send_message when the draft is sent.
16
+ const key = (draftId) => `draft_held_files:${draftId}`;
17
+ /** De-duplicate, preserving first-seen order. */
18
+ export function uniqueIds(ids) {
19
+ return [...new Set(ids)];
20
+ }
21
+ /** The file ids held for a draft (empty when none). */
22
+ export async function getHeldFiles(cache, draftId) {
23
+ const raw = await cache.getMeta(key(draftId));
24
+ if (!raw)
25
+ return [];
26
+ try {
27
+ const parsed = JSON.parse(raw);
28
+ return Array.isArray(parsed) ? parsed.filter((v) => Number.isInteger(v)) : [];
29
+ }
30
+ catch {
31
+ return [];
32
+ }
33
+ }
34
+ /** Replace the held set for a draft. An empty set clears it. */
35
+ export async function setHeldFiles(cache, draftId, ids) {
36
+ await cache.setMeta(key(draftId), JSON.stringify(uniqueIds(ids)));
37
+ }
38
+ /** Forget a draft's held files (sent, deleted, or replaced). */
39
+ export async function clearHeldFiles(cache, draftId) {
40
+ await cache.setMeta(key(draftId), '[]');
41
+ }
42
+ /** Held sets for several drafts at once, for list-shaped reads. */
43
+ export async function heldFilesFor(cache, draftIds) {
44
+ const out = new Map();
45
+ for (const id of draftIds)
46
+ out.set(id, await getHeldFiles(cache, id));
47
+ return out;
48
+ }
49
+ /** The note every response about held files carries. */
50
+ export const HELD_NOTE = 'OurFamilyWizard drafts do not store attachments, so these files are held with this draft by this server and attached when you send it with ofw_send_message (draftId). They are not visible on the draft in the OurFamilyWizard web app.';
@@ -1,3 +1,4 @@
1
+ import { getHeldFiles } from './held-attachments.js';
1
2
  import { resolveFolderIds } from '../sync.js';
2
3
  import { draftRevision, fetchMessageSnapshot } from './draft-freshness.js';
3
4
  import { deriveRead } from './_shared.js';
@@ -194,7 +195,7 @@ export async function probeIds(client, store, ids, opts) {
194
195
  items.push({ id: p.id, skipped: true, reason: 'WOULD_MARK_READ', note: SKIP_NOTE });
195
196
  continue;
196
197
  }
197
- const probe = await probeOne(client, p, map, keyById.get(p.id) ?? null);
198
+ const probe = await probeOne(client, p, map, keyById.get(p.id) ?? null, await getHeldFiles(store, p.id));
198
199
  requests += probe.requests;
199
200
  items.push(probe.item);
200
201
  }
@@ -205,7 +206,7 @@ export async function probeIds(client, store, ids, opts) {
205
206
  * back as an error item, because a check that failed must never read as
206
207
  * "in sync".
207
208
  */
208
- async function probeOne(client, prepared, map, draftKey) {
209
+ async function probeOne(client, prepared, map, draftKey, heldFiles) {
209
210
  const { id, cachedDraft } = prepared;
210
211
  let snapshot;
211
212
  try {
@@ -224,8 +225,10 @@ async function probeOne(client, prepared, map, draftKey) {
224
225
  };
225
226
  }
226
227
  const state = classifyState(snapshot, map);
227
- const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft);
228
- const serverRevision = snapshot === null ? null : draftRevision(snapshot.content);
228
+ // Both sides carry the files held for this draft (held-attachments.ts), so
229
+ // the reported revisions match the one ofw_save_draft returned.
230
+ const cacheRevision = cachedDraft === null ? null : draftRevision(cachedDraft, heldFiles);
231
+ const serverRevision = snapshot === null ? null : draftRevision(snapshot.content, heldFiles);
229
232
  const viewedAt = snapshot?.content.recipients.find((r) => r.viewedAt !== null)?.viewedAt ?? null;
230
233
  // `inSync` compares the CACHED DRAFT against the server, and it is FALSE the
231
234
  // moment the entity stops being what the cache says it is — even when every