From 797b6c608ca42124b43672eda5809dc333ec0019 Mon Sep 17 00:00:00 2001 From: le king fu Date: Sun, 15 Nov 2026 12:25:28 -0500 Subject: [PATCH] feat(web): agent action journal and its purge at server start (#203) agentJournal.ts: recordAction (in the transaction of the write it records), listActions (lines of the account of the last 90 days, newest first, by pages, with the name of the row each line touched read on the live row of the account, and tokenRevoked for a deleted token), purgeOldActions (lines older than 90 days) and safePurge (logs the count, never throws, logs only the class name of an error). No function imports the database client: each one receives what it runs on, so that web/server.ts can call the purge from its own bundle. web/server.ts: once the migrations are done, and outside their try block, a purge on a pool of its own (max: 1), then one every 24 hours on a timer that does not hold the process. A purge that fails never stops the server. Co-Authored-By: Claude Fable 5.2 --- web/server.ts | 29 +++ web/src/lib/agentJournal.test.ts | 421 +++++++++++++++++++++++++++++++ web/src/lib/agentJournal.ts | 212 ++++++++++++++++ 3 files changed, 662 insertions(+) create mode 100644 web/src/lib/agentJournal.test.ts create mode 100644 web/src/lib/agentJournal.ts 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/lib/agentJournal.test.ts b/web/src/lib/agentJournal.test.ts new file mode 100644 index 0000000..a03bef8 --- /dev/null +++ b/web/src/lib/agentJournal.test.ts @@ -0,0 +1,421 @@ +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. + const empty = drizzle(new PGlite()); + await expect(safePurge(() => purgeOldActions(empty, NOW), log)).resolves.toBeUndefined(); + 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. + } + } +}