diff --git a/CHANGELOG.md b/CHANGELOG.md index c6a80fe..b3a1351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,54 @@ # Changelog +## 2.1.0 + +Writes could report success for changes that never happened. 2.0.4 fixed one +command; this finishes the job, verifies every write against the database, adds +re-parenting, and closes a credential leak found on the way. + +- **`complete`, `move` and `tag` still no-opped on projects.** 2.0.4 routed + `update` to `things:///update-project` but left the other three building + `things:///update`, which Things ignores for a project uuid. `open` still + exits 0, so `thingsctl complete ` printed `✓ Completed` while the row + stayed `status = 0`. All write commands now route by entity type, and headings + are refused outright rather than dispatched into a command that cannot apply. +- **Success is now verified against the database, not assumed.** `open` exiting + 0 only means macOS handed the URL to Things. Writes poll the row until the + change is visible and report a clear failure otherwise. This is what turned + the routing bug from an error into a lie. Timeout is overridable with + `THINGSCTL_VERIFY_TIMEOUT_MS` (the URL scheme can cold-launch Things, which + takes longer than the 3s default); the MCP server defaults to 1200ms because + the wait is synchronous and blocks its event loop. Bulk `complete` now shares + one budget instead of spending the full timeout on every id. +- **Security: the auth token leaked into error output.** macOS `open` echoes the + whole failing URL, `auth-token` included, and that text was spliced into + `ThingsUrlError` — which the CLI prints to stderr and the MCP server returns + as tool output, i.e. into a model transcript. The token is now redacted before + it can reach any sink. +- **Security: `%` in an id matched every task.** `resolveTaskId` interpolated + the id straight into a `LIKE` pattern, so `complete '%' --yes-first` resolved + to an arbitrary row. Wildcards are escaped now. This mattered more once + `update` could relocate work rather than only complete it. +- **`--completed false` completed the task instead of reopening it.** The CLI + parser yields the string `'false'`, which is truthy, so the flag sent the + opposite of what it says. Booleans are normalised once, up front. +- **Added: move a to-do or project to a different parent.** Previously + impossible through the tool. `update --list` / `--list-id` moves a to-do into + a project or area, `update --area` / `--area-id` moves a project into an area, + and the move is verified against the row rather than against "something + changed". Passing the wrong pair for the type is refused with an explanation. +- `tag` now tells the truth when a tag does not exist. Things silently drops an + `add-tags` naming a tag it has never seen; that used to print a checkmark. +- `things_move`'s description said "moving it to...", which read as a re-parent + when it only ever rescheduled. Fixed, along with its success string, which + said "Moved" while its failure string said "did not reschedule". +- `thingsctl update --help` was missing every flag added here; the CLI keeps a + hand-curated flag allowlist, so a new option has to be registered in four + places. Documented; consolidating that is left as follow-up. + +New: `src/lib/verify.js`, `url.buildUpdateProjectUrl` (from 2.0.4), +`db.openFresh`, `exec.redactToken`. 129 tests, up from 79 at 2.0.3. + ## 2.0.4 Fix `update` silently no-opping on projects. Things applies the `update` diff --git a/README.md b/README.md index 1202039..48dac2d 100644 --- a/README.md +++ b/README.md @@ -67,12 +67,25 @@ thingsctl add "Trip prep" --checklist "Passport,Tickets,Charger" thingsctl add "Tax filing" --when 2027-04-15 --deadline 2027-04-15 --tags Important thingsctl update 7Ae --title "New title" --append-notes "context" -thingsctl complete 7Ae # Single +thingsctl complete 7Ae # Single (to-do or project) thingsctl complete 7Ae 17j 9pU # Bulk -thingsctl move 7Ae --to "next week" +thingsctl move 7Ae --to "next week" # RESCHEDULES; does not change project/area thingsctl tag 7Ae --add Urgent ``` +### Moving between projects and areas + +`move` reschedules. To change what a to-do or project *belongs to*, use `update`. +Things exposes different parameters for the two, and mixing them up is refused +rather than silently dropped: + +```bash +thingsctl update 7Ae --list "Berlin Trip" # to-do → project or area, by title +thingsctl update 7Ae --list-id Xm55Bsr1Wmk # to-do → project or area, by uuid +thingsctl update p01 --area "Travel" # project → area, by title +thingsctl update p01 --area-id 7U6P28t2BfE # project → area, by uuid +``` + ### Workflows ```bash diff --git a/bin/thingsctl-mcp.js b/bin/thingsctl-mcp.js index edfc451..0cd5a85 100755 --- a/bin/thingsctl-mcp.js +++ b/bin/thingsctl-mcp.js @@ -4,6 +4,11 @@ // Force NO_COLOR for MCP responses — clients render the text content as-is. process.env.NO_COLOR = '1'; +// Write verification sleeps synchronously, which blocks this server's event +// loop. The CLI can afford a 3s worst case; a long-lived stdio server cannot, +// so default it lower here. THINGSCTL_VERIFY_TIMEOUT_MS still wins if set. +if (!process.env.THINGSCTL_VERIFY_TIMEOUT_MS) process.env.THINGSCTL_VERIFY_TIMEOUT_MS = '1200'; + const { start } = require('../src/mcp/server'); start().catch((e) => { diff --git a/package-lock.json b/package-lock.json index b16c7b3..4eca949 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "thingsctl", - "version": "2.0.4", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "thingsctl", - "version": "2.0.4", + "version": "2.1.0", "license": "MIT", "os": [ "darwin" diff --git a/package.json b/package.json index 9f9f63e..ee343ed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "thingsctl", - "version": "2.0.4", + "version": "2.1.0", "description": "A full-featured command-line interface and MCP server for Things 3 on macOS.", "main": "src/cli.js", "type": "commonjs", diff --git a/src/cli.js b/src/cli.js index 6766573..f62c06d 100644 --- a/src/cli.js +++ b/src/cli.js @@ -97,6 +97,7 @@ function dispatch(parsed) { title: o.title, notes: o.notes, 'append-notes': o['append-notes'], 'prepend-notes': o['prepend-notes'], when: o.when, deadline: o.deadline, 'add-tags': o['add-tags'], + list: o.list, 'list-id': o['list-id'], area: o.area, 'area-id': o['area-id'], completed: o.completed, canceled: o.canceled, 'yes-first': opts['yes-first'], }); diff --git a/src/commands/complete.js b/src/commands/complete.js index 45e2fe8..7a205ac 100644 --- a/src/commands/complete.js +++ b/src/commands/complete.js @@ -2,11 +2,12 @@ const db = require('../lib/db'); const { resolveMany } = require('../lib/uuid'); -const { buildUpdateUrl } = require('../lib/url'); +const { buildUpdateUrl, buildUpdateProjectUrl } = require('../lib/url'); const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); const { colors } = require('../lib/format'); -const { STATUS } = require('../lib/constants'); +const { STATUS, TYPE } = require('../lib/constants'); +const { waitForWrite, notApplied, DEFAULT_TIMEOUT_MS } = require('../lib/verify'); const queries = require('../lib/queries'); function run(ids, opts = {}) { @@ -14,6 +15,10 @@ function run(ids, opts = {}) { const database = db.open(); const { resolved, errors } = resolveMany(database, list, { yesFirst: opts['yes-first'] }); const out = []; + // One slow id should not make the whole batch slow. If Things did not take + // write #1 it is not taking #7 either, so drop to a short probe after the + // first timeout instead of burning the full budget per item. + let budgetMs = DEFAULT_TIMEOUT_MS; for (const { error, input } of errors) { out.push(`${colors.red('✗')} ${error.code === 'E_AMBIGUOUS' ? error.message : `Not found: ${input}`}`); @@ -25,12 +30,33 @@ function run(ids, opts = {}) { out.push(`${colors.dim('Already completed: ' + full.title)}`); continue; } + if (task.type === TYPE.HEADING) { + out.push(`${colors.red('✗')} Cannot complete a heading: ${task.title}`); + continue; + } + + // Projects are only reachable through `update-project`. Sending them to + // `update` is a silent no-op — the bug this dispatch exists to prevent. + const isProject = task.type === TYPE.PROJECT; + const params = { id: task.uuid, completed: 'true', 'auth-token': getToken() }; + const url = isProject ? buildUpdateProjectUrl(params) : buildUpdateUrl(params); + const label = isProject ? 'project' : 'task'; + try { - openUrl(buildUpdateUrl({ id: task.uuid, completed: 'true', 'auth-token': getToken() })); - out.push(`${colors.green('✓')} Completed: ${task.title}`); + openUrl(url); } catch (e) { - out.push(`${colors.red('✗')} Failed: ${task.title} (${e.message})`); + // e.message carries the redacted url; keep it out of per-item output anyway. + out.push(`${colors.red('✗')} Failed: ${task.title} (could not reach Things)`); + continue; } + + const { ok } = waitForWrite(task.uuid, (r) => r.status === STATUS.COMPLETED, { timeoutMs: budgetMs }); + if (!ok) budgetMs = 250; + out.push( + ok + ? `${colors.green('✓')} Completed ${label}: ${task.title}` + : notApplied(`complete the ${label}`, task.title) + ); } return list.length === 1 ? out[0] : out; } @@ -39,7 +65,7 @@ module.exports = { run, mcp: { name: 'things_complete', - description: 'Mark one or more tasks as complete.', + description: 'Mark one or more tasks or projects as complete. Verified against the database before reporting success.', inputSchema: { type: 'object', properties: { diff --git a/src/commands/move.js b/src/commands/move.js index cafb749..e659735 100644 --- a/src/commands/move.js +++ b/src/commands/move.js @@ -2,25 +2,43 @@ const db = require('../lib/db'); const { resolveTaskId } = require('../lib/uuid'); -const { buildUpdateUrl } = require('../lib/url'); +const { buildUpdateUrl, buildUpdateProjectUrl } = require('../lib/url'); const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); +const { colors } = require('../lib/format'); +const { TYPE } = require('../lib/constants'); +const { waitForWrite, snapshot, modifiedSince, notApplied } = require('../lib/verify'); +// NOTE: this command RESCHEDULES. It does not change which project or area a +// task belongs to — that is `update --list` / `update --area`. The name is +// historical; the description says so plainly so callers stop guessing. function run(id, opts = {}) { if (!id) throw new Error('Task id required'); if (!opts.to) throw new Error('--to option required'); if (opts.to === 'inbox') throw new Error('Moving to inbox is not supported via the Things URL scheme'); const database = db.open(); const ref = resolveTaskId(database, id, { yesFirst: opts['yes-first'] }); - openUrl(buildUpdateUrl({ id: ref.uuid, when: opts.to, 'auth-token': getToken() })); - return `Moved "${ref.title}" to ${opts.to}`; + if (ref.type === TYPE.HEADING) { + throw new Error(`"${ref.title}" is a heading. Headings cannot be scheduled.`); + } + + const params = { id: ref.uuid, when: opts.to, 'auth-token': getToken() }; + const before = snapshot(ref.uuid); + openUrl(ref.type === TYPE.PROJECT ? buildUpdateProjectUrl(params) : buildUpdateUrl(params)); + + const { ok } = waitForWrite(ref.uuid, modifiedSince(before)); + if (!ok) return notApplied('reschedule', ref.title); + return `Rescheduled "${ref.title}" to ${opts.to}`; } module.exports = { run, mcp: { name: 'things_move', - description: 'Reschedule a task by moving it to today/anytime/someday/evening or a specific date.', + description: + 'RESCHEDULE a to-do or project to today/anytime/someday/evening or a specific date. ' + + 'This does NOT change which project or area it belongs to — use things_update with ' + + 'list/list-id (to-dos) or area/area-id (projects) for that.', inputSchema: { type: 'object', properties: { diff --git a/src/commands/tag.js b/src/commands/tag.js index 7595017..295d271 100644 --- a/src/commands/tag.js +++ b/src/commands/tag.js @@ -2,9 +2,12 @@ const db = require('../lib/db'); const { resolveTaskId } = require('../lib/uuid'); -const { buildUpdateUrl } = require('../lib/url'); +const { buildUpdateUrl, buildUpdateProjectUrl } = require('../lib/url'); const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); +const { colors } = require('../lib/format'); +const { TYPE } = require('../lib/constants'); +const { waitForWrite, snapshot, modifiedSince, notApplied } = require('../lib/verify'); function run(id, opts = {}) { if (!id) throw new Error('Task id required'); @@ -12,8 +15,20 @@ function run(id, opts = {}) { const ref = resolveTaskId(database, id, { yesFirst: opts['yes-first'] }); if (opts.add) { - openUrl(buildUpdateUrl({ id: ref.uuid, 'add-tags': opts.add, 'auth-token': getToken() })); - return `Added tag "${opts.add}" to "${ref.title}"`; + if (ref.type === TYPE.HEADING) { + throw new Error(`"${ref.title}" is a heading. Headings cannot be tagged.`); + } + const params = { id: ref.uuid, 'add-tags': opts.add, 'auth-token': getToken() }; + // Same routing rule as every other write: Things ignores `update` on a + // project, so tagging one through it was a silent no-op reporting success. + const isProject = ref.type === TYPE.PROJECT; + const before = snapshot(ref.uuid); + openUrl(isProject ? buildUpdateProjectUrl(params) : buildUpdateUrl(params)); + + const { ok } = waitForWrite(ref.uuid, modifiedSince(before)); + if (!ok) return notApplied('tag', ref.title); + const label = isProject ? 'project ' : ''; + return `${colors.green('✓')} Added tag "${opts.add}" to ${label}"${ref.title}"`; } if (opts.remove) { throw new Error('Removing tags is not supported by the Things URL scheme (it would replace all tags).'); @@ -25,7 +40,7 @@ module.exports = { run, mcp: { name: 'things_tag', - description: 'Add a tag to a task. Tags must already exist in Things.', + description: 'Add a tag to a to-do or project. Tags must already exist in Things. Verified against the database before reporting success.', inputSchema: { type: 'object', properties: { id: { type: 'string' }, add: { type: 'string' } }, diff --git a/src/commands/update.js b/src/commands/update.js index c33efba..97f8e47 100644 --- a/src/commands/update.js +++ b/src/commands/update.js @@ -7,15 +7,67 @@ const { buildUpdateUrl, buildUpdateProjectUrl } = require('../lib/url'); const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); const { colors } = require('../lib/format'); +const { TYPE, STATUS } = require('../lib/constants'); +const { waitForWrite, snapshot, modifiedSince, notApplied } = require('../lib/verify'); + +// The CLI parser hands flag values through as strings, so `--completed false` +// arrives as the STRING 'false', which is truthy. Left uncoerced that sends +// completed=true and COMPLETES the task the flag was meant to reopen. +function asBool(v) { + if (v === undefined || v === null) return undefined; + if (typeof v === 'boolean') return v; + const s = String(v).trim().toLowerCase(); + if (s === 'false' || s === '0' || s === 'no') return false; + return true; +} + +// Resolve a project or area TITLE to its uuid so the re-parent can be verified +// against the row rather than trusting "something changed". +function _resolveListTarget(database, title) { + const proj = database + .prepare('SELECT uuid FROM TMTask WHERE type = ? AND trashed = 0 AND title = ? LIMIT 2') + .all(TYPE.PROJECT, title); + if (proj.length === 1) return { field: 'project', uuid: proj[0].uuid }; + const area = database + .prepare('SELECT uuid FROM TMArea WHERE title = ? LIMIT 2') + .all(title); + if (area.length === 1) return { field: 'area', uuid: area[0].uuid }; + return null; +} function run(id, opts = {}) { if (!id) throw new Error('Task id required'); const database = db.open(); const ref = resolveTaskId(database, id, { yesFirst: opts['yes-first'] }); const task = queries.getTask(database, ref.uuid); + const isProject = ref.type === TYPE.PROJECT; + + if (ref.type === TYPE.HEADING) { + throw new Error(`"${ref.title}" is a heading. Things has no update command for headings.`); + } + + // `list`/`list-id` exist only on `update`; `area`/`area-id` only on + // `update-project`. Passing the wrong one is dropped silently by Things, so + // refuse it here rather than report a move that never happened. + if (isProject && (opts.list || opts['list-id'])) { + throw new Error( + `"${task.title}" is a project. Use --area/--area-id to move it into an area; ` + + '--list/--list-id only applies to to-dos.' + ); + } + if (!isProject && (opts.area || opts['area-id'])) { + throw new Error( + `"${task.title}" is a to-do. Use --list/--list-id to move it into a project or area; ` + + '--area/--area-id only applies to projects.' + ); + } + + const completed = asBool(opts.completed); + const canceled = asBool(opts.canceled); const params = { id: task.uuid, 'auth-token': getToken() }; const changes = []; + let reparent = null; // { field, uuid } when we can verify the move exactly if (opts.title) { params.title = opts.title; changes.push(`title → "${opts.title}"`); } if (opts.notes) { params.notes = opts.notes; changes.push('notes updated'); } @@ -30,20 +82,59 @@ function run(id, opts = {}) { if (opts.when) { params.when = opts.when; changes.push(`when → ${opts.when}`); } if (opts.deadline) { params.deadline = opts.deadline; changes.push(`deadline → ${opts.deadline}`); } if (opts['add-tags']) { params['add-tags'] = opts['add-tags']; changes.push(`tags += ${opts['add-tags']}`); } - if (opts.completed !== undefined) { - params.completed = opts.completed ? 'true' : 'false'; - changes.push(opts.completed ? 'completed' : 'reopened'); + + // Re-parenting. The -id forms take precedence over the title forms, matching + // the Things URL scheme. + if (opts['list-id']) { + params['list-id'] = opts['list-id']; + changes.push(`moved into ${opts['list-id']}`); + reparent = { field: null, uuid: opts['list-id'] }; // project OR area column + } else if (opts.list) { + params.list = opts.list; + changes.push(`moved into "${opts.list}"`); + reparent = _resolveListTarget(database, opts.list); + } + if (opts['area-id']) { + params['area-id'] = opts['area-id']; + changes.push(`moved into area ${opts['area-id']}`); + reparent = { field: 'area', uuid: opts['area-id'] }; + } else if (opts.area) { + params.area = opts.area; + changes.push(`moved into area "${opts.area}"`); + const found = database.prepare('SELECT uuid FROM TMArea WHERE title = ? LIMIT 2').all(opts.area); + reparent = found.length === 1 ? { field: 'area', uuid: found[0].uuid } : null; + } + + if (completed !== undefined) { + params.completed = completed ? 'true' : 'false'; + changes.push(completed ? 'completed' : 'reopened'); } - if (opts.canceled !== undefined) { - params.canceled = opts.canceled ? 'true' : 'false'; - changes.push(opts.canceled ? 'canceled' : 'uncanceled'); + if (canceled !== undefined) { + params.canceled = canceled ? 'true' : 'false'; + changes.push(canceled ? 'canceled' : 'uncanceled'); } if (changes.length === 0) throw new Error('No changes specified'); - // type 1 = project; Things ignores `update` on projects, so route to `update-project`. - const isProject = ref.type === 1; + const before = snapshot(task.uuid); openUrl(isProject ? buildUpdateProjectUrl(params) : buildUpdateUrl(params)); + + // Assert the end state wherever we know it. modifiedSince is the weak + // fallback: it cannot tell our write apart from a concurrent edit or a sync. + let predicate = modifiedSince(before); + if (canceled === true) predicate = (r) => r.status === STATUS.CANCELED; + else if (completed === true) predicate = (r) => r.status === STATUS.COMPLETED; + else if (completed === false || canceled === false) predicate = (r) => r.status === STATUS.OPEN; + else if (reparent) { + const want = reparent.uuid; + predicate = reparent.field + ? (r) => r[reparent.field] === want + : (r) => r.project === want || r.area === want; + } + + const { ok } = waitForWrite(task.uuid, predicate); + if (!ok) return notApplied('apply the change to', task.title); + const label = isProject ? 'project ' : ''; return `${colors.green('✓')} Updated ${label}"${task.title}": ${changes.join(', ')}`; } @@ -52,7 +143,9 @@ module.exports = { run, mcp: { name: 'things_update', - description: 'Update fields on an existing task.', + description: + 'Update fields on an existing to-do or project, including moving it to a different ' + + 'project or area. Verified against the database before reporting success.', inputSchema: { type: 'object', properties: { @@ -64,12 +157,25 @@ module.exports = { when: { type: 'string' }, deadline: { type: 'string' }, 'add-tags': { type: 'string' }, + list: { type: 'string', description: 'TO-DOS ONLY. Title of a project or area to move the to-do into.' }, + 'list-id': { type: 'string', description: 'TO-DOS ONLY. UUID of a project or area to move the to-do into. Takes precedence over list.' }, + area: { type: 'string', description: 'PROJECTS ONLY. Title of an area to move the project into.' }, + 'area-id': { type: 'string', description: 'PROJECTS ONLY. UUID of an area to move the project into. Takes precedence over area.' }, completed: { type: 'boolean' }, canceled: { type: 'boolean' }, }, required: ['id'], additionalProperties: false, }, - handler: ({ id, ...rest }) => ({ ok: true, message: run(id, rest) }), + // Whitelist rather than spreading rest: the low-level MCP Server does not + // enforce inputSchema, so additionalProperties:false buys nothing at runtime. + handler: (a = {}) => + ({ ok: true, message: run(a.id, { + title: a.title, notes: a.notes, + 'append-notes': a['append-notes'], 'prepend-notes': a['prepend-notes'], + when: a.when, deadline: a.deadline, 'add-tags': a['add-tags'], + list: a.list, 'list-id': a['list-id'], area: a.area, 'area-id': a['area-id'], + completed: a.completed, canceled: a.canceled, + }) }), }, }; diff --git a/src/help.js b/src/help.js index 48aeb63..6530ab7 100644 --- a/src/help.js +++ b/src/help.js @@ -94,8 +94,12 @@ ${colors.bold('Options:')} --when Reschedule --deadline Set deadline --add-tags Add tags - --completed Mark complete - --canceled Mark canceled + --completed [true|false] Mark complete, or reopen with --completed false + --canceled [true|false] Mark canceled, or reopen with --canceled false + --list TO-DOS: move into this project or area + --list-id <uuid> TO-DOS: move into this project or area (wins over --list) + --area <title> PROJECTS: move into this area + --area-id <uuid> PROJECTS: move into this area (wins over --area) `, complete: ` ${colors.bold('thingsctl complete')} - Mark task(s) complete diff --git a/src/lib/db.js b/src/lib/db.js index b96b38e..4942ce1 100644 --- a/src/lib/db.js +++ b/src/lib/db.js @@ -3,6 +3,7 @@ const { DB_PATH } = require('./constants'); let _db = null; +let _isTestDb = false; function open(dbPath = DB_PATH) { if (_db) return _db; @@ -11,16 +12,31 @@ function open(dbPath = DB_PATH) { return _db; } +// A separate, short-lived readonly connection. Used by lib/verify to re-read a +// row after a URL-scheme write without disturbing (or reading a stale snapshot +// through) the long-lived singleton. Caller closes it. +function openFresh(dbPath = DB_PATH) { + // Under the test seam there is exactly one fixture database and it must not + // be closed out from under the suite, so hand back a facade instead. + if (_isTestDb && _db) { + return { prepare: (...a) => _db.prepare(...a), close: () => {} }; + } + const Database = require('better-sqlite3'); + return new Database(dbPath, { readonly: true, fileMustExist: true }); +} + function close() { if (_db) { try { _db.close(); } catch (_) {} _db = null; + _isTestDb = false; } } // Test seam: replace the singleton with an existing Database instance. function _setForTest(db) { _db = db; + _isTestDb = true; } -module.exports = { open, close, _setForTest }; +module.exports = { open, openFresh, close, _setForTest }; diff --git a/src/lib/exec.js b/src/lib/exec.js index 5f4cc32..b934672 100644 --- a/src/lib/exec.js +++ b/src/lib/exec.js @@ -3,6 +3,14 @@ const { execFileSync } = require('child_process'); const { ThingsUrlError } = require('./errors'); +// macOS `open` echoes the ENTIRE url back on failure, and our urls carry +// auth-token=<secret>. That message is spliced into ThingsUrlError, which the +// CLI prints to stderr and the MCP server returns as tool output — i.e. straight +// into a model transcript. Redact before the value can reach any sink. +function redactToken(text) { + return String(text).replace(/auth-token=[^&\s)]*/gi, 'auth-token=<redacted>'); +} + // Open a things:/// URL via macOS `open`. Throws ThingsUrlError on failure. // Uses execFileSync (not execSync) so the URL is a single argv argument and // is not subject to shell expansion. @@ -13,7 +21,7 @@ function openUrl(url) { try { execFileSync('open', [url], { stdio: ['ignore', 'ignore', 'pipe'] }); } catch (e) { - const stderr = (e.stderr && e.stderr.toString()) || ''; + const stderr = redactToken((e.stderr && e.stderr.toString()) || ''); throw new ThingsUrlError( `Failed to open Things URL.${stderr ? ' ' + stderr.trim() : ''} ` + 'Is Things 3 installed and running?' @@ -21,4 +29,4 @@ function openUrl(url) { } } -module.exports = { openUrl }; +module.exports = { openUrl, redactToken }; diff --git a/src/lib/url.js b/src/lib/url.js index 0c56a0e..4c79e3f 100644 --- a/src/lib/url.js +++ b/src/lib/url.js @@ -26,7 +26,9 @@ function buildUpdateUrl(params) { return `things:///update?${_encode(params)}`; } -// Things applies `update` to to-dos only; projects need `update-project`. +// Projects MUST use `update-project`. Things silently ignores an `update` +// aimed at a project uuid — and `open` still exits 0 — so using the wrong +// builder produces a write that never happens and never reports an error. function buildUpdateProjectUrl(params) { return `things:///update-project?${_encode(params)}`; } diff --git a/src/lib/uuid.js b/src/lib/uuid.js index 342c3ee..e67eeb8 100644 --- a/src/lib/uuid.js +++ b/src/lib/uuid.js @@ -9,8 +9,12 @@ function resolveTaskId(db, partial, opts = {}) { if (!partial) throw new TaskNotFoundError(partial); const { type, yesFirst = false, includeTrashed = false } = opts; - let sql = 'SELECT uuid, title, type FROM TMTask WHERE uuid LIKE ?'; - const params = [`${partial}%`]; + // Escape LIKE wildcards: without this, an id of '%' matches EVERY row, and + // with --yes-first that silently resolves to an arbitrary task. Reachable over + // MCP, and now that update can re-parent, a mis-resolved id relocates work. + const escaped = String(partial).replace(/[\\%_]/g, (c) => `\\${c}`); + let sql = "SELECT uuid, title, type FROM TMTask WHERE uuid LIKE ? ESCAPE '\\'"; + const params = [`${escaped}%`]; if (!includeTrashed) sql += ' AND trashed = 0'; if (type !== undefined) { sql += ' AND type = ?'; diff --git a/src/lib/verify.js b/src/lib/verify.js new file mode 100644 index 0000000..855a574 --- /dev/null +++ b/src/lib/verify.js @@ -0,0 +1,118 @@ +'use strict'; + +const db = require('./db'); +const { colors } = require('./format'); + +// Why this module exists. +// +// Every write in thingsctl goes out through the Things URL scheme via `open`. +// `open` exits 0 as soon as macOS hands the URL to Things — it says nothing +// about whether Things accepted the command. Things silently ignores a command +// it cannot apply (the classic case: `things:///update` aimed at a project, +// which only `update-project` handles). The result is a write that never +// happened and a CLI that cheerfully prints a checkmark. +// +// So: a write is not confirmed until the database says it landed. + +// Overridable because one number has to cover two very different situations. +// Things already running applies a write well inside 500ms. A `things:///` URL +// that cold-launches the app can take longer than 3s, and that shows up as a +// false "did not apply" on a write that does eventually land. +const DEFAULT_TIMEOUT_MS = Number(process.env.THINGSCTL_VERIFY_TIMEOUT_MS) || 3000; + +// The first read almost always misses: `open` returns as soon as LaunchServices +// hands over the URL, well before Things has committed anything. Start tight and +// back off, so the common case pays ~20ms rather than a flat 100ms. +const BACKOFF_MS = [20, 40, 80]; +const STEADY_INTERVAL_MS = 100; + +// Only columns a predicate actually reads. Keep this tight: it is the surface +// that can rot, and it runs on every write on a user's machine. +const VERIFY_FIELDS = + 'uuid, status, project, area, start, startBucket, startDate, userModificationDate'; + +// Synchronous sleep. The CLI is synchronous end to end (better-sqlite3, +// execFileSync), so this keeps the control flow flat. +// +// NOTE: this blocks the Node main thread. Harmless for the one-shot CLI; in the +// long-lived MCP server it freezes the event loop for the duration of the wait, +// which is why bin/thingsctl-mcp.js sets a shorter default timeout. Making the +// whole write path async is the real fix and is deliberately not done here. +function sleepSync(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +// One short-lived connection per wait, not one per poll. The database is in WAL +// mode and a readonly connection in autocommit opens a fresh read transaction +// per statement, so a single connection already sees another process's commits +// between polls — reopening bought nothing and cost ~1.2ms each time. +function _withConnection(fn) { + const conn = db.openFresh(); + try { + return fn(conn); + } finally { + try { conn.close(); } catch (_) { /* handle dies with the process anyway */ } + } +} + +// Read a row once. Also the "before" snapshot for change-based predicates. +function snapshot(uuid) { + return _withConnection((conn) => + conn.prepare(`SELECT ${VERIFY_FIELDS} FROM TMTask WHERE uuid = ?`).get(uuid) + ); +} + +// Poll until `predicate(row)` holds or we run out of patience. +// Returns { ok, row }. Never throws on a failed predicate — callers decide how +// loudly to complain. +function waitForWrite(uuid, predicate, opts = {}) { + const timeoutMs = opts.timeoutMs == null ? DEFAULT_TIMEOUT_MS : opts.timeoutMs; + const deadline = Date.now() + timeoutMs; + + return _withConnection((conn) => { + const stmt = conn.prepare(`SELECT ${VERIFY_FIELDS} FROM TMTask WHERE uuid = ?`); + for (let attempt = 0; ; attempt++) { + const row = stmt.get(uuid); + if (row && predicate(row)) return { ok: true, row }; + if (Date.now() >= deadline) return { ok: false, row }; + sleepSync(BACKOFF_MS[attempt] == null ? STEADY_INTERVAL_MS : BACKOFF_MS[attempt]); + } + }); +} + +// The general-purpose predicate: Things bumps userModificationDate on any real +// edit. Prefer a field-specific predicate where one exists — this one cannot +// tell our write apart from a Things Cloud sync or a concurrent edit in the UI, +// and it cannot see a write that changed nothing. +// +// A missing baseline (the row could not be read before the write) makes this +// vacuously true on the first read, which degrades to the old assume-success +// behaviour. Callers that care should pass a field-specific predicate. +function modifiedSince(before) { + const was = before ? before.userModificationDate : null; + return (row) => row.userModificationDate !== was; +} + +// Assert a column holds an expected value — the strong form, used where we know +// the end state (a re-parent target, a status change). +function fieldEquals(field, expected) { + return (row) => row[field] === expected; +} + +// One failure message, not one per command. Every write command reports the +// same thing: macOS took the URL, Things did nothing with it. +function notApplied(verb, title) { + return ( + `${colors.red('✗')} Things did not ${verb} "${title}" ` + + '(the URL was accepted but the database never changed)' + ); +} + +module.exports = { + waitForWrite, + snapshot, + modifiedSince, + fieldEquals, + notApplied, + DEFAULT_TIMEOUT_MS, +}; diff --git a/test/integration/verify-read.test.js b/test/integration/verify-read.test.js new file mode 100644 index 0000000..8a23f05 --- /dev/null +++ b/test/integration/verify-read.test.js @@ -0,0 +1,50 @@ +'use strict'; + +// verify.js's SQL runs on every write on a user's machine and was previously +// stubbed out of every test, so a column typo would have shipped green. This +// reads the fixture through the real code path, which also exercises the +// db.openFresh test-seam facade. + +require('./setup'); +const verify = require('../../src/lib/verify'); +const db = require('../../src/lib/db'); + +describe('snapshot reads real rows', () => { + test('returns the columns predicates depend on', () => { + const row = verify.snapshot('t-today-1'); + expect(row).toBeDefined(); + expect(row.uuid).toBe('t-today-1'); + for (const col of ['status', 'project', 'area', 'start', 'startBucket', 'startDate', 'userModificationDate']) { + expect(row).toHaveProperty(col); + } + }); + + test('a project row reads back too', () => { + expect(verify.snapshot('p-001').uuid).toBe('p-001'); + }); + + test('an unknown uuid is undefined, not a throw', () => { + expect(verify.snapshot('does-not-exist')).toBeUndefined(); + }); +}); + +describe('openFresh under the test seam', () => { + test('hands back a facade that must not close the shared fixture', () => { + const conn = db.openFresh(); + conn.close(); + expect(verify.snapshot('t-today-1')).toBeDefined(); + }); +}); + +describe('waitForWrite against a row that will never change', () => { + test('gives up and reports the row it last saw', () => { + const { ok, row } = verify.waitForWrite('t-today-1', () => false, { timeoutMs: 60 }); + expect(ok).toBe(false); + expect(row.uuid).toBe('t-today-1'); + }); + + test('succeeds immediately when the predicate already holds', () => { + const { ok } = verify.waitForWrite('t-today-1', (r) => r.uuid === 't-today-1', { timeoutMs: 60 }); + expect(ok).toBe(true); + }); +}); diff --git a/test/integration/write-dispatch.test.js b/test/integration/write-dispatch.test.js new file mode 100644 index 0000000..5e2ddf3 --- /dev/null +++ b/test/integration/write-dispatch.test.js @@ -0,0 +1,181 @@ +'use strict'; + +// Regression guard for the bug that shipped in 2.0.3 and earlier: every write +// went to `things:///update`, which Things silently ignores when the target is +// a project. `open` still exits 0, so the CLI printed a checkmark for a write +// that never happened. 2.0.4 fixed `update` only; complete, move and tag were +// still broken. +// +// Only waitForWrite is stubbed. snapshot() and notApplied() run for real, so +// this suite also exercises verify.js's SQL against the fixture database and +// pins the exact failure text users see. + +jest.mock('../../src/lib/exec', () => ({ openUrl: jest.fn(), redactToken: (s) => s })); +jest.mock('../../src/lib/token', () => ({ getToken: () => 'TESTTOKEN' })); +jest.mock('../../src/lib/verify', () => { + const actual = jest.requireActual('../../src/lib/verify'); + return { ...actual, waitForWrite: jest.fn(() => ({ ok: true, row: {} })) }; +}); + +require('./setup'); +const { openUrl } = require('../../src/lib/exec'); +const { waitForWrite } = require('../../src/lib/verify'); +const complete = require('../../src/commands/complete'); +const update = require('../../src/commands/update'); +const move = require('../../src/commands/move'); +const tag = require('../../src/commands/tag'); + +const lastUrl = () => { + expect(openUrl).toHaveBeenCalled(); + return openUrl.mock.calls[openUrl.mock.calls.length - 1][0]; +}; + +beforeEach(() => { + openUrl.mockClear(); + waitForWrite.mockClear(); + waitForWrite.mockReturnValue({ ok: true, row: {} }); +}); + +describe('writes route by entity type', () => { + test('complete: project → update-project', () => { + complete.run(['p-001']); + expect(lastUrl()).toContain('things:///update-project?'); + expect(lastUrl()).toContain('completed=true'); + }); + + test('complete: to-do → update', () => { + complete.run(['t-today-1']); + expect(lastUrl()).toContain('things:///update?'); + expect(lastUrl()).not.toContain('update-project'); + }); + + test('update: project → update-project', () => { + update.run('p-001', { title: 'Launch v2' }); + expect(lastUrl()).toContain('things:///update-project?'); + }); + + test('move: project → update-project', () => { + move.run('p-001', { to: 'today' }); + expect(lastUrl()).toContain('things:///update-project?'); + expect(lastUrl()).toContain('when=today'); + }); + + test('tag: project → update-project (still broken on 2.0.4)', () => { + tag.run('p-001', { add: 'Urgent' }); + expect(lastUrl()).toContain('things:///update-project?'); + expect(lastUrl()).toContain('add-tags=Urgent'); + }); + + test('tag: to-do → update', () => { + tag.run('t-today-1', { add: 'Urgent' }); + expect(lastUrl()).toContain('things:///update?'); + expect(lastUrl()).not.toContain('update-project'); + }); +}); + +describe('an unapplied write is reported as a failure, not a checkmark', () => { + beforeEach(() => waitForWrite.mockReturnValue({ ok: false, row: {} })); + + test('complete says so', () => { + const out = complete.run(['t-today-1']); + expect(out).toContain('✗'); + expect(out).toContain('the URL was accepted but the database never changed'); + }); + + test('update says so', () => { + const out = update.run('t-today-1', { title: 'X' }); + expect(out).toContain('✗'); + expect(out).toContain('the URL was accepted but the database never changed'); + }); + + test('move says so', () => { + const out = move.run('t-today-1', { to: 'today' }); + expect(out).toContain('✗'); + expect(out).not.toContain('Rescheduled'); + }); + + test('tag says so', () => { + const out = tag.run('t-today-1', { add: 'Urgent' }); + expect(out).toContain('✗'); + expect(out).not.toContain('Added tag'); + }); +}); + +describe('headings are refused, not dispatched into a no-op', () => { + test('complete refuses', () => { + const out = complete.run(['h-001']); + expect(out).toMatch(/Cannot complete a heading/); + expect(openUrl).not.toHaveBeenCalled(); + }); + + test('update refuses', () => { + expect(() => update.run('h-001', { title: 'X' })).toThrow(/is a heading/); + expect(openUrl).not.toHaveBeenCalled(); + }); + + test('move refuses', () => { + expect(() => move.run('h-001', { to: 'today' })).toThrow(/is a heading/); + expect(openUrl).not.toHaveBeenCalled(); + }); + + test('tag refuses', () => { + expect(() => tag.run('h-001', { add: 'X' })).toThrow(/is a heading/); + expect(openUrl).not.toHaveBeenCalled(); + }); +}); + +describe('re-parenting', () => { + test('to-do moves into a project by title', () => { + update.run('t-today-1', { list: 'Launch' }); + expect(lastUrl()).toContain('list=Launch'); + }); + + test('list-id takes precedence over list', () => { + update.run('t-today-1', { list: 'Launch', 'list-id': 'p-001' }); + expect(lastUrl()).toContain('list-id=p-001'); + expect(lastUrl()).not.toContain('&list=Launch'); + }); + + test('area-id takes precedence over area', () => { + update.run('p-001', { area: 'Work', 'area-id': 'a-work' }); + expect(lastUrl()).toContain('area-id=a-work'); + expect(lastUrl()).not.toContain('&area=Work'); + }); + + test('list on a project is refused, because Things would drop it silently', () => { + expect(() => update.run('p-001', { list: 'Somewhere' })).toThrow(/is a project/); + expect(openUrl).not.toHaveBeenCalled(); + }); + + test('area on a to-do is refused for the same reason', () => { + expect(() => update.run('t-today-1', { area: 'Somewhere' })).toThrow(/is a to-do/); + expect(openUrl).not.toHaveBeenCalled(); + }); + + test('a resolvable move is verified against the row, not just "something changed"', () => { + update.run('t-today-1', { 'list-id': 'p-001' }); + const predicate = waitForWrite.mock.calls[0][1]; + expect(predicate({ project: 'p-001', area: null })).toBe(true); + expect(predicate({ project: null, area: null })).toBe(false); + }); +}); + +describe('--completed false reopens, it does not complete', () => { + test('the string "false" from the CLI parser is not treated as truthy', () => { + update.run('t-today-1', { completed: 'false' }); + expect(lastUrl()).toContain('completed=false'); + expect(lastUrl()).not.toContain('completed=true'); + }); + + test('and the predicate asserts the task ends up OPEN', () => { + update.run('t-today-1', { completed: 'false' }); + const predicate = waitForWrite.mock.calls[0][1]; + expect(predicate({ status: 0 })).toBe(true); + expect(predicate({ status: 3 })).toBe(false); + }); + + test('boolean true still completes', () => { + update.run('t-today-1', { completed: true }); + expect(lastUrl()).toContain('completed=true'); + }); +}); diff --git a/test/unit/exec.test.js b/test/unit/exec.test.js new file mode 100644 index 0000000..2a9a9b5 --- /dev/null +++ b/test/unit/exec.test.js @@ -0,0 +1,31 @@ +'use strict'; + +const { redactToken } = require('../../src/lib/exec'); + +// macOS `open` echoes the whole url back on failure, and our urls carry +// auth-token=<secret>. That text lands in CLI stderr AND in MCP tool output, +// i.e. a model transcript. It must never carry the token. +describe('redactToken', () => { + test('strips the token out of an open(1) failure message', () => { + const msg = + 'No application knows how to open URL things:///update?id=abc&auth-token=SECRET123 ' + + '(Error Domain=NSOSStatusErrorDomain Code=-10814)'; + const out = redactToken(msg); + expect(out).not.toContain('SECRET123'); + expect(out).toContain('auth-token=<redacted>'); + expect(out).toContain('id=abc'); + }); + + test('handles the token at the end of the url', () => { + expect(redactToken('things:///update?auth-token=ZZZ')).toBe('things:///update?auth-token=<redacted>'); + }); + + test('redacts every occurrence', () => { + const out = redactToken('a auth-token=ONE b auth-token=TWO c'); + expect(out).not.toMatch(/ONE|TWO/); + }); + + test('leaves messages without a token alone', () => { + expect(redactToken('Is Things 3 installed?')).toBe('Is Things 3 installed?'); + }); +}); diff --git a/test/unit/url.test.js b/test/unit/url.test.js index 5a613d3..fa810f2 100644 --- a/test/unit/url.test.js +++ b/test/unit/url.test.js @@ -46,13 +46,6 @@ describe('buildUpdateUrl', () => { }); }); -describe('buildUpdateProjectUrl', () => { - test('targets the update-project endpoint', () => { - const u = url.buildUpdateProjectUrl({ id: 'proj1', title: 'New Name' }); - expect(u).toBe('things:///update-project?id=proj1&title=New%20Name'); - }); -}); - describe('buildJsonUrl', () => { test('encodes nested data as JSON', () => { const u = url.buildJsonUrl({ @@ -67,3 +60,32 @@ describe('buildJsonUrl', () => { ]); }); }); + +describe('buildUpdateProjectUrl', () => { + test('targets the update-project endpoint', () => { + const u = url.buildUpdateProjectUrl({ id: 'proj1', title: 'New Name' }); + expect(u).toBe('things:///update-project?id=proj1&title=New%20Name'); + }); + + test('targets the update-project endpoint, not update', () => { + const u = url.buildUpdateProjectUrl({ id: 'abc123', completed: 'true' }); + expect(u).toBe('things:///update-project?id=abc123&completed=true'); + }); + + test('carries area params used to re-parent a project', () => { + const u = url.buildUpdateProjectUrl({ id: 'p1', area: 'Travel Plans' }); + expect(u).toBe('things:///update-project?id=p1&area=Travel%20Plans'); + }); +}); + +describe('re-parenting params on update', () => { + test('list moves a to-do into a project or area', () => { + const u = url.buildUpdateUrl({ id: 't1', list: 'Berlin Trip' }); + expect(u).toBe('things:///update?id=t1&list=Berlin%20Trip'); + }); + + test('list-id is carried verbatim', () => { + const u = url.buildUpdateUrl({ id: 't1', 'list-id': 'Xm55Bsr1WmkUDQsmxd7CBn' }); + expect(u).toContain('list-id=Xm55Bsr1WmkUDQsmxd7CBn'); + }); +}); diff --git a/test/unit/uuid.test.js b/test/unit/uuid.test.js index 1f52fda..defceac 100644 --- a/test/unit/uuid.test.js +++ b/test/unit/uuid.test.js @@ -70,3 +70,25 @@ describe('resolveMany', () => { expect(out.errors[0].input).toBe('zzz'); }); }); + +describe('LIKE wildcards in the id prefix', () => { + const Database = require('better-sqlite3'); + const { OUT } = require('../fixtures/build'); + let db; + beforeAll(() => { db = new Database(OUT, { readonly: true }); }); + afterAll(() => { try { db.close(); } catch (_) {} }); + + test("'%' does not match every task", () => { + // Before escaping, this resolved to an arbitrary row with --yes-first, + // which over MCP meant a destructive verb could hit the wrong task. + expect(() => resolveTaskId(db, '%', { yesFirst: true })).toThrow(/not found/i); + }); + + test("'_' is not a single-character wildcard either", () => { + expect(() => resolveTaskId(db, '_', { yesFirst: true })).toThrow(/not found/i); + }); + + test('ordinary prefixes still resolve', () => { + expect(resolveTaskId(db, 't-today-1').uuid).toBe('t-today-1'); + }); +}); diff --git a/test/unit/verify.test.js b/test/unit/verify.test.js new file mode 100644 index 0000000..737f613 --- /dev/null +++ b/test/unit/verify.test.js @@ -0,0 +1,92 @@ +'use strict'; + +const db = require('../../src/lib/db'); +const verify = require('../../src/lib/verify'); + +// Stand in for a better-sqlite3 connection. `rows` is read fresh on every +// prepare().get() so a test can mutate it mid-poll to imitate Things catching up. +function fakeConn(getRow) { + return { prepare: () => ({ get: () => getRow() }), close: () => {} }; +} + +describe('waitForWrite', () => { + const realOpenFresh = db.openFresh; + afterEach(() => { db.openFresh = realOpenFresh; }); + + test('succeeds immediately when the row already satisfies the predicate', () => { + db.openFresh = () => fakeConn(() => ({ uuid: 'x', status: 3 })); + const { ok, row } = verify.waitForWrite('x', (r) => r.status === 3); + expect(ok).toBe(true); + expect(row.status).toBe(3); + }); + + test('fails after the timeout when the write never lands', () => { + db.openFresh = () => fakeConn(() => ({ uuid: 'x', status: 0 })); + const started = Date.now(); + const { ok } = verify.waitForWrite('x', (r) => r.status === 3, { timeoutMs: 120, intervalMs: 20 }); + expect(ok).toBe(false); + expect(Date.now() - started).toBeGreaterThanOrEqual(100); + }); + + test('polls until Things applies the change', () => { + let reads = 0; + db.openFresh = () => fakeConn(() => ({ uuid: 'x', status: ++reads >= 3 ? 3 : 0 })); + const { ok } = verify.waitForWrite('x', (r) => r.status === 3, { timeoutMs: 1000, intervalMs: 5 }); + expect(ok).toBe(true); + expect(reads).toBeGreaterThanOrEqual(3); + }); + + test('a missing row never satisfies the predicate', () => { + db.openFresh = () => fakeConn(() => undefined); + const { ok, row } = verify.waitForWrite('gone', () => true, { timeoutMs: 40, intervalMs: 10 }); + expect(ok).toBe(false); + expect(row).toBeUndefined(); + }); +}); + +describe('modifiedSince', () => { + test('is false until userModificationDate moves', () => { + const pred = verify.modifiedSince({ userModificationDate: 100 }); + expect(pred({ userModificationDate: 100 })).toBe(false); + expect(pred({ userModificationDate: 101 })).toBe(true); + }); + + test('treats a missing baseline as "any value counts as changed"', () => { + const pred = verify.modifiedSince(undefined); + expect(pred({ userModificationDate: 7 })).toBe(true); + }); +}); + +describe('fieldEquals', () => { + test('asserts an exact column value', () => { + const pred = verify.fieldEquals('project', 'p-001'); + expect(pred({ project: 'p-001' })).toBe(true); + expect(pred({ project: null })).toBe(false); + }); +}); + +describe('notApplied', () => { + test('is the one failure message every write command shares', () => { + const msg = verify.notApplied('complete', 'Ship the demo'); + expect(msg).toContain('Things did not complete "Ship the demo"'); + expect(msg).toContain('the URL was accepted but the database never changed'); + }); +}); + +describe('timeout is overridable', () => { + const real = process.env.THINGSCTL_VERIFY_TIMEOUT_MS; + afterEach(() => { + if (real === undefined) delete process.env.THINGSCTL_VERIFY_TIMEOUT_MS; + else process.env.THINGSCTL_VERIFY_TIMEOUT_MS = real; + jest.resetModules(); + }); + + test('THINGSCTL_VERIFY_TIMEOUT_MS sets the default', () => { + // Things can take longer than 3s when the url cold-launches the app, which + // otherwise reads as a false "did not apply" on a write that does land. + jest.resetModules(); + process.env.THINGSCTL_VERIFY_TIMEOUT_MS = '750'; + const fresh = require('../../src/lib/verify'); + expect(fresh.DEFAULT_TIMEOUT_MS).toBe(750); + }); +});