Skip to content

fix(webapp): dashboard agent maintenance moves into the agent project - #4599

Open
kathiekiwi wants to merge 10 commits into
mainfrom
feature/tri-13182-move-dashboard-agent-maintenance
Open

fix(webapp): dashboard agent maintenance moves into the agent project#4599
kathiekiwi wants to merge 10 commits into
mainfrom
feature/tri-13182-move-dashboard-agent-maintenance

Conversation

@kathiekiwi

@kathiekiwi kathiekiwi commented Aug 13, 2026

Copy link
Copy Markdown
Collaborator

What & why

The dashboard agent's upkeep — retention deletes and the investigation sweep — ran as cron jobs on the webapp's common worker, even though it only touches the agent's own datastore. This moves that upkeep into the agent's Trigger project as scheduled tasks (TRI-13182).

What's inside

Retentioninternal-packages/dashboard-agent/src/maintenance.ts, a daily task (03:00 UTC). Deletes turn evals older than 30 days, hard-deletes chats soft-deleted more than 30 days ago, and purges terminal watches and submission rows older than 7 days. It used to run every 5 minutes; nothing needs a hard delete that fast, so it is daily now, draining in bounded batches and warning if it hits the cap. It retries (3 attempts) because the next run is a day away. It connects with DASHBOARD_AGENT_DATABASE_URL, falling back to DATABASE_URL like every other task in the package (the deletes are confined to the agent's own Postgres schema), and skips when neither is set.

Investigation sweepsrc/investigation-sweep.ts, every 5 minutes, same as before: settles investigation cards stuck in_progress (30-minute window, attempt cap, force-abandon note). It keeps the fast cadence because it fixes live state the UI is showing.

What stays in the webapp. The watch finalize/deliver sweep and batch rearm: they cover a dead agent-side tick chain — a backstop can't live inside the thing it backstops — and they need the main database and the alerts worker. The org-deletion chat purge also stays: deletion must not depend on the agent project being deployed. The removed cron job keeps a cron-less tombstone entry so already-queued items drain cleanly; remove it in a follow-up.

Test plumbing — the drizzle migration replayer that webapp tests hand-rolled is now exported once from @internal/dashboard-agent-db/testing; the moved tests live in the agent package as src/*.test.ts against real Postgres.

Testing

Agent package: retention passes (backlog drain, batch cap, no-op guard, chat-delete cascade) and the sweep, on testcontainers Postgres. Webapp: the watch/chat suites, plus a test that a settlement card stops the dashboard spinner. Full typecheck on both.

Drop the eval retention, soft-deleted-chat retention and investigation
sweeps, plus the retention half of the watch sweep. They now run in the
agent trigger project. Watch finalize/deliver, batch re-arm and the org
purge stay.
Tests hand-rolled the drizzle migration replay against a testcontainers
Postgres. Export it once from the package as `@internal/dashboard-agent-db/testing`,
taking whatever client the suite already has.
Two scheduled tasks, the project's first crons:

- `dashboard-agent-maintenance` (daily, 03:00) is retention: judged turns
  and soft-deleted chats past 30 days, terminal watches and their
  submission ledger past 7 days. Each pass drains in bounded batches, so
  a backlog doesn't wait a day per batch, and a failing pass is reported
  at the end instead of masking the others.
- `dashboard-agent-investigation-sweep` (every 5 min) settles cards left
  `in_progress` past 30 minutes, force-abandoning a poison row past the
  attempt cap.

The two differ on purpose in how they find their database. Retention
reads only `DASHBOARD_AGENT_DATABASE_URL` and no-ops when it is unset: a
delete sweep must never guess which database it deletes from. The
investigation sweep deletes nothing, so it reuses the project's existing
`getWatchDb()`, which still falls back to `DATABASE_URL`.

The org-deletion purge stays in the webapp.
Keep a cron-less catalog entry with a no-op handler so the queued items
left behind ack instead of logging a missing schema every run. Also
restore the settlement-card coupling test and trim the release note.
…atch cap

Ports the hard-delete cascade test back from the webapp suite, logs when a
retention pass ends on a full batch, and drops the unused exports.
@changeset-bot

changeset-bot Bot commented Aug 13, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: 34e9e29

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@coderabbitai

coderabbitai Bot commented Aug 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro Plus

Run ID: 1794933d-3290-4bc4-8191-497986f1a4a5

📥 Commits

Reviewing files that changed from the base of the PR and between 758ff35 and 34e9e29.

📒 Files selected for processing (6)
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/README.md
  • internal-packages/dashboard-agent/src/investigation-sweep.test.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/watch-task-adapters.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • internal-packages/dashboard-agent/src/watch-task-adapters.ts
  • internal-packages/dashboard-agent/GUIDEBOOK.md
  • internal-packages/dashboard-agent/src/investigation-sweep.test.ts
📜 Recent review details
⏰ Context from checks skipped due to timeout. (34)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (10, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (2, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (9, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (8, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (11, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (7, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (12, 12)
  • GitHub Check: sdk-compat / Node.js 22.23 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (3, 12)
  • GitHub Check: sdk-compat / Bun Runtime
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (4, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (6, 12)
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (1, 12)
  • GitHub Check: sdk-compat / Node.js 26.4 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Cloudflare Workers
  • GitHub Check: webapp / 🧪 Unit Tests: Webapp (5, 12)
  • GitHub Check: obsmap / 🧪 Unit Tests: Observability Map
  • GitHub Check: sdk-compat / Node.js 24.18 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Node.js 20.20 (warp-ubuntu-latest-x64-4x)
  • GitHub Check: sdk-compat / Deno Runtime
  • GitHub Check: e2e-webapp / 🧪 E2E Tests: Webapp
  • GitHub Check: packages / 🧪 Unit Tests: Packages (1, 3)
  • GitHub Check: packages / 🧪 Unit Tests: Packages (2, 3)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - npm)
  • GitHub Check: runops-guard / runops-guard
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - npm)
  • GitHub Check: typecheck / typecheck
  • GitHub Check: packages / 🧪 Unit Tests: Packages (3, 3)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-windows-latest-x64-8x - pnpm)
  • GitHub Check: e2e / 🧪 CLI v3 tests (warp-ubuntu-latest-x64-4x - pnpm)
  • GitHub Check: code-quality / code-quality
  • GitHub Check: audit
  • GitHub Check: audit
  • GitHub Check: Analyze (javascript-typescript)
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

**/*.{ts,tsx}: Use types over interfaces for TypeScript
Avoid using enums; prefer string unions or const objects instead

**/*.{ts,tsx}: Prefer static imports over dynamic import(); use dynamic imports only for unresolvable circular dependencies, genuine performance code splitting, or conditional runtime loading.
Import Trigger.dev tasks from @trigger.dev/sdk; never use @trigger.dev/sdk/v3 or deprecated client.defineJob.
Add agentcrumbs while writing code using approved namespaces; mark lines with // @Crumbs or blocks with `// `#region` `@crumbs, and strip them before merging.

Files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use function declarations instead of default exports

Files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
**/*.ts

📄 CodeRabbit inference engine (.cursor/rules/otel-metrics.mdc)

**/*.ts: When creating or editing OTEL metrics (counters, histograms, gauges), ensure metric attributes have low cardinality by using only enums, booleans, bounded error codes, or bounded shard IDs
Do not use high-cardinality attributes in OTEL metrics such as UUIDs/IDs (envId, userId, runId, projectId, organizationId), unbounded integers (itemCount, batchSize, retryCount), timestamps (createdAt, startTime), or free-form strings (errorMessage, taskName, queueName)
When exporting OTEL metrics via OTLP to Prometheus, be aware that the exporter automatically adds unit suffixes to metric names (e.g., 'my_duration_ms' becomes 'my_duration_ms_milliseconds', 'my_counter' becomes 'my_counter_total'). Account for these transformations when writing Grafana dashboards or Prometheus queries

Files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
internal-packages/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

For internal packages, use typecheck for verification and never use build as the correctness check.

Files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
**/*.{test,spec}.{ts,tsx}

📄 CodeRabbit inference engine (.github/copilot-instructions.md)

Use vitest for all tests in the Trigger.dev repository

**/*.{test,spec}.{ts,tsx}: Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.
Place test files next to the source files they test.

Files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
🧠 Learnings (53)
📓 Common learnings
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4418
File: apps/webapp/app/v3/commonWorker.server.ts:151-160
Timestamp: 2026-08-08T08:29:21.685Z
Learning: In the dashboard-agent maintenance flow, `sweepDashboardAgentInvestigations` in `apps/webapp/app/services/dashboardAgentInvestigationSweep.server.ts` processes at most 100 stale investigations per run. `settleInvestigationAndCloseCard` in `internal-packages/dashboard-agent-db/src/queries.ts` conditionally updates only investigations whose JSONB `state.outcome` remains `"in_progress"` and atomically appends the closing transcript card. Concurrent or redelivered sweeps cannot double-settle a row; later writers receive `null` and count the row as `alreadySettled`.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: internal-packages/dashboard-agent-db/src/watch-queries.ts:794-808
Timestamp: 2026-08-12T07:30:37.802Z
Learning: In triggerdotdev/trigger.dev dashboard-agent watches, `softDeleteChatsForOrganization()` does not serialize with `createWatch()` through the per-chat advisory lock. A create-versus-organization-delete race can temporarily leave an active watch on a deleted chat. This behavior existed before the Watch feature and is accepted as a bounded, rare administrative-path condition: the next watch tick calls `authorizeWatchEnvironment`, cancels the watch with `access_lost` after organization deletion, and chat hard deletion removes residual watch rows. Per-chat or organization-level locking and a concurrent regression test belong to the dedicated organization-deletion durability follow-up.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4516
File: apps/webapp/app/services/dashboardAgentQuota.server.ts:36-89
Timestamp: 2026-08-12T08:49:18.799Z
Learning: For dashboard agent message quotas in `apps/webapp/app/services/dashboardAgentQuota.server.ts`, production currently resolves to the `UNLIMITED_AGENT_MESSAGES` sentinel because cloud billing does not yet provide a finite `agentMessages` limit. The check-then-increment race is accepted during this fail-open rollout. TRI-12863 P0 will introduce finite limits and must implement atomic, idempotent quota reservation and settlement with concurrent-send and redelivery coverage.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts:159-169
Timestamp: 2026-08-08T08:30:57.294Z
Learning: For dashboard-agent watch checks, the single-watch lifecycle in `internal-packages/dashboard-agent/src/watch-lifecycle.ts` claims the watch row before it calls `apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts`. If a non-final check is unavailable, the lifecycle persists `{ checkFailed: true, detail, previous: claimed.lastResult }`. `previousCheckFacts` in `apps/webapp/app/services/dashboardAgentWatchChecks.ts` recursively unwraps `previous`, so queue-streak facts survive unavailable reads. The batch evaluator uses `recordWatchAttempt` instead because it does not hold a claimed prior row to preserve.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4418
File: internal-packages/dashboard-agent-db/src/queries.ts:253-281
Timestamp: 2026-08-08T08:29:46.703Z
Learning: In `internal-packages/dashboard-agent-db/src/queries.ts`, `softDeleteChat` authorization is enforced by organization-scoped `chatExists` checks in its route callers. On the dashboard-agent route, `chatExists` receives `chatId`, `userId`, and `project.organizationId` and returns HTTP 404 before `softDeleteChat` runs. Since `chats.id` is the primary key, an additional `organizationId` predicate in `softDeleteChat` does not narrow the targeted row for this path.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/test/dashboardAgentWatchAlertOwnerScope.test.ts:101-109
Timestamp: 2026-08-08T12:49:17.489Z
Learning: In `apps/webapp/test`, each test suite that creates a client with `createDashboardAgentDb(connectionUri, ...)` must close the `DashboardAgentDbClient` in `afterEach`. `postgresTest` drops cloned databases with `WITH (FORCE)`, which removes server-side backends, but it does not clean up the client-side `postgres-js` pool sockets and idle timers.
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4124
File: internal-packages/database/prisma/migrations/20260629120000_drop_run_ops_control_plane_foreign_keys/migration.sql:1-26
Timestamp: 2026-07-02T19:14:58.851Z
Learning: Repo triggerdotdev/trigger.dev: In the run-ops DB split (schema.prisma / internal-packages/database/prisma/migrations), the intentional pattern is to keep Prisma `relation` declarations on models like TaskRun, Waitpoint, TaskRunWaitpoint, TaskRunCheckpoint, TaskRunAttempt, TaskRunTag, and WaitpointTag even after dropping the corresponding DB-level foreign key constraints via migration (e.g., migrations under 20260629120000_drop_run_ops_control_plane_foreign_keys and related). This is not schema drift: on the dedicated run-ops DB, `internal-packages/run-store/src/PostgresRunStore.ts` uses `stripDedicatedRelations` to strip these relation keys from Prisma select/include before querying, then `#hydrateDedicatedRelations` re-populates them from scalar columns or join lookups (e.g., hydrateAssociatedWaitpoint, hydrateBlockingTaskRuns). Do not flag missing schema updates to remove `relation` fields when FK constraints are dropped in this codebase's run-ops split migrations.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4552
File: apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts:158-165
Timestamp: 2026-08-11T10:53:21.099Z
Learning: For the dashboard agent message quota rollout, `apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts` intentionally fails open when the cloud `agentMessages` plan limit is unavailable. During this transition, `apps/webapp/app/components/dashboard-agent/useAgentMessageQuota.ts` applies the client-side free-plan upgrade nudge because it can identify a cloud free plan. Server-provided quota-limit propagation is planned in TRI-12863.
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4418
File: apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx:113-122
Timestamp: 2026-08-09T18:17:04.306Z
Learning: In `apps/webapp/app/components/dashboard-agent/DashboardAgentMessages.tsx`, this backend PR intentionally does not pass `onIntent`, URI resolution, report page paths, or `answered` to `ViewBlocks`. `ViewBlocks` treats these host inputs as optional, and its cards suppress actions when `onIntent` is absent so they do not render inactive controls. A UI PR above this branch will pass `onIntent` and `answered={answerContinuesAfter(message.parts, i)}`.
📚 Learning: 2026-08-08T08:29:21.685Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4418
File: apps/webapp/app/v3/commonWorker.server.ts:151-160
Timestamp: 2026-08-08T08:29:21.685Z
Learning: In the dashboard-agent maintenance flow, `sweepDashboardAgentInvestigations` in `apps/webapp/app/services/dashboardAgentInvestigationSweep.server.ts` processes at most 100 stale investigations per run. `settleInvestigationAndCloseCard` in `internal-packages/dashboard-agent-db/src/queries.ts` conditionally updates only investigations whose JSONB `state.outcome` remains `"in_progress"` and atomically appends the closing transcript card. Concurrent or redelivered sweeps cannot double-settle a row; later writers receive `null` and count the row as `alreadySettled`.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-08T08:30:57.294Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts:159-169
Timestamp: 2026-08-08T08:30:57.294Z
Learning: For dashboard-agent watch checks, the single-watch lifecycle in `internal-packages/dashboard-agent/src/watch-lifecycle.ts` claims the watch row before it calls `apps/webapp/app/routes/api.v1.dashboard-agent.watches.$watchId.check.ts`. If a non-final check is unavailable, the lifecycle persists `{ checkFailed: true, detail, previous: claimed.lastResult }`. `previousCheckFacts` in `apps/webapp/app/services/dashboardAgentWatchChecks.ts` recursively unwraps `previous`, so queue-streak facts survive unavailable reads. The batch evaluator uses `recordWatchAttempt` instead because it does not hold a claimed prior row to preserve.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-05-14T16:39:02.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3546
File: packages/cli-v3/src/mcp/tools/agentChat.ts:29-29
Timestamp: 2026-05-14T16:39:02.759Z
Learning: In `packages/cli-v3/src/mcp/tools/agentChat.ts`, the `activeSessions` Map intentionally has no TTL, LRU eviction, or size limit. The MCP server is dev-only (`start_agent_chat` enforces `input.environment === "dev"`) and runs as a short-lived subprocess of the MCP host (Claude Code / Cursor / etc.). The process is restarted whenever the IDE restarts, so sessions never accumulate across host lifetimes. Do not flag the lack of automatic cleanup as a memory-leak risk in this file.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:30:23.116Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx:292-301
Timestamp: 2026-08-08T08:30:23.116Z
Learning: In `apps/webapp/app/components/dashboard-agent/DashboardAgentChat.tsx`, `onWatchIntent` maps to `openWatchCard` in `apps/webapp/app/components/dashboard-agent/DashboardAgentPanel.tsx`. `openWatchCard` stores one draft with `setWatchDraft(watchDraftFor(spec))`. When one transcript update contains multiple watch intents, `pending.at(-1)` is intentional because only the final watch draft can be displayed.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-07-02T19:14:58.851Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4124
File: internal-packages/database/prisma/migrations/20260629120000_drop_run_ops_control_plane_foreign_keys/migration.sql:1-26
Timestamp: 2026-07-02T19:14:58.851Z
Learning: Repo triggerdotdev/trigger.dev: In the run-ops DB split (schema.prisma / internal-packages/database/prisma/migrations), the intentional pattern is to keep Prisma `relation` declarations on models like TaskRun, Waitpoint, TaskRunWaitpoint, TaskRunCheckpoint, TaskRunAttempt, TaskRunTag, and WaitpointTag even after dropping the corresponding DB-level foreign key constraints via migration (e.g., migrations under 20260629120000_drop_run_ops_control_plane_foreign_keys and related). This is not schema drift: on the dedicated run-ops DB, `internal-packages/run-store/src/PostgresRunStore.ts` uses `stripDedicatedRelations` to strip these relation keys from Prisma select/include before querying, then `#hydrateDedicatedRelations` re-populates them from scalar columns or join lookups (e.g., hydrateAssociatedWaitpoint, hydrateBlockingTaskRuns). Do not flag missing schema updates to remove `relation` fields when FK constraints are dropped in this codebase's run-ops split migrations.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-12T08:49:18.799Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4516
File: apps/webapp/app/services/dashboardAgentQuota.server.ts:36-89
Timestamp: 2026-08-12T08:49:18.799Z
Learning: For dashboard agent message quotas in `apps/webapp/app/services/dashboardAgentQuota.server.ts`, production currently resolves to the `UNLIMITED_AGENT_MESSAGES` sentinel because cloud billing does not yet provide a finite `agentMessages` limit. The check-then-increment race is accepted during this fail-open rollout. TRI-12863 P0 will introduce finite limits and must implement atomic, idempotent quota reservation and settlement with concurrent-send and redelivery coverage.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/README.md
📚 Learning: 2026-04-30T13:05:56.593Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3476
File: internal-packages/schedule-engine/src/engine/index.ts:555-559
Timestamp: 2026-04-30T13:05:56.593Z
Learning: In `internal-packages/schedule-engine/src/engine/index.ts`, the recovery path (`#recoverTaskScheduleInstance`) seeds `lastScheduleTime` using pure cron-math (`previousScheduledTimestamp(schedule.generatorExpression, schedule.timezone)`), guarded by `instance.createdAt` (to avoid seeding a stale timestamp for new schedules that haven't fired yet) and wrapped in try/catch (to degrade gracefully on malformed expressions). This is a zero-DB-read approximation: accurate for continuously-running schedules, slightly approximate for recently-edited crons or paused-then-resumed schedules. After one potentially-approximate fire, the worker payload flow takes over and becomes accurate permanently. This intentionally avoids: (a) querying TaskRun per-instance during recovery fan-outs (would convert a Redis incident into a DB incident), and (b) persisting a new "last fired" column (would revert the PR's core purpose of eliminating per-tick DB writes). Do NOT flag the recovery path for using cron-mat...

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-12T06:32:24.127Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4577
File: apps/webapp/app/v3/services/createBackgroundWorker.server.ts:779-781
Timestamp: 2026-08-12T06:32:24.127Z
Learning: In `apps/webapp/app/v3/services/createBackgroundWorker.server.ts`, `syncDeclarativeSchedules` has a pre-existing non-serialized read/modify/delete reconciliation flow. Changes that reuse its initial schedule snapshot instead of a redundant re-fetch do not introduce this concurrency risk. Track reconciliation serialization separately from read-side performance changes unless a change modifies the synchronization boundary.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-06-01T12:05:44.112Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3754
File: apps/webapp/app/v3/mollifierStaleSweepWorker.server.ts:30-32
Timestamp: 2026-06-01T12:05:44.112Z
Learning: In the triggerdotdev/trigger.dev codebase, the mollifier stale-entry sweep (`initMollifierStaleSweepWorker` in `apps/webapp/app/v3/mollifierStaleSweepWorker.server.ts`) intentionally runs per-webapp instance without a distributed lease in its initial implementation. All Redis ops (cursor, counts hash, reconcile) are individually atomic and produce correct shared state even with multiple concurrent sweepers. The known limitation is that OpenTelemetry metric output (`recordStaleEntry`, `reportStaleEntrySnapshot`) multiplies by N webapp instances, mis-calibrating alert thresholds by a factor of N. A SETNX-based per-tick lease (SET NX PX on the sweep's existing Redis) is the planned follow-up fix. Until then, alert thresholds should be scaled accordingly. Do not re-raise this as a blocking correctness bug — it is a documented metric-scaling limitation with a tracked follow-up.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-12T07:30:37.802Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: internal-packages/dashboard-agent-db/src/watch-queries.ts:794-808
Timestamp: 2026-08-12T07:30:37.802Z
Learning: In triggerdotdev/trigger.dev dashboard-agent watches, `softDeleteChatsForOrganization()` does not serialize with `createWatch()` through the per-chat advisory lock. A create-versus-organization-delete race can temporarily leave an active watch on a deleted chat. This behavior existed before the Watch feature and is accepted as a bounded, rare administrative-path condition: the next watch tick calls `authorizeWatchEnvironment`, cancels the watch with `access_lost` after organization deletion, and chat hard deletion removes residual watch rows. Per-chat or organization-level locking and a concurrent regression test belong to the dedicated organization-deletion durability follow-up.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:29:46.703Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4418
File: internal-packages/dashboard-agent-db/src/queries.ts:253-281
Timestamp: 2026-08-08T08:29:46.703Z
Learning: In `internal-packages/dashboard-agent-db/src/queries.ts`, `softDeleteChat` authorization is enforced by organization-scoped `chatExists` checks in its route callers. On the dashboard-agent route, `chatExists` receives `chatId`, `userId`, and `project.organizationId` and returns HTTP 404 before `softDeleteChat` runs. Since `chats.id` is the primary key, an additional `organizationId` predicate in `softDeleteChat` does not narrow the targeted row for this path.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:33:22.847Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts:127-134
Timestamp: 2026-08-08T08:33:22.847Z
Learning: In triggerdotdev/trigger.dev dashboard routes, `apps/webapp/app/models/project.server.ts` function `findProjectBySlug` resolves the project slug and organization membership scope through `$replica`. Equivalent dashboard-agent scope lookups, including the `unread=1` path in `apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts`, should retain `$replica` consistency unless the repository establishes a specific primary-read requirement.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-11T10:53:21.099Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4552
File: apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts:158-165
Timestamp: 2026-08-11T10:53:21.099Z
Learning: For the dashboard agent message quota rollout, `apps/webapp/app/routes/resources.orgs.$organizationSlug.projects.$projectParam.env.$envParam.dashboard-agent.ts` intentionally fails open when the cloud `agentMessages` plan limit is unavailable. During this transition, `apps/webapp/app/components/dashboard-agent/useAgentMessageQuota.ts` applies the client-side free-plan upgrade nudge because it can identify a cloud free plan. Server-provided quota-limit propagation is planned in TRI-12863.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/README.md
📚 Learning: 2026-05-15T08:05:57.683Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3625
File: apps/webapp/app/services/taskMetadataCache.server.ts:270-291
Timestamp: 2026-05-15T08:05:57.683Z
Learning: In the triggerdotdev/trigger.dev codebase, `populateByCurrentWorker()` in `apps/webapp/app/services/taskMetadataCache.server.ts` intentionally logs and swallows Redis errors rather than rethrowing. The design rationale: rethrowing would propagate into `ChangeCurrentDeploymentService.call` and break deploy promotion when Redis is briefly unavailable; the 24h `TASK_META_CACHE_CURRENT_ENV_TTL_SECONDS` TTL acts as the self-healing window for cache drift, and next-promotion overwrites the env key sooner in practice. A compensating DEL on failure is also not a win because if Redis is unreachable the DEL fails identically, and Lua scripts are atomic so a partial write is impossible. Do not flag this log+swallow pattern as a bug in future reviews.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:33:52.819Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts:500-506
Timestamp: 2026-08-08T08:33:52.819Z
Learning: In `apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts` and `apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts`, the Slack error predicates are intentionally kept byte-for-byte identical. Any hardening change to these predicates must update both alert deliverers in a separate pull request, rather than diverging one feature pull request.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-03-26T10:02:25.354Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3254
File: apps/webapp/app/services/platformNotifications.server.ts:363-385
Timestamp: 2026-03-26T10:02:25.354Z
Learning: In `triggerdotdev/trigger.dev`, the `getNextCliNotification` fallback in `apps/webapp/app/services/platformNotifications.server.ts` intentionally uses `prisma.orgMember.findFirst` (single org) when no `projectRef` is provided. This is acceptable for v1 because the CLI (`dev` and `login` commands) always passes `projectRef` in normal usage, making the fallback a rare edge case. Do not flag the single-org fallback as a multi-org correctness bug in this file.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-06-17T17:13:49.929Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3948
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.bulk-actions.$bulkActionParam/route.tsx:48-62
Timestamp: 2026-06-17T17:13:49.929Z
Learning: In triggerdotdev/trigger.dev, within `dashboardLoader`/`dashboardAction` (or similar context resolver code) whenever you resolve an organization ID from an organization slug for RBAC/enterprise authorization scope, always read from the primary Prisma client (`prisma`), not `$replica`. Using `$replica` can hit replica-lag and cause the RBAC lookup/authorization to run without the correct org scope (bypassing intended role enforcement). Implement the slug→org lookup with `prisma.organization.findFirst(...)` (or equivalent primary-client query) and add an inline comment documenting why the primary client is required (replica lag could lead to unscoped RBAC checks).

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-04-13T21:44:00.032Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/app/services/taskIdentifierRegistry.server.ts:24-67
Timestamp: 2026-04-13T21:44:00.032Z
Learning: In `apps/webapp/app/services/taskIdentifierRegistry.server.ts`, the sequential upsert/updateMany/findMany writes in `syncTaskIdentifiers` are intentionally NOT wrapped in a Prisma transaction. This function runs only during deployment-change events (low-concurrency path), and any partial `isInLatestDeployment` state is acceptable because it self-corrects on the next deployment. Do not flag this as a missing-transaction/atomicity issue in future reviews.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-06-30T14:58:42.838Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 4086
File: packages/redis-worker/src/queue.ts:0-0
Timestamp: 2026-06-30T14:58:42.838Z
Learning: In `triggerdotdev/trigger.dev` `packages/redis-worker/src/queue.ts`, `SimpleQueue.oldestMessageAge()` should ignore orphaned `queue` zset entries by resolving the oldest due candidate against the `items` hash via the read-only `getOldestDueScore` Lua command. For this metric path, do not mutate Redis state (for example, do not `ZREM` orphans during observation); keep the scan bounded (`LIMIT 0 100`) so metric collection does not degrade to an unbounded O(n) walk when stale entries exist.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-05-12T14:13:17.114Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3561
File: .claude/scripts/check-review-md.sh:76-79
Timestamp: 2026-05-12T14:13:17.114Z
Learning: In the triggerdotdev/trigger.dev repository, `.claude/REVIEW.md` drift/audit checking is handled by an LLM-based workflow using `anthropics/claude-code-action` (mirroring `.github/workflows/claude-md-audit.yml`), not a static bash script. The LLM audit catches semantic drift, stale references, contradictions, and missing/obsolete rules — not just deleted paths. The bash script `.claude/scripts/check-review-md.sh` was dropped in favor of this approach.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-06-16T13:14:20.816Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3964
File: docs/ai-chat/reference.mdx:478-478
Timestamp: 2026-06-16T13:14:20.816Z
Learning: In the triggerdotdev/trigger.dev repo, the RC-gated `ai-chat` docs section (under `docs/ai-chat/`) is often updated in companion docs PRs that are meant to land alongside implementation PRs (e.g., PR `#3963` adds `handover: { isFinal: boolean } | null` to the exported `ChatTurn` type in `packages/trigger-sdk/src/v3/ai.ts`). When searching for SDK types referenced in these docs PRs, the field may not exist on the docs branch yet — check the companion implementation PR before flagging missing implementations.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-05-12T21:04:01.335Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3542
File: apps/webapp/app/routes/_app.orgs.$organizationSlug.projects.$projectParam.env.$envParam.sessions._index/route.tsx:78-78
Timestamp: 2026-05-12T21:04:01.335Z
Learning: In the triggerdotdev/trigger.dev codebase, the Sessions feature (routes under `sessions._index` and `sessions.$sessionParam`) intentionally uses `docsPath("/ai-chat/overview")` for its docs link. Sessions documentation lives under the AI chat overview as part of the chat.agent feature surface. Do not flag this as a mismatched link text/path.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-07-26T13:14:05.711Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4378
File: .server-changes/realtime-run-reads-from-primary.md:0-0
Timestamp: 2026-07-26T13:14:05.711Z
Learning: In this repository, `.server-changes` body text ships verbatim as dashboard-facing user release notes. Write these entries in terms of user-visible behavior rather than implementation mechanisms such as environment-variable names; document operational configuration details in the PR description instead.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/README.md
📚 Learning: 2026-07-18T13:08:54.672Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4284
File: apps/webapp/test/cancelRouteReplicaLag.guard.test.ts:50-123
Timestamp: 2026-07-18T13:08:54.672Z
Learning: In `triggerdotdev/trigger.dev` replica-lag route regression guards that use real Postgres Testcontainers and invoke a route’s real exported handler may stub fix-orthogonal collaborators (such as auth/session gates, downstream engine work, buffer state, redirect formatting, presigning, or realtime instances) when the test still exercises the real run-store routing and the replica-read/primary-fallback decision under guard. Do not flag these targeted stubs merely because the test is Testcontainer-backed.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T12:49:17.489Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/test/dashboardAgentWatchAlertOwnerScope.test.ts:101-109
Timestamp: 2026-08-08T12:49:17.489Z
Learning: In `apps/webapp/test`, each test suite that creates a client with `createDashboardAgentDb(connectionUri, ...)` must close the `DashboardAgentDbClient` in `afterEach`. `postgresTest` drops cloned databases with `WITH (FORCE)`, which removes server-side backends, but it does not clean up the client-side `postgres-js` pool sockets and idle timers.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-08T12:22:34.925Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: internal-packages/dashboard-agent/src/watch-actions.ts:564-590
Timestamp: 2026-08-08T12:22:34.925Z
Learning: In `internal-packages/dashboard-agent/src/watch-actions.ts`, consented watch investigations must use `watchInvestigationId(action.watchId)` in the wake, investigation, and redelivery paths. Do not use a chat-wide open-investigation lookup because it can associate a watch with a manually started or sibling-watch investigation card.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-11T22:35:29.301Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4556
File: apps/webapp/app/services/dashboardAgentWatches.server.ts:364-375
Timestamp: 2026-08-11T22:35:29.301Z
Learning: In `apps/webapp/app/services/dashboardAgentWatches.server.ts`, `resolveWatchPlanLimits` currently resolves watcher limits to the unlimited sentinel until cloud ships real plan limits. The non-atomic organization active-watch count and `createWatch` sequence is accepted temporarily because finite watcher quotas are not currently enforced. TRI-12863 tracks an organization-scoped atomic guard and concurrent-create test before finite limits are enabled.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:33:38.878Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/services/dashboardAgentWatchBatch.server.ts:112-120
Timestamp: 2026-08-08T08:33:38.878Z
Learning: For dashboard-agent watches, a `deliverOnly` entry in `internal-packages/dashboard-agent/src/watch-lifecycle.ts` takes the terminal delivery path to `deliverWake`. Wake delivery uses `appendWakeToSession` and does not require the dashboard-agent watch token. The token is used only by `postCheck`, `postFired`, and `postInvestigate`; the fired and investigation notification calls are best-effort and do not block marking a wake as delivered.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-08-08T08:34:41.913Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: internal-packages/emails/emails/alert-dashboard-agent-watch.tsx:93-110
Timestamp: 2026-08-08T08:34:41.913Z
Learning: For dashboard-agent watch alert emails, `apps/webapp/app/v3/services/alerts/deliverDashboardAgentWatchAlert.server.ts` supplies own properties for `headline`, `tone`, `noteLine`, and `unsubscribeLink` to `sendAlertEmail`. `internal-packages/emails/src/index.tsx` forwards this data directly to `AlertDashboardAgentWatchEmail` without Zod parsing, so an own optional property with value `undefined` overrides `previewDefaults` during the component's object spread and preserves its nullish fallbacks.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
📚 Learning: 2026-03-22T13:26:12.060Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3244
File: apps/webapp/app/components/code/TextEditor.tsx:81-86
Timestamp: 2026-03-22T13:26:12.060Z
Learning: In the triggerdotdev/trigger.dev codebase, do not flag `navigator.clipboard.writeText(...)` calls for `missing-await`/`unhandled-promise` issues. These clipboard writes are intentionally invoked without `await` and without `catch` handlers across the project; keep that behavior consistent when reviewing TypeScript/TSX files (e.g., usages like in `apps/webapp/app/components/code/TextEditor.tsx`).

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-03-22T19:24:14.403Z
Learnt from: matt-aitken
Repo: triggerdotdev/trigger.dev PR: 3187
File: apps/webapp/app/v3/services/alerts/deliverErrorGroupAlert.server.ts:200-204
Timestamp: 2026-03-22T19:24:14.403Z
Learning: In the triggerdotdev/trigger.dev codebase, webhook URLs are not expected to contain embedded credentials/secrets (e.g., fields like `ProjectAlertWebhookProperties` should only hold credential-free webhook endpoints). During code review, if you see logging or inclusion of raw webhook URLs in error messages, do not automatically treat it as a credential-leak/secrets-in-logs issue by default—first verify the URL does not contain embedded credentials (for example, no username/password in the URL, no obvious secret/token query params or fragments). If the URL is credential-free per this project’s conventions, allow the logging.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma error P1001 ("Can't reach database server") in TypeScript, don’t assume a single error shape. Prisma can surface P1001 via two different error classes/fields: `PrismaClientKnownRequestError` exposes it as `err.code === "P1001"` (common during mid-query connection drops), while `PrismaClientInitializationError` exposes it as `err.errorCode === "P1001"` (common on client startup failure). Therefore, predicates should use `err.code === "P1001" || err.errorCode === "P1001"`. Do not flag `err.code === "P1001"` as “unreachable/never matches,” as it is expected in production.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-05-18T08:21:27.694Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3632
File: apps/webapp/sentry.server.ts:4-21
Timestamp: 2026-05-18T08:21:27.694Z
Learning: When handling Prisma errors for P1001 ("Can't reach database server"), do not assume it only appears under a single property name. Prisma may surface P1001 via either `PrismaClientKnownRequestError` (`err.code === "P1001"`, e.g., mid-query connection drops) or `PrismaClientInitializationError` (`err.errorCode === "P1001"`, e.g., client startup connection failure). To reliably detect the condition, check `err.code === "P1001" || err.errorCode === "P1001"`, and avoid review rules that would incorrectly flag `err.code === "P1001"` as unreachable/never-matching.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-06-13T19:53:13.759Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3937
File: packages/trigger-sdk/skills/realtime-and-frontend/SKILL.md:258-260
Timestamp: 2026-06-13T19:53:13.759Z
Learning: When reviewing code that uses `trigger.dev/react-hooks`’s `useRealtimeRun`, preserve the call signature where the first argument is the full realtime handle object (not `handle.id`). This is intentional to maintain type-safety and is consistent with the official docs; do not suggest changing the first argument from the handle object to `handle.id`.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-06-23T13:04:21.413Z
Learnt from: carderne
Repo: triggerdotdev/trigger.dev PR: 4023
File: apps/webapp/app/services/upsertBranch.server.ts:14-18
Timestamp: 2026-06-23T13:04:21.413Z
Learning: In TypeScript, it’s valid to `import { type X }` and then use `typeof X` in a type-only position, e.g. `type Alias = z.infer<typeof X>`. The `type` modifier suppresses the runtime import, but the type checker still has the full exported type so `z.infer<typeof X>` can resolve correctly. In code reviews, don’t flag this as a TypeScript compile error as long as `typeof X` is used in a type context (e.g., with `z.infer`, `type` aliases, generics), not as a runtime value.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-06-04T18:16:35.386Z
Learnt from: nicktrn
Repo: triggerdotdev/trigger.dev PR: 3836
File: apps/supervisor/src/backpressure/backpressureMonitor.ts:3-5
Timestamp: 2026-06-04T18:16:35.386Z
Learning: When reviewing TypeScript in this repo, apply the rule “prefer type aliases over interfaces” only to data/object shapes and union/intersection type modeling. If an interface is being used as a behavioral contract for collaborators to implement (e.g., method-shape interfaces that define required behavior, such as `BackpressureLogger` / `BackpressureSignalSource` in `apps/supervisor/src/backpressure/backpressureMonitor.ts`), keep it as an `interface` and do not flag it as a type-alias-vs-interface violation.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-06-09T17:58:04.699Z
Learnt from: 0ski
Repo: triggerdotdev/trigger.dev PR: 3879
File: apps/webapp/app/models/vercelIntegration.server.ts:619-630
Timestamp: 2026-06-09T17:58:04.699Z
Learning: In this codebase, outbound raw `fetch` calls should typically rely on Node/undici’s default request timeout (about ~300s) rather than adding a per-call `AbortController` + `setTimeout` wrapper inside individual functions (e.g. in files like `apps/webapp/app/models/vercelIntegration.server.ts`). During code review, do not flag the absence of a per-call timeout on a single `fetch` as an issue; if per-call timeouts are needed, they should be implemented via a codebase-wide convention (e.g., a shared fetch wrapper or documented pattern) rather than ad-hoc per-function changes.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.ts
  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-11T22:35:59.403Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4556
File: apps/webapp/test/dashboardAgentWatchLimitStatus.test.ts:22-55
Timestamp: 2026-08-11T22:35:59.403Z
Learning: In `apps/webapp/test/dashboardAgentWatchLimitStatus.test.ts`, route-level tests may use narrow Vitest module seams to provide authentication, access control, and deterministic plan-limit configuration when the test uses `postgresTest` with real Prisma seeding and a real dashboard-agent database client. Do not flag these seams as Testcontainers violations when the test verifies a route response and container-backed persistence behavior remains real.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-03-02T12:43:25.254Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: internal-packages/run-engine/CLAUDE.md:0-0
Timestamp: 2026-03-02T12:43:25.254Z
Learning: Applies to internal-packages/run-engine/src/engine/tests/**/*.test.ts : Implement tests for RunEngine in `src/engine/tests/` using testcontainers for Redis and PostgreSQL containerization

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-07-18T18:31:37.633Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts:24-65
Timestamp: 2026-07-18T18:31:37.633Z
Learning: In `triggerdotdev/trigger.dev`’s `internal-packages/run-store/src/runOpsStore.presentersWaitpointReadView.replicaLag.test.ts`, retain the local real-Testcontainers Prisma proxy rather than requiring the shared `laggingReplica` helper: the test must simulate lag for `waitpointTag` reads and for `findWaitpointConnectedRunIds`, which uses `$queryRaw`. The shared primitive intercepts configured Prisma models but not raw queries, so replacing the proxy would allow the live raw join to observe primary data and invalidate the replica-lag guard. The related taskRun-only tests (`runOpsStore.realtimeServicesReadView.replicaLag.test.ts`, `runOpsStore.replayReadAfterWrite.replicaLag.test.ts`, and `runOpsStore.resolveRunForMutationReplicaLag.test.ts`) can use the shared primitive with `{ model: "taskRun", mode: "missing" }`.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-07-18T18:17:16.266Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 4285
File: internal-packages/run-store/src/runOpsStore.routesSpanTraceReadView.replicaLag.test.ts:50-81
Timestamp: 2026-07-18T18:17:16.266Z
Learning: In triggerdotdev/trigger.dev replica-lag integration tests, some sibling test files intentionally use shape-scoped local Prisma proxy wrappers over real Postgres testcontainers to simulate only the read operations exercised by that site. These are not dependency mocks or Testcontainers-policy violations. Consolidation onto the shared `laggingReplica` primitive may be deliberately deferred to a follow-up to avoid infrastructure churn before merge; treat this as a consistency/maintenance concern rather than a merge-blocking functional defect.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-04-16T13:45:22.317Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3368
File: apps/webapp/test/engine/taskIdentifierRegistry.test.ts:3-19
Timestamp: 2026-04-16T13:45:22.317Z
Learning: In `apps/webapp/test/engine/taskIdentifierRegistry.test.ts`, the `vi.mock` calls for `~/services/taskIdentifierCache.server` (stubbing `getTaskIdentifiersFromCache` and `populateTaskIdentifierCache`), `~/models/task.server` (stubbing `getAllTaskIdentifiers`), and `~/db.server` (stubbing `prisma` and `$replica`) are intentional. The suite uses real Postgres via testcontainers for all `TaskIdentifier` DB operations, but isolates the Redis cache layer and legacy query fallback as separate concerns not exercised in this test file. Do not flag these mocks as violations of the no-mocks policy in future reviews.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2025-11-27T16:26:37.432Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T16:26:37.432Z
Learning: Applies to internal-packages/database/**/*.{ts,tsx} : Use Prisma for database interactions in internal-packages/database with PostgreSQL

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-07-27T15:07:14.579Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4397
File: apps/webapp/test/batchStreamGrants.test.ts:0-0
Timestamp: 2026-07-27T15:07:14.579Z
Learning: In `triggerdotdev/trigger.dev`, `apps/webapp/test/authorizationRateLimitMiddleware.test.ts` remains skipped because correcting its plaintext Redis fixture setup (`tlsDisabled`) exposed a timing-sensitive sliding-window test based on real 10-second windows. The new authorization-rate-limit bypass coverage instead lives in the unskipped, deterministic `apps/webapp/test/authorizationRateLimitMiddlewareBypass.test.ts`. Do not flag the legacy suite's continued skip as missing coverage for the bypass behavior.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-12T08:49:25.047Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4516
File: apps/webapp/test/queryRouteReadOnly.test.ts:38-84
Timestamp: 2026-08-12T08:49:25.047Z
Learning: In `apps/webapp/test/queryRouteReadOnly.test.ts`, Vitest module mocks are intentional for route tests that must prove rejected write queries do not call ClickHouse, persistence, or concurrency infrastructure. Use container-backed tests when persistence behavior is under test, not to replace this verify-not-called seam.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-06-16T09:19:47.637Z
Learnt from: d-cs
Repo: triggerdotdev/trigger.dev PR: 3960
File: apps/webapp/test/prismaInfrastructureErrorCapture.test.ts:0-0
Timestamp: 2026-06-16T09:19:47.637Z
Learning: In this repo’s Vitest setup, `vitest.config.ts` uses `globals: true`, so identifiers like `vi`, `describe`, `it`, and `expect` are available as globals in Vitest test files. During code review, do not flag missing `vi`/`describe`/`it`/`expect` imports as a runtime error or correctness issue when they’re used in `*.test.ts/tsx` or `*.spec.ts/tsx` files. Explicit imports are still preferred for consistency, but they’re not required for runtime behavior.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-07-13T14:51:32.938Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: packages/redis-worker/CLAUDE.md:0-0
Timestamp: 2026-07-13T14:51:32.938Z
Learning: Applies to packages/redis-worker/**/*.{test,spec}.{ts,tsx} : Test Redis worker behavior with ioredis and testcontainers for Redis.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2025-11-27T16:26:37.432Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: .github/copilot-instructions.md:0-0
Timestamp: 2025-11-27T16:26:37.432Z
Learning: Applies to **/*.{test,spec}.{ts,tsx} : Use vitest for all tests in the Trigger.dev repository

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-07-13T14:51:40.805Z
Learnt from: CR
Repo: triggerdotdev/trigger.dev PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-07-13T14:51:40.805Z
Learning: Applies to **/*.{test,spec}.{ts,tsx} : Use Vitest exclusively and never mock dependencies; use Testcontainers for integration dependencies.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-08T17:53:06.947Z
Learnt from: kathiekiwi
Repo: triggerdotdev/trigger.dev PR: 4525
File: apps/webapp/app/components/dashboard-agent/turn-teardown.test.ts:0-0
Timestamp: 2026-08-08T17:53:06.947Z
Learning: In `apps/webapp/app/components/dashboard-agent/turn-teardown.ts`, `unmountTeardown` accepts pathname values and compares them directly. Its call sites pass `location.pathname`, so query strings cannot reach this helper. Query-string behavior must be tested at the call site, not in `unmountTeardown`.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-05-18T14:40:02.173Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 3658
File: packages/core/src/v3/realtimeStreams/manager.test.ts:1-147
Timestamp: 2026-05-18T14:40:02.173Z
Learning: In the triggerdotdev/trigger.dev repo, the policy “Never mock anything — use testcontainers instead” should only be enforced for integration tests that interact with real external services (e.g., Redis, Postgres) via actual infrastructure. For unit tests that exercise pure in-memory logic (e.g., cache semantics) it is OK to stub collaborators such as `ApiClient` using Vitest (`vi.fn()`) to assert call counts or control behavior. Do not flag `vi.fn()`-based `ApiClient` stubs in unit tests as violations of the testcontainers policy.

Applied to files:

  • internal-packages/dashboard-agent/src/maintenance.test.ts
📚 Learning: 2026-08-05T16:10:45.358Z
Learnt from: ericallam
Repo: triggerdotdev/trigger.dev PR: 4515
File: docs/self-hosting/env/webapp.mdx:29-33
Timestamp: 2026-08-05T16:10:45.358Z
Learning: In `docs/self-hosting/env/webapp.mdx`, document only environment variables that apply to the single-database self-hosted webapp configuration. Do not add `RUN_OPS_*`, `RUN_OPS_LEGACY_*`, or `CONTROL_PLANE_*` variables because they apply only to the cloud multi-database split and would mislead self-hosted operators.

Applied to files:

  • internal-packages/dashboard-agent/README.md
🔇 Additional comments (3)
internal-packages/dashboard-agent/src/maintenance.ts (1)

10-10: LGTM!

Also applies to: 123-130

internal-packages/dashboard-agent/src/maintenance.test.ts (1)

10-11: LGTM!

internal-packages/dashboard-agent/README.md (1)

35-36: LGTM!


Walkthrough

Dashboard-agent retention now runs in the dashboard-agent package through a daily scheduled task. Investigation settlement runs through a separate five-minute scheduled task. Both tasks use dashboard-agent database wiring and include new integration coverage. The webapp retention sweeps and related watch purge logic were removed, and the former maintenance worker entry became a deprecated no-op. Documentation and changelog entries describe the new schedules.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.93% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly summarizes the primary change: moving dashboard-agent maintenance from the webapp into the agent project.
Description check ✅ Passed The description clearly explains the motivation, implementation, retained webapp responsibilities, and testing performed, but omits the template checklist, changelog, and screenshots sections.
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/tri-13182-move-dashboard-agent-maintenance

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@kathiekiwi kathiekiwi changed the title refactor: move dashboard-agent maintenance sweeps into the agent trigger project refactor(webapp): dashboard agent maintenance moves into the agent project Aug 13, 2026
devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

@kathiekiwi kathiekiwi changed the title refactor(webapp): dashboard agent maintenance moves into the agent project fix(webapp): dashboard agent maintenance moves into the agent project Aug 13, 2026
@kathiekiwi

Copy link
Copy Markdown
Collaborator Author

Re the CodeRabbit nitpicks, all in 8f64cc5: the chat-retention test now uses applyDashboardAgentMigrations (the ~25 older webapp tests with the same hand-rolled helper predate this branch — separate cleanup), caught errors are serialized explicitly, and the investigation sweep skips with a zero result when no database is configured instead of failing every 5 minutes. Skipped asserting the batch-cap warn — it would need a logger spy, and this repo's tests avoid mocks.

devin-ai-integration[bot]

This comment was marked as resolved.

coderabbitai[bot]

This comment was marked as resolved.

devin-ai-integration[bot]

This comment was marked as resolved.

@devin-ai-integration devin-ai-integration Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Devin Review found 2 new potential issues.

Open in Devin Review

Comment on lines +122 to +128
run: async (): Promise<RetentionResult | undefined> => {
if (!watchConnectionString()) {
logger.warn(
"dashboard-agent maintenance skipped: no DASHBOARD_AGENT_DATABASE_URL or DATABASE_URL"
);
return undefined;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Retention does fall back to DATABASE_URL, contradicting the PR description

The PR description states "When DASHBOARD_AGENT_DATABASE_URL is unset the task does nothing — a delete sweep must never guess its database, so there is no DATABASE_URL fallback here." The code does the opposite: the guard and the connection both go through watchConnectionString() (internal-packages/dashboard-agent/src/watch-task-adapters.ts:21-24), which is DASHBOARD_AGENT_DATABASE_URL || DATABASE_URL. So retention will connect to (and hard-delete from) the main database's trigger_dashboard_agent schema whenever only DATABASE_URL is set. The updated GUIDEBOOK (internal-packages/dashboard-agent/GUIDEBOOK.md:385-392) and the webapp's own resolution (apps/webapp/app/services/dashboardAgentDb.server.ts:16) both use the same fallback, so the code is self-consistent — but the description's stated safety property is not implemented. Worth confirming which behaviour is intended before merge, since this pass issues destructive deletes.

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Comment on lines 9 to 14
/**
* How long a soft-deleted chat is kept before it and its children are hard-deleted.
* Long enough that an accidental delete can still be investigated; org deletion soft-
* deletes the org's chats, so those are removed the same way once the window passes.
*/
export const CHAT_SOFT_DELETE_RETENTION_MS = 30 * 24 * 60 * 60 * 1000;

/** Per-run cap. Retention is one bounded statement, not a row-at-a-time loop. */
const RETENTION_BATCH_LIMIT = 500;

export type ChatRetentionResult = {
/** Soft-deleted chats past the retention window dropped this run. */
purged: number;
failed: number;
};

export type ChatRetentionDeps = {
now?: () => Date;
limit?: number;
/** Hard-delete chats soft-deleted before `before`. Returns how many went. */
purge?: (params: { before: Date; limit: number }) => Promise<number>;
};

export async function sweepDashboardAgentSoftDeletedChats(
deps: ChatRetentionDeps = {}
): Promise<ChatRetentionResult> {
const now = deps.now?.() ?? new Date();
const limit = deps.limit ?? RETENTION_BATCH_LIMIT;
const purge =
deps.purge ?? ((params) => hardDeleteChatsSoftDeletedBefore(dashboardAgentDb, params));

const result: ChatRetentionResult = { purged: 0, failed: 0 };

try {
result.purged = await purge({
before: new Date(now.getTime() - CHAT_SOFT_DELETE_RETENTION_MS),
limit,
});
} catch (error) {
result.failed++;
logger.error("Dashboard agent chat retention failed", { error });
}

if (result.failed > 0) {
throw new Error("The dashboard agent chat retention pass failed");
}

return result;
}

/**
* Soft-delete every chat belonging to a deleted organization. The retention sweep above
* hard-deletes them once the window passes, so the org-deletion request never runs a
* cross-database hard delete.
* Soft-delete every chat belonging to a deleted organization. Retention hard-deletes them
* once the window passes, so the org-deletion request never runs a cross-database hard delete.
*/
export async function purgeDashboardAgentChatsForOrganization(params: {
organizationId: string;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔍 Chat hard-delete now depends entirely on the agent project being deployed

purgeDashboardAgentChatsForOrganization still only soft-deletes on org deletion, and the webapp no longer has any hard-delete path (sweepDashboardAgentSoftDeletedChats is gone). The eventual erasure of a deleted organization's chat transcripts now happens only if the separate agent Trigger project is deployed and its 03:00 UTC task runs. For a deployment where the dashboard agent datastore exists but the agent project isn't deployed (or its schedule is disabled), soft-deleted chats — including org-deletion purges — are retained indefinitely. Worth confirming that's acceptable for the data-deletion guarantee.

(Refers to lines 9-17)

Open in Devin Review

Was this helpful? React with 👍 or 👎 to provide feedback.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant