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.
@@ -9,6 +9,7 @@ import { getFolderVerifiedAt } from '../sync.js';
9
9
  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
+ import { clearHeldFiles, getHeldFiles, heldFilesFor, HELD_NOTE, setHeldFiles, uniqueIds } from './held-attachments.js';
12
13
  import { buildInlineDelivery, MAX_INLINE_BYTES, tryExtract } from './delivery.js';
13
14
  import { resolveDownloadMime, resolveSaveDest } from './attachments.js';
14
15
  import { getAllowMarkRead, getConfirmMarkRead, getAttachmentsDir, getAutoRefreshStaleReads, getDefaultInlineAttachments, getFetchUnreadBodies, getSyncMaxRequests, getWriteMode, } from '../config.js';
@@ -21,6 +22,27 @@ import { MESSAGE_VIEWS, senderOf, viewDrafts, viewMessages, viewOne } from './pr
21
22
  import { resolveView, viewParam } from '@chrischall/mcp-utils';
22
23
  import { displayTimeZone, formatInstant, normalizeTimestampsInValue, nowNaiveWallClock, toNaiveWallClock } from '../timestamps.js';
23
24
  import { readingBlockedToday } from '../read-days.js';
25
+ /** Why a draft has no draftKey — said instead of a bare null. */
26
+ export const DRAFT_KEY_NULL_REASON = 'No draftKey: this draft was not saved through this server\'s cache — it may have been created in the OurFamilyWizard web app or replaced from another session — so its lineage is unknown. The next ofw_save_draft on it starts a new key.';
27
+ /** `{draftKey, draftKeyInferred?}` or `{draftKey: null, draftKeyReason}` for one draft. */
28
+ async function describeDraftKey(cache, id) {
29
+ const row = await cache.getDraftLineageById(id);
30
+ if (!row)
31
+ return { draftKey: null, draftKeyReason: DRAFT_KEY_NULL_REASON };
32
+ return { draftKey: row.draftKey, ...((await cache.getMeta(`draft_key_inferred:${id}`)) === '1' ? { draftKeyInferred: true } : {}) };
33
+ }
34
+ /** The ids whose draftKey was carried over by inference (see syncDrafts). */
35
+ async function inferredDraftKeys(cache, ids) {
36
+ const out = new Set();
37
+ for (const id of ids)
38
+ if ((await cache.getMeta(`draft_key_inferred:${id}`)) === '1')
39
+ out.add(id);
40
+ return out;
41
+ }
42
+ /** Held file ids → `{fileId, fileName, held: true}`, names from the attachment cache (null when unknown). */
43
+ async function describeHeld(cache, ids) {
44
+ return Promise.all(ids.map(async (fileId) => ({ fileId, fileName: (await cache.getAttachment(fileId))?.fileName ?? null, held: true })));
45
+ }
24
46
  /** A confirmation preview raised from inside a blob consume — carries it out. */
25
47
  class GateHalt extends Error {
26
48
  response;
@@ -48,6 +70,8 @@ const SentDetailSchema = z.looseObject({
48
70
  replyToId: z.number().nullable().optional(),
49
71
  inReplyTo: z.number().nullable().optional(),
50
72
  showContext: z.boolean().optional(),
73
+ // What OFW actually attached — checked against what was sent.
74
+ files: z.array(z.number()).optional(),
51
75
  });
52
76
  const SavedDraftDetailSchema = z.looseObject({
53
77
  subject: z.string().optional(),
@@ -623,12 +647,13 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
623
647
  const draftRow = await cache.getDraft(id);
624
648
  if (draftRow !== null) {
625
649
  const { freshness, serverConfirmed, cacheStatus } = await draftsFreshness(cache);
650
+ const held = await getHeldFiles(cache, draftRow.id);
626
651
  return jsonResponse({
627
652
  // Stable identity FIRST — the id below changes on every edit
628
653
  // (create-then-delete), so callers should key off draftKey. Null when
629
654
  // this draft was never written through this tool (e.g. authored in
630
655
  // the web app).
631
- draftKey: (await cache.getDraftLineageById(draftRow.id))?.draftKey ?? null,
656
+ ...(await describeDraftKey(cache, draftRow.id)),
632
657
  id: draftRow.id,
633
658
  folder: 'drafts',
634
659
  subject: draftRow.subject,
@@ -652,11 +677,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
652
677
  // the DRAFTS table, which is the source of truth for a draft id — the
653
678
  // echo duplicates it and adds a stale copy of nothing else.
654
679
  ...(view === 'compact' ? {} : { listData: draftRow.listData }),
655
- attachments: [],
680
+ // OFW keeps no files on a draft; these are the ones HELD for it here
681
+ // and attached when it is sent (held-attachments.ts).
682
+ attachments: await describeHeld(cache, held),
683
+ ...(held.length > 0 ? { attachmentsNote: HELD_NOTE } : {}),
656
684
  // Concurrency token — pass as expectedRevision to ofw_save_draft /
657
685
  // ofw_delete_draft / ofw_send_message to assert you are acting on
658
686
  // THIS version.
659
- revision: draftRevision(draftRow),
687
+ revision: draftRevision(draftRow, held),
660
688
  cacheStatus,
661
689
  // False = this draft's existence and unsent status are remembered from
662
690
  // a cache, not confirmed on OFW. Call ofw_check_freshness before
@@ -790,7 +818,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
790
818
  if (allowSend)
791
819
  server.registerTool('ofw_send_message', {
792
820
  _meta: familyMeta('send', { aliases: ['message', 'co-parent', 'reply', 'ofw'] }),
793
- description: 'Send a message via OurFamilyWizard — the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId — same thing). The tool re-reads the draft from OFW and sends the SERVER\'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers — subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it — or no longer exists (it may already have been SENT) — the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted — the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: when sending by draftId, the server draft\'s own attachments carry over automatically; myFileIDs (from ofw_upload_attachment) overrides or attaches files on a fresh compose. The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
821
+ description: 'Send a message via OurFamilyWizard — the ONE irreversible operation here, so it carries the strongest guard. TO SEND AN EXISTING DRAFT (the safe default): pass draftId (or messageId — same thing). The tool re-reads the draft from OFW and sends the SERVER\'S version, so what goes out is what is on OurFamilyWizard, not what this session remembers — subject/body act only as explicit overrides. It is guarded exactly like ofw_save_draft: pass expectedRevision to assert which version you are sending; if the draft changed on OFW since you read it — or no longer exists (it may already have been SENT) — the send is REFUSED with the current server content echoed back, and nothing goes out. RECIPIENTS: OurFamilyWizard does not persist recipients on drafts, so recipientIds is usually still required at send time (ids from ofw_get_profile). After the send is CONFIRMED (OFW returned the new message id and the re-fetched sent record matches what was posted), the source draft is deleted automatically; pass deleteDraftOnSuccess:false to keep it. On ANY failure or ambiguity the draft is never deleted — the response carries draftRetained:true with the reason. If the send request times out or drops without a definitive answer, the result is SEND_UNCONFIRMED: the message may already have been delivered, so do NOT retry until a sent-folder sync (or ourfamilywizard.com) shows it did not go out. TO COMPOSE FROM SCRATCH: supply subject/body/recipientIds with no draftId. If replyToId is provided (or inherited from the draft), the cache may rewrite it to the latest reply in the same thread (a note is included when this happens). ATTACHMENTS: OurFamilyWizard keeps no files on drafts, so when sending by draftId the files ofw_save_draft HELD for it are attached automatically; myFileIDs (from ofw_upload_attachment) overrides them, or attaches files on a fresh compose; inlineAttachments/blobKeys upload new ones. Files are attached as they are (PRIVATE files attach fine); new files are uploaded PRIVATE, only after the send is approved. The response verifies them against the sent message (attachments.verified/missing). The response leads with sentMessageId and the stable draftKey, and reports threaded (whether OFW actually linked the reply) and draftDeleted. ' + CONFIRM_NOTE,
794
822
  annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: true },
795
823
  inputSchema: z.object({
796
824
  subject: z.string().describe('Message subject. Required unless draftId/messageId is given (then it overrides the server draft\'s subject).').optional(),
@@ -897,10 +925,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
897
925
  replyParent = await cache.getMessage(resolvedReplyTo);
898
926
  chainRootId = replyParent?.chainRootId ?? replyParent?.id ?? requestedReplyTo;
899
927
  }
900
- // Attachments carry over from the SERVER draft the guard read — sending
901
- // "the draft as it exists on the server" includes its files, or the send
902
- // would silently strip them. Explicit myFileIDs still overrides.
903
- let myFileIDs = args.myFileIDs ?? serverDraft?.files ?? [];
928
+ // Attachments: the files HELD for this draft (OFW keeps none on a draft —
929
+ // held-attachments.ts) plus any the server draft does report. An explicit
930
+ // myFileIDs still overrides both.
931
+ const heldForDraft = draftRef !== undefined ? await getHeldFiles(cache, draftRef) : [];
932
+ let myFileIDs = args.myFileIDs ?? uniqueIds([...(serverDraft?.files ?? []), ...heldForDraft]);
904
933
  // ── Confirmation gate ────────────────────────────────────────────────
905
934
  // Everything above this line is a read. This is the ONE irreversible
906
935
  // operation in the server, and until here the only things between a
@@ -917,6 +946,10 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
917
946
  serverDraft?.recipients, cachedDraft?.recipients, replyParent?.recipients,
918
947
  ]);
919
948
  const unresolved = to.filter((r) => r.name === null).map((r) => r.userId);
949
+ // Files are attached as they are. A send keeps PRIVATE files (verified
950
+ // live: four PRIVATE fileIds all came back on the sent message), so no
951
+ // file is re-uploaded — a re-upload as SHARED would leave an extra,
952
+ // co-parent-visible copy in My Files for nothing.
920
953
  const attachments = await Promise.all(myFileIDs.map(async (fileId) => {
921
954
  const known = await cache.getAttachment(fileId);
922
955
  return { fileId, fileName: known?.fileName ?? null };
@@ -945,7 +978,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
945
978
  action: 'ofw.message.send',
946
979
  message: 'Review and confirm this OurFamilyWizard message. Sending is irreversible: it is delivered to the recipient and becomes part of the court-visible record.',
947
980
  target: draftRef !== undefined ? `draft:${draftRef}` : 'compose',
948
- ...(serverDraft != null ? { revision: draftRevision(serverDraft) } : {}),
981
+ ...(serverDraft != null ? { revision: draftRevision(serverDraft, heldForDraft) } : {}),
949
982
  payload: {
950
983
  subject, body, recipientIds, myFileIDs, replyToId: resolvedReplyTo, deleteDraftOnSuccess: deleteOnSuccess,
951
984
  ...(pending.length > 0
@@ -957,10 +990,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
957
990
  });
958
991
  if (gate)
959
992
  return gate;
960
- // Approved. Upload the new files (PRIVATE) now; a failure stops here,
961
- // before the send, naming whatever did upload.
993
+ // Approved. Upload the new files (PRIVATE — the send itself shares them
994
+ // with the recipient); a failure stops here, before the send, naming
995
+ // whatever did upload.
962
996
  const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
963
- client, cache, store: blobStore, nothingWas: 'sent',
997
+ client, cache, store: blobStore, nothingWas: 'sent', shareClass: 'PRIVATE',
964
998
  });
965
999
  myFileIDs = [...myFileIDs, ...newFiles.map((f) => f.fileId)];
966
1000
  let posted;
@@ -1002,7 +1036,26 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1002
1036
  let sentDraftKey = null;
1003
1037
  let threaded = false;
1004
1038
  let threadNote = null;
1039
+ let attachmentCheck = null;
1040
+ let attachmentNote = null;
1041
+ if (newId !== null && myFileIDs.length > 0) {
1042
+ const onMessage = Array.isArray(detail.files) ? detail.files : null;
1043
+ const missing = onMessage === null ? [] : myFileIDs.filter((id) => !onMessage.includes(id));
1044
+ attachmentCheck = {
1045
+ onMessage,
1046
+ verified: onMessage === null ? null : missing.length === 0,
1047
+ ...(missing.length > 0 ? { missing } : {}),
1048
+ };
1049
+ if (missing.length > 0) {
1050
+ attachmentNote = `WARNING: the message was SENT, but OurFamilyWizard did not attach fileId(s) ${missing.join(', ')}. It cannot be edited; send the missing file(s) in a follow-up message.`;
1051
+ }
1052
+ else if (onMessage === null) {
1053
+ attachmentNote = 'NOTE: OurFamilyWizard did not report the sent message\'s attachments, so they could not be verified. Check the sent message on ourfamilywizard.com.';
1054
+ }
1055
+ }
1005
1056
  if (newId !== null) {
1057
+ if (draftRef !== undefined)
1058
+ await clearHeldFiles(cache, draftRef);
1006
1059
  verifyNote = verifyWriteLanded('message', { subject, body }, detail);
1007
1060
  // Threading verdict, from OFW's own echo on the re-fetched sent record.
1008
1061
  // Both directions demand POSITIVE evidence (see reportsUnthreaded): a
@@ -1149,13 +1202,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1149
1202
  }
1150
1203
  : {}),
1151
1204
  ...persisted,
1205
+ ...(attachmentCheck !== null ? { attachments: attachmentCheck } : {}),
1152
1206
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1153
1207
  ...(uploadWarnings.length > 0 ? { warnings: uploadWarnings } : {}),
1154
1208
  };
1155
- return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1209
+ return notedJsonResponse([guardNote, rewriteNote, verifyNote, threadNote, attachmentNote, unconfirmedNote, retainNote], responseObj, 'Message sent successfully.');
1156
1210
  });
1157
1211
  async function guardDestructiveDraftOp(input) {
1158
1212
  const { cache, draftId, expectedRevision, force, action } = input;
1213
+ const heldFiles = await getHeldFiles(cache, draftId);
1159
1214
  const cachedRow = await cache.getDraft(draftId);
1160
1215
  const cached = cachedRow === null ? null : {
1161
1216
  subject: cachedRow.subject,
@@ -1177,7 +1232,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1177
1232
  // `.message`, which every Error carries.)
1178
1233
  const reason = e.message;
1179
1234
  if (force) {
1180
- return { ok: true, note: `WARNING: force:true — proceeded with ${action} on draft ${draftId} even though its current state could not be read from OurFamilyWizard (${reason}). Any newer server-side version was destroyed and is NOT recoverable from this response.`, server: undefined };
1235
+ return { ok: true, note: `WARNING: force:true — proceeded with ${action} on draft ${draftId} even though its current state could not be read from OurFamilyWizard (${reason}). Any newer server-side version was destroyed and is NOT recoverable from this response.`, server: undefined, heldFiles };
1181
1236
  }
1182
1237
  return {
1183
1238
  ok: false,
@@ -1189,7 +1244,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1189
1244
  }),
1190
1245
  };
1191
1246
  }
1192
- const verdict = checkDraftFreshness({ server, cached, expectedRevision });
1247
+ const verdict = checkDraftFreshness({ server, cached, expectedRevision, heldFiles });
1193
1248
  if (verdict.verdict === 'FRESH') {
1194
1249
  // A metadata-only "conflict" is the connector's own post-save replyToId
1195
1250
  // normalization catching up — safe to proceed, but say so rather than
@@ -1197,7 +1252,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1197
1252
  const note = verdict.metadataOnly
1198
1253
  ? `NOTE: draft ${draftId} was treated as current for this ${action}. Since you read it, OurFamilyWizard normalized connector-authored metadata (${verdict.changedFields.join(', ')}); the subject, body and recipients are unchanged, so this is not a conflict.`
1199
1254
  : null;
1200
- return { ok: true, note, server };
1255
+ return { ok: true, note, server, heldFiles };
1201
1256
  }
1202
1257
  if (force) {
1203
1258
  // Loud, and the overwritten content rides along in the response so it is
@@ -1208,8 +1263,9 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1208
1263
  : `The server version that was overwritten is preserved below under "overwrittenServerDraft".`;
1209
1264
  return {
1210
1265
  ok: true,
1211
- note: `WARNING: force:true overrode a ${verdict.verdict} freshness verdict on draft ${draftId}. ${verdict.reason} ${echoed}\n\n${jsonText({ overwrittenServerDraft: server === null ? null : { ...server, revision: draftRevision(server) } })}`,
1266
+ note: `WARNING: force:true overrode a ${verdict.verdict} freshness verdict on draft ${draftId}. ${verdict.reason} ${echoed}\n\n${jsonText({ overwrittenServerDraft: server === null ? null : { ...server, revision: draftRevision(server, heldFiles) } })}`,
1212
1267
  server,
1268
+ heldFiles,
1213
1269
  };
1214
1270
  }
1215
1271
  return {
@@ -1220,6 +1276,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1220
1276
  verdict,
1221
1277
  server,
1222
1278
  cached,
1279
+ heldFiles,
1223
1280
  })),
1224
1281
  };
1225
1282
  }
@@ -1280,10 +1337,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1280
1337
  // Every draft carries the concurrency token to echo back on a write, its
1281
1338
  // stable identity across edits, and whether the last sync actually
1282
1339
  // compared this cache against OFW.
1340
+ const held = await heldFilesFor(cache, rows.map((d) => d.id));
1341
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
1283
1342
  const drafts = rows.map((d) => ({
1284
1343
  ...d,
1285
- revision: draftRevision(d),
1344
+ revision: draftRevision(d, held.get(d.id)),
1345
+ ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
1286
1346
  draftKey: keyById.get(d.id) ?? null,
1347
+ ...(inferred.has(d.id) ? { draftKeyInferred: true } : {}),
1287
1348
  cacheStatus,
1288
1349
  serverConfirmed,
1289
1350
  asOf: freshness.asOf,
@@ -1344,7 +1405,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1344
1405
  if (allowDrafts)
1345
1406
  server.registerTool('ofw_save_draft', {
1346
1407
  _meta: familyMeta('change'),
1347
- description: 'Save a message as a draft in OurFamilyWizard. RECIPIENTS: OurFamilyWizard does NOT persist recipients on drafts — recipientIds are accepted but the saved draft comes back with none (documented OFW behavior, noted once in the response, not warned about; supply recipientIds at send time instead). 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. Attach files via myFileIDs (from ofw_upload_attachment). 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.',
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.',
1348
1409
  // Destructive: with messageId, saving REPLACES the draft by creating a new
1349
1410
  // one and deleting the old (OFW has no draft update), so the old draft's
1350
1411
  // server content is gone. Not idempotent: every call mints a new draft id.
@@ -1355,7 +1416,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1355
1416
  recipientIds: z.array(z.number()).describe('Array of recipient user IDs (optional for drafts)').optional(),
1356
1417
  messageId: z.number().describe('ID of an existing draft to replace (the new draft will have a new id; the old is deleted)').optional(),
1357
1418
  replyToId: z.number().describe('ID of the message this draft replies to').optional(),
1358
- myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment). When replacing a draft (messageId), omit it to KEEP the draft\'s current attachments; passing it replaces them.').optional(),
1419
+ myFileIDs: z.array(z.number()).describe('Attachment file ids (from ofw_upload_attachment) to attach. OurFamilyWizard does not store attachments on drafts, so they are HELD with this draft by this server and attached when you send it with ofw_send_message(draftId). When replacing a draft (messageId), the files already held are kept and these are added (de-duplicated); use removeFileIDs to drop one.').optional(),
1420
+ removeFileIDs: z.array(z.number()).describe('When replacing a draft: held attachment file ids to drop.').optional(),
1359
1421
  inlineAttachments: inlineAttachmentsParam,
1360
1422
  blobKeys: blobKeysParam,
1361
1423
  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(),
@@ -1371,6 +1433,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1371
1433
  // a stray draft behind for a write we then decline to finish.
1372
1434
  let forceNote = null;
1373
1435
  let serverFiles;
1436
+ let priorHeld = [];
1437
+ let serverRecipientIds;
1374
1438
  if (args.messageId !== undefined) {
1375
1439
  const guard = await guardDestructiveDraftOp({
1376
1440
  cache,
@@ -1383,6 +1447,12 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1383
1447
  return guard.response;
1384
1448
  forceNote = guard.note;
1385
1449
  serverFiles = guard.server?.files;
1450
+ priorHeld = guard.heldFiles;
1451
+ // OFW does keep recipients on a draft when they were posted (observed
1452
+ // live), so a replace that names none must not post [] and drop them.
1453
+ const kept = (guard.server?.recipients ?? []).map((r) => r.userId).filter((id) => id !== 0);
1454
+ if (kept.length > 0)
1455
+ serverRecipientIds = [...new Set(kept)];
1386
1456
  }
1387
1457
  const requestedReplyTo = args.replyToId ?? null;
1388
1458
  let resolvedReplyTo = requestedReplyTo;
@@ -1393,15 +1463,19 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1393
1463
  rewriteNote = `replyToId rewritten from ${requestedReplyTo} to ${resolvedReplyTo} (later reply in same thread found in sent cache).`;
1394
1464
  }
1395
1465
  }
1396
- // Replacing a draft creates a NEW one, so its files must be posted again
1397
- // or the edit silently strips them: they carry over from the server copy
1398
- // the guard just read (an explicit myFileIDs still replaces them, as on
1399
- // send). New uploads go on top, after the guard, so a refused replace
1400
- // uploads nothing.
1466
+ // OFW keeps no files on a draft (held-attachments.ts), so the draft's
1467
+ // attachments are the set HELD for it here: what was held before, anything
1468
+ // OFW did report, the caller's myFileIDs, and new uploads — de-duplicated,
1469
+ // minus removeFileIDs. New uploads happen after the guard, so a refused
1470
+ // replace uploads nothing. They stay PRIVATE: a send attaches PRIVATE files as they are.
1401
1471
  const { uploaded: newFiles, warnings: uploadWarnings } = await uploadPending(pending, {
1402
- client, cache, store: blobStore, nothingWas: 'saved',
1472
+ client, cache, store: blobStore, nothingWas: 'saved', shareClass: 'PRIVATE',
1403
1473
  });
1404
- const myFileIDs = [...(args.myFileIDs ?? serverFiles ?? []), ...newFiles.map((f) => f.fileId)];
1474
+ const removed = new Set(args.removeFileIDs ?? []);
1475
+ const myFileIDs = uniqueIds([
1476
+ ...priorHeld, ...(serverFiles ?? []), ...(args.myFileIDs ?? []), ...newFiles.map((f) => f.fileId),
1477
+ ]).filter((id) => !removed.has(id));
1478
+ // Posted anyway: should OFW ever keep them on the draft, they show there.
1405
1479
  // Deliberately do NOT pass `args.messageId` to OFW's POST payload.
1406
1480
  // OFW's update-by-messageId path silently no-ops on subsequent
1407
1481
  // updates while echoing the posted body in the immediate GET — so
@@ -1411,7 +1485,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1411
1485
  const payload = {
1412
1486
  subject: args.subject,
1413
1487
  body: args.body,
1414
- recipientIds: args.recipientIds ?? [],
1488
+ recipientIds: args.recipientIds ?? serverRecipientIds ?? [],
1415
1489
  attachments: { myFileIDs },
1416
1490
  draft: true,
1417
1491
  includeOriginal: resolvedReplyTo !== null,
@@ -1423,6 +1497,8 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1423
1497
  let verifyNote = null;
1424
1498
  let recipientsNote = null;
1425
1499
  let newRevision = null;
1500
+ let onDraft = [];
1501
+ let held = [];
1426
1502
  let draftKey = null;
1427
1503
  // Fields accepted on the write that the saved draft must carry — or their
1428
1504
  // loss must be reported. Never a silent drop (Defect 3).
@@ -1451,9 +1527,15 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1451
1527
  listData: detail,
1452
1528
  };
1453
1529
  await cache.upsertDraft(persisted);
1454
- // The revision is now computed from the server-authoritative detail, so it
1455
- // is the value a subsequent read/verify will observe (Defect 1).
1456
- newRevision = draftRevision(persisted);
1530
+ // What OFW actually kept on the draft (in practice none), and what is
1531
+ // therefore held here for the send.
1532
+ onDraft = Array.isArray(detail.files) ? detail.files : [];
1533
+ held = myFileIDs.filter((id) => !onDraft.includes(id));
1534
+ await setHeldFiles(cache, newId, held);
1535
+ // The revision is computed from the server-authoritative detail plus the
1536
+ // held files, so it is the value a subsequent read/verify will observe
1537
+ // (Defect 1) — and it moves when only the attachments change.
1538
+ newRevision = draftRevision(persisted, held);
1457
1539
  // Carry the logical identity across the id change. Replacing a draft mints
1458
1540
  // a NEW OFW id every time (create-then-delete — see the note below), so
1459
1541
  // ten edits produced ten unrelated ids and there was no way to ask what
@@ -1521,20 +1603,14 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1521
1603
  warnings.push(`recipientIds were requested as [${requested.join(', ')}] but the saved draft has [${stored.join(', ')}]. Verify the recipients on ourfamilywizard.com.`);
1522
1604
  }
1523
1605
  }
1524
- if (myFileIDs.length > 0 && Array.isArray(detail.files)) {
1525
- const storedFiles = new Set(detail.files);
1526
- const missing = myFileIDs.filter((id) => !storedFiles.has(id));
1527
- if (missing.length > 0) {
1528
- warnings.push(`Attachment fileId(s) ${missing.join(', ')} were requested in myFileIDs but are not attached to the saved draft. Re-upload or re-attach if needed.`);
1529
- }
1530
- }
1531
1606
  // Replace-path: caller passed messageId, so they want the old draft
1532
1607
  // gone. Delete it after the new one is safely created+cached.
1533
1608
  if (args.messageId !== undefined && args.messageId !== newId) {
1534
1609
  try {
1535
1610
  await deleteOFWMessages(client, [args.messageId]);
1536
1611
  await cache.deleteDraft(args.messageId);
1537
- replaceNote = `NOTE: ofw_save_draft replaced draft ${args.messageId} via create-then-delete. The new draft id is ${newId}; the old draft has been deleted. The draftKey is UNCHANGED — key off it rather than the volatile id, which changes on every edit. (OFW's update-in-place endpoint silently no-ops on subsequent updates, so we never use it.) Fields carried over to the new draft: subject, body, recipients (${persisted.recipients.length}), replyToId (${persisted.replyToId === null ? 'none' : persisted.replyToId}), attachments (${myFileIDs.length}).${warnings.length > 0 ? ' See warnings above for any field OurFamilyWizard did not carry over.' : ''}`;
1612
+ await clearHeldFiles(cache, args.messageId);
1613
+ replaceNote = `NOTE: ofw_save_draft replaced draft ${args.messageId} via create-then-delete. The new draft id is ${newId}; the old draft has been deleted. The draftKey is UNCHANGED — key off it rather than the volatile id, which changes on every edit. (OFW's update-in-place endpoint silently no-ops on subsequent updates, so we never use it.) Fields carried over to the new draft: subject, body, recipients (${persisted.recipients.length}), replyToId (${persisted.replyToId === null ? 'none' : persisted.replyToId}), attachments: ${onDraft.length} on the draft, ${held.length} held for send.${warnings.length > 0 ? ' See warnings above for any field OurFamilyWizard did not carry over.' : ''}`;
1538
1614
  }
1539
1615
  catch (e) {
1540
1616
  // Partial-failure safety: the new draft is already created and
@@ -1560,6 +1636,11 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1560
1636
  previousId: args.messageId ?? null,
1561
1637
  cacheStatus: 'fresh',
1562
1638
  serverConfirmed: true,
1639
+ attachments: {
1640
+ onDraft,
1641
+ held: await describeHeld(cache, held),
1642
+ ...(held.length > 0 ? { note: HELD_NOTE } : {}),
1643
+ },
1563
1644
  ...(newFiles.length > 0 ? { attachmentsUploaded: newFiles } : {}),
1564
1645
  ...(warnings.length > 0 ? { warnings } : {}),
1565
1646
  ...(recipientsNote !== null ? { recipientsNote } : {}),
@@ -1593,6 +1674,7 @@ export function registerMessageTools(server, client, cacheProvider, attachmentIO
1593
1674
  return guard.response;
1594
1675
  const data = await deleteOFWMessages(client, [args.messageId]);
1595
1676
  await cache.deleteDraft(args.messageId);
1677
+ await clearHeldFiles(cache, args.messageId);
1596
1678
  return notedJsonResponse([guard.note], data, 'Draft deleted.');
1597
1679
  });
1598
1680
  server.registerTool('ofw_get_unread_sent', {
@@ -2255,11 +2337,15 @@ Up to ${MAX_FILES_PER_CALL} files per call; each must be non-empty and at most 2
2255
2337
  const total = await cache.countDrafts();
2256
2338
  const rows = await cache.listDrafts({ page: 1, size: Math.max(total, 1) });
2257
2339
  const keyById = new Map((await cache.getDraftLineageByIds(rows.map((d) => d.id))).map((l) => [l.id, l.draftKey]));
2340
+ const held = await heldFilesFor(cache, rows.map((d) => d.id));
2341
+ const inferred = await inferredDraftKeys(cache, rows.map((d) => d.id));
2258
2342
  drafts = rows.map((d) => ({
2259
2343
  id: d.id,
2260
2344
  draftKey: keyById.get(d.id) ?? null,
2345
+ ...(inferred.has(d.id) ? { draftKeyInferred: true } : {}),
2261
2346
  subject: d.subject,
2262
- revision: draftRevision(d),
2347
+ revision: draftRevision(d, held.get(d.id)),
2348
+ ...(held.get(d.id).length > 0 ? { heldFiles: held.get(d.id) } : {}),
2263
2349
  modifiedAt: d.modifiedAt,
2264
2350
  recipients: d.recipients,
2265
2351
  replyToId: d.replyToId,