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.
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
Markdown
[](/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
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
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "apple-notes-mcp",
- "version": "1.0.0",
- "description": "Apple Notes integration for Claude Code via MCP",
- "owner": {
- "name": "Rob Sweet",
- "email": "rob@superiortech.io"
- },
- "plugins": [
- {
- "name": "apple-notes",
- "description": "Manage Apple Notes through natural language - create, search, read, update, delete, and organize notes and folders",
- "version": "2.16.8",
- "author": {
- "name": "Rob Sweet",
- "email": "rob@superiortech.io"
- },
- "source": "./",
- "category": "productivity"
- }
- ]
- }
README.md · README · 3,229 lines
- # Apple Notes MCP Server
- 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.
- 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.
- [](https://www.npmjs.com/package/apple-notes-mcp)
- [](https://www.npmjs.com/package/apple-notes-mcp)
- [](https://www.npmjs.com/package/apple-notes-mcp)
- [](https://github.com/sweetrb/apple-notes-mcp/actions/workflows/ci.yml)
- [](https://scorecard.dev/viewer/?uri=github.com/sweetrb/apple-notes-mcp)
- [](https://www.apple.com/macos/)
- [](https://opensource.org/licenses/MIT)
- [](https://modelcontextprotocol.io)
- <p align="center">
- <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">
- </p>
- ## Contents
- - [What is This?](#what-is-this) · [Setup on your Mac](#setup-on-your-mac) · [Requirements](#requirements) · [macOS compatibility](#macos-compatibility) · [Features](#features)
- - [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)
- - [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)
- - [Security and Privacy](#security-and-privacy) · [Known Limitations](#known-limitations) · [Troubleshooting](#troubleshooting) · [Recurring macOS permission prompts](#recurring-macos-permission-prompts) · [Development](#development)
- ## What is This?
- This server acts as a bridge between AI assistants and Apple Notes. Once configured, you can ask Claude (or any MCP-compatible AI) to:
- - "Save this conversation as a note called 'Meeting Summary'"
- - "Find all my notes about the project deadline"
- - "Read my shopping list note"
- - "Move my draft notes to the Archive folder"
- - "What notes do I have in my Work folder?"
- 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.
- <a id="quick-start"></a>
- ## Setup on your Mac
- 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 |
- | 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 |
- | Classic drawing decode (`get-note-drawings`, needs the helper and Full Disk Access) | Yes | Yes | Yes |
- | 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 |
- | Stored audio transcripts (`get-audio-transcripts`) | With Full Disk Access | With Full Disk Access | With Full Disk Access |
- 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`.
- 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.
- 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)).
- 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.
- 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.
- ### 1. Choose one client registration
- 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.
- #### Claude Code
- For the plugin, run these commands inside a Claude Code session:
- ```text
- /plugin marketplace add sweetrb/apple-notes-mcp#v2.15.1
- /plugin install apple-notes@apple-notes-mcp
- ```
- The plugin bundles the server and the Apple Notes skill. For a manual MCP registration instead, run this in your terminal:
- ```bash
- claude mcp add apple-notes -s user -- npx -y apple-notes-mcp@latest
- ```
- 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.
- #### Claude Desktop
- Open **Settings → Developer → Edit Config**. Merge the following server entry into `~/Library/Application Support/Claude/claude_desktop_config.json`, preserving any existing servers:
- ```json
- {
- "mcpServers": {
- "apple-notes": {
- "command": "npx",
- "args": ["-y", "apple-notes-mcp@latest"]
- }
- }
- }
- ```
- 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.
- #### Codex
- For the plugin and its Apple Notes skill:
- ```bash
- codex plugin marketplace add sweetrb/apple-notes-mcp --ref v2.15.1
- codex plugin add apple-notes@apple-notes-mcp
- ```
- For a manual MCP registration instead:
- ```bash
- codex mcp add apple-notes -- npx -y apple-notes-mcp@latest
- ```
- The equivalent entry in `~/.codex/config.toml` is:
- ```toml
- [mcp_servers.apple-notes]
- command = "npx"
- args = ["-y", "apple-notes-mcp@latest"]
- ```
- 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.
- 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.
- 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.
- #### Hermes
- Register a local stdio server:
- ```bash
- hermes mcp add apple-notes --command npx --args -y apple-notes-mcp@latest
- ```
- Or merge this entry into `~/.hermes/config.yaml`:
- ```yaml
- mcp_servers:
- apple-notes:
- command: npx
- args: ["-y", "apple-notes-mcp@latest"]
- ```
- 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).
- #### Antigravity
- 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.
- 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`.
- #### Gemini Spark (macOS Local MCP)
- 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:
- | Field | Value |
- |-------|-------|
- | Server Name | Apple Notes |
- | Description | Read, search, create, edit, organize, and export Apple Notes on this Mac. |
- | Command | `npx -y apple-notes-mcp@latest` |
- You can print these instructions from the installed server:
- ```bash
- npx -y apple-notes-mcp setup --gemini-spark
- ```
- 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.
- 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.
- 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.
- 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.
- #### Other MCP clients and remote execution
- 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.
- 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.
- The optional `anchors serve` command is a paragraph-link resolver, and `templates edit` is a template editor. Neither is a remote MCP server.
- <a id="full-disk-access"></a>
- <a id="permissions-check"></a>
- ### 2. Verify the server and macOS access
- 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.
- | Access or component | What it enables | How to complete it |
- |---|---|---|
- | 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. |
- | 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`. |
- | Shortcut installation and consent | Native tag, checklist, table, pin, link, and append routes | Import the bridges and complete their foreground consent steps below. |
- | 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. |
- **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.
- 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.
- To inspect setup from a terminal without opening permission panes or requesting Automation access:
- ```bash
- npx -y apple-notes-mcp@latest setup --permissions --check --json
- ```
- 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:
- ```bash
- npx -y apple-notes-mcp@latest setup --permissions --once --probe-automation
- ```
- For an interactive checklist that also opens the relevant settings panes:
- ```bash
- npx -y apple-notes-mcp@latest setup --permissions --open --probe-automation
- ```
- 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.
- 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).
- ### 3. Enable the native Shortcut features you need
- Run explicit setup on your Mac:
- ```bash
- npx -y apple-notes-mcp@latest setup
- ```
- Approve **Add Shortcut** for the missing signed workflows that macOS opens:
- - `Notes MCP Tags`
- - `Notes MCP Background v6`
- - `Notes MCP Markdown`, offered only on macOS 26 or newer and optional for native Markdown creation
- Releases before 2.16.1 installed these as `Apple Notes MCP - Native Tags`,
- `Apple Notes MCP - Background Operations v6` and `Apple Notes MCP - Create Markdown Note`.
- Those still work. To switch to the short names, run `setup` after deleting the old ones
- in Shortcuts.app. Delete `Apple Notes MCP - Background Operations v5` in any case; the
- server no longer uses it.
- Then check installation:
- ```bash
- npx -y apple-notes-mcp@latest setup --check
- ```
- 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.
- 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.
- 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.
- ### 4. Build optional helpers
- 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.
- #### Public native helper
- <a id="public-native-helper"></a>
- 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:
- ```bash
- npx -y apple-notes-mcp@latest setup --public-helper
- npx -y apple-notes-mcp@latest setup --public-helper --check
- ```
- 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.
- 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.
- #### Private helper setup
- 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:
- ```bash
- npx -y apple-notes-mcp@latest setup --native-helper
- npx -y apple-notes-mcp@latest setup --native-helper --check
- ```
- 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.
- #### Optional checklist window
- Optional graphical presentation of the checklist:
- ```bash
- npx -y apple-notes-mcp@latest setup --permissions-window
- npx -y apple-notes-mcp@latest setup --permissions --window
- ```
- It displays the command's checks and opens settings on request. It does not become the permission owner or replace the client process.
- ### 5. Confirm the capabilities you intend to use
- 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.
- 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.
- 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.
- ## Features
- | Feature | Description |
- |---------|-------------|
- | **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) |
- | **Search Notes** | Find notes by title or search within note content |
- | **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) |
- | **Read Notes** | Retrieve note content as HTML, plain text, or Markdown, plus metadata that AppleScript does not expose (pinned, Quick Note, locked, Recently Deleted) |
- | **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) |
- | **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 |
- | **Delete Notes** | Remove notes (moves to Recently Deleted) |
- | **Move Notes** | Organize notes into folders (supports nested paths) |
- | **Folder Management** | Create, list, rename, and delete folders with full hierarchical path support; read the folder tree with note counts and Smart Folder rules |
- | **Multi-Account** | Work with iCloud, Gmail, Exchange, or any configured account, including account IDs and default folders |
- | **Batch Operations** | Delete or move multiple notes at once |
- | **Native Tags** | List, add, remove, and replace real Notes tags (not just `#hashtag` text) |
- | **Checklists** | Read checklist done/undone state from the Notes database, and append real checklist items through a Shortcut |
- | **Tables** | Read native tables as Markdown and JSON, and append new native tables |
- | **Pinning** | Read pinned state and pin or unpin a note |
- | **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 |
- | **Export** | Export notes as paginated JSON, or render a note or folder as Markdown (with reusable templates) or standalone HTML |
- | **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 |
- | **Audio and Drawings** | Read the transcripts Notes stored for recordings, transcribe audio on-device, and decode drawings to strokes and SVG |
- | **Incremental Sync** | `list-recent-notes` pages through notes by modification time with an exact cursor |
- | **Notes.app UI State** | Reveal a note, folder, account, or attachment in Notes.app, or read the current Notes.app selection |
- | **Sync Awareness** | Detect iCloud sync in progress, warn about incomplete results |
- | **Collaboration** | Detect shared notes, warn before modifying |
- | **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 |
- Read/list/get tools also return **structured JSON** (`structuredContent`) alongside the text, so agents can consume results without parsing prose.
- Some clients (Claude Desktop among them) pass the model only a result's text
- and drop `structuredContent`. So every result that has `structuredContent` also
- ends with one more text block holding the same data as a single JSON line:
- ```
- structuredContent: {"id":"x-coredata://…/ICNote/p123","contentHash":"sha256:…","writable":true,…}
- ```
- That line carries every token a follow-up call needs: the `contentHash`
- revision token for `expectedContentHash`, new ids, `nativeTags`, `writable`,
- `page.nextOffset`, and an error's `code`, `committed` and `indeterminate`. A
- long value the text above already shows in full, such as the body from
- `get-note-content`, appears as `"[shown in full above]"` instead of twice. If
- the line would still exceed 16 KB, fields larger than 1 KB (usually a list
- already printed above) are left out and named in `_omitted`. Tools whose text
- already is that JSON get no extra block. `structuredContent` itself is
- unchanged.
- ### MCP resources & prompts
- Resources expose read-only context the client can attach without a tool call:
- `notes://accounts`, `notes://folders`, `notes://stats`, and the
- `notes://note/{id}` template (returns the note as Markdown). Prompts package
- common workflows: `find-note`, `weekly-review`, `new-meeting-note`.
- ### AppleScript limitations
- A few Notes UI features are not exposed to AppleScript. Some are recovered by
- reading Notes' own database instead; the rest genuinely cannot be supported. See
- **[docs/APPLESCRIPT-LIMITATIONS.md](https://github.com/sweetrb/apple-notes-mcp/blob/main/docs/APPLESCRIPT-LIMITATIONS.md)**
- for the investigation and verification behind each:
- - **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).
- - **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).
- ---
- ## Tool Reference
- This section documents all available tools. AI agents should use these tool names and parameters exactly as specified.
- ### Identifier forms
- 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:
- | Form | Example shape | Needs Full Disk Access |
- |------|---------------|------------------------|
- | AppleScript id (canonical) | `x-coredata://<store-uuid>/ICNote/p123` | No |
- | Notes UUID (`identifier`) | `8-4-4-4-12` hex digits, as in `notes://showNote?identifier=` links | Yes |
- | Numeric Core Data key | `123` (the digits after `p`) | Yes |
- 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.
- 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`.
- ### Error results
- A failed call returns `isError: true` with the same human-readable text as
- before, plus `structuredContent` carrying a stable machine-readable `code`
- (also repeated in the trailing `structuredContent:` text line, for clients
- that drop `structuredContent`).
- Branch on `code`, not on the prose, which may be reworded.
- | `code` | Meaning |
- |--------|---------|
- | `not_found` | The note, folder, account, attachment, or checklist does not exist |
- | `ambiguous` | More than one item matched; use an exact id |
- | `permission_denied` | macOS refused Automation access to Notes.app |
- | `full_disk_access_missing` | The Notes database is not readable; grant Full Disk Access |
- | `shortcut_not_installed` | A native-write bridge Shortcut is not installed exactly once |
- | `timeout_indeterminate` | The operation timed out; for a write, the outcome is unknown |
- | `verification_failed` | The write ran, but exact-ID readback did not confirm it |
- | `revision_conflict` | The note changed since it was read |
- | `validation_error` | The request was rejected before anything ran |
- | `unsupported` | Not supported for this note or in this mode, such as a locked note |
- | `notes_unavailable` | Notes.app is not running, busy, or not responding |
- | `operation_failed` | The server could not classify the failure; read the text |
- Two optional booleans describe a write's outcome when it is known.
- `indeterminate: true` means the outcome is uncertain: read the target by exact
- id before any retry, and never retry blindly. `committed: true` means the write
- took effect even though its verification failed; `committed: false` means
- nothing was written (for example a `revision_conflict`). An absent flag means
- unknown. An argument that fails the input schema is rejected before the tool
- runs, with `code: "validation_error"` and `committed: false`. The exception is
- a Notes UUID or numeric key that could not be resolved to an id: it carries
- `not_found`, or `full_disk_access_missing` when the database is unreadable.
- ### Note Operations
- #### `create-note`
- Creates a new note in Apple Notes.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `title` | string | Yes | The title of the note. Automatically prepended as `<h1>` — do NOT include the title in `content` |
- | `content` | string | One of `content`/`contentPath` | The body content of the note (do not repeat the title here) |
- | `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 |
- | `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"` |
- | `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 |
- | `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) |
- | `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) |
- | `markdownRoute` | string | No | With `format: "markdown"` only: `"shortcut"` (default) or `"html"`. See [Markdown through HTML](#markdown-through-html) |
- | `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` |
- **Example (with inline textual hashtags):**
- ```json
- {
- "title": "Meeting Notes",
- "content": "Discussed Q4 roadmap and budget allocation\n\n#work #meetings"
- }
- ```
- **Example - Create in a specific folder:**
- ```json
- {
- "title": "Client Meeting",
- "content": "Discussed project timeline",
- "folder": "Work/Clients"
- }
- ```
- **Example - HTML formatting:**
- ```json
- {
- "title": "Status Report",
- "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>",
- "format": "html"
- }
- ```
- > **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.
- > **Known limitation:** with `"plaintext"` or `"html"`, `create-note` sets the note
- > body directly via AppleScript's `body` property, which does not apply real Notes
- > paragraph styles for interior content — an `<h2>`/`<h3>` tag or a
- > `<span style="font-size: …px">` heading span in `content` renders as plain bold,
- > styled text, not an actual Heading or Subheading
- > ([#172](https://github.com/sweetrb/apple-notes-mcp/issues/172)). Use
- > `format: "markdown"` for real headings in a new note, or
- > [`append-native`](#append-native)'s `format: "markdown"` on a note that already
- > exists.
- ##### Markdown notes
- `format: "markdown"` creates the note with Notes' own Markdown importer (the
- Create Note action's "Interpret as Markdown" option, macOS 26+), run through the
- packaged `Notes MCP Markdown` Shortcut. `#`, `##` and `###`
- become real Title, Heading and Subheading styles, and the note starts with the
- title line, with no seed line.
- ```json
- {
- "title": "Project Plan",
- "content": "## Goals\n\n- Ship the beta\n- Collect feedback\n\n### Links\n\n[Tracker](https://example.com/tracker)",
- "format": "markdown",
- "folder": "Work"
- }
- ```
- - Notes interprets Markdown only in an iCloud account. The note is created in the
- iCloud account's default folder, then moved to `folder` in that account.
- `folder` must already exist and is checked before anything is created. If it
- exists only in another account, the note is still created and verified in the
- iCloud default folder, and the error names that account and the note's id so
- you can create the folder there and `move-note` it instead of creating the
- note again. `account` is refused with this format.
- - `tags` are refused with this format. Create the note without them, then add
- native tags to the returned id with [`add-native-tags`](#add-native-tags).
- - `content` accepts the same bounded subset as `append-native`'s Markdown:
- `#`/`##`/`###` headings, flat lists, `**bold**`, `*italic*` and inline links.
- It also refuses Markdown that Notes would rewrite and the server could not
- verify: `_` emphasis (underscores inside a word, as in `snake_case`, and
- inside a link destination, as in `[docs](https://example.com/_next/static)`,
- are fine), backslash escapes, character references such as `&`, `===` lines
- and rule lines other than the `---` divider described below, indented headings or list items, `1)` lists, closing `#`s, and
- formatting inside link labels. Content that needs one of these literally, such
- as a `/_next` path or a literal `\*`, has no Markdown form here: use
- `format: "html"` for that note (or `append-native` with `format: "html"` on an
- existing one), which keeps the characters but not the Heading and Subheading
- styles. Markdown punctuation in `title` is escaped, so the title stays literal.
- - Notes' importer also maps these block constructs to native styles. They are
- gated separately, and `get-capabilities` reports them as
- `create-note-markdown-blocks`. Each mapping below was live-verified on
- macOS 27.2 by reading the created note's stored styles.
- | Markdown | Native result |
- |----------|---------------|
- | `- [ ] item` / `- [x] item` | Checklist item, unchecked / checked |
- | `> text` (consecutive lines form one quote) | Body paragraph with a block quote |
- | A fence of bare ```` ``` ```` lines (no language) | Monospaced paragraphs; the code text is kept literally |
- | `---` on its own line, after a blank line | Divider line |
- | `` `inline code` `` | **Highlighted** text, not monospace |
- Constructs Notes would not render faithfully, or that this server cannot yet
- verify, are refused before anything is created: `~~~` fences, a language
- after the opening fence, nested (`>>`) or indented quotes, lists or headings
- inside a quote, a quote followed directly by text (Markdown would join that
- text to the quote), `---` directly under text (Markdown would make that text
- a heading), `***`/`___`/`----` rules, `[X]`, `* [ ]` or `+ [ ]` items, checklist
- items directly next to ordinary list items, inline code padded with spaces or
- inside a link label, tables, and `~~strikethrough~~`. The readback checks the
- block-quote text, the Monospaced text, each checklist item's text and done
- state, the divider count, and the highlighted text. These mappings apply to
- the default Shortcut route only; see
- [Markdown through HTML](#markdown-through-html) for `markdownRoute: "html"`.
- - [`append-native`](#append-native)'s `format: "markdown"` refuses all of the
- constructs above: its Shortcuts converter is a different one, which renders
- a quote and a fenced block as plain body text, `- [ ]` as a bullet with
- literal brackets, and inline code as plain text, and drops `---`.
- - The server finds the new note among the notes added to the default folder
- during the run by verifying each one's visible text, heading levels and links
- by exact-ID readback, and moves it only after exactly one verifies. On any
- uncertain result it names the note (or says to search for the title) and
- never retries.
- - It is gated like the other native operations; `get-capabilities` reports it
- as `create-note-markdown`. The Create Markdown Note Shortcut is optional and
- needed only for this format (macOS 26+); install and approve it as described in
- [`shortcuts/README.md`](shortcuts/README.md).
- - A first line that is exactly `# <title>` (same case and spacing as `title`) is
- removed together with one blank line after it, because the title is supplied
- separately; the response then carries `strippedDuplicateTitle: true`. A
- different first heading stays in the body. This applies to both Markdown
- routes, and Markdown that holds only that heading is refused.
- ##### Markdown through HTML
- `markdownRoute: "html"` imports the same bounded Markdown subset without the
- Shortcut: the server converts it to HTML and creates the note through AppleScript,
- like `format: "html"`. It works in any account, accepts `tags`, and needs no
- Shortcut, but headings get the plain bold styling described in the known
- limitation above rather than real Heading and Subheading styles.
- On this route, bullet task items (`- [ ] item`, `- [x] item`) become ordinary
- list rows that start with a visible `☐` or `☑` character, and the response
- reports how many as `taskItemsRendered`. They are text, not native checkable
- checklist items. Use this route as the glyph fallback when the Shortcut is not
- installed or the note is outside iCloud. Block quotes, fenced code and inline code, which
- the Shortcut route maps natively, are refused on this route, and a `---` line
- stays literal text rather than becoming a divider.
- ```json
- {
- "title": "Weekly Review",
- "contentPath": "/Users/me/Documents/weekly-review.md",
- "format": "markdown",
- "markdownRoute": "html",
- "folder": "Work"
- }
- ```
- **Returns:** Confirmation message with note title and ID. Save the ID for subsequent operations like `update-note`, `delete-note`, etc.
- ---
- #### `search-notes`
- Searches for notes by title or content.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `query` | string | Yes | Text to search for |
- | `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 |
- | `account` | string | No | Account to search in (defaults to Notes.app's default account; exact or unique-prefix match) |
- | `folder` | string | No | Limit search to a specific folder (supports nested paths like `"Work/Clients"`) |
- | `modifiedSince` | string | No | ISO 8601 date string to filter notes modified on or after this date (e.g., `"2025-01-01"`) |
- | `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. |
- | `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. |
- **Example - Search titles:**
- ```json
- {
- "query": "meeting"
- }
- ```
- **Example - Search content:**
- ```json
- {
- "query": "budget allocation",
- "searchContent": true
- }
- ```
- **Example - Search recent notes with limit:**
- ```json
- {
- "query": "todo",
- "searchContent": true,
- "modifiedSince": "2025-01-01",
- "limit": 10
- }
- ```
- **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.
- 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`.
- **Example - Content search with word counts:**
- ```json
- {
- "query": "budget",
- "searchContent": true,
- "includeWordCount": true
- }
- ```
- ---
- #### `query-notes`
- Finds notes with a boolean query expression evaluated against the NoteStore
- database, read-only. Because it does not go through AppleScript, a query over
- several hundred notes typically returns in well under a second, and one call
- can match titles and bodies together.
- **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)). Without it, use `search-notes`.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `query` | string | Yes | Query expression (syntax below), at most 2000 characters |
- | `limit` | number | No | Maximum notes to return. Defaults to 50, maximum 500. The response reports the total match count. |
- | `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. |
- | `includeDeleted` | boolean | No | Also scan notes in Recently Deleted, notes pending deletion, and folderless notes. Defaults to `false`. |
- | `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`. |
- **Syntax:**
- | Form | Matches |
- |------|---------|
- | `budget`, `"quarterly budget"` | Title or body contains the word or phrase (case-insensitive substring) |
- | `title:x`, `body:x`, `text:x` | Title only, body only (text after the first line), or either |
- | `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` |
- | `account:iCloud` | Account name, case-insensitive |
- | `tag:finance` | Native Notes tag (with or without `#`); textual hashtags are ordinary words |
- | `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 |
- | `checklist:open`, `checklist:done` | At least one unchecked item; or items present and all checked |
- | `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) |
- | `words:>250` | Word count, with `=`, `>`, `>=`, `<`, `<=` |
- | `created:>=2026-07-01`, `modified:<2026-09-01` | Dates as `YYYY-MM-DD` in local time, with the same operators; `=` means that whole day |
- | `a b`, `a AND b`, `a OR b`, `NOT a`, `-a`, `( … )` | AND is implicit and binds tighter than OR |
- Operators are case-insensitive. Quote an operator or flag word to search it
- literally, for example `"and"` or `"pinned"`. Queries are capped at 256 tokens
- and 64 levels of nesting. An unknown field such as `titel:x` is an error rather
- than a silent text search; quote it to search the literal text.
- Password-protected notes match on title and metadata only. Their bodies are
- encrypted, so a body predicate is unknown for them rather than false: neither
- `body:x` nor `-body:x` matches them, though `-body:x OR pinned` matches a
- pinned one. Notes whose body cannot be decoded are treated the same way. Their
- snippets are always empty.
- **Example - Open to-dos in a folder:**
- ```json
- {
- "query": "folder:\"Work Projects\" has:checklist -checklist:done"
- }
- ```
- **Example - Invoices or finance-tagged notes since July, scanning more history:**
- ```json
- {
- "query": "(title:invoice OR tag:finance) modified:>=2026-07-01",
- "scanLimit": 2000,
- "limit": 20
- }
- ```
- **Returns:** Matching notes, most recently modified first, each with `id`,
- `title`, `folder`, `account`, `modified`, `created`, and a `snippet` centred on
- the first matched phrase. Each note also has `matchedIn` when the query has a
- positive text term: `["title"]`, `["body"]`, or both, saying where those terms
- occur (a `title:` term is only looked for in the title, a `body:` term only in
- the body). It is absent for locked or undecodable notes, and an empty list
- means the note matched through a non-text branch such as `pinned OR x`. The ids are the same `x-coredata://…/ICNote/p…` form
- every other tool accepts. `structuredContent` also reports `matched` (total
- matches), `scanned`, `eligible`, `scanTruncated`, `truncated`, and `unreadable`
- (bodies that could not be decoded). A malformed query returns an error naming
- the problem and its position.
- ---
- #### `get-note-content`
- Retrieves the full content of a specific note.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | No | Note ID (preferred - more reliable than title) |
- | `title` | string | No | Note title (use `id` instead when available) |
- | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
- | `timeoutSeconds` | number | No | Whole seconds, 1–120, for the body read; overrides `APPLE_NOTES_MCP_TIMEOUT_MS` for this call only |
- **Note:** Either `id` or `title` must be provided. Using `id` is recommended as it's unique and avoids issues with duplicate titles.
- **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.
- **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.
- **Example - Using ID (recommended):**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456"
- }
- ```
- **Example - Using title:**
- ```json
- {
- "title": "Shopping List"
- }
- ```
- **Returns:** The HTML content of the note, its exact `id`, and a
- `contentHash`. Pass that hash back as `expectedContentHash` for a later update,
- append, or delete; the write is rejected if the note's body or rich metadata
- changed after this read. With Full Disk Access, embedded URLs omitted by
- AppleScript are restored and returned in `links`. The response also reports
- actual `nativeTags`, `richContentComplete`, and `writable`. Textual `hashtags`
- remain a separate field and are not proof that Notes registered native tags.
- `writable` is also false when the note uses formatting that AppleScript's HTML
- does not carry (superscript, subscript, non-left paragraph alignment, or
- highlight): a full-body `update-note` would silently drop it, so it is refused
- and the `warning` names the formatting. `append-to-note` with `scopeText` still
- works through the native path, which verifies existing formatting.
- **⚠️ The returned body can be lossy — do not write it back verbatim.** Inline
- base64 images larger than `APPLE_NOTES_MCP_MAX_INLINE_IMAGE_BYTES` (default
- 256 KB) are replaced with `[inline image omitted: …]` text placeholders so an
- image-heavy note cannot blow the MCP message limit. `structuredContent` reports
- this as `strippedImages` (count) and `truncated` (boolean). When either is set,
- passing this body to an unguarded full-body writer would replace the real images
- with placeholder text. This server's `update-note` refuses attachment-bearing
- notes, and `append-to-note` routes them to native end-append with `scopeText`,
- which never rewrites the existing body; make any other edit in Notes.app.
- ---
- #### `get-native-objects`
- Reads native object identities and ranges, checklist item IDs and state, actual
- native tags, and native table data from one exact note ID. Table output includes
- stable row and column identifiers. `tableCellsComplete` is false when Notes
- metadata cannot be decoded completely. This tool is read-only and requires Full
- Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact note ID, in any [identifier form](#identifier-forms) |
- ---
- #### `get-note-tables`
- Reads a page of native tables in one exact note, in body order, from the NoteStore
- database. Each table is returned as GitHub-flavored Markdown and as JSON `rows`
- with stable `rowIds` and `columnIds`. Notes tables have no header row, so the
- Markdown uses the first row as the header. Pipes are escaped as `\|`,
- backslashes are doubled, and line breaks inside a cell become `<br>`.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact note ID (`x-coredata://…/ICNote/pNNN`) |
- | `offset` | integer | No | Zero-based position of the first table (default 0); use `page.nextOffset` |
- | `limit` | integer | No | Maximum tables per page (default and maximum 500) |
- | `maxBytes` | integer | No | Full serialized response budget in UTF-8 bytes (default 4 MiB, minimum 1024 bytes, maximum 8 MiB) |
- The byte budget includes both the text response and structured data, including
- repeated Markdown and JSON escaping. Tables are returned whole. `tableCount`
- and `page.totalAvailable` count all tables in the note; `page.returned` counts
- the entries in this response. While `page.hasMore` is true, call again with
- `offset: page.nextOffset` and the same `limit` and `maxBytes`. Each call reads
- the note again, so finish paging before editing it.
- If one table exceeds an otherwise empty page, its entry contains identifying
- metadata, `complete: false`, `contentOmitted: true`, and a `reason`, without
- partial rows or row/column IDs. The next offset advances past that entry. To
- retrieve its content, retry that offset with a larger `maxBytes`, or export the
- note to a file. If even the metadata exceeds the budget, the tool returns a
- validation error. `page.stoppedAtSizeLimit` reports a byte-budget stop.
- `tableCellsComplete` is false when any table or cell could not be decoded, or
- when the current page omits a table's content for its byte budget. A
- cell holding an embedded object is `null` in `rows`, listed in
- `incompleteCells`, and shown as `[undecoded cell]` in Markdown. A table whose
- data cannot be decoded at all has `complete: false`, a `reason`, and no rows.
- Cell text is never guessed. Links and styling inside cells are not rendered.
- A note without tables returns an empty `tables` list. This tool is read-only,
- requires Full Disk Access, and refuses password-protected notes.
- ---
- #### `get-note-blocks`
- Decodes one note's body into typed blocks, read-only, from the NoteStore
- database. Each block is one paragraph with its `style` (`title`, `heading`,
- `subheading`, `body`, `monospaced`, `bulleted`, `dashed`, `numbered`,
- `checklist`, or `unknown` with the raw `styleType`), `indent`, `alignment`,
- `blockQuote`, checklist `id`/`done`, and `paragraphUuid` when stored. Each
- block lists its inline `runs` with `bold`, `italic`, `underline`,
- `strikethrough`, `superscript`, `subscript`, `color`, `highlight`, `link`
- (plus `linkSafe`), `font`, and `attachment`, and its attachment markers in body
- order. Offsets and lengths count UTF-16 code units. `summary` counts styles and
- inline attributes for the whole note. `undecodedFields` lists stored field
- numbers the decoder deliberately does not interpret.
- **Requires:** Full Disk Access. Password-protected notes are refused.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact note ID |
- | `offset` | number | No | First block to return (default 0). Use `page.nextOffset` |
- | `limit` | number | No | Maximum blocks per page (default 500, max 5000) |
- A page also stops early to stay under `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES`
- (default 4 MB). `paragraphUuid` is not unique: Notes copies it when a paragraph
- is split. Link URLs are returned as stored, and `linkSafe` is false for schemes
- other than http(s), `notes:`, `applenotes:` and `mailto:`. Errors carry a
- stable code in brackets, such as `[encrypted]` or `[no-full-disk-access]`.
- ---
- #### `list-note-paragraphs`
- Lists one note's non-empty paragraphs in body order, read from the NoteStore
- database. It never changes Notes. With `recordAnchors` it also writes the
- local anchor registry, so the tool is not marked read-only in its MCP
- annotations. Each paragraph has `blockIndex` (its index in
- `get-note-blocks`, where empty paragraphs also count), `text`, `style`,
- `styleType`, `paragraphId` (the UUID Notes stores on the paragraph's first
- text run), and `paragraphIdStatus`:
- - `unique`: no other paragraph in the note carries this ID. The paragraph also
- gets `url`, a direct
- `applenotes://showNote?identifier=<note>¶graphID=<paragraph>` link that
- opens Notes at that paragraph.
- - `shared`: other paragraphs carry the same ID (`sharedWith` counts them).
- Notes copies the ID when a paragraph is split, so this is common for body
- text. No `url` is given, because it could open the wrong paragraph.
- - `missing`: no ID is stored.
- `mixedParagraphIds: true` marks a paragraph whose text runs carry more than
- one ID; only the first-run ID is used. Titles and headings usually have unique
- IDs.
- **Requires:** Full Disk Access. Password-protected notes are refused.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | One of `id`, `title` | Exact note ID, or the note's Notes UUID |
- | `title` | string | One of `id`, `title` | Exact note title; must match one note. Notes in Recently Deleted are ignored, as in `list-notes` |
- | `folder` | string | No | With `title`: the folder's name or full path as `list-folders` shows it, such as `Work/Clients` |
- | `linkableOnly` | boolean | No | Return only paragraphs with a `url` |
- | `offset` | number | No | First paragraph to return (default 0). Use `page.nextOffset` |
- | `limit` | number | No | Maximum paragraphs per page (default 500, max 5000) |
- | `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 |
- ---
- #### `get-paragraph-link`
- Returns a direct link to one paragraph of a note:
- `applenotes://showNote?identifier=<note>¶graphID=<paragraph>`. It selects
- the note like `list-note-paragraphs` and the paragraph by exactly one of:
- - `contains`: a snippet of the paragraph. Case, runs of spaces, and Unicode
- width are ignored.
- - `match`: the whole paragraph, compared the same way.
- - `blockIndex`: from `list-note-paragraphs`.
- When `contains` or `match` hits several paragraphs, pass `occurrence` (1-based)
- or a longer snippet.
- The link is returned only when the paragraph's ID is `unique` in the note.
- Otherwise the result is an error whose `structuredContent` carries the usual
- `code` plus a `reason`: `paragraph-id-shared`, `paragraph-id-missing`,
- `no-match`, `ambiguous-paragraph`, `occurrence-out-of-range`, `ambiguous-note`
- (several notes have that title; the message lists their folders), `not-found`,
- `encrypted`, or `no-body`. The tool never creates or changes a paragraph ID,
- and an edit in Notes can later replace the ID and break the link. With
- `recordAnchor` it also writes the local anchor registry, so the tool is not
- marked read-only in its MCP annotations.
- **Requires:** Full Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id`, `title`, `folder` | string | One of `id`, `title` | Note selector, as in `list-note-paragraphs` |
- | `contains` | string | One of `contains`, `match`, `blockIndex` | Snippet of the paragraph |
- | `match` | string | One of `contains`, `match`, `blockIndex` | The whole paragraph |
- | `blockIndex` | number | One of `contains`, `match`, `blockIndex` | The paragraph's `blockIndex` |
- | `occurrence` | number | No | Which match to use when several paragraphs match |
- | `recordAnchor` | boolean | No | Also record a [paragraph anchor](#paragraph-anchors) for the linked paragraph and return its `anchorId`. Writes only the local anchor registry |
- ---
- #### Paragraph anchors
- A paragraph link breaks when Notes replaces or copies the paragraph's ID. A
- paragraph anchor records enough about the paragraph to find it again: the
- note's Notes UUID, the paragraph ID and its status, the paragraph's normalized
- text and a fingerprint of it, the fingerprints of the paragraphs before and
- after it, its `blockIndex`, and when it was recorded. Anchors are kept in one
- local file, `~/Library/Application Support/apple-notes-mcp/paragraph-anchors.json`
- (or the absolute path in `APPLE_NOTES_MCP_ANCHOR_FILE`). It is created with
- mode 0600 in a 0700 directory, replaced atomically under a lock file, and
- holds the text of every anchored paragraph. A symlinked, unreadable or
- corrupt registry is refused and left as it is. The anchor tools never change
- Notes.
- Resolving an anchor tries three steps in order, and every step fails closed:
- 1. **Paragraph ID.** A paragraph whose ID is still unique in the note is the
- anchored paragraph, even if its text was edited or it moved. A link to that
- ID opens exactly that paragraph.
- 2. **Exact text.** The same normalized text. When several paragraphs have it,
- only the one whose neighbours still match is chosen; a tie is `ambiguous`.
- 3. **Text and neighbours.** Similar text between both recorded neighbours, or
- nearly identical text beside one of them. Two close candidates are
- `ambiguous`; one below `minConfidence` is `low-confidence`.
- A match whose ID is now shared or missing is `needs-reminting`: the paragraph
- is found (the result names its block), but no safe link exists until it gets a
- new ID. Public automation cannot set a paragraph ID, so this server only
- reports it and returns no `url`.
- To share anchored links outside Notes, see the
- [paragraph anchor resolver](#paragraph-anchor-resolver-opt-in).
- #### `create-paragraph-anchor`
- Records an anchor for one paragraph, selected exactly as in
- `get-paragraph-link` (note by `id` or `title`/`folder`; paragraph by one of
- `contains`, `match`, `blockIndex`, plus `occurrence`). Unlike
- `get-paragraph-link`, a paragraph whose ID is shared or missing can be
- anchored. Recording the same paragraph again (same note, ID, text and block)
- returns the existing anchor with `created: false`.
- Returns `anchor`, `created`, and `url` when the paragraph currently has a
- unique ID.
- **Requires:** Full Disk Access. Writes only the anchor registry.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id`, `title`, `folder` | string | One of `id`, `title` | Note selector, as in `list-note-paragraphs` |
- | `contains`, `match`, `blockIndex`, `occurrence` | | One of `contains`, `match`, `blockIndex` | Paragraph selector, as in `get-paragraph-link` |
- #### `resolve-paragraph-anchor`
- Finds an anchored paragraph in the note as it is now. The result has `status`
- (`resolved`, `needs-reminting`, `ambiguous`, `low-confidence`, `not-found`,
- `note-not-found`, `note-deleted` for a note in Recently Deleted, or
- `note-unreadable` for a locked note), `method` (`paragraph-id`, `exact-text`,
- `text-and-neighbours`), `confidence` (0 to 1), `match` (`blockIndex`, `text`,
- `paragraphId`, `paragraphIdStatus`), `changes` (`textChanged`,
- `blockIndexChanged`, `paragraphIdChanged`), and `message`. `url`, the current
- `applenotes://` link, is present only when `status` is `resolved`.
- **Requires:** Full Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `anchorId` | string | Yes | The anchor (`pa_` and 24 hex digits) |
- | `minConfidence` | number | No | Lowest confidence accepted as a match (default 0.6) |
- | `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` |
- #### `list-paragraph-anchors`
- Lists recorded anchors in the order recorded, with `total`, the `registry`
- path and `page` info. Reads only the registry.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `noteIdentifier` | string | No | Only anchors in the note with this Notes UUID |
- | `offset` | number | No | First anchor to return (default 0) |
- | `limit` | number | No | Maximum anchors (default 100, max 1000) |
- #### `get-paragraph-anchor`
- Returns one stored anchor as recorded. Reads only the registry.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `anchorId` | string | Yes | The anchor |
- #### `prune-paragraph-anchors`
- Removes anchors that no longer resolve, or the anchors you list. It is a dry
- run unless `dryRun` is `false`. Without `anchorIds` it resolves every anchor
- in scope and treats `not-found` and `note-not-found` as stale. A note in
- Recently Deleted (`note-deleted`) is kept by default because it can be
- restored. Returns `stale` (`anchorId`, `status`, `message`), `examined`, and
- `removed`.
- **Requires:** Full Disk Access unless `anchorIds` is given.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `anchorIds` | string[] | No | Remove exactly these anchors instead of resolving |
- | `noteIdentifier` | string | No | Only anchors in the note with this Notes UUID |
- | `statuses` | string[] | No | Statuses treated as stale (default `not-found`, `note-not-found`) |
- | `dryRun` | boolean | No | Report without removing (default `true`) |
- ---
- #### `get-note-structure`
- Returns a read-only overview of one note from the NoteStore database, in one
- call:
- - `text` (decoded body), `textLength`, `wordCount`, `charCount` (Unicode
- characters, attachment placeholders excluded), and `blockSummary` (the
- `get-note-blocks` summary counts).
- - `links`, each with a `kind`: `inline` (a hyperlink on text), `card` (a rich
- link preview attachment, with `attachmentId` and `previewPath`), `note` (a
- native link chip to another note), or `section` (a native link chip to a
- heading or paragraph, with `section`). Notes deep links also carry
- `targetNote` and `paragraphId`. `linkCounts` totals them.
- - `tags` (native tags in body order) and `attachments`, listed the way
- [`list-attachments`](#list-attachments) with `includePaths` lists them: the
- same `kind` (`image`, `scan`, `drawing`, `pdf`, `audio`, `video`, `url`,
- `table`, `other`), the same body order, and the same `previewPath`, plus the
- card `title`/`url`, `fileSize`, and body position. Gallery items and
- recording parts are nested under `children`; `attachmentCount` counts
- top-level attachments only.
- - `deepLink`, `isShared` (the note or any enclosing folder is shared),
- `isLocked`, `isPinned`, `inRecentlyDeleted`, `lastViewed`,
- `checklistTotal`, `checklistDone`, `hasDrawing` (classic sketches and Paper
- drawings), and `firstImage` (the same lead visual `list-attachments`
- returns with `firstImage`, plus its attachment `id`).
- `lastViewed` is an ISO date, or null with `lastViewedStatus` set to
- `never-viewed`, `not-recorded`, `malformed`, or `unsupported` (the column
- does not exist on this macOS version). A password-protected note returns its
- metadata and attachment rows with `bodyDecoded: false` and the body-derived
- fields null.
- **Requires:** Full Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact note ID: the `x-coredata://` id, or the note's Notes UUID or numeric key (see [Identifier forms](#identifier-forms)) |
- | `includeText` | boolean | No | Include the decoded text (default true). Text larger than `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES` is omitted with `textOmitted: true` |
- Link URLs are returned as stored; check `linkSafe` before emitting one into
- HTML.
- ---
- #### `list-note-links`
- Lists links, read-only from the NoteStore database, in one note (`id`) or
- across a `folder`, an `account`, or the whole library (no selector). Each link
- has a `kind`:
- | Kind | What it is | Where Notes stores it |
- |------|------------|-----------------------|
- | `inline` | A hyperlink on text | Inside the note body |
- | `card` | A rich link preview | An attachment row with the URL and title |
- | `note` | A native link chip to another note | An inline-attachment row with a Notes deep link |
- | `section` | A native link chip to a heading or paragraph | Same, with `paragraphID` in the deep link |
- Each row has `url`, `text` (label), `linkSafe`, `targetNote` and `paragraphId`
- for Notes deep links, `section` for section chips, and for cards
- `attachmentId` and `previewPath` (Notes' largest cached preview image, found
- the same way [`list-attachments`](#list-attachments) finds it, or null when
- Notes has none). Each row also names its source: `noteId`, `noteIdentifier`,
- `noteTitle`, `noteModified`, `folder`, `folderPath` (as `list-folders` prints
- it), `account`, and `accountIdentifier`. When bodies were decoded, `start` and
- `blockIndex` give the link's position, and `inBody: false` marks a card or chip
- row with no marker left in the body.
- Inline links need every body in scope decompressed and decoded, so a folder,
- account, or library scan includes them only with `includeInline: true`
- (slower). A single note always includes them. A `folder` scope includes its
- subfolders unless `includeSubfolders` is false. Scans skip Recently Deleted
- and folderless notes; a note requested by `id` is read wherever it is. Links
- come newest-modified note first, in body order within a note.
- **Requires:** Full Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | No | One exact note ID (x-coredata id, Notes UUID, or numeric key). Do not combine with `account` or `folder` |
- | `account` | string | No | Account name (exact or unique-prefix match, as in the other tools) |
- | `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 `\/` |
- | `includeSubfolders` | boolean | No | With `folder`, also list notes in its subfolders (default true) |
- | `includeInline` | boolean | No | Decode bodies for inline links (default true for `id`, false otherwise) |
- | `kinds` | string[] | No | Only these kinds: `inline`, `card`, `note`, `section` |
- | `offset` | number | No | First link to return (default 0). Use `page.nextOffset` |
- | `limit` | number | No | Maximum links per page (default 200, max 2000) |
- The response also reports `scope`, `counts` per kind, `notesInScope`,
- `notesWithoutBody` (locked, empty or undecodable bodies when inline links were
- requested), and `page`. A page stops early to stay under
- `APPLE_NOTES_MCP_BLOCKS_MAX_BYTES`. An ambiguous folder name is refused with a
- message that lists the matching paths.
- ---
- #### `list-native-tags`
- Lists actual native Notes tags. This differs from textual hashtag search. It is
- read-only and requires Full Disk Access.
- - **Folder mode** (pass `folder`, optionally `account`): maps each tag used in that
- folder to its matching note IDs. The response reports `complete: false` and per-note
- errors when some native metadata is unavailable.
- - **Inventory mode** (omit `folder`): an account-wide inventory with counts, read-only from the
- database. `account` narrows it to one account; omit it to count every
- account. Each `inventory` entry has `tag`, `noteCount` (distinct notes, Recently
- Deleted excluded), per-account counts in `accounts`, and any other `spellings` Notes
- treats as the same tag. Tags with no remaining notes are listed with `noteCount: 0`.
- A tag counts for a note only while the note body still references it. Locked or
- unreadable bodies are counted from the tag objects alone and reported through
- `unverifiedNotes` and `complete: false`.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `folder` | string | No | Folder to list (nested paths supported). Omit for the inventory |
- | `account` | string | No | Account name, exact or unique prefix |
- ---
- #### `native-tags-status`
- Checks whether exactly one configured Native Tags Shortcut is installed. An
- installed workflow may still need macOS permission on its first execution, and
- installation does not show whether that consent was given: run it once in the
- foreground in Shortcuts.app and choose **Always Allow** after install or upgrade
- (see [Troubleshooting](#native-writes-time-out-or-report-an-uncertain-outcome)).
- ---
- #### `add-native-tags`
- Adds actual native Notes tag objects to one exact note using `id`, a fresh
- `expectedContentHash`, a distinctive existing `scopeText`, and `tags`. The
- operation verifies the note's original text, links, and native objects after the
- Shortcut runs. It refuses ambiguous title-and-scope matches and never retries an
- uncertain write. Install the signed workflow as described in
- [`shortcuts/README.md`](shortcuts/README.md).
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact note ID, in any [identifier form](#identifier-forms) |
- | `expectedContentHash` | string | Yes | `contentHash` from a fresh read of the note |
- | `scopeText` | string | Yes | Distinctive phrase already in the note, 12–500 characters |
- | `tags` | string[] | Yes | 1–100 tag names to add |
- ---
- #### `get-note-plaintext`
- Retrieves a note's body as plain text, with no HTML markup.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | No | Note ID (preferred - more reliable than title) |
- | `title` | string | No | Note title (use `id` instead when available) |
- | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
- **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.
- **Returns:** The plain-text content of the note in `structuredContent.plaintext`, or error if not found.
- ---
- #### `get-note-details`
- Retrieves metadata about a note (without full content).
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `title` | string | Yes | Exact title of the note |
- | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match) |
- **Example:**
- ```json
- {
- "title": "Project Plan"
- }
- ```
- **Returns:** JSON with note metadata:
- ```json
- {
- "id": "x-coredata://...",
- "title": "Project Plan",
- "created": "2025-01-15T10:30:00.000Z",
- "modified": "2025-01-20T14:22:00.000Z",
- "shared": false,
- "passwordProtected": false,
- "account": "iCloud"
- }
- ```
- ---
- #### `get-note-by-id`
- Retrieves a note using its unique CoreData identifier.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `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)) |
- **Returns:** JSON with note metadata, plus `identifier`, `folderIdentifier`, and `accountIdentifier` when Full Disk Access is granted, or error if not found.
- ---
- #### `show-note`
- Reveals a note in Notes.app using its unique CoreData identifier.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | The CoreData URL identifier (e.g., `x-coredata://...`), or the note's Notes UUID or numeric key |
- | `separately` | boolean | No | Open in a separate note window when supported by Notes.app |
- **Returns:** Confirmation that Notes.app accepted the show command.
- ---
- #### `update-note`
- Updates an existing note's content and/or title.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
- | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being replaced |
- | `newTitle` | string | No | New title (if changing the title; ignored when `format` is `"html"`) |
- | `newContent` | string | Yes | New content for the note body |
- | `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) |
- | `allowLinkChanges` | boolean | No | Set to `true` only when intentionally changing or removing existing links |
- | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
- | `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 |
- Title-only updates are rejected because Apple Notes titles are not unique.
- **Example - Using ID (recommended):**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "newContent": "Updated content here"
- }
- ```
- **Example - Update with HTML formatting:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "newContent": "<p>New findings with <b>bold</b> emphasis.</p><pre><code>console.log('hello');</code></pre>",
- "format": "html"
- }
- ```
- **Returns:** Confirmation with the exact ID, post-save `contentHash`, and
- `verifiedVisibleText: true`, or an error if the note changed before saving.
- Apple Notes normalizes HTML, so this proves the visible text after saving, not
- byte-identical rich formatting.
- **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.
- **Rich-content safety:** `update-note` refuses to replace a note when its rich
- metadata is unavailable or it contains attachments, native tags, inline
- objects, or checklists that AppleScript cannot preserve. Existing link
- destinations must remain present unless `allowLinkChanges` is explicitly set.
- ---
- #### `delete-note`
- Deletes a note (moves to Recently Deleted in Notes.app).
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
- | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being deleted |
- | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
- | `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 |
- | `guardNoteId` | string | No | A second note (usually a verified copy) that must still be intact; needs Full Disk Access |
- | `expectedGuardContentHash` | string | With `guardNoteId` | `contentHash` of the guard note from `get-note-content` |
- | `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 |
- Title-only deletion is rejected. If the note changed after the supplied hash
- was read, deletion is also rejected.
- **Notes with large images.** Notes.app returns a note's body with each inline
- image embedded as base64, so a note holding one 40 MB image has a body of about
- 110 MB. Body reads accept up to 512 MB of output, and `delete-note` compares a
- body longer than 5 MB against a private temporary file rather than embedding it
- in the AppleScript. The comparison still covers the whole body, and the file
- is removed when the delete finishes.
- **Copy-then-retire.** To delete an original only while its copy is still good,
- read both notes, verify the copy, and pass the copy as `guardNoteId` with its
- `contentHash` as `expectedGuardContentHash`. The copy's revision is re-read just
- before the delete, and its body, lock state, and folder are checked again
- inside the delete AppleScript, with the same fail-closed Recently Deleted test
- as the note being deleted. The guard note must not be a Quick Note, a flag only
- the database holds, so the guard needs Full Disk Access. A copy the database
- has not saved yet passes on the live checks alone. The pair is still not one
- transaction: the rich revision (which also covers checklists and attachments)
- is a pre-check, and the in-script check covers the body and state Notes.app
- exposes. `requireActiveNoteId` is the narrower form for a destination you
- wrote yourself rather than copied.
- **Example - Using ID (recommended):**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
- }
- ```
- **Returns:** Confirmation message, or error if note not found. The delete and a
- check of the note's original folder run in one AppleScript: if Notes.app accepts
- the delete but the note is still listed in that folder, the call reports that
- nothing was deleted instead of claiming success.
- A note that is already in Recently Deleted is refused, because deleting it there
- removes it permanently. The folder is read live from Notes.app in the same
- AppleScript; the Recently Deleted folder is recognised by its database id (with
- Full Disk Access) or by its English name. The check fails closed: a note whose
- folder Notes.app reports as something other than a folder (as it does for a note
- trashed earlier in the same Notes session) is refused the same way, and a note
- whose folder cannot be read at all is refused with a message to retry. To remove
- such a note for good, do it in Notes.app.
- **⚠️ 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.
- ---
- #### `move-note`
- 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).
- 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.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
- | `folder` | string | Yes | Destination folder name or nested path (e.g., `"Work/Clients"`) |
- | `account` | string | No | Account whose `folder` is the destination (default: the default account) |
- | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
- | `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 |
- Title-only moves are rejected.
- **Example - Using ID (recommended):**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "folder": "Archive"
- }
- ```
- **Returns:** Confirmation only after the same note ID is read back and its
- actual destination folder ID matches the requested folder.
- ---
- #### Folder scope guards
- `update-note`, `append-to-note`, `delete-note`, `move-note`, and
- `batch-move-notes` accept three optional folder preconditions. Use exact
- folder ids from `list-folders`.
- - `ifFolderId`: the note must currently be in exactly this folder.
- - `ifAncestorFolderId`: the note must be inside this folder or any of its
- subfolders.
- - `forbiddenAncestorFolderIds` (up to 50): the note must not be inside any of
- these folders or their subfolders. For `move-note` and `batch-move-notes`,
- the destination must not be either.
- The checks read Notes.app's live folders inside the same AppleScript as the
- write, immediately before it. If the folder observed by the check fails a
- precondition, the write is refused with `Scope guard failed: …`. The check and
- write are separate Notes operations; another actor can move the note between
- them. A native append to a protected note runs through Shortcuts, so its
- precheck runs in a separate AppleScript before the append.
- For `batch-move-notes`, the same preconditions apply to every supplied note ID.
- Each note is checked independently immediately before its move. A scope mismatch
- leaves that note unchanged and appears in its failure result; the remaining
- items continue. A batch can therefore move some notes and refuse others.
- **Example - retire a note only while it is still in the inbox:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "ifFolderId": "x-coredata://ABC123/ICFolder/p12"
- }
- ```
- ---
- #### `append-to-note`
- Appends or prepends content to an existing note without replacing it. Always reads and writes as HTML, preserving all existing rich formatting.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact CoreData note ID returned by a read or search |
- | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being extended |
- | `content` | string | Yes | Text to append to the note body |
- | `position` | string | No | `"after"` (default) appends to the end; `"before"` inserts directly below the note's title line, so the title stays first |
- | `separator` | string | No | String placed between existing content and new content (default: two newlines → `<div><br></div>` in HTML) |
- | `format` | string | No | Format of the content being appended: `"plaintext"` (default) or `"html"` |
- | `scopeText` | string | Native-object notes only | Unique existing phrase, as for [`append-native`](#append-native) |
- | `ifFolderId`, `ifAncestorFolderId`, `forbiddenAncestorFolderIds` | string, string, string[] | No | Folder preconditions; see [Folder scope guards](#folder-scope-guards) |
- | `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 |
- Title-only appends are rejected.
- **Example - Append plaintext:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "content": "New item added today"
- }
- ```
- **Example - Prepend HTML:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "content": "<div><b>Status:</b> done</div>",
- "format": "html",
- "position": "before"
- }
- ```
- **Returns:** Confirmation with the exact ID, post-save `contentHash`, and
- `verifiedVisibleText: true`. Apple Notes normalizes HTML, so this proves the
- visible text after saving, not byte-identical rich formatting. Warns when the
- note is shared with collaborators.
- **Safety:** The append is rejected if the note changed since it was read, rich
- metadata is unavailable, or the note contains attachments. Existing link
- destinations are verified after saving.
- **Notes containing native objects** (a table, a checklist, native tags) cannot be
- spliced, so they are routed to the native end-append bridge — see
- [`append-native`](#append-native). That path additionally requires `scopeText`,
- keeps the default blank-line `separator` and `position: "after"`, and accepts a
- fixed HTML subset rather than anything Notes.app can render:
- | | Native append |
- |---|---|
- | Elements | `<a>` `<b>` `<br>` `<code>` `<del>` `<div>` `<em>` `<h1>` `<h2>` `<h3>` `<i>` `<li>` `<ol>` `<p>` `<s>` `<span>` `<strong>` `<tt>` `<u>` `<ul>` |
- | 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 |
- | 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 |
- Ordinary notes take the guarded HTML path and are not restricted to that subset.
- ---
- #### `insert-link`
- Adds one web, mail or Notes link to an exact note as its own paragraph, then
- proves it from the link runs Notes actually stored. Use `mode: "raw"` to show
- the URL itself, or `mode: "hyperlink"` with a `label` to show text that links to
- the URL. For a link to another note by id, use
- [`insert-note-link`](#insert-note-link), which looks up that note's real deep
- link.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact CoreData note ID |
- | `expectedContentHash` | string | Yes | `contentHash` from the exact note version being extended |
- | `url` | string | Yes | Absolute `http(s)` URL with a host, or a `mailto:`, `notes://` or `applenotes:` link. No spaces, `<`, `>` or `"` |
- | `mode` | string | No | `"raw"` (default) shows the URL; `"hyperlink"` shows `label` |
- | `label` | string | Hyperlink only | Visible text for `mode: "hyperlink"`; refused in raw mode |
- | `linked` | boolean | No | Raw mode only. `true` (default) stores a real link on the URL text. `false` writes plain text with no stored link |
- | `position` | string | No | `"end"` (default) or `"after-title"` (first paragraph under the title) |
- | `blankLine` | boolean | No | Leave a blank line between existing text and the link paragraph (default `true`) |
- | `scopeText` | string | Native-object notes only | Unique existing phrase, as for [`append-native`](#append-native) |
- **Example - Hyperlink under the title:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456",
- "expectedContentHash": "sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
- "url": "https://example.com/report",
- "mode": "hyperlink",
- "label": "Quarterly report",
- "position": "after-title"
- }
- ```
- **Returns:** `route` (`"applescript"` for ordinary notes, `"native"` for notes
- with native objects), `linkStored`, `storedUrl` (the destination read back from
- the note, for example `https://example.com/` for a bare origin), and the new
- `contentHash`.
- **Safety:** The same guards as [`append-to-note`](#append-to-note): a fresh
- `expectedContentHash`, the attachment block, and every existing link must
- survive. A linked insert must add exactly one stored link with the requested
- label and destination; if the text lands but that proof fails, the error says
- the write happened so it is not repeated.
- **Limits:**
- - Plain URL text is not linked by Notes when written this way. With
- `linked: false`, the note stores no link and readers of the body see ordinary
- text; Notes.app may still underline the URL on screen through its own data
- detection. The result reports `linkStored: false`.
- - Notes with native objects (a table, a checklist, native tags) take the native
- end-append path, so only `position: "end"` with `blankLine: true` works there.
- - The link always gets its own paragraph. Placing it at the end of one existing
- paragraph, or inside the text, is not available.
- - Rich URL preview cards (the link tile Notes makes when you paste a URL) are
- not produced. No public automation route creates one: the Shortcuts Notes
- actions write text, and AppleScript's `body` has no card markup.
- - To start a new note with a link, use [`create-note`](#create-note) with
- `format: "html"` and an `<a href>` in `content`; the link is stored the same
- way.
- ---
- #### `get-note-link`
- 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.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | No | Note ID (preferred - more reliable than title) |
- | `title` | string | No | Note title (use `id` instead when available) |
- | `account` | string | No | Account containing the note (defaults to Notes.app's default account; exact or unique-prefix match, ignored if `id` is provided) |
- **Note:** Either `id` or `title` must be provided. Using `id` is recommended. Password-protected notes cannot be linked.
- **Example:**
- ```json
- {
- "id": "x-coredata://ABC123/ICNote/p456"
- }
- ```
- **Returns:** `notes://showNote?identifier=<uuid>` URL string, plus the note id and title.
- **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.
- ---
- #### `list-notes`
- Lists all notes, optionally filtered by folder, date, and limit.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `account` | string | No | Account to list notes from (defaults to Notes.app's default account; exact or unique-prefix match) |
- | `folder` | string | No | Filter to notes in this folder only (supports nested paths like `"Work/Clients"`) |
- | `modifiedSince` | string | No | ISO 8601 date string to filter notes modified on or after this date (e.g., `"2025-01-01"`) |
- | `limit` | number | No | Maximum number of notes to return |
- | `includeRecentlyDeleted` | boolean | No | Also list notes in Recently Deleted, each flagged `inRecentlyDeleted: true` (default `false`) |
- **Example - All notes:**
- ```json
- {}
- ```
- **Example - Notes in a folder:**
- ```json
- {
- "folder": "Work"
- }
- ```
- **Example - Recent notes with limit:**
- ```json
- {
- "modifiedSince": "2025-06-01",
- "limit": 20
- }
- ```
- **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)).
- 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.
- > **Changed in 2.7.0:** `notes` was previously `string[]` (titles only). Callers that treated the array as strings must now read `.title`.
- For date order, incremental sync cursors, Recently Deleted, or word counts, use [`list-recent-notes`](#list-recent-notes).
- ---
- #### `list-recent-notes`
- 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.
- **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)).
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `account` | string | No | Only this account (exact or unique-prefix name). Omit for every account |
- | `folder` | string | No | Only notes directly in this folder: a full path in `list-folders` syntax, or a unique folder name |
- | `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 |
- | `limit` | number | No | Maximum rows, 1–1000 (default 50) |
- | `includeDeleted` | boolean | No | Also return notes in Recently Deleted, notes awaiting deletion, and folderless notes (default `false`) |
- | `wordCounts` | boolean | No | Decode each body and add `wordCount` and `charCount` (default `false`) |
- | `bodyPreview` | boolean | No | Add `bodyPreview` (up to 180 characters) and `textDecoded` (default `false`) |
- **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`.
- - **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`.
- - **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.
- - **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.
- - **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`.
- - **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.
- - **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.
- - **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.
- - **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.
- - 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.
- **Example - incremental sync:**
- ```json
- {
- "since": "cdts1:41c7e0ef438fcd6f:4312",
- "limit": 200
- }
- ```
- ---
- #### `get-selected-notes`
- Reads the currently selected note(s) from the Notes.app UI.
- **Parameters:** None
- **Returns:** Selected note metadata, including IDs for follow-up operations. Returns an empty list when Notes.app has no selected note.
- ---
- ### Folder Operations
- #### `list-folders`
- Lists all folders in an account with full hierarchical paths.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `account` | string | No | Account to list folders from (defaults to Notes.app's default account; exact or unique-prefix match) |
- **Example:**
- ```json
- {}
- ```
- **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.
- ---
- #### `list-smart-folders`
- Lists every Smart Folder with the rules that define it, read from the NoteStore
- database. Requires Full Disk Access.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `includeMatchingNotes` | boolean | No | Also list the notes each smart folder currently shows (default `false`) |
- | `limit` | number | No | Maximum matching notes per folder, 1–500 (default 50). `matchingNoteCount` is always the total |
- **Example:**
- ```json
- {
- "includeMatchingNotes": true,
- "limit": 20
- }
- ```
- **Returns:** For each smart folder: `name`, `id`, `identifier`, `account`,
- `accountId`, `accountIdentifier`, `parent`, `parentId`, and `parentIdentifier`
- (the parent fields are `null` at the account root). Its rules are decoded as
- `match` (`"all"`, `"any"`, or `"none"`) and `filters`. Each filter has a `type`
- (the stored rule key, such as `folder`, `tag`, `checklist`, or
- `creationDateRelativeRange`), its stored `value`, `excluded` for an Exclude
- rule, and a readable `description`. Folder filters add the folder's `name` and
- `folderId`, and a nested rule group is a filter of type `group` with its own
- `match` and `filters`. Notes stores each query inside an outer
- `{"deleted": false}` wrapper that keeps Recently Deleted out. `query` is the
- stored query with that wrapper removed, `includesRecentlyDeleted` reports the
- wrapper's value, and `rawQuery` is the stored JSON verbatim. A rule this server
- does not recognize is kept as a filter of type `unknown`, and `fullyDecoded` is
- then `false`.
- With `includeMatchingNotes`, each folder also carries `matchingNoteCount` and
- `matchingNotes` (`title` and `id`). These come from Notes.app itself, which
- evaluates the folder's rules, so they need Automation permission. The server
- does not re-evaluate the rules on its own. A folder whose notes cannot be read
- carries `matchingNotesError` instead.
- ---
- #### `list-folder-tree`
- Returns the folder hierarchy with note counts for each account, read from the NoteStore database in one pass.
- **Requires:** Full Disk Access for the MCP host process (see [Full Disk Access Setup](#full-disk-access)).
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `account` | string | No | Only this account (exact or unique-prefix name). Omit for every account |
- | `includeDeleted` | boolean | No | Include folders marked for deletion (flagged `markedForDeletion`) and folders whose account no longer exists (default `false`) |
- **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`.
- ---
- #### `create-folder`
- Creates a new folder, including a whole nested hierarchy in one call.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `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 |
- | `account` | string | No | Account to create folder in (defaults to Notes.app's default account; exact or unique-prefix match) |
- **Example:**
- ```json
- {
- "name": "Work Projects"
- }
- ```
- **Example - Create a nested hierarchy:**
- ```json
- {
- "name": "Work/Clients/Omnia"
- }
- ```
- **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.
- 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.
- ---
- #### `get-folder-by-id`
- Reads one exact folder's current name, parent ID, and account ID (`accountId`,
- plus `isRoot`, true when the folder sits at the account root). Use these values
- with `rename-folder` or `delete-folder-by-id`; this avoids relying on ambiguous
- folder names or paths. The `id` may also be the folder's Notes UUID or numeric
- key, and the result adds `identifier`, `parentIdentifier`, and
- `accountIdentifier` when Full Disk Access is granted.
- ---
- #### `rename-folder`
- Renames an existing folder in place using its exact `id`, `expectedName`,
- `expectedParentId`, and `newName`. The operation preserves the folder ID, notes,
- and descendants. It refuses stale metadata and a conflicting sibling name.
- ---
- #### `delete-folder-by-id`
- Deletes one exact, empty, ordinary folder through a plan-then-apply handshake.
- Read the folder first with `get-folder-by-id`, call once with `dryRun: true`,
- then repeat the same guards with `dryRun: false` and the returned `revision`.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | Exact folder id (`x-coredata://…/ICFolder/pN`), or the folder's Notes UUID or numeric key |
- | `expectedName` | string | Yes | Current folder name (not a path), matched case-sensitively |
- | `expectedAccountId` | string | Yes | Owning account id (`x-coredata://…/ICAccount/pN`) |
- | `expectedParentId` | string | One of these two | Current parent folder id (same forms as `id`) |
- | `expectedRoot` | `true` | One of these two | The folder sits at the account root |
- | `dryRun` | boolean | Yes | `true` plans; `false` applies |
- | `expectedRevision` | string | On apply | The `revision` from the dry run |
- **Example (plan, then apply with the returned revision):**
- ```json
- {
- "id": "x-coredata://ABC/ICFolder/p42",
- "expectedName": "Old Projects",
- "expectedAccountId": "x-coredata://ABC/ICAccount/p3",
- "expectedRoot": true,
- "dryRun": true
- }
- ```
- **Returns:** `status: "planned"` with `wouldDelete`, `identifier`, `name`,
- `accountId`, `parentId`, `folderType: 0`, zero `childFolderCount` and
- `noteCount`, and `revision`; on apply, `status: "deleted"`, `committed: true`,
- `verified: true` (Notes.app no longer resolves the id), and `storeTombstoned`.
- **Safety:** it always refuses Recently Deleted, smart folders, the account's
- default and other system folders, shared folders (or folders inside a shared
- folder), and any folder that still holds notes or subfolders. There is no
- override. It is **not atomic**: the guard is a pre-check followed by an
- AppleScript delete. The name, parent, account, sharing, and emptiness checks
- repeat inside the delete script, but the folder type and stable identifier come
- from the local Notes database just before it. It needs Full Disk Access and
- fails closed without it.
- **Errors** carry the standard `code`: `revision_conflict` (a `Conflict:` message;
- read and plan again), `unsupported` (a `Refused:` message), `verification_failed`
- with `indeterminate: true` (read the folder before any retry), and
- `full_disk_access_missing`.
- ---
- #### `delete-folder`
- Deletes a folder.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `name` | string | Yes | Name or path of the folder to delete (supports nested paths like `"Work/Old"`) |
- | `account` | string | No | Account containing the folder (defaults to Notes.app's default account; exact or unique-prefix match) |
- **Example:**
- ```json
- {
- "name": "Old Projects"
- }
- ```
- **Returns:** Confirmation message, or error if folder not found or not empty.
- **⚠️ Safety:** Irreversible — requires explicit user confirmation before calling. Prefer `list-folders` first to confirm the exact folder path being deleted.
- ---
- #### `show-folder`
- Reveals a folder in Notes.app using its unique CoreData identifier.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | The folder's CoreData identifier (from `list-folders`), or its Notes UUID or numeric key |
- | `separately` | boolean | No | Open in a separate window when supported by Notes.app |
- **Returns:** Confirmation that Notes.app accepted the show command.
- ---
- ### Account Operations
- #### `list-accounts`
- Lists all configured Notes accounts.
- **Parameters:** None
- **Example:**
- ```json
- {}
- ```
- **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.
- ---
- #### `get-default-location`
- Returns the default account and folder Notes.app uses for newly created notes.
- **Parameters:** None
- **Returns:** Default account and folder metadata, including IDs and shared state.
- ---
- #### `show-account`
- Reveals an account in Notes.app using its unique CoreData identifier.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `id` | string | Yes | The account's CoreData identifier (from `list-accounts`) |
- | `separately` | boolean | No | Open in a separate window when supported by Notes.app |
- **Returns:** Confirmation that Notes.app accepted the show command.
- ---
- ### Batch Operations
- #### `batch-delete-notes`
- Deletes multiple notes at once by ID.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `notes` | object[] | Yes | Array of `{id, expectedContentHash}` snapshots to delete (max 500 per request) |
- **Returns:** Summary of successes and failures. A note already in Recently Deleted fails without being deleted, as in `delete-note`.
- **⚠️ Safety:** Irreversible — requires explicit user confirmation before calling. Prefer `search-notes` / `list-notes` first to confirm the exact ids being deleted.
- ---
- #### `batch-move-notes`
- Moves multiple notes to a folder.
- | Parameter | Type | Required | Description |
- |-----------|------|----------|-------------|
- | `ids` | string[] | Yes | Array of note IDs to move (max 500 per request) |
- | `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 |
- | `account` | string | No | Account containing the folder |
- | `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 |
- **Returns:** Summary of successes and failures. Each success is reported only
- after the note's actual container folder ID matches the destination folder ID.
- If every note fails, the call returns its existing error response; the exact
- note IDs and reasons remain in the failure text.
- Failure rows carry `committed: false, indeterminate: false` only when that
- item was refused before its move. Move/readback failures and an unknown
- whole-script outcome carry `indeterminate: true`, with `committed` omitted.
- If every item fails, the batch reports `committed: false` only when every row
- is a proven pre-move refusal. Otherwise its error result is indeterminate;
- read each exact note ID before retrying, even if another row has a scope refusal.
- **Example - move only notes that are still in the reviewed inbox:**
- ```json
- {
- "ids": ["x-coredata://ABC123/ICNote/p456", "x-coredata://ABC123/ICNote/p457"],
- "folder": "Archive",
- "ifFolderId": "x-coredata://ABC123/ICFolder/p12"
- }
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
- /**
- * Unit Tests for Apple Notes Manager
- *
- * These tests verify the AppleNotesManager class and its helper functions.
- * The AppleScript execution is mocked to allow testing without macOS.
- *
- * Test Strategy:
- * - Helper functions (escapeForAppleScript, parseAppleScriptDate) are tested
- * with various inputs to ensure correct escaping and parsing
- * - Manager methods are tested for success/failure paths
- * - Script generation is verified by checking for expected AppleScript patterns
- */
- import { describe, it, expect, vi, beforeEach } from "vitest";
- import { execFileSync } from "node:child_process";
- import { writeFileSync, rmSync, mkdtempSync, readFileSync, statSync, existsSync } from "node:fs";
- import { tmpdir } from "node:os";
- import { join } from "node:path";
- import {
- AppleNotesManager,
- ExpectedBodies,
- escapeForAppleScript,
- escapeHtmlForAppleScript,
- buildAppleScriptDateVar,
- buildFolderReference,
- buildLiveFolderResolution,
- LIVE_FOLDER_NOT_FOUND,
- splitFolderPath,
- parseAppleScriptDate,
- sanitizeId,
- sanitizeNoteId,
- DEFAULT_EXPORT_PAGE_SIZE,
- estimateExportNoteBytes,
- exportMaxResponseBytes,
- } from "./appleNotesManager.js";
- // Mock the AppleScript execution module
- // This prevents actual osascript calls during testing
- // Only the executor is stubbed. `isPermissionDenied` is deliberately the REAL
- // implementation: the whole point of the shared classifier is that the health
- // check and the error mapping run the same code, so a mock here would test a
- // copy instead of the thing that ships.
- vi.mock("@/utils/applescript.js", async (importOriginal) => {
- const actual = await importOriginal<typeof import("@/utils/applescript.js")>();
- return {
- ...actual,
- executeAppleScript: vi.fn(),
- BULK_LIST_MUTATION_ERROR: "Notes changed during listing",
- };
- });
- // Mock the checklist parser to avoid SQLite access during tests
- vi.mock("@/utils/checklistParser.js", () => ({
- getChecklistItems: vi.fn().mockReturnValue({ items: null }),
- }));
- import { executeAppleScript, noteBodyMaxBuffer } from "@/utils/applescript.js";
- const mockExecuteAppleScript = vi.mocked(executeAppleScript);
- const NO_RETRY_OPTIONS = { maxRetries: 1 };
- import { getChecklistItems } from "@/utils/checklistParser.js";
- const mockGetChecklistItems = vi.mocked(getChecklistItems);
- // Mock the transcript reader so the delegation test never touches SQLite.
- vi.mock("@/utils/audioTranscripts.js", () => ({
- readAudioTranscripts: vi.fn(),
- }));
- import { readAudioTranscripts } from "@/utils/audioTranscripts.js";
- const mockReadAudioTranscripts = vi.mocked(readAudioTranscripts);
- // Recently Deleted folder ids come from the database; keep tests off it.
- vi.mock("@/utils/trashFolders.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@/utils/trashFolders.js")>()),
- readTrashFolderIds: vi.fn(() => []),
- }));
- import { readTrashFolderIds } from "@/utils/trashFolders.js";
- const mockReadTrashFolderIds = vi.mocked(readTrashFolderIds);
- // Smart folder ids come from the database too; none here, so destination
- // scripts are exactly what they were. smartFolderDestination.test.ts covers them.
- vi.mock("@/utils/smartFolders.js", async (importOriginal) => ({
- ...(await importOriginal<typeof import("@/utils/smartFolders.js")>()),
- readSmartFolders: vi.fn(() => ({ folders: [] })),
- }));
- const G = "\x1d";
- const TRASH_FOLDER = "x-coredata://ABC-123/ICFolder/p9";
- function compilesAsAppleScript(script: string): void {
- const dir = mkdtempSync(join(tmpdir(), "trash-script-"));
- try {
- writeFileSync(join(dir, "s.applescript"), script);
- execFileSync("/usr/bin/osacompile", ["-o", join(dir, "s.scpt"), join(dir, "s.applescript")], {
- stdio: "pipe",
- });
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- }
- // Result delimiters (#18) — must match appleNotesManager.ts.
- // FIELD_SEP (US, \x1f) separates fields within a record;
- // RECORD_SEP (RS, \x1e) separates records within a list.
- const F = "\x1f";
- const R = "\x1e";
- // =============================================================================
- // Text Escaping Tests
- // =============================================================================
- describe("escapeForAppleScript", () => {
- describe("empty and null handling", () => {
- it("returns empty string for empty input", () => {
- expect(escapeForAppleScript("")).toBe("");
- });
- it("returns empty string for null-like input", () => {
- // TypeScript prevents actual null, but runtime might have undefined
- expect(escapeForAppleScript(undefined as unknown as string)).toBe("");
- });
- });
- describe("single quote handling", () => {
- it("preserves single quotes (no escaping needed in AppleScript double-quoted strings)", () => {
- // Single quotes don't need escaping inside AppleScript double-quoted strings
- const result = escapeForAppleScript("it's working");
- expect(result).toBe("it's working");
- });
- it("handles multiple single quotes", () => {
- const result = escapeForAppleScript("Rob's mom's note");
- expect(result).toBe("Rob's mom's note");
- });
- });
- describe("double quote escaping (AppleScript strings)", () => {
- it("escapes double quotes for AppleScript", () => {
- // AppleScript strings: "hello \"quoted\" world"
- const result = escapeForAppleScript('say "hello"');
- expect(result).toBe('say \\"hello\\"');
- });
- it("handles mixed quotes", () => {
- const result = escapeForAppleScript('He said "it\'s fine"');
- expect(result).toBe('He said \\"it\'s fine\\"');
- });
- });
- describe("control character conversion (HTML for Notes.app)", () => {
- it("converts newlines to <br> tags", () => {
- const result = escapeForAppleScript("line 1\nline 2\nline 3");
- expect(result).toBe("line 1<br>line 2<br>line 3");
- });
- it("converts tabs to <br> tags", () => {
- const result = escapeForAppleScript("col1\tcol2\tcol3");
- expect(result).toBe("col1<br>col2<br>col3");
- });
- it("handles mixed control characters", () => {
- const result = escapeForAppleScript("row1\tcol2\nrow2\tcol2");
- expect(result).toBe("row1<br>col2<br>row2<br>col2");
- });
- });
- describe("complex content", () => {
- it("handles real-world note content", () => {
- const content = 'John\'s "Meeting Notes"\n- Item 1\n- Item 2';
- const result = escapeForAppleScript(content);
- expect(result).toBe('John\'s \\"Meeting Notes\\"<br>- Item 1<br>- Item 2');
- });
- });
- describe("unicode and special characters", () => {
- it("preserves unicode characters", () => {
- const result = escapeForAppleScript("日本語テスト 🎉");
- expect(result).toBe("日本語テスト 🎉");
- });
- it("preserves emoji in content", () => {
- const result = escapeForAppleScript("Shopping 🛒\n- Eggs 🥚\n- Milk 🥛");
- expect(result).toBe("Shopping 🛒<br>- Eggs 🥚<br>- Milk 🥛");
- });
- it("handles accented characters", () => {
- const result = escapeForAppleScript("Café résumé naïve");
- expect(result).toBe("Café résumé naïve");
- });
- it("handles backslashes", () => {
- // Backslashes are HTML-encoded to avoid AppleScript escaping issues
- const result = escapeForAppleScript("path\\to\\file");
- expect(result).toBe("path\to\file");
- });
- it("handles ampersands", () => {
- // Ampersands are HTML-encoded for Notes.app (& becomes &)
- const result = escapeForAppleScript("A && B & C");
- expect(result).toBe("A && B & C");
- });
- it("handles angle brackets (HTML-like content)", () => {
- // Single quotes pass through unchanged
- const result = escapeForAppleScript("<script>alert('xss')</script>");
- expect(result).toBe("<script>alert('xss')</script>");
- });
- });
- describe("boundary conditions", () => {
- it("handles very short strings", () => {
- expect(escapeForAppleScript("a")).toBe("a");
- expect(escapeForAppleScript("'")).toBe("'");
- expect(escapeForAppleScript('"')).toBe('\\"');
- });
- it("handles string with only whitespace", () => {
- expect(escapeForAppleScript(" ")).toBe(" ");
- });
- it("handles multiple consecutive special characters", () => {
- // Single quotes pass through, double quotes are escaped
- const result = escapeForAppleScript("'''\"\"\"");
- expect(result).toBe("'''\\\"\\\"\\\"");
- });
- });
- });
- // =============================================================================
- // HTML Content Escaping Tests (for already-HTML content)
- // =============================================================================
- describe("escapeHtmlForAppleScript", () => {
- describe("basic escaping", () => {
- it("returns empty string for null/undefined", () => {
- expect(escapeHtmlForAppleScript("")).toBe("");
- expect(escapeHtmlForAppleScript(null as unknown as string)).toBe("");
- expect(escapeHtmlForAppleScript(undefined as unknown as string)).toBe("");
- });
- it("escapes double quotes for AppleScript", () => {
- const result = escapeHtmlForAppleScript('<div>Hello "World"</div>');
- expect(result).toBe('<div>Hello \\"World\\"</div>');
- });
- it("escapes backslashes for AppleScript", () => {
- const result = escapeHtmlForAppleScript("<div>Path: C:\\Users\\test</div>");
- expect(result).toBe("<div>Path: C:\\\\Users\\\\test</div>");
- });
- it("handles both backslashes and quotes", () => {
- const result = escapeHtmlForAppleScript('<div>Path: "C:\\test"</div>');
- expect(result).toBe('<div>Path: \\"C:\\\\test\\"</div>');
- });
- });
- describe("preserves HTML content", () => {
- it("does not re-encode existing HTML entities", () => {
- const result = escapeHtmlForAppleScript("<div>& < ></div>");
- expect(result).toBe("<div>& < ></div>");
- });
- it("preserves HTML tags", () => {
- const result = escapeHtmlForAppleScript("<div><b>Bold</b><br><i>Italic</i></div>");
- expect(result).toBe("<div><b>Bold</b><br><i>Italic</i></div>");
- });
- it("preserves numeric HTML entities", () => {
- const result = escapeHtmlForAppleScript("<div>\ < ></div>");
- expect(result).toBe("<div>\ < ></div>");
- });
- });
- });
- // =============================================================================
- // Date Parsing Tests
- // =============================================================================
- describe("parseAppleScriptDate", () => {
- describe("standard format parsing", () => {
- it("parses AppleScript date with 'date' prefix", () => {
- const dateStr = "date Saturday, December 27, 2025 at 3:44:02 PM";
- const result = parseAppleScriptDate(dateStr);
- expect(result.getFullYear()).toBe(2025);
- expect(result.getMonth()).toBe(11); // December is month 11 (0-indexed)
- expect(result.getDate()).toBe(27);
- });
- it("parses date without 'date' prefix", () => {
- const dateStr = "Saturday, December 27, 2025 at 3:44:02 PM";
- const result = parseAppleScriptDate(dateStr);
- expect(result.getFullYear()).toBe(2025);
- expect(result.getMonth()).toBe(11);
- });
- it("correctly handles AM/PM times", () => {
- const morningDate = "date Monday, January 1, 2025 at 9:30:00 AM";
- const eveningDate = "date Monday, January 1, 2025 at 9:30:00 PM";
- const morning = parseAppleScriptDate(morningDate);
- const evening = parseAppleScriptDate(eveningDate);
- expect(morning.getHours()).toBe(9);
- expect(evening.getHours()).toBe(21);
- });
- });
- describe("locale-independent numeric format (#25)", () => {
- it("parses the Y-M-D-H-m-s form emitted by our producers", () => {
- const result = parseAppleScriptDate("2025-12-27-15-44-2");
- expect(result.getFullYear()).toBe(2025);
- expect(result.getMonth()).toBe(11);
- expect(result.getDate()).toBe(27);
- expect(result.getHours()).toBe(15);
- expect(result.getMinutes()).toBe(44);
- expect(result.getSeconds()).toBe(2);
- });
- it("handles single-digit components and midnight", () => {
- const result = parseAppleScriptDate("2025-1-5-0-0-0");
- expect(result.getMonth()).toBe(0);
- expect(result.getDate()).toBe(5);
- expect(result.getHours()).toBe(0);
- });
- });
- describe("fallback behavior", () => {
- it("returns current date for invalid input", () => {
- const before = new Date();
- const result = parseAppleScriptDate("not a valid date");
- const after = new Date();
- // Result should be between before and after (i.e., "now")
- expect(result.getTime()).toBeGreaterThanOrEqual(before.getTime());
- expect(result.getTime()).toBeLessThanOrEqual(after.getTime());
- });
- it("returns current date for empty string", () => {
- const before = new Date();
- const result = parseAppleScriptDate("");
- const after = new Date();
- expect(result.getTime()).toBeGreaterThanOrEqual(before.getTime());
- expect(result.getTime()).toBeLessThanOrEqual(after.getTime());
- });
- });
- });
- // =============================================================================
- // buildFolderReference Tests
- // =============================================================================
- describe("splitFolderPath", () => {
- it("splits simple path on /", () => {
- expect(splitFolderPath("Work/Clients")).toEqual(["Work", "Clients"]);
- });
- it("returns single segment for a name without /", () => {
- expect(splitFolderPath("Work")).toEqual(["Work"]);
- });
- it("preserves escaped slashes in folder names", () => {
- expect(splitFolderPath("Travel/Spain\\/Portugal 2023")).toEqual([
- "Travel",
- "Spain/Portugal 2023",
- ]);
- });
- it("handles multiple escaped slashes", () => {
- expect(splitFolderPath("A\\/B/C\\/D")).toEqual(["A/B", "C/D"]);
- });
- });
- describe("buildFolderReference", () => {
- it("returns simple folder reference for a single name", () => {
- expect(buildFolderReference("Work")).toBe('folder "Work"');
- });
- it("returns nested folder reference for a path", () => {
- expect(buildFolderReference("Work/Clients")).toBe('folder "Clients" of folder "Work"');
- });
- it("handles deeply nested paths", () => {
- expect(buildFolderReference("Work/Clients/Omnia")).toBe(
- 'folder "Omnia" of folder "Clients" of folder "Work"'
- );
- });
- it("handles special characters in folder names", () => {
- const result = buildFolderReference("Food & Drink/🥘 Recipes");
- expect(result).toContain('folder "🥘 Recipes"');
- expect(result).toContain('folder "Food & Drink"');
- });
- it("handles escaped slashes in folder names", () => {
- const result = buildFolderReference("Travel/Spain\\/Portugal 2023");
- expect(result).toBe('folder "Spain/Portugal 2023" of folder "Travel"');
- });
- });
- // #213: name references keep resolving folders deleted earlier in the Notes
- // session, so folder writes resolve each path segment to a live id.
- describe("buildLiveFolderResolution", () => {
- it("accepts a root segment only when it still exists by id", () => {
- const script = buildLiveFolderResolution("Work", "f");
- expect(script).toContain('repeat with f_c in (folders of __acctRef whose name is "Work")');
- expect(script).toContain("set f_cid to id of f_c");
- expect(script).toContain("if exists folder id f_cid then");
- expect(script).toContain("if class of (container of f_c) is not folder then");
- expect(script).toContain("set f to folder id f_cid");
- expect(script).toContain(
- `if f is missing value then error "${LIVE_FOLDER_NOT_FOUND}: Work" number -1728`
- );
- expect(script).not.toContain('folder "Work"');
- });
- it("falls back to a live nested namesake unless rootOnly", () => {
- expect(buildLiveFolderResolution("Work", "f")).toContain(
- "if f is missing value then set f to f_any"
- );
- expect(buildLiveFolderResolution("Work", "f", { rootOnly: true })).not.toContain(
- "set f to f_any"
- );
- });
- it("walks nested segments under the resolved parent", () => {
- const script = buildLiveFolderResolution("Work/Clients/Omnia", "f");
- const clients = script.indexOf('repeat with f_c in (folders of f_p whose name is "Clients")');
- const omnia = script.indexOf('repeat with f_c in (folders of f_p whose name is "Omnia")');
- expect(script.indexOf('whose name is "Work"')).toBeLessThan(clients);
- expect(clients).toBeGreaterThan(0);
- expect(omnia).toBeGreaterThan(clients);
- expect(script.match(/if exists folder id f_cid then/g)).toHaveLength(3);
- expect(script.match(/if f is missing value then error/g)).toHaveLength(3);
- });
- it("escapes names and honours escaped slashes", () => {
- const script = buildLiveFolderResolution('Travel/Spain\\/Portugal "23"', "f");
- expect(script).toContain('whose name is "Spain/Portugal \\"23\\""');
- });
- it("rejects invalid variables and paths", () => {
- expect(() => buildLiveFolderResolution("Work", "bad name")).toThrow(/variable/);
- expect(() => buildLiveFolderResolution("", "f")).toThrow();
- });
- });
- // =============================================================================
- // buildAppleScriptDateVar Tests
- // =============================================================================
- describe("buildAppleScriptDateVar", () => {
- it("generates locale-safe AppleScript date setup code", () => {
- const date = new Date(2025, 5, 15, 14, 30, 0); // June 15, 2025 2:30 PM
- const result = buildAppleScriptDateVar(date);
- expect(result).toContain("set thresholdDate to current date");
- expect(result).toContain("set year of thresholdDate to 2025");
- expect(result).toContain("set month of thresholdDate to 6");
- expect(result).toContain("set day of thresholdDate to 15");
- // 14*3600 + 30*60 = 52200
- expect(result).toContain("set time of thresholdDate to 52200");
- });
- it("handles midnight (time = 0)", () => {
- const date = new Date(2025, 0, 1, 0, 0, 0); // Jan 1, 2025 midnight
- const result = buildAppleScriptDateVar(date);
- expect(result).toContain("set month of thresholdDate to 1");
- expect(result).toContain("set day of thresholdDate to 1");
- expect(result).toContain("set time of thresholdDate to 0");
- });
- it("uses custom variable name", () => {
- const date = new Date(2025, 0, 1, 0, 0, 0);
- const result = buildAppleScriptDateVar(date, "myDate");
- expect(result).toContain("set myDate to current date");
- expect(result).toContain("set year of myDate to 2025");
- expect(result).toContain("set month of myDate to 1");
- });
- it("calculates time in seconds correctly", () => {
- const date = new Date(2025, 11, 25, 9, 5, 3); // 9:05:03 AM
- const result = buildAppleScriptDateVar(date);
- // 9*3600 + 5*60 + 3 = 32703
- expect(result).toContain("set time of thresholdDate to 32703");
- });
- it("resets day to 1 before month to prevent month rollover (#86)", () => {
- // AppleScript rolls invalid intermediate dates: with `current date` on the
- // 31st, setting month to June yields July 1 before day is ever assigned.
- // Day must be pinned to 1 before the year/month assignments.
- const date = new Date(2025, 5, 15, 0, 0, 0); // June 15, 2025
- const result = buildAppleScriptDateVar(date);
- const lines = result.split("\n");
- const dayResetIdx = lines.indexOf("set day of thresholdDate to 1");
- const yearIdx = lines.indexOf("set year of thresholdDate to 2025");
- const monthIdx = lines.indexOf("set month of thresholdDate to 6");
- const dayIdx = lines.indexOf("set day of thresholdDate to 15");
- expect(dayResetIdx).toBeGreaterThan(-1);
- expect(dayResetIdx).toBeLessThan(yearIdx);
- expect(yearIdx).toBeLessThan(monthIdx);
- expect(monthIdx).toBeLessThan(dayIdx);
- });
- });
- // =============================================================================
- // AppleNotesManager Tests
- // =============================================================================
- describe("AppleNotesManager", () => {
- let manager: AppleNotesManager;
- beforeEach(() => {
- manager = new AppleNotesManager();
- vi.clearAllMocks();
- });
- // ---------------------------------------------------------------------------
- // Account Resolution (#128)
- // ---------------------------------------------------------------------------
- describe("account resolution", () => {
- it("targets Notes.app's own default account when none is given", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.searchNotes("anything");
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- // A hardcoded "iCloud" is wrong whenever the real default account differs
- // — a non-iCloud default, a localized name, or a U+F8FF suffix (#128).
- expect(script).toContain("set __acctRef to default account");
- expect(script).not.toContain('tell account "iCloud"');
- });
- it("prefers an exact name match over a prefix match", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.searchNotes("anything", false, "Work");
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- const exactAt = script.indexOf('every account whose name is "Work"');
- const prefixAt = script.indexOf('every account whose name starts with "Work"');
- expect(exactAt).toBeGreaterThan(-1);
- expect(prefixAt).toBeGreaterThan(-1);
- // Exact is tested first, and prefix is only consulted in the else branch.
- expect(exactAt).toBeLessThan(prefixAt);
- });
- it("refuses an ambiguous prefix match instead of silently picking the first", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.searchNotes("anything", false, "rob");
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- // `first account whose name starts with ...` would resolve "rob" to
- // whichever of rob@… / robert@… Notes lists first and report success —
- // on the delete/move paths that is a destructive wrong-account write.
- expect(script).not.toContain("first account whose name starts with");
- expect(script).toContain("is ambiguous");
- expect(script).toContain("(count of _prefixMatches) > 1");
- });
- it("errors rather than proceeding when the named account does not exist", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.searchNotes("anything", false, "Nope");
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- expect(script).toContain('Account \\"Nope\\" not found"');
- // Tagged so the swallow-into-false callers can tell a precondition error
- // from a genuine "note not found" outcome.
- expect(script).toContain("AccountResolutionError:");
- });
- it("reports an unresolvable account as such instead of 'note not found' on destructive paths", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error:
- 'AccountResolutionError: Account "rob" is ambiguous - it matches 2 accounts: rob@a, rob@b. Use the full account name.',
- });
- // deleteFolder normally swallows failures into `false`; an unresolvable
- // account must surface instead, or the caller goes hunting for a missing
- // folder that was never the problem. (Same resolveAccount() path every
- // account-scoped destructive method uses.)
- expect(() => manager.deleteFolder("Doomed", "rob")).toThrow(/is ambiguous/);
- expect(() => manager.deleteFolder("Doomed", "rob")).not.toThrow(/AccountResolutionError/);
- });
- it("still swallows a genuine operation failure into false", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: 'Can\'t get folder "Doomed".',
- });
- expect(manager.deleteFolder("Doomed", "iCloud")).toBe(false);
- });
- it("resolves the account for destructive paths too (deleteFolder, batch move)", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.deleteFolder("Doomed", "rob");
- const deleteScript = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
- expect(deleteScript).toContain("is ambiguous");
- expect(deleteScript).not.toContain("first account whose name starts with");
- manager.batchMoveNotes(["x-coredata://ABC/ICNote/p1"], "Archive", "rob");
- const moveScript = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
- expect(moveScript).toContain("is ambiguous");
- expect(moveScript).toContain("of __acctRef");
- });
- it("treats a blank account string as 'use the default'", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.searchNotes("anything", false, " ");
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- expect(script).toContain("set __acctRef to default account");
- });
- });
- describe("listAttachments — security", () => {
- it("escapes the account name so it cannot break out of the AppleScript literal (injection regression)", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.listAttachments("My Note", 'evil" injected');
- const script = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
- // The account's double-quote must be escaped (\\") — a raw quote would
- // terminate the account-name string literal and allow `do shell script` injection.
- expect(script).toContain('every account whose name is "evil\\" injected"');
- expect(script).not.toContain('every account whose name is "evil" injected"');
- });
- });
- // ---------------------------------------------------------------------------
- // Note Creation
- // ---------------------------------------------------------------------------
- describe("createNote", () => {
- it("does not retry creation after an ambiguous timeout", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Operation timed out after 30 seconds",
- });
- manager.createNote("One copy", "Body");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), { maxRetries: 1 });
- });
- it("returns Note object on successful creation", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({
- success: true,
- output: "note id x-coredata://12345/ICNote/p100",
- })
- // The reported account comes from Notes.app's own default account (#128),
- // not a hardcoded "iCloud".
- .mockReturnValueOnce({ success: true, output: "Personal" });
- const result = manager.createNote("Shopping List", "Eggs, Milk, Bread");
- expect(result).not.toBeNull();
- expect(result?.title).toBe("Shopping List");
- expect(result?.content).toBe("Eggs, Milk, Bread");
- expect(result?.account).toBe("Personal");
- });
- it("strips the 'note id ' prefix from the returned id (#create-note-id)", () => {
- // AppleScript's `id of newNote` yields an object specifier with a literal
- // "note id " prefix. The returned id must be the bare x-coredata:// URL so
- // downstream tools (get-note-content, update-note) accept it.
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://ABC-DEF/ICNote/p42",
- });
- const result = manager.createNote("Prefixed", "Body");
- expect(result?.id).toBe("x-coredata://ABC-DEF/ICNote/p42");
- expect(result?.id).not.toMatch(/^note id /);
- });
- it("accepts the bare canonical ID form returned by some Notes accounts", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "x-coredata://ABC-DEF/ICNote/p43",
- });
- expect(manager.createNote("Bare ID", "Body")?.id).toBe("x-coredata://ABC-DEF/ICNote/p43");
- });
- it("fails closed when Notes does not return a real CoreData note ID", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "note 1 of folder Notes" });
- const result = manager.createNote("No writable identity", "Body");
- expect(result).toBeNull();
- });
- it("returned id round-trips through get-note-content and update-note (#create-note-id)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://ABC-DEF/ICNote/p99",
- });
- const created = manager.createNote("Roundtrip", "Body");
- const id = created?.id as string;
- expect(id).toBe("x-coredata://ABC-DEF/ICNote/p99");
- // Reading back by the returned id must not throw "Invalid note ID format".
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "Body text" });
- expect(() => manager.getNoteContentById(id)).not.toThrow();
- // Updating by the returned id must not throw either.
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_UPDATED" });
- expect(() =>
- manager.updateNoteByIdIfUnchanged(id, "Roundtrip", "<div>Body</div>", undefined, "New body")
- ).not.toThrow();
- });
- it("returns null when AppleScript fails", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Notes.app not responding",
- });
- const result = manager.createNote("Test", "Content");
- expect(result).toBeNull();
- });
- it("uses specified account instead of default", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://ABC/ICNote/p201",
- });
- const result = manager.createNote("Draft", "Email content", [], undefined, "Gmail");
- expect(result?.account).toBe("Gmail");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Gmail"'),
- NO_RETRY_OPTIONS
- );
- });
- it("creates note in specified folder", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://ABC/ICNote/p202",
- });
- manager.createNote("Work Note", "Content", [], "Work Projects");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain('whose name is "Work Projects"');
- expect(script).toContain("exists folder id __folder_cid");
- expect(script).toContain("make new note at __folder with properties");
- expect(script).not.toContain('at folder "Work Projects"');
- expect(mockExecuteAppleScript.mock.calls[0][1]).toEqual(NO_RETRY_OPTIONS);
- });
- it("stores tags in returned Note object", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://ABC/ICNote/p203",
- });
- const result = manager.createNote("Tagged Note", "Content", ["work", "urgent"]);
- expect(result?.tags).toEqual(["work", "urgent"]);
- });
- it("uses escapeHtmlForAppleScript when format is html", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p200",
- });
- const htmlContent = "<h2>Heading</h2><div>Body text</div>";
- const result = manager.createNote("HTML Note", htmlContent, [], undefined, undefined, "html");
- expect(result).not.toBeNull();
- // HTML tags should NOT be entity-encoded — they should pass through to AppleScript
- // escapeHtmlForAppleScript only escapes \ and ", not HTML tags
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("<h2>Heading</h2><div>Body text</div>"),
- NO_RETRY_OPTIONS
- );
- });
- it("uses escapeForAppleScript when format is plaintext (default)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p201",
- });
- const result = manager.createNote("Plain Note", "Simple text with\nnewline");
- expect(result).not.toBeNull();
- // Default plaintext: newlines become <br>
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("Simple text with<br>newline"),
- NO_RETRY_OPTIONS
- );
- });
- it("escapes double quotes in html format for AppleScript safety", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p202",
- });
- manager.createNote(
- "Quote Test",
- '<div class="test">Content</div>',
- [],
- undefined,
- undefined,
- "html"
- );
- // Double quotes must be escaped for AppleScript string embedding
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('<div class=\\"test\\">Content</div>'),
- NO_RETRY_OPTIONS
- );
- });
- it("sets title as h1 in body, not as name property", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p203",
- });
- manager.createNote("My Title", "Body content");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- // Title must appear as h1 in body
- expect(script).toContain("<h1>My Title</h1>");
- // name property must NOT be set (causes title duplication in Notes.app)
- expect(script).not.toContain('name:"My Title"');
- });
- it("HTML-encodes special chars in title for h1 tag", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p204",
- });
- manager.createNote("Q&A: <Hello> World", "Content");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("<h1>Q&A: <Hello> World</h1>"),
- NO_RETRY_OPTIONS
- );
- });
- it("HTML-encodes special chars in plaintext content", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p205",
- });
- manager.createNote("Title", "Price: <10 & >5\nNext line");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain("Price: <10 & >5<br>Next line");
- });
- it("prepends h1 title before html content", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p206",
- });
- manager.createNote(
- "Report",
- "<h2>Section</h2><div>Details</div>",
- [],
- undefined,
- undefined,
- "html"
- );
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain("<h1>Report</h1><h2>Section</h2><div>Details</div>");
- });
- it("encodes backslashes as HTML entities in plaintext content", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p207",
- });
- manager.createNote("Title", "path\\to\\file");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain("path\to\file");
- });
- it("converts tabs to br in plaintext content", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "note id x-coredata://12345/ICNote/p208",
- });
- manager.createNote("Title", "col1\tcol2\tcol3");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain("col1<br>col2<br>col3");
- });
- });
- // ---------------------------------------------------------------------------
- // Note Search
- // ---------------------------------------------------------------------------
- describe("searchNotes", () => {
- it("returns array of matching notes with folder info", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Meeting Notes", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
- ["Project Plan", "x-coredata://ABC/ICNote/p2", "Notes"].join(F),
- ["Weekly Review", "x-coredata://ABC/ICNote/p3", "Archive"].join(F),
- ].join(R),
- });
- const results = manager.searchNotes("notes");
- expect(results).toHaveLength(3);
- expect(results[0].title).toBe("Meeting Notes");
- expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
- expect(results[0].folder).toBe("Work");
- expect(results[1].title).toBe("Project Plan");
- expect(results[1].id).toBe("x-coredata://ABC/ICNote/p2");
- expect(results[1].folder).toBe("Notes");
- expect(results[2].title).toBe("Weekly Review");
- expect(results[2].id).toBe("x-coredata://ABC/ICNote/p3");
- expect(results[2].folder).toBe("Archive");
- });
- it("dereferences the note container before reading its folder name", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Meeting Notes", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
- });
- manager.searchNotes("meeting");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain("set noteContainer to container of n");
- expect(script).toContain("set noteFolder to name of noteContainer");
- expect(script).not.toContain("set noteFolder to name of container of n");
- });
- it("returns actual creation and modification timestamps", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Meeting Notes",
- "x-coredata://ABC/ICNote/p1",
- "Work",
- "2024-2-3-10-11-12",
- "2025-6-7-13-14-15",
- ].join(F),
- });
- const [result] = manager.searchNotes("meeting");
- expect(result.created).toEqual(new Date(2024, 1, 3, 10, 11, 12));
- expect(result.modified).toEqual(new Date(2025, 5, 7, 13, 14, 15));
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain("set noteCreated to creation date of n");
- expect(script).toContain("set noteModified to modification date of n");
- expect(script).toContain("year of noteCreated");
- expect(script).toContain("year of noteModified");
- });
- it("returns empty array when no matches found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- const results = manager.searchNotes("nonexistent");
- expect(results).toHaveLength(0);
- });
- it("throws on AppleScript error rather than returning empty (#19)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Search failed",
- });
- expect(() => manager.searchNotes("test")).toThrow(/Search failed/);
- });
- it("searches content when searchContent is true", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Note with keyword", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("project alpha", true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('body contains "project alpha"')
- );
- });
- it("searches titles when searchContent is false", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Project Alpha Notes", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("Project Alpha", false);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('name contains "Project Alpha"')
- );
- });
- it("identifies notes in Recently Deleted folder", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Old Note", "x-coredata://ABC/ICNote/p1", "Recently Deleted"].join(F),
- ["Active Note", "x-coredata://ABC/ICNote/p2", "Notes"].join(F),
- ].join(R),
- });
- const results = manager.searchNotes("note");
- expect(results).toHaveLength(2);
- expect(results[0].title).toBe("Old Note");
- expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
- expect(results[0].folder).toBe("Recently Deleted");
- expect(results[1].title).toBe("Active Note");
- expect(results[1].id).toBe("x-coredata://ABC/ICNote/p2");
- expect(results[1].folder).toBe("Notes");
- });
- it("deduplicates duplicate note IDs returned by Notes.app", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Not uploaded", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- ["Not uploaded", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- ].join(R),
- });
- const results = manager.searchNotes("Not uploaded");
- expect(results).toHaveLength(1);
- expect(results[0].title).toBe("Not uploaded");
- expect(results[0].id).toBe("x-coredata://ABC/ICNote/p1");
- });
- it("scopes search to specified account", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- manager.searchNotes("work", false, "Exchange");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Exchange"')
- );
- });
- it("limits search to specified folder", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Work Note", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
- });
- manager.searchNotes("note", false, undefined, "Work");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('notes of folder "Work"')
- );
- });
- it("combines folder and account filters", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- manager.searchNotes("task", false, "Exchange", "Projects");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain('every account whose name is "Exchange"');
- expect(script).toContain('notes of folder "Projects"');
- });
- it("adds date filter when modifiedSince is provided", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Recent Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("note", false, undefined, undefined, "2025-06-15T00:00:00");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- // Locale-safe: uses variable setup instead of date "string"
- expect(script).toContain("set thresholdDate to current date");
- expect(script).toContain("set year of thresholdDate to 2025");
- expect(script).toContain("set month of thresholdDate to 6");
- expect(script).toContain("set day of thresholdDate to 15");
- expect(script).toContain("modification date >= thresholdDate");
- expect(script).toContain('name contains "note"');
- });
- it("combines date filter with content search", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("keyword", true, undefined, undefined, "2025-01-01");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain('body contains "keyword"');
- expect(script).toContain("set thresholdDate to current date");
- expect(script).toContain("modification date >= thresholdDate");
- });
- it("ignores invalid modifiedSince date", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Note", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("note", false, undefined, undefined, "not-a-date");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).not.toContain("modification date >= thresholdDate");
- });
- it("applies limit to search results", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Note 1", "x-coredata://ABC/ICNote/p1", "Notes"].join(F),
- });
- manager.searchNotes("note", false, undefined, undefined, undefined, 5);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain("(count of resultList) >= 5");
- expect(script).toContain("exit repeat");
- });
- it("combines modifiedSince, limit, folder, and content search", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Note", "x-coredata://ABC/ICNote/p1", "Work"].join(F),
- });
- manager.searchNotes("project", true, "iCloud", "Work", "2025-03-01", 10);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain('body contains "project"');
- expect(script).toContain("set thresholdDate to current date");
- expect(script).toContain("modification date >= thresholdDate");
- expect(script).toContain('notes of folder "Work"');
- expect(script).toContain("(count of resultList) >= 10");
- expect(script).toContain('every account whose name is "iCloud"');
- });
- });
- // ---------------------------------------------------------------------------
- // Note Content Retrieval
- // ---------------------------------------------------------------------------
- describe("getNoteContent", () => {
- it("returns HTML content of note", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "<div>Shopping List</div><div>- Eggs<br>- Milk</div>",
- });
- const content = manager.getNoteContent("Shopping List");
- expect(content).toBe("<div>Shopping List</div><div>- Eggs<br>- Milk</div>");
- });
- it("returns empty string when note not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: 'Can\'t get note "Missing"',
- });
- const content = manager.getNoteContent("Missing Note");
- expect(content).toBe("");
- });
- it("looks up titles containing & literally, not HTML-escaped (regression)", () => {
- // Bug found in live testing: titles with "&" were HTML-escaped to "&"
- // in the `note "..."` lookup, so the note could never be found.
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "<div>x</div>" });
- manager.getNoteContent("Tom & Jerry", "iCloud");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain("Tom & Jerry");
- expect(script).not.toContain("Tom & Jerry");
- });
- it("uses specified account", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "<div>Content</div>",
- });
- manager.getNoteContent("My Note", "Gmail");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Gmail"'),
- { maxBufferBytes: noteBodyMaxBuffer() }
- );
- });
- it("reads bodies with the note-body output cap, by title and by id (#237)", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "<div>x</div>" });
- manager.getNoteContent("Photo note", "iCloud");
- manager.getNoteContentById("x-coredata://ABC/ICNote/p1");
- const bodyReads = mockExecuteAppleScript.mock.calls.filter(([script]) =>
- String(script).includes("get body of note")
- );
- expect(bodyReads).toHaveLength(2);
- for (const [, options] of bodyReads) {
- expect(options).toEqual({ maxBufferBytes: noteBodyMaxBuffer() });
- }
- });
- });
- describe("getNotePlaintext", () => {
- it("reads the note's plaintext property by title", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "Shopping List\n- Eggs\n- Milk",
- });
- const text = manager.getNotePlaintext("Shopping List");
- expect(text).toBe("Shopping List\n- Eggs\n- Milk");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('get plaintext of note "Shopping List"')
- );
- });
- it("returns empty string when the note is not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: 'Can\'t get note "Missing"',
- });
- expect(manager.getNotePlaintext("Missing Note")).toBe("");
- });
- it("uses the specified account", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "Content" });
- manager.getNotePlaintext("My Note", "Gmail");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Gmail"')
- );
- });
- });
- describe("getNotePlaintextById", () => {
- it("reads the note's plaintext property by id at the application level", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "Just the text" });
- const text = manager.getNotePlaintextById("x-coredata://ABC/ICNote/p1");
- expect(text).toBe("Just the text");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('get plaintext of note id "x-coredata://ABC/ICNote/p1"')
- );
- });
- it("returns empty string when Notes.app rejects the read", () => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "no such note" });
- expect(manager.getNotePlaintextById("x-coredata://ABC/ICNote/p1")).toBe("");
- });
- it("rejects malformed IDs", () => {
- expect(() => manager.getNotePlaintextById("arbitrary string")).toThrow();
- });
- });
- // ---------------------------------------------------------------------------
- // Password Protection Helpers
- // ---------------------------------------------------------------------------
- describe("isNotePasswordProtected", () => {
- it("returns true when note is password-protected", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Locked Note",
- "x-coredata://ABC/ICNote/p1",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "false",
- "true",
- ].join(F),
- });
- const result = manager.isNotePasswordProtected("Locked Note");
- expect(result).toBe(true);
- });
- it("returns false when note is not password-protected", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Open Note",
- "x-coredata://ABC/ICNote/p2",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "false",
- "false",
- ].join(F),
- });
- const result = manager.isNotePasswordProtected("Open Note");
- expect(result).toBe(false);
- });
- it("returns false when note is not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Note not found",
- });
- const result = manager.isNotePasswordProtected("Missing Note");
- expect(result).toBe(false);
- });
- });
- describe("isNotePasswordProtectedById", () => {
- it("returns true when note is password-protected", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Locked Note",
- "x-coredata://ABC/ICNote/p1",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "false",
- "true",
- ].join(F),
- });
- const result = manager.isNotePasswordProtectedById("x-coredata://ABC/ICNote/p1");
- expect(result).toBe(true);
- });
- it("returns false when note is not password-protected", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Open Note",
- "x-coredata://ABC/ICNote/p2",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "Monday, January 1, 2024 at 12:00:00 PM",
- "false",
- "false",
- ].join(F),
- });
- const result = manager.isNotePasswordProtectedById("x-coredata://ABC/ICNote/p2");
- expect(result).toBe(false);
- });
- it("returns false when note is not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Note not found",
- });
- const result = manager.isNotePasswordProtectedById(
- "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
- );
- expect(result).toBe(false);
- });
- });
- // ---------------------------------------------------------------------------
- // Get Note By ID
- // ---------------------------------------------------------------------------
- describe("readNoteById", () => {
- const id = "x-coredata://ABC123/ICNote/p100";
- it("retains all successful metadata, including the password flag", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Locked note",
- id,
- "2026-10-12-10-20-0",
- "2026-10-12-11-30-0",
- "true",
- "true",
- ].join(F),
- });
- expect(manager.readNoteById(id)).toEqual({
- note: {
- id,
- title: "Locked note",
- content: "",
- tags: [],
- created: new Date(2026, 9, 12, 10, 20, 0),
- modified: new Date(2026, 9, 12, 11, 30, 0),
- shared: true,
- passwordProtected: true,
- },
- });
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- expect(mockExecuteAppleScript.mock.calls[0][0]).not.toContain("get body");
- });
- it.each([
- "Not authorized to send Apple events to Notes. (-1743)",
- "Operation timed out after 30 seconds",
- "Lost connection to Notes.app",
- "spawnSync osascript EACCES",
- "spawnSync osascript EACCES: Operation not permitted",
- "Can't get note id",
- "Note not found. The note may have been deleted or the ID is invalid.",
- ])("preserves executor failure %j while the legacy getter stays nullable", (error) => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error });
- expect(manager.readNoteById(id)).toEqual({ note: null, error });
- expect(manager.getNoteById(id)).toBeNull();
- });
- it.each([undefined, "", " "])(
- "supplies a diagnostic when the executor has no error: %j",
- (error) => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error });
- expect(manager.readNoteById(id)).toEqual({
- note: null,
- error: "AppleScript note metadata read failed",
- });
- expect(manager.getNoteById(id)).toBeNull();
- }
- );
- it("reports malformed metadata without echoing its contents or claiming absence", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: 'Private "timed out -1743" note not found',
- });
- expect(manager.readNoteById(id)).toEqual({
- note: null,
- error: "Unexpected note metadata response",
- });
- expect(manager.getNoteById(id)).toBeNull();
- });
- it("preserves invalid-ID rejection before either metadata reader runs", () => {
- expect(() => manager.readNoteById('invalid" id')).toThrow();
- expect(() => manager.getNoteById('invalid" id')).toThrow();
- expect(mockExecuteAppleScript).not.toHaveBeenCalled();
- });
- });
- describe("getNoteById", () => {
- it("returns Note object with metadata for valid ID", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "My Note",
- "x-coredata://ABC123/ICNote/p100",
- "Saturday, December 27, 2025 at 3:00:00 PM",
- "Saturday, December 27, 2025 at 4:00:00 PM",
- "false",
- "false",
- ].join(F),
- });
- const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
- expect(result).not.toBeNull();
- expect(result?.title).toBe("My Note");
- expect(result?.id).toBe("x-coredata://ABC123/ICNote/p100");
- expect(result?.shared).toBe(false);
- expect(result?.passwordProtected).toBe(false);
- });
- it("returns null when note ID not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Can't get note id",
- });
- const result = manager.getNoteById(
- "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
- );
- expect(result).toBeNull();
- });
- it("returns null when response format is unexpected (no commas)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "incomplete data with no commas",
- });
- const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
- expect(result).toBeNull();
- });
- it("returns null when response format is missing second comma", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "title only, no more data",
- });
- const result = manager.getNoteById("x-coredata://ABC123/ICNote/p100");
- // The new parsing requires at least title and ID separated by commas
- expect(result).toBeNull();
- });
- it("correctly parses shared and passwordProtected as true", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Shared Note",
- "x-coredata://ABC/ICNote/p1",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "true",
- "true",
- ].join(F),
- });
- const result = manager.getNoteById("x-coredata://ABC/ICNote/p1");
- expect(result?.shared).toBe(true);
- expect(result?.passwordProtected).toBe(true);
- });
- });
- // ---------------------------------------------------------------------------
- // Get Note Details
- // ---------------------------------------------------------------------------
- describe("getNoteDetails", () => {
- it("returns Note object with full metadata", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Project Notes",
- "x-coredata://ABC123/ICNote/p200",
- "Friday, December 20, 2025 at 10:00:00 AM",
- "Saturday, December 27, 2025 at 2:30:00 PM",
- "false",
- "false",
- ].join(F),
- });
- const result = manager.getNoteDetails("Project Notes");
- expect(result).not.toBeNull();
- expect(result?.title).toBe("Project Notes");
- expect(result?.id).toBe("x-coredata://ABC123/ICNote/p200");
- });
- it("returns null when note not found", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Can't get note",
- });
- const result = manager.getNoteDetails("Nonexistent");
- expect(result).toBeNull();
- });
- it("uses specified account", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Note",
- "id123",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "false",
- "false",
- ].join(F),
- });
- const result = manager.getNoteDetails("My Note", "Exchange");
- expect(result?.account).toBe("Exchange");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Exchange"')
- );
- });
- it("handles shared notes correctly", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "Shared Doc",
- "id456",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "Monday, January 1, 2025 at 12:00:00 PM",
- "true",
- "false",
- ].join(F),
- });
- const result = manager.getNoteDetails("Shared Doc");
- expect(result?.shared).toBe(true);
- });
- });
- describe("updateNoteByIdIfUnchanged", () => {
- const id = "x-coredata://ABC00000-0000-0000-0000-000000000003/ICNote/p789";
- const oldBody = "<div>Title</div><div>Old body</div>";
- it("checks body identity and attachments in the same AppleScript before writing", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_UPDATED" });
- const result = manager.updateNoteByIdIfUnchanged(id, "Title", oldBody, undefined, "New body");
- expect(result.status).toBe("updated");
- expect(result.writtenBody).toBe("<div>Title</div><div>New body</div>");
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(script).toContain("count of attachments of noteRef");
- expect(script).toContain("currentBody is not");
- expect(script).toContain(
- 'currentBody is not "<div>Title</div><div>Old body</div>" & linefeed'
- );
- expect(script.indexOf("count of attachments of noteRef")).toBeLessThan(
- script.indexOf("set body of noteRef")
- );
- expect(script.indexOf("currentBody is not")).toBeLessThan(
- script.indexOf("set body of noteRef")
- );
- // AppleScript's `is`/`is not` is case-insensitive by default, so a
- // case-only concurrent edit would otherwise slip past the conflict
- // guard. `considering case` must wrap the comparison (and the write,
- // so a false-equal never reaches `set body of noteRef`).
- expect(script.indexOf("considering case")).toBeLessThan(script.indexOf("currentBody is not"));
- expect(script.indexOf("set body of noteRef")).toBeLessThan(script.indexOf("end considering"));
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), NO_RETRY_OPTIONS);
- });
- it("reports a conflict without claiming an update", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_CONFLICT" });
- const result = manager.updateNoteByIdIfUnchanged(
- id,
- "Title",
- oldBody,
- undefined,
- "Stale body"
- );
- expect(result).toEqual({ status: "conflict" });
- });
- it("reports attachments without claiming an update", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_ATTACHMENTS" });
- const result = manager.updateNoteByIdIfUnchanged(
- id,
- "Title",
- oldBody,
- undefined,
- "Replacement"
- );
- expect(result).toEqual({ status: "attachments" });
- });
- });
- describe("deleteNoteByIdIfUnchanged", () => {
- const id = "x-coredata://ABC00000-0000-0000-0000-000000000004/ICNote/p790";
- it("compares the exact body in the same AppleScript before deleting", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
- const result = manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>");
- expect(result.status).toBe("deleted");
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(script).toContain("currentBody is not");
- expect(script.indexOf("currentBody is not")).toBeLessThan(script.indexOf("delete noteRef"));
- expect(script.indexOf("considering case")).toBeLessThan(script.indexOf("currentBody is not"));
- expect(script.indexOf("delete noteRef")).toBeLessThan(script.indexOf("end considering"));
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(expect.any(String), NO_RETRY_OPTIONS);
- });
- it("rejects deletion when the reviewed body is stale", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_CONFLICT" });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Old body</div>")).toEqual({
- status: "conflict",
- });
- });
- it("reports a delete that left the note in its original folder", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_NOT_DELETED" });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>")).toEqual({
- status: "not-deleted",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- // The folder is captured before the delete and re-read after it.
- expect(script.indexOf("container of noteRef")).toBeLessThan(script.indexOf("delete noteRef"));
- expect(script.indexOf("delete noteRef")).toBeLessThan(
- script.indexOf("id of notes of originalFolder")
- );
- });
- // #195: a failed placement re-read is not evidence the note left its folder.
- it("reports an unverified delete when the placement re-read fails", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "SAFETY_DELETE_UNVERIFIED",
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Reviewed body</div>")).toEqual({
- status: "unverified",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- const recheck = script.slice(script.indexOf("delete noteRef"));
- expect(recheck).toMatch(
- /if __stillThere is missing value then return "SAFETY_DELETE_UNVERIFIED"/
- );
- expect(recheck.indexOf("SAFETY_DELETE_UNVERIFIED")).toBeLessThan(
- recheck.indexOf('return "SAFETY_DELETED"')
- );
- });
- it("generates a delete script that AppleScript compiles", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
- manager.deleteNoteByIdIfUnchanged(id, '<div>Body with "quotes" and \\ slash</div>');
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- const dir = mkdtempSync(join(tmpdir(), "delete-script-"));
- try {
- writeFileSync(join(dir, "delete.applescript"), script);
- expect(() =>
- execFileSync(
- "/usr/bin/osacompile",
- ["-o", join(dir, "delete.scpt"), join(dir, "delete.applescript")],
- { stdio: "pipe" }
- )
- ).not.toThrow();
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
- });
- // ---------------------------------------------------------------------------
- // Note Listing
- // ---------------------------------------------------------------------------
- describe("listNotes", () => {
- it("returns array of note titles", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
- ["Note C", "x-coredata://ABC/ICNote/p3"].join(F),
- ].join(R),
- });
- const titles = manager.listNotes();
- expect(titles).toEqual(["Note A", "Note B", "Note C"]);
- });
- it("filters out empty entries", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
- "",
- ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
- "",
- "",
- ].join(R),
- });
- const titles = manager.listNotes();
- expect(titles).toEqual(["Note A", "Note B"]);
- });
- it("deduplicates duplicate note IDs while preserving separate notes with the same title", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Same Title", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const titles = manager.listNotes();
- expect(titles).toEqual(["Same Title", "Same Title"]);
- });
- it("throws on failure rather than returning empty (#19)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Account not found",
- });
- expect(() => manager.listNotes()).toThrow(/Account not found/);
- });
- it("filters by folder when specified", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Work Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Work Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- manager.listNotes("iCloud", "Work");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('notes of folder "Work"')
- );
- });
- it("filters by bulk-fetched modification dates when modifiedSince is provided", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Recent Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Recent Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const results = manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
- const script = mockExecuteAppleScript.mock.calls[0][0];
- // Locale-safe: variable setup + local comparison over bulk-fetched
- // dates (whose clauses evaluate per-note server-side and are slow)
- expect(script).toContain("set thresholdDate to current date");
- expect(script).toContain("set year of thresholdDate to 2025");
- expect(script).toContain("set month of thresholdDate to 6");
- expect(script).toContain("set day of thresholdDate to 15");
- expect(script).toContain("set noteDates to modification date of notes");
- expect(script).toContain("if (item i of noteDates) >= thresholdDate then");
- expect(results).toEqual(["Recent Note 1", "Recent Note 2"]);
- });
- it("slices the AppleScript fetch to the limit and returns a totalCount header", () => {
- // Sliced response: totalCount header record, then limit records.
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "10",
- ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
- ["Note 3", "x-coredata://ABC/ICNote/p3"].join(F),
- ].join(R),
- });
- const results = manager.listNotes(undefined, undefined, undefined, 3);
- // One sliced call satisfies the limit — no full-fetch fallback.
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain("set totalCount to count of notes");
- expect(script).toContain("set fetchCount to 3");
- expect(script).toContain("set noteNames to name of (notes 1 thru fetchCount)");
- expect(script).toContain("set noteIds to id of (notes 1 thru fetchCount)");
- expect(results).toEqual(["Note 1", "Note 2", "Note 3"]);
- });
- it("returns short slice without fallback when the library is smaller than the limit", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["2", ["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
- });
- const results = manager.listNotes(undefined, undefined, undefined, 5);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- expect(results).toEqual(["Note 1", "Note 2"]);
- });
- it("falls back to a full fetch when dedup leaves the slice short of the limit", () => {
- // Slice of 3 contains a duplicated id -> only 2 uniques, but 10 total
- // notes exist, so later uniques may have been hidden by the duplicate.
- mockExecuteAppleScript
- .mockReturnValueOnce({
- success: true,
- output: [
- "10",
- ["Note 1", "p1"].join(F),
- ["Note 1 dup", "p1"].join(F),
- ["Note 2", "p2"].join(F),
- ].join(R),
- })
- .mockReturnValueOnce({
- success: true,
- output: [
- ["Note 1", "p1"].join(F),
- ["Note 2", "p2"].join(F),
- ["Note 3", "p3"].join(F),
- ["Note 4", "p4"].join(F),
- ].join(R),
- });
- const results = manager.listNotes(undefined, undefined, undefined, 3);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
- // Fallback is the unsliced full fetch.
- const fallbackScript = mockExecuteAppleScript.mock.calls[1][0];
- expect(fallbackScript).not.toContain("thru fetchCount");
- expect(fallbackScript).toContain("set noteNames to name of notes");
- expect(results).toEqual(["Note 1", "Note 2", "Note 3"]);
- });
- it("falls back to a full fetch when the slice header is malformed", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({
- success: true,
- // No totalCount header — should not be trusted as a sliced response.
- output: [["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
- })
- .mockReturnValueOnce({
- success: true,
- output: [["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
- });
- const results = manager.listNotes(undefined, undefined, undefined, 5);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
- expect(results).toEqual(["Note 1", "Note 2"]);
- });
- it("returns empty from an empty sliced library without fallback", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: `0${R}` });
- const results = manager.listNotes(undefined, undefined, undefined, 3);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- expect(results).toEqual([]);
- });
- it("guards every bulk list against mid-listing library mutation", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- // Unfiltered full fetch: names/ids count guard.
- manager.listNotes();
- const fullScript = mockExecuteAppleScript.mock.calls[0][0];
- expect(fullScript).toContain(
- 'if (count of noteIds) is not (count of noteNames) then error "Notes changed during listing"'
- );
- // Date-filtered fetch adds the dates count guard.
- manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
- const dateScript = mockExecuteAppleScript.mock.calls[1][0];
- expect(dateScript).toContain(
- 'if (count of noteDates) is not (count of noteNames) then error "Notes changed during listing"'
- );
- // Sliced fetch guards and remaps a shrink between count and fetch —
- // but ONLY the out-of-range error numbers. Timeouts (-1712), lost
- // connection, and permission errors must be rethrown unchanged so
- // their honest messages and remedies survive.
- manager.listNotes(undefined, undefined, undefined, 3);
- const sliceScript = mockExecuteAppleScript.mock.calls[2][0];
- expect(sliceScript).toContain(
- 'if (count of noteIds) is not (count of noteNames) then error "Notes changed during listing"'
- );
- expect(sliceScript).toContain("on error errMsg number errNum");
- expect(sliceScript).toContain("if errNum is -1719 or errNum is -1728 then");
- expect(sliceScript).toContain('error "Notes changed during listing"');
- expect(sliceScript).toContain("error errMsg number errNum");
- });
- it("combines folder, modifiedSince, and limit", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Work Note", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Another Work Note", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- manager.listNotes("iCloud", "Work", "2025-01-01", 10);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain('notes of folder "Work"');
- expect(script).toContain('set noteDates to modification date of notes of folder "Work"');
- expect(script).toContain('set noteNames to name of notes of folder "Work"');
- });
- it("returns empty array when modifiedSince yields no results", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- const results = manager.listNotes(undefined, undefined, "2099-01-01");
- expect(results).toEqual([]);
- });
- it("ignores invalid modifiedSince date and falls back to limit-only", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- "2",
- ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const results = manager.listNotes(undefined, undefined, "not-a-date", 5);
- // Invalid date means no date filter, so the limit-only slice path runs.
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).not.toContain("thresholdDate");
- expect(script).toContain("set noteNames to name of (notes 1 thru fetchCount)");
- expect(results).toEqual(["Note 1", "Note 2"]);
- });
- });
- describe("large-library listing (#162)", () => {
- // `ASCII character` is a Standard Additions command: inside a Notes tell
- // block each evaluation is its own Apple Event (~8.5 ms measured), so a
- // per-record separator cost two round trips per note.
- it("builds every per-note record with local separators, never an Apple Event per record", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.listNotes();
- manager.listNotes(undefined, undefined, "2025-06-15T00:00:00");
- manager.listNotes(undefined, undefined, undefined, 3);
- expect(mockExecuteAppleScript.mock.calls.length).toBeGreaterThanOrEqual(3);
- for (const [script] of mockExecuteAppleScript.mock.calls) {
- expect(script).not.toContain("ASCII character");
- expect(script).toContain("(character id 31)");
- expect(script).toContain("(character id 30)");
- }
- });
- it("reads the whole collection, not a range, when the limit covers the library", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["2", ["Note 1", "p1"].join(F), ["Note 2", "p2"].join(F)].join(R),
- });
- const results = manager.listNotes("iCloud", undefined, undefined, 700);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toMatch(
- /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\)/
- );
- expect(results).toEqual(["Note 1", "Note 2"]);
- });
- });
- describe("separators in every generated script (#162)", () => {
- // Every script below runs inside a `tell application "Notes"` block, where
- // each `ASCII character` evaluation is dispatched to Notes.app as its own
- // Apple Event. Search, folder, account and stats scripts build one record
- // per item, so the separators must be `character id`, evaluated locally.
- const NOTE_ID = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICNote/p1";
- const FOLDER_ID = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICFolder/p2";
- const scriptsFor = (call: () => unknown): string[] => {
- mockExecuteAppleScript.mockReset();
- mockExecuteAppleScript.mockImplementation((script: string) => ({
- success: true,
- // listAccounts feeds the per-account stats and shared-notes scripts.
- output: script.includes("repeat with a in accounts") ? "iCloud" : "",
- }));
- try {
- call();
- } catch {
- // Empty output makes some parsers throw; only the scripts matter here.
- }
- return mockExecuteAppleScript.mock.calls.map(([script]) => String(script));
- };
- it.each<[string, () => unknown, string[]]>([
- ["searchNotes (title)", () => manager.searchNotes("the"), ["31", "30"]],
- ["searchNotes (content)", () => manager.searchNotes("the", true), ["31", "30"]],
- ["listFolders", () => manager.listFolders(), ["31", "30"]],
- ["listAccounts", () => manager.listAccounts(), ["31", "30"]],
- ["getNotesStats", () => manager.getNotesStats(), ["31", "30"]],
- ["getSelectedNotes", () => manager.getSelectedNotes(), ["31", "30"]],
- ["getDefaultLocation", () => manager.getDefaultLocation(), ["31"]],
- ["getNoteById", () => manager.getNoteById(NOTE_ID), ["31"]],
- ["getNoteDetails", () => manager.getNoteDetails("Groceries"), ["31"]],
- ["getFolderById", () => manager.getFolderById(FOLDER_ID), ["31"]],
- ["createFolder", () => manager.createFolder("Archive"), ["31"]],
- ["listAttachmentsById", () => manager.listAttachmentsById(NOTE_ID), ["31", "30"]],
- ["listAttachments", () => manager.listAttachments("Groceries"), ["31", "30"]],
- ["showAttachmentById", () => manager.showAttachmentById(NOTE_ID, "att-1"), ["31"]],
- [
- "saveAttachmentById",
- () => manager.saveAttachmentById(NOTE_ID, "att-1", join(tmpdir(), "x.png")),
- ["31"],
- ],
- ["batchMoveNotes", () => manager.batchMoveNotes([NOTE_ID], "Archive"), ["30"]],
- ["listNotes", () => manager.listNotes(), ["31", "30"]],
- ["listSharedNotes", () => manager.listSharedNotes(), ["31", "30"]],
- ])("%s never emits ASCII character", (_name, call, codes) => {
- const scripts = scriptsFor(call);
- const all = scripts.join("\n");
- expect(scripts.length).toBeGreaterThan(0);
- expect(all).not.toContain("ASCII character");
- for (const code of codes) {
- expect(all).toContain(`(character id ${code})`);
- }
- });
- });
- describe("listSharedNotes", () => {
- it("reads sharing state in one bulk read and stops there when nothing is shared", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" }) // listAccounts
- .mockReturnValueOnce({ success: true, output: "" });
- expect(manager.listSharedNotes()).toEqual([]);
- const script = mockExecuteAppleScript.mock.calls[1][0];
- expect(script).toContain("set noteShared to shared of notes");
- expect(script).toContain("if noteShared contains true then");
- expect(script).not.toContain("repeat with n in notes");
- expect(script).not.toContain("ASCII character");
- });
- it("parses shared notes built from bulk-read properties", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({
- success: true,
- output: [
- "Team plan",
- "x-coredata://ABC/ICNote/p7",
- "2025-1-2-3-4-5",
- "2025-6-7-8-9-10",
- "true",
- "false",
- ].join(F),
- });
- const notes = manager.listSharedNotes();
- expect(notes).toHaveLength(1);
- expect(notes[0]).toMatchObject({
- id: "x-coredata://ABC/ICNote/p7",
- title: "Team plan",
- account: "iCloud",
- shared: true,
- passwordProtected: false,
- });
- expect(notes[0].modified.getMonth()).toBe(5);
- const script = mockExecuteAppleScript.mock.calls[1][0];
- expect(script).toContain(
- 'if (count of noteIds) is not (count of noteShared) then error "Notes changed during listing"'
- );
- });
- it("reports a note Notes enumerates twice only once, in first-seen order (#183)", () => {
- const row = (title: string, id: string) =>
- [title, id, "2025-1-2-3-4-5", "2025-6-7-8-9-10", "true", "false"].join(F);
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({
- success: true,
- output: [
- row("Team plan", "x-coredata://ABC/ICNote/p7"),
- row("Budget", "x-coredata://ABC/ICNote/p8"),
- row("Team plan", "x-coredata://ABC/ICNote/p7"),
- ].join(R),
- });
- expect(manager.listSharedNotes().map((note) => note.id)).toEqual([
- "x-coredata://ABC/ICNote/p7",
- "x-coredata://ABC/ICNote/p8",
- ]);
- });
- });
- describe("deleteNoteByIdIfUnchanged guard notes (copy-then-retire)", () => {
- const id = "x-coredata://ABC/ICNote/p1";
- const copy = "x-coredata://ABC/ICNote/p2";
- const other = "x-coredata://ABC/ICNote/p3";
- const guards = [{ id: copy, expectedBody: '<div>Copy with "quotes"</div>' }, { id: other }];
- it("checks every guard live, after the source trash check and before the delete", () => {
- mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
- status: "deleted",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- const sourceTrash = script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"');
- const guardStart = script.indexOf(`exists note id "${copy}"`);
- expect(guardStart).toBeGreaterThan(sourceTrash);
- for (const needle of [
- 'return "SAFETY_GUARD_INACTIVE:0:missing"',
- "if password protected of __guardRef0",
- 'return "SAFETY_GUARD_INACTIVE:0:locked"',
- 'return "SAFETY_GUARD_INACTIVE:0:folder unknown"',
- "if (class of __guardFolder0) is folder then set __guardInTrash to false",
- `{"${TRASH_FOLDER}"} contains (id of __guardFolder0)`,
- '(name of __guardFolder0) is "Recently Deleted"',
- 'return "SAFETY_GUARD_INACTIVE:0:in Recently Deleted"',
- 'return "SAFETY_GUARD_CONFLICT:0"',
- // The target cannot guard its own delete, however its id was spelled (#214).
- 'if (id of __guardRef0) is (id of noteRef) then return "SAFETY_GUARD_INACTIVE:0:the note being deleted"',
- `exists note id "${other}"`,
- 'return "SAFETY_GUARD_INACTIVE:1:in Recently Deleted"',
- ]) {
- const at = script.indexOf(needle);
- expect(at, needle).toBeGreaterThan(sourceTrash);
- expect(at, needle).toBeLessThan(script.indexOf("delete noteRef"));
- }
- // Only the fingerprinted guard compares its body.
- expect(script).not.toContain("SAFETY_GUARD_CONFLICT:1");
- expect(script).toContain('__guardBody is not "<div>Copy with \\"quotes\\"</div>"');
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("maps guard outcomes to their index", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "SAFETY_GUARD_CONFLICT:0",
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
- status: "guard-conflict",
- index: 0,
- });
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "SAFETY_GUARD_INACTIVE:1:in Recently Deleted",
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, guards)).toEqual({
- status: "guard-inactive",
- index: 1,
- reason: "in Recently Deleted",
- });
- });
- it("treats a guard outcome for an unknown index as failed", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "SAFETY_GUARD_INACTIVE:5:missing",
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
- status: "failed",
- });
- });
- it("rejects an invalid guard id before running anything", () => {
- expect(() =>
- manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>", undefined, [
- { id: 'x" & do shell script "id' },
- ])
- ).toThrow();
- expect(mockExecuteAppleScript).not.toHaveBeenCalled();
- });
- });
- // A note's body carries its inline images as base64, so one large image makes
- // a body far longer than a script literal should be (#237).
- describe("deleteNoteByIdIfUnchanged with a body too long for a literal (#237)", () => {
- const id = "x-coredata://ABC/ICNote/p1";
- const copy = "x-coredata://ABC/ICNote/p2";
- const largeBody = (marker: string) =>
- `<div>${marker} "quoted" \\ slash é 😀</div><img src="data:image/png;base64,${"A".repeat(5 * 1024 * 1024)}">`;
- const filePaths = (script: string) =>
- [...script.matchAll(/POSIX file "([^"]+)"/g)].map((match) => match[1]);
- it("compares the whole body against a private temporary file, then removes it", () => {
- const body = largeBody("Photo");
- let seen: { script: string; contents: string[]; modes: number[] } | undefined;
- mockExecuteAppleScript.mockImplementation((script: string) => {
- const paths = filePaths(script);
- seen = {
- script,
- contents: paths.map((path) => readFileSync(path, "utf8")),
- modes: paths.map((path) => statSync(path).mode & 0o777),
- };
- return { success: true, output: "SAFETY_DELETED" };
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, body)).toEqual({ status: "deleted" });
- expect(seen!.contents).toEqual([body]);
- expect(seen!.modes).toEqual([0o600]);
- // The script stays small: the body is read from the file, not embedded.
- expect(seen!.script.length).toBeLessThan(10_000);
- expect(seen!.script).toContain(
- 'if currentBody is not __expectedBody and currentBody is not __expectedBody & linefeed then return "SAFETY_CONFLICT"'
- );
- expect(seen!.script.indexOf("set __expectedBody to read")).toBeLessThan(
- seen!.script.indexOf("set currentBody to body of noteRef")
- );
- expect(existsSync(filePaths(seen!.script)[0])).toBe(false);
- });
- it("reads a large guard body from its own file", () => {
- const body = largeBody("Original");
- const guardBody = largeBody("Copy");
- let contents: string[] = [];
- let script = "";
- mockExecuteAppleScript.mockImplementation((text: string) => {
- script = text;
- contents = filePaths(text).map((path) => readFileSync(path, "utf8"));
- return { success: true, output: "SAFETY_GUARD_CONFLICT:0" };
- });
- expect(
- manager.deleteNoteByIdIfUnchanged(id, body, undefined, [
- { id: copy, expectedBody: guardBody },
- ])
- ).toEqual({ status: "guard-conflict", index: 0 });
- expect(contents).toEqual([guardBody, body]);
- expect(script).toContain(
- 'if __guardBody is not __expectedGuardBody0 and __guardBody is not __expectedGuardBody0 & linefeed then return "SAFETY_GUARD_CONFLICT:0"'
- );
- for (const path of filePaths(script)) expect(existsSync(path)).toBe(false);
- });
- it("removes the temporary file when the script run throws", () => {
- let paths: string[] = [];
- mockExecuteAppleScript.mockImplementation((script: string) => {
- paths = filePaths(script);
- throw new Error("osascript failed");
- });
- expect(() => manager.deleteNoteByIdIfUnchanged(id, largeBody("Photo"))).toThrow(
- "osascript failed"
- );
- expect(paths).toHaveLength(1);
- expect(existsSync(paths[0])).toBe(false);
- });
- it("generates a file-backed delete script that AppleScript compiles", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
- manager.deleteNoteByIdIfUnchanged(id, largeBody("Photo"), undefined, [
- { id: copy, expectedBody: largeBody("Copy") },
- ]);
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- const dir = mkdtempSync(join(tmpdir(), "delete-script-"));
- try {
- writeFileSync(join(dir, "delete.applescript"), script);
- expect(() =>
- execFileSync(
- "/usr/bin/osacompile",
- ["-o", join(dir, "delete.scpt"), join(dir, "delete.applescript")],
- { stdio: "pipe" }
- )
- ).not.toThrow();
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
- });
- describe("ExpectedBodies", () => {
- it("embeds a short body as an escaped literal and writes no file", () => {
- const bodies = new ExpectedBodies();
- expect(bodies.bind('<div>Say "hi" \\ there</div>', "__x")).toEqual({
- setup: "",
- operand: '"<div>Say \\"hi\\" \\\\ there</div>"',
- });
- bodies.cleanup();
- bodies.cleanup();
- });
- it("reads a long body back through real osascript byte for byte", () => {
- const body = `<div>Line one "q" \\ é 😀\ttab</div>\n<div>${"B".repeat(5 * 1024 * 1024)}</div>`;
- const bodies = new ExpectedBodies();
- try {
- const { setup, operand } = bodies.bind(body, "__roundTrip");
- expect(operand).toBe("__roundTrip");
- // Inside a Notes tell block, as in the delete script, but without
- // sending Notes anything: the read runs in osascript itself.
- const output = execFileSync("osascript", ["-"], {
- input: `${setup}\nreturn __roundTrip`,
- encoding: "utf8",
- maxBuffer: 64 * 1024 * 1024,
- });
- expect(output).toBe(`${body}\n`);
- } finally {
- bodies.cleanup();
- }
- });
- });
- describe("Recently Deleted (#198, #207)", () => {
- const id = "x-coredata://ABC/ICNote/p1";
- it("delete refuses a note whose folder is Recently Deleted, before deleting", () => {
- mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER, "not-a-folder-id"]);
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "SAFETY_IN_RECENTLY_DELETED",
- });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
- status: "in-recently-deleted",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- // Checked live against Notes.app's container, by database id and by name.
- expect(script).toContain(`{"${TRASH_FOLDER}"} contains (id of originalFolder)`);
- expect(script).not.toContain("not-a-folder-id");
- expect(script).toContain('(name of originalFolder) is "Recently Deleted"');
- expect(script.indexOf("SAFETY_IN_RECENTLY_DELETED")).toBeLessThan(
- script.indexOf("delete noteRef")
- );
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("delete refuses a note whose container is not a folder, failing closed (#214)", () => {
- mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "SAFETY_IN_RECENTLY_DELETED",
- });
- // Shared by delete-note and batch-delete-notes.
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
- status: "in-recently-deleted",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- // In-trash is the default; only a readable folder class clears it, so a
- // non-folder container or an unreadable class both refuse.
- const defaultTrue = script.indexOf("set __inTrash to true");
- const classCheck = script.indexOf(
- "if (class of originalFolder) is folder then set __inTrash to false"
- );
- expect(defaultTrue).toBeGreaterThan(-1);
- expect(classCheck).toBeGreaterThan(defaultTrue);
- // The id and name checks can only set it true afterwards, never clear it.
- expect(script.indexOf("contains (id of originalFolder)")).toBeGreaterThan(classCheck);
- expect(script.slice(script.indexOf("\n", classCheck))).not.toMatch(/set __inTrash to false/);
- expect(classCheck).toBeLessThan(script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"'));
- expect(script.indexOf('return "SAFETY_IN_RECENTLY_DELETED"')).toBeLessThan(
- script.indexOf("delete noteRef")
- );
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("delete refuses a note whose container cannot be read, failing closed", () => {
- mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "SAFETY_CONTAINER_UNKNOWN",
- });
- // Shared by delete-note and batch-delete-notes.
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>")).toEqual({
- status: "container-unknown",
- });
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- const refusal = script.indexOf(
- 'if originalFolder is missing value then return "SAFETY_CONTAINER_UNKNOWN"'
- );
- expect(refusal).toBeGreaterThan(script.indexOf("set originalFolder to container of noteRef"));
- expect(refusal).toBeLessThan(script.indexOf("set __inTrash to true"));
- expect(refusal).toBeLessThan(script.indexOf("delete noteRef"));
- // No path reaches the delete with an unread container any more.
- expect(script).not.toContain("originalFolder is not missing value");
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("delete still checks the folder name without database access", () => {
- mockReadTrashFolderIds.mockReturnValue([]);
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "SAFETY_DELETED" });
- expect(manager.deleteNoteByIdIfUnchanged(id, "<div>Body</div>").status).toBe("deleted");
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(script).toContain("{} contains (id of originalFolder)");
- expect(script).toContain('(name of originalFolder) is "Recently Deleted"');
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("list excludes notes Notes.app reports in Recently Deleted", () => {
- mockReadTrashFolderIds.mockReturnValue([TRASH_FOLDER]);
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output:
- [["Live", id].join(F), ["Gone", "x-coredata://ABC/ICNote/p2"].join(F)].join(R) +
- G +
- ["x-coredata://ABC/ICNote/p2", "x-coredata://ABC/ICNote/p3"].join(R),
- });
- expect(manager.listNoteRefsDetailed()).toEqual({
- refs: [{ title: "Live", id }],
- excludedRecentlyDeleted: 1,
- });
- expect(manager.listNoteRefs()).toEqual([{ title: "Live", id }]);
- expect(manager.listNotes()).toEqual(["Live"]);
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(script).toContain(`repeat with __trashFolderId in {"${TRASH_FOLDER}"}`);
- expect(script).toContain('every folder whose name is "Recently Deleted"');
- expect(script).toContain("(character id 29) & (__trashNoteIds as text)");
- expect(() => compilesAsAppleScript(script)).not.toThrow();
- });
- it("list includes and flags Recently Deleted notes on request", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output:
- [["Live", id].join(F), ["Gone", "x-coredata://ABC/ICNote/p2"].join(F)].join(R) +
- G +
- "x-coredata://ABC/ICNote/p2",
- });
- expect(
- manager.listNoteRefsDetailed(undefined, undefined, undefined, undefined, true)
- ).toEqual({
- refs: [
- { title: "Live", id },
- { title: "Gone", id: "x-coredata://ABC/ICNote/p2", inRecentlyDeleted: true },
- ],
- excludedRecentlyDeleted: 0,
- });
- });
- it("an empty trash list excludes nothing", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["Live", id].join(F) + G,
- });
- expect(manager.listNoteRefsDetailed()).toEqual({
- refs: [{ title: "Live", id }],
- excludedRecentlyDeleted: 0,
- });
- });
- it("a bounded slice thinned by exclusion falls back to the full listing", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({
- success: true,
- output:
- "3" +
- R +
- [["Gone", "x-coredata://ABC/ICNote/p2"].join(F), ["Live", id].join(F)].join(R) +
- G +
- "x-coredata://ABC/ICNote/p2",
- })
- .mockReturnValueOnce({
- success: true,
- output:
- [
- ["Gone", "x-coredata://ABC/ICNote/p2"].join(F),
- ["Live", id].join(F),
- ["Also", "x-coredata://ABC/ICNote/p3"].join(F),
- ].join(R) +
- G +
- "x-coredata://ABC/ICNote/p2",
- });
- expect(manager.listNoteRefsDetailed(undefined, undefined, undefined, 2)).toEqual({
- refs: [
- { title: "Live", id },
- { title: "Also", id: "x-coredata://ABC/ICNote/p3" },
- ],
- excludedRecentlyDeleted: 1,
- });
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
- const sliceScript = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(sliceScript).toContain("(character id 29) & (__trashNoteIds as text)");
- expect(() => compilesAsAppleScript(sliceScript)).not.toThrow();
- });
- it("a bounded slice that stays full after exclusion is returned as is", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "5" + R + ["Live", id].join(F) + G,
- });
- expect(manager.listNoteRefsDetailed(undefined, undefined, undefined, 1)).toEqual({
- refs: [{ title: "Live", id }],
- excludedRecentlyDeleted: 0,
- });
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- });
- it("smart folder listings carry no trash check", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "0" + R });
- manager.listSmartFolderNoteRefs("x-coredata://ABC/ICFolder/p4", 5);
- const script = String(mockExecuteAppleScript.mock.calls[0]?.[0]);
- expect(script).not.toContain("__trashNoteIds");
- });
- });
- describe("listNoteRefs", () => {
- it("returns title/id pairs, not just titles", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Note A", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Note B", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const refs = manager.listNoteRefs();
- expect(refs).toEqual([
- { title: "Note A", id: "x-coredata://ABC/ICNote/p1" },
- { title: "Note B", id: "x-coredata://ABC/ICNote/p2" },
- ]);
- });
- it("keeps two distinct notes with the same title distinguishable by id", () => {
- // This is the exact shape of bug #115 (see exportNotesAsJson's fix):
- // listNotes() alone collapses these to two identical-looking "Same
- // Title" strings, which a caller can't use to fetch the second note
- // without AppleScript's ambiguous by-name resolution returning the
- // first one twice. listNoteRefs() must expose the distinguishing id.
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["Same Title", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Same Title", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const refs = manager.listNoteRefs();
- expect(refs).toEqual([
- { title: "Same Title", id: "x-coredata://ABC/ICNote/p1" },
- { title: "Same Title", id: "x-coredata://ABC/ICNote/p2" },
- ]);
- expect(refs[0].id).not.toEqual(refs[1].id);
- });
- it("supports the same folder/modifiedSince/limit filtering as listNotes", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [["Note 1", "x-coredata://ABC/ICNote/p1"].join(F)].join(R),
- });
- manager.listNoteRefs("iCloud", "Work", "2025-01-01", 10);
- const script = mockExecuteAppleScript.mock.calls[0][0];
- expect(script).toContain("Work");
- expect(script).toContain("thresholdDate");
- });
- it("throws on failure rather than returning empty", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Account not found",
- });
- expect(() => manager.listNoteRefs()).toThrow(/Account not found/);
- });
- });
- // ---------------------------------------------------------------------------
- // Folder Operations
- // ---------------------------------------------------------------------------
- describe("listFolders", () => {
- it("returns array of Folder objects with paths", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["id1", "Notes", "", "false"].join(F),
- ["id2", "Archive", "", "false"].join(F),
- ["id3", "Work", "", "true"].join(F),
- ].join(R),
- });
- const folders = manager.listFolders();
- expect(folders).toHaveLength(3);
- expect(folders[0].name).toBe("Notes");
- expect(folders[1].name).toBe("Archive");
- expect(folders[2].name).toBe("Work");
- expect(folders[0].id).toBe("id1");
- expect(folders[2].shared).toBe(true);
- });
- it("marks smart folders, which AppleScript lists like ordinary ones (#247)", () => {
- const smartId = "x-coredata://ABC/ICFolder/p9";
- const plainId = "x-coredata://ABC/ICFolder/p2";
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- [plainId, "Notes", "", "false"].join(F),
- [smartId, "Recents", "", "false"].join(F),
- ].join(R),
- });
- const spy = vi.spyOn(manager, "smartFolderIds").mockReturnValue([smartId]);
- const folders = manager.listFolders();
- expect(folders.find((f) => f.id === smartId)?.smartFolder).toBe(true);
- expect(folders.find((f) => f.id === plainId)).not.toHaveProperty("smartFolder");
- spy.mockRestore();
- });
- it("includes parent folder in path", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["id1", "Dev", "", "false"].join(F),
- ["id2", "Accessibility", "id1", "false"].join(F),
- ["id3", "Work", "", "false"].join(F),
- ["id4", "Clients", "id3", "false"].join(F),
- ].join(R),
- });
- const folders = manager.listFolders();
- expect(folders).toHaveLength(4);
- expect(folders[0].name).toBe("Dev");
- expect(folders[1].name).toBe("Dev/Accessibility");
- expect(folders[2].name).toBe("Work");
- expect(folders[3].name).toBe("Work/Clients");
- });
- it("disambiguates duplicate folder names using IDs", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["id1", "Finance", "", "false"].join(F),
- ["id2", "Archive", "id1", "false"].join(F),
- ["id3", "Travel", "", "false"].join(F),
- ["id4", "Trips", "id3", "false"].join(F),
- ["id5", "Archive", "id4", "false"].join(F),
- ].join(R),
- });
- const folders = manager.listFolders();
- expect(folders).toHaveLength(5);
- expect(folders[1].name).toBe("Finance/Archive");
- expect(folders[4].name).toBe("Travel/Trips/Archive");
- });
- it("escapes slashes in folder names", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["id1", "Travel", "", "false"].join(F),
- ["id2", "Spain/Portugal 2023", "id1", "false"].join(F),
- ].join(R),
- });
- const folders = manager.listFolders();
- expect(folders).toHaveLength(2);
- expect(folders[0].name).toBe("Travel");
- expect(folders[1].name).toBe("Travel/Spain\\/Portugal 2023");
- });
- it("parses legacy tab/newline output (backward compat)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "id1\tNotes\nid2\tArchive\tid1",
- });
- const folders = manager.listFolders();
- expect(folders).toHaveLength(2);
- expect(folders[0].name).toBe("Notes");
- expect(folders[1].name).toBe("Notes/Archive");
- expect(folders[1].shared).toBe(false);
- });
- it("includes account in Folder objects", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["id1", "Notes", "", "false"].join(F),
- });
- const folders = manager.listFolders("Gmail");
- expect(folders[0].account).toBe("Gmail");
- });
- });
- describe("createFolder", () => {
- it("returns Folder object on success", () => {
- mockExecuteAppleScript
- // Check existence — folder doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create the folder
- .mockReturnValueOnce({
- success: true,
- output: "folder id x-coredata://ABC123/ICFolder/p456",
- })
- // Get ID of created folder
- .mockReturnValueOnce({
- success: true,
- output: "folder id x-coredata://ABC123/ICFolder/p456",
- });
- const result = manager.createFolder("New Project");
- expect(result).not.toBeNull();
- expect(result?.name).toBe("New Project");
- expect(result?.id).toBe("x-coredata://ABC123/ICFolder/p456");
- });
- it("returns existing folder without creating duplicate", () => {
- mockExecuteAppleScript
- // Check existence — folder already exists
- .mockReturnValueOnce({
- success: true,
- output: "x-coredata://ABC123/ICFolder/p789",
- })
- // Get ID of existing folder
- .mockReturnValueOnce({
- success: true,
- output: "folder id x-coredata://ABC123/ICFolder/p789",
- });
- const result = manager.createFolder("Existing Folder");
- expect(result).not.toBeNull();
- expect(result?.name).toBe("Existing Folder");
- expect(result?.id).toBe("x-coredata://ABC123/ICFolder/p789");
- // Should only have 2 calls (check + get ID), no create call
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(2);
- });
- it("returns null on genuine failure", () => {
- mockExecuteAppleScript
- // Check existence — doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create fails
- .mockReturnValueOnce({
- success: false,
- output: "",
- error: "Permission denied",
- });
- const result = manager.createFolder("Restricted Folder");
- expect(result).toBeNull();
- });
- it("creates nested folder path", () => {
- mockExecuteAppleScript
- // Check "Retro Tech" — doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create "Retro Tech"
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p1" })
- // Check "Retro Tech/PC" — doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create "PC" inside "Retro Tech"
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" })
- // Check "Retro Tech/PC/CPUs" — doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create "CPUs" inside "Retro Tech/PC"
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p3" })
- // Get ID of final folder
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p3" });
- const result = manager.createFolder("Retro Tech/PC/CPUs");
- expect(result).not.toBeNull();
- expect(result?.name).toBe("Retro Tech/PC/CPUs");
- expect(result?.id).toBe("x-coredata://A/ICFolder/p3");
- // Verify the create commands (calls at index 1, 3, 5)
- const calls = mockExecuteAppleScript.mock.calls;
- expect(calls[1][0]).toContain('make new folder with properties {name:"Retro Tech"}');
- expect(calls[3][0]).toContain('whose name is "Retro Tech"');
- expect(calls[3][0]).toContain('make new folder at __parent with properties {name:"PC"}');
- expect(calls[5][0]).toContain('whose name is "Retro Tech"');
- expect(calls[5][0]).toContain('whose name is "PC"');
- expect(calls[5][0]).toContain('make new folder at __parent with properties {name:"CPUs"}');
- });
- // #213: a folder deleted earlier in the Notes session still answers a
- // name reference, so existence must be decided by id.
- it("checks existence by id, not by a name reference", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" })
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p9" })
- .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p9" });
- const result = manager.createFolder("Gone");
- const check = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(check).toContain('whose name is "Gone"');
- expect(check).toContain("if exists folder id __folder_cid then");
- expect(check).toContain("return id of __folder");
- expect(check).not.toMatch(/return id of folder "/);
- // rootOnly: a same-named nested folder is not a fallback for "Gone"
- expect(check).not.toContain("set __folder to __folder_any");
- expect(mockExecuteAppleScript.mock.calls[1][0]).toContain(
- 'make new folder with properties {name:"Gone"}'
- );
- expect(result?.id).toBe("x-coredata://A/ICFolder/p9");
- });
- it("reports failure when the created folder cannot be confirmed by id", () => {
- mockExecuteAppleScript
- // Check — not found
- .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" })
- // Create reports success but did nothing
- .mockReturnValueOnce({ success: true, output: "" })
- // Post-check — still no live folder
- .mockReturnValueOnce({ success: false, output: "", error: "Folder not found: Gone" });
- const result = manager.createFolder("Gone");
- expect(result).toBeNull();
- expect(mockExecuteAppleScript.mock.calls[2][0]).toContain("exists folder id __folder_cid");
- });
- it("reports failure when the post-check returns no folder id", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p1" })
- .mockReturnValueOnce({ success: true, output: "" });
- expect(manager.createFolder("Existing")).toBeNull();
- });
- it("skips existing intermediate folders in nested path", () => {
- mockExecuteAppleScript
- // Check "Retro Tech" — exists
- .mockReturnValueOnce({ success: true, output: "x-coredata://A/ICFolder/p1" })
- // Check "Retro Tech/PC" — doesn't exist
- .mockReturnValueOnce({ success: false, output: "", error: "Can't get folder" })
- // Create "PC" inside "Retro Tech"
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" })
- // Get ID of final folder
- .mockReturnValueOnce({ success: true, output: "folder id x-coredata://A/ICFolder/p2" });
- const result = manager.createFolder("Retro Tech/PC");
- expect(result).not.toBeNull();
- expect(result?.name).toBe("Retro Tech/PC");
- // No create call for "Retro Tech" — only for "PC"
- const createCalls = mockExecuteAppleScript.mock.calls.filter((c) =>
- c[0].includes("make new folder")
- );
- expect(createCalls).toHaveLength(1);
- expect(createCalls[0][0]).toContain('name:"PC"');
- });
- });
- describe("deleteFolder", () => {
- it("returns true on successful deletion", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- const result = manager.deleteFolder("Empty Folder");
- expect(result).toBe(true);
- });
- it("returns false when deletion fails", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Folder contains notes",
- });
- const result = manager.deleteFolder("Non-Empty Folder");
- expect(result).toBe(false);
- });
- it("deletes the live folder resolved by id, not a name reference (#213)", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.deleteFolder("Work/Old");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain('whose name is "Work"');
- expect(script).toContain('whose name is "Old"');
- expect(script).toContain("delete __folder");
- expect(script).not.toContain('delete folder "Old"');
- });
- it("returns false when the folder was already deleted this session (#213)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Folder not found: Doomed",
- });
- expect(manager.deleteFolder("Doomed")).toBe(false);
- });
- });
- // ---------------------------------------------------------------------------
- // Note Moving
- // ---------------------------------------------------------------------------
- describe("moveNoteById", () => {
- it("returns true when the native move succeeds", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "SAFETY_MOVED" });
- const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Archive");
- expect(result).toBe(true);
- // Single native `move` — no getNoteContentById/create/delete fan-out.
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- const moveScript = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(moveScript).toContain("move noteRef to destFolder");
- expect(moveScript).toContain("id of actualFolder");
- expect(moveScript).toContain('return "SAFETY_MOVED"');
- expect(moveScript).not.toContain("make new note");
- });
- it("resolves the destination to a live folder id (#213)", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "SAFETY_MOVED" });
- manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Work/Archive");
- const moveScript = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(moveScript).toContain('whose name is "Archive"');
- expect(moveScript).toContain("if exists folder id destFolder_cid then");
- expect(moveScript).not.toContain('folder "Archive" of folder "Work"');
- expect(moveScript.indexOf("destFolder_cid")).toBeLessThan(
- moveScript.indexOf("move noteRef to destFolder")
- );
- });
- it("returns false when Notes cannot verify the destination folder", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "SAFETY_WRONG_FOLDER",
- });
- const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Archive");
- expect(result).toBe(false);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- });
- it("returns false when the move fails", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Folder not found",
- });
- const result = manager.moveNoteById("x-coredata://ABC/ICNote/p123", "Nonexistent");
- expect(result).toBe(false);
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- });
- });
- // ---------------------------------------------------------------------------
- // Account Operations
- // ---------------------------------------------------------------------------
- describe("listAccounts", () => {
- it("returns array of Account objects", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- ["acc1", "iCloud", "true", "folder1", "Notes"].join(F),
- ["acc2", "Gmail", "false", "folder2", "Inbox"].join(F),
- ["acc3", "Exchange", "false", "", ""].join(F),
- ].join(R),
- });
- const accounts = manager.listAccounts();
- expect(accounts).toHaveLength(3);
- expect(accounts[0].name).toBe("iCloud");
- expect(accounts[1].name).toBe("Gmail");
- expect(accounts[2].name).toBe("Exchange");
- expect(accounts[0].id).toBe("acc1");
- expect(accounts[0].upgraded).toBe(true);
- expect(accounts[0].defaultFolder).toBe("Notes");
- });
- it("parses legacy plain-name output (backward compat)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["iCloud", "Gmail"].join(R),
- });
- const accounts = manager.listAccounts();
- expect(accounts).toHaveLength(2);
- expect(accounts[0]).toEqual({ name: "iCloud" });
- expect(accounts[1]).toEqual({ name: "Gmail" });
- });
- it("handles account records with empty fields", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["", "", "", "", ""].join(F),
- });
- const accounts = manager.listAccounts();
- expect(accounts).toHaveLength(1);
- expect(accounts[0].name).toBe("");
- expect(accounts[0].upgraded).toBe(false);
- expect(accounts[0].defaultFolderId).toBeUndefined();
- });
- it("throws on failure rather than returning empty (#19)", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "Notes.app not available",
- });
- expect(() => manager.listAccounts()).toThrow(/Notes.app not available/);
- });
- });
- describe("getDefaultLocation", () => {
- it("returns default account and folder metadata", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["acc1", "iCloud", "true", "folder1", "Notes", "false"].join(F),
- });
- const location = manager.getDefaultLocation();
- expect(location.account).toMatchObject({
- id: "acc1",
- name: "iCloud",
- upgraded: true,
- defaultFolderId: "folder1",
- defaultFolder: "Notes",
- });
- expect(location.folder).toMatchObject({
- id: "folder1",
- name: "Notes",
- account: "iCloud",
- shared: false,
- });
- });
- it("throws when default location output cannot be parsed", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "bad-output",
- });
- expect(() => manager.getDefaultLocation()).toThrow(/parse default Notes location/);
- });
- it("throws when AppleScript fails", () => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "boom" });
- expect(() => manager.getDefaultLocation()).toThrow(/Failed to get default Notes location/);
- });
- it("handles empty fields in default location output", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["", "", "", "", "", ""].join(F),
- });
- const location = manager.getDefaultLocation();
- expect(location.account.name).toBe("");
- expect(location.account.upgraded).toBe(false);
- expect(location.folder.id).toBe("");
- expect(location.folder.shared).toBe(false);
- });
- });
- describe("getSelectedNotes", () => {
- it("returns selected note metadata", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: [
- [
- "x-coredata://ABC/ICNote/p1",
- "Selected Note",
- "2026-6-22-14-30-0",
- "2026-6-22-14-35-0",
- "false",
- "false",
- "Notes",
- "iCloud",
- ].join(F),
- ].join(R),
- });
- const notes = manager.getSelectedNotes();
- expect(notes).toHaveLength(1);
- expect(notes[0]).toMatchObject({
- id: "x-coredata://ABC/ICNote/p1",
- title: "Selected Note",
- shared: false,
- passwordProtected: false,
- folder: "Notes",
- account: "iCloud",
- });
- expect(notes[0].created.getFullYear()).toBe(2026);
- });
- it("returns an empty array when no note is selected", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- expect(manager.getSelectedNotes()).toEqual([]);
- });
- it("throws when AppleScript fails", () => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "boom" });
- expect(() => manager.getSelectedNotes()).toThrow(/Failed to get selected notes/);
- });
- it("handles selected notes with empty optional fields", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: ["", "", "", "", "", "", "", ""].join(F),
- });
- const notes = manager.getSelectedNotes();
- expect(notes).toHaveLength(1);
- expect(notes[0].id).toBe("");
- expect(notes[0].shared).toBe(false);
- expect(notes[0].passwordProtected).toBe(false);
- expect(notes[0].folder).toBeUndefined();
- expect(notes[0].account).toBeUndefined();
- });
- });
- describe("showNoteById", () => {
- it("shows a note by id", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- expect(manager.showNoteById("x-coredata://ABC/ICNote/p1")).toBe(true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('show note id "x-coredata://ABC/ICNote/p1"'),
- NO_RETRY_OPTIONS
- );
- });
- it("can request a separate window", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: "",
- });
- manager.showNoteById("x-coredata://ABC/ICNote/p1", true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("separately true"),
- NO_RETRY_OPTIONS
- );
- });
- it("returns false when Notes.app rejects the show command", () => {
- mockExecuteAppleScript.mockReturnValue({ success: false, output: "", error: "no such note" });
- expect(manager.showNoteById("x-coredata://ABC/ICNote/p1")).toBe(false);
- });
- });
- describe("showFolderById", () => {
- it("shows a folder by id", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- expect(manager.showFolderById("x-coredata://ABC/ICFolder/p1")).toBe(true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('show folder id "x-coredata://ABC/ICFolder/p1"'),
- NO_RETRY_OPTIONS
- );
- });
- it("can request a separate window", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.showFolderById("x-coredata://ABC/ICFolder/p1", true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("separately true"),
- NO_RETRY_OPTIONS
- );
- });
- it("returns false when Notes.app rejects the show command", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "no such folder",
- });
- expect(manager.showFolderById("x-coredata://ABC/ICFolder/p1")).toBe(false);
- });
- });
- describe("showAccountById", () => {
- it("shows an account by id", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- expect(manager.showAccountById("x-coredata://ABC/ICAccount/p1")).toBe(true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('show account id "x-coredata://ABC/ICAccount/p1"'),
- NO_RETRY_OPTIONS
- );
- });
- it("can request a separate window", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.showAccountById("x-coredata://ABC/ICAccount/p1", true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("separately true"),
- NO_RETRY_OPTIONS
- );
- });
- it("returns false when Notes.app rejects the show command", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "no such account",
- });
- expect(manager.showAccountById("x-coredata://ABC/ICAccount/p1")).toBe(false);
- });
- });
- describe("showAttachmentById", () => {
- it("resolves the attachment within its note and shows it", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "OK" });
- expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123")).toBe(true);
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).toContain('set theNote to note id "x-coredata://ABC/ICNote/p1"');
- // Addressed directly rather than scanned for: one Apple Event instead of up
- // to N, and still scoped to theNote (a foreign id resolves to missing value).
- expect(script).toContain('set theAttachment to attachment id "att-123" of theNote');
- expect(script).not.toContain("repeat with a in attachments of theNote");
- expect(script).toContain("show theAttachment");
- });
- it("can request a separate window", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "OK" });
- manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123", true);
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining("separately true"),
- NO_RETRY_OPTIONS
- );
- });
- it("returns false when the attachment is not found on the note", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: true,
- output: `ERR${F}attachment not found`,
- });
- expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "missing")).toBe(false);
- });
- it("returns false when Notes.app rejects the show command", () => {
- mockExecuteAppleScript.mockReturnValue({
- success: false,
- output: "",
- error: "no such note",
- });
- expect(manager.showAttachmentById("x-coredata://ABC/ICNote/p1", "att-123")).toBe(false);
- });
- });
- // ---------------------------------------------------------------------------
- // Health Check
- // ---------------------------------------------------------------------------
- describe("healthCheck", () => {
- it("returns healthy when all checks pass", () => {
- mockExecuteAppleScript
- // Check 1: Notes.app accessible
- .mockReturnValueOnce({ success: true, output: "ok" })
- // Check 2: Permissions (get account name)
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // Check 3: listAccounts
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // Check 4: listNotes
- .mockReturnValueOnce({
- success: true,
- output: [
- ["Note 1", "x-coredata://ABC/ICNote/p1"].join(F),
- ["Note 2", "x-coredata://ABC/ICNote/p2"].join(F),
- ].join(R),
- });
- const result = manager.healthCheck();
- expect(result.healthy).toBe(true);
- expect(result.checks).toHaveLength(4);
- expect(result.checks.every((c) => c.passed)).toBe(true);
- });
- it("returns unhealthy when Notes.app is not accessible", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Application not found",
- });
- const result = manager.healthCheck();
- expect(result.healthy).toBe(false);
- expect(result.checks).toHaveLength(1);
- expect(result.checks[0].name).toBe("notes_app");
- expect(result.checks[0].passed).toBe(false);
- });
- it("returns unhealthy with permission hint when not authorized", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "not authorized to send Apple events",
- });
- const result = manager.healthCheck();
- expect(result.healthy).toBe(false);
- expect(result.checks[0].message).toContain("Automation permissions");
- });
- it('classifies an en-GB "Not authorised" refusal as a permission failure', () => {
- // The regression this guards: on an en_GB / en_AU / en_IE Mac the
- // refusal reads "Not authorised", the American-only substring check
- // missed it, and a genuine TCC denial reported `passed: true` and then
- // misdirected the user to check their accounts.
- mockExecuteAppleScript
- // Check 1: Notes.app accessible
- .mockReturnValueOnce({ success: true, output: "ok" })
- // Check 2: permission probe refused, British spelling
- .mockReturnValueOnce({
- success: false,
- output: "",
- error: "27:44: execution error: Not authorised to send Apple events to Notes. (-1743)",
- });
- const result = manager.healthCheck();
- const permCheck = result.checks.find((c) => c.name === "permissions");
- expect(permCheck?.passed).toBe(false);
- expect(permCheck?.message).toContain("AppleScript permissions denied");
- // The early return fires: no account/note checks ran.
- expect(result.healthy).toBe(false);
- expect(result.checks).toHaveLength(2);
- });
- it("classifies a fully localised refusal by its -1743 OSStatus alone", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "ok" })
- .mockReturnValueOnce({
- success: false,
- output: "",
- error: "27:44: execution error: Non autorisé à envoyer des événements Apple (-1743)",
- });
- const result = manager.healthCheck();
- expect(result.checks.find((c) => c.name === "permissions")?.passed).toBe(false);
- expect(result.healthy).toBe(false);
- expect(result.checks).toHaveLength(2);
- });
- it("returns unhealthy with permission hint when the refusal is British-spelled", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Not authorised to send Apple events to Notes. (-1743)",
- });
- const result = manager.healthCheck();
- expect(result.healthy).toBe(false);
- expect(result.checks[0].message).toContain("Automation permissions");
- });
- it("returns unhealthy when no accounts found", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "ok" })
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({ success: true, output: "" }); // No accounts
- const result = manager.healthCheck();
- expect(result.healthy).toBe(false);
- expect(result.checks.find((c) => c.name === "accounts")?.passed).toBe(false);
- });
- it("includes account names in successful account check", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "ok" })
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
- .mockReturnValueOnce({ success: true, output: "" });
- const result = manager.healthCheck();
- const accountCheck = result.checks.find((c) => c.name === "accounts");
- expect(accountCheck?.message).toContain("iCloud");
- expect(accountCheck?.message).toContain("Gmail");
- });
- });
- // ---------------------------------------------------------------------------
- // Statistics
- // ---------------------------------------------------------------------------
- describe("getNotesStats", () => {
- it("returns statistics for all accounts and folders", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // per-account folder counts: name<F>count, records joined by R
- .mockReturnValueOnce({
- success: true,
- output: ["Notes", "3"].join(F) + R + ["Work", "2"].join(F) + R,
- })
- // getRecentlyModifiedCounts: c1<F>c7<F>c30
- .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
- const stats = manager.getNotesStats();
- expect(stats.totalNotes).toBe(5);
- expect(stats.accounts).toHaveLength(1);
- expect(stats.accounts[0].name).toBe("iCloud");
- expect(stats.accounts[0].totalNotes).toBe(5);
- expect(stats.accounts[0].folderCount).toBe(2);
- expect(stats.accounts[0].folders).toHaveLength(2);
- });
- it("returns zero counts when no notes exist", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({ success: true, output: ["Notes", "0"].join(F) + R })
- .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
- const stats = manager.getNotesStats();
- expect(stats.totalNotes).toBe(0);
- expect(stats.recentlyModified.last24h).toBe(0);
- expect(stats.recentlyModified.last7d).toBe(0);
- expect(stats.recentlyModified.last30d).toBe(0);
- });
- it("handles multiple accounts", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
- // iCloud folder counts
- .mockReturnValueOnce({ success: true, output: ["Notes", "1"].join(F) + R })
- // Gmail folder counts
- .mockReturnValueOnce({ success: true, output: ["Notes", "1"].join(F) + R })
- // getRecentlyModifiedCounts
- .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
- const stats = manager.getNotesStats();
- expect(stats.totalNotes).toBe(2);
- expect(stats.accounts).toHaveLength(2);
- expect(stats.accounts[0].name).toBe("iCloud");
- expect(stats.accounts[1].name).toBe("Gmail");
- });
- it("reports complete coverage when every scope succeeds (#19)", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({ success: true, output: ["Notes", "3"].join(F) + R })
- .mockReturnValueOnce({ success: true, output: ["1", "2", "3"].join(F) });
- const stats = manager.getNotesStats();
- expect(stats.coverage.complete).toBe(true);
- expect(stats.coverage.warnings).toEqual([]);
- expect(stats.coverage.covered).toBe(stats.coverage.scanned);
- });
- it("degrades gracefully when one account fails, with a coverage warning (#19)", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
- // iCloud folder counts succeed
- .mockReturnValueOnce({ success: true, output: ["Notes", "4"].join(F) + R })
- // Gmail folder counts FAIL
- .mockReturnValueOnce({ success: false, output: "", error: "Gmail account is locked" })
- // getRecentlyModifiedCounts succeed
- .mockReturnValueOnce({ success: true, output: ["0", "0", "0"].join(F) });
- const stats = manager.getNotesStats();
- // Healthy account's data is preserved, not discarded
- expect(stats.totalNotes).toBe(4);
- expect(stats.accounts).toHaveLength(1);
- expect(stats.accounts[0].name).toBe("iCloud");
- // Failure surfaced as a coverage warning
- expect(stats.coverage.complete).toBe(false);
- expect(stats.coverage.warnings).toHaveLength(1);
- expect(stats.coverage.warnings[0].scope).toBe("Gmail");
- expect(stats.coverage.warnings[0].reason).toContain("locked");
- });
- it("flags recent-activity failure as a coverage warning, not fake zeros (#19)", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- .mockReturnValueOnce({ success: true, output: ["Notes", "5"].join(F) + R })
- // getRecentlyModifiedCounts FAILS
- .mockReturnValueOnce({ success: false, output: "", error: "timed out" });
- const stats = manager.getNotesStats();
- expect(stats.totalNotes).toBe(5);
- expect(stats.recentlyModified.last24h).toBe(0);
- expect(stats.coverage.complete).toBe(false);
- expect(stats.coverage.warnings.some((w) => w.scope === "recent-activity")).toBe(true);
- });
- it("throws when no account can be read at all (#19)", () => {
- mockExecuteAppleScript
- .mockReturnValueOnce({ success: true, output: ["iCloud", "Gmail"].join(R) })
- .mockReturnValueOnce({ success: false, output: "", error: "iCloud unreachable" })
- .mockReturnValueOnce({ success: false, output: "", error: "Gmail unreachable" });
- expect(() => manager.getNotesStats()).toThrow(/Failed to read folder stats for any/);
- });
- });
- // ---------------------------------------------------------------------------
- // Attachment Listing
- // ---------------------------------------------------------------------------
- describe("listAttachmentsById", () => {
- it("returns attachments for a note", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- ["x-coredata://ABC/ICAttachment/p1", "photo.jpg", "public.jpeg"].join(F),
- ["x-coredata://ABC/ICAttachment/p2", "document.pdf", "com.adobe.pdf"].join(F),
- ].join(R),
- });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments).toHaveLength(2);
- expect(attachments[0]).toMatchObject({
- id: "x-coredata://ABC/ICAttachment/p1",
- name: "photo.jpg",
- contentType: "public.jpeg",
- contentId: "public.jpeg",
- });
- expect(attachments[1]).toMatchObject({
- id: "x-coredata://ABC/ICAttachment/p2",
- name: "document.pdf",
- contentType: "com.adobe.pdf",
- contentId: "com.adobe.pdf",
- });
- });
- it("parses richer attachment metadata when present", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- [
- "x-coredata://ABC/ICAttachment/p1",
- "site.webloc",
- "cid:123",
- "https://example.com",
- "2026-6-22-10-0-0",
- "2026-6-22-11-0-0",
- "true",
- ].join(F),
- ].join(R),
- });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments[0]).toMatchObject({
- id: "x-coredata://ABC/ICAttachment/p1",
- name: "site.webloc",
- contentType: "cid:123",
- contentId: "cid:123",
- url: "https://example.com",
- shared: true,
- });
- expect(attachments[0].created?.getFullYear()).toBe(2026);
- expect(attachments[0].modified?.getHours()).toBe(11);
- });
- it("reports an attachment enumerated twice only once, in first-seen order (#197)", () => {
- const output = [
- ["x-coredata://ABC/ICAttachment/p2", "new.png", "public.png"].join(F),
- ["x-coredata://ABC/ICAttachment/p1", "photo.jpg", "public.jpeg"].join(F),
- ["x-coredata://ABC/ICAttachment/p2", "new.png", "public.png"].join(F),
- ].join(R);
- mockExecuteAppleScript.mockReturnValue({ success: true, output });
- const expected = ["x-coredata://ABC/ICAttachment/p2", "x-coredata://ABC/ICAttachment/p1"];
- expect(manager.listAttachmentsById("x-coredata://ABC/ICNote/p123").map((a) => a.id)).toEqual(
- expected
- );
- expect(manager.listAttachments("My Note", "iCloud").map((a) => a.id)).toEqual(expected);
- });
- it("returns empty array when note has no attachments", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments).toEqual([]);
- });
- it("surfaces an error rather than an empty array when the lookup fails", () => {
- // Previously this returned [], which the tool layer rendered as the cheerful
- // "has no attachments" -- indistinguishable from a genuinely empty note.
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Note not found",
- });
- expect(() => manager.listAttachmentsById("x-coredata://ABC/ICNote/p999")).toThrow(
- /Note not found/
- );
- });
- it("generates correct AppleScript for ID lookup", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('note id "x-coredata://ABC/ICNote/p123"')
- );
- });
- it("bulk-fetches properties instead of sending Apple Events per attachment", () => {
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- manager.listAttachments("My Note", "iCloud");
- for (const [script] of mockExecuteAppleScript.mock.calls) {
- expect(script).toContain("set attachmentIds to id of every attachment of theNote");
- expect(script).toContain("set attachmentNames to name of every attachment of theNote");
- expect(script).toContain(
- 'if (count of attachmentNames) is not (count of attachmentIds) then error "Notes changed during listing"'
- );
- expect(script).toContain("repeat with i from 1 to count of attachmentIds");
- expect(script).not.toContain("repeat with a in attachments of theNote");
- }
- });
- it("does not use the reserved word `item` as a repeat loop variable", () => {
- // Regression: `repeat with item in ...` fails to COMPILE ("Expected
- // variable name or property but found class name", -2741), so every
- // list-attachments call errored and surfaced as an empty array.
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- const script = mockExecuteAppleScript.mock.calls[0][0] as string;
- expect(script).not.toMatch(/repeat with item\b/);
- expect(script).toContain("repeat with recordItem in attachmentList");
- });
- it("normalizes a 'missing value' URL to undefined", () => {
- // `URL of a as text` renders as the literal string "missing value" for
- // attachments without a URL (most images); that sentinel must not leak
- // into the parsed url field.
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- "x-coredata://ABC/ICAttachment/p1",
- "photo.png",
- "cid:abc",
- "missing value",
- "2026-7-5-22-7-39",
- "2026-7-5-22-7-39",
- "false",
- ].join(F),
- });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments).toHaveLength(1);
- expect(attachments[0].url).toBeUndefined();
- });
- it("keeps every field aligned with its own attachment across records", () => {
- // The bulk fetch zips seven independently-fetched lists. If the zip ever
- // slipped, a record would carry one attachment's id with another's name --
- // and save-attachment/fetch-attachment resolve bytes from that id, so the
- // wrong file would be written under the wrong name.
- const record = (n: number) =>
- [
- `x-coredata://ABC/ICAttachment/p${n}`,
- `file${n}.png`,
- `cid:${n}`,
- "missing value",
- "2026-7-5-22-7-39",
- "2026-7-5-22-7-39",
- n === 2 ? "true" : "false",
- ].join(F);
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [record(1), record(2), record(3)].join(R),
- });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments).toHaveLength(3);
- attachments.forEach((a, i) => {
- const n = i + 1;
- expect(a.id).toBe(`x-coredata://ABC/ICAttachment/p${n}`);
- expect(a.name).toBe(`file${n}.png`);
- expect(a.contentId).toBe(`cid:${n}`);
- expect(a.shared).toBe(n === 2);
- });
- });
- it("guards the zip against a concurrent mutation that preserves the count", () => {
- // Count guards alone cannot see a same-length reorder or delete+add, so the
- // script re-reads the ids after the other six fetches and compares them
- // element-wise. Without this, a swap between Apple Events passes every check.
- mockExecuteAppleScript.mockReturnValue({ success: true, output: "" });
- manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- manager.listAttachments("My Note", "iCloud");
- for (const [script] of mockExecuteAppleScript.mock.calls) {
- expect(script).toContain("set attachmentIdsAfter to id of every attachment of theNote");
- expect(script).toContain(
- 'if (item i of attachmentIdsAfter) is not (item i of attachmentIds) then error "Notes changed during listing"'
- );
- }
- });
- it("throws instead of reporting an empty note when the AppleScript call fails", () => {
- // A false empty is the exact hazard this tool exists to prevent: callers gate
- // destructive full-body updates on it. Exhausted retries must surface as an error.
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- error: "Notes changed during listing",
- });
- expect(() => manager.listAttachmentsById("x-coredata://ABC/ICNote/p123")).toThrow(
- /Notes changed during listing/
- );
- });
- it("still returns an empty array when the note genuinely has no attachments", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- expect(manager.listAttachmentsById("x-coredata://ABC/ICNote/p123")).toEqual([]);
- });
- it("does not surface the literal 'missing value' as an attachment name", () => {
- // Notes leaves `name` unset on some attachments; `name of a as text` then
- // renders the AppleScript sentinel, which previously reached callers as a
- // filename (`- missing value (cid:abc)`).
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- "x-coredata://ABC/ICAttachment/p1",
- "missing value",
- "cid:abc",
- "missing value",
- "2026-7-5-22-7-39",
- "2026-7-5-22-7-39",
- "false",
- ].join(F),
- });
- const attachments = manager.listAttachmentsById("x-coredata://ABC/ICNote/p123");
- expect(attachments[0].name).not.toBe("missing value");
- expect(attachments[0].name).toBe("cid:abc");
- });
- it("leaves an unnamed saved attachment's name undefined rather than the sentinel", () => {
- // save-attachment/fetch-attachment render `r.name ?? "attachment"`, and `??`
- // does not catch the literal string -- so this must be undefined, not passed
- // through, or the response reads `Saved "missing value" to ...`.
- // AppleScript is mocked, so stand in for the file Notes would have written
- // (the manager verifies a non-empty file landed before reporting success).
- // mkdtemp, not a predictable name in the shared temp dir: a guessable path
- // there is a symlink-race vector (CodeQL js/insecure-temporary-file).
- const dir = mkdtempSync(join(tmpdir(), "apple-notes-mcp-test-"));
- const dest = join(dir, "attachment.bin");
- writeFileSync(dest, "x");
- try {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: `OK${F}missing value${F}missing value`,
- });
- const saved = manager.saveAttachmentById("x-coredata://ABC/ICNote/p1", "att-1", dest);
- expect(saved.success).toBe(true);
- expect(saved.name).toBeUndefined();
- expect(saved.contentType).toBeUndefined();
- } finally {
- rmSync(dir, { recursive: true, force: true });
- }
- });
- });
- describe("listAttachments", () => {
- it("returns attachments for a note by title", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: ["attach-id", "image.png", "public.png"].join(F),
- });
- const attachments = manager.listAttachments("My Note");
- expect(attachments).toHaveLength(1);
- expect(attachments[0]).toMatchObject({
- id: "attach-id",
- name: "image.png",
- contentType: "public.png",
- contentId: "public.png",
- });
- });
- it("uses specified account", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- manager.listAttachments("My Note", "Gmail");
- expect(mockExecuteAppleScript).toHaveBeenCalledWith(
- expect.stringContaining('every account whose name is "Gmail"')
- );
- });
- it("defaults to Notes.app's own default account, not a hardcoded iCloud", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- manager.listAttachments("My Note");
- const script = String(mockExecuteAppleScript.mock.calls.at(-1)?.[0]);
- expect(script).toContain("set __acctRef to default account");
- expect(script).not.toContain('"iCloud"');
- });
- it("returns empty array when note has no attachments", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "" });
- const attachments = manager.listAttachments("Empty Note");
- expect(attachments).toEqual([]);
- });
- });
- // ---------------------------------------------------------------------------
- // Batch Operations
- // ---------------------------------------------------------------------------
- describe("batchMoveNotes", () => {
- const ID1 = "x-coredata://ABC00000-0000-0000-0000-000000000011/ICNote/p1";
- const ID2 = "x-coredata://ABC00000-0000-0000-0000-000000000012/ICNote/p2";
- it("moves the whole batch in a single osascript spawn (#26)", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: ["ok", "ok"].join(R) + R,
- });
- const results = manager.batchMoveNotes([ID1, ID2], "Archive");
- expect(mockExecuteAppleScript).toHaveBeenCalledTimes(1);
- expect(results).toHaveLength(2);
- expect(results[0]).toEqual({ id: ID1, success: true });
- expect(results[1]).toEqual({ id: ID2, success: true });
- const script = String(mockExecuteAppleScript.mock.calls[0][0]);
- expect(script).toContain("id of actualFolder");
- expect(script).toContain('"wrongfolder"');
- // #213: the destination is a live folder id, not a name reference.
- expect(script).toContain('whose name is "Archive"');
- expect(script).toContain("if exists folder id destFolder_cid then");
- expect(script).not.toContain('folder "Archive" of __acctRef');
- });
- it("returns error for non-existent note", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "missing" + R });
- const results = manager.batchMoveNotes(
- ["x-coredata://ABC00000-0000-0000-0000-000000000099/ICNote/p404"],
- "Archive"
- );
- expect(results[0]).toEqual({
- id: "x-coredata://ABC00000-0000-0000-0000-000000000099/ICNote/p404",
- success: false,
- error: "Note not found",
- committed: false,
- indeterminate: false,
- });
- });
- it("returns error for password-protected note", () => {
- mockExecuteAppleScript.mockReturnValueOnce({ success: true, output: "pw" + R });
- const results = manager.batchMoveNotes([ID1], "Archive");
- expect(results[0]).toEqual({
- id: ID1,
- success: false,
- error: "Note is password-protected",
- committed: false,
- indeterminate: false,
- });
- });
- it("maps a per-item move failure to 'Move failed'", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: ["ok", "fail"].join(R) + R,
- });
- const results = manager.batchMoveNotes([ID1, ID2], "Archive");
- expect(results[0]).toEqual({ id: ID1, success: true });
- expect(results[1]).toEqual({
- id: ID2,
- success: false,
- error: "Move failed",
- indeterminate: true,
- });
- });
- it("reports a move whose destination folder cannot be verified", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "wrongfolder" + R,
- });
- const results = manager.batchMoveNotes([ID1], "Archive");
- expect(results[0]).toEqual({
- id: ID1,
- success: false,
- error: "Destination folder verification failed",
- indeterminate: true,
- });
- });
- });
- // ---------------------------------------------------------------------------
- // Export Operations
- // ---------------------------------------------------------------------------
- describe("exportNotesAsJson", () => {
- // Note details output helper - format: title, id, date, date, shared, passwordProtected
- const noteDetailsOutput = (title: string, passwordProtected = false) =>
- [
- title,
- "x-coredata://ABC/ICNote/p1",
- "Sunday, January 1, 2025 at 1:00:00 PM",
- "Sunday, January 1, 2025 at 1:00:00 PM",
- "false",
- String(passwordProtected),
- ].join(F);
- it("exports notes with metadata and content", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // listFolders for iCloud
- .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
- // listNotes for Notes folder
- .mockReturnValueOnce({
- success: true,
- output: ["Test Note", "x-coredata://ABC/ICNote/p1"].join(F),
- })
- // getNoteDetails
- .mockReturnValueOnce({ success: true, output: noteDetailsOutput("Test Note", false) })
- // getNoteContent
- .mockReturnValueOnce({
- success: true,
- output: "<div>Test Note</div><div>Content here</div>",
- });
- const result = manager.exportNotesAsJson() as {
- exportDate: string;
- version: string;
- accounts: { name: string; folders: { name: string; notes: object[] }[] }[];
- summary: { totalNotes: number; totalFolders: number; totalAccounts: number };
- };
- expect(result.version).toBe("1.0");
- expect(result.exportDate).toBeDefined();
- expect(result.summary.totalNotes).toBe(1);
- expect(result.summary.totalFolders).toBe(1);
- expect(result.summary.totalAccounts).toBe(1);
- expect(result.accounts[0].name).toBe("iCloud");
- expect(result.accounts[0].folders[0].name).toBe("Notes");
- expect(result.accounts[0].folders[0].notes).toHaveLength(1);
- });
- it("skips content for password-protected notes", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // listFolders for iCloud
- .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
- // listNotes for Notes folder
- .mockReturnValueOnce({
- success: true,
- output: ["Locked Note", "x-coredata://ABC/ICNote/p1"].join(F),
- })
- // getNoteDetails (passwordProtected = true)
- .mockReturnValueOnce({ success: true, output: noteDetailsOutput("Locked Note", true) });
- // No getNoteContent call because note is password-protected
- const result = manager.exportNotesAsJson() as {
- accounts: { folders: { notes: { content: string; passwordProtected: boolean }[] }[] }[];
- };
- const note = result.accounts[0].folders[0].notes[0];
- expect(note.passwordProtected).toBe(true);
- expect(note.content).toBe("");
- });
- it("handles empty accounts", () => {
- mockExecuteAppleScript
- // listAccounts
- .mockReturnValueOnce({ success: true, output: "iCloud" })
- // listFolders for iCloud
- .mockReturnValueOnce({ success: true, output: "id1\tNotes" })
- // listNotes returns empty
- .mockReturnValueOnce({ success: true, output: "" });
- const result = manager.exportNotesAsJson() as {
- summary: { totalNotes: number };
- };
- expect(result.summary.totalNotes).toBe(0);
- });
- it("exports both notes when two notes share an exact title", () => {
- const idA = "x-coredata://ABC/ICNote/p1";
- const idB = "x-coredata://ABC/ICNote/p2";
- const title = "Duplicate Title";
- const detailsFor = (id: string) =>
- [
- title,
- id,
- "Sunday, January 1, 2025 at 1:00:00 PM",
- "Sunday, January 1, 2025 at 1:00:00 PM",
- "false",
- "false",
- ].join(F);
- const contentFor = (id: string) =>
- id === idA ? "<div>Content A</div>" : "<div>Content B</div>";
- let callIndex = 0;
- mockExecuteAppleScript.mockImplementation((script: string) => {
- callIndex++;
- if (callIndex === 1) return { success: true, output: "iCloud" }; // listAccounts
- if (callIndex === 2) return { success: true, output: "id1\tNotes" }; // listFolders
- if (callIndex === 3) {
- // Bulk listNotes fetch: two distinct notes, same title, different ids.
- return { success: true, output: [title + F + idA, title + F + idB].join(R) };
- }
- // Any later lookup keyed by id resolves to the real, distinct note.
- // A lookup keyed only by (ambiguous, duplicated) title mirrors real
- // AppleScript's `note "<name>"` behavior: it deterministically
- // resolves to the same one note every time, regardless of which
- // iteration is asking.
- const idMatch = script.match(/note id "([^"]+)"/);
- const targetId = idMatch ? idMatch[1] : idA;
- if (script.includes("get body of note")) {
- return { success: true, output: contentFor(targetId) };
- }
- return { success: true, output: detailsFor(targetId) };
- });
- const result = manager.exportNotesAsJson() as {
- summary: { totalNotes: number };
- accounts: { folders: { notes: { id: string; content: string }[] }[] }[];
- };
- const notes = result.accounts[0].folders[0].notes;
- expect(result.summary.totalNotes).toBe(2);
- expect(notes.map((n) => n.id).sort()).toEqual([idA, idB].sort());
- expect(notes.find((n) => n.id === idA)?.content).toBe(contentFor(idA));
- expect(notes.find((n) => n.id === idB)?.content).toBe(contentFor(idB));
- });
- });
- describe("exportNotesAsJson paging and response size budget (#162)", () => {
- type Page = {
- offset: number;
- limit: number;
- totalAvailable: number;
- returned: number;
- nextOffset?: number;
- hasMore: boolean;
- stoppedAtSizeLimit: boolean;
- };
- type ExportedPage = {
- summary: { totalNotes: number; totalFolders: number };
- page: Page;
- accounts: {
- folders: {
- name: string;
- notes: {
- id: string;
- content: string;
- plaintext: string;
- strippedImages?: number;
- contentOmitted?: boolean;
- }[];
- }[];
- }[];
- };
- const noteIds = (n: number) =>
- Array.from({ length: n }, (_, i) => `x-coredata://ABC/ICNote/p${i + 1}`);
- const exportedIds = (page: ExportedPage) =>
- page.accounts.flatMap((a) => a.folders.flatMap((f) => f.notes.map((n) => n.id)));
- /**
- * One iCloud account whose folders hold the given [id, body] notes. Each
- * script is answered by what it asks for; body reads are recorded.
- */
- const mockLibrary = (folders: Record<string, [string, string][]>) => {
- const bodyReads: string[] = [];
- mockExecuteAppleScript.mockImplementation((script: string) => {
- if (script.includes("repeat with a in accounts"))
- return { success: true, output: "iCloud" };
- if (script.includes("set allFolders to every folder")) {
- return {
- success: true,
- output: Object.keys(folders)
- .map((name, i) => [`f${i}`, name, "", "false", "iCloud"].join(F))
- .join(R),
- };
- }
- if (script.includes("set noteNames to name of")) {
- const folder = Object.keys(folders).find((name) => script.includes(`folder "${name}"`));
- const notes = folder ? folders[folder] : [];
- return {
- success: true,
- output: notes.map(([id]) => [`Title ${id}`, id].join(F)).join(R),
- };
- }
- const id = script.match(/note id "([^"]+)"/)?.[1] ?? "";
- const body =
- Object.values(folders)
- .flat()
- .find(([noteId]) => noteId === id)?.[1] ?? "";
- if (script.includes("get body of note id")) {
- bodyReads.push(id);
- return { success: true, output: body };
- }
- return {
- success: true,
- output: [`Title ${id}`, id, "2025-1-1-0-0-0", "2025-1-1-0-0-0", "false", "false"].join(F),
- };
- });
- return bodyReads;
- };
- it("returns the requested window across folders and reads bodies only for it", () => {
- const [a, b, c, d, e] = noteIds(5);
- const bodyReads = mockLibrary({
- Notes: [
- [a, "<div>a</div>"],
- [b, "<div>b</div>"],
- [c, "<div>c</div>"],
- ],
- Work: [
- [d, "<div>d</div>"],
- [e, "<div>e</div>"],
- ],
- });
- const result = manager.exportNotesAsJson({ offset: 2, limit: 2 }) as unknown as ExportedPage;
- expect(exportedIds(result)).toEqual([c, d]);
- expect(bodyReads).toEqual([c, d]);
- expect(result.summary.totalNotes).toBe(2);
- expect(result.summary.totalFolders).toBe(2);
- expect(result.page).toEqual({
- offset: 2,
- limit: 2,
- totalAvailable: 5,
- returned: 2,
- nextOffset: 4,
- hasMore: true,
- stoppedAtSizeLimit: false,
- });
- });
- it("reports the final page without a nextOffset", () => {
- const [a, b] = noteIds(2);
- mockLibrary({
- Notes: [
- [a, "<div>a</div>"],
- [b, "<div>b</div>"],
- ],
- });
- const result = manager.exportNotesAsJson({ offset: 1 }) as unknown as ExportedPage;
- expect(exportedIds(result)).toEqual([b]);
- expect(result.page.hasMore).toBe(false);
- expect(result.page.nextOffset).toBeUndefined();
- expect(result.page.totalAvailable).toBe(2);
- });
- it("bounds a no-argument export to the default page size", () => {
- const all = noteIds(DEFAULT_EXPORT_PAGE_SIZE + 10);
- const bodyReads = mockLibrary({
- Notes: all.map((id) => [id, "<div>x</div>"] as [string, string]),
- });
- const result = manager.exportNotesAsJson() as unknown as ExportedPage;
- expect(result.summary.totalNotes).toBe(DEFAULT_EXPORT_PAGE_SIZE);
- expect(bodyReads).toHaveLength(DEFAULT_EXPORT_PAGE_SIZE);
- expect(result.page.nextOffset).toBe(DEFAULT_EXPORT_PAGE_SIZE);
- expect(result.page.hasMore).toBe(true);
- });
- it("stops a page before it outgrows the response budget, then resumes at the next note", () => {
- const body = `<div>${"x".repeat(10_000)}</div>`;
- const all = noteIds(4);
- mockLibrary({ Notes: all.map((id) => [id, body] as [string, string]) });
- const first = manager.exportNotesAsJson({
- maxResponseBytes: 100_000,
- }) as unknown as ExportedPage;
- expect(exportedIds(first)).toEqual(all.slice(0, 2));
- expect(first.page).toMatchObject({ nextOffset: 2, hasMore: true, stoppedAtSizeLimit: true });
- const second = manager.exportNotesAsJson({
- offset: 2,
- maxResponseBytes: 100_000,
- }) as unknown as ExportedPage;
- expect(exportedIds(second)).toEqual(all.slice(2));
- expect(second.page).toMatchObject({ hasMore: false, stoppedAtSizeLimit: false });
- for (const note of [...first.accounts, ...second.accounts].flatMap((a) =>
- a.folders.flatMap((f) => f.notes)
- )) {
- expect(note.content).toBe(body);
- expect(note.contentOmitted).toBeUndefined();
- }
- });
- it("degrades a single note that alone exceeds the budget instead of failing", () => {
- const [img, markup, text] = noteIds(3);
- mockLibrary({
- Notes: [
- [img, `<div>caption</div><img src="data:image/png;base64,${"A".repeat(300_000)}">`],
- [markup, `<div>${"<b>z</b>".repeat(20_000)}</div>`],
- [text, `<div>${"y".repeat(200_000)}</div>`],
- ],
- });
- const onlyNote = (offset: number) =>
- (
- manager.exportNotesAsJson({
- offset,
- limit: 1,
- maxResponseBytes: 100_000,
- }) as unknown as ExportedPage
- ).accounts[0].folders[0].notes[0];
- // 1. Oversized inline images are replaced with placeholders first.
- const imgNote = onlyNote(0);
- expect(imgNote.id).toBe(img);
- expect(imgNote.strippedImages).toBe(1);
- expect(imgNote.content).toContain("caption");
- expect(imgNote.content).not.toContain("A".repeat(1000));
- expect(imgNote.contentOmitted).toBeUndefined();
- // 2. Otherwise the HTML body is omitted but the plaintext is kept.
- const markupNote = onlyNote(1);
- expect(markupNote.contentOmitted).toBe(true);
- expect(markupNote.content).toBe("");
- expect(markupNote.plaintext).toBe("z".repeat(20_000));
- // 3. And if even the plaintext cannot fit, both are omitted.
- const textNote = onlyNote(2);
- expect(textNote.contentOmitted).toBe(true);
- expect(textNote.content).toBe("");
- expect(textNote.plaintext).toBe("");
- });
- it("applies modifiedSince to the listing before paging", () => {
- const [a] = noteIds(1);
- mockLibrary({ Notes: [[a, "<div>a</div>"]] });
- manager.exportNotesAsJson({ modifiedSince: "2025-06-15" });
- const listScript = mockExecuteAppleScript.mock.calls
- .map(([script]) => script)
- .find((script) => script.includes("set noteNames to name of"));
- expect(listScript).toContain("thresholdDate");
- });
- it("reads the response budget from APPLE_NOTES_MCP_EXPORT_MAX_BYTES", () => {
- expect(exportMaxResponseBytes({})).toBe(8 * 1024 * 1024);
- expect(exportMaxResponseBytes({ APPLE_NOTES_MCP_EXPORT_MAX_BYTES: "2048" })).toBe(2048);
- expect(exportMaxResponseBytes({ APPLE_NOTES_MCP_EXPORT_MAX_BYTES: "nope" })).toBe(
- 8 * 1024 * 1024
- );
- });
- it("estimates both copies of a note that a tool response carries", () => {
- const note = {
- id: "x-coredata://ABC/ICNote/p1",
- title: 'A "quoted" title',
- content: '<div class="a">b\\c</div>',
- plaintext: "b\\c",
- folder: "Notes",
- account: "iCloud",
- created: "2025-01-01T00:00:00.000Z",
- modified: "2025-01-01T00:00:00.000Z",
- shared: false,
- passwordProtected: false,
- };
- const structuredCopy = Buffer.byteLength(JSON.stringify(note));
- const escapedTextCopy = Buffer.byteLength(JSON.stringify(JSON.stringify(note, null, 2)));
- expect(estimateExportNoteBytes(note)).toBeGreaterThan(structuredCopy + escapedTextCopy);
- });
- });
- // ---------------------------------------------------------------------------
- // Markdown Conversion
- // ---------------------------------------------------------------------------
- describe("getNoteMarkdown", () => {
- it("converts HTML to Markdown", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "<div>My Title</div><div>This is a paragraph.</div><div><b>Bold text</b></div>",
- });
- const markdown = manager.getNoteMarkdown("My Note");
- expect(markdown).toContain("My Title");
- expect(markdown).toContain("This is a paragraph.");
- expect(markdown).toContain("**Bold text**");
- });
- it("returns empty string when note not found", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Note not found",
- });
- const markdown = manager.getNoteMarkdown("Missing Note");
- expect(markdown).toBe("");
- });
- it("handles lists correctly", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "<ul><li>Item 1</li><li>Item 2</li></ul>",
- });
- const markdown = manager.getNoteMarkdown("List Note");
- // Turndown may add extra whitespace after the bullet
- expect(markdown).toMatch(/-\s+Item 1/);
- expect(markdown).toMatch(/-\s+Item 2/);
- });
- });
- describe("getNoteMarkdownById", () => {
- it("converts HTML to Markdown using ID", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "<div>Note Title</div><div>Content here</div>",
- });
- const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p123");
- expect(markdown).toContain("Note Title");
- expect(markdown).toContain("Content here");
- });
- it("returns empty string when note ID not found", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Note not found",
- });
- const markdown = manager.getNoteMarkdownById(
- "x-coredata://00000000-0000-0000-0000-000000000000/ICNote/p999"
- );
- expect(markdown).toBe("");
- });
- it("enriches markdown with checklist state when available", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "<ul><li>Buy milk</li><li>Walk dog</li><li>Send email</li></ul>",
- });
- mockGetChecklistItems.mockReturnValueOnce({
- items: [
- { text: "Buy milk", done: true },
- { text: "Walk dog", done: false },
- { text: "Send email", done: true },
- ],
- });
- const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p123");
- expect(markdown).toMatch(/-\s+\[x\] Buy milk/);
- expect(markdown).toMatch(/-\s+\[ \] Walk dog/);
- expect(markdown).toMatch(/-\s+\[x\] Send email/);
- });
- it("returns plain markdown when checklist state is unavailable", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "<ul><li>Item 1</li><li>Item 2</li></ul>",
- });
- mockGetChecklistItems.mockReturnValueOnce({
- items: null,
- error: "no_fda",
- message: "Full Disk Access required",
- });
- const markdown = manager.getNoteMarkdownById("x-coredata://ABC/ICNote/p456");
- expect(markdown).toMatch(/-\s+Item 1/);
- expect(markdown).toMatch(/-\s+Item 2/);
- expect(markdown).not.toContain("[x]");
- expect(markdown).not.toContain("[ ]");
- });
- });
- // ===========================================================================
- // Security Tests
- // ===========================================================================
- describe("sanitizeId", () => {
- it("accepts valid CoreData IDs", () => {
- const id = "x-coredata://12345ABC-DEF0-1234-5678-9ABCDEF01234/ICNote/p100";
- expect(sanitizeId(id)).toBe(id);
- });
- it("accepts temp IDs from generateFallbackId", () => {
- expect(sanitizeId("temp-1704067200000-0")).toBe("temp-1704067200000-0");
- expect(sanitizeId("temp-1704067200000-42")).toBe("temp-1704067200000-42");
- });
- it("rejects IDs with AppleScript injection", () => {
- 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
- "Invalid note ID format"
- );
- });
- it("rejects IDs with double-quote breakout", () => {
- expect(() => sanitizeId('x-coredata://test"; delete note id "dummy" & "')).toThrow(
- "Invalid note ID format"
- );
- });
- it("rejects arbitrary strings", () => {
- expect(() => sanitizeId("not-a-valid-id")).toThrow("Invalid note ID format");
- });
- it("rejects empty string", () => {
- expect(() => sanitizeId("")).toThrow("Invalid note ID format");
- });
- it("accepts various ICEntity types", () => {
- expect(sanitizeId("x-coredata://ABC123/ICFolder/p50")).toBe(
- "x-coredata://ABC123/ICFolder/p50"
- );
- expect(sanitizeId("x-coredata://ABC123/ICAttachment/p1")).toBe(
- "x-coredata://ABC123/ICAttachment/p1"
- );
- });
- });
- describe("sanitizeNoteId", () => {
- it("accepts only canonical Apple Note IDs", () => {
- const id = "x-coredata://12345ABC-DEF0-1234-5678-9ABCDEF01234/ICNote/p100";
- expect(sanitizeNoteId(id)).toBe(id);
- });
- it("rejects synthetic IDs and IDs for other CoreData entities", () => {
- expect(() => sanitizeNoteId("temp-1704067200000-0")).toThrow("Invalid note ID format");
- expect(() => sanitizeNoteId("x-coredata://ABC123/ICFolder/p50")).toThrow(
- "Invalid note ID format"
- );
- });
- });
- describe("escapeForAppleScript - injection prevention", () => {
- it("escapes double quotes to prevent AppleScript string breakout", () => {
- const malicious = 'Hello "World" end tell';
- const escaped = escapeForAppleScript(malicious);
- expect(escaped).toContain('\\"');
- expect(escaped).not.toContain('"World"');
- });
- it("escapes backslashes to prevent escape sequence injection", () => {
- const malicious = "path\\to\\file";
- const escaped = escapeForAppleScript(malicious);
- // Backslashes should be encoded as HTML entities (\)
- expect(escaped).toContain("\");
- });
- it("handles combined injection payload", () => {
- const payload = '" & do shell script "echo pwned" & "';
- const escaped = escapeForAppleScript(payload);
- // All double quotes must be escaped with backslash
- // Count unescaped double quotes — there should be none
- const unescapedQuotes = escaped.replace(/\\"/g, "").match(/"/g);
- expect(unescapedQuotes).toBeNull();
- });
- });
- describe("buildFolderReference - input validation", () => {
- it("rejects empty folder paths", () => {
- expect(() => buildFolderReference("")).toThrow("Folder path is empty");
- });
- it("rejects paths that are only slashes", () => {
- expect(() => buildFolderReference("///")).toThrow("Folder path is empty");
- });
- it("rejects excessively deep folder nesting", () => {
- const deepPath = Array(25).fill("folder").join("/");
- expect(() => buildFolderReference(deepPath)).toThrow("maximum nesting depth");
- });
- it("rejects excessively long folder paths", () => {
- const longPath = "a".repeat(1001);
- expect(() => buildFolderReference(longPath)).toThrow("maximum length");
- });
- it("escapes folder names with double quotes", () => {
- const result = buildFolderReference('My "Special" Folder');
- expect(result).toContain('\\"');
- expect(result).not.toContain('"Special"');
- });
- it("handles folder names with emoji", () => {
- const result = buildFolderReference("Food & Drink/\uD83C\uDF72 Recipes");
- expect(result).toContain("folder");
- expect(result).toContain("of");
- });
- });
- describe("ID-based operations sanitize input", () => {
- it("getNoteById rejects malformed IDs", () => {
- expect(() => {
- manager.getNoteById('malicious" & do shell script "echo pwned');
- }).toThrow("Invalid note ID format");
- });
- it("getNoteContentById rejects malformed IDs", () => {
- expect(() => {
- manager.getNoteContentById("arbitrary string");
- }).toThrow("Invalid note ID format");
- });
- it("updateNoteByIdIfUnchanged rejects malformed IDs", () => {
- expect(() => {
- manager.updateNoteByIdIfUnchanged(
- "not-valid",
- "Title",
- "<div>Body</div>",
- undefined,
- "content"
- );
- }).toThrow("Invalid note ID format");
- });
- it("deleteNoteByIdIfUnchanged rejects malformed IDs", () => {
- expect(() => {
- manager.deleteNoteByIdIfUnchanged(
- 'x-coredata://test"; delete note 1 & "',
- "<div>Body</div>"
- );
- }).toThrow("Invalid note ID format");
- });
- it("moveNoteById rejects malformed IDs", () => {
- expect(() => {
- manager.moveNoteById("not-valid", "Archive");
- }).toThrow("Invalid note ID format");
- });
- // #146: batchMoveNotes validated with the looser sanitizeId (accepts any
- // ICEntity, plus legacy temp-* ids), unlike every other #144-hardened
- // mutation — bring it in line with moveNoteById's sanitizeNoteId.
- it("batchMoveNotes rejects a non-ICNote CoreData ID as a per-item failure, without spawning osascript", () => {
- const results = manager.batchMoveNotes(
- ["x-coredata://ABC123/ICFolder/p50", "temp-1704067200000-0"],
- "Archive"
- );
- expect(mockExecuteAppleScript).not.toHaveBeenCalled();
- expect(results[0]).toEqual({
- id: "x-coredata://ABC123/ICFolder/p50",
- success: false,
- error: expect.stringContaining("Invalid note ID format"),
- committed: false,
- indeterminate: false,
- });
- expect(results[1]).toEqual({
- id: "temp-1704067200000-0",
- success: false,
- error: expect.stringContaining("Invalid note ID format"),
- committed: false,
- indeterminate: false,
- });
- });
- });
- // ---------------------------------------------------------------------------
- // getNoteLinkById
- // ---------------------------------------------------------------------------
- describe("getNoteLinkById", () => {
- const VALID_ID = "x-coredata://ABC123/ICNote/p50338";
- it("returns null immediately for a password-protected note without calling executeAppleScript for the link", () => {
- // First call: getNoteById (returns a protected note)
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- "Locked Note",
- VALID_ID,
- "2025-12-27-15-0-0",
- "2025-12-27-15-0-0",
- "false",
- "true", // passwordProtected = true
- ].join(F),
- });
- const result = manager.getNoteLinkById(VALID_ID);
- expect(result).toBeNull();
- // The link-fetching AppleScript (note link property) must NOT be called
- // — the function should bail out after the password check.
- const calls = mockExecuteAppleScript.mock.calls;
- // Only one call: getNoteById
- expect(calls).toHaveLength(1);
- });
- it("returns null when the note is not found", () => {
- mockExecuteAppleScript.mockReturnValueOnce({
- success: false,
- output: "",
- error: "Can't get note id",
- });
- const result = manager.getNoteLinkById(VALID_ID);
- expect(result).toBeNull();
- });
- it("returns a notes:// URL for a valid, non-protected note", () => {
- // getNoteById returns a non-protected note
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: [
- "My Note",
- VALID_ID,
- "2025-12-27-15-0-0",
- "2025-12-27-15-0-0",
- "false",
- "false",
- ].join(F),
- });
- // SQLite path (getNoteLinkFromDB) may succeed (if the Notes DB is
- // accessible on the test machine) or fail and fall through to the
- // AppleScript fallback. Mock the AppleScript fallback so it can
- // return a URL in the fallback-path case.
- mockExecuteAppleScript.mockReturnValueOnce({
- success: true,
- output: "notes://showNote?identifier=ABCD-1234-5678",
- });
- const result = manager.getNoteLinkById(VALID_ID);
- // Either the SQLite path or the AppleScript fallback should return
- // a notes:// URL — either form is acceptable.
- expect(result).not.toBeNull();
- expect(result).toMatch(/^notes:\/\/showNote\?identifier=/);
- });
- });
- });
- describe("getNoteLinkFromDB — CoreData PK parsing", () => {
- // getNoteLinkFromDB is module-private, but we can verify the PK extraction
- // logic indirectly by checking that getNoteLinkById passes the right primary
- // key to the database query. We test the regex rule by covering the
- // CoreData ID formats the function must handle.
- it("sanitizeId accepts the x-coredata URL used by getNoteLinkById", () => {
- // If sanitizeId throws, getNoteLinkById would not even reach the DB call.
- // This assertion confirms the ID format is considered valid.
- expect(() => sanitizeId("x-coredata://ABC123/ICNote/p50338")).not.toThrow();
- });
- it("sanitizeId rejects IDs without a /p<digits> suffix", () => {
- expect(() => sanitizeId("x-coredata://ABC123/ICNote/pXXX")).toThrow("Invalid note ID format");
- });
- });
- describe("htmlToPlaintext (export helper)", () => {
- // htmlToPlaintext is a private, pure string transform used by exportNote; it
- // touches no AppleScript, so we exercise it directly through a cast.
- const toPlaintext = (html: string): string =>
- (
- new AppleNotesManager() as unknown as {
- htmlToPlaintext(h: string): string;
- }
- ).htmlToPlaintext(html);
- it("decodes the basic HTML entities", () => {
- expect(toPlaintext("a & b")).toBe("a & b");
- expect(toPlaintext("<tag>")).toBe("<tag>");
- expect(toPlaintext("say "hi"")).toBe('say "hi"');
- expect(toPlaintext("path\file")).toBe("path\\file");
- expect(toPlaintext("a b")).toBe("a b");
- });
- it("decodes & last so encoded entities round-trip (no double-unescape)", () => {
- // The literal text "<" is stored in HTML as "&lt;" and must decode
- // back to "<", NOT be double-unescaped to "<".
- expect(toPlaintext("&lt;")).toBe("<");
- expect(toPlaintext("&gt;")).toBe(">");
- expect(toPlaintext("&amp;")).toBe("&");
- expect(toPlaintext("&nbsp;")).toBe(" ");
- });
- it("converts block/line tags to newlines and strips other tags", () => {
- expect(toPlaintext("one<br>two")).toBe("one\ntwo");
- expect(toPlaintext("<div>a</div><div>b</div>")).toBe("a\nb");
- expect(toPlaintext("<p>x</p><p>y</p>")).toBe("x\ny");
- expect(toPlaintext("<b>bold</b>")).toBe("bold");
- });
- it("collapses 3+ newlines and trims surrounding whitespace", () => {
- expect(toPlaintext("a<br><br><br><br>b")).toBe("a\n\nb");
- expect(toPlaintext(" <div>x</div> ")).toBe("x");
- });
- it("strips nested/overlapping tags without leaving a tag (iterated strip)", () => {
- // A single pass can leave residue when removing one tag re-forms another;
- // the loop keeps stripping until no <...> remains.
- expect(toPlaintext("a<<i>>b")).not.toMatch(/<[^>]*>/);
- expect(toPlaintext("<x<y>z>")).not.toMatch(/<[^>]*>/);
- expect(toPlaintext("plain <b>text</b> here")).toBe("plain text here");
- });
- });
- describe("getAudioTranscripts", () => {
- it("delegates to the read-only transcript reader with the caller's options", () => {
- const result = {
- id: "x-coredata://S/ICNote/p1",
- attachments: [],
- bodyOrder: true,
- truncated: false,
- };
- mockReadAudioTranscripts.mockReturnValueOnce(result);
- const manager = new AppleNotesManager();
- expect(
- manager.getAudioTranscripts("x-coredata://S/ICNote/p1", {
- includeSegments: true,
- maxSegments: 5,
- })
- ).toBe(result);
- expect(mockReadAudioTranscripts).toHaveBeenCalledWith("x-coredata://S/ICNote/p1", {
- includeSegments: true,
- maxSegments: 5,
- });
- });
- });
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.