From dfb022f6ffc52f88c12a3c94e8afe918a329a481 Mon Sep 17 00:00:00 2001 From: Henry Kaufman Date: Tue, 16 Jun 2026 13:50:09 -0400 Subject: [PATCH 1/2] fix: decode XML-plist recurrence rules and hide templates from someday MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Current Things writes the recurrence rule as an XML plist (fu=NSCalendarUnit, fa=interval, of=weekday/day), not the binary-plist format the decoder sniffed for, so every repeat read as UNKNOWN. Rewrite the decoder to parse it. Repeating-task templates are stored with start=2 (same as Someday) but the app hides them; somedayTasks and the stats someday count now exclude rows with a recurrence rule so templates stop masquerading as Someday tasks. rt1_nextInstanceStartDate is a bit-packed calendar date, not Unix seconds — decode it with thingsDateToIso/formatThingsShortDate instead of the never-true >= 1e9 guard. Fixture emits real recurrence XML plus a Someday-template row; regression tests cover the someday exclusion, frequency decode, and next-instance date. --- src/commands/repeating.js | 12 +++-- src/commands/stats.js | 1 + src/lib/queries.js | 5 ++ src/lib/rrule.js | 91 +++++++++++++++++++++------------- test/fixtures/build.js | 34 +++++++++++-- test/integration/lists.test.js | 23 ++++++++- test/unit/rrule.test.js | 33 ++++++++++++ 7 files changed, 155 insertions(+), 44 deletions(-) diff --git a/src/commands/repeating.js b/src/commands/repeating.js index e6b3eb3..83e0c5c 100644 --- a/src/commands/repeating.js +++ b/src/commands/repeating.js @@ -5,7 +5,7 @@ const queries = require('../lib/queries'); const { colors } = require('../lib/format'); const { taskToJson } = require('../lib/format'); const { decodeRecurrenceRule, describe } = require('../lib/rrule'); -const { formatShortDate, unixToDate } = require('../lib/dates'); +const { formatThingsShortDate, thingsDateToIso } = require('../lib/dates'); const { pickFilters, filterSchema, outputSchema } = require('./_filters'); function _line(t, decode) { @@ -14,8 +14,10 @@ function _line(t, decode) { const rule = decodeRecurrenceRule(t.rt1_recurrenceRule); line += ` ${colors.dim('(' + describe(rule) + ')')}`; } - if (t.rt1_nextInstanceStartDate >= 1000000000) { - const next = formatShortDate(t.rt1_nextInstanceStartDate); + // rt1_nextInstanceStartDate is a bit-packed Things calendar date, NOT Unix + // seconds — decode it the same way as startDate/deadline. + if (t.rt1_nextInstanceStartDate > 0) { + const next = formatThingsShortDate(t.rt1_nextInstanceStartDate); if (next) line += ` ${colors.blue('next ' + next)}`; } const tags = t.tagList ? t.tagList.split(',').filter(Boolean) : []; @@ -29,8 +31,8 @@ function run(opts = {}) { return tasks.map((t) => ({ ...taskToJson(t), recurrence: decodeRecurrenceRule(t.rt1_recurrenceRule), - nextInstance: t.rt1_nextInstanceStartDate >= 1000000000 - ? unixToDate(t.rt1_nextInstanceStartDate).toISOString() : null, + nextInstance: t.rt1_nextInstanceStartDate > 0 + ? thingsDateToIso(t.rt1_nextInstanceStartDate) : null, })); } if (opts.ids) return tasks.map((t) => t.uuid); diff --git a/src/commands/stats.js b/src/commands/stats.js index ad503e5..15e6a5a 100644 --- a/src/commands/stats.js +++ b/src/commands/stats.js @@ -25,6 +25,7 @@ function _gather(database) { SELECT COUNT(*) as count FROM TMTask WHERE status=0 AND trashed=0 AND type=0 AND start=2 AND todayIndex<=0 AND startDate IS NULL + AND rt1_recurrenceRule IS NULL `), upcoming: q(`SELECT COUNT(*) as count FROM TMTask WHERE status=0 AND trashed=0 AND type=0 AND startDate IS NOT NULL AND startDate >= ? AND todayIndex<=0`, tomorrow), evening: q(`SELECT COUNT(*) as count FROM TMTask WHERE status=0 AND trashed=0 AND type=0 AND startBucket=1 AND todayIndex<=0`), diff --git a/src/lib/queries.js b/src/lib/queries.js index 539dabd..d126209 100644 --- a/src/lib/queries.js +++ b/src/lib/queries.js @@ -99,10 +99,15 @@ function anytimeTasks(db, filters = {}) { function somedayTasks(db, filters = {}) { const f = _filterClauses(filters); + // Repeating-task templates are stored with start=2 (the same value as + // Someday) but Things hides them from the Someday list — only their + // generated instances show (in Today/Upcoming). Exclude any row that carries + // a recurrence rule so templates don't masquerade as Someday tasks. return db.prepare(` SELECT ${SELECT_TASK_FIELDS} ${BASE} AND t.start = 2 AND t.todayIndex <= 0 AND t.startDate IS NULL + AND t.rt1_recurrenceRule IS NULL ${f.sql} ORDER BY t."index" ASC `).all(...f.params); diff --git a/src/lib/rrule.js b/src/lib/rrule.js index 0bfd70d..05f12be 100644 --- a/src/lib/rrule.js +++ b/src/lib/rrule.js @@ -1,44 +1,65 @@ 'use strict'; -// Best-effort decode of TMTask.rt1_recurrenceRule (a binary plist that -// archives an EKRecurrenceRule). We don't ship a full plist parser; instead -// we sniff the canonical bytes that always appear in the buffer. +// Decode TMTask.rt1_recurrenceRule. In current Things 3 builds this is an +// XML *property list* (not a binary plist) archiving the repeat rule. It uses +// short keys: // -// Returns { freq, interval, weekdays, raw } where freq ∈ -// 'DAILY'|'WEEKLY'|'MONTHLY'|'YEARLY'|'UNKNOWN'. +// fu frequency unit — an NSCalendarUnit bit value: +// 4=year, 8=month, 16=day, 256=weekday(week), +// 512=weekday-ordinal (nth weekday of month) +// fa frequency amount — the interval ("every N units") +// of array of "on" specifiers, each a dict with either +// wd=<1..7> (weekday, 1=Sun) or dy=<1..31> (day of month) +// tp schedule type, ed/ia/sr anchor + end dates (not needed for cadence) +// +// Returns { freq, interval, weekday?, dayOfMonth? } where freq ∈ +// 'DAILY'|'WEEKLY'|'MONTHLY'|'YEARLY'|'UNKNOWN'. Anything we can't parse +// degrades to { freq: 'UNKNOWN', interval: 1 }. + +function _toXml(buf) { + if (buf == null) return null; + if (Buffer.isBuffer(buf)) return buf.length ? buf.toString('utf8') : null; + const s = String(buf); + return s.length ? s : null; +} + +function _int(xml, key) { + const m = xml.match(new RegExp(`${key}\\s*(-?\\d+)`)); + return m ? parseInt(m[1], 10) : null; +} -const FREQ = { 0: 'DAILY', 1: 'WEEKLY', 2: 'MONTHLY', 3: 'YEARLY' }; +// First weekday/day-of-month inside the of array, if any. +function _ofInt(xml, subkey) { + const idx = xml.indexOf('of'); + if (idx < 0) return null; + const m = xml.slice(idx).match(new RegExp(`${subkey}\\s*(-?\\d+)`)); + return m ? parseInt(m[1], 10) : null; +} + +function _freqFromUnit(fu) { + if (fu == null) return 'UNKNOWN'; + if (fu & 4) return 'YEARLY'; // NSCalendarUnitYear + if (fu & 8) return 'MONTHLY'; // NSCalendarUnitMonth + if (fu & 512) return 'MONTHLY'; // NSCalendarUnitWeekdayOrdinal (nth weekday) + if (fu & 256) return 'WEEKLY'; // NSCalendarUnitWeekday + if (fu & 16) return 'DAILY'; // NSCalendarUnitDay + return 'UNKNOWN'; +} function decodeRecurrenceRule(buf) { - if (!buf || !Buffer.isBuffer(buf)) return { freq: 'UNKNOWN', interval: 1 }; - - let freq = 'UNKNOWN'; - let interval = 1; - - // Look for "frequency" / "interval" UTF-8 keys, then read the byte after the - // associated kCFNumberSInt32Type marker. This is heuristic but stable across - // recent Things versions. - const text = buf.toString('binary'); - - const fIdx = text.indexOf('frequency'); - if (fIdx >= 0) { - // After 'frequency' (9 bytes) comes a few bytes of plist metadata, then - // the integer value as a single byte for small numbers. - for (let off = fIdx + 9; off < Math.min(fIdx + 24, buf.length); off++) { - const b = buf[off]; - if (b >= 0 && b <= 3) { freq = FREQ[b]; break; } - } - } - - const iIdx = text.indexOf('interval'); - if (iIdx >= 0) { - for (let off = iIdx + 8; off < Math.min(iIdx + 24, buf.length); off++) { - const b = buf[off]; - if (b >= 1 && b <= 60) { interval = b; break; } - } - } - - return { freq, interval }; + const xml = _toXml(buf); + if (!xml) return { freq: 'UNKNOWN', interval: 1 }; + + const freq = _freqFromUnit(_int(xml, 'fu')); + const fa = _int(xml, 'fa'); + const interval = fa && fa > 0 ? fa : 1; + + const rule = { freq, interval }; + const wd = _ofInt(xml, 'wd'); + if (wd != null) rule.weekday = wd; // 1=Sun … 7=Sat + const dy = _ofInt(xml, 'dy'); + if (dy != null) rule.dayOfMonth = dy; + return rule; } function describe(rule) { diff --git a/test/fixtures/build.js b/test/fixtures/build.js index ca2076c..bcffcfa 100644 --- a/test/fixtures/build.js +++ b/test/fixtures/build.js @@ -34,6 +34,24 @@ const PACK_DAYS = (offset) => { }; const PACKED_TODAY = PACK(TODAY_MIDNIGHT); +// Real Things recurrence rule: an XML plist with fu (NSCalendarUnit: 4=year, +// 8=month, 16=day, 256=weekday), fa (interval), and an `of` array carrying a +// weekday (wd) or day-of-month (dy). Mirrors what current Things 3 writes. +const RRULE = ({ fu, fa = 1, wd, dy }) => { + const of = + wd != null ? `wd${wd}` + : dy != null ? `dy${dy}` + : ''; + const xml = + `\n` + + `fa${fa}` + + `fu${fu}` + + `of${of}` + + `tp1` + + ``; + return Buffer.from(xml, 'utf8'); +}; + function build() { if (fs.existsSync(OUT)) fs.unlinkSync(OUT); const db = new Database(OUT); @@ -90,7 +108,16 @@ function build() { insertTask.run( 't-template-1', 0, 0, 'Weekly review template', null, 2, null, 0, null, 1, 900, 'a-work', null, null, NOW_UNIX - 86400 * 60, NOW_UNIX - 86400 * 30, null, 0, 0, - Buffer.from('frequency\x00\x01interval\x00\x01'), PACK_DAYS(7) + RRULE({ fu: 256, fa: 1, wd: 2 }), PACK_DAYS(7) + ); + + // Recurrence template in Someday with todayIndex=0 — exactly how the real DB + // stores a repeating to-do. Regression guard for the "templates leak into + // Someday" bug: it must be excluded from `someday` but listed by `repeating`. + insertTask.run( + 't-template-someday', 0, 0, 'Biweekly 1:1 recurring', null, 2, null, 0, null, 2, 0, 'a-work', null, null, + NOW_UNIX - 86400 * 60, NOW_UNIX - 86400 * 30, null, 0, 0, + RRULE({ fu: 256, fa: 2, wd: 4 }), PACK_DAYS(3) ); // Inbox task @@ -137,11 +164,12 @@ function build() { NOW_UNIX - 86400, NOW_UNIX - 3600, null, 0, 0, null, 0 ); - // Repeating task with a stub recurrence rule blob + // Repeating task (daily) — anchored in Anytime, with a real recurrence rule + // and a packed next-instance date. insertTask.run( 't-repeat-1', 0, 0, 'Standup recurring', null, 1, null, 0, null, 1, 0, 'a-work', null, null, NOW_UNIX - 86400 * 30, NOW_UNIX - 86400, null, 0, 0, - Buffer.from('frequency\x00\x01interval\x00\x01'), PACK_DAYS(1) + RRULE({ fu: 16, fa: 1 }), PACK_DAYS(1) ); // Completed task (logbook) — stopDate is Unix seconds diff --git a/test/integration/lists.test.js b/test/integration/lists.test.js index 678dcc6..ec00930 100644 --- a/test/integration/lists.test.js +++ b/test/integration/lists.test.js @@ -31,6 +31,11 @@ describe('list commands against fixture', () => { expect(out.map((t) => t.title)).toEqual(['Learn Mandarin']); }); + test('someday excludes repeating-task templates (start=2 + recurrence rule)', () => { + const out = someday.run({ json: true }); + expect(out.find((t) => t.title === 'Biweekly 1:1 recurring')).toBeUndefined(); + }); + test('upcoming lists future-scheduled tasks', () => { const out = upcoming.run({ json: true }); expect(out.map((t) => t.title)).toEqual(['Future thing']); @@ -53,7 +58,23 @@ describe('list commands against fixture', () => { test('repeating lists tasks with rt1_recurrenceRule', () => { const out = repeating.run({ json: true }); - expect(out.map((t) => t.title).sort()).toEqual(['Standup recurring', 'Weekly review template']); + expect(out.map((t) => t.title).sort()).toEqual([ + 'Biweekly 1:1 recurring', 'Standup recurring', 'Weekly review template', + ]); + }); + + test('repeating decodes frequency and interval from the recurrence rule', () => { + const byTitle = Object.fromEntries(repeating.run({ json: true }).map((t) => [t.title, t])); + expect(byTitle['Standup recurring'].recurrence).toMatchObject({ freq: 'DAILY', interval: 1 }); + expect(byTitle['Weekly review template'].recurrence).toMatchObject({ freq: 'WEEKLY', interval: 1 }); + expect(byTitle['Biweekly 1:1 recurring'].recurrence).toMatchObject({ freq: 'WEEKLY', interval: 2 }); + }); + + test('repeating decodes nextInstance as a real calendar date (not Unix-epoch)', () => { + const standup = repeating.run({ json: true }).find((t) => t.title === 'Standup recurring'); + expect(standup.nextInstance).not.toBeNull(); + expect(Number.isNaN(Date.parse(standup.nextInstance))).toBe(false); + expect(new Date(standup.nextInstance).getFullYear()).toBeGreaterThan(2000); }); test('projects includes the seeded project with task count', () => { diff --git a/test/unit/rrule.test.js b/test/unit/rrule.test.js index 26d9ff6..0f0cae0 100644 --- a/test/unit/rrule.test.js +++ b/test/unit/rrule.test.js @@ -2,12 +2,45 @@ const { decodeRecurrenceRule, describe: describeRule } = require('../../src/lib/rrule'); +// Minimal real-format Things recurrence plist. +const plist = ({ fu, fa, of = '' }) => + Buffer.from( + `\n` + + `fa${fa}` + + `fu${fu}` + + `of${of}` + + ``, + 'utf8' + ); + describe('decodeRecurrenceRule', () => { test('returns UNKNOWN for empty buffer', () => { expect(decodeRecurrenceRule(null)).toEqual({ freq: 'UNKNOWN', interval: 1 }); expect(decodeRecurrenceRule(Buffer.alloc(0))).toEqual({ freq: 'UNKNOWN', interval: 1 }); }); + test('decodes daily / weekly / monthly / yearly from fu (NSCalendarUnit)', () => { + expect(decodeRecurrenceRule(plist({ fu: 16, fa: 1 }))).toMatchObject({ freq: 'DAILY', interval: 1 }); + expect(decodeRecurrenceRule(plist({ fu: 256, fa: 1 }))).toMatchObject({ freq: 'WEEKLY', interval: 1 }); + expect(decodeRecurrenceRule(plist({ fu: 8, fa: 1 }))).toMatchObject({ freq: 'MONTHLY', interval: 1 }); + expect(decodeRecurrenceRule(plist({ fu: 4, fa: 1 }))).toMatchObject({ freq: 'YEARLY', interval: 1 }); + }); + + test('reads the interval from fa', () => { + expect(decodeRecurrenceRule(plist({ fu: 256, fa: 2 }))).toMatchObject({ freq: 'WEEKLY', interval: 2 }); + }); + + test('extracts weekday and day-of-month from the `of` array', () => { + const weekly = decodeRecurrenceRule(plist({ fu: 256, fa: 1, of: 'wd6' })); + expect(weekly.weekday).toBe(6); + const monthly = decodeRecurrenceRule(plist({ fu: 8, fa: 1, of: 'dy18' })); + expect(monthly.dayOfMonth).toBe(18); + }); + + test('accepts a string rule as well as a Buffer', () => { + expect(decodeRecurrenceRule(plist({ fu: 16, fa: 1 }).toString('utf8'))).toMatchObject({ freq: 'DAILY' }); + }); + test('describes UNKNOWN as "repeats"', () => { expect(describeRule({ freq: 'UNKNOWN', interval: 1 })).toBe('repeats'); }); From d0de515667878b7c7f8a00554ef2b467ecdc8b90 Mon Sep 17 00:00:00 2001 From: Henry Kaufman Date: Tue, 16 Jun 2026 13:50:09 -0400 Subject: [PATCH 2/2] chore: bump version and changelog (v2.0.3) Co-Authored-By: Claude Opus 4.8 --- CHANGELOG.md | 27 +++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 7959f9d..4bd7f7d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,32 @@ # Changelog +## 2.0.3 + +Fix recurring tasks across `someday` and `repeating`. Two bugs, both from the same +wrong-format assumption as 2.0.2: the code expected an older recurrence encoding +that current Things no longer writes. + +- **Repeating-task templates leaked into `someday`.** Things stores a repeating + to-do's template with `start = 2` (the same value as Someday) but hides it from + the Someday list, surfacing only the generated instances. `someday` (and the + `stats` someday count) listed every template, so a bank of recurring chores and + calls showed up as phantom Someday tasks. Both now exclude rows that carry a + recurrence rule, matching the app. +- **Recurrence rules never decoded.** `repeating` reported every task as + `freq: UNKNOWN` because the decoder sniffed for binary-plist `frequency` / + `interval` keys, but current Things writes an **XML plist** (`fu` = + NSCalendarUnit unit, `fa` = interval, `of` = weekday / day-of-month). Rewrote the + decoder to parse it, so cadences read correctly (`every week`, `every 2 weeks`, + `every month`, `every 2 days`). +- **`repeating` next-instance was always null.** `rt1_nextInstanceStartDate` is a + bit-packed calendar date (like `startDate`), not Unix seconds, but the code gated + it on `>= 1000000000`, which packed dates never satisfy. Now decoded with + `thingsDateToIso` / `formatThingsShortDate`. + +Fixture rebuilt to emit real recurrence-rule XML plus a Someday-template row; +regression tests added for the someday exclusion, frequency decoding, and +next-instance date. + ## 2.0.2 Fix date decoding across every list and stat. The previous releases misread the diff --git a/package.json b/package.json index 34df35e..8fa10b3 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "thingsctl", - "version": "2.0.2", + "version": "2.0.3", "description": "A full-featured command-line interface and MCP server for Things 3 on macOS.", "main": "src/cli.js", "type": "commonjs",