Skip to content
Back to search

apple-notes-mcp

Apple Notes integration for Claude Code via MCP

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today

Check it deeper on your machine

It has changed since its scan on 13 Nov 2026. Its scripts were only partly scanned.

As a Claude Code plugin, install it and then ask Claude Code:

/plugin marketplace add keithmackay/mackayi/plugin install scanskillsafety@mackayiDo a deep scan of https://github.com/sweetrb/apple-notes-mcp with scanskillsafety

Or from a terminal, clone it and run it:

git clone https://github.com/keithmackay/scanskillsafety-skill ~/.claude/skills/scanskillsafetynode ~/.claude/skills/scanskillsafety/cli.cjs --deep 'https://github.com/sweetrb/apple-notes-mcp'

It checks the exact commit: every file, its packages against OSV (api.osv.dev), how it compares with this page's scan (findsafeskills.com receives the repository's address), and, if you agree, Claude reading every file with your own Claude subscription. It never runs the code.

Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/sweetrb--apple-notes-mcp/badge.svg)](/listings/sweetrb--apple-notes-mcp)

HTML

<a href="/listings/sweetrb--apple-notes-mcp"><img src="/api/listings/sweetrb--apple-notes-mcp/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

Apple Notes MCP runs on the Mac that holds your Notes library. Your assistant starts a local MCP server over **stdio**, and the server uses AppleScript, signed Apple Shortcuts, and read-only database access. Choose one client setup below, then complete the macOS permissions and optional feature setup you need.

**Version boundary:** these instructions describe v2.15.1, including the optional [permission broker](#permission-broker-opt-in). Normal client registration starts an in-process server unless a matching broker is already installed and answering. Broker installation is a separate opt-in step.

Manual client entries, setup commands, and the source checkout below select v2.15.1. Run setup from the same release as the server your client actually launches. The Claude Code plugin bundles its server; the Codex plugin manifest launches an unpinned npm package even when its marketplace is pinned. For reproducible Codex setup, use the manual registration below instead of the plugin. When upgrading, update the selected version consistently in the client and setup commands.

Run each setup target separately and use the exact options shown. Version 2.15.1 does not reject all unknown or mixed setup flags; a misspelled target can fall through to Shortcut setup and open import windows.

Requirements

- macOS with Notes.app and at least one configured Notes account. Features depend on the installed macOS version and account type; inspect `get-capabilities` before relying on optional features. - Node.js 20 or newer. The `npx` examples also need npm, normally included with Node.js. - A client that can launch a local stdio MCP server on this Mac. The configurations below cover Claude Code, Claude Desktop, Codex, Hermes, and Antigravity. - Automation permission to control Notes.app for AppleScript operations. Database-backed operations also need Full Disk Access for the process macOS holds responsible for the server. - Apple Shortcuts for native writes such as native tags, checklists, tables, pinning, and rich append. The optional native Markdown creation route needs macOS 26 or newer and an iCloud account. - An Apple developer toolchain only if you choose to build an optional native helper or permissions window. The public helper builds with older SDKs too; only a macOS 26 or newer SDK compiles in its `SpeechAnalyzer` route (see [macOS compatibility](#macos-compatibility)).

macOS compatibility

What works depends on the macOS release. `get-capabilities` reports this for the Mac it runs on (`features.<name>.minimumMacOSVersion`, `osSupported`, and a `reason` such as `requires_macos_13`), so check it there rather than relying on this table alone. The server is developed and tested on current macOS; rows for older releases come from each feature's declared minimum and Apple's API availability, not from testing on those releases.

| Feature | macOS 12 | macOS 13–15 | macOS 26 and later | |---|---|---|---| | AppleScript core: create, read, search, update, move and delete notes and folders (`applescriptCore`) | Yes | Yes | Yes | | Notes database reads with Full Disk Access: queries, structure, checklist state, exports, attachments (`fullDiskAccessReads`) | Yes | Yes | Yes | | `get-note-link` without Full Disk Access | Yes, AppleScript fallback | Yes, AppleScript fallback | No, needs Full Disk Access | | Listing bridge Shortcuts (`doctor`, `setup --check`, `shortcutsBridges`) | Yes, by name (12's `shortcuts list` cannot show identifiers) | Yes | Yes | | Native Tags and Background Operations bridges: native tags, checklists, tables, pinning, note links, `append-native` (`nativeTagsBridge`, `backgroundOperationsBridge`) | No: they call Notes App Intents actions, which macOS 12 does not have | Minimum declared; untested | Yes | | Markdown note creation through the Markdown bridge (`markdownNoteBridge`) | No | No | Yes, iCloud account only |

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

.claude-plugin/marketplace.json · Manifest · 23 lines
  1. {
  2. "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
  3. "name": "apple-notes-mcp",
  4. "version": "1.0.0",
  5. "description": "Apple Notes integration for Claude Code via MCP",
  6. "owner": {
  7. "name": "Rob Sweet",
  8. "email": "rob@superiortech.io"
  9. },
  10. "plugins": [
  11. {
  12. "name": "apple-notes",
  13. "description": "Manage Apple Notes through natural language - create, search, read, update, delete, and organize notes and folders",
  14. "version": "2.16.8",
  15. "author": {
  16. "name": "Rob Sweet",
  17. "email": "rob@superiortech.io"
  18. },
  19. "source": "./",
  20. "category": "productivity"
  21. }
  22. ]
  23. }
README.md · README · 3,229 lines
  1. # Apple Notes MCP Server
  2. A [Model Context Protocol (MCP)](https://modelcontextprotocol.io/) server that lets Claude (Claude Code and Claude Desktop), Codex, and other MCP clients read, search, create, edit, organize, and export notes in Apple Notes on macOS. It runs locally on your Mac and talks to Notes through AppleScript, Apple Shortcuts, and read-only access to the Notes database.
  3. Beyond creating and editing notes, it manages folders and accounts, native tags, checklists, tables, pinned notes, links, and attachments. It can also export notes as Markdown (through templates you can edit in a local web editor), HTML (with classic drawings as SVG), or JSON, read audio transcripts and drawings, link to single paragraphs with anchors that survive edits, and run a query language across your whole library.
  4. [![npm version](https://img.shields.io/npm/v/apple-notes-mcp)](https://www.npmjs.com/package/apple-notes-mcp)
  5. [![npm downloads](https://img.shields.io/npm/dm/apple-notes-mcp)](https://www.npmjs.com/package/apple-notes-mcp)
  6. [![node](https://img.shields.io/node/v/apple-notes-mcp)](https://www.npmjs.com/package/apple-notes-mcp)
  7. [![CI](https://github.com/sweetrb/apple-notes-mcp/actions/workflows/ci.yml/badge.svg)](https://github.com/sweetrb/apple-notes-mcp/actions/workflows/ci.yml)
  8. [![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/sweetrb/apple-notes-mcp/badge)](https://scorecard.dev/viewer/?uri=github.com/sweetrb/apple-notes-mcp)
  9. [![platform: macOS](https://img.shields.io/badge/platform-macOS-111?logo=apple&logoColor=white)](https://www.apple.com/macos/)
  10. [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
  11. [![MCP](https://img.shields.io/badge/MCP-server-blue)](https://modelcontextprotocol.io)
  12. <p align="center">
  13. <img src="https://raw.githubusercontent.com/sweetrb/apple-notes-mcp/main/codex/assets/screenshot.png" alt="Apple Notes MCP — create, search, and organize Apple Notes from Codex, Claude, and other AI assistants" width="680">
  14. </p>
  15. ## Contents
  16. - [What is This?](#what-is-this) · [Setup on your Mac](#setup-on-your-mac) · [Requirements](#requirements) · [macOS compatibility](#macos-compatibility) · [Features](#features)
  17. - [Tool Reference](#tool-reference): [notes](#note-operations), [folders](#folder-operations), [accounts](#account-operations), [batch](#batch-operations), [export, attachments, and media](#export-operations), [diagnostics](#diagnostics), [native background operations](#native-background-operations), [private helper](#private-helper-opt-in-unsupported-apple-api)
  18. - [Usage Patterns](#usage-patterns) · [Installation choices and upgrades](#installation-choices-and-upgrades) · [Server settings](#server-settings) · [Full Disk Access](docs/FULL-DISK-ACCESS.md) · [Public native helper](#public-native-helper) · [Permission broker](#permission-broker-opt-in)
  19. - [Security and Privacy](#security-and-privacy) · [Known Limitations](#known-limitations) · [Troubleshooting](#troubleshooting) · [Recurring macOS permission prompts](#recurring-macos-permission-prompts) · [Development](#development)
  20. ## What is This?
  21. This server acts as a bridge between AI assistants and Apple Notes. Once configured, you can ask Claude (or any MCP-compatible AI) to:
  22. - "Save this conversation as a note called 'Meeting Summary'"
  23. - "Find all my notes about the project deadline"
  24. - "Read my shopping list note"
  25. - "Move my draft notes to the Archive folder"
  26. - "What notes do I have in my Work folder?"
  27. The AI assistant communicates with this server, which then uses AppleScript to interact with the Notes app on your Mac. Some features also use packaged Apple Shortcuts (native tags, checklists, tables, pinning) or read the Notes database read-only (queries, checklist state, transcripts). Notes operations and speech recognition run locally. If you explicitly enable `downloadAssets: true`, the public helper may download speech models; what your MCP client does with tool results is up to that client.
  28. <a id="quick-start"></a>
  29. ## Setup on your Mac
  30. Apple Notes MCP runs on the Mac that holds your Notes library. Your assistant starts a local MCP server over **stdio**, and the server uses AppleScript, signed Apple Shortcuts, and read-only database access. Choose one client setup below, then complete the macOS permissions and optional feature setup you need.
  31. **Version boundary:** these instructions describe v2.15.1, including the optional [permission broker](#permission-broker-opt-in). Normal client registration starts an in-process server unless a matching broker is already installed and answering. Broker installation is a separate opt-in step.
  32. Manual client entries, setup commands, and the source checkout below select v2.15.1. Run setup from the same release as the server your client actually launches. The Claude Code plugin bundles its server; the Codex plugin manifest launches an unpinned npm package even when its marketplace is pinned. For reproducible Codex setup, use the manual registration below instead of the plugin. When upgrading, update the selected version consistently in the client and setup commands.
  33. Run each setup target separately and use the exact options shown. Version 2.15.1 does not reject all unknown or mixed setup flags; a misspelled target can fall through to Shortcut setup and open import windows.
  34. ### Requirements
  35. - macOS with Notes.app and at least one configured Notes account. Features depend on the installed macOS version and account type; inspect `get-capabilities` before relying on optional features.
  36. - Node.js 20 or newer. The `npx` examples also need npm, normally included with Node.js.
  37. - A client that can launch a local stdio MCP server on this Mac. The configurations below cover Claude Code, Claude Desktop, Codex, Hermes, and Antigravity.
  38. - Automation permission to control Notes.app for AppleScript operations. Database-backed operations also need Full Disk Access for the process macOS holds responsible for the server.
  39. - Apple Shortcuts for native writes such as native tags, checklists, tables, pinning, and rich append. The optional native Markdown creation route needs macOS 26 or newer and an iCloud account.
  40. - An Apple developer toolchain only if you choose to build an optional native helper or permissions window. The public helper builds with older SDKs too; only a macOS 26 or newer SDK compiles in its `SpeechAnalyzer` route (see [macOS compatibility](#macos-compatibility)).
  41. ### macOS compatibility
  42. What works depends on the macOS release. `get-capabilities` reports this for the Mac it runs on (`features.<name>.minimumMacOSVersion`, `osSupported`, and a `reason` such as `requires_macos_13`), so check it there rather than relying on this table alone. The server is developed and tested on current macOS; rows for older releases come from each feature's declared minimum and Apple's API availability, not from testing on those releases.
  43. | Feature | macOS 12 | macOS 13–15 | macOS 26 and later |
  44. |---|---|---|---|
  45. | AppleScript core: create, read, search, update, move and delete notes and folders (`applescriptCore`) | Yes | Yes | Yes |
  46. | Notes database reads with Full Disk Access: queries, structure, checklist state, exports, attachments (`fullDiskAccessReads`) | Yes | Yes | Yes |
  47. | `get-note-link` without Full Disk Access | Yes, AppleScript fallback | Yes, AppleScript fallback | No, needs Full Disk Access |
  48. | Listing bridge Shortcuts (`doctor`, `setup --check`, `shortcutsBridges`) | Yes, by name (12's `shortcuts list` cannot show identifiers) | Yes | Yes |
  49. | Native Tags and Background Operations bridges: native tags, checklists, tables, pinning, note links, `append-native` (`nativeTagsBridge`, `backgroundOperationsBridge`) | No: they call Notes App Intents actions, which macOS 12 does not have | Minimum declared; untested | Yes |
  50. | Markdown note creation through the Markdown bridge (`markdownNoteBridge`) | No | No | Yes, iCloud account only |
  51. | Public native helper build (`setup --public-helper`) | Builds with the SDK that release's Xcode or Command Line Tools provide; not tested on macOS 12 itself | Builds | Builds |
  52. | Classic drawing decode (`get-note-drawings`, needs the helper and Full Disk Access) | Yes | Yes | Yes |
  53. | On-device transcription (`transcribe-note-audio`, needs the helper and Full Disk Access) | `SFSpeechRecognizer`: needs a Speech Recognition grant for the app that launches the server, and an on-device model for the locale | Same as macOS 12 | `SpeechAnalyzer`, no grant needed, when the helper was built with a macOS 26 or newer SDK; otherwise as on macOS 12 |
  54. | Stored audio transcripts (`get-audio-transcripts`) | With Full Disk Access | With Full Disk Access | With Full Disk Access |
  55. Before macOS 13, `setup` does not open the Tags or Background bridge for import, and `setup` and `setup --check` report both as skipped with `requires_macos_13`.
  56. The public helper compiles its `SpeechAnalyzer` route only when the SDK provides it. With an older SDK the same helper builds without it and transcribes through `SFSpeechRecognizer` on every release, even on macOS 26 and later. Node.js 20 or newer is required everywhere.
  57. On macOS 12 the privacy panes are under **System Preferences → Security & Privacy → Privacy**, not System Settings. macOS never prompts for Full Disk Access on any release: nothing will ask, and you add the app or executable yourself (see [which process needs it](#full-disk-access)).
  58. Python is **not** an Apple Notes MCP runtime dependency. The package includes its compiled JavaScript server and signed Shortcut files. Python is used by developer scripts that regenerate those workflows, not by normal installation or MCP tool calls.
  59. You do not need an Apple ID password, API key, or NotesCTL installation to configure this server. A client's own login and tool-approval policy are separate from macOS privacy permissions.
  60. ### 1. Choose one client registration
  61. Use either a plugin or a manual MCP entry for the same client. Registering both can load duplicate servers or leave you using a different package version than expected. Adding a client entry does not grant macOS permissions or import Shortcuts.
  62. #### Claude Code
  63. For the plugin, run these commands inside a Claude Code session:
  64. ```text
  65. /plugin marketplace add sweetrb/apple-notes-mcp#v2.15.1
  66. /plugin install apple-notes@apple-notes-mcp
  67. ```
  68. The plugin bundles the server and the Apple Notes skill. For a manual MCP registration instead, run this in your terminal:
  69. ```bash
  70. claude mcp add apple-notes -s user -- npx -y apple-notes-mcp@latest
  71. ```
  72. Check the connection with `/mcp` in Claude Code. `claude mcp get apple-notes` inspects the manually registered server. Project-scoped `.mcp.json` entries require workspace/server approval and can override a user-scoped entry.
  73. #### Claude Desktop
  74. Open **Settings → Developer → Edit Config**. Merge the following server entry into `~/Library/Application Support/Claude/claude_desktop_config.json`, preserving any existing servers:
  75. ```json
  76. {
  77. "mcpServers": {
  78. "apple-notes": {
  79. "command": "npx",
  80. "args": ["-y", "apple-notes-mcp@latest"]
  81. }
  82. }
  83. }
  84. ```
  85. Fully quit and reopen Claude Desktop. This `npx` route does not require a preceding global npm installation. If the desktop app cannot find `npx`, use an absolute executable path or the fixed Node configuration below. The desktop app may have a different `PATH` from your interactive shell.
  86. #### Codex
  87. For the plugin and its Apple Notes skill:
  88. ```bash
  89. codex plugin marketplace add sweetrb/apple-notes-mcp --ref v2.15.1
  90. codex plugin add apple-notes@apple-notes-mcp
  91. ```
  92. For a manual MCP registration instead:
  93. ```bash
  94. codex mcp add apple-notes -- npx -y apple-notes-mcp@latest
  95. ```
  96. The equivalent entry in `~/.codex/config.toml` is:
  97. ```toml
  98. [mcp_servers.apple-notes]
  99. command = "npx"
  100. args = ["-y", "apple-notes-mcp@latest"]
  101. ```
  102. If `codex` is not on your terminal's `PATH`, use the desktop client's **Settings → MCP servers → Add server**: choose **STDIO**, enter `npx` with arguments `-y` and `apple-notes-mcp@latest`, save, and restart the server.
  103. Restart the relevant local Codex session or client. Use `/mcp` in the CLI or the client's MCP settings to inspect the connection. `codex mcp list` lists manually configured servers. The desktop client, CLI, and IDE extension share the Codex configuration; select local execution on the Mac containing your Notes library.
  104. The plugin's server entry runs the published npm package through unpinned `npx`, despite the marketplace ref above. Its server may therefore differ from v2.15.1. Use the manual entry to pin the runtime for these instructions, or run setup from the release matching the plugin's actual server. This is a different distribution path from the Claude Code plugin's bundled server.
  105. #### Hermes
  106. Register a local stdio server:
  107. ```bash
  108. hermes mcp add apple-notes --command npx --args -y apple-notes-mcp@latest
  109. ```
  110. Or merge this entry into `~/.hermes/config.yaml`:
  111. ```yaml
  112. mcp_servers:
  113. apple-notes:
  114. command: npx
  115. args: ["-y", "apple-notes-mcp@latest"]
  116. ```
  117. Restart the Hermes session. This repository supplies an MCP configuration route for Hermes; see its [CLI commands](https://hermes-agent.nousresearch.com/docs/reference/cli-commands#hermes-mcp) and [MCP configuration reference](https://hermes-agent.nousresearch.com/docs/reference/mcp-config-reference).
  118. #### Antigravity
  119. In the IDE, open **MCP Servers → Manage MCP Servers → View raw config**. Merge the same `mcpServers` JSON entry shown for Claude Desktop into the global `~/.gemini/config/mcp_config.json`, or use the workspace configuration at `.agents/mcp_config.json`. Refresh or restart the client so it loads the server. Google's [MCP guide](https://antigravity.google/docs/mcp) describes the current menu and configuration paths.
  120. The repository's `.antigravity-plugin/mcp_config.json` supplies an unpinned stdio server entry; the JSON above pins the audited release. Use `command` and `args`; this package does not provide a remote `serverUrl`.
  121. #### Gemini Spark (macOS Local MCP)
  122. In Gemini macOS builds that offer **Local MCP**, open **Connected Apps**, click **+ Custom**, and select **Local MCP** in "Set up a custom connected app". Fill in the form with:
  123. | Field | Value |
  124. |-------|-------|
  125. | Server Name | Apple Notes |
  126. | Description | Read, search, create, edit, organize, and export Apple Notes on this Mac. |
  127. | Command | `npx -y apple-notes-mcp@latest` |
  128. You can print these instructions from the installed server:
  129. ```bash
  130. npx -y apple-notes-mcp setup --gemini-spark
  131. ```
  132. The command only prints the guide. It exits before loading server configuration, checking Notes, or running the other setup commands, and it doesn't register the app or change permissions. Exit 0 means the guide was printed, not that Gemini connected. Run it by itself; combining it with other setup options exits 2.
  133. Keep **Sandbox settings** at **Default** initially, then click **Next** and review the discovered tools and permission requests before connecting. If Gemini can't launch the server, inspect **Show Logs** and check whether `npx` is available to the app. For a stable local installation, `npm install -g apple-notes-mcp` provides the `apple-notes-mcp` command; you can also use absolute paths to your Node executable and the installed `build/index.js` if the app can't find them. Keep that installation available, and update the command if you move it or replace Node.
  134. Gemini's sandbox and macOS permissions are separate. Review any additional filesystem access the launcher needs; **Full Access** isn't a required setup step. Automation of Notes.app enables the AppleScript tools, while database tools need the runtime's [Full Disk Access](#full-disk-access). Shortcut operations need the packaged bridge setup above. After connecting, ask Gemini to run `get-capabilities` for tool availability, then `doctor` for Notes access diagnostics before attempting a write. A successful terminal check doesn't verify the permissions of Gemini's process.
  135. This integration uses the Mac app's Local MCP command interface and the server's existing stdio transport. Availability depends on your Gemini build. Google's [custom apps documentation](https://support.google.com/gemini/answer/17209137) currently describes URL-based setup in the web app; it doesn't document this local form. **Cloud MCP**, Gemini web/mobile, and a hosted HTTP endpoint aren't supported by this server. These instructions apply to Gemini Spark, separately from Gemini CLI and Antigravity.
  136. #### Other MCP clients and remote execution
  137. A local MCP client can use the command `npx` with arguments `-y` and `apple-notes-mcp@latest`. Follow that client's stdio configuration format: JSON `mcpServers`, TOML, and YAML are not interchangeable.
  138. Apple Notes MCP has no built-in HTTP, SSE, WebSocket, or OAuth MCP endpoint. A cloud-only client cannot access your Mac's Notes library merely by installing the npm package in a Linux container or entering a URL. A separately managed transport bridge or client feature that delegates tool execution to your Mac needs its own configuration and security review; it is not part of this package's supported setup. GUI reveal and clipboard tools also need your logged-in desktop session.
  139. The optional `anchors serve` command is a paragraph-link resolver, and `templates edit` is a template editor. Neither is a remote MCP server.
  140. <a id="full-disk-access"></a>
  141. <a id="permissions-check"></a>
  142. ### 2. Verify the server and macOS access
  143. In the configured client, ask it to run `get-capabilities` and then `doctor`. `get-capabilities` inspects feature availability without opening Notes or running the bridges. `doctor` also sends a read-only Apple event to Notes and may trigger the macOS Automation prompt. Run these from the actual client because a successful terminal check does not establish that a different desktop app has the same permissions.
  144. | Access or component | What it enables | How to complete it |
  145. |---|---|---|
  146. | Automation of Notes.app | AppleScript reads and writes | Allow the macOS prompt for the responsible app to control Notes. Inspect **Privacy & Security → Automation** if access was denied. |
  147. | Full Disk Access | Database reads, rich-content inspection and safety checks, query tools, native object reads, and database-backed exports | macOS never prompts for it. Add the responsible executable/app under **Privacy & Security → Full Disk Access** (macOS 12: **System Preferences → Security & Privacy → Privacy**), fully quit and relaunch the host, then rerun `doctor`. |
  148. | Shortcut installation and consent | Native tag, checklist, table, pin, link, and append routes | Import the bridges and complete their foreground consent steps below. |
  149. | Public helper and, where required, Speech Recognition | Classic drawing decoding and on-device audio transcription | Build the optional helper; follow the permission result from `doctor` or the tool. |
  150. **Which process needs Full Disk Access?** macOS never shows a Full Disk Access prompt, so nothing will ask; you add the entry yourself. For a brokered session, grant the signed **Apple Notes MCP Broker.app** access; `doctor` reports whether that session uses it. Without the broker, Claude Desktop needs the exact **Node executable** printed by `doctor`; granting Claude.app alone does not reach the server in that launch path. Add that exact path: a Node found some other way (`which node` in a shell, another install, or a Homebrew symlink) can be a different binary. For a terminal-launched client, the terminal app is normally the responsible app; for an editor-launched server, check that editor. Most other desktop clients stay responsible for the servers they launch, so grant the client app itself (and the Node path from `doctor` if that alone does not work). Use the actual running client's diagnostics instead of assuming that all clients share grants.
  151. Client sandbox access is a separate boundary. A sandboxed client must be able to launch the executable and reach its files; a brokered client also needs access to the broker's local Unix socket. Full Disk Access and Automation grants do not expand the client's sandbox. Diagnose a launch or socket-access refusal in the client before changing macOS privacy permissions.
  152. To inspect setup from a terminal without opening permission panes or requesting Automation access:
  153. ```bash
  154. npx -y apple-notes-mcp@latest setup --permissions --check --json
  155. ```
  156. The Automation result is intentionally unknown in this mode. When you are at the Mac and want to check it, this command sends a read-only Apple event and may show the macOS consent prompt:
  157. ```bash
  158. npx -y apple-notes-mcp@latest setup --permissions --once --probe-automation
  159. ```
  160. For an interactive checklist that also opens the relevant settings panes:
  161. ```bash
  162. npx -y apple-notes-mcp@latest setup --permissions --open --probe-automation
  163. ```
  164. The command checks permissions; it does not grant them. `--check` and SSH sessions suppress the Automation probe even when `--probe-automation` is supplied. Without the probe, exit status 0 does not establish Automation access.
  165. Full Disk Access is optional if you only need operations that can safely run through AppleScript, but many capabilities and safety checks depend on it. It can also be required by guards on existing-note writes, including rich-content and revision verification; it is not merely an enhancement for read tools. Do not interpret an unavailable database-backed feature as an empty result. In particular, sync results without database visibility do not prove that iCloud sync is idle. Use the tool reference and `get-capabilities` for individual requirements, and see the [Full Disk Access guide](docs/FULL-DISK-ACCESS.md).
  166. ### 3. Enable the native Shortcut features you need
  167. Run explicit setup on your Mac:
  168. ```bash
  169. npx -y apple-notes-mcp@latest setup
  170. ```
  171. Approve **Add Shortcut** for the missing signed workflows that macOS opens:
  172. - `Notes MCP Tags`
  173. - `Notes MCP Background v6`
  174. - `Notes MCP Markdown`, offered only on macOS 26 or newer and optional for native Markdown creation
  175. Releases before 2.16.1 installed these as `Apple Notes MCP - Native Tags`,
  176. `Apple Notes MCP - Background Operations v6` and `Apple Notes MCP - Create Markdown Note`.
  177. Those still work. To switch to the short names, run `setup` after deleting the old ones
  178. in Shortcuts.app. Delete `Apple Notes MCP - Background Operations v5` in any case; the
  179. server no longer uses it.
  180. Then check installation:
  181. ```bash
  182. npx -y apple-notes-mcp@latest setup --check
  183. ```
  184. The first two bridges determine this check's readiness; the optional Markdown bridge is reported separately. Keep only one installed copy of each named bridge. The server refuses duplicate bridge names.
  185. After installation or upgrade, run each installed bridge once in the foreground in Shortcuts.app and answer its access prompts. Choose **Always Allow** if you want that bridge to run unattended. For the Markdown bridge, use the first-run request in [`shortcuts/README.md`](shortcuts/README.md); running it without input stops before it asks Notes for access. That request creates a disposable check note.
  186. An installed bridge is not proof of consent: `shortcuts list`, `setup --check`, and `doctor` cannot observe the first-run consent state. A background native write can stall on an unanswered prompt. After a timeout or an indeterminate write result, read the exact note before retrying because the write may already have happened.
  187. ### 4. Build optional helpers
  188. These commands are separate from registering the MCP client. If `xcrun swiftc` or `clang` is unavailable, install Apple's Command Line Tools with `xcode-select --install` before building a helper. The public helper compiles its macOS 26 `SpeechAnalyzer`/`SpeechTranscriber` route only when the SDK declares those APIs; with an older SDK it builds with the `SFSpeechRecognizer` route only. A build against the macOS 15.4 SDK targeting macOS 12 compiles; running it on macOS 12 itself is untested.
  189. #### Public native helper
  190. <a id="public-native-helper"></a>
  191. Needed for `get-note-drawings` and `transcribe-note-audio`. Brokered sessions do not load external helpers; set `APPLE_NOTES_MCP_BROKER=off` for this client and restart it before using these tools:
  192. ```bash
  193. npx -y apple-notes-mcp@latest setup --public-helper
  194. npx -y apple-notes-mcp@latest setup --public-helper --check
  195. ```
  196. It compiles locally, signs ad hoc, verifies its handshake, and records source and binary checksums. The server refuses stale or modified helpers; rerun setup after a relevant package upgrade. This helper uses public Apple frameworks and does not open or write the Notes database. The server still needs Full Disk Access to read the drawing/audio assets it passes to the helper.
  197. On older macOS versions, speech transcription needs Speech Recognition access for the responsible host. The helper never requests this silently. On macOS 26 and newer, the SpeechAnalyzer route has been observed to work without a prior grant; explicit denial or restriction still blocks it. Inspect the returned capability/permission status on your Mac.
  198. #### Private helper setup
  199. Optional read-only NotesShared state inspection, disabled by default. Brokered sessions do not load this helper; set `APPLE_NOTES_MCP_BROKER=off` for this client and restart it first:
  200. ```bash
  201. npx -y apple-notes-mcp@latest setup --native-helper
  202. npx -y apple-notes-mcp@latest setup --native-helper --check
  203. ```
  204. To enable it, set the string environment value `APPLE_NOTES_MCP_ENABLE_PRIVATE=1` for the server and restart the client. Inspect `native-helper-status` before using `native-note-state`. This released helper opens the store read-only and cannot provide deep native writes. Apple's private API may change with macOS updates; the remaining server features do not require this helper.
  205. #### Optional checklist window
  206. Optional graphical presentation of the checklist:
  207. ```bash
  208. npx -y apple-notes-mcp@latest setup --permissions-window
  209. npx -y apple-notes-mcp@latest setup --permissions --window
  210. ```
  211. It displays the command's checks and opens settings on request. It does not become the permission owner or replace the client process.
  212. ### 5. Confirm the capabilities you intend to use
  213. After restarting the client, run `doctor` and `get-capabilities` again. Confirm that the specific routes you need are available, not just that the server connected. Private helper status, public helper readiness, Markdown creation, and the native-write bridges are separate checks.
  214. Use read-only operations first, such as listing accounts/folders and reading a note you select. If you want to exercise a write route, use a dedicated disposable note and verify the result by its exact ID. A successful plain note creation does not validate native tables, checklists, or Markdown creation; test the feature you plan to use.
  215. Keep the server's revision and scope checks enabled. Updates, appends, and deletes use exact IDs and content hashes; native routes may also require a distinctive existing `scopeText`. Full-body updates refuse rich notes they cannot preserve. Follow the returned error and capability information instead of falling back to a lower-level write.
  216. ## Features
  217. | Feature | Description |
  218. |---------|-------------|
  219. | **Create Notes** | Create notes from plaintext, HTML, or Markdown, with optional folder/account targeting (Markdown creation uses an optional Shortcut on macOS 26 or later) |
  220. | **Search Notes** | Find notes by title or search within note content |
  221. | **Query Language** | `query-notes` combines text, folder, account, tag, attachment, checklist, flag, word-count, and date conditions with AND/OR/NOT, read from the Notes database (requires Full Disk Access) |
  222. | **Read Notes** | Retrieve note content as HTML, plain text, or Markdown, plus metadata that AppleScript does not expose (pinned, Quick Note, locked, Recently Deleted) |
  223. | **Note Structure** | Decode a note into typed paragraph blocks, list its paragraphs and links, and get a direct link to one paragraph (requires Full Disk Access) |
  224. | **Update Notes** | Replace, append to, or prepend to an existing note, guarded by a content hash so a note that changed since it was read is never overwritten |
  225. | **Delete Notes** | Remove notes (moves to Recently Deleted) |
  226. | **Move Notes** | Organize notes into folders (supports nested paths) |
  227. | **Folder Management** | Create, list, rename, and delete folders with full hierarchical path support; read the folder tree with note counts and Smart Folder rules |
  228. | **Multi-Account** | Work with iCloud, Gmail, Exchange, or any configured account, including account IDs and default folders |
  229. | **Batch Operations** | Delete or move multiple notes at once |
  230. | **Native Tags** | List, add, remove, and replace real Notes tags (not just `#hashtag` text) |
  231. | **Checklists** | Read checklist done/undone state from the Notes database, and append real checklist items through a Shortcut |
  232. | **Tables** | Read native tables as Markdown and JSON, and append new native tables |
  233. | **Pinning** | Read pinned state and pin or unpin a note |
  234. | **Links** | Get a note's `notes://` deep link, insert web, mail, or note-to-note links, and list the links in a note or folder |
  235. | **Export** | Export notes as paginated JSON, or render a note or folder as Markdown (with reusable templates) or standalone HTML |
  236. | **Attachments** | Add files to notes (from a path or the pasteboard), list attachments with their on-disk paths, find a note's lead image, save or batch-export them, or fetch their bytes as base64 |
  237. | **Audio and Drawings** | Read the transcripts Notes stored for recordings, transcribe audio on-device, and decode drawings to strokes and SVG |
  238. | **Incremental Sync** | `list-recent-notes` pages through notes by modification time with an exact cursor |
  239. | **Notes.app UI State** | Reveal a note, folder, account, or attachment in Notes.app, or read the current Notes.app selection |
  240. | **Sync Awareness** | Detect iCloud sync in progress, warn about incomplete results |
  241. | **Collaboration** | Detect shared notes, warn before modifying |
  242. | **Diagnostics** | `health-check` plus a richer `doctor` (server version, reachability, automation permission, accounts, Full Disk Access), sync status, statistics, and `get-capabilities` for the Shortcut bridges |
  243. Read/list/get tools also return **structured JSON** (`structuredContent`) alongside the text, so agents can consume results without parsing prose.
  244. Some clients (Claude Desktop among them) pass the model only a result's text
  245. and drop `structuredContent`. So every result that has `structuredContent` also
  246. ends with one more text block holding the same data as a single JSON line:
  247. ```
  248. structuredContent: {"id":"x-coredata://…/ICNote/p123","contentHash":"sha256:…","writable":true,…}
  249. ```
  250. That line carries every token a follow-up call needs: the `contentHash`
  251. revision token for `expectedContentHash`, new ids, `nativeTags`, `writable`,
  252. `page.nextOffset`, and an error's `code`, `committed` and `indeterminate`. A
  253. long value the text above already shows in full, such as the body from
  254. `get-note-content`, appears as `"[shown in full above]"` instead of twice. If
  255. the line would still exceed 16 KB, fields larger than 1 KB (usually a list
  256. already printed above) are left out and named in `_omitted`. Tools whose text
  257. already is that JSON get no extra block. `structuredContent` itself is
  258. unchanged.
  259. ### MCP resources & prompts
  260. Resources expose read-only context the client can attach without a tool call:
  261. `notes://accounts`, `notes://folders`, `notes://stats`, and the
  262. `notes://note/{id}` template (returns the note as Markdown). Prompts package
  263. common workflows: `find-note`, `weekly-review`, `new-meeting-note`.
  264. ### AppleScript limitations
  265. A few Notes UI features are not exposed to AppleScript. Some are recovered by
  266. reading Notes' own database instead; the rest genuinely cannot be supported. See
  267. **[docs/APPLESCRIPT-LIMITATIONS.md](https://github.com/sweetrb/apple-notes-mcp/blob/main/docs/APPLESCRIPT-LIMITATIONS.md)**
  268. for the investigation and verification behind each:
  269. - **Pinned notes** — Notes has no scriptable `pinned` property via AppleScript. Pin state is **read** from the NoteStore database by the BETA `get-note-metadata` tool and `list-special-notes`, and **set** through the Background Operations Shortcut by [`set-note-pinned`](#set-note-pinned).
  270. - **Note-to-note links** — AppleScript exposes no link property or link element. Links are instead read from the NoteStore database by [`list-note-links`](#list-note-links), and inserted by [`insert-note-link`](#insert-note-link) (through a Shortcut) or [`insert-link`](#insert-link). A shareable `notes://showNote?identifier=<uuid>` deep link is available via [`get-note-link`](#get-note-link).
  271. ---
  272. ## Tool Reference
  273. This section documents all available tools. AI agents should use these tool names and parameters exactly as specified.
  274. ### Identifier forms
  275. Every tool that takes a note id (`id`, `noteId`, `ids`, `linkedNoteId`, or the `id` inside a batch entry) accepts any of three forms of the same note:
  276. | Form | Example shape | Needs Full Disk Access |
  277. |------|---------------|------------------------|
  278. | AppleScript id (canonical) | `x-coredata://<store-uuid>/ICNote/p123` | No |
  279. | Notes UUID (`identifier`) | `8-4-4-4-12` hex digits, as in `notes://showNote?identifier=` links | Yes |
  280. | Numeric Core Data key | `123` (the digits after `p`) | Yes |
  281. The server turns a UUID or numeric key into the canonical id before the tool runs, reading the Notes database read-only. A numeric key or UUID resolves only to a note, never to a folder or attachment. Without Full Disk Access those two forms fail with an error that says so, while `x-coredata` ids keep working as before. Folder-id inputs (`show-folder`, `get-folder-by-id`, `rename-folder`) accept a folder's UUID or numeric key the same way, resolving only to folders.
  282. When Full Disk Access is granted, list and read tools also return stable identifiers next to each `id`: notes carry `identifier`, `folderIdentifier`, and `accountIdentifier`; folders carry `identifier`, `parentIdentifier` (nested folders only), and `accountIdentifier`; accounts carry `identifier`. These fields come from one batched read-only query per call and are omitted when the database cannot be read. Tools that return them: `search-notes`, `list-notes`, `get-selected-notes`, `list-shared-notes`, `get-note-content`, `get-note-by-id`, `get-note-details`, `list-folders`, `get-folder-by-id`, `list-accounts`, and `get-default-location`.
  283. ### Error results
  284. A failed call returns `isError: true` with the same human-readable text as
  285. before, plus `structuredContent` carrying a stable machine-readable `code`
  286. (also repeated in the trailing `structuredContent:` text line, for clients
  287. that drop `structuredContent`).
  288. Branch on `code`, not on the prose, which may be reworded.
  289. | `code` | Meaning |
  290. |--------|---------|
  291. | `not_found` | The note, folder, account, attachment, or checklist does not exist |
  292. | `ambiguous` | More than one item matched; use an exact id |
  293. | `permission_denied` | macOS refused Automation access to Notes.app |
  294. | `full_disk_access_missing` | The Notes database is not readable; grant Full Disk Access |
  295. | `shortcut_not_installed` | A native-write bridge Shortcut is not installed exactly once |
  296. | `timeout_indeterminate` | The operation timed out; for a write, the outcome is unknown |
  297. | `verification_failed` | The write ran, but exact-ID readback did not confirm it |
  298. | `revision_conflict` | The note changed since it was read |
  299. | `validation_error` | The request was rejected before anything ran |
  300. | `unsupported` | Not supported for this note or in this mode, such as a locked note |
  301. | `notes_unavailable` | Notes.app is not running, busy, or not responding |
  302. | `operation_failed` | The server could not classify the failure; read the text |
  303. Two optional booleans describe a write's outcome when it is known.
  304. `indeterminate: true` means the outcome is uncertain: read the target by exact
  305. id before any retry, and never retry blindly. `committed: true` means the write
  306. took effect even though its verification failed; `committed: false` means
  307. nothing was written (for example a `revision_conflict`). An absent flag means
  308. unknown. An argument that fails the input schema is rejected before the tool
  309. runs, with `code: "validation_error"` and `committed: false`. The exception is
  310. a Notes UUID or numeric key that could not be resolved to an id: it carries
  311. `not_found`, or `full_disk_access_missing` when the database is unreadable.
  312. ### Note Operations
  313. #### `create-note`
  314. Creates a new note in Apple Notes.
  315. | Parameter | Type | Required | Description |
  316. |-----------|------|----------|-------------|
  317. | `title` | string | Yes | The title of the note. Automatically prepended as `<h1>` — do NOT include the title in `content` |
  318. | `content` | string | One of `content`/`contentPath` | The body content of the note (do not repeat the title here) |
  319. | `contentPath` | string | One of `content`/`contentPath` | Absolute path of a local UTF-8 file to use as the body instead of `content`. Allowed in the same places [`save-attachment`](#save-attachment) may write (home, temp, `/Volumes`), except hidden paths (any component starting with `.`, such as `~/.ssh` or a project `.env`) and `~/Library` other than iCloud Drive (`~/Library/Mobile Documents`) and cloud storage folders (`~/Library/CloudStorage`), which can hold credentials; set `APPLE_NOTES_MCP_ALLOW_PRIVATE_CONTENT_PATHS=1` to allow those. Symbolic links, non-regular files, invalid UTF-8 and files over 1 MiB are refused before anything is written. A leading byte-order mark is dropped |
  320. | `tags` | string[] | No | Returned-only metadata — **NOT written to Notes.app**. Apple Notes tags can't be set via AppleScript, so values passed here are echoed back in the response but do not appear on the created note. Inline `#hashtags` in `content` stay searchable text and are returned as `hashtags`, but they do not become native Notes tags; add real tags afterwards with [`add-native-tags`](#add-native-tags). Refused with `format: "markdown"` |
  321. | `folder` | string | No | Folder to create the note in. Supports nested paths like `"Work/Clients"`. **The folder must already exist** — create it first with [`create-folder`](#create-folder). A smart folder is refused (see [`move-note`](#move-note)). Defaults to account root |
  322. | `account` | string | No | Account name (defaults to Notes.app's default account; matched exactly or by a *unique* prefix — an ambiguous prefix is refused). Must be an account Notes.app already has configured — see [`list-accounts`](#list-accounts) |
  323. | `format` | string | No | Content format: `"plaintext"` (default), `"html"`, or `"markdown"`. In all formats, the title is automatically prepended as the note's title line. In plaintext mode, newlines become `<br>`, tabs become `<br>`, and backslashes are preserved as HTML entities. `"markdown"` produces real Title/Heading/Subheading styles through a Shortcut; see [Markdown notes](#markdown-notes) |
  324. | `markdownRoute` | string | No | With `format: "markdown"` only: `"shortcut"` (default) or `"html"`. See [Markdown through HTML](#markdown-through-html) |
  325. | `timeoutSeconds` | number | No | Whole seconds, 1–120, for each Notes.app automation step this call runs; overrides `APPLE_NOTES_MCP_TIMEOUT_MS` for this call only. A timed-out write is uncertain, not failed: read the note by id before any retry. Also accepted by `get-note-content`, `update-note`, `append-to-note`, `delete-note` and `move-note` |
  326. **Example (with inline textual hashtags):**
  327. ```json
  328. {
  329. "title": "Meeting Notes",
  330. "content": "Discussed Q4 roadmap and budget allocation\n\n#work #meetings"
  331. }
  332. ```
  333. **Example - Create in a specific folder:**
  334. ```json
  335. {
  336. "title": "Client Meeting",
  337. "content": "Discussed project timeline",
  338. "folder": "Work/Clients"
  339. }
  340. ```
  341. **Example - HTML formatting:**
  342. ```json
  343. {
  344. "title": "Status Report",
  345. "content": "<h2>Summary</h2><p>All tasks <b>on track</b>.</p><ul><li>Feature A: complete</li><li>Feature B: in progress</li></ul>",
  346. "format": "html"
  347. }
  348. ```
  349. > **Note:** The title is automatically prepended as `<h1>` in both plaintext and HTML formats. Do not include a `<h1>` title tag in the `content` parameter, or the title will appear twice.
  350. > **Known limitation:** with `"plaintext"` or `"html"`, `create-note` sets the note
  351. > body directly via AppleScript's `body` property, which does not apply real Notes
  352. > paragraph styles for interior content — an `<h2>`/`<h3>` tag or a
  353. > `<span style="font-size: …px">` heading span in `content` renders as plain bold,
  354. > styled text, not an actual Heading or Subheading
  355. > ([#172](https://github.com/sweetrb/apple-notes-mcp/issues/172)). Use
  356. > `format: "markdown"` for real headings in a new note, or
  357. > [`append-native`](#append-native)'s `format: "markdown"` on a note that already
  358. > exists.
  359. ##### Markdown notes
  360. `format: "markdown"` creates the note with Notes' own Markdown importer (the
  361. Create Note action's "Interpret as Markdown" option, macOS 26+), run through the
  362. packaged `Notes MCP Markdown` Shortcut. `#`, `##` and `###`
  363. become real Title, Heading and Subheading styles, and the note starts with the
  364. title line, with no seed line.
  365. ```json
  366. {
  367. "title": "Project Plan",
  368. "content": "## Goals\n\n- Ship the beta\n- Collect feedback\n\n### Links\n\n[Tracker](https://example.com/tracker)",
  369. "format": "markdown",
  370. "folder": "Work"
  371. }
  372. ```
  373. - Notes interprets Markdown only in an iCloud account. The note is created in the
  374. iCloud account's default folder, then moved to `folder` in that account.
  375. `folder` must already exist and is checked before anything is created. If it
  376. exists only in another account, the note is still created and verified in the
  377. iCloud default folder, and the error names that account and the note's id so
  378. you can create the folder there and `move-note` it instead of creating the
  379. note again. `account` is refused with this format.
  380. - `tags` are refused with this format. Create the note without them, then add
  381. native tags to the returned id with [`add-native-tags`](#add-native-tags).
  382. - `content` accepts the same bounded subset as `append-native`'s Markdown:
  383. `#`/`##`/`###` headings, flat lists, `**bold**`, `*italic*` and inline links.
  384. It also refuses Markdown that Notes would rewrite and the server could not
  385. verify: `_` emphasis (underscores inside a word, as in `snake_case`, and
  386. inside a link destination, as in `[docs](https://example.com/_next/static)`,
  387. are fine), backslash escapes, character references such as `&amp;`, `===` lines
  388. and rule lines other than the `---` divider described below, indented headings or list items, `1)` lists, closing `#`s, and
  389. formatting inside link labels. Content that needs one of these literally, such
  390. as a `/_next` path or a literal `\*`, has no Markdown form here: use
  391. `format: "html"` for that note (or `append-native` with `format: "html"` on an
  392. existing one), which keeps the characters but not the Heading and Subheading
  393. styles. Markdown punctuation in `title` is escaped, so the title stays literal.
  394. - Notes' importer also maps these block constructs to native styles. They are
  395. gated separately, and `get-capabilities` reports them as
  396. `create-note-markdown-blocks`. Each mapping below was live-verified on
  397. macOS 27.2 by reading the created note's stored styles.
  398. | Markdown | Native result |
  399. |----------|---------------|
  400. | `- [ ] item` / `- [x] item` | Checklist item, unchecked / checked |
  401. | `> text` (consecutive lines form one quote) | Body paragraph with a block quote |
  402. | A fence of bare ```` ``` ```` lines (no language) | Monospaced paragraphs; the code text is kept literally |
  403. | `---` on its own line, after a blank line | Divider line |
  404. | `` `inline code` `` | **Highlighted** text, not monospace |
  405. Constructs Notes would not render faithfully, or that this server cannot yet
  406. verify, are refused before anything is created: `~~~` fences, a language
  407. after the opening fence, nested (`>>`) or indented quotes, lists or headings
  408. inside a quote, a quote followed directly by text (Markdown would join that
  409. text to the quote), `---` directly under text (Markdown would make that text
  410. a heading), `***`/`___`/`----` rules, `[X]`, `* [ ]` or `+ [ ]` items, checklist
  411. items directly next to ordinary list items, inline code padded with spaces or
  412. inside a link label, tables, and `~~strikethrough~~`. The readback checks the
  413. block-quote text, the Monospaced text, each checklist item's text and done
  414. state, the divider count, and the highlighted text. These mappings apply to
  415. the default Shortcut route only; see
  416. [Markdown through HTML](#markdown-through-html) for `markdownRoute: "html"`.
  417. - [`append-native`](#append-native)'s `format: "markdown"` refuses all of the
  418. constructs above: its Shortcuts converter is a different one, which renders
  419. a quote and a fenced block as plain body text, `- [ ]` as a bullet with
  420. literal brackets, and inline code as plain text, and drops `---`.
  421. - The server finds the new note among the notes added to the default folder
  422. during the run by verifying each one's visible text, heading levels and links
  423. by exact-ID readback, and moves it only after exactly one verifies. On any
  424. uncertain result it names the note (or says to search for the title) and
  425. never retries.
  426. - It is gated like the other native operations; `get-capabilities` reports it
  427. as `create-note-markdown`. The Create Markdown Note Shortcut is optional and
  428. needed only for this format (macOS 26+); install and approve it as described in
  429. [`shortcuts/README.md`](shortcuts/README.md).
  430. - A first line that is exactly `# <title>` (same case and spacing as `title`) is
  431. removed together with one blank line after it, because the title is supplied
  432. separately; the response then carries `strippedDuplicateTitle: true`. A
  433. different first heading stays in the body. This applies to both Markdown
  434. routes, and Markdown that holds only that heading is refused.
  435. ##### Markdown through HTML
  436. `markdownRoute: "html"` imports the same bounded Markdown subset without the
  437. Shortcut: the server converts it to HTML and creates the note through AppleScript,
  438. like `format: "html"`. It works in any account, accepts `tags`, and needs no
  439. Shortcut, but headings get the plain bold styling described in the known
  440. limitation above rather than real Heading and Subheading styles.
  441. On this route, bullet task items (`- [ ] item`, `- [x] item`) become ordinary
  442. list rows that start with a visible `☐` or `☑` character, and the response
  443. reports how many as `taskItemsRendered`. They are text, not native checkable
  444. checklist items. Use this route as the glyph fallback when the Shortcut is not
  445. installed or the note is outside iCloud. Block quotes, fenced code and inline code, which
  446. the Shortcut route maps natively, are refused on this route, and a `---` line
  447. stays literal text rather than becoming a divider.
  448. ```json
  449. {
  450. "title": "Weekly Review",
  451. "contentPath": "/Users/me/Documents/weekly-review.md",
  452. "format": "markdown",
  453. "markdownRoute": "html",
  454. "folder": "Work"
  455. }
  456. ```
  457. **Returns:** Confirmation message with note title and ID. Save the ID for subsequent operations like `update-note`, `delete-note`, etc.
  458. ---
  459. #### `search-notes`
  460. Searches for notes by title or content.
  461. | Parameter | Type | Required | Description |
  462. |-----------|------|----------|-------------|
  463. | `query` | string | Yes | Text to search for |
  464. | `searchContent` | boolean | No | If `true`, searches note content (title line included); if `false` (default), searches titles only. With Full Disk Access, content search reads the Notes database (well under a second, the 5000 most recently modified notes, Recently Deleted excluded); without it, it falls back to AppleScript, which scans every body and can time out on a broad term |
  465. | `account` | string | No | Account to search in (defaults to Notes.app's default account; exact or unique-prefix match) |
  466. | `folder` | string | No | Limit search to a specific folder (supports nested paths like `"Work/Clients"`) |
  467. | `modifiedSince` | string | No | ISO 8601 date string to filter notes modified on or after this date (e.g., `"2025-01-01"`) |
  468. | `limit` | number | No | Maximum number of results to return. **Defaults to 50** — a broad query reads several properties per match via AppleScript (~200ms/note), so an unbounded search over hundreds of matches can exceed Notes' 30s timeout and return an error instead of results. Pass a higher value to see more; the applied limit (and whether it truncated the results) is disclosed in the response. |
  469. | `includeWordCount` | boolean | No | Add `wordCount` to each result (`null` when the note is locked or its body unreadable). A database content search already has the text. Otherwise the bodies are read in one batched read-only database query, never one AppleScript call per note; that needs Full Disk Access and also adds `matchedIn`. Without it, the response carries `wordCountUnavailable` and the results are unchanged. |
  470. **Example - Search titles:**
  471. ```json
  472. {
  473. "query": "meeting"
  474. }
  475. ```
  476. **Example - Search content:**
  477. ```json
  478. {
  479. "query": "budget allocation",
  480. "searchContent": true
  481. }
  482. ```
  483. **Example - Search recent notes with limit:**
  484. ```json
  485. {
  486. "query": "todo",
  487. "searchContent": true,
  488. "modifiedSince": "2025-01-01",
  489. "limit": 10
  490. }
  491. ```
  492. **Returns:** List of matching notes with titles, folder names, and IDs. Use the returned ID for subsequent operations like `get-note-content`, `update-note`, etc. A content search also returns `source` (`"database"` or `"applescript"`), and `scanTruncated` when the database path left older notes unsearched.
  493. When the note text came from the database (a database content search, or any search with `includeWordCount`), each result also carries `matchedIn`: `["title"]`, `["body"]`, or `["title", "body"]`, saying where the query text occurs. The body is the text after the first line. `matchedIn` is absent for locked notes and for AppleScript searches without `includeWordCount`. The text output appends the same details to each line, for example `· matched in title, body · 245 words`.
  494. **Example - Content search with word counts:**
  495. ```json
  496. {
  497. "query": "budget",
  498. "searchContent": true,
  499. "includeWordCount": true
  500. }
  501. ```
  502. ---
  503. #### `query-notes`
  504. Finds notes with a boolean query expression evaluated against the NoteStore
  505. database, read-only. Because it does not go through AppleScript, a query over
  506. several hundred notes typically returns in well under a second, and one call
  507. can match titles and bodies together.
  508. **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)). Without it, use `search-notes`.
  509. | Parameter | Type | Required | Description |
  510. |-----------|------|----------|-------------|
  511. | `query` | string | Yes | Query expression (syntax below), at most 2000 characters |
  512. | `limit` | number | No | Maximum notes to return. Defaults to 50, maximum 500. The response reports the total match count. |
  513. | `scanLimit` | number | No | How many of the most recently modified notes to examine. Defaults to 500, maximum 10000. The response says when older notes were left unscanned. A large scan decodes more bodies, so it takes longer. |
  514. | `includeDeleted` | boolean | No | Also scan notes in Recently Deleted, notes pending deletion, and folderless notes. Defaults to `false`. |
  515. | `includeWordCount` | boolean | No | Add `wordCount` to each returned note, the same count `words:` filters on (`null` when locked or unreadable). Free when the query already reads bodies; a metadata-only query (for example `pinned`) reads just the returned notes' bodies in one extra read-only query. Defaults to `false`. |
  516. **Syntax:**
  517. | Form | Matches |
  518. |------|---------|
  519. | `budget`, `"quarterly budget"` | Title or body contains the word or phrase (case-insensitive substring) |
  520. | `title:x`, `body:x`, `text:x` | Title only, body only (text after the first line), or either |
  521. | `folder:Work`, `folder:"Work/Clients"` | The note's own folder, by name or full path, case-insensitive (notes in subfolders are not included); a literal `/` in a name can be written `\/` as in `list-folders` |
  522. | `account:iCloud` | Account name, case-insensitive |
  523. | `tag:finance` | Native Notes tag (with or without `#`); textual hashtags are ordinary words |
  524. | `has:link`, `has:attachment`, `has:checklist`, `has:drawing`, `has:image`, `has:video`, `has:audio`, `has:pdf`, `has:table`, `has:scan`, `has:url`, `has:map`, `has:tag` | The note body contains that kind of object. `has:url` is a link preview card (it also counts as `has:link`, as inline links do); `has:map` is a map attachment |
  525. | `checklist:open`, `checklist:done` | At least one unchecked item; or items present and all checked |
  526. | `pinned`, `locked`, `shared`, `quicknote` (or `is:pinned` …) | Note flags; `shared` includes notes in a shared folder, and `quicknote` is a note created as a Quick Note (the same flag `list-special-notes kind=quick-notes` reads) |
  527. | `words:>250` | Word count, with `=`, `>`, `>=`, `<`, `<=` |
  528. | `created:>=2026-07-01`, `modified:<2026-09-01` | Dates as `YYYY-MM-DD` in local time, with the same operators; `=` means that whole day |
  529. | `a b`, `a AND b`, `a OR b`, `NOT a`, `-a`, `( … )` | AND is implicit and binds tighter than OR |
  530. Operators are case-insensitive. Quote an operator or flag word to search it
  531. literally, for example `"and"` or `"pinned"`. Queries are capped at 256 tokens
  532. and 64 levels of nesting. An unknown field such as `titel:x` is an error rather
  533. than a silent text search; quote it to search the literal text.
  534. Password-protected notes match on title and metadata only. Their bodies are
  535. encrypted, so a body predicate is unknown for them rather than false: neither
  536. `body:x` nor `-body:x` matches them, though `-body:x OR pinned` matches a
  537. pinned one. Notes whose body cannot be decoded are treated the same way. Their
  538. snippets are always empty.
  539. **Example - Open to-dos in a folder:**
  540. ```json
  541. {
  542. "query": "folder:\"Work Projects\" has:checklist -checklist:done"
  543. }
  544. ```
  545. **Example - Invoices or finance-tagged notes since July, scanning more history:**
  546. ```json
  547. {
  548. "query": "(title:invoice OR tag:finance) modified:>=2026-07-01",
  549. "scanLimit": 2000,
  550. "limit": 20
  551. }
  552. ```
  553. **Returns:** Matching notes, most recently modified first, each with `id`,
  554. `title`, `folder`, `account`, `modified`, `created`, and a `snippet` centred on
  555. the first matched phrase. Each note also has `matchedIn` when the query has a
  556. positive text term: `["title"]`, `["body"]`, or both, saying where those terms
  557. occur (a `title:` term is only looked for in the title, a `body:` term only in
  558. the body). It is absent for locked or undecodable notes, and an empty list
  559. means the note matched through a non-text branch such as `pinned OR x`. The ids are the same `x-coredata://…/ICNote/p…` form
  560. every other tool accepts. `structuredContent` also reports `matched` (total
  561. matches), `scanned`, `eligible`, `scanTruncated`, `truncated`, and `unreadable`
  562. (bodies that could not be decoded). A malformed query returns an error naming
  563. the problem and its position.
  564. ---
  565. #### `get-note-content`
  566. Retrieves the full content of a specific note.
  567. | Parameter | Type | Required | Description |
  568. |-----------|------|----------|-------------|
  569. | `id` | string | No | Note ID (preferred - more reliable than title) |
  570. | `title` | string | No | Note title (use `id` instead when available) |
  571. | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
  572. | `timeoutSeconds` | number | No | Whole seconds, 1–120, for the body read; overrides `APPLE_NOTES_MCP_TIMEOUT_MS` for this call only |
  573. **Note:** Either `id` or `title` must be provided. Using `id` is recommended as it's unique and avoids issues with duplicate titles.
  574. **Busy Notes.app:** with an `id` and Full Disk Access, the note's existence and password flag are read from the NoteStore database (as `get-note-structure` does), so only the body read goes through Notes.app. A timeout is always reported as `timeout_indeterminate`, never as `not_found`, even when an automatic retry then fails differently; and when Notes.app cannot resolve an id the database still holds, the error is `notes_unavailable`. Retry in a moment, or use `get-note-structure` for a read that does not need Notes.app.
  575. **Large images:** Notes.app returns images inside the body as base64, so a note holding a very large image (tens of MB) can take longer to read than the timeout allows. When the read times out or overflows the output buffer, the error says so and, with Full Disk Access, names the attachments of 5 MB or more. Retry with a larger `timeoutSeconds`; `delete-note` accepts the same argument, and it needs a successful read to verify the note before deleting it.
  576. **Example - Using ID (recommended):**
  577. ```json
  578. {
  579. "id": "x-coredata://ABC123/ICNote/p456"
  580. }
  581. ```
  582. **Example - Using title:**
  583. ```json
  584. {
  585. "title": "Shopping List"
  586. }
  587. ```
  588. **Returns:** The HTML content of the note, its exact `id`, and a
  589. `contentHash`. Pass that hash back as `expectedContentHash` for a later update,
  590. append, or delete; the write is rejected if the note's body or rich metadata
  591. changed after this read. With Full Disk Access, embedded URLs omitted by
  592. AppleScript are restored and returned in `links`. The response also reports
  593. actual `nativeTags`, `richContentComplete`, and `writable`. Textual `hashtags`
  594. remain a separate field and are not proof that Notes registered native tags.
  595. `writable` is also false when the note uses formatting that AppleScript's HTML
  596. does not carry (superscript, subscript, non-left paragraph alignment, or
  597. highlight): a full-body `update-note` would silently drop it, so it is refused
  598. and the `warning` names the formatting. `append-to-note` with `scopeText` still
  599. works through the native path, which verifies existing formatting.
  600. **⚠️ The returned body can be lossy — do not write it back verbatim.** Inline
  601. base64 images larger than `APPLE_NOTES_MCP_MAX_INLINE_IMAGE_BYTES` (default
  602. 256 KB) are replaced with `[inline image omitted: …]` text placeholders so an
  603. image-heavy note cannot blow the MCP message limit. `structuredContent` reports
  604. this as `strippedImages` (count) and `truncated` (boolean). When either is set,
  605. passing this body to an unguarded full-body writer would replace the real images
  606. with placeholder text. This server's `update-note` refuses attachment-bearing
  607. notes, and `append-to-note` routes them to native end-append with `scopeText`,
  608. which never rewrites the existing body; make any other edit in Notes.app.
  609. ---
  610. #### `get-native-objects`
  611. Reads native object identities and ranges, checklist item IDs and state, actual
  612. native tags, and native table data from one exact note ID. Table output includes
  613. stable row and column identifiers. `tableCellsComplete` is false when Notes
  614. metadata cannot be decoded completely. This tool is read-only and requires Full
  615. Disk Access.
  616. | Parameter | Type | Required | Description |
  617. |-----------|------|----------|-------------|
  618. | `id` | string | Yes | Exact note ID, in any [identifier form](#identifier-forms) |
  619. ---
  620. #### `get-note-tables`
  621. Reads a page of native tables in one exact note, in body order, from the NoteStore
  622. database. Each table is returned as GitHub-flavored Markdown and as JSON `rows`
  623. with stable `rowIds` and `columnIds`. Notes tables have no header row, so the
  624. Markdown uses the first row as the header. Pipes are escaped as `\|`,
  625. backslashes are doubled, and line breaks inside a cell become `<br>`.
  626. | Parameter | Type | Required | Description |
  627. |-----------|------|----------|-------------|
  628. | `id` | string | Yes | Exact note ID (`x-coredata://…/ICNote/pNNN`) |
  629. | `offset` | integer | No | Zero-based position of the first table (default 0); use `page.nextOffset` |
  630. | `limit` | integer | No | Maximum tables per page (default and maximum 500) |
  631. | `maxBytes` | integer | No | Full serialized response budget in UTF-8 bytes (default 4 MiB, minimum 1024 bytes, maximum 8 MiB) |
  632. The byte budget includes both the text response and structured data, including
  633. repeated Markdown and JSON escaping. Tables are returned whole. `tableCount`
  634. and `page.totalAvailable` count all tables in the note; `page.returned` counts
  635. the entries in this response. While `page.hasMore` is true, call again with
  636. `offset: page.nextOffset` and the same `limit` and `maxBytes`. Each call reads
  637. the note again, so finish paging before editing it.
  638. If one table exceeds an otherwise empty page, its entry contains identifying
  639. metadata, `complete: false`, `contentOmitted: true`, and a `reason`, without
  640. partial rows or row/column IDs. The next offset advances past that entry. To
  641. retrieve its content, retry that offset with a larger `maxBytes`, or export the
  642. note to a file. If even the metadata exceeds the budget, the tool returns a
  643. validation error. `page.stoppedAtSizeLimit` reports a byte-budget stop.
  644. `tableCellsComplete` is false when any table or cell could not be decoded, or
  645. when the current page omits a table's content for its byte budget. A
  646. cell holding an embedded object is `null` in `rows`, listed in
  647. `incompleteCells`, and shown as `[undecoded cell]` in Markdown. A table whose
  648. data cannot be decoded at all has `complete: false`, a `reason`, and no rows.
  649. Cell text is never guessed. Links and styling inside cells are not rendered.
  650. A note without tables returns an empty `tables` list. This tool is read-only,
  651. requires Full Disk Access, and refuses password-protected notes.
  652. ---
  653. #### `get-note-blocks`
  654. Decodes one note's body into typed blocks, read-only, from the NoteStore
  655. database. Each block is one paragraph with its `style` (`title`, `heading`,
  656. `subheading`, `body`, `monospaced`, `bulleted`, `dashed`, `numbered`,
  657. `checklist`, or `unknown` with the raw `styleType`), `indent`, `alignment`,
  658. `blockQuote`, checklist `id`/`done`, and `paragraphUuid` when stored. Each
  659. block lists its inline `runs` with `bold`, `italic`, `underline`,
  660. `strikethrough`, `superscript`, `subscript`, `color`, `highlight`, `link`
  661. (plus `linkSafe`), `font`, and `attachment`, and its attachment markers in body
  662. order. Offsets and lengths count UTF-16 code units. `summary` counts styles and
  663. inline attributes for the whole note. `undecodedFields` lists stored field
  664. numbers the decoder deliberately does not interpret.
  665. **Requires:** Full Disk Access. Password-protected notes are refused.
  666. | Parameter | Type | Required | Description |
  667. |-----------|------|----------|-------------|
  668. | `id` | string | Yes | Exact note ID |
  669. | `offset` | number | No | First block to return (default 0). Use `page.nextOffset` |
  670. | `limit` | number | No | Maximum blocks per page (default 500, max 5000) |
  671. A page also stops early to stay under `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES`
  672. (default 4 MB). `paragraphUuid` is not unique: Notes copies it when a paragraph
  673. is split. Link URLs are returned as stored, and `linkSafe` is false for schemes
  674. other than http(s), `notes:`, `applenotes:` and `mailto:`. Errors carry a
  675. stable code in brackets, such as `[encrypted]` or `[no-full-disk-access]`.
  676. ---
  677. #### `list-note-paragraphs`
  678. Lists one note's non-empty paragraphs in body order, read from the NoteStore
  679. database. It never changes Notes. With `recordAnchors` it also writes the
  680. local anchor registry, so the tool is not marked read-only in its MCP
  681. annotations. Each paragraph has `blockIndex` (its index in
  682. `get-note-blocks`, where empty paragraphs also count), `text`, `style`,
  683. `styleType`, `paragraphId` (the UUID Notes stores on the paragraph's first
  684. text run), and `paragraphIdStatus`:
  685. - `unique`: no other paragraph in the note carries this ID. The paragraph also
  686. gets `url`, a direct
  687. `applenotes://showNote?identifier=<note>&paragraphID=<paragraph>` link that
  688. opens Notes at that paragraph.
  689. - `shared`: other paragraphs carry the same ID (`sharedWith` counts them).
  690. Notes copies the ID when a paragraph is split, so this is common for body
  691. text. No `url` is given, because it could open the wrong paragraph.
  692. - `missing`: no ID is stored.
  693. `mixedParagraphIds: true` marks a paragraph whose text runs carry more than
  694. one ID; only the first-run ID is used. Titles and headings usually have unique
  695. IDs.
  696. **Requires:** Full Disk Access. Password-protected notes are refused.
  697. | Parameter | Type | Required | Description |
  698. |-----------|------|----------|-------------|
  699. | `id` | string | One of `id`, `title` | Exact note ID, or the note's Notes UUID |
  700. | `title` | string | One of `id`, `title` | Exact note title; must match one note. Notes in Recently Deleted are ignored, as in `list-notes` |
  701. | `folder` | string | No | With `title`: the folder's name or full path as `list-folders` shows it, such as `Work/Clients` |
  702. | `linkableOnly` | boolean | No | Return only paragraphs with a `url` |
  703. | `offset` | number | No | First paragraph to return (default 0). Use `page.nextOffset` |
  704. | `limit` | number | No | Maximum paragraphs per page (default 500, max 5000) |
  705. | `recordAnchors` | boolean | No | Also record a [paragraph anchor](#paragraph-anchors) for each returned paragraph (at most 500 per call); each row gains `anchorId` and the result gains `anchorsRecorded` (the new ones). Writes only the local anchor registry |
  706. ---
  707. #### `get-paragraph-link`
  708. Returns a direct link to one paragraph of a note:
  709. `applenotes://showNote?identifier=<note>&paragraphID=<paragraph>`. It selects
  710. the note like `list-note-paragraphs` and the paragraph by exactly one of:
  711. - `contains`: a snippet of the paragraph. Case, runs of spaces, and Unicode
  712. width are ignored.
  713. - `match`: the whole paragraph, compared the same way.
  714. - `blockIndex`: from `list-note-paragraphs`.
  715. When `contains` or `match` hits several paragraphs, pass `occurrence` (1-based)
  716. or a longer snippet.
  717. The link is returned only when the paragraph's ID is `unique` in the note.
  718. Otherwise the result is an error whose `structuredContent` carries the usual
  719. `code` plus a `reason`: `paragraph-id-shared`, `paragraph-id-missing`,
  720. `no-match`, `ambiguous-paragraph`, `occurrence-out-of-range`, `ambiguous-note`
  721. (several notes have that title; the message lists their folders), `not-found`,
  722. `encrypted`, or `no-body`. The tool never creates or changes a paragraph ID,
  723. and an edit in Notes can later replace the ID and break the link. With
  724. `recordAnchor` it also writes the local anchor registry, so the tool is not
  725. marked read-only in its MCP annotations.
  726. **Requires:** Full Disk Access.
  727. | Parameter | Type | Required | Description |
  728. |-----------|------|----------|-------------|
  729. | `id`, `title`, `folder` | string | One of `id`, `title` | Note selector, as in `list-note-paragraphs` |
  730. | `contains` | string | One of `contains`, `match`, `blockIndex` | Snippet of the paragraph |
  731. | `match` | string | One of `contains`, `match`, `blockIndex` | The whole paragraph |
  732. | `blockIndex` | number | One of `contains`, `match`, `blockIndex` | The paragraph's `blockIndex` |
  733. | `occurrence` | number | No | Which match to use when several paragraphs match |
  734. | `recordAnchor` | boolean | No | Also record a [paragraph anchor](#paragraph-anchors) for the linked paragraph and return its `anchorId`. Writes only the local anchor registry |
  735. ---
  736. #### Paragraph anchors
  737. A paragraph link breaks when Notes replaces or copies the paragraph's ID. A
  738. paragraph anchor records enough about the paragraph to find it again: the
  739. note's Notes UUID, the paragraph ID and its status, the paragraph's normalized
  740. text and a fingerprint of it, the fingerprints of the paragraphs before and
  741. after it, its `blockIndex`, and when it was recorded. Anchors are kept in one
  742. local file, `~/Library/Application Support/apple-notes-mcp/paragraph-anchors.json`
  743. (or the absolute path in `APPLE_NOTES_MCP_ANCHOR_FILE`). It is created with
  744. mode 0600 in a 0700 directory, replaced atomically under a lock file, and
  745. holds the text of every anchored paragraph. A symlinked, unreadable or
  746. corrupt registry is refused and left as it is. The anchor tools never change
  747. Notes.
  748. Resolving an anchor tries three steps in order, and every step fails closed:
  749. 1. **Paragraph ID.** A paragraph whose ID is still unique in the note is the
  750. anchored paragraph, even if its text was edited or it moved. A link to that
  751. ID opens exactly that paragraph.
  752. 2. **Exact text.** The same normalized text. When several paragraphs have it,
  753. only the one whose neighbours still match is chosen; a tie is `ambiguous`.
  754. 3. **Text and neighbours.** Similar text between both recorded neighbours, or
  755. nearly identical text beside one of them. Two close candidates are
  756. `ambiguous`; one below `minConfidence` is `low-confidence`.
  757. A match whose ID is now shared or missing is `needs-reminting`: the paragraph
  758. is found (the result names its block), but no safe link exists until it gets a
  759. new ID. Public automation cannot set a paragraph ID, so this server only
  760. reports it and returns no `url`.
  761. To share anchored links outside Notes, see the
  762. [paragraph anchor resolver](#paragraph-anchor-resolver-opt-in).
  763. #### `create-paragraph-anchor`
  764. Records an anchor for one paragraph, selected exactly as in
  765. `get-paragraph-link` (note by `id` or `title`/`folder`; paragraph by one of
  766. `contains`, `match`, `blockIndex`, plus `occurrence`). Unlike
  767. `get-paragraph-link`, a paragraph whose ID is shared or missing can be
  768. anchored. Recording the same paragraph again (same note, ID, text and block)
  769. returns the existing anchor with `created: false`.
  770. Returns `anchor`, `created`, and `url` when the paragraph currently has a
  771. unique ID.
  772. **Requires:** Full Disk Access. Writes only the anchor registry.
  773. | Parameter | Type | Required | Description |
  774. |-----------|------|----------|-------------|
  775. | `id`, `title`, `folder` | string | One of `id`, `title` | Note selector, as in `list-note-paragraphs` |
  776. | `contains`, `match`, `blockIndex`, `occurrence` | | One of `contains`, `match`, `blockIndex` | Paragraph selector, as in `get-paragraph-link` |
  777. #### `resolve-paragraph-anchor`
  778. Finds an anchored paragraph in the note as it is now. The result has `status`
  779. (`resolved`, `needs-reminting`, `ambiguous`, `low-confidence`, `not-found`,
  780. `note-not-found`, `note-deleted` for a note in Recently Deleted, or
  781. `note-unreadable` for a locked note), `method` (`paragraph-id`, `exact-text`,
  782. `text-and-neighbours`), `confidence` (0 to 1), `match` (`blockIndex`, `text`,
  783. `paragraphId`, `paragraphIdStatus`), `changes` (`textChanged`,
  784. `blockIndexChanged`, `paragraphIdChanged`), and `message`. `url`, the current
  785. `applenotes://` link, is present only when `status` is `resolved`.
  786. **Requires:** Full Disk Access.
  787. | Parameter | Type | Required | Description |
  788. |-----------|------|----------|-------------|
  789. | `anchorId` | string | Yes | The anchor (`pa_` and 24 hex digits) |
  790. | `minConfidence` | number | No | Lowest confidence accepted as a match (default 0.6) |
  791. | `refresh` | boolean | No | After a match with confidence 0.8 or more, store the paragraph as it is now (text, neighbours, block, ID), so later edits are tracked from here. Reports `refreshed` or `refreshSkipped` |
  792. #### `list-paragraph-anchors`
  793. Lists recorded anchors in the order recorded, with `total`, the `registry`
  794. path and `page` info. Reads only the registry.
  795. | Parameter | Type | Required | Description |
  796. |-----------|------|----------|-------------|
  797. | `noteIdentifier` | string | No | Only anchors in the note with this Notes UUID |
  798. | `offset` | number | No | First anchor to return (default 0) |
  799. | `limit` | number | No | Maximum anchors (default 100, max 1000) |
  800. #### `get-paragraph-anchor`
  801. Returns one stored anchor as recorded. Reads only the registry.
  802. | Parameter | Type | Required | Description |
  803. |-----------|------|----------|-------------|
  804. | `anchorId` | string | Yes | The anchor |
  805. #### `prune-paragraph-anchors`
  806. Removes anchors that no longer resolve, or the anchors you list. It is a dry
  807. run unless `dryRun` is `false`. Without `anchorIds` it resolves every anchor
  808. in scope and treats `not-found` and `note-not-found` as stale. A note in
  809. Recently Deleted (`note-deleted`) is kept by default because it can be
  810. restored. Returns `stale` (`anchorId`, `status`, `message`), `examined`, and
  811. `removed`.
  812. **Requires:** Full Disk Access unless `anchorIds` is given.
  813. | Parameter | Type | Required | Description |
  814. |-----------|------|----------|-------------|
  815. | `anchorIds` | string[] | No | Remove exactly these anchors instead of resolving |
  816. | `noteIdentifier` | string | No | Only anchors in the note with this Notes UUID |
  817. | `statuses` | string[] | No | Statuses treated as stale (default `not-found`, `note-not-found`) |
  818. | `dryRun` | boolean | No | Report without removing (default `true`) |
  819. ---
  820. #### `get-note-structure`
  821. Returns a read-only overview of one note from the NoteStore database, in one
  822. call:
  823. - `text` (decoded body), `textLength`, `wordCount`, `charCount` (Unicode
  824. characters, attachment placeholders excluded), and `blockSummary` (the
  825. `get-note-blocks` summary counts).
  826. - `links`, each with a `kind`: `inline` (a hyperlink on text), `card` (a rich
  827. link preview attachment, with `attachmentId` and `previewPath`), `note` (a
  828. native link chip to another note), or `section` (a native link chip to a
  829. heading or paragraph, with `section`). Notes deep links also carry
  830. `targetNote` and `paragraphId`. `linkCounts` totals them.
  831. - `tags` (native tags in body order) and `attachments`, listed the way
  832. [`list-attachments`](#list-attachments) with `includePaths` lists them: the
  833. same `kind` (`image`, `scan`, `drawing`, `pdf`, `audio`, `video`, `url`,
  834. `table`, `other`), the same body order, and the same `previewPath`, plus the
  835. card `title`/`url`, `fileSize`, and body position. Gallery items and
  836. recording parts are nested under `children`; `attachmentCount` counts
  837. top-level attachments only.
  838. - `deepLink`, `isShared` (the note or any enclosing folder is shared),
  839. `isLocked`, `isPinned`, `inRecentlyDeleted`, `lastViewed`,
  840. `checklistTotal`, `checklistDone`, `hasDrawing` (classic sketches and Paper
  841. drawings), and `firstImage` (the same lead visual `list-attachments`
  842. returns with `firstImage`, plus its attachment `id`).
  843. `lastViewed` is an ISO date, or null with `lastViewedStatus` set to
  844. `never-viewed`, `not-recorded`, `malformed`, or `unsupported` (the column
  845. does not exist on this macOS version). A password-protected note returns its
  846. metadata and attachment rows with `bodyDecoded: false` and the body-derived
  847. fields null.
  848. **Requires:** Full Disk Access.
  849. | Parameter | Type | Required | Description |
  850. |-----------|------|----------|-------------|
  851. | `id` | string | Yes | Exact note ID: the `x-coredata://` id, or the note's Notes UUID or numeric key (see [Identifier forms](#identifier-forms)) |
  852. | `includeText` | boolean | No | Include the decoded text (default true). Text larger than `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES` is omitted with `textOmitted: true` |
  853. Link URLs are returned as stored; check `linkSafe` before emitting one into
  854. HTML.
  855. ---
  856. #### `list-note-links`
  857. Lists links, read-only from the NoteStore database, in one note (`id`) or
  858. across a `folder`, an `account`, or the whole library (no selector). Each link
  859. has a `kind`:
  860. | Kind | What it is | Where Notes stores it |
  861. |------|------------|-----------------------|
  862. | `inline` | A hyperlink on text | Inside the note body |
  863. | `card` | A rich link preview | An attachment row with the URL and title |
  864. | `note` | A native link chip to another note | An inline-attachment row with a Notes deep link |
  865. | `section` | A native link chip to a heading or paragraph | Same, with `paragraphID` in the deep link |
  866. Each row has `url`, `text` (label), `linkSafe`, `targetNote` and `paragraphId`
  867. for Notes deep links, `section` for section chips, and for cards
  868. `attachmentId` and `previewPath` (Notes' largest cached preview image, found
  869. the same way [`list-attachments`](#list-attachments) finds it, or null when
  870. Notes has none). Each row also names its source: `noteId`, `noteIdentifier`,
  871. `noteTitle`, `noteModified`, `folder`, `folderPath` (as `list-folders` prints
  872. it), `account`, and `accountIdentifier`. When bodies were decoded, `start` and
  873. `blockIndex` give the link's position, and `inBody: false` marks a card or chip
  874. row with no marker left in the body.
  875. Inline links need every body in scope decompressed and decoded, so a folder,
  876. account, or library scan includes them only with `includeInline: true`
  877. (slower). A single note always includes them. A `folder` scope includes its
  878. subfolders unless `includeSubfolders` is false. Scans skip Recently Deleted
  879. and folderless notes; a note requested by `id` is read wherever it is. Links
  880. come newest-modified note first, in body order within a note.
  881. **Requires:** Full Disk Access.
  882. | Parameter | Type | Required | Description |
  883. |-----------|------|----------|-------------|
  884. | `id` | string | No | One exact note ID (x-coredata id, Notes UUID, or numeric key). Do not combine with `account` or `folder` |
  885. | `account` | string | No | Account name (exact or unique-prefix match, as in the other tools) |
  886. | `folder` | string | No | Folder name (any depth, must be unique) or path from the top level as `list-folders` prints it, such as `Work/Clients`; escape a literal slash as `\/` |
  887. | `includeSubfolders` | boolean | No | With `folder`, also list notes in its subfolders (default true) |
  888. | `includeInline` | boolean | No | Decode bodies for inline links (default true for `id`, false otherwise) |
  889. | `kinds` | string[] | No | Only these kinds: `inline`, `card`, `note`, `section` |
  890. | `offset` | number | No | First link to return (default 0). Use `page.nextOffset` |
  891. | `limit` | number | No | Maximum links per page (default 200, max 2000) |
  892. The response also reports `scope`, `counts` per kind, `notesInScope`,
  893. `notesWithoutBody` (locked, empty or undecodable bodies when inline links were
  894. requested), and `page`. A page stops early to stay under
  895. `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES`. An ambiguous folder name is refused with a
  896. message that lists the matching paths.
  897. ---
  898. #### `list-native-tags`
  899. Lists actual native Notes tags. This differs from textual hashtag search. It is
  900. read-only and requires Full Disk Access.
  901. - **Folder mode** (pass `folder`, optionally `account`): maps each tag used in that
  902. folder to its matching note IDs. The response reports `complete: false` and per-note
  903. errors when some native metadata is unavailable.
  904. - **Inventory mode** (omit `folder`): an account-wide inventory with counts, read-only from the
  905. database. `account` narrows it to one account; omit it to count every
  906. account. Each `inventory` entry has `tag`, `noteCount` (distinct notes, Recently
  907. Deleted excluded), per-account counts in `accounts`, and any other `spellings` Notes
  908. treats as the same tag. Tags with no remaining notes are listed with `noteCount: 0`.
  909. A tag counts for a note only while the note body still references it. Locked or
  910. unreadable bodies are counted from the tag objects alone and reported through
  911. `unverifiedNotes` and `complete: false`.
  912. | Parameter | Type | Required | Description |
  913. |-----------|------|----------|-------------|
  914. | `folder` | string | No | Folder to list (nested paths supported). Omit for the inventory |
  915. | `account` | string | No | Account name, exact or unique prefix |
  916. ---
  917. #### `native-tags-status`
  918. Checks whether exactly one configured Native Tags Shortcut is installed. An
  919. installed workflow may still need macOS permission on its first execution, and
  920. installation does not show whether that consent was given: run it once in the
  921. foreground in Shortcuts.app and choose **Always Allow** after install or upgrade
  922. (see [Troubleshooting](#native-writes-time-out-or-report-an-uncertain-outcome)).
  923. ---
  924. #### `add-native-tags`
  925. Adds actual native Notes tag objects to one exact note using `id`, a fresh
  926. `expectedContentHash`, a distinctive existing `scopeText`, and `tags`. The
  927. operation verifies the note's original text, links, and native objects after the
  928. Shortcut runs. It refuses ambiguous title-and-scope matches and never retries an
  929. uncertain write. Install the signed workflow as described in
  930. [`shortcuts/README.md`](shortcuts/README.md).
  931. | Parameter | Type | Required | Description |
  932. |-----------|------|----------|-------------|
  933. | `id` | string | Yes | Exact note ID, in any [identifier form](#identifier-forms) |
  934. | `expectedContentHash` | string | Yes | `contentHash` from a fresh read of the note |
  935. | `scopeText` | string | Yes | Distinctive phrase already in the note, 12–500 characters |
  936. | `tags` | string[] | Yes | 1–100 tag names to add |
  937. ---
  938. #### `get-note-plaintext`
  939. Retrieves a note's body as plain text, with no HTML markup.
  940. | Parameter | Type | Required | Description |
  941. |-----------|------|----------|-------------|
  942. | `id` | string | No | Note ID (preferred - more reliable than title) |
  943. | `title` | string | No | Note title (use `id` instead when available) |
  944. | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
  945. **Note:** Either `id` or `title` must be provided. This reads the note's native `plaintext` property, so it skips the HTML-to-text conversion that `get-note-content` plus a Markdown pass would do. Use `get-note-content` when you need the HTML, or `get-note-markdown` when you want Markdown with checklist state.
  946. **Returns:** The plain-text content of the note in `structuredContent.plaintext`, or error if not found.
  947. ---
  948. #### `get-note-details`
  949. Retrieves metadata about a note (without full content).
  950. | Parameter | Type | Required | Description |
  951. |-----------|------|----------|-------------|
  952. | `title` | string | Yes | Exact title of the note |
  953. | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match) |
  954. **Example:**
  955. ```json
  956. {
  957. "title": "Project Plan"
  958. }
  959. ```
  960. **Returns:** JSON with note metadata:
  961. ```json
  962. {
  963. "id": "x-coredata://...",
  964. "title": "Project Plan",
  965. "created": "2025-01-15T10:30:00.000Z",
  966. "modified": "2025-01-20T14:22:00.000Z",
  967. "shared": false,
  968. "passwordProtected": false,
  969. "account": "iCloud"
  970. }
  971. ```
  972. ---
  973. #### `get-note-by-id`
  974. Retrieves a note using its unique CoreData identifier.
  975. | Parameter | Type | Required | Description |
  976. |-----------|------|----------|-------------|
  977. | `id` | string | Yes | The CoreData URL identifier (e.g., `x-coredata://...`), or the note's Notes UUID or numeric key (see [Identifier forms](#identifier-forms)) |
  978. **Returns:** JSON with note metadata, plus `identifier`, `folderIdentifier`, and `accountIdentifier` when Full Disk Access is granted, or error if not found.
  979. ---
  980. #### `show-note`
  981. Reveals a note in Notes.app using its unique CoreData identifier.
  982. | Parameter | Type | Required | Description |
  983. |-----------|------|----------|-------------|
  984. | `id` | string | Yes | The CoreData URL identifier (e.g., `x-coredata://...`), or the note's Notes UUID or numeric key |
  985. | `separately` | boolean | No | Open in a separate note window when supported by Notes.app |
  986. **Returns:** Confirmation that Notes.app accepted the show command.
  987. ---
  988. #### `update-note`
  989. Updates an existing note's content and/or title.
  990. | Parameter | Type | Required | Description |
  991. |-----------|------|----------|-------------|
  992. | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
  993. | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being replaced |
  994. | `newTitle` | string | No | New title (if changing the title; ignored when `format` is `"html"`) |
  995. | `newContent` | string | Yes | New content for the note body |
  996. | `format` | string | No | Content format: `"plaintext"` (default) or `"html"`. When `"html"`, content replaces the entire note body as raw HTML and `newTitle` is ignored (the first HTML element serves as the title) |
  997. | `allowLinkChanges` | boolean | No | Set to `true` only when intentionally changing or removing existing links |
  998. | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
  999. | `timeoutSeconds` | number | No | Per-call timeout, 1–120 seconds, as for [`create-note`](#create-note). A timed-out write is uncertain: read the note by id before any retry |
  1000. Title-only updates are rejected because Apple Notes titles are not unique.
  1001. **Example - Using ID (recommended):**
  1002. ```json
  1003. {
  1004. "id": "x-coredata://ABC123/ICNote/p456",
  1005. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1006. "newContent": "Updated content here"
  1007. }
  1008. ```
  1009. **Example - Update with HTML formatting:**
  1010. ```json
  1011. {
  1012. "id": "x-coredata://ABC123/ICNote/p456",
  1013. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1014. "newContent": "<p>New findings with <b>bold</b> emphasis.</p><pre><code>console.log('hello');</code></pre>",
  1015. "format": "html"
  1016. }
  1017. ```
  1018. **Returns:** Confirmation with the exact ID, post-save `contentHash`, and
  1019. `verifiedVisibleText: true`, or an error if the note changed before saving.
  1020. Apple Notes normalizes HTML, so this proves the visible text after saving, not
  1021. byte-identical rich formatting.
  1022. **Note:** `newContent` **replaces the entire note body** — it is not appended. To add to a note, prefer [`append-to-note`](#append-to-note), which does the read-and-concatenate for you and always round-trips the body as HTML. If you do read-modify-write by hand, note that `get-note-content` replaces oversized inline images with text placeholders (see [`get-note-content`](#get-note-content)) — writing that body back bakes the placeholders in.
  1023. **Rich-content safety:** `update-note` refuses to replace a note when its rich
  1024. metadata is unavailable or it contains attachments, native tags, inline
  1025. objects, or checklists that AppleScript cannot preserve. Existing link
  1026. destinations must remain present unless `allowLinkChanges` is explicitly set.
  1027. ---
  1028. #### `delete-note`
  1029. Deletes a note (moves to Recently Deleted in Notes.app).
  1030. | Parameter | Type | Required | Description |
  1031. |-----------|------|----------|-------------|
  1032. | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
  1033. | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being deleted |
  1034. | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
  1035. | `timeoutSeconds` | number | No | Per-call timeout, 1–120 seconds, as for [`create-note`](#create-note). A timed-out write is uncertain: read the note by id before any retry |
  1036. | `guardNoteId` | string | No | A second note (usually a verified copy) that must still be intact; needs Full Disk Access |
  1037. | `expectedGuardContentHash` | string | With `guardNoteId` | `contentHash` of the guard note from `get-note-content` |
  1038. | `requireActiveNoteId` | string | No | A second note that must still exist, be unlocked, stay outside Recently Deleted, and not be a Quick Note; its content is not fingerprinted. Needs Full Disk Access |
  1039. Title-only deletion is rejected. If the note changed after the supplied hash
  1040. was read, deletion is also rejected.
  1041. **Notes with large images.** Notes.app returns a note's body with each inline
  1042. image embedded as base64, so a note holding one 40 MB image has a body of about
  1043. 110 MB. Body reads accept up to 512 MB of output, and `delete-note` compares a
  1044. body longer than 5 MB against a private temporary file rather than embedding it
  1045. in the AppleScript. The comparison still covers the whole body, and the file
  1046. is removed when the delete finishes.
  1047. **Copy-then-retire.** To delete an original only while its copy is still good,
  1048. read both notes, verify the copy, and pass the copy as `guardNoteId` with its
  1049. `contentHash` as `expectedGuardContentHash`. The copy's revision is re-read just
  1050. before the delete, and its body, lock state, and folder are checked again
  1051. inside the delete AppleScript, with the same fail-closed Recently Deleted test
  1052. as the note being deleted. The guard note must not be a Quick Note, a flag only
  1053. the database holds, so the guard needs Full Disk Access. A copy the database
  1054. has not saved yet passes on the live checks alone. The pair is still not one
  1055. transaction: the rich revision (which also covers checklists and attachments)
  1056. is a pre-check, and the in-script check covers the body and state Notes.app
  1057. exposes. `requireActiveNoteId` is the narrower form for a destination you
  1058. wrote yourself rather than copied.
  1059. **Example - Using ID (recommended):**
  1060. ```json
  1061. {
  1062. "id": "x-coredata://ABC123/ICNote/p456",
  1063. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
  1064. }
  1065. ```
  1066. **Returns:** Confirmation message, or error if note not found. The delete and a
  1067. check of the note's original folder run in one AppleScript: if Notes.app accepts
  1068. the delete but the note is still listed in that folder, the call reports that
  1069. nothing was deleted instead of claiming success.
  1070. A note that is already in Recently Deleted is refused, because deleting it there
  1071. removes it permanently. The folder is read live from Notes.app in the same
  1072. AppleScript; the Recently Deleted folder is recognised by its database id (with
  1073. Full Disk Access) or by its English name. The check fails closed: a note whose
  1074. folder Notes.app reports as something other than a folder (as it does for a note
  1075. trashed earlier in the same Notes session) is refused the same way, and a note
  1076. whose folder cannot be read at all is refused with a message to retry. To remove
  1077. such a note for good, do it in Notes.app.
  1078. **⚠️ Safety:** Irreversible from the agent's side — requires explicit user confirmation before calling. Prefer `search-notes` / `list-notes` first to confirm the exact id(s) being deleted.
  1079. ---
  1080. #### `move-note`
  1081. Moves a note to a different folder. The note is relocated in place via Notes.app's native `move`, so its id, creation date, and all embedded attachments (files, images, scans, PDFs, audio) are preserved. The destination folder must already exist — create it first with [`create-folder`](#create-folder).
  1082. A smart folder is never a destination: it only gathers notes by its rules, and Notes.app would move the note to Recently Deleted or store a created note where no folder shows it. `create-note`, `create-note-with-attachment`, `move-note`, `batch-move-notes`, and `create-folder` refuse one before writing anything, with `code: "unsupported"`, `committed: false`, and `reason: "smart_folder_destination"`. An ordinary folder that shares a smart folder's name is still found. Detection reads the NoteStore database, so it needs Full Disk Access; without it, destinations resolve as before.
  1083. | Parameter | Type | Required | Description |
  1084. |-----------|------|----------|-------------|
  1085. | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
  1086. | `folder` | string | Yes | Destination folder name or nested path (e.g., `"Work/Clients"`) |
  1087. | `account` | string | No | Account whose `folder` is the destination (default: the default account) |
  1088. | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
  1089. | `timeoutSeconds` | number | No | Per-call timeout, 1–120 seconds, as for [`create-note`](#create-note). A timed-out write is uncertain: read the note by id before any retry |
  1090. Title-only moves are rejected.
  1091. **Example - Using ID (recommended):**
  1092. ```json
  1093. {
  1094. "id": "x-coredata://ABC123/ICNote/p456",
  1095. "folder": "Archive"
  1096. }
  1097. ```
  1098. **Returns:** Confirmation only after the same note ID is read back and its
  1099. actual destination folder ID matches the requested folder.
  1100. ---
  1101. #### Folder scope guards
  1102. `update-note`, `append-to-note`, `delete-note`, `move-note`, and
  1103. `batch-move-notes` accept three optional folder preconditions. Use exact
  1104. folder ids from `list-folders`.
  1105. - `ifFolderId`: the note must currently be in exactly this folder.
  1106. - `ifAncestorFolderId`: the note must be inside this folder or any of its
  1107. subfolders.
  1108. - `forbiddenAncestorFolderIds` (up to 50): the note must not be inside any of
  1109. these folders or their subfolders. For `move-note` and `batch-move-notes`,
  1110. the destination must not be either.
  1111. The checks read Notes.app's live folders inside the same AppleScript as the
  1112. write, immediately before it. If the folder observed by the check fails a
  1113. precondition, the write is refused with `Scope guard failed: …`. The check and
  1114. write are separate Notes operations; another actor can move the note between
  1115. them. A native append to a protected note runs through Shortcuts, so its
  1116. precheck runs in a separate AppleScript before the append.
  1117. For `batch-move-notes`, the same preconditions apply to every supplied note ID.
  1118. Each note is checked independently immediately before its move. A scope mismatch
  1119. leaves that note unchanged and appears in its failure result; the remaining
  1120. items continue. A batch can therefore move some notes and refuse others.
  1121. **Example - retire a note only while it is still in the inbox:**
  1122. ```json
  1123. {
  1124. "id": "x-coredata://ABC123/ICNote/p456",
  1125. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1126. "ifFolderId": "x-coredata://ABC123/ICFolder/p12"
  1127. }
  1128. ```
  1129. ---
  1130. #### `append-to-note`
  1131. Appends or prepends content to an existing note without replacing it. Always reads and writes as HTML, preserving all existing rich formatting.
  1132. | Parameter | Type | Required | Description |
  1133. |-----------|------|----------|-------------|
  1134. | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
  1135. | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being extended |
  1136. | `content` | string | Yes | Text to append to the note body |
  1137. | `position` | string | No | `"after"` (default) appends to the end; `"before"` inserts directly below the note's title line, so the title stays first |
  1138. | `separator` | string | No | String placed between existing content and new content (default: two newlines → `<div><br></div>` in HTML) |
  1139. | `format` | string | No | Format of the content being appended: `"plaintext"` (default) or `"html"` |
  1140. | `scopeText` | string | Native-object notes only | Unique existing phrase, as for [`append-native`](#append-native) |
  1141. | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
  1142. | `timeoutSeconds` | number | No | Per-call timeout, 1–120 seconds, as for [`create-note`](#create-note). A timed-out write is uncertain: read the note by id before any retry |
  1143. Title-only appends are rejected.
  1144. **Example - Append plaintext:**
  1145. ```json
  1146. {
  1147. "id": "x-coredata://ABC123/ICNote/p456",
  1148. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1149. "content": "New item added today"
  1150. }
  1151. ```
  1152. **Example - Prepend HTML:**
  1153. ```json
  1154. {
  1155. "id": "x-coredata://ABC123/ICNote/p456",
  1156. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1157. "content": "<div><b>Status:</b> done</div>",
  1158. "format": "html",
  1159. "position": "before"
  1160. }
  1161. ```
  1162. **Returns:** Confirmation with the exact ID, post-save `contentHash`, and
  1163. `verifiedVisibleText: true`. Apple Notes normalizes HTML, so this proves the
  1164. visible text after saving, not byte-identical rich formatting. Warns when the
  1165. note is shared with collaborators.
  1166. **Safety:** The append is rejected if the note changed since it was read, rich
  1167. metadata is unavailable, or the note contains attachments. Existing link
  1168. destinations are verified after saving.
  1169. **Notes containing native objects** (a table, a checklist, native tags) cannot be
  1170. spliced, so they are routed to the native end-append bridge — see
  1171. [`append-native`](#append-native). That path additionally requires `scopeText`,
  1172. keeps the default blank-line `separator` and `position: "after"`, and accepts a
  1173. fixed HTML subset rather than anything Notes.app can render:
  1174. | | Native append |
  1175. |---|---|
  1176. | Elements | `<a>` `<b>` `<br>` `<code>` `<del>` `<div>` `<em>` `<h1>` `<h2>` `<h3>` `<i>` `<li>` `<ol>` `<p>` `<s>` `<span>` `<strong>` `<tt>` `<u>` `<ul>` |
  1177. | Attributes | `href` on `<a>` (`https:`, `http:`, `notes:`, `applenotes:`, `mailto:` only) and a `font-size` style on `<span>`, e.g. `<span style="font-size: 18px">` — the form Notes itself stores a heading as |
  1178. | Refused | every other element and attribute, by name, naming the accepted subset; a table, in whole or in part (`<table>` `<thead>` `<tbody>` `<tr>` `<td>` `<th>`) — use [`create-table`](#create-table) instead; comments, doctype and processing instructions |
  1179. Ordinary notes take the guarded HTML path and are not restricted to that subset.
  1180. ---
  1181. #### `insert-link`
  1182. Adds one web, mail or Notes link to an exact note as its own paragraph, then
  1183. proves it from the link runs Notes actually stored. Use `mode: "raw"` to show
  1184. the URL itself, or `mode: "hyperlink"` with a `label` to show text that links to
  1185. the URL. For a link to another note by id, use
  1186. [`insert-note-link`](#insert-note-link), which looks up that note's real deep
  1187. link.
  1188. | Parameter | Type | Required | Description |
  1189. |-----------|------|----------|-------------|
  1190. | `id` | string | Yes | Exact CoreData note ID |
  1191. | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being extended |
  1192. | `url` | string | Yes | Absolute `http(s)` URL with a host, or a `mailto:`, `notes://` or `applenotes:` link. No spaces, `<`, `>` or `"` |
  1193. | `mode` | string | No | `"raw"` (default) shows the URL; `"hyperlink"` shows `label` |
  1194. | `label` | string | Hyperlink only | Visible text for `mode: "hyperlink"`; refused in raw mode |
  1195. | `linked` | boolean | No | Raw mode only. `true` (default) stores a real link on the URL text. `false` writes plain text with no stored link |
  1196. | `position` | string | No | `"end"` (default) or `"after-title"` (first paragraph under the title) |
  1197. | `blankLine` | boolean | No | Leave a blank line between existing text and the link paragraph (default `true`) |
  1198. | `scopeText` | string | Native-object notes only | Unique existing phrase, as for [`append-native`](#append-native) |
  1199. **Example - Hyperlink under the title:**
  1200. ```json
  1201. {
  1202. "id": "x-coredata://ABC123/ICNote/p456",
  1203. "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
  1204. "url": "https://example.com/report",
  1205. "mode": "hyperlink",
  1206. "label": "Quarterly report",
  1207. "position": "after-title"
  1208. }
  1209. ```
  1210. **Returns:** `route` (`"applescript"` for ordinary notes, `"native"` for notes
  1211. with native objects), `linkStored`, `storedUrl` (the destination read back from
  1212. the note, for example `https://example.com/` for a bare origin), and the new
  1213. `contentHash`.
  1214. **Safety:** The same guards as [`append-to-note`](#append-to-note): a fresh
  1215. `expectedContentHash`, the attachment block, and every existing link must
  1216. survive. A linked insert must add exactly one stored link with the requested
  1217. label and destination; if the text lands but that proof fails, the error says
  1218. the write happened so it is not repeated.
  1219. **Limits:**
  1220. - Plain URL text is not linked by Notes when written this way. With
  1221. `linked: false`, the note stores no link and readers of the body see ordinary
  1222. text; Notes.app may still underline the URL on screen through its own data
  1223. detection. The result reports `linkStored: false`.
  1224. - Notes with native objects (a table, a checklist, native tags) take the native
  1225. end-append path, so only `position: "end"` with `blankLine: true` works there.
  1226. - The link always gets its own paragraph. Placing it at the end of one existing
  1227. paragraph, or inside the text, is not available.
  1228. - Rich URL preview cards (the link tile Notes makes when you paste a URL) are
  1229. not produced. No public automation route creates one: the Shortcuts Notes
  1230. actions write text, and AppleScript's `body` has no card markup.
  1231. - To start a new note with a link, use [`create-note`](#create-note) with
  1232. `format: "html"` and an `<a href>` in `content`; the link is stored the same
  1233. way.
  1234. ---
  1235. #### `get-note-link`
  1236. Returns the `notes://showNote?identifier=<uuid>` deep-link URL for a note. The URL opens the note in Notes.app on iOS and macOS and can be stored in Reminders tasks or shared links.
  1237. | Parameter | Type | Required | Description |
  1238. |-----------|------|----------|-------------|
  1239. | `id` | string | No | Note ID (preferred - more reliable than title) |
  1240. | `title` | string | No | Note title (use `id` instead when available) |
  1241. | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
  1242. **Note:** Either `id` or `title` must be provided. Using `id` is recommended. Password-protected notes cannot be linked.
  1243. **Example:**
  1244. ```json
  1245. {
  1246. "id": "x-coredata://ABC123/ICNote/p456"
  1247. }
  1248. ```
  1249. **Returns:** `notes://showNote?identifier=<uuid>` URL string, plus the note id and title.
  1250. **Note:** Requires Full Disk Access for the process that runs the server so the Notes SQLite database is readable. On macOS 12–15 the tool also falls back to the AppleScript `note link` property. Run the `doctor` tool to verify access.
  1251. ---
  1252. #### `list-notes`
  1253. Lists all notes, optionally filtered by folder, date, and limit.
  1254. | Parameter | Type | Required | Description |
  1255. |-----------|------|----------|-------------|
  1256. | `account` | string | No | Account to list notes from (defaults to Notes.app's default account; exact or unique-prefix match) |
  1257. | `folder` | string | No | Filter to notes in this folder only (supports nested paths like `"Work/Clients"`) |
  1258. | `modifiedSince` | string | No | ISO 8601 date string to filter notes modified on or after this date (e.g., `"2025-01-01"`) |
  1259. | `limit` | number | No | Maximum number of notes to return |
  1260. | `includeRecentlyDeleted` | boolean | No | Also list notes in Recently Deleted, each flagged `inRecentlyDeleted: true` (default `false`) |
  1261. **Example - All notes:**
  1262. ```json
  1263. {}
  1264. ```
  1265. **Example - Notes in a folder:**
  1266. ```json
  1267. {
  1268. "folder": "Work"
  1269. }
  1270. ```
  1271. **Example - Recent notes with limit:**
  1272. ```json
  1273. {
  1274. "modifiedSince": "2025-06-01",
  1275. "limit": 20
  1276. }
  1277. ```
  1278. **Returns:** List of notes as `{title, id}` pairs — `notes: Array<{title, id}>`, plus `count`. The human-readable line is ` - <title> [id: <id>]`. Notes in Recently Deleted are left out by default and counted in `excludedRecentlyDeleted` (present only when nonzero); with `includeRecentlyDeleted: true` they are listed with `inRecentlyDeleted: true` and a `[RECENTLY DELETED]` marker. Notes.app's own listing includes them, so the Recently Deleted folder is recognised by its database id (with Full Disk Access) or by its English name. With Full Disk Access each entry also carries `identifier`, `folderIdentifier`, and `accountIdentifier` (see [Identifier forms](#identifier-forms)).
  1279. Use the returned `id` for any follow-up read/update/move/delete rather than re-resolving the title: titles are not unique, and a by-title lookup resolves a duplicated title to the same one note every time, silently skipping the others.
  1280. > **Changed in 2.7.0:** `notes` was previously `string[]` (titles only). Callers that treated the array as strings must now read `.title`.
  1281. For date order, incremental sync cursors, Recently Deleted, or word counts, use [`list-recent-notes`](#list-recent-notes).
  1282. ---
  1283. #### `list-recent-notes`
  1284. Lists notes from the NoteStore database (read-only) by stored modification time, with an exact cursor for incremental sync. With `since`, it pages through changes oldest first; without it, it shows the newest notes first. Unlike `list-notes`, it can include Recently Deleted and can count words.
  1285. **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)).
  1286. | Parameter | Type | Required | Description |
  1287. |-----------|------|----------|-------------|
  1288. | `account` | string | No | Only this account (exact or unique-prefix name). Omit for every account |
  1289. | `folder` | string | No | Only notes directly in this folder: a full path in `list-folders` syntax, or a unique folder name |
  1290. | `since` | string | No | Return notes after this point, **oldest first**. A `modifiedCheckpoint` cursor (from a row or `nextSince`), or an ISO 8601 date (local midnight) or date-time (local time unless it carries `Z` or an offset), meaning modified strictly after it |
  1291. | `limit` | number | No | Maximum rows, 1–1000 (default 50) |
  1292. | `includeDeleted` | boolean | No | Also return notes in Recently Deleted, notes awaiting deletion, and folderless notes (default `false`) |
  1293. | `wordCounts` | boolean | No | Decode each body and add `wordCount` and `charCount` (default `false`) |
  1294. | `bodyPreview` | boolean | No | Add `bodyPreview` (up to 180 characters) and `textDecoded` (default `false`) |
  1295. **Returns:** `notes`, each with `id`, `identifier`, `title`, `folder`, `account`, `created`, `modified`, `modifiedCheckpoint`, `pinned`, `locked`, `inRecentlyDeleted`, and `markedForDeletion`. Also `count`, `limit`, `order` (`oldest-first` or `newest-first`), `saturated`, and `nextSince`.
  1296. - **Cursors.** `modifiedCheckpoint` is an opaque token (`cdts1:`, 16 hex digits, `:`, the note's database key). It carries the exact stored timestamp bits, so it never loses precision the way an ISO string can, and the key orders notes that share one timestamp. Pass it back as `since`.
  1297. - **Syncing.** Call with `since`, store `nextSince`, and pass it as the next `since`. `nextSince` is the last returned row's cursor, or the incoming boundary when nothing matched, so every call advances. `saturated` is `true` when `count` equals `limit`: more changes may follow, so call again right away. When it is `false`, you are caught up. Notes that share a timestamp are split across pages by key, so none is skipped or repeated.
  1298. - **First sync.** Start with `since: "1970-01-01"` and page the same way. A library larger than the 1000-row maximum is reached in full.
  1299. - **Browsing.** Without `since`, rows come newest first. `nextSince` is then the newest row's cursor, set only when the call returned every matching note (`saturated` is `false`); otherwise it is `null`.
  1300. - **Late edits.** A modification-date cursor can miss an edit that iCloud delivers later from another device with an older timestamp, for example after that device was offline. The row then sorts before the cursor. Run a full pass from the start now and then to catch these.
  1301. - **Deletions.** Deleted notes are invisible unless `includeDeleted` is `true`. With it, notes in Recently Deleted and notes awaiting deletion appear, flagged, when their modification date is after the cursor. A note purged from the database leaves no row, so compare ids against a full pass to detect it.
  1302. - **Word counts.** A word is a whitespace-separated token containing a letter or digit, except that Chinese, Japanese, Thai, Lao, Khmer and Myanmar text, which has no spaces between words, is split at word boundaries (the same count `query-notes` uses for `words:` and `wordCount`); `charCount` counts Unicode code points. Attachment markers are not counted. Both are `null` for locked notes and bodies that are not downloaded or cannot be decoded, and `0` for a body known to be empty.
  1303. - **Previews.** With `wordCounts`, `bodyPreview` comes from the decoded body and `textDecoded` is `true`. Otherwise it is the stored snippet. Locked notes never get a preview.
  1304. - Folderless notes (abandoned Quick Note drafts Notes.app never shows) and Recently Deleted appear only with `includeDeleted`. Notes without a stored modification date never match a `since` query.
  1305. **Example - incremental sync:**
  1306. ```json
  1307. {
  1308. "since": "cdts1:41c7e0ef438fcd6f:4312",
  1309. "limit": 200
  1310. }
  1311. ```
  1312. ---
  1313. #### `get-selected-notes`
  1314. Reads the currently selected note(s) from the Notes.app UI.
  1315. **Parameters:** None
  1316. **Returns:** Selected note metadata, including IDs for follow-up operations. Returns an empty list when Notes.app has no selected note.
  1317. ---
  1318. ### Folder Operations
  1319. #### `list-folders`
  1320. Lists all folders in an account with full hierarchical paths.
  1321. | Parameter | Type | Required | Description |
  1322. |-----------|------|----------|-------------|
  1323. | `account` | string | No | Account to list folders from (defaults to Notes.app's default account; exact or unique-prefix match) |
  1324. **Example:**
  1325. ```json
  1326. {}
  1327. ```
  1328. **Returns:** List of folders with IDs, paths, account names, and shared state, plus `identifier`, `parentIdentifier`, and `accountIdentifier` when Full Disk Access is granted. Nested folders are shown as full paths (e.g., `Work/Clients/Omnia`). Duplicate folder names are disambiguated by their full path. Literal slashes in folder names are escaped as `\/` (e.g., `Spain\/Portugal 2023`). Smart folders are listed too, because Notes' AppleScript lists them like ordinary folders; with Full Disk Access they carry `smartFolder: true` (and `(smart folder)` in the text list). A smart folder cannot hold notes or folders.
  1329. ---
  1330. #### `list-smart-folders`
  1331. Lists every Smart Folder with the rules that define it, read from the NoteStore
  1332. database. Requires Full Disk Access.
  1333. | Parameter | Type | Required | Description |
  1334. |-----------|------|----------|-------------|
  1335. | `includeMatchingNotes` | boolean | No | Also list the notes each smart folder currently shows (default `false`) |
  1336. | `limit` | number | No | Maximum matching notes per folder, 1–500 (default 50). `matchingNoteCount` is always the total |
  1337. **Example:**
  1338. ```json
  1339. {
  1340. "includeMatchingNotes": true,
  1341. "limit": 20
  1342. }
  1343. ```
  1344. **Returns:** For each smart folder: `name`, `id`, `identifier`, `account`,
  1345. `accountId`, `accountIdentifier`, `parent`, `parentId`, and `parentIdentifier`
  1346. (the parent fields are `null` at the account root). Its rules are decoded as
  1347. `match` (`"all"`, `"any"`, or `"none"`) and `filters`. Each filter has a `type`
  1348. (the stored rule key, such as `folder`, `tag`, `checklist`, or
  1349. `creationDateRelativeRange`), its stored `value`, `excluded` for an Exclude
  1350. rule, and a readable `description`. Folder filters add the folder's `name` and
  1351. `folderId`, and a nested rule group is a filter of type `group` with its own
  1352. `match` and `filters`. Notes stores each query inside an outer
  1353. `{"deleted": false}` wrapper that keeps Recently Deleted out. `query` is the
  1354. stored query with that wrapper removed, `includesRecentlyDeleted` reports the
  1355. wrapper's value, and `rawQuery` is the stored JSON verbatim. A rule this server
  1356. does not recognize is kept as a filter of type `unknown`, and `fullyDecoded` is
  1357. then `false`.
  1358. With `includeMatchingNotes`, each folder also carries `matchingNoteCount` and
  1359. `matchingNotes` (`title` and `id`). These come from Notes.app itself, which
  1360. evaluates the folder's rules, so they need Automation permission. The server
  1361. does not re-evaluate the rules on its own. A folder whose notes cannot be read
  1362. carries `matchingNotesError` instead.
  1363. ---
  1364. #### `list-folder-tree`
  1365. Returns the folder hierarchy with note counts for each account, read from the NoteStore database in one pass.
  1366. **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)).
  1367. | Parameter | Type | Required | Description |
  1368. |-----------|------|----------|-------------|
  1369. | `account` | string | No | Only this account (exact or unique-prefix name). Omit for every account |
  1370. | `includeDeleted` | boolean | No | Include folders marked for deletion (flagged `markedForDeletion`) and folders whose account no longer exists (default `false`) |
  1371. **Returns:** `accounts`, each with `account`, `identifier`, `noteCount`, and `folders`. Each folder node has `id`, `identifier`, `name`, `path` (in `list-folders` syntax), `kind` (`folder`, `smart`, or `trash`), `noteCount` (notes directly inside), `totalNoteCount` (including subfolders), and `children`. Regular folders sort by name, then smart folders, then Recently Deleted. An account's `noteCount` sums its regular folders. Smart folders report 0 because their contents are a saved search. Also returns `folderCount`.
  1372. ---
  1373. #### `create-folder`
  1374. Creates a new folder, including a whole nested hierarchy in one call.
  1375. | Parameter | Type | Required | Description |
  1376. |-----------|------|----------|-------------|
  1377. | `name` | string | Yes | Folder name, or a nested path separated by `/` (e.g. `"Retro Tech/PC/CPUs"`). Every intermediate folder is created; segments that already exist are skipped. A segment that names a smart folder is refused before anything is created |
  1378. | `account` | string | No | Account to create folder in (defaults to Notes.app's default account; exact or unique-prefix match) |
  1379. **Example:**
  1380. ```json
  1381. {
  1382. "name": "Work Projects"
  1383. }
  1384. ```
  1385. **Example - Create a nested hierarchy:**
  1386. ```json
  1387. {
  1388. "name": "Work/Clients/Omnia"
  1389. }
  1390. ```
  1391. **Returns:** Confirmation message. The call is **idempotent** — an already-existing folder (or path segment) is skipped rather than treated as an error, so it is safe to call before every `create-note` that targets a folder.
  1392. Existence is decided by folder id, not by name: a folder deleted earlier in the same Notes session no longer counts as existing, and the call succeeds only once the created folder is confirmed by its id. Otherwise it reports failure.
  1393. ---
  1394. #### `get-folder-by-id`
  1395. Reads one exact folder's current name, parent ID, and account ID (`accountId`,
  1396. plus `isRoot`, true when the folder sits at the account root). Use these values
  1397. with `rename-folder` or `delete-folder-by-id`; this avoids relying on ambiguous
  1398. folder names or paths. The `id` may also be the folder's Notes UUID or numeric
  1399. key, and the result adds `identifier`, `parentIdentifier`, and
  1400. `accountIdentifier` when Full Disk Access is granted.
  1401. ---
  1402. #### `rename-folder`
  1403. Renames an existing folder in place using its exact `id`, `expectedName`,
  1404. `expectedParentId`, and `newName`. The operation preserves the folder ID, notes,
  1405. and descendants. It refuses stale metadata and a conflicting sibling name.
  1406. ---
  1407. #### `delete-folder-by-id`
  1408. Deletes one exact, empty, ordinary folder through a plan-then-apply handshake.
  1409. Read the folder first with `get-folder-by-id`, call once with `dryRun: true`,
  1410. then repeat the same guards with `dryRun: false` and the returned `revision`.
  1411. | Parameter | Type | Required | Description |
  1412. |-----------|------|----------|-------------|
  1413. | `id` | string | Yes | Exact folder id (`x-coredata://…/ICFolder/pN`), or the folder's Notes UUID or numeric key |
  1414. | `expectedName` | string | Yes | Current folder name (not a path), matched case-sensitively |
  1415. | `expectedAccountId` | string | Yes | Owning account id (`x-coredata://…/ICAccount/pN`) |
  1416. | `expectedParentId` | string | One of these two | Current parent folder id (same forms as `id`) |
  1417. | `expectedRoot` | `true` | One of these two | The folder sits at the account root |
  1418. | `dryRun` | boolean | Yes | `true` plans; `false` applies |
  1419. | `expectedRevision` | string | On apply | The `revision` from the dry run |
  1420. **Example (plan, then apply with the returned revision):**
  1421. ```json
  1422. {
  1423. "id": "x-coredata://ABC/ICFolder/p42",
  1424. "expectedName": "Old Projects",
  1425. "expectedAccountId": "x-coredata://ABC/ICAccount/p3",
  1426. "expectedRoot": true,
  1427. "dryRun": true
  1428. }
  1429. ```
  1430. **Returns:** `status: "planned"` with `wouldDelete`, `identifier`, `name`,
  1431. `accountId`, `parentId`, `folderType: 0`, zero `childFolderCount` and
  1432. `noteCount`, and `revision`; on apply, `status: "deleted"`, `committed: true`,
  1433. `verified: true` (Notes.app no longer resolves the id), and `storeTombstoned`.
  1434. **Safety:** it always refuses Recently Deleted, smart folders, the account's
  1435. default and other system folders, shared folders (or folders inside a shared
  1436. folder), and any folder that still holds notes or subfolders. There is no
  1437. override. It is **not atomic**: the guard is a pre-check followed by an
  1438. AppleScript delete. The name, parent, account, sharing, and emptiness checks
  1439. repeat inside the delete script, but the folder type and stable identifier come
  1440. from the local Notes database just before it. It needs Full Disk Access and
  1441. fails closed without it.
  1442. **Errors** carry the standard `code`: `revision_conflict` (a `Conflict:` message;
  1443. read and plan again), `unsupported` (a `Refused:` message), `verification_failed`
  1444. with `indeterminate: true` (read the folder before any retry), and
  1445. `full_disk_access_missing`.
  1446. ---
  1447. #### `delete-folder`
  1448. Deletes a folder.
  1449. | Parameter | Type | Required | Description |
  1450. |-----------|------|----------|-------------|
  1451. | `name` | string | Yes | Name or path of the folder to delete (supports nested paths like `"Work/Old"`) |
  1452. | `account` | string | No | Account containing the folder (defaults to Notes.app's default account; exact or unique-prefix match) |
  1453. **Example:**
  1454. ```json
  1455. {
  1456. "name": "Old Projects"
  1457. }
  1458. ```
  1459. **Returns:** Confirmation message, or error if folder not found or not empty.
  1460. **⚠️ Safety:** Irreversible — requires explicit user confirmation before calling. Prefer `list-folders` first to confirm the exact folder path being deleted.
  1461. ---
  1462. #### `show-folder`
  1463. Reveals a folder in Notes.app using its unique CoreData identifier.
  1464. | Parameter | Type | Required | Description |
  1465. |-----------|------|----------|-------------|
  1466. | `id` | string | Yes | The folder's CoreData identifier (from `list-folders`), or its Notes UUID or numeric key |
  1467. | `separately` | boolean | No | Open in a separate window when supported by Notes.app |
  1468. **Returns:** Confirmation that Notes.app accepted the show command.
  1469. ---
  1470. ### Account Operations
  1471. #### `list-accounts`
  1472. Lists all configured Notes accounts.
  1473. **Parameters:** None
  1474. **Example:**
  1475. ```json
  1476. {}
  1477. ```
  1478. **Returns:** List of accounts with names, IDs, upgraded state, and default folder metadata, plus each account's `identifier` (Notes UUID) when Full Disk Access is granted.
  1479. ---
  1480. #### `get-default-location`
  1481. Returns the default account and folder Notes.app uses for newly created notes.
  1482. **Parameters:** None
  1483. **Returns:** Default account and folder metadata, including IDs and shared state.
  1484. ---
  1485. #### `show-account`
  1486. Reveals an account in Notes.app using its unique CoreData identifier.
  1487. | Parameter | Type | Required | Description |
  1488. |-----------|------|----------|-------------|
  1489. | `id` | string | Yes | The account's CoreData identifier (from `list-accounts`) |
  1490. | `separately` | boolean | No | Open in a separate window when supported by Notes.app |
  1491. **Returns:** Confirmation that Notes.app accepted the show command.
  1492. ---
  1493. ### Batch Operations
  1494. #### `batch-delete-notes`
  1495. Deletes multiple notes at once by ID.
  1496. | Parameter | Type | Required | Description |
  1497. |-----------|------|----------|-------------|
  1498. | `notes` | object[] | Yes | Array of `{id, expectedContentHash}` snapshots to delete (max 500 per request) |
  1499. **Returns:** Summary of successes and failures. A note already in Recently Deleted fails without being deleted, as in `delete-note`.
  1500. **⚠️ Safety:** Irreversible — requires explicit user confirmation before calling. Prefer `search-notes` / `list-notes` first to confirm the exact ids being deleted.
  1501. ---
  1502. #### `batch-move-notes`
  1503. Moves multiple notes to a folder.
  1504. | Parameter | Type | Required | Description |
  1505. |-----------|------|----------|-------------|
  1506. | `ids` | string[] | Yes | Array of note IDs to move (max 500 per request) |
  1507. | `folder` | string | Yes | Destination folder name or nested path (e.g., `"Work/Clients"`). Must already exist — create it with [`create-folder`](#create-folder). A smart folder is refused for the whole call before any note moves |
  1508. | `account` | string | No | Account containing the folder |
  1509. | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Shared folder preconditions applied independently to each note; see [Folder scope guards](#folder-scope-guards). Forbidden folders also apply to the destination |
  1510. **Returns:** Summary of successes and failures. Each success is reported only
  1511. after the note's actual container folder ID matches the destination folder ID.
  1512. If every note fails, the call returns its existing error response; the exact
  1513. note IDs and reasons remain in the failure text.
  1514. Failure rows carry `committed: false, indeterminate: false` only when that
  1515. item was refused before its move. Move/readback failures and an unknown
  1516. whole-script outcome carry `indeterminate: true`, with `committed` omitted.
  1517. If every item fails, the batch reports `committed: false` only when every row
  1518. is a proven pre-move refusal. Otherwise its error result is indeterminate;
  1519. read each exact note ID before retrying, even if another row has a scope refusal.
  1520. **Example - move only notes that are still in the reviewed inbox:**
  1521. ```json
  1522. {
  1523. "ids": ["x-coredata://ABC123/ICNote/p456", "x-coredata://ABC123/ICNote/p457"],
  1524. "folder": "Archive",
  1525. "ifFolderId": "x-coredata://ABC123/ICFolder/p12"
  1526. }

Lines 2,001–3,229 are not shown. The link to the file on GitHub has every line.

src/services/appleNotesManager.test.ts · Bundled script · 4,931 lines · 1 finding marked
  1. /**
  2. * Unit Tests for Apple Notes Manager
  3. *
  4. * These tests verify the AppleNotesManager class and its helper functions.
  5. * The AppleScript execution is mocked to allow testing without macOS.
  6. *
  7. * Test Strategy:
  8. * - Helper functions (escapeForAppleScript, parseAppleScriptDate) are tested
  9. * with various inputs to ensure correct escaping and parsing
  10. * - Manager methods are tested for success/failure paths
  11. * - Script generation is verified by checking for expected AppleScript patterns
  12. */
  13. import { describe, it, expect, vi, beforeEach } from "vitest";
  14. import { execFileSync } from "node:child_process";
  15. import { writeFileSync, rmSync, mkdtempSync, readFileSync, statSync, existsSync } from "node:fs";
  16. import { tmpdir } from "node:os";
  17. import { join } from "node:path";
  18. import {
  19. AppleNotesManager,
  20. ExpectedBodies,
  21. escapeForAppleScript,
  22. escapeHtmlForAppleScript,
  23. buildAppleScriptDateVar,
  24. buildFolderReference,
  25. buildLiveFolderResolution,
  26. LIVE_FOLDER_NOT_FOUND,
  27. splitFolderPath,
  28. parseAppleScriptDate,
  29. sanitizeId,
  30. sanitizeNoteId,
  31. DEFAULT_EXPORT_PAGE_SIZE,
  32. estimateExportNoteBytes,
  33. exportMaxResponseBytes,
  34. } from "./appleNotesManager.js";
  35. // Mock the AppleScript execution module
  36. // This prevents actual osascript calls during testing
  37. // Only the executor is stubbed. `isPermissionDenied` is deliberately the REAL
  38. // implementation: the whole point of the shared classifier is that the health
  39. // check and the error mapping run the same code, so a mock here would test a
  40. // copy instead of the thing that ships.
  41. vi.mock("@/utils/applescript.js", async (importOriginal) => {
  42. const actual = await importOriginal<typeof import("@/utils/applescript.js")>();
  43. return {
  44. ...actual,
  45. executeAppleScript: vi.fn(),
  46. BULK_LIST_MUTATION_ERROR: "Notes changed during listing",
  47. };
  48. });
  49. // Mock the checklist parser to avoid SQLite access during tests
  50. vi.mock("@/utils/checklistParser.js", () => ({
  51. getChecklistItems: vi.fn().mockReturnValue({ items: null }),
  52. }));
  53. import { executeAppleScript, noteBodyMaxBuffer } from "@/utils/applescript.js";
  54. const mockExecuteAppleScript = vi.mocked(executeAppleScript);
  55. const NO_RETRY_OPTIONS = { maxRetries: 1 };
  56. import { getChecklistItems } from "@/utils/checklistParser.js";
  57. const mockGetChecklistItems = vi.mocked(getChecklistItems);
  58. // Mock the transcript reader so the delegation test never touches SQLite.
  59. vi.mock("@/utils/audioTranscripts.js", () => ({
  60. readAudioTranscripts: vi.fn(),
  61. }));
  62. import { readAudioTranscripts } from "@/utils/audioTranscripts.js";
  63. const mockReadAudioTranscripts = vi.mocked(readAudioTranscripts);
  64. // Recently Deleted folder ids come from the database; keep tests off it.
  65. vi.mock("@/utils/trashFolders.js", async (importOriginal) => ({
  66. ...(await importOriginal<typeof import("@/utils/trashFolders.js")>()),
  67. readTrashFolderIds: vi.fn(() => []),
  68. }));
  69. import { readTrashFolderIds } from "@/utils/trashFolders.js";
  70. const mockReadTrashFolderIds = vi.mocked(readTrashFolderIds);
  71. // Smart folder ids come from the database too; none here, so destination
  72. // scripts are exactly what they were. smartFolderDestination.test.ts covers them.
  73. vi.mock("@/utils/smartFolders.js", async (importOriginal) => ({
  74. ...(await importOriginal<typeof import("@/utils/smartFolders.js")>()),
  75. readSmartFolders: vi.fn(() => ({ folders: [] })),
  76. }));
  77. const G = "\x1d";
  78. const TRASH_FOLDER = "x-coredata://ABC-123/ICFolder/p9";
  79. function compilesAsAppleScript(script: string): void {
  80. const dir = mkdtempSync(join(tmpdir(), "trash-script-"));
  81. try {
  82. writeFileSync(join(dir, "s.applescript"), script);
  83. execFileSync("/usr/bin/osacompile", ["-o", join(dir, "s.scpt"), join(dir, "s.applescript")], {
  84. stdio: "pipe",
  85. });
  86. } finally {
  87. rmSync(dir, { recursive: true, force: true });
  88. }
  89. }
  90. // Result delimiters (#18) — must match appleNotesManager.ts.
  91. // FIELD_SEP (US, \x1f) separates fields within a record;
  92. // RECORD_SEP (RS, \x1e) separates records within a list.
  93. const F = "\x1f";
  94. const R = "\x1e";
  95. // =============================================================================
  96. // Text Escaping Tests
  97. // =============================================================================
  98. describe("escapeForAppleScript", () => {
  99. describe("empty and null handling", () => {
  100. it("returns empty string for empty input", () => {
  101. expect(escapeForAppleScript("")).toBe("");
  102. });
  103. it("returns empty string for null-like input", () => {
  104. // TypeScript prevents actual null, but runtime might have undefined
  105. expect(escapeForAppleScript(undefined as unknown as string)).toBe("");
  106. });
  107. });
  108. describe("single quote handling", () => {
  109. it("preserves single quotes (no escaping needed in AppleScript double-quoted strings)", () => {
  110. // Single quotes don't need escaping inside AppleScript double-quoted strings
  111. const result = escapeForAppleScript("it's working");
  112. expect(result).toBe("it's working");
  113. });
  114. it("handles multiple single quotes", () => {
  115. const result = escapeForAppleScript("Rob's mom's note");
  116. expect(result).toBe("Rob's mom's note");
  117. });
  118. });
  119. describe("double quote escaping (AppleScript strings)", () => {
  120. it("escapes double quotes for AppleScript", () => {
  121. // AppleScript strings: "hello \"quoted\" world"
  122. const result = escapeForAppleScript('say "hello"');
  123. expect(result).toBe('say \\"hello\\"');
  124. });
  125. it("handles mixed quotes", () => {
  126. const result = escapeForAppleScript('He said "it\'s fine"');
  127. expect(result).toBe('He said \\"it\'s fine\\"');
  128. });
  129. });
  130. describe("control character conversion (HTML for Notes.app)", () => {
  131. it("converts newlines to <br> tags", () => {
  132. const result = escapeForAppleScript("line 1\nline 2\nline 3");
  133. expect(result).toBe("line 1<br>line 2<br>line 3");
  134. });
  135. it("converts tabs to <br> tags", () => {
  136. const result = escapeForAppleScript("col1\tcol2\tcol3");
  137. expect(result).toBe("col1<br>col2<br>col3");
  138. });
  139. it("handles mixed control characters", () => {
  140. const result = escapeForAppleScript("row1\tcol2\nrow2\tcol2");
  141. expect(result).toBe("row1<br>col2<br>row2<br>col2");
  142. });
  143. });
  144. describe("complex content", () => {
  145. it("handles real-world note content", () => {
  146. const content = 'John\'s "Meeting Notes"\n- Item 1\n- Item 2';
  147. const result = escapeForAppleScript(content);
  148. expect(result).toBe('John\'s \\"Meeting Notes\\"<br>- Item 1<br>- Item 2');
  149. });
  150. });
  151. describe("unicode and special characters", () => {
  152. it("preserves unicode characters", () => {
  153. const result = escapeForAppleScript("日本語テスト 🎉");
  154. expect(result).toBe("日本語テスト 🎉");
  155. });
  156. it("preserves emoji in content", () => {
  157. const result = escapeForAppleScript("Shopping 🛒\n- Eggs 🥚\n- Milk 🥛");
  158. expect(result).toBe("Shopping 🛒<br>- Eggs 🥚<br>- Milk 🥛");
  159. });
  160. it("handles accented characters", () => {
  161. const result = escapeForAppleScript("Café résumé naïve");
  162. expect(result).toBe("Café résumé naïve");
  163. });
  164. it("handles backslashes", () => {
  165. // Backslashes are HTML-encoded to avoid AppleScript escaping issues
  166. const result = escapeForAppleScript("path\\to\\file");
  167. expect(result).toBe("path&#92;to&#92;file");
  168. });
  169. it("handles ampersands", () => {
  170. // Ampersands are HTML-encoded for Notes.app (& becomes &amp;)
  171. const result = escapeForAppleScript("A && B & C");
  172. expect(result).toBe("A &amp;&amp; B &amp; C");
  173. });
  174. it("handles angle brackets (HTML-like content)", () => {
  175. // Single quotes pass through unchanged
  176. const result = escapeForAppleScript("<script>alert('xss')</script>");
  177. expect(result).toBe("<script>alert('xss')</script>");
  178. });
  179. });
  180. describe("boundary conditions", () => {
  181. it("handles very short strings", () => {
  182. expect(escapeForAppleScript("a")).toBe("a");
  183. expect(escapeForAppleScript("'")).toBe("'");
  184. expect(escapeForAppleScript('"')).toBe('\\"');
  185. });
  186. it("handles string with only whitespace", () => {
  187. expect(escapeForAppleScript(" ")).toBe(" ");
  188. });
  189. it("handles multiple consecutive special characters", () => {
  190. // Single quotes pass through, double quotes are escaped
  191. const result = escapeForAppleScript("'''\"\"\"");
  192. expect(result).toBe("'''\\\"\\\"\\\"");
  193. });
  194. });
  195. });
  196. // =============================================================================
  197. // HTML Content Escaping Tests (for already-HTML content)
  198. // =============================================================================
  199. describe("escapeHtmlForAppleScript", () => {
  200. describe("basic escaping", () => {
  201. it("returns empty string for null/undefined", () => {
  202. expect(escapeHtmlForAppleScript("")).toBe("");
  203. expect(escapeHtmlForAppleScript(null as unknown as string)).toBe("");
  204. expect(escapeHtmlForAppleScript(undefined as unknown as string)).toBe("");
  205. });
  206. it("escapes double quotes for AppleScript", () => {
  207. const result = escapeHtmlForAppleScript('<div>Hello "World"</div>');
  208. expect(result).toBe('<div>Hello \\"World\\"</div>');
  209. });
  210. it("escapes backslashes for AppleScript", () => {
  211. const result = escapeHtmlForAppleScript("<div>Path: C:\\Users\\test</div>");
  212. expect(result).toBe("<div>Path: C:\\\\Users\\\\test</div>");
  213. });
  214. it("handles both backslashes and quotes", () => {
  215. const result = escapeHtmlForAppleScript('<div>Path: "C:\\test"</div>');
  216. expect(result).toBe('<div>Path: \\"C:\\\\test\\"</div>');
  217. });
  218. });
  219. describe("preserves HTML content", () => {
  220. it("does not re-encode existing HTML entities", () => {
  221. const result = escapeHtmlForAppleScript("<div>&amp; &lt; &gt;</div>");
  222. expect(result).toBe("<div>&amp; &lt; &gt;</div>");
  223. });
  224. it("preserves HTML tags", () => {
  225. const result = escapeHtmlForAppleScript("<div><b>Bold</b><br><i>Italic</i></div>");
  226. expect(result).toBe("<div><b>Bold</b><br><i>Italic</i></div>");
  227. });
  228. it("preserves numeric HTML entities", () => {
  229. const result = escapeHtmlForAppleScript("<div>&#92; &#60; &#62;</div>");
  230. expect(result).toBe("<div>&#92; &#60; &#62;</div>");
  231. });
  232. });
  233. });
  234. // =============================================================================
  235. // Date Parsing Tests
  236. // =============================================================================
  237. describe("parseAppleScriptDate", () => {
  238. describe("standard format parsing", () => {
  239. it("parses AppleScript date with 'date' prefix", () => {
  240. const dateStr = "date Saturday, December 27, 2025 at 3:44:02 PM";
  241. const result = parseAppleScriptDate(dateStr);
  242. expect(result.getFullYear()).toBe(2025);
  243. expect(result.getMonth()).toBe(11); // December is month 11 (0-indexed)
  244. expect(result.getDate()).toBe(27);
  245. });
  246. it("parses date without 'date' prefix", () => {
  247. const dateStr = "Saturday, December 27, 2025 at 3:44:02 PM";
  248. const result = parseAppleScriptDate(dateStr);
  249. expect(result.getFullYear()).toBe(2025);
  250. expect(result.getMonth()).toBe(11);
  251. });
  252. it("correctly handles AM/PM times", () => {
  253. const morningDate = "date Monday, January 1, 2025 at 9:30:00 AM";
  254. const eveningDate = "date Monday, January 1, 2025 at 9:30:00 PM";
  255. const morning = parseAppleScriptDate(morningDate);
  256. const evening = parseAppleScriptDate(eveningDate);
  257. expect(morning.getHours()).toBe(9);
  258. expect(evening.getHours()).toBe(21);
  259. });
  260. });
  261. describe("locale-independent numeric format (#25)", () => {
  262. it("parses the Y-M-D-H-m-s form emitted by our producers", () => {
  263. const result = parseAppleScriptDate("2025-12-27-15-44-2");
  264. expect(result.getFullYear()).toBe(2025);
  265. expect(result.getMonth()).toBe(11);
  266. expect(result.getDate()).toBe(27);
  267. expect(result.getHours()).toBe(15);
  268. expect(result.getMinutes()).toBe(44);
  269. expect(result.getSeconds()).toBe(2);
  270. });
  271. it("handles single-digit components and midnight", () => {
  272. const result = parseAppleScriptDate("2025-1-5-0-0-0");
  273. expect(result.getMonth()).toBe(0);
  274. expect(result.getDate()).toBe(5);
  275. expect(result.getHours()).toBe(0);
  276. });
  277. });
  278. describe("fallback behavior", () => {
  279. it("returns current date for invalid input", () => {
  280. const before = new Date();
  281. const result = parseAppleScriptDate("not a valid date");
  282. const after = new Date();
  283. // Result should be between before and after (i.e., "now")
  284. expect(result.getTime()).toBeGreaterThanOrEqual(before.getTime());
  285. expect(result.getTime()).toBeLessThanOrEqual(after.getTime());
  286. });
  287. it("returns current date for empty string", () => {
  288. const before = new Date();
  289. const result = parseAppleScriptDate("");
  290. const after = new Date();
  291. expect(result.getTime()).toBeGreaterThanOrEqual(before.getTime());
  292. expect(result.getTime()).toBeLessThanOrEqual(after.getTime());
  293. });
  294. });
  295. });
  296. // =============================================================================
  297. // buildFolderReference Tests
  298. // =============================================================================
  299. describe("splitFolderPath", () => {
  300. it("splits simple path on /", () => {
  301. expect(splitFolderPath("Work/Clients")).toEqual(["Work", "Clients"]);
  302. });
  303. it("returns single segment for a name without /", () => {
  304. expect(splitFolderPath("Work")).toEqual(["Work"]);
  305. });
  306. it("preserves escaped slashes in folder names", () => {
  307. expect(splitFolderPath("Travel/Spain\\/Portugal 2023")).toEqual([
  308. "Travel",
  309. "Spain/Portugal 2023",
  310. ]);
  311. });
  312. it("handles multiple escaped slashes", () => {
  313. expect(splitFolderPath("A\\/B/C\\/D")).toEqual(["A/B", "C/D"]);
  314. });
  315. });
  316. describe("buildFolderReference", () => {
  317. it("returns simple folder reference for a single name", () => {
  318. expect(buildFolderReference("Work")).toBe('folder "Work"');
  319. });
  320. it("returns nested folder reference for a path", () => {
  321. expect(buildFolderReference("Work/Clients")).toBe('folder "Clients" of folder "Work"');
  322. });
  323. it("handles deeply nested paths", () => {
  324. expect(buildFolderReference("Work/Clients/Omnia")).toBe(
  325. 'folder "Omnia" of folder "Clients" of folder "Work"'
  326. );
  327. });
  328. it("handles special characters in folder names", () => {
  329. const result = buildFolderReference("Food & Drink/🥘 Recipes");
  330. expect(result).toContain('folder "🥘 Recipes"');
  331. expect(result).toContain('folder "Food & Drink"');
  332. });
  333. it("handles escaped slashes in folder names", () => {
  334. const result = buildFolderReference("Travel/Spain\\/Portugal 2023");
  335. expect(result).toBe('folder "Spain/Portugal 2023" of folder "Travel"');
  336. });
  337. });
  338. // #213: name references keep resolving folders deleted earlier in the Notes
  339. // session, so folder writes resolve each path segment to a live id.
  340. describe("buildLiveFolderResolution", () => {
  341. it("accepts a root segment only when it still exists by id", () => {
  342. const script = buildLiveFolderResolution("Work", "f");
  343. expect(script).toContain('repeat with f_c in (folders of __acctRef whose name is "Work")');
  344. expect(script).toContain("set f_cid to id of f_c");
  345. expect(script).toContain("if exists folder id f_cid then");
  346. expect(script).toContain("if class of (container of f_c) is not folder then");
  347. expect(script).toContain("set f to folder id f_cid");
  348. expect(script).toContain(
  349. `if f is missing value then error "${LIVE_FOLDER_NOT_FOUND}: Work" number -1728`
  350. );
  351. expect(script).not.toContain('folder "Work"');
  352. });
  353. it("falls back to a live nested namesake unless rootOnly", () => {
  354. expect(buildLiveFolderResolution("Work", "f")).toContain(
  355. "if f is missing value then set f to f_any"
  356. );
  357. expect(buildLiveFolderResolution("Work", "f", { rootOnly: true })).not.toContain(
  358. "set f to f_any"
  359. );
  360. });
  361. it("walks nested segments under the resolved parent", () => {
  362. const script = buildLiveFolderResolution("Work/Clients/Omnia", "f");
  363. const clients = script.indexOf('repeat with f_c in (folders of f_p whose name is "Clients")');
  364. const omnia = script.indexOf('repeat with f_c in (folders of f_p whose name is "Omnia")');
  365. expect(script.indexOf('whose name is "Work"')).toBeLessThan(clients);
  366. expect(clients).toBeGreaterThan(0);
  367. expect(omnia).toBeGreaterThan(clients);
  368. expect(script.match(/if exists folder id f_cid then/g)).toHaveLength(3);
  369. expect(script.match(/if f is missing value then error/g)).toHaveLength(3);
  370. });
  371. it("escapes names and honours escaped slashes", () => {
  372. const script = buildLiveFolderResolution('Travel/Spain\\/Portugal "23"', "f");
  373. expect(script).toContain('whose name is "Spain/Portugal \\"23\\""');
  374. });
  375. it("rejects invalid variables and paths", () => {
  376. expect(() => buildLiveFolderResolution("Work", "bad name")).toThrow(/variable/);
  377. expect(() => buildLiveFolderResolution("", "f")).toThrow();
  378. });
  379. });
  380. // =============================================================================
  381. // buildAppleScriptDateVar Tests
  382. // =============================================================================
  383. describe("buildAppleScriptDateVar", () => {
  384. it("generates locale-safe AppleScript date setup code", () => {
  385. const date = new Date(2025, 5, 15, 14, 30, 0); // June 15, 2025 2:30 PM
  386. const result = buildAppleScriptDateVar(date);
  387. expect(result).toContain("set thresholdDate to current date");
  388. expect(result).toContain("set year of thresholdDate to 2025");
  389. expect(result).toContain("set month of thresholdDate to 6");
  390. expect(result).toContain("set day of thresholdDate to 15");
  391. // 14*3600 + 30*60 = 52200
  392. expect(result).toContain("set time of thresholdDate to 52200");
  393. });
  394. it("handles midnight (time = 0)", () => {
  395. const date = new Date(2025, 0, 1, 0, 0, 0); // Jan 1, 2025 midnight
  396. const result = buildAppleScriptDateVar(date);
  397. expect(result).toContain("set month of thresholdDate to 1");
  398. expect(result).toContain("set day of thresholdDate to 1");
  399. expect(result).toContain("set time of thresholdDate to 0");
  400. });
  401. it("uses custom variable name", () => {
  402. const date = new Date(2025, 0, 1, 0, 0, 0);
  403. const result = buildAppleScriptDateVar(date, "myDate");
  404. expect(result).toContain("set myDate to current date");
  405. expect(result).toContain("set year of myDate to 2025");
  406. expect(result).toContain("set month of myDate to 1");
  407. });
  408. it("calculates time in seconds correctly", () => {
  409. const date = new Date(2025, 11, 25, 9, 5, 3); // 9:05:03 AM
  410. const result = buildAppleScriptDateVar(date);
  411. // 9*3600 + 5*60 + 3 = 32703
  412. expect(result).toContain("set time of thresholdDate to 32703");
  413. });
  414. it("resets day to 1 before month to prevent month rollover (#86)", () => {
  415. // AppleScript rolls invalid intermediate dates: with `current date` on the
  416. // 31st, setting month to June yields July 1 before day is ever assigned.
  417. // Day must be pinned to 1 before the year/month assignments.
  418. const date = new Date(2025, 5, 15, 0, 0, 0); // June 15, 2025
  419. const result = buildAppleScriptDateVar(date);
  420. const lines = result.split("\n");
  421. const dayResetIdx = lines.indexOf("set day of thresholdDate to 1");
  422. const yearIdx = lines.indexOf("set year of thresholdDate to 2025");
  423. const monthIdx = lines.indexOf("set month of thresholdDate to 6");
  424. const dayIdx = lines.indexOf("set day of thresholdDate to 15");
  425. expect(dayResetIdx).toBeGreaterThan(-1);
  426. expect(dayResetIdx).toBeLessThan(yearIdx);
  427. expect(yearIdx).toBeLessThan(monthIdx);
  428. expect(monthIdx).toBeLessThan(dayIdx);
  429. });
  430. });
  431. // =============================================================================
  432. // AppleNotesManager Tests
  433. // =============================================================================
  434. describe("AppleNotesManager", () => {
  435. let manager: AppleNotesManager;
  436. beforeEach(() => {
  437. manager = new AppleNotesManager();
  438. vi.clearAllMocks();
  439. });
  440. // ---------------------------------------------------------------------------
  441. // Account Resolution (#128)
  442. // ---------------------------------------------------------------------------
  443. describe("account resolution", () => {
  444. it("targets Notes.app's own default account when none is given", () => {
  445. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  446. manager.searchNotes("anything");
  447. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  448. // A hardcoded "iCloud" is wrong whenever the real default account differs
  449. // — a non-iCloud default, a localized name, or a U+F8FF suffix (#128).
  450. expect(script).toContain("set __acctRef to default account");
  451. expect(script).not.toContain('tell account "iCloud"');
  452. });
  453. it("prefers an exact name match over a prefix match", () => {
  454. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  455. manager.searchNotes("anything", false, "Work");
  456. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  457. const exactAt = script.indexOf('every account whose name is "Work"');
  458. const prefixAt = script.indexOf('every account whose name starts with "Work"');
  459. expect(exactAt).toBeGreaterThan(-1);
  460. expect(prefixAt).toBeGreaterThan(-1);
  461. // Exact is tested first, and prefix is only consulted in the else branch.
  462. expect(exactAt).toBeLessThan(prefixAt);
  463. });
  464. it("refuses an ambiguous prefix match instead of silently picking the first", () => {
  465. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  466. manager.searchNotes("anything", false, "rob");
  467. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  468. // `first account whose name starts with ...` would resolve "rob" to
  469. // whichever of rob@… / robert@… Notes lists first and report success —
  470. // on the delete/move paths that is a destructive wrong-account write.
  471. expect(script).not.toContain("first account whose name starts with");
  472. expect(script).toContain("is ambiguous");
  473. expect(script).toContain("(count of _prefixMatches) > 1");
  474. });
  475. it("errors rather than proceeding when the named account does not exist", () => {
  476. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  477. manager.searchNotes("anything", false, "Nope");
  478. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  479. expect(script).toContain('Account \\"Nope\\" not found"');
  480. // Tagged so the swallow-into-false callers can tell a precondition error
  481. // from a genuine "note not found" outcome.
  482. expect(script).toContain("AccountResolutionError:");
  483. });
  484. it("reports an unresolvable account as such instead of 'note not found' on destructive paths", () => {
  485. mockExecuteAppleScript.mockReturnValue({
  486. success: false,
  487. output: "",
  488. error:
  489. 'AccountResolutionError: Account "rob" is ambiguous - it matches 2 accounts: rob@a, rob@b. Use the full account name.',
  490. });
  491. // deleteFolder normally swallows failures into `false`; an unresolvable
  492. // account must surface instead, or the caller goes hunting for a missing
  493. // folder that was never the problem. (Same resolveAccount() path every
  494. // account-scoped destructive method uses.)
  495. expect(() => manager.deleteFolder("Doomed", "rob")).toThrow(/is ambiguous/);
  496. expect(() => manager.deleteFolder("Doomed", "rob")).not.toThrow(/AccountResolutionError/);
  497. });
  498. it("still swallows a genuine operation failure into false", () => {
  499. mockExecuteAppleScript.mockReturnValue({
  500. success: false,
  501. output: "",
  502. error: 'Can\'t get folder "Doomed".',
  503. });
  504. expect(manager.deleteFolder("Doomed", "iCloud")).toBe(false);
  505. });
  506. it("resolves the account for destructive paths too (deleteFolder, batch move)", () => {
  507. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  508. manager.deleteFolder("Doomed", "rob");
  509. const deleteScript = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
  510. expect(deleteScript).toContain("is ambiguous");
  511. expect(deleteScript).not.toContain("first account whose name starts with");
  512. manager.batchMoveNotes(["x-coredata://ABC/ICNote/p1"], "Archive", "rob");
  513. const moveScript = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
  514. expect(moveScript).toContain("is ambiguous");
  515. expect(moveScript).toContain("of __acctRef");
  516. });
  517. it("treats a blank account string as 'use the default'", () => {
  518. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  519. manager.searchNotes("anything", false, " ");
  520. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  521. expect(script).toContain("set __acctRef to default account");
  522. });
  523. });
  524. describe("listAttachments — security", () => {
  525. it("escapes the account name so it cannot break out of the AppleScript literal (injection regression)", () => {
  526. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  527. manager.listAttachments("My Note", 'evil" injected');
  528. const script = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
  529. // The account's double-quote must be escaped (\\") — a raw quote would
  530. // terminate the account-name string literal and allow `do shell script` injection.
  531. expect(script).toContain('every account whose name is "evil\\" injected"');
  532. expect(script).not.toContain('every account whose name is "evil" injected"');
  533. });
  534. });
  535. // ---------------------------------------------------------------------------
  536. // Note Creation
  537. // ---------------------------------------------------------------------------
  538. describe("createNote", () => {
  539. it("does not retry creation after an ambiguous timeout", () => {
  540. mockExecuteAppleScript.mockReturnValue({
  541. success: false,
  542. output: "",
  543. error: "Operation timed out after 30 seconds",
  544. });
  545. manager.createNote("One copy", "Body");
  546. expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), { maxRetries: 1 });
  547. });
  548. it("returns Note object on successful creation", () => {
  549. mockExecuteAppleScript
  550. .mockReturnValueOnce({
  551. success: true,
  552. output: "note id x-coredata://12345/ICNote/p100",
  553. })
  554. // The reported account comes from Notes.app's own default account (#128),
  555. // not a hardcoded "iCloud".
  556. .mockReturnValueOnce({ success: true, output: "Personal" });
  557. const result = manager.createNote("Shopping List", "Eggs, Milk, Bread");
  558. expect(result).not.toBeNull();
  559. expect(result?.title).toBe("Shopping List");
  560. expect(result?.content).toBe("Eggs, Milk, Bread");
  561. expect(result?.account).toBe("Personal");
  562. });
  563. it("strips the 'note id ' prefix from the returned id (#create-note-id)", () => {
  564. // AppleScript's `id of newNote` yields an object specifier with a literal
  565. // "note id " prefix. The returned id must be the bare x-coredata:// URL so
  566. // downstream tools (get-note-content, update-note) accept it.
  567. mockExecuteAppleScript.mockReturnValue({
  568. success: true,
  569. output: "note id x-coredata://ABC-DEF/ICNote/p42",
  570. });
  571. const result = manager.createNote("Prefixed", "Body");
  572. expect(result?.id).toBe("x-coredata://ABC-DEF/ICNote/p42");
  573. expect(result?.id).not.toMatch(/^note id /);
  574. });
  575. it("accepts the bare canonical ID form returned by some Notes accounts", () => {
  576. mockExecuteAppleScript.mockReturnValue({
  577. success: true,
  578. output: "x-coredata://ABC-DEF/ICNote/p43",
  579. });
  580. expect(manager.createNote("Bare ID", "Body")?.id).toBe("x-coredata://ABC-DEF/ICNote/p43");
  581. });
  582. it("fails closed when Notes does not return a real CoreData note ID", () => {
  583. mockExecuteAppleScript.mockReturnValue({ success: true, output: "note 1 of folder Notes" });
  584. const result = manager.createNote("No writable identity", "Body");
  585. expect(result).toBeNull();
  586. });
  587. it("returned id round-trips through get-note-content and update-note (#create-note-id)", () => {
  588. mockExecuteAppleScript.mockReturnValue({
  589. success: true,
  590. output: "note id x-coredata://ABC-DEF/ICNote/p99",
  591. });
  592. const created = manager.createNote("Roundtrip", "Body");
  593. const id = created?.id as string;
  594. expect(id).toBe("x-coredata://ABC-DEF/ICNote/p99");
  595. // Reading back by the returned id must not throw "Invalid note ID format".
  596. mockExecuteAppleScript.mockReturnValue({ success: true, output: "Body text" });
  597. expect(() => manager.getNoteContentById(id)).not.toThrow();
  598. // Updating by the returned id must not throw either.
  599. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_UPDATED" });
  600. expect(() =>
  601. manager.updateNoteByIdIfUnchanged(id, "Roundtrip", "<div>Body</div>", undefined, "New body")
  602. ).not.toThrow();
  603. });
  604. it("returns null when AppleScript fails", () => {
  605. mockExecuteAppleScript.mockReturnValue({
  606. success: false,
  607. output: "",
  608. error: "Notes.app not responding",
  609. });
  610. const result = manager.createNote("Test", "Content");
  611. expect(result).toBeNull();
  612. });
  613. it("uses specified account instead of default", () => {
  614. mockExecuteAppleScript.mockReturnValue({
  615. success: true,
  616. output: "note id x-coredata://ABC/ICNote/p201",
  617. });
  618. const result = manager.createNote("Draft", "Email content", [], undefined, "Gmail");
  619. expect(result?.account).toBe("Gmail");
  620. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  621. expect.stringContaining('every account whose name is "Gmail"'),
  622. NO_RETRY_OPTIONS
  623. );
  624. });
  625. it("creates note in specified folder", () => {
  626. mockExecuteAppleScript.mockReturnValue({
  627. success: true,
  628. output: "note id x-coredata://ABC/ICNote/p202",
  629. });
  630. manager.createNote("Work Note", "Content", [], "Work Projects");
  631. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  632. expect(script).toContain('whose name is "Work Projects"');
  633. expect(script).toContain("exists folder id __folder_cid");
  634. expect(script).toContain("make new note at __folder with properties");
  635. expect(script).not.toContain('at folder "Work Projects"');
  636. expect(mockExecuteAppleScript.mock.calls[0][1]).toEqual(NO_RETRY_OPTIONS);
  637. });
  638. it("stores tags in returned Note object", () => {
  639. mockExecuteAppleScript.mockReturnValue({
  640. success: true,
  641. output: "note id x-coredata://ABC/ICNote/p203",
  642. });
  643. const result = manager.createNote("Tagged Note", "Content", ["work", "urgent"]);
  644. expect(result?.tags).toEqual(["work", "urgent"]);
  645. });
  646. it("uses escapeHtmlForAppleScript when format is html", () => {
  647. mockExecuteAppleScript.mockReturnValue({
  648. success: true,
  649. output: "note id x-coredata://12345/ICNote/p200",
  650. });
  651. const htmlContent = "<h2>Heading</h2><div>Body text</div>";
  652. const result = manager.createNote("HTML Note", htmlContent, [], undefined, undefined, "html");
  653. expect(result).not.toBeNull();
  654. // HTML tags should NOT be entity-encoded — they should pass through to AppleScript
  655. // escapeHtmlForAppleScript only escapes \ and ", not HTML tags
  656. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  657. expect.stringContaining("<h2>Heading</h2><div>Body text</div>"),
  658. NO_RETRY_OPTIONS
  659. );
  660. });
  661. it("uses escapeForAppleScript when format is plaintext (default)", () => {
  662. mockExecuteAppleScript.mockReturnValue({
  663. success: true,
  664. output: "note id x-coredata://12345/ICNote/p201",
  665. });
  666. const result = manager.createNote("Plain Note", "Simple text with\nnewline");
  667. expect(result).not.toBeNull();
  668. // Default plaintext: newlines become <br>
  669. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  670. expect.stringContaining("Simple text with<br>newline"),
  671. NO_RETRY_OPTIONS
  672. );
  673. });
  674. it("escapes double quotes in html format for AppleScript safety", () => {
  675. mockExecuteAppleScript.mockReturnValue({
  676. success: true,
  677. output: "note id x-coredata://12345/ICNote/p202",
  678. });
  679. manager.createNote(
  680. "Quote Test",
  681. '<div class="test">Content</div>',
  682. [],
  683. undefined,
  684. undefined,
  685. "html"
  686. );
  687. // Double quotes must be escaped for AppleScript string embedding
  688. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  689. expect.stringContaining('<div class=\\"test\\">Content</div>'),
  690. NO_RETRY_OPTIONS
  691. );
  692. });
  693. it("sets title as h1 in body, not as name property", () => {
  694. mockExecuteAppleScript.mockReturnValue({
  695. success: true,
  696. output: "note id x-coredata://12345/ICNote/p203",
  697. });
  698. manager.createNote("My Title", "Body content");
  699. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  700. // Title must appear as h1 in body
  701. expect(script).toContain("<h1>My Title</h1>");
  702. // name property must NOT be set (causes title duplication in Notes.app)
  703. expect(script).not.toContain('name:"My Title"');
  704. });
  705. it("HTML-encodes special chars in title for h1 tag", () => {
  706. mockExecuteAppleScript.mockReturnValue({
  707. success: true,
  708. output: "note id x-coredata://12345/ICNote/p204",
  709. });
  710. manager.createNote("Q&A: <Hello> World", "Content");
  711. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  712. expect.stringContaining("<h1>Q&amp;A: &lt;Hello&gt; World</h1>"),
  713. NO_RETRY_OPTIONS
  714. );
  715. });
  716. it("HTML-encodes special chars in plaintext content", () => {
  717. mockExecuteAppleScript.mockReturnValue({
  718. success: true,
  719. output: "note id x-coredata://12345/ICNote/p205",
  720. });
  721. manager.createNote("Title", "Price: <10 & >5\nNext line");
  722. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  723. expect(script).toContain("Price: &lt;10 &amp; &gt;5<br>Next line");
  724. });
  725. it("prepends h1 title before html content", () => {
  726. mockExecuteAppleScript.mockReturnValue({
  727. success: true,
  728. output: "note id x-coredata://12345/ICNote/p206",
  729. });
  730. manager.createNote(
  731. "Report",
  732. "<h2>Section</h2><div>Details</div>",
  733. [],
  734. undefined,
  735. undefined,
  736. "html"
  737. );
  738. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  739. expect(script).toContain("<h1>Report</h1><h2>Section</h2><div>Details</div>");
  740. });
  741. it("encodes backslashes as HTML entities in plaintext content", () => {
  742. mockExecuteAppleScript.mockReturnValue({
  743. success: true,
  744. output: "note id x-coredata://12345/ICNote/p207",
  745. });
  746. manager.createNote("Title", "path\\to\\file");
  747. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  748. expect(script).toContain("path&#92;to&#92;file");
  749. });
  750. it("converts tabs to br in plaintext content", () => {
  751. mockExecuteAppleScript.mockReturnValue({
  752. success: true,
  753. output: "note id x-coredata://12345/ICNote/p208",
  754. });
  755. manager.createNote("Title", "col1\tcol2\tcol3");
  756. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  757. expect(script).toContain("col1<br>col2<br>col3");
  758. });
  759. });
  760. // ---------------------------------------------------------------------------
  761. // Note Search
  762. // ---------------------------------------------------------------------------
  763. describe("searchNotes", () => {
  764. it("returns array of matching notes with folder info", () => {
  765. mockExecuteAppleScript.mockReturnValue({
  766. success: true,
  767. output: [
  768. ["Meeting Notes", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
  769. ["Project Plan", "x-coredata://ABC/ICNote/p2", "Notes"].join(F),
  770. ["Weekly Review", "x-coredata://ABC/ICNote/p3", "Archive"].join(F),
  771. ].join(R),
  772. });
  773. const results = manager.searchNotes("notes");
  774. expect(results).toHaveLength(3);
  775. expect(results[0].title).toBe("Meeting Notes");
  776. expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
  777. expect(results[0].folder).toBe("Work");
  778. expect(results[1].title).toBe("Project Plan");
  779. expect(results[1].id).toBe("x-coredata://ABC/ICNote/p2");
  780. expect(results[1].folder).toBe("Notes");
  781. expect(results[2].title).toBe("Weekly Review");
  782. expect(results[2].id).toBe("x-coredata://ABC/ICNote/p3");
  783. expect(results[2].folder).toBe("Archive");
  784. });
  785. it("dereferences the note container before reading its folder name", () => {
  786. mockExecuteAppleScript.mockReturnValue({
  787. success: true,
  788. output: ["Meeting Notes", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
  789. });
  790. manager.searchNotes("meeting");
  791. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  792. expect(script).toContain("set noteContainer to container of n");
  793. expect(script).toContain("set noteFolder to name of noteContainer");
  794. expect(script).not.toContain("set noteFolder to name of container of n");
  795. });
  796. it("returns actual creation and modification timestamps", () => {
  797. mockExecuteAppleScript.mockReturnValue({
  798. success: true,
  799. output: [
  800. "Meeting Notes",
  801. "x-coredata://ABC/ICNote/p1",
  802. "Work",
  803. "2024-2-3-10-11-12",
  804. "2025-6-7-13-14-15",
  805. ].join(F),
  806. });
  807. const [result] = manager.searchNotes("meeting");
  808. expect(result.created).toEqual(new Date(2024, 1, 3, 10, 11, 12));
  809. expect(result.modified).toEqual(new Date(2025, 5, 7, 13, 14, 15));
  810. const script = mockExecuteAppleScript.mock.calls[0][0];
  811. expect(script).toContain("set noteCreated to creation date of n");
  812. expect(script).toContain("set noteModified to modification date of n");
  813. expect(script).toContain("year of noteCreated");
  814. expect(script).toContain("year of noteModified");
  815. });
  816. it("returns empty array when no matches found", () => {
  817. mockExecuteAppleScript.mockReturnValue({
  818. success: true,
  819. output: "",
  820. });
  821. const results = manager.searchNotes("nonexistent");
  822. expect(results).toHaveLength(0);
  823. });
  824. it("throws on AppleScript error rather than returning empty (#19)", () => {
  825. mockExecuteAppleScript.mockReturnValue({
  826. success: false,
  827. output: "",
  828. error: "Search failed",
  829. });
  830. expect(() => manager.searchNotes("test")).toThrow(/Search failed/);
  831. });
  832. it("searches content when searchContent is true", () => {
  833. mockExecuteAppleScript.mockReturnValue({
  834. success: true,
  835. output: ["Note with keyword", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  836. });
  837. manager.searchNotes("project alpha", true);
  838. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  839. expect.stringContaining('body contains "project alpha"')
  840. );
  841. });
  842. it("searches titles when searchContent is false", () => {
  843. mockExecuteAppleScript.mockReturnValue({
  844. success: true,
  845. output: ["Project Alpha Notes", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  846. });
  847. manager.searchNotes("Project Alpha", false);
  848. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  849. expect.stringContaining('name contains "Project Alpha"')
  850. );
  851. });
  852. it("identifies notes in Recently Deleted folder", () => {
  853. mockExecuteAppleScript.mockReturnValue({
  854. success: true,
  855. output: [
  856. ["Old Note", "x-coredata://ABC/ICNote/p1", "Recently Deleted"].join(F),
  857. ["Active Note", "x-coredata://ABC/ICNote/p2", "Notes"].join(F),
  858. ].join(R),
  859. });
  860. const results = manager.searchNotes("note");
  861. expect(results).toHaveLength(2);
  862. expect(results[0].title).toBe("Old Note");
  863. expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
  864. expect(results[0].folder).toBe("Recently Deleted");
  865. expect(results[1].title).toBe("Active Note");
  866. expect(results[1].id).toBe("x-coredata://ABC/ICNote/p2");
  867. expect(results[1].folder).toBe("Notes");
  868. });
  869. it("deduplicates duplicate note IDs returned by Notes.app", () => {
  870. mockExecuteAppleScript.mockReturnValue({
  871. success: true,
  872. output: [
  873. ["Not uploaded", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  874. ["Not uploaded", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  875. ].join(R),
  876. });
  877. const results = manager.searchNotes("Not uploaded");
  878. expect(results).toHaveLength(1);
  879. expect(results[0].title).toBe("Not uploaded");
  880. expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
  881. });
  882. it("scopes search to specified account", () => {
  883. mockExecuteAppleScript.mockReturnValue({
  884. success: true,
  885. output: "",
  886. });
  887. manager.searchNotes("work", false, "Exchange");
  888. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  889. expect.stringContaining('every account whose name is "Exchange"')
  890. );
  891. });
  892. it("limits search to specified folder", () => {
  893. mockExecuteAppleScript.mockReturnValue({
  894. success: true,
  895. output: ["Work Note", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
  896. });
  897. manager.searchNotes("note", false, undefined, "Work");
  898. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  899. expect.stringContaining('notes of folder "Work"')
  900. );
  901. });
  902. it("combines folder and account filters", () => {
  903. mockExecuteAppleScript.mockReturnValue({
  904. success: true,
  905. output: "",
  906. });
  907. manager.searchNotes("task", false, "Exchange", "Projects");
  908. const script = mockExecuteAppleScript.mock.calls[0][0];
  909. expect(script).toContain('every account whose name is "Exchange"');
  910. expect(script).toContain('notes of folder "Projects"');
  911. });
  912. it("adds date filter when modifiedSince is provided", () => {
  913. mockExecuteAppleScript.mockReturnValue({
  914. success: true,
  915. output: ["Recent Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  916. });
  917. manager.searchNotes("note", false, undefined, undefined, "2025-06-15T00:00:00");
  918. const script = mockExecuteAppleScript.mock.calls[0][0];
  919. // Locale-safe: uses variable setup instead of date "string"
  920. expect(script).toContain("set thresholdDate to current date");
  921. expect(script).toContain("set year of thresholdDate to 2025");
  922. expect(script).toContain("set month of thresholdDate to 6");
  923. expect(script).toContain("set day of thresholdDate to 15");
  924. expect(script).toContain("modification date >= thresholdDate");
  925. expect(script).toContain('name contains "note"');
  926. });
  927. it("combines date filter with content search", () => {
  928. mockExecuteAppleScript.mockReturnValue({
  929. success: true,
  930. output: ["Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  931. });
  932. manager.searchNotes("keyword", true, undefined, undefined, "2025-01-01");
  933. const script = mockExecuteAppleScript.mock.calls[0][0];
  934. expect(script).toContain('body contains "keyword"');
  935. expect(script).toContain("set thresholdDate to current date");
  936. expect(script).toContain("modification date >= thresholdDate");
  937. });
  938. it("ignores invalid modifiedSince date", () => {
  939. mockExecuteAppleScript.mockReturnValue({
  940. success: true,
  941. output: ["Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  942. });
  943. manager.searchNotes("note", false, undefined, undefined, "not-a-date");
  944. const script = mockExecuteAppleScript.mock.calls[0][0];
  945. expect(script).not.toContain("modification date >= thresholdDate");
  946. });
  947. it("applies limit to search results", () => {
  948. mockExecuteAppleScript.mockReturnValue({
  949. success: true,
  950. output: ["Note 1", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
  951. });
  952. manager.searchNotes("note", false, undefined, undefined, undefined, 5);
  953. const script = mockExecuteAppleScript.mock.calls[0][0];
  954. expect(script).toContain("(count of resultList) >= 5");
  955. expect(script).toContain("exit repeat");
  956. });
  957. it("combines modifiedSince, limit, folder, and content search", () => {
  958. mockExecuteAppleScript.mockReturnValue({
  959. success: true,
  960. output: ["Note", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
  961. });
  962. manager.searchNotes("project", true, "iCloud", "Work", "2025-03-01", 10);
  963. const script = mockExecuteAppleScript.mock.calls[0][0];
  964. expect(script).toContain('body contains "project"');
  965. expect(script).toContain("set thresholdDate to current date");
  966. expect(script).toContain("modification date >= thresholdDate");
  967. expect(script).toContain('notes of folder "Work"');
  968. expect(script).toContain("(count of resultList) >= 10");
  969. expect(script).toContain('every account whose name is "iCloud"');
  970. });
  971. });
  972. // ---------------------------------------------------------------------------
  973. // Note Content Retrieval
  974. // ---------------------------------------------------------------------------
  975. describe("getNoteContent", () => {
  976. it("returns HTML content of note", () => {
  977. mockExecuteAppleScript.mockReturnValue({
  978. success: true,
  979. output: "<div>Shopping List</div><div>- Eggs<br>- Milk</div>",
  980. });
  981. const content = manager.getNoteContent("Shopping List");
  982. expect(content).toBe("<div>Shopping List</div><div>- Eggs<br>- Milk</div>");
  983. });
  984. it("returns empty string when note not found", () => {
  985. mockExecuteAppleScript.mockReturnValue({
  986. success: false,
  987. output: "",
  988. error: 'Can\'t get note "Missing"',
  989. });
  990. const content = manager.getNoteContent("Missing Note");
  991. expect(content).toBe("");
  992. });
  993. it("looks up titles containing & literally, not HTML-escaped (regression)", () => {
  994. // Bug found in live testing: titles with "&" were HTML-escaped to "&amp;"
  995. // in the `note "..."` lookup, so the note could never be found.
  996. mockExecuteAppleScript.mockReturnValue({ success: true, output: "<div>x</div>" });
  997. manager.getNoteContent("Tom & Jerry", "iCloud");
  998. const script = mockExecuteAppleScript.mock.calls[0][0];
  999. expect(script).toContain("Tom & Jerry");
  1000. expect(script).not.toContain("Tom &amp; Jerry");
  1001. });
  1002. it("uses specified account", () => {
  1003. mockExecuteAppleScript.mockReturnValue({
  1004. success: true,
  1005. output: "<div>Content</div>",
  1006. });
  1007. manager.getNoteContent("My Note", "Gmail");
  1008. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1009. expect.stringContaining('every account whose name is "Gmail"'),
  1010. { maxBufferBytes: noteBodyMaxBuffer() }
  1011. );
  1012. });
  1013. it("reads bodies with the note-body output cap, by title and by id (#237)", () => {
  1014. mockExecuteAppleScript.mockReturnValue({ success: true, output: "<div>x</div>" });
  1015. manager.getNoteContent("Photo note", "iCloud");
  1016. manager.getNoteContentById("x-coredata://ABC/ICNote/p1");
  1017. const bodyReads = mockExecuteAppleScript.mock.calls.filter(([script]) =>
  1018. String(script).includes("get body of note")
  1019. );
  1020. expect(bodyReads).toHaveLength(2);
  1021. for (const [, options] of bodyReads) {
  1022. expect(options).toEqual({ maxBufferBytes: noteBodyMaxBuffer() });
  1023. }
  1024. });
  1025. });
  1026. describe("getNotePlaintext", () => {
  1027. it("reads the note's plaintext property by title", () => {
  1028. mockExecuteAppleScript.mockReturnValue({
  1029. success: true,
  1030. output: "Shopping List\n- Eggs\n- Milk",
  1031. });
  1032. const text = manager.getNotePlaintext("Shopping List");
  1033. expect(text).toBe("Shopping List\n- Eggs\n- Milk");
  1034. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1035. expect.stringContaining('get plaintext of note "Shopping List"')
  1036. );
  1037. });
  1038. it("returns empty string when the note is not found", () => {
  1039. mockExecuteAppleScript.mockReturnValue({
  1040. success: false,
  1041. output: "",
  1042. error: 'Can\'t get note "Missing"',
  1043. });
  1044. expect(manager.getNotePlaintext("Missing Note")).toBe("");
  1045. });
  1046. it("uses the specified account", () => {
  1047. mockExecuteAppleScript.mockReturnValue({ success: true, output: "Content" });
  1048. manager.getNotePlaintext("My Note", "Gmail");
  1049. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1050. expect.stringContaining('every account whose name is "Gmail"')
  1051. );
  1052. });
  1053. });
  1054. describe("getNotePlaintextById", () => {
  1055. it("reads the note's plaintext property by id at the application level", () => {
  1056. mockExecuteAppleScript.mockReturnValue({ success: true, output: "Just the text" });
  1057. const text = manager.getNotePlaintextById("x-coredata://ABC/ICNote/p1");
  1058. expect(text).toBe("Just the text");
  1059. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1060. expect.stringContaining('get plaintext of note id "x-coredata://ABC/ICNote/p1"')
  1061. );
  1062. });
  1063. it("returns empty string when Notes.app rejects the read", () => {
  1064. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "no such note" });
  1065. expect(manager.getNotePlaintextById("x-coredata://ABC/ICNote/p1")).toBe("");
  1066. });
  1067. it("rejects malformed IDs", () => {
  1068. expect(() => manager.getNotePlaintextById("arbitrary string")).toThrow();
  1069. });
  1070. });
  1071. // ---------------------------------------------------------------------------
  1072. // Password Protection Helpers
  1073. // ---------------------------------------------------------------------------
  1074. describe("isNotePasswordProtected", () => {
  1075. it("returns true when note is password-protected", () => {
  1076. mockExecuteAppleScript.mockReturnValue({
  1077. success: true,
  1078. output: [
  1079. "Locked Note",
  1080. "x-coredata://ABC/ICNote/p1",
  1081. "Monday, January 1, 2024 at 12:00:00 PM",
  1082. "Monday, January 1, 2024 at 12:00:00 PM",
  1083. "false",
  1084. "true",
  1085. ].join(F),
  1086. });
  1087. const result = manager.isNotePasswordProtected("Locked Note");
  1088. expect(result).toBe(true);
  1089. });
  1090. it("returns false when note is not password-protected", () => {
  1091. mockExecuteAppleScript.mockReturnValue({
  1092. success: true,
  1093. output: [
  1094. "Open Note",
  1095. "x-coredata://ABC/ICNote/p2",
  1096. "Monday, January 1, 2024 at 12:00:00 PM",
  1097. "Monday, January 1, 2024 at 12:00:00 PM",
  1098. "false",
  1099. "false",
  1100. ].join(F),
  1101. });
  1102. const result = manager.isNotePasswordProtected("Open Note");
  1103. expect(result).toBe(false);
  1104. });
  1105. it("returns false when note is not found", () => {
  1106. mockExecuteAppleScript.mockReturnValue({
  1107. success: false,
  1108. output: "",
  1109. error: "Note not found",
  1110. });
  1111. const result = manager.isNotePasswordProtected("Missing Note");
  1112. expect(result).toBe(false);
  1113. });
  1114. });
  1115. describe("isNotePasswordProtectedById", () => {
  1116. it("returns true when note is password-protected", () => {
  1117. mockExecuteAppleScript.mockReturnValue({
  1118. success: true,
  1119. output: [
  1120. "Locked Note",
  1121. "x-coredata://ABC/ICNote/p1",
  1122. "Monday, January 1, 2024 at 12:00:00 PM",
  1123. "Monday, January 1, 2024 at 12:00:00 PM",
  1124. "false",
  1125. "true",
  1126. ].join(F),
  1127. });
  1128. const result = manager.isNotePasswordProtectedById("x-coredata://ABC/ICNote/p1");
  1129. expect(result).toBe(true);
  1130. });
  1131. it("returns false when note is not password-protected", () => {
  1132. mockExecuteAppleScript.mockReturnValue({
  1133. success: true,
  1134. output: [
  1135. "Open Note",
  1136. "x-coredata://ABC/ICNote/p2",
  1137. "Monday, January 1, 2024 at 12:00:00 PM",
  1138. "Monday, January 1, 2024 at 12:00:00 PM",
  1139. "false",
  1140. "false",
  1141. ].join(F),
  1142. });
  1143. const result = manager.isNotePasswordProtectedById("x-coredata://ABC/ICNote/p2");
  1144. expect(result).toBe(false);
  1145. });
  1146. it("returns false when note is not found", () => {
  1147. mockExecuteAppleScript.mockReturnValue({
  1148. success: false,
  1149. output: "",
  1150. error: "Note not found",
  1151. });
  1152. const result = manager.isNotePasswordProtectedById(
  1153. "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
  1154. );
  1155. expect(result).toBe(false);
  1156. });
  1157. });
  1158. // ---------------------------------------------------------------------------
  1159. // Get Note By ID
  1160. // ---------------------------------------------------------------------------
  1161. describe("readNoteById", () => {
  1162. const id = "x-coredata://ABC123/ICNote/p100";
  1163. it("retains all successful metadata, including the password flag", () => {
  1164. mockExecuteAppleScript.mockReturnValue({
  1165. success: true,
  1166. output: [
  1167. "Locked note",
  1168. id,
  1169. "2026-10-12-10-20-0",
  1170. "2026-10-12-11-30-0",
  1171. "true",
  1172. "true",
  1173. ].join(F),
  1174. });
  1175. expect(manager.readNoteById(id)).toEqual({
  1176. note: {
  1177. id,
  1178. title: "Locked note",
  1179. content: "",
  1180. tags: [],
  1181. created: new Date(2026, 9, 12, 10, 20, 0),
  1182. modified: new Date(2026, 9, 12, 11, 30, 0),
  1183. shared: true,
  1184. passwordProtected: true,
  1185. },
  1186. });
  1187. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  1188. expect(mockExecuteAppleScript.mock.calls[0][0]).not.toContain("get body");
  1189. });
  1190. it.each([
  1191. "Not authorized to send Apple events to Notes. (-1743)",
  1192. "Operation timed out after 30 seconds",
  1193. "Lost connection to Notes.app",
  1194. "spawnSync osascript EACCES",
  1195. "spawnSync osascript EACCES: Operation not permitted",
  1196. "Can't get note id",
  1197. "Note not found. The note may have been deleted or the ID is invalid.",
  1198. ])("preserves executor failure %j while the legacy getter stays nullable", (error) => {
  1199. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error });
  1200. expect(manager.readNoteById(id)).toEqual({ note: null, error });
  1201. expect(manager.getNoteById(id)).toBeNull();
  1202. });
  1203. it.each([undefined, "", " "])(
  1204. "supplies a diagnostic when the executor has no error: %j",
  1205. (error) => {
  1206. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error });
  1207. expect(manager.readNoteById(id)).toEqual({
  1208. note: null,
  1209. error: "AppleScript note metadata read failed",
  1210. });
  1211. expect(manager.getNoteById(id)).toBeNull();
  1212. }
  1213. );
  1214. it("reports malformed metadata without echoing its contents or claiming absence", () => {
  1215. mockExecuteAppleScript.mockReturnValue({
  1216. success: true,
  1217. output: 'Private "timed out -1743" note not found',
  1218. });
  1219. expect(manager.readNoteById(id)).toEqual({
  1220. note: null,
  1221. error: "Unexpected note metadata response",
  1222. });
  1223. expect(manager.getNoteById(id)).toBeNull();
  1224. });
  1225. it("preserves invalid-ID rejection before either metadata reader runs", () => {
  1226. expect(() => manager.readNoteById('invalid" id')).toThrow();
  1227. expect(() => manager.getNoteById('invalid" id')).toThrow();
  1228. expect(mockExecuteAppleScript).not.toHaveBeenCalled();
  1229. });
  1230. });
  1231. describe("getNoteById", () => {
  1232. it("returns Note object with metadata for valid ID", () => {
  1233. mockExecuteAppleScript.mockReturnValue({
  1234. success: true,
  1235. output: [
  1236. "My Note",
  1237. "x-coredata://ABC123/ICNote/p100",
  1238. "Saturday, December 27, 2025 at 3:00:00 PM",
  1239. "Saturday, December 27, 2025 at 4:00:00 PM",
  1240. "false",
  1241. "false",
  1242. ].join(F),
  1243. });
  1244. const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
  1245. expect(result).not.toBeNull();
  1246. expect(result?.title).toBe("My Note");
  1247. expect(result?.id).toBe("x-coredata://ABC123/ICNote/p100");
  1248. expect(result?.shared).toBe(false);
  1249. expect(result?.passwordProtected).toBe(false);
  1250. });
  1251. it("returns null when note ID not found", () => {
  1252. mockExecuteAppleScript.mockReturnValue({
  1253. success: false,
  1254. output: "",
  1255. error: "Can't get note id",
  1256. });
  1257. const result = manager.getNoteById(
  1258. "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
  1259. );
  1260. expect(result).toBeNull();
  1261. });
  1262. it("returns null when response format is unexpected (no commas)", () => {
  1263. mockExecuteAppleScript.mockReturnValue({
  1264. success: true,
  1265. output: "incomplete data with no commas",
  1266. });
  1267. const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
  1268. expect(result).toBeNull();
  1269. });
  1270. it("returns null when response format is missing second comma", () => {
  1271. mockExecuteAppleScript.mockReturnValue({
  1272. success: true,
  1273. output: "title only, no more data",
  1274. });
  1275. const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
  1276. // The new parsing requires at least title and ID separated by commas
  1277. expect(result).toBeNull();
  1278. });
  1279. it("correctly parses shared and passwordProtected as true", () => {
  1280. mockExecuteAppleScript.mockReturnValue({
  1281. success: true,
  1282. output: [
  1283. "Shared Note",
  1284. "x-coredata://ABC/ICNote/p1",
  1285. "Monday, January 1, 2025 at 12:00:00 PM",
  1286. "Monday, January 1, 2025 at 12:00:00 PM",
  1287. "true",
  1288. "true",
  1289. ].join(F),
  1290. });
  1291. const result = manager.getNoteById("x-coredata://ABC/ICNote/p1");
  1292. expect(result?.shared).toBe(true);
  1293. expect(result?.passwordProtected).toBe(true);
  1294. });
  1295. });
  1296. // ---------------------------------------------------------------------------
  1297. // Get Note Details
  1298. // ---------------------------------------------------------------------------
  1299. describe("getNoteDetails", () => {
  1300. it("returns Note object with full metadata", () => {
  1301. mockExecuteAppleScript.mockReturnValue({
  1302. success: true,
  1303. output: [
  1304. "Project Notes",
  1305. "x-coredata://ABC123/ICNote/p200",
  1306. "Friday, December 20, 2025 at 10:00:00 AM",
  1307. "Saturday, December 27, 2025 at 2:30:00 PM",
  1308. "false",
  1309. "false",
  1310. ].join(F),
  1311. });
  1312. const result = manager.getNoteDetails("Project Notes");
  1313. expect(result).not.toBeNull();
  1314. expect(result?.title).toBe("Project Notes");
  1315. expect(result?.id).toBe("x-coredata://ABC123/ICNote/p200");
  1316. });
  1317. it("returns null when note not found", () => {
  1318. mockExecuteAppleScript.mockReturnValue({
  1319. success: false,
  1320. output: "",
  1321. error: "Can't get note",
  1322. });
  1323. const result = manager.getNoteDetails("Nonexistent");
  1324. expect(result).toBeNull();
  1325. });
  1326. it("uses specified account", () => {
  1327. mockExecuteAppleScript.mockReturnValue({
  1328. success: true,
  1329. output: [
  1330. "Note",
  1331. "id123",
  1332. "Monday, January 1, 2025 at 12:00:00 PM",
  1333. "Monday, January 1, 2025 at 12:00:00 PM",
  1334. "false",
  1335. "false",
  1336. ].join(F),
  1337. });
  1338. const result = manager.getNoteDetails("My Note", "Exchange");
  1339. expect(result?.account).toBe("Exchange");
  1340. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1341. expect.stringContaining('every account whose name is "Exchange"')
  1342. );
  1343. });
  1344. it("handles shared notes correctly", () => {
  1345. mockExecuteAppleScript.mockReturnValue({
  1346. success: true,
  1347. output: [
  1348. "Shared Doc",
  1349. "id456",
  1350. "Monday, January 1, 2025 at 12:00:00 PM",
  1351. "Monday, January 1, 2025 at 12:00:00 PM",
  1352. "true",
  1353. "false",
  1354. ].join(F),
  1355. });
  1356. const result = manager.getNoteDetails("Shared Doc");
  1357. expect(result?.shared).toBe(true);
  1358. });
  1359. });
  1360. describe("updateNoteByIdIfUnchanged", () => {
  1361. const id = "x-coredata://ABC00000-0000-0000-0000-000000000003/ICNote/p789";
  1362. const oldBody = "<div>Title</div><div>Old body</div>";
  1363. it("checks body identity and attachments in the same AppleScript before writing", () => {
  1364. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_UPDATED" });
  1365. const result = manager.updateNoteByIdIfUnchanged(id, "Title", oldBody, undefined, "New body");
  1366. expect(result.status).toBe("updated");
  1367. expect(result.writtenBody).toBe("<div>Title</div><div>New body</div>");
  1368. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1369. expect(script).toContain("count of attachments of noteRef");
  1370. expect(script).toContain("currentBody is not");
  1371. expect(script).toContain(
  1372. 'currentBody is not "<div>Title</div><div>Old body</div>" & linefeed'
  1373. );
  1374. expect(script.indexOf("count of attachments of noteRef")).toBeLessThan(
  1375. script.indexOf("set body of noteRef")
  1376. );
  1377. expect(script.indexOf("currentBody is not")).toBeLessThan(
  1378. script.indexOf("set body of noteRef")
  1379. );
  1380. // AppleScript's `is`/`is not` is case-insensitive by default, so a
  1381. // case-only concurrent edit would otherwise slip past the conflict
  1382. // guard. `considering case` must wrap the comparison (and the write,
  1383. // so a false-equal never reaches `set body of noteRef`).
  1384. expect(script.indexOf("considering case")).toBeLessThan(script.indexOf("currentBody is not"));
  1385. expect(script.indexOf("set body of noteRef")).toBeLessThan(script.indexOf("end considering"));
  1386. expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), NO_RETRY_OPTIONS);
  1387. });
  1388. it("reports a conflict without claiming an update", () => {
  1389. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_CONFLICT" });
  1390. const result = manager.updateNoteByIdIfUnchanged(
  1391. id,
  1392. "Title",
  1393. oldBody,
  1394. undefined,
  1395. "Stale body"
  1396. );
  1397. expect(result).toEqual({ status: "conflict" });
  1398. });
  1399. it("reports attachments without claiming an update", () => {
  1400. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_ATTACHMENTS" });
  1401. const result = manager.updateNoteByIdIfUnchanged(
  1402. id,
  1403. "Title",
  1404. oldBody,
  1405. undefined,
  1406. "Replacement"
  1407. );
  1408. expect(result).toEqual({ status: "attachments" });
  1409. });
  1410. });
  1411. describe("deleteNoteByIdIfUnchanged", () => {
  1412. const id = "x-coredata://ABC00000-0000-0000-0000-000000000004/ICNote/p790";
  1413. it("compares the exact body in the same AppleScript before deleting", () => {
  1414. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
  1415. const result = manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>");
  1416. expect(result.status).toBe("deleted");
  1417. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1418. expect(script).toContain("currentBody is not");
  1419. expect(script.indexOf("currentBody is not")).toBeLessThan(script.indexOf("delete noteRef"));
  1420. expect(script.indexOf("considering case")).toBeLessThan(script.indexOf("currentBody is not"));
  1421. expect(script.indexOf("delete noteRef")).toBeLessThan(script.indexOf("end considering"));
  1422. expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), NO_RETRY_OPTIONS);
  1423. });
  1424. it("rejects deletion when the reviewed body is stale", () => {
  1425. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_CONFLICT" });
  1426. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Old body</div>")).toEqual({
  1427. status: "conflict",
  1428. });
  1429. });
  1430. it("reports a delete that left the note in its original folder", () => {
  1431. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_NOT_DELETED" });
  1432. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>")).toEqual({
  1433. status: "not-deleted",
  1434. });
  1435. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1436. // The folder is captured before the delete and re-read after it.
  1437. expect(script.indexOf("container of noteRef")).toBeLessThan(script.indexOf("delete noteRef"));
  1438. expect(script.indexOf("delete noteRef")).toBeLessThan(
  1439. script.indexOf("id of notes of originalFolder")
  1440. );
  1441. });
  1442. // #195: a failed placement re-read is not evidence the note left its folder.
  1443. it("reports an unverified delete when the placement re-read fails", () => {
  1444. mockExecuteAppleScript.mockReturnValue({
  1445. success: true,
  1446. output: "SAFETY_DELETE_UNVERIFIED",
  1447. });
  1448. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>")).toEqual({
  1449. status: "unverified",
  1450. });
  1451. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1452. const recheck = script.slice(script.indexOf("delete noteRef"));
  1453. expect(recheck).toMatch(
  1454. /if __stillThere is missing value then return "SAFETY_DELETE_UNVERIFIED"/
  1455. );
  1456. expect(recheck.indexOf("SAFETY_DELETE_UNVERIFIED")).toBeLessThan(
  1457. recheck.indexOf('return "SAFETY_DELETED"')
  1458. );
  1459. });
  1460. it("generates a delete script that AppleScript compiles", () => {
  1461. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
  1462. manager.deleteNoteByIdIfUnchanged(id, '<div>Body with "quotes" and \\ slash</div>');
  1463. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1464. const dir = mkdtempSync(join(tmpdir(), "delete-script-"));
  1465. try {
  1466. writeFileSync(join(dir, "delete.applescript"), script);
  1467. expect(() =>
  1468. execFileSync(
  1469. "/usr/bin/osacompile",
  1470. ["-o", join(dir, "delete.scpt"), join(dir, "delete.applescript")],
  1471. { stdio: "pipe" }
  1472. )
  1473. ).not.toThrow();
  1474. } finally {
  1475. rmSync(dir, { recursive: true, force: true });
  1476. }
  1477. });
  1478. });
  1479. // ---------------------------------------------------------------------------
  1480. // Note Listing
  1481. // ---------------------------------------------------------------------------
  1482. describe("listNotes", () => {
  1483. it("returns array of note titles", () => {
  1484. mockExecuteAppleScript.mockReturnValue({
  1485. success: true,
  1486. output: [
  1487. ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
  1488. ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
  1489. ["Note C", "x-coredata://ABC/ICNote/p3"].join(F),
  1490. ].join(R),
  1491. });
  1492. const titles = manager.listNotes();
  1493. expect(titles).toEqual(["Note A", "Note B", "Note C"]);
  1494. });
  1495. it("filters out empty entries", () => {
  1496. mockExecuteAppleScript.mockReturnValue({
  1497. success: true,
  1498. output: [
  1499. ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
  1500. "",
  1501. ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
  1502. "",
  1503. "",
  1504. ].join(R),
  1505. });
  1506. const titles = manager.listNotes();
  1507. expect(titles).toEqual(["Note A", "Note B"]);
  1508. });
  1509. it("deduplicates duplicate note IDs while preserving separate notes with the same title", () => {
  1510. mockExecuteAppleScript.mockReturnValue({
  1511. success: true,
  1512. output: [
  1513. ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
  1514. ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
  1515. ["Same Title", "x-coredata://ABC/ICNote/p2"].join(F),
  1516. ].join(R),
  1517. });
  1518. const titles = manager.listNotes();
  1519. expect(titles).toEqual(["Same Title", "Same Title"]);
  1520. });
  1521. it("throws on failure rather than returning empty (#19)", () => {
  1522. mockExecuteAppleScript.mockReturnValue({
  1523. success: false,
  1524. output: "",
  1525. error: "Account not found",
  1526. });
  1527. expect(() => manager.listNotes()).toThrow(/Account not found/);
  1528. });
  1529. it("filters by folder when specified", () => {
  1530. mockExecuteAppleScript.mockReturnValue({
  1531. success: true,
  1532. output: [
  1533. ["Work Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
  1534. ["Work Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
  1535. ].join(R),
  1536. });
  1537. manager.listNotes("iCloud", "Work");
  1538. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  1539. expect.stringContaining('notes of folder "Work"')
  1540. );
  1541. });
  1542. it("filters by bulk-fetched modification dates when modifiedSince is provided", () => {
  1543. mockExecuteAppleScript.mockReturnValue({
  1544. success: true,
  1545. output: [
  1546. ["Recent Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
  1547. ["Recent Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
  1548. ].join(R),
  1549. });
  1550. const results = manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
  1551. const script = mockExecuteAppleScript.mock.calls[0][0];
  1552. // Locale-safe: variable setup + local comparison over bulk-fetched
  1553. // dates (whose clauses evaluate per-note server-side and are slow)
  1554. expect(script).toContain("set thresholdDate to current date");
  1555. expect(script).toContain("set year of thresholdDate to 2025");
  1556. expect(script).toContain("set month of thresholdDate to 6");
  1557. expect(script).toContain("set day of thresholdDate to 15");
  1558. expect(script).toContain("set noteDates to modification date of notes");
  1559. expect(script).toContain("if (item i of noteDates) >= thresholdDate then");
  1560. expect(results).toEqual(["Recent Note 1", "Recent Note 2"]);
  1561. });
  1562. it("slices the AppleScript fetch to the limit and returns a totalCount header", () => {
  1563. // Sliced response: totalCount header record, then limit records.
  1564. mockExecuteAppleScript.mockReturnValue({
  1565. success: true,
  1566. output: [
  1567. "10",
  1568. ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
  1569. ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
  1570. ["Note 3", "x-coredata://ABC/ICNote/p3"].join(F),
  1571. ].join(R),
  1572. });
  1573. const results = manager.listNotes(undefined, undefined, undefined, 3);
  1574. // One sliced call satisfies the limit — no full-fetch fallback.
  1575. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  1576. const script = mockExecuteAppleScript.mock.calls[0][0];
  1577. expect(script).toContain("set totalCount to count of notes");
  1578. expect(script).toContain("set fetchCount to 3");
  1579. expect(script).toContain("set noteNames to name of (notes 1 thru fetchCount)");
  1580. expect(script).toContain("set noteIds to id of (notes 1 thru fetchCount)");
  1581. expect(results).toEqual(["Note 1", "Note 2", "Note 3"]);
  1582. });
  1583. it("returns short slice without fallback when the library is smaller than the limit", () => {
  1584. mockExecuteAppleScript.mockReturnValue({
  1585. success: true,
  1586. output: ["2", ["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
  1587. });
  1588. const results = manager.listNotes(undefined, undefined, undefined, 5);
  1589. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  1590. expect(results).toEqual(["Note 1", "Note 2"]);
  1591. });
  1592. it("falls back to a full fetch when dedup leaves the slice short of the limit", () => {
  1593. // Slice of 3 contains a duplicated id -> only 2 uniques, but 10 total
  1594. // notes exist, so later uniques may have been hidden by the duplicate.
  1595. mockExecuteAppleScript
  1596. .mockReturnValueOnce({
  1597. success: true,
  1598. output: [
  1599. "10",
  1600. ["Note 1", "p1"].join(F),
  1601. ["Note 1 dup", "p1"].join(F),
  1602. ["Note 2", "p2"].join(F),
  1603. ].join(R),
  1604. })
  1605. .mockReturnValueOnce({
  1606. success: true,
  1607. output: [
  1608. ["Note 1", "p1"].join(F),
  1609. ["Note 2", "p2"].join(F),
  1610. ["Note 3", "p3"].join(F),
  1611. ["Note 4", "p4"].join(F),
  1612. ].join(R),
  1613. });
  1614. const results = manager.listNotes(undefined, undefined, undefined, 3);
  1615. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
  1616. // Fallback is the unsliced full fetch.
  1617. const fallbackScript = mockExecuteAppleScript.mock.calls[1][0];
  1618. expect(fallbackScript).not.toContain("thru fetchCount");
  1619. expect(fallbackScript).toContain("set noteNames to name of notes");
  1620. expect(results).toEqual(["Note 1", "Note 2", "Note 3"]);
  1621. });
  1622. it("falls back to a full fetch when the slice header is malformed", () => {
  1623. mockExecuteAppleScript
  1624. .mockReturnValueOnce({
  1625. success: true,
  1626. // No totalCount header — should not be trusted as a sliced response.
  1627. output: [["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
  1628. })
  1629. .mockReturnValueOnce({
  1630. success: true,
  1631. output: [["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
  1632. });
  1633. const results = manager.listNotes(undefined, undefined, undefined, 5);
  1634. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
  1635. expect(results).toEqual(["Note 1", "Note 2"]);
  1636. });
  1637. it("returns empty from an empty sliced library without fallback", () => {
  1638. mockExecuteAppleScript.mockReturnValue({ success: true, output: `0${R}` });
  1639. const results = manager.listNotes(undefined, undefined, undefined, 3);
  1640. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  1641. expect(results).toEqual([]);
  1642. });
  1643. it("guards every bulk list against mid-listing library mutation", () => {
  1644. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  1645. // Unfiltered full fetch: names/ids count guard.
  1646. manager.listNotes();
  1647. const fullScript = mockExecuteAppleScript.mock.calls[0][0];
  1648. expect(fullScript).toContain(
  1649. 'if (count of noteIds) is not (count of noteNames) then error "Notes changed during listing"'
  1650. );
  1651. // Date-filtered fetch adds the dates count guard.
  1652. manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
  1653. const dateScript = mockExecuteAppleScript.mock.calls[1][0];
  1654. expect(dateScript).toContain(
  1655. 'if (count of noteDates) is not (count of noteNames) then error "Notes changed during listing"'
  1656. );
  1657. // Sliced fetch guards and remaps a shrink between count and fetch —
  1658. // but ONLY the out-of-range error numbers. Timeouts (-1712), lost
  1659. // connection, and permission errors must be rethrown unchanged so
  1660. // their honest messages and remedies survive.
  1661. manager.listNotes(undefined, undefined, undefined, 3);
  1662. const sliceScript = mockExecuteAppleScript.mock.calls[2][0];
  1663. expect(sliceScript).toContain(
  1664. 'if (count of noteIds) is not (count of noteNames) then error "Notes changed during listing"'
  1665. );
  1666. expect(sliceScript).toContain("on error errMsg number errNum");
  1667. expect(sliceScript).toContain("if errNum is -1719 or errNum is -1728 then");
  1668. expect(sliceScript).toContain('error "Notes changed during listing"');
  1669. expect(sliceScript).toContain("error errMsg number errNum");
  1670. });
  1671. it("combines folder, modifiedSince, and limit", () => {
  1672. mockExecuteAppleScript.mockReturnValue({
  1673. success: true,
  1674. output: [
  1675. ["Work Note", "x-coredata://ABC/ICNote/p1"].join(F),
  1676. ["Another Work Note", "x-coredata://ABC/ICNote/p2"].join(F),
  1677. ].join(R),
  1678. });
  1679. manager.listNotes("iCloud", "Work", "2025-01-01", 10);
  1680. const script = mockExecuteAppleScript.mock.calls[0][0];
  1681. expect(script).toContain('notes of folder "Work"');
  1682. expect(script).toContain('set noteDates to modification date of notes of folder "Work"');
  1683. expect(script).toContain('set noteNames to name of notes of folder "Work"');
  1684. });
  1685. it("returns empty array when modifiedSince yields no results", () => {
  1686. mockExecuteAppleScript.mockReturnValue({
  1687. success: true,
  1688. output: "",
  1689. });
  1690. const results = manager.listNotes(undefined, undefined, "2099-01-01");
  1691. expect(results).toEqual([]);
  1692. });
  1693. it("ignores invalid modifiedSince date and falls back to limit-only", () => {
  1694. mockExecuteAppleScript.mockReturnValue({
  1695. success: true,
  1696. output: [
  1697. "2",
  1698. ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
  1699. ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
  1700. ].join(R),
  1701. });
  1702. const results = manager.listNotes(undefined, undefined, "not-a-date", 5);
  1703. // Invalid date means no date filter, so the limit-only slice path runs.
  1704. const script = mockExecuteAppleScript.mock.calls[0][0];
  1705. expect(script).not.toContain("thresholdDate");
  1706. expect(script).toContain("set noteNames to name of (notes 1 thru fetchCount)");
  1707. expect(results).toEqual(["Note 1", "Note 2"]);
  1708. });
  1709. });
  1710. describe("large-library listing (#162)", () => {
  1711. // `ASCII character` is a Standard Additions command: inside a Notes tell
  1712. // block each evaluation is its own Apple Event (~8.5 ms measured), so a
  1713. // per-record separator cost two round trips per note.
  1714. it("builds every per-note record with local separators, never an Apple Event per record", () => {
  1715. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  1716. manager.listNotes();
  1717. manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
  1718. manager.listNotes(undefined, undefined, undefined, 3);
  1719. expect(mockExecuteAppleScript.mock.calls.length).toBeGreaterThanOrEqual(3);
  1720. for (const [script] of mockExecuteAppleScript.mock.calls) {
  1721. expect(script).not.toContain("ASCII character");
  1722. expect(script).toContain("(character id 31)");
  1723. expect(script).toContain("(character id 30)");
  1724. }
  1725. });
  1726. it("reads the whole collection, not a range, when the limit covers the library", () => {
  1727. mockExecuteAppleScript.mockReturnValue({
  1728. success: true,
  1729. output: ["2", ["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
  1730. });
  1731. const results = manager.listNotes("iCloud", undefined, undefined, 700);
  1732. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  1733. const script = mockExecuteAppleScript.mock.calls[0][0];
  1734. expect(script).toMatch(
  1735. /if fetchCount is totalCount then\s+set noteNames to name of notes\s+set noteIds to id of notes\s+else\s+set noteNames to name of \(notes 1 thru fetchCount\)/
  1736. );
  1737. expect(results).toEqual(["Note 1", "Note 2"]);
  1738. });
  1739. });
  1740. describe("separators in every generated script (#162)", () => {
  1741. // Every script below runs inside a `tell application "Notes"` block, where
  1742. // each `ASCII character` evaluation is dispatched to Notes.app as its own
  1743. // Apple Event. Search, folder, account and stats scripts build one record
  1744. // per item, so the separators must be `character id`, evaluated locally.
  1745. const NOTE_ID = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICNote/p1";
  1746. const FOLDER_ID = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICFolder/p2";
  1747. const scriptsFor = (call: () => unknown): string[] => {
  1748. mockExecuteAppleScript.mockReset();
  1749. mockExecuteAppleScript.mockImplementation((script: string) => ({
  1750. success: true,
  1751. // listAccounts feeds the per-account stats and shared-notes scripts.
  1752. output: script.includes("repeat with a in accounts") ? "iCloud" : "",
  1753. }));
  1754. try {
  1755. call();
  1756. } catch {
  1757. // Empty output makes some parsers throw; only the scripts matter here.
  1758. }
  1759. return mockExecuteAppleScript.mock.calls.map(([script]) => String(script));
  1760. };
  1761. it.each<[string, () => unknown, string[]]>([
  1762. ["searchNotes (title)", () => manager.searchNotes("the"), ["31", "30"]],
  1763. ["searchNotes (content)", () => manager.searchNotes("the", true), ["31", "30"]],
  1764. ["listFolders", () => manager.listFolders(), ["31", "30"]],
  1765. ["listAccounts", () => manager.listAccounts(), ["31", "30"]],
  1766. ["getNotesStats", () => manager.getNotesStats(), ["31", "30"]],
  1767. ["getSelectedNotes", () => manager.getSelectedNotes(), ["31", "30"]],
  1768. ["getDefaultLocation", () => manager.getDefaultLocation(), ["31"]],
  1769. ["getNoteById", () => manager.getNoteById(NOTE_ID), ["31"]],
  1770. ["getNoteDetails", () => manager.getNoteDetails("Groceries"), ["31"]],
  1771. ["getFolderById", () => manager.getFolderById(FOLDER_ID), ["31"]],
  1772. ["createFolder", () => manager.createFolder("Archive"), ["31"]],
  1773. ["listAttachmentsById", () => manager.listAttachmentsById(NOTE_ID), ["31", "30"]],
  1774. ["listAttachments", () => manager.listAttachments("Groceries"), ["31", "30"]],
  1775. ["showAttachmentById", () => manager.showAttachmentById(NOTE_ID, "att-1"), ["31"]],
  1776. [
  1777. "saveAttachmentById",
  1778. () => manager.saveAttachmentById(NOTE_ID, "att-1", join(tmpdir(), "x.png")),
  1779. ["31"],
  1780. ],
  1781. ["batchMoveNotes", () => manager.batchMoveNotes([NOTE_ID], "Archive"), ["30"]],
  1782. ["listNotes", () => manager.listNotes(), ["31", "30"]],
  1783. ["listSharedNotes", () => manager.listSharedNotes(), ["31", "30"]],
  1784. ])("%s never emits ASCII character", (_name, call, codes) => {
  1785. const scripts = scriptsFor(call);
  1786. const all = scripts.join("\n");
  1787. expect(scripts.length).toBeGreaterThan(0);
  1788. expect(all).not.toContain("ASCII character");
  1789. for (const code of codes) {
  1790. expect(all).toContain(`(character id ${code})`);
  1791. }
  1792. });
  1793. });
  1794. describe("listSharedNotes", () => {
  1795. it("reads sharing state in one bulk read and stops there when nothing is shared", () => {
  1796. mockExecuteAppleScript
  1797. .mockReturnValueOnce({ success: true, output: "iCloud" }) // listAccounts
  1798. .mockReturnValueOnce({ success: true, output: "" });
  1799. expect(manager.listSharedNotes()).toEqual([]);
  1800. const script = mockExecuteAppleScript.mock.calls[1][0];
  1801. expect(script).toContain("set noteShared to shared of notes");
  1802. expect(script).toContain("if noteShared contains true then");
  1803. expect(script).not.toContain("repeat with n in notes");
  1804. expect(script).not.toContain("ASCII character");
  1805. });
  1806. it("parses shared notes built from bulk-read properties", () => {
  1807. mockExecuteAppleScript
  1808. .mockReturnValueOnce({ success: true, output: "iCloud" })
  1809. .mockReturnValueOnce({
  1810. success: true,
  1811. output: [
  1812. "Team plan",
  1813. "x-coredata://ABC/ICNote/p7",
  1814. "2025-1-2-3-4-5",
  1815. "2025-6-7-8-9-10",
  1816. "true",
  1817. "false",
  1818. ].join(F),
  1819. });
  1820. const notes = manager.listSharedNotes();
  1821. expect(notes).toHaveLength(1);
  1822. expect(notes[0]).toMatchObject({
  1823. id: "x-coredata://ABC/ICNote/p7",
  1824. title: "Team plan",
  1825. account: "iCloud",
  1826. shared: true,
  1827. passwordProtected: false,
  1828. });
  1829. expect(notes[0].modified.getMonth()).toBe(5);
  1830. const script = mockExecuteAppleScript.mock.calls[1][0];
  1831. expect(script).toContain(
  1832. 'if (count of noteIds) is not (count of noteShared) then error "Notes changed during listing"'
  1833. );
  1834. });
  1835. it("reports a note Notes enumerates twice only once, in first-seen order (#183)", () => {
  1836. const row = (title: string, id: string) =>
  1837. [title, id, "2025-1-2-3-4-5", "2025-6-7-8-9-10", "true", "false"].join(F);
  1838. mockExecuteAppleScript
  1839. .mockReturnValueOnce({ success: true, output: "iCloud" })
  1840. .mockReturnValueOnce({
  1841. success: true,
  1842. output: [
  1843. row("Team plan", "x-coredata://ABC/ICNote/p7"),
  1844. row("Budget", "x-coredata://ABC/ICNote/p8"),
  1845. row("Team plan", "x-coredata://ABC/ICNote/p7"),
  1846. ].join(R),
  1847. });
  1848. expect(manager.listSharedNotes().map((note) => note.id)).toEqual([
  1849. "x-coredata://ABC/ICNote/p7",
  1850. "x-coredata://ABC/ICNote/p8",
  1851. ]);
  1852. });
  1853. });
  1854. describe("deleteNoteByIdIfUnchanged guard notes (copy-then-retire)", () => {
  1855. const id = "x-coredata://ABC/ICNote/p1";
  1856. const copy = "x-coredata://ABC/ICNote/p2";
  1857. const other = "x-coredata://ABC/ICNote/p3";
  1858. const guards = [{ id: copy, expectedBody: '<div>Copy with "quotes"</div>' }, { id: other }];
  1859. it("checks every guard live, after the source trash check and before the delete", () => {
  1860. mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
  1861. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
  1862. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
  1863. status: "deleted",
  1864. });
  1865. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  1866. const sourceTrash = script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"');
  1867. const guardStart = script.indexOf(`exists note id "${copy}"`);
  1868. expect(guardStart).toBeGreaterThan(sourceTrash);
  1869. for (const needle of [
  1870. 'return "SAFETY_GUARD_INACTIVE:0:missing"',
  1871. "if password protected of __guardRef0",
  1872. 'return "SAFETY_GUARD_INACTIVE:0:locked"',
  1873. 'return "SAFETY_GUARD_INACTIVE:0:folder unknown"',
  1874. "if (class of __guardFolder0) is folder then set __guardInTrash to false",
  1875. `{"${TRASH_FOLDER}"} contains (id of __guardFolder0)`,
  1876. '(name of __guardFolder0) is "Recently Deleted"',
  1877. 'return "SAFETY_GUARD_INACTIVE:0:in Recently Deleted"',
  1878. 'return "SAFETY_GUARD_CONFLICT:0"',
  1879. // The target cannot guard its own delete, however its id was spelled (#214).
  1880. 'if (id of __guardRef0) is (id of noteRef) then return "SAFETY_GUARD_INACTIVE:0:the note being deleted"',
  1881. `exists note id "${other}"`,
  1882. 'return "SAFETY_GUARD_INACTIVE:1:in Recently Deleted"',
  1883. ]) {
  1884. const at = script.indexOf(needle);
  1885. expect(at, needle).toBeGreaterThan(sourceTrash);
  1886. expect(at, needle).toBeLessThan(script.indexOf("delete noteRef"));
  1887. }
  1888. // Only the fingerprinted guard compares its body.
  1889. expect(script).not.toContain("SAFETY_GUARD_CONFLICT:1");
  1890. expect(script).toContain('__guardBody is not "<div>Copy with \\"quotes\\"</div>"');
  1891. expect(() => compilesAsAppleScript(script)).not.toThrow();
  1892. });
  1893. it("maps guard outcomes to their index", () => {
  1894. mockExecuteAppleScript.mockReturnValueOnce({
  1895. success: true,
  1896. output: "SAFETY_GUARD_CONFLICT:0",
  1897. });
  1898. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
  1899. status: "guard-conflict",
  1900. index: 0,
  1901. });
  1902. mockExecuteAppleScript.mockReturnValueOnce({
  1903. success: true,
  1904. output: "SAFETY_GUARD_INACTIVE:1:in Recently Deleted",
  1905. });
  1906. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
  1907. status: "guard-inactive",
  1908. index: 1,
  1909. reason: "in Recently Deleted",
  1910. });
  1911. });
  1912. it("treats a guard outcome for an unknown index as failed", () => {
  1913. mockExecuteAppleScript.mockReturnValueOnce({
  1914. success: true,
  1915. output: "SAFETY_GUARD_INACTIVE:5:missing",
  1916. });
  1917. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
  1918. status: "failed",
  1919. });
  1920. });
  1921. it("rejects an invalid guard id before running anything", () => {
  1922. expect(() =>
  1923. manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, [
  1924. { id: 'x" & do shell script "id' },
  1925. ])
  1926. ).toThrow();
  1927. expect(mockExecuteAppleScript).not.toHaveBeenCalled();
  1928. });
  1929. });
  1930. // A note's body carries its inline images as base64, so one large image makes
  1931. // a body far longer than a script literal should be (#237).
  1932. describe("deleteNoteByIdIfUnchanged with a body too long for a literal (#237)", () => {
  1933. const id = "x-coredata://ABC/ICNote/p1";
  1934. const copy = "x-coredata://ABC/ICNote/p2";
  1935. const largeBody = (marker: string) =>
  1936. `<div>${marker} "quoted" \\ slash é 😀</div><img src="data:image/png;base64,${"A".repeat(5 * 1024 * 1024)}">`;
  1937. const filePaths = (script: string) =>
  1938. [...script.matchAll(/POSIX file "([^"]+)"/g)].map((match) => match[1]);
  1939. it("compares the whole body against a private temporary file, then removes it", () => {
  1940. const body = largeBody("Photo");
  1941. let seen: { script: string; contents: string[]; modes: number[] } | undefined;
  1942. mockExecuteAppleScript.mockImplementation((script: string) => {
  1943. const paths = filePaths(script);
  1944. seen = {
  1945. script,
  1946. contents: paths.map((path) => readFileSync(path, "utf8")),
  1947. modes: paths.map((path) => statSync(path).mode & 0o777),
  1948. };
  1949. return { success: true, output: "SAFETY_DELETED" };
  1950. });
  1951. expect(manager.deleteNoteByIdIfUnchanged(id, body)).toEqual({ status: "deleted" });
  1952. expect(seen!.contents).toEqual([body]);
  1953. expect(seen!.modes).toEqual([0o600]);
  1954. // The script stays small: the body is read from the file, not embedded.
  1955. expect(seen!.script.length).toBeLessThan(10_000);
  1956. expect(seen!.script).toContain(
  1957. 'if currentBody is not __expectedBody and currentBody is not __expectedBody & linefeed then return "SAFETY_CONFLICT"'
  1958. );
  1959. expect(seen!.script.indexOf("set __expectedBody to read")).toBeLessThan(
  1960. seen!.script.indexOf("set currentBody to body of noteRef")
  1961. );
  1962. expect(existsSync(filePaths(seen!.script)[0])).toBe(false);
  1963. });
  1964. it("reads a large guard body from its own file", () => {
  1965. const body = largeBody("Original");
  1966. const guardBody = largeBody("Copy");
  1967. let contents: string[] = [];
  1968. let script = "";
  1969. mockExecuteAppleScript.mockImplementation((text: string) => {
  1970. script = text;
  1971. contents = filePaths(text).map((path) => readFileSync(path, "utf8"));
  1972. return { success: true, output: "SAFETY_GUARD_CONFLICT:0" };
  1973. });
  1974. expect(
  1975. manager.deleteNoteByIdIfUnchanged(id, body, undefined, [
  1976. { id: copy, expectedBody: guardBody },
  1977. ])
  1978. ).toEqual({ status: "guard-conflict", index: 0 });
  1979. expect(contents).toEqual([guardBody, body]);
  1980. expect(script).toContain(
  1981. 'if __guardBody is not __expectedGuardBody0 and __guardBody is not __expectedGuardBody0 & linefeed then return "SAFETY_GUARD_CONFLICT:0"'
  1982. );
  1983. for (const path of filePaths(script)) expect(existsSync(path)).toBe(false);
  1984. });
  1985. it("removes the temporary file when the script run throws", () => {
  1986. let paths: string[] = [];
  1987. mockExecuteAppleScript.mockImplementation((script: string) => {
  1988. paths = filePaths(script);
  1989. throw new Error("osascript failed");
  1990. });
  1991. expect(() => manager.deleteNoteByIdIfUnchanged(id, largeBody("Photo"))).toThrow(
  1992. "osascript failed"
  1993. );
  1994. expect(paths).toHaveLength(1);
  1995. expect(existsSync(paths[0])).toBe(false);
  1996. });
  1997. it("generates a file-backed delete script that AppleScript compiles", () => {
  1998. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
  1999. manager.deleteNoteByIdIfUnchanged(id, largeBody("Photo"), undefined, [
  2000. { id: copy, expectedBody: largeBody("Copy") },
  2001. ]);
  2002. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2003. const dir = mkdtempSync(join(tmpdir(), "delete-script-"));
  2004. try {
  2005. writeFileSync(join(dir, "delete.applescript"), script);
  2006. expect(() =>
  2007. execFileSync(
  2008. "/usr/bin/osacompile",
  2009. ["-o", join(dir, "delete.scpt"), join(dir, "delete.applescript")],
  2010. { stdio: "pipe" }
  2011. )
  2012. ).not.toThrow();
  2013. } finally {
  2014. rmSync(dir, { recursive: true, force: true });
  2015. }
  2016. });
  2017. });
  2018. describe("ExpectedBodies", () => {
  2019. it("embeds a short body as an escaped literal and writes no file", () => {
  2020. const bodies = new ExpectedBodies();
  2021. expect(bodies.bind('<div>Say "hi" \\ there</div>', "__x")).toEqual({
  2022. setup: "",
  2023. operand: '"<div>Say \\"hi\\" \\\\ there</div>"',
  2024. });
  2025. bodies.cleanup();
  2026. bodies.cleanup();
  2027. });
  2028. it("reads a long body back through real osascript byte for byte", () => {
  2029. const body = `<div>Line one "q" \\ é 😀\ttab</div>\n<div>${"B".repeat(5 * 1024 * 1024)}</div>`;
  2030. const bodies = new ExpectedBodies();
  2031. try {
  2032. const { setup, operand } = bodies.bind(body, "__roundTrip");
  2033. expect(operand).toBe("__roundTrip");
  2034. // Inside a Notes tell block, as in the delete script, but without
  2035. // sending Notes anything: the read runs in osascript itself.
  2036. const output = execFileSync("osascript", ["-"], {
  2037. input: `${setup}\nreturn __roundTrip`,
  2038. encoding: "utf8",
  2039. maxBuffer: 64 * 1024 * 1024,
  2040. });
  2041. expect(output).toBe(`${body}\n`);
  2042. } finally {
  2043. bodies.cleanup();
  2044. }
  2045. });
  2046. });
  2047. describe("Recently Deleted (#198, #207)", () => {
  2048. const id = "x-coredata://ABC/ICNote/p1";
  2049. it("delete refuses a note whose folder is Recently Deleted, before deleting", () => {
  2050. mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER, "not-a-folder-id"]);
  2051. mockExecuteAppleScript.mockReturnValue({
  2052. success: true,
  2053. output: "SAFETY_IN_RECENTLY_DELETED",
  2054. });
  2055. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
  2056. status: "in-recently-deleted",
  2057. });
  2058. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2059. // Checked live against Notes.app's container, by database id and by name.
  2060. expect(script).toContain(`{"${TRASH_FOLDER}"} contains (id of originalFolder)`);
  2061. expect(script).not.toContain("not-a-folder-id");
  2062. expect(script).toContain('(name of originalFolder) is "Recently Deleted"');
  2063. expect(script.indexOf("SAFETY_IN_RECENTLY_DELETED")).toBeLessThan(
  2064. script.indexOf("delete noteRef")
  2065. );
  2066. expect(() => compilesAsAppleScript(script)).not.toThrow();
  2067. });
  2068. it("delete refuses a note whose container is not a folder, failing closed (#214)", () => {
  2069. mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
  2070. mockExecuteAppleScript.mockReturnValue({
  2071. success: true,
  2072. output: "SAFETY_IN_RECENTLY_DELETED",
  2073. });
  2074. // Shared by delete-note and batch-delete-notes.
  2075. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
  2076. status: "in-recently-deleted",
  2077. });
  2078. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2079. // In-trash is the default; only a readable folder class clears it, so a
  2080. // non-folder container or an unreadable class both refuse.
  2081. const defaultTrue = script.indexOf("set __inTrash to true");
  2082. const classCheck = script.indexOf(
  2083. "if (class of originalFolder) is folder then set __inTrash to false"
  2084. );
  2085. expect(defaultTrue).toBeGreaterThan(-1);
  2086. expect(classCheck).toBeGreaterThan(defaultTrue);
  2087. // The id and name checks can only set it true afterwards, never clear it.
  2088. expect(script.indexOf("contains (id of originalFolder)")).toBeGreaterThan(classCheck);
  2089. expect(script.slice(script.indexOf("\n", classCheck))).not.toMatch(/set __inTrash to false/);
  2090. expect(classCheck).toBeLessThan(script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"'));
  2091. expect(script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"')).toBeLessThan(
  2092. script.indexOf("delete noteRef")
  2093. );
  2094. expect(() => compilesAsAppleScript(script)).not.toThrow();
  2095. });
  2096. it("delete refuses a note whose container cannot be read, failing closed", () => {
  2097. mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
  2098. mockExecuteAppleScript.mockReturnValue({
  2099. success: true,
  2100. output: "SAFETY_CONTAINER_UNKNOWN",
  2101. });
  2102. // Shared by delete-note and batch-delete-notes.
  2103. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
  2104. status: "container-unknown",
  2105. });
  2106. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2107. const refusal = script.indexOf(
  2108. 'if originalFolder is missing value then return "SAFETY_CONTAINER_UNKNOWN"'
  2109. );
  2110. expect(refusal).toBeGreaterThan(script.indexOf("set originalFolder to container of noteRef"));
  2111. expect(refusal).toBeLessThan(script.indexOf("set __inTrash to true"));
  2112. expect(refusal).toBeLessThan(script.indexOf("delete noteRef"));
  2113. // No path reaches the delete with an unread container any more.
  2114. expect(script).not.toContain("originalFolder is not missing value");
  2115. expect(() => compilesAsAppleScript(script)).not.toThrow();
  2116. });
  2117. it("delete still checks the folder name without database access", () => {
  2118. mockReadTrashFolderIds.mockReturnValue([]);
  2119. mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
  2120. expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>").status).toBe("deleted");
  2121. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2122. expect(script).toContain("{} contains (id of originalFolder)");
  2123. expect(script).toContain('(name of originalFolder) is "Recently Deleted"');
  2124. expect(() => compilesAsAppleScript(script)).not.toThrow();
  2125. });
  2126. it("list excludes notes Notes.app reports in Recently Deleted", () => {
  2127. mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
  2128. mockExecuteAppleScript.mockReturnValue({
  2129. success: true,
  2130. output:
  2131. [["Live", id].join(F), ["Gone", "x-coredata://ABC/ICNote/p2"].join(F)].join(R) +
  2132. G +
  2133. ["x-coredata://ABC/ICNote/p2", "x-coredata://ABC/ICNote/p3"].join(R),
  2134. });
  2135. expect(manager.listNoteRefsDetailed()).toEqual({
  2136. refs: [{ title: "Live", id }],
  2137. excludedRecentlyDeleted: 1,
  2138. });
  2139. expect(manager.listNoteRefs()).toEqual([{ title: "Live", id }]);
  2140. expect(manager.listNotes()).toEqual(["Live"]);
  2141. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2142. expect(script).toContain(`repeat with __trashFolderId in {"${TRASH_FOLDER}"}`);
  2143. expect(script).toContain('every folder whose name is "Recently Deleted"');
  2144. expect(script).toContain("(character id 29) & (__trashNoteIds as text)");
  2145. expect(() => compilesAsAppleScript(script)).not.toThrow();
  2146. });
  2147. it("list includes and flags Recently Deleted notes on request", () => {
  2148. mockExecuteAppleScript.mockReturnValue({
  2149. success: true,
  2150. output:
  2151. [["Live", id].join(F), ["Gone", "x-coredata://ABC/ICNote/p2"].join(F)].join(R) +
  2152. G +
  2153. "x-coredata://ABC/ICNote/p2",
  2154. });
  2155. expect(
  2156. manager.listNoteRefsDetailed(undefined, undefined, undefined, undefined, true)
  2157. ).toEqual({
  2158. refs: [
  2159. { title: "Live", id },
  2160. { title: "Gone", id: "x-coredata://ABC/ICNote/p2", inRecentlyDeleted: true },
  2161. ],
  2162. excludedRecentlyDeleted: 0,
  2163. });
  2164. });
  2165. it("an empty trash list excludes nothing", () => {
  2166. mockExecuteAppleScript.mockReturnValue({
  2167. success: true,
  2168. output: ["Live", id].join(F) + G,
  2169. });
  2170. expect(manager.listNoteRefsDetailed()).toEqual({
  2171. refs: [{ title: "Live", id }],
  2172. excludedRecentlyDeleted: 0,
  2173. });
  2174. });
  2175. it("a bounded slice thinned by exclusion falls back to the full listing", () => {
  2176. mockExecuteAppleScript
  2177. .mockReturnValueOnce({
  2178. success: true,
  2179. output:
  2180. "3" +
  2181. R +
  2182. [["Gone", "x-coredata://ABC/ICNote/p2"].join(F), ["Live", id].join(F)].join(R) +
  2183. G +
  2184. "x-coredata://ABC/ICNote/p2",
  2185. })
  2186. .mockReturnValueOnce({
  2187. success: true,
  2188. output:
  2189. [
  2190. ["Gone", "x-coredata://ABC/ICNote/p2"].join(F),
  2191. ["Live", id].join(F),
  2192. ["Also", "x-coredata://ABC/ICNote/p3"].join(F),
  2193. ].join(R) +
  2194. G +
  2195. "x-coredata://ABC/ICNote/p2",
  2196. });
  2197. expect(manager.listNoteRefsDetailed(undefined, undefined, undefined, 2)).toEqual({
  2198. refs: [
  2199. { title: "Live", id },
  2200. { title: "Also", id: "x-coredata://ABC/ICNote/p3" },
  2201. ],
  2202. excludedRecentlyDeleted: 1,
  2203. });
  2204. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
  2205. const sliceScript = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2206. expect(sliceScript).toContain("(character id 29) & (__trashNoteIds as text)");
  2207. expect(() => compilesAsAppleScript(sliceScript)).not.toThrow();
  2208. });
  2209. it("a bounded slice that stays full after exclusion is returned as is", () => {
  2210. mockExecuteAppleScript.mockReturnValueOnce({
  2211. success: true,
  2212. output: "5" + R + ["Live", id].join(F) + G,
  2213. });
  2214. expect(manager.listNoteRefsDetailed(undefined, undefined, undefined, 1)).toEqual({
  2215. refs: [{ title: "Live", id }],
  2216. excludedRecentlyDeleted: 0,
  2217. });
  2218. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  2219. });
  2220. it("smart folder listings carry no trash check", () => {
  2221. mockExecuteAppleScript.mockReturnValue({ success: true, output: "0" + R });
  2222. manager.listSmartFolderNoteRefs("x-coredata://ABC/ICFolder/p4", 5);
  2223. const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
  2224. expect(script).not.toContain("__trashNoteIds");
  2225. });
  2226. });
  2227. describe("listNoteRefs", () => {
  2228. it("returns title/id pairs, not just titles", () => {
  2229. mockExecuteAppleScript.mockReturnValue({
  2230. success: true,
  2231. output: [
  2232. ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
  2233. ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
  2234. ].join(R),
  2235. });
  2236. const refs = manager.listNoteRefs();
  2237. expect(refs).toEqual([
  2238. { title: "Note A", id: "x-coredata://ABC/ICNote/p1" },
  2239. { title: "Note B", id: "x-coredata://ABC/ICNote/p2" },
  2240. ]);
  2241. });
  2242. it("keeps two distinct notes with the same title distinguishable by id", () => {
  2243. // This is the exact shape of bug #115 (see exportNotesAsJson's fix):
  2244. // listNotes() alone collapses these to two identical-looking "Same
  2245. // Title" strings, which a caller can't use to fetch the second note
  2246. // without AppleScript's ambiguous by-name resolution returning the
  2247. // first one twice. listNoteRefs() must expose the distinguishing id.
  2248. mockExecuteAppleScript.mockReturnValue({
  2249. success: true,
  2250. output: [
  2251. ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
  2252. ["Same Title", "x-coredata://ABC/ICNote/p2"].join(F),
  2253. ].join(R),
  2254. });
  2255. const refs = manager.listNoteRefs();
  2256. expect(refs).toEqual([
  2257. { title: "Same Title", id: "x-coredata://ABC/ICNote/p1" },
  2258. { title: "Same Title", id: "x-coredata://ABC/ICNote/p2" },
  2259. ]);
  2260. expect(refs[0].id).not.toEqual(refs[1].id);
  2261. });
  2262. it("supports the same folder/modifiedSince/limit filtering as listNotes", () => {
  2263. mockExecuteAppleScript.mockReturnValue({
  2264. success: true,
  2265. output: [["Note 1", "x-coredata://ABC/ICNote/p1"].join(F)].join(R),
  2266. });
  2267. manager.listNoteRefs("iCloud", "Work", "2025-01-01", 10);
  2268. const script = mockExecuteAppleScript.mock.calls[0][0];
  2269. expect(script).toContain("Work");
  2270. expect(script).toContain("thresholdDate");
  2271. });
  2272. it("throws on failure rather than returning empty", () => {
  2273. mockExecuteAppleScript.mockReturnValue({
  2274. success: false,
  2275. output: "",
  2276. error: "Account not found",
  2277. });
  2278. expect(() => manager.listNoteRefs()).toThrow(/Account not found/);
  2279. });
  2280. });
  2281. // ---------------------------------------------------------------------------
  2282. // Folder Operations
  2283. // ---------------------------------------------------------------------------
  2284. describe("listFolders", () => {
  2285. it("returns array of Folder objects with paths", () => {
  2286. mockExecuteAppleScript.mockReturnValue({
  2287. success: true,
  2288. output: [
  2289. ["id1", "Notes", "", "false"].join(F),
  2290. ["id2", "Archive", "", "false"].join(F),
  2291. ["id3", "Work", "", "true"].join(F),
  2292. ].join(R),
  2293. });
  2294. const folders = manager.listFolders();
  2295. expect(folders).toHaveLength(3);
  2296. expect(folders[0].name).toBe("Notes");
  2297. expect(folders[1].name).toBe("Archive");
  2298. expect(folders[2].name).toBe("Work");
  2299. expect(folders[0].id).toBe("id1");
  2300. expect(folders[2].shared).toBe(true);
  2301. });
  2302. it("marks smart folders, which AppleScript lists like ordinary ones (#247)", () => {
  2303. const smartId = "x-coredata://ABC/ICFolder/p9";
  2304. const plainId = "x-coredata://ABC/ICFolder/p2";
  2305. mockExecuteAppleScript.mockReturnValue({
  2306. success: true,
  2307. output: [
  2308. [plainId, "Notes", "", "false"].join(F),
  2309. [smartId, "Recents", "", "false"].join(F),
  2310. ].join(R),
  2311. });
  2312. const spy = vi.spyOn(manager, "smartFolderIds").mockReturnValue([smartId]);
  2313. const folders = manager.listFolders();
  2314. expect(folders.find((f) => f.id === smartId)?.smartFolder).toBe(true);
  2315. expect(folders.find((f) => f.id === plainId)).not.toHaveProperty("smartFolder");
  2316. spy.mockRestore();
  2317. });
  2318. it("includes parent folder in path", () => {
  2319. mockExecuteAppleScript.mockReturnValue({
  2320. success: true,
  2321. output: [
  2322. ["id1", "Dev", "", "false"].join(F),
  2323. ["id2", "Accessibility", "id1", "false"].join(F),
  2324. ["id3", "Work", "", "false"].join(F),
  2325. ["id4", "Clients", "id3", "false"].join(F),
  2326. ].join(R),
  2327. });
  2328. const folders = manager.listFolders();
  2329. expect(folders).toHaveLength(4);
  2330. expect(folders[0].name).toBe("Dev");
  2331. expect(folders[1].name).toBe("Dev/Accessibility");
  2332. expect(folders[2].name).toBe("Work");
  2333. expect(folders[3].name).toBe("Work/Clients");
  2334. });
  2335. it("disambiguates duplicate folder names using IDs", () => {
  2336. mockExecuteAppleScript.mockReturnValue({
  2337. success: true,
  2338. output: [
  2339. ["id1", "Finance", "", "false"].join(F),
  2340. ["id2", "Archive", "id1", "false"].join(F),
  2341. ["id3", "Travel", "", "false"].join(F),
  2342. ["id4", "Trips", "id3", "false"].join(F),
  2343. ["id5", "Archive", "id4", "false"].join(F),
  2344. ].join(R),
  2345. });
  2346. const folders = manager.listFolders();
  2347. expect(folders).toHaveLength(5);
  2348. expect(folders[1].name).toBe("Finance/Archive");
  2349. expect(folders[4].name).toBe("Travel/Trips/Archive");
  2350. });
  2351. it("escapes slashes in folder names", () => {
  2352. mockExecuteAppleScript.mockReturnValue({
  2353. success: true,
  2354. output: [
  2355. ["id1", "Travel", "", "false"].join(F),
  2356. ["id2", "Spain/Portugal 2023", "id1", "false"].join(F),
  2357. ].join(R),
  2358. });
  2359. const folders = manager.listFolders();
  2360. expect(folders).toHaveLength(2);
  2361. expect(folders[0].name).toBe("Travel");
  2362. expect(folders[1].name).toBe("Travel/Spain\\/Portugal 2023");
  2363. });
  2364. it("parses legacy tab/newline output (backward compat)", () => {
  2365. mockExecuteAppleScript.mockReturnValue({
  2366. success: true,
  2367. output: "id1\tNotes\nid2\tArchive\tid1",
  2368. });
  2369. const folders = manager.listFolders();
  2370. expect(folders).toHaveLength(2);
  2371. expect(folders[0].name).toBe("Notes");
  2372. expect(folders[1].name).toBe("Notes/Archive");
  2373. expect(folders[1].shared).toBe(false);
  2374. });
  2375. it("includes account in Folder objects", () => {
  2376. mockExecuteAppleScript.mockReturnValue({
  2377. success: true,
  2378. output: ["id1", "Notes", "", "false"].join(F),
  2379. });
  2380. const folders = manager.listFolders("Gmail");
  2381. expect(folders[0].account).toBe("Gmail");
  2382. });
  2383. });
  2384. describe("createFolder", () => {
  2385. it("returns Folder object on success", () => {
  2386. mockExecuteAppleScript
  2387. // Check existence — folder doesn't exist
  2388. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2389. // Create the folder
  2390. .mockReturnValueOnce({
  2391. success: true,
  2392. output: "folder id x-coredata://ABC123/ICFolder/p456",
  2393. })
  2394. // Get ID of created folder
  2395. .mockReturnValueOnce({
  2396. success: true,
  2397. output: "folder id x-coredata://ABC123/ICFolder/p456",
  2398. });
  2399. const result = manager.createFolder("New Project");
  2400. expect(result).not.toBeNull();
  2401. expect(result?.name).toBe("New Project");
  2402. expect(result?.id).toBe("x-coredata://ABC123/ICFolder/p456");
  2403. });
  2404. it("returns existing folder without creating duplicate", () => {
  2405. mockExecuteAppleScript
  2406. // Check existence — folder already exists
  2407. .mockReturnValueOnce({
  2408. success: true,
  2409. output: "x-coredata://ABC123/ICFolder/p789",
  2410. })
  2411. // Get ID of existing folder
  2412. .mockReturnValueOnce({
  2413. success: true,
  2414. output: "folder id x-coredata://ABC123/ICFolder/p789",
  2415. });
  2416. const result = manager.createFolder("Existing Folder");
  2417. expect(result).not.toBeNull();
  2418. expect(result?.name).toBe("Existing Folder");
  2419. expect(result?.id).toBe("x-coredata://ABC123/ICFolder/p789");
  2420. // Should only have 2 calls (check + get ID), no create call
  2421. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
  2422. });
  2423. it("returns null on genuine failure", () => {
  2424. mockExecuteAppleScript
  2425. // Check existence — doesn't exist
  2426. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2427. // Create fails
  2428. .mockReturnValueOnce({
  2429. success: false,
  2430. output: "",
  2431. error: "Permission denied",
  2432. });
  2433. const result = manager.createFolder("Restricted Folder");
  2434. expect(result).toBeNull();
  2435. });
  2436. it("creates nested folder path", () => {
  2437. mockExecuteAppleScript
  2438. // Check "Retro Tech" — doesn't exist
  2439. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2440. // Create "Retro Tech"
  2441. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p1" })
  2442. // Check "Retro Tech/PC" — doesn't exist
  2443. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2444. // Create "PC" inside "Retro Tech"
  2445. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" })
  2446. // Check "Retro Tech/PC/CPUs" — doesn't exist
  2447. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2448. // Create "CPUs" inside "Retro Tech/PC"
  2449. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p3" })
  2450. // Get ID of final folder
  2451. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p3" });
  2452. const result = manager.createFolder("Retro Tech/PC/CPUs");
  2453. expect(result).not.toBeNull();
  2454. expect(result?.name).toBe("Retro Tech/PC/CPUs");
  2455. expect(result?.id).toBe("x-coredata://A/ICFolder/p3");
  2456. // Verify the create commands (calls at index 1, 3, 5)
  2457. const calls = mockExecuteAppleScript.mock.calls;
  2458. expect(calls[1][0]).toContain('make new folder with properties {name:"Retro Tech"}');
  2459. expect(calls[3][0]).toContain('whose name is "Retro Tech"');
  2460. expect(calls[3][0]).toContain('make new folder at __parent with properties {name:"PC"}');
  2461. expect(calls[5][0]).toContain('whose name is "Retro Tech"');
  2462. expect(calls[5][0]).toContain('whose name is "PC"');
  2463. expect(calls[5][0]).toContain('make new folder at __parent with properties {name:"CPUs"}');
  2464. });
  2465. // #213: a folder deleted earlier in the Notes session still answers a
  2466. // name reference, so existence must be decided by id.
  2467. it("checks existence by id, not by a name reference", () => {
  2468. mockExecuteAppleScript
  2469. .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" })
  2470. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p9" })
  2471. .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p9" });
  2472. const result = manager.createFolder("Gone");
  2473. const check = mockExecuteAppleScript.mock.calls[0][0] as string;
  2474. expect(check).toContain('whose name is "Gone"');
  2475. expect(check).toContain("if exists folder id __folder_cid then");
  2476. expect(check).toContain("return id of __folder");
  2477. expect(check).not.toMatch(/return id of folder "/);
  2478. // rootOnly: a same-named nested folder is not a fallback for "Gone"
  2479. expect(check).not.toContain("set __folder to __folder_any");
  2480. expect(mockExecuteAppleScript.mock.calls[1][0]).toContain(
  2481. 'make new folder with properties {name:"Gone"}'
  2482. );
  2483. expect(result?.id).toBe("x-coredata://A/ICFolder/p9");
  2484. });
  2485. it("reports failure when the created folder cannot be confirmed by id", () => {
  2486. mockExecuteAppleScript
  2487. // Check — not found
  2488. .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" })
  2489. // Create reports success but did nothing
  2490. .mockReturnValueOnce({ success: true, output: "" })
  2491. // Post-check — still no live folder
  2492. .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" });
  2493. const result = manager.createFolder("Gone");
  2494. expect(result).toBeNull();
  2495. expect(mockExecuteAppleScript.mock.calls[2][0]).toContain("exists folder id __folder_cid");
  2496. });
  2497. it("reports failure when the post-check returns no folder id", () => {
  2498. mockExecuteAppleScript
  2499. .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p1" })
  2500. .mockReturnValueOnce({ success: true, output: "" });
  2501. expect(manager.createFolder("Existing")).toBeNull();
  2502. });
  2503. it("skips existing intermediate folders in nested path", () => {
  2504. mockExecuteAppleScript
  2505. // Check "Retro Tech" — exists
  2506. .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p1" })
  2507. // Check "Retro Tech/PC" — doesn't exist
  2508. .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
  2509. // Create "PC" inside "Retro Tech"
  2510. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" })
  2511. // Get ID of final folder
  2512. .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" });
  2513. const result = manager.createFolder("Retro Tech/PC");
  2514. expect(result).not.toBeNull();
  2515. expect(result?.name).toBe("Retro Tech/PC");
  2516. // No create call for "Retro Tech" — only for "PC"
  2517. const createCalls = mockExecuteAppleScript.mock.calls.filter((c) =>
  2518. c[0].includes("make new folder")
  2519. );
  2520. expect(createCalls).toHaveLength(1);
  2521. expect(createCalls[0][0]).toContain('name:"PC"');
  2522. });
  2523. });
  2524. describe("deleteFolder", () => {
  2525. it("returns true on successful deletion", () => {
  2526. mockExecuteAppleScript.mockReturnValue({
  2527. success: true,
  2528. output: "",
  2529. });
  2530. const result = manager.deleteFolder("Empty Folder");
  2531. expect(result).toBe(true);
  2532. });
  2533. it("returns false when deletion fails", () => {
  2534. mockExecuteAppleScript.mockReturnValue({
  2535. success: false,
  2536. output: "",
  2537. error: "Folder contains notes",
  2538. });
  2539. const result = manager.deleteFolder("Non-Empty Folder");
  2540. expect(result).toBe(false);
  2541. });
  2542. it("deletes the live folder resolved by id, not a name reference (#213)", () => {
  2543. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  2544. manager.deleteFolder("Work/Old");
  2545. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  2546. expect(script).toContain('whose name is "Work"');
  2547. expect(script).toContain('whose name is "Old"');
  2548. expect(script).toContain("delete __folder");
  2549. expect(script).not.toContain('delete folder "Old"');
  2550. });
  2551. it("returns false when the folder was already deleted this session (#213)", () => {
  2552. mockExecuteAppleScript.mockReturnValue({
  2553. success: false,
  2554. output: "",
  2555. error: "Folder not found: Doomed",
  2556. });
  2557. expect(manager.deleteFolder("Doomed")).toBe(false);
  2558. });
  2559. });
  2560. // ---------------------------------------------------------------------------
  2561. // Note Moving
  2562. // ---------------------------------------------------------------------------
  2563. describe("moveNoteById", () => {
  2564. it("returns true when the native move succeeds", () => {
  2565. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "SAFETY_MOVED" });
  2566. const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Archive");
  2567. expect(result).toBe(true);
  2568. // Single native `move` — no getNoteContentById/create/delete fan-out.
  2569. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  2570. const moveScript = mockExecuteAppleScript.mock.calls[0][0] as string;
  2571. expect(moveScript).toContain("move noteRef to destFolder");
  2572. expect(moveScript).toContain("id of actualFolder");
  2573. expect(moveScript).toContain('return "SAFETY_MOVED"');
  2574. expect(moveScript).not.toContain("make new note");
  2575. });
  2576. it("resolves the destination to a live folder id (#213)", () => {
  2577. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "SAFETY_MOVED" });
  2578. manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Work/Archive");
  2579. const moveScript = mockExecuteAppleScript.mock.calls[0][0] as string;
  2580. expect(moveScript).toContain('whose name is "Archive"');
  2581. expect(moveScript).toContain("if exists folder id destFolder_cid then");
  2582. expect(moveScript).not.toContain('folder "Archive" of folder "Work"');
  2583. expect(moveScript.indexOf("destFolder_cid")).toBeLessThan(
  2584. moveScript.indexOf("move noteRef to destFolder")
  2585. );
  2586. });
  2587. it("returns false when Notes cannot verify the destination folder", () => {
  2588. mockExecuteAppleScript.mockReturnValueOnce({
  2589. success: true,
  2590. output: "SAFETY_WRONG_FOLDER",
  2591. });
  2592. const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Archive");
  2593. expect(result).toBe(false);
  2594. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  2595. });
  2596. it("returns false when the move fails", () => {
  2597. mockExecuteAppleScript.mockReturnValueOnce({
  2598. success: false,
  2599. output: "",
  2600. error: "Folder not found",
  2601. });
  2602. const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Nonexistent");
  2603. expect(result).toBe(false);
  2604. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  2605. });
  2606. });
  2607. // ---------------------------------------------------------------------------
  2608. // Account Operations
  2609. // ---------------------------------------------------------------------------
  2610. describe("listAccounts", () => {
  2611. it("returns array of Account objects", () => {
  2612. mockExecuteAppleScript.mockReturnValue({
  2613. success: true,
  2614. output: [
  2615. ["acc1", "iCloud", "true", "folder1", "Notes"].join(F),
  2616. ["acc2", "Gmail", "false", "folder2", "Inbox"].join(F),
  2617. ["acc3", "Exchange", "false", "", ""].join(F),
  2618. ].join(R),
  2619. });
  2620. const accounts = manager.listAccounts();
  2621. expect(accounts).toHaveLength(3);
  2622. expect(accounts[0].name).toBe("iCloud");
  2623. expect(accounts[1].name).toBe("Gmail");
  2624. expect(accounts[2].name).toBe("Exchange");
  2625. expect(accounts[0].id).toBe("acc1");
  2626. expect(accounts[0].upgraded).toBe(true);
  2627. expect(accounts[0].defaultFolder).toBe("Notes");
  2628. });
  2629. it("parses legacy plain-name output (backward compat)", () => {
  2630. mockExecuteAppleScript.mockReturnValue({
  2631. success: true,
  2632. output: ["iCloud", "Gmail"].join(R),
  2633. });
  2634. const accounts = manager.listAccounts();
  2635. expect(accounts).toHaveLength(2);
  2636. expect(accounts[0]).toEqual({ name: "iCloud" });
  2637. expect(accounts[1]).toEqual({ name: "Gmail" });
  2638. });
  2639. it("handles account records with empty fields", () => {
  2640. mockExecuteAppleScript.mockReturnValue({
  2641. success: true,
  2642. output: ["", "", "", "", ""].join(F),
  2643. });
  2644. const accounts = manager.listAccounts();
  2645. expect(accounts).toHaveLength(1);
  2646. expect(accounts[0].name).toBe("");
  2647. expect(accounts[0].upgraded).toBe(false);
  2648. expect(accounts[0].defaultFolderId).toBeUndefined();
  2649. });
  2650. it("throws on failure rather than returning empty (#19)", () => {
  2651. mockExecuteAppleScript.mockReturnValue({
  2652. success: false,
  2653. output: "",
  2654. error: "Notes.app not available",
  2655. });
  2656. expect(() => manager.listAccounts()).toThrow(/Notes.app not available/);
  2657. });
  2658. });
  2659. describe("getDefaultLocation", () => {
  2660. it("returns default account and folder metadata", () => {
  2661. mockExecuteAppleScript.mockReturnValue({
  2662. success: true,
  2663. output: ["acc1", "iCloud", "true", "folder1", "Notes", "false"].join(F),
  2664. });
  2665. const location = manager.getDefaultLocation();
  2666. expect(location.account).toMatchObject({
  2667. id: "acc1",
  2668. name: "iCloud",
  2669. upgraded: true,
  2670. defaultFolderId: "folder1",
  2671. defaultFolder: "Notes",
  2672. });
  2673. expect(location.folder).toMatchObject({
  2674. id: "folder1",
  2675. name: "Notes",
  2676. account: "iCloud",
  2677. shared: false,
  2678. });
  2679. });
  2680. it("throws when default location output cannot be parsed", () => {
  2681. mockExecuteAppleScript.mockReturnValue({
  2682. success: true,
  2683. output: "bad-output",
  2684. });
  2685. expect(() => manager.getDefaultLocation()).toThrow(/parse default Notes location/);
  2686. });
  2687. it("throws when AppleScript fails", () => {
  2688. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "boom" });
  2689. expect(() => manager.getDefaultLocation()).toThrow(/Failed to get default Notes location/);
  2690. });
  2691. it("handles empty fields in default location output", () => {
  2692. mockExecuteAppleScript.mockReturnValue({
  2693. success: true,
  2694. output: ["", "", "", "", "", ""].join(F),
  2695. });
  2696. const location = manager.getDefaultLocation();
  2697. expect(location.account.name).toBe("");
  2698. expect(location.account.upgraded).toBe(false);
  2699. expect(location.folder.id).toBe("");
  2700. expect(location.folder.shared).toBe(false);
  2701. });
  2702. });
  2703. describe("getSelectedNotes", () => {
  2704. it("returns selected note metadata", () => {
  2705. mockExecuteAppleScript.mockReturnValue({
  2706. success: true,
  2707. output: [
  2708. [
  2709. "x-coredata://ABC/ICNote/p1",
  2710. "Selected Note",
  2711. "2026-6-22-14-30-0",
  2712. "2026-6-22-14-35-0",
  2713. "false",
  2714. "false",
  2715. "Notes",
  2716. "iCloud",
  2717. ].join(F),
  2718. ].join(R),
  2719. });
  2720. const notes = manager.getSelectedNotes();
  2721. expect(notes).toHaveLength(1);
  2722. expect(notes[0]).toMatchObject({
  2723. id: "x-coredata://ABC/ICNote/p1",
  2724. title: "Selected Note",
  2725. shared: false,
  2726. passwordProtected: false,
  2727. folder: "Notes",
  2728. account: "iCloud",
  2729. });
  2730. expect(notes[0].created.getFullYear()).toBe(2026);
  2731. });
  2732. it("returns an empty array when no note is selected", () => {
  2733. mockExecuteAppleScript.mockReturnValue({
  2734. success: true,
  2735. output: "",
  2736. });
  2737. expect(manager.getSelectedNotes()).toEqual([]);
  2738. });
  2739. it("throws when AppleScript fails", () => {
  2740. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "boom" });
  2741. expect(() => manager.getSelectedNotes()).toThrow(/Failed to get selected notes/);
  2742. });
  2743. it("handles selected notes with empty optional fields", () => {
  2744. mockExecuteAppleScript.mockReturnValue({
  2745. success: true,
  2746. output: ["", "", "", "", "", "", "", ""].join(F),
  2747. });
  2748. const notes = manager.getSelectedNotes();
  2749. expect(notes).toHaveLength(1);
  2750. expect(notes[0].id).toBe("");
  2751. expect(notes[0].shared).toBe(false);
  2752. expect(notes[0].passwordProtected).toBe(false);
  2753. expect(notes[0].folder).toBeUndefined();
  2754. expect(notes[0].account).toBeUndefined();
  2755. });
  2756. });
  2757. describe("showNoteById", () => {
  2758. it("shows a note by id", () => {
  2759. mockExecuteAppleScript.mockReturnValue({
  2760. success: true,
  2761. output: "",
  2762. });
  2763. expect(manager.showNoteById("x-coredata://ABC/ICNote/p1")).toBe(true);
  2764. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2765. expect.stringContaining('show note id "x-coredata://ABC/ICNote/p1"'),
  2766. NO_RETRY_OPTIONS
  2767. );
  2768. });
  2769. it("can request a separate window", () => {
  2770. mockExecuteAppleScript.mockReturnValue({
  2771. success: true,
  2772. output: "",
  2773. });
  2774. manager.showNoteById("x-coredata://ABC/ICNote/p1", true);
  2775. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2776. expect.stringContaining("separately true"),
  2777. NO_RETRY_OPTIONS
  2778. );
  2779. });
  2780. it("returns false when Notes.app rejects the show command", () => {
  2781. mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "no such note" });
  2782. expect(manager.showNoteById("x-coredata://ABC/ICNote/p1")).toBe(false);
  2783. });
  2784. });
  2785. describe("showFolderById", () => {
  2786. it("shows a folder by id", () => {
  2787. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  2788. expect(manager.showFolderById("x-coredata://ABC/ICFolder/p1")).toBe(true);
  2789. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2790. expect.stringContaining('show folder id "x-coredata://ABC/ICFolder/p1"'),
  2791. NO_RETRY_OPTIONS
  2792. );
  2793. });
  2794. it("can request a separate window", () => {
  2795. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  2796. manager.showFolderById("x-coredata://ABC/ICFolder/p1", true);
  2797. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2798. expect.stringContaining("separately true"),
  2799. NO_RETRY_OPTIONS
  2800. );
  2801. });
  2802. it("returns false when Notes.app rejects the show command", () => {
  2803. mockExecuteAppleScript.mockReturnValue({
  2804. success: false,
  2805. output: "",
  2806. error: "no such folder",
  2807. });
  2808. expect(manager.showFolderById("x-coredata://ABC/ICFolder/p1")).toBe(false);
  2809. });
  2810. });
  2811. describe("showAccountById", () => {
  2812. it("shows an account by id", () => {
  2813. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  2814. expect(manager.showAccountById("x-coredata://ABC/ICAccount/p1")).toBe(true);
  2815. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2816. expect.stringContaining('show account id "x-coredata://ABC/ICAccount/p1"'),
  2817. NO_RETRY_OPTIONS
  2818. );
  2819. });
  2820. it("can request a separate window", () => {
  2821. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  2822. manager.showAccountById("x-coredata://ABC/ICAccount/p1", true);
  2823. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2824. expect.stringContaining("separately true"),
  2825. NO_RETRY_OPTIONS
  2826. );
  2827. });
  2828. it("returns false when Notes.app rejects the show command", () => {
  2829. mockExecuteAppleScript.mockReturnValue({
  2830. success: false,
  2831. output: "",
  2832. error: "no such account",
  2833. });
  2834. expect(manager.showAccountById("x-coredata://ABC/ICAccount/p1")).toBe(false);
  2835. });
  2836. });
  2837. describe("showAttachmentById", () => {
  2838. it("resolves the attachment within its note and shows it", () => {
  2839. mockExecuteAppleScript.mockReturnValue({ success: true, output: "OK" });
  2840. expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123")).toBe(true);
  2841. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  2842. expect(script).toContain('set theNote to note id "x-coredata://ABC/ICNote/p1"');
  2843. // Addressed directly rather than scanned for: one Apple Event instead of up
  2844. // to N, and still scoped to theNote (a foreign id resolves to missing value).
  2845. expect(script).toContain('set theAttachment to attachment id "att-123" of theNote');
  2846. expect(script).not.toContain("repeat with a in attachments of theNote");
  2847. expect(script).toContain("show theAttachment");
  2848. });
  2849. it("can request a separate window", () => {
  2850. mockExecuteAppleScript.mockReturnValue({ success: true, output: "OK" });
  2851. manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123", true);
  2852. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  2853. expect.stringContaining("separately true"),
  2854. NO_RETRY_OPTIONS
  2855. );
  2856. });
  2857. it("returns false when the attachment is not found on the note", () => {
  2858. mockExecuteAppleScript.mockReturnValue({
  2859. success: true,
  2860. output: `ERR${F}attachment not found`,
  2861. });
  2862. expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "missing")).toBe(false);
  2863. });
  2864. it("returns false when Notes.app rejects the show command", () => {
  2865. mockExecuteAppleScript.mockReturnValue({
  2866. success: false,
  2867. output: "",
  2868. error: "no such note",
  2869. });
  2870. expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123")).toBe(false);
  2871. });
  2872. });
  2873. // ---------------------------------------------------------------------------
  2874. // Health Check
  2875. // ---------------------------------------------------------------------------
  2876. describe("healthCheck", () => {
  2877. it("returns healthy when all checks pass", () => {
  2878. mockExecuteAppleScript
  2879. // Check 1: Notes.app accessible
  2880. .mockReturnValueOnce({ success: true, output: "ok" })
  2881. // Check 2: Permissions (get account name)
  2882. .mockReturnValueOnce({ success: true, output: "iCloud" })
  2883. // Check 3: listAccounts
  2884. .mockReturnValueOnce({ success: true, output: "iCloud" })
  2885. // Check 4: listNotes
  2886. .mockReturnValueOnce({
  2887. success: true,
  2888. output: [
  2889. ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
  2890. ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
  2891. ].join(R),
  2892. });
  2893. const result = manager.healthCheck();
  2894. expect(result.healthy).toBe(true);
  2895. expect(result.checks).toHaveLength(4);
  2896. expect(result.checks.every((c) => c.passed)).toBe(true);
  2897. });
  2898. it("returns unhealthy when Notes.app is not accessible", () => {
  2899. mockExecuteAppleScript.mockReturnValueOnce({
  2900. success: false,
  2901. output: "",
  2902. error: "Application not found",
  2903. });
  2904. const result = manager.healthCheck();
  2905. expect(result.healthy).toBe(false);
  2906. expect(result.checks).toHaveLength(1);
  2907. expect(result.checks[0].name).toBe("notes_app");
  2908. expect(result.checks[0].passed).toBe(false);
  2909. });
  2910. it("returns unhealthy with permission hint when not authorized", () => {
  2911. mockExecuteAppleScript.mockReturnValueOnce({
  2912. success: false,
  2913. output: "",
  2914. error: "not authorized to send Apple events",
  2915. });
  2916. const result = manager.healthCheck();
  2917. expect(result.healthy).toBe(false);
  2918. expect(result.checks[0].message).toContain("Automation permissions");
  2919. });
  2920. it('classifies an en-GB "Not authorised" refusal as a permission failure', () => {
  2921. // The regression this guards: on an en_GB / en_AU / en_IE Mac the
  2922. // refusal reads "Not authorised", the American-only substring check
  2923. // missed it, and a genuine TCC denial reported `passed: true` and then
  2924. // misdirected the user to check their accounts.
  2925. mockExecuteAppleScript
  2926. // Check 1: Notes.app accessible
  2927. .mockReturnValueOnce({ success: true, output: "ok" })
  2928. // Check 2: permission probe refused, British spelling
  2929. .mockReturnValueOnce({
  2930. success: false,
  2931. output: "",
  2932. error: "27:44: execution error: Not authorised to send Apple events to Notes. (-1743)",
  2933. });
  2934. const result = manager.healthCheck();
  2935. const permCheck = result.checks.find((c) => c.name === "permissions");
  2936. expect(permCheck?.passed).toBe(false);
  2937. expect(permCheck?.message).toContain("AppleScript permissions denied");
  2938. // The early return fires: no account/note checks ran.
  2939. expect(result.healthy).toBe(false);
  2940. expect(result.checks).toHaveLength(2);
  2941. });
  2942. it("classifies a fully localised refusal by its -1743 OSStatus alone", () => {
  2943. mockExecuteAppleScript
  2944. .mockReturnValueOnce({ success: true, output: "ok" })
  2945. .mockReturnValueOnce({
  2946. success: false,
  2947. output: "",
  2948. error: "27:44: execution error: Non autorisé à envoyer des événements Apple (-1743)",
  2949. });
  2950. const result = manager.healthCheck();
  2951. expect(result.checks.find((c) => c.name === "permissions")?.passed).toBe(false);
  2952. expect(result.healthy).toBe(false);
  2953. expect(result.checks).toHaveLength(2);
  2954. });
  2955. it("returns unhealthy with permission hint when the refusal is British-spelled", () => {
  2956. mockExecuteAppleScript.mockReturnValueOnce({
  2957. success: false,
  2958. output: "",
  2959. error: "Not authorised to send Apple events to Notes. (-1743)",
  2960. });
  2961. const result = manager.healthCheck();
  2962. expect(result.healthy).toBe(false);
  2963. expect(result.checks[0].message).toContain("Automation permissions");
  2964. });
  2965. it("returns unhealthy when no accounts found", () => {
  2966. mockExecuteAppleScript
  2967. .mockReturnValueOnce({ success: true, output: "ok" })
  2968. .mockReturnValueOnce({ success: true, output: "iCloud" })
  2969. .mockReturnValueOnce({ success: true, output: "" }); // No accounts
  2970. const result = manager.healthCheck();
  2971. expect(result.healthy).toBe(false);
  2972. expect(result.checks.find((c) => c.name === "accounts")?.passed).toBe(false);
  2973. });
  2974. it("includes account names in successful account check", () => {
  2975. mockExecuteAppleScript
  2976. .mockReturnValueOnce({ success: true, output: "ok" })
  2977. .mockReturnValueOnce({ success: true, output: "iCloud" })
  2978. .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
  2979. .mockReturnValueOnce({ success: true, output: "" });
  2980. const result = manager.healthCheck();
  2981. const accountCheck = result.checks.find((c) => c.name === "accounts");
  2982. expect(accountCheck?.message).toContain("iCloud");
  2983. expect(accountCheck?.message).toContain("Gmail");
  2984. });
  2985. });
  2986. // ---------------------------------------------------------------------------
  2987. // Statistics
  2988. // ---------------------------------------------------------------------------
  2989. describe("getNotesStats", () => {
  2990. it("returns statistics for all accounts and folders", () => {
  2991. mockExecuteAppleScript
  2992. // listAccounts
  2993. .mockReturnValueOnce({ success: true, output: "iCloud" })
  2994. // per-account folder counts: name<F>count, records joined by R
  2995. .mockReturnValueOnce({
  2996. success: true,
  2997. output: ["Notes", "3"].join(F) + R + ["Work", "2"].join(F) + R,
  2998. })
  2999. // getRecentlyModifiedCounts: c1<F>c7<F>c30
  3000. .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
  3001. const stats = manager.getNotesStats();
  3002. expect(stats.totalNotes).toBe(5);
  3003. expect(stats.accounts).toHaveLength(1);
  3004. expect(stats.accounts[0].name).toBe("iCloud");
  3005. expect(stats.accounts[0].totalNotes).toBe(5);
  3006. expect(stats.accounts[0].folderCount).toBe(2);
  3007. expect(stats.accounts[0].folders).toHaveLength(2);
  3008. });
  3009. it("returns zero counts when no notes exist", () => {
  3010. mockExecuteAppleScript
  3011. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3012. .mockReturnValueOnce({ success: true, output: ["Notes", "0"].join(F) + R })
  3013. .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
  3014. const stats = manager.getNotesStats();
  3015. expect(stats.totalNotes).toBe(0);
  3016. expect(stats.recentlyModified.last24h).toBe(0);
  3017. expect(stats.recentlyModified.last7d).toBe(0);
  3018. expect(stats.recentlyModified.last30d).toBe(0);
  3019. });
  3020. it("handles multiple accounts", () => {
  3021. mockExecuteAppleScript
  3022. // listAccounts
  3023. .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
  3024. // iCloud folder counts
  3025. .mockReturnValueOnce({ success: true, output: ["Notes", "1"].join(F) + R })
  3026. // Gmail folder counts
  3027. .mockReturnValueOnce({ success: true, output: ["Notes", "1"].join(F) + R })
  3028. // getRecentlyModifiedCounts
  3029. .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
  3030. const stats = manager.getNotesStats();
  3031. expect(stats.totalNotes).toBe(2);
  3032. expect(stats.accounts).toHaveLength(2);
  3033. expect(stats.accounts[0].name).toBe("iCloud");
  3034. expect(stats.accounts[1].name).toBe("Gmail");
  3035. });
  3036. it("reports complete coverage when every scope succeeds (#19)", () => {
  3037. mockExecuteAppleScript
  3038. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3039. .mockReturnValueOnce({ success: true, output: ["Notes", "3"].join(F) + R })
  3040. .mockReturnValueOnce({ success: true, output: ["1", "2", "3"].join(F) });
  3041. const stats = manager.getNotesStats();
  3042. expect(stats.coverage.complete).toBe(true);
  3043. expect(stats.coverage.warnings).toEqual([]);
  3044. expect(stats.coverage.covered).toBe(stats.coverage.scanned);
  3045. });
  3046. it("degrades gracefully when one account fails, with a coverage warning (#19)", () => {
  3047. mockExecuteAppleScript
  3048. // listAccounts
  3049. .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
  3050. // iCloud folder counts succeed
  3051. .mockReturnValueOnce({ success: true, output: ["Notes", "4"].join(F) + R })
  3052. // Gmail folder counts FAIL
  3053. .mockReturnValueOnce({ success: false, output: "", error: "Gmail account is locked" })
  3054. // getRecentlyModifiedCounts succeed
  3055. .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
  3056. const stats = manager.getNotesStats();
  3057. // Healthy account's data is preserved, not discarded
  3058. expect(stats.totalNotes).toBe(4);
  3059. expect(stats.accounts).toHaveLength(1);
  3060. expect(stats.accounts[0].name).toBe("iCloud");
  3061. // Failure surfaced as a coverage warning
  3062. expect(stats.coverage.complete).toBe(false);
  3063. expect(stats.coverage.warnings).toHaveLength(1);
  3064. expect(stats.coverage.warnings[0].scope).toBe("Gmail");
  3065. expect(stats.coverage.warnings[0].reason).toContain("locked");
  3066. });
  3067. it("flags recent-activity failure as a coverage warning, not fake zeros (#19)", () => {
  3068. mockExecuteAppleScript
  3069. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3070. .mockReturnValueOnce({ success: true, output: ["Notes", "5"].join(F) + R })
  3071. // getRecentlyModifiedCounts FAILS
  3072. .mockReturnValueOnce({ success: false, output: "", error: "timed out" });
  3073. const stats = manager.getNotesStats();
  3074. expect(stats.totalNotes).toBe(5);
  3075. expect(stats.recentlyModified.last24h).toBe(0);
  3076. expect(stats.coverage.complete).toBe(false);
  3077. expect(stats.coverage.warnings.some((w) => w.scope === "recent-activity")).toBe(true);
  3078. });
  3079. it("throws when no account can be read at all (#19)", () => {
  3080. mockExecuteAppleScript
  3081. .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
  3082. .mockReturnValueOnce({ success: false, output: "", error: "iCloud unreachable" })
  3083. .mockReturnValueOnce({ success: false, output: "", error: "Gmail unreachable" });
  3084. expect(() => manager.getNotesStats()).toThrow(/Failed to read folder stats for any/);
  3085. });
  3086. });
  3087. // ---------------------------------------------------------------------------
  3088. // Attachment Listing
  3089. // ---------------------------------------------------------------------------
  3090. describe("listAttachmentsById", () => {
  3091. it("returns attachments for a note", () => {
  3092. mockExecuteAppleScript.mockReturnValueOnce({
  3093. success: true,
  3094. output: [
  3095. ["x-coredata://ABC/ICAttachment/p1", "photo.jpg", "public.jpeg"].join(F),
  3096. ["x-coredata://ABC/ICAttachment/p2", "document.pdf", "com.adobe.pdf"].join(F),
  3097. ].join(R),
  3098. });
  3099. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3100. expect(attachments).toHaveLength(2);
  3101. expect(attachments[0]).toMatchObject({
  3102. id: "x-coredata://ABC/ICAttachment/p1",
  3103. name: "photo.jpg",
  3104. contentType: "public.jpeg",
  3105. contentId: "public.jpeg",
  3106. });
  3107. expect(attachments[1]).toMatchObject({
  3108. id: "x-coredata://ABC/ICAttachment/p2",
  3109. name: "document.pdf",
  3110. contentType: "com.adobe.pdf",
  3111. contentId: "com.adobe.pdf",
  3112. });
  3113. });
  3114. it("parses richer attachment metadata when present", () => {
  3115. mockExecuteAppleScript.mockReturnValueOnce({
  3116. success: true,
  3117. output: [
  3118. [
  3119. "x-coredata://ABC/ICAttachment/p1",
  3120. "site.webloc",
  3121. "cid:123",
  3122. "https://example.com",
  3123. "2026-6-22-10-0-0",
  3124. "2026-6-22-11-0-0",
  3125. "true",
  3126. ].join(F),
  3127. ].join(R),
  3128. });
  3129. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3130. expect(attachments[0]).toMatchObject({
  3131. id: "x-coredata://ABC/ICAttachment/p1",
  3132. name: "site.webloc",
  3133. contentType: "cid:123",
  3134. contentId: "cid:123",
  3135. url: "https://example.com",
  3136. shared: true,
  3137. });
  3138. expect(attachments[0].created?.getFullYear()).toBe(2026);
  3139. expect(attachments[0].modified?.getHours()).toBe(11);
  3140. });
  3141. it("reports an attachment enumerated twice only once, in first-seen order (#197)", () => {
  3142. const output = [
  3143. ["x-coredata://ABC/ICAttachment/p2", "new.png", "public.png"].join(F),
  3144. ["x-coredata://ABC/ICAttachment/p1", "photo.jpg", "public.jpeg"].join(F),
  3145. ["x-coredata://ABC/ICAttachment/p2", "new.png", "public.png"].join(F),
  3146. ].join(R);
  3147. mockExecuteAppleScript.mockReturnValue({ success: true, output });
  3148. const expected = ["x-coredata://ABC/ICAttachment/p2", "x-coredata://ABC/ICAttachment/p1"];
  3149. expect(manager.listAttachmentsById("x-coredata://ABC/ICNote/p123").map((a) => a.id)).toEqual(
  3150. expected
  3151. );
  3152. expect(manager.listAttachments("My Note", "iCloud").map((a) => a.id)).toEqual(expected);
  3153. });
  3154. it("returns empty array when note has no attachments", () => {
  3155. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3156. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3157. expect(attachments).toEqual([]);
  3158. });
  3159. it("surfaces an error rather than an empty array when the lookup fails", () => {
  3160. // Previously this returned [], which the tool layer rendered as the cheerful
  3161. // "has no attachments" -- indistinguishable from a genuinely empty note.
  3162. mockExecuteAppleScript.mockReturnValueOnce({
  3163. success: false,
  3164. output: "",
  3165. error: "Note not found",
  3166. });
  3167. expect(() => manager.listAttachmentsById("x-coredata://ABC/ICNote/p999")).toThrow(
  3168. /Note not found/
  3169. );
  3170. });
  3171. it("generates correct AppleScript for ID lookup", () => {
  3172. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3173. manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3174. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  3175. expect.stringContaining('note id "x-coredata://ABC/ICNote/p123"')
  3176. );
  3177. });
  3178. it("bulk-fetches properties instead of sending Apple Events per attachment", () => {
  3179. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  3180. manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3181. manager.listAttachments("My Note", "iCloud");
  3182. for (const [script] of mockExecuteAppleScript.mock.calls) {
  3183. expect(script).toContain("set attachmentIds to id of every attachment of theNote");
  3184. expect(script).toContain("set attachmentNames to name of every attachment of theNote");
  3185. expect(script).toContain(
  3186. 'if (count of attachmentNames) is not (count of attachmentIds) then error "Notes changed during listing"'
  3187. );
  3188. expect(script).toContain("repeat with i from 1 to count of attachmentIds");
  3189. expect(script).not.toContain("repeat with a in attachments of theNote");
  3190. }
  3191. });
  3192. it("does not use the reserved word `item` as a repeat loop variable", () => {
  3193. // Regression: `repeat with item in ...` fails to COMPILE ("Expected
  3194. // variable name or property but found class name", -2741), so every
  3195. // list-attachments call errored and surfaced as an empty array.
  3196. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3197. manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3198. const script = mockExecuteAppleScript.mock.calls[0][0] as string;
  3199. expect(script).not.toMatch(/repeat with item\b/);
  3200. expect(script).toContain("repeat with recordItem in attachmentList");
  3201. });
  3202. it("normalizes a 'missing value' URL to undefined", () => {
  3203. // `URL of a as text` renders as the literal string "missing value" for
  3204. // attachments without a URL (most images); that sentinel must not leak
  3205. // into the parsed url field.
  3206. mockExecuteAppleScript.mockReturnValueOnce({
  3207. success: true,
  3208. output: [
  3209. "x-coredata://ABC/ICAttachment/p1",
  3210. "photo.png",
  3211. "cid:abc",
  3212. "missing value",
  3213. "2026-7-5-22-7-39",
  3214. "2026-7-5-22-7-39",
  3215. "false",
  3216. ].join(F),
  3217. });
  3218. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3219. expect(attachments).toHaveLength(1);
  3220. expect(attachments[0].url).toBeUndefined();
  3221. });
  3222. it("keeps every field aligned with its own attachment across records", () => {
  3223. // The bulk fetch zips seven independently-fetched lists. If the zip ever
  3224. // slipped, a record would carry one attachment's id with another's name --
  3225. // and save-attachment/fetch-attachment resolve bytes from that id, so the
  3226. // wrong file would be written under the wrong name.
  3227. const record = (n: number) =>
  3228. [
  3229. `x-coredata://ABC/ICAttachment/p${n}`,
  3230. `file${n}.png`,
  3231. `cid:${n}`,
  3232. "missing value",
  3233. "2026-7-5-22-7-39",
  3234. "2026-7-5-22-7-39",
  3235. n === 2 ? "true" : "false",
  3236. ].join(F);
  3237. mockExecuteAppleScript.mockReturnValueOnce({
  3238. success: true,
  3239. output: [record(1), record(2), record(3)].join(R),
  3240. });
  3241. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3242. expect(attachments).toHaveLength(3);
  3243. attachments.forEach((a, i) => {
  3244. const n = i + 1;
  3245. expect(a.id).toBe(`x-coredata://ABC/ICAttachment/p${n}`);
  3246. expect(a.name).toBe(`file${n}.png`);
  3247. expect(a.contentId).toBe(`cid:${n}`);
  3248. expect(a.shared).toBe(n === 2);
  3249. });
  3250. });
  3251. it("guards the zip against a concurrent mutation that preserves the count", () => {
  3252. // Count guards alone cannot see a same-length reorder or delete+add, so the
  3253. // script re-reads the ids after the other six fetches and compares them
  3254. // element-wise. Without this, a swap between Apple Events passes every check.
  3255. mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
  3256. manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3257. manager.listAttachments("My Note", "iCloud");
  3258. for (const [script] of mockExecuteAppleScript.mock.calls) {
  3259. expect(script).toContain("set attachmentIdsAfter to id of every attachment of theNote");
  3260. expect(script).toContain(
  3261. 'if (item i of attachmentIdsAfter) is not (item i of attachmentIds) then error "Notes changed during listing"'
  3262. );
  3263. }
  3264. });
  3265. it("throws instead of reporting an empty note when the AppleScript call fails", () => {
  3266. // A false empty is the exact hazard this tool exists to prevent: callers gate
  3267. // destructive full-body updates on it. Exhausted retries must surface as an error.
  3268. mockExecuteAppleScript.mockReturnValueOnce({
  3269. success: false,
  3270. error: "Notes changed during listing",
  3271. });
  3272. expect(() => manager.listAttachmentsById("x-coredata://ABC/ICNote/p123")).toThrow(
  3273. /Notes changed during listing/
  3274. );
  3275. });
  3276. it("still returns an empty array when the note genuinely has no attachments", () => {
  3277. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3278. expect(manager.listAttachmentsById("x-coredata://ABC/ICNote/p123")).toEqual([]);
  3279. });
  3280. it("does not surface the literal 'missing value' as an attachment name", () => {
  3281. // Notes leaves `name` unset on some attachments; `name of a as text` then
  3282. // renders the AppleScript sentinel, which previously reached callers as a
  3283. // filename (`- missing value (cid:abc)`).
  3284. mockExecuteAppleScript.mockReturnValueOnce({
  3285. success: true,
  3286. output: [
  3287. "x-coredata://ABC/ICAttachment/p1",
  3288. "missing value",
  3289. "cid:abc",
  3290. "missing value",
  3291. "2026-7-5-22-7-39",
  3292. "2026-7-5-22-7-39",
  3293. "false",
  3294. ].join(F),
  3295. });
  3296. const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
  3297. expect(attachments[0].name).not.toBe("missing value");
  3298. expect(attachments[0].name).toBe("cid:abc");
  3299. });
  3300. it("leaves an unnamed saved attachment's name undefined rather than the sentinel", () => {
  3301. // save-attachment/fetch-attachment render `r.name ?? "attachment"`, and `??`
  3302. // does not catch the literal string -- so this must be undefined, not passed
  3303. // through, or the response reads `Saved "missing value" to ...`.
  3304. // AppleScript is mocked, so stand in for the file Notes would have written
  3305. // (the manager verifies a non-empty file landed before reporting success).
  3306. // mkdtemp, not a predictable name in the shared temp dir: a guessable path
  3307. // there is a symlink-race vector (CodeQL js/insecure-temporary-file).
  3308. const dir = mkdtempSync(join(tmpdir(), "apple-notes-mcp-test-"));
  3309. const dest = join(dir, "attachment.bin");
  3310. writeFileSync(dest, "x");
  3311. try {
  3312. mockExecuteAppleScript.mockReturnValueOnce({
  3313. success: true,
  3314. output: `OK${F}missing value${F}missing value`,
  3315. });
  3316. const saved = manager.saveAttachmentById("x-coredata://ABC/ICNote/p1", "att-1", dest);
  3317. expect(saved.success).toBe(true);
  3318. expect(saved.name).toBeUndefined();
  3319. expect(saved.contentType).toBeUndefined();
  3320. } finally {
  3321. rmSync(dir, { recursive: true, force: true });
  3322. }
  3323. });
  3324. });
  3325. describe("listAttachments", () => {
  3326. it("returns attachments for a note by title", () => {
  3327. mockExecuteAppleScript.mockReturnValueOnce({
  3328. success: true,
  3329. output: ["attach-id", "image.png", "public.png"].join(F),
  3330. });
  3331. const attachments = manager.listAttachments("My Note");
  3332. expect(attachments).toHaveLength(1);
  3333. expect(attachments[0]).toMatchObject({
  3334. id: "attach-id",
  3335. name: "image.png",
  3336. contentType: "public.png",
  3337. contentId: "public.png",
  3338. });
  3339. });
  3340. it("uses specified account", () => {
  3341. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3342. manager.listAttachments("My Note", "Gmail");
  3343. expect(mockExecuteAppleScript).toHaveBeenCalledWith(
  3344. expect.stringContaining('every account whose name is "Gmail"')
  3345. );
  3346. });
  3347. it("defaults to Notes.app's own default account, not a hardcoded iCloud", () => {
  3348. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3349. manager.listAttachments("My Note");
  3350. const script = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
  3351. expect(script).toContain("set __acctRef to default account");
  3352. expect(script).not.toContain('"iCloud"');
  3353. });
  3354. it("returns empty array when note has no attachments", () => {
  3355. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
  3356. const attachments = manager.listAttachments("Empty Note");
  3357. expect(attachments).toEqual([]);
  3358. });
  3359. });
  3360. // ---------------------------------------------------------------------------
  3361. // Batch Operations
  3362. // ---------------------------------------------------------------------------
  3363. describe("batchMoveNotes", () => {
  3364. const ID1 = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICNote/p1";
  3365. const ID2 = "x-coredata://ABC00000-0000-0000-0000-000000000012/ICNote/p2";
  3366. it("moves the whole batch in a single osascript spawn (#26)", () => {
  3367. mockExecuteAppleScript.mockReturnValueOnce({
  3368. success: true,
  3369. output: ["ok", "ok"].join(R) + R,
  3370. });
  3371. const results = manager.batchMoveNotes([ID1, ID2], "Archive");
  3372. expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
  3373. expect(results).toHaveLength(2);
  3374. expect(results[0]).toEqual({ id: ID1, success: true });
  3375. expect(results[1]).toEqual({ id: ID2, success: true });
  3376. const script = String(mockExecuteAppleScript.mock.calls[0][0]);
  3377. expect(script).toContain("id of actualFolder");
  3378. expect(script).toContain('"wrongfolder"');
  3379. // #213: the destination is a live folder id, not a name reference.
  3380. expect(script).toContain('whose name is "Archive"');
  3381. expect(script).toContain("if exists folder id destFolder_cid then");
  3382. expect(script).not.toContain('folder "Archive" of __acctRef');
  3383. });
  3384. it("returns error for non-existent note", () => {
  3385. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "missing" + R });
  3386. const results = manager.batchMoveNotes(
  3387. ["x-coredata://ABC00000-0000-0000-0000-000000000099/ICNote/p404"],
  3388. "Archive"
  3389. );
  3390. expect(results[0]).toEqual({
  3391. id: "x-coredata://ABC00000-0000-0000-0000-000000000099/ICNote/p404",
  3392. success: false,
  3393. error: "Note not found",
  3394. committed: false,
  3395. indeterminate: false,
  3396. });
  3397. });
  3398. it("returns error for password-protected note", () => {
  3399. mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "pw" + R });
  3400. const results = manager.batchMoveNotes([ID1], "Archive");
  3401. expect(results[0]).toEqual({
  3402. id: ID1,
  3403. success: false,
  3404. error: "Note is password-protected",
  3405. committed: false,
  3406. indeterminate: false,
  3407. });
  3408. });
  3409. it("maps a per-item move failure to 'Move failed'", () => {
  3410. mockExecuteAppleScript.mockReturnValueOnce({
  3411. success: true,
  3412. output: ["ok", "fail"].join(R) + R,
  3413. });
  3414. const results = manager.batchMoveNotes([ID1, ID2], "Archive");
  3415. expect(results[0]).toEqual({ id: ID1, success: true });
  3416. expect(results[1]).toEqual({
  3417. id: ID2,
  3418. success: false,
  3419. error: "Move failed",
  3420. indeterminate: true,
  3421. });
  3422. });
  3423. it("reports a move whose destination folder cannot be verified", () => {
  3424. mockExecuteAppleScript.mockReturnValueOnce({
  3425. success: true,
  3426. output: "wrongfolder" + R,
  3427. });
  3428. const results = manager.batchMoveNotes([ID1], "Archive");
  3429. expect(results[0]).toEqual({
  3430. id: ID1,
  3431. success: false,
  3432. error: "Destination folder verification failed",
  3433. indeterminate: true,
  3434. });
  3435. });
  3436. });
  3437. // ---------------------------------------------------------------------------
  3438. // Export Operations
  3439. // ---------------------------------------------------------------------------
  3440. describe("exportNotesAsJson", () => {
  3441. // Note details output helper - format: title, id, date, date, shared, passwordProtected
  3442. const noteDetailsOutput = (title: string, passwordProtected = false) =>
  3443. [
  3444. title,
  3445. "x-coredata://ABC/ICNote/p1",
  3446. "Sunday, January 1, 2025 at 1:00:00 PM",
  3447. "Sunday, January 1, 2025 at 1:00:00 PM",
  3448. "false",
  3449. String(passwordProtected),
  3450. ].join(F);
  3451. it("exports notes with metadata and content", () => {
  3452. mockExecuteAppleScript
  3453. // listAccounts
  3454. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3455. // listFolders for iCloud
  3456. .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
  3457. // listNotes for Notes folder
  3458. .mockReturnValueOnce({
  3459. success: true,
  3460. output: ["Test Note", "x-coredata://ABC/ICNote/p1"].join(F),
  3461. })
  3462. // getNoteDetails
  3463. .mockReturnValueOnce({ success: true, output: noteDetailsOutput("Test Note", false) })
  3464. // getNoteContent
  3465. .mockReturnValueOnce({
  3466. success: true,
  3467. output: "<div>Test Note</div><div>Content here</div>",
  3468. });
  3469. const result = manager.exportNotesAsJson() as {
  3470. exportDate: string;
  3471. version: string;
  3472. accounts: { name: string; folders: { name: string; notes: object[] }[] }[];
  3473. summary: { totalNotes: number; totalFolders: number; totalAccounts: number };
  3474. };
  3475. expect(result.version).toBe("1.0");
  3476. expect(result.exportDate).toBeDefined();
  3477. expect(result.summary.totalNotes).toBe(1);
  3478. expect(result.summary.totalFolders).toBe(1);
  3479. expect(result.summary.totalAccounts).toBe(1);
  3480. expect(result.accounts[0].name).toBe("iCloud");
  3481. expect(result.accounts[0].folders[0].name).toBe("Notes");
  3482. expect(result.accounts[0].folders[0].notes).toHaveLength(1);
  3483. });
  3484. it("skips content for password-protected notes", () => {
  3485. mockExecuteAppleScript
  3486. // listAccounts
  3487. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3488. // listFolders for iCloud
  3489. .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
  3490. // listNotes for Notes folder
  3491. .mockReturnValueOnce({
  3492. success: true,
  3493. output: ["Locked Note", "x-coredata://ABC/ICNote/p1"].join(F),
  3494. })
  3495. // getNoteDetails (passwordProtected = true)
  3496. .mockReturnValueOnce({ success: true, output: noteDetailsOutput("Locked Note", true) });
  3497. // No getNoteContent call because note is password-protected
  3498. const result = manager.exportNotesAsJson() as {
  3499. accounts: { folders: { notes: { content: string; passwordProtected: boolean }[] }[] }[];
  3500. };
  3501. const note = result.accounts[0].folders[0].notes[0];
  3502. expect(note.passwordProtected).toBe(true);
  3503. expect(note.content).toBe("");
  3504. });
  3505. it("handles empty accounts", () => {
  3506. mockExecuteAppleScript
  3507. // listAccounts
  3508. .mockReturnValueOnce({ success: true, output: "iCloud" })
  3509. // listFolders for iCloud
  3510. .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
  3511. // listNotes returns empty
  3512. .mockReturnValueOnce({ success: true, output: "" });
  3513. const result = manager.exportNotesAsJson() as {
  3514. summary: { totalNotes: number };
  3515. };
  3516. expect(result.summary.totalNotes).toBe(0);
  3517. });
  3518. it("exports both notes when two notes share an exact title", () => {
  3519. const idA = "x-coredata://ABC/ICNote/p1";
  3520. const idB = "x-coredata://ABC/ICNote/p2";
  3521. const title = "Duplicate Title";
  3522. const detailsFor = (id: string) =>
  3523. [
  3524. title,
  3525. id,
  3526. "Sunday, January 1, 2025 at 1:00:00 PM",
  3527. "Sunday, January 1, 2025 at 1:00:00 PM",
  3528. "false",
  3529. "false",
  3530. ].join(F);
  3531. const contentFor = (id: string) =>
  3532. id === idA ? "<div>Content A</div>" : "<div>Content B</div>";
  3533. let callIndex = 0;
  3534. mockExecuteAppleScript.mockImplementation((script: string) => {
  3535. callIndex++;
  3536. if (callIndex === 1) return { success: true, output: "iCloud" }; // listAccounts
  3537. if (callIndex === 2) return { success: true, output: "id1\tNotes" }; // listFolders
  3538. if (callIndex === 3) {
  3539. // Bulk listNotes fetch: two distinct notes, same title, different ids.
  3540. return { success: true, output: [title + F + idA, title + F + idB].join(R) };
  3541. }
  3542. // Any later lookup keyed by id resolves to the real, distinct note.
  3543. // A lookup keyed only by (ambiguous, duplicated) title mirrors real
  3544. // AppleScript's `note "<name>"` behavior: it deterministically
  3545. // resolves to the same one note every time, regardless of which
  3546. // iteration is asking.
  3547. const idMatch = script.match(/note id "([^"]+)"/);
  3548. const targetId = idMatch ? idMatch[1] : idA;
  3549. if (script.includes("get body of note")) {
  3550. return { success: true, output: contentFor(targetId) };
  3551. }
  3552. return { success: true, output: detailsFor(targetId) };
  3553. });
  3554. const result = manager.exportNotesAsJson() as {
  3555. summary: { totalNotes: number };
  3556. accounts: { folders: { notes: { id: string; content: string }[] }[] }[];
  3557. };
  3558. const notes = result.accounts[0].folders[0].notes;
  3559. expect(result.summary.totalNotes).toBe(2);
  3560. expect(notes.map((n) => n.id).sort()).toEqual([idA, idB].sort());
  3561. expect(notes.find((n) => n.id === idA)?.content).toBe(contentFor(idA));
  3562. expect(notes.find((n) => n.id === idB)?.content).toBe(contentFor(idB));
  3563. });
  3564. });
  3565. describe("exportNotesAsJson paging and response size budget (#162)", () => {
  3566. type Page = {
  3567. offset: number;
  3568. limit: number;
  3569. totalAvailable: number;
  3570. returned: number;
  3571. nextOffset?: number;
  3572. hasMore: boolean;
  3573. stoppedAtSizeLimit: boolean;
  3574. };
  3575. type ExportedPage = {
  3576. summary: { totalNotes: number; totalFolders: number };
  3577. page: Page;
  3578. accounts: {
  3579. folders: {
  3580. name: string;
  3581. notes: {
  3582. id: string;
  3583. content: string;
  3584. plaintext: string;
  3585. strippedImages?: number;
  3586. contentOmitted?: boolean;
  3587. }[];
  3588. }[];
  3589. }[];
  3590. };
  3591. const noteIds = (n: number) =>
  3592. Array.from({ length: n }, (_, i) => `x-coredata://ABC/ICNote/p${i + 1}`);
  3593. const exportedIds = (page: ExportedPage) =>
  3594. page.accounts.flatMap((a) => a.folders.flatMap((f) => f.notes.map((n) => n.id)));
  3595. /**
  3596. * One iCloud account whose folders hold the given [id, body] notes. Each
  3597. * script is answered by what it asks for; body reads are recorded.
  3598. */
  3599. const mockLibrary = (folders: Record<string, [string, string][]>) => {
  3600. const bodyReads: string[] = [];
  3601. mockExecuteAppleScript.mockImplementation((script: string) => {
  3602. if (script.includes("repeat with a in accounts"))
  3603. return { success: true, output: "iCloud" };
  3604. if (script.includes("set allFolders to every folder")) {
  3605. return {
  3606. success: true,
  3607. output: Object.keys(folders)
  3608. .map((name, i) => [`f${i}`, name, "", "false", "iCloud"].join(F))
  3609. .join(R),
  3610. };
  3611. }
  3612. if (script.includes("set noteNames to name of")) {
  3613. const folder = Object.keys(folders).find((name) => script.includes(`folder "${name}"`));
  3614. const notes = folder ? folders[folder] : [];
  3615. return {
  3616. success: true,
  3617. output: notes.map(([id]) => [`Title ${id}`, id].join(F)).join(R),
  3618. };
  3619. }
  3620. const id = script.match(/note id "([^"]+)"/)?.[1] ?? "";
  3621. const body =
  3622. Object.values(folders)
  3623. .flat()
  3624. .find(([noteId]) => noteId === id)?.[1] ?? "";
  3625. if (script.includes("get body of note id")) {
  3626. bodyReads.push(id);
  3627. return { success: true, output: body };
  3628. }
  3629. return {
  3630. success: true,
  3631. output: [`Title ${id}`, id, "2025-1-1-0-0-0", "2025-1-1-0-0-0", "false", "false"].join(F),
  3632. };
  3633. });
  3634. return bodyReads;
  3635. };
  3636. it("returns the requested window across folders and reads bodies only for it", () => {
  3637. const [a, b, c, d, e] = noteIds(5);
  3638. const bodyReads = mockLibrary({
  3639. Notes: [
  3640. [a, "<div>a</div>"],
  3641. [b, "<div>b</div>"],
  3642. [c, "<div>c</div>"],
  3643. ],
  3644. Work: [
  3645. [d, "<div>d</div>"],
  3646. [e, "<div>e</div>"],
  3647. ],
  3648. });
  3649. const result = manager.exportNotesAsJson({ offset: 2, limit: 2 }) as unknown as ExportedPage;
  3650. expect(exportedIds(result)).toEqual([c, d]);
  3651. expect(bodyReads).toEqual([c, d]);
  3652. expect(result.summary.totalNotes).toBe(2);
  3653. expect(result.summary.totalFolders).toBe(2);
  3654. expect(result.page).toEqual({
  3655. offset: 2,
  3656. limit: 2,
  3657. totalAvailable: 5,
  3658. returned: 2,
  3659. nextOffset: 4,
  3660. hasMore: true,
  3661. stoppedAtSizeLimit: false,
  3662. });
  3663. });
  3664. it("reports the final page without a nextOffset", () => {
  3665. const [a, b] = noteIds(2);
  3666. mockLibrary({
  3667. Notes: [
  3668. [a, "<div>a</div>"],
  3669. [b, "<div>b</div>"],
  3670. ],
  3671. });
  3672. const result = manager.exportNotesAsJson({ offset: 1 }) as unknown as ExportedPage;
  3673. expect(exportedIds(result)).toEqual([b]);
  3674. expect(result.page.hasMore).toBe(false);
  3675. expect(result.page.nextOffset).toBeUndefined();
  3676. expect(result.page.totalAvailable).toBe(2);
  3677. });
  3678. it("bounds a no-argument export to the default page size", () => {
  3679. const all = noteIds(DEFAULT_EXPORT_PAGE_SIZE + 10);
  3680. const bodyReads = mockLibrary({
  3681. Notes: all.map((id) => [id, "<div>x</div>"] as [string, string]),
  3682. });
  3683. const result = manager.exportNotesAsJson() as unknown as ExportedPage;
  3684. expect(result.summary.totalNotes).toBe(DEFAULT_EXPORT_PAGE_SIZE);
  3685. expect(bodyReads).toHaveLength(DEFAULT_EXPORT_PAGE_SIZE);
  3686. expect(result.page.nextOffset).toBe(DEFAULT_EXPORT_PAGE_SIZE);
  3687. expect(result.page.hasMore).toBe(true);
  3688. });
  3689. it("stops a page before it outgrows the response budget, then resumes at the next note", () => {
  3690. const body = `<div>${"x".repeat(10_000)}</div>`;
  3691. const all = noteIds(4);
  3692. mockLibrary({ Notes: all.map((id) => [id, body] as [string, string]) });
  3693. const first = manager.exportNotesAsJson({
  3694. maxResponseBytes: 100_000,
  3695. }) as unknown as ExportedPage;
  3696. expect(exportedIds(first)).toEqual(all.slice(0, 2));
  3697. expect(first.page).toMatchObject({ nextOffset: 2, hasMore: true, stoppedAtSizeLimit: true });
  3698. const second = manager.exportNotesAsJson({
  3699. offset: 2,
  3700. maxResponseBytes: 100_000,
  3701. }) as unknown as ExportedPage;
  3702. expect(exportedIds(second)).toEqual(all.slice(2));
  3703. expect(second.page).toMatchObject({ hasMore: false, stoppedAtSizeLimit: false });
  3704. for (const note of [...first.accounts, ...second.accounts].flatMap((a) =>
  3705. a.folders.flatMap((f) => f.notes)
  3706. )) {
  3707. expect(note.content).toBe(body);
  3708. expect(note.contentOmitted).toBeUndefined();
  3709. }
  3710. });
  3711. it("degrades a single note that alone exceeds the budget instead of failing", () => {
  3712. const [img, markup, text] = noteIds(3);
  3713. mockLibrary({
  3714. Notes: [
  3715. [img, `<div>caption</div><img src="data:image/png;base64,${"A".repeat(300_000)}">`],
  3716. [markup, `<div>${"<b>z</b>".repeat(20_000)}</div>`],
  3717. [text, `<div>${"y".repeat(200_000)}</div>`],
  3718. ],
  3719. });
  3720. const onlyNote = (offset: number) =>
  3721. (
  3722. manager.exportNotesAsJson({
  3723. offset,
  3724. limit: 1,
  3725. maxResponseBytes: 100_000,
  3726. }) as unknown as ExportedPage
  3727. ).accounts[0].folders[0].notes[0];
  3728. // 1. Oversized inline images are replaced with placeholders first.
  3729. const imgNote = onlyNote(0);
  3730. expect(imgNote.id).toBe(img);
  3731. expect(imgNote.strippedImages).toBe(1);
  3732. expect(imgNote.content).toContain("caption");
  3733. expect(imgNote.content).not.toContain("A".repeat(1000));
  3734. expect(imgNote.contentOmitted).toBeUndefined();
  3735. // 2. Otherwise the HTML body is omitted but the plaintext is kept.
  3736. const markupNote = onlyNote(1);
  3737. expect(markupNote.contentOmitted).toBe(true);
  3738. expect(markupNote.content).toBe("");
  3739. expect(markupNote.plaintext).toBe("z".repeat(20_000));
  3740. // 3. And if even the plaintext cannot fit, both are omitted.
  3741. const textNote = onlyNote(2);
  3742. expect(textNote.contentOmitted).toBe(true);
  3743. expect(textNote.content).toBe("");
  3744. expect(textNote.plaintext).toBe("");
  3745. });
  3746. it("applies modifiedSince to the listing before paging", () => {
  3747. const [a] = noteIds(1);
  3748. mockLibrary({ Notes: [[a, "<div>a</div>"]] });
  3749. manager.exportNotesAsJson({ modifiedSince: "2025-06-15" });
  3750. const listScript = mockExecuteAppleScript.mock.calls
  3751. .map(([script]) => script)
  3752. .find((script) => script.includes("set noteNames to name of"));
  3753. expect(listScript).toContain("thresholdDate");
  3754. });
  3755. it("reads the response budget from APPLE_NOTES_MCP_EXPORT_MAX_BYTES", () => {
  3756. expect(exportMaxResponseBytes({})).toBe(8 * 1024 * 1024);
  3757. expect(exportMaxResponseBytes({ APPLE_NOTES_MCP_EXPORT_MAX_BYTES: "2048" })).toBe(2048);
  3758. expect(exportMaxResponseBytes({ APPLE_NOTES_MCP_EXPORT_MAX_BYTES: "nope" })).toBe(
  3759. 8 * 1024 * 1024
  3760. );
  3761. });
  3762. it("estimates both copies of a note that a tool response carries", () => {
  3763. const note = {
  3764. id: "x-coredata://ABC/ICNote/p1",
  3765. title: 'A "quoted" title',
  3766. content: '<div class="a">b\\c</div>',
  3767. plaintext: "b\\c",
  3768. folder: "Notes",
  3769. account: "iCloud",
  3770. created: "2025-01-01T00:00:00.000Z",
  3771. modified: "2025-01-01T00:00:00.000Z",
  3772. shared: false,
  3773. passwordProtected: false,
  3774. };
  3775. const structuredCopy = Buffer.byteLength(JSON.stringify(note));
  3776. const escapedTextCopy = Buffer.byteLength(JSON.stringify(JSON.stringify(note, null, 2)));
  3777. expect(estimateExportNoteBytes(note)).toBeGreaterThan(structuredCopy + escapedTextCopy);
  3778. });
  3779. });
  3780. // ---------------------------------------------------------------------------
  3781. // Markdown Conversion
  3782. // ---------------------------------------------------------------------------
  3783. describe("getNoteMarkdown", () => {
  3784. it("converts HTML to Markdown", () => {
  3785. mockExecuteAppleScript.mockReturnValueOnce({
  3786. success: true,
  3787. output: "<div>My Title</div><div>This is a paragraph.</div><div><b>Bold text</b></div>",
  3788. });
  3789. const markdown = manager.getNoteMarkdown("My Note");
  3790. expect(markdown).toContain("My Title");
  3791. expect(markdown).toContain("This is a paragraph.");
  3792. expect(markdown).toContain("**Bold text**");
  3793. });
  3794. it("returns empty string when note not found", () => {
  3795. mockExecuteAppleScript.mockReturnValueOnce({
  3796. success: false,
  3797. output: "",
  3798. error: "Note not found",
  3799. });
  3800. const markdown = manager.getNoteMarkdown("Missing Note");
  3801. expect(markdown).toBe("");
  3802. });
  3803. it("handles lists correctly", () => {
  3804. mockExecuteAppleScript.mockReturnValueOnce({
  3805. success: true,
  3806. output: "<ul><li>Item 1</li><li>Item 2</li></ul>",
  3807. });
  3808. const markdown = manager.getNoteMarkdown("List Note");
  3809. // Turndown may add extra whitespace after the bullet
  3810. expect(markdown).toMatch(/-\s+Item 1/);
  3811. expect(markdown).toMatch(/-\s+Item 2/);
  3812. });
  3813. });
  3814. describe("getNoteMarkdownById", () => {
  3815. it("converts HTML to Markdown using ID", () => {
  3816. mockExecuteAppleScript.mockReturnValueOnce({
  3817. success: true,
  3818. output: "<div>Note Title</div><div>Content here</div>",
  3819. });
  3820. const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p123");
  3821. expect(markdown).toContain("Note Title");
  3822. expect(markdown).toContain("Content here");
  3823. });
  3824. it("returns empty string when note ID not found", () => {
  3825. mockExecuteAppleScript.mockReturnValueOnce({
  3826. success: false,
  3827. output: "",
  3828. error: "Note not found",
  3829. });
  3830. const markdown = manager.getNoteMarkdownById(
  3831. "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
  3832. );
  3833. expect(markdown).toBe("");
  3834. });
  3835. it("enriches markdown with checklist state when available", () => {
  3836. mockExecuteAppleScript.mockReturnValueOnce({
  3837. success: true,
  3838. output: "<ul><li>Buy milk</li><li>Walk dog</li><li>Send email</li></ul>",
  3839. });
  3840. mockGetChecklistItems.mockReturnValueOnce({
  3841. items: [
  3842. { text: "Buy milk", done: true },
  3843. { text: "Walk dog", done: false },
  3844. { text: "Send email", done: true },
  3845. ],
  3846. });
  3847. const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p123");
  3848. expect(markdown).toMatch(/-\s+\[x\] Buy milk/);
  3849. expect(markdown).toMatch(/-\s+\[ \] Walk dog/);
  3850. expect(markdown).toMatch(/-\s+\[x\] Send email/);
  3851. });
  3852. it("returns plain markdown when checklist state is unavailable", () => {
  3853. mockExecuteAppleScript.mockReturnValueOnce({
  3854. success: true,
  3855. output: "<ul><li>Item 1</li><li>Item 2</li></ul>",
  3856. });
  3857. mockGetChecklistItems.mockReturnValueOnce({
  3858. items: null,
  3859. error: "no_fda",
  3860. message: "Full Disk Access required",
  3861. });
  3862. const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p456");
  3863. expect(markdown).toMatch(/-\s+Item 1/);
  3864. expect(markdown).toMatch(/-\s+Item 2/);
  3865. expect(markdown).not.toContain("[x]");
  3866. expect(markdown).not.toContain("[ ]");
  3867. });
  3868. });
  3869. // ===========================================================================
  3870. // Security Tests
  3871. // ===========================================================================
  3872. describe("sanitizeId", () => {
  3873. it("accepts valid CoreData IDs", () => {
  3874. const id = "x-coredata://12345ABC-DEF0-1234-5678-9ABCDEF01234/ICNote/p100";
  3875. expect(sanitizeId(id)).toBe(id);
  3876. });
  3877. it("accepts temp IDs from generateFallbackId", () => {
  3878. expect(sanitizeId("temp-1704067200000-0")).toBe("temp-1704067200000-0");
  3879. expect(sanitizeId("temp-1704067200000-42")).toBe("temp-1704067200000-42");
  3880. });
  3881. it("rejects IDs with AppleScript injection", () => {
  3882. expect(() => sanitizeId('x-coredata://test" & do shell script "rm -rf ~" & "')).toThrow(
    • Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
    • Line 4,604 on GitHub
  3883. "Invalid note ID format"
  3884. );
  3885. });
  3886. it("rejects IDs with double-quote breakout", () => {
  3887. expect(() => sanitizeId('x-coredata://test"; delete note id "dummy" & "')).toThrow(
  3888. "Invalid note ID format"
  3889. );
  3890. });
  3891. it("rejects arbitrary strings", () => {
  3892. expect(() => sanitizeId("not-a-valid-id")).toThrow("Invalid note ID format");
  3893. });
  3894. it("rejects empty string", () => {
  3895. expect(() => sanitizeId("")).toThrow("Invalid note ID format");
  3896. });
  3897. it("accepts various ICEntity types", () => {
  3898. expect(sanitizeId("x-coredata://ABC123/ICFolder/p50")).toBe(
  3899. "x-coredata://ABC123/ICFolder/p50"
  3900. );
  3901. expect(sanitizeId("x-coredata://ABC123/ICAttachment/p1")).toBe(
  3902. "x-coredata://ABC123/ICAttachment/p1"
  3903. );
  3904. });
  3905. });
  3906. describe("sanitizeNoteId", () => {
  3907. it("accepts only canonical Apple Note IDs", () => {
  3908. const id = "x-coredata://12345ABC-DEF0-1234-5678-9ABCDEF01234/ICNote/p100";
  3909. expect(sanitizeNoteId(id)).toBe(id);
  3910. });
  3911. it("rejects synthetic IDs and IDs for other CoreData entities", () => {
  3912. expect(() => sanitizeNoteId("temp-1704067200000-0")).toThrow("Invalid note ID format");
  3913. expect(() => sanitizeNoteId("x-coredata://ABC123/ICFolder/p50")).toThrow(
  3914. "Invalid note ID format"
  3915. );
  3916. });
  3917. });
  3918. describe("escapeForAppleScript - injection prevention", () => {
  3919. it("escapes double quotes to prevent AppleScript string breakout", () => {
  3920. const malicious = 'Hello "World" end tell';
  3921. const escaped = escapeForAppleScript(malicious);
  3922. expect(escaped).toContain('\\"');
  3923. expect(escaped).not.toContain('"World"');
  3924. });
  3925. it("escapes backslashes to prevent escape sequence injection", () => {
  3926. const malicious = "path\\to\\file";
  3927. const escaped = escapeForAppleScript(malicious);
  3928. // Backslashes should be encoded as HTML entities (&#92;)
  3929. expect(escaped).toContain("&#92;");
  3930. });
  3931. it("handles combined injection payload", () => {
  3932. const payload = '" & do shell script "echo pwned" & "';
  3933. const escaped = escapeForAppleScript(payload);
  3934. // All double quotes must be escaped with backslash
  3935. // Count unescaped double quotes — there should be none
  3936. const unescapedQuotes = escaped.replace(/\\"/g, "").match(/"/g);
  3937. expect(unescapedQuotes).toBeNull();
  3938. });
  3939. });
  3940. describe("buildFolderReference - input validation", () => {
  3941. it("rejects empty folder paths", () => {
  3942. expect(() => buildFolderReference("")).toThrow("Folder path is empty");
  3943. });
  3944. it("rejects paths that are only slashes", () => {
  3945. expect(() => buildFolderReference("///")).toThrow("Folder path is empty");
  3946. });
  3947. it("rejects excessively deep folder nesting", () => {
  3948. const deepPath = Array(25).fill("folder").join("/");
  3949. expect(() => buildFolderReference(deepPath)).toThrow("maximum nesting depth");
  3950. });
  3951. it("rejects excessively long folder paths", () => {
  3952. const longPath = "a".repeat(1001);
  3953. expect(() => buildFolderReference(longPath)).toThrow("maximum length");
  3954. });
  3955. it("escapes folder names with double quotes", () => {
  3956. const result = buildFolderReference('My "Special" Folder');
  3957. expect(result).toContain('\\"');
  3958. expect(result).not.toContain('"Special"');
  3959. });
  3960. it("handles folder names with emoji", () => {
  3961. const result = buildFolderReference("Food & Drink/\uD83C\uDF72 Recipes");
  3962. expect(result).toContain("folder");
  3963. expect(result).toContain("of");
  3964. });
  3965. });
  3966. describe("ID-based operations sanitize input", () => {
  3967. it("getNoteById rejects malformed IDs", () => {
  3968. expect(() => {
  3969. manager.getNoteById('malicious" & do shell script "echo pwned');
  3970. }).toThrow("Invalid note ID format");
  3971. });
  3972. it("getNoteContentById rejects malformed IDs", () => {
  3973. expect(() => {
  3974. manager.getNoteContentById("arbitrary string");
  3975. }).toThrow("Invalid note ID format");
  3976. });
  3977. it("updateNoteByIdIfUnchanged rejects malformed IDs", () => {
  3978. expect(() => {
  3979. manager.updateNoteByIdIfUnchanged(
  3980. "not-valid",
  3981. "Title",
  3982. "<div>Body</div>",
  3983. undefined,
  3984. "content"
  3985. );
  3986. }).toThrow("Invalid note ID format");
  3987. });
  3988. it("deleteNoteByIdIfUnchanged rejects malformed IDs", () => {
  3989. expect(() => {
  3990. manager.deleteNoteByIdIfUnchanged(
  3991. 'x-coredata://test"; delete note 1 & "',
  3992. "<div>Body</div>"
  3993. );
  3994. }).toThrow("Invalid note ID format");
  3995. });
  3996. it("moveNoteById rejects malformed IDs", () => {
  3997. expect(() => {
  3998. manager.moveNoteById("not-valid", "Archive");
  3999. }).toThrow("Invalid note ID format");
  4000. });
  4001. // #146: batchMoveNotes validated with the looser sanitizeId (accepts any
  4002. // ICEntity, plus legacy temp-* ids), unlike every other #144-hardened
  4003. // mutation — bring it in line with moveNoteById's sanitizeNoteId.
  4004. it("batchMoveNotes rejects a non-ICNote CoreData ID as a per-item failure, without spawning osascript", () => {
  4005. const results = manager.batchMoveNotes(
  4006. ["x-coredata://ABC123/ICFolder/p50", "temp-1704067200000-0"],
  4007. "Archive"
  4008. );
  4009. expect(mockExecuteAppleScript).not.toHaveBeenCalled();
  4010. expect(results[0]).toEqual({
  4011. id: "x-coredata://ABC123/ICFolder/p50",
  4012. success: false,
  4013. error: expect.stringContaining("Invalid note ID format"),
  4014. committed: false,
  4015. indeterminate: false,
  4016. });
  4017. expect(results[1]).toEqual({
  4018. id: "temp-1704067200000-0",
  4019. success: false,
  4020. error: expect.stringContaining("Invalid note ID format"),
  4021. committed: false,
  4022. indeterminate: false,
  4023. });
  4024. });
  4025. });
  4026. // ---------------------------------------------------------------------------
  4027. // getNoteLinkById
  4028. // ---------------------------------------------------------------------------
  4029. describe("getNoteLinkById", () => {
  4030. const VALID_ID = "x-coredata://ABC123/ICNote/p50338";
  4031. it("returns null immediately for a password-protected note without calling executeAppleScript for the link", () => {
  4032. // First call: getNoteById (returns a protected note)
  4033. mockExecuteAppleScript.mockReturnValueOnce({
  4034. success: true,
  4035. output: [
  4036. "Locked Note",
  4037. VALID_ID,
  4038. "2025-12-27-15-0-0",
  4039. "2025-12-27-15-0-0",
  4040. "false",
  4041. "true", // passwordProtected = true
  4042. ].join(F),
  4043. });
  4044. const result = manager.getNoteLinkById(VALID_ID);
  4045. expect(result).toBeNull();
  4046. // The link-fetching AppleScript (note link property) must NOT be called
  4047. // — the function should bail out after the password check.
  4048. const calls = mockExecuteAppleScript.mock.calls;
  4049. // Only one call: getNoteById
  4050. expect(calls).toHaveLength(1);
  4051. });
  4052. it("returns null when the note is not found", () => {
  4053. mockExecuteAppleScript.mockReturnValueOnce({
  4054. success: false,
  4055. output: "",
  4056. error: "Can't get note id",
  4057. });
  4058. const result = manager.getNoteLinkById(VALID_ID);
  4059. expect(result).toBeNull();
  4060. });
  4061. it("returns a notes:// URL for a valid, non-protected note", () => {
  4062. // getNoteById returns a non-protected note
  4063. mockExecuteAppleScript.mockReturnValueOnce({
  4064. success: true,
  4065. output: [
  4066. "My Note",
  4067. VALID_ID,
  4068. "2025-12-27-15-0-0",
  4069. "2025-12-27-15-0-0",
  4070. "false",
  4071. "false",
  4072. ].join(F),
  4073. });
  4074. // SQLite path (getNoteLinkFromDB) may succeed (if the Notes DB is
  4075. // accessible on the test machine) or fail and fall through to the
  4076. // AppleScript fallback. Mock the AppleScript fallback so it can
  4077. // return a URL in the fallback-path case.
  4078. mockExecuteAppleScript.mockReturnValueOnce({
  4079. success: true,
  4080. output: "notes://showNote?identifier=ABCD-1234-5678",
  4081. });
  4082. const result = manager.getNoteLinkById(VALID_ID);
  4083. // Either the SQLite path or the AppleScript fallback should return
  4084. // a notes:// URL — either form is acceptable.
  4085. expect(result).not.toBeNull();
  4086. expect(result).toMatch(/^notes:\/\/showNote\?identifier=/);
  4087. });
  4088. });
  4089. });
  4090. describe("getNoteLinkFromDB — CoreData PK parsing", () => {
  4091. // getNoteLinkFromDB is module-private, but we can verify the PK extraction
  4092. // logic indirectly by checking that getNoteLinkById passes the right primary
  4093. // key to the database query. We test the regex rule by covering the
  4094. // CoreData ID formats the function must handle.
  4095. it("sanitizeId accepts the x-coredata URL used by getNoteLinkById", () => {
  4096. // If sanitizeId throws, getNoteLinkById would not even reach the DB call.
  4097. // This assertion confirms the ID format is considered valid.
  4098. expect(() => sanitizeId("x-coredata://ABC123/ICNote/p50338")).not.toThrow();
  4099. });
  4100. it("sanitizeId rejects IDs without a /p<digits> suffix", () => {
  4101. expect(() => sanitizeId("x-coredata://ABC123/ICNote/pXXX")).toThrow("Invalid note ID format");
  4102. });
  4103. });
  4104. describe("htmlToPlaintext (export helper)", () => {
  4105. // htmlToPlaintext is a private, pure string transform used by exportNote; it
  4106. // touches no AppleScript, so we exercise it directly through a cast.
  4107. const toPlaintext = (html: string): string =>
  4108. (
  4109. new AppleNotesManager() as unknown as {
  4110. htmlToPlaintext(h: string): string;
  4111. }
  4112. ).htmlToPlaintext(html);
  4113. it("decodes the basic HTML entities", () => {
  4114. expect(toPlaintext("a &amp; b")).toBe("a & b");
  4115. expect(toPlaintext("&lt;tag&gt;")).toBe("<tag>");
  4116. expect(toPlaintext("say &quot;hi&quot;")).toBe('say "hi"');
  4117. expect(toPlaintext("path&#92;file")).toBe("path\\file");
  4118. expect(toPlaintext("a&nbsp;b")).toBe("a b");
  4119. });
  4120. it("decodes &amp; last so encoded entities round-trip (no double-unescape)", () => {
  4121. // The literal text "&lt;" is stored in HTML as "&amp;lt;" and must decode
  4122. // back to "&lt;", NOT be double-unescaped to "<".
  4123. expect(toPlaintext("&amp;lt;")).toBe("&lt;");
  4124. expect(toPlaintext("&amp;gt;")).toBe("&gt;");
  4125. expect(toPlaintext("&amp;amp;")).toBe("&amp;");
  4126. expect(toPlaintext("&amp;nbsp;")).toBe("&nbsp;");
  4127. });
  4128. it("converts block/line tags to newlines and strips other tags", () => {
  4129. expect(toPlaintext("one<br>two")).toBe("one\ntwo");
  4130. expect(toPlaintext("<div>a</div><div>b</div>")).toBe("a\nb");
  4131. expect(toPlaintext("<p>x</p><p>y</p>")).toBe("x\ny");
  4132. expect(toPlaintext("<b>bold</b>")).toBe("bold");
  4133. });
  4134. it("collapses 3+ newlines and trims surrounding whitespace", () => {
  4135. expect(toPlaintext("a<br><br><br><br>b")).toBe("a\n\nb");
  4136. expect(toPlaintext(" <div>x</div> ")).toBe("x");
  4137. });
  4138. it("strips nested/overlapping tags without leaving a tag (iterated strip)", () => {
  4139. // A single pass can leave residue when removing one tag re-forms another;
  4140. // the loop keeps stripping until no <...> remains.
  4141. expect(toPlaintext("a<<i>>b")).not.toMatch(/<[^>]*>/);
  4142. expect(toPlaintext("<x<y>z>")).not.toMatch(/<[^>]*>/);
  4143. expect(toPlaintext("plain <b>text</b> here")).toBe("plain text here");
  4144. });
  4145. });
  4146. describe("getAudioTranscripts", () => {
  4147. it("delegates to the read-only transcript reader with the caller's options", () => {
  4148. const result = {
  4149. id: "x-coredata://S/ICNote/p1",
  4150. attachments: [],
  4151. bodyOrder: true,
  4152. truncated: false,
  4153. };
  4154. mockReadAudioTranscripts.mockReturnValueOnce(result);
  4155. const manager = new AppleNotesManager();
  4156. expect(
  4157. manager.getAudioTranscripts("x-coredata://S/ICNote/p1", {
  4158. includeSegments: true,
  4159. maxSegments: 5,
  4160. })
  4161. ).toBe(result);
  4162. expect(mockReadAudioTranscripts).toHaveBeenCalledWith("x-coredata://S/ICNote/p1", {
  4163. includeSegments: true,
  4164. maxSegments: 5,
  4165. });
  4166. });
  4167. });

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.