omnifocus_mcp 1.0.2 → 1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +9 -0
  3. data/README.md +16 -3
  4. data/docs/superpowers/plans/2026-11-17-server-gap-fixes.md +192 -0
  5. data/lib/omnifocus_mcp/infrastructure/apple_script.rb +83 -19
  6. data/lib/omnifocus_mcp/infrastructure/script_runner.rb +5 -4
  7. data/lib/omnifocus_mcp/json_rpc_compat.rb +1 -2
  8. data/lib/omnifocus_mcp/logger.rb +1 -0
  9. data/lib/omnifocus_mcp/resources/base.rb +2 -37
  10. data/lib/omnifocus_mcp/resources/stats_resource.rb +1 -1
  11. data/lib/omnifocus_mcp/tools/database_stats.rb +3 -3
  12. data/lib/omnifocus_mcp/tools/definitions/add_omni_focus_task_tool.rb +5 -1
  13. data/lib/omnifocus_mcp/tools/definitions/add_project_tool.rb +4 -1
  14. data/lib/omnifocus_mcp/tools/definitions/batch_add_items_tool.rb +5 -3
  15. data/lib/omnifocus_mcp/tools/definitions/date_formatter.rb +6 -3
  16. data/lib/omnifocus_mcp/tools/definitions/edit_item_tool.rb +25 -6
  17. data/lib/omnifocus_mcp/tools/definitions/key_normalizer.rb +21 -1
  18. data/lib/omnifocus_mcp/tools/definitions/query_omnifocus_tool.rb +1 -2
  19. data/lib/omnifocus_mcp/tools/generators/add_omni_focus_task.rb +8 -13
  20. data/lib/omnifocus_mcp/tools/generators/add_project.rb +4 -6
  21. data/lib/omnifocus_mcp/tools/generators/database_stats.rb +1 -2
  22. data/lib/omnifocus_mcp/tools/generators/edit_item.rb +38 -53
  23. data/lib/omnifocus_mcp/tools/generators/note_edit.rb +108 -0
  24. data/lib/omnifocus_mcp/tools/generators/query_omnifocus.rb +11 -7
  25. data/lib/omnifocus_mcp/tools/generators/remove_item.rb +1 -1
  26. data/lib/omnifocus_mcp/tools/messages/add_omni_focus_task.rb +5 -3
  27. data/lib/omnifocus_mcp/tools/operations/add_omni_focus_task.rb +5 -3
  28. data/lib/omnifocus_mcp/tools/operations/add_project.rb +3 -3
  29. data/lib/omnifocus_mcp/tools/operations/batch_add_items/bulk_executor.rb +1 -1
  30. data/lib/omnifocus_mcp/tools/operations/batch_add_items.rb +4 -2
  31. data/lib/omnifocus_mcp/tools/operations/database_stats.rb +3 -3
  32. data/lib/omnifocus_mcp/tools/operations/edit_item.rb +3 -3
  33. data/lib/omnifocus_mcp/tools/operations/list_perspectives.rb +1 -1
  34. data/lib/omnifocus_mcp/tools/operations/remove_item.rb +3 -3
  35. data/lib/omnifocus_mcp/tools/params/mcp_boundary.rb +4 -2
  36. data/lib/omnifocus_mcp/tools/params.rb +2 -2
  37. data/lib/omnifocus_mcp/tools/presenters/query_results.rb +12 -8
  38. data/lib/omnifocus_mcp/utils/blank.rb +4 -0
  39. data/lib/omnifocus_mcp/utils/date_filter.rb +1 -2
  40. data/lib/omnifocus_mcp/version.rb +1 -1
  41. metadata +4 -2
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b8c375f2413b7dd77c677c5abed0ccb49b4efebd2ed7e8fc36179f65cd763154
4
- data.tar.gz: ca70f41c0e96bbb3a5048d1c673a950fe91f252c3b658eb09c99d0462452a35c
3
+ metadata.gz: 7fd32047c6b85209ce4dafb0e0fc40418be8378b72392e26b50caad5eed8bd6a
4
+ data.tar.gz: 2ccdcf095791c70141484d137039dec9b606a19792be98201e986ed8ea4f7301
5
5
  SHA512:
6
- metadata.gz: e2887652751a36fec3f1fbadfbc9feca9c64a9063317f25a1c13a8f0817236c4f2fa0fdf022b4930d8cce7493a8a0b217c72ed100755b55a44a9733888f122a8
7
- data.tar.gz: fd235093c277e4bd78d5886512d66489f2524c39c3af875877502bdd7fba3064de3b19287660e7582009eab69a9e7646ca98e0ab3c7b3cab451124f3a4940556
6
+ metadata.gz: 465e32cdd0343b752abdf94016ec27f096c84a60070b561ec4b17471b6404092584b765924be6827f1c70a563fd2e9d47a7d920bf617d4d8b330487b19898358
7
+ data.tar.gz: bfe75ebd34e7c4ad70ce1ae92e59dd5af3cdc6afab91c45fa6cc92957c9564af61f2ed4407ea71d7db51acf08de3198f518795c37ed364584cab42f87fab688e
data/CHANGELOG.md CHANGED
@@ -1,5 +1,14 @@
1
1
  # Changelog
2
2
 
3
+ ## [1.1]
4
+
5
+ - Fix `hasNote: false` excluding tasks with empty notes
6
+ - Stop task queries returning each project's root task as a task
7
+ - Escape names in AppleScript JSON replies so a `"` or `\` in a name no longer makes a saved change report as failed
8
+ - Keep line breaks in notes written by `add_omnifocus_task`, `add_project` and `edit_item`
9
+ - Support nested tag paths such as `"Work/Mac"` in `tags`, `addTags`, `removeTags` and `replaceTags`. A tag name containing `/` is now read as a path
10
+ - Add `appendNote` and `noteReplacements` to `edit_item` so part of a note can change without rewriting it
11
+
3
12
  ## [1.0.2]
4
13
 
5
14
  - Remove `bundler/setup` from the executable so the gem runs correctly when
data/README.md CHANGED
@@ -26,7 +26,9 @@ This tool was heavily inspired by [OmniFocus MCP Server](https://github.com/them
26
26
  - `remove_item` - Removes a task or project by ID, or by name when an ID is not
27
27
  available.
28
28
  - `edit_item` - Updates a task or project, including names, notes, dates, flags,
29
- estimates, statuses, tags, and location.
29
+ estimates, statuses, tags, and location. `appendNote` adds a line to the end
30
+ of a note and `noteReplacements` swaps text inside it, without rewriting the
31
+ whole note.
30
32
  - `batch_add_items` - Adds multiple tasks or projects in one operation,
31
33
  including support for task hierarchy within the batch.
32
34
  - `batch_remove_items` - Removes multiple tasks or projects in one operation.
@@ -60,9 +62,15 @@ This tool was heavily inspired by [OmniFocus MCP Server](https://github.com/them
60
62
  gem install omnifocus-mcp
61
63
  ```
62
64
 
63
- ## Configure an MCP Client
65
+ ## Install in Claude Code
64
66
 
65
- After installing the executable, add this config to any MCP client that supports
67
+ ```sh
68
+ claude mcp add --transport stdio --scope user omnifocus -- omnifocus-mcp
69
+ ```
70
+
71
+ ## Configure other MCP Clients
72
+
73
+ After installing the executable, add this server to any MCP client that supports
66
74
  stdio servers:
67
75
 
68
76
  ```json
@@ -103,6 +111,11 @@ RESOURCES:
103
111
 
104
112
  QUERY FILTER TIPS:
105
113
  - Tags filter is case-sensitive and exact match
114
+ - When adding or removing tags, "Parent/Child" picks a nested tag (e.g.
115
+ "Work/Mac"); a bare name matches the first tag with that name anywhere
116
+ - Use edit_item noteReplacements to change one line of a note (e.g. a
117
+ "Status: open" line) and appendNote to add to it; newNote replaces the
118
+ whole note
106
119
  - projectName filter is case-insensitive partial match
107
120
  - Status values for tasks: Next, Available, Blocked, DueSoon, Overdue
108
121
  - Status values for projects: Active, OnHold, Done, Dropped
@@ -0,0 +1,192 @@
1
+ # Server Gap Fixes Implementation Plan
2
+
3
+ > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
4
+
5
+ **Goal:** Fix the four confirmed server bugs and add the two missing features (nested tag paths, partial note edits) that force Gidoca agents to work around the server with a shell script.
6
+
7
+ **Architecture:** Every fix lives in the script generators (Ruby that emits AppleScript or Omni Automation JS) plus shared fragments in `Infrastructure::AppleScript`. New AppleScript building blocks (`multiline_string`, `json_escape_handler`, `tag_lookup`) are added there and reused by `AddOmniFocusTask`, `AddProject` and `EditItem`. `batch_add_items` reuses the `AddOmniFocusTask` generator, so it gets every add-side fix for free.
8
+
9
+ **Tech Stack:** Ruby 4.0, RSpec, fast-mcp, AppleScript and Omni Automation JS run via `osascript`.
10
+
11
+ **Spec:** The gap list in the Bear note "Why OmniFocus tags and status go through a shell script" (`bear://x-callback-url/open-note?id=965DA43D-6C6B-4910-9802-A7F8DAAA5054`), as checked against the code on 2026-11-17:
12
+
13
+ 1. `hasNote: false` matches nothing.
14
+ 2. A `"` in an item name breaks the JSON reply of `edit_item`, `add_omnifocus_task` and `add_project` (the change is saved but reported as failed).
15
+ 3. `AppleScript.escape` turns CR/LF into spaces, so every note the server writes is one line.
16
+ 4. `query_omnifocus` with `entity: "tasks"` returns each project's root task as a task.
17
+ 5. Tags are found by bare name only; there is no way to pick "ready-for-agent" inside "Gidoca triage", and nested tags can't be created.
18
+ 6. `edit_item` can only replace a whole note.
19
+
20
+ Out of scope: tag inheritance for new sub-actions (OmniFocus behaviour), exact `projectName` matching (`projectId` exists), root tasks in `database_stats` counts.
21
+
22
+ ## Global Constraints
23
+
24
+ - Follow `AGENTS.md`: `subject` declared above every `let` and `before`; group by `context`; one `expect` per example where practical.
25
+ - After every task: `bundle exec rspec` passes and `bundle exec rubocop` reports no offences.
26
+ - Tag path separator is `/`, matching the existing folder/project path syntax (`"Work/My Project"`).
27
+ - Note text keeps its line breaks as LF. Item **names** keep collapsing line breaks to spaces (`AppleScript.escape` is unchanged).
28
+ - Each task adds a bullet to a new `## [Unreleased]` section at the top of `CHANGELOG.md`.
29
+
30
+ ## Review Focus
31
+
32
+ 1. **Tag names that already contain `/`.** After Task 5 a bare tag named `a/b` becomes a path lookup. Expected: a path that resolves nothing with `create: true` creates the nested tags; document this in the tool description. Test in Task 5.
33
+ 2. **`noteReplacements` whose `find` text is absent.** Expected: error reply naming the missing text, and *no* property on the item changed, even if the same call also sets `newName`. Test in Task 6.
34
+ 3. **Names containing backslashes, not just quotes.** Expected: reply JSON parses and the name round-trips exactly. Test in Task 3.
35
+ 4. **Windows line endings (`\r\n`) in notes.** Expected: one LF per line break, not two. Test in Task 4.
36
+ 5. **`hasNote: false` on a task whose note is only whitespace.** Expected: matches (whitespace counts as no note, per the tool description). Test in Task 1.
37
+
38
+ ---
39
+
40
+ ### Task 1: Fix the `hasNote` filter
41
+
42
+ **Files:**
43
+ - Modify: `lib/omnifocus_mcp/tools/generators/query_omnifocus.rb:286-291` (`apply_task_misc_filters`)
44
+ - Test: `spec/omnifocus_mcp/tools/generators/query_omnifocus_spec.rb`
45
+
46
+ **Interfaces:** none new.
47
+
48
+ - [ ] **Step 1: Write the failing test.** In a `context "with hasNote filter"`, generate the script with `filters: { has_note: false }` and assert the emitted JS coerces to a boolean:
49
+
50
+ ```ruby
51
+ it "compares a boolean note check" do
52
+ expect(script).to include("const hasNote = Boolean(item.note && item.note.trim().length > 0);")
53
+ end
54
+ ```
55
+
56
+ - [ ] **Step 2: Run** `bundle exec rspec spec/omnifocus_mcp/tools/generators/query_omnifocus_spec.rb` — expect FAIL.
57
+ - [ ] **Step 3: Implement** — wrap the expression in `Boolean(...)`. (`"" && …` evaluates to `""`, and `"" !== false` is what drops every empty-note task.)
58
+ - [ ] **Step 4: Run** the spec — expect PASS. Run the full suite.
59
+ - [ ] **Step 5: Commit** `Fix hasNote: false excluding tasks with empty notes`.
60
+
61
+ ### Task 2: Exclude project root tasks from task queries
62
+
63
+ **Files:**
64
+ - Modify: `lib/omnifocus_mcp/tools/generators/query_omnifocus.rb:514-516`
65
+ - Test: `spec/omnifocus_mcp/tools/generators/query_omnifocus_spec.rb`
66
+
67
+ **Interfaces:** none new.
68
+
69
+ - [ ] **Step 1: Write the failing test** for `entity: "tasks"`:
70
+
71
+ ```ruby
72
+ it "skips project root tasks" do
73
+ expect(script).to include("items = flattenedTasks.filter(task => task.project === null);")
74
+ end
75
+ ```
76
+
77
+ - [ ] **Step 2: Run** — expect FAIL.
78
+ - [ ] **Step 3: Implement.** `Task.project` is non-null only for a project's root task.
79
+ - [ ] **Step 4: Run** — expect PASS. Full suite.
80
+ - [ ] **Step 5: Commit** `Exclude project root tasks from task queries`.
81
+
82
+ ### Task 3: JSON-safe replies from AppleScript
83
+
84
+ **Files:**
85
+ - Modify: `lib/omnifocus_mcp/infrastructure/apple_script.rb` (`tell_document`, new `json_escape_handler`)
86
+ - Modify: `lib/omnifocus_mcp/tools/generators/edit_item.rb:224` (`finalize_and_return`)
87
+ - Modify: `lib/omnifocus_mcp/tools/generators/add_omni_focus_task.rb:176-183` (`success_return`)
88
+ - Modify: `lib/omnifocus_mcp/tools/generators/add_project.rb:79`
89
+ - Test: `spec/omnifocus_mcp/infrastructure/apple_script_spec.rb`, the three generator specs, `spec/integration/task_lifecycle_spec.rb`
90
+
91
+ **Interfaces:**
92
+ - Produces: `AppleScript.json_escape_handler -> String` — a top-level AppleScript handler `on jsonEscape(theText) … end jsonEscape`. Callers inside a `tell` block call it as `my jsonEscape(x)`.
93
+ - `tell_document(body)` now appends `json_escape_handler` after `end try`, so every script built with it can call `my jsonEscape`.
94
+
95
+ - [ ] **Step 1: Write failing unit tests.**
96
+ - `apple_script_spec`: `tell_document("x")` includes `"on jsonEscape(theText)"`; its `on error` branch includes `my jsonEscape(errorMessage)`.
97
+ - `edit_item_spec`: script includes `my jsonEscape(itemName)`.
98
+ - `add_omni_focus_task_spec`: script includes `my jsonEscape(name of newTask)` and no longer embeds the literal escaped name in the reply.
99
+ - `add_project_spec`: script includes `my jsonEscape(name of newProject)`.
100
+ - [ ] **Step 2: Write the failing integration test** (`:requires_omnifocus`): create a task named `TEST:Say "hi" \ bye`, edit its note, assert `result.ok.name == 'TEST:Say "hi" \ bye'`.
101
+ - [ ] **Step 3: Run** unit specs — expect FAIL.
102
+ - [ ] **Step 4: Implement `json_escape_handler`.** Use text item delimiters to replace, in this order: `\` → `\\`, `"` → `\"`, `linefeed` → `\n`, `return` → `\r`, `tab` → `\t`; reset delimiters to `""` before returning. Route every interpolated name/error in the three replies through `my jsonEscape(...)`; build the add-task reply name from `name of newTask`, not the Ruby-escaped input.
103
+ - [ ] **Step 5: Run** unit specs — PASS. Run `INTEGRATION=1 bundle exec rspec spec/integration/task_lifecycle_spec.rb` — PASS.
104
+ - [ ] **Step 6: Commit** `Escape names in AppleScript JSON replies`.
105
+
106
+ ### Task 4: Keep line breaks in notes
107
+
108
+ **Files:**
109
+ - Modify: `lib/omnifocus_mcp/infrastructure/apple_script.rb` (new `multiline_string`)
110
+ - Modify: `add_omni_focus_task.rb:81`, `add_project.rb:39`, `edit_item.rb:148` (`new_note`)
111
+ - Test: `apple_script_spec.rb`, the three generator specs, `spec/integration/task_lifecycle_spec.rb`
112
+
113
+ **Interfaces:**
114
+ - Produces: `AppleScript.multiline_string(value) -> String` — escapes `"` and `\` like `escape`, normalises `\r\n` and `\r` to `\n`, and emits each LF as the two-character AppleScript escape `\n`. Result is the *inside* of a quoted literal, same contract as `escape`.
115
+
116
+ - [ ] **Step 1: Write failing unit tests.**
117
+ - `multiline_string("a\nb")` → `'a\nb'` (backslash + n).
118
+ - `multiline_string("a\r\nb\rc")` → `'a\nb\nc'`.
119
+ - `multiline_string('say "hi"')` → `'say \"hi\"'`.
120
+ - `edit_item` with `new_note: "Status: open\nBody"` includes `set note of foundItem to "Status: open\nBody"` (literal backslash-n).
121
+ - Same shape for `add_omni_focus_task` and `add_project` notes.
122
+ - [ ] **Step 2: Write the failing integration test:** add a task with note `"line one\nline two"`, query it back, assert `note == "line one\nline two"`.
123
+ - [ ] **Step 3: Run** — FAIL.
124
+ - [ ] **Step 4: Implement** `multiline_string` and switch the three note call sites to it. `update_string_property` in `EditItem` takes a new `escaper:` keyword so `name` keeps `escape`.
125
+ - [ ] **Step 5: Run** unit + integration — PASS.
126
+ - [ ] **Step 6: Commit** `Preserve line breaks in notes`.
127
+
128
+ ### Task 5: Nested tag paths
129
+
130
+ **Files:**
131
+ - Modify: `lib/omnifocus_mcp/infrastructure/apple_script.rb` (new `tag_lookup`, rewrite `tag_assignment`)
132
+ - Modify: `add_omni_focus_task.rb:326-337`, `add_project.rb:124-135`, `edit_item.rb:292-369`
133
+ - Modify: tag descriptions in `add_omni_focus_task_tool.rb:33`, `add_project_tool.rb:31`, `batch_add_items_tool.rb:36`, `edit_item_tool.rb:48-50`
134
+ - Test: `apple_script_spec.rb`, the three generator specs, `spec/integration/task_lifecycle_spec.rb`
135
+
136
+ **Interfaces:**
137
+ - Produces: `AppleScript.tag_lookup(var:, tag_path:, create:) -> String`. `tag_path` is raw (unescaped) text; the method splits on `/`, drops empty parts, escapes each. Sets `var` to the tag or `missing value`.
138
+ - Changes: `AppleScript.tag_assignment(item_var:, tag_path:)` (was `tag_name:`; callers now pass the raw tag, not an escaped one). Uses `tag_lookup(create: true)`.
139
+
140
+ Lookup algorithm for `["A", "B", "C"]`:
141
+ 1. `A` → `first flattened tag whose name is "A"` (bare names keep today's behaviour).
142
+ 2. Each later part → `first tag of <current> whose name is "<part>"`.
143
+ 3. On a miss: with `create: true`, `make new tag with properties {name:"<part>"}` (at `end of tags of <current>` after the first part); with `create: false`, set `var` to `missing value` and skip the remaining parts.
144
+
145
+ - [ ] **Step 1: Write failing unit tests.**
146
+ - `tag_lookup(var: "t", tag_path: "Gidoca triage/ready-for-agent", create: true)` includes `first flattened tag whose name is "Gidoca triage"` and `first tag of`, and `whose name is "ready-for-agent"`, and `at end of tags of`.
147
+ - With `create: false` the script does not include `make new tag`.
148
+ - A bare `"Mac"` produces no `first tag of`.
149
+ - `"a/b"` (Review Focus 1) is treated as a two-part path.
150
+ - `edit_item` with `remove_tags: ["Gidoca triage/wontfix"]` uses the lookup with `create: false`.
151
+ - `edit_item` with `replace_tags` still clears existing tags first.
152
+ - [ ] **Step 2: Write the failing integration test:** create a tag group `TEST:Triage` with child `ready`, plus a top-level `ready`; add a task with `tags: ["TEST:Triage/ready"]`; assert the task's tag id is the child's. Clean up both tags.
153
+ - [ ] **Step 3: Run** — FAIL.
154
+ - [ ] **Step 4: Implement.** Generate tag blocks per tag in Ruby (drop the AppleScript `repeat with tagName in tagNames` loops in `EditItem`). Update tool descriptions to: `Tags to assign. Use "Parent/Child" to pick a nested tag, e.g. "Gidoca triage/ready-for-agent"; missing tags are created at that path.` (remove: `…missing tags are ignored.`)
155
+ - [ ] **Step 5: Run** unit + integration — PASS.
156
+ - [ ] **Step 6: Commit** `Support nested tag paths`.
157
+
158
+ ### Task 6: Partial note edits in `edit_item`
159
+
160
+ **Files:**
161
+ - Modify: `lib/omnifocus_mcp/tools/params.rb:27-33` (`EditItemParams` gains `:append_note, :note_replacements`)
162
+ - Modify: `lib/omnifocus_mcp/tools/definitions/edit_item_tool.rb`
163
+ - Modify: `lib/omnifocus_mcp/tools/generators/edit_item.rb`
164
+ - Test: `edit_item_tool_spec.rb`, `edit_item_spec.rb`, `spec/integration/task_lifecycle_spec.rb`
165
+
166
+ **Interfaces:**
167
+ - Consumes: `AppleScript.multiline_string` (Task 4), `my jsonEscape` (Task 3).
168
+ - Produces (MCP schema):
169
+ - `appendNote` — `optional(:appendNote).filled(:string)`: appended after the existing note, separated by one LF (no separator when the note is empty).
170
+ - `noteReplacements` — `optional(:noteReplacements).array(:hash) { required(:find).filled(:string); required(:replace).value(:string) }`: each `find` replaced everywhere in the note by `replace`.
171
+ - Order when combined: `newNote`, then `noteReplacements`, then `appendNote`.
172
+ - Changed-properties labels: `"note (replaced text)"`, `"note (appended)"`.
173
+
174
+ - [ ] **Step 1: Write failing tests.**
175
+ - Tool spec: `noteReplacements: [{ find: "Status: open", replace: "Status: claimed" }]` reaches the operation as `note_replacements: [{ find: "Status: open", replace: "Status: claimed" }]`.
176
+ - Generator: with `note_replacements`, the script checks `if note of foundItem does not contain "Status: open"` and returns `Note text not found: Status: open` **before** any `set … of foundItem` line (assert the check's index is lower than `set name of foundItem`'s index when `new_name` is also given — Review Focus 2).
177
+ - Generator: with `append_note: "Answer"` the script includes `"Answer"` and `"note (appended)"`.
178
+ - [ ] **Step 2: Write the failing integration test:** create a task with note `"Status: open\nDetails"`; call `edit_item` with `noteReplacements` → note is `"Status: claimed\nDetails"`; call again with `appendNote: "Answer: done"` → note ends with `"Details\nAnswer: done"`.
179
+ - [ ] **Step 3: Run** — FAIL.
180
+ - [ ] **Step 4: Implement.** Put all `does not contain` guards first in `item_found_body`. Do the replacement with an AppleScript text-item-delimiters handler `replaceText(theText, findText, replaceText)` emitted next to `jsonEscape` (only when replacements are present).
181
+ - [ ] **Step 5: Run** unit + integration — PASS.
182
+ - [ ] **Step 6: Commit** `Add appendNote and noteReplacements to edit_item`.
183
+
184
+ ### Task 7: Live check and docs
185
+
186
+ **Files:**
187
+ - Modify: `README.md` (tool reference for tag paths, `appendNote`, `noteReplacements`)
188
+ - Modify: Bear note (spec) — strike the quirks this plan fixed
189
+
190
+ - [ ] **Step 1:** `INTEGRATION=1 bundle exec rspec` — all pass.
191
+ - [ ] **Step 2:** Restart the MCP server (`/mcp`) and by hand: query `Omnifocus MCP` tasks (no root task), add a task with a quoted multi-line note and tag `Gidoca triage/ready-for-agent` to the inbox, flip a `Status:` line with `noteReplacements`, then remove it.
192
+ - [ ] **Step 3:** Update README and the Bear note; commit `Document tag paths and partial note edits`.
@@ -3,7 +3,7 @@
3
3
  module OmnifocusMcp
4
4
  module Infrastructure
5
5
  # Composable AppleScript fragments for write-side primitives.
6
- # rubocop:disable Metrics/ModuleLength
6
+ # rubocop:disable-next Metrics/ModuleLength
7
7
  module AppleScript
8
8
  ITEM_TYPES = %w[task project].freeze
9
9
  LOOKUP_KINDS = %i[folder project].freeze
@@ -26,8 +26,18 @@ module OmnifocusMcp
26
26
  .gsub(/[\r\n]/, " ")
27
27
  end
28
28
 
29
+ # Like {escape}, but keeps line breaks: CRLF and CR become LF, and
30
+ # each LF is written as the AppleScript `\n` escape. Use for notes.
31
+ def multiline_string(value)
32
+ value.to_s
33
+ .gsub(/\r\n?/, "\n")
34
+ .gsub(/["\\]/) { |m| "\\#{m}" }
35
+ .gsub("\n", "\\n")
36
+ end
37
+
29
38
  # Wrap a script `body` in the standard OmniFocus front document
30
- # envelope used by write-side primitives.
39
+ # envelope used by write-side primitives. The script also defines
40
+ # the `jsonEscape` handler, so the body can call `my jsonEscape(x)`.
31
41
  def tell_document(body)
32
42
  <<~APPLESCRIPT
33
43
  try
@@ -37,8 +47,30 @@ module OmnifocusMcp
37
47
  end tell
38
48
  end tell
39
49
  on error errorMessage
40
- return "{\\"success\\":false,\\"error\\":\\"" & errorMessage & "\\"}"
50
+ return "{\\"success\\":false,\\"error\\":\\"" & my jsonEscape(errorMessage) & "\\"}"
41
51
  end try
52
+
53
+ #{json_escape_handler}
54
+ APPLESCRIPT
55
+ end
56
+
57
+ # Top-level AppleScript handler that escapes text for a JSON string
58
+ # value. Backslashes are replaced first so later escapes survive.
59
+ def json_escape_handler
60
+ <<~'APPLESCRIPT'.chomp
61
+ on jsonEscape(theText)
62
+ set theText to theText as text
63
+ set replacements to {{"\\", "\\\\"}, {"\"", "\\\""}, {linefeed, "\\n"}, {return, "\\r"}, {tab, "\\t"}}
64
+ set savedDelimiters to AppleScript's text item delimiters
65
+ repeat with pair in replacements
66
+ set AppleScript's text item delimiters to item 1 of pair
67
+ set parts to text items of theText
68
+ set AppleScript's text item delimiters to item 2 of pair
69
+ set theText to parts as text
70
+ end repeat
71
+ set AppleScript's text item delimiters to savedDelimiters
72
+ return theText
73
+ end jsonEscape
42
74
  APPLESCRIPT
43
75
  end
44
76
 
@@ -59,24 +91,43 @@ module OmnifocusMcp
59
91
  "#{sections.flatten.join("\n")}\n"
60
92
  end
61
93
 
62
- # Add an existing tag to `item_var`, creating it if it does not exist.
63
- def tag_assignment(item_var:, tag_name:)
94
+ # Add the tag at `tag_path` (raw text, e.g. "Parent/Child") to
95
+ # `item_var`, creating any missing tags along the path.
96
+ def tag_assignment(item_var:, tag_path:)
64
97
  <<~APPLESCRIPT.chomp
65
98
  try
66
- set theTag to first flattened tag where name = "#{tag_name}"
67
- add theTag to tags of #{item_var}
99
+ #{indent(text: tag_lookup(var: "theTag", tag_path: tag_path, create: true), prefix: " ")}
100
+ if theTag is not missing value then add theTag to tags of #{item_var}
68
101
  on error
69
- -- Tag might not exist, try to create it
70
- try
71
- set theTag to make new tag with properties {name:"#{tag_name}"}
72
- add theTag to tags of #{item_var}
73
- on error
74
- -- Could not create or add tag
75
- end try
102
+ -- Could not create or add tag
76
103
  end try
77
104
  APPLESCRIPT
78
105
  end
79
106
 
107
+ # Resolve the tag at `tag_path` (raw text). "A/B/C" finds A anywhere,
108
+ # then B inside A, then C inside B. Sets `var` to the tag, or to
109
+ # `missing value` when a part is missing and `create` is false.
110
+ def tag_lookup(var:, tag_path:, create:)
111
+ parts = tag_path.to_s.split("/")
112
+ .reject(&:empty?)
113
+ .map { |part| escape(part) }
114
+ return "set #{var} to missing value" if parts.empty?
115
+
116
+ first, *rest = parts
117
+ lines = [
118
+ "set #{var} to missing value",
119
+ "try",
120
+ %( set #{var} to first flattened tag whose name is "#{first}"),
121
+ "end try"
122
+ ]
123
+ if create
124
+ lines << %(if #{var} is missing value then set #{var} to make new tag with properties {name:"#{first}"})
125
+ end
126
+
127
+ rest.each { |part| lines << child_tag_lookup(var:, part:, create:) }
128
+ lines.join("\n")
129
+ end
130
+
80
131
  # Generate AppleScript that resolves a folder by path or simple name.
81
132
  def generate_folder_lookup_script(raw_folder_path:, var_name:, error_return_json:)
82
133
  generate_lookup_script(
@@ -114,6 +165,22 @@ module OmnifocusMcp
114
165
 
115
166
  private
116
167
 
168
+ def child_tag_lookup(var:, part:, create:)
169
+ parent = "#{var}Parent"
170
+ make_line = " if #{var} is missing value then set #{var} to " \
171
+ "make new tag with properties {name:\"#{part}\"} at end of tags of #{parent}"
172
+ [
173
+ "if #{var} is not missing value then",
174
+ " set #{parent} to #{var}",
175
+ " set #{var} to missing value",
176
+ " try",
177
+ %( set #{var} to first tag of #{parent} whose name is "#{part}"),
178
+ " end try",
179
+ (make_line if create),
180
+ "end if"
181
+ ].compact.join("\n")
182
+ end
183
+
117
184
  def id_lookup_lines(var:, collection:, item_type:, id:)
118
185
  return [] if id.empty?
119
186
 
@@ -167,7 +234,7 @@ module OmnifocusMcp
167
234
  APPLESCRIPT
168
235
  end
169
236
 
170
- # rubocop:disable Metrics/MethodLength
237
+ # rubocop:disable-next Metrics/MethodLength
171
238
  def nested_folder_lookup(var_name:, escaped_components:, error_return_json:)
172
239
  leaf_name = escaped_components.last
173
240
  list_items = applescript_string_list(escaped_components)
@@ -203,7 +270,6 @@ module OmnifocusMcp
203
270
  end if
204
271
  APPLESCRIPT
205
272
  end
206
- # rubocop:enable Metrics/MethodLength
207
273
 
208
274
  def simple_project_lookup(var_name:, escaped_components:, error_return_json:)
209
275
  name = escaped_components.first
@@ -218,7 +284,7 @@ module OmnifocusMcp
218
284
  APPLESCRIPT
219
285
  end
220
286
 
221
- # rubocop:disable Metrics/MethodLength
287
+ # rubocop:disable-next Metrics/MethodLength
222
288
  def nested_project_lookup(var_name:, escaped_components:, error_return_json:)
223
289
  project_name = escaped_components.last
224
290
  folder_components = escaped_components[0...-1]
@@ -255,9 +321,7 @@ module OmnifocusMcp
255
321
  end if
256
322
  APPLESCRIPT
257
323
  end
258
- # rubocop:enable Metrics/MethodLength
259
324
  end
260
325
  end
261
- # rubocop:enable Metrics/ModuleLength
262
326
  end
263
327
  end
@@ -175,7 +175,9 @@ module OmnifocusMcp
175
175
  stdout, stderr, status = runner.call("osascript", "-l", "JavaScript", path)
176
176
  return Result.error(format_run_failure(stderr, status)) unless status.success?
177
177
 
178
- OmnifocusMcp.logger.warn("[script_execution] Script stderr output: #{stderr}") if stderr && !stderr.empty?
178
+ if Utils::Blank.present?(stderr)
179
+ OmnifocusMcp.logger.warn("[script_execution] Script stderr output: #{stderr}")
180
+ end
179
181
  Result.ok(stdout)
180
182
  end
181
183
  rescue StandardError => e
@@ -185,13 +187,13 @@ module OmnifocusMcp
185
187
  def format_run_failure(stderr, status)
186
188
  exit_code = status.respond_to?(:exitstatus) ? status.exitstatus : status
187
189
  message = "osascript failed (exit #{exit_code})"
188
- message += ": #{stderr.strip}" unless stderr.nil? || stderr.empty?
190
+ message += ": #{stderr.strip}" unless Utils::Blank.blank?(stderr)
189
191
  message
190
192
  end
191
193
 
192
194
  # Build the JXA wrapper that calls `app.evaluateJavascript` with the
193
195
  # OmniJS source embedded inside a backtick template literal.
194
- # rubocop:disable Metrics/MethodLength
196
+ # rubocop:disable-next Metrics/MethodLength
195
197
  def wrap_omnifocus_source(source:, args:)
196
198
  script_with_args =
197
199
  if Utils::Blank.blank?(args)
@@ -220,7 +222,6 @@ module OmnifocusMcp
220
222
  }
221
223
  JXA
222
224
  end
223
- # rubocop:enable Metrics/MethodLength
224
225
 
225
226
  # JXA stdout -> {Result.ok(parsed)} or {Result.error} on parse failure.
226
227
  def parse_jxa_output(stdout)
@@ -34,7 +34,7 @@ module OmnifocusMcp
34
34
  end
35
35
  private_class_method :patch_server_send_error!
36
36
 
37
- # rubocop:disable Metrics
37
+ # rubocop:disable-next Metrics
38
38
  def patch_stdio_transport!
39
39
  return if stdio_transport_patched?
40
40
 
@@ -66,7 +66,6 @@ module OmnifocusMcp
66
66
  end
67
67
  end
68
68
  end
69
- # rubocop:enable Metrics
70
69
  private_class_method :patch_stdio_transport!
71
70
 
72
71
  def server_send_error_patched?
@@ -22,6 +22,7 @@ module OmnifocusMcp
22
22
  def build_logger
23
23
  Logger.new($stderr, progname: "omnifocus_mcp").tap { |log| log.level = Logger::WARN }
24
24
  end
25
+
25
26
  private :build_logger
26
27
 
27
28
  def reset_logger_if_stderr_changed
@@ -33,44 +33,9 @@ module OmnifocusMcp
33
33
  { error: e.message }
34
34
  end
35
35
 
36
- def snake_case_keys(obj)
37
- case obj
38
- when Hash
39
- obj.each_with_object({}) do |(key, value), out|
40
- out[snake_case_key(key)] = snake_case_keys(value)
41
- end
42
- when Array
43
- obj.map { |item| snake_case_keys(item) }
44
- else
45
- obj
46
- end
47
- end
48
-
49
- def camelize_keys(obj)
50
- case obj
51
- when Hash
52
- obj.each_with_object({}) do |(key, value), out|
53
- out[camel_case_key(key)] = camelize_keys(value)
54
- end
55
- when Array
56
- obj.map { |item| camelize_keys(item) }
57
- else
58
- obj
59
- end
60
- end
61
-
62
- def snake_case_key(key)
63
- return key unless key.is_a?(Symbol) || key.is_a?(String)
36
+ def snake_case_keys(obj) = Tools::Definitions::KeyNormalizer.snake_keys(obj, deep: true)
64
37
 
65
- key.to_s.gsub(/([a-z\d])([A-Z])/, '\1_\2').downcase.to_sym
66
- end
67
-
68
- def camel_case_key(key)
69
- return key unless key.is_a?(Symbol) || key.is_a?(String)
70
-
71
- parts = key.to_s.split("_")
72
- ([parts.first] + parts.drop(1).map(&:capitalize)).join
73
- end
38
+ def camelize_keys(obj) = Tools::Definitions::KeyNormalizer.camel_keys(obj)
74
39
 
75
40
  public
76
41
 
@@ -12,7 +12,7 @@ module OmnifocusMcp
12
12
  description "Quick OmniFocus database statistics overview"
13
13
 
14
14
  def payload
15
- Tools::Operations::DatabaseStats.get_database_stats.fold(
15
+ Tools::Operations::DatabaseStats.database_stats.fold(
16
16
  on_ok: ->(stats) { snake_case_keys(stats || {}) },
17
17
  on_error: ->(err) { { error: err } }
18
18
  )
@@ -6,14 +6,14 @@ module OmnifocusMcp
6
6
  # full OmniFocus dataset.
7
7
  #
8
8
  # Provides:
9
- # * {.get_database_stats} — counts + last-modified timestamp
9
+ # * {.database_stats} — counts + last-modified timestamp
10
10
  # * {.get_changes_since} — incremental change feed since a timestamp
11
11
  module DatabaseStats
12
12
  class << self
13
- def get_database_stats
13
+ def database_stats
14
14
  require_relative "operations/database_stats"
15
15
 
16
- Operations::DatabaseStats.get_database_stats
16
+ Operations::DatabaseStats.database_stats
17
17
  end
18
18
 
19
19
  # Incremental change feed since `since` (a Time, DateTime, or ISO string).
@@ -16,6 +16,7 @@ module OmnifocusMcp
16
16
  tool_name "add_omnifocus_task"
17
17
  description "Add a new task to OmniFocus"
18
18
 
19
+ # rubocop:disable-next Metrics/BlockLength
19
20
  arguments do
20
21
  required(:name).filled(:string).description("The name of the task")
21
22
  optional(:note).filled(:string).description("Additional notes for the task")
@@ -30,7 +31,10 @@ module OmnifocusMcp
30
31
  optional(:flagged).filled(:bool).description("Whether the task is flagged or not")
31
32
  optional(:estimatedMinutes).filled(:integer)
32
33
  .description("Estimated time to complete the task, in minutes")
33
- optional(:tags).array(:string).description("Tags to assign to the task")
34
+ optional(:tags).array(:string).description(
35
+ "Tags to assign to the task. " \
36
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are created at that path"
37
+ )
34
38
  optional(:projectName).filled(:string).description(
35
39
  "The name of the project to add the task to (will add to inbox if not specified)"
36
40
  )
@@ -28,7 +28,10 @@ module OmnifocusMcp
28
28
  optional(:flagged).filled(:bool).description("Whether the project is flagged or not")
29
29
  optional(:estimatedMinutes).filled(:integer)
30
30
  .description("Estimated time to complete the project, in minutes")
31
- optional(:tags).array(:string).description("Tags to assign to the project")
31
+ optional(:tags).array(:string).description(
32
+ "Tags to assign to the project. " \
33
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are created at that path"
34
+ )
32
35
  optional(:folderName).filled(:string).description(
33
36
  "The name of the folder to add the project to (will add to root if not specified)"
34
37
  )
@@ -16,7 +16,7 @@ module OmnifocusMcp
16
16
  tool_name "batch_add_items"
17
17
  description "Add multiple tasks or projects to OmniFocus in a single operation"
18
18
 
19
- # rubocop:disable Metrics/BlockLength
19
+ # rubocop:disable-next Metrics/BlockLength
20
20
  arguments do
21
21
  required(:items).array(:hash) do
22
22
  required(:type).filled(included_in?: %w[task project])
@@ -33,7 +33,10 @@ module OmnifocusMcp
33
33
  optional(:flagged).filled(:bool).description("Whether the item is flagged or not")
34
34
  optional(:estimatedMinutes).filled(:integer)
35
35
  .description("Estimated time to complete the item, in minutes")
36
- optional(:tags).array(:string).description("Tags to assign to the item")
36
+ optional(:tags).array(:string).description(
37
+ "Tags to assign to the item. " \
38
+ "Use 'Parent/Child' for a nested tag, e.g. 'Work/Mac'; missing tags are created at that path"
39
+ )
37
40
 
38
41
  optional(:projectName).filled(:string)
39
42
  .description("For tasks: The name of the project to add the task to")
@@ -56,7 +59,6 @@ module OmnifocusMcp
56
59
  "Process parents before children; when false, best-effort order will still try to resolve parents first"
57
60
  )
58
61
  end
59
- # rubocop:enable Metrics/BlockLength
60
62
 
61
63
  extend OperationFactory
62
64
 
@@ -14,9 +14,12 @@ module OmnifocusMcp
14
14
  return "" if Utils::Blank.blank?(iso)
15
15
 
16
16
  case style
17
- when :locale then format_parsed(iso) { |d| us_short_date(d) }
18
- when :compact then format_parsed(iso) { |d| us_compact_date(d) }
19
- when :iso then Utils::IsoDate.to_date_only(iso)
17
+ when :locale
18
+ format_parsed(iso) { |d| us_short_date(d) }
19
+ when :compact
20
+ format_parsed(iso) { |d| us_compact_date(d) }
21
+ when :iso
22
+ Utils::IsoDate.to_date_only(iso)
20
23
  else raise ArgumentError, "Unknown date style: #{style.inspect}"
21
24
  end
22
25
  end