diff --git a/backend/__tests__/service/agentRunContentWindow.test.js b/backend/__tests__/service/agentRunContentWindow.test.js new file mode 100644 index 0000000000..f2d69a30f5 --- /dev/null +++ b/backend/__tests__/service/agentRunContentWindow.test.js @@ -0,0 +1,161 @@ +/** + * F84 — AgentRun content window. Real Mongo (tier 1): the redaction is an + * aggregation-pipeline update, which an in-process fake can't evaluate. + * + * After 30 days a run loses the model's text, each tool call's args, result + * and error, and its own errorMessage. The row and its metadata stay; nothing + * is deleted; a dry run changes nothing. + */ +const mongoose = require('mongoose'); + +const { setupMongoDb, closeMongoDb } = require('../utils/testUtils'); + +const AgentRun = require('../../models/AgentRun'); +const { redactExpiredRunContent, RUN_CONTENT_WINDOW_DAYS } = require('../../services/agentRunContentWindow'); + +jest.setTimeout(60_000); + +const DAY = 24 * 60 * 60 * 1000; +const NOW = new Date('2026-11-04T04:23:00Z'); +const daysAgo = (d) => new Date(NOW.getTime() - d * DAY); + +const runAt = (startedAt, extra = {}) => ({ + podId: new mongoose.Types.ObjectId(), + agentName: 'scout', + instanceId: 'default', + trigger: 'mention', + status: 'failed', + errorKind: 'tool_error', + errorMessage: 'calendar_list_events failed: Dentist at 3pm', + totalTokens: 1200, + startedAt, + turns: [ + { + turnIndex: 0, + model: 'deepseek-chat', + servedModel: 'deepseek-chat', + totalTokens: 1200, + elapsedMs: 900, + llmResponseText: 'Your 3pm with the dentist moved to Friday.', + toolCalls: [ + { + name: 'calendar_list_events', + args: { calendarId: 'primary' }, + result: { items: [{ summary: 'Dentist' }] }, + error: 'upstream echoed: Dentist', + elapsedMs: 300, + }, + { name: 'commonly_post_message', callId: 'call-1', outcome: 'ok', elapsedMs: 40 }, + ], + }, + { turnIndex: 1, model: 'deepseek-chat', elapsedMs: 100 }, + ], + ...extra, +}); + +describe('AgentRun content window', () => { + beforeAll(async () => { await setupMongoDb(); }); + afterAll(async () => { await closeMongoDb(); }); + beforeEach(async () => { await AgentRun.deleteMany({}); }); + + test('the window is 30 days', () => { + expect(RUN_CONTENT_WINDOW_DAYS).toBe(30); + }); + + test('a dry run counts the expired runs and changes nothing', async () => { + await AgentRun.create([runAt(daysAgo(45)), runAt(daysAgo(31)), runAt(daysAgo(29))]); + + const report = await redactExpiredRunContent({ now: NOW }); + + expect(report).toMatchObject({ matched: 2, redacted: 0 }); + expect(report.cutoff.toISOString()).toBe(daysAgo(30).toISOString()); + const withText = await AgentRun.countDocuments({ 'turns.llmResponseText': { $exists: true } }); + expect(withText).toBe(3); + }); + + test('an expired run loses its text, tool args/results/errors and errorMessage, and keeps everything else', async () => { + const [old] = await AgentRun.create([runAt(daysAgo(45))]); + + const report = await redactExpiredRunContent({ apply: true, now: NOW }); + expect(report).toMatchObject({ matched: 1, redacted: 1 }); + + const row = await AgentRun.collection.findOne({ _id: old._id }); + expect(row.contentRedactedAt.toISOString()).toBe(NOW.toISOString()); + expect(row.turns[0]).not.toHaveProperty('llmResponseText'); + expect(row.turns[0].toolCalls[0]).not.toHaveProperty('args'); + expect(row.turns[0].toolCalls[0]).not.toHaveProperty('result'); + expect(row.turns[0].toolCalls[0]).not.toHaveProperty('error'); + expect(row).not.toHaveProperty('errorMessage'); + expect(JSON.stringify(row)).not.toMatch(/Dentist|dentist|primary/); + + // Metadata stays: what proof of life, activity, traces and spend read. + expect(row).toMatchObject({ + agentName: 'scout', trigger: 'mention', status: 'failed', errorKind: 'tool_error', totalTokens: 1200, + }); + expect(row.startedAt.toISOString()).toBe(daysAgo(45).toISOString()); + expect(row.turns).toHaveLength(2); + expect(row.turns[0]).toMatchObject({ + turnIndex: 0, model: 'deepseek-chat', servedModel: 'deepseek-chat', totalTokens: 1200, elapsedMs: 900, + }); + expect(row.turns[0].toolCalls).toEqual([ + { name: 'calendar_list_events', elapsedMs: 300 }, + { name: 'commonly_post_message', callId: 'call-1', outcome: 'ok', elapsedMs: 40 }, + ]); + expect(row.turns[1]).toMatchObject({ turnIndex: 1, model: 'deepseek-chat', toolCalls: [] }); + }); + + test('runs inside the window are untouched and no row is deleted', async () => { + const [, recent] = await AgentRun.create([runAt(daysAgo(60)), runAt(daysAgo(29))]); + + await redactExpiredRunContent({ apply: true, now: NOW }); + + expect(await AgentRun.countDocuments({})).toBe(2); + const row = await AgentRun.collection.findOne({ _id: recent._id }); + expect(row).not.toHaveProperty('contentRedactedAt'); + expect(row.turns[0].llmResponseText).toBe('Your 3pm with the dentist moved to Friday.'); + expect(row.turns[0].toolCalls[0].result).toEqual({ items: [{ summary: 'Dentist' }] }); + expect(row.turns[0].toolCalls[0].error).toBe('upstream echoed: Dentist'); + expect(row.errorMessage).toBe('calendar_list_events failed: Dentist at 3pm'); + }); + + test('a run exactly at the cutoff keeps its content; one millisecond older loses it', async () => { + const [atCutoff, justExpired] = await AgentRun.create([ + runAt(daysAgo(30)), + runAt(new Date(daysAgo(30).getTime() - 1)), + ]); + + const report = await redactExpiredRunContent({ apply: true, now: NOW }); + expect(report).toMatchObject({ matched: 1, redacted: 1 }); + + const kept = await AgentRun.collection.findOne({ _id: atCutoff._id }); + expect(kept).not.toHaveProperty('contentRedactedAt'); + expect(kept.turns[0].toolCalls[0].error).toBe('upstream echoed: Dentist'); + expect(kept.errorMessage).toBe('calendar_list_events failed: Dentist at 3pm'); + + const expired = await AgentRun.collection.findOne({ _id: justExpired._id }); + expect(expired).not.toHaveProperty('errorMessage'); + expect(expired.turns[0].toolCalls[0]).not.toHaveProperty('error'); + }); + + test('a second pass finds nothing left to redact', async () => { + await AgentRun.create([runAt(daysAgo(45))]); + await redactExpiredRunContent({ apply: true, now: NOW }); + + const again = await redactExpiredRunContent({ apply: true, now: new Date(NOW.getTime() + DAY) }); + + expect(again).toMatchObject({ matched: 0, redacted: 0 }); + }); + + test('an old row with no turns array is stamped without an error', async () => { + const { insertedId } = await AgentRun.collection.insertOne({ + podId: new mongoose.Types.ObjectId(), agentName: 'scout', trigger: 'heartbeat', startedAt: daysAgo(90), + }); + + const report = await redactExpiredRunContent({ apply: true, now: NOW }); + + expect(report).toMatchObject({ matched: 1, redacted: 1 }); + const row = await AgentRun.collection.findOne({ _id: insertedId }); + expect(row.turns).toEqual([]); + expect(row.contentRedactedAt).toBeInstanceOf(Date); + }); +}); diff --git a/backend/__tests__/unit/services/schedulerService.runContentWindow.test.js b/backend/__tests__/unit/services/schedulerService.runContentWindow.test.js new file mode 100644 index 0000000000..2b683f3542 --- /dev/null +++ b/backend/__tests__/unit/services/schedulerService.runContentWindow.test.js @@ -0,0 +1,69 @@ +// The run content window unsets stored run content, so the scheduler may only +// register it once the deployment opts in with exactly AGENT_RUN_CONTENT_WINDOW=true +// (after a dry run has counted what it would redact). +jest.mock('node-cron', () => ({ + schedule: jest.fn((expression, task, options) => ({ + expression, task, options, start: jest.fn(), stop: jest.fn(), + })), +})); +jest.mock('../../../services/agentRunContentWindow', () => ({ + redactExpiredRunContent: jest.fn(async () => ({ cutoff: new Date(0), matched: 0, redacted: 0 })), +})); + +const cron = require('node-cron'); +const scheduler = require('../../../services/schedulerService'); + +const WINDOW_SCHEDULE = '23 4 * * *'; +const windowJobs = () => cron.schedule.mock.results + .map((r) => r.value) + .filter((job) => job.expression === WINDOW_SCHEDULE); +const windowJobStarted = () => windowJobs().some((job) => job.start.mock.calls.length > 0); + +describe('scheduler: run content window opt-in', () => { + const original = process.env.AGENT_RUN_CONTENT_WINDOW; + afterEach(() => { + scheduler.stop(); + cron.schedule.mockClear(); + if (original === undefined) delete process.env.AGENT_RUN_CONTENT_WINDOW; + else process.env.AGENT_RUN_CONTENT_WINDOW = original; + }); + + it.each([undefined, 'false', 'TRUE', '1'])('does not start the window job when the flag is %p', (value) => { + if (value === undefined) delete process.env.AGENT_RUN_CONTENT_WINDOW; + else process.env.AGENT_RUN_CONTENT_WINDOW = value; + scheduler.start(); + expect(windowJobStarted()).toBe(false); + }); + + it('starts the window job only when the flag is exactly "true"', () => { + process.env.AGENT_RUN_CONTENT_WINDOW = 'true'; + scheduler.start(); + expect(windowJobStarted()).toBe(true); + }); + + // node-cron starts a task at creation unless it is told not to, which would + // run the job with the flag unset no matter what start() registers. + it('creates the window job stopped', () => { + delete process.env.AGENT_RUN_CONTENT_WINDOW; + scheduler.start(); + expect(windowJobs()).toHaveLength(1); + expect(windowJobs()[0].options).toMatchObject({ scheduled: false }); + }); + + it('the job applies the redaction, not a dry run', async () => { + const { redactExpiredRunContent } = require('../../../services/agentRunContentWindow'); + redactExpiredRunContent.mockClear(); + const log = jest.spyOn(console, 'log').mockImplementation(() => {}); + try { + process.env.AGENT_RUN_CONTENT_WINDOW = 'true'; + scheduler.start(); + // Starting the scheduler (a deploy) must not redact; only the cron tick does. + expect(redactExpiredRunContent).not.toHaveBeenCalled(); + await windowJobs()[0].task(); + expect(redactExpiredRunContent).toHaveBeenCalledTimes(1); + expect(redactExpiredRunContent).toHaveBeenCalledWith({ apply: true }); + } finally { + log.mockRestore(); + } + }); +}); diff --git a/backend/models/AgentRun.ts b/backend/models/AgentRun.ts index 7ef6ea60dd..c1ed237f2c 100644 --- a/backend/models/AgentRun.ts +++ b/backend/models/AgentRun.ts @@ -111,6 +111,7 @@ export interface IAgentRun extends Document { completedAt?: Date; errorKind?: AgentRunErrorKind; errorMessage?: string; + contentRedactedAt?: Date; createdAt: Date; updatedAt: Date; } @@ -179,6 +180,9 @@ const AgentRunSchema = new Schema( enum: ['turn_cap', 'token_cap', 'timeout', 'tool_error', 'llm_error', 'guardrail_blocked', 'config', 'unknown'], }, errorMessage: { type: String }, + // Set when the content window unset this run's text and tool args/results + // (services/agentRunContentWindow.ts). + contentRedactedAt: { type: Date }, }, { timestamps: true }, ); diff --git a/backend/services/agentRunContentWindow.ts b/backend/services/agentRunContentWindow.ts new file mode 100644 index 0000000000..59334ad7c9 --- /dev/null +++ b/backend/services/agentRunContentWindow.ts @@ -0,0 +1,77 @@ +/** + * AgentRun content window (F84, ruled 2026-11-04). + * + * A run stores the model's text, each tool call's args, result and error, + * and its own errorMessage, any of which can carry connector data (a calendar + * event, an issue body, an exception that echoed either). Nothing in the + * product reads any of them back: every AgentRun reader selects metadata only. + * So after RUN_CONTENT_WINDOW_DAYS they are unset and the + * row stays, with its status, errorKind, trigger, tokens, timings, models and + * tool names, so proof of life, recent activity, traces and spend history are + * unchanged. No row is deleted. + */ +import AgentRun from '../models/AgentRun'; + +export const RUN_CONTENT_WINDOW_DAYS = 30; +const DAY_MS = 24 * 60 * 60 * 1000; + +// Drop `keys` from an embedded object. Aggregation, so a turn or tool call +// missing the field (or the array) is handled without a per-row path error. +const without = (input: string, keys: string[]) => ({ + $arrayToObject: { + $filter: { + input: { $objectToArray: input }, + as: 'kv', + cond: { $not: [{ $in: ['$$kv.k', keys] }] }, + }, + }, +}); + +export interface RunContentWindowReport { + cutoff: Date; + matched: number; + redacted: number; +} + +/** + * Unset the content of runs started before the window. `apply: false` (the + * default) only counts what it would redact. + */ +export const redactExpiredRunContent = async ( + { apply = false, now = new Date() }: { apply?: boolean; now?: Date } = {}, +): Promise => { + const cutoff = new Date(now.getTime() - RUN_CONTENT_WINDOW_DAYS * DAY_MS); + const filter = { startedAt: { $lt: cutoff }, contentRedactedAt: { $exists: false } }; + const matched = await AgentRun.countDocuments(filter); + if (!apply || matched === 0) return { cutoff, matched, redacted: 0 }; + + const result = await AgentRun.collection.updateMany(filter, [ + { + $set: { + turns: { + $map: { + input: { $ifNull: ['$turns', []] }, + as: 'turn', + in: { + $mergeObjects: [ + without('$$turn', ['llmResponseText', 'toolCalls']), + { + toolCalls: { + $map: { + input: { $ifNull: ['$$turn.toolCalls', []] }, + as: 'call', + in: without('$$call', ['args', 'result', 'error']), + }, + }, + }, + ], + }, + }, + }, + contentRedactedAt: now, + }, + }, + { $unset: 'errorMessage' }, + ]); + return { cutoff, matched, redacted: result.modifiedCount }; +}; diff --git a/backend/services/schedulerService.ts b/backend/services/schedulerService.ts index e4afa16c1a..530c64e470 100644 --- a/backend/services/schedulerService.ts +++ b/backend/services/schedulerService.ts @@ -657,6 +657,24 @@ class SchedulerService { { scheduled: false, timezone: 'UTC' }, ); + // F84: unset run text and tool args/results after 30 days; rows stay + // (services/agentRunContentWindow.ts). Off unless the deployment opts in. + const runContentWindowJob: CronJob = cron.schedule( + '23 4 * * *', + async () => { + try { + // eslint-disable-next-line global-require, @typescript-eslint/no-require-imports + const { redactExpiredRunContent } = require('./agentRunContentWindow'); + const report = await redactExpiredRunContent({ apply: true }); + console.log(`[run-content] redacted=${report.redacted} matched=${report.matched} ` + + `cutoff=${report.cutoff.toISOString()}`); + } catch (error) { + console.error('[run-content] redaction failed:', error); + } + }, + { scheduled: false, timezone: 'UTC' }, + ); + this.jobs = [ summarizerJob, externalFeedJob, @@ -683,6 +701,7 @@ class SchedulerService { accountDeletionUploadJob, spendAlarmJob, ...(process.env.SYNTHETIC_ACCOUNT_PURGE === 'true' ? [syntheticAccountPurgeJob] : []), + ...(process.env.AGENT_RUN_CONTENT_WINDOW === 'true' ? [runContentWindowJob] : []), ]; this.jobs.forEach((job) => job.start()); this.isRunning = true;