Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -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",
Expand Down
12 changes: 7 additions & 5 deletions src/commands/repeating.js
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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) : [];
Expand All @@ -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);
Expand Down
1 change: 1 addition & 0 deletions src/commands/stats.js
Original file line number Diff line number Diff line change
Expand Up @@ -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`),
Expand Down
5 changes: 5 additions & 0 deletions src/lib/queries.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
91 changes: 56 additions & 35 deletions src/lib/rrule.js
Original file line number Diff line number Diff line change
@@ -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>${key}</key>\\s*<integer>(-?\\d+)</integer>`));
return m ? parseInt(m[1], 10) : null;
}

const FREQ = { 0: 'DAILY', 1: 'WEEKLY', 2: 'MONTHLY', 3: 'YEARLY' };
// First weekday/day-of-month inside the <key>of</key> array, if any.
function _ofInt(xml, subkey) {
const idx = xml.indexOf('<key>of</key>');
if (idx < 0) return null;
const m = xml.slice(idx).match(new RegExp(`<key>${subkey}</key>\\s*<integer>(-?\\d+)</integer>`));
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) {
Expand Down
34 changes: 31 additions & 3 deletions test/fixtures/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 ? `<dict><key>wd</key><integer>${wd}</integer></dict>`
: dy != null ? `<dict><key>dy</key><integer>${dy}</integer></dict>`
: '';
const xml =
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict>` +
`<key>fa</key><integer>${fa}</integer>` +
`<key>fu</key><integer>${fu}</integer>` +
`<key>of</key><array>${of}</array>` +
`<key>tp</key><integer>1</integer>` +
`</dict></plist>`;
return Buffer.from(xml, 'utf8');
};

function build() {
if (fs.existsSync(OUT)) fs.unlinkSync(OUT);
const db = new Database(OUT);
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
23 changes: 22 additions & 1 deletion test/integration/lists.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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']);
Expand All @@ -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', () => {
Expand Down
33 changes: 33 additions & 0 deletions test/unit/rrule.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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(
`<?xml version="1.0" encoding="UTF-8"?>\n<plist version="1.0"><dict>` +
`<key>fa</key><integer>${fa}</integer>` +
`<key>fu</key><integer>${fu}</integer>` +
`<key>of</key><array>${of}</array>` +
`</dict></plist>`,
'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: '<dict><key>wd</key><integer>6</integer></dict>' }));
expect(weekly.weekday).toBe(6);
const monthly = decodeRecurrenceRule(plist({ fu: 8, fa: 1, of: '<dict><key>dy</key><integer>18</integer></dict>' }));
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');
});
Expand Down
Loading