diff --git a/web/src/lib/taskWrites.test.ts b/web/src/lib/taskWrites.test.ts new file mode 100644 index 0000000..74837ae --- /dev/null +++ b/web/src/lib/taskWrites.test.ts @@ -0,0 +1,552 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll, vi } from 'vitest'; +import type { PGlite } from 'electric-sql-pglite'; + +// createTask, updateTask and setTaskTags (#203), called as the write envelope +// of the MCP tools calls them: in a transaction of the caller, against an +// in-memory Postgres (PGlite) with the companion migrations. completeTask and +// reopenTask are tested with the route that shares them +// (../app/api/tasks/route.test.ts). The database client is replaced by +// PGlite: taskWrites.ts never imports it, taskDelete.ts (lockTaskForLinks) +// does. + +const h = await vi.hoisted(async () => { + const { PGlite } = await import('electric-sql-pglite'); + return { pg: new PGlite() as PGlite }; +}); + +vi.mock('@/db/client', async () => { + const { drizzle } = await import('drizzle-orm/pglite'); + const schema = await import('@/db/schema'); + return { db: drizzle(h.pg, { schema }) }; +}); + +const { db } = await import('@/db/client'); +const { createTask, updateTask, setTaskTags, WriteRefusal } = await import('./taskWrites'); +const { ToolRefusal } = await import('./mcp/errors'); + +type CreateInput = Parameters[2]; +type Patch = Parameters[3]; + +type Account = { userId: string; inbox: string }; + +// Every column of sl_tasks, as PGlite returns a row. +type StoredTask = { + id: string; user_id: string; title: string; notes: string | null; completed: boolean; completed_at: Date | null; + priority: number; due_date: Date | null; list_id: string; parent_id: string | null; position: number; + recurrence: string | null; created_at: Date; updated_at: Date; deleted_at: Date | null; +}; + +type TaskFields = { + list?: string; parentId?: string; position?: number; title?: string; notes?: string; priority?: number; + dueDate?: string; recurrence?: string; deletedAt?: string; +}; + +// When the rows of a test were written, when a deleted one was deleted, and +// the instant the function under test receives. +const SEEDED = '2026-11-01T10:00:00.000Z'; +const GONE = '2026-11-10T09:00:00.000Z'; +const NOW = new Date('2026-11-15T15:00:00.000Z'); + +async function rows(sql: string, params: unknown[] = []): Promise { + return (await h.pg.query(sql, params)).rows; +} + +// Each test creates its own accounts (#148). An account without any list is +// one that never synced a device. +const bare = () => `user-${u()}`; + +async function newList(userId: string, fields: { inbox?: boolean; createdAt?: string; deletedAt?: string } = {}): Promise { + const id = u(); + await h.pg.query( + 'insert into sl_lists (id, user_id, name, is_inbox, created_at, deleted_at) values ($1, $2, $3, $4, $5, $6)', + [id, userId, fields.inbox ? 'Inbox' : 'List', fields.inbox ?? false, fields.createdAt ?? SEEDED, fields.deletedAt ?? null], + ); + return id; +} + +async function newAccount(): Promise { + const userId = bare(); + return { userId, inbox: await newList(userId, { inbox: true }) }; +} + +// What newTask needs to write a row the sync never writes: a task of +// `account` in a list of another account. +const misplaced = (account: Account, list: string): Account => ({ userId: account.userId, inbox: list }); + +async function newTask(account: Account, fields: TaskFields = {}): Promise { + const id = u(); + await h.pg.query( + `insert into sl_tasks + (id, user_id, title, list_id, parent_id, position, notes, priority, due_date, recurrence, created_at, updated_at, deleted_at) + values ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $11, $12)`, + [ + id, account.userId, fields.title ?? 'Task', fields.list ?? account.inbox, fields.parentId ?? null, + fields.position ?? 0, fields.notes ?? null, fields.priority ?? 0, fields.dueDate ?? null, + fields.recurrence ?? null, SEEDED, fields.deletedAt ?? null, + ], + ); + return id; +} + +async function newTag(userId: string, fields: { deletedAt?: string } = {}): Promise { + const id = u(); + await h.pg.query('insert into sl_tags (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [id, userId, 'Tag', fields.deletedAt ?? null]); + return id; +} + +async function link(taskId: string, tagId: string) { + await h.pg.query('insert into sl_task_tags (task_id, tag_id) values ($1, $2)', [taskId, tagId]); +} + +async function stored(id: string): Promise { + return (await rows('select * from sl_tasks where id = $1', [id]))[0]; +} + +// The tags a task is linked to, whatever they are, in a stable order. +async function tagsOf(taskId: string): Promise { + return (await rows<{ tag_id: string }>('select tag_id from sl_task_tags where task_id = $1 order by tag_id', [taskId])) + .map((row) => row.tag_id); +} + +async function listsOf(userId: string) { + return rows<{ id: string; name: string; is_inbox: boolean; deleted_at: Date | null }>( + 'select id, name, is_inbox, deleted_at from sl_lists where user_id = $1 order by created_at, id', [userId], + ); +} + +// Every row of the four tables, every column: what a refused write must leave +// exactly as it was. The tests of a file run one after the other. +async function everything() { + return { + lists: await rows('select * from sl_lists order by id'), + tasks: await rows('select * from sl_tasks order by id'), + tags: await rows('select * from sl_tags order by id'), + links: await rows('select * from sl_task_tags order by task_id, tag_id'), + }; +} + +const create = (userId: string, input: CreateInput) => db.transaction((tx) => createTask(tx, userId, input, NOW)); +const update = (userId: string, taskId: string, patch: Patch) => db.transaction((tx) => updateTask(tx, userId, taskId, patch, NOW)); +const setTags = (userId: string, taskId: string, tagIds: string[]) => db.transaction((tx) => setTaskTags(tx, userId, taskId, tagIds, NOW)); + +// The code a write is refused with. The refusal is the exception the envelope +// of the MCP tools renders, and it left nothing behind. +async function refusal(write: () => Promise): Promise { + const before = await everything(); + const error = await write().then(() => null, (e: unknown) => e); + expect(error).toBeInstanceOf(WriteRefusal); + expect(error).toBeInstanceOf(ToolRefusal); + expect(await everything()).toEqual(before); + return (error as InstanceType).code; +} + +// A write that answers null: not a task of the account, and nothing written. +async function absent(write: () => Promise) { + const before = await everything(); + expect(await write()).toBeNull(); + expect(await everything()).toEqual(before); +} + +beforeAll(async () => { + const dir = path.join(__dirname, '../db/migrations'); + for (const f of fs.readdirSync(dir).filter((f) => f.endsWith('.sql')).sort()) { + for (const stmt of fs.readFileSync(path.join(dir, f), 'utf8').split('--> statement-breakpoint')) { + if (stmt.trim()) await h.pg.exec(stmt); + } + } +}); + +describe('createTask', () => { + it('puts a task without a list at the end of the live Inbox of the account, with every field it received', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + await newTask(A, { position: 4 }); + // Neither a deleted task, nor a subtask, nor a task of another list counts. + const parent = await newTask(A, { position: 2 }); + await newTask(A, { position: 9, deletedAt: GONE }); + await newTask(A, { position: 8, parentId: parent }); + await newTask(A, { position: 7, list: await newList(A.userId) }); + // Nor a task of another account that sits in the list: a row the sync never writes. + await newTask(misplaced(B, A.inbox), { position: 99 }); + + const dueDate = new Date('2026-12-01T12:00:00.000Z'); + const result = await create(A.userId, { title: 'Call Paul', notes: 'About the roof', priority: 2, dueDate, recurrence: 'weekly' }); + expect(result.changed).toBe(true); + expect(await stored(result.task.id)).toEqual({ + id: result.task.id, user_id: A.userId, title: 'Call Paul', notes: 'About the roof', completed: false, completed_at: null, + priority: 2, due_date: dueDate, list_id: A.inbox, parent_id: null, position: 5, recurrence: 'weekly', + created_at: NOW, updated_at: NOW, deleted_at: null, + }); + // The row it returns is the row it wrote. + expect(result.task).toMatchObject({ id: result.task.id, userId: A.userId, listId: A.inbox, position: 5, updatedAt: NOW }); + + // Without the optional fields: the defaults of the table, first of an empty list. + const list = await newList(A.userId); + const plain = await create(A.userId, { title: 'Plain', listId: list }); + expect(await stored(plain.task.id)).toMatchObject({ + notes: null, priority: 0, due_date: null, recurrence: null, list_id: list, parent_id: null, position: 1, completed: false, + }); + expect(await tagsOf(plain.task.id)).toEqual([]); + }); + + it('gives an account without a live Inbox one Inbox, and only one after two creations', async () => { + const userId = bare(); + const first = await create(userId, { title: 'First' }); + const second = await create(userId, { title: 'Second' }); + const lists = await listsOf(userId); + expect(lists).toEqual([{ id: first.task.listId, name: 'Inbox', is_inbox: true, deleted_at: null }]); + expect(second.task.listId).toBe(first.task.listId); + expect([first.task.position, second.task.position]).toEqual([1, 2]); + + // A deleted Inbox is not an Inbox, and a list that is not the Inbox is not used. + const other = bare(); + const deleted = await newList(other, { inbox: true, deletedAt: GONE }); + const plain = await newList(other); + const created = await create(other, { title: 'Third' }); + expect([deleted, plain]).not.toContain(created.task.listId); + expect((await listsOf(other)).filter((list) => list.is_inbox && !list.deleted_at).map((list) => list.id)).toEqual([created.task.listId]); + + // Of two live Inboxes, the most recent one, as POST /api/sync picks it. + const twice = bare(); + await newList(twice, { inbox: true, createdAt: '2026-10-01T00:00:00Z' }); + const recent = await newList(twice, { inbox: true, createdAt: '2026-10-02T00:00:00Z' }); + expect((await create(twice, { title: 'Fourth' })).task.listId).toBe(recent); + expect(await listsOf(twice)).toHaveLength(2); + }); + + it('never uses the Inbox of another account: an account without one gets its own', async () => { + const [A, B] = [await newAccount(), bare()]; + const created = await create(B, { title: 'Mine' }); + expect(created.task.listId).not.toBe(A.inbox); + expect(created.task.userId).toBe(B); + expect(await listsOf(B)).toEqual([{ id: created.task.listId, name: 'Inbox', is_inbox: true, deleted_at: null }]); + expect((await listsOf(A.userId)).map((list) => list.id)).toEqual([A.inbox]); + }); + + it('refuses a list that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + for (const listId of [u(), await newList(A.userId, { deletedAt: GONE }), B.inbox, await newList(B.userId)]) { + expect(await refusal(() => create(A.userId, { title: 'Nowhere', listId })), listId).toBe('list_not_found'); + } + // The same list for its own account. + expect((await create(B.userId, { title: 'Mine', listId: B.inbox })).task.listId).toBe(B.inbox); + }); + + it('creates a subtask in the list of its parent, at the end of its subtasks, and ignores listId', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const list = await newList(A.userId); + const parent = await newTask(A, { list }); + await newTask(A, { parentId: parent, list, position: 3 }); + await newTask(A, { parentId: parent, list, position: 6, deletedAt: GONE }); + // Top-level tasks of the list do not count for a subtask, nor does a task + // of another account placed under the parent (a row the sync never writes). + await newTask(A, { list, position: 8 }); + await newTask(B, { parentId: parent, position: 50 }); + + // Whatever listId names: another list of the account, a list of another + // account, no list at all. + for (const [index, listId] of [A.inbox, B.inbox, u(), undefined].entries()) { + const { task } = await create(A.userId, { title: 'Sub', parentId: parent, listId }); + expect(await stored(task.id)).toMatchObject({ user_id: A.userId, list_id: list, parent_id: parent, position: 4 + index }); + } + // No Inbox was looked for. + expect((await listsOf(A.userId)).map((l) => l.id).sort()).toEqual([A.inbox, list].sort()); + }); + + it('refuses a parent that is unknown, deleted, of another account or a subtask itself', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const top = await newTask(A); + const subtask = await newTask(A, { parentId: top }); + for (const parentId of [u(), await newTask(A, { deletedAt: GONE }), await newTask(B)]) { + expect(await refusal(() => create(A.userId, { title: 'Orphan', parentId })), parentId).toBe('parent_not_found'); + } + expect(await refusal(() => create(A.userId, { title: 'Too deep', parentId: subtask }))).toBe('parent_is_subtask'); + // A subtask of another account is not found before it is a subtask. + const foreignSubtask = await newTask(B, { parentId: await newTask(B) }); + expect(await refusal(() => create(A.userId, { title: 'Orphan', parentId: foreignSubtask }))).toBe('parent_not_found'); + }); + + it('links the tags of the account, each once, whatever the letter case of their ids', async () => { + const A = await newAccount(); + const [red, blue] = [await newTag(A.userId), await newTag(A.userId)]; + const { task } = await create(A.userId, { title: 'Tagged', tagIds: [red, blue.toUpperCase(), red] }); + expect(await tagsOf(task.id)).toEqual([red, blue].sort()); + // An empty list links nothing. + expect(await tagsOf((await create(A.userId, { title: 'Bare', tagIds: [] })).task.id)).toEqual([]); + }); + + it('refuses a tag that is unknown, deleted or of another account, and writes nothing: neither the task nor the Inbox', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const own = await newTag(A.userId); + const parent = await newTask(A); + for (const tagId of [u(), await newTag(A.userId, { deletedAt: GONE }), await newTag(B.userId)]) { + expect(await refusal(() => create(A.userId, { title: 'Tagged', tagIds: [own, tagId] })), tagId).toBe('tag_not_found'); + expect(await refusal(() => create(A.userId, { title: 'Tagged', parentId: parent, tagIds: [tagId] })), tagId).toBe('tag_not_found'); + } + // An account without a list: the Inbox created for the task goes with it. + const userId = bare(); + expect(await refusal(() => create(userId, { title: 'Tagged', tagIds: [own] }))).toBe('tag_not_found'); + expect(await listsOf(userId)).toEqual([]); + }); +}); + +describe('updateTask', () => { + it('writes the fields of the patch and no other, and moves updatedAt', async () => { + const A = await newAccount(); + const id = await newTask(A, { title: 'Old', notes: 'Old notes', priority: 1, dueDate: '2026-12-01T12:00:00Z', recurrence: 'daily', position: 3 }); + const before = await stored(id); + + const result = await update(A.userId, id, { title: 'New' }); + expect(result).toMatchObject({ changed: true, task: { id, title: 'New', notes: 'Old notes', updatedAt: NOW } }); + expect(await stored(id)).toEqual({ ...before, title: 'New', updated_at: NOW }); + + const dueDate = new Date('2027-01-15T14:30:00.000Z'); + await update(A.userId, id, { notes: 'New notes', priority: 3, dueDate, recurrence: 'yearly' }); + expect(await stored(id)).toEqual({ + ...before, title: 'New', notes: 'New notes', priority: 3, due_date: dueDate, recurrence: 'yearly', updated_at: NOW, + }); + }); + + it('clears the notes, the due date and the recurrence with null', async () => { + const A = await newAccount(); + const id = await newTask(A, { notes: 'Notes', dueDate: '2026-12-01T12:00:00Z', recurrence: 'daily', priority: 2 }); + const before = await stored(id); + await update(A.userId, id, { notes: null }); + expect(await stored(id)).toEqual({ ...before, notes: null, updated_at: NOW }); + await update(A.userId, id, { dueDate: null, recurrence: null }); + expect(await stored(id)).toEqual({ ...before, notes: null, due_date: null, recurrence: null, updated_at: NOW }); + }); + + it('counts a patch that changes no value as a write, and a patch without a key as none', async () => { + const A = await newAccount(); + const id = await newTask(A, { title: 'Same', priority: 1 }); + const before = await stored(id); + + expect(await update(A.userId, id, {})).toMatchObject({ changed: false, task: { id, updatedAt: before.updated_at } }); + expect(await stored(id)).toEqual(before); + + expect(await update(A.userId, id, { title: 'Same', priority: 1 })).toMatchObject({ changed: true, task: { id, updatedAt: NOW } }); + expect(await stored(id)).toEqual({ ...before, updated_at: NOW }); + }); + + it('moves a task to the end of another list with its live subtasks', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const target = await newList(A.userId); + await newTask(A, { list: target, position: 6 }); + await newTask(A, { list: target, position: 9, deletedAt: GONE }); + await newTask(misplaced(B, target), { position: 99 }); + const id = await newTask(A, { position: 2, title: 'Parent' }); + const [first, second] = [await newTask(A, { parentId: id, position: 1 }), await newTask(A, { parentId: id, position: 2 })]; + const deleted = await newTask(A, { parentId: id, position: 3, deletedAt: GONE }); + // A neighbour of the task and its subtask stay where they are, and so does + // a task of another account placed under the task (a row the sync never writes). + const neighbour = await newTask(A, { position: 3 }); + const neighbourSub = await newTask(A, { parentId: neighbour }); + const foreignSub = await newTask(B, { parentId: id }); + const untouched = [await stored(deleted), await stored(neighbour), await stored(neighbourSub), await stored(foreignSub)]; + + const result = await update(A.userId, id, { listId: target, title: 'Moved' }); + expect(result).toMatchObject({ changed: true, task: { id, listId: target, position: 7, title: 'Moved' } }); + expect(await stored(id)).toMatchObject({ list_id: target, position: 7, parent_id: null, updated_at: NOW }); + // The subtasks follow, in their own order, and their updatedAt moves. + expect(await stored(first)).toMatchObject({ list_id: target, parent_id: id, position: 1, updated_at: NOW }); + expect(await stored(second)).toMatchObject({ list_id: target, parent_id: id, position: 2, updated_at: NOW }); + expect([await stored(deleted), await stored(neighbour), await stored(neighbourSub), await stored(foreignSub)]).toEqual(untouched); + }); + + it('moves nothing for the list the task is already in, whatever the letter case of the id', async () => { + const A = await newAccount(); + const id = await newTask(A, { position: 2 }); + await newTask(A, { position: 5 }); + const sub = await newTask(A, { parentId: id }); + const [before, subBefore] = [await stored(id), await stored(sub)]; + + for (const listId of [A.inbox, A.inbox.toUpperCase()]) { + expect(await update(A.userId, id, { listId })).toMatchObject({ changed: true, task: { listId: A.inbox, position: 2 } }); + } + // A write all the same: updatedAt of the task moved, the subtask was not written. + expect(await stored(id)).toEqual({ ...before, updated_at: NOW }); + expect(await stored(sub)).toEqual(subBefore); + }); + + it('refuses a list that is unknown, deleted or of another account, and to move a subtask', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const id = await newTask(A); + const sub = await newTask(A, { parentId: id }); + const target = await newList(A.userId); + for (const listId of [u(), await newList(A.userId, { deletedAt: GONE }), B.inbox]) { + // Nothing of the patch is written, its other fields included. + expect(await refusal(() => update(A.userId, id, { listId, title: 'Elsewhere' })), listId).toBe('list_not_found'); + expect(await refusal(() => update(A.userId, sub, { listId })), listId).toBe('list_not_found'); + } + // A subtask stays in the list of its parent: another list, and its own. + for (const listId of [target, A.inbox]) { + expect(await refusal(() => update(A.userId, sub, { listId, title: 'Elsewhere' })), listId).toBe('subtask_not_movable'); + } + // Its other fields can be written. + expect(await update(A.userId, sub, { title: 'Renamed' })).toMatchObject({ changed: true, task: { id: sub, title: 'Renamed', listId: A.inbox } }); + }); + + it('answers null for a task that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const target = await newList(A.userId); + const foreign = await newTask(B); + await newTask(B, { parentId: foreign }); + for (const id of [u(), await newTask(A, { deletedAt: GONE }), foreign]) { + await absent(() => update(A.userId, id, { title: 'Taken' })); + await absent(() => update(A.userId, id, { listId: target })); + await absent(() => update(A.userId, id, {})); + } + // Its own account writes it. + expect(await update(B.userId, foreign, { title: 'Mine' })).toMatchObject({ changed: true, task: { id: foreign, title: 'Mine' } }); + }); +}); + +describe('setTaskTags', () => { + it('replaces the tags of the task: removes what is not wanted, adds what is missing, moves updatedAt', async () => { + const A = await newAccount(); + const [red, blue, green] = [await newTag(A.userId), await newTag(A.userId), await newTag(A.userId)]; + const id = await newTask(A); + const other = await newTask(A); + await link(id, red); + await link(id, blue); + await link(other, red); + const before = await stored(id); + + const result = await setTags(A.userId, id, [blue, green]); + expect(result).toMatchObject({ changed: true, task: { id, updatedAt: NOW } }); + expect(await tagsOf(id)).toEqual([blue, green].sort()); + expect(await stored(id)).toEqual({ ...before, updated_at: NOW }); + // The links of another task are not touched, nor the task itself. + expect(await tagsOf(other)).toEqual([red]); + expect((await stored(other)).updated_at).toEqual(new Date(SEEDED)); + + // An empty list removes them all. + expect(await setTags(A.userId, id, [])).toMatchObject({ changed: true }); + expect(await tagsOf(id)).toEqual([]); + }); + + it('writes nothing for the set the task already has, in any order and any letter case', async () => { + const A = await newAccount(); + const [red, blue] = [await newTag(A.userId), await newTag(A.userId)]; + const [id, bareTask] = [await newTask(A), await newTask(A)]; + await link(id, red); + await link(id, blue); + const before = await everything(); + + for (const tagIds of [[red, blue], [blue, red], [blue, red.toUpperCase(), blue]]) { + expect(await setTags(A.userId, id, tagIds)).toMatchObject({ changed: false, task: { id, updatedAt: new Date(SEEDED) } }); + } + expect(await setTags(A.userId, bareTask, [])).toMatchObject({ changed: false, task: { id: bareTask } }); + expect(await everything()).toEqual(before); + }); + + it('removes a link left on a deleted tag or on a tag of another account', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const [kept, deleted, foreign] = [await newTag(A.userId), await newTag(A.userId, { deletedAt: GONE }), await newTag(B.userId)]; + const id = await newTask(A); + for (const tag of [kept, deleted, foreign]) await link(id, tag); + expect(await setTags(A.userId, id, [kept])).toMatchObject({ changed: true }); + expect(await tagsOf(id)).toEqual([kept]); + }); + + it('refuses a tag that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const own = await newTag(A.userId); + const id = await newTask(A); + await link(id, own); + for (const tagId of [u(), await newTag(A.userId, { deletedAt: GONE }), await newTag(B.userId)]) { + expect(await refusal(() => setTags(A.userId, id, [tagId])), tagId).toBe('tag_not_found'); + expect(await refusal(() => setTags(A.userId, id, [own, tagId])), tagId).toBe('tag_not_found'); + } + expect(await tagsOf(id)).toEqual([own]); + }); + + it('answers null for a task that is unknown, deleted or of another account, and writes nothing', async () => { + const [A, B] = [await newAccount(), await newAccount()]; + const [tagA, tagB] = [await newTag(A.userId), await newTag(B.userId)]; + const foreign = await newTask(B); + await link(foreign, tagB); + for (const id of [u(), await newTask(A, { deletedAt: GONE }), foreign]) { + await absent(() => setTags(A.userId, id, [tagA])); + await absent(() => setTags(A.userId, id, [])); + // The task is looked for first: a tag that would be refused is not read. + await absent(() => setTags(A.userId, id, [tagB])); + } + expect(await tagsOf(foreign)).toEqual([tagB]); + }); +}); + +describe('the contract of the module', () => { + it('writes in the transaction it receives: a rollback of the caller undoes everything', async () => { + const A = await newAccount(); + const [red, blue] = [await newTag(A.userId), await newTag(A.userId)]; + const target = await newList(A.userId); + const id = await newTask(A); + await newTask(A, { parentId: id }); + await link(id, red); + const userId = bare(); + const before = await everything(); + + await expect(db.transaction(async (tx) => { + expect(await createTask(tx, userId, { title: 'New' }, NOW)).toMatchObject({ changed: true }); + expect(await createTask(tx, A.userId, { title: 'Tagged', tagIds: [red] }, NOW)).toMatchObject({ changed: true }); + expect(await updateTask(tx, A.userId, id, { listId: target }, NOW)).toMatchObject({ changed: true }); + expect(await setTaskTags(tx, A.userId, id, [blue], NOW)).toMatchObject({ changed: true }); + // What a refused journal line does in an MCP tool. + throw new Error('journal line refused'); + })).rejects.toThrow('journal line refused'); + expect(await everything()).toEqual(before); + }); + + it('a WriteRefusal carries its code and nothing of the request', () => { + const error = new WriteRefusal('tag_not_found'); + expect(error).toBeInstanceOf(ToolRefusal); + expect(error).toMatchObject({ name: 'WriteRefusal', code: 'tag_not_found', message: 'tag_not_found', details: {} }); + }); + + // PGlite has a single connection: no test sees two transactions wait for + // each other. The locks are read in the source, each where its rule wants it. + it('taskWrites.ts takes its locks where their rules want them', () => { + const source = fs.readFileSync(path.join(__dirname, 'taskWrites.ts'), 'utf8'); + const body = (name: string) => { + const start = source.indexOf(`export async function ${name}(`); + expect(start, name).toBeGreaterThan(-1); + const end = source.indexOf('\n}\n', start); + return source.slice(start, end); + }; + const before = (text: string, first: string, then: string) => { + expect(text).toContain(first); + expect(text).toContain(then); + expect(text.indexOf(first)).toBeLessThan(text.indexOf(then)); + }; + + // The Inbox is found or created under the account lock (accountLock.ts). + expect(body('createTask')).toContain('await lockAccount(tx, userId);\n listId = await inboxId(tx, userId, now);'); + // A link is written once the task row is locked, then the tags (taskDelete.ts). + before(body('createTask'), 'await lockTaskForLinks(tx, task.id);', 'await liveTagIds(tx, userId, input.tagIds);'); + before(body('createTask'), 'await liveTagIds(tx, userId, input.tagIds);', 'tx.insert(slTaskTags)'); + before(body('setTaskTags'), 'await lockTaskForLinks(tx, own.id);', 'await liveTagIds(tx, userId, tagIds);'); + before(body('setTaskTags'), 'await liveTagIds(tx, userId, tagIds);', 'tx.delete(slTaskTags)'); + before(body('setTaskTags'), 'tx.delete(slTaskTags)', 'tx.insert(slTaskTags)'); + // The account of the task is checked before its row is locked. + before(body('setTaskTags'), 'where(ownTask(userId, taskId))', 'await lockTaskForLinks(tx, own.id);'); + // The tags are read FOR SHARE, and updateTask reads the row it locks. + expect(source).toMatch(/async function liveTagIds\([\s\S]*?\.for\('share'\);/); + expect(body('updateTask')).toContain(".where(ownTask(userId, taskId)).for('no key update');"); + expect(source.match(/\.for\('share'\)/g)).toHaveLength(1); + }); + + it('taskWrites.ts deletes nothing but tag links', () => { + const source = fs.readFileSync(path.join(__dirname, 'taskWrites.ts'), 'utf8'); + for (const name of ['createTask', 'updateTask', 'setTaskTags']) { + expect(source).toMatch(new RegExp(`^export async function ${name}\\(`, 'm')); + } + const deletes = source.match(/\.delete\([^)]*\)/g) ?? []; + expect(deletes).toEqual(['.delete(slTaskTags)']); + // No row is ever marked as deleted either. + expect(source).not.toMatch(/deletedAt\s*:/); + }); +}); diff --git a/web/src/lib/taskWrites.ts b/web/src/lib/taskWrites.ts index 08799c8..e4cf512 100644 --- a/web/src/lib/taskWrites.ts +++ b/web/src/lib/taskWrites.ts @@ -1,7 +1,9 @@ -import { and, eq, isNull, sql } from 'drizzle-orm'; -import { slTasks } from '@/db/schema'; -import { isRecurrence, nextOccurrence } from './recurrence'; -import type { Tx } from './taskDelete'; +import { and, desc, eq, inArray, isNull, sql, type SQL } from 'drizzle-orm'; +import { slLists, slTags, slTasks, slTaskTags } from '@/db/schema'; +import { lockAccount } from './accountLock'; +import { ToolRefusal, type ToolErrorCode } from './mcp/errors'; +import { isRecurrence, nextOccurrence, type Recurrence } from './recurrence'; +import { lockTaskForLinks, type Tx } from './taskDelete'; // Task writes shared by the site (PUT /api/tasks/[id]) and by the MCP tools // (#203, #204), so that both paths do the same thing (#201). @@ -14,10 +16,15 @@ import type { Tx } from './taskDelete'; // another connection in production and waits for its lock on PGlite; // - no notification: the caller notifies once, after its transaction commits; // - no import of the database client: `tx` is the only way to the database; -// - every statement filters on `userId`, and a deleted task is not a task; +// - every statement on a task, a list or a tag filters on `userId`, and a +// deleted row is not a row. A link (sl_task_tags has no account column) is +// only read, written or locked for a task that the function has just found +// in the account; // - the result is `{ changed, ... }`, or null when the row does not exist, is // deleted or belongs to another account. `changed: false` means that -// nothing was written. +// nothing was written; +// - a write that must be refused throws a WriteRefusal (#203): the caller +// lets it through, and its transaction is rolled back. export type TaskRow = typeof slTasks.$inferSelect; @@ -29,6 +36,51 @@ export type CompleteTaskResult = export type ReopenTaskResult = { changed: boolean; task: TaskRow }; +// What createTask receives. `listId` is ignored when `parentId` is given: a +// subtask lives in the list of its parent. +export type CreateTaskInput = { + title: string; + listId?: string; + parentId?: string; + notes?: string; + priority?: number; + dueDate?: Date; + recurrence?: Recurrence; + tagIds?: string[]; +}; + +export type CreateTaskResult = { changed: true; task: TaskRow }; + +// What updateTask may change. An absent key leaves its column as it is; null +// clears the notes, the due date or the recurrence. +export type UpdateTaskPatch = { + title?: string; + notes?: string | null; + priority?: number; + dueDate?: Date | null; + recurrence?: Recurrence | null; + listId?: string; +}; + +export type UpdateTaskResult = { changed: boolean; task: TaskRow }; + +export type SetTaskTagsResult = { changed: boolean; task: TaskRow }; + +// A write that is refused (#203): an id of the input names no live row of the +// account, or the write would break a rule (two levels of tasks, a subtask in +// the list of its parent). It is thrown, never returned: the transaction of +// the caller is rolled back with whatever the function wrote before it (the +// Inbox createTask created, the task whose tags are refused). It carries a +// code of mcp/errors.ts, and the envelope of the MCP tools renders it as it +// renders any ToolRefusal: an id of another account answers like an unknown +// one. +export class WriteRefusal extends ToolRefusal { + constructor(code: ToolErrorCode) { + super(code); + this.name = 'WriteRefusal'; + } +} + // PostgreSQL reads the ISO text drizzle sends for a timestamp, and that text // only holds the years up to 9999 in UTC (see `storable` in dueDate.ts): an // occurrence past it cannot be written. @@ -39,6 +91,83 @@ function ownTask(userId: string, taskId: string) { return and(eq(slTasks.id, taskId), eq(slTasks.userId, userId), isNull(slTasks.deletedAt)); } +// The live top-level tasks of a list of the account, done or not. +function topLevelOf(userId: string, listId: string) { + return and( + eq(slTasks.userId, userId), + eq(slTasks.listId, listId), + isNull(slTasks.parentId), + isNull(slTasks.deletedAt), + ); +} + +// The live subtasks of a task of the account. +function subtasksOf(userId: string, parentId: string) { + return and(eq(slTasks.userId, userId), eq(slTasks.parentId, parentId), isNull(slTasks.deletedAt)); +} + +// Where a task that joins `siblings` goes: after the last of them, as +// createTask does in the app (src/db/repository/tasks.ts). One more than the +// largest position, 1 when there is none. +async function endPosition(tx: Tx, siblings: SQL | undefined): Promise { + const [{ last }] = await tx + .select({ last: sql`coalesce(max(${slTasks.position}), 0)`.mapWith(Number) }) + .from(slTasks) + .where(siblings); + return last + 1; +} + +// The id of the live list `listId` of the account, or null. The id is the one +// the database returns: a client may write the same id in another letter +// case, which a comparison of two strings would take for another list. +async function ownListId(tx: Tx, userId: string, listId: string): Promise { + const [list] = await tx + .select({ id: slLists.id }) + .from(slLists) + .where(and(eq(slLists.id, listId), eq(slLists.userId, userId), isNull(slLists.deletedAt))); + return list?.id ?? null; +} + +// The live Inbox of the account: the most recent one, as POST /api/sync picks +// it (resolveTaskListId). An account without one gets it here: an account +// that never synced a device has no list at all. The first sync of a device +// then merges this Inbox into the one of the device, as it does for any other. +// The caller holds the account lock: two calls at once would otherwise both +// find none, and both create one. +async function inboxId(tx: Tx, userId: string, now: Date): Promise { + const [inbox] = await tx + .select({ id: slLists.id }) + .from(slLists) + .where(and(eq(slLists.userId, userId), eq(slLists.isInbox, true), isNull(slLists.deletedAt))) + .orderBy(desc(slLists.createdAt), desc(slLists.id)) + .limit(1); + if (inbox) return inbox.id; + + const [created] = await tx + .insert(slLists) + .values({ userId, name: 'Inbox', isInbox: true, createdAt: now, updatedAt: now }) + .returning({ id: slLists.id }); + return created.id; +} + +// The ids of `tagIds`, each once and as the database returns them, when every +// one names a live tag of the account; a refusal otherwise, whichever id is +// wrong. The rows are read FOR SHARE, as POST /api/tasks/[id]/tags reads +// them: a delete of one of these tags that runs at the same time waits for +// this transaction, then removes the link written here with the others of +// the tag. Called once the task row is locked (lock rule of taskDelete.ts). +async function liveTagIds(tx: Tx, userId: string, tagIds: string[]): Promise { + const wanted = [...new Set(tagIds.map((id) => id.toLowerCase()))]; + if (wanted.length === 0) return []; + const found = await tx + .select({ id: slTags.id }) + .from(slTags) + .where(and(eq(slTags.userId, userId), inArray(slTags.id, wanted), isNull(slTags.deletedAt))) + .for('share'); + if (found.length !== wanted.length) throw new WriteRefusal('tag_not_found'); + return found.map((tag) => tag.id); +} + // Complete a task and, for a recurring task with a due date, create its next // occurrence, as toggleComplete does in the app (src/db/repository/tasks.ts). // @@ -77,17 +206,8 @@ export async function completeTask( return { changed: true, task, next: null }; } - // End of the list, as createTask does in the app: one more than the largest - // position of the live top-level tasks of the list, done or not. - const [{ last }] = await tx - .select({ last: sql`coalesce(max(${slTasks.position}), 0)`.mapWith(Number) }) - .from(slTasks) - .where(and( - eq(slTasks.userId, userId), - eq(slTasks.listId, task.listId), - isNull(slTasks.parentId), - isNull(slTasks.deletedAt), - )); + // End of the list: after its live top-level tasks, done or not. + const position = await endPosition(tx, topLevelOf(userId, task.listId)); const [next] = await tx.insert(slTasks) .values({ @@ -98,7 +218,7 @@ export async function completeTask( dueDate, listId: task.listId, recurrence: task.recurrence, - position: last + 1, + position, createdAt: now, updatedAt: now, }) @@ -125,3 +245,193 @@ export async function reopenTask( const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId)); return current ? { changed: false, task: current } : null; } + +// Create a task (#203), at the end of its list or of the subtasks of its +// parent, as the app does. Where it goes: +// - with `parentId`: under that task, which must be a live task of the +// account (`parent_not_found`) and not a subtask itself +// (`parent_is_subtask`). The subtask takes the list of its parent, and +// `listId` is not even read; +// - with `listId` alone: in that list, which must be a live list of the +// account (`list_not_found`); +// - with neither: in the live Inbox of the account, created when the account +// has none. Finding or creating it happens under the account lock, which +// accountLock.ts wants as the first statement of the transaction: a caller +// that may reach this case calls createTask before any other statement. +// +// `tagIds` must all be live tags of the account (`tag_not_found`). They are +// checked after the task is inserted, because the lock rule of taskDelete.ts +// takes the task row before any tag: the refusal is thrown, and the rollback +// of the caller takes the task away, with the Inbox when one was created. +// +// Nothing holds the list or the parent between their check and the insert, +// as in the REST routes (#208): a list or a parent deleted at that very +// moment by another request still receives the task. +export async function createTask( + tx: Tx, + userId: string, + input: CreateTaskInput, + now = new Date(), +): Promise { + let listId: string; + let parentId: string | null = null; + let position: number; + + if (input.parentId !== undefined) { + const [parent] = await tx + .select({ id: slTasks.id, listId: slTasks.listId, parentId: slTasks.parentId }) + .from(slTasks) + .where(ownTask(userId, input.parentId)); + if (!parent) throw new WriteRefusal('parent_not_found'); + // Two levels at most, as the app and the site show them. + if (parent.parentId !== null) throw new WriteRefusal('parent_is_subtask'); + listId = parent.listId; + parentId = parent.id; + position = await endPosition(tx, subtasksOf(userId, parent.id)); + } else if (input.listId !== undefined) { + const list = await ownListId(tx, userId, input.listId); + if (list === null) throw new WriteRefusal('list_not_found'); + listId = list; + position = await endPosition(tx, topLevelOf(userId, list)); + } else { + await lockAccount(tx, userId); + listId = await inboxId(tx, userId, now); + position = await endPosition(tx, topLevelOf(userId, listId)); + } + + // Every column is named: nothing of the input reaches the row by itself. + const [task] = await tx.insert(slTasks) + .values({ + userId, + title: input.title, + notes: input.notes ?? null, + priority: input.priority ?? 0, + dueDate: input.dueDate ?? null, + recurrence: input.recurrence ?? null, + listId, + parentId, + position, + createdAt: now, + updatedAt: now, + }) + .returning(); + + if (input.tagIds !== undefined && input.tagIds.length > 0) { + await lockTaskForLinks(tx, task.id); + const tagIds = await liveTagIds(tx, userId, input.tagIds); + await tx.insert(slTaskTags).values(tagIds.map((tagId) => ({ taskId: task.id, tagId }))); + } + + return { changed: true, task }; +} + +// Change fields of a live task of the account (#203); null for any other +// task. Only the keys of the patch are written, and `updatedAt` moves on +// every row written. A patch that names at least one key is a write, even +// when every value is the one the row already had; a patch without a key +// writes nothing (`changed: false`). +// +// `listId` must be a live list of the account (`list_not_found`). A subtask +// stays in the list of its parent, whatever the list (`subtask_not_movable`). +// A top-level task that changes list goes to the end of the new one, and its +// live subtasks follow it in the same transaction: unlike PUT /api/tasks/[id], +// which moves the task alone and leaves its subtasks in a list that may be +// deleted later. The list the task is already in moves nothing. +// +// The task row is locked before it is read (FOR NO KEY UPDATE, the lock its +// update takes anyway): what is decided from the row (subtask or not, same +// list or not) still holds when the row is written. +export async function updateTask( + tx: Tx, + userId: string, + taskId: string, + patch: UpdateTaskPatch, + now = new Date(), +): Promise { + const [current] = await tx.select().from(slTasks).where(ownTask(userId, taskId)).for('no key update'); + if (!current) return null; + + // Every column is named: a key the patch should not carry is not written. + const fields: Partial> = {}; + if (patch.title !== undefined) fields.title = patch.title; + if (patch.notes !== undefined) fields.notes = patch.notes; + if (patch.priority !== undefined) fields.priority = patch.priority; + if (patch.dueDate !== undefined) fields.dueDate = patch.dueDate; + if (patch.recurrence !== undefined) fields.recurrence = patch.recurrence; + + let move: { listId: string; position: number } | null = null; + if (patch.listId !== undefined) { + const list = await ownListId(tx, userId, patch.listId); + if (list === null) throw new WriteRefusal('list_not_found'); + if (current.parentId !== null) throw new WriteRefusal('subtask_not_movable'); + if (list !== current.listId) { + move = { listId: list, position: await endPosition(tx, topLevelOf(userId, list)) }; + } + } else if (Object.keys(fields).length === 0) { + return { changed: false, task: current }; + } + + const [task] = await tx.update(slTasks) + .set({ ...fields, ...move, updatedAt: now }) + .where(ownTask(userId, current.id)) + .returning(); + + if (move) { + await tx.update(slTasks) + .set({ listId: move.listId, updatedAt: now }) + .where(subtasksOf(userId, current.id)); + } + + return { changed: true, task }; +} + +// Replace the tags of a live task of the account by `tagIds` (#203); null for +// any other task. Every id must be a live tag of the account +// (`tag_not_found`, nothing written). The set the task already has, in any +// order, writes nothing (`changed: false`); otherwise the links that are not +// wanted are removed, the missing ones are added, and `updatedAt` of the task +// moves, so that GET /api/sync sends the task again with its links (#180). +// +// Every link of the task counts, whatever its tag: a link left on a deleted +// tag or on a tag of another account (rows the routes no longer write) is not +// in `tagIds`, and goes with the others. +// +// The task row is locked first, before any tag (lock rule of taskDelete.ts). +// The account is checked before the lock: a row of another account is never +// locked. +export async function setTaskTags( + tx: Tx, + userId: string, + taskId: string, + tagIds: string[], + now = new Date(), +): Promise { + const [own] = await tx.select({ id: slTasks.id }).from(slTasks).where(ownTask(userId, taskId)); + if (!own) return null; + const locked = await lockTaskForLinks(tx, own.id); + // Deleted between the check and the lock. + if (!locked || locked.deletedAt) return null; + + const wanted = await liveTagIds(tx, userId, tagIds); + const links = await tx.select({ tagId: slTaskTags.tagId }).from(slTaskTags).where(eq(slTaskTags.taskId, own.id)); + const linked = links.map((link) => link.tagId); + const removed = linked.filter((id) => !wanted.includes(id)); + const added = wanted.filter((id) => !linked.includes(id)); + + if (removed.length === 0 && added.length === 0) { + const [task] = await tx.select().from(slTasks).where(ownTask(userId, own.id)); + return { changed: false, task }; + } + + if (removed.length > 0) { + await tx.delete(slTaskTags).where(and(eq(slTaskTags.taskId, own.id), inArray(slTaskTags.tagId, removed))); + } + if (added.length > 0) { + await tx.insert(slTaskTags).values(added.map((tagId) => ({ taskId: own.id, tagId }))); + } + const [task] = await tx.update(slTasks) + .set({ updatedAt: now }) + .where(ownTask(userId, own.id)) + .returning(); + return { changed: true, task }; +}