@mgcrea/mcp-apple-reminders 1.31.0 → 1.35.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.
- package/dist/cli.js +1 -1
- package/dist/index.d.ts +21 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/{server-DtVE675D.js → server-98Ip7blI.js} +145 -71
- package/dist/server-98Ip7blI.js.map +1 -0
- package/package.json +5 -4
- package/dist/server-DtVE675D.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"server-DtVE675D.js","names":["#col","#selectList","#live","#baseSelect","#rowToReminder","#logger","#now","#storeTried","#store","#allowedAccount","#allowedList","#bulk","#cache","#bounds","#dueInstant","#order","#listPk","#fromIndex","#matchesIndex","#indexCanAnswer","#fromStore","#matches","#summarise","#capped","#toJxaFields"],"sources":["../src/build-info.ts","../src/client/errors.ts","../src/client/locate.ts","../src/client/priority.ts","../src/client/ref.ts","../src/client/jxa/core.ts","../src/client/jxa/read.ts","../src/client/jxa/write.ts","../src/client/store.ts","../src/client/reminders.ts","../src/config.ts","../src/guide.ts","../src/prompts.ts","../src/tools/util.ts","../src/tools/diagnostics.ts","../src/tools/accounts.ts","../src/tools/actions.ts","../src/tools/reminders.ts","../src/tools/index.ts","../src/server.ts"],"sourcesContent":["// Build-time / runtime identity for the running server. `name`/`version` are\n// read from package.json at startup (always accurate); `gitCommit` /\n// `gitCommitDate` are injected by tsdown's `define` substitution at build time\n// and fall back to \"unknown\" when running from source (e.g. vitest).\n\nimport { readPackageIdentity, type BuildInfo } from \"@mgcrea/mcp-apple-core\";\n\n// oxlint-disable no-underscore-dangle -- bundler-injected build-time constants.\ndeclare const __GIT_COMMIT__: string;\ndeclare const __GIT_COMMIT_DATE__: string;\n\nconst pkg = readPackageIdentity(new URL(\"../package.json\", import.meta.url), {\n name: \"@mgcrea/mcp-apple-reminders\",\n version: \"0.0.0\",\n});\n\nexport type { BuildInfo };\n\nexport const BUILD_INFO: BuildInfo = {\n name: pkg.name,\n version: pkg.version,\n gitCommit: typeof __GIT_COMMIT__ === \"string\" ? __GIT_COMMIT__ : \"unknown\",\n gitCommitDate: typeof __GIT_COMMIT_DATE__ === \"string\" ? __GIT_COMMIT_DATE__ : \"unknown\",\n};\n","/**\n * Reminders' error surface. The taxonomy lives in `@mgcrea/mcp-apple-core`;\n * what belongs here is the identity those messages are written against, and the\n * errors that are genuinely about reminders.\n */\n\nimport { AppleAutomationError, type SurfaceContext } from \"@mgcrea/mcp-apple-core\";\n\n/** Named in every user-facing error and in the env vars they mention. */\nexport const REMINDERS_SURFACE: SurfaceContext = {\n appName: \"Reminders\",\n envPrefix: \"APPLE_REMINDERS\",\n};\n\nexport {\n AppleAutomationError as AppleRemindersError,\n AppBusyError as RemindersBusyError,\n AppNotRunningError as RemindersNotRunningError,\n IndexUnavailableError,\n OsascriptTimeoutError,\n PlatformError,\n PreconditionError,\n ProtocolError,\n SchemaDriftError,\n TccDeniedError,\n WritesDisabledError,\n} from \"@mgcrea/mcp-apple-core\";\n\n/** A ReminderRef no longer resolves — completed-and-cleared, deleted, or stale. */\nexport class ReminderNotFoundError extends AppleAutomationError {\n override readonly name = \"ReminderNotFoundError\";\n\n constructor(ref: string) {\n super(\n `No reminder for ref \"${ref}\". It was probably deleted since the search ran — and note ` +\n `that completing a reminder can also remove it from the default view. Re-run the search ` +\n `to get a current ref.`,\n );\n }\n}\n\n/** A list was named that Reminders does not have. */\nexport class ListNotFoundError extends AppleAutomationError {\n override readonly name = \"ListNotFoundError\";\n\n constructor(name: string, available: readonly string[] = []) {\n super(\n `No Reminders list named \"${name}\".` +\n (available.length\n ? ` Available: ${available.slice(0, 20).join(\", \")}${available.length > 20 ? \", …\" : \"\"}.`\n : ` Use apple_reminders_list_lists to see what exists.`),\n { requested: name },\n );\n }\n}\n\n/**\n * A date argument could not be read.\n *\n * Re-exported from core, which now owns the grammar every surface parses dates\n * with. Kept as a name in this module so `catch (e) { e instanceof\n * InvalidDateError }` here keeps working, and so the surface's error list reads\n * as one list.\n */\nexport { InvalidDateError } from \"@mgcrea/mcp-apple-core\";\n","import { readdirSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { describeStore, type StoreFacts } from \"@mgcrea/mcp-apple-core\";\n\n/**\n * Find Reminders' store.\n *\n * ## Why this is harder than Notes'\n *\n * Notes has one constant path, so its locator can `statSync` a known file and\n * learn \"exists but unreadable\" — the signature of a TCC denial — without any\n * permission at all. Reminders keeps its database under a **generated\n * directory name**:\n *\n * ~/Library/Group Containers/group.com.apple.reminders/Container_v1/Stores/Data-<UUID>.sqlite\n *\n * Resolving that means *listing* a protected directory, which is itself the\n * privileged operation. So without Full Disk Access there is not even a path to\n * stat, and this returns `storePath: null` with a reason rather than reporting a\n * file that does not exist. Those are different failures and lead to different\n * fixes.\n *\n * ## Why it globs rather than hardcoding `Container_v1/Stores`\n *\n * That subpath is the observed layout, not a documented one, and Apple has\n * moved this data before — `~/Library/Reminders/Container_v1/Stores` on older\n * releases, and `~/Library/Calendars` in the EventKit era. A bounded walk for\n * `*.sqlite` survives a reshuffle; a hardcoded path turns one into a total\n * outage. The known layout is still *preferred* when present, so the common\n * case costs one readdir.\n */\n\n/** `group.com.apple.reminders`, under `~/Library/Group Containers`. */\nexport const GROUP_CONTAINER = \"group.com.apple.reminders\";\n\n/** The observed layout. Preferred when it exists; not required. */\nconst PREFERRED = [\"Container_v1\", \"Stores\"];\n\n/** Depth cap for the fallback walk. The real store sits at depth 2. */\nconst MAX_DEPTH = 4;\n\nexport type StoreCandidate = StoreFacts & { path: string };\n\nexport type LocateResult = StoreFacts & {\n containerPath: string;\n /** Null when discovery could not run — see `reason`. */\n storePath: string | null;\n /** Every `.sqlite` found, largest first. More than one is normal. */\n candidates: StoreCandidate[];\n /** Whether the container could be listed at all. The FDA signal for this surface. */\n containerListable: boolean;\n reason: string | null;\n};\n\nexport const defaultContainerPath = (home: string = homedir()): string =>\n join(home, \"Library\", \"Group Containers\", GROUP_CONTAINER);\n\nconst listDir = (dir: string): string[] => {\n try {\n return readdirSync(dir, { withFileTypes: true }).flatMap((e) =>\n e.isDirectory() ? [] : [e.name],\n );\n } catch {\n return [];\n }\n};\n\nconst walk = (dir: string, depth: number, out: string[]): string[] => {\n if (depth > MAX_DEPTH) return out;\n let entries;\n try {\n entries = readdirSync(dir, { withFileTypes: true });\n } catch {\n return out;\n }\n for (const e of entries) {\n const p = join(dir, e.name);\n if (e.isDirectory()) walk(p, depth + 1, out);\n else if (e.name.endsWith(\".sqlite\")) out.push(p);\n }\n return out;\n};\n\nconst FDA_HINT =\n \"Grant Full Disk Access to the app running this server (System Settings > Privacy & \" +\n \"Security > Full Disk Access) and restart it. Granting it to Reminders.app does nothing — \" +\n \"the reader needs the permission.\";\n\nexport const locateStore = (\n opts: { storePath?: string | undefined; home?: string } = {},\n): LocateResult => {\n const containerPath = defaultContainerPath(opts.home);\n\n // An explicit path is a bypass, for tests and forensic copies. No discovery.\n if (opts.storePath) {\n const facts = describeStore(opts.storePath);\n return {\n ...facts,\n containerPath,\n storePath: opts.storePath,\n candidates: [{ ...facts, path: opts.storePath }],\n containerListable: true,\n reason: facts.readable\n ? null\n : facts.exists\n ? `The store at ${opts.storePath} exists but cannot be read. ${FDA_HINT}`\n : `No file at ${opts.storePath}. APPLE_REMINDERS_STORE points at nothing.`,\n };\n }\n\n // The preferred subpath first, so the common case is one readdir rather than\n // a walk of the whole container.\n const preferredDir = join(containerPath, ...PREFERRED);\n const found = listDir(preferredDir)\n .filter((n) => n.endsWith(\".sqlite\"))\n .map((n) => join(preferredDir, n));\n const paths = found.length ? found : walk(containerPath, 0, []);\n\n const candidates: StoreCandidate[] = paths\n .map((p) => ({ ...describeStore(p), path: p }))\n .toSorted((a, b) => (b.size ?? 0) - (a.size ?? 0));\n\n // Largest readable file wins. Reminders keeps per-store containers, and a\n // stale or empty one can sit beside the real database — picking the first\n // entry readdir happens to return would be a coin flip between them.\n const chosen = candidates.find((c) => c.readable) ?? candidates[0] ?? null;\n\n // Distinguishing \"cannot list\" from \"listed, found nothing\" is the whole\n // point: the first is a permission problem, the second is a Reminders that\n // was never set up.\n const containerListable = paths.length > 0 || listDir(containerPath).length > 0;\n\n const reason = chosen\n ? chosen.readable\n ? null\n : `Found the Reminders store but cannot read it. ${FDA_HINT}`\n : containerListable\n ? `No .sqlite file under ${containerPath}. Has Reminders ever been set up on this account?`\n : `Cannot list ${containerPath}, so the store cannot even be located — its filename ` +\n `carries a generated UUID. ${FDA_HINT}`;\n\n const facts: StoreFacts = chosen\n ? {\n exists: chosen.exists,\n readable: chosen.readable,\n size: chosen.size,\n mtime: chosen.mtime,\n walPresent: chosen.walPresent,\n walSizeBytes: chosen.walSizeBytes,\n }\n : {\n exists: false,\n readable: false,\n size: null,\n mtime: null,\n walPresent: false,\n walSizeBytes: null,\n };\n\n return {\n ...facts,\n containerPath,\n storePath: chosen?.path ?? null,\n candidates,\n containerListable,\n reason,\n };\n};\n","/**\n * Reminder priority, which is a range on the wire and a set of buttons in the UI.\n *\n * The scripting dictionary documents the encoding exactly:\n *\n * priority — 0: no priority, 1–4: high, 5: medium, 6–9: low\n *\n * Two things follow, and naive implementations get both wrong.\n *\n * **Reading is a bucket, not a lookup.** The range exists because Reminders\n * shares this field with CalDAV, where any 1–9 is legal. A reminder synced from\n * another client can arrive as priority 3, and a `switch` over {0,1,5,9} would\n * report it as unknown — or, worse, fall through to \"none\" and show an urgent\n * item as unflagged.\n *\n * **Writing is a choice of representative.** The UI offers four buttons, so\n * each bucket needs one canonical value. These match what Reminders itself\n * writes, which keeps a round trip through this server from silently rewriting\n * a value the app would have left alone.\n *\n * Note the inversion: a *lower* number is a *higher* priority. Sorting by the\n * raw field ascending puts \"none\" (0) first, ahead of high (1) — so ordering by\n * urgency needs `rank`, not the raw value.\n */\n\n/** What the tools accept and return. */\nexport type PriorityName = \"none\" | \"low\" | \"medium\" | \"high\";\n\nexport const PRIORITY_NAMES: readonly PriorityName[] = [\"none\", \"low\", \"medium\", \"high\"];\n\n/** The value Reminders.app itself writes for each bucket. */\nconst CANONICAL: Record<PriorityName, number> = { none: 0, high: 1, medium: 5, low: 9 };\n\n/** Name → wire value, for writes. */\nexport const toPriorityValue = (name: PriorityName): number => CANONICAL[name];\n\n/**\n * Wire value → name, for reads. Buckets the whole legal range, so a value\n * written by another CalDAV client is still classified rather than dropped.\n */\nexport const toPriorityName = (value: number | null | undefined): PriorityName => {\n if (value === null || value === undefined || !Number.isFinite(value)) return \"none\";\n const n = Math.trunc(value);\n if (n <= 0) return \"none\";\n if (n <= 4) return \"high\";\n if (n === 5) return \"medium\";\n if (n <= 9) return \"low\";\n // Out of the documented range. Something is set, and \"none\" would be a lie.\n return \"low\";\n};\n\n/**\n * Sort key, ascending = most urgent first, with \"none\" last.\n *\n * The raw field cannot be used for this: 0 means \"no priority\" but sorts ahead\n * of 1, which means \"high\".\n */\nexport const rank = (value: number | null | undefined): number => {\n const name = toPriorityName(value);\n return name === \"none\" ? Number.MAX_SAFE_INTEGER : CANONICAL[name];\n};\n","/**\n * ReminderRef — the one identifier any tool accepts or returns.\n *\n * Wire format: r1:<reminders-id>\n *\n * The `r1:` prefix follows the same reasoning as Notes' `n1:`: if the id scheme\n * ever changes, a versioned prefix makes that an additive change instead of a\n * silent reinterpretation of every ref already sitting in a conversation.\n *\n * Deliberately NOT shared with Notes' or Mail's codec. Mail's assumes an integer\n * id; Notes' hardcodes `ICNote/p<N>` and returns a numeric `primaryKey`.\n * Reminders' `id` is declared `type=\"text\"` in the scripting dictionary and is\n * opaque — so this codec validates the envelope and refuses to invent structure\n * inside it.\n *\n * ## Why this is tolerant about the id's shape\n *\n * Apple Events ids are observed as `x-apple-reminder://<uuid>`, but that is a\n * shape this server *observes*, not one Apple documents. Rejecting anything\n * else would turn a harmless format change into total failure, and a reminder\n * synced from a CalDAV account is exactly the case most likely to differ. So an\n * id is carried through verbatim, and the UUID is extracted opportunistically —\n * it is what joins a row in the store to a reminder in the app, and when it is\n * absent the index lane simply cannot enrich that one result.\n */\n\nimport { PreconditionError } from \"./errors.js\";\n\nexport const REF_VERSION = \"r1\";\n\n/** The observed Apple Events form. Used to *find* the uuid, never to require it. */\nconst UUID = /([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i;\n\nexport type ReminderRef = {\n /** The full id, exactly as Apple Events issued it. This is what resolves. */\n id: string;\n /**\n * The bridge to the store, when the id carries one.\n *\n * Null is a legitimate value, not an error: it means this reminder can still\n * be read and written over Apple Events, and only the index-only fields\n * (tags, url, recurrence, alarms) are unavailable for it.\n */\n uuid: string | null;\n};\n\nexport const encodeRef = (id: string): string => `${REF_VERSION}:${id}`;\n\nexport const decodeRef = (raw: string): ReminderRef => {\n const m = /^([a-z0-9]+):(.+)$/.exec(String(raw ?? \"\"));\n if (!m) {\n throw new PreconditionError(\n `Malformed reminder ref ${JSON.stringify(raw)}. Refs come from the search and list tools — ` +\n `construct them from those results rather than by hand.`,\n { expected: `${REF_VERSION}:<reminders-id>` },\n );\n }\n const [, version, id] = m;\n if (version !== REF_VERSION) {\n throw new PreconditionError(\n `Unknown reminder ref version \"${version}\". This server issues \"${REF_VERSION}:\" refs.`,\n );\n }\n return { id: id as string, uuid: UUID.exec(id ?? \"\")?.[1]?.toUpperCase() ?? null };\n};\n\n/**\n * Build a ref from an index row, which only ever knows the bare UUID.\n *\n * The scheme is measured, not assumed: the probe read a real id from Apple\n * Events and found `x-apple-reminder://<uuid>`, then located the same UUID in\n * `ZREMCDREMINDER.ZCKIDENTIFIER`. That round trip is what makes reconstructing\n * an id from the store defensible.\n */\nexport const refFromUuid = (uuid: string): string =>\n encodeRef(`x-apple-reminder://${uuid.toUpperCase()}`);\n\n/** The store keeps bare identifiers; normalise for comparison against a ref. */\nexport const uuidOf = (id: string): string | null =>\n UUID.exec(String(id ?? \"\"))?.[1]?.toUpperCase() ?? null;\n","/**\n * JXA script fragments.\n *\n * Every script here is a static constant. None of them may contain a template\n * interpolation — `assertStaticScript` rejects any script containing a dollar\n * sign followed by a brace, and that includes JavaScript template literals\n * written *inside* the JXA source. Use string concatenation in JXA code.\n *\n * Every script follows the same contract:\n * - it reads its parameters from `JSON.parse(argv[0])`\n * - it returns `JSON.stringify({ok: true, data})` on success\n * - it returns `JSON.stringify({ok: false, error: {code, message}})` on an\n * application-level failure, still exiting 0\n * so that a non-zero exit always means infrastructure rather than \"no such\n * reminder\".\n *\n * ## The read discipline\n *\n * A bulk array fetch (`R.reminders.name()`) is ONE Apple Event whatever the\n * library holds. Reading the same property one reminder at a time is one event\n * each. So every read here fetches columns, never rows: a server that reads\n * twelve properties pays twelve round trips total, not twelve per reminder.\n *\n * Whether a `whose` specifier beats that for a *boolean* filter is a genuinely\n * open question, and `scripts/probe-reminders.mjs` measures it. Notes settled\n * the same question for `whose` over *text* — 6.9x slower, because the\n * specifier evaluates per item across the bridge — but a boolean predicate can\n * be pushed into the app in a way a substring match cannot, so that answer does\n * not transfer. Until it is measured, these scripts use the form that is known\n * to be size-independent.\n *\n * ## What the dictionary does not allow\n *\n * `reminder.container` and `list.container` are both declared `access=\"r\"`.\n * There is therefore **no way to move a reminder between lists by assignment** —\n * see `write.ts`, where move is implemented as copy-then-delete and says so.\n */\n\n/**\n * Shared prelude.\n *\n * The liveness gate matters more than it looks. `Application(\"Reminders\").lists`\n * *launches* Reminders if it isn't running — which steals focus and starts a\n * sync as a side effect of a read. `NSRunningApplication` answers the same\n * question without launching anything and without a second TCC prompt.\n *\n * Note the bundle identifier is lower-case `com.apple.reminders`. Notes uses\n * `com.apple.Notes`, and `runningApplicationsWithBundleIdentifier` matches\n * exactly — getting the case wrong makes every read report \"not running\".\n *\n * Deliberately NOT shared with Mail's or Notes' prelude. Mail's is 45% a\n * UI-scripting workaround for its forced blockquote citation; Notes' knows\n * about password-protected notes and folder trees. Neither is about reminders.\n */\nexport const PRELUDE = `\nObjC.import(\"AppKit\");\n\nfunction isRemindersRunning() {\n var apps = $.NSRunningApplication.runningApplicationsWithBundleIdentifier(\"com.apple.reminders\");\n return apps.count > 0;\n}\n\nfunction ok(data) { return JSON.stringify({ ok: true, data: data }); }\nfunction err(code, message) { return JSON.stringify({ ok: false, error: { code: code, message: String(message) } }); }\n\nfunction iso(d) {\n try { return d ? d.toISOString() : null; } catch (e) { return null; }\n}\n\n/** Read one property defensively: Reminders throws on properties it cannot supply. */\nfunction prop(fn, fallback) {\n try {\n var v = fn();\n return v === undefined ? fallback : v;\n } catch (e) {\n return fallback;\n }\n}\n\n/**\n * Zip parallel bulk arrays into records.\n *\n * Bulk fetches are the only affordable read shape, and they come back as\n * separate arrays that line up by index. Rebuilding records here keeps that\n * assumption in one place.\n */\nfunction zip(keys, columns, count) {\n var out = [];\n for (var i = 0; i < count; i++) {\n var row = {};\n for (var k = 0; k < keys.length; k++) {\n var col = columns[k];\n row[keys[k]] = col && i < col.length ? col[i] : null;\n }\n out.push(row);\n }\n return out;\n}\n\n/**\n * Walk the list tree.\n *\n * \\`list.container\\` is typed \"account OR list\", so lists nest — Reminders calls\n * the nesting \"groups\" in its UI. A flat \\`account.lists()\\` would silently drop\n * everything inside a group, which is why this recurses even on libraries where\n * no group exists today.\n */\nfunction listTree(container, accountId, depth, out) {\n if (depth > 8) return out;\n var subs = [];\n try { subs = container.lists(); } catch (e) { return out; }\n for (var i = 0; i < subs.length; i++) {\n var l = subs[i];\n var id = prop(function () { return String(l.id()); }, null);\n out.push({\n id: id,\n name: prop(function () { return String(l.name()); }, null),\n accountId: accountId,\n depth: depth,\n color: prop(function () { return String(l.color()); }, null),\n emblem: prop(function () { return String(l.emblem()); }, null)\n });\n listTree(l, accountId, depth + 1, out);\n }\n return out;\n}\n\n/**\n * Build reminder-id -> list.\n *\n * MEASURED: a bulk property fetch costs ~700ms on this bridge whatever the\n * library size (317 reminders, macOS 26.6), so round trips are the only thing\n * that matters here. One call per list would be 12 events — 8 seconds — on a\n * perfectly ordinary account.\n *\n * \\`R.lists.reminders.id()\\` is a chained element fetch that returns one array\n * per list in a SINGLE event. It is not documented to work, so the per-list\n * form stays as a fallback and the script reports which one answered.\n */\nfunction membership(lists) {\n var map = {};\n var app = Application(\"Reminders\");\n\n var nested = prop(function () { return app.lists.reminders.id(); }, null);\n if (nested && nested.length === lists.length) {\n for (var n = 0; n < lists.length; n++) {\n var group = nested[n] || [];\n for (var g = 0; g < group.length; g++) {\n map[String(group[g])] = { listId: lists[n].id, list: lists[n].name, accountId: lists[n].accountId };\n }\n }\n return { map: map, via: \"nested\" };\n }\n\n for (var i = 0; i < lists.length; i++) {\n var l = lists[i];\n var ids = prop(function () { return app.lists.byId(l.id).reminders.id(); }, []);\n for (var j = 0; j < ids.length; j++) {\n map[String(ids[j])] = { listId: l.id, list: l.name, accountId: l.accountId };\n }\n }\n return { map: map, via: \"per-list\" };\n}\n\n/**\n * Whether a due date names a whole day, and which day that is.\n *\n * MEASURED, and there are two traps stacked here.\n *\n * **First:** Reminders populates BOTH \\`due date\\` and \\`allday due date\\` for\n * every dated reminder — 144 of each over 144 dated reminders, all carrying\n * both. So presence discriminates nothing, and \"allday is set, therefore\n * all-day\" marks every dated reminder as all-day.\n *\n * **Second:** the two lanes disagree about how an all-day date is stored, and\n * verifying against only one of them gets the other backwards. The same\n * reminder, due 9 November:\n *\n * Apple Events 2025-11-08T23:00:00Z = LOCAL midnight (Paris, UTC+1)\n * ZDUEDATE 2025-11-09T00:00:00Z = UTC midnight\n *\n * Both mean the 9th. So the check here reads **local** time, because this\n * script runs in the user's zone and that is the convention Apple Events uses.\n * The store's UTC convention is converted separately, on the store's side.\n *\n * \\`dayOf\\` exists for the same reason: an all-day reminder names a day, and\n * deriving that day from the UTC ISO string would land on the 8th for everyone\n * east of Greenwich. Formatting it here, from local components, cannot.\n *\n * This is still a heuristic — a reminder deliberately set to local midnight\n * defeats it — and is labelled as one. \\`ZALLDAY\\` in the store is the\n * authoritative flag, so the index lane overrides it whenever it is live.\n */\nfunction isMidnight(d) {\n try {\n return Boolean(d) && d.getHours() === 0 && d.getMinutes() === 0 && d.getSeconds() === 0;\n } catch (e) {\n return false;\n }\n}\n\n/** Local calendar day as YYYY-MM-DD. Never derive this from a UTC string. */\nfunction dayOf(d) {\n try {\n if (!d) return null;\n var m = d.getMonth() + 1;\n var day = d.getDate();\n return d.getFullYear() + \"-\" + (m < 10 ? \"0\" : \"\") + m + \"-\" + (day < 10 ? \"0\" : \"\") + day;\n } catch (e) {\n return null;\n }\n}\n`;\n\n/**\n * Wrap a script body in the prelude and the liveness gate.\n *\n * `allowLaunch` is opt-in per script, and only tools whose whole purpose is to\n * make Reminders do something set it. A read that silently launches Reminders is\n * a read with a side effect.\n */\nexport const script = (body: string, opts: { allowLaunch?: boolean } = {}): string => `\n${PRELUDE}\nfunction run(argv) {\n var p = JSON.parse(argv[0] || \"{}\");\n if (!isRemindersRunning() && !${opts.allowLaunch ? \"true\" : \"false\"}) {\n return err(\"APP_NOT_RUNNING\", \"Reminders is not running.\");\n }\n try {\n var R = Application(\"Reminders\");\n ${body}\n } catch (e) {\n var msg = String(e && e.message ? e.message : e);\n if (msg.indexOf(\"-1743\") !== -1) return err(\"NOT_AUTHORIZED\", msg);\n return err(\"SCRIPT_ERROR\", msg);\n }\n}\n`;\n","import { script } from \"./core.js\";\n\n/** Accounts, with the list count each one holds. */\nexport const LIST_ACCOUNTS = script(`\n var accounts = R.accounts();\n var out = [];\n var defaultAccountId = prop(function () { return String(R.defaultAccount.id()); }, null);\n var defaultListId = prop(function () { return String(R.defaultList.id()); }, null);\n for (var i = 0; i < accounts.length; i++) {\n var a = accounts[i];\n var id = prop(function () { return String(a.id()); }, null);\n out.push({\n id: id,\n name: prop(function () { return String(a.name()); }, null),\n isDefault: id !== null && id === defaultAccountId,\n listCount: prop(function () { return a.lists().length; }, 0),\n reminderCount: prop(function () { return a.reminders().length; }, 0)\n });\n }\n return ok({ accounts: out, defaultAccountId: defaultAccountId, defaultListId: defaultListId });\n`);\n\n/**\n * The list tree. Lists nest inside other lists (Reminders calls them groups),\n * so this is depth-first rather than a flat account.lists() read.\n */\nexport const LIST_LISTS = script(`\n var accounts = R.accounts();\n var out = [];\n var defaultListId = prop(function () { return String(R.defaultList.id()); }, null);\n for (var i = 0; i < accounts.length; i++) {\n var a = accounts[i];\n var accountId = prop(function () { return String(a.id()); }, null);\n var accountName = prop(function () { return String(a.name()); }, null);\n var lists = listTree(a, accountId, 1, []);\n for (var j = 0; j < lists.length; j++) {\n var l = lists[j];\n l.accountName = accountName;\n l.isDefault = l.id !== null && l.id === defaultListId;\n // Counted per list, which is one Apple Event each — a handful, not one\n // per reminder. Split so a caller can see a list's live workload without\n // paging through years of finished items.\n var counts = prop(function () {\n var done = R.lists.byId(l.id).reminders.completed();\n var total = done.length, open = 0;\n for (var k = 0; k < done.length; k++) if (!done[k]) open++;\n return { total: total, incomplete: open };\n }, { total: null, incomplete: null });\n l.reminderCount = counts.total;\n l.incompleteCount = counts.incomplete;\n out.push(l);\n }\n }\n return ok(out);\n`);\n\n/**\n * Every reminder's metadata, as bulk arrays.\n *\n * MEASURED on macOS 26.6 over 317 reminders: each bulk property fetch costs\n * ~700ms and is independent of library size, so this is ~9 seconds of Apple\n * Events. That is the price of the unprivileged lane, and it is why the result\n * is cached on a TTL and why the index lane carries listing whenever it is\n * live. The per-reminder alternative would be twelve events EACH.\n *\n * ## Subtasks are not reachable here\n *\n * The dictionary types `reminder.container` as \"list OR reminder\", which reads\n * like subtasks are addressable over Apple Events. They are not: calling\n * `container()` on a reminder threw on 60 of 60 attempts. So parentage is left\n * null on this lane and the index fills it in from `ZPARENTREMINDER`.\n *\n * Subtasks are still LISTED — `R.reminders()` returns all 317, matching the\n * store exactly — they simply arrive without a parent. Missing parentage and a\n * missing reminder are very different claims, so `parentId` is null rather than\n * the row being dropped.\n */\nexport const BULK_REMINDERS = script(`\n var ids = R.reminders.id();\n var count = ids.length;\n var dueDates = prop(function () { return R.reminders.dueDate(); }, []);\n var allDayDates = prop(function () { return R.reminders.alldayDueDate(); }, []);\n\n var rows = zip(\n [\"id\", \"name\", \"body\", \"completed\", \"completionDate\", \"remindMeDate\",\n \"priority\", \"flagged\", \"created\", \"modified\"],\n [\n ids,\n prop(function () { return R.reminders.name(); }, []),\n prop(function () { return R.reminders.body(); }, []),\n prop(function () { return R.reminders.completed(); }, []),\n prop(function () { return R.reminders.completionDate(); }, []),\n prop(function () { return R.reminders.remindMeDate(); }, []),\n prop(function () { return R.reminders.priority(); }, []),\n prop(function () { return R.reminders.flagged(); }, []),\n prop(function () { return R.reminders.creationDate(); }, []),\n prop(function () { return R.reminders.modificationDate(); }, [])\n ],\n count\n );\n\n var accounts = R.accounts();\n var lists = [];\n for (var i = 0; i < accounts.length; i++) {\n var accountId = prop(function () { return String(accounts[i].id()); }, null);\n lists = lists.concat(listTree(accounts[i], accountId, 1, []));\n }\n var member = membership(lists);\n var listOf = member.map;\n var accountNames = {};\n for (var n = 0; n < accounts.length; n++) {\n accountNames[String(prop(function () { return String(accounts[n].id()); }, \"\"))] =\n prop(function () { return String(accounts[n].name()); }, null);\n }\n\n var unmapped = 0;\n for (var r = 0; r < rows.length; r++) {\n var row = rows[r];\n row.id = String(row.id);\n row.completionDate = iso(row.completionDate);\n row.remindMeDate = iso(row.remindMeDate);\n row.created = iso(row.created);\n row.modified = iso(row.modified);\n\n // Both properties are populated for every dated reminder, so the local\n // time component is the only signal available without the index.\n var due = r < dueDates.length ? dueDates[r] : null;\n var allday = r < allDayDates.length ? allDayDates[r] : null;\n row.dueDate = iso(due);\n row.alldayDueDate = iso(allday);\n row.allDayGuess = isMidnight(allday || due);\n row.dueDay = dayOf(allday || due);\n\n // Apple Events cannot answer this; the index does. Null means unknown.\n row.parentId = null;\n\n var where = listOf[row.id];\n if (where) {\n row.list = where.list;\n row.listId = where.listId;\n row.accountId = where.accountId;\n row.account = accountNames[String(where.accountId)] || null;\n } else {\n row.list = null; row.listId = null; row.accountId = null; row.account = null;\n unmapped++;\n }\n }\n\n return ok({\n count: count,\n reminders: rows,\n lists: lists,\n unmapped: unmapped,\n membershipVia: member.via\n });\n`);\n\n/**\n * Full detail for a specific set of reminders, by id.\n *\n * Used after the index narrows things down, and to re-read a reminder after a\n * write so the result reflects what Reminders actually stored rather than what\n * was requested.\n */\nexport const GET_REMINDERS = script(`\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = String(p.ids[i]);\n var r = null;\n try { r = R.reminders.byId(id); } catch (e) { r = null; }\n if (!r) { out.push({ id: id, found: false }); continue; }\n // container() throws on a reminder on macOS 26.6 (60/60 attempts), so this\n // is expected to be null. Kept because it costs nothing when it fails and\n // would start working silently if Apple ever fixes it.\n var container = prop(function () { return r.container(); }, null);\n var containerClass = container === null ? null : prop(function () { return String(container.class()); }, null);\n var dueRaw = prop(function () { return r.dueDate(); }, null);\n var allDayRaw = prop(function () { return r.alldayDueDate(); }, null);\n out.push({\n id: id,\n found: true,\n name: prop(function () { return String(r.name()); }, null),\n body: prop(function () { var b = r.body(); return b === null ? null : String(b); }, null),\n completed: prop(function () { return r.completed(); }, null),\n completionDate: iso(prop(function () { return r.completionDate(); }, null)),\n dueDate: iso(dueRaw),\n alldayDueDate: iso(allDayRaw),\n allDayGuess: isMidnight(allDayRaw || dueRaw),\n dueDay: dayOf(allDayRaw || dueRaw),\n remindMeDate: iso(prop(function () { return r.remindMeDate(); }, null)),\n priority: prop(function () { return r.priority(); }, 0),\n flagged: prop(function () { return r.flagged(); }, false),\n created: iso(prop(function () { return r.creationDate(); }, null)),\n modified: iso(prop(function () { return r.modificationDate(); }, null)),\n containerClass: containerClass,\n containerId: container === null ? null : prop(function () { return String(container.id()); }, null),\n containerName: container === null ? null : prop(function () { return String(container.name()); }, null)\n });\n }\n return ok(out);\n`);\n","import { script } from \"./core.js\";\n\n/**\n * Mutating scripts.\n *\n * These are the only place Reminders is asked to change anything, and every one\n * of them re-reads the affected reminder afterwards: the result a tool returns\n * is what Reminders stored, never what the caller requested. The two differ\n * more often than you would expect — setting `dueDate` on an all-day reminder\n * is a property assignment whose visible effect is decided by the app.\n *\n * Dates arrive as ISO-8601 strings carrying an explicit offset (see\n * `dates.ts`) and are turned back into Date objects here. Passing a bare local\n * string would have Reminders resolve it in whatever zone it feels like.\n */\n\n/** Read-back shape, shared by every write so their results are uniform. */\nconst READBACK = `\nfunction readback(r) {\n return {\n id: prop(function () { return String(r.id()); }, null),\n name: prop(function () { return String(r.name()); }, null),\n body: prop(function () { var b = r.body(); return b === null ? null : String(b); }, null),\n completed: prop(function () { return r.completed(); }, null),\n completionDate: iso(prop(function () { return r.completionDate(); }, null)),\n dueDate: iso(prop(function () { return r.dueDate(); }, null)),\n alldayDueDate: iso(prop(function () { return r.alldayDueDate(); }, null)),\n remindMeDate: iso(prop(function () { return r.remindMeDate(); }, null)),\n priority: prop(function () { return r.priority(); }, 0),\n flagged: prop(function () { return r.flagged(); }, false),\n created: iso(prop(function () { return r.creationDate(); }, null)),\n modified: iso(prop(function () { return r.modificationDate(); }, null))\n };\n}\n\n/** Apply the optional fields a create and an update have in common. */\nfunction applyFields(target, f) {\n if (f.name !== undefined && f.name !== null) target.name = String(f.name);\n if (f.body !== undefined) target.body = f.body === null ? \"\" : String(f.body);\n if (f.dueDate !== undefined && f.dueDate !== null) target.dueDate = new Date(f.dueDate);\n if (f.alldayDueDate !== undefined && f.alldayDueDate !== null) target.alldayDueDate = new Date(f.alldayDueDate);\n if (f.remindMeDate !== undefined && f.remindMeDate !== null) target.remindMeDate = new Date(f.remindMeDate);\n if (f.priority !== undefined && f.priority !== null) target.priority = f.priority;\n if (f.flagged !== undefined && f.flagged !== null) target.flagged = f.flagged;\n if (f.completed !== undefined && f.completed !== null) target.completed = f.completed;\n}\n`;\n\n/**\n * Create a reminder.\n *\n * `listId` is optional: with none, Reminders' own default list wins, which is\n * the same list the app would have used. Guessing \"the first list\" instead\n * would put things somewhere the person does not look.\n */\nexport const CREATE_REMINDER = script(\n `${READBACK}\n var target = null;\n if (p.listId) {\n try { target = R.lists.byId(String(p.listId)); } catch (e) { target = null; }\n if (!target) return err(\"LIST_NOT_FOUND\", \"No list with id \" + p.listId);\n } else {\n target = prop(function () { return R.defaultList; }, null);\n if (!target) return err(\"NO_DEFAULT_LIST\", \"Reminders reports no default list.\");\n }\n\n var fields = { name: String(p.name) };\n var r = R.Reminder(fields);\n target.reminders.push(r);\n // Set the rest AFTER the push: a Reminder object that is not yet in a\n // container has nowhere to store a date, and the assignment is dropped.\n applyFields(r, p);\n return ok(readback(r));\n`,\n { allowLaunch: true },\n);\n\n/** Update whatever fields were supplied, leaving the rest untouched. */\nexport const UPDATE_REMINDER = script(\n `${READBACK}\n var r = null;\n try { r = R.reminders.byId(String(p.id)); } catch (e) { r = null; }\n if (!r) return err(\"REMINDER_NOT_FOUND\", \"No reminder with id \" + p.id);\n applyFields(r, p);\n return ok(readback(r));\n`,\n { allowLaunch: true },\n);\n\n/**\n * Complete (or un-complete) reminders in bulk.\n *\n * Separate from update because it is the single most common mutation and is\n * naturally plural — a caller ticking off four things should not have to make\n * four round trips.\n */\nexport const COMPLETE_REMINDERS = script(\n `${READBACK}\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = String(p.ids[i]);\n var r = null;\n try { r = R.reminders.byId(id); } catch (e) { r = null; }\n if (!r) { out.push({ id: id, found: false }); continue; }\n r.completed = p.completed === false ? false : true;\n var after = readback(r);\n after.found = true;\n out.push(after);\n }\n return ok(out);\n`,\n { allowLaunch: true },\n);\n\n/**\n * Move reminders to another list.\n *\n * **This is a copy followed by a delete, and it cannot be anything else.**\n * `reminder.container` is declared `access=\"r\"` in the scripting dictionary, so\n * there is no assignment that relocates a reminder. Two consequences the caller\n * has to know about, and which the tool description repeats:\n *\n * - the reminder gets a **new id**, so any ref held for it stops resolving\n * - the creation date becomes now, because a new object is what was made\n *\n * The original is deleted only after the copy has been created and read back.\n * If the copy fails, nothing is destroyed and the failure is reported per id.\n */\nexport const MOVE_REMINDERS = script(\n `${READBACK}\n var target = null;\n try { target = R.lists.byId(String(p.listId)); } catch (e) { target = null; }\n if (!target) return err(\"LIST_NOT_FOUND\", \"No list with id \" + p.listId);\n\n var out = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = String(p.ids[i]);\n var src = null;\n try { src = R.reminders.byId(id); } catch (e) { src = null; }\n if (!src) { out.push({ id: id, found: false }); continue; }\n\n var snapshot = readback(src);\n // Reminders fills BOTH date properties for every dated reminder, and the\n // last one assigned wins: setting alldayDueDate after dueDate kept only the\n // day, so a reminder due at 16:40 arrived all-day. Copy exactly one, chosen\n // by ZALLDAY when the caller had the index, else by the local-midnight guess.\n var known = p.allDay ? p.allDay[id] : undefined;\n var dueSource = snapshot.dueDate || snapshot.alldayDueDate;\n var allDay = known === true || known === false\n ? known\n : isMidnight(dueSource ? new Date(dueSource) : null);\n var copy = R.Reminder({ name: snapshot.name === null ? \"\" : snapshot.name });\n target.reminders.push(copy);\n applyFields(copy, {\n body: snapshot.body,\n dueDate: allDay ? null : dueSource,\n alldayDueDate: allDay ? dueSource : null,\n remindMeDate: snapshot.remindMeDate,\n priority: snapshot.priority,\n flagged: snapshot.flagged,\n completed: snapshot.completed\n });\n var made = readback(copy);\n if (made.id === null) {\n out.push({ id: id, found: true, moved: false, error: \"the copy could not be read back; nothing was deleted\" });\n continue;\n }\n // Only now is the original expendable.\n var deleted = true;\n try { R.delete(src); } catch (e) { deleted = false; }\n made.found = true;\n made.moved = true;\n made.previousId = id;\n made.originalDeleted = deleted;\n out.push(made);\n }\n return ok(out);\n`,\n { allowLaunch: true },\n);\n\n/** Delete reminders. Irreversible: they do not land anywhere recoverable. */\nexport const DELETE_REMINDERS = script(\n `\n var deleted = 0;\n var missing = [];\n for (var i = 0; i < p.ids.length; i++) {\n var id = String(p.ids[i]);\n var r = null;\n try { r = R.reminders.byId(id); } catch (e) { r = null; }\n if (!r) { missing.push(id); continue; }\n try { R.delete(r); deleted++; } catch (e) { missing.push(id); }\n }\n return ok({ deleted: deleted, missing: missing });\n`,\n { allowLaunch: true },\n);\n","import type { DatabaseSync } from \"node:sqlite\";\n\nimport {\n columnsOf,\n CORE_DATA_EPOCH_OFFSET,\n escapeLike,\n fingerprintSchema,\n openReadOnly,\n SchemaDriftError,\n type Logger,\n type ReadOnlyMode,\n} from \"@mgcrea/mcp-apple-core\";\n\n/**\n * The index lane: Reminders' Core Data store, read-only.\n *\n * Every fact encoded here was measured by `scripts/probe-reminders.mjs` against\n * a real store on macOS 26.6 — see docs/reminders.md. The three that matter:\n *\n * 1. **The bridge is `ZREMCDREMINDER.ZCKIDENTIFIER`**, which holds the bare\n * UUID from the Apple Events id `x-apple-reminder://<uuid>`. Found by\n * scanning all 139 TEXT columns for a known id rather than by guessing a\n * name — the guess would have been plausible and wrong, which is how the\n * Notes body decoder passed at 51% accuracy.\n *\n * 2. **The live predicate is `ZMARKEDFORDELETION` falsy.** Verified by\n * comparing ID SETS against Apple Events, not counts: all rows gave 338 with\n * 21 extra, the filtered set gave exactly 317 with 0 missing and 0 extra. A\n * matching count is not a matching set.\n *\n * 3. **`ZALLDAY` is the authoritative all-day flag**, and it exists nowhere\n * else. Apple Events populates both `due date` and `allday due date` for\n * every dated reminder — 144 of 144 carried both — so presence discriminates\n * nothing there. This column is the whole reason the index improves\n * correctness and not merely speed.\n *\n * Writes never come here. The Apple Events lane is the authority for mutation,\n * as in Mail and Notes; this store is opened read-only and `PRAGMA query_only`\n * is set on top.\n */\n\n/** Tables the lane cannot work without. Anything else degrades to a null field. */\nconst REQUIRED = [\"ZREMCDREMINDER\", \"ZREMCDBASELIST\"] as const;\n\nexport type StoreCapabilities = {\n fingerprint: string;\n /** Present columns, so an Apple rename degrades one field instead of the lane. */\n reminderColumns: Set<string>;\n listColumns: Set<string>;\n hasAttachments: boolean;\n hasObjects: boolean;\n epochOffset: number;\n};\n\nexport type IndexReminder = {\n primaryKey: number;\n /** The bridge to an Apple Events id. Null rows cannot be joined to the app. */\n uuid: string | null;\n title: string | null;\n notes: string | null;\n completed: boolean;\n /** The one thing Apple Events genuinely cannot tell you. */\n allDay: boolean;\n due: string | null;\n completionDate: string | null;\n created: string | null;\n modified: string | null;\n priority: number | null;\n flagged: boolean;\n listPk: number | null;\n listName: string | null;\n parentPk: number | null;\n parentUuid: string | null;\n};\n\nexport type IndexList = {\n primaryKey: number;\n uuid: string | null;\n name: string | null;\n isGroup: boolean;\n parentListPk: number | null;\n smartListType: string | null;\n};\n\nexport type IndexAttachment = {\n primaryKey: number;\n uuid: string | null;\n reminderPk: number | null;\n filename: string | null;\n uti: string | null;\n sha512: string | null;\n};\n\n/** Enrichment the scripting dictionary has no class for at all. */\nexport type IndexEnrichment = {\n alarmCount: number;\n hasRecurrence: boolean;\n location: { latitude: number; longitude: number; proximity: number | null } | null;\n};\n\nexport type ReminderQuery = {\n query?: string | undefined;\n scope?: \"title\" | \"full\" | undefined;\n listPk?: number | undefined;\n includeCompleted?: boolean | undefined;\n limit: number;\n offset?: number | undefined;\n};\n\n/** SQLite hands back unknown; only a real number is a value. */\nconst num = (v: unknown): number | null => (typeof v === \"number\" ? v : null);\n\n/** Core Data seconds -> ISO, or null. Guards the 31-year offset mistake. */\nconst toIso = (seconds: number | null, offset: number): string | null => {\n if (seconds === null || seconds === undefined || !Number.isFinite(seconds)) return null;\n const d = new Date((seconds + offset) * 1000);\n return Number.isNaN(d.getTime()) ? null : d.toISOString();\n};\n\nexport class ReminderStore {\n readonly db: DatabaseSync;\n readonly mode: string;\n readonly caps: StoreCapabilities;\n\n constructor(db: DatabaseSync, mode: string, caps: StoreCapabilities) {\n this.db = db;\n this.mode = mode;\n this.caps = caps;\n }\n\n /** Only select columns this store actually has, so a rename degrades one field. */\n #col(table: \"reminder\" | \"list\", name: string, as = name): string {\n const set = table === \"reminder\" ? this.caps.reminderColumns : this.caps.listColumns;\n return set.has(name) ? `r.\"${name}\" AS ${as}` : `NULL AS ${as}`;\n }\n\n /**\n * The live-reminder predicate, verified by set comparison against Apple\n * Events. `ZMARKEDFORDELETION` is a tombstone Reminders leaves behind until\n * the CloudKit sync settles; without this filter the store reports 21 rows\n * the user deleted and cannot see.\n */\n #live(): string {\n return this.caps.reminderColumns.has(\"ZMARKEDFORDELETION\")\n ? `(r.\"ZMARKEDFORDELETION\" IS NULL OR r.\"ZMARKEDFORDELETION\" = 0)`\n : \"1 = 1\";\n }\n\n #selectList(): string {\n return this.caps.listColumns.has(\"ZNAME\") ? `l.\"ZNAME\"` : \"NULL\";\n }\n\n #rowToReminder = (row: Record<string, unknown>): IndexReminder => {\n const o = this.caps.epochOffset;\n return {\n primaryKey: row.pk as number,\n uuid: row.uuid === null || row.uuid === undefined ? null : String(row.uuid).toUpperCase(),\n title: (row.title as string | null) ?? null,\n notes: (row.notes as string | null) ?? null,\n completed: Boolean(row.completed),\n allDay: Boolean(row.allday),\n due: toIso(num(row.due), o),\n completionDate: toIso(num(row.completionDate), o),\n created: toIso(num(row.created), o),\n modified: toIso(num(row.modified), o),\n priority: num(row.priority),\n flagged: Boolean(row.flagged),\n listPk: num(row.listPk),\n listName: (row.listName as string | null) ?? null,\n parentPk: num(row.parentPk),\n parentUuid:\n row.parentUuid === null || row.parentUuid === undefined\n ? null\n : String(row.parentUuid).toUpperCase(),\n };\n };\n\n #baseSelect(): string {\n return `SELECT r.\"Z_PK\" AS pk,\n ${this.#col(\"reminder\", \"ZCKIDENTIFIER\", \"uuid\")},\n ${this.#col(\"reminder\", \"ZTITLE\", \"title\")},\n ${this.#col(\"reminder\", \"ZNOTES\", \"notes\")},\n ${this.#col(\"reminder\", \"ZCOMPLETED\", \"completed\")},\n ${this.#col(\"reminder\", \"ZALLDAY\", \"allday\")},\n ${this.#col(\"reminder\", \"ZDUEDATE\", \"due\")},\n ${this.#col(\"reminder\", \"ZCOMPLETIONDATE\", \"completionDate\")},\n ${this.#col(\"reminder\", \"ZCREATIONDATE\", \"created\")},\n ${this.#col(\"reminder\", \"ZLASTMODIFIEDDATE\", \"modified\")},\n ${this.#col(\"reminder\", \"ZPRIORITY\", \"priority\")},\n ${this.#col(\"reminder\", \"ZFLAGGED\", \"flagged\")},\n ${this.#col(\"reminder\", \"ZLIST\", \"listPk\")},\n ${this.#col(\"reminder\", \"ZPARENTREMINDER\", \"parentPk\")},\n ${this.#col(\"reminder\", \"ZCKPARENTREMINDERIDENTIFIER\", \"parentUuid\")},\n ${this.#selectList()} AS listName\n FROM ZREMCDREMINDER r\n LEFT JOIN ZREMCDBASELIST l ON l.\"Z_PK\" = r.\"ZLIST\"`;\n }\n\n search(q: ReminderQuery): IndexReminder[] {\n const where: string[] = [this.#live()];\n const params: (string | number)[] = [];\n\n if (!q.includeCompleted && this.caps.reminderColumns.has(\"ZCOMPLETED\")) {\n where.push(`(r.\"ZCOMPLETED\" IS NULL OR r.\"ZCOMPLETED\" = 0)`);\n }\n if (q.listPk !== undefined) {\n where.push(`r.\"ZLIST\" = ?`);\n params.push(q.listPk);\n }\n if (q.query) {\n // ESCAPE is not optional: a reminder called \"100% rye\" would otherwise\n // make every query containing % match everything.\n const needle = `%${escapeLike(q.query)}%`;\n const full = (q.scope ?? \"full\") === \"full\" && this.caps.reminderColumns.has(\"ZNOTES\");\n where.push(\n full\n ? `(r.\"ZTITLE\" LIKE ? ESCAPE '\\\\' OR r.\"ZNOTES\" LIKE ? ESCAPE '\\\\')`\n : `r.\"ZTITLE\" LIKE ? ESCAPE '\\\\'`,\n );\n params.push(needle);\n if (full) params.push(needle);\n }\n\n // Undated reminders sort last: ZDUEDATE is NULL for them, and NULL sorts\n // first in SQLite, which would bury everything that actually has a deadline.\n const rows = this.db\n .prepare(\n `${this.#baseSelect()} WHERE ${where.join(\" AND \")}\n ORDER BY (r.\"ZDUEDATE\" IS NULL), r.\"ZDUEDATE\" ASC, r.\"ZTITLE\" ASC\n LIMIT ? OFFSET ?`,\n )\n .all(...params, q.limit, q.offset ?? 0) as Record<string, unknown>[];\n return rows.map(this.#rowToReminder);\n }\n\n byUuid(uuid: string): IndexReminder | null {\n if (!this.caps.reminderColumns.has(\"ZCKIDENTIFIER\")) return null;\n // Stored case is not guaranteed to match the id Apple Events hands out.\n const row = this.db\n .prepare(\n `${this.#baseSelect()} WHERE ${this.#live()} AND UPPER(r.\"ZCKIDENTIFIER\") = ? LIMIT 1`,\n )\n .get(uuid.toUpperCase()) as Record<string, unknown> | undefined;\n return row ? this.#rowToReminder(row) : null;\n }\n\n /**\n * Subtasks, which Apple Events cannot reach at all — `container()` throws on\n * every reminder, so this column is the only way to know a reminder has a\n * parent.\n */\n subtasksOf(parentPk: number): IndexReminder[] {\n if (!this.caps.reminderColumns.has(\"ZPARENTREMINDER\")) return [];\n const rows = this.db\n .prepare(\n // Same tiebreaker as search(): subtasks are usually all undated, so\n // without the title they come back in whatever order the table gives.\n `${this.#baseSelect()} WHERE ${this.#live()} AND r.\"ZPARENTREMINDER\" = ?\n ORDER BY (r.\"ZDUEDATE\" IS NULL), r.\"ZDUEDATE\" ASC, r.\"ZTITLE\" ASC`,\n )\n .all(parentPk) as Record<string, unknown>[];\n return rows.map(this.#rowToReminder);\n }\n\n lists(): IndexList[] {\n const c = this.caps.listColumns;\n const pick = (n: string, as: string) => (c.has(n) ? `\"${n}\" AS ${as}` : `NULL AS ${as}`);\n const live = c.has(\"ZMARKEDFORDELETION\")\n ? `WHERE (\"ZMARKEDFORDELETION\" IS NULL OR \"ZMARKEDFORDELETION\" = 0)`\n : \"\";\n const rows = this.db\n .prepare(\n `SELECT \"Z_PK\" AS pk, ${pick(\"ZCKIDENTIFIER\", \"uuid\")}, ${pick(\"ZNAME\", \"name\")},\n ${pick(\"ZISGROUP\", \"isGroup\")}, ${pick(\"ZPARENTLIST\", \"parentListPk\")},\n ${pick(\"ZSMARTLISTTYPE\", \"smartListType\")}\n FROM ZREMCDBASELIST ${live} ORDER BY \"ZNAME\"`,\n )\n .all() as Record<string, unknown>[];\n return rows.map((r) => ({\n primaryKey: r.pk as number,\n uuid: r.uuid === null || r.uuid === undefined ? null : String(r.uuid).toUpperCase(),\n name: (r.name as string | null) ?? null,\n isGroup: Boolean(r.isGroup),\n parentListPk: typeof r.parentListPk === \"number\" ? r.parentListPk : null,\n smartListType: (r.smartListType as string | null) ?? null,\n }));\n }\n\n attachmentsOf(reminderPk: number): IndexAttachment[] {\n if (!this.caps.hasAttachments) return [];\n const rows = this.db\n .prepare(\n `SELECT \"Z_PK\" AS pk, \"ZCKIDENTIFIER\" AS uuid, \"ZREMINDER\" AS reminderPk,\n \"ZFILENAME\" AS filename, \"ZUTI\" AS uti, \"ZSHA512SUM\" AS sha512\n FROM ZREMCDSAVEDATTACHMENT\n WHERE \"ZREMINDER\" = ? AND (\"ZMARKEDFORDELETION\" IS NULL OR \"ZMARKEDFORDELETION\" = 0)`,\n )\n .all(reminderPk) as Record<string, unknown>[];\n return rows.map((r) => ({\n primaryKey: r.pk as number,\n uuid: r.uuid === null || r.uuid === undefined ? null : String(r.uuid).toUpperCase(),\n reminderPk: typeof r.reminderPk === \"number\" ? r.reminderPk : null,\n filename: (r.filename as string | null) ?? null,\n uti: (r.uti as string | null) ?? null,\n sha512: (r.sha512 as string | null) ?? null,\n }));\n }\n\n /**\n * Alarms, recurrence and location for one reminder.\n *\n * `ZREMCDOBJECT` is polymorphic — alarm rows and recurrence rows share it and\n * are told apart by which columns are populated, not by a type column we can\n * rely on. So this reports presence and counts rather than pretending to\n * reconstruct an RFC 5545 rule from columns nobody has documented.\n */\n enrichmentOf(reminderPk: number): IndexEnrichment {\n const empty: IndexEnrichment = { alarmCount: 0, hasRecurrence: false, location: null };\n if (!this.caps.hasObjects) return empty;\n const rows = this.db\n .prepare(\n `SELECT \"ZFREQUENCY\" AS frequency, \"ZLATITUDE\" AS latitude, \"ZLONGITUDE\" AS longitude,\n \"ZPROXIMITY\" AS proximity, \"ZALARMUID\" AS alarmUid\n FROM ZREMCDOBJECT WHERE \"ZREMINDER\" = ?`,\n )\n .all(reminderPk) as Record<string, unknown>[];\n if (!rows.length) return empty;\n\n let alarmCount = 0;\n let hasRecurrence = false;\n let location: IndexEnrichment[\"location\"] = null;\n for (const r of rows) {\n if (r.alarmUid !== null && r.alarmUid !== undefined) alarmCount += 1;\n if (typeof r.frequency === \"number\") hasRecurrence = true;\n if (typeof r.latitude === \"number\" && typeof r.longitude === \"number\" && !location) {\n location = {\n latitude: r.latitude,\n longitude: r.longitude,\n proximity: typeof r.proximity === \"number\" ? r.proximity : null,\n };\n }\n }\n return { alarmCount, hasRecurrence, location };\n }\n}\n\n/** Read the store's shape once, so every query can degrade per column. */\nexport const introspect = (db: DatabaseSync): StoreCapabilities => {\n const reminderColumns = new Set(columnsOf(db, \"ZREMCDREMINDER\"));\n const listColumns = new Set(columnsOf(db, \"ZREMCDBASELIST\"));\n for (const t of REQUIRED) {\n const cols = t === \"ZREMCDREMINDER\" ? reminderColumns : listColumns;\n if (cols.size === 0) {\n throw new SchemaDriftError(\n `This Reminders store has no ${t} table. It was probed on macOS 26.6 with schema ` +\n `fingerprint 278b001e3c55; re-run \\`pnpm probe:reminders\\` to see what changed.`,\n );\n }\n }\n return {\n fingerprint: fingerprintSchema(db),\n reminderColumns,\n listColumns,\n hasAttachments: columnsOf(db, \"ZREMCDSAVEDATTACHMENT\").length > 0,\n hasObjects: columnsOf(db, \"ZREMCDOBJECT\").length > 0,\n // Measured at 978307200 on this store, but detected rather than assumed:\n // being 31 years out is the classic Core Data date bug.\n epochOffset: CORE_DATA_EPOCH_OFFSET,\n };\n};\n\nexport const openStore = (\n path: string | null,\n mode: ReadOnlyMode,\n logger?: Logger,\n): ReminderStore | null => {\n if (!path) return null;\n const {\n db,\n mode: used,\n validated,\n } = openReadOnly<StoreCapabilities>(path, mode, {\n label: \"Reminders store\",\n envVar: \"APPLE_REMINDERS_INDEX_MODE\",\n validate: introspect,\n fatal: (err) => err instanceof SchemaDriftError,\n onFallback: () =>\n logger?.debug?.(\n \"opened the Reminders store with immutable=1, which skips the write-ahead log — \" +\n \"very recent changes may be missing until Reminders checkpoints.\",\n ),\n });\n return new ReminderStore(db, used, validated);\n};\n","import {\n createOsascriptRunner,\n withBusyRetry,\n type Logger,\n type OsascriptRunner,\n} from \"@mgcrea/mcp-apple-core\";\n\nimport type { Config } from \"../config.js\";\nimport { parseBound, parseDate, type ParsedDate } from \"./dates.js\";\nimport { ListNotFoundError, ReminderNotFoundError, REMINDERS_SURFACE } from \"./errors.js\";\nimport { BULK_REMINDERS, GET_REMINDERS, LIST_ACCOUNTS, LIST_LISTS } from \"./jxa/read.js\";\nimport {\n COMPLETE_REMINDERS,\n CREATE_REMINDER,\n DELETE_REMINDERS,\n MOVE_REMINDERS,\n UPDATE_REMINDER,\n} from \"./jxa/write.js\";\nimport { locateStore, type LocateResult } from \"./locate.js\";\nimport { toPriorityName, toPriorityValue, type PriorityName } from \"./priority.js\";\nimport { decodeRef, encodeRef, refFromUuid } from \"./ref.js\";\nimport { openStore, ReminderStore, type IndexEnrichment, type IndexReminder } from \"./store.js\";\n\nexport type LaneStatus = {\n applescript: \"live\" | \"unavailable\";\n index: \"live\" | \"unavailable\" | \"disabled\";\n indexMode: string | null;\n storeFingerprint: string | null;\n reason: string | null;\n};\n\nexport type ReminderAccount = {\n id: string | null;\n name: string | null;\n isDefault: boolean;\n listCount: number;\n reminderCount: number;\n};\n\nexport type ReminderList = {\n id: string | null;\n name: string | null;\n accountId: string | null;\n accountName: string | null;\n depth: number;\n color: string | null;\n emblem: string | null;\n isDefault: boolean;\n reminderCount: number | null;\n incompleteCount: number | null;\n};\n\nexport type ReminderSummary = {\n ref: string;\n name: string | null;\n completed: boolean;\n /** The effective due instant, whichever of the two properties carries it. */\n due: string | null;\n /** True when the due date names a day rather than a time. */\n dueAllDay: boolean;\n /**\n * Where `dueAllDay` came from.\n *\n * `index` is `ZALLDAY`, which is authoritative. `heuristic` means the index\n * was unavailable and the flag was inferred from the due time being local\n * midnight — because Apple Events populates BOTH date properties for every\n * dated reminder and so cannot answer the question itself.\n */\n dueAllDaySource: \"index\" | \"heuristic\";\n remindMe: string | null;\n priority: PriorityName;\n flagged: boolean;\n list: string | null;\n account: string | null;\n /** Set when this reminder's container is another reminder, i.e. it is a subtask. */\n parentRef: string | null;\n created: string | null;\n modified: string | null;\n source: \"index\" | \"apple-events\";\n};\n\n/**\n * A page of reminders, plus what a bare array could not say: which lane\n * answered, and whether anything was left behind.\n *\n * Both lanes truncate, for different reasons, and neither had a way to admit\n * it. Apple Events reads every reminder and then cuts to a cap independent of\n * `limit`. The index lane over-fetches from SQL and applies the date and flag\n * predicates afterwards in JS, so a query whose filters reject most rows can\n * exhaust the over-fetch window before it fills the page — a short list that\n * looks complete. `note` names whichever of the two happened.\n */\nexport type ReminderListing = {\n reminders: ReminderSummary[];\n source: \"index\" | \"apple-events\";\n hasMore: boolean;\n note?: string;\n};\n\nexport type ReminderDetail = ReminderSummary & {\n body: string | null;\n completionDate: string | null;\n /** Kept separate from `due` so a caller can see which property actually holds it. */\n dueDate: string | null;\n alldayDueDate: string | null;\n subtasks: ReminderSummary[];\n /**\n * Fields the scripting dictionary has no class for. Null — not empty — when\n * the index lane is unavailable, so a caller can tell \"none\" from \"unknown\".\n */\n attachments: { id: string | null; filename: string | null; uti: string | null }[] | null;\n alarms: IndexEnrichment | null;\n};\n\n/** Filters accepted by list and search. Every one is applied in JS over bulk arrays. */\nexport type ReminderFilters = {\n list?: string | undefined;\n includeCompleted?: boolean | undefined;\n dueBefore?: string | undefined;\n dueAfter?: string | undefined;\n flagged?: boolean | undefined;\n priority?: PriorityName | undefined;\n hasDueDate?: boolean | undefined;\n limit: number;\n};\n\n/** The fields a create or update may set. Absent means \"leave alone\". */\nexport type ReminderFields = {\n name?: string | undefined;\n body?: string | null | undefined;\n due?: string | undefined;\n remindMe?: string | undefined;\n priority?: PriorityName | undefined;\n flagged?: boolean | undefined;\n completed?: boolean | undefined;\n};\n\n/** One row as the bulk read returns it, before any interpretation. */\ntype RawReminder = {\n id: string;\n name: string | null;\n body: string | null;\n completed: boolean | null;\n completionDate: string | null;\n dueDate: string | null;\n alldayDueDate: string | null;\n remindMeDate: string | null;\n priority: number | null;\n flagged: boolean | null;\n created: string | null;\n modified: string | null;\n list: string | null;\n listId: string | null;\n account: string | null;\n accountId: string | null;\n parentId: string | null;\n /** Local-midnight heuristic computed inside JXA, where the time zone is real. */\n allDayGuess?: boolean;\n /** The local calendar day, also computed inside JXA. See jxa/core.ts. */\n dueDay?: string | null;\n};\n\ntype BulkPayload = {\n count: number;\n reminders: RawReminder[];\n lists: { id: string | null; name: string | null; accountId: string | null }[];\n unmapped: number;\n membershipVia: \"nested\" | \"per-list\";\n};\n\ntype BulkCache = { at: number; data: BulkPayload };\n\n/**\n * Render a due date for the caller.\n *\n * An all-day reminder names a DAY, and reporting it as an instant is wrong\n * rather than merely ugly — the same value reads as a different date either\n * side of Greenwich.\n *\n * Which day, though, depends on the lane, because the two genuinely disagree.\n * The same reminder, due 9 November, measured on a real library:\n *\n * Apple Events 2025-11-08T23:00:00Z LOCAL midnight (Paris, UTC+1)\n * ZDUEDATE 2025-11-09T00:00:00Z UTC midnight\n *\n * So neither lane's string can be sliced by the other's rule. Each converts on\n * its own terms — JXA formats from local components, the store from UTC — and\n * hands the finished day in here.\n */\nconst renderDue = (instant: string | null, allDay: boolean, day: string | null): string | null =>\n allDay ? day : instant;\n\n/** The store keeps all-day dates at UTC midnight, so the UTC date IS the day. */\nconst utcDay = (iso: string | null): string | null => (iso ? iso.slice(0, 10) : null);\n\n/** Sort key for due dates: undated reminders sort last rather than first. */\nconst dueAt = (s: ReminderSummary): number =>\n s.due ? new Date(s.due).getTime() : Number.MAX_SAFE_INTEGER;\n\nexport type AppleRemindersClientOptions = {\n config: Config;\n logger?: Logger | undefined;\n /** Injected by tests so nothing spawns a process or touches a real Reminders. */\n osascript?: OsascriptRunner | undefined;\n /** Injected by tests so the TTL cache can be exercised without waiting. */\n now?: (() => Date) | undefined;\n};\n\n/**\n * The Reminders client.\n *\n * Two lanes, and which one answers depends on what was granted:\n *\n * - **Apple Events** — accounts, lists, every mutation, and the whole core\n * model. Always the authority: after a write, the result is what Reminders\n * re-read, never what was requested.\n * - **Index** — the Core Data store, for the fields the scripting dictionary\n * has no class for at all: tags, url, recurrence, alarms.\n *\n * That split is the opposite way round from Mail, where the file lane exists\n * because Apple Events search took 74 seconds. Here the dictionary is complete\n * enough to ship on, and the permission buys capability rather than speed —\n * which is the rule recorded in docs/distribution.md.\n */\nexport class AppleRemindersClient {\n readonly config: Config;\n readonly runner: OsascriptRunner;\n readonly #logger: Logger | undefined;\n readonly #now: () => Date;\n #cache: BulkCache | null = null;\n #store: ReminderStore | null = null;\n #storeTried = false;\n\n constructor(opts: AppleRemindersClientOptions) {\n this.config = opts.config;\n this.#logger = opts.logger;\n this.#now = opts.now ?? (() => new Date());\n this.runner =\n opts.osascript ??\n createOsascriptRunner({\n osascriptPath: opts.config.osascriptPath,\n timeoutMs: opts.config.osascriptTimeoutMs,\n surface: REMINDERS_SURFACE,\n logger: opts.logger,\n });\n }\n\n locate(): LocateResult {\n return locateStore({ storePath: this.config.storePath });\n }\n\n /** Open the index once and remember the outcome, including the failure. */\n index(): ReminderStore | null {\n if (this.#storeTried) return this.#store;\n this.#storeTried = true;\n if (this.config.indexMode === \"off\") return null;\n try {\n this.#store = openStore(this.locate().storePath, this.config.indexMode, this.#logger);\n } catch (err) {\n this.#logger?.debug?.(\"index lane unavailable\", err);\n this.#store = null;\n }\n return this.#store;\n }\n\n /**\n * Probe both lanes.\n *\n * Apple Events is probed twice with a gap: the first event is what triggers\n * the Automation prompt, and it can return failure while the user is still\n * deciding — reporting \"denied\" then would be wrong.\n */\n async lanes(): Promise<LaneStatus> {\n let applescript: LaneStatus[\"applescript\"] = \"unavailable\";\n for (let attempt = 0; attempt < 2; attempt += 1) {\n try {\n await this.runner.run(LIST_ACCOUNTS);\n applescript = \"live\";\n break;\n } catch (err) {\n this.#logger?.debug?.(\"applescript probe failed\", err);\n if (attempt === 0) await new Promise((r) => setTimeout(r, 400));\n }\n }\n\n const located = this.locate();\n const store = this.index();\n return {\n applescript,\n index: this.config.indexMode === \"off\" ? \"disabled\" : store ? \"live\" : \"unavailable\",\n indexMode: store?.mode ?? null,\n storeFingerprint: store?.caps.fingerprint ?? null,\n reason: store ? null : located.reason,\n };\n }\n\n // ─── reads ────────────────────────────────────────────────────────────────\n\n #allowedAccount(name: string | null): boolean {\n const list = this.config.accounts;\n if (!list.length) return true;\n return Boolean(name && list.some((a) => a.toLowerCase() === name.toLowerCase()));\n }\n\n #allowedList(name: string | null): boolean {\n const list = this.config.lists;\n if (!list.length) return true;\n return Boolean(name && list.some((l) => l.toLowerCase() === name.toLowerCase()));\n }\n\n async accounts(): Promise<ReminderAccount[]> {\n const data = await withBusyRetry(() =>\n this.runner.run<{ accounts: ReminderAccount[] }>(LIST_ACCOUNTS),\n );\n return data.accounts.filter((a) => this.#allowedAccount(a.name));\n }\n\n async lists(): Promise<ReminderList[]> {\n const all = await withBusyRetry(() => this.runner.run<ReminderList[]>(LIST_LISTS));\n return all.filter((l) => this.#allowedAccount(l.accountName) && this.#allowedList(l.name));\n }\n\n /**\n * Every reminder, cached on a TTL.\n *\n * Same trade Notes documented: there is no cheap way to ask \"has anything\n * changed\" — the freshness check is itself a bulk fetch of ids and\n * modification dates, which costs about what re-reading everything costs. So\n * a TTL with bounded staleness is the honest option, and it is configurable\n * because the right bound depends on whether a person is actively editing.\n */\n async #bulk(): Promise<BulkPayload> {\n const ttl = this.config.searchCacheTtlMs;\n const now = this.#now().getTime();\n if (this.#cache && ttl > 0 && now - this.#cache.at < ttl) return this.#cache.data;\n\n const data = await withBusyRetry(() => this.runner.run<BulkPayload>(BULK_REMINDERS, {}));\n // ~700ms per property fetch on this bridge, so the nested membership call\n // is the difference between one round trip and one per list.\n if (data.membershipVia === \"per-list\") {\n this.#logger?.debug?.(\n `the chained membership fetch did not work; fell back to one call per list ` +\n `(${data.lists.length} extra Apple Events).`,\n );\n }\n if (data.unmapped) {\n this.#logger?.debug?.(\n `${data.unmapped} reminders belong to no list — usually subtasks, whose parentage ` +\n `only the index lane can resolve.`,\n );\n }\n this.#cache = { at: now, data };\n return data;\n }\n\n /** Drop the cache after a write, so the next read reflects it. */\n invalidate(): void {\n this.#cache = null;\n }\n\n #summarise(r: RawReminder, source: ReminderSummary[\"source\"] = \"apple-events\"): ReminderSummary {\n // MEASURED: Reminders populates BOTH date properties for every dated\n // reminder (144 of 144), so presence discriminates nothing and the earlier\n // \"allday wins\" rule marked every dated reminder as all-day. The JXA side\n // computes a local-midnight guess instead; `ZALLDAY` overrides it whenever\n // the index is live.\n const allDay = Boolean(r.allDayGuess);\n return {\n ref: encodeRef(r.id),\n name: r.name,\n completed: Boolean(r.completed),\n due: renderDue(r.dueDate ?? r.alldayDueDate, allDay, r.dueDay ?? null),\n dueAllDay: allDay,\n dueAllDaySource: \"heuristic\",\n remindMe: r.remindMeDate,\n priority: toPriorityName(r.priority),\n flagged: Boolean(r.flagged),\n list: r.list,\n account: r.account,\n parentRef: r.parentId ? encodeRef(r.parentId) : null,\n created: r.created,\n modified: r.modified,\n source,\n };\n }\n\n /**\n * Both range bounds, resolved ONCE per request.\n *\n * They used to be parsed inside the per-row matcher, behind an early return\n * for reminders with no due date. Two consequences, both silent: an invalid\n * bound was only reported if some row happened to carry a date, so\n * `dueBefore: \"sometime\"` over an all-undated list answered `[]` instead of\n * refusing; and the same string was re-parsed once per reminder.\n */\n static #bounds(f: ReminderFilters, now: Date): { before?: number; after?: number } {\n const out: { before?: number; after?: number } = {};\n if (f.dueBefore) out.before = parseBound(\"dueBefore\", f.dueBefore, \"end\", now).getTime();\n if (f.dueAfter) out.after = parseBound(\"dueAfter\", f.dueAfter, \"start\", now).getTime();\n return out;\n }\n\n /**\n * A due date as an instant, reading a bare day as LOCAL midnight.\n *\n * The index renders an all-day reminder as `\"2026-08-20\"`, and\n * `new Date(\"2026-08-20\")` is UTC midnight while every bound here is local.\n * West of Greenwich that put an all-day reminder before its own day's lower\n * bound, so it dropped out of a range that named it.\n */\n static #dueInstant(due: string): number {\n const bare = /^(\\d{4})-(\\d{2})-(\\d{2})$/.exec(due);\n if (bare) {\n return new Date(Number(bare[1]), Number(bare[2]) - 1, Number(bare[3])).getTime();\n }\n return new Date(due).getTime();\n }\n\n #matches(\n r: RawReminder,\n f: ReminderFilters,\n bounds: { before?: number; after?: number },\n ): boolean {\n if (!this.#allowedAccount(r.account) || !this.#allowedList(r.list)) return false;\n\n const includeCompleted = f.includeCompleted ?? this.config.includeCompleted;\n if (!includeCompleted && r.completed) return false;\n\n if (f.list) {\n const want = f.list.toLowerCase();\n if ((r.list ?? \"\").toLowerCase() !== want && r.listId !== f.list) return false;\n }\n if (f.flagged !== undefined && Boolean(r.flagged) !== f.flagged) return false;\n if (f.priority && toPriorityName(r.priority) !== f.priority) return false;\n\n const due = r.alldayDueDate ?? r.dueDate;\n if (f.hasDueDate !== undefined && Boolean(due) !== f.hasDueDate) return false;\n\n // A range bound over reminders with no due date at all would be a silent\n // \"no\": excluding them explicitly is the same answer, arrived at on purpose.\n if (bounds.before !== undefined || bounds.after !== undefined) {\n if (!due) return false;\n const at = AppleRemindersClient.#dueInstant(String(due));\n // `>=` rather than `>`: an upper bound is now the next day's midnight, so\n // it is exclusive and the day it names is fully included.\n if (bounds.before !== undefined && at >= bounds.before) return false;\n if (bounds.after !== undefined && at < bounds.after) return false;\n }\n return true;\n }\n\n /** Soonest-due first, then by urgency, with undated reminders last. */\n static #order(a: ReminderSummary, b: ReminderSummary): number {\n return dueAt(a) - dueAt(b) || a.name?.localeCompare(b.name ?? \"\") || 0;\n }\n\n /** An index row wears the same shape as an Apple Events one. */\n #fromIndex(r: IndexReminder, listName?: string | null): ReminderSummary {\n return {\n ref: r.uuid ? refFromUuid(r.uuid) : encodeRef(String(r.primaryKey)),\n name: r.title,\n completed: r.completed,\n due: renderDue(r.due, r.allDay, utcDay(r.due)),\n // ZALLDAY is the authoritative flag and exists nowhere else.\n dueAllDay: r.allDay,\n dueAllDaySource: \"index\",\n remindMe: null,\n priority: toPriorityName(r.priority),\n flagged: r.flagged,\n list: listName ?? r.listName,\n account: null,\n parentRef: r.parentUuid ? refFromUuid(r.parentUuid) : null,\n created: r.created,\n modified: r.modified,\n source: \"index\",\n };\n }\n\n /** Resolve a list name to its index primary key, for an index-side filter. */\n #listPk(store: ReminderStore, name: string): number | undefined {\n const want = name.toLowerCase();\n return store.lists().find((l) => l.name?.toLowerCase() === want)?.primaryKey;\n }\n\n /**\n * Post-filter index rows for the predicates SQL did not apply.\n *\n * Dates are compared here rather than in SQL because the bounds accept\n * relative offsets, which have to be resolved against the same clock the rest\n * of the request uses.\n */\n #matchesIndex(\n r: ReminderSummary,\n f: ReminderFilters,\n bounds: { before?: number; after?: number },\n ): boolean {\n if (!this.#allowedList(r.list)) return false;\n if (f.flagged !== undefined && r.flagged !== f.flagged) return false;\n if (f.priority && r.priority !== f.priority) return false;\n if (f.hasDueDate !== undefined && Boolean(r.due) !== f.hasDueDate) return false;\n if (bounds.before !== undefined || bounds.after !== undefined) {\n if (!r.due) return false;\n const at = AppleRemindersClient.#dueInstant(r.due);\n if (bounds.before !== undefined && at >= bounds.before) return false;\n if (bounds.after !== undefined && at < bounds.after) return false;\n }\n return true;\n }\n\n /**\n * The index path for listing and search.\n *\n * Preferred whenever the store is readable, and not only for scale: a bulk\n * Apple Events read costs ~700ms PER PROPERTY on this bridge — about nine\n * seconds for a full listing, whatever the library size. It is also the only\n * lane that knows whether a due date is all-day.\n */\n #fromStore(\n store: ReminderStore,\n filters: ReminderFilters,\n query: string | undefined,\n scope: \"title\" | \"full\" | undefined,\n now: Date,\n ): ReminderListing {\n // Resolved before the query runs, so an unreadable bound is refused even\n // when nothing would have matched it.\n const bounds = AppleRemindersClient.#bounds(filters, now);\n const listPk = filters.list ? this.#listPk(store, filters.list) : undefined;\n // A named list that the index does not know would otherwise silently widen\n // the query to every list, which is worse than returning nothing.\n if (filters.list && listPk === undefined) {\n return { reminders: [], source: \"index\", hasMore: false };\n }\n // Over-fetch, because the date and flag predicates are applied after SQL.\n const sqlLimit = Math.min(filters.limit * 4 + 50, 2_000);\n const rows = store.search({\n ...(query ? { query } : {}),\n ...(scope ? { scope } : {}),\n ...(listPk === undefined ? {} : { listPk }),\n includeCompleted: filters.includeCompleted ?? this.config.includeCompleted,\n limit: sqlLimit,\n });\n const matched = rows\n .map((r) => this.#fromIndex(r))\n .filter((r) => this.#matchesIndex(r, filters, bounds));\n // A full window means SQL had more to give, so matches may exist past it\n // whether or not the page filled.\n const windowFull = rows.length >= sqlLimit;\n return {\n reminders: matched.slice(0, filters.limit),\n source: \"index\",\n hasMore: matched.length > filters.limit || windowFull,\n // The over-fetch is a multiple of `limit` on the assumption that the\n // post-SQL predicates reject a minority of rows. When they reject most of\n // them the window runs out first and the page comes back short — which is\n // indistinguishable from \"that is all there is\" unless it says so.\n ...(windowFull && matched.length <= filters.limit\n ? {\n note:\n `The index query read ${rows.length} rows and the filters applied after SQL left ` +\n `${matched.length}, short of the ${filters.limit} asked for. More may match beyond ` +\n `that window. Narrow with \\`list\\` or a search term, which filter inside the query ` +\n `rather than after it.`,\n }\n : {}),\n };\n }\n\n /**\n * Whether the index can answer this request faithfully.\n *\n * The store has no readable account name — `ZREMCDACCOUNTLISTDATA` is a blob\n * and nothing else carries one — so an account allowlist cannot be applied on\n * that lane. Returning index rows anyway would silently ignore the setting\n * whose entire job is limiting what gets read, and would do so ONLY on\n * machines with Full Disk Access, which is exactly where it matters. So a\n * configured allowlist takes the slower Apple Events lane instead.\n */\n #indexCanAnswer(): boolean {\n return this.config.accounts.length === 0;\n }\n\n async listReminders(filters: ReminderFilters): Promise<ReminderListing> {\n const now = this.#now();\n const store = this.#indexCanAnswer() ? this.index() : null;\n if (store) return this.#fromStore(store, filters, undefined, undefined, now);\n\n // Before the bulk read, not inside the row filter: a bad bound should cost\n // a refusal, not nine seconds of Apple Events followed by an empty list.\n const bounds = AppleRemindersClient.#bounds(filters, now);\n const data = await this.#bulk();\n const matched = data.reminders\n .filter((r) => this.#matches(r, filters, bounds))\n .map((r) => this.#summarise(r))\n .toSorted(AppleRemindersClient.#order);\n return this.#capped(matched, filters.limit);\n }\n\n /**\n * Cut an Apple Events result to the page, and say which bound did the cutting.\n *\n * The lane cap exists because a bulk read costs ~700ms per property whatever\n * the library size; it is not the caller's `limit` and can sit well below it.\n * Shared by list and search so the two cannot describe it differently.\n */\n #capped(matched: ReminderSummary[], limit: number): ReminderListing {\n const cap = Math.min(limit, this.config.degradedMaxReminders);\n return {\n reminders: matched.slice(0, cap),\n source: \"apple-events\",\n hasMore: matched.length > cap,\n ...(matched.length > cap && this.config.degradedMaxReminders < limit\n ? {\n note:\n `The Apple Events lane is capped at ${this.config.degradedMaxReminders} reminders ` +\n `and you asked for ${limit}, so this list stops short of what matched. Grant Full ` +\n `Disk Access to read the Reminders index instead, or raise ` +\n `APPLE_REMINDERS_DEGRADED_MAX_REMINDERS.`,\n }\n : {}),\n };\n }\n\n /**\n * Text search over name and, optionally, body.\n *\n * Filtering happens in JS over the bulk arrays rather than through a `whose`\n * specifier. `whose` evaluates per item across the Apple Event bridge, which\n * Notes measured at 6.9x slower for a substring match on a comparable library.\n */\n async searchReminders(\n query: string,\n opts: { scope?: \"title\" | \"full\" } & ReminderFilters,\n ): Promise<ReminderListing> {\n const now = this.#now();\n const needle = query.trim().toLowerCase();\n const full = (opts.scope ?? \"full\") === \"full\";\n\n const store = this.#indexCanAnswer() ? this.index() : null;\n if (store) return this.#fromStore(store, opts, query.trim(), opts.scope ?? \"full\", now);\n\n const bounds = AppleRemindersClient.#bounds(opts, now);\n const data = await this.#bulk();\n const matched = data.reminders\n .filter((r) => this.#matches(r, opts, bounds))\n .filter((r) => {\n if (!needle) return true;\n if ((r.name ?? \"\").toLowerCase().includes(needle)) return true;\n return full && (r.body ?? \"\").toLowerCase().includes(needle);\n })\n .map((r) => this.#summarise(r))\n .toSorted(AppleRemindersClient.#order);\n return this.#capped(matched, opts.limit);\n }\n\n /**\n * One reminder in full.\n *\n * Apple Events is the authority for the core model, and the index supplies\n * what the dictionary has no class for: the authoritative all-day flag,\n * subtasks (`container()` throws on every reminder, so there is no other\n * way), attachments, alarms, recurrence and location.\n *\n * The two are joined on the UUID inside the Apple Events id — measured, by\n * scanning every TEXT column in the store for a real id rather than guessing\n * a column name.\n */\n async getReminder(ref: string): Promise<ReminderDetail> {\n const { id, uuid } = decodeRef(ref);\n const rows = await withBusyRetry(() =>\n this.runner.run<(RawReminder & { found: boolean; containerClass: string | null })[]>(\n GET_REMINDERS,\n { ids: [id] },\n ),\n );\n const row = rows[0];\n if (!row?.found) throw new ReminderNotFoundError(ref);\n\n const summary = this.#summarise(row);\n const store = this.index();\n const indexed = store && uuid ? store.byUuid(uuid) : null;\n\n // Null, not [], when the index is unavailable: \"none\" and \"unknown\" are\n // different answers and a caller acts differently on each.\n let subtasks: ReminderSummary[] = [];\n let attachments: ReminderDetail[\"attachments\"] = null;\n let alarms: IndexEnrichment | null = null;\n\n if (store && indexed) {\n subtasks = store.subtasksOf(indexed.primaryKey).map((r) => this.#fromIndex(r));\n attachments = store.attachmentsOf(indexed.primaryKey).map((a) => ({\n id: a.uuid,\n filename: a.filename,\n uti: a.uti,\n }));\n alarms = store.enrichmentOf(indexed.primaryKey);\n }\n\n return {\n ...summary,\n // ZALLDAY beats the local-midnight guess whenever it is available.\n ...(indexed\n ? {\n dueAllDay: indexed.allDay,\n dueAllDaySource: \"index\" as const,\n due: renderDue(indexed.due, indexed.allDay, utcDay(indexed.due)),\n }\n : {}),\n body: row.body,\n completionDate: row.completionDate,\n dueDate: row.dueDate,\n alldayDueDate: row.alldayDueDate,\n subtasks,\n attachments,\n alarms,\n };\n }\n\n // ─── writes ───────────────────────────────────────────────────────────────\n\n /** Resolve a list by name or id, erroring with what is available. */\n async resolveList(nameOrId: string): Promise<string> {\n const lists = await this.lists();\n const want = nameOrId.toLowerCase();\n const hit =\n lists.find((l) => l.id === nameOrId) ?? lists.find((l) => l.name?.toLowerCase() === want);\n if (!hit?.id) {\n throw new ListNotFoundError(\n nameOrId,\n lists.map((l) => l.name).filter((n): n is string => Boolean(n)),\n );\n }\n return hit.id;\n }\n\n /**\n * Turn the caller's field bag into JXA parameters.\n *\n * The due date is where the shape of the input picks the property: a bare day\n * sets `allday due date`, a date-time sets `due date`. See dates.ts.\n */\n #toJxaFields(fields: ReminderFields): Record<string, unknown> & { resolved?: ParsedDate } {\n const now = this.#now();\n const out: Record<string, unknown> = {};\n if (fields.name !== undefined) out.name = fields.name;\n if (fields.body !== undefined) out.body = fields.body;\n if (fields.priority !== undefined) out.priority = toPriorityValue(fields.priority);\n if (fields.flagged !== undefined) out.flagged = fields.flagged;\n if (fields.completed !== undefined) out.completed = fields.completed;\n if (fields.remindMe !== undefined) {\n out.remindMeDate = parseDate(\"remindMe\", fields.remindMe, now).iso;\n }\n if (fields.due !== undefined) {\n const parsed = parseDate(\"due\", fields.due, now);\n if (parsed.kind === \"allDay\") out.alldayDueDate = parsed.iso;\n else out.dueDate = parsed.iso;\n out.resolved = parsed;\n }\n return out;\n }\n\n async createReminder(\n fields: ReminderFields & { name: string; list?: string | undefined },\n ): Promise<ReminderDetail> {\n const target = fields.list ?? this.config.defaultList;\n const listId = target ? await this.resolveList(target) : undefined;\n const jxa = this.#toJxaFields(fields);\n delete jxa.resolved;\n const made = await withBusyRetry(() =>\n this.runner.run<RawReminder>(CREATE_REMINDER, {\n ...jxa,\n name: fields.name,\n ...(listId ? { listId } : {}),\n }),\n );\n this.invalidate();\n return this.getReminder(encodeRef(made.id));\n }\n\n async updateReminder(ref: string, fields: ReminderFields): Promise<ReminderDetail> {\n const { id } = decodeRef(ref);\n const jxa = this.#toJxaFields(fields);\n delete jxa.resolved;\n await withBusyRetry(() => this.runner.run<RawReminder>(UPDATE_REMINDER, { ...jxa, id }));\n this.invalidate();\n return this.getReminder(ref);\n }\n\n async completeReminders(\n refs: string[],\n completed = true,\n ): Promise<{ ref: string; found: boolean; completed: boolean }[]> {\n const ids = refs.map((r) => decodeRef(r).id);\n const rows = await withBusyRetry(() =>\n this.runner.run<{ id: string; found: boolean; completed: boolean }[]>(COMPLETE_REMINDERS, {\n ids,\n completed,\n }),\n );\n this.invalidate();\n return rows.map((r) => ({\n ref: encodeRef(r.id),\n found: Boolean(r.found),\n completed: Boolean(r.completed),\n }));\n }\n\n /**\n * Move reminders to another list.\n *\n * Copy-then-delete, because `reminder.container` is read-only in the scripting\n * dictionary. The new ref is returned alongside the old one so a caller can\n * update anything it was holding — the old ref stops resolving.\n */\n async moveReminders(\n refs: string[],\n list: string,\n ): Promise<{ ref: string | null; previousRef: string; moved: boolean; error?: string }[]> {\n const listId = await this.resolveList(list);\n const decoded = refs.map((r) => decodeRef(r));\n const ids = decoded.map((d) => d.id);\n // ZALLDAY is the only authoritative all-day flag, and only the index has\n // it. Ids it cannot answer for are left out, and the script guesses.\n const store = this.index();\n const allDay: Record<string, boolean> = {};\n for (const { id, uuid } of decoded) {\n const indexed = store && uuid ? store.byUuid(uuid) : null;\n if (indexed) allDay[id] = indexed.allDay;\n }\n const rows = await withBusyRetry(() =>\n this.runner.run<\n {\n id: string | null;\n previousId?: string;\n found: boolean;\n moved?: boolean;\n error?: string;\n }[]\n >(MOVE_REMINDERS, { ids, listId, allDay }),\n );\n this.invalidate();\n return rows.map((r, i) => ({\n ref: r.id ? encodeRef(r.id) : null,\n previousRef: r.previousId ? encodeRef(r.previousId) : (refs[i] as string),\n moved: Boolean(r.moved),\n ...(r.error ? { error: r.error } : {}),\n }));\n }\n\n async deleteReminders(refs: string[]): Promise<{ deleted: number; missing: string[] }> {\n const ids = refs.map((r) => decodeRef(r).id);\n const out = await withBusyRetry(() =>\n this.runner.run<{ deleted: number; missing: string[] }>(DELETE_REMINDERS, { ids }),\n );\n this.invalidate();\n return { deleted: out.deleted, missing: out.missing.map((id) => encodeRef(id)) };\n }\n}\n","import { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport {\n BaseConfigSchema,\n parseBool,\n parseConfig,\n parseIntOpt,\n parseList,\n trimmed,\n} from \"@mgcrea/mcp-apple-core\";\nimport { z } from \"zod\";\n\n/**\n * Configuration is environment-only — this server holds no secret at all, its\n * access is the macOS permission the user granted.\n *\n * `allowWrites`, `osascriptPath`, `osascriptTimeoutMs` and `maxResults`\n * come from `BaseConfigSchema`.\n */\nconst ConfigSchema = BaseConfigSchema.extend({\n /** Account allowlist (names or ids). Empty means every account. */\n accounts: z.array(z.string().min(1)).default([]),\n /**\n * List allowlist (names or ids). Empty means every list.\n *\n * Finer-grained than the account allowlist and worth having here in a way it\n * was not for Notes: a shared \"Groceries\" list and a private one live in the\n * same account, so the account is often the wrong unit to scope by.\n */\n lists: z.array(z.string().min(1)).default([]),\n /** Explicit store path. Bypasses discovery — for tests and forensic copies. */\n storePath: z.string().optional(),\n indexMode: z.enum([\"auto\", \"ro\", \"immutable\", \"off\"]).default(\"auto\"),\n /** List a new reminder goes to when the caller names none. Empty = Reminders' default list. */\n defaultList: z.string().optional(),\n /**\n * Whether completed reminders are included when the caller does not say.\n *\n * Off, matching what Reminders itself shows. A long-lived account accumulates\n * years of completed items that would otherwise dominate every result.\n */\n includeCompleted: z.boolean().default(false),\n /** Cap for the Apple Events listing lane. */\n degradedMaxReminders: z.number().int().min(1).max(5_000).default(500),\n /** The only directory save_attachment may write into, enforced after realpath. */\n attachmentDir: z.string().default(join(homedir(), \"Downloads\")),\n /**\n * How long the Apple Events bulk-property cache stays warm.\n *\n * Same trade as Notes: a bulk fetch is one Apple Event per property whatever\n * the library size, so there is no cheap way to ask \"has anything changed\"\n * that costs less than simply asking again. A TTL with bounded staleness is\n * the honest option.\n */\n searchCacheTtlMs: z.number().int().min(0).max(3_600_000).default(30_000),\n}).strict();\n\nexport type Config = z.infer<typeof ConfigSchema>;\n\n/**\n * `env` is a parameter with a default so tests are hermetic — they pass their\n * own object rather than mutating (and having to restore) process.env.\n */\nexport const loadConfig = (env: NodeJS.ProcessEnv = process.env): Config =>\n parseConfig(ConfigSchema, {\n allowWrites: parseBool(env.APPLE_REMINDERS_ALLOW_WRITES),\n exposePrompts: parseBool(env.APPLE_REMINDERS_EXPOSE_PROMPTS),\n lazyTools: parseBool(env.APPLE_REMINDERS_LAZY_TOOLS),\n accounts: parseList(env.APPLE_REMINDERS_ACCOUNTS),\n lists: parseList(env.APPLE_REMINDERS_LISTS),\n storePath: trimmed(env.APPLE_REMINDERS_STORE),\n indexMode: trimmed(env.APPLE_REMINDERS_INDEX_MODE),\n defaultList: trimmed(env.APPLE_REMINDERS_DEFAULT_LIST),\n includeCompleted: parseBool(env.APPLE_REMINDERS_INCLUDE_COMPLETED),\n osascriptPath: trimmed(env.APPLE_REMINDERS_OSASCRIPT_PATH),\n osascriptTimeoutMs: parseIntOpt(env.APPLE_REMINDERS_OSASCRIPT_TIMEOUT_MS),\n maxResults: parseIntOpt(env.APPLE_REMINDERS_MAX_RESULTS),\n degradedMaxReminders: parseIntOpt(env.APPLE_REMINDERS_DEGRADED_MAX_REMINDERS),\n attachmentDir: trimmed(env.APPLE_REMINDERS_ATTACHMENT_DIR),\n searchCacheTtlMs: parseIntOpt(env.APPLE_REMINDERS_SEARCH_CACHE_TTL_MS),\n });\n","/**\n * The Reminders operating manual, served as `cupertino://reminders/guide` and\n * embedded ahead of every Reminders prompt. Static by design — see the note in\n * the Mail guide.\n */\nexport const REMINDERS_GUIDE = `# Apple Reminders — how to drive this server\n\n## Refs are opaque\n\nReminders come back with a \\`ref\\` like \\`r1:x-apple-reminder://…\\`. Pass it back\nverbatim; never build, parse or reuse one across surfaces.\n\n## Which tool, under which constraint\n\n- **Anything with a date bound, a list or a completion state** is\n \\`apple_reminders_list_reminders\\` — it takes all of those as filters.\n- **Text** is \\`apple_reminders_search_reminders\\`. \\`scope: \"full\"\\` (the default)\n matches the name and the notes body; \\`scope: \"title\"\\` matches only the name.\n It accepts the same filters, so search *within* a list or a date range rather\n than searching everything and filtering afterwards.\n- **List names** must match what Reminders calls them. Read\n \\`apple_reminders_list_lists\\` — or the inventory resource — before filtering\n on one, because a name that does not match returns nothing rather than an\n error, and that looks exactly like an empty list.\n- **\\`apple_reminders_get_reminder\\`** returns the notes body and any subtasks.\n\n## Subtasks, and what the index cannot see\n\nA subtask's container is another reminder, not a list. Reminders whose parent\nis unresolved are reported as unmapped: that is parentage the Apple Events lane\ncannot reach, **not** a set of orphans to re-file.\n\nTags, URLs, recurrence and alarms are index-only. On a ref that did not come\nfrom the index they are unavailable — absent from the answer, which is not the\nsame as absent from the reminder.\n\n## Writes\n\nMutating tools exist only when writes are enabled. If you cannot see\n\\`apple_reminders_create_reminder\\`, writes are off — say so rather than\ndescribing reminders you did not create.\n\nWhen creating in bulk, **search for what already exists first**. Re-running a\ncapture over the same source is the normal way this surface accumulates\nduplicates, and nothing here deduplicates for you.\n`;\n","import {\n promptArg,\n registerWorkflowPrompt,\n requiredPromptArg,\n type PromptContext,\n} from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { REMINDERS_GUIDE } from \"./guide.js\";\n\nconst CTX: PromptContext = { surface: \"reminders\", guide: REMINDERS_GUIDE };\n\n/**\n * Reminders' workflow prompts.\n *\n * The capture prompt is the reason this file exists. Turning a thread into\n * reminders is the single most requested thing on this surface and the single\n * easiest to get wrong: run it twice over the same source and you have two of\n * everything, because no tool here deduplicates and no tool description is the\n * right place to say so.\n */\nexport const registerPrompts = (server: McpServer, allowWrites: boolean): void => {\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_reminders_whats_due\",\n title: \"What's due\",\n description:\n \"Report what is actually outstanding across the lists, separating overdue from upcoming \" +\n \"and from undated. Read-only — it does not complete or reschedule anything.\",\n argsSchema: {\n window: promptArg('How far ahead to look, e.g. \"today\", \"this week\". Defaults to 7 days.'),\n list: promptArg(\"Restrict to one list, exactly as Reminders spells it. Omit for all.\"),\n },\n build: ({ window, list }) => `Tell me what is due${\n window ? ` ${window}` : \" over the next 7 days\"\n }${list ? `, in the ${list} list` : \"\"}.\n\n1. ${\n list\n ? `Confirm the ${list} list exists via \\`apple_reminders_list_lists\\` — a name that does not match returns nothing, which reads as an empty list.`\n : \"`apple_reminders_list_lists` first, so you know what you are covering.\"\n }\n2. \\`apple_reminders_list_reminders\\` with \\`completed: false\\` and a date bound.\n Do not page everything and filter afterwards.\n3. Separate into **overdue**, **due in the window**, and **undated**. The\n undated group matters: it is where things go to be forgotten, so surface the\n oldest few rather than dropping them.\n4. Where a reminder has subtasks, say how many are outstanding — a parent that\n looks like one item can be six.\n\nReport it as a list someone can act on, ordered by when it is due. Do not\ncomplete, reschedule or move anything.`,\n });\n\n if (!allowWrites) return;\n\n registerWorkflowPrompt(server, CTX, {\n name: \"apple_reminders_capture_action_items\",\n title: \"Capture action items as reminders\",\n description:\n \"Turn a thread, a meeting or a note into reminders — checking what already exists first, \" +\n \"because re-running this over the same source is how duplicates happen. Requires writes.\",\n argsSchema: {\n source: requiredPromptArg(\n 'What to extract from, e.g. \"yesterday\\'s thread with the Atlas client\".',\n ),\n list: promptArg(\"Which list to file them under, exactly as Reminders spells it.\"),\n due: promptArg(\n 'When they are due, e.g. \"Friday\". Applied to all unless the source says otherwise.',\n ),\n },\n build: ({ source, list, due }) => `Capture the action items from: ${source}\n\n1. Extract only what is genuinely **mine to do**. Something the other person\n committed to is not my action item; note it separately if it matters, but do\n not create a reminder for it.\n2. **Check what already exists before creating anything.**\n \\`apple_reminders_search_reminders\\` for each item's distinctive words${\n list ? `, scoped to the ${list} list` : \"\"\n }. If this source has been captured before, the reminders are already there\n and a second set is worse than none. Nothing here deduplicates for you.\n3. ${\n list\n ? `Confirm the ${list} list exists with \\`apple_reminders_list_lists\\` — creating into a mistyped name does not fail loudly.`\n : \"Pick a list from `apple_reminders_list_lists` rather than inventing one.\"\n }\n4. Create one reminder per action, with \\`apple_reminders_create_reminder\\`. Title\n it as the thing to do, starting with a verb — not as the topic it came from.\n Put the context and the source in the notes body so it still makes sense in a\n month.${due ? `\\n5. Set all of them due ${due} unless the source names a specific date for one, in which case use that.` : \"\\n5. Set a due date where the source names one. Leave the rest undated rather than inventing deadlines.\"}\n\nThen list what you created and what you deliberately skipped, so the user can\ntell you missed nothing.`,\n });\n};\n","import { z } from \"zod\";\n\n/**\n * Reminders' tool helpers. The generic half lives in `@mgcrea/mcp-apple-core`;\n * re-exported here so tools import from one place.\n */\nexport {\n compact,\n confirmArg,\n fail,\n limitArg,\n ok,\n okText,\n resolveLimit,\n toFailure,\n wrap,\n wrapResult,\n type ToolResult,\n} from \"@mgcrea/mcp-apple-core\";\n\n// ─── Reminders' own args ─────────────────────────────────────────────────────\n\nexport const reminderRefArg = z\n .string()\n .min(1)\n .describe(\n 'An opaque reminder ref from a search or list result (looks like \"r1:x-apple-reminder://…\"). ' +\n \"Do not construct one by hand.\",\n );\n\nexport const reminderRefsArg = z\n .array(z.string().min(1))\n .min(1)\n .max(200)\n .describe(\"Reminder refs from a search or list result.\");\n\nexport const listArg = z\n .string()\n .optional()\n .describe(\n 'A list name or id, e.g. \"Groceries\". Lists can be nested inside other lists; give the ' +\n \"leaf name. Use apple_reminders_list_lists to see what exists.\",\n );\n\nexport const priorityArg = z\n .enum([\"none\", \"low\", \"medium\", \"high\"])\n .optional()\n .describe(\n \"Reminders stores priority as 0-9 and shows four buckets; these are the four. \" +\n \"A value synced from another CalDAV client is bucketed into the nearest one.\",\n );\n\n/**\n * The date grammar, written out in full.\n *\n * The description is load-bearing: the caller is usually a model that gets one\n * retry, and the difference between a bare day and a date-time is the\n * difference between an all-day reminder and one due at a specific minute.\n */\nexport const dateArg = z\n .string()\n .describe(\n 'ISO-8601 — \"2026-08-20\" for an all-day reminder, \"2026-08-20T09:00\" for a timed one — ' +\n 'or a relative offset: \"+2d\", \"+3h\", \"+45m\", \"+1w\", \"today\", \"tomorrow\", ' +\n '\"tomorrow 09:00\", \"next monday\". Resolved in local time. Naming a day gives an all-day ' +\n \"reminder; naming a time or a duration gives a timed one. The result echoes back the \" +\n \"absolute time it resolved to.\",\n );\n\nexport const includeCompletedArg = z\n .boolean()\n .optional()\n .describe(\n \"Include completed reminders. Off by default, matching what Reminders itself shows — a \" +\n \"long-lived account holds years of finished items.\",\n );\n","import { buildBaseDiagnostics } from \"@mgcrea/mcp-apple-core\";\nimport type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { BUILD_INFO } from \"../build-info.js\";\nimport type { AppleRemindersClient } from \"../client/reminders.js\";\nimport { ok, wrap } from \"./util.js\";\n\n/**\n * Build the report.\n *\n * Split out of the tool registration so the `cupertino://reminders/diagnostics`\n * resource can serve the same bytes. Two renderings of one probe: duplicated,\n * the resource and the tool would drift, and the disagreement would surface as\n * \"the diagnostics lied\" — the one thing this file must never do.\n */\nexport const buildDiagnostics = async (\n client: AppleRemindersClient,\n ctx: { allowWrites: boolean },\n): Promise<Record<string, unknown>> => {\n const lanes = await client.lanes();\n const located = client.locate();\n const accounts = lanes.applescript === \"live\" ? await client.accounts() : [];\n\n /**\n * Reminders' Full Disk Access signal is not \"can I read the file\" but\n * \"can I list the directory\". The store's filename carries a generated\n * UUID, so without the grant there is no path to even test.\n */\n const fullDiskAccess = located.readable\n ? \"granted\"\n : located.containerListable\n ? \"denied (found the store, cannot read it)\"\n : \"denied (cannot list the container, so the store cannot be located)\";\n\n const base = buildBaseDiagnostics({\n build: BUILD_INFO,\n config: client.config,\n allowWrites: ctx.allowWrites,\n });\n\n return {\n ...base,\n // Out of `server` and into its own key. It lived under `server` on this\n // surface and two others, which is why they could not report their own\n // version: the one field that block is for had been given away.\n lanes,\n permissions: {\n automation: lanes.applescript === \"live\" ? \"granted\" : \"denied-or-reminders-not-running\",\n fullDiskAccess,\n ...(located.readable\n ? {}\n : {\n howToGrant: [\n \"System Settings > Privacy & Security > Full Disk Access\",\n \"Add the app that launches this server (Terminal, iTerm, VS Code, Claude...), then restart it.\",\n \"Granting it to Reminders.app does nothing — the reader needs the permission, not Reminders.\",\n ],\n }),\n },\n store: {\n containerPath: located.containerPath,\n path: located.storePath,\n containerListable: located.containerListable,\n candidates: located.candidates.length,\n exists: located.exists,\n readable: located.readable,\n sizeBytes: located.size,\n walPresent: located.walPresent,\n walSizeBytes: located.walSizeBytes,\n fingerprint: lanes.storeFingerprint,\n reason: located.reason,\n },\n accounts,\n settings: {\n ...base.settings,\n accountAllowlist: client.config.accounts,\n listAllowlist: client.config.lists,\n defaultList: client.config.defaultList ?? null,\n includeCompleted: client.config.includeCompleted,\n indexMode: client.config.indexMode,\n maxResults: client.config.maxResults,\n // The Apple Events listing cap. Reported because list_reminders now names\n // it when it is what ended a list, and a number in an error is only\n // useful if there is somewhere to go and see what it is.\n degradedMaxReminders: client.config.degradedMaxReminders,\n searchCacheTtlMs: client.config.searchCacheTtlMs,\n },\n caveats: [\n \"Reminders' scripting dictionary covers the core model read-write, so this server \" +\n \"works with Automation alone. But a bulk read costs about 700ms PER PROPERTY on \" +\n \"that bridge — roughly nine seconds for a full listing, whatever the library \" +\n \"size — so the index lane carries listing and search whenever it is available.\",\n \"Without the index, `dueAllDay` is a guess. Reminders populates BOTH `due date` \" +\n \"and `allday due date` for every dated reminder, so only the store's ZALLDAY \" +\n \"column can actually answer it. Each result says which source it used.\",\n \"Subtasks need the index. The scripting dictionary types a reminder's container \" +\n 'as \"list or reminder\", but calling container() on a reminder throws every ' +\n \"time, so parentage is unreachable over Apple Events.\",\n \"Also index-only: attachments, alarms, recurrence and location alerts. There is \" +\n \"no URL field in this store despite the folklore — it was looked for and is \" +\n \"not there.\",\n \"Moving a reminder between lists is a copy-and-delete, because the scripting \" +\n \"dictionary makes a reminder's list read-only. Moved reminders get a new ref.\",\n \"Apple Events results are cached for \" +\n `${client.config.searchCacheTtlMs}ms. Checking for changes costs about as much ` +\n \"as re-reading everything, so there is no cheaper invalidation to be had.\",\n `Listings over Apple Events stop at ${client.config.degradedMaxReminders} reminders ` +\n \"whatever `limit` says. The index lane has its own bound: it over-fetches from SQL \" +\n \"and applies the date, flag and priority filters afterwards, so a query those reject \" +\n \"can come back short. Both cases are reported in a `note` field rather than \" +\n \"returning a short list silently.\",\n ],\n };\n};\n\n/**\n * One tool that answers \"why is this not working\".\n *\n * Lanes are probed before anything else is read, because the first Apple Event\n * is what triggers the Automation prompt: reading accounts first and probing\n * afterwards makes the two disagree whenever that first event loses the race.\n */\nexport const registerDiagnosticsTools = (\n server: McpServer,\n client: AppleRemindersClient,\n ctx: { allowWrites: boolean },\n): void => {\n server.registerTool(\n \"apple_reminders_diagnostics\",\n {\n description:\n \"Report which lanes are live, which macOS permissions are granted, and what each \" +\n \"missing one is blocking. Start here when a tool fails, or answers from the Apple \" +\n \"Events lane when you expected the index — it names the exact System Settings pane to \" +\n \"open.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n async () => wrap(() => buildDiagnostics(client, ctx)).then((r) => r ?? ok({})),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport type { AppleRemindersClient } from \"../client/reminders.js\";\nimport { wrap } from \"./util.js\";\n\nexport const registerAccountTools = (server: McpServer, client: AppleRemindersClient): void => {\n server.registerTool(\n \"apple_reminders_list_accounts\",\n {\n description:\n \"List the Reminders accounts, with how many lists and reminders each holds. Start here \" +\n \"to discover account names for the other tools.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n async () => wrap(() => client.accounts()),\n );\n\n server.registerTool(\n \"apple_reminders_list_lists\",\n {\n description:\n \"List every Reminders list, across accounts. Lists nest inside other lists (Reminders \" +\n \"calls those groups), so each entry carries its depth. Each also reports its total and \" +\n \"incomplete counts, which is the cheapest way to see where the live work is.\",\n inputSchema: {},\n annotations: { readOnlyHint: true },\n },\n async () => wrap(() => client.lists()),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleRemindersClient } from \"../client/reminders.js\";\nimport {\n confirmArg,\n dateArg,\n listArg,\n priorityArg,\n reminderRefArg,\n reminderRefsArg,\n wrap,\n} from \"./util.js\";\n\n/**\n * The mutating tools.\n *\n * Registered only when writes are enabled, so with the flag off they are\n * invisible to the model rather than merely refused.\n *\n * Every one of these re-reads the reminder afterwards and returns what\n * Reminders stored — not what was asked for. That matters most for dates: a\n * relative offset like \"+2d\" is resolved here, and the result says what instant\n * it became.\n */\nexport const registerActionTools = (server: McpServer, client: AppleRemindersClient): void => {\n server.registerTool(\n \"apple_reminders_create_reminder\",\n {\n description:\n \"Create a reminder. With no list, it goes to the list Reminders itself treats as the \" +\n \"default — the same one the app would have used.\",\n inputSchema: {\n name: z.string().min(1).describe(\"The reminder's title.\"),\n body: z.string().optional().describe(\"Notes attached to the reminder.\"),\n list: listArg,\n due: dateArg.optional(),\n remindMe: dateArg\n .optional()\n .describe(\"When to actually alert, if different from the due date.\"),\n priority: priorityArg,\n flagged: z.boolean().optional().describe(\"Flag it.\"),\n },\n },\n async (args) => wrap(() => client.createReminder(args)),\n );\n\n server.registerTool(\n \"apple_reminders_update_reminder\",\n {\n description:\n \"Change fields on one reminder. Anything you omit is left alone. Setting `due` to a \" +\n \"bare day converts it to an all-day reminder; setting a date-time makes it timed.\",\n inputSchema: {\n ref: reminderRefArg,\n name: z.string().optional(),\n body: z\n .string()\n .optional()\n .describe(\"Replaces the notes body. Pass an empty string to clear it.\"),\n due: dateArg.optional(),\n remindMe: dateArg.optional(),\n priority: priorityArg,\n flagged: z.boolean().optional(),\n },\n },\n async ({ ref, ...fields }) => wrap(() => client.updateReminder(ref, fields)),\n );\n\n server.registerTool(\n \"apple_reminders_complete_reminders\",\n {\n description:\n \"Tick reminders off, or un-tick them with `completed: false`. Separate from update \" +\n \"because it is the common case and takes several at once.\",\n inputSchema: {\n refs: reminderRefsArg,\n completed: z\n .boolean()\n .optional()\n .describe(\"Defaults to true. Pass false to mark them not done again.\"),\n },\n },\n async ({ refs, completed }) => wrap(() => client.completeReminders(refs, completed ?? true)),\n );\n\n server.registerTool(\n \"apple_reminders_move_reminders\",\n {\n description:\n \"Move reminders to another list. NOTE: Reminders' scripting interface makes a list \" +\n \"read-only on a reminder, so this is a copy followed by a delete. Each moved reminder \" +\n \"therefore gets a NEW ref (returned alongside the old one) and a new creation date. \" +\n \"The original is deleted only after the copy is confirmed.\",\n inputSchema: {\n refs: reminderRefsArg,\n list: z.string().min(1).describe(\"Target list name or id.\"),\n confirm: confirmArg,\n },\n },\n async ({ refs, list }) => wrap(() => client.moveReminders(refs, list)),\n );\n\n server.registerTool(\n \"apple_reminders_delete_reminders\",\n {\n description:\n \"Delete reminders. Unlike Notes, Reminders has no Recently Deleted — this is \" +\n \"irreversible, so it requires an explicit confirm.\",\n inputSchema: { refs: reminderRefsArg, confirm: confirmArg },\n },\n async ({ refs }) => wrap(() => client.deleteReminders(refs)),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\nimport { z } from \"zod\";\n\nimport type { AppleRemindersClient } from \"../client/reminders.js\";\nimport {\n includeCompletedArg,\n limitArg,\n listArg,\n priorityArg,\n reminderRefArg,\n resolveLimit,\n wrap,\n} from \"./util.js\";\n\n/** Filters shared by list and search, declared once so the two cannot drift. */\nconst filterSchema = {\n list: listArg,\n includeCompleted: includeCompletedArg,\n dueBefore: z\n .string()\n .optional()\n .describe(\n 'Only reminders due at or before this. A bare day means the WHOLE day, so \"2026-08-20\" ' +\n \"includes everything due that evening. Same grammar as the due argument.\",\n ),\n dueAfter: z\n .string()\n .optional()\n .describe(\n \"Only reminders due at or after this. A bare day means from that morning. Combine with \" +\n \"dueBefore for a range.\",\n ),\n flagged: z.boolean().optional().describe(\"Only flagged, or only unflagged.\"),\n priority: priorityArg,\n hasDueDate: z\n .boolean()\n .optional()\n .describe(\"true = only reminders with a due date; false = only those without one.\"),\n limit: limitArg,\n};\n\nexport const registerReminderTools = (server: McpServer, client: AppleRemindersClient): void => {\n server.registerTool(\n \"apple_reminders_list_reminders\",\n {\n description:\n \"List reminders, soonest due first, with undated ones last. Returns `reminders` with a \" +\n \"`ref` each for the read and action tools, alongside `source` and `hasMore`. Completed \" +\n \"reminders are excluded unless you ask for them. Every filter is optional; with none, \" +\n \"this is the whole live list — but check `hasMore` before believing that, and read the \" +\n \"`note` field if one is present: it means a lane bound, not your `limit`, ended the list.\",\n inputSchema: filterSchema,\n annotations: { readOnlyHint: true },\n },\n async (args) =>\n wrap(() =>\n client.listReminders({\n ...args,\n limit: resolveLimit(args.limit, client.config.maxResults, 50),\n }),\n ),\n );\n\n server.registerTool(\n \"apple_reminders_search_reminders\",\n {\n description:\n 'Search reminders by text. `scope: \"full\"` (the default) matches the name and the ' +\n 'notes body; `scope: \"title\"` matches only the name. Accepts the same filters as ' +\n \"list_reminders, so you can search within one list or one date range. Carries the same \" +\n \"`hasMore` and `note` fields as list_reminders.\",\n inputSchema: {\n query: z.string().min(1).describe(\"Text to look for. Case-insensitive substring match.\"),\n scope: z\n .enum([\"full\", \"title\"])\n .optional()\n .describe(\"full = name and notes body (default). title = name only.\"),\n ...filterSchema,\n },\n annotations: { readOnlyHint: true },\n },\n async ({ query, scope, ...rest }) =>\n wrap(() =>\n client.searchReminders(query, {\n ...rest,\n ...(scope ? { scope } : {}),\n limit: resolveLimit(rest.limit, client.config.maxResults, 50),\n }),\n ),\n );\n\n server.registerTool(\n \"apple_reminders_get_reminder\",\n {\n description:\n \"Read one reminder in full by ref, including its notes body and any subtasks. \" +\n \"`dueDate` and `alldayDueDate` are reported separately from the combined `due` field, \" +\n \"so you can see which property actually holds the date.\",\n inputSchema: { ref: reminderRefArg },\n annotations: { readOnlyHint: true },\n },\n async ({ ref }) => wrap(() => client.getReminder(ref)),\n );\n};\n","import type { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport type { AppleRemindersClient } from \"../client/reminders.js\";\nimport { registerAccountTools } from \"./accounts.js\";\nimport { registerActionTools } from \"./actions.js\";\nimport { registerDiagnosticsTools } from \"./diagnostics.js\";\nimport { registerReminderTools } from \"./reminders.js\";\n\nexport type ToolContext = {\n /**\n * Register the mutating tools too. Off by default — with the flag off they are\n * not merely refused, they are invisible and cannot be called at all.\n */\n allowWrites: boolean;\n};\n\n/**\n * Register the Apple Reminders tools.\n *\n * The registered set is a pure function of `allowWrites` and nothing else. In\n * particular it does NOT vary with whether Full Disk Access is granted: that is\n * a runtime condition which can change while the process lives, and MCP clients\n * cache the tool list, so a tool that appears and disappears would leave clients\n * calling names the server no longer has. Tools that need the index instead\n * report their source, or explain what is missing.\n */\nexport const registerTools = (\n server: McpServer,\n client: AppleRemindersClient,\n ctx: ToolContext,\n): void => {\n registerDiagnosticsTools(server, client, ctx);\n registerAccountTools(server, client);\n registerReminderTools(server, client);\n\n if (!ctx.allowWrites) return;\n registerActionTools(server, client);\n};\n","import {\n type Logger,\n type OsascriptRunner,\n registerSurfaceResources,\n withLazyTools,\n} from \"@mgcrea/mcp-apple-core\";\nimport { McpServer } from \"@modelcontextprotocol/sdk/server/mcp.js\";\n\nimport { BUILD_INFO } from \"./build-info.js\";\nimport { AppleRemindersClient } from \"./client/reminders.js\";\nimport type { Config } from \"./config.js\";\nimport { REMINDERS_GUIDE } from \"./guide.js\";\nimport { registerPrompts } from \"./prompts.js\";\nimport { buildDiagnostics } from \"./tools/diagnostics.js\";\nimport { registerTools } from \"./tools/index.js\";\n\nexport const SERVER_NAME = BUILD_INFO.name;\nexport const SERVER_VERSION = BUILD_INFO.version;\n\nexport type CreateServerOptions = {\n config: Config;\n logger?: Logger;\n /** Injected by tests so nothing spawns a process or touches a real Reminders. */\n osascript?: OsascriptRunner;\n /** Injected by tests so the TTL cache can be exercised without waiting. */\n now?: () => Date;\n};\n\nexport type CreatedServer = {\n server: McpServer;\n client: AppleRemindersClient;\n};\n\n/**\n * Build the server. Side-effect free: it opens no connection, spawns no\n * process and reads no file, so a test can construct it freely and every\n * external dependency arrives through an option.\n */\nexport const createServer = (opts: CreateServerOptions): CreatedServer => {\n const { config } = opts;\n const server = new McpServer({ name: SERVER_NAME, version: SERVER_VERSION });\n\n const client = new AppleRemindersClient({\n config,\n ...(opts.logger ? { logger: opts.logger } : {}),\n ...(opts.osascript ? { osascript: opts.osascript } : {}),\n ...(opts.now ? { now: opts.now } : {}),\n });\n\n withLazyTools(\n server,\n {\n surface: \"reminders\",\n displayName: \"Reminders\",\n lazy: config.lazyTools,\n allowWrites: config.allowWrites,\n },\n (target, allowWrites) => registerTools(target, client, { allowWrites }),\n );\n /*\n * One flag, both primitives — see `exposePrompts` in core's config. A prompt\n * embeds its surface guide, so registering prompts without the resources\n * would leave every expansion naming a `cupertino://…/guide` that this\n * server does not serve.\n */\n if (config.exposePrompts) {\n registerPrompts(server, config.allowWrites);\n registerSurfaceResources(server, {\n surface: \"reminders\",\n displayName: \"Reminders\",\n guide: REMINDERS_GUIDE,\n diagnostics: () => buildDiagnostics(client, { allowWrites: config.allowWrites }),\n inventory: {\n describes: \"accounts and lists\",\n read: async () => ({\n accounts: await client.accounts(),\n lists: await client.lists(),\n }),\n },\n });\n }\n\n return { server, client };\n};\n"],"mappings":";;;;;;;AAWA,MAAM,MAAM,oBAAoB,IAAI,IAAI,mBAAmB,YAAY,GAAG,GAAG;CAC3E,MAAM;CACN,SAAS;AACX,CAAC;AAID,MAAa,aAAwB;CACnC,MAAM,IAAI;CACV,SAAS,IAAI;CACb,WAAA;CACA,eAAA;AACF;;;;;;;;;ACdA,MAAa,oBAAoC;CAC/C,SAAS;CACT,WAAW;AACb;;AAiBA,IAAa,wBAAb,cAA2C,qBAAqB;CAC9D,OAAyB;CAEzB,YAAY,KAAa;EACvB,MACE,wBAAwB,IAAI,wKAG9B;CACF;AACF;;AAGA,IAAa,oBAAb,cAAuC,qBAAqB;CAC1D,OAAyB;CAEzB,YAAY,MAAc,YAA+B,CAAC,GAAG;EAC3D,MACE,4BAA4B,KAAK,OAC9B,UAAU,SACP,eAAe,UAAU,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,IAAI,UAAU,SAAS,KAAK,QAAQ,GAAG,KACtF,wDACN,EAAE,WAAW,KAAK,CACpB;CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;ACnBA,MAAa,kBAAkB;;AAG/B,MAAM,YAAY,CAAC,gBAAgB,QAAQ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