⭐️⭐️⭐️ Open-source, self-hosted alternative to Linear and Plane. Project management and issue tracking where teams and AI agents work side by side to plan and ship products.
TypeScript agenticagileai-agentsbug-reportingbug-trackerganttissue-trackerjirajira-alternativekanbanlinearlinear-alternativeopen-sourceproduct-managementproject-managementroadmapself-hostedsprint-planningteam-collaborationtrello-alternative
fix(api): deleting an issue deletes its agents' memory threads (#697)
Pasqual Troncone02235dd57a6c
diff --git a/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts b/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.tsindex 35eb2c1d..8504066a 100644--- a/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts+++ b/apps/api/src/modules/agents/core/__tests__/integration/thread-cleanup.test.ts@@ -9,8 +9,8 @@ import { createAgent } from '#tests/helpers/agents';// Agent conversation threads live in Mastra's tables, which carry no foreign key of// ours, so they are deleted explicitly when what they are bound to goes away: the-// agent, its project, or the schedule. Archiving an issue is reversible and drops-// none of them.+// agent, its project, the issue, or the schedule. Archiving an issue is reversible and+// drops none of them.//// The runtime is not exercised — a live model call would be needed to produce a thread// — so threads are seeded through the memory module the same way a run creates them.@@ -31,8 +31,10 @@ async function createInternalAgent(asOwner: Api, name: string, username: string)return res.data!.agent;}-async function createIssue(asOwner: Api, columnId: number, title: string) {- const res = await asOwner.projects({ projectKey: 'MKT' }).issues.post({ columnId, title });+async function createIssue(asOwner: Api, columnId: number, title: string, parentId?: number) {+ const res = await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.post({ columnId, title, parentId });return res.data!;}@@ -183,4 +185,91 @@ describe('agent thread cleanup', () => {expect(await threadExists(threadB)).toBe(true);expect(await messageCount(threadA)).toBe(1);});++ it("deletes an issue's run threads with their messages when it is deleted", async () => {+ const { asOwner, columnId } = await setup();+ const a = await createInternalAgent(asOwner, 'Bot A', 'bota');+ const b = await createInternalAgent(asOwner, 'Bot B', 'botb');+ const issue = await createIssue(asOwner, columnId, 'Ship it');+ const other = await createIssue(asOwner, columnId, 'Keep it');+ const threadA = await seedIssueThread(a, issue.id);+ const threadB = await seedIssueThread(b, issue.id);+ const kept = await seedIssueThread(a, other.id);+ await seedMessage(threadA, 'agent-bot');++ const res = await asOwner.issues({ issueId: issue.id }).delete();+ expect(res.status).toBe(204);++ expect(await threadExists(threadA)).toBe(false);+ expect(await threadExists(threadB)).toBe(false);+ expect(await messageCount(threadA)).toBe(0);+ expect(await threadExists(kept)).toBe(true);+ });++ it('deletes the run threads of the issues a bulk delete removes', async () => {+ const { asOwner, columnId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const first = await createIssue(asOwner, columnId, 'First');+ const second = await createIssue(asOwner, columnId, 'Second');+ const other = await createIssue(asOwner, columnId, 'Keep it');+ const threads = [+ await seedIssueThread(agent, first.id),+ await seedIssueThread(agent, second.id),+ ];+ const kept = await seedIssueThread(agent, other.id);++ const res = await asOwner+ .projects({ projectKey: 'MKT' })+ .issues.bulk.delete.post({ ids: [first.id, second.id] });+ expect(res.status).toBe(200);++ for (const thread of threads) expect(await threadExists(thread)).toBe(false);+ expect(await threadExists(kept)).toBe(true);+ });++ it('deletes the run threads of the subtasks a delete cascades to', async () => {+ const { asOwner, columnId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const parent = await createIssue(asOwner, columnId, 'Parent');+ const subtask = await createIssue(asOwner, columnId, 'Subtask', parent.id);+ const thread = await seedIssueThread(agent, subtask.id);++ const res = await asOwner+ .issues({ issueId: parent.id })+ .delete(undefined, { query: { subtasks: 'cascade' } });+ expect(res.status).toBe(204);++ expect(await threadExists(thread)).toBe(false);+ });++ it('deletes the run threads of the issues a deleted column takes with it', async () => {+ const { asOwner } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const columns = asOwner.projects({ projectKey: 'MKT' }).columns;+ const doomed = (await columns.post({ name: 'Doomed', stateType: 'started' })).data!;+ const issue = await createIssue(asOwner, doomed.id, 'Ship it');+ const thread = await seedIssueThread(agent, issue.id);++ const res = await columns({ columnId: doomed.id }).delete({ mode: 'delete' });+ expect(res.status).toBe(204);++ expect(await threadExists(thread)).toBe(false);+ });++ it('keeps the run threads of the issues a deleted column moves elsewhere', async () => {+ const { asOwner, columnId } = await setup();+ const agent = await createInternalAgent(asOwner, 'Design Bot', 'design');+ const columns = asOwner.projects({ projectKey: 'MKT' }).columns;+ const doomed = (await columns.post({ name: 'Doomed', stateType: 'started' })).data!;+ const issue = await createIssue(asOwner, doomed.id, 'Ship it');+ const thread = await seedIssueThread(agent, issue.id);++ const res = await columns({ columnId: doomed.id }).delete({+ mode: 'move',+ targetColumnId: columnId,+ });+ expect(res.status).toBe(204);++ expect(await threadExists(thread)).toBe(true);+ });});diff --git a/apps/api/src/modules/agents/core/runtime/memory.ts b/apps/api/src/modules/agents/core/runtime/memory.tsindex 2d99678d..f57653ce 100644--- a/apps/api/src/modules/agents/core/runtime/memory.ts+++ b/apps/api/src/modules/agents/core/runtime/memory.ts@@ -117,10 +117,11 @@ export async function deleteChatThread(threadId: string, resourceId: string): Prreturn true;}-// Deletes every thread bound to the given agent, project or schedule, with its+// Deletes every thread bound to the given agent, project, issue or schedule, with its// messages, and returns how many were deleted. Called when that binding goes away.export async function deleteThreadsWhere(- binding: { agentId: number } | { projectId: number } | { scheduleId: number },+ binding:+ { agentId: number } | { projectId: number } | { issueId: number } | { scheduleId: number },): Promise<number> {const memory = getReadMemory();const { threads } = await memory.listThreads({ filter: { metadata: binding }, perPage: false });diff --git a/apps/api/src/modules/columns/service.ts b/apps/api/src/modules/columns/service.tsindex e283bc3a..2bc831db 100644--- a/apps/api/src/modules/columns/service.ts+++ b/apps/api/src/modules/columns/service.ts@@ -16,6 +16,7 @@ import { emitIssueEvents, issuePayloads } from '#modules/issues/webhook-payload'import { emitWebhookEvents, projectEventWanted } from '#modules/webhooks/emit';import { recordStatusChange } from '#modules/issues/status-history';import { hasUnfinishedStatusRuns, queueStatusRuns } from '#modules/agents/schedules/issue-runs';+import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';export interface ColumnRow {id: number;@@ -252,7 +253,7 @@ export async function deleteColumn(deletedPayloads = await issuePayloads(await getIssues(rows.map((r) => r.id)));}- const movedIssueIds = await db.transaction(async (tx) => {+ const columnIssueIds = await db.transaction(async (tx) => {if (column.stateType === 'backlog') {// Serialize backlog deletions so concurrent requests cannot remove the last two.await tx@@ -267,37 +268,37 @@ export async function deleteColumn(if (count <= 1) throw new HttpError(400, 'The last backlog column cannot be deleted');}- let moved: number[] = [];+ let rows: { id: number }[];if (opts.mode === 'move') {- const rows = await tx+ rows = await tx.update(issue).set({ columnId: opts.targetColumnId, updatedAt: sql`now()` }).where(eq(issue.columnId, columnId)).returning({ id: issue.id });- moved = rows.map((r) => r.id);} else {const issueIds = tx.select({ id: issue.id }).from(issue).where(eq(issue.columnId, columnId));await tx.delete(issueFieldOption).where(inArray(issueFieldOption.issueId, issueIds));await tx.delete(issueFieldValue).where(inArray(issueFieldValue.issueId, issueIds));await tx.delete(issueLabel).where(inArray(issueLabel.issueId, issueIds));- await tx.delete(issue).where(eq(issue.columnId, columnId));+ rows = await tx.delete(issue).where(eq(issue.columnId, columnId)).returning({ id: issue.id });}await tx.delete(projectColumn).where(eq(projectColumn.id, columnId));- return moved;+ return rows.map((r) => r.id);});if (target) {- await recordStatusChange(movedIssueIds, target.id);+ await recordStatusChange(columnIssueIds, target.id);await recordActivityForIssues(- movedIssueIds,+ columnIssueIds,{ action: 'status', from: statusSide(column), to: statusSide(target) },actorUserId,);- const moved = () => getIssues(movedIssueIds);+ const moved = () => getIssues(columnIssueIds);await emitIssueEvents(projectId, 'issue.updated', moved, actorUserId);await emitIssueEvents(projectId, 'issue.state_changed', moved, actorUserId);- await queueStatusRuns(movedIssueIds, target.id, actorUserId);+ await queueStatusRuns(columnIssueIds, target.id, actorUserId);} else {+ for (const issueId of columnIssueIds) await deleteThreadsWhere({ issueId });await emitWebhookEvents(projectId, 'issue.deleted', async () => deletedPayloads, actorUserId);}}diff --git a/apps/api/src/modules/issues/service.ts b/apps/api/src/modules/issues/service.tsindex ddaac867..5a152c46 100644--- a/apps/api/src/modules/issues/service.ts+++ b/apps/api/src/modules/issues/service.ts@@ -71,6 +71,7 @@ import { getInitiativeProjectId } from '#modules/initiatives/service';import { cycleStatus, getCycleRef, type CycleStatus } from '#modules/cycles/service';import { getMembership } from '#modules/members/service';import { enqueueAgentRun } from '#modules/agents/core/run-queue';+import { deleteThreadsWhere } from '#modules/agents/core/runtime/memory';import { queueStatusRuns } from '#modules/agents/schedules/issue-runs';import { applySubtaskAutomation } from './automation';import { assertWipLimit, columnAutoAssignee, wipLimitBreach } from '#modules/columns/service';@@ -1167,9 +1168,11 @@ async function enqueueDelegateRun(after: IssueRow, actor?: ActivityActor): Promi}// Deletes an issue and everything attached to it. Field options/values, labels,-// attachments, and activity all go by their ON DELETE CASCADE on issue_id. Returns-// the deleted attachment rows so the caller can remove their objects from the store.-// Returns null if the issue did not exist.+// attachments, and activity all go by their ON DELETE CASCADE on issue_id; the agents'+// conversation threads about it live outside the cascades and are deleted after. Unlike+// archiving, this cannot be undone, so nothing would ever read those threads again.+// Returns the deleted attachment rows so the caller can remove their objects from the+// store. Returns null if the issue did not exist.export async function deleteIssue(issueId: number,actorUserId?: string | null,@@ -1186,6 +1189,7 @@ export async function deleteIssue(return removed.length ? attachmentRows.map(mapAttachment) : null;});if (!attachments) return null;+ await deleteThreadsWhere({ issueId });await emitIssueEvent('issue.deleted', deleted, actorUserId);return attachments;}