From 639fb67e58fdef41e46ace1fef6cccac37a83edf Mon Sep 17 00:00:00 2001 From: Henry Kaufman Date: Tue, 29 Sep 2026 11:50:10 -0400 Subject: [PATCH 1/2] v2.1.0: fix silent no-op writes on projects, verify writes, add re-parenting Writes aimed at a project were discarded by Things and still reported success. `complete`, `update` and `move` all built `things:///update`, which Things only applies to to-dos; it ignores a project uuid without raising anything. `open` exits 0 either way, so the CLI printed a checkmark for a write that never happened. Found when completing a project appeared to work and the row stayed `type=1, status=0`. Three changes: - Route projects to `things:///update-project`, the endpoint Things documents for them. Headings are refused outright rather than dispatched into a no-op. - Confirm every write against the database before reporting success. `open` exiting 0 says macOS handed over the URL, nothing more, so lib/verify polls the row (up to 3s) until the change is visible and reports a clear failure otherwise. This is what turned the routing bug from an error into a lie. - Add re-parenting, which the tool could not do at all: `update --list` / `--list-id` moves a to-do into a project or area, `update --area` / `--area-id` moves a project into an area. Passing the wrong pair for the type is refused with an explanation instead of being silently dropped by Things. Also fixes `things_move`'s description, which read as a re-parent when it only ever rescheduled, and the CLI's hand-curated flag allowlist for `update`, which would have dropped the new options. Verified end to end against real Things: a scratch project completes and lands `status=3`, a scratch to-do re-parents into an area and completes. Claude-Session: https://claude.ai/code/session_01LMbjcZogpv9EbVnqovXpSX --- CHANGELOG.md | 30 +++++++++ README.md | 17 ++++- package-lock.json | 4 +- package.json | 2 +- src/cli.js | 1 + src/commands/complete.js | 31 +++++++-- src/commands/move.js | 24 ++++++- src/commands/update.js | 51 ++++++++++++++- src/lib/db.js | 17 ++++- src/lib/errors.js | 16 +++++ src/lib/url.js | 8 +++ src/lib/verify.js | 77 ++++++++++++++++++++++ test/integration/write-dispatch.test.js | 87 +++++++++++++++++++++++++ test/unit/url.test.js | 24 +++++++ test/unit/verify.test.js | 58 +++++++++++++++++ 15 files changed, 430 insertions(+), 17 deletions(-) create mode 100644 src/lib/verify.js create mode 100644 test/integration/write-dispatch.test.js create mode 100644 test/unit/verify.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 4bd7f7d..9e55578 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,35 @@ # Changelog +## 2.1.0 + +Writes could silently do nothing and still report success. Fixed, plus the +missing ability to move a to-do or project to a different parent. + +- **Every write on a PROJECT was a no-op that reported success.** `complete`, + `update` and `move` all built `things:///update`, which Things only applies to + to-dos; it ignores a project uuid without error. `open` still exits 0, so the + CLI printed `✓ Completed: ` while nothing changed. Projects now route + to `things:///update-project`, which is the endpoint Things documents for them. +- **Success is now verified against the database, not assumed.** `open` exiting 0 + only means macOS handed the URL to Things — it says nothing about whether Things + accepted it. Writes now poll the database (up to 3s) until the change is visible + and report a clear failure if it never lands. This is what turned the bug above + from an error into a lie. +- **Added: move a to-do or project to a different parent.** Previously impossible + through the tool — `update` had no parameter for it and `move` only reschedules + despite the name. Now `update --list` / `--list-id` moves a to-do into a project + or area, and `update --area` / `--area-id` moves a project into an area. Passing + the wrong pair for the type (e.g. `--list` on a project) is refused with an + explanatory error rather than dropped silently by Things. +- **`complete` refuses headings** instead of dispatching a URL that does nothing. +- **`things_move`'s description now says it only reschedules**, and points at + `things_update` for re-parenting. The old wording ("moving it to...") read as a + re-parent and misled callers. + +New: `src/lib/verify.js` (post-write confirmation), `url.buildUpdateProjectUrl`, +`db.openFresh`, `WriteNotAppliedError`. 20 regression tests added, including one +that pins each write command to the correct endpoint per task type. + ## 2.0.3 Fix recurring tasks across `someday` and `repeating`. Two bugs, both from the same 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/package-lock.json b/package-lock.json index b29cdce..4eca949 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "thingsctl", - "version": "2.0.1", + "version": "2.1.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "thingsctl", - "version": "2.0.1", + "version": "2.1.0", "license": "MIT", "os": [ "darwin" diff --git a/package.json b/package.json index 8fa10b3..ee343ed 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "thingsctl", - "version": "2.0.3", + "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..e9acfac 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 } = require('../lib/verify'); const queries = require('../lib/queries'); function run(ids, opts = {}) { @@ -25,12 +26,32 @@ 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})`); + continue; } + + const { ok } = waitForWrite(task.uuid, (r) => r.status === STATUS.COMPLETED); + out.push( + ok + ? `${colors.green('✓')} Completed ${label}: ${task.title}` + : `${colors.red('✗')} Things did not complete the ${label} "${task.title}" ` + + `(the URL was accepted but the database never changed)` + ); } return list.length === 1 ? out[0] : out; } @@ -39,7 +60,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..a9ab859 100644 --- a/src/commands/move.js +++ b/src/commands/move.js @@ -2,17 +2,32 @@ 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 } = 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() })); + + 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 `${colors.red('✗')} Things did not reschedule "${ref.title}" ` + + `(the URL was accepted but the database never changed)`; + } return `Moved "${ref.title}" to ${opts.to}`; } @@ -20,7 +35,10 @@ 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/update.js b/src/commands/update.js index 154ae54..54d4603 100644 --- a/src/commands/update.js +++ b/src/commands/update.js @@ -3,16 +3,35 @@ const db = require('../lib/db'); const queries = require('../lib/queries'); 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, STATUS } = require('../lib/constants'); +const { waitForWrite, snapshot, modifiedSince } = require('../lib/verify'); 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; + + // `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 params = { id: task.uuid, 'auth-token': getToken() }; const changes = []; @@ -30,6 +49,13 @@ 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']}`); } + + // Re-parenting. list-id takes precedence over list, area-id over area. + if (opts['list-id']) { params['list-id'] = opts['list-id']; changes.push(`moved into ${opts['list-id']}`); } + else if (opts.list) { params.list = opts.list; changes.push(`moved into "${opts.list}"`); } + if (opts['area-id']) { params['area-id'] = opts['area-id']; changes.push(`moved into area ${opts['area-id']}`); } + else if (opts.area) { params.area = opts.area; changes.push(`moved into area "${opts.area}"`); } + if (opts.completed !== undefined) { params.completed = opts.completed ? 'true' : 'false'; changes.push(opts.completed ? 'completed' : 'reopened'); @@ -41,7 +67,20 @@ function run(id, opts = {}) { if (changes.length === 0) throw new Error('No changes specified'); - openUrl(buildUpdateUrl(params)); + const before = snapshot(task.uuid); + openUrl(isProject ? buildUpdateProjectUrl(params) : buildUpdateUrl(params)); + + // Assert the end state where we know it; fall back to "something changed". + let predicate = modifiedSince(before); + if (opts.canceled === true) predicate = (r) => r.status === STATUS.CANCELED; + else if (opts.completed === true) predicate = (r) => r.status === STATUS.COMPLETED; + else if (opts.completed === false || opts.canceled === false) predicate = (r) => r.status === STATUS.OPEN; + + const { ok } = waitForWrite(task.uuid, predicate); + if (!ok) { + return `${colors.red('✗')} Things did not apply the change to "${task.title}" ` + + `(the URL was accepted but the database never changed)`; + } return `${colors.green('✓')} Updated "${task.title}": ${changes.join(', ')}`; } @@ -49,7 +88,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: { @@ -61,6 +102,10 @@ 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' }, }, diff --git a/src/lib/db.js b/src/lib/db.js index b96b38e..841fd5b 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,6 +12,19 @@ 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 (_) {} @@ -21,6 +35,7 @@ function close() { // 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/errors.js b/src/lib/errors.js index 45ddb9f..4b35a54 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -37,6 +37,21 @@ class ThingsUrlError extends ThingsCtlError { } } +// Raised when a URL-scheme write was dispatched but the database never showed +// the change. Usually means Things rejected the command outright. +class WriteNotAppliedError extends ThingsCtlError { + constructor(title, detail) { + super( + `Things did not apply the change to "${title}".` + + (detail ? ` ${detail}` : '') + + '\n The command was accepted by macOS but Things made no change.' + + '\n Check that Things 3 is running and that the auth token is valid.', + 'E_WRITE_NOT_APPLIED' + ); + this.title = title; + } +} + class TokenMissingError extends ThingsCtlError { constructor() { super( @@ -54,5 +69,6 @@ module.exports = { TaskNotFoundError, AmbiguousIdError, ThingsUrlError, + WriteNotAppliedError, TokenMissingError, }; diff --git a/src/lib/url.js b/src/lib/url.js index de43fb8..4c79e3f 100644 --- a/src/lib/url.js +++ b/src/lib/url.js @@ -26,6 +26,13 @@ function buildUpdateUrl(params) { return `things:///update?${_encode(params)}`; } +// 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)}`; +} + function buildShowUrl(params) { return `things:///show?${_encode(params)}`; } @@ -46,6 +53,7 @@ function buildJsonUrl({ data, authToken, reveal }) { module.exports = { buildAddUrl, buildUpdateUrl, + buildUpdateProjectUrl, buildShowUrl, buildAddProjectUrl, buildJsonUrl, diff --git a/src/lib/verify.js b/src/lib/verify.js new file mode 100644 index 0000000..b4df136 --- /dev/null +++ b/src/lib/verify.js @@ -0,0 +1,77 @@ +'use strict'; + +const db = require('./db'); + +// 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. + +const DEFAULT_TIMEOUT_MS = 3000; +const DEFAULT_INTERVAL_MS = 100; + +const VERIFY_FIELDS = ` + uuid, title, type, status, project, area, heading, + start, startBucket, startDate, deadline, notes, userModificationDate +`; + +// Synchronous sleep. The CLI is synchronous end to end (better-sqlite3, +// execFileSync), so this keeps the control flow flat rather than turning every +// command into a promise chain. +function sleepSync(ms) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms); +} + +function readRow(uuid) { + const conn = db.openFresh(); + try { + return conn.prepare(`SELECT ${VERIFY_FIELDS} FROM TMTask WHERE uuid = ?`).get(uuid); + } finally { + try { conn.close(); } catch (_) { /* nothing useful to do */ } + } +} + +// 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 intervalMs = opts.intervalMs == null ? DEFAULT_INTERVAL_MS : opts.intervalMs; + const deadline = Date.now() + timeoutMs; + + for (;;) { + const row = readRow(uuid); + if (row && predicate(row)) return { ok: true, row }; + if (Date.now() >= deadline) return { ok: false, row }; + sleepSync(intervalMs); + } +} + +// Snapshot the fields a command is about to change, so the predicate can ask +// "did anything actually move?" rather than guessing at final values. +function snapshot(uuid) { + return readRow(uuid); +} + +// The general-purpose predicate: Things bumps userModificationDate on any real +// edit. Use a field-specific predicate where one exists (status, project) — +// this is the fallback for edits whose end state we can't cheaply assert. +function modifiedSince(before) { + const was = before ? before.userModificationDate : null; + return (row) => row.userModificationDate !== was; +} + +module.exports = { + waitForWrite, + snapshot, + modifiedSince, + readRow, + sleepSync, + DEFAULT_TIMEOUT_MS, +}; diff --git a/test/integration/write-dispatch.test.js b/test/integration/write-dispatch.test.js new file mode 100644 index 0000000..45234ef --- /dev/null +++ b/test/integration/write-dispatch.test.js @@ -0,0 +1,87 @@ +'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. + +jest.mock('../../src/lib/exec', () => ({ openUrl: jest.fn() })); +jest.mock('../../src/lib/token', () => ({ getToken: () => 'TESTTOKEN' })); +jest.mock('../../src/lib/verify', () => ({ + waitForWrite: () => ({ ok: true, row: {} }), + snapshot: () => ({ userModificationDate: 1 }), + modifiedSince: () => () => true, +})); + +require('./setup'); +const { openUrl } = require('../../src/lib/exec'); +const complete = require('../../src/commands/complete'); +const update = require('../../src/commands/update'); +const move = require('../../src/commands/move'); + +const lastUrl = () => openUrl.mock.calls[openUrl.mock.calls.length - 1][0]; + +beforeEach(() => openUrl.mockClear()); + +describe('complete routes by task type', () => { + test('a project goes to update-project', () => { + complete.run(['p-001']); + expect(lastUrl()).toContain('things:///update-project?'); + expect(lastUrl()).toContain('id=p-001'); + expect(lastUrl()).toContain('completed=true'); + }); + + test('a to-do goes to update', () => { + complete.run(['t-today-1']); + expect(lastUrl()).toContain('things:///update?'); + expect(lastUrl()).not.toContain('update-project'); + }); + + test('a heading is refused rather than silently dropped', () => { + const out = complete.run(['h-001']); + expect(out).toMatch(/Cannot complete a heading/); + expect(openUrl).not.toHaveBeenCalled(); + }); +}); + +describe('update routes by task type', () => { + test('a project goes to update-project', () => { + update.run('p-001', { title: 'Launch v2' }); + expect(lastUrl()).toContain('things:///update-project?'); + }); + + test('a to-do goes to update', () => { + update.run('t-today-1', { title: 'Ship it' }); + expect(lastUrl()).toContain('things:///update?'); + }); +}); + +describe('move routes by task type', () => { + test('rescheduling a project goes to update-project', () => { + move.run('p-001', { to: 'today' }); + expect(lastUrl()).toContain('things:///update-project?'); + expect(lastUrl()).toContain('when=today'); + }); +}); + +describe('re-parenting', () => { + test('a to-do can be moved into a project by title', () => { + update.run('t-today-1', { list: 'Berlin Trip' }); + expect(lastUrl()).toContain('list=Berlin%20Trip'); + }); + + test('a project can be moved into an area', () => { + update.run('p-001', { area: 'Travel' }); + expect(lastUrl()).toContain('area=Travel'); + }); + + 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(); + }); +}); diff --git a/test/unit/url.test.js b/test/unit/url.test.js index 2bb83a1..b2aca62 100644 --- a/test/unit/url.test.js +++ b/test/unit/url.test.js @@ -60,3 +60,27 @@ describe('buildJsonUrl', () => { ]); }); }); + +describe('buildUpdateProjectUrl', () => { + 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/verify.test.js b/test/unit/verify.test.js new file mode 100644 index 0000000..a7bad05 --- /dev/null +++ b/test/unit/verify.test.js @@ -0,0 +1,58 @@ +'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); + }); +}); From aed788e97ce08754548d329d6edac7120bda15ac Mon Sep 17 00:00:00 2001 From: Henry Kaufman Date: Tue, 29 Sep 2026 13:05:52 -0400 Subject: [PATCH 2/2] Address pre-landing review: finish the routing fix, close a token leak Five review lenses ran against this branch. What they found, and what changed: SECURITY - macOS `open` echoes the whole failing url back on stderr, auth-token included, and exec.js spliced that into ThingsUrlError. The CLI prints it to stderr and the MCP server returns it as tool output, so the token landed in a model transcript. Redacted at the source; complete.js no longer interpolates the raw error into per-item output either. - resolveTaskId interpolated the id into a LIKE pattern, so `complete '%' --yes-first` resolved to an arbitrary row. Wildcards are escaped now. This got worse the moment update could relocate work instead of only completing it. CORRECTNESS - tag.js was still building `things:///update`, so tagging a project stayed a silent no-op. The diff claimed to fix every write and had missed one. - `--completed false` sent completed=true: the parser yields the string 'false', which is truthy. Booleans are normalised once, up front. - Re-parenting was verified only by "userModificationDate moved", which a concurrent edit or a Cloud sync also satisfies. It now asserts the row's project/area column equals the resolved target. - update/move refused nothing for headings and would stall the full timeout. - Restored the "project" label on update's success line, dropped when I resolved the 2.0.4 merge. PERFORMANCE - One connection per wait, not one per poll (measured ~18x on the poll loop). - Backoff 20/40/80 then 100ms; the first read almost always misses, so every verified write used to pay a flat 100ms. - Bulk complete shares one budget: N ids against a quit Things was N x 3s. - The wait is synchronous and blocks the MCP server's event loop, so that server now defaults to a 1200ms timeout. THINGSCTL_VERIFY_TIMEOUT_MS overrides both. Making the write path async is the real fix; not done here. SIMPLIFICATION / MAINTAINABILITY - Deleted WriteNotAppliedError, which was dead on arrival, and replaced the three hand-copied failure strings with verify.notApplied. - verify.js exports 6 names instead of 6 with 3 unused; VERIFY_FIELDS selects the 8 columns predicates actually read, not 13. - db.close() resets the test-seam flag; help.js documents the new flags. - move.js says "Rescheduled" on success, matching its own failure string. TESTS: 100 -> 129. The old dispatch suite mocked verification wholesale, so every failure path was uncovered. It now stubs only waitForWrite, leaving the SQL and the failure text real, and covers: failure reporting for all four write commands, heading refusal, list-id/area-id precedence, row-level re-parent verification, --completed false, LIKE escaping, and token redaction. Verified end to end against real Things: re-parent lands in the project column, task and project both complete, and tagging with a tag that does not exist now reports failure instead of a checkmark. Claude-Session: https://claude.ai/code/session_01LMbjcZogpv9EbVnqovXpSX --- CHANGELOG.md | 69 ++++++---- bin/thingsctl-mcp.js | 5 + src/commands/complete.js | 15 ++- src/commands/move.js | 12 +- src/commands/tag.js | 23 +++- src/commands/update.js | 108 ++++++++++++---- src/help.js | 8 +- src/lib/db.js | 1 + src/lib/errors.js | 16 --- src/lib/exec.js | 12 +- src/lib/uuid.js | 8 +- src/lib/verify.js | 97 ++++++++++---- test/integration/verify-read.test.js | 50 ++++++++ test/integration/write-dispatch.test.js | 162 +++++++++++++++++++----- test/unit/exec.test.js | 31 +++++ test/unit/uuid.test.js | 22 ++++ test/unit/verify.test.js | 34 +++++ 17 files changed, 527 insertions(+), 146 deletions(-) create mode 100644 test/integration/verify-read.test.js create mode 100644 test/unit/exec.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index 35beeb5..b3a1351 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,34 +2,53 @@ ## 2.1.0 -Writes could silently do nothing and still report success. Fixed, plus the -missing ability to move a to-do or project to a different parent. +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` and `move` still no-opped on projects.** 2.0.4 routed `update` - to `things:///update-project` but left `complete` and `move` building +- **`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`. Both now route by entity type, finishing - the fix 2.0.4 started. -- **Success is now verified against the database, not assumed.** `open` exiting 0 - only means macOS handed the URL to Things — it says nothing about whether Things - accepted it. Writes now poll the database (up to 3s) until the change is visible - and report a clear failure if it never lands. This is what turned the bug above - from an error into a lie. -- **Added: move a to-do or project to a different parent.** Previously impossible - through the tool — `update` had no parameter for it and `move` only reschedules - despite the name. Now `update --list` / `--list-id` moves a to-do into a project - or area, and `update --area` / `--area-id` moves a project into an area. Passing - the wrong pair for the type (e.g. `--list` on a project) is refused with an - explanatory error rather than dropped silently by Things. -- **`complete` refuses headings** instead of dispatching a URL that does nothing. -- **`things_move`'s description now says it only reschedules**, and points at - `things_update` for re-parenting. The old wording ("moving it to...") read as a - re-parent and misled callers. + 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. -New: `src/lib/verify.js` (post-write confirmation), `url.buildUpdateProjectUrl`, -`db.openFresh`, `WriteNotAppliedError`. 20 regression tests added, including one -that pins each write command to the correct endpoint per task type. ## 2.0.4 Fix `update` silently no-opping on projects. Things applies the `update` 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/src/commands/complete.js b/src/commands/complete.js index e9acfac..7a205ac 100644 --- a/src/commands/complete.js +++ b/src/commands/complete.js @@ -7,7 +7,7 @@ const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); const { colors } = require('../lib/format'); const { STATUS, TYPE } = require('../lib/constants'); -const { waitForWrite } = require('../lib/verify'); +const { waitForWrite, notApplied, DEFAULT_TIMEOUT_MS } = require('../lib/verify'); const queries = require('../lib/queries'); function run(ids, opts = {}) { @@ -15,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}`}`); @@ -41,16 +45,17 @@ function run(ids, opts = {}) { try { 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); + 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}` - : `${colors.red('✗')} Things did not complete the ${label} "${task.title}" ` + - `(the URL was accepted but the database never changed)` + : notApplied(`complete the ${label}`, task.title) ); } return list.length === 1 ? out[0] : out; diff --git a/src/commands/move.js b/src/commands/move.js index a9ab859..e659735 100644 --- a/src/commands/move.js +++ b/src/commands/move.js @@ -7,7 +7,7 @@ const { openUrl } = require('../lib/exec'); const { getToken } = require('../lib/token'); const { colors } = require('../lib/format'); const { TYPE } = require('../lib/constants'); -const { waitForWrite, snapshot, modifiedSince } = require('../lib/verify'); +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 @@ -18,17 +18,17 @@ function run(id, opts = {}) { 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'] }); + 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 `${colors.red('✗')} Things did not reschedule "${ref.title}" ` + - `(the URL was accepted but the database never changed)`; - } - return `Moved "${ref.title}" to ${opts.to}`; + if (!ok) return notApplied('reschedule', ref.title); + return `Rescheduled "${ref.title}" to ${opts.to}`; } module.exports = { 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 54d4603..97f8e47 100644 --- a/src/commands/update.js +++ b/src/commands/update.js @@ -8,7 +8,32 @@ 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 } = require('../lib/verify'); +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'); @@ -17,6 +42,10 @@ function run(id, opts = {}) { 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. @@ -33,8 +62,12 @@ function run(id, opts = {}) { ); } + 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'); } @@ -50,19 +83,35 @@ function run(id, opts = {}) { 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']}`); } - // Re-parenting. list-id takes precedence over list, area-id over area. - if (opts['list-id']) { params['list-id'] = opts['list-id']; changes.push(`moved into ${opts['list-id']}`); } - else if (opts.list) { params.list = opts.list; changes.push(`moved into "${opts.list}"`); } - if (opts['area-id']) { params['area-id'] = opts['area-id']; changes.push(`moved into area ${opts['area-id']}`); } - else if (opts.area) { params.area = opts.area; changes.push(`moved into area "${opts.area}"`); } + // 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 (opts.completed !== undefined) { - params.completed = opts.completed ? 'true' : 'false'; - changes.push(opts.completed ? 'completed' : 'reopened'); + 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'); @@ -70,18 +119,24 @@ function run(id, opts = {}) { const before = snapshot(task.uuid); openUrl(isProject ? buildUpdateProjectUrl(params) : buildUpdateUrl(params)); - // Assert the end state where we know it; fall back to "something changed". + // 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 (opts.canceled === true) predicate = (r) => r.status === STATUS.CANCELED; - else if (opts.completed === true) predicate = (r) => r.status === STATUS.COMPLETED; - else if (opts.completed === false || opts.canceled === false) predicate = (r) => r.status === STATUS.OPEN; + 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 `${colors.red('✗')} Things did not apply the change to "${task.title}" ` + - `(the URL was accepted but the database never changed)`; - } - return `${colors.green('✓')} Updated "${task.title}": ${changes.join(', ')}`; + if (!ok) return notApplied('apply the change to', task.title); + + const label = isProject ? 'project ' : ''; + return `${colors.green('✓')} Updated ${label}"${task.title}": ${changes.join(', ')}`; } module.exports = { @@ -112,6 +167,15 @@ module.exports = { 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 841fd5b..4942ce1 100644 --- a/src/lib/db.js +++ b/src/lib/db.js @@ -29,6 +29,7 @@ function close() { if (_db) { try { _db.close(); } catch (_) {} _db = null; + _isTestDb = false; } } diff --git a/src/lib/errors.js b/src/lib/errors.js index 4b35a54..45ddb9f 100644 --- a/src/lib/errors.js +++ b/src/lib/errors.js @@ -37,21 +37,6 @@ class ThingsUrlError extends ThingsCtlError { } } -// Raised when a URL-scheme write was dispatched but the database never showed -// the change. Usually means Things rejected the command outright. -class WriteNotAppliedError extends ThingsCtlError { - constructor(title, detail) { - super( - `Things did not apply the change to "${title}".` + - (detail ? ` ${detail}` : '') + - '\n The command was accepted by macOS but Things made no change.' + - '\n Check that Things 3 is running and that the auth token is valid.', - 'E_WRITE_NOT_APPLIED' - ); - this.title = title; - } -} - class TokenMissingError extends ThingsCtlError { constructor() { super( @@ -69,6 +54,5 @@ module.exports = { TaskNotFoundError, AmbiguousIdError, ThingsUrlError, - WriteNotAppliedError, TokenMissingError, }; 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/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 index b4df136..855a574 100644 --- a/src/lib/verify.js +++ b/src/lib/verify.js @@ -1,6 +1,7 @@ 'use strict'; const db = require('./db'); +const { colors } = require('./format'); // Why this module exists. // @@ -13,65 +14,105 @@ const db = require('./db'); // // So: a write is not confirmed until the database says it landed. -const DEFAULT_TIMEOUT_MS = 3000; -const DEFAULT_INTERVAL_MS = 100; +// 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; -const VERIFY_FIELDS = ` - uuid, title, type, status, project, area, heading, - start, startBucket, startDate, deadline, notes, userModificationDate -`; +// 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 rather than turning every -// command into a promise chain. +// 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); } -function readRow(uuid) { +// 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 conn.prepare(`SELECT ${VERIFY_FIELDS} FROM TMTask WHERE uuid = ?`).get(uuid); + return fn(conn); } finally { - try { conn.close(); } catch (_) { /* nothing useful to do */ } + 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 intervalMs = opts.intervalMs == null ? DEFAULT_INTERVAL_MS : opts.intervalMs; const deadline = Date.now() + timeoutMs; - for (;;) { - const row = readRow(uuid); - if (row && predicate(row)) return { ok: true, row }; - if (Date.now() >= deadline) return { ok: false, row }; - sleepSync(intervalMs); - } -} - -// Snapshot the fields a command is about to change, so the predicate can ask -// "did anything actually move?" rather than guessing at final values. -function snapshot(uuid) { - return readRow(uuid); + 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. Use a field-specific predicate where one exists (status, project) — -// this is the fallback for edits whose end state we can't cheaply assert. +// 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, - readRow, - sleepSync, + 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 index 45234ef..5e2ddf3 100644 --- a/test/integration/write-dispatch.test.js +++ b/test/integration/write-dispatch.test.js @@ -3,76 +3,143 @@ // 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. +// 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() })); +jest.mock('../../src/lib/exec', () => ({ openUrl: jest.fn(), redactToken: (s) => s })); jest.mock('../../src/lib/token', () => ({ getToken: () => 'TESTTOKEN' })); -jest.mock('../../src/lib/verify', () => ({ - waitForWrite: () => ({ ok: true, row: {} }), - snapshot: () => ({ userModificationDate: 1 }), - modifiedSince: () => () => true, -})); +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 = () => openUrl.mock.calls[openUrl.mock.calls.length - 1][0]; +const lastUrl = () => { + expect(openUrl).toHaveBeenCalled(); + return openUrl.mock.calls[openUrl.mock.calls.length - 1][0]; +}; -beforeEach(() => openUrl.mockClear()); +beforeEach(() => { + openUrl.mockClear(); + waitForWrite.mockClear(); + waitForWrite.mockReturnValue({ ok: true, row: {} }); +}); -describe('complete routes by task type', () => { - test('a project goes to update-project', () => { +describe('writes route by entity type', () => { + test('complete: project → update-project', () => { complete.run(['p-001']); expect(lastUrl()).toContain('things:///update-project?'); - expect(lastUrl()).toContain('id=p-001'); expect(lastUrl()).toContain('completed=true'); }); - test('a to-do goes to update', () => { + test('complete: to-do → update', () => { complete.run(['t-today-1']); expect(lastUrl()).toContain('things:///update?'); expect(lastUrl()).not.toContain('update-project'); }); - test('a heading is refused rather than silently dropped', () => { - const out = complete.run(['h-001']); - expect(out).toMatch(/Cannot complete a heading/); - expect(openUrl).not.toHaveBeenCalled(); + test('update: project → update-project', () => { + update.run('p-001', { title: 'Launch v2' }); + expect(lastUrl()).toContain('things:///update-project?'); }); -}); -describe('update routes by task type', () => { - test('a project goes to update-project', () => { - update.run('p-001', { title: 'Launch v2' }); + 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('a to-do goes to update', () => { - update.run('t-today-1', { title: 'Ship it' }); + test('tag: to-do → update', () => { + tag.run('t-today-1', { add: 'Urgent' }); expect(lastUrl()).toContain('things:///update?'); + expect(lastUrl()).not.toContain('update-project'); }); }); -describe('move routes by task type', () => { - test('rescheduling a project goes to update-project', () => { - move.run('p-001', { to: 'today' }); - expect(lastUrl()).toContain('things:///update-project?'); - expect(lastUrl()).toContain('when=today'); +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('a to-do can be moved into a project by title', () => { - update.run('t-today-1', { list: 'Berlin Trip' }); - expect(lastUrl()).toContain('list=Berlin%20Trip'); + 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('a project can be moved into an area', () => { - update.run('p-001', { area: 'Travel' }); - expect(lastUrl()).toContain('area=Travel'); + 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', () => { @@ -84,4 +151,31 @@ describe('re-parenting', () => { 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/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 index a7bad05..737f613 100644 --- a/test/unit/verify.test.js +++ b/test/unit/verify.test.js @@ -56,3 +56,37 @@ describe('modifiedSince', () => { 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); + }); +});