diff --git a/REVIEW.md b/REVIEW.md index 752efc6..498db2a 100644 --- a/REVIEW.md +++ b/REVIEW.md @@ -27,7 +27,7 @@ Motifs : chemins depuis la racine. `*` ne traverse jamais un `/` ; `**/` vaut z | Motif | Condition | Zone | |---|---|---| | `src/lib/{authToken,logtoConfig,validation}.ts`, `web/src/lib/{auth,logto,api,agentTokens,agentAccess,origin}.ts`, `web/src/middleware.ts`, `web/src/app/api/logto/**`, `web/src/app/auth/**` | toujours | Authentification | -| `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts`, `web/src/lib/mcp/**`, `web/server.ts` | toujours | API et isolation des comptes | +| `web/src/app/api/**`, `web/src/lib/{validators,syncData,rateLimit,ws,idempotency,taskWrites,agentJournal}.ts`, `web/src/lib/mcp/**`, `web/server.ts` | toujours | API et isolation des comptes | | `src/services/{syncClient,syncRules,syncSchedule,syncTrigger,syncSocket,syncSocketClient}.ts`, `src/db/repository/outbox.ts` | toujours | Sync | | `src/db/{schema,client}.ts`, `src/db/migrations/**`, `web/src/db/{schema,client,seed}.ts`, `web/src/db/migrations/**`, `drizzle.config.ts`, `web/drizzle.config.ts`, `sql-transformer.js` | toujours | Migrations et données | | `app/_layout.tsx` | le diff touche les migrations (`useMigrations`), `LogtoProvider`, le jeton (`setTokenGetter`) ou les appels de sync (`fullSync`, `cleanOutbox`, `scheduleSync`, `setSyncSubscriber`) | Migrations et données, Authentification, Sync | @@ -112,6 +112,10 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Tableaux d'un schéma d'outil MCP : chacun porte un `.max()`, et le serveur est construit avec `maxToolInputElements: 64`, qui compte les éléments de tableau et les clés d'objet des arguments d'un appel, à toute profondeur, avant que le schéma soit lu (le SDK ne pose aucune limite par défaut ; l'avis GHSA-46jr-4wx8-v453 demande de la poser et d'abaisser `maxRequestBodySize`). `.max()` seul ne borne pas un tableau hostile, parce que zod valide chaque élément avant la longueur. La forme `z.array(z.unknown()).max(n).pipe(…)` des routes ne sert pas ici : elle retirerait le type des éléments du schéma JSON que le modèle lit. Le plus gros appel légitime compte moins de 30 éléments : un outil qui en demande davantage relève la borne dans sa PR, avec son compte. Les schémas d'entrée sont `.strict()` : une clé inconnue est refusée. — `web/src/lib/mcp/server.ts`, `web/src/lib/mcp/readTools.ts`, `web/src/app/api/mcp/route.test.ts`, #202 - Tout outil MCP se déclare par `register()` de `server.ts`, qui le place dans l'enveloppe commune ; aucun outil ne s'enregistre directement auprès du SDK, qui rendrait au modèle le message d'une exception (une erreur de drizzle porte la requête SQL et ses paramètres, dont le `sub`). Un refus voulu est une `ToolRefusal`, qui porte un code de `errors.ts` : le modèle lit `{ "error": "", "message": "" }` dans un résultat `isError`, jamais une erreur JSON-RPC, et un message ne cite ni la requête ni la base. Toute autre exception devient `internal_error`, et le journal n'en garde que le nom de classe. Un succès rend `structuredContent` et le même objet en texte JSON, mis en forme par `shape.ts`, qui nomme chaque colonne : `user_id` et `deleted_at` n'y figurent jamais, et une colonne ajoutée à une table n'atteint un modèle que si elle y est nommée. Une ligne supprimée et une ligne d'un autre compte répondent comme une ligne inconnue (`not_found`, `list_not_found`). — `web/src/lib/mcp/server.ts`, `web/src/lib/mcp/errors.ts`, `web/src/lib/mcp/shape.ts`, `web/src/lib/mcp/readTools.ts`, `web/src/app/api/mcp/route.test.ts`, #202 - Lectures de compte des outils MCP : `readTools.ts` ne lance aucune requête à lui, il met en forme ce que rendent `queryAccountTasks`, `loadAccountTask`, `loadAccountLists`, `loadOpenTaskCounts`, `loadSubtasks`, `loadTaskTags` et `loadAccountTags`. `queryAccountTasks` et `loadAccountTask` filtrent une tâche deux fois sur le compte, par `sl_tasks.user_id` et par sa liste, qui doit être une liste active du compte ; les tests écrivent les lignes que la sync n'écrit jamais (une tâche d'un compte dans la liste d'un autre), pour que chaque filtre tombe seul sous sa mutation. `list_tasks` suit un ordre total, l'instant de création coupé à la milliseconde puis l'identifiant, et son curseur porte cette clé : `created_at` garde des microsecondes en base et une `Date` de JavaScript des millisecondes, un curseur comparé à la colonne brute rendrait deux fois la même ligne. Les bornes `due_before` et `due_after` sont incluses et passent par `dueDateSchema` (une date seule vaut 12:00 UTC) ; les filtres portent sur les tâches de premier niveau. — `web/src/lib/taskQueries.ts`, `web/src/lib/taskQueries.test.ts`, `web/src/lib/mcp/readTools.ts`, #202 +- Écritures des outils MCP : les cinq outils d'écriture (`create_task`, `update_task`, `complete_task`, `reopen_task`, `set_task_tags`) ne sont enregistrés que pour un jeton « Lecture et écriture », et aucun ne supprime une tâche, une liste ni une étiquette (décision de Max du 2026-11-14) : `writeTools.ts` ne contient aucun `.delete(`, et le seul `delete` de `taskWrites.ts` porte sur `sl_task_tags`. Chacun se déclare par `registerWriteTool`, l'enveloppe unique des écritures, placée dans celle de tous les outils (`register`, limite `mcp-write`) : une transaction, l'appel d'une fonction de `taskWrites.ts`, puis, si elle a écrit (`changed`), la ligne de journal dans cette même transaction (`recordAction`) ; après le commit seulement, un seul `notifyUserChanged`, puis la réponse, relue par `renderTask`. Une insertion de journal qui échoue annule l'écriture : c'est le cas d'un jeton révoqué pendant sa requête, dont la ligne que vise `token_id` n'existe plus (`23503`) ; l'outil répond alors `internal_error`, et l'appel suivant reçoit 401. Un appel sans effet (`complete_task` rejoué, `reopen_task` sur une tâche ouverte, `set_task_tags` avec l'ensemble déjà en place) n'écrit ni ligne de journal ni avis ; `update_task` compte comme une écriture dès qu'il reçoit un champ, même identique, et son schéma refuse un appel sans champ. Si la relecture échoue après le commit, l'outil répond `internal_error` pour une écriture gardée, que sa ligne de journal montre. Un outil d'écriture ajouté passe par `registerWriteTool` et ajoute son nom à `WRITE_TOOL_NAMES`, que le journal affiche. — `web/src/lib/mcp/writeTools.ts`, `web/src/lib/mcp/server.ts`, `web/src/lib/taskWrites.ts`, `web/src/app/api/mcp/route.test.ts`, `DECISIONS.md` « Assistants IA (MCP) », #203 +- Références des outils d'écriture : `task_id`, `list_id`, `parent_id` et `tag_ids` sont vérifiés contre le compte du jeton dans la transaction de l'écriture, par les fonctions de `taskWrites.ts` (`createTask`, `updateTask`, `setTaskTags`, `completeTask`, `reopenTask`), dont chaque requête sur une tâche, une liste ou une étiquette filtre sur `userId` et écarte les lignes supprimées. Une ligne d'un autre compte répond comme une ligne absente : `null` pour la tâche (`not_found`), et pour le reste une `WriteRefusal` (`list_not_found`, `parent_not_found`, `tag_not_found`), qui hérite de `ToolRefusal` pour que l'enveloppe la rende, et qui annule la transaction avec ce que la fonction avait déjà écrit (l'Inbox créée, la tâche dont les étiquettes sont refusées). Chacun de ces quatre contrôles a ses tests, qui tombent quand on retire son filtre sur le compte ; la preuve d'un refus compare toutes les lignes des deux comptes avant et après. Un identifiant comparé en JavaScript est celui que la base rend, jamais celui de l'appel : le même identifiant en majuscules désigne la même ligne. Un compte sans Inbox active en reçoit une à sa première création sans liste (`name: 'Inbox'`), sous `lockAccount`, première instruction de la transaction ; `POST /api/sync` ne prend pas ce verrou, et la première sync d'un appareil qui croiserait cette création laisserait deux Inbox actives, que la prochaine Inbox créée par la sync absorbe. `updateTask` verrouille la ligne de la tâche avant de la lire ; aucun verrou ne tient la liste ni le parent entre leur contrôle et l'écriture, comme dans les routes REST (#208). — `web/src/lib/taskWrites.ts`, `web/src/lib/taskWrites.test.ts`, `web/src/lib/accountLock.ts`, `web/src/app/api/mcp/route.test.ts`, #203 +- Écarts voulus entre l'API REST et les outils MCP, à ne pas rapprocher dans une revue (le spec exclut la refonte des routes REST, décisions de planification du 2026-11-14) : `update_task` déplace une tâche avec ses sous-tâches actives, là où `PUT /api/tasks/[id]` ne déplace que la tâche ; une tâche créée ou déplacée par un outil va en fin de liste (la plus grande position des tâches actives de même rang, plus un, comme dans l'app), là où `POST /api/tasks` laisse la position à 0 ; un outil refuse de changer la liste d'une sous-tâche (`subtask_not_movable`), ce que le `PUT` accepte ; `create_task` sans liste va dans l'Inbox, alors que `POST /api/tasks` exige `listId`, et avec `parent_id` il ignore `list_id` ; `update_task` ne prend ni `completed`, ni `parent_id`, ni `position`. Les deux chemins partagent `completeTask` et `reopenTask`. — `web/src/lib/taskWrites.ts`, `web/src/lib/mcp/writeTools.ts`, `web/src/app/api/tasks/route.ts`, `web/src/app/api/tasks/[id]/route.ts`, #203 +- Journal des assistants : `sl_agent_actions` garde une ligne par écriture réussie d'un outil (l'outil, le type et l'identifiant de la ligne touchée, le jeton et son nom au moment de l'appel), jamais un titre ni un contenu, pendant 90 jours comptés depuis l'instant de l'écriture (90 fois 24 heures, sans jour civil : aucun fuseau en jeu). `listActions` ne rend que les lignes du compte de moins de 90 jours, purgées ou non, de la plus récente à la plus ancienne, par pages de 100 au plus, avec un curseur sur l'instant coupé à la milliseconde puis l'identifiant ; le nom affiché est lu sur la ligne active du compte (tâche, liste ou étiquette), nul si elle est supprimée, absente ou d'un autre compte, et `tokenRevoked` signale un `token_id` nul. `purgeOldActions` supprime les lignes plus vieilles, tous comptes confondus. `web/server.ts` lance la purge après les migrations et hors de leur bloc `try`, sans l'attendre, puis toutes les 24 heures (`setInterval(…).unref()` : un intervalle depuis le démarrage, pas une heure du jour), sur un `Pool` à elle (`max: 1`, avec son écouteur d'erreur) et par `safePurge`, qui attrape tout et ne journalise que le nom de classe de l'erreur : une purge en échec n'arrête jamais le serveur. `agentJournal.ts` n'importe pas `@/db/client` et garde des imports relatifs, parce que `server.ts` l'embarque dans son bundle, à part des routes : chaque fonction reçoit la base sur laquelle elle tourne. `server.ts` échappe à vitest et à `next build` : son câblage se prouve par la commande esbuild de `web/Dockerfile`, rejouée par la revue, et par le test qui relit sa source. — `web/src/lib/agentJournal.ts`, `web/src/lib/agentJournal.test.ts`, `web/server.ts`, `web/Dockerfile`, `web/scripts/probe.sql` (contrôle `journal_plus_de_90_jours`), `DECISIONS.md` « Assistants IA (MCP) », #199, #203 - WebSocket : ticket à usage unique de 30 s, origines autorisées listées (`origin.ts`, liste partagée avec les routes, voir « Authentification »), revalidation toutes les 15 min ; aucun paramètre de requête de `/ws` n'est journalisé. — `web/src/lib/ws.ts`, `web/src/lib/origin.ts`, `web/src/app/api/ws-ticket/route.ts`, `web/server.ts` - Une route de diagnostic (`/api/debug`) ne renvoie que les données de la session qui l'appelle, jamais de secret ni de valeur de cookie. — `web/src/app/api/debug/route.ts` @@ -121,7 +125,8 @@ Chaque règle cite sa source. Elles valent quel que soit le niveau : une PR norm - Les formes de données sont croisées : le client pousse en camelCase (`listId`, `dueDate`), le serveur renvoie en snake_case (`list_id`, `due_date`). Un champ ajouté l'est des deux côtés, avec la conversion des dates. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts` - L'Inbox locale a l'identifiant fixe `00000000-0000-0000-0000-000000000001`, remappé vers un UUID serveur à la première sync (`initialMerge`). Une Inbox créée par la sync absorbe toutes les autres Inbox actives du compte (tâches déplacées, Inbox archivées), et elle est insérée avant le déplacement, car la clé étrangère `sl_tasks.list_id` n'est pas différable. Un id déjà présent dans le compte ne fusionne rien. Une seule Inbox est créée par POST, la suivante revient `skipped`. Une tâche envoyée vers une Inbox archivée, à la création comme à la mise à jour, va dans l'Inbox active. — `src/services/syncClient.ts`, `web/src/app/api/sync/route.ts`, PR #58, #64, #145, `web/src/db/migrations/0002_cleanup_duplicate_inboxes.sql` - `task create` écrit `completed` et `completedAt` ; une tâche terminée sans date reçoit la date du serveur, une tâche non terminée n'a pas de date (#146). — `web/src/lib/syncData.ts`, `web/src/app/api/sync/route.ts` -- L'occurrence suivante d'une tâche récurrente est créée par celui qui la coche, une seule fois : l'app pour ses propres complétions (`toggleComplete`, qui la pousse ensuite par la sync), et `completeTask` pour le site (`PUT /api/tasks/[id]`) et pour les outils MCP, qui l'appelleront (#203). Jamais `POST /api/sync` : un `task update` ou un `task create` terminé n'y crée aucune occurrence, sinon chaque complétion faite sur le téléphone en créerait deux. `completeTask` ne la crée que si son `UPDATE … WHERE completed = false … RETURNING` rend la ligne : un rejeu n'en crée pas une seconde, et deux requêtes simultanées n'en créent qu'une (la seconde attend la première, ce qu'aucun test PGlite ne voit, faute d'une seconde connexion). Elle est créée pour une tâche qui a une échéance et une récurrence de `RECURRENCES` : mêmes titre, notes, priorité, liste et récurrence, sans étiquettes ni parent, à l'échéance de la tâche plus une période, en fin de liste ; `reopenTask` la laisse en place. Le serveur calcule en UTC (`nextOccurrence`) et l'app en heure locale : à un changement d'heure, l'heure locale d'une occurrence créée par le serveur glisse d'une heure, et en fin de mois une échéance posée le soir au Québec, déjà le lendemain en UTC, peut donner un jour d'écart avec l'app ; les deux codes rendent les mêmes instants sous `TZ=UTC`, ce que vérifie `web/src/test/sync/recurrence.test.ts`. Contrat de `taskWrites.ts`, pour toutes ses fonctions : la transaction de l'appelant en premier argument, puis `userId` ; aucune transaction ouverte, aucune notification, aucun import de `@/db/client` ; `{ changed, … }`, ou `null` pour une ligne absente, supprimée ou d'un autre compte. L'appelant notifie une fois, après le commit. — `web/src/lib/taskWrites.ts`, `web/src/lib/recurrence.ts`, `web/src/app/api/tasks/[id]/route.ts`, `src/db/repository/tasks.ts`, `web/src/app/api/tasks/route.test.ts`, `web/src/app/api/sync/route.test.ts`, #201 +- L'occurrence suivante d'une tâche récurrente est créée par celui qui la coche, une seule fois : l'app pour ses propres complétions (`toggleComplete`, qui la pousse ensuite par la sync), et `completeTask` pour le site (`PUT /api/tasks/[id]`) et pour l'outil MCP `complete_task` (#203). Jamais `POST /api/sync` : un `task update` ou un `task create` terminé n'y crée aucune occurrence, sinon chaque complétion faite sur le téléphone en créerait deux. `completeTask` ne la crée que si son `UPDATE … WHERE completed = false … RETURNING` rend la ligne : un rejeu n'en crée pas une seconde, et deux requêtes simultanées n'en créent qu'une (la seconde attend la première, ce qu'aucun test PGlite ne voit, faute d'une seconde connexion). Elle est créée pour une tâche qui a une échéance et une récurrence de `RECURRENCES` : mêmes titre, notes, priorité, liste et récurrence, sans étiquettes ni parent, à l'échéance de la tâche plus une période, en fin de liste ; `reopenTask` la laisse en place. Le serveur calcule en UTC (`nextOccurrence`) et l'app en heure locale : à un changement d'heure, l'heure locale d'une occurrence créée par le serveur glisse d'une heure, et en fin de mois une échéance posée le soir au Québec, déjà le lendemain en UTC, peut donner un jour d'écart avec l'app ; les deux codes rendent les mêmes instants sous `TZ=UTC`, ce que vérifie `web/src/test/sync/recurrence.test.ts`. Contrat de `taskWrites.ts`, pour toutes ses fonctions : la transaction de l'appelant en premier argument, puis `userId` ; aucune transaction ouverte, aucune notification, aucun import de `@/db/client` ; `{ changed, … }`, ou `null` pour une ligne absente, supprimée ou d'un autre compte. L'appelant notifie une fois, après le commit. — `web/src/lib/taskWrites.ts`, `web/src/lib/recurrence.ts`, `web/src/app/api/tasks/[id]/route.ts`, `src/db/repository/tasks.ts`, `web/src/app/api/tasks/route.test.ts`, `web/src/app/api/sync/route.test.ts`, #201 +- Un outil d'écriture MCP écrit comme une route : chaque ligne qu'il touche avance son `updatedAt` (la tâche créée, modifiée, cochée ou décochée ; chaque sous-tâche active déplacée avec sa tâche ; la tâche dont les étiquettes changent, pour que `GET /api/sync` la renvoie avec ses liens ; l'Inbox créée pour un compte qui n'en a pas), et l'outil envoie un seul `notifyUserChanged` après le commit, que l'app ouverte reçoit par le WebSocket. Un appel sans effet n'avance rien et n'envoie rien. Les liens d'étiquettes écrits par un outil suivent la règle de verrou de `taskDelete.ts` : la ligne de la tâche d'abord (`lockTaskForLinks`), puis les étiquettes, lues en `FOR SHARE` pour qu'une suppression simultanée attende et retire le lien avec les autres. L'Inbox créée par un outil est une Inbox comme une autre : la première sync d'un appareil la fusionne dans la sienne. — `web/src/lib/taskWrites.ts`, `web/src/lib/mcp/writeTools.ts`, `web/src/lib/taskDelete.ts`, `web/src/app/api/mcp/route.test.ts`, #203 - `initialReset` efface toutes les données locales avant de tirer celles du serveur : un appel ajouté se justifie, et il reste derrière une confirmation de l'utilisateur. — `src/services/syncClient.ts`, `app/(tabs)/settings.tsx` - Pas de fusion entre comptes : `dataOwnerId` (store de réglages, persisté, gardé à la déconnexion) nomme le compte des données locales ; un appareil qui porte les données d'un autre compte n'offre que « Charger ce compte » (`initialReset`) ou « Annuler » (déconnexion sans toucher aux données), règle `firstSyncChoice`. La sync reste éteinte jusqu'à la réussite de `initialMerge` / `initialReset` (un seul `setSyncEnabled(true)`, dans `runFirstSync`), et le planificateur refuse toute sync tant que `dataOwnerId` diffère du compte connecté (`canSync`) : sinon l'outbox de l'ancien compte part sous le nouveau. La déconnexion envoie d'abord l'outbox (`pushBeforeSignOut`, 10 s, état « sync initiale », une requête réservée hors budget). — `src/services/syncRules.ts`, `src/services/syncSchedule.ts`, `src/services/syncClient.ts`, `app/(tabs)/settings.tsx`, `tests/smoke.test.cjs`, #165 - Une suppression côté serveur est un soft-delete (`deletedAt`), relayé à l'app par le pull. — `web/src/app/api/sync/route.ts` diff --git a/scripts/review-levels.py b/scripts/review-levels.py index 04b1122..15dd72b 100755 --- a/scripts/review-levels.py +++ b/scripts/review-levels.py @@ -45,7 +45,7 @@ HIGH_ALWAYS = [ "src/lib/{authToken,logtoConfig,validation}.ts", "web/src/lib/{auth,logto,api,agentTokens,agentAccess,origin}.ts", "web/src/middleware.ts", "web/src/app/api/logto/**", "web/src/app/auth/**", - "web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency}.ts", "web/src/lib/mcp/**", "web/server.ts", + "web/src/app/api/**", "web/src/lib/{validators,syncData,rateLimit,ws,idempotency,taskWrites,agentJournal}.ts", "web/src/lib/mcp/**", "web/server.ts", "src/services/{syncClient,syncRules,syncSchedule,syncTrigger,syncSocket,syncSocketClient}.ts", "src/db/repository/outbox.ts", "src/db/{schema,client}.ts", "src/db/migrations/**", "web/src/db/{schema,client,seed}.ts", "web/src/db/migrations/**", diff --git a/web/server.ts b/web/server.ts index 20de806..2599d27 100644 --- a/web/server.ts +++ b/web/server.ts @@ -4,11 +4,18 @@ import { Pool } from 'pg'; import { drizzle } from 'drizzle-orm/node-postgres'; import { migrate } from 'drizzle-orm/node-postgres/migrator'; import { setupWebSocket } from './src/lib/ws'; +import { purgeOldActions, safePurge } from './src/lib/agentJournal'; +import { errorName } from './src/lib/mcp/errors'; const dev = process.env.NODE_ENV !== 'production'; const hostname = process.env.HOSTNAME || '0.0.0.0'; const port = parseInt(process.env.PORT || '3000', 10); +// The journal of the AI assistants is kept 90 days (src/lib/agentJournal.ts): +// the older lines are deleted when the server starts, then every 24 hours. An +// interval, not a time of day: no time zone is involved. +const JOURNAL_PURGE_INTERVAL_MS = 24 * 60 * 60 * 1000; + async function runMigrations() { const pool = new Pool({ connectionString: process.env.DATABASE_URL }); const db = drizzle(pool); @@ -20,6 +27,24 @@ async function runMigrations() { } } +// Purge of the journal (#203). It has a pool of its own, of one connection: +// the pool of the migrations is closed when they end, and this file is +// bundled apart from the routes (Dockerfile), whose pool it cannot reach. +// Nothing here may stop the server: safePurge catches whatever a purge throws +// and logs the class name of the error, the first purge is not awaited, and +// the timer does not keep the process alive. +function startJournalPurge() { + const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 1 }); + // Without a listener, the error of an idle connection (the database + // restarts between two purges) is an uncaught exception. + pool.on('error', (error) => { + console.log(`> Journal purge pool error: ${errorName(error)}`); + }); + const purge = () => safePurge(() => purgeOldActions(drizzle(pool))); + void purge(); + setInterval(purge, JOURNAL_PURGE_INTERVAL_MS).unref(); +} + const app = next({ dev, hostname, port }); const handle = app.getRequestHandler(); @@ -31,6 +56,10 @@ const handle = app.getRequestHandler(); process.exit(1); } + // After the migrations, which create the table, and outside their try + // block: a purge that fails is not a migration error. + startJournalPurge(); + await app.prepare(); const server = createServer((req, res) => { diff --git a/web/src/app/api/mcp/route.test.ts b/web/src/app/api/mcp/route.test.ts index a3c90fe..4f482d6 100644 --- a/web/src/app/api/mcp/route.test.ts +++ b/web/src/app/api/mcp/route.test.ts @@ -9,10 +9,13 @@ import type { PGlite } from 'electric-sql-pglite'; // verification, the real pilot, the real rate limiter and the real queries, // against an in-memory Postgres (PGlite) with the companion migrations. // Requests are JSON-RPC messages written by hand, in both generations of the -// protocol: no MCP client is installed. Two modules are replaced: -// - the database client, by PGlite; +// protocol: no MCP client is installed. Three modules are replaced: +// - the database client, by PGlite, which also counts the transactions +// opened through db.transaction and those still open (#203); // - the Logto session helper (vitest cannot load @logto/next), which gives -// the session a test sets and counts how often it is asked. +// the session a test sets and counts how often it is asked; +// - the WebSocket notice, which is recorded with whether every transaction +// had settled when it left (#203). // Every request is sent to the container's host, as in production. const h = await vi.hoisted(async () => { @@ -21,13 +24,31 @@ const h = await vi.hoisted(async () => { pg: new PGlite() as PGlite, session: null as { userId: string } | null, sessionReads: 0, + // Transactions opened through db.transaction: all of them, and those + // that have not settled yet. + transactions: 0, + openTransactions: 0, + // WebSocket notices, in order: the account, and whether the notice left + // after the commit. + notified: [] as { userId: string; afterCommit: boolean }[], }; }); 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 = drizzle(h.pg, { schema }); + const transaction = db.transaction.bind(db); + db.transaction = (async (...args: Parameters) => { + h.transactions++; + h.openTransactions++; + try { + return await transaction(...args); + } finally { + h.openTransactions--; + } + }) as typeof db.transaction; + return { db }; }); vi.mock('@/lib/auth', () => ({ @@ -37,6 +58,12 @@ vi.mock('@/lib/auth', () => ({ }, })); +vi.mock('@/lib/ws', () => ({ + notifyUserChanged: (userId: string) => { + h.notified.push({ userId, afterCommit: h.openTransactions === 0 }); + }, +})); + const route = await import('./route'); const { POST } = route; const { createAgentToken, revokeAgentToken } = await import('@/lib/agentTokens'); @@ -44,6 +71,9 @@ const { rateLimit, rateLimitDelay } = await import('@/lib/rateLimit'); const { loadAccountTags } = await import('@/lib/taskQueries'); const { TOOL_ERROR_MESSAGES, errorName } = await import('@/lib/mcp/errors'); const { instructionsFor, mcpHandler } = await import('@/lib/mcp/server'); +const { WRITE_TOOL_NAMES } = await import('@/lib/mcp/writeTools'); +const { listActions } = await import('@/lib/agentJournal'); +const { db } = await import('@/db/client'); const SITE = 'https://liste.lacompagniemaximus.com'; // Origin of `request.url` in production: the container's, not the site's. @@ -56,7 +86,13 @@ const ENVELOPE = { }; const ERAS = ['modern', 'legacy'] as const; const READ_TOOLS = ['get_task', 'list_lists', 'list_tags', 'list_tasks']; +const WRITE_TOOLS = ['complete_task', 'create_task', 'reopen_task', 'set_task_tags', 'update_task']; const READ_ONLY = { readOnlyHint: true, openWorldHint: false }; +// Keys of a top-level task as a tool returns it, in order. +const TASK_KEYS = [ + 'id', 'title', 'notes', 'completed', 'completed_at', 'priority', 'due_date', 'recurrence', + 'list_id', 'parent_id', 'created_at', 'updated_at', 'tags', 'subtasks', +]; const UNAUTHORIZED = { status: 401, message: { error: 'unauthorized' } }; const FORBIDDEN = { status: 403, message: { error: 'forbidden' } }; const GONE = '2026-02-01T00:00:00.000Z'; @@ -227,6 +263,61 @@ async function connected(scope: 'read' | 'write' = 'read'): Promise { + const account = { userId: `user-${u()}`, inbox: '' }; + seen.users.push(account.userId); + return { ...account, ...(await newToken(account, { scope: 'write' })) }; +} + +// Columns of sl_tasks the write tests read, as PGlite returns a row. +type StoredTask = { + id: string; user_id: string; title: string; list_id: string; parent_id: string | null; position: number; + completed: boolean; updated_at: Date; deleted_at: Date | null; +}; + +async function stored(id: string): Promise { + return (await h.pg.query('SELECT * FROM sl_tasks WHERE id = $1', [id])).rows[0]; +} + +type JournalLine = { tool: string; entity_type: string; entity_id: string; token_id: string | null; token_name: string }; + +// The journal lines of an account, oldest first. +async function journal(userId: string): Promise { + return (await h.pg.query( + 'SELECT tool, entity_type, entity_id, token_id, token_name FROM sl_agent_actions WHERE user_id = $1 ORDER BY created_at, id', + [userId], + )).rows; +} + +// The journal line a write tool leaves for a task, written with this token. +function lineOf(tool: string, taskId: string, token: Token): JournalLine { + return { tool, entity_type: 'task', entity_id: taskId, token_id: token.id, token_name: 'Assistant' }; +} + +// The WebSocket notices sent to an account, in order: true for a notice that +// left after the commit, false for one sent while a transaction was open. +function notices(userId: string): boolean[] { + return h.notified.filter((notice) => notice.userId === userId).map((notice) => notice.afterCommit); +} + +// Every row of the accounts, every column: lists, tasks, tags, links and +// journal lines. What a refused write must leave exactly as it was. +async function state(...accounts: Account[]) { + const users = accounts.map((account) => account.userId); + const marks = users.map((_, i) => `$${i + 1}`).join(', '); + const read = async (sql: string) => (await h.pg.query(sql, users)).rows; + return { + lists: await read(`SELECT * FROM sl_lists WHERE user_id IN (${marks}) ORDER BY id`), + tasks: await read(`SELECT * FROM sl_tasks WHERE user_id IN (${marks}) ORDER BY id`), + tags: await read(`SELECT * FROM sl_tags WHERE user_id IN (${marks}) ORDER BY id`), + links: await read( + `SELECT tt.* FROM sl_task_tags tt JOIN sl_tasks t ON t.id = tt.task_id WHERE t.user_id IN (${marks}) ORDER BY tt.task_id, tt.tag_id`, + ), + journal: await read(`SELECT * FROM sl_agent_actions WHERE user_id IN (${marks}) ORDER BY id`), + }; +} + async function answer(res: Response): Promise { const text = await res.text(); let messages: Json[] = []; @@ -438,6 +529,7 @@ beforeEach(() => { pilot('*'); h.session = null; h.sessionReads = 0; + h.notified = []; seen.users = []; seen.tokens = []; seen.content = []; @@ -803,6 +895,698 @@ describe('the tools of a token', () => { const a = await connected('write'); expect((await listTools(a.token)).map((tool) => tool.name)).toEqual(expect.arrayContaining(READ_TOOLS)); }); + + it('a read-write token sees the five write tools as well, the same in both generations', async () => { + const a = await connected('write'); + const [modern, legacy] = [await listTools(a.token), await listTools(a.token, { era: 'legacy' })]; + expect(legacy).toEqual(modern); + expect(modern.map((tool) => tool.name).sort()).toEqual([...READ_TOOLS, ...WRITE_TOOLS].sort()); + // The names the journal holds are the names of the write tools, all of them. + expect([...WRITE_TOOL_NAMES].sort()).toEqual(WRITE_TOOLS); + + const byName = Object.fromEntries(modern.map((tool) => [tool.name, tool])); + // Additive, or overwriting a value; calling again with the same arguments changes nothing more. + expect(byName.create_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, openWorldHint: false }); + expect(byName.update_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }); + expect(byName.complete_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }); + expect(byName.reopen_task.annotations).toEqual({ readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }); + expect(byName.set_task_tags.annotations).toEqual({ readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false }); + for (const name of READ_TOOLS) expect(byName[name].annotations).toEqual(READ_ONLY); + + const inputs = Object.fromEntries(WRITE_TOOLS.map((name) => [name, byName[name].inputSchema as { properties: Json; required?: string[] }])); + for (const name of WRITE_TOOLS) { + expect(byName[name].description.length).toBeGreaterThan(20); + // Strict input: an unknown key is refused. + expect(inputs[name]).toMatchObject({ type: 'object', additionalProperties: false }); + expect(byName[name]).not.toHaveProperty('outputSchema'); + } + expect(Object.keys(inputs.create_task.properties).sort()).toEqual( + ['due_date', 'list_id', 'notes', 'parent_id', 'priority', 'recurrence', 'tag_ids', 'title'], + ); + expect(inputs.create_task.required).toEqual(['title']); + expect(inputs.create_task.properties).toMatchObject({ + title: { type: 'string', minLength: 1, maxLength: 500 }, + notes: { type: 'string', maxLength: 5000 }, + priority: { type: 'integer', minimum: 0, maximum: 3 }, + recurrence: { enum: ['daily', 'weekly', 'monthly', 'yearly'] }, + tag_ids: { type: 'array', maxItems: 20 }, + }); + expect(Object.keys(inputs.update_task.properties).sort()).toEqual( + ['due_date', 'list_id', 'notes', 'priority', 'recurrence', 'task_id', 'title'], + ); + expect(inputs.update_task.required).toEqual(['task_id']); + for (const name of ['complete_task', 'reopen_task']) { + expect(Object.keys(inputs[name].properties)).toEqual(['task_id']); + expect(inputs[name].required).toEqual(['task_id']); + } + expect(Object.keys(inputs.set_task_tags.properties).sort()).toEqual(['tag_ids', 'task_id']); + expect(inputs.set_task_tags.required?.sort()).toEqual(['tag_ids', 'task_id']); + expect(inputs.set_task_tags.properties).toMatchObject({ tag_ids: { type: 'array', maxItems: 20 } }); + // No tool takes an account, and none deletes. + const text = JSON.stringify(modern); + expect(text).not.toMatch(/user_id|userId/); + expect(modern.map((tool) => tool.name).filter((name) => /delete|remove/.test(name))).toEqual([]); + }); +}); + +// A tool call sent straight to the handler, with the context the route would +// have written for a token: what a request looks like once it is +// authenticated, whatever became of its token since. +async function handled( + extra: { userId: string; scope: 'read' | 'write'; tokenId: string | null; tokenName: string }, + name: string, + args: Json, +): Promise<{ isError: boolean; data: Json }> { + const request = new Request(`${CONTAINER}/api/mcp`, { + method: 'POST', + headers: { 'content-type': 'application/json', 'mcp-protocol-version': MODERN, 'mcp-method': 'tools/call', 'mcp-name': name }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args, _meta: ENVELOPE } }), + }); + const served = await answer(await mcpHandler.fetch(request, { + authInfo: { token: '', clientId: extra.tokenId ?? '', scopes: [extra.scope], extra }, + })); + const result = resultOf(served) as { content: { text: string }[]; isError?: boolean }; + return { isError: result.isError === true, data: JSON.parse(result.content[0].text) as Json }; +} + +describe('create_task', () => { + it.each(ERAS)('creates a task at the end of the Inbox, returns it, journals it and notifies once, after the commit (%s)', async (era) => { + const a = await connected('write'); + await newTask(a, { position: 3 }); + const title = words('title'); + + const created = await ok(a.token, 'create_task', { title }, { era }); + expect(Object.keys(created)).toEqual(['task']); + const task = created.task as ShapedTask; + expect(Object.keys(task)).toEqual(TASK_KEYS); + expect(task).toMatchObject({ + title, notes: null, completed: false, completed_at: null, priority: 0, due_date: null, recurrence: null, + list_id: a.inbox, parent_id: null, tags: [], subtasks: [], + }); + expect(task.created_at).toBe(task.updated_at); + expect(await stored(task.id)).toMatchObject({ user_id: a.userId, title, list_id: a.inbox, parent_id: null, position: 4, deleted_at: null }); + + expect(await journal(a.userId)).toEqual([lineOf('create_task', task.id, a)]); + expect(notices(a.userId)).toEqual([true]); + expect(logLines('mcp-tool')).toEqual([{ at: 'mcp-tool', tool: 'create_task', outcome: 'ok', ms: expect.any(Number), token: a.id }]); + // The read tools return the same task. + expect((await ok(a.token, 'get_task', { task_id: task.id }, { era })).task).toEqual(task); + }); + + it('stores every argument: notes, a priority, a due date at noon UTC, a recurrence and tags', async () => { + const a = await connected('write'); + const list = await newList(a); + const [red, blue] = [await newTag(a, { name: words('a-red') }), await newTag(a, { name: words('b-blue') })]; + const [title, notes] = [words('title'), words('notes')]; + + const { task } = await ok(a.token, 'create_task', { + title, list_id: list, notes, priority: 3, due_date: '2026-12-24', recurrence: 'yearly', tag_ids: [blue, red], + }) as { task: ShapedTask }; + expect(task).toMatchObject({ + title, notes, priority: 3, due_date: '2026-12-24T12:00:00.000Z', recurrence: 'yearly', list_id: list, parent_id: null, + tags: [{ id: red }, { id: blue }], subtasks: [], + }); + // A date-time is kept as it is: an evening in Quebec (UTC-5), the next day in UTC. + const evening = (await ok(a.token, 'create_task', { title: words('title'), due_date: '2026-12-24T19:30:00-05:00' })).task as ShapedTask; + expect(evening.due_date).toBe('2026-12-25T00:30:00.000Z'); + expect(await taskIds(a.token, { tag_ids: [red] })).toEqual([task.id]); + }); + + it('gives an account without a list its Inbox, and only one after two creations', async () => { + const a = await bare(); + const first = (await ok(a.token, 'create_task', { title: words('title') })).task as ShapedTask; + const second = (await ok(a.token, 'create_task', { title: words('title') })).task as ShapedTask; + expect(second.list_id).toBe(first.list_id); + expect((await ok(a.token, 'list_lists')).lists).toEqual([ + { id: first.list_id, name: 'Inbox', color: null, icon: null, is_inbox: true, open_task_count: 2 }, + ]); + // Two lines, for the two tasks: the Inbox has none. + expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_type} ${line.entity_id}`).sort()) + .toEqual([first.id, second.id].map((id) => `create_task task ${id}`).sort()); + expect(notices(a.userId)).toEqual([true, true]); + }); + + it('creates a subtask in the list of its parent, at the end of its subtasks, and ignores list_id', async () => { + const [a, b] = [await connected('write'), await connected()]; + const list = await newList(a); + const parent = await newTask(a, { list }); + const sibling = await newTask(a, { parentId: parent, list, position: 2 }); + + // Whatever list_id names: another list of the account, a list of another account, no list. + const created: string[] = []; + for (const [index, list_id] of [a.inbox, b.inbox, u(), undefined].entries()) { + const args = { title: words('title'), parent_id: parent, ...(list_id === undefined ? {} : { list_id }) }; + const task = (await ok(a.token, 'create_task', args, { era: ERAS[index % 2] })).task as ShapedTask; + expect(task).toMatchObject({ parent_id: parent, list_id: list, tags: [] }); + expect(task).not.toHaveProperty('subtasks'); + expect(await stored(task.id)).toMatchObject({ user_id: a.userId, list_id: list, parent_id: parent, position: 3 + index }); + created.push(task.id); + } + const read = (await ok(a.token, 'get_task', { task_id: parent })).task as ShapedTask; + expect(read.subtasks?.map((subtask) => subtask.id)).toEqual([sibling, ...created]); + expect((await journal(a.userId)).map((line) => line.entity_id).sort()).toEqual([...created].sort()); + }); + + it.each(ERAS)('refuses a list, a parent or a tag that is unknown, deleted or of another account, and writes nothing (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const top = await newTask(a); + const subtask = await newTask(a, { parentId: top }); + const own = await newTag(a); + const cases: [Json, keyof typeof TOOL_ERROR_MESSAGES][] = [ + [{ list_id: u() }, 'list_not_found'], + [{ list_id: await newList(a, { deletedAt: GONE }) }, 'list_not_found'], + [{ list_id: b.inbox }, 'list_not_found'], + [{ parent_id: u() }, 'parent_not_found'], + [{ parent_id: await newTask(a, { deletedAt: GONE }) }, 'parent_not_found'], + [{ parent_id: await newTask(b) }, 'parent_not_found'], + [{ parent_id: subtask }, 'parent_is_subtask'], + [{ tag_ids: [own, u()] }, 'tag_not_found'], + [{ tag_ids: [await newTag(a, { deletedAt: GONE })] }, 'tag_not_found'], + [{ tag_ids: [own, await newTag(b)] }, 'tag_not_found'], + [{ parent_id: top, tag_ids: [await newTag(b)] }, 'tag_not_found'], + ]; + const before = await state(a, b); + for (const [args, code] of cases) { + // The code and its fixed message, nothing else: a row of another + // account reads like a row that does not exist. + expect(await refused(a.token, 'create_task', { title: words('title'), ...args }, code, { era })) + .toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] }); + } + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + expect(logLines('mcp-tool').map((line) => line.outcome)).toEqual(cases.map(([, code]) => code)); + + // An account without a list: the Inbox created for the refused task is not kept. + const c = await bare(); + await refused(c.token, 'create_task', { title: words('title'), tag_ids: [own] }, 'tag_not_found', { era }); + expect((await ok(c.token, 'list_lists', {}, { era })).lists).toEqual([]); + }); + + it.each([ + ['no title', {}, 'title'], + ['an empty title', { title: '' }, 'title'], + ['a title of 501 characters', { title: 'x'.repeat(501) }, 'title'], + ['notes of 5001 characters', { title: 'x', notes: 'x'.repeat(5001) }, 'notes'], + ['null notes', { title: 'x', notes: null }, 'notes'], + ['a priority of 4', { title: 'x', priority: 4 }, 'priority'], + ['a recurrence the app does not know', { title: 'x', recurrence: 'hourly' }, 'recurrence'], + ['21 tags', { title: 'x', tag_ids: Array.from({ length: 21 }, () => u()) }, 'tag_ids'], + ['a tag id that is not a uuid', { title: 'x', tag_ids: ['red'] }, 'tag_ids'], + ['a list id that is not a uuid', { title: 'x', list_id: 'inbox' }, 'list_id'], + ['a parent id that is not a uuid', { title: 'x', parent_id: 'first' }, 'parent_id'], + ['a date-time without an offset', { title: 'x', due_date: '2026-06-01T10:00:00' }, 'Invalid due date'], + ['a date that does not exist', { title: 'x', due_date: '2026-02-30' }, 'Invalid due date'], + ['an account', { title: 'x', user_id: 'someone-else' }, 'user_id'], + ['a completed flag', { title: 'x', completed: true }, 'completed'], + ['a position', { title: 'x', position: 0 }, 'position'], + ])('refuses %s before the tool runs', async (_label, args, named) => { + const a = await connected('write'); + const before = await state(a); + for (const era of ERAS) expect(await invalid(a.token, 'create_task', args, { era })).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); + + it('accepts a title of 500 characters, notes of 5000 and 20 tags', async () => { + const a = await connected('write'); + const tags: string[] = []; + for (let i = 0; i < 20; i++) tags.push(await newTag(a)); + const task = (await ok(a.token, 'create_task', { title: 'x'.repeat(500), notes: 'y'.repeat(5000), tag_ids: tags })).task as ShapedTask; + expect(task.title).toHaveLength(500); + expect(task.notes).toHaveLength(5000); + expect(task.tags.map((tag) => tag.id).sort()).toEqual([...tags].sort()); + }); +}); + +describe('update_task', () => { + it.each(ERAS)('changes the fields it receives, clears with null, and every call is a write (%s)', async (era) => { + const a = await connected('write'); + const notes = words('notes'); + const id = await newTask(a, { notes, priority: 1, dueDate: '2026-06-01T12:00:00Z', recurrence: 'daily' }); + const title = words('title'); + + const renamed = await ok(a.token, 'update_task', { task_id: id, title, priority: 3 }, { era }); + expect(Object.keys(renamed)).toEqual(['task']); + expect(Object.keys(renamed.task as ShapedTask)).toEqual(TASK_KEYS); + expect(renamed.task).toMatchObject({ id, title, priority: 3, notes, due_date: '2026-06-01T12:00:00.000Z', recurrence: 'daily', completed: false }); + + const cleared = await ok(a.token, 'update_task', { task_id: id, notes: null, due_date: null, recurrence: null }, { era }); + expect(cleared.task).toMatchObject({ id, title, priority: 3, notes: null, due_date: null, recurrence: null }); + + const dated = await ok(a.token, 'update_task', { task_id: id, due_date: '2026-07-01', recurrence: 'monthly' }, { era }); + expect(dated.task).toMatchObject({ id, due_date: '2026-07-01T12:00:00.000Z', recurrence: 'monthly', notes: null }); + + // The value the task already has: a write all the same. + const same = await ok(a.token, 'update_task', { task_id: id, title }, { era }); + expect(same.task).toMatchObject({ id, title, due_date: '2026-07-01T12:00:00.000Z' }); + expect(new Date((same.task as ShapedTask).updated_at).getTime()) + .toBeGreaterThan(new Date((same.task as ShapedTask).created_at).getTime()); + + expect(await journal(a.userId)).toEqual(Array(4).fill(lineOf('update_task', id, a))); + expect(notices(a.userId)).toEqual([true, true, true, true]); + }); + + it('moves a task to the end of another list, with its live subtasks', async () => { + const a = await connected('write'); + const target = await newList(a); + const other = await newTask(a, { list: target, position: 4 }); + const id = await newTask(a, { position: 1 }); + 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 }); + + const { task } = await ok(a.token, 'update_task', { task_id: id, list_id: target }) as { task: ShapedTask }; + expect(task).toMatchObject({ id, list_id: target, parent_id: null }); + expect(task.subtasks?.map((subtask) => [subtask.id, subtask.list_id])).toEqual([[first, target], [second, target]]); + expect(await stored(id)).toMatchObject({ list_id: target, position: 5 }); + expect(await stored(deleted)).toMatchObject({ list_id: a.inbox, deleted_at: new Date(GONE) }); + expect(await taskIds(a.token, { list_id: a.inbox })).toEqual([]); + expect(await taskIds(a.token, { list_id: target })).toEqual([other, id]); + // One line, for the task: its subtasks have none. + expect(await journal(a.userId)).toEqual([lineOf('update_task', id, a)]); + expect(notices(a.userId)).toEqual([true]); + }); + + it.each(ERAS)('refuses to move a subtask, and a list that is unknown, deleted or of another account (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const id = await newTask(a); + const sub = await newTask(a, { parentId: id }); + const target = await newList(a); + const lists = [u(), await newList(a, { deletedAt: GONE }), b.inbox]; + const before = await state(a, b); + + for (const list_id of lists) { + // Nothing of the call is written, its other fields included. + expect(await refused(a.token, 'update_task', { task_id: id, list_id, title: words('title') }, 'list_not_found', { era })) + .toStrictEqual({ error: 'list_not_found', message: 'No list with this id exists in this account.' }); + } + for (const list_id of [target, a.inbox]) { + expect(await refused(a.token, 'update_task', { task_id: sub, list_id, title: words('title') }, 'subtask_not_movable', { era })) + .toStrictEqual({ error: 'subtask_not_movable', message: 'A subtask stays in the list of its parent task: it cannot be moved to another list.' }); + } + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + // The other fields of a subtask can be written. + expect((await ok(a.token, 'update_task', { task_id: sub, priority: 2 }, { era })).task).toMatchObject({ id: sub, priority: 2, parent_id: id }); + }); + + it('refuses a call without a field to change, and a field it does not take, before the tool runs', async () => { + const a = await connected('write'); + const id = await newTask(a); + const before = await state(a); + for (const era of ERAS) { + expect(await invalid(a.token, 'update_task', { task_id: id }, { era })) + .toContain('Nothing to change: pass at least one of title, notes, priority, due_date, recurrence, list_id.'); + } + const cases: [Json, string][] = [ + [{ title: 'x' }, 'task_id'], + [{ task_id: 'first', title: 'x' }, 'task_id'], + [{ task_id: id, title: '' }, 'title'], + [{ task_id: id, title: null }, 'title'], + [{ task_id: id, priority: null }, 'priority'], + [{ task_id: id, list_id: null }, 'list_id'], + [{ task_id: id, notes: 'x'.repeat(5001) }, 'notes'], + [{ task_id: id, due_date: 'tomorrow' }, 'Invalid due date'], + [{ task_id: id, recurrence: 'hourly' }, 'recurrence'], + // What the REST route takes and the tool does not. + [{ task_id: id, completed: true }, 'completed'], + [{ task_id: id, parent_id: u() }, 'parent_id'], + [{ task_id: id, position: 0 }, 'position'], + [{ task_id: id, title: 'x', user_id: 'someone-else' }, 'user_id'], + ]; + for (const [args, named] of cases) expect(await invalid(a.token, 'update_task', args), JSON.stringify(args)).toContain(named); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + }); +}); + +describe('complete_task and reopen_task', () => { + it.each(ERAS)('complete a recurring task once, with one next occurrence, and reopen it (%s)', async (era) => { + const a = await connected('write'); + const title = words('title'); + const id = await newTask(a, { title, notes: words('notes'), dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly', priority: 2 }); + await tagTask(id, await newTag(a)); + + const done = await ok(a.token, 'complete_task', { task_id: id }, { era }); + expect(Object.keys(done)).toEqual(['task', 'next_occurrence', 'changed']); + expect(done).toMatchObject({ changed: true, task: { id, completed: true, due_date: '2026-06-01T12:00:00.000Z' } }); + const completedAt = (done.task as ShapedTask).completed_at; + expect(completedAt).toMatch(/^\d{4}-\d{2}-\d{2}T/); + // The next occurrence: a week later, same title, priority and list, without the tags. + const next = done.next_occurrence as ShapedTask; + expect(Object.keys(next)).toEqual(TASK_KEYS); + expect(next).toMatchObject({ + title, completed: false, completed_at: null, priority: 2, due_date: '2026-06-08T12:00:00.000Z', recurrence: 'weekly', + list_id: a.inbox, parent_id: null, tags: [], subtasks: [], + }); + expect(next.id).not.toBe(id); + + // Replayed: nothing happens, and there is still one occurrence. + const replayed = await ok(a.token, 'complete_task', { task_id: id }, { era }); + expect(replayed).toMatchObject({ changed: false, next_occurrence: null, task: { id, completed: true, completed_at: completedAt } }); + expect(await taskIds(a.token, { status: 'all' })).toEqual([id, next.id]); + // One line, for the task that was completed, and one notice. + expect(await journal(a.userId)).toEqual([lineOf('complete_task', id, a)]); + expect(notices(a.userId)).toEqual([true]); + + const reopened = await ok(a.token, 'reopen_task', { task_id: id }, { era }); + expect(Object.keys(reopened)).toEqual(['task', 'changed']); + expect(reopened).toMatchObject({ changed: true, task: { id, completed: false, completed_at: null } }); + // An open task: nothing happens. The occurrence stays. + expect(await ok(a.token, 'reopen_task', { task_id: id }, { era })).toMatchObject({ changed: false, task: { id, completed: false } }); + expect(await ok(a.token, 'reopen_task', { task_id: next.id }, { era })).toMatchObject({ changed: false, task: { id: next.id } }); + expect(await taskIds(a.token, { status: 'all' })).toEqual([id, next.id]); + + expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_id}`).sort()) + .toEqual([`complete_task ${id}`, `reopen_task ${id}`]); + expect(notices(a.userId)).toEqual([true, true]); + // A call that changes nothing is still a call that succeeded. + expect(logLines('mcp-tool').filter((line) => line.tool !== 'list_tasks').map((line) => `${line.tool} ${line.outcome}`)).toEqual([ + 'complete_task ok', 'complete_task ok', 'reopen_task ok', 'reopen_task ok', 'reopen_task ok', + ]); + }); + + it('complete a task without a recurrence or without a due date: no next occurrence', async () => { + const a = await connected('write'); + const [plain, undated] = [await newTask(a), await newTask(a, { recurrence: 'daily' })]; + for (const id of [plain, undated]) { + expect(await ok(a.token, 'complete_task', { task_id: id })).toMatchObject({ changed: true, next_occurrence: null, task: { id, completed: true } }); + } + // A subtask is completed like a task, and comes back with its parent_id. + const child = await newTask(a, { parentId: plain }); + const done = await ok(a.token, 'complete_task', { task_id: child }); + expect(done).toMatchObject({ changed: true, next_occurrence: null, task: { id: child, parent_id: plain, completed: true } }); + expect(done.task).not.toHaveProperty('subtasks'); + expect(await taskIds(a.token, { status: 'all' })).toEqual([plain, undated]); + expect((await journal(a.userId)).map((line) => line.entity_id).sort()).toEqual([plain, undated, child].sort()); + }); + + it.each([ + ['no id', {}], + ['an id that is not a uuid', { task_id: 'first' }], + ['an unknown key', { task_id: u(), user_id: 'someone-else' }], + ])('refuse %s before the tool runs', async (_label, args) => { + const a = await connected('write'); + for (const name of ['complete_task', 'reopen_task']) await invalid(a.token, name, args); + expect(notices(a.userId)).toEqual([]); + }); +}); + +describe('set_task_tags', () => { + it.each(ERAS)('replaces the tags of a task, and changes nothing for the set it already has (%s)', async (era) => { + const a = await connected('write'); + const [red, blue, green] = [ + await newTag(a, { name: words('a-red') }), await newTag(a, { name: words('b-blue') }), await newTag(a, { name: words('c-green') }), + ]; + const id = await newTask(a); + const sub = await newTask(a, { parentId: id }); + await tagTask(id, red); + const tagsOf = (result: Json) => (result.task as ShapedTask).tags.map((tag) => tag.id); + + const set = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [green, blue] }, { era }); + expect(Object.keys(set)).toEqual(['task', 'changed']); + expect(Object.keys(set.task as ShapedTask)).toEqual(TASK_KEYS); + expect(set).toMatchObject({ changed: true, task: { id } }); + expect(tagsOf(set)).toEqual([blue, green]); + + // The same set in another order, and twice the same id. + const same = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [blue, green, blue] }, { era }); + expect(same).toMatchObject({ changed: false, task: { id, updated_at: (set.task as ShapedTask).updated_at } }); + expect(tagsOf(same)).toEqual([blue, green]); + + // A subtask has tags of its own. + const onSub = await ok(a.token, 'set_task_tags', { task_id: sub, tag_ids: [red] }, { era }); + expect(onSub).toMatchObject({ changed: true, task: { id: sub, parent_id: id } }); + expect(tagsOf(onSub)).toEqual([red]); + + // An empty list takes every tag off; a second time, there is nothing to take off. + const emptied = await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [] }, { era }); + expect(emptied).toMatchObject({ changed: true }); + expect(tagsOf(emptied)).toEqual([]); + expect(await ok(a.token, 'set_task_tags', { task_id: id, tag_ids: [] }, { era })).toMatchObject({ changed: false }); + + // Three writes out of five calls: three lines, three notices. + expect((await journal(a.userId)).map((line) => `${line.tool} ${line.entity_id}`).sort()) + .toEqual([`set_task_tags ${id}`, `set_task_tags ${id}`, `set_task_tags ${sub}`].sort()); + expect(notices(a.userId)).toEqual([true, true, true]); + // The tags themselves are still there. + expect(((await ok(a.token, 'list_tags', {}, { era })).tags as ShapedTag[]).map((tag) => tag.id)).toEqual([red, blue, green]); + }); + + it.each(ERAS)('refuses a tag that is unknown, deleted or of another account, and writes nothing (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const own = await newTag(a); + const id = await newTask(a); + await tagTask(id, own); + const tags = [u(), await newTag(a, { deletedAt: GONE }), await newTag(b)]; + const before = await state(a, b); + for (const tag of tags) { + for (const tag_ids of [[tag], [own, tag]]) { + expect(await refused(a.token, 'set_task_tags', { task_id: id, tag_ids }, 'tag_not_found', { era })) + .toStrictEqual({ error: 'tag_not_found', message: 'No tag with this id exists in this account.' }); + } + } + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + }); + + it.each([ + ['no tag_ids', (id: string) => ({ task_id: id }), 'tag_ids'], + ['a null tag_ids', (id: string) => ({ task_id: id, tag_ids: null }), 'tag_ids'], + ['21 tags', (id: string) => ({ task_id: id, tag_ids: Array.from({ length: 21 }, () => u()) }), 'tag_ids'], + ['a tag id that is not a uuid', (id: string) => ({ task_id: id, tag_ids: ['red'] }), 'tag_ids'], + ['no task', () => ({ tag_ids: [] }), 'task_id'], + ['an unknown key', (id: string) => ({ task_id: id, tag_ids: [], user_id: 'someone-else' }), 'user_id'], + ])('refuses %s before the tool runs', async (_label, args, named) => { + const a = await connected('write'); + const id = await newTask(a); + await tagTask(id, await newTag(a)); + const before = await state(a); + for (const era of ERAS) expect(await invalid(a.token, 'set_task_tags', args(id), { era })).toContain(named); + expect(await state(a)).toEqual(before); + }); +}); + +describe('the write tools and the other accounts', () => { + it.each(ERAS)('a task that is unknown, deleted or of another account answers not_found to every write tool (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const tag = await newTag(a); + const ids = [u(), await newTask(a, { deletedAt: GONE }), await newTask(b), await newTask(b, { parentId: await newTask(b) })]; + const before = await state(a, b); + for (const task_id of ids) { + for (const [name, args] of [ + ['update_task', { title: words('title') }], + ['complete_task', {}], + ['reopen_task', {}], + ['set_task_tags', { tag_ids: [tag] }], + ] as const) { + expect(await refused(a.token, name, { task_id, ...args }, 'not_found', { era }), `${name} ${task_id}`) + .toStrictEqual({ error: 'not_found', message: 'No task with this id exists in this account.' }); + } + } + // Nothing of the refusals tells one case from another. + expect(new Set(seen.answers.map((answered) => answered.text)).size).toBe(1); + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + }); + + it.each(ERAS)('no write tool writes, moves or links a row of another account (%s)', async (era) => { + const [a, b] = [await connected('write'), await connected('write')]; + const [titleB, notesB] = [words('title'), words('notes')]; + const taskB = await newTask(b, { title: titleB, notes: notesB, dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly' }); + const subB = await newTask(b, { parentId: taskB }); + const doneB = await newTask(b, { completed: true, completedAt: '2026-03-02T00:00:00Z' }); + const listB = await newList(b); + const tagB = await newTag(b); + await tagTask(taskB, tagB); + const own = await newTask(a); + const ownTag = await newTag(a); + await tagTask(own, ownTag); + + const attempts: [string, Json, keyof typeof TOOL_ERROR_MESSAGES][] = [ + // A task of the account in a list, under a task or with a tag of the other. + ['create_task', { title: words('title'), list_id: listB }, 'list_not_found'], + ['create_task', { title: words('title'), list_id: b.inbox }, 'list_not_found'], + ['create_task', { title: words('title'), parent_id: taskB }, 'parent_not_found'], + ['create_task', { title: words('title'), parent_id: subB }, 'parent_not_found'], + ['create_task', { title: words('title'), tag_ids: [tagB] }, 'tag_not_found'], + ['update_task', { task_id: own, list_id: listB }, 'list_not_found'], + ['set_task_tags', { task_id: own, tag_ids: [tagB] }, 'tag_not_found'], + ['set_task_tags', { task_id: own, tag_ids: [ownTag, tagB] }, 'tag_not_found'], + // A task of the other account: renamed, taken into a list of the account, completed, reopened, tagged. + ['update_task', { task_id: taskB, title: words('title') }, 'not_found'], + ['update_task', { task_id: taskB, list_id: a.inbox }, 'not_found'], + ['update_task', { task_id: subB, notes: null }, 'not_found'], + ['complete_task', { task_id: taskB }, 'not_found'], + ['reopen_task', { task_id: doneB }, 'not_found'], + ['set_task_tags', { task_id: taskB, tag_ids: [] }, 'not_found'], + ['set_task_tags', { task_id: taskB, tag_ids: [ownTag] }, 'not_found'], + ['set_task_tags', { task_id: taskB, tag_ids: [tagB] }, 'not_found'], + ]; + const before = await state(a, b); + for (const [name, args, code] of attempts) { + expect(await refused(a.token, name, args, code, { era }), `${name} ${JSON.stringify(args)}`) + .toStrictEqual({ error: code, message: TOOL_ERROR_MESSAGES[code] }); + } + // Not a row of either account changed, no line was journaled, nobody was notified. + expect(await state(a, b)).toEqual(before); + expect([notices(a.userId), notices(b.userId)]).toEqual([[], []]); + // Nothing of the other account was read back either. + const answered = seen.answers.map((x) => x.text).join('\n'); + for (const leak of [titleB, notesB, taskB, subB, listB, tagB]) expect(answered).not.toContain(leak); + + // The other account does all of it on its own rows. + expect(await ok(b.token, 'update_task', { task_id: taskB, list_id: listB }, { era })).toMatchObject({ task: { id: taskB, list_id: listB } }); + expect(await ok(b.token, 'set_task_tags', { task_id: taskB, tag_ids: [] }, { era })).toMatchObject({ changed: true }); + expect(await ok(b.token, 'complete_task', { task_id: taskB }, { era })).toMatchObject({ changed: true, next_occurrence: { list_id: listB } }); + expect(await ok(b.token, 'reopen_task', { task_id: doneB }, { era })).toMatchObject({ changed: true }); + expect(await ok(b.token, 'create_task', { title: words('title'), parent_id: taskB, tag_ids: [tagB] }, { era })) + .toMatchObject({ task: { parent_id: taskB, list_id: listB, tags: [{ id: tagB }] } }); + expect((await journal(b.userId)).every((line) => line.token_id === b.id)).toBe(true); + expect(await journal(a.userId)).toEqual([]); + expect([notices(a.userId), notices(b.userId).length]).toEqual([[], 5]); + }); +}); + +describe('the journal and the notice of a write', () => { + // A token revoked while its request runs: the request was authenticated, + // and the row its journal line points to is gone (#199). + it('takes the write back when its journal line cannot be written, and answers internal_error', async () => { + const a = await connected('write'); + const id = await newTask(a, { dueDate: '2026-06-01T12:00:00Z', recurrence: 'weekly' }); + const done = await newTask(a, { completed: true, completedAt: '2026-03-02T00:00:00Z' }); + const tag = await newTag(a); + const target = await newList(a); + const revoked = { userId: a.userId, scope: 'write', tokenId: u(), tokenName: 'Assistant' } as const; + const writes: [string, Json][] = [ + ['create_task', { title: words('title'), tag_ids: [tag] }], + ['update_task', { task_id: id, title: words('title'), list_id: target }], + ['complete_task', { task_id: id }], + ['reopen_task', { task_id: done }], + ['set_task_tags', { task_id: id, tag_ids: [tag] }], + ]; + const before = await state(a); + for (const [name, args] of writes) { + expect(await handled(revoked, name, args), name).toStrictEqual({ + isError: true, + data: { error: 'internal_error', message: 'The server could not complete this call. Try again later.' }, + }); + } + // Neither the task, nor the move, nor the completion and its next + // occurrence, nor the link: nothing was kept, and nobody was notified. + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toEqual([]); + const lines = logLines('mcp-tool'); + expect(lines.map((line) => `${line.tool} ${line.outcome}`)).toEqual(writes.map(([name]) => `${name} internal_error`)); + for (const line of lines) { + expect(line.token).toBe(revoked.tokenId); + // The class name of the database error, never its text. + expect(line.error).toMatch(/^[A-Za-z]+$/); + } + + // A call that changes nothing writes no line: it is served. + expect(await handled(revoked, 'reopen_task', { task_id: id })).toMatchObject({ isError: false, data: { changed: false } }); + // Control: the same writes with the token of the account are kept. + for (const [name, args] of writes) await ok(a.token, name, args); + expect((await journal(a.userId)).map((line) => line.tool).sort()).toEqual(writes.map(([name]) => name).sort()); + expect(notices(a.userId)).toEqual(Array(5).fill(true)); + }); + + it('journals a write of a caller without a token row under a null token', async () => { + const a = await connected('write'); + const oauth = { userId: a.userId, scope: 'write', tokenId: null, tokenName: 'Connection' } as const; + const { data } = await handled(oauth, 'create_task', { title: words('title') }); + const task = data.task as ShapedTask; + expect(await journal(a.userId)).toEqual([ + { tool: 'create_task', entity_type: 'task', entity_id: task.id, token_id: null, token_name: 'Connection' }, + ]); + expect(notices(a.userId)).toEqual([true]); + }); + + it('keeps the lines of a token once it is revoked, and writes nothing more with it', async () => { + const a = await connected('write'); + const title = words('title'); + const task = (await ok(a.token, 'create_task', { title })).task as ShapedTask; + // What the page of the assistants reads: the line, with the title of the task as it is now. + const line = { tool: 'create_task', entityType: 'task', entityId: task.id, entityName: title, tokenName: 'Assistant' }; + expect((await listActions(db, a.userId, { limit: 10 })).actions).toMatchObject([{ ...line, tokenId: a.id, tokenRevoked: false }]); + + expect(await revokeAgentToken(a.userId, a.id)).toBe(true); + expect((await listActions(db, a.userId, { limit: 10 })).actions).toMatchObject([{ ...line, tokenId: null, tokenRevoked: true }]); + expect(await journal(a.userId)).toEqual([{ ...lineOf('create_task', task.id, a), token_id: null }]); + expect(await rpc(a.token, 'tools/call', { name: 'complete_task', arguments: { task_id: task.id } })).toMatchObject(UNAUTHORIZED); + expect((await stored(task.id)).completed).toBe(false); + expect(notices(a.userId)).toEqual([true]); + }); +}); + +describe('the write limit', () => { + it('refuses the 31st write of a minute with rate_limited, all tokens and all write tools of the account together', async () => { + const a = await connected('write'); + const second = await newToken(a, { scope: 'write' }); + const b = await connected('write'); + const id = await newTask(a); + + await frozen(async (advance) => { + // 30 calls over two tokens, the five tools and both generations: a call + // that changes nothing and a call the tool refuses count like the others. + const writes = [ + ['create_task', { title: 'x' }], ['update_task', { task_id: id, priority: 1 }], ['complete_task', { task_id: id }], + ['reopen_task', { task_id: id }], ['set_task_tags', { task_id: id, tag_ids: [] }], ['complete_task', { task_id: u() }], + ] as const; + for (let i = 0; i < 30; i++) { + const [name, args] = writes[i % writes.length]; + const r = await call(i % 2 === 0 ? a.token : second.token, name, args, { era: ERAS[(i >> 1) % 2] }); + expect(r.data.error === 'rate_limited', `write ${i + 1}: ${r.text}`).toBe(false); + } + const [before, transactions, sent] = [await state(a), h.transactions, notices(a.userId).length]; + + advance(20_000); + for (const era of ERAS) { + expect(await refused(a.token, 'create_task', { title: 'x' }, 'rate_limited', { era })).toStrictEqual({ + error: 'rate_limited', + message: 'Too many calls for this account: wait retry_after_seconds seconds, then try again.', + retry_after_seconds: 40, + }); + } + // The other token of the account, and every write tool. + await refused(second.token, 'update_task', { task_id: id, priority: 2 }, 'rate_limited'); + await refused(second.token, 'complete_task', { task_id: id }, 'rate_limited'); + await refused(second.token, 'reopen_task', { task_id: id }, 'rate_limited'); + await refused(second.token, 'set_task_tags', { task_id: id, tag_ids: [] }, 'rate_limited'); + // Refused before the transaction: nothing written, nobody notified. + expect(h.transactions).toBe(transactions); + expect(await state(a)).toEqual(before); + expect(notices(a.userId)).toHaveLength(sent); + // An answer of the tool, not an HTTP error. + expect(seen.answers.every((answered) => answered.status === 200)).toBe(true); + expect(logLines('mcp-tool').slice(-6).map((line) => line.outcome)).toEqual(Array(6).fill('rate_limited')); + + // The reads are counted apart, and another account is not slowed down. + await ok(a.token, 'get_task', { task_id: id }); + await ok(b.token, 'create_task', { title: 'x' }); + + // A refused call is not counted: once the minute has passed, the account writes again. + advance(39_999); + expect(await refused(a.token, 'create_task', { title: 'x' }, 'rate_limited')).toMatchObject({ retry_after_seconds: 1 }); + advance(1); + await ok(a.token, 'create_task', { title: 'x' }); + }); + }); + + it('counts every write of a JSON-RPC batch', async () => { + const a = await connected('write'); + await frozen(async () => { + for (let i = 0; i < 28; i++) expect(rateLimitDelay(a.userId, 'mcp-write')).toBeNull(); + const batch = [1, 2, 3].map((id) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'create_task', arguments: { title: 'x' } } })); + const answered = await post(a.token, JSON.stringify(batch), { headers: LEGACY_ACCEPT }); + expect(answered.status).toBe(200); + // One HTTP request, three calls: two tasks are created, the third call is the 31st. + expect(logLines('mcp-tool').map((line) => line.outcome).sort()).toEqual(['ok', 'ok', 'rate_limited']); + expect(await journal(a.userId)).toHaveLength(2); + // The calls of a batch may overlap: only their number is read here. + expect(notices(a.userId)).toHaveLength(2); + }); + }); }); describe('list_lists', () => { diff --git a/web/src/lib/agentJournal.test.ts b/web/src/lib/agentJournal.test.ts new file mode 100644 index 0000000..92ea9fe --- /dev/null +++ b/web/src/lib/agentJournal.test.ts @@ -0,0 +1,430 @@ +import fs from 'node:fs'; +import path from 'node:path'; +import { createHash, randomUUID as u } from 'node:crypto'; +import { describe, it, expect, beforeAll } from 'vitest'; +import { PGlite } from 'electric-sql-pglite'; +import { eq } from 'drizzle-orm'; +import { drizzle } from 'drizzle-orm/pglite'; +import { migrate } from 'drizzle-orm/pglite/migrator'; +import type { db as routesDb } from '@/db/client'; +import * as schema from '@/db/schema'; +import { + JOURNAL_PAGE_MAX, + JOURNAL_RETENTION_DAYS, + listActions, + purgeOldActions, + recordAction, + safePurge, + type JournalCursor, + type JournalExecutor, +} from './agentJournal'; + +// The journal of the agent tokens (#203), on an in-memory Postgres (PGlite) +// with the companion migrations. Nothing is mocked: every function receives +// the database it queries, as web/server.ts and the write envelope of the MCP +// tools give it. + +const { slAgentActions, slAgentTokens, slLists } = schema; + +const pg = new PGlite(); +const db = drizzle(pg, { schema }); + +const DAY_MS = 24 * 60 * 60 * 1000; +const NOW = new Date('2026-11-15T15:00:00.000Z'); +const GONE = '2026-11-10T09:00:00.000Z'; +const UUID = /^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/; + +// `days` before NOW, plus `ms`. +const ago = (days: number, ms = 0) => new Date(NOW.getTime() - days * DAY_MS + ms); + +beforeAll(async () => { + await migrate(db, { migrationsFolder: path.join(__dirname, '../db/migrations') }); +}); + +// Each test creates its own accounts (#148), with invented ids. +const newUser = () => `user-${u()}`; + +async function newToken(userId: string, name = 'Assistant') { + const tokenHash = createHash('sha256').update(u()).digest('hex'); + const [row] = await db.insert(slAgentTokens).values({ userId, name, tokenHash, hint: 'abcd', scope: 'write' }).returning(); + return row; +} + +type RowFields = { name?: string; deletedAt?: string }; + +async function newList(userId: string, fields: RowFields = {}): Promise { + const id = u(); + await pg.query('insert into sl_lists (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [id, userId, fields.name ?? 'List', fields.deletedAt ?? null]); + return id; +} + +async function newTask(userId: string, fields: RowFields = {}): Promise { + const id = u(); + await pg.query( + 'insert into sl_tasks (id, user_id, title, list_id, deleted_at) values ($1, $2, $3, $4, $5)', + [id, userId, fields.name ?? 'Task', await newList(userId), fields.deletedAt ?? null], + ); + return id; +} + +async function newTag(userId: string, fields: RowFields = {}): Promise { + const id = u(); + await pg.query('insert into sl_tags (id, user_id, name, deleted_at) values ($1, $2, $3, $4)', [id, userId, fields.name ?? 'Tag', fields.deletedAt ?? null]); + return id; +} + +type LineFields = { + id?: string; tokenId?: string | null; tokenName?: string; tool?: string; entityType?: string; entityId?: string; + // An instant, or the text PostgreSQL reads (microseconds). + at?: Date | string; +}; + +// A journal line written straight to the table; one minute before NOW unless +// `at` says when. +async function line(userId: string, fields: LineFields = {}): Promise { + const id = fields.id ?? u(); + const at = fields.at ?? ago(0, -60_000); + await pg.query( + 'insert into sl_agent_actions (id, user_id, token_id, token_name, tool, entity_type, entity_id, created_at) values ($1, $2, $3, $4, $5, $6, $7, $8)', + [ + id, userId, fields.tokenId ?? null, fields.tokenName ?? 'Assistant', fields.tool ?? 'update_task', + fields.entityType ?? 'task', fields.entityId ?? u(), typeof at === 'string' ? at : at.toISOString(), + ], + ); + return id; +} + +async function idsOf(userId: string): Promise { + const rows = await db.select({ id: slAgentActions.id }).from(slAgentActions).where(eq(slAgentActions.userId, userId)); + return rows.map((row) => row.id).sort(); +} + +// Every page of the journal of an account, read one after the other. +async function pagesOf(userId: string, limit: number): Promise { + const pages: string[][] = []; + let before: JournalCursor | null = null; + do { + const page = await listActions(db, userId, { before, limit }, NOW); + pages.push(page.actions.map((action) => action.id)); + before = page.nextCursor; + } while (before !== null && pages.length < 50); + return pages; +} + +describe('recordAction', () => { + it('writes one line: the account, the token, the tool and the row touched, at the instant it receives', async () => { + const userId = newUser(); + const token = await newToken(userId, 'Hermes'); + const entityId = u(); + await recordAction(db, { userId, tokenId: token.id, tokenName: 'Hermes', tool: 'create_task', entityType: 'task', entityId }, NOW); + expect(await db.select().from(slAgentActions).where(eq(slAgentActions.userId, userId))).toEqual([{ + id: expect.stringMatching(UUID), userId, tokenId: token.id, tokenName: 'Hermes', tool: 'create_task', + entityType: 'task', entityId, createdAt: NOW, + }]); + + // A caller without a token row, and the current instant by default. + const other = newUser(); + await recordAction(db, { userId: other, tokenId: null, tokenName: 'Connection', tool: 'update_list', entityType: 'list', entityId }); + const [written] = await db.select().from(slAgentActions).where(eq(slAgentActions.userId, other)); + expect(written).toMatchObject({ tokenId: null, tokenName: 'Connection', tool: 'update_list', entityType: 'list' }); + expect(Math.abs(Date.now() - written.createdAt.getTime())).toBeLessThan(60_000); + }); + + it('fails for a token that no longer exists, and the transaction of the write fails with it', async () => { + const userId = newUser(); + const listId = u(); + const failure = await db.transaction(async (tx) => { + await tx.insert(slLists).values({ id: listId, userId, name: 'Written before the line' }); + await recordAction(tx, { userId, tokenId: u(), tokenName: 'Revoked', tool: 'create_list', entityType: 'list', entityId: listId }, NOW); + }).then(() => null, (error: { cause?: { code?: string; constraint?: string } }) => error); + expect(failure?.cause).toMatchObject({ code: '23503', constraint: 'sl_agent_actions_token_id_sl_agent_tokens_id_fk' }); + expect(await db.select().from(slLists).where(eq(slLists.id, listId))).toEqual([]); + expect(await idsOf(userId)).toEqual([]); + }); +}); + +describe('listActions', () => { + it('returns the lines of the account, newest first, with the name of the row each one touched', async () => { + const userId = newUser(); + const token = await newToken(userId, 'Hermes'); + const [task, list, tag] = [ + await newTask(userId, { name: 'Call Paul' }), await newList(userId, { name: 'Home' }), await newTag(userId, { name: 'urgent' }), + ]; + const onTask = await line(userId, { tokenId: token.id, tokenName: 'Hermes', tool: 'create_task', entityId: task, at: ago(3) }); + const onList = await line(userId, { tokenId: token.id, tokenName: 'Hermes', tool: 'update_list', entityType: 'list', entityId: list, at: ago(2) }); + const onTag = await line(userId, { tokenId: token.id, tokenName: 'Hermes', tool: 'create_tag', entityType: 'tag', entityId: tag, at: ago(1) }); + + const page = await listActions(db, userId, { limit: 10 }, NOW); + expect(page.nextCursor).toBeNull(); + expect(page.actions).toStrictEqual([ + { + id: onTag, tool: 'create_tag', entityType: 'tag', entityId: tag, entityName: 'urgent', + tokenId: token.id, tokenName: 'Hermes', tokenRevoked: false, createdAt: ago(1), + }, + { + id: onList, tool: 'update_list', entityType: 'list', entityId: list, entityName: 'Home', + tokenId: token.id, tokenName: 'Hermes', tokenRevoked: false, createdAt: ago(2), + }, + { + id: onTask, tool: 'create_task', entityType: 'task', entityId: task, entityName: 'Call Paul', + tokenId: token.id, tokenName: 'Hermes', tokenRevoked: false, createdAt: ago(3), + }, + ]); + }); + + it('gives a null name to a row that was deleted, that is not there, or whose type is not its own', async () => { + const userId = newUser(); + const [task, list, tag] = [await newTask(userId, { name: 'Kept' }), await newList(userId, { name: 'Home' }), await newTag(userId, { name: 'urgent' })]; + const lines = [ + await line(userId, { entityId: await newTask(userId, { deletedAt: GONE }) }), + await line(userId, { entityType: 'list', entityId: await newList(userId, { deletedAt: GONE }) }), + await line(userId, { entityType: 'tag', entityId: await newTag(userId, { deletedAt: GONE }) }), + await line(userId, { entityId: u() }), + // The id of a list under the type of a task, and so on: no name is borrowed. + await line(userId, { entityType: 'task', entityId: list }), + await line(userId, { entityType: 'list', entityId: tag }), + await line(userId, { entityType: 'tag', entityId: task }), + await line(userId, { entityType: 'note', entityId: task }), + ]; + const named = await line(userId, { entityId: task }); + + const { actions } = await listActions(db, userId, { limit: 20 }, NOW); + expect(actions).toHaveLength(9); + const names = Object.fromEntries(actions.map((action) => [action.id, action.entityName])); + for (const id of lines) expect(names[id], id).toBeNull(); + expect(names[named]).toBe('Kept'); + }); + + it('marks the lines of a revoked token, and keeps the name the token had', async () => { + const userId = newUser(); + const [revoked, live] = [await newToken(userId, 'Hermes'), await newToken(userId, 'Claude')]; + const first = await line(userId, { tokenId: revoked.id, tokenName: 'Hermes', at: ago(2) }); + const second = await line(userId, { tokenId: live.id, tokenName: 'Claude', at: ago(1) }); + // Revoking a token deletes its row: token_id falls to null (#199). + await db.delete(slAgentTokens).where(eq(slAgentTokens.id, revoked.id)); + + const { actions } = await listActions(db, userId, { limit: 10 }, NOW); + expect(actions.map(({ id, tokenId, tokenName, tokenRevoked }) => ({ id, tokenId, tokenName, tokenRevoked }))).toEqual([ + { id: second, tokenId: live.id, tokenName: 'Claude', tokenRevoked: false }, + { id: first, tokenId: null, tokenName: 'Hermes', tokenRevoked: true }, + ]); + }); + + it('never returns a line of another account, nor the name of a row of another account', async () => { + const [A, B] = [newUser(), newUser()]; + const [taskA, taskB, listB, tagB] = [ + await newTask(A, { name: 'Task of A' }), await newTask(B, { name: 'Task of B' }), + await newList(B, { name: 'List of B' }), await newTag(B, { name: 'Tag of B' }), + ]; + const own = await line(A, { entityId: taskA, at: ago(1) }); + const lineB = await line(B, { entityId: taskB, at: ago(1) }); + // Lines no tool writes: a line of A that points at rows of B. + const strays = [ + await line(A, { entityId: taskB, at: ago(2) }), + await line(A, { entityType: 'list', entityId: listB, at: ago(3) }), + await line(A, { entityType: 'tag', entityId: tagB, at: ago(4) }), + ]; + + const forA = await listActions(db, A, { limit: 10 }, NOW); + expect(forA.actions.map((action) => [action.id, action.entityName])).toEqual([ + [own, 'Task of A'], [strays[0], null], [strays[1], null], [strays[2], null], + ]); + const forB = await listActions(db, B, { limit: 10 }, NOW); + expect(forB.actions.map((action) => [action.id, action.entityName])).toEqual([[lineB, 'Task of B']]); + // No field of a line carries the account. + expect(JSON.stringify([forA, forB])).not.toMatch(/user-|userId|user_id/); + expect(await listActions(db, newUser(), { limit: 10 }, NOW)).toEqual({ actions: [], nextCursor: null }); + }); + + it('returns nothing older than 90 days, purged or not', async () => { + const userId = newUser(); + expect(JOURNAL_RETENTION_DAYS).toBe(90); + const recent = await line(userId, { at: ago(89) }); + const onTheBound = await line(userId, { at: ago(90) }); + await line(userId, { at: ago(90, -1) }); + await line(userId, { at: ago(91) }); + await line(userId, { at: ago(400) }); + expect(await pagesOf(userId, 10)).toEqual([[recent, onTheBound]]); + expect(await pagesOf(userId, 1)).toEqual([[recent], [onTheBound]]); + // The bound moves with the clock: a day later, both are out. + const later = new Date(NOW.getTime() + DAY_MS + 1); + expect((await listActions(db, userId, { limit: 10 }, later)).actions).toEqual([]); + // The five lines are still in the table: the purge is another function. + expect(await idsOf(userId)).toHaveLength(5); + }); + + it('reads by pages: the cursor of a page opens the next one, the last page has none', async () => { + const userId = newUser(); + const ids: string[] = []; + for (let day = 1; day <= 5; day++) ids.push(await line(userId, { at: ago(day) })); + + const first = await listActions(db, userId, { limit: 2 }, NOW); + expect(first.actions.map((action) => action.id)).toEqual(ids.slice(0, 2)); + expect(first.nextCursor).toEqual({ createdAt: ago(2), id: ids[1] }); + + expect(await pagesOf(userId, 2)).toEqual([ids.slice(0, 2), ids.slice(2, 4), ids.slice(4)]); + expect(await pagesOf(userId, 5)).toEqual([ids]); + expect(await pagesOf(userId, 1)).toEqual(ids.map((id) => [id])); + // A cursor is a place, not a line: one that names no line reads what is older. + const between = await listActions(db, userId, { before: { createdAt: ago(2, 1000), id: u() }, limit: 10 }, NOW); + expect(between.actions.map((action) => action.id)).toEqual(ids.slice(1)); + // A cursor of another account is a place in the journal of the reader. + const other = newUser(); + const foreign = await line(other, { at: ago(1) }); + const fromOther = (await listActions(db, other, { limit: 1 }, NOW)).actions[0]; + const read = await listActions(db, userId, { before: { createdAt: fromOther.createdAt, id: fromOther.id }, limit: 10 }, NOW); + expect(read.actions.map((action) => action.id)).not.toContain(foreign); + expect(read.actions.every((action) => ids.includes(action.id))).toBe(true); + }); + + // created_at holds microseconds, the cursor milliseconds. + it('returns each of the lines written in the same millisecond exactly once', async () => { + const userId = newUser(); + // Lowercase hexadecimal: the order of the strings is the order of the uuids. + const [low, high] = [u(), u()].sort(); + const before = await line(userId, { at: '2026-11-14T10:00:00.122999Z' }); + await line(userId, { id: low, at: '2026-11-14T10:00:00.123999Z' }); + await line(userId, { id: high, at: '2026-11-14T10:00:00.123001Z' }); + const after = await line(userId, { at: '2026-11-14T10:00:00.124000Z' }); + expect(await pagesOf(userId, 1)).toEqual([[after], [high], [low], [before]]); + expect(await pagesOf(userId, 2)).toEqual([[after, high], [low, before]]); + expect(await pagesOf(userId, 3)).toEqual([[after, high, low], [before]]); + }); + + it('bounds a page to 100 lines, and reads one line for a limit below one', async () => { + const userId = newUser(); + await pg.query( + `insert into sl_agent_actions (user_id, token_name, tool, entity_type, entity_id, created_at) + select $1::text, 'Assistant', 'update_task', 'task', gen_random_uuid(), $2::timestamptz - n * interval '1 second' + from generate_series(1, 101) as n`, + [userId, NOW.toISOString()], + ); + expect(JOURNAL_PAGE_MAX).toBe(100); + for (const limit of [100, 101, 5000, Number.POSITIVE_INFINITY]) { + const page = await listActions(db, userId, { limit }, NOW); + expect(page.actions, String(limit)).toHaveLength(100); + expect(page.nextCursor).not.toBeNull(); + } + for (const limit of [1, 0, -3, 0.5, Number.NaN]) { + expect((await listActions(db, userId, { limit }, NOW)).actions, String(limit)).toHaveLength(1); + } + expect((await pagesOf(userId, 100)).map((page) => page.length)).toEqual([100, 1]); + }); +}); + +describe('purgeOldActions', () => { + it('deletes the lines of more than 90 days, of every account, and says how many', async () => { + const [A, B] = [newUser(), newUser()]; + const kept = [await line(A, { at: ago(89) }), await line(A, { at: ago(90) }), await line(A, { at: ago(0) })]; + await line(A, { at: ago(91) }); + await line(A, { at: ago(90, -1) }); + const keptB = await line(B, { at: ago(1) }); + await line(B, { at: ago(365) }); + + // Other tests of this file may have left old lines: count them first. + const { rows: [{ old }] } = await pg.query<{ old: number }>( + 'select count(*)::int as old from sl_agent_actions where created_at < $1', [ago(90).toISOString()], + ); + expect(old).toBeGreaterThanOrEqual(3); + expect(await purgeOldActions(db, NOW)).toBe(old); + expect(await idsOf(A)).toEqual([...kept].sort()); + expect(await idsOf(B)).toEqual([keptB]); + // Nothing left to purge, and what was kept is what listActions shows. + expect(await purgeOldActions(db, NOW)).toBe(0); + expect((await listActions(db, A, { limit: 10 }, NOW)).actions.map((action) => action.id).sort()).toEqual([...kept].sort()); + + // 90 days later, by the clock of the call, the rest goes too. + expect(await purgeOldActions(db, new Date(NOW.getTime() + 91 * DAY_MS))).toBeGreaterThanOrEqual(4); + expect([await idsOf(A), await idsOf(B)]).toEqual([[], []]); + }); +}); + +describe('safePurge', () => { + it('logs the number of lines purged', async () => { + const lines: string[] = []; + await safePurge(async () => 12, (text) => lines.push(text)); + await safePurge(() => purgeOldActions(db, new Date('2000-01-01T00:00:00Z')), (text) => lines.push(text)); + expect(lines).toEqual(['> Journal purge: 12 rows', '> Journal purge: 0 rows']); + }); + + it('never throws: a purge that fails logs the class name of its error, and nothing else of it', async () => { + class QueryError extends Error { + name = 'QueryError'; + } + const lines: string[] = []; + const log = (text: string) => lines.push(text); + await expect(safePurge(() => Promise.reject(new QueryError('Failed query: delete from "sl_agent_actions" for user-1')), log)).resolves.toBeUndefined(); + await expect(safePurge(() => { throw new TypeError('connection refused by db-host'); }, log)).resolves.toBeUndefined(); + await expect(safePurge(() => Promise.reject('a string'), log)).resolves.toBeUndefined(); + expect(lines).toEqual(['> Journal purge failed: QueryError', '> Journal purge failed: TypeError', '> Journal purge failed: Error']); + + // A real failure: the table is not there for the time of one purge. No + // second database is started for it: a PGlite that boots inside a test + // has exceeded the test timeout when the other files boot theirs. + await pg.exec('alter table sl_agent_actions rename to sl_agent_actions_away'); + try { + // Control: what safePurge has to hide. The query fails with its text. + const failure = await purgeOldActions(db, NOW).then(() => null, (error: Error) => error); + expect(failure?.message).toContain('sl_agent_actions'); + await expect(safePurge(() => purgeOldActions(db, NOW), log)).resolves.toBeUndefined(); + } finally { + await pg.exec('alter table sl_agent_actions_away rename to sl_agent_actions'); + } + expect(lines).toHaveLength(4); + expect(lines[3]).toMatch(/^> Journal purge failed: [A-Za-z]+$/); + expect(lines.join('\n')).not.toMatch(/sl_agent_actions|delete|user-1|db-host/); + }); + + it('a log that throws stops nothing either', async () => { + const failing = () => { throw new Error('stdout closed'); }; + await expect(safePurge(async () => 1, failing)).resolves.toBeUndefined(); + await expect(safePurge(() => Promise.reject(new Error('purge failed')), failing)).resolves.toBeUndefined(); + }); +}); + +// web/server.ts is bundled by esbuild, apart from the routes (web/Dockerfile), +// and neither vitest nor `next build` loads it: these read the sources. +describe('the purge in the server bundle', () => { + const read = (file: string) => fs.readFileSync(path.join(__dirname, file), 'utf8'); + // `[^;]` also matches a line break: an import written on several lines is read. + const importsOf = (source: string) => [...source.matchAll(/^import\s[^;]*?from '([^']+)';$/gm)].map((match) => match[1]); + + it('agentJournal.ts imports nothing that reaches the database client', () => { + // Checked by tsc, not by vitest: the database of the routes is something + // the functions accept, though the module never imports it (the import + // above is a type, erased at build time). + const accepted = (executor: typeof routesDb): JournalExecutor => executor; + expect(accepted).toBeTypeOf('function'); + + const source = read('agentJournal.ts'); + expect(importsOf(source)).toEqual(['drizzle-orm', 'drizzle-orm/pg-core', '../db/schema', './mcp/errors']); + expect(source).not.toMatch(/db\/client|import\(|require\(/); + // What it imports from the project imports nothing of the project. + expect(importsOf(read('../db/schema.ts')).every((name) => name.startsWith('drizzle-orm'))).toBe(true); + expect(importsOf(read('mcp/errors.ts'))).toEqual([]); + }); + + it('server.ts purges once the migrations are done, outside their try block, then every 24 hours', () => { + const source = read('../../server.ts'); + // A pool of its own, of one connection, whose errors are listened to. + expect(source).toContain('const pool = new Pool({ connectionString: process.env.DATABASE_URL, max: 1 });'); + expect(source).toContain("pool.on('error',"); + expect(source).toContain('const purge = () => safePurge(() => purgeOldActions(drizzle(pool)));'); + expect(source).toContain('const JOURNAL_PURGE_INTERVAL_MS = 24 * 60 * 60 * 1000;'); + // The first purge is not awaited, and the timer does not hold the process. + expect(source).toContain('void purge();'); + expect(source).toContain('setInterval(purge, JOURNAL_PURGE_INTERVAL_MS).unref();'); + + // Started once: after the block that stops the process on a migration + // error has closed, and before the site is prepared. + const starts = [...source.matchAll(/^ *startJournalPurge\(\);$/gm)]; + expect(starts).toHaveLength(1); + const migrationBlock = source.match(/\n try \{\n await runMigrations\(\);\n \} catch \(err\) \{\n[^}]*process\.exit\(1\);\n \}\n/); + expect(migrationBlock).not.toBeNull(); + const afterMigrations = (migrationBlock?.index ?? 0) + (migrationBlock?.[0].length ?? 0); + expect(starts[0].index).toBeGreaterThanOrEqual(afterMigrations); + expect(starts[0].index).toBeLessThan(source.indexOf('await app.prepare();')); + // The pool of the migrations is closed when they end: the purge does not use it. + expect(source.match(/new Pool\(/g)).toHaveLength(2); + }); +}); diff --git a/web/src/lib/agentJournal.ts b/web/src/lib/agentJournal.ts new file mode 100644 index 0000000..76f407b --- /dev/null +++ b/web/src/lib/agentJournal.ts @@ -0,0 +1,212 @@ +// The journal of what the agent tokens wrote (#203): one line per successful +// write of an MCP tool, kept 90 days. An assistant deletes nothing and its +// changes cannot be undone: this journal is the only trace of them. A line +// holds the type and the id of the row that was touched, never its content; +// the name shown with it is read from the live row when the journal is read. +// +// No function here imports the database client: each one receives what it +// runs its queries on. recordAction runs in the transaction of the write it +// records; the purge runs in web/server.ts, which is bundled apart from the +// routes (web/Dockerfile) and has a pool of its own. For that bundle, the +// imports of this module stay relative, and none of them reaches the client. + +import { and, desc, eq, gte, isNull, lt, or, sql, type SQL } from 'drizzle-orm'; +import type { PgDatabase, PgQueryResultHKT } from 'drizzle-orm/pg-core'; +import { slAgentActions, slLists, slTags, slTasks } from '../db/schema'; +import { errorName } from './mcp/errors'; + +// What the queries run on: the database of the routes, the transaction of a +// write, or the database server.ts builds on its own pool. +export type JournalExecutor = PgDatabase>; + +export type JournalEntityType = 'task' | 'list' | 'tag'; + +// A write to record. `tokenId` is null for a caller without a token row (the +// future OAuth connection); `tokenName` is the name of the token at the time +// of the call, which the line keeps once the token is revoked. +export type JournalEntry = { + userId: string; + tokenId: string | null; + tokenName: string; + // Name of the MCP tool, one of WRITE_TOOL_NAMES (mcp/writeTools.ts). + tool: string; + entityType: JournalEntityType; + entityId: string; +}; + +// A line as the page of the assistants shows it. Neither the account nor any +// other column: a column added to the table is not returned unless it is +// named here. +export type JournalAction = { + id: string; + tool: string; + entityType: string; + entityId: string; + // Title of the task, name of the list or of the tag, read on the live row + // of the account; null when the row was deleted since, or is not there. + entityName: string | null; + // null once the token is revoked: revoking deletes the token row. + tokenId: string | null; + tokenName: string; + tokenRevoked: boolean; + createdAt: Date; +}; + +// Where a line stands in the order of listActions: its instant cut to the +// millisecond, then its id. +export type JournalCursor = { createdAt: Date; id: string }; + +export type JournalPage = { + actions: JournalAction[]; + // The last line of the page when older lines follow, null on the last page: + // pass it as `before` to read them. + nextCursor: JournalCursor | null; +}; + +// The journal is kept 90 days (DECISIONS.md, 2026-11-14), counted in hours +// from the instant of the write: 90 times 24 hours, whatever the time zone. +export const JOURNAL_RETENTION_DAYS = 90; +const DAY_MS = 24 * 60 * 60 * 1000; + +// Largest page of listActions, whatever the caller asks for. +export const JOURNAL_PAGE_MAX = 100; + +// The oldest instant the journal still shows at `now`. A line written before +// it is not returned by listActions, and purgeOldActions deletes it. +function retentionStart(now: Date): Date { + return new Date(now.getTime() - JOURNAL_RETENTION_DAYS * DAY_MS); +} + +// created_at may hold microseconds and a JavaScript Date holds milliseconds: +// the order and the cursor both use the instant cut to the millisecond, as +// queryAccountTasks does (taskQueries.ts). +const createdAtMs = sql`date_trunc('milliseconds', ${slAgentActions.createdAt})`; + +// Write the journal line of a write, in the transaction of that write: the +// line and the write are committed together, or neither is. An insert that +// fails (a token revoked since the request was authenticated no longer has +// the row `token_id` points to) throws, and the write is rolled back with it. +export async function recordAction(tx: JournalExecutor, entry: JournalEntry, now = new Date()): Promise { + await tx.insert(slAgentActions).values({ + userId: entry.userId, + tokenId: entry.tokenId, + tokenName: entry.tokenName, + tool: entry.tool, + entityType: entry.entityType, + entityId: entry.entityId, + createdAt: now, + }); +} + +// The journal lines of an account written in the last 90 days, newest first, +// by pages of `limit` lines (1 to JOURNAL_PAGE_MAX). A line older than that +// is never returned, purged or not. +// +// The name of the touched row comes from the tasks, the lists and the tags of +// the account that are not deleted: a line that points at a row of another +// account, which no tool writes, shows no name. +export async function listActions( + db: JournalExecutor, + userId: string, + page: { before?: JournalCursor | null; limit: number }, + now = new Date(), +): Promise { + const limit = Math.min(Math.max(Math.trunc(page.limit) || 1, 1), JOURNAL_PAGE_MAX); + + const conditions: (SQL | undefined)[] = [ + eq(slAgentActions.userId, userId), + gte(slAgentActions.createdAt, retentionStart(now)), + ]; + if (page.before) { + const at = sql`${page.before.createdAt.toISOString()}::timestamptz`; + conditions.push(or( + sql`${createdAtMs} < ${at}`, + and(sql`${createdAtMs} = ${at}`, lt(slAgentActions.id, page.before.id)), + )); + } + + // One row more than the page, to know whether older lines follow. Each + // join names its type: at most one of the three names is not null. + const rows = await db + .select({ + id: slAgentActions.id, + tool: slAgentActions.tool, + entityType: slAgentActions.entityType, + entityId: slAgentActions.entityId, + tokenId: slAgentActions.tokenId, + tokenName: slAgentActions.tokenName, + createdAt: slAgentActions.createdAt, + taskTitle: slTasks.title, + listName: slLists.name, + tagName: slTags.name, + }) + .from(slAgentActions) + .leftJoin(slTasks, and( + eq(slAgentActions.entityType, 'task'), + eq(slTasks.id, slAgentActions.entityId), + eq(slTasks.userId, userId), + isNull(slTasks.deletedAt), + )) + .leftJoin(slLists, and( + eq(slAgentActions.entityType, 'list'), + eq(slLists.id, slAgentActions.entityId), + eq(slLists.userId, userId), + isNull(slLists.deletedAt), + )) + .leftJoin(slTags, and( + eq(slAgentActions.entityType, 'tag'), + eq(slTags.id, slAgentActions.entityId), + eq(slTags.userId, userId), + isNull(slTags.deletedAt), + )) + .where(and(...conditions)) + .orderBy(desc(createdAtMs), desc(slAgentActions.id)) + .limit(limit + 1); + + const actions = rows.slice(0, limit).map((row): JournalAction => ({ + id: row.id, + tool: row.tool, + entityType: row.entityType, + entityId: row.entityId, + entityName: row.taskTitle ?? row.listName ?? row.tagName ?? null, + tokenId: row.tokenId, + tokenName: row.tokenName, + tokenRevoked: row.tokenId === null, + createdAt: row.createdAt, + })); + const last = actions[actions.length - 1]; + return { + actions, + nextCursor: rows.length > limit && last ? { createdAt: last.createdAt, id: last.id } : null, + }; +} + +// Delete the lines written more than 90 days before `now`, of every account, +// and return how many there were. +export async function purgeOldActions(db: JournalExecutor, now = new Date()): Promise { + const purged = await db + .delete(slAgentActions) + .where(lt(slAgentActions.createdAt, retentionStart(now))) + .returning({ id: slAgentActions.id }); + return purged.length; +} + +// Run a purge for the server (web/server.ts): log its count, and never throw. +// A purge that fails must not stop the site: only the class name of its error +// is logged (the message of a database error names the query, and may name +// the database or its user). +export async function safePurge( + purge: () => Promise, + log: (line: string) => void = console.log, +): Promise { + try { + const rows = await purge(); + log(`> Journal purge: ${rows} rows`); + } catch (error) { + try { + log(`> Journal purge failed: ${errorName(error)}`); + } catch { + // A log that throws stops nothing either. + } + } +} diff --git a/web/src/lib/mcp/server.ts b/web/src/lib/mcp/server.ts index b0b5a3c..31f6719 100644 --- a/web/src/lib/mcp/server.ts +++ b/web/src/lib/mcp/server.ts @@ -14,6 +14,7 @@ import type { AgentTokenContext, AgentTokenScope } from '@/lib/agentTokens'; import { rateLimitDelay } from '@/lib/rateLimit'; import { ToolRefusal, errorName, toolErrorBody, type ToolErrorCode } from './errors'; import { registerReadTools } from './readTools'; +import { registerWriteTools } from './writeTools'; const SERVER_NAME = 'simpl-liste'; const SERVER_VERSION = '1.0.0'; @@ -166,8 +167,10 @@ function buildServer(authInfo: AuthInfo | undefined): McpServer { }; // A read-only token sees the read tools and nothing else: a tool it may not - // call does not exist for it. + // call does not exist for it. The write tools (#203) are registered for a + // read-write token only. registerReadTools(register); + if (context.scope === 'write') registerWriteTools(register); return server; } diff --git a/web/src/lib/mcp/writeTools.ts b/web/src/lib/mcp/writeTools.ts new file mode 100644 index 0000000..5012169 --- /dev/null +++ b/web/src/lib/mcp/writeTools.ts @@ -0,0 +1,245 @@ +// The write tools of the MCP server (#203), registered for a read-write token +// only. This module validates inputs and shapes outputs: every write is a +// function of taskWrites.ts, scoped to the account of the token, and every +// task leaves through renderTask (readTools.ts). +// +// No tool removes a task, a list or a tag (DECISIONS.md, 2026-11-14), and a +// change cannot be undone: the journal (agentJournal.ts) is its only trace. +// A task that was deleted, or that belongs to another account, answers like +// one that never existed, and so do a list, a parent and a tag. + +import { z } from 'zod'; +import { db } from '@/db/client'; +import { recordAction, type JournalEntityType } from '@/lib/agentJournal'; +import { RECURRENCES } from '@/lib/recurrence'; +import type { Tx } from '@/lib/taskDelete'; +import { completeTask, createTask, reopenTask, setTaskTags, updateTask, type TaskRow } from '@/lib/taskWrites'; +import { dueDateSchema } from '@/lib/validators'; +import { notifyUserChanged } from '@/lib/ws'; +import { ToolRefusal } from './errors'; +import { renderTask } from './readTools'; +import type { RegisterTool, ToolContext } from './server'; + +// The names of the write tools: what the journal holds in its `tool` column. +// A tool registered through registerWriteTool has its name here. +export const WRITE_TOOL_NAMES = [ + 'create_task', + 'update_task', + 'complete_task', + 'reopen_task', + 'set_task_tags', +] as const; + +export type WriteToolName = (typeof WRITE_TOOL_NAMES)[number]; + +// What a write did: whether it wrote anything, the row it touched (for the +// journal), and what the tool renders its answer from once the transaction +// has committed. +export type WriteOutcome = { + changed: boolean; + entityType: JournalEntityType; + entityId: string; + value: Value; +}; + +// A write tool, as registerWriteTool takes it. +export type WriteToolDefinition = { + name: WriteToolName; + description: string; + inputSchema: Schema; + // readOnlyHint and openWorldHint are the same for every write tool. + annotations: { destructiveHint: boolean; idempotentHint?: boolean }; + // Runs in the transaction of the envelope, and queries through `tx` only. + // It refuses by throwing (a WriteRefusal of taskWrites.ts, or a ToolRefusal): + // the transaction is rolled back, and nothing is journaled nor notified. + write: (tx: Tx, input: z.output, context: ToolContext) => Promise>; + // Runs after the commit, outside the transaction: the answer of the tool. + render: (value: Value, context: ToolContext) => Promise>; +}; + +// The envelope of every write tool, inside the envelope of every tool +// (server.ts), which has already counted the call in `mcp-write`: +// 1. one transaction: the write, then its journal line when it changed +// something. The line and the write are committed together, or neither +// is: a journal insert that fails takes the write back; +// 2. after the commit, one notification, so that an open page or the app +// that reloads on it finds what was written; +// 3. the answer, read from the committed rows. A read that fails here +// answers `internal_error` for a write that is kept, and that its +// journal line shows. +// A call that changes nothing (`changed: false`) writes no journal line and +// notifies nobody. +export function registerWriteTool( + register: RegisterTool, + tool: WriteToolDefinition, +): void { + register({ + name: tool.name, + description: tool.description, + inputSchema: tool.inputSchema, + annotations: { readOnlyHint: false, openWorldHint: false, ...tool.annotations }, + limit: 'mcp-write', + run: async (input, context) => { + const outcome = await db.transaction(async (tx) => { + const written = await tool.write(tx, input, context); + if (written.changed) { + await recordAction(tx, { + userId: context.userId, + tokenId: context.tokenId, + tokenName: context.tokenName, + tool: tool.name, + entityType: written.entityType, + entityId: written.entityId, + }); + } + return written; + }); + if (outcome.changed) notifyUserChanged(context.userId); + return tool.render(outcome.value, context); + }, + }); +} + +// What taskWrites.ts answers for a task that is unknown, deleted or of +// another account: the three read the same. +function found(result: Result | null): Result { + if (result === null) throw new ToolRefusal('not_found'); + return result; +} + +// The journal line of a write on a task. +function onTask(result: Value): WriteOutcome { + return { changed: result.changed, entityType: 'task', entityId: result.task.id, value: result }; +} + +// `tag_ids` holds at most 20 ids, as the tag filter of list_tasks. With the +// other arguments, the largest call (create_task: 8 keys and 20 ids) stays +// below `maxToolInputElements` (server.ts), which bounds a hostile array +// before zod reads its elements. +const TAG_IDS_MAX = 20; + +const DUE_DATE_FORMATS = 'YYYY-MM-DD for a day (stored at 12:00 UTC of that day), or an ISO 8601 date-time with a UTC offset for a precise time'; + +const taskId = z.string().uuid().describe('Id of the task, top-level or subtask.'); +const title = z.string().min(1).max(500); +// 5 000 characters, as the REST API; the app allows 10 000. +const notes = z.string().max(5000); +const priority = z.number().int().min(0).max(3); +const recurrence = z.enum(RECURRENCES); +const tagIds = z.array(z.string().uuid()).max(TAG_IDS_MAX); + +const createTaskInput = z.object({ + title: title.describe('Title of the task, 1 to 500 characters.'), + list_id: z.string().uuid().optional() + .describe('List the task is created in. Without it, the task goes to the Inbox. Ignored when parent_id is given.'), + parent_id: z.string().uuid().optional() + .describe('Id of a top-level task: the new task becomes its subtask, in the list of that task. A subtask cannot have subtasks.'), + notes: notes.optional().describe('Notes of the task, 5000 characters at most.'), + priority: priority.optional().describe('0 none (default), 1 low, 2 medium, 3 high.'), + due_date: dueDateSchema.optional().describe(`Due date: ${DUE_DATE_FORMATS}.`), + recurrence: recurrence.optional() + .describe('How often the task comes back. A recurring task that has a due date gets its next occurrence when it is completed.'), + tag_ids: tagIds.optional().describe('Ids of the tags to put on the task, 20 at most.'), +}).strict(); + +const UPDATE_FIELDS = ['title', 'notes', 'priority', 'due_date', 'recurrence', 'list_id'] as const; + +const updateTaskInput = z.object({ + task_id: taskId, + title: title.optional().describe('New title, 1 to 500 characters.'), + notes: notes.nullable().optional().describe('New notes, 5000 characters at most; null removes them.'), + priority: priority.optional().describe('New priority: 0 none, 1 low, 2 medium, 3 high.'), + due_date: dueDateSchema.nullable().optional().describe(`New due date: ${DUE_DATE_FORMATS}; null removes it.`), + recurrence: recurrence.nullable().optional().describe('New recurrence; null makes the task stop coming back.'), + list_id: z.string().uuid().optional() + .describe('List to move the task to: it goes to the end of that list, with its subtasks. A subtask cannot be moved.'), +}).strict().refine( + (input) => UPDATE_FIELDS.some((field) => input[field] !== undefined), + { message: `Nothing to change: pass at least one of ${UPDATE_FIELDS.join(', ')}.` }, +); + +const taskInput = z.object({ task_id: taskId }).strict(); + +const setTaskTagsInput = z.object({ + task_id: taskId, + tag_ids: tagIds.describe('Ids of the tags the task must have, 20 at most. An empty list removes every tag.'), +}).strict(); + +export function registerWriteTools(register: RegisterTool): void { + // Adds a task: nothing existing is changed. + registerWriteTool(register, { + name: 'create_task', + description: 'Creates a task and returns it. Without list_id the task goes to the Inbox; with parent_id it becomes a subtask of that task. The task is placed at the end of its list, or of the subtasks of its parent.', + inputSchema: createTaskInput, + annotations: { destructiveHint: false }, + write: async (tx, input, { userId }) => onTask(await createTask(tx, userId, { + title: input.title, + listId: input.list_id, + parentId: input.parent_id, + notes: input.notes, + priority: input.priority, + dueDate: input.due_date, + recurrence: input.recurrence, + tagIds: input.tag_ids, + })), + render: async ({ task }, { userId }) => ({ task: await renderTask(userId, task) }), + }); + + // Overwrites values: the previous ones are lost. Calling it again with the + // same arguments leaves the task as it is. + registerWriteTool(register, { + name: 'update_task', + description: 'Changes a task and returns it. Only the fields passed are changed; null removes the notes, the due date or the recurrence. list_id moves a top-level task to the end of another list, with its subtasks. The previous values are not kept: a change cannot be undone. To complete or reopen a task, use complete_task or reopen_task; to change its tags, set_task_tags.', + inputSchema: updateTaskInput, + annotations: { destructiveHint: true, idempotentHint: true }, + write: async (tx, input, { userId }) => onTask(found(await updateTask(tx, userId, input.task_id, { + title: input.title, + notes: input.notes, + priority: input.priority, + dueDate: input.due_date, + recurrence: input.recurrence, + listId: input.list_id, + }))), + render: async ({ task }, { userId }) => ({ task: await renderTask(userId, task) }), + }); + + registerWriteTool(register, { + name: 'complete_task', + description: 'Marks a task as completed and returns it. A recurring task that has a due date gets its next occurrence, a new task returned in next_occurrence (null for any other task). When the task was already completed, nothing happens and changed is false.', + inputSchema: taskInput, + annotations: { destructiveHint: false, idempotentHint: true }, + // One journal line, for the task that was completed: its next occurrence + // has none. + write: async (tx, input, { userId }) => onTask(found(await completeTask(tx, userId, input.task_id))), + render: async (result, { userId }) => ({ + task: await renderTask(userId, result.task), + next_occurrence: result.changed && result.next ? await renderTask(userId, result.next) : null, + changed: result.changed, + }), + }); + + registerWriteTool(register, { + name: 'reopen_task', + description: 'Marks a completed task as not completed and returns it. The next occurrence that completing a recurring task created stays. When the task was not completed, nothing happens and changed is false.', + inputSchema: taskInput, + annotations: { destructiveHint: false, idempotentHint: true }, + write: async (tx, input, { userId }) => onTask(found(await reopenTask(tx, userId, input.task_id))), + render: async (result, { userId }) => ({ + task: await renderTask(userId, result.task), + changed: result.changed, + }), + }); + + // Overwrites the set of tags: a tag that is not listed leaves the task. + registerWriteTool(register, { + name: 'set_task_tags', + description: 'Replaces the tags of a task by the given ones and returns the task: a tag that is not in tag_ids is taken off the task (the tag itself stays), and an empty list takes them all off. When the task already has exactly these tags, nothing happens and changed is false.', + inputSchema: setTaskTagsInput, + annotations: { destructiveHint: true, idempotentHint: true }, + write: async (tx, input, { userId }) => onTask(found(await setTaskTags(tx, userId, input.task_id, input.tag_ids))), + render: async (result, { userId }) => ({ + task: await renderTask(userId, result.task), + changed: result.changed, + }), + }); +} diff --git a/web/src/lib/taskWrites.test.ts b/web/src/lib/taskWrites.test.ts new file mode 100644 index 0000000..59191b1 --- /dev/null +++ b/web/src/lib/taskWrites.test.ts @@ -0,0 +1,553 @@ +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)]; + // Twice the same id, and the same id in both letter cases: one tag each. + const { task } = await create(A.userId, { title: 'Tagged', tagIds: [red, blue.toUpperCase(), red, blue] }); + 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, red]]) { + 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 }; +}