upnote-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ddoobyddooby
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,107 @@
1
+ Metadata-Version: 2.4
2
+ Name: upnote-mcp
3
+ Version: 0.1.0
4
+ Summary: Read-only MCP server to search and read your local UpNote notes from Claude Code and Codex CLI (unofficial, macOS).
5
+ Keywords: upnote,mcp,model-context-protocol,notes,claude,codex
6
+ Author: Ddoobyddooby
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Environment :: Console
11
+ Classifier: Intended Audience :: End Users/Desktop
12
+ Classifier: Operating System :: MacOS
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Programming Language :: Python :: 3.12
15
+ Classifier: Programming Language :: Python :: 3.13
16
+ Classifier: Programming Language :: Python :: 3.14
17
+ Classifier: Topic :: Text Processing
18
+ Classifier: Topic :: Utilities
19
+ Requires-Dist: mcp>=2.3,<3
20
+ Requires-Python: >=3.12
21
+ Project-URL: Homepage, https://github.com/Ddoobyddooby/upnote-mcp
22
+ Project-URL: Repository, https://github.com/Ddoobyddooby/upnote-mcp
23
+ Project-URL: Issues, https://github.com/Ddoobyddooby/upnote-mcp/issues
24
+ Project-URL: Changelog, https://github.com/Ddoobyddooby/upnote-mcp/blob/main/CHANGELOG.md
25
+ Description-Content-Type: text/markdown
26
+
27
+ # upnote-mcp
28
+
29
+ > **Status: v0.1.0 (alpha, macOS only).** Not affiliated with or endorsed by UpNote.
30
+ > Unofficial: it only reads the local data of the UpNote desktop app.
31
+
32
+ A read-only [MCP](https://modelcontextprotocol.io/) server that lets AI agent CLIs
33
+ (Claude Code, Codex CLI) search and read notes stored locally by the UpNote desktop app on macOS.
34
+
35
+ ## Read this first
36
+ - **Your notes are sent to an AI model.** Everything a tool returns (titles, previews, note text,
37
+ tag and notebook names) goes to the model provider behind your CLI. Note text is returned as written,
38
+ so URLs, paths and personal data typed into a visible note are sent too. Details: [SECURITY](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/SECURITY.md).
39
+ - **Read-only.** The UpNote SQLite database is opened with `mode=ro` and `query_only=ON`.
40
+ There is no tool that creates, edits or deletes anything.
41
+ - **Fail-closed.** Notes in locked notebooks (or under a locked parent), in locked or
42
+ non-allowed spaces, in the trash, or whose protection state cannot be determined are not returned.
43
+ - **Note text is data, not instructions.** Tool descriptions and server instructions say so,
44
+ but a model can still be influenced by text inside a note. Treat results accordingly.
45
+
46
+ ## Requirements
47
+ - macOS with the UpNote desktop app (other platforms are not supported or tested)
48
+ - Python 3.12+ and [uv](https://docs.astral.sh/uv/)
49
+
50
+ ## Quick start
51
+ Once v0.1.0 is published on PyPI (until then use the source install below):
52
+ ```sh
53
+ # Claude Code
54
+ claude mcp add upnote -- uvx upnote-mcp
55
+ # Codex CLI
56
+ codex mcp add upnote -- uvx upnote-mcp
57
+ ```
58
+ (`pip install upnote-mcp` also works; register the `upnote-mcp` command.)
59
+
60
+ From source (works today):
61
+ ```sh
62
+ git clone https://github.com/Ddoobyddooby/upnote-mcp.git upnote-mcp && cd upnote-mcp
63
+ uv sync --locked
64
+ claude mcp add upnote -- uv run --directory "$PWD" upnote-mcp
65
+ codex mcp add upnote -- uv run --directory "$PWD" upnote-mcp
66
+ ```
67
+ Full instructions (scopes, configuration, removal, macOS permissions, troubleshooting):
68
+ **[INSTALL](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/INSTALL.md)**.
69
+
70
+ ## Tools
71
+ | Tool | Purpose |
72
+ |---|---|
73
+ | `search_notes` | Literal keyword search in title, text and summary; optional notebook filter |
74
+ | `get_note` | Read one note as plain text in chunks (`contentFormat: "plain"`) |
75
+ | `list_notes` | List notes (including uncategorized ones), all or per notebook |
76
+ | `list_notebooks` | Accessible notebooks with the verified hierarchy |
77
+ | `list_tags` | Accessible tags with note counts |
78
+ | `get_source_status` | Connection/schema state and read time (no paths, no account data) |
79
+
80
+ Limits: `limit` default 20, max 100; query 1-200 characters; note text chunks of at most
81
+ 10,000 characters; preview 300 characters. The serialized result (UTF-8 JSON DTO) is at most 64 KiB; the MCP
82
+ SDK sends it twice (as text and as structured content) plus a JSON-RPC wrapper, so the message on the wire can be
83
+ about twice that.
84
+ Results are ordered by update time (newest first, id as tie-breaker). Times are ISO 8601 UTC.
85
+
86
+ Errors are returned as `{"code": ..., "message": ...}`:
87
+ `invalid_argument`, `not_found` (missing and protected notes look identical), `note_changed`,
88
+ `response_too_large`, `internal`, and source errors `source_missing`, `permission_denied`,
89
+ `schema_unsupported`, `source_corrupt`, `busy`.
90
+
91
+ ## Development
92
+ ```sh
93
+ uv sync --locked
94
+ uv run ruff check .
95
+ uv run ruff format --check .
96
+ uv run pytest
97
+ uv build
98
+ ```
99
+ Tests use synthetic fixtures only (`tests/fixtures/`) and never open the real UpNote database.
100
+ Never commit real notes, databases, backups or logs.
101
+
102
+ ## Documents
103
+ [SPEC](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/SPEC.md) · [PLAN](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/PLAN.md) · [INSTALL](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/INSTALL.md) ·
104
+ [SECURITY](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/SECURITY.md) · [CHANGELOG](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/CHANGELOG.md)
105
+
106
+ ## License
107
+ MIT. See [LICENSE](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/LICENSE).
@@ -0,0 +1,81 @@
1
+ # upnote-mcp
2
+
3
+ > **Status: v0.1.0 (alpha, macOS only).** Not affiliated with or endorsed by UpNote.
4
+ > Unofficial: it only reads the local data of the UpNote desktop app.
5
+
6
+ A read-only [MCP](https://modelcontextprotocol.io/) server that lets AI agent CLIs
7
+ (Claude Code, Codex CLI) search and read notes stored locally by the UpNote desktop app on macOS.
8
+
9
+ ## Read this first
10
+ - **Your notes are sent to an AI model.** Everything a tool returns (titles, previews, note text,
11
+ tag and notebook names) goes to the model provider behind your CLI. Note text is returned as written,
12
+ so URLs, paths and personal data typed into a visible note are sent too. Details: [SECURITY](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/SECURITY.md).
13
+ - **Read-only.** The UpNote SQLite database is opened with `mode=ro` and `query_only=ON`.
14
+ There is no tool that creates, edits or deletes anything.
15
+ - **Fail-closed.** Notes in locked notebooks (or under a locked parent), in locked or
16
+ non-allowed spaces, in the trash, or whose protection state cannot be determined are not returned.
17
+ - **Note text is data, not instructions.** Tool descriptions and server instructions say so,
18
+ but a model can still be influenced by text inside a note. Treat results accordingly.
19
+
20
+ ## Requirements
21
+ - macOS with the UpNote desktop app (other platforms are not supported or tested)
22
+ - Python 3.12+ and [uv](https://docs.astral.sh/uv/)
23
+
24
+ ## Quick start
25
+ Once v0.1.0 is published on PyPI (until then use the source install below):
26
+ ```sh
27
+ # Claude Code
28
+ claude mcp add upnote -- uvx upnote-mcp
29
+ # Codex CLI
30
+ codex mcp add upnote -- uvx upnote-mcp
31
+ ```
32
+ (`pip install upnote-mcp` also works; register the `upnote-mcp` command.)
33
+
34
+ From source (works today):
35
+ ```sh
36
+ git clone https://github.com/Ddoobyddooby/upnote-mcp.git upnote-mcp && cd upnote-mcp
37
+ uv sync --locked
38
+ claude mcp add upnote -- uv run --directory "$PWD" upnote-mcp
39
+ codex mcp add upnote -- uv run --directory "$PWD" upnote-mcp
40
+ ```
41
+ Full instructions (scopes, configuration, removal, macOS permissions, troubleshooting):
42
+ **[INSTALL](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/INSTALL.md)**.
43
+
44
+ ## Tools
45
+ | Tool | Purpose |
46
+ |---|---|
47
+ | `search_notes` | Literal keyword search in title, text and summary; optional notebook filter |
48
+ | `get_note` | Read one note as plain text in chunks (`contentFormat: "plain"`) |
49
+ | `list_notes` | List notes (including uncategorized ones), all or per notebook |
50
+ | `list_notebooks` | Accessible notebooks with the verified hierarchy |
51
+ | `list_tags` | Accessible tags with note counts |
52
+ | `get_source_status` | Connection/schema state and read time (no paths, no account data) |
53
+
54
+ Limits: `limit` default 20, max 100; query 1-200 characters; note text chunks of at most
55
+ 10,000 characters; preview 300 characters. The serialized result (UTF-8 JSON DTO) is at most 64 KiB; the MCP
56
+ SDK sends it twice (as text and as structured content) plus a JSON-RPC wrapper, so the message on the wire can be
57
+ about twice that.
58
+ Results are ordered by update time (newest first, id as tie-breaker). Times are ISO 8601 UTC.
59
+
60
+ Errors are returned as `{"code": ..., "message": ...}`:
61
+ `invalid_argument`, `not_found` (missing and protected notes look identical), `note_changed`,
62
+ `response_too_large`, `internal`, and source errors `source_missing`, `permission_denied`,
63
+ `schema_unsupported`, `source_corrupt`, `busy`.
64
+
65
+ ## Development
66
+ ```sh
67
+ uv sync --locked
68
+ uv run ruff check .
69
+ uv run ruff format --check .
70
+ uv run pytest
71
+ uv build
72
+ ```
73
+ Tests use synthetic fixtures only (`tests/fixtures/`) and never open the real UpNote database.
74
+ Never commit real notes, databases, backups or logs.
75
+
76
+ ## Documents
77
+ [SPEC](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/SPEC.md) · [PLAN](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/PLAN.md) · [INSTALL](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/INSTALL.md) ·
78
+ [SECURITY](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/docs/SECURITY.md) · [CHANGELOG](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/CHANGELOG.md)
79
+
80
+ ## License
81
+ MIT. See [LICENSE](https://github.com/Ddoobyddooby/upnote-mcp/blob/main/LICENSE).
@@ -0,0 +1,107 @@
1
+ [project]
2
+ name = "upnote-mcp"
3
+ version = "0.1.0"
4
+ description = "Read-only MCP server to search and read your local UpNote notes from Claude Code and Codex CLI (unofficial, macOS)."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.12"
9
+ keywords = [
10
+ "upnote",
11
+ "mcp",
12
+ "model-context-protocol",
13
+ "notes",
14
+ "claude",
15
+ "codex",
16
+ ]
17
+ dependencies = ["mcp>=2.3,<3"]
18
+ classifiers = [
19
+ "Development Status :: 3 - Alpha",
20
+ "Environment :: Console",
21
+ "Intended Audience :: End Users/Desktop",
22
+ "Operating System :: MacOS",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.12",
25
+ "Programming Language :: Python :: 3.13",
26
+ "Programming Language :: Python :: 3.14",
27
+ "Topic :: Text Processing",
28
+ "Topic :: Utilities",
29
+ ]
30
+
31
+ [[project.authors]]
32
+ name = "Ddoobyddooby"
33
+
34
+ [project.urls]
35
+ Homepage = "https://github.com/Ddoobyddooby/upnote-mcp"
36
+ Repository = "https://github.com/Ddoobyddooby/upnote-mcp"
37
+ Issues = "https://github.com/Ddoobyddooby/upnote-mcp/issues"
38
+ Changelog = "https://github.com/Ddoobyddooby/upnote-mcp/blob/main/CHANGELOG.md"
39
+
40
+ [project.scripts]
41
+ upnote-mcp = "upnote_mcp.server:main"
42
+
43
+ [build-system]
44
+ requires = ["uv_build>=0.13.7,<0.14.0"]
45
+ build-backend = "uv_build"
46
+
47
+ [tool.uv.build-backend]
48
+ source-exclude = [
49
+ "**/*.sqlite*",
50
+ "**/*.db*",
51
+ "**/*-wal",
52
+ "**/*-shm",
53
+ "**/*-journal",
54
+ "**/*.upn*",
55
+ "**/*.bak",
56
+ "**/*.backup",
57
+ "**/*backup*/**",
58
+ "**/*.log",
59
+ "**/logs",
60
+ "**/.*",
61
+ ]
62
+ wheel-exclude = [
63
+ "**/*.sqlite*",
64
+ "**/*.db*",
65
+ "**/*-wal",
66
+ "**/*-shm",
67
+ "**/*-journal",
68
+ "**/*.upn*",
69
+ "**/*.bak",
70
+ "**/*.backup",
71
+ "**/*backup*/**",
72
+ "**/*.log",
73
+ "**/logs",
74
+ "**/.*",
75
+ ]
76
+
77
+ [tool.pytest.ini_options]
78
+ testpaths = ["tests"]
79
+ addopts = "-ra --strict-markers"
80
+
81
+ [tool.ruff]
82
+ line-length = 100
83
+ target-version = "py312"
84
+
85
+ [tool.ruff.lint]
86
+ select = [
87
+ "E",
88
+ "W",
89
+ "F",
90
+ "I",
91
+ "B",
92
+ "UP",
93
+ "SIM",
94
+ "S",
95
+ ]
96
+
97
+ [tool.ruff.lint.per-file-ignores]
98
+ "tests/**" = [
99
+ "S101",
100
+ "S603",
101
+ ]
102
+
103
+ [dependency-groups]
104
+ dev = [
105
+ "pytest>=9.2.0",
106
+ "ruff>=0.17.6",
107
+ ]
@@ -0,0 +1,73 @@
1
+ [project]
2
+ name = "upnote-mcp"
3
+ version = "0.1.0"
4
+ description = "Read-only MCP server to search and read your local UpNote notes from Claude Code and Codex CLI (unofficial, macOS)."
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ authors = [{ name = "Ddoobyddooby" }]
9
+ requires-python = ">=3.12"
10
+ keywords = ["upnote", "mcp", "model-context-protocol", "notes", "claude", "codex"]
11
+ dependencies = [
12
+ "mcp>=2.3,<3",
13
+ ]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: End Users/Desktop",
18
+ "Operating System :: MacOS",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3.12",
21
+ "Programming Language :: Python :: 3.13",
22
+ "Programming Language :: Python :: 3.14",
23
+ "Topic :: Text Processing",
24
+ "Topic :: Utilities",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/Ddoobyddooby/upnote-mcp"
29
+ Repository = "https://github.com/Ddoobyddooby/upnote-mcp"
30
+ Issues = "https://github.com/Ddoobyddooby/upnote-mcp/issues"
31
+ Changelog = "https://github.com/Ddoobyddooby/upnote-mcp/blob/main/CHANGELOG.md"
32
+
33
+ [project.scripts]
34
+ upnote-mcp = "upnote_mcp.server:main"
35
+
36
+ [build-system]
37
+ requires = ["uv_build>=0.13.7,<0.14.0"]
38
+ build-backend = "uv_build"
39
+
40
+ [tool.uv.build-backend]
41
+ # Never ship local data even if it lands inside the package directory (review T-01 #1).
42
+ source-exclude = [
43
+ "**/*.sqlite*", "**/*.db*", "**/*-wal", "**/*-shm", "**/*-journal",
44
+ "**/*.upn*", "**/*.bak", "**/*.backup", "**/*backup*/**", "**/*.log", "**/logs",
45
+ # Hidden files/dirs never belong in the package (.env*, .envrc, .omc/, .DS_Store, ...).
46
+ "**/.*",
47
+ ]
48
+ wheel-exclude = [
49
+ "**/*.sqlite*", "**/*.db*", "**/*-wal", "**/*-shm", "**/*-journal",
50
+ "**/*.upn*", "**/*.bak", "**/*.backup", "**/*backup*/**", "**/*.log", "**/logs",
51
+ # Hidden files/dirs never belong in the package (.env*, .envrc, .omc/, .DS_Store, ...).
52
+ "**/.*",
53
+ ]
54
+
55
+ [dependency-groups]
56
+ dev = [
57
+ "pytest>=9.2.0",
58
+ "ruff>=0.17.6",
59
+ ]
60
+
61
+ [tool.pytest.ini_options]
62
+ testpaths = ["tests"]
63
+ addopts = "-ra --strict-markers"
64
+
65
+ [tool.ruff]
66
+ line-length = 100
67
+ target-version = "py312"
68
+
69
+ [tool.ruff.lint]
70
+ select = ["E", "W", "F", "I", "B", "UP", "SIM", "S"]
71
+
72
+ [tool.ruff.lint.per-file-ignores]
73
+ "tests/**" = ["S101", "S603"]
@@ -0,0 +1,3 @@
1
+ """Read-only MCP server for local UpNote data (unofficial, not affiliated with UpNote)."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,52 @@
1
+ """Server settings. Configuration only: Tools can never change the DB path or the spaces.
2
+
3
+ Environment variables
4
+ ---------------------
5
+ ``UPNOTE_MCP_DB_PATH``
6
+ Optional. Path to the UpNote SQLite file (``~`` is expanded). Empty or unset means the
7
+ default macOS location of the UpNote desktop app under the current user's home directory.
8
+ ``UPNOTE_MCP_SPACES``
9
+ Optional. Comma-separated space (workspace) names that may be exposed in addition to the
10
+ default space, e.g. ``Work,Reading list``. Each name is trimmed of surrounding whitespace,
11
+ empty entries are ignored, and matching is exact (case-sensitive). Unset or empty means
12
+ only the default space is exposed. A name shared by several spaces, or naming a locked or
13
+ deleted space, never exposes anything.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import os
19
+ from collections.abc import Mapping
20
+ from dataclasses import dataclass
21
+ from pathlib import Path
22
+
23
+ ENV_DB_PATH = "UPNOTE_MCP_DB_PATH"
24
+ ENV_SPACES = "UPNOTE_MCP_SPACES"
25
+
26
+ _DEFAULT_RELATIVE = Path(
27
+ "Library/Containers/com.getupnote.desktop/Data/Library/Application Support/UpNote/"
28
+ "upnote.sqlite3"
29
+ )
30
+
31
+
32
+ @dataclass(frozen=True, slots=True)
33
+ class Settings:
34
+ db_path: Path
35
+ allowed_spaces: frozenset[str]
36
+
37
+
38
+ def default_db_path() -> Path:
39
+ return Path.home() / _DEFAULT_RELATIVE
40
+
41
+
42
+ def parse_spaces(raw: str | None) -> frozenset[str]:
43
+ if not raw:
44
+ return frozenset()
45
+ return frozenset(name for part in raw.split(",") if (name := part.strip()))
46
+
47
+
48
+ def load_settings(env: Mapping[str, str] | None = None) -> Settings:
49
+ source = os.environ if env is None else env
50
+ raw_path = source.get(ENV_DB_PATH, "").strip()
51
+ db_path = Path(raw_path).expanduser() if raw_path else default_db_path()
52
+ return Settings(db_path=db_path, allowed_spaces=parse_spaces(source.get(ENV_SPACES)))
@@ -0,0 +1,176 @@
1
+ """Read-only SQLite access: one short read transaction per snapshot.
2
+
3
+ Safety rules (docs/PLAN.md section 3): existing file only, ``mode=ro`` URI with the path
4
+ percent-encoded, ``PRAGMA query_only=ON``, never ``immutable=1``, never create, never write,
5
+ never touch WAL/SHM files ourselves. Errors are sanitized: no path, id or content.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import errno
11
+ import os
12
+ import sqlite3
13
+ import time
14
+ from collections.abc import Iterator
15
+ from contextlib import contextmanager, suppress
16
+ from pathlib import Path
17
+
18
+ from upnote_mcp.records import SourceError
19
+
20
+ DEFAULT_BUSY_TIMEOUT_MS = 1000
21
+ DEFAULT_RETRIES = 2 # extra attempts after the first one, busy errors only
22
+ _RETRY_SLEEP_S = 0.05
23
+
24
+ # Columns the policy and repository read, with the declared types of the real UpNote DDL.
25
+ # Every table's ``id`` must be the PRIMARY KEY: the policy keys decisions by id and the detail
26
+ # queries assume one row per id. Anything else -> schema_unsupported before any read.
27
+ REQUIRED_COLUMNS: dict[str, dict[str, str]] = {
28
+ "notes": {
29
+ "id": "TEXT",
30
+ "title": "TEXT",
31
+ "text": "TEXT",
32
+ "summary": "TEXT",
33
+ "deleted": "INTEGER",
34
+ "trashed": "INTEGER",
35
+ "space": "TEXT",
36
+ "updatedAt": "DOUBLE",
37
+ "createdAt": "DOUBLE",
38
+ "revision": "INTEGER",
39
+ "tagLinks": "TEXT",
40
+ },
41
+ "notebooks": {
42
+ "id": "TEXT",
43
+ "title": "TEXT",
44
+ "deleted": "INTEGER",
45
+ "inactive": "INTEGER",
46
+ "locked": "INTEGER",
47
+ "notes": "TEXT",
48
+ "childNotebooks": "TEXT",
49
+ "parent": "TEXT",
50
+ "space": "TEXT",
51
+ },
52
+ "organizers": {"id": "TEXT", "noteId": "TEXT", "notebookId": "TEXT", "deleted": "INTEGER"},
53
+ "lists": {"id": "TEXT", "deleted": "INTEGER", "content": "TEXT", "space": "TEXT"},
54
+ "workspaces": {"id": "TEXT", "name": "TEXT", "deleted": "INTEGER", "locked": "INTEGER"},
55
+ "tags": {
56
+ "id": "TEXT",
57
+ "title": "TEXT",
58
+ "deleted": "INTEGER",
59
+ "inactive": "INTEGER",
60
+ "space": "TEXT",
61
+ },
62
+ }
63
+
64
+
65
+ _MISSING = SourceError("source_missing", "UpNote database not found")
66
+ _DENIED = SourceError("permission_denied", "Permission denied reading UpNote data")
67
+
68
+
69
+ def _from_os_error(exc: BaseException) -> SourceError:
70
+ """Classify a path-level failure without exposing the OS message or the path."""
71
+ if isinstance(exc, PermissionError) or getattr(exc, "errno", None) in (
72
+ errno.EACCES,
73
+ errno.EPERM,
74
+ ):
75
+ return SourceError(_DENIED.code, str(_DENIED))
76
+ return SourceError(_MISSING.code, str(_MISSING)) # ENOENT/ENOTDIR/ELOOP/ENAMETOOLONG/...
77
+
78
+
79
+ def _readonly_uri(path: Path) -> str:
80
+ # as_uri() percent-encodes '?', '#', '%' and non-ASCII, so a path can't inject URI options
81
+ return f"{path.resolve(strict=True).as_uri()}?mode=ro"
82
+
83
+
84
+ def _check_file(path: Path) -> None:
85
+ try:
86
+ os.stat(path) # noqa: PTH116 - need the raw errno mapping
87
+ if not path.is_file():
88
+ raise SourceError(_MISSING.code, str(_MISSING))
89
+ if not os.access(path, os.R_OK):
90
+ raise SourceError(_DENIED.code, str(_DENIED))
91
+ except (OSError, ValueError, RuntimeError) as exc: # ELOOP, ENAMETOOLONG, NUL byte, ...
92
+ raise _from_os_error(exc) from None
93
+
94
+
95
+ def _map_error(exc: sqlite3.Error, path: Path) -> SourceError:
96
+ msg = str(exc).lower()
97
+ if "locked" in msg or "busy" in msg:
98
+ return SourceError("busy", "UpNote database is busy; try again")
99
+ if isinstance(exc, sqlite3.OperationalError) and "unable to open" in msg:
100
+ try:
101
+ _check_file(path)
102
+ except SourceError as err:
103
+ return err
104
+ return SourceError("permission_denied", "Permission denied reading UpNote data")
105
+ if "not a database" in msg or "malformed" in msg or "corrupt" in msg:
106
+ return SourceError("source_corrupt", "UpNote database is unreadable")
107
+ return SourceError("schema_unsupported", "UpNote database could not be read")
108
+
109
+
110
+ def _check_schema(con: sqlite3.Connection) -> None:
111
+ for table, columns in REQUIRED_COLUMNS.items():
112
+ info = { # name -> (declared type, primary-key position)
113
+ row[1]: (str(row[2]).strip().upper(), row[5])
114
+ for row in con.execute(f"PRAGMA table_info({table})") # noqa: S608 - fixed names
115
+ }
116
+ ok = all(name in info and info[name][0] == typ for name, typ in columns.items())
117
+ # the primary key must be exactly (id): a composite key would allow duplicate ids
118
+ only_id = ok and info["id"][1] == 1 and all(v[1] == 0 for k, v in info.items() if k != "id")
119
+ if not only_id:
120
+ raise SourceError("schema_unsupported", "UpNote database schema is not supported")
121
+
122
+
123
+ def _open_once(path: Path, busy_timeout_ms: int) -> sqlite3.Connection:
124
+ _check_file(path)
125
+ try:
126
+ uri = _readonly_uri(path)
127
+ except (OSError, ValueError, RuntimeError) as exc:
128
+ raise _from_os_error(exc) from None
129
+ con = sqlite3.connect(
130
+ uri,
131
+ uri=True,
132
+ timeout=busy_timeout_ms / 1000,
133
+ isolation_level=None, # we issue BEGIN/ROLLBACK ourselves
134
+ )
135
+ try:
136
+ con.execute(f"PRAGMA busy_timeout={int(busy_timeout_ms)}")
137
+ con.execute("PRAGMA query_only=ON")
138
+ con.execute("BEGIN") # deferred: the snapshot starts at the first read
139
+ _check_schema(con) # first read: pins the WAL snapshot for everything that follows
140
+ except BaseException:
141
+ con.close()
142
+ raise
143
+ return con
144
+
145
+
146
+ @contextmanager
147
+ def read_snapshot(
148
+ path: Path,
149
+ *,
150
+ busy_timeout_ms: int = DEFAULT_BUSY_TIMEOUT_MS,
151
+ retries: int = DEFAULT_RETRIES,
152
+ ) -> Iterator[sqlite3.Connection]:
153
+ """Yield a connection inside one read transaction. Raises ``SourceError`` only."""
154
+ con: sqlite3.Connection | None = None
155
+ for attempt in range(retries + 1):
156
+ try:
157
+ con = _open_once(path, busy_timeout_ms)
158
+ break
159
+ except SourceError as err:
160
+ if err.code != "busy" or attempt == retries:
161
+ raise
162
+ except sqlite3.Error as exc:
163
+ err = _map_error(exc, path)
164
+ if err.code != "busy" or attempt == retries:
165
+ raise err from None
166
+ time.sleep(_RETRY_SLEEP_S * (attempt + 1))
167
+ if con is None: # unreachable: the last attempt either connects or raises
168
+ raise SourceError("busy", "UpNote database is busy; try again")
169
+ try:
170
+ yield con
171
+ except sqlite3.Error as exc:
172
+ raise _map_error(exc, path) from None
173
+ finally:
174
+ with suppress(sqlite3.Error):
175
+ con.execute("ROLLBACK")
176
+ con.close()