Skip to content

"CLI-Anything: Making ALL Software Agent-Native" -- CLI-Hub: https://clianything.cc/

Python

Add Joplin CLI harness with tests and skill

杜新予02a1065d8d65
diff --git a/.gitignore b/.gitignore
index b17f6696e..3710efab5 100644
--- a/.gitignore
+++ b/.gitignore
@@ -83,6 +83,7 @@
!/QGIS/
!/n8n/
!/obsidian/
+!/joplin/
!/unrealinsights/
!/firefly-iii/
!/nsight-graphics/
@@ -175,6 +176,8 @@
/n8n/.*
/obsidian/*
/obsidian/.*
+/joplin/*
+/joplin/.*
/unrealinsights/*
/unrealinsights/.*
/nsight-graphics/*
@@ -236,6 +239,7 @@
!/QGIS/agent-harness/
!/n8n/agent-harness/
!/obsidian/agent-harness/
+!/joplin/agent-harness/
!/safari/
!/safari/agent-harness/
!/unrealinsights/agent-harness/
diff --git a/joplin/agent-harness/JOPLIN.md b/joplin/agent-harness/JOPLIN.md
new file mode 100644
index 000000000..c68f70894
--- /dev/null
+++ b/joplin/agent-harness/JOPLIN.md
@@ -0,0 +1,146 @@
+# JOPLIN Harness SOP
+
+## Overview
+
+`cli-anything-joplin` is a stateful CLI harness for Joplin automation backed by
+the real `joplin` terminal binary. It is intended for command-driven
+workflows, real-backend validation, and agent-style demo runs.
+
+## Requirements
+
+- Python 3.10+
+- Joplin terminal CLI installed and available in `PATH` as `joplin`
+- The harness package installed in editable mode for local development
+
+Verify the backend with:
+
+```bash
+where joplin # or `which joplin` on POSIX
+joplin help
+```
+
+## Install
+
+```bash
+cd joplin/agent-harness
+pip install -e .
+```
+
+## Usage
+
+```bash
+# REPL mode (default)
+cli-anything-joplin
+
+# One-shot command mode with JSON output
+cli-anything-joplin --json notebooks list
+
+# Use a project file
+cli-anything-joplin --project ./demo.joplin-harness.json notes create "hello"
+
+# Dry-run (no auto-save)
+cli-anything-joplin --json --dry-run --project ./demo.joplin-harness.json notes create temp
+```
+
+## Command groups
+
+- `project`: `new`, `open`, `save`, `info`, `json`, `status`
+- `notebooks`: `list`, `create`, `use`, `remove`
+- `notes`: `list`, `create`, `set`, `get`, `remove`, `copy`, `move`, `rename`
+- `todos`: `list`, `create`, `toggle`, `clear`, `done`, `undone`
+- `tags`: `list`, `add`, `remove`, `notetags`, `tagnotes`
+- `search`: `run`
+- `sync`: `run` (`--target`, `--upgrade`, `--use-lock`)
+- `interop`: `import`, `export`
+- `config`: `get`, `set`, `list`, `export`, `import-file`
+- `attach`: `add`
+- `status`: `show`, `restore`
+- `backend`: `version`, `dump`, `keymap`, `geoloc`, `export-sync-status`
+- `server`: `status`, `start`, `stop`
+- `e2ee`: `status`, `target-status`, `decrypt`, `decrypt-file`
+- `session`: `status`, `undo`, `redo`, `history`
+
+## State model
+
+The harness project is JSON-based and stores:
+
+- `name`
+- `created_at`, `updated_at`
+- backend settings such as `binary` and `profile`
+- user context such as `current_notebook`
+- `history` as an operations log
+
+The session keeps in-memory project state plus undo/redo snapshots.
+
+## Save behavior
+
+- One-shot mutating commands auto-save when a project is loaded.
+- `--dry-run` disables auto-save.
+- REPL mode does not auto-save; the user saves explicitly with `project save`.
+- Commands that should not produce an undo snapshot (e.g. `sync run`,
+ `interop export`) still mark the project dirty via `Session.mark_dirty()`
+ so the auto-save still persists their history entry.
+
+## JSON output contract
+
+When `--json` is enabled, commands return a stable envelope:
+
+- `ok`: boolean
+- `command`: command identifier such as `notes.list`, `todos.toggle`
+- `data`: command payload
+- `error`: `null` on success, or `{ type, message }` on failure
+
+## Testing strategy
+
+### 1. Unit / command tests (`test_core.py`)
+Validate harness internals and CLI contract without any backend.
+
+### 2. CLI subprocess tests (`TestCLISubprocess`)
+Run the installed `cli-anything-joplin` (or `python -m`) entry point and
+assert the externally visible JSON contract for non-mutating commands.
+
+### 3. Real-backend command tests (`TestBackendCommands`)
+Single-command checks against the real backend on a fresh profile.
+
+### 4. Real-backend workflow tests (`TestBackendWorkflows`)
+Short user-flow scripts covering note lifecycle, organization, todos,
+tagging, search (best-effort), sync, export, import, attach, history.
+
+### 5. End-to-end integration test (`TestBackendIntegration`)
+Full demo flow used for regression and agent demonstrations; verifies that
+the saved project history captures every action performed.
+
+### Test commands
+
+```bash
+python -m pytest -q cli_anything/joplin/tests/test_core.py
+python -m pytest -q cli_anything/joplin/tests/test_full_e2e.py::TestCLISubprocess
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendCommands
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendWorkflows
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendIntegration
+python -m pytest -v --tb=no cli_anything/joplin/tests
+```
+
+For real backend runs, ensure `joplin` is installed and available in `PATH`.
+
+## Development notes
+
+- Prefer adding new coverage as a small command test first.
+- Promote longer user journeys into workflow tests.
+- Keep exactly one full integration flow for demonstration and regression.
+- Preserve the JSON envelope and backend command naming conventions.
+- Prefer Joplin's native `--format json` for list-style commands when the
+ source command supports it (`ls` does; `tag list` does not).
+- New mutating commands should either call `sess.snapshot(reason)` (creates an
+ undo point) or `sess.mark_dirty()` (just marks the project as modified) so
+ auto-save still persists the appended history entry.
+
+## Known limitations
+
+- Some Joplin CLI builds reject `search` outside the REPL with
+ `"only available in GUI mode"`. The harness surfaces this as a normal
+ `ok=false` JSON envelope; agents should treat search as best-effort.
+- Non-ASCII process arguments on Windows pass through `joplin.cmd` → `cmd.exe`,
+ which truncates them to the active code page. Harness JSON state handles
+ unicode correctly; only argv-forwarded titles are affected. The unicode
+ workflow test is skipped on Windows.
diff --git a/joplin/agent-harness/README.md b/joplin/agent-harness/README.md
new file mode 100644
index 000000000..691a5ed34
--- /dev/null
+++ b/joplin/agent-harness/README.md
@@ -0,0 +1,67 @@
+# Joplin Agent Harness
+
+`cli-anything-joplin` is a stateful CLI harness for the Joplin terminal
+application. It wraps the real `joplin` binary for backend operations and is
+designed for agent-driven workflows, command validation, and end-to-end
+demonstrations.
+
+## What it does
+
+- wraps a Joplin project/session JSON state with undo/redo
+- exposes notebook, note, to-do, tag, search, sync, import/export, attachment,
+ status, config, backend utility, API server, and E2EE command groups
+- emits a stable JSON envelope (`ok`/`command`/`data`/`error`) for machine
+ parsing
+- supports one-shot mode and REPL mode
+- auto-saves the harness project on mutation; honors `--dry-run`
+
+## Requirements
+
+- Python 3.10+
+- Joplin terminal CLI installed and available in `PATH` as `joplin`
+
+## Usage
+
+```bash
+# REPL mode
+cli-anything-joplin
+
+# One-shot command mode
+cli-anything-joplin --json notebooks list
+
+# Use a saved project file
+cli-anything-joplin --project ./demo.joplin-harness.json notes create "hello"
+
+# Dry run (no auto-save)
+cli-anything-joplin --dry-run --project ./demo.joplin-harness.json todos create temp
+```
+
+## Command groups
+
+- `project`
+- `notebooks`
+- `notes`
+- `todos`
+- `tags`
+- `search`
+- `sync`
+- `interop`
+- `config`
+- `attach`
+- `status`
+- `backend`
+- `server`
+- `e2ee`
+- `session`
+
+## Test structure
+
+- pure unit + CLI-contract tests (no `joplin` binary required)
+- CLI subprocess smoke tests
+- isolated backend command tests
+- short backend workflow tests (note lifecycle, organization, todos, tags,
+ search, sync, export, import, attach, history)
+- one full end-to-end roundtrip
+
+See `cli_anything/joplin/tests/TEST.md` for the full plan and
+`cli_anything/joplin/WORKFLOWS.md` for the verified workflow inventory.
diff --git a/joplin/agent-harness/cli_anything/joplin/README.md b/joplin/agent-harness/cli_anything/joplin/README.md
new file mode 100644
index 000000000..b967b2219
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/README.md
@@ -0,0 +1,111 @@
+# cli-anything-joplin
+
+`cli-anything-joplin` is a stateful CLI harness that wraps the real `joplin` terminal
+binary, exposing every common Joplin workflow under a uniform JSON command envelope.
+
+It supports:
+
+- harness project state with undo/redo
+- notebook lifecycle (`list`, `create`, `use`, `remove`; list supports sort/reverse/long/json)
+- note lifecycle (`list`, `create`, `set`, `get`, `remove`, `copy`, `move`, `rename`; list supports sort/reverse/type/long/json)
+- to-do management (`create`, `toggle`, `clear`, `done`, `undone`, `list`)
+- tag management (`list`, `add`, `remove`, `notetags`, `tagnotes`)
+- search (best-effort; some Joplin CLI builds gate `search` behind GUI mode)
+- sync (`sync run`, including `--target`, `--upgrade`, `--use-lock`)
+- import / export (`jex`, `md`, `enex`, `raw`, `md_frontmatter`, plus import `--force` and `--output-format`)
+- attachments (`attach add`)
+- backend status and trash restore (`status show`, `status restore`)
+- config get/set/list/export/import-file
+- backend utilities (`version`, `dump`, `keymap`, `geoloc`, `export-sync-status`)
+- API server controls (`server status/start/stop`)
+- E2EE utilities (`status`, `target-status`, `decrypt`, `decrypt-file`)
+- session controls (`status`, `undo`, `redo`, `history`)
+- REPL mode and one-shot command mode
+
+## Requirements
+
+- Python 3.10+
+- Joplin terminal CLI installed and available in `PATH` as `joplin`
+- Optional: pass `--profile` to target a specific Joplin profile
+
+## Install
+
+```bash
+cd joplin/agent-harness
+pip install -e .
+```
+
+## Usage
+
+```bash
+# REPL mode (default)
+cli-anything-joplin
+
+# Machine-readable one-shot command
+cli-anything-joplin --json notebooks list
+
+# Stateful project
+cli-anything-joplin project new --name demo -o ./demo.joplin-harness.json
+cli-anything-joplin --project ./demo.joplin-harness.json notes create "Meeting note"
+
+# Dry run (no auto-save)
+cli-anything-joplin --json --dry-run --project ./demo.joplin-harness.json notes create temp
+```
+
+## JSON output contract
+
+When `--json` is enabled, every command returns:
+
+- `ok`: boolean
+- `command`: stable command identifier (e.g. `notes.list`, `todos.toggle`)
+- `data`: command payload
+- `error`: `null` on success, or `{ type, message }` on failure
+
+## Command groups
+
+- `project`: `new`, `open`, `save`, `info`, `json`, `status`
+- `notebooks`: `list`, `create`, `use`, `remove`
+- `notes`: `list`, `create`, `set`, `get`, `remove`, `copy`, `move`, `rename`
+- `todos`: `list`, `create`, `toggle`, `clear`, `done`, `undone`
+- `tags`: `list`, `add`, `remove`, `notetags`, `tagnotes`
+- `search`: `run`
+- `sync`: `run`
+- `interop`: `import`, `export`
+- `config`: `get`, `set`, `list`, `export`, `import-file`
+- `attach`: `add`
+- `status`: `show`, `restore`
+- `backend`: `version`, `dump`, `keymap`, `geoloc`, `export-sync-status`
+- `server`: `status`, `start`, `stop`
+- `e2ee`: `status`, `target-status`, `decrypt`, `decrypt-file`
+- `session`: `status`, `undo`, `redo`, `history`
+
+## Save behavior
+
+- One-shot mutating commands auto-save when a project is loaded.
+- `--dry-run` disables auto-save.
+- REPL mode does not auto-save; the user saves explicitly with `project save`.
+- Commands that don't deserve a dedicated undo snapshot (e.g. `sync run`,
+ `interop export`) still mark the project as dirty via `Session.mark_dirty()`
+ so that auto-save still captures the recorded history.
+
+## Test workflow
+
+```bash
+# Quick feedback loop
+python -m pytest -q cli_anything/joplin/tests/test_core.py
+python -m pytest -q cli_anything/joplin/tests/test_full_e2e.py::TestCLISubprocess
+
+# Real backend (requires joplin in PATH)
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendCommands
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendWorkflows
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendIntegration
+
+# Full suite
+python -m pytest -v --tb=no cli_anything/joplin/tests
+
+# Verify the installed console script (as opposed to `python -m`)
+CLI_ANYTHING_FORCE_INSTALLED=1 python -m pytest -v -s cli_anything/joplin/tests/test_full_e2e.py
+```
+
+See `cli_anything/joplin/tests/TEST.md` for the full test plan and
+`cli_anything/joplin/WORKFLOWS.md` for the verified workflow inventory.
diff --git a/joplin/agent-harness/cli_anything/joplin/WORKFLOWS.md b/joplin/agent-harness/cli_anything/joplin/WORKFLOWS.md
new file mode 100644
index 000000000..ccfa2f4b6
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/WORKFLOWS.md
@@ -0,0 +1,113 @@
+# Joplin Workflow Inventory
+
+This document enumerates the workflows that the `cli-anything-joplin` harness
+has implemented and verified. It is intended as the single source of truth for
+"what does this harness already cover?".
+
+## 1. Categories
+
+The harness covers 11 workflow categories:
+
+1. CLI surface — `--help`, every group's help, JSON envelope
+2. Project lifecycle — `new`, `open`, `info`, `json`, `save`, `status`,
+ `session status/undo/redo/history`
+3. Notebook lifecycle — `list`, `create`, `use`, `remove`
+4. Note lifecycle — `list`, `create`, `set`, `get`, `remove`
+5. Note organization — `copy`, `move`, `rename`
+6. To-do lifecycle — `create`, `list`, `toggle`, `clear`, `done`, `undone`
+7. Tag management — `list`, `add`, `remove`, `notetags`, `tagnotes`
+8. Search — `run` (best-effort; some Joplin CLI builds gate this behind GUI mode)
+9. Sync — `run` (verified with the default no-target configuration)
+10. Import / export — `import` (md, jex, enex, raw, html, …), `export`
+ (jex, md, raw, md_frontmatter)
+11. Attachments and status — `attach add`, `status show`, `status restore`
+12. Backend utilities — `version`, `dump`, `keymap`, `geoloc`,
+ `export-sync-status`, `server`, and `e2ee`
+
+## 2. Workflow points (real-backend)
+
+The real-backend `TestBackendWorkflows` class executes the following short
+scripts end-to-end:
+
+- **Note lifecycle** — create notebook → use → create note → rename via `set`
+ → get → remove note → remove notebook
+- **Note organization** — create source/target notebooks → create note → copy
+ to target → rename source → move renamed to target → list target → cleanup
+- **Todo lifecycle** — create todo → list → done → undone → toggle → clear →
+ cleanup
+- **Tagging** — create notebook/note → add tag → list tags → notetags →
+ tagnotes → remove tag → cleanup
+- **Search** — create notebook/note → search (tolerates GUI-mode rejection)
+ → cleanup
+- **Sync** — `sync run` returns a payload even when no target is configured
+- **Export** — JEX and Markdown for the same note set
+- **Import** — Markdown directory import into a fresh notebook
+- **Attach** — create notebook/note → attach a real text file → verbose get →
+ cleanup
+- **Unicode** — `notebooks create/use/notes create/remove` with CJK + Greek
+ characters (skipped on Windows due to `cmd.exe` codepage truncation)
+- **Session history persists** — three mutating commands → reload the saved
+ project → assert every action is present in `history`
+
+## 3. Full end-to-end integration
+
+`TestBackendIntegration.test_full_backend_roundtrip` runs the following phases
+in one process against a real Joplin profile, then verifies that the saved
+project history contains every expected action:
+
+1. Inspect project (status / info / session)
+2. Notebook setup (list, create main, create archive, use main)
+3. Note lifecycle (list, create, rename, get, copy to archive, create+move,
+ rename via `ren`)
+4. Todos (create, list, done, undone, toggle, clear)
+5. Tags (add primary, add secondary, list, notetags, tagnotes, remove)
+6. Attach (attach real file, verbose get)
+7. Status and config (`status show`, `config get sync.target`, `config list`)
+8. Sync (no-target no-op)
+9. Export (JEX + MD)
+10. Cleanup (remove note, remove notebooks, save, final status, session history)
+
+Expected history actions verified after save:
+
+```
+notebook.create, notebook.use, note.create, note.set, note.copy, note.move,
+note.rename, todo.create, todo.toggle, todo.done, todo.undone, todo.clear,
+tag.add, tag.remove, attach.add, interop.export, note.remove, notebook.remove
+```
+
+## 4. Test layering summary
+
+| Layer | File / class | Backend needed | Workflows |
+|--------------------------|--------------------------------------|----------------|-----------|
+| Unit + CLI contract | `test_core.py` | No | 65 tests |
+| CLI subprocess | `TestCLISubprocess` | No | 10 tests |
+| Real-backend commands | `TestBackendCommands` | Yes | 6 tests |
+| Real-backend workflows | `TestBackendWorkflows` | Yes | 11 tests |
+| End-to-end integration | `TestBackendIntegration` | Yes | 1 test |
+
+## 5. Adding a new workflow
+
+1. Add a thin core module under `cli_anything/joplin/core/`.
+2. Wire it into `joplin_cli.py` with a single Click command that:
+ - records `add_history(...)` on success
+ - calls either `sess.snapshot(reason)` (creates an undo point) or
+ `sess.mark_dirty()` (just marks dirty) so the auto-save fires.
+3. Add a unit test in `test_core.py` (argument shape + JSON envelope).
+4. Add a real-backend workflow test in `test_full_e2e.py` under
+ `TestBackendWorkflows`.
+5. If the workflow is large or demoable, extend
+ `TestBackendIntegration.test_full_backend_roundtrip`.
+
+## 6. Known limitations
+
+- `joplin search` is gated behind GUI mode on some Joplin CLI 3.x builds. The
+ search workflow accepts a clean `ok=false` JSON envelope with the original
+ error message.
+- Non-ASCII process arguments on Windows pass through `joplin.cmd` → `cmd.exe`,
+ which downgrades them to the active code page. The harness's JSON state
+ itself handles unicode correctly (see the unicode roundtrip in
+ `test_core.py`); only the argv path is affected. The unicode workflow test
+ is therefore skipped on Windows.
+- `joplin version` can fail in npm global layouts because the upstream command
+ looks for `../package.json`. `backend version` falls back to the installed
+ `node_modules/joplin/package.json` metadata.
diff --git a/joplin/agent-harness/cli_anything/joplin/__init__.py b/joplin/agent-harness/cli_anything/joplin/__init__.py
new file mode 100644
index 000000000..fed85b3ef
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/__init__.py
@@ -0,0 +1 @@
+"""cli_anything.joplin package."""
diff --git a/joplin/agent-harness/cli_anything/joplin/__main__.py b/joplin/agent-harness/cli_anything/joplin/__main__.py
new file mode 100644
index 000000000..e5121c23d
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/__main__.py
@@ -0,0 +1,4 @@
+from cli_anything.joplin.joplin_cli import main
+
+if __name__ == "__main__":
+ main()
diff --git a/joplin/agent-harness/cli_anything/joplin/core/__init__.py b/joplin/agent-harness/cli_anything/joplin/core/__init__.py
new file mode 100644
index 000000000..f41ce6dfe
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/__init__.py
@@ -0,0 +1 @@
+"""Core package for cli-anything-joplin."""
diff --git a/joplin/agent-harness/cli_anything/joplin/core/attach.py b/joplin/agent-harness/cli_anything/joplin/core/attach.py
new file mode 100644
index 000000000..5c9824795
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/attach.py
@@ -0,0 +1,5 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def attach_file(config: BackendConfig, note_ref: str, file_path: str) -> dict:
+ return run_joplin_command(["attach", note_ref, file_path], config, timeout=300)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/backend.py b/joplin/agent-harness/cli_anything/joplin/core/backend.py
new file mode 100644
index 000000000..d1e0aa034
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/backend.py
@@ -0,0 +1,99 @@
+import json
+from pathlib import Path
+
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, find_joplin, run_joplin_command, run_joplin_json
+
+
+def version_info(config: BackendConfig) -> dict:
+ try:
+ return run_joplin_command(["version"], config)
+ except RuntimeError as exc:
+ # Joplin 3.6.2's installed `command-version.js` may require
+ # `../package.json`, which is missing in npm -g layouts. Fall back to
+ # the package metadata next to the installed CLI.
+ if "package.json" not in str(exc):
+ raise
+
+ binary = Path(find_joplin(config.binary))
+ package_json = binary.parent / "node_modules" / "joplin" / "package.json"
+ if not package_json.exists():
+ raise
+ metadata = json.loads(package_json.read_text(encoding="utf-8"))
+ return {
+ "command": [str(binary), "version"],
+ "returncode": 0,
+ "stdout": metadata.get("version", ""),
+ "stderr": f"Fallback after broken Joplin version command: {exc}",
+ "metadata": {
+ "name": metadata.get("name"),
+ "version": metadata.get("version"),
+ "description": metadata.get("description"),
+ },
+ }
+
+
+def dump_database(config: BackendConfig) -> dict:
+ return run_joplin_json(["dump"], config, timeout=600)
+
+
+def keymap(config: BackendConfig) -> dict:
+ return run_joplin_command(["keymap"], config)
+
+
+def geoloc(config: BackendConfig, note_ref: str) -> dict:
+ return run_joplin_command(["geoloc", note_ref], config)
+
+
+def export_sync_status(config: BackendConfig) -> dict:
+ return run_joplin_command(["export-sync-status"], config, timeout=300)
+
+
+def server_status(config: BackendConfig) -> dict:
+ return run_joplin_command(["server", "status"], config)
+
+
+def server_start(config: BackendConfig, exit_early: bool = True, quiet: bool = False) -> dict:
+ args = ["server", "start"]
+ if exit_early:
+ args.append("--exit-early")
+ if quiet:
+ args.append("--quiet")
+ return run_joplin_command(args, config, timeout=300)
+
+
+def server_stop(config: BackendConfig) -> dict:
+ return run_joplin_command(["server", "stop"], config)
+
+
+def e2ee_status(config: BackendConfig) -> dict:
+ return run_joplin_command(["e2ee", "status"], config)
+
+
+def e2ee_target_status(config: BackendConfig, target_path: str, verbose: bool = False) -> dict:
+ args = ["e2ee", "target-status", target_path]
+ if verbose:
+ args.append("--verbose")
+ return run_joplin_command(args, config, timeout=300)
+
+
+def e2ee_decrypt(
+ config: BackendConfig,
+ encrypted_text: str | None = None,
+ retry_failed_items: bool = False,
+ force: bool = False,
+) -> dict:
+ args = ["e2ee", "decrypt"]
+ if encrypted_text:
+ args.append(encrypted_text)
+ if retry_failed_items:
+ args.append("--retry-failed-items")
+ if force:
+ args.append("--force")
+ return run_joplin_command(args, config, timeout=600)
+
+
+def e2ee_decrypt_file(config: BackendConfig, file_path: str, output_dir: str | None = None) -> dict:
+ args = ["e2ee", "decrypt-file", file_path]
+ if output_dir:
+ args += ["--output", output_dir]
+ return run_joplin_command(args, config, timeout=600)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/config.py b/joplin/agent-harness/cli_anything/joplin/core/config.py
new file mode 100644
index 000000000..7653f9cbb
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/config.py
@@ -0,0 +1,30 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def config_get(config: BackendConfig, key: str, verbose: bool = False) -> dict:
+ args = ["config", key]
+ if verbose:
+ args.append("--verbose")
+ return run_joplin_command(args, config)
+
+
+def config_set(config: BackendConfig, key: str, value: str) -> dict:
+ return run_joplin_command(["config", key, value], config)
+
+
+def config_list(config: BackendConfig, verbose: bool = False) -> dict:
+ args = ["config"]
+ if verbose:
+ args.append("--verbose")
+ return run_joplin_command(args, config)
+
+
+def config_export(config: BackendConfig, verbose: bool = False) -> dict:
+ args = ["config", "--export"]
+ if verbose:
+ args.append("--verbose")
+ return run_joplin_command(args, config)
+
+
+def config_import_file(config: BackendConfig, file_path: str) -> dict:
+ return run_joplin_command(["config", "--import-file", file_path], config)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/interop.py b/joplin/agent-harness/cli_anything/joplin/core/interop.py
new file mode 100644
index 000000000..452daa797
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/interop.py
@@ -0,0 +1,30 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def import_data(
+ config: BackendConfig,
+ path: str,
+ notebook: str | None = None,
+ fmt: str | None = None,
+ force: bool = False,
+ output_format: str | None = None,
+) -> dict:
+ args = ["import", path]
+ if notebook:
+ args.append(notebook)
+ if fmt:
+ args += ["--format", fmt]
+ if force:
+ args.append("--force")
+ if output_format:
+ args += ["--output-format", output_format]
+ return run_joplin_command(args, config, timeout=600)
+
+
+def export_data(config: BackendConfig, path: str, fmt: str = "jex", note: str | None = None, notebook: str | None = None) -> dict:
+ args = ["export", path, "--format", fmt]
+ if note:
+ args += ["--note", note]
+ if notebook:
+ args += ["--notebook", notebook]
+ return run_joplin_command(args, config, timeout=600)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/notebooks.py b/joplin/agent-harness/cli_anything/joplin/core/notebooks.py
new file mode 100644
index 000000000..692dcc16a
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/notebooks.py
@@ -0,0 +1,40 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command, run_joplin_json
+
+
+def list_notebooks(
+ config: BackendConfig,
+ limit: int | None = None,
+ sort: str | None = None,
+ reverse: bool = False,
+ long: bool = False,
+) -> dict:
+ args = ["ls", "/", "--format", "json"]
+ if limit:
+ args += ["--limit", str(limit)]
+ if sort:
+ args += ["--sort", sort]
+ if reverse:
+ args.append("--reverse")
+ if long:
+ args.append("--long")
+ return run_joplin_json(args, config)
+
+
+def create_notebook(config: BackendConfig, title: str, parent: str | None = None) -> dict:
+ args = ["mkbook", title]
+ if parent:
+ args += ["-p", parent]
+ return run_joplin_command(args, config)
+
+
+def use_notebook(config: BackendConfig, notebook: str) -> dict:
+ return run_joplin_command(["use", notebook], config)
+
+
+def remove_notebook(config: BackendConfig, notebook: str, force: bool = True, permanent: bool = False) -> dict:
+ args = ["rmbook", notebook]
+ if force:
+ args.append("-f")
+ if permanent:
+ args.append("-p")
+ return run_joplin_command(args, config)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/notes.py b/joplin/agent-harness/cli_anything/joplin/core/notes.py
new file mode 100644
index 000000000..179b62746
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/notes.py
@@ -0,0 +1,70 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command, run_joplin_json
+
+
+def list_notes(
+ config: BackendConfig,
+ pattern: str | None = None,
+ limit: int | None = None,
+ sort: str | None = None,
+ reverse: bool = False,
+ item_type: str | None = None,
+ long: bool = False,
+) -> dict:
+ args = ["ls"]
+ if pattern:
+ args.append(pattern)
+ if limit:
+ args += ["-n", str(limit)]
+ if sort:
+ args += ["--sort", sort]
+ if reverse:
+ args.append("--reverse")
+ if item_type:
+ args += ["--type", item_type]
+ if long:
+ args.append("--long")
+ args += ["--format", "json"]
+ return run_joplin_json(args, config)
+
+
+def create_note(config: BackendConfig, title: str) -> dict:
+ return run_joplin_command(["mknote", title], config)
+
+
+def set_note_field(config: BackendConfig, note_ref: str, field: str, value: str) -> dict:
+ return run_joplin_command(["set", note_ref, field, value], config)
+
+
+def get_note(config: BackendConfig, note_ref: str, verbose: bool = False) -> dict:
+ args = ["cat", note_ref]
+ if verbose:
+ args.append("-v")
+ return run_joplin_command(args, config)
+
+
+def remove_note(config: BackendConfig, note_ref: str, force: bool = True, permanent: bool = False) -> dict:
+ args = ["rmnote", note_ref]
+ if force:
+ args.append("-f")
+ if permanent:
+ args.append("-p")
+ return run_joplin_command(args, config)
+
+
+def copy_note(config: BackendConfig, note_ref: str, notebook: str | None = None) -> dict:
+ args = ["cp", note_ref]
+ if notebook:
+ args.append(notebook)
+ return run_joplin_command(args, config)
+
+
+def move_note(config: BackendConfig, item: str, notebook: str) -> dict:
+ return run_joplin_command(["mv", item, notebook], config)
+
+
+def rename_note(config: BackendConfig, item: str, new_name: str) -> dict:
+ return run_joplin_command(["ren", item, new_name], config)
+
+
+def duplicate_note(config: BackendConfig, note_ref: str, notebook: str | None = None) -> dict:
+ return copy_note(config, note_ref, notebook=notebook)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/project.py b/joplin/agent-harness/cli_anything/joplin/core/project.py
new file mode 100644
index 000000000..0aedab0c5
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/project.py
@@ -0,0 +1,65 @@
+from __future__ import annotations
+
+import json
+import os
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+
+def utc_now() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def create_project(name: str = "joplin-project", backend_binary: str = "joplin", backend_profile: Optional[str] = None) -> dict:
+ now = utc_now()
+ return {
+ "name": name,
+ "created_at": now,
+ "updated_at": now,
+ "backend": {
+ "binary": backend_binary,
+ "profile": backend_profile,
+ },
+ "context": {
+ "current_notebook": None,
+ },
+ "history": [],
+ }
+
+
+def open_project(path: str) -> dict:
+ with open(path, "r", encoding="utf-8") as f:
+ return json.load(f)
+
+
+def save_project(project: dict, path: str) -> str:
+ project["updated_at"] = utc_now()
+ parent = os.path.dirname(os.path.abspath(path))
+ if parent and not os.path.exists(parent):
+ os.makedirs(parent, exist_ok=True)
+ tmp_path = f"{path}.tmp"
+ with open(tmp_path, "w", encoding="utf-8") as f:
+ json.dump(project, f, indent=2, ensure_ascii=False)
+ os.replace(tmp_path, path)
+ return path
+
+
+def add_history(project: dict, action: str, payload: Optional[dict] = None) -> None:
+ project.setdefault("history", []).append(
+ {
+ "at": utc_now(),
+ "action": action,
+ "payload": payload or {},
+ }
+ )
+
+
+def project_info(project: dict) -> dict[str, Any]:
+ return {
+ "name": project.get("name"),
+ "created_at": project.get("created_at"),
+ "updated_at": project.get("updated_at"),
+ "backend": project.get("backend", {}),
+ "context": project.get("context", {}),
+ "history_count": len(project.get("history", [])),
+ }
diff --git a/joplin/agent-harness/cli_anything/joplin/core/search.py b/joplin/agent-harness/cli_anything/joplin/core/search.py
new file mode 100644
index 000000000..54cb90c77
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/search.py
@@ -0,0 +1,8 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def search(config: BackendConfig, pattern: str, notebook: str | None = None) -> dict:
+ args = ["search", pattern]
+ if notebook:
+ args.append(notebook)
+ return run_joplin_command(args, config)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/session.py b/joplin/agent-harness/cli_anything/joplin/core/session.py
new file mode 100644
index 000000000..bf1b5b217
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/session.py
@@ -0,0 +1,101 @@
+from __future__ import annotations
+
+import copy
+import json
+import os
+from dataclasses import dataclass, field
+from typing import Optional
+
+from cli_anything.joplin.core import project as project_mod
+
+
+@dataclass
+class Session:
+ project: Optional[dict] = None
+ project_path: Optional[str] = None
+ _modified: bool = False
+ _undo_stack: list[dict] = field(default_factory=list)
+ _redo_stack: list[dict] = field(default_factory=list)
+
+ def has_project(self) -> bool:
+ return self.project is not None
+
+ def set_project(self, project: dict, path: Optional[str] = None) -> None:
+ self.project = project
+ self.project_path = path
+ self._modified = False
+ self._undo_stack.clear()
+ self._redo_stack.clear()
+
+ def get_project(self) -> dict:
+ if not self.project:
+ raise RuntimeError("No project loaded")
+ return self.project
+
+ def snapshot(self, reason: str) -> None:
+ if not self.project:
+ raise RuntimeError("No project loaded")
+ self._undo_stack.append(copy.deepcopy(self.project))
+ self._redo_stack.clear()
+ self._modified = True
+ project_mod.add_history(self.project, "snapshot", {"reason": reason})
+
+ def mark_dirty(self) -> None:
+ """Mark the loaded project as modified without creating an undo snapshot.
+
+ Used by commands that should auto-save (e.g. sync, export) but should
+ not contribute to undo/redo depth.
+ """
+ if not self.project:
+ raise RuntimeError("No project loaded")
+ self._modified = True
+
+ def undo(self) -> dict:
+ if not self._undo_stack:
+ raise RuntimeError("Nothing to undo")
+ if self.project:
+ self._redo_stack.append(copy.deepcopy(self.project))
+ self.project = self._undo_stack.pop()
+ self._modified = True
+ return self.project
+
+ def redo(self) -> dict:
+ if not self._redo_stack:
+ raise RuntimeError("Nothing to redo")
+ if self.project:
+ self._undo_stack.append(copy.deepcopy(self.project))
+ self.project = self._redo_stack.pop()
+ self._modified = True
+ return self.project
+
+ def status(self) -> dict:
+ return {
+ "has_project": self.has_project(),
+ "project_path": self.project_path,
+ "modified": self._modified,
+ "undo_depth": len(self._undo_stack),
+ "redo_depth": len(self._redo_stack),
+ }
+
+ def _locked_save_json(self, path: str, data: dict) -> None:
+ lock_path = f"{path}.lock"
+ lock_fd = os.open(lock_path, os.O_CREAT | os.O_RDWR)
+ try:
+ tmp = f"{path}.tmp"
+ with open(tmp, "w", encoding="utf-8") as f:
+ json.dump(data, f, indent=2, ensure_ascii=False)
+ os.replace(tmp, path)
+ finally:
+ os.close(lock_fd)
+
+ def save_session(self, path: Optional[str] = None) -> str:
+ if not self.project:
+ raise RuntimeError("No project loaded")
+ target = path or self.project_path
+ if not target:
+ raise RuntimeError("No project path set")
+ self.project["updated_at"] = project_mod.utc_now()
+ self._locked_save_json(target, self.project)
+ self.project_path = target
+ self._modified = False
+ return target
diff --git a/joplin/agent-harness/cli_anything/joplin/core/status.py b/joplin/agent-harness/cli_anything/joplin/core/status.py
new file mode 100644
index 000000000..1dca514a3
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/status.py
@@ -0,0 +1,9 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def get_status(config: BackendConfig) -> dict:
+ return run_joplin_command(["status"], config)
+
+
+def restore_items(config: BackendConfig, pattern: str) -> dict:
+ return run_joplin_command(["restore", pattern], config)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/sync.py b/joplin/agent-harness/cli_anything/joplin/core/sync.py
new file mode 100644
index 000000000..0a5d8ecd3
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/sync.py
@@ -0,0 +1,17 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def run_sync(
+ config: BackendConfig,
+ target: str | None = None,
+ upgrade: bool = False,
+ use_lock: str | None = None,
+) -> dict:
+ args = ["sync"]
+ if target:
+ args += ["--target", target]
+ if upgrade:
+ args.append("--upgrade")
+ if use_lock is not None:
+ args += ["--use-lock", use_lock]
+ return run_joplin_command(args, config, timeout=600)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/tags.py b/joplin/agent-harness/cli_anything/joplin/core/tags.py
new file mode 100644
index 000000000..190b26de0
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/tags.py
@@ -0,0 +1,21 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command
+
+
+def list_tags(config: BackendConfig) -> dict:
+ return run_joplin_command(["tag", "list"], config)
+
+
+def add_tag(config: BackendConfig, tag: str, note: str) -> dict:
+ return run_joplin_command(["tag", "add", tag, note], config)
+
+
+def remove_tag(config: BackendConfig, tag: str, note: str) -> dict:
+ return run_joplin_command(["tag", "remove", tag, note], config)
+
+
+def note_tags(config: BackendConfig, note: str) -> dict:
+ return run_joplin_command(["tag", "notetags", note], config)
+
+
+def tag_notes(config: BackendConfig, tag: str) -> dict:
+ return run_joplin_command(["tag", "list", tag], config)
diff --git a/joplin/agent-harness/cli_anything/joplin/core/todos.py b/joplin/agent-harness/cli_anything/joplin/core/todos.py
new file mode 100644
index 000000000..747d0c8d5
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/core/todos.py
@@ -0,0 +1,40 @@
+from cli_anything.joplin.utils.joplin_backend import BackendConfig, run_joplin_command, run_joplin_json
+
+
+def create_todo(config: BackendConfig, title: str) -> dict:
+ return run_joplin_command(["mktodo", title], config)
+
+
+def toggle_todo(config: BackendConfig, pattern: str) -> dict:
+ return run_joplin_command(["todo", "toggle", pattern], config)
+
+
+def clear_todo(config: BackendConfig, pattern: str) -> dict:
+ return run_joplin_command(["todo", "clear", pattern], config)
+
+
+def mark_done(config: BackendConfig, note_ref: str) -> dict:
+ return run_joplin_command(["done", note_ref], config)
+
+
+def mark_undone(config: BackendConfig, note_ref: str) -> dict:
+ return run_joplin_command(["undone", note_ref], config)
+
+
+def list_todos(
+ config: BackendConfig,
+ limit: int | None = None,
+ sort: str | None = None,
+ reverse: bool = False,
+ long: bool = False,
+) -> dict:
+ args = ["ls", "--type", "t", "--format", "json"]
+ if limit:
+ args += ["-n", str(limit)]
+ if sort:
+ args += ["--sort", sort]
+ if reverse:
+ args.append("--reverse")
+ if long:
+ args.append("--long")
+ return run_joplin_json(args, config)
diff --git a/joplin/agent-harness/cli_anything/joplin/joplin_cli.py b/joplin/agent-harness/cli_anything/joplin/joplin_cli.py
new file mode 100644
index 000000000..2f46c4181
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/joplin_cli.py
@@ -0,0 +1,970 @@
+#!/usr/bin/env python3
+
+import json
+import os
+import shlex
+import sys
+from typing import Optional
+
+import click
+
+from cli_anything.joplin.core import attach as attach_mod
+from cli_anything.joplin.core import backend as backend_mod
+from cli_anything.joplin.core import config as config_mod
+from cli_anything.joplin.core import interop as interop_mod
+from cli_anything.joplin.core import notebooks as notebook_mod
+from cli_anything.joplin.core import notes as note_mod
+from cli_anything.joplin.core import project as project_mod
+from cli_anything.joplin.core import search as search_mod
+from cli_anything.joplin.core import status as status_mod
+from cli_anything.joplin.core import sync as sync_mod
+from cli_anything.joplin.core import tags as tag_mod
+from cli_anything.joplin.core import todos as todo_mod
+from cli_anything.joplin.core.session import Session
+from cli_anything.joplin.utils.joplin_backend import BackendConfig
+from cli_anything.joplin.utils.repl_skin import ReplSkin
+
+_session: Optional[Session] = None
+_json_output = False
+_repl_mode = False
+
+
+def get_session() -> Session:
+ global _session
+ if _session is None:
+ _session = Session()
+ return _session
+
+
+def _json_envelope(ok: bool, command: str, data=None, error: Exception | None = None):
+ payload = {
+ "ok": ok,
+ "command": command,
+ "data": data,
+ "error": None,
+ }
+ if error is not None:
+ payload["error"] = {
+ "type": type(error).__name__,
+ "message": str(error),
+ }
+ return payload
+
+
+def output(data, message: str = "", command: str = ""):
+ if _json_output:
+ click.echo(json.dumps(_json_envelope(True, command or "unknown", data=data), indent=2, ensure_ascii=False, default=str))
+ return
+
+ if message:
+ click.echo(message)
+ if isinstance(data, dict):
+ for k, v in data.items():
+ click.echo(f"{k}: {v}")
+ elif isinstance(data, list):
+ for item in data:
+ click.echo(item)
+ elif data is not None:
+ click.echo(data)
+
+
+def _emit_error(err: Exception, command: str = "unknown"):
+ if _json_output:
+ click.echo(json.dumps(_json_envelope(False, command, data=None, error=err), ensure_ascii=False))
+ else:
+ click.echo(f"Error: {err}", err=True)
+
+
+def handle_error(func):
+ def wrapper(*args, **kwargs):
+ try:
+ return func(*args, **kwargs)
+ except (RuntimeError, ValueError, FileNotFoundError, IndexError) as e:
+ _emit_error(e, command=func.__name__.replace("_", "."))
+ if not _repl_mode:
+ sys.exit(1)
+ wrapper.__name__ = func.__name__
+ wrapper.__doc__ = func.__doc__
+ return wrapper
+
+
+def _backend_config(binary: str, profile: Optional[str]) -> BackendConfig:
+ sess = get_session()
+ if sess.has_project():
+ proj = sess.get_project()
+ backend = proj.get("backend", {})
+ return BackendConfig(binary=binary or backend.get("binary", "joplin"), profile=profile if profile is not None else backend.get("profile"))
+ return BackendConfig(binary=binary, profile=profile)
+
+
[email protected](invoke_without_command=True)
[email protected]("--json", "use_json", is_flag=True, help="Output as JSON")
[email protected]("--project", "project_path", type=str, default=None, help="Harness project JSON path")
[email protected]("--binary", type=str, default="joplin", help="Joplin CLI binary name/path")
[email protected]("--profile", type=str, default=None, help="Joplin profile path")
[email protected]("--dry-run", "dry_run", is_flag=True, default=False, help="Run command without saving harness project")
+def cli(ctx, use_json, project_path, binary, profile, dry_run):
+ """cli-anything-joplin - Stateful Joplin harness CLI."""
+ global _json_output
+ _json_output = use_json
+
+ sess = get_session()
+
+ if project_path:
+ if not sess.has_project() and os.path.exists(project_path):
+ proj = project_mod.open_project(project_path)
+ sess.set_project(proj, project_path)
+
+ ctx.ensure_object(dict)
+ ctx.obj["binary"] = binary
+ ctx.obj["profile"] = profile
+ ctx.obj["dry_run"] = dry_run
+
+ if ctx.invoked_subcommand is None:
+ ctx.invoke(repl)
+
+
+def auto_save_on_exit(result, use_json, project_path, binary, profile, dry_run, **kwargs):
+ if _repl_mode:
+ return
+ if dry_run:
+ return
+ sess = get_session()
+ if sess.has_project() and sess._modified and sess.project_path:
+ try:
+ sess.save_session()
+ except Exception as e:
+ click.echo(f"Warning: Auto-save failed: {e}", err=True)
+
+
+def project():
+ """Project management commands."""
+
+
[email protected]("--name", "name", default="joplin-project", help="Project name")
[email protected]("--output", "output_path", "-o", required=False, help="Output path")
+@handle_error
+def project_new(ctx, name, output_path):
+ proj = project_mod.create_project(name=name, backend_binary=ctx.obj["binary"], backend_profile=ctx.obj["profile"])
+ sess = get_session()
+ sess.set_project(proj, output_path)
+ if output_path:
+ sess.save_session(output_path)
+ output(project_mod.project_info(proj), f"Created project: {name}", command="project.new")
+
+
+@handle_error
+def project_open(path):
+ proj = project_mod.open_project(path)
+ sess = get_session()
+ sess.set_project(proj, path)
+ output(project_mod.project_info(proj), f"Opened: {path}", command="project.open")
+
+
[email protected]("path", required=False)
+@handle_error
+def project_save(path):
+ sess = get_session()
+ saved = sess.save_session(path)
+ output({"saved": saved}, f"Saved project: {saved}", command="project.save")
+
+
+@handle_error
+def project_info():
+ sess = get_session()
+ output(project_mod.project_info(sess.get_project()), command="project.info")
+
+
+@handle_error
+def project_json():
+ sess = get_session()
+ output(sess.get_project(), command="project.json")
+
+
+@handle_error
+def project_status():
+ sess = get_session()
+ proj = sess.get_project()
+ output(
+ {
+ "project": project_mod.project_info(proj),
+ "project_path": sess.project_path,
+ "session": sess.status(),
+ },
+ command="project.status",
+ )
+
+
[email protected]("notebooks")
+def notebooks_group():
+ """Notebook commands."""
+
+
+@notebooks_group.command("list")
[email protected]("--limit", "limit", type=int, default=None)
[email protected]("--sort", "sort", default=None)
[email protected]("--reverse", is_flag=True, default=False)
[email protected]("--long", "long", is_flag=True, default=False)
+@handle_error
+def notebooks_list(ctx, limit, sort, reverse, long):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = notebook_mod.list_notebooks(cfg, limit=limit, sort=sort, reverse=reverse, long=long)
+ output(result.get("data", result), command="notebooks.list")
+
+
+@notebooks_group.command("create")
[email protected]("--parent", "parent", default=None)
+@handle_error
+def notebooks_create(ctx, title, parent):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = notebook_mod.create_notebook(cfg, title=title, parent=parent)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Create notebook: {title}")
+ project_mod.add_history(sess.get_project(), "notebook.create", {"title": title, "parent": parent})
+ output(result, f"Created notebook: {title}", command="notebooks.create")
+
+
+@notebooks_group.command("use")
[email protected]("notebook")
+@handle_error
+def notebooks_use(ctx, notebook):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = notebook_mod.use_notebook(cfg, notebook=notebook)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Use notebook: {notebook}")
+ sess.get_project().setdefault("context", {})["current_notebook"] = notebook
+ project_mod.add_history(sess.get_project(), "notebook.use", {"notebook": notebook})
+ output(result, f"Switched notebook: {notebook}", command="notebooks.use")
+
+
+@notebooks_group.command("remove")
[email protected]("notebook")
[email protected]("--force/--no-force", default=True)
[email protected]("--permanent", is_flag=True, default=False)
+@handle_error
+def notebooks_remove(ctx, notebook, force, permanent):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = notebook_mod.remove_notebook(cfg, notebook, force=force, permanent=permanent)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Remove notebook: {notebook}")
+ project_mod.add_history(sess.get_project(), "notebook.remove", {"notebook": notebook, "permanent": permanent})
+ output(result, f"Removed notebook: {notebook}", command="notebooks.remove")
+
+
+def notes_group():
+ """Note commands."""
+
+
+@notes_group.command("list")
[email protected]("--pattern", "pattern", default=None)
[email protected]("--limit", "limit", type=int, default=None)
[email protected]("--sort", "sort", default=None)
[email protected]("--reverse", is_flag=True, default=False)
[email protected]("--type", "item_type", default=None, help="Joplin item type filter: n, t, or nt")
[email protected]("--long", "long", is_flag=True, default=False)
+@handle_error
+def notes_list(ctx, pattern, limit, sort, reverse, item_type, long):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.list_notes(
+ cfg,
+ pattern=pattern,
+ limit=limit,
+ sort=sort,
+ reverse=reverse,
+ item_type=item_type,
+ long=long,
+ )
+ output(result.get("data", result), command="notes.list")
+
+
+@notes_group.command("create")
+@handle_error
+def notes_create(ctx, title):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.create_note(cfg, title)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Create note: {title}")
+ project_mod.add_history(sess.get_project(), "note.create", {"title": title})
+ output(result, f"Created note: {title}", command="notes.create")
+
+
+@notes_group.command("set")
[email protected]("note_ref")
+@handle_error
+def notes_set(ctx, note_ref, field, value):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.set_note_field(cfg, note_ref, field, value)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Set note field {field}")
+ project_mod.add_history(sess.get_project(), "note.set", {"note": note_ref, "field": field})
+ output(result, f"Updated note: {note_ref}", command="notes.set")
+
+
+@notes_group.command("get")
[email protected]("note_ref")
[email protected]("--verbose", "-v", is_flag=True, default=False)
+@handle_error
+def notes_get(ctx, note_ref, verbose):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.get_note(cfg, note_ref, verbose=verbose)
+ output(result, command="notes.get")
+
+
+@notes_group.command("remove")
[email protected]("note_ref")
[email protected]("--force/--no-force", default=True)
[email protected]("--permanent", is_flag=True, default=False)
+@handle_error
+def notes_remove(ctx, note_ref, force, permanent):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.remove_note(cfg, note_ref, force=force, permanent=permanent)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Remove note: {note_ref}")
+ project_mod.add_history(sess.get_project(), "note.remove", {"note": note_ref, "permanent": permanent})
+ output(result, f"Removed note: {note_ref}", command="notes.remove")
+
+
+@notes_group.command("copy")
[email protected]("note_ref")
[email protected]("notebook", required=False)
+@handle_error
+def notes_copy(ctx, note_ref, notebook):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.copy_note(cfg, note_ref, notebook=notebook)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Copy note: {note_ref}")
+ project_mod.add_history(sess.get_project(), "note.copy", {"note": note_ref, "notebook": notebook})
+ output(result, f"Copied note: {note_ref}", command="notes.copy")
+
+
+@notes_group.command("move")
[email protected]("notebook")
+@handle_error
+def notes_move(ctx, item, notebook):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.move_note(cfg, item, notebook)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Move note: {item}")
+ project_mod.add_history(sess.get_project(), "note.move", {"item": item, "notebook": notebook})
+ output(result, f"Moved {item} to {notebook}", command="notes.move")
+
+
+@notes_group.command("rename")
[email protected]("new_name")
+@handle_error
+def notes_rename(ctx, item, new_name):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = note_mod.rename_note(cfg, item, new_name)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Rename {item} -> {new_name}")
+ project_mod.add_history(sess.get_project(), "note.rename", {"item": item, "new_name": new_name})
+ output(result, f"Renamed {item} -> {new_name}", command="notes.rename")
+
+
+def todos_group():
+ """To-do commands."""
+
+
+@todos_group.command("list")
[email protected]("--limit", "limit", type=int, default=None)
[email protected]("--sort", "sort", default=None)
[email protected]("--reverse", is_flag=True, default=False)
[email protected]("--long", "long", is_flag=True, default=False)
+@handle_error
+def todos_list(ctx, limit, sort, reverse, long):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.list_todos(cfg, limit=limit, sort=sort, reverse=reverse, long=long)
+ output(result.get("data", result), command="todos.list")
+
+
+@todos_group.command("create")
+@handle_error
+def todos_create(ctx, title):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.create_todo(cfg, title)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Create todo: {title}")
+ project_mod.add_history(sess.get_project(), "todo.create", {"title": title})
+ output(result, f"Created todo: {title}", command="todos.create")
+
+
+@todos_group.command("toggle")
+@handle_error
+def todos_toggle(ctx, pattern):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.toggle_todo(cfg, pattern)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Toggle todo: {pattern}")
+ project_mod.add_history(sess.get_project(), "todo.toggle", {"pattern": pattern})
+ output(result, f"Toggled todo: {pattern}", command="todos.toggle")
+
+
+@todos_group.command("clear")
+@handle_error
+def todos_clear(ctx, pattern):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.clear_todo(cfg, pattern)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Clear todo: {pattern}")
+ project_mod.add_history(sess.get_project(), "todo.clear", {"pattern": pattern})
+ output(result, f"Cleared todo: {pattern}", command="todos.clear")
+
+
+@todos_group.command("done")
[email protected]("note_ref")
+@handle_error
+def todos_done(ctx, note_ref):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.mark_done(cfg, note_ref)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Mark done: {note_ref}")
+ project_mod.add_history(sess.get_project(), "todo.done", {"note": note_ref})
+ output(result, f"Marked done: {note_ref}", command="todos.done")
+
+
+@todos_group.command("undone")
[email protected]("note_ref")
+@handle_error
+def todos_undone(ctx, note_ref):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = todo_mod.mark_undone(cfg, note_ref)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Mark undone: {note_ref}")
+ project_mod.add_history(sess.get_project(), "todo.undone", {"note": note_ref})
+ output(result, f"Marked undone: {note_ref}", command="todos.undone")
+
+
+def tags_group():
+ """Tag commands."""
+
+
+@tags_group.command("list")
+@handle_error
+def tags_list(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(tag_mod.list_tags(cfg), command="tags.list")
+
+
+@tags_group.command("add")
+@handle_error
+def tags_add(ctx, tag, note):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = tag_mod.add_tag(cfg, tag, note)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Add tag: {tag}")
+ project_mod.add_history(sess.get_project(), "tag.add", {"tag": tag, "note": note})
+ output(result, f"Added tag '{tag}' to {note}", command="tags.add")
+
+
+@tags_group.command("remove")
+@handle_error
+def tags_remove(ctx, tag, note):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = tag_mod.remove_tag(cfg, tag, note)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Remove tag: {tag}")
+ project_mod.add_history(sess.get_project(), "tag.remove", {"tag": tag, "note": note})
+ output(result, f"Removed tag '{tag}' from {note}", command="tags.remove")
+
+
+@tags_group.command("notetags")
+@handle_error
+def tags_notetags(ctx, note):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(tag_mod.note_tags(cfg, note), command="tags.notetags")
+
+
+@tags_group.command("tagnotes")
+@handle_error
+def tags_tagnotes(ctx, tag):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(tag_mod.tag_notes(cfg, tag), command="tags.tagnotes")
+
+
+def search_group():
+ """Search commands."""
+
+
+@search_group.command("run")
[email protected]("--notebook", "notebook", default=None)
+@handle_error
+def search_run(ctx, pattern, notebook):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(search_mod.search(cfg, pattern, notebook=notebook), command="search.run")
+
+
+def sync_group():
+ """Sync commands."""
+
+
+@sync_group.command("run")
[email protected]("--target", "target", default=None)
[email protected]("--upgrade", is_flag=True, default=False)
[email protected]("--use-lock", "use_lock", default=None)
+@handle_error
+def sync_run(ctx, target, upgrade, use_lock):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = sync_mod.run_sync(cfg, target=target, upgrade=upgrade, use_lock=use_lock)
+ sess = get_session()
+ if sess.has_project():
+ project_mod.add_history(sess.get_project(), "sync.run", {"target": target, "upgrade": upgrade, "use_lock": use_lock})
+ sess.mark_dirty()
+ output(result, "Sync completed", command="sync.run")
+
+
+def interop_group():
+ """Import/export commands."""
+
+
+@interop_group.command("import")
[email protected]("--notebook", "notebook", default=None)
[email protected]("--format", "fmt", default=None)
[email protected]("--force", is_flag=True, default=False)
[email protected]("--output-format", "output_format", default=None)
+@handle_error
+def interop_import(ctx, path, notebook, fmt, force, output_format):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = interop_mod.import_data(cfg, path, notebook=notebook, fmt=fmt, force=force, output_format=output_format)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Import: {path}")
+ project_mod.add_history(
+ sess.get_project(),
+ "interop.import",
+ {"path": path, "format": fmt, "force": force, "output_format": output_format},
+ )
+ output(result, f"Imported: {path}", command="interop.import")
+
+
+@interop_group.command("export")
[email protected]("--format", "fmt", default="jex")
[email protected]("--note", "note", default=None)
[email protected]("--notebook", "notebook", default=None)
+@handle_error
+def interop_export(ctx, path, fmt, note, notebook):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = interop_mod.export_data(cfg, path, fmt=fmt, note=note, notebook=notebook)
+ sess = get_session()
+ if sess.has_project():
+ project_mod.add_history(sess.get_project(), "interop.export", {"path": path, "format": fmt})
+ sess.mark_dirty()
+ output(result, f"Exported: {path}", command="interop.export")
+
+
+def config_group():
+ """Joplin config commands."""
+
+
+@config_group.command("get")
[email protected]("--verbose", "-v", is_flag=True, default=False)
+@handle_error
+def config_get(ctx, key, verbose):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(config_mod.config_get(cfg, key, verbose=verbose), command="config.get")
+
+
+@config_group.command("set")
+@handle_error
+def config_set(ctx, key, value):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = config_mod.config_set(cfg, key, value)
+ output(result, command="config.set")
+
+
+@config_group.command("list")
[email protected]("--verbose", "-v", is_flag=True, default=False)
+@handle_error
+def config_list(ctx, verbose):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(config_mod.config_list(cfg, verbose=verbose), command="config.list")
+
+
+@config_group.command("export")
[email protected]("--verbose", "-v", is_flag=True, default=False)
+@handle_error
+def config_export(ctx, verbose):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(config_mod.config_export(cfg, verbose=verbose), command="config.export")
+
+
+@config_group.command("import-file")
[email protected]("file_path")
+@handle_error
+def config_import_file(ctx, file_path):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = config_mod.config_import_file(cfg, file_path)
+ sess = get_session()
+ if sess.has_project():
+ project_mod.add_history(sess.get_project(), "config.import_file", {"file": file_path})
+ sess.mark_dirty()
+ output(result, command="config.import_file")
+
+
+def attach_group():
+ """Attachment commands."""
+
+
+@attach_group.command("add")
[email protected]("note_ref")
[email protected]("file_path")
+@handle_error
+def attach_add(ctx, note_ref, file_path):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = attach_mod.attach_file(cfg, note_ref, file_path)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Attach file to: {note_ref}")
+ project_mod.add_history(sess.get_project(), "attach.add", {"note": note_ref, "file": file_path})
+ output(result, f"Attached {file_path} to {note_ref}", command="attach.add")
+
+
+def status_group():
+ """Backend status commands."""
+
+
+@status_group.command("show")
+@handle_error
+def status_show(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(status_mod.get_status(cfg), command="status.show")
+
+
+@status_group.command("restore")
+@handle_error
+def status_restore(ctx, pattern):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = status_mod.restore_items(cfg, pattern)
+ sess = get_session()
+ if sess.has_project():
+ sess.snapshot(f"Restore: {pattern}")
+ project_mod.add_history(sess.get_project(), "status.restore", {"pattern": pattern})
+ output(result, f"Restored: {pattern}", command="status.restore")
+
+
+def backend_group():
+ """Backend utility commands."""
+
+
+@backend_group.command("version")
+@handle_error
+def backend_version(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.version_info(cfg), command="backend.version")
+
+
+@backend_group.command("dump")
+@handle_error
+def backend_dump(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.dump_database(cfg), command="backend.dump")
+
+
+@backend_group.command("keymap")
+@handle_error
+def backend_keymap(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.keymap(cfg), command="backend.keymap")
+
+
+@backend_group.command("geoloc")
[email protected]("note_ref")
+@handle_error
+def backend_geoloc(ctx, note_ref):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.geoloc(cfg, note_ref), command="backend.geoloc")
+
+
+@backend_group.command("export-sync-status")
+@handle_error
+def backend_export_sync_status(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.export_sync_status(cfg), command="backend.export_sync_status")
+
+
+def server_group():
+ """Joplin API server commands."""
+
+
+@server_group.command("status")
+@handle_error
+def server_status(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.server_status(cfg), command="server.status")
+
+
+@server_group.command("start")
[email protected]("--exit-early/--wait", default=True, help="Return after starting instead of waiting forever")
[email protected]("--quiet", is_flag=True, default=False)
+@handle_error
+def server_start(ctx, exit_early, quiet):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = backend_mod.server_start(cfg, exit_early=exit_early, quiet=quiet)
+ sess = get_session()
+ if sess.has_project():
+ project_mod.add_history(sess.get_project(), "server.start", {"exit_early": exit_early, "quiet": quiet})
+ sess.mark_dirty()
+ output(result, command="server.start")
+
+
+@server_group.command("stop")
+@handle_error
+def server_stop(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ result = backend_mod.server_stop(cfg)
+ sess = get_session()
+ if sess.has_project():
+ project_mod.add_history(sess.get_project(), "server.stop")
+ sess.mark_dirty()
+ output(result, command="server.stop")
+
+
+def e2ee_group():
+ """Joplin E2EE commands."""
+
+
+@e2ee_group.command("status")
+@handle_error
+def e2ee_status(ctx):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.e2ee_status(cfg), command="e2ee.status")
+
+
+@e2ee_group.command("target-status")
[email protected]("target_path")
[email protected]("--verbose", "-v", is_flag=True, default=False)
+@handle_error
+def e2ee_target_status(ctx, target_path, verbose):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.e2ee_target_status(cfg, target_path, verbose=verbose), command="e2ee.target_status")
+
+
+@e2ee_group.command("decrypt")
[email protected]("encrypted_text", required=False)
[email protected]("--retry-failed-items", is_flag=True, default=False)
[email protected]("--force", is_flag=True, default=False)
+@handle_error
+def e2ee_decrypt(ctx, encrypted_text, retry_failed_items, force):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(
+ backend_mod.e2ee_decrypt(
+ cfg,
+ encrypted_text=encrypted_text,
+ retry_failed_items=retry_failed_items,
+ force=force,
+ ),
+ command="e2ee.decrypt",
+ )
+
+
+@e2ee_group.command("decrypt-file")
[email protected]("file_path")
[email protected]("--output", "output_dir", default=None)
+@handle_error
+def e2ee_decrypt_file(ctx, file_path, output_dir):
+ cfg = _backend_config(ctx.obj["binary"], ctx.obj["profile"])
+ output(backend_mod.e2ee_decrypt_file(cfg, file_path, output_dir=output_dir), command="e2ee.decrypt_file")
+
+
+def session_group():
+ """Session commands."""
+
+
+@session_group.command("status")
+@handle_error
+def session_status():
+ output(get_session().status(), command="session.status")
+
+
+@session_group.command("undo")
+@handle_error
+def session_undo():
+ sess = get_session()
+ sess.undo()
+ output(sess.status(), "Undo complete", command="session.undo")
+
+
+@session_group.command("redo")
+@handle_error
+def session_redo():
+ sess = get_session()
+ sess.redo()
+ output(sess.status(), "Redo complete", command="session.redo")
+
+
+@session_group.command("history")
+@handle_error
+def session_history():
+ sess = get_session()
+ proj = sess.get_project()
+ output(proj.get("history", []), command="session.history")
+
+
[email protected](hidden=True)
+def repl(ctx):
+ global _repl_mode
+ _repl_mode = True
+
+ skin = ReplSkin("joplin", version="1.0.0")
+ skin.print_banner()
+ skin.info("Type 'help' to list commands, 'exit' to quit.")
+
+ pt_session = skin.create_prompt_session()
+
+ while True:
+ try:
+ line = skin.get_input(pt_session, project_name="joplin-harness", modified=get_session()._modified)
+ except (EOFError, KeyboardInterrupt):
+ break
+
+ line = line.strip()
+ if not line:
+ continue
+ if line in ("exit", "quit"):
+ break
+ if line == "help":
+ skin.help({
+ "project new/open/save/info/json/status": "Harness project management",
+ "notebooks list/create/use/remove": "Notebook operations",
+ "notes list/create/set/get/remove/copy/move/rename": "Note operations",
+ "todos list/create/toggle/clear/done/undone": "To-do operations",
+ "tags list/add/remove/notetags/tagnotes": "Tag operations",
+ "search run": "Search notes",
+ "sync run": "Run sync",
+ "interop import/export": "Import and export",
+ "config get/set/list/export/import-file": "Joplin config",
+ "attach add": "Attach file to note",
+ "status show/restore": "Backend status and trash restore",
+ "backend version/dump/keymap/geoloc/export-sync-status": "Backend utilities",
+ "server status/start/stop": "Joplin API server",
+ "e2ee status/target-status/decrypt/decrypt-file": "Encryption utilities",
+ "session status/undo/redo/history": "Session controls",
+ })
+ continue
+
+ try:
+ args = shlex.split(line)
+ cli.main(args=args, obj=dict(ctx.obj), standalone_mode=False)
+ except click.exceptions.UsageError as e:
+ skin.error(str(e))
+ except Exception as e:
+ skin.error(str(e))
+
+ skin.print_goodbye()
+
+
+def main():
+ cli(obj={})
+
+
+if __name__ == "__main__":
+ main()
diff --git a/joplin/agent-harness/cli_anything/joplin/skills/SKILL.md b/joplin/agent-harness/cli_anything/joplin/skills/SKILL.md
new file mode 100644
index 000000000..193ad0b96
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/skills/SKILL.md
@@ -0,0 +1,97 @@
+---
+name: "cli-anything-joplin"
+description: "Command-line interface for Joplin workflows using the real joplin terminal backend"
+---
+
+# cli-anything-joplin
+
+Use this skill to automate Joplin notebook, note, to-do, tag, attachment,
+search, sync, and import/export workflows through a stateful harness backed by
+the real `joplin` terminal binary.
+
+## Requirements
+
+- Python 3.10+
+- Joplin terminal binary available as `joplin`
+- Optional: pass `--profile` to target a specific Joplin profile
+
+## Install
+
+```bash
+cd joplin/agent-harness
+pip install -e .
+```
+
+## Usage
+
+```bash
+# REPL mode (default)
+cli-anything-joplin
+
+# Machine-readable one-shot command
+cli-anything-joplin --json notebooks list
+
+# Stateful project
+cli-anything-joplin project new --name demo -o ./demo.joplin-harness.json
+cli-anything-joplin --project ./demo.joplin-harness.json notes create "Meeting note"
+
+# Dry-run (no auto-save)
+cli-anything-joplin --json --dry-run --project ./demo.joplin-harness.json notes create temp
+```
+
+## JSON output contract
+
+When `--json` is enabled, commands return:
+
+- `ok`: boolean
+- `command`: stable command identifier such as `notes.list`, `todos.toggle`
+- `data`: command payload
+- `error`: null on success, or `{ type, message }` on failure
+
+## Command groups
+
+- `project`: `new`, `open`, `save`, `info`, `json`, `status`
+- `notebooks`: `list`, `create`, `use`, `remove`
+- `notes`: `list`, `create`, `set`, `get`, `remove`, `copy`, `move`, `rename`
+- `todos`: `list`, `create`, `toggle`, `clear`, `done`, `undone`
+- `tags`: `list`, `add`, `remove`, `notetags`, `tagnotes`
+- `search`: `run`
+- `sync`: `run` (`--target`, `--upgrade`, `--use-lock`)
+- `interop`: `import`, `export`
+- `config`: `get`, `set`, `list`, `export`, `import-file`
+- `attach`: `add`
+- `status`: `show`, `restore`
+- `backend`: `version`, `dump`, `keymap`, `geoloc`, `export-sync-status`
+- `server`: `status`, `start`, `stop`
+- `e2ee`: `status`, `target-status`, `decrypt`, `decrypt-file`
+- `session`: `status`, `undo`, `redo`, `history`
+
+## Agent guidance
+
+- Prefer `--json` for parseable output.
+- Use `--project` when running multi-step workflows so history is persisted.
+- One-shot mutating commands auto-save the project unless `--dry-run` is set.
+- REPL mode does not auto-save; run `project save` explicitly.
+- Some Joplin CLI builds gate `search` behind GUI mode; if you see
+ `"only available in GUI mode"`, treat search as best-effort.
+- Joplin 3.6.x can have a broken `version` command in npm global layouts; the
+ harness falls back to the installed package metadata for `backend version`.
+
+## Test workflow
+
+```bash
+# Quick feedback loop
+python -m pytest -q cli_anything/joplin/tests/test_core.py
+python -m pytest -q cli_anything/joplin/tests/test_full_e2e.py::TestCLISubprocess
+
+# Real backend (joplin must be in PATH)
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendCommands
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendWorkflows
+python -m pytest -v cli_anything/joplin/tests/test_full_e2e.py::TestBackendIntegration
+
+# Full suite
+python -m pytest -v --tb=no cli_anything/joplin/tests
+
+# Verify the installed console script entry point
+CLI_ANYTHING_FORCE_INSTALLED=1 python -m pytest -v -s cli_anything/joplin/tests/test_full_e2e.py
+```
diff --git a/joplin/agent-harness/cli_anything/joplin/tests/TEST.md b/joplin/agent-harness/cli_anything/joplin/tests/TEST.md
new file mode 100644
index 000000000..5f876055a
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/tests/TEST.md
@@ -0,0 +1,133 @@
+# Test Plan — cli-anything-joplin
+
+The suite has two files:
+
+- `test_core.py` — pure unit + CLI-contract tests (no `joplin` binary required)
+- `test_full_e2e.py` — CLI subprocess tests + real-backend workflows + full
+ end-to-end roundtrip
+
+Real-backend classes are skipped automatically when `joplin` is not on `PATH`.
+
+## test_core.py (65 tests)
+
+Pure Python tests covering the harness surface. Safe to run anywhere without
+a Joplin backend.
+
+Coverage areas:
+
+- Project schema, save/open roundtrip, unicode roundtrip, history shape
+- Session lifecycle: set/get, snapshot, undo, redo, undo→redo chain,
+ redo cleared on new snapshot, save/save-without-path, `mark_dirty`
+- Backend runner: `find_joplin`, profile/no-profile invocation, error path,
+ benign Node punycode warning passthrough, timeout, JSON parse fallback,
+ empty stdout
+- Core module argument shapes for: notes (cp/mv/ren/remove/get verbose),
+ notebooks (rmbook flags), todos (mktodo/toggle/clear/done/undone), tags
+ (tagnotes via `tag list`)
+- JSON envelope shape (success + error)
+- JSON contract per command group: notebooks, notes, todos, tags, search,
+ sync, interop, config, session, attach, status, backend, server, e2ee
+- Cross-group full workflow scripted against the mocked backend
+- Error contract: search failure, missing note, missing backend, invalid
+ export format
+- `project status` and `project save` errors when no project is loaded
+- Auto-save behavior: mutation auto-saves; `--dry-run` suppresses save
+- Todo and notebook-remove flows write the expected history actions
+- `session save` keeps undo/redo depth consistent across save → undo → redo → save
+- Joplin source parity checks for `ls --format json`, `config --export`,
+ `config --import-file`, `sync --upgrade/--use-lock`, `import --force`,
+ `import --output-format`, `version`, `server`, and `e2ee` wrapper arguments
+
+```bash
+python -m pytest -q cli_anything/joplin/tests/test_core.py
+```
+
+## test_full_e2e.py
+
+### `TestCLISubprocess` (10 tests, backend-free)
+
+Runs the CLI as a subprocess (either the installed console script or
+`python -m cli_anything.joplin.joplin_cli`). Tests the externally visible
+behavior:
+
+- `--help` shows usage
+- every command group (`project`, `notebooks`, `notes`, `todos`, `tags`,
+ `search`, `sync`, `interop`, `config`, `attach`, `status`, `backend`,
+ `server`, `e2ee`, `session`) accepts `--help`
+- `project new`, `project info`, `project json`, `project save`,
+ `project status` all return the expected JSON envelope
+- `session status` reports `has_project=false` without a loaded project
+- `--dry-run` does not mutate the project file
+- unknown subcommand exits non-zero
+
+### `TestBackendCommands` (5 tests, backend required)
+
+Isolated real-backend command tests:
+
+- project status/info while pointed at a real profile
+- `notebooks list` and `notes list`
+- `config get sync.target` and `config list`
+- `status show`
+- `session undo` / `session redo` return the documented errors on a clean
+ project
+
+### `TestBackendWorkflows` (11 tests, backend required)
+
+Short backend flows:
+
+- **Note lifecycle** — create notebook → use → create note → rename via `set`
+ → get → remove note → remove notebook
+- **Note organization** — copy, rename (via `ren`), move (via `mv`) between
+ notebooks
+- **Todo lifecycle** — create todo → list → done → undone → toggle → clear
+- **Tagging** — add, list, notetags, tagnotes, remove
+- **Search** — best-effort; tolerates the GUI-mode restriction by checking the
+ error message when the backend rejects `search` outside the REPL
+- **Sync (no target)** — verifies `sync run` returns a payload even when no
+ target is configured
+- **Export** — JEX and Markdown
+- **Import** — Markdown directory import
+- **Attach** — attach file to note, then read it back
+- **Unicode** — skipped on Windows because `joplin.cmd` truncates non-ASCII
+ args; the Python-only unicode roundtrip in `test_core.py` covers harness
+ encoding
+- **Session history persists** — verifies history actions land in the saved
+ project file
+
+### `TestBackendIntegration` (1 test, backend required)
+
+Full end-to-end roundtrip used for agent demos and regression. Phases:
+
+1. Inspect project (status / info / session)
+2. Notebook setup (list, create main, create archive, use main)
+3. Note lifecycle (list, create, rename via `set`, get, copy, create+move, rename via `ren`)
+4. Todos (create, list, done, undone, toggle, clear)
+5. Tags (add primary, add secondary, list, notetags, tagnotes, remove)
+6. Attach (attach file, verbose get)
+7. Status and config (status show, config get, config list)
+8. Sync (no-op)
+9. Export (JEX + MD)
+10. Cleanup (remove notes, remove notebooks, save project, final status, session history)
+
+After the run, the test verifies that the saved project's history contains
+every expected action (`notebook.create`, `note.copy`, `note.move`,
+`todo.toggle`, `tag.add`, `attach.add`, `interop.export`, …).
+
+## Forcing the installed console script
+
+```bash
+CLI_ANYTHING_FORCE_INSTALLED=1 python -m pytest -v -s cli_anything/joplin/tests/test_full_e2e.py
+```
+
+## Known limitations
+
+- `joplin search` is gated to GUI mode on some Joplin CLI builds (3.x); the
+ harness emits a normal `ok=false` JSON envelope with the original error
+ message, and the workflow test accepts that shape.
+- `joplin version` is broken in some npm global layouts because
+ `command-version.js` requires `../package.json`. The harness falls back to
+ `node_modules/joplin/package.json` and includes the original error in stderr.
+- Non-ASCII process arguments on Windows pass through `joplin.cmd` →
+ `cmd.exe`, which drops to the active code page. The unicode workflow test
+ is therefore skipped on Windows. The Python-level unicode handling in the
+ harness (project JSON, history, REPL) is covered in `test_core.py`.
diff --git a/joplin/agent-harness/cli_anything/joplin/tests/test_core.py b/joplin/agent-harness/cli_anything/joplin/tests/test_core.py
new file mode 100644
index 000000000..3f8fb2518
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/tests/test_core.py
@@ -0,0 +1,1012 @@
+"""Command-level unit tests for cli-anything-joplin.
+
+These tests run without a real Joplin backend. They cover:
+
+- harness project schema, save/open, history
+- session state machine (set/get/snapshot/undo/redo/save)
+- backend command runner (subprocess invocation, JSON parsing, error handling)
+- CLI JSON envelope contract across every command group
+- auto-save behavior, dry-run, project status reporting
+- new commands: notes copy/move/rename, notebooks remove, todos group,
+ attach, status, session history, tag tagnotes
+"""
+
+import json
+import os
+
+import pytest
+from click.testing import CliRunner
+
+from cli_anything.joplin import joplin_cli
+from cli_anything.joplin.core import backend as backend_core
+from cli_anything.joplin.core import config as config_core
+from cli_anything.joplin.core import interop as interop_core
+from cli_anything.joplin.core import notes as note_core
+from cli_anything.joplin.core import notebooks as notebook_core
+from cli_anything.joplin.core import project as project_mod
+from cli_anything.joplin.core import sync as sync_core
+from cli_anything.joplin.core import tags as tag_core
+from cli_anything.joplin.core import todos as todo_core
+from cli_anything.joplin.core.session import Session
+from cli_anything.joplin.utils import joplin_backend
+
+
+# ---------------------------------------------------------------------------
+# Project schema / persistence
+# ---------------------------------------------------------------------------
+
+
+def test_create_project_schema():
+ proj = project_mod.create_project(name="demo", backend_binary="joplin", backend_profile=None)
+ assert proj["name"] == "demo"
+ assert "backend" in proj
+ assert "context" in proj
+ assert isinstance(proj["history"], list)
+ assert proj["context"]["current_notebook"] is None
+
+
+def test_project_save_open_roundtrip(tmp_path):
+ proj = project_mod.create_project(name="rt")
+ p = tmp_path / "p.json"
+ project_mod.save_project(proj, str(p))
+ loaded = project_mod.open_project(str(p))
+ assert loaded["name"] == "rt"
+
+
+def test_project_save_open_unicode_roundtrip(tmp_path):
+ proj = project_mod.create_project(name="笔记本-中文")
+ proj["context"]["current_notebook"] = "笔记 A"
+ p = tmp_path / "u.json"
+ project_mod.save_project(proj, str(p))
+ loaded = project_mod.open_project(str(p))
+ assert loaded["name"] == "笔记本-中文"
+ assert loaded["context"]["current_notebook"] == "笔记 A"
+
+
+def test_project_add_history():
+ proj = project_mod.create_project(name="h")
+ project_mod.add_history(proj, "action", {"k": "v"})
+ assert len(proj["history"]) == 1
+ assert proj["history"][0]["action"] == "action"
+ assert proj["history"][0]["payload"] == {"k": "v"}
+
+
+def test_project_add_history_without_payload():
+ proj = project_mod.create_project(name="h")
+ project_mod.add_history(proj, "tick")
+ assert proj["history"][0]["payload"] == {}
+
+
+def test_project_save_creates_parent(tmp_path):
+ proj = project_mod.create_project(name="nested")
+ p = tmp_path / "a" / "b" / "p.json"
+ project_mod.save_project(proj, str(p))
+ assert p.exists()
+
+
+def test_project_info_shape():
+ proj = project_mod.create_project(name="info")
+ project_mod.add_history(proj, "x")
+ info = project_mod.project_info(proj)
+ assert info["name"] == "info"
+ assert info["history_count"] == 1
+ assert "backend" in info
+ assert "context" in info
+
+
+# ---------------------------------------------------------------------------
+# Session state machine
+# ---------------------------------------------------------------------------
+
+
+def test_session_set_get_has_project():
+ sess = Session()
+ assert not sess.has_project()
+ proj = project_mod.create_project(name="s")
+ sess.set_project(proj)
+ assert sess.has_project()
+ assert sess.get_project()["name"] == "s"
+
+
+def test_session_get_project_without_project_raises():
+ sess = Session()
+ with pytest.raises(RuntimeError):
+ sess.get_project()
+
+
+def test_session_snapshot_undo_redo():
+ sess = Session()
+ proj = project_mod.create_project(name="s")
+ sess.set_project(proj)
+ sess.snapshot("before")
+ sess.get_project()["context"]["current_notebook"] = "A"
+ sess.undo()
+ assert sess.get_project()["context"]["current_notebook"] is None
+ sess.redo()
+ assert sess.get_project()["context"]["current_notebook"] == "A"
+
+
+def test_session_multiple_snapshots_undo_chain():
+ sess = Session()
+ proj = project_mod.create_project(name="chain")
+ sess.set_project(proj)
+ for i in range(3):
+ sess.snapshot(f"step-{i}")
+ sess.get_project()["context"]["current_notebook"] = f"book-{i}"
+ assert sess.status()["undo_depth"] == 3
+ sess.undo()
+ sess.undo()
+ sess.undo()
+ assert sess.get_project()["context"]["current_notebook"] is None
+ assert sess.status()["redo_depth"] == 3
+
+
+def test_session_snapshot_clears_redo():
+ sess = Session()
+ proj = project_mod.create_project(name="redo-clear")
+ sess.set_project(proj)
+ sess.snapshot("a")
+ sess.get_project()["context"]["current_notebook"] = "X"
+ sess.undo()
+ assert sess.status()["redo_depth"] == 1
+
+ sess.snapshot("b")
+ assert sess.status()["redo_depth"] == 0
+
+
+def test_session_undo_empty_raises():
+ sess = Session()
+ with pytest.raises(RuntimeError):
+ sess.undo()
+
+
+def test_session_redo_empty_raises():
+ sess = Session()
+ with pytest.raises(RuntimeError):
+ sess.redo()
+
+
+def test_session_save_without_path_raises():
+ sess = Session()
+ sess.set_project(project_mod.create_project())
+ with pytest.raises(RuntimeError):
+ sess.save_session()
+
+
+def test_session_save_with_path(tmp_path):
+ sess = Session()
+ sess.set_project(project_mod.create_project(name="save"), str(tmp_path / "x.json"))
+ saved = sess.save_session()
+ assert os.path.exists(saved)
+
+
+def test_session_set_project_clears_undo_redo():
+ sess = Session()
+ sess.set_project(project_mod.create_project(name="a"))
+ sess.snapshot("change")
+ assert sess.status()["undo_depth"] == 1
+ sess.set_project(project_mod.create_project(name="b"))
+ assert sess.status()["undo_depth"] == 0
+ assert sess.status()["redo_depth"] == 0
+ assert sess.status()["modified"] is False
+
+
+def test_session_status_shape():
+ sess = Session()
+ s = sess.status()
+ assert set(s.keys()) >= {"has_project", "project_path", "modified", "undo_depth", "redo_depth"}
+
+
+def test_session_mark_dirty_sets_modified_without_snapshot():
+ sess = Session()
+ sess.set_project(project_mod.create_project(name="dirty"))
+ assert sess.status()["modified"] is False
+ sess.mark_dirty()
+ assert sess.status()["modified"] is True
+ assert sess.status()["undo_depth"] == 0
+
+
+def test_session_mark_dirty_without_project_raises():
+ sess = Session()
+ with pytest.raises(RuntimeError):
+ sess.mark_dirty()
+
+
+# ---------------------------------------------------------------------------
+# Backend runner
+# ---------------------------------------------------------------------------
+
+
+def test_backend_find_joplin_missing(monkeypatch):
+ monkeypatch.setattr(joplin_backend.shutil, "which", lambda _: None)
+ with pytest.raises(RuntimeError):
+ joplin_backend.find_joplin("joplin")
+
+
+def test_backend_find_joplin_ok(monkeypatch):
+ monkeypatch.setattr(joplin_backend.shutil, "which", lambda _: "/usr/bin/joplin")
+ assert joplin_backend.find_joplin("joplin") == "/usr/bin/joplin"
+
+
+def test_backend_run_command_invokes_subprocess(monkeypatch):
+ class Proc:
+ returncode = 0
+ stdout = "ok"
+ stderr = ""
+
+ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")
+
+ captured = {}
+
+ def fake_run(cmd, capture_output, text, timeout, check):
+ captured["cmd"] = cmd
+ captured["timeout"] = timeout
+ return Proc()
+
+ monkeypatch.setattr(joplin_backend.subprocess, "run", fake_run)
+ cfg = joplin_backend.BackendConfig(binary="joplin", profile="/tmp/p")
+ out = joplin_backend.run_joplin_command(["ls"], cfg)
+ assert out["returncode"] == 0
+ assert captured["cmd"][:3] == ["joplin", "--profile", "/tmp/p"]
+ assert captured["cmd"][-1] == "ls"
+
+
+def test_backend_run_command_without_profile(monkeypatch):
+ class Proc:
+ returncode = 0
+ stdout = "ok"
+ stderr = ""
+
+ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")
+
+ captured = {}
+
+ def fake_run(cmd, **kwargs):
+ captured["cmd"] = cmd
+ return Proc()
+
+ monkeypatch.setattr(joplin_backend.subprocess, "run", fake_run)
+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)
+ joplin_backend.run_joplin_command(["ls"], cfg)
+ assert "--profile" not in captured["cmd"]
+
+
+def test_backend_run_command_error(monkeypatch):
+ class Proc:
+ returncode = 1
+ stdout = ""
+ stderr = "boom"
+
+ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")
+ monkeypatch.setattr(joplin_backend.subprocess, "run", lambda *a, **k: Proc())
+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)
+ with pytest.raises(RuntimeError):
+ joplin_backend.run_joplin_command(["ls"], cfg)
+
+
+def test_backend_run_command_node_warning_passes(monkeypatch):
+ class Proc:
+ returncode = 1
+ stdout = ""
+ stderr = "(node:1234) [DEP0040] DeprecationWarning: The `punycode` module is deprecated."
+
+ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")
+ monkeypatch.setattr(joplin_backend.subprocess, "run", lambda *a, **k: Proc())
+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)
+ result = joplin_backend.run_joplin_command(["ls"], cfg)
+ assert result["returncode"] == 1
+
+
+def test_backend_run_command_timeout(monkeypatch):
+ import subprocess
+
+ monkeypatch.setattr(joplin_backend, "find_joplin", lambda _: "joplin")
+
+ def fake_run(*a, **k):
+ raise subprocess.TimeoutExpired(cmd="joplin", timeout=1)
+
+ monkeypatch.setattr(joplin_backend.subprocess, "run", fake_run)
+ cfg = joplin_backend.BackendConfig(binary="joplin", profile=None)
+ with pytest.raises(RuntimeError) as excinfo:
+ joplin_backend.run_joplin_command(["ls"], cfg, timeout=1)
+ assert "timed out" in str(excinfo.value)
+
+
+def test_backend_run_json_parse(monkeypatch):
+ monkeypatch.setattr(
+ joplin_backend,
+ "run_joplin_command",
+ lambda args, config, timeout=120: {"stdout": json.dumps({"a": 1}), "returncode": 0, "stderr": "", "command": args},
+ )
+ cfg = joplin_backend.BackendConfig()
+ data = joplin_backend.run_joplin_json(["ls"], cfg)
+ assert data["data"]["a"] == 1
+
+
+def test_backend_run_json_fallback_text(monkeypatch):
+ monkeypatch.setattr(
+ joplin_backend,
+ "run_joplin_command",
+ lambda args, config, timeout=120: {"stdout": "plain text", "returncode": 0, "stderr": "", "command": args},
+ )
+ cfg = joplin_backend.BackendConfig()
+ data = joplin_backend.run_joplin_json(["ls"], cfg)
+ assert data["data"]["text"] == "plain text"
+
+
+def test_backend_run_json_empty_stdout(monkeypatch):
+ monkeypatch.setattr(
+ joplin_backend,
+ "run_joplin_command",
+ lambda args, config, timeout=120: {"stdout": "", "returncode": 0, "stderr": "", "command": args},
+ )
+ cfg = joplin_backend.BackendConfig()
+ data = joplin_backend.run_joplin_json(["ls"], cfg)
+ assert data["data"] is None
+
+
+# ---------------------------------------------------------------------------
+# Core module argument shapes (white-box)
+# ---------------------------------------------------------------------------
+
+
+def test_notes_remove_passes_force_and_permanent(monkeypatch):
+ captured = {}
+
+ def fake(args, cfg):
+ captured["args"] = args
+ return {"returncode": 0}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", fake)
+ note_core.remove_note(joplin_backend.BackendConfig(), "n1", force=True, permanent=True)
+ assert "rmnote" in captured["args"]
+ assert "-f" in captured["args"]
+ assert "-p" in captured["args"]
+
+
+def test_notes_copy_with_notebook(monkeypatch):
+ captured = {}
+
+ def fake(args, cfg):
+ captured["args"] = args
+ return {"returncode": 0}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", fake)
+ note_core.copy_note(joplin_backend.BackendConfig(), "n1", notebook="BookA")
+ assert captured["args"] == ["cp", "n1", "BookA"]
+
+
+def test_notes_copy_without_notebook(monkeypatch):
+ captured = {}
+
+ def fake(args, cfg):
+ captured["args"] = args
+ return {"returncode": 0}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", fake)
+ note_core.copy_note(joplin_backend.BackendConfig(), "n1")
+ assert captured["args"] == ["cp", "n1"]
+
+
+def test_notes_move_args(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", lambda a, c: captured.setdefault("args", a) or {})
+ note_core.move_note(joplin_backend.BackendConfig(), "n1", "BookB")
+ assert captured["args"] == ["mv", "n1", "BookB"]
+
+
+def test_notes_rename_args(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", lambda a, c: captured.setdefault("args", a) or {})
+ note_core.rename_note(joplin_backend.BackendConfig(), "n1", "fresh")
+ assert captured["args"] == ["ren", "n1", "fresh"]
+
+
+def test_notes_get_verbose_passes_v(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(note_core, "run_joplin_command", lambda a, c: captured.setdefault("args", a) or {})
+ note_core.get_note(joplin_backend.BackendConfig(), "n1", verbose=True)
+ assert captured["args"] == ["cat", "n1", "-v"]
+
+
+def test_notes_list_uses_json_and_supported_ls_options(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(note_core, "run_joplin_json", lambda a, c: captured.setdefault("args", a) or {})
+ note_core.list_notes(
+ joplin_backend.BackendConfig(),
+ pattern="needle",
+ limit=10,
+ sort="updated_time",
+ reverse=True,
+ item_type="nt",
+ long=True,
+ )
+ assert captured["args"] == [
+ "ls",
+ "needle",
+ "-n",
+ "10",
+ "--sort",
+ "updated_time",
+ "--reverse",
+ "--type",
+ "nt",
+ "--long",
+ "--format",
+ "json",
+ ]
+
+
+def test_notebooks_list_uses_json_and_ls_options(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(notebook_core, "run_joplin_json", lambda a, c: captured.setdefault("args", a) or {})
+ notebook_core.list_notebooks(
+ joplin_backend.BackendConfig(),
+ limit=3,
+ sort="title",
+ reverse=True,
+ long=True,
+ )
+ assert captured["args"] == [
+ "ls",
+ "/",
+ "--format",
+ "json",
+ "--limit",
+ "3",
+ "--sort",
+ "title",
+ "--reverse",
+ "--long",
+ ]
+
+
+def test_notebooks_remove_passes_flags(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(notebook_core, "run_joplin_command", lambda a, c: captured.setdefault("args", a) or {})
+ notebook_core.remove_notebook(joplin_backend.BackendConfig(), "BookA", force=True, permanent=False)
+ assert captured["args"][:2] == ["rmbook", "BookA"]
+ assert "-f" in captured["args"]
+ assert "-p" not in captured["args"]
+
+
+def test_todos_args_correct(monkeypatch):
+ captured = []
+
+ def fake(args, cfg):
+ captured.append(args)
+ return {"returncode": 0}
+
+ monkeypatch.setattr(todo_core, "run_joplin_command", fake)
+ cfg = joplin_backend.BackendConfig()
+ todo_core.create_todo(cfg, "Wash dishes")
+ todo_core.toggle_todo(cfg, "Wash dishes")
+ todo_core.clear_todo(cfg, "Wash dishes")
+ todo_core.mark_done(cfg, "Wash dishes")
+ todo_core.mark_undone(cfg, "Wash dishes")
+
+ assert captured[0] == ["mktodo", "Wash dishes"]
+ assert captured[1] == ["todo", "toggle", "Wash dishes"]
+ assert captured[2] == ["todo", "clear", "Wash dishes"]
+ assert captured[3] == ["done", "Wash dishes"]
+ assert captured[4] == ["undone", "Wash dishes"]
+
+
+def test_todos_list_uses_json_and_ls_options(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(todo_core, "run_joplin_json", lambda a, c: captured.setdefault("args", a) or {})
+ todo_core.list_todos(joplin_backend.BackendConfig(), limit=5, sort="created_time", reverse=True, long=True)
+ assert captured["args"] == [
+ "ls",
+ "--type",
+ "t",
+ "--format",
+ "json",
+ "-n",
+ "5",
+ "--sort",
+ "created_time",
+ "--reverse",
+ "--long",
+ ]
+
+
+def test_tags_tagnotes_uses_tag_list(monkeypatch):
+ captured = {}
+
+ monkeypatch.setattr(tag_core, "run_joplin_command", lambda a, c: captured.setdefault("args", a) or {})
+ tag_core.tag_notes(joplin_backend.BackendConfig(), "work")
+ assert captured["args"] == ["tag", "list", "work"]
+
+
+def test_sync_import_config_and_backend_args(monkeypatch):
+ captured = []
+
+ def fake_command(args, cfg, timeout=120):
+ captured.append(args)
+ return {"returncode": 0}
+
+ monkeypatch.setattr(sync_core, "run_joplin_command", fake_command)
+ monkeypatch.setattr(interop_core, "run_joplin_command", fake_command)
+ monkeypatch.setattr(config_core, "run_joplin_command", fake_command)
+ monkeypatch.setattr(backend_core, "run_joplin_command", fake_command)
+
+ cfg = joplin_backend.BackendConfig()
+ sync_core.run_sync(cfg, target="2", upgrade=True, use_lock="0")
+ interop_core.import_data(cfg, "in.enex", notebook="Inbox", fmt="enex", force=True, output_format="md")
+ config_core.config_export(cfg, verbose=True)
+ config_core.config_import_file(cfg, "settings.json")
+ backend_core.version_info(cfg)
+ backend_core.server_start(cfg, exit_early=True, quiet=True)
+ backend_core.e2ee_decrypt_file(cfg, "encrypted.bin", output_dir="out")
+
+ assert captured[0] == ["sync", "--target", "2", "--upgrade", "--use-lock", "0"]
+ assert captured[1] == [
+ "import",
+ "in.enex",
+ "Inbox",
+ "--format",
+ "enex",
+ "--force",
+ "--output-format",
+ "md",
+ ]
+ assert captured[2] == ["config", "--export", "--verbose"]
+ assert captured[3] == ["config", "--import-file", "settings.json"]
+ assert captured[4] == ["version"]
+ assert captured[5] == ["server", "start", "--exit-early", "--quiet"]
+ assert captured[6] == ["e2ee", "decrypt-file", "encrypted.bin", "--output", "out"]
+
+
+# ---------------------------------------------------------------------------
+# JSON envelope shape
+# ---------------------------------------------------------------------------
+
+
+def test_json_envelope_shape():
+ ok_payload = joplin_cli._json_envelope(True, "notes.list", data={"k": 1})
+ assert ok_payload["ok"] is True
+ assert ok_payload["command"] == "notes.list"
+ assert ok_payload["data"]["k"] == 1
+ assert ok_payload["error"] is None
+
+ err = RuntimeError("boom")
+ bad_payload = joplin_cli._json_envelope(False, "notes.create", data=None, error=err)
+ assert bad_payload["ok"] is False
+ assert bad_payload["command"] == "notes.create"
+ assert bad_payload["data"] is None
+ assert bad_payload["error"]["type"] == "RuntimeError"
+ assert bad_payload["error"]["message"] == "boom"
+
+
+# ---------------------------------------------------------------------------
+# CLI JSON-contract integration (mocked backend)
+# ---------------------------------------------------------------------------
+
+
[email protected](autouse=True)
+def reset_global_session():
+ joplin_cli._session = None
+ joplin_cli._json_output = False
+ joplin_cli._repl_mode = False
+ yield
+ joplin_cli._session = None
+ joplin_cli._json_output = False
+ joplin_cli._repl_mode = False
+
+
+def _mock_ok(monkeypatch):
+ monkeypatch.setattr(joplin_cli, "_backend_config", lambda *a, **k: object())
+ monkeypatch.setattr(joplin_cli.notebook_mod, "list_notebooks", lambda cfg, **kwargs: {"data": [{"title": "N1"}]})
+ monkeypatch.setattr(joplin_cli.notebook_mod, "create_notebook", lambda cfg, title, parent=None: {"created": title})
+ monkeypatch.setattr(joplin_cli.notebook_mod, "use_notebook", lambda cfg, notebook: {"used": notebook})
+ monkeypatch.setattr(joplin_cli.notebook_mod, "remove_notebook", lambda cfg, notebook, force=True, permanent=False: {"removed": notebook})
+ monkeypatch.setattr(joplin_cli.note_mod, "list_notes", lambda cfg, **kwargs: {"data": [{"title": "A"}]})
+ monkeypatch.setattr(joplin_cli.note_mod, "create_note", lambda cfg, title: {"created": title})
+ monkeypatch.setattr(joplin_cli.note_mod, "set_note_field", lambda cfg, note_ref, field, value: {"updated": note_ref})
+ monkeypatch.setattr(joplin_cli.note_mod, "get_note", lambda cfg, note_ref, verbose=False: {"body": "x", "id": note_ref, "verbose": verbose})
+ monkeypatch.setattr(joplin_cli.note_mod, "remove_note", lambda cfg, note_ref, force=True, permanent=False: {"removed": note_ref})
+ monkeypatch.setattr(joplin_cli.note_mod, "copy_note", lambda cfg, note_ref, notebook=None: {"copied": note_ref})
+ monkeypatch.setattr(joplin_cli.note_mod, "move_note", lambda cfg, item, notebook: {"moved": item, "to": notebook})
+ monkeypatch.setattr(joplin_cli.note_mod, "rename_note", lambda cfg, item, new_name: {"renamed": item, "to": new_name})
+ monkeypatch.setattr(joplin_cli.todo_mod, "list_todos", lambda cfg, **kwargs: {"data": [{"title": "T1"}]})
+ monkeypatch.setattr(joplin_cli.todo_mod, "create_todo", lambda cfg, title: {"created": title})
+ monkeypatch.setattr(joplin_cli.todo_mod, "toggle_todo", lambda cfg, pattern: {"toggled": pattern})
+ monkeypatch.setattr(joplin_cli.todo_mod, "clear_todo", lambda cfg, pattern: {"cleared": pattern})
+ monkeypatch.setattr(joplin_cli.todo_mod, "mark_done", lambda cfg, note_ref: {"done": note_ref})
+ monkeypatch.setattr(joplin_cli.todo_mod, "mark_undone", lambda cfg, note_ref: {"undone": note_ref})
+ monkeypatch.setattr(joplin_cli.tag_mod, "list_tags", lambda cfg: {"tags": ["t1"]})
+ monkeypatch.setattr(joplin_cli.tag_mod, "add_tag", lambda cfg, tag, note: {"added": tag})
+ monkeypatch.setattr(joplin_cli.tag_mod, "remove_tag", lambda cfg, tag, note: {"removed": tag})
+ monkeypatch.setattr(joplin_cli.tag_mod, "note_tags", lambda cfg, note: {"tags": ["t1"]})
+ monkeypatch.setattr(joplin_cli.tag_mod, "tag_notes", lambda cfg, tag: {"notes": ["NoteA"]})
+ monkeypatch.setattr(joplin_cli.search_mod, "search", lambda cfg, pattern, notebook=None: {"hits": [pattern]})
+ monkeypatch.setattr(joplin_cli.sync_mod, "run_sync", lambda cfg, **kwargs: {"synced": True})
+ monkeypatch.setattr(joplin_cli.interop_mod, "import_data", lambda cfg, path, **kwargs: {"imported": path})
+ monkeypatch.setattr(joplin_cli.interop_mod, "export_data", lambda cfg, path, fmt="jex", note=None, notebook=None: {"exported": path})
+ monkeypatch.setattr(joplin_cli.config_mod, "config_get", lambda cfg, key, **kwargs: {key: "v"})
+ monkeypatch.setattr(joplin_cli.config_mod, "config_set", lambda cfg, key, value: {key: value})
+ monkeypatch.setattr(joplin_cli.config_mod, "config_list", lambda cfg, **kwargs: {"k": "v"})
+ monkeypatch.setattr(joplin_cli.config_mod, "config_export", lambda cfg, **kwargs: {"exported": True})
+ monkeypatch.setattr(joplin_cli.config_mod, "config_import_file", lambda cfg, file_path: {"imported": file_path})
+ monkeypatch.setattr(joplin_cli.attach_mod, "attach_file", lambda cfg, note_ref, file_path: {"attached": file_path, "note": note_ref})
+ monkeypatch.setattr(joplin_cli.status_mod, "get_status", lambda cfg: {"raw": "Sync status"})
+ monkeypatch.setattr(joplin_cli.status_mod, "restore_items", lambda cfg, pattern: {"restored": pattern})
+ monkeypatch.setattr(joplin_cli.backend_mod, "version_info", lambda cfg: {"version": "3.x"})
+ monkeypatch.setattr(joplin_cli.backend_mod, "dump_database", lambda cfg: {"data": []})
+ monkeypatch.setattr(joplin_cli.backend_mod, "keymap", lambda cfg: {"keymap": True})
+ monkeypatch.setattr(joplin_cli.backend_mod, "geoloc", lambda cfg, note_ref: {"note": note_ref})
+ monkeypatch.setattr(joplin_cli.backend_mod, "export_sync_status", lambda cfg: {"exported": True})
+ monkeypatch.setattr(joplin_cli.backend_mod, "server_status", lambda cfg: {"status": "stopped"})
+ monkeypatch.setattr(joplin_cli.backend_mod, "server_start", lambda cfg, exit_early=True, quiet=False: {"started": True})
+ monkeypatch.setattr(joplin_cli.backend_mod, "server_stop", lambda cfg: {"stopped": True})
+ monkeypatch.setattr(joplin_cli.backend_mod, "e2ee_status", lambda cfg: {"enabled": False})
+ monkeypatch.setattr(joplin_cli.backend_mod, "e2ee_target_status", lambda cfg, target_path, verbose=False: {"target": target_path})
+ monkeypatch.setattr(joplin_cli.backend_mod, "e2ee_decrypt", lambda cfg, **kwargs: {"decrypted": True})
+ monkeypatch.setattr(joplin_cli.backend_mod, "e2ee_decrypt_file", lambda cfg, file_path, output_dir=None: {"file": file_path})
+
+
+def _invoke(monkeypatch, args):
+ runner = CliRunner()
+ return runner.invoke(joplin_cli.cli, args)
+
+
+def _json_invoke(monkeypatch, args):
+ return json.loads(_invoke(monkeypatch, args).output)
+
+
+def test_json_contract_notebooks_group(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "notebooks", "list"])["command"] == "notebooks.list"
+ assert _json_invoke(
+ monkeypatch,
+ ["--json", "notebooks", "list", "--limit", "5", "--sort", "title", "--reverse", "--long"],
+ )["command"] == "notebooks.list"
+ assert _json_invoke(monkeypatch, ["--json", "notebooks", "create", "BookA"])["command"] == "notebooks.create"
+ assert _json_invoke(monkeypatch, ["--json", "notebooks", "use", "BookA"])["command"] == "notebooks.use"
+ assert _json_invoke(monkeypatch, ["--json", "notebooks", "remove", "BookA"])["command"] == "notebooks.remove"
+
+
+def test_json_contract_notes_group(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "notes", "list"])["command"] == "notes.list"
+ assert _json_invoke(
+ monkeypatch,
+ ["--json", "notes", "list", "--pattern", "A", "--limit", "5", "--sort", "updated_time", "--reverse", "--type", "nt", "--long"],
+ )["command"] == "notes.list"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "create", "A"])["command"] == "notes.create"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "set", "A", "title", "B"])["command"] == "notes.set"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "get", "A"])["command"] == "notes.get"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "get", "A", "--verbose"])["command"] == "notes.get"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "remove", "A"])["command"] == "notes.remove"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "copy", "A"])["command"] == "notes.copy"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "copy", "A", "BookB"])["command"] == "notes.copy"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "move", "A", "BookC"])["command"] == "notes.move"
+ assert _json_invoke(monkeypatch, ["--json", "notes", "rename", "A", "B"])["command"] == "notes.rename"
+
+
+def test_json_contract_todos_group(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "todos", "list"])["command"] == "todos.list"
+ assert _json_invoke(
+ monkeypatch,
+ ["--json", "todos", "list", "--limit", "5", "--sort", "created_time", "--reverse", "--long"],
+ )["command"] == "todos.list"
+ assert _json_invoke(monkeypatch, ["--json", "todos", "create", "task"])["command"] == "todos.create"
+ assert _json_invoke(monkeypatch, ["--json", "todos", "toggle", "task"])["command"] == "todos.toggle"
+ assert _json_invoke(monkeypatch, ["--json", "todos", "clear", "task"])["command"] == "todos.clear"
+ assert _json_invoke(monkeypatch, ["--json", "todos", "done", "task"])["command"] == "todos.done"
+ assert _json_invoke(monkeypatch, ["--json", "todos", "undone", "task"])["command"] == "todos.undone"
+
+
+def test_json_contract_tags_group(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "tags", "list"])["command"] == "tags.list"
+ assert _json_invoke(monkeypatch, ["--json", "tags", "add", "t1", "n1"])["command"] == "tags.add"
+ assert _json_invoke(monkeypatch, ["--json", "tags", "remove", "t1", "n1"])["command"] == "tags.remove"
+ assert _json_invoke(monkeypatch, ["--json", "tags", "notetags", "n1"])["command"] == "tags.notetags"
+ assert _json_invoke(monkeypatch, ["--json", "tags", "tagnotes", "t1"])["command"] == "tags.tagnotes"
+
+
+def test_json_contract_search_sync_interop(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "search", "run", "keyword"])["data"]["hits"] == ["keyword"]
+ assert _json_invoke(monkeypatch, ["--json", "sync", "run"])["data"]["synced"] is True
+ assert _json_invoke(monkeypatch, ["--json", "sync", "run", "--target", "2", "--upgrade", "--use-lock", "0"])["command"] == "sync.run"
+ assert _json_invoke(monkeypatch, ["--json", "interop", "import", "in.enex"])["data"]["imported"] == "in.enex"
+ assert _json_invoke(
+ monkeypatch,
+ ["--json", "interop", "import", "in.enex", "--format", "enex", "--force", "--output-format", "md"],
+ )["command"] == "interop.import"
+ assert _json_invoke(monkeypatch, ["--json", "interop", "export", "out.jex"])["data"]["exported"] == "out.jex"
+
+
+def test_json_contract_config_session_attach_status(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "config", "get", "locale"])["command"] == "config.get"
+ assert _json_invoke(monkeypatch, ["--json", "config", "get", "locale", "--verbose"])["command"] == "config.get"
+ assert _json_invoke(monkeypatch, ["--json", "config", "set", "locale", "en_US"])["command"] == "config.set"
+ assert _json_invoke(monkeypatch, ["--json", "config", "list"])["command"] == "config.list"
+ assert _json_invoke(monkeypatch, ["--json", "config", "list", "--verbose"])["command"] == "config.list"
+ assert _json_invoke(monkeypatch, ["--json", "config", "export"])["command"] == "config.export"
+ assert _json_invoke(monkeypatch, ["--json", "config", "import-file", "settings.json"])["command"] == "config.import_file"
+ assert _json_invoke(monkeypatch, ["--json", "session", "status"])["command"] == "session.status"
+ assert _json_invoke(monkeypatch, ["--json", "attach", "add", "noteA", "file.png"])["command"] == "attach.add"
+ assert _json_invoke(monkeypatch, ["--json", "status", "show"])["command"] == "status.show"
+ assert _json_invoke(monkeypatch, ["--json", "status", "restore", "*"])["command"] == "status.restore"
+
+
+def test_json_contract_backend_server_e2ee(monkeypatch):
+ _mock_ok(monkeypatch)
+ assert _json_invoke(monkeypatch, ["--json", "backend", "version"])["command"] == "backend.version"
+ assert _json_invoke(monkeypatch, ["--json", "backend", "dump"])["command"] == "backend.dump"
+ assert _json_invoke(monkeypatch, ["--json", "backend", "keymap"])["command"] == "backend.keymap"
+ assert _json_invoke(monkeypatch, ["--json", "backend", "geoloc", "noteA"])["command"] == "backend.geoloc"
+ assert _json_invoke(monkeypatch, ["--json", "backend", "export-sync-status"])["command"] == "backend.export_sync_status"
+ assert _json_invoke(monkeypatch, ["--json", "server", "status"])["command"] == "server.status"
+ assert _json_invoke(monkeypatch, ["--json", "server", "start", "--quiet"])["command"] == "server.start"
+ assert _json_invoke(monkeypatch, ["--json", "server", "stop"])["command"] == "server.stop"
+ assert _json_invoke(monkeypatch, ["--json", "e2ee", "status"])["command"] == "e2ee.status"
+ assert _json_invoke(monkeypatch, ["--json", "e2ee", "target-status", "target", "--verbose"])["command"] == "e2ee.target_status"
+ assert _json_invoke(monkeypatch, ["--json", "e2ee", "decrypt", "encrypted", "--force"])["command"] == "e2ee.decrypt"
+ assert _json_invoke(monkeypatch, ["--json", "e2ee", "decrypt-file", "file.bin", "--output", "out"])["command"] == "e2ee.decrypt_file"
+
+
+def test_json_contract_project_status(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+
+ project_path = tmp_path / "status.json"
+ project_mod.save_project(project_mod.create_project(name="status"), str(project_path))
+
+ result = runner.invoke(joplin_cli.cli, ["--json", "--project", str(project_path), "project", "status"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is True
+ assert payload["command"] == "project.status"
+ assert payload["data"]["project"]["name"] == "status"
+ assert payload["data"]["project_path"] == str(project_path)
+
+
+def test_json_contract_session_history(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+ project_path = tmp_path / "hist.json"
+ project_mod.save_project(project_mod.create_project(name="hist"), str(project_path))
+ # mutate the project so a history entry is added
+ result = runner.invoke(joplin_cli.cli, ["--json", "--project", str(project_path), "notebooks", "create", "Books"])
+ assert result.exit_code == 0
+
+ history = json.loads(runner.invoke(joplin_cli.cli, ["--json", "--project", str(project_path), "session", "history"]).output)
+ assert history["ok"] is True
+ assert history["command"] == "session.history"
+ assert any(h["action"] == "notebook.create" for h in history["data"])
+
+
+def test_json_contract_full_workflow(monkeypatch):
+ _mock_ok(monkeypatch)
+
+ workflow = [
+ (["notebooks", "create", "BookA"], "notebooks.create"),
+ (["notebooks", "use", "BookA"], "notebooks.use"),
+ (["notes", "create", "NoteA"], "notes.create"),
+ (["notes", "set", "NoteA", "title", "NoteB"], "notes.set"),
+ (["notes", "copy", "NoteB"], "notes.copy"),
+ (["notes", "rename", "NoteB", "Renamed"], "notes.rename"),
+ (["notes", "move", "Renamed", "BookA"], "notes.move"),
+ (["tags", "add", "TagA", "Renamed"], "tags.add"),
+ (["tags", "notetags", "Renamed"], "tags.notetags"),
+ (["tags", "tagnotes", "TagA"], "tags.tagnotes"),
+ (["tags", "remove", "TagA", "Renamed"], "tags.remove"),
+ (["todos", "create", "Buy milk"], "todos.create"),
+ (["todos", "toggle", "Buy milk"], "todos.toggle"),
+ (["todos", "done", "Buy milk"], "todos.done"),
+ (["todos", "undone", "Buy milk"], "todos.undone"),
+ (["todos", "clear", "Buy milk"], "todos.clear"),
+ (["search", "run", "Renamed"], "search.run"),
+ (["sync", "run"], "sync.run"),
+ (["interop", "import", "in.enex"], "interop.import"),
+ (["interop", "export", "out.jex"], "interop.export"),
+ (["attach", "add", "Renamed", "/tmp/a.png"], "attach.add"),
+ (["config", "list"], "config.list"),
+ (["status", "show"], "status.show"),
+ (["session", "status"], "session.status"),
+ ]
+ runner = CliRunner()
+ for args, expected_cmd in workflow:
+ result = runner.invoke(joplin_cli.cli, ["--json", *args])
+ payload = json.loads(result.output)
+ assert payload["ok"] is True, f"Workflow step {args} failed: {result.output}"
+ assert payload["command"] == expected_cmd
+
+
+# ---------------------------------------------------------------------------
+# Error contract
+# ---------------------------------------------------------------------------
+
+
+def _raises_runtime(msg: str):
+ def raiser(*a, **k):
+ raise RuntimeError(msg)
+
+ return raiser
+
+
+def test_json_error_contract_search(monkeypatch):
+ monkeypatch.setattr(joplin_cli, "_backend_config", lambda *a, **k: object())
+ monkeypatch.setattr(joplin_cli.search_mod, "search", _raises_runtime("search failed"))
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "search", "run", "abc"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert payload["error"]["type"] == "RuntimeError"
+ assert payload["error"]["message"] == "search failed"
+
+
+def test_json_error_contract_note_missing(monkeypatch):
+ monkeypatch.setattr(joplin_cli, "_backend_config", lambda *a, **k: object())
+ monkeypatch.setattr(joplin_cli.note_mod, "get_note", _raises_runtime("Cannot find note"))
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "notes", "get", "missing-note"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert payload["command"] == "notes.get"
+
+
+def test_json_error_contract_backend_missing(monkeypatch):
+ monkeypatch.setattr(joplin_cli, "_backend_config", lambda *a, **k: object())
+ monkeypatch.setattr(joplin_cli.tag_mod, "add_tag", _raises_runtime("Joplin terminal binary not found in PATH"))
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "tags", "add", "t1", "n1"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert "not found" in payload["error"]["message"]
+
+
+def test_json_error_contract_invalid_format(monkeypatch):
+ monkeypatch.setattr(joplin_cli, "_backend_config", lambda *a, **k: object())
+ monkeypatch.setattr(joplin_cli.interop_mod, "export_data", _raises_runtime("Unknown format: bogus"))
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "interop", "export", "out.foo", "--format", "bogus"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert "Unknown format" in payload["error"]["message"]
+
+
+def test_project_status_requires_project(monkeypatch):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "project", "status"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert payload["command"] == "project.status"
+ assert payload["error"]["message"] == "No project loaded"
+
+
+def test_project_save_requires_path(monkeypatch):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+ result = runner.invoke(joplin_cli.cli, ["--json", "project", "save"])
+ payload = json.loads(result.output)
+ assert payload["ok"] is False
+ assert payload["command"] == "project.save"
+ assert payload["error"]["message"] == "No project loaded"
+
+
+# ---------------------------------------------------------------------------
+# Auto-save / dry-run
+# ---------------------------------------------------------------------------
+
+
+def test_one_shot_mutation_auto_saves_project(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+
+ project_path = tmp_path / "autosave.json"
+ project_mod.save_project(project_mod.create_project(name="auto"), str(project_path))
+ before = project_mod.open_project(str(project_path))
+ before_hist = len(before["history"])
+
+ result = runner.invoke(
+ joplin_cli.cli,
+ ["--json", "--project", str(project_path), "notebooks", "create", "AutoBook"],
+ )
+ assert result.exit_code == 0
+
+ after = project_mod.open_project(str(project_path))
+ assert len(after["history"]) >= before_hist + 2
+ actions = [h.get("action") for h in after["history"]]
+ assert "snapshot" in actions
+ assert "notebook.create" in actions
+
+
+def test_dry_run_suppresses_auto_save(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+
+ project_path = tmp_path / "dryrun.json"
+ project_mod.save_project(project_mod.create_project(name="dry"), str(project_path))
+ before = project_mod.open_project(str(project_path))
+
+ result = runner.invoke(
+ joplin_cli.cli,
+ ["--json", "--dry-run", "--project", str(project_path), "notebooks", "create", "DryBook"],
+ )
+ assert result.exit_code == 0
+
+ after = project_mod.open_project(str(project_path))
+ assert len(after["history"]) == len(before["history"])
+
+
+def test_todo_workflow_writes_history(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+
+ project_path = tmp_path / "todos.json"
+ project_mod.save_project(project_mod.create_project(name="todos"), str(project_path))
+
+ for args in (
+ ["todos", "create", "task"],
+ ["todos", "toggle", "task"],
+ ["todos", "done", "task"],
+ ["todos", "undone", "task"],
+ ["todos", "clear", "task"],
+ ):
+ result = runner.invoke(
+ joplin_cli.cli,
+ ["--json", "--project", str(project_path), *args],
+ )
+ assert result.exit_code == 0
+
+ after = project_mod.open_project(str(project_path))
+ actions = [h.get("action") for h in after["history"]]
+ for expected in ("todo.create", "todo.toggle", "todo.done", "todo.undone", "todo.clear"):
+ assert expected in actions
+
+
+def test_notebook_remove_writes_history(monkeypatch, tmp_path):
+ _mock_ok(monkeypatch)
+ runner = CliRunner()
+
+ project_path = tmp_path / "rmbook.json"
+ project_mod.save_project(project_mod.create_project(name="rmbook"), str(project_path))
+
+ result = runner.invoke(
+ joplin_cli.cli,
+ ["--json", "--project", str(project_path), "notebooks", "remove", "BookA"],
+ )
+ assert result.exit_code == 0
+
+ after = project_mod.open_project(str(project_path))
+ assert any(h.get("action") == "notebook.remove" for h in after["history"])
+
+
+def test_session_save_keeps_undo_redo_consistent(tmp_path):
+ sess = Session()
+ project_path = tmp_path / "session.json"
+
+ proj = project_mod.create_project(name="persist")
+ sess.set_project(proj, str(project_path))
+ sess.snapshot("set notebook")
+ sess.get_project()["context"]["current_notebook"] = "NB1"
+
+ saved = sess.save_session()
+ assert os.path.exists(saved)
+ assert sess.status()["modified"] is False
+ assert sess.status()["undo_depth"] == 1
+
+ sess.undo()
+ assert sess.get_project()["context"]["current_notebook"] is None
+ assert sess.status()["redo_depth"] == 1
+
+ sess.redo()
+ assert sess.get_project()["context"]["current_notebook"] == "NB1"
+
+ saved2 = sess.save_session()
+ assert os.path.exists(saved2)
diff --git a/joplin/agent-harness/cli_anything/joplin/tests/test_full_e2e.py b/joplin/agent-harness/cli_anything/joplin/tests/test_full_e2e.py
new file mode 100644
index 000000000..3b73cb253
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/tests/test_full_e2e.py
@@ -0,0 +1,656 @@
+"""E2E coverage for the Joplin backend CLI.
+
+Test layout:
+- `TestCLISubprocess`: CLI command checks that do not require a Joplin binary
+- `TestBackendCommands`: isolated command-level checks against the real backend
+- `TestBackendWorkflows`: short workflow tests for common user flows
+- `TestBackendIntegration`: full end-to-end demonstration flow
+
+Real-backend test classes are skipped automatically when the `joplin` binary
+is not on PATH.
+"""
+
+import json
+import os
+import shutil
+import subprocess
+import sys
+from dataclasses import dataclass
+
+import pytest
+
+
+def _resolve_cli(name: str) -> list[str]:
+ force = os.environ.get("CLI_ANYTHING_FORCE_INSTALLED", "").strip() == "1"
+ path = shutil.which(name)
+ if path:
+ print(f"[_resolve_cli] Using installed command: {path}")
+ return [path]
+ if force:
+ raise RuntimeError(f"{name} not found in PATH. Install with: pip install -e .")
+ module = "cli_anything.joplin.joplin_cli"
+ print(f"[_resolve_cli] Falling back to: {sys.executable} -m {module}")
+ return [sys.executable, "-m", module]
+
+
+@dataclass
+class WorkflowStep:
+ title: str
+ args: list[str]
+
+
+class BackendTestBase:
+ CLI_BASE = _resolve_cli("cli-anything-joplin")
+
+ def _run(self, args: list[str], check: bool = True, timeout: int | None = None):
+ return subprocess.run(
+ self.CLI_BASE + args,
+ capture_output=True,
+ text=True,
+ check=check,
+ timeout=timeout,
+ )
+
+ def _run_json(self, args: list[str], check: bool = True, timeout: int | None = None) -> dict:
+ result = self._run(["--json", *args], check=check, timeout=timeout)
+ if not result.stdout.strip():
+ raise AssertionError(
+ f"Empty stdout for args {args}; stderr was:\n{result.stderr}"
+ )
+ return json.loads(result.stdout)
+
+ def _print_workflow_start(self, name: str, total_steps: int):
+ print(f"\n=== Workflow: {name} ===")
+ print(f"Steps: {total_steps}")
+
+ def _print_step(self, index: int, total_steps: int, title: str, args: list[str]):
+ print(f"[{index}/{total_steps}] {title}")
+ print(f"Command: {' '.join(args)}")
+
+ def _print_result(self, payload: dict):
+ if payload.get("ok"):
+ print(f"Result: ok=true, command={payload.get('command')}")
+ data = payload.get("data")
+ if isinstance(data, dict) and data:
+ preview_keys = list(data.keys())[:3]
+ preview = {k: data[k] for k in preview_keys}
+ print(f"Data: {json.dumps(preview, ensure_ascii=False, default=str)}")
+ elif data is not None:
+ print(f"Data: {data}")
+ else:
+ err = payload.get("error") or {}
+ print(f"Result: ok=false, command={payload.get('command')}, error={err.get('message')}")
+
+ def _print_workflow_end(self, name: str, success: bool = True):
+ if success:
+ print(f"[PASS] Workflow passed: {name}")
+ else:
+ print(f"[FAIL] Workflow failed: {name}")
+
+ def _run_workflow_step(self, step: WorkflowStep, check: bool = True, timeout: int | None = None) -> dict:
+ result = self._run(["--json", *step.args], check=check, timeout=timeout)
+ if not result.stdout.strip():
+ self._print_workflow_end(step.title, success=False)
+ raise AssertionError(
+ f"Empty stdout for step '{step.title}' args={step.args}; stderr:\n{result.stderr}"
+ )
+ payload = json.loads(result.stdout)
+ self._print_result(payload)
+ return payload
+
+ def _create_project(self, tmp_path, name: str):
+ project_file = tmp_path / f"{name}.json"
+ payload = self._run_json(["project", "new", "--name", name, "-o", str(project_file)])
+ assert payload["ok"] is True
+ assert payload["command"] == "project.new"
+ assert project_file.exists()
+ return project_file
+
+ def _prepare_workspace(self, tmp_path, project_name: str):
+ project_file = self._create_project(tmp_path, project_name)
+ profile_dir = tmp_path / "profile"
+ profile_dir.mkdir(parents=True, exist_ok=True)
+ return project_file, profile_dir
+
+
+# ---------------------------------------------------------------------------
+# CLI-only tests (no backend required)
+# ---------------------------------------------------------------------------
+
+
+class TestCLISubprocess(BackendTestBase):
+ def test_help_shows_usage(self):
+ r = self._run(["--help"])
+ assert r.returncode == 0
+ assert "cli-anything-joplin" in r.stdout or "Usage" in r.stdout
+
+ def test_subgroup_help_for_every_group(self):
+ for group in (
+ "project",
+ "notebooks",
+ "notes",
+ "todos",
+ "tags",
+ "search",
+ "sync",
+ "interop",
+ "config",
+ "attach",
+ "status",
+ "backend",
+ "server",
+ "e2ee",
+ "session",
+ ):
+ r = self._run([group, "--help"])
+ assert r.returncode == 0, f"{group} --help failed: {r.stderr}"
+ assert "Commands:" in r.stdout or "Usage:" in r.stdout
+
+ def test_project_new_returns_json_payload(self, tmp_path):
+ out = tmp_path / "p.json"
+ payload = self._run_json(["project", "new", "--name", "demo", "-o", str(out)])
+ assert payload["ok"] is True
+ assert payload["command"] == "project.new"
+ assert payload["data"]["name"] == "demo"
+ assert out.exists()
+
+ def test_project_info_works_on_new_project(self, tmp_path):
+ out = tmp_path / "p.json"
+ self._run(["project", "new", "--name", "demo", "-o", str(out)])
+ payload = self._run_json(["--project", str(out), "project", "info"])
+ assert payload["ok"] is True
+ assert payload["data"]["name"] == "demo"
+
+ def test_project_json_dump(self, tmp_path):
+ out = tmp_path / "p.json"
+ self._run(["project", "new", "--name", "dump", "-o", str(out)])
+ payload = self._run_json(["--project", str(out), "project", "json"])
+ assert payload["ok"] is True
+ assert payload["data"]["name"] == "dump"
+ assert payload["data"]["backend"]["binary"] == "joplin"
+
+ def test_session_status_without_project(self):
+ payload = self._run_json(["session", "status"])
+ assert payload["ok"] is True
+ assert payload["data"]["has_project"] is False
+
+ def test_project_save_roundtrip(self, tmp_path):
+ out = tmp_path / "p.json"
+ self._run(["project", "new", "--name", "demo", "-o", str(out)])
+ payload = self._run_json(["--project", str(out), "project", "save"])
+ assert payload["ok"] is True
+ assert "saved" in payload["data"]
+
+ def test_project_status_reports_loaded_project(self, tmp_path):
+ out = tmp_path / "status.json"
+ self._run(["project", "new", "--name", "status-demo", "-o", str(out)])
+ payload = self._run_json(["--project", str(out), "project", "status"])
+ assert payload["ok"] is True
+ assert payload["data"]["project"]["name"] == "status-demo"
+ assert payload["data"]["project_path"] == str(out)
+ assert payload["data"]["session"]["has_project"] is True
+
+ def test_dry_run_does_not_modify_project(self, tmp_path):
+ out = tmp_path / "p.json"
+ self._run(["project", "new", "--name", "dry", "-o", str(out)])
+ with open(out, "r", encoding="utf-8") as f:
+ before = json.load(f)
+
+ # backend mutation in dry-run + bogus profile cannot actually run; we only
+ # care that auto-save is suppressed even on error
+ self._run(
+ [
+ "--dry-run",
+ "--project",
+ str(out),
+ "--profile",
+ str(tmp_path / "no-profile"),
+ "session",
+ "status",
+ ],
+ check=False,
+ )
+ with open(out, "r", encoding="utf-8") as f:
+ after = json.load(f)
+ assert len(after["history"]) == len(before["history"])
+
+ def test_invalid_subcommand_exits_nonzero(self):
+ r = self._run(["bogus-command"], check=False)
+ assert r.returncode != 0
+
+
+# ---------------------------------------------------------------------------
+# Real backend tests
+# ---------------------------------------------------------------------------
+
+
+_JOPLIN_INSTALLED = shutil.which("joplin") is not None
+
+
[email protected](not _JOPLIN_INSTALLED, reason="joplin binary not installed")
+class TestBackendCommands(BackendTestBase):
+ def test_project_status_and_info(self, tmp_path):
+ project_file = self._create_project(tmp_path, "commands-project")
+
+ status = self._run_json(["--project", str(project_file), "project", "status"])
+ assert status["data"]["project"]["name"] == "commands-project"
+
+ info = self._run_json(["--project", str(project_file), "project", "info"])
+ assert info["data"]["name"] == "commands-project"
+
+ def test_notebooks_and_notes_list(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "commands-lists")
+
+ notebooks = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "notebooks", "list"])
+ assert notebooks["ok"] is True
+ assert notebooks["command"] == "notebooks.list"
+
+ notes = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "notes", "list"])
+ assert notes["ok"] is True
+
+ def test_config_get_and_list(self, tmp_path):
+ project_file = self._create_project(tmp_path, "commands-config")
+
+ config_get = self._run_json(["--project", str(project_file), "config", "get", "sync.target"])
+ assert config_get["ok"] is True
+
+ config_list = self._run_json(["--project", str(project_file), "config", "list"])
+ assert config_list["ok"] is True
+ assert config_list["data"] is not None
+
+ def test_status_show(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "commands-status")
+ payload = self._run_json([
+ "--project", str(project_file),
+ "--profile", str(profile_dir),
+ "status", "show",
+ ])
+ assert payload["ok"] is True
+ assert payload["command"] == "status.show"
+
+ def test_backend_utilities(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "commands-backend")
+
+ version = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "backend", "version"])
+ assert version["ok"] is True
+ assert version["command"] == "backend.version"
+
+ dump = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "backend", "dump"])
+ assert dump["ok"] is True
+ assert dump["command"] == "backend.dump"
+
+ e2ee = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "e2ee", "status"])
+ assert e2ee["ok"] is True
+ assert e2ee["command"] == "e2ee.status"
+
+ server = self._run_json(["--project", str(project_file), "--profile", str(profile_dir), "server", "status"])
+ assert server["ok"] is True
+ assert server["command"] == "server.status"
+
+ def test_session_undo_redo(self, tmp_path):
+ project_file = self._create_project(tmp_path, "commands-session")
+
+ undo = self._run_json(["--project", str(project_file), "session", "undo"], check=False)
+ assert undo["ok"] is False
+ assert undo["error"]["message"] == "Nothing to undo"
+
+ redo = self._run_json(["--project", str(project_file), "session", "redo"], check=False)
+ assert redo["ok"] is False
+ assert redo["error"]["message"] == "Nothing to redo"
+
+
[email protected](not _JOPLIN_INSTALLED, reason="joplin binary not installed")
+class TestBackendWorkflows(BackendTestBase):
+ def _common_args(self, project_file, profile_dir):
+ return ["--project", str(project_file), "--profile", str(profile_dir)]
+
+ def test_note_lifecycle_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-notes")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "WorkflowBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "WorkflowBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "WorkflowNote"]),
+ WorkflowStep("Rename via set", base + ["notes", "set", "WorkflowNote", "title", "WorkflowNoteRenamed"]),
+ WorkflowStep("Get note", base + ["notes", "get", "WorkflowNoteRenamed"]),
+ WorkflowStep("Remove note", base + ["notes", "remove", "WorkflowNoteRenamed"]),
+ WorkflowStep("Remove notebook", base + ["notebooks", "remove", "WorkflowBook"]),
+ ]
+ self._print_workflow_start("Note lifecycle", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Note lifecycle")
+
+ def test_note_organization_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-org")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create source notebook", base + ["notebooks", "create", "OrgSrc"]),
+ WorkflowStep("Create target notebook", base + ["notebooks", "create", "OrgDst"]),
+ WorkflowStep("Use source notebook", base + ["notebooks", "use", "OrgSrc"]),
+ WorkflowStep("Create note", base + ["notes", "create", "OrgNote"]),
+ WorkflowStep("Copy to target", base + ["notes", "copy", "OrgNote", "OrgDst"]),
+ WorkflowStep("Rename source note", base + ["notes", "rename", "OrgNote", "OrgNoteRenamed"]),
+ WorkflowStep("Move renamed note to target", base + ["notes", "move", "OrgNoteRenamed", "OrgDst"]),
+ WorkflowStep("Use target notebook", base + ["notebooks", "use", "OrgDst"]),
+ WorkflowStep("List target notebook", base + ["notes", "list"]),
+ WorkflowStep("Cleanup source notebook", base + ["notebooks", "remove", "OrgSrc"]),
+ WorkflowStep("Cleanup target notebook", base + ["notebooks", "remove", "OrgDst"]),
+ ]
+ self._print_workflow_start("Note organization", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Note organization")
+
+ def test_todo_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-todos")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "TodoBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "TodoBook"]),
+ WorkflowStep("Create todo", base + ["todos", "create", "Buy milk"]),
+ WorkflowStep("List todos", base + ["todos", "list"]),
+ WorkflowStep("Mark done", base + ["todos", "done", "Buy milk"]),
+ WorkflowStep("Mark undone", base + ["todos", "undone", "Buy milk"]),
+ WorkflowStep("Toggle todo", base + ["todos", "toggle", "Buy milk"]),
+ WorkflowStep("Clear todo (back to note)", base + ["todos", "clear", "Buy milk"]),
+ WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "TodoBook"]),
+ ]
+ self._print_workflow_start("Todo lifecycle", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Todo lifecycle")
+
+ def test_tagging_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-tags")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "TagBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "TagBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "TagNote"]),
+ WorkflowStep("Add tag", base + ["tags", "add", "wf-tag", "TagNote"]),
+ WorkflowStep("List tags", base + ["tags", "list"]),
+ WorkflowStep("Note tags", base + ["tags", "notetags", "TagNote"]),
+ WorkflowStep("Tag notes", base + ["tags", "tagnotes", "wf-tag"]),
+ WorkflowStep("Remove tag", base + ["tags", "remove", "wf-tag", "TagNote"]),
+ WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "TagBook"]),
+ ]
+ self._print_workflow_start("Tagging", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Tagging")
+
+ def test_search_workflow(self, tmp_path):
+ # `search` is documented as "only available in GUI mode" in some Joplin CLI
+ # builds, so a clean ok=false response with a GUI-mode error message is also
+ # acceptable. We require the rest of the workflow to succeed.
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-search")
+ base = self._common_args(project_file, profile_dir)
+ prep = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "SearchBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "SearchBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "FindMe"]),
+ ]
+ self._print_workflow_start("Search", len(prep) + 2)
+ for index, step in enumerate(prep, start=1):
+ self._print_step(index, len(prep) + 2, step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+
+ search_step = WorkflowStep("Search note by title", base + ["search", "run", "FindMe"])
+ self._print_step(len(prep) + 1, len(prep) + 2, search_step.title, search_step.args)
+ search_payload = self._run_workflow_step(search_step, check=False)
+ if not search_payload["ok"]:
+ assert "GUI" in search_payload["error"]["message"] or "search" in search_payload["error"]["message"].lower()
+
+ cleanup_step = WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "SearchBook"])
+ self._print_step(len(prep) + 2, len(prep) + 2, cleanup_step.title, cleanup_step.args)
+ payload = self._run_workflow_step(cleanup_step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Search")
+
+ def test_sync_workflow_runs(self, tmp_path):
+ # sync.target=0 (none) is the default. `sync run` is expected to be a no-op
+ # in that state. We only require the command exits successfully.
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-sync")
+ base = self._common_args(project_file, profile_dir)
+ payload = self._run_workflow_step(WorkflowStep("Run sync", base + ["sync", "run"]), check=False)
+ assert payload["command"] == "sync.run"
+
+ def test_export_workflow_jex_and_md(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-export")
+ export_jex = tmp_path / "wf.jex"
+ export_md = tmp_path / "wf_md"
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "ExportBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "ExportBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "ExportNote"]),
+ WorkflowStep("Export JEX", base + ["interop", "export", str(export_jex), "--format", "jex"]),
+ WorkflowStep("Export MD", base + ["interop", "export", str(export_md), "--format", "md"]),
+ WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "ExportBook"]),
+ ]
+ self._print_workflow_start("Export", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ assert export_jex.exists() and export_jex.stat().st_size > 0
+ assert export_md.exists()
+ self._print_workflow_end("Export")
+
+ def test_import_md_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-import")
+ md_source = tmp_path / "to_import"
+ md_source.mkdir()
+ (md_source / "imported_note.md").write_text("# Imported\n\nHello from import.", encoding="utf-8")
+
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create destination notebook", base + ["notebooks", "create", "ImportBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "ImportBook"]),
+ WorkflowStep("Import markdown", base + ["interop", "import", str(md_source), "--format", "md"]),
+ WorkflowStep("List notes after import", base + ["notes", "list"]),
+ WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "ImportBook"]),
+ ]
+ self._print_workflow_start("Import", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Import")
+
+ def test_attach_workflow(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-attach")
+ attachment = tmp_path / "attach.txt"
+ attachment.write_text("attached file contents", encoding="utf-8")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "AttachBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "AttachBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "AttachNote"]),
+ WorkflowStep("Attach file", base + ["attach", "add", "AttachNote", str(attachment)]),
+ WorkflowStep("Get note", base + ["notes", "get", "AttachNote"]),
+ WorkflowStep("Cleanup notebook", base + ["notebooks", "remove", "AttachBook"]),
+ ]
+ self._print_workflow_start("Attach", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Attach")
+
+ @pytest.mark.skipif(
+ sys.platform.startswith("win"),
+ reason="Unicode argument forwarding through joplin.cmd / cmd.exe on Windows "
+ "drops to the active code page and corrupts non-ASCII titles. The harness "
+ "itself handles unicode correctly (see test_core unicode roundtrip).",
+ )
+ def test_unicode_notebook_and_note(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-unicode")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create unicode notebook", base + ["notebooks", "create", "笔记本-中文"]),
+ WorkflowStep("Use unicode notebook", base + ["notebooks", "use", "笔记本-中文"]),
+ WorkflowStep("Create unicode note", base + ["notes", "create", "笔记 A — αβγ"]),
+ WorkflowStep("Cleanup unicode notebook", base + ["notebooks", "remove", "笔记本-中文"]),
+ ]
+ self._print_workflow_start("Unicode", len(steps))
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ payload = self._run_workflow_step(step)
+ assert payload["ok"] is True
+ self._print_workflow_end("Unicode")
+
+ def test_session_history_persists(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "workflow-history")
+ base = self._common_args(project_file, profile_dir)
+ steps = [
+ WorkflowStep("Create notebook", base + ["notebooks", "create", "HistBook"]),
+ WorkflowStep("Use notebook", base + ["notebooks", "use", "HistBook"]),
+ WorkflowStep("Create note", base + ["notes", "create", "HistNote"]),
+ ]
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ self._run_workflow_step(step)
+
+ history = self._run_json(["--project", str(project_file), "session", "history"])
+ assert history["ok"] is True
+ actions = [h["action"] for h in history["data"]]
+ for expected in ("notebook.create", "notebook.use", "note.create"):
+ assert expected in actions
+
+ # cleanup
+ self._run(["--project", str(project_file), "--profile", str(profile_dir), "notebooks", "remove", "HistBook"], check=False)
+
+
+# ---------------------------------------------------------------------------
+# Full end-to-end roundtrip
+# ---------------------------------------------------------------------------
+
+
[email protected](not _JOPLIN_INSTALLED, reason="joplin binary not installed")
+class TestBackendIntegration(BackendTestBase):
+ def test_full_backend_roundtrip(self, tmp_path):
+ project_file, profile_dir = self._prepare_workspace(tmp_path, "integration-full")
+ export_jex_path = tmp_path / "integration-full.jex"
+ export_md_path = tmp_path / "integration-md"
+ attachment = tmp_path / "attachment.txt"
+ attachment.write_text("integration attachment payload", encoding="utf-8")
+
+ base = ["--project", str(project_file), "--profile", str(profile_dir)]
+
+ phases = [
+ ("Inspect project", [
+ WorkflowStep("Project status", ["--project", str(project_file), "project", "status"]),
+ WorkflowStep("Project info", ["--project", str(project_file), "project", "info"]),
+ WorkflowStep("Session status (no mutation yet)", ["--project", str(project_file), "session", "status"]),
+ ]),
+ ("Notebook setup", [
+ WorkflowStep("List notebooks", base + ["notebooks", "list"]),
+ WorkflowStep("Create main notebook", base + ["notebooks", "create", "IntegrationBook"]),
+ WorkflowStep("Create secondary notebook", base + ["notebooks", "create", "IntegrationArchive"]),
+ WorkflowStep("Use main notebook", base + ["notebooks", "use", "IntegrationBook"]),
+ ]),
+ ("Note lifecycle", [
+ WorkflowStep("List notes", base + ["notes", "list"]),
+ WorkflowStep("Create note", base + ["notes", "create", "IntegrationNote"]),
+ WorkflowStep("Rename via set", base + ["notes", "set", "IntegrationNote", "title", "IntegrationNoteRenamed"]),
+ WorkflowStep("Get note", base + ["notes", "get", "IntegrationNoteRenamed"]),
+ WorkflowStep("Copy note to archive", base + ["notes", "copy", "IntegrationNoteRenamed", "IntegrationArchive"]),
+ WorkflowStep("Create note for organization", base + ["notes", "create", "Orphan"]),
+ WorkflowStep("Move note via mv", base + ["notes", "move", "Orphan", "IntegrationArchive"]),
+ WorkflowStep("Rename note via ren", base + ["notes", "rename", "IntegrationNoteRenamed", "IntegrationNoteFinal"]),
+ ]),
+ ("Todos", [
+ WorkflowStep("Create todo", base + ["todos", "create", "Drink water"]),
+ WorkflowStep("List todos", base + ["todos", "list"]),
+ WorkflowStep("Mark done", base + ["todos", "done", "Drink water"]),
+ WorkflowStep("Mark undone", base + ["todos", "undone", "Drink water"]),
+ WorkflowStep("Toggle todo", base + ["todos", "toggle", "Drink water"]),
+ WorkflowStep("Clear todo back to note", base + ["todos", "clear", "Drink water"]),
+ ]),
+ ("Tags", [
+ WorkflowStep("Add primary tag", base + ["tags", "add", "integration-tag", "IntegrationNoteFinal"]),
+ WorkflowStep("Add secondary tag", base + ["tags", "add", "another-tag", "IntegrationNoteFinal"]),
+ WorkflowStep("List tags", base + ["tags", "list"]),
+ WorkflowStep("Note tags", base + ["tags", "notetags", "IntegrationNoteFinal"]),
+ WorkflowStep("Tag notes", base + ["tags", "tagnotes", "integration-tag"]),
+ WorkflowStep("Remove tag", base + ["tags", "remove", "integration-tag", "IntegrationNoteFinal"]),
+ ]),
+ ("Attach", [
+ WorkflowStep("Attach file", base + ["attach", "add", "IntegrationNoteFinal", str(attachment)]),
+ WorkflowStep("Verbose get", base + ["notes", "get", "IntegrationNoteFinal", "--verbose"]),
+ ]),
+ ("Status and config", [
+ WorkflowStep("Backend status", base + ["status", "show"]),
+ WorkflowStep("Config get", base + ["config", "get", "sync.target"]),
+ WorkflowStep("Config list", base + ["config", "list"]),
+ ]),
+ ("Sync (no-op)", [
+ WorkflowStep("Run sync (no target)", base + ["sync", "run"]),
+ ]),
+ ("Export and import", [
+ WorkflowStep("Export JEX", base + ["interop", "export", str(export_jex_path), "--format", "jex"]),
+ WorkflowStep("Export MD", base + ["interop", "export", str(export_md_path), "--format", "md"]),
+ ]),
+ ("Cleanup", [
+ WorkflowStep("Remove final note", base + ["notes", "remove", "IntegrationNoteFinal"]),
+ WorkflowStep("Remove main notebook", base + ["notebooks", "remove", "IntegrationBook"]),
+ WorkflowStep("Remove archive notebook", base + ["notebooks", "remove", "IntegrationArchive"]),
+ WorkflowStep("Save project", ["--project", str(project_file), "project", "save"]),
+ WorkflowStep("Final project status", ["--project", str(project_file), "project", "status"]),
+ WorkflowStep("Session history", ["--project", str(project_file), "session", "history"]),
+ ]),
+ ]
+
+ print("\n=== Workflow: Full backend roundtrip ===")
+ for phase_name, steps in phases:
+ print(f"\n--- Phase: {phase_name} ---")
+ for index, step in enumerate(steps, start=1):
+ self._print_step(index, len(steps), step.title, step.args)
+ # `sync run` may return ok=true with target=0 (none) or ok=false
+ # depending on backend version; tolerate either.
+ check = step.title not in {"Run sync (no target)"}
+ payload = self._run_workflow_step(step, check=check)
+ if step.title == "Run sync (no target)":
+ continue
+ assert payload["ok"] is True, f"Step '{step.title}' failed: {payload}"
+
+ assert export_jex_path.exists() and export_jex_path.stat().st_size > 0
+ assert export_md_path.exists()
+
+ # Verify the saved project carries the expected history
+ final_project = json.loads(open(project_file, "r", encoding="utf-8").read())
+ history_actions = [h["action"] for h in final_project["history"]]
+ for action in (
+ "notebook.create",
+ "notebook.use",
+ "note.create",
+ "note.set",
+ "note.copy",
+ "note.move",
+ "note.rename",
+ "todo.create",
+ "todo.toggle",
+ "todo.done",
+ "todo.undone",
+ "todo.clear",
+ "tag.add",
+ "tag.remove",
+ "attach.add",
+ "interop.export",
+ "note.remove",
+ "notebook.remove",
+ ):
+ assert action in history_actions, f"Missing history action: {action}"
+
+ print("[PASS] Workflow passed: Full backend roundtrip")
diff --git a/joplin/agent-harness/cli_anything/joplin/utils/__init__.py b/joplin/agent-harness/cli_anything/joplin/utils/__init__.py
new file mode 100644
index 000000000..c193c06a6
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/utils/__init__.py
@@ -0,0 +1 @@
+"""Utility package for cli-anything-joplin."""
diff --git a/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py b/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py
new file mode 100644
index 000000000..51165d021
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/utils/joplin_backend.py
@@ -0,0 +1,73 @@
+import json
+import shutil
+import subprocess
+from dataclasses import dataclass
+from typing import Optional
+
+
+@dataclass
+class BackendConfig:
+ binary: str = "joplin"
+ profile: Optional[str] = None
+
+
+def find_joplin(binary: str = "joplin") -> str:
+ path = shutil.which(binary)
+ if path:
+ return path
+ raise RuntimeError(
+ "Joplin terminal binary not found in PATH. Install Joplin CLI and ensure `joplin` is executable."
+ )
+
+
+def _is_benign_node_warning(stderr: str, stdout: str = "") -> bool:
+ text = f"{stderr}\n{stdout}".strip().lower()
+ return bool(text) and "dep0040" in text and "punycode" in text
+
+
+def run_joplin_command(args: list[str], config: BackendConfig, timeout: int = 120) -> dict:
+ binary = find_joplin(config.binary)
+ cmd = [binary]
+ if config.profile:
+ cmd += ["--profile", config.profile]
+ cmd += args
+
+ try:
+ proc = subprocess.run(
+ cmd,
+ capture_output=True,
+ text=True,
+ timeout=timeout,
+ check=False,
+ )
+ except subprocess.TimeoutExpired as e:
+ raise RuntimeError(f"Joplin command timed out after {timeout}s") from e
+
+ stdout = (proc.stdout or "").strip()
+ stderr = (proc.stderr or "").strip()
+ result = {
+ "command": cmd,
+ "returncode": proc.returncode,
+ "stdout": stdout,
+ "stderr": stderr,
+ }
+
+ if proc.returncode != 0 and not _is_benign_node_warning(stderr, stdout):
+ raise RuntimeError(stderr or stdout or "Joplin command failed")
+
+ return result
+
+
+def run_joplin_json(args: list[str], config: BackendConfig, timeout: int = 120) -> dict:
+ command_args = args if "--format" in args or "-f" in args else args + ["--format", "json"]
+ raw = run_joplin_command(command_args, config, timeout=timeout)
+ text = raw["stdout"]
+ if not text:
+ return {"raw": raw, "data": None}
+
+ try:
+ data = json.loads(text)
+ except json.JSONDecodeError:
+ data = {"text": text}
+
+ return {"raw": raw, "data": data}
diff --git a/joplin/agent-harness/cli_anything/joplin/utils/repl_skin.py b/joplin/agent-harness/cli_anything/joplin/utils/repl_skin.py
new file mode 100644
index 000000000..bc1fb6d1d
--- /dev/null
+++ b/joplin/agent-harness/cli_anything/joplin/utils/repl_skin.py
@@ -0,0 +1,567 @@
+"""cli-anything REPL Skin — Unified terminal interface for all CLI harnesses.
+
+Copy this file into your CLI package at:
+ cli_anything/<software>/utils/repl_skin.py
+
+Usage:
+ from cli_anything.<software>.utils.repl_skin import ReplSkin
+
+ skin = ReplSkin("shotcut", version="1.0.0")
+ skin.print_banner() # auto-detects repo-root or packaged SKILL.md
+ prompt_text = skin.prompt(project_name="my_video.mlt", modified=True)
+ skin.success("Project saved")
+ skin.error("File not found")
+ skin.warning("Unsaved changes")
+ skin.info("Processing 24 clips...")
+ skin.status("Track 1", "3 clips, 00:02:30")
+ skin.table(headers, rows)
+ skin.print_goodbye()
+"""
+
+import os
+import sys
+from pathlib import Path
+
+# ── ANSI color codes (no external deps for core styling) ──────────────
+
+_RESET = "\033[0m"
+_BOLD = "\033[1m"
+_DIM = "\033[2m"
+_ITALIC = "\033[3m"
+_UNDERLINE = "\033[4m"
+
+# Brand colors
+_CYAN = "\033[38;5;80m" # cli-anything brand cyan
+_CYAN_BG = "\033[48;5;80m"
+_WHITE = "\033[97m"
+_GRAY = "\033[38;5;245m"
+_DARK_GRAY = "\033[38;5;240m"
+_LIGHT_GRAY = "\033[38;5;250m"
+
+# Software accent colors — each software gets a unique accent
+_ACCENT_COLORS = {
+ "gimp": "\033[38;5;214m", # warm orange
+ "blender": "\033[38;5;208m", # deep orange
+ "inkscape": "\033[38;5;39m", # bright blue
+ "audacity": "\033[38;5;33m", # navy blue
+ "libreoffice": "\033[38;5;40m", # green
+ "obs_studio": "\033[38;5;55m", # purple
+ "kdenlive": "\033[38;5;69m", # slate blue
+ "shotcut": "\033[38;5;35m", # teal green
+}
+_DEFAULT_ACCENT = "\033[38;5;75m" # default sky blue
+
+# Status colors
+_GREEN = "\033[38;5;78m"
+_YELLOW = "\033[38;5;220m"
+_RED = "\033[38;5;196m"
+_BLUE = "\033[38;5;75m"
+_MAGENTA = "\033[38;5;176m"
+
+_SKILL_SOURCE_REPO = os.environ.get("CLI_ANYTHING_SKILL_REPO", "HKUDS/CLI-Anything")
+
+# ── Brand icon ────────────────────────────────────────────────────────
+
+# The cli-anything icon: a small colored diamond/chevron mark
+_ICON = f"{_CYAN}{_BOLD}◆{_RESET}"
+_ICON_SMALL = f"{_CYAN}▸{_RESET}"
+
+# ── Box drawing characters ────────────────────────────────────────────
+
+_H_LINE = "─"
+_V_LINE = "│"
+_TL = "╭"
+_TR = "╮"
+_BL = "╰"
+_BR = "╯"
+_T_DOWN = "┬"
+_T_UP = "┴"
+_T_RIGHT = "├"
+_T_LEFT = "┤"
+_CROSS = "┼"
+
+
+def _strip_ansi(text: str) -> str:
+ """Remove ANSI escape codes for length calculation."""
+ import re
+ return re.sub(r"\033\[[^m]*m", "", text)
+
+
+def _visible_len(text: str) -> int:
+ """Get visible length of text (excluding ANSI codes)."""
+ return len(_strip_ansi(text))
+
+
+def _display_home_path(path: str) -> str:
+ """Display a path relative to the home directory when possible."""
+ expanded = Path(path).expanduser().resolve()
+ home = Path.home().resolve()
+ try:
+ relative = expanded.relative_to(home)
+ return f"~/{relative.as_posix()}"
+ except ValueError:
+ return str(expanded)
+
+
+class ReplSkin:
+ """Unified REPL skin for cli-anything CLIs.
+
+ Provides consistent branding, prompts, and message formatting
+ across all CLI harnesses built with the cli-anything methodology.
+ """
+
+ def __init__(self, software: str, version: str = "1.0.0",
+ history_file: str | None = None, skill_path: str | None = None):
+ """Initialize the REPL skin.
+
+ Args:
+ software: Software name (e.g., "gimp", "shotcut", "blender").
+ version: CLI version string.
+ history_file: Path for persistent command history.
+ Defaults to ~/.cli-anything-<software>/history
+ skill_path: Path to the SKILL.md file for agent discovery.
+ Auto-detected from the repo-root skills/ tree when present,
+ otherwise from the package's skills/ directory.
+ Displayed in banner for AI agents to know where to read skill info.
+ """
+ self.software = software.lower().replace("-", "_")
+ self.display_name = software.replace("_", " ").title()
+ self.version = version
+ software_aliases = {"iterm2_ctl": "iterm2"}
+ self.skill_slug = software_aliases.get(self.software, self.software).replace("_", "-")
+ self.skill_id = f"cli-anything-{self.skill_slug}"
+ self.skill_install_cmd = (
+ f"npx skills add {_SKILL_SOURCE_REPO} --skill {self.skill_id} -g -y"
+ )
+ global_skill_root = Path(
+ os.environ.get("CLI_ANYTHING_GLOBAL_SKILLS_DIR", str(Path.home() / ".agents" / "skills"))
+ ).expanduser()
+ self.global_skill_path = str(global_skill_root / self.skill_id / "SKILL.md")
+
+ # Prefer repo-root canonical skills/<skill-id>/SKILL.md when running
+ # inside the CLI-Anything monorepo. Fall back to the packaged
+ # cli_anything/<software>/skills/SKILL.md for installed harnesses.
+ if skill_path is None:
+ package_skill = Path(__file__).resolve().parent.parent / "skills" / "SKILL.md"
+ repo_skill = None
+ for parent in Path(__file__).resolve().parents:
+ candidate = parent / "skills" / self.skill_id / "SKILL.md"
+ if candidate.is_file():
+ repo_skill = candidate
+ break
+ if repo_skill and repo_skill.is_file():
+ skill_path = str(repo_skill)
+ elif package_skill.is_file():
+ skill_path = str(package_skill)
+ self.skill_path = skill_path
+ self.accent = _ACCENT_COLORS.get(self.software, _DEFAULT_ACCENT)
+
+ # History file
+ if history_file is None:
+ hist_dir = Path.home() / f".cli-anything-{self.software}"
+ hist_dir.mkdir(parents=True, exist_ok=True)
+ self.history_file = str(hist_dir / "history")
+ else:
+ self.history_file = history_file
+
+ # Detect terminal capabilities
+ self._color = self._detect_color_support()
+
+ def _detect_color_support(self) -> bool:
+ """Check if terminal supports color."""
+ if os.environ.get("NO_COLOR"):
+ return False
+ if os.environ.get("CLI_ANYTHING_NO_COLOR"):
+ return False
+ if not hasattr(sys.stdout, "isatty"):
+ return False
+ return sys.stdout.isatty()
+
+ def _c(self, code: str, text: str) -> str:
+ """Apply color code if colors are supported."""
+ if not self._color:
+ return text
+ return f"{code}{text}{_RESET}"
+
+ # ── Banner ────────────────────────────────────────────────────────
+
+ def print_banner(self):
+ """Print the startup banner with branding."""
+ import textwrap
+
+ inner = 72
+
+ def _box_line(content: str) -> str:
+ """Wrap content in box drawing, padding to inner width."""
+ pad = inner - _visible_len(content)
+ vl = self._c(_DARK_GRAY, _V_LINE)
+ return f"{vl}{content}{' ' * max(0, pad)}{vl}"
+
+ def _meta_lines(label: str, value: str) -> list[str]:
+ """Wrap a metadata line for the banner box."""
+ icon = self._c(_MAGENTA, "◇")
+ label_text = self._c(_DARK_GRAY, label)
+ prefix = f" {icon} {label_text} "
+ available = max(12, inner - _visible_len(prefix))
+ wrapped = textwrap.wrap(
+ value,
+ width=available,
+ break_long_words=True,
+ break_on_hyphens=False,
+ ) or [""]
+ lines = [f"{prefix}{self._c(_LIGHT_GRAY, wrapped[0])}"]
+ continuation_prefix = " " * _visible_len(prefix)
+ for chunk in wrapped[1:]:
+ lines.append(f"{continuation_prefix}{self._c(_LIGHT_GRAY, chunk)}")
+ return lines
+
+ top = self._c(_DARK_GRAY, f"{_TL}{_H_LINE * inner}{_TR}")
+ bot = self._c(_DARK_GRAY, f"{_BL}{_H_LINE * inner}{_BR}")
+
+ # Title: ◆ cli-anything · Shotcut
+ icon = self._c(_CYAN + _BOLD, "◆")
+ brand = self._c(_CYAN + _BOLD, "cli-anything")
+ dot = self._c(_DARK_GRAY, "·")
+ name = self._c(self.accent + _BOLD, self.display_name)
+ title = f" {icon} {brand} {dot} {name}"
+
+ ver = f" {self._c(_DARK_GRAY, f' v{self.version}')}"
+ tip = f" {self._c(_DARK_GRAY, ' Type help for commands, quit to exit')}"
+ empty = ""
+
+ meta_lines: list[str] = []
+ meta_lines.extend(_meta_lines("Install:", self.skill_install_cmd))
+ meta_lines.extend(_meta_lines("Global skill:", _display_home_path(self.global_skill_path)))
+ print(top)
+ print(_box_line(title))
+ print(_box_line(ver))
+ for line in meta_lines:
+ print(_box_line(line))
+ print(_box_line(empty))
+ print(_box_line(tip))
+ print(bot)
+ print()
+
+ # ── Prompt ────────────────────────────────────────────────────────
+
+ def prompt(self, project_name: str = "", modified: bool = False,
+ context: str = "") -> str:
+ """Build a styled prompt string for prompt_toolkit or input().
+
+ Args:
+ project_name: Current project name (empty if none open).
+ modified: Whether the project has unsaved changes.
+ context: Optional extra context to show in prompt.
+
+ Returns:
+ Formatted prompt string.
+ """
+ parts = []
+
+ # Icon
+ if self._color:
+ parts.append(f"{_CYAN}◆{_RESET} ")
+ else:
+ parts.append("> ")
+
+ # Software name
+ parts.append(self._c(self.accent + _BOLD, self.software))
+
+ # Project context
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ parts.append(f" {self._c(_DARK_GRAY, '[')}")
+ parts.append(self._c(_LIGHT_GRAY, f"{ctx}{mod}"))
+ parts.append(self._c(_DARK_GRAY, ']'))
+
+ parts.append(self._c(_GRAY, " ❯ "))
+
+ return "".join(parts)
+
+ def prompt_tokens(self, project_name: str = "", modified: bool = False,
+ context: str = ""):
+ """Build prompt_toolkit formatted text tokens for the prompt.
+
+ Use with prompt_toolkit's FormattedText for proper ANSI handling.
+
+ Returns:
+ list of (style, text) tuples for prompt_toolkit.
+ """
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+ tokens = []
+
+ tokens.append(("class:icon", "◆ "))
+ tokens.append(("class:software", self.software))
+
+ if project_name or context:
+ ctx = context or project_name
+ mod = "*" if modified else ""
+ tokens.append(("class:bracket", " ["))
+ tokens.append(("class:context", f"{ctx}{mod}"))
+ tokens.append(("class:bracket", "]"))
+
+ tokens.append(("class:arrow", " ❯ "))
+
+ return tokens
+
+ def get_prompt_style(self):
+ """Get a prompt_toolkit Style object matching the skin.
+
+ Returns:
+ prompt_toolkit.styles.Style
+ """
+ try:
+ from prompt_toolkit.styles import Style
+ except ImportError:
+ return None
+
+ accent_hex = _ANSI_256_TO_HEX.get(self.accent, "#5fafff")
+
+ return Style.from_dict({
+ "icon": "#5fdfdf bold", # cyan brand color
+ "software": f"{accent_hex} bold",
+ "bracket": "#585858",
+ "context": "#bcbcbc",
+ "arrow": "#808080",
+ # Completion menu
+ "completion-menu.completion": "bg:#303030 #bcbcbc",
+ "completion-menu.completion.current": f"bg:{accent_hex} #000000",
+ "completion-menu.meta.completion": "bg:#303030 #808080",
+ "completion-menu.meta.completion.current": f"bg:{accent_hex} #000000",
+ # Auto-suggest
+ "auto-suggest": "#585858",
+ # Bottom toolbar
+ "bottom-toolbar": "bg:#1c1c1c #808080",
+ "bottom-toolbar.text": "#808080",
+ })
+
+ # ── Messages ──────────────────────────────────────────────────────
+
+ def success(self, message: str):
+ """Print a success message with green checkmark."""
+ icon = self._c(_GREEN + _BOLD, "✓")
+ print(f" {icon} {self._c(_GREEN, message)}")
+
+ def error(self, message: str):
+ """Print an error message with red cross."""
+ icon = self._c(_RED + _BOLD, "✗")
+ print(f" {icon} {self._c(_RED, message)}", file=sys.stderr)
+
+ def warning(self, message: str):
+ """Print a warning message with yellow triangle."""
+ icon = self._c(_YELLOW + _BOLD, "⚠")
+ print(f" {icon} {self._c(_YELLOW, message)}")
+
+ def info(self, message: str):
+ """Print an info message with blue dot."""
+ icon = self._c(_BLUE, "●")
+ print(f" {icon} {self._c(_LIGHT_GRAY, message)}")
+
+ def hint(self, message: str):
+ """Print a subtle hint message."""
+ print(f" {self._c(_DARK_GRAY, message)}")
+
+ def section(self, title: str):
+ """Print a section header."""
+ print()
+ print(f" {self._c(self.accent + _BOLD, title)}")
+ print(f" {self._c(_DARK_GRAY, _H_LINE * len(title))}")
+
+ # ── Status display ────────────────────────────────────────────────
+
+ def status(self, label: str, value: str):
+ """Print a key-value status line."""
+ lbl = self._c(_GRAY, f" {label}:")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def status_block(self, items: dict[str, str], title: str = ""):
+ """Print a block of status key-value pairs.
+
+ Args:
+ items: Dict of label -> value pairs.
+ title: Optional title for the block.
+ """
+ if title:
+ self.section(title)
+
+ max_key = max(len(k) for k in items) if items else 0
+ for label, value in items.items():
+ lbl = self._c(_GRAY, f" {label:<{max_key}}")
+ val = self._c(_WHITE, f" {value}")
+ print(f"{lbl}{val}")
+
+ def progress(self, current: int, total: int, label: str = ""):
+ """Print a simple progress indicator.
+
+ Args:
+ current: Current step number.
+ total: Total number of steps.
+ label: Optional label for the progress.
+ """
+ pct = int(current / total * 100) if total > 0 else 0
+ bar_width = 20
+ filled = int(bar_width * current / total) if total > 0 else 0
+ bar = "█" * filled + "░" * (bar_width - filled)
+ text = f" {self._c(_CYAN, bar)} {self._c(_GRAY, f'{pct:3d}%')}"
+ if label:
+ text += f" {self._c(_LIGHT_GRAY, label)}"
+ print(text)
+
+ # ── Table display ─────────────────────────────────────────────────
+
+ def table(self, headers: list[str], rows: list[list[str]],
+ max_col_width: int = 40):
+ """Print a formatted table with box-drawing characters.
+
+ Args:
+ headers: Column header strings.
+ rows: List of rows, each a list of cell strings.
+ max_col_width: Maximum column width before truncation.
+ """
+ if not headers:
+ return
+
+ # Calculate column widths
+ col_widths = [min(len(h), max_col_width) for h in headers]
+ for row in rows:
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ col_widths[i] = min(
+ max(col_widths[i], len(str(cell))), max_col_width
+ )
+
+ def pad(text: str, width: int) -> str:
+ t = str(text)[:width]
+ return t + " " * (width - len(t))
+
+ # Header
+ header_cells = [
+ self._c(_CYAN + _BOLD, pad(h, col_widths[i]))
+ for i, h in enumerate(headers)
+ ]
+ sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ header_line = f" {sep.join(header_cells)}"
+ print(header_line)
+
+ # Separator
+ sep_parts = [self._c(_DARK_GRAY, _H_LINE * w) for w in col_widths]
+ sep_line = self._c(_DARK_GRAY, f" {'───'.join([_H_LINE * w for w in col_widths])}")
+ print(sep_line)
+
+ # Rows
+ for row in rows:
+ cells = []
+ for i, cell in enumerate(row):
+ if i < len(col_widths):
+ cells.append(self._c(_LIGHT_GRAY, pad(str(cell), col_widths[i])))
+ row_sep = self._c(_DARK_GRAY, f" {_V_LINE} ")
+ print(f" {row_sep.join(cells)}")
+
+ # ── Help display ──────────────────────────────────────────────────
+
+ def help(self, commands: dict[str, str]):
+ """Print a formatted help listing.
+
+ Args:
+ commands: Dict of command -> description pairs.
+ """
+ self.section("Commands")
+ max_cmd = max(len(c) for c in commands) if commands else 0
+ for cmd, desc in commands.items():
+ cmd_styled = self._c(self.accent, f" {cmd:<{max_cmd}}")
+ desc_styled = self._c(_GRAY, f" {desc}")
+ print(f"{cmd_styled}{desc_styled}")
+ print()
+
+ # ── Goodbye ───────────────────────────────────────────────────────
+
+ def print_goodbye(self):
+ """Print a styled goodbye message."""
+ print(f"\n {_ICON_SMALL} {self._c(_GRAY, 'Goodbye!')}\n")
+
+ # ── Prompt toolkit session factory ────────────────────────────────
+
+ def create_prompt_session(self):
+ """Create a prompt_toolkit PromptSession with skin styling.
+
+ Returns:
+ A configured PromptSession, or None if prompt_toolkit unavailable.
+ """
+ try:
+ from prompt_toolkit import PromptSession
+ from prompt_toolkit.history import FileHistory
+ from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
+ from prompt_toolkit.formatted_text import FormattedText
+
+ style = self.get_prompt_style()
+
+ session = PromptSession(
+ history=FileHistory(self.history_file),
+ auto_suggest=AutoSuggestFromHistory(),
+ style=style,
+ enable_history_search=True,
+ )
+ return session
+ except ImportError:
+ return None
+
+ def get_input(self, pt_session, project_name: str = "",
+ modified: bool = False, context: str = "") -> str:
+ """Get input from user using prompt_toolkit or fallback.
+
+ Args:
+ pt_session: A prompt_toolkit PromptSession (or None).
+ project_name: Current project name.
+ modified: Whether project has unsaved changes.
+ context: Optional context string.
+
+ Returns:
+ User input string (stripped).
+ """
+ if pt_session is not None:
+ from prompt_toolkit.formatted_text import FormattedText
+ tokens = self.prompt_tokens(project_name, modified, context)
+ return pt_session.prompt(FormattedText(tokens)).strip()
+ else:
+ raw_prompt = self.prompt(project_name, modified, context)
+ return input(raw_prompt).strip()
+
+ # ── Toolbar builder ───────────────────────────────────────────────
+
+ def bottom_toolbar(self, items: dict[str, str]):
+ """Create a bottom toolbar callback for prompt_toolkit.
+
+ Args:
+ items: Dict of label -> value pairs to show in toolbar.
+
+ Returns:
+ A callable that returns FormattedText for the toolbar.
+ """
+ def toolbar():
+ from prompt_toolkit.formatted_text import FormattedText
+ parts = []
+ for i, (k, v) in enumerate(items.items()):
+ if i > 0:
+ parts.append(("class:bottom-toolbar.text", " │ "))
+ parts.append(("class:bottom-toolbar.text", f" {k}: "))
+ parts.append(("class:bottom-toolbar", v))
+ return FormattedText(parts)
+ return toolbar
+
+
+# ── ANSI 256-color to hex mapping (for prompt_toolkit styles) ─────────
+
+_ANSI_256_TO_HEX = {
+ "\033[38;5;33m": "#0087ff", # audacity navy blue
+ "\033[38;5;35m": "#00af5f", # shotcut teal
+ "\033[38;5;39m": "#00afff", # inkscape bright blue
+ "\033[38;5;40m": "#00d700", # libreoffice green
+ "\033[38;5;55m": "#5f00af", # obs purple
+ "\033[38;5;69m": "#5f87ff", # kdenlive slate blue
+ "\033[38;5;75m": "#5fafff", # default sky blue
+ "\033[38;5;80m": "#5fd7d7", # brand cyan
+ "\033[38;5;208m": "#ff8700", # blender deep orange
+ "\033[38;5;214m": "#ffaf00", # gimp warm orange
+}
diff --git a/joplin/agent-harness/setup.py b/joplin/agent-harness/setup.py
new file mode 100644
index 000000000..c2af15721
--- /dev/null
+++ b/joplin/agent-harness/setup.py
@@ -0,0 +1,69 @@
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+
+PACKAGE_NAME = "cli-anything-joplin"
+PACKAGE_VERSION = "1.0.0"
+
+
+def _handle_metadata_query(argv: list[str]) -> bool:
+ if len(argv) != 2:
+ return False
+ if argv[1] == "--name":
+ print(PACKAGE_NAME)
+ return True
+ if argv[1] == "--version":
+ print(PACKAGE_VERSION)
+ return True
+ return False
+
+
+if __name__ == "__main__" and _handle_metadata_query(sys.argv):
+ raise SystemExit(0)
+
+from setuptools import find_namespace_packages, setup
+
+
+ROOT = Path(__file__).parent
+README = ROOT / "cli_anything" / "joplin" / "README.md"
+LONG_DESCRIPTION = README.read_text(encoding="utf-8") if README.exists() else ""
+
+
+setup(
+ name=PACKAGE_NAME,
+ version=PACKAGE_VERSION,
+ author="cli-anything contributors",
+ author_email="",
+ description="CLI harness for Joplin workflows using the real joplin terminal backend.",
+ long_description=LONG_DESCRIPTION,
+ long_description_content_type="text/markdown",
+ url="https://github.com/HKUDS/CLI-Anything",
+ packages=find_namespace_packages(include=["cli_anything.*"]),
+ python_requires=">=3.10",
+ install_requires=[
+ "click>=8.0.0",
+ "prompt-toolkit>=3.0.0",
+ ],
+ extras_require={
+ "dev": [
+ "pytest>=7.0.0",
+ "pytest-cov>=4.0.0",
+ ],
+ },
+ entry_points={
+ "console_scripts": [
+ "cli-anything-joplin=cli_anything.joplin.joplin_cli:main",
+ ],
+ },
+ package_data={
+ "cli_anything.joplin": [
+ "README.md",
+ "skills/SKILL.md",
+ "tests/TEST.md",
+ ],
+ },
+ include_package_data=True,
+ zip_safe=False,
+)
diff --git a/registry.json b/registry.json
index 6488bb30a..27f64f593 100644
--- a/registry.json
+++ b/registry.json
@@ -973,6 +973,25 @@
}
]
},
+ {
+ "name": "joplin",
+ "display_name": "Joplin",
+ "version": "1.0.0",
+ "description": "Note-taking and to-do automation — manage notebooks, notes, to-dos, tags, attachments, search, sync, and import/export via the Joplin terminal CLI",
+ "requires": "Joplin terminal CLI installed and available in PATH as `joplin` (npm install -g joplin)",
+ "homepage": "https://joplinapp.org",
+ "source_url": null,
+ "install_cmd": "pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=joplin/agent-harness",
+ "entry_point": "cli-anything-joplin",
+ "skill_md": "skills/cli-anything-joplin/SKILL.md",
+ "category": "knowledge",
+ "contributors": [
+ {
+ "name": "Rowan-coder1",
+ "url": "https://github.com/Rowan-coder1"
+ }
+ ]
+ },
{
"name": "unimol_tools",
"display_name": "Uni-Mol Tools",
diff --git a/skills/cli-anything-joplin/SKILL.md b/skills/cli-anything-joplin/SKILL.md
new file mode 100644
index 000000000..444b147ae
--- /dev/null
+++ b/skills/cli-anything-joplin/SKILL.md
@@ -0,0 +1,89 @@
+---
+name: "cli-anything-joplin"
+description: "Command-line interface for Joplin workflows using the real joplin terminal backend"
+---
+
+# cli-anything-joplin
+
+Use this skill to automate Joplin notebook, note, to-do, tag, attachment,
+search, sync, and import/export workflows through a stateful harness backed by
+the real `joplin` terminal binary.
+
+## Requirements
+
+- Python 3.10+
+- Joplin terminal binary available as `joplin` (`npm install -g joplin`)
+- Optional: pass `--profile` to target a specific Joplin profile
+
+## Install
+
+```bash
+pip install git+https://github.com/HKUDS/CLI-Anything.git#subdirectory=joplin/agent-harness
+```
+
+## Usage
+
+```bash
+# REPL mode (default)
+cli-anything-joplin
+
+# Machine-readable one-shot command
+cli-anything-joplin --json notebooks list
+
+# Stateful project
+cli-anything-joplin project new --name demo -o ./demo.joplin-harness.json
+cli-anything-joplin --project ./demo.joplin-harness.json notes create "Meeting note"
+
+# Dry-run (no auto-save)
+cli-anything-joplin --json --dry-run --project ./demo.joplin-harness.json notes create temp
+```
+
+## JSON output contract
+
+When `--json` is enabled, commands return:
+
+- `ok`: boolean
+- `command`: stable command identifier such as `notes.list`, `todos.toggle`
+- `data`: command payload
+- `error`: null on success, or `{ type, message }` on failure
+
+## Command groups
+
+- `project`: `new`, `open`, `save`, `info`, `json`, `status`
+- `notebooks`: `list`, `create`, `use`, `remove`
+- `notes`: `list`, `create`, `set`, `get`, `remove`, `copy`, `move`, `rename`
+- `todos`: `list`, `create`, `toggle`, `clear`, `done`, `undone`
+- `tags`: `list`, `add`, `remove`, `notetags`, `tagnotes`
+- `search`: `run`
+- `sync`: `run` (`--target`, `--upgrade`, `--use-lock`)
+- `interop`: `import`, `export`
+- `config`: `get`, `set`, `list`, `export`, `import-file`
+- `attach`: `add`
+- `status`: `show`, `restore`
+- `backend`: `version`, `dump`, `keymap`, `geoloc`, `export-sync-status`
+- `server`: `status`, `start`, `stop`
+- `e2ee`: `status`, `target-status`, `decrypt`, `decrypt-file`
+- `session`: `status`, `undo`, `redo`, `history`
+
+## Agent guidance
+
+- Prefer `--json` for parseable output.
+- Use `--project` when running multi-step workflows so history is persisted.
+- One-shot mutating commands auto-save the project unless `--dry-run` is set.
+- REPL mode does not auto-save; run `project save` explicitly.
+- Some Joplin CLI builds gate `search` behind GUI mode; if you see
+ `"only available in GUI mode"`, treat search as best-effort and parse the
+ `error.message` in the JSON envelope to decide whether to retry inside the
+ REPL.
+- Joplin 3.6.x can have a broken `version` command in npm global layouts; the
+ harness falls back to installed package metadata for `backend version`.
+
+## Recommended workflow
+
+1. `project new --name my-task -o ./my-task.joplin-harness.json` to create
+ harness state.
+2. Configure backend with `--profile /path/to/joplin-profile` to isolate from
+ the user's personal Joplin install.
+3. Run mutating commands with `--json --project ./my-task.joplin-harness.json`.
+4. Use `session history` for a structured audit of what the agent did.
+5. Export with `interop export <path> --format jex` for portable backups.