Skip to content

⭐️⭐️⭐️ 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.

feat(api): give agents the project activity feed and dated issue lists by period (#634)

Ilija Matoski9a80a52bd853
diff --git a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
index 1a0c1a83..d79a5b41 100644
--- a/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
+++ b/apps/api/src/modules/agents/core/runtime/tools/catalog.ts
@@ -329,7 +329,8 @@ export const ALWAYS_ON_ACTIONS: ToolMeta[] = [
key: 'list_issues',
group: 'issues',
label: 'List issues by filters',
- description: 'List issues filtered by state, type, assignee, priority, label, or due date.',
+ description:
+ 'List issues filtered by state, type, assignee, priority, label, due date, or when they were created or updated.',
always: true,
},
{
@@ -346,6 +347,13 @@ export const ALWAYS_ON_ACTIONS: ToolMeta[] = [
description: "Read an issue's comments and change log, replies included.",
always: true,
},
+ {
+ key: 'get_project_activity',
+ group: 'project',
+ label: 'Read project activity',
+ description: 'Read the comments and changes across all issues of the project, by period.',
+ always: true,
+ },
{
key: 'list_attachments',
group: 'issues',
diff --git a/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
index 96ca8703..1f164f05 100644
--- a/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
+++ b/apps/api/src/modules/analytics/__tests__/integration/analytics.test.ts
@@ -605,6 +605,20 @@ describe('analytics', () => {
expect(none.data?.items).toHaveLength(0);
});
+ it('limits the feed to a period', async () => {
+ const { asOwner, col } = await setupProject();
+ await createIssue(asOwner, col.started);
+ const past = new Date(Date.now() - 60_000).toISOString();
+ const future = new Date(Date.now() + 60_000).toISOString();
+ const feed = (query: { from?: string; to?: string }) =>
+ asOwner.projects({ projectKey: 'MKT' }).analytics.activity.get({ query });
+
+ expect((await feed({ from: past, to: future })).data?.items).toHaveLength(1);
+ expect((await feed({ from: future })).data?.items).toHaveLength(0);
+ expect((await feed({ to: past })).data?.items).toHaveLength(0);
+ expect((await feed({ from: 'yesterday' })).status).toBe(400);
+ });
+
it('clamps a limit below 1 up to a single item', async () => {
const { asOwner, col } = await setupProject();
await createIssue(asOwner, col.started);
diff --git a/apps/api/src/modules/analytics/index.ts b/apps/api/src/modules/analytics/index.ts
index cf31a915..d0bc72f2 100644
--- a/apps/api/src/modules/analytics/index.ts
+++ b/apps/api/src/modules/analytics/index.ts
@@ -4,6 +4,7 @@ import { requireUser } from '#shared/access';
import { guards } from '#shared/guards';
import { mcpTool } from '#mcp/generate';
import { accessErrors, commonErrors } from '#shared/responses';
+import { instantParam } from '#shared/lib';
import {
ActivityPage,
AgentRunFeedListResponse,
@@ -184,6 +185,8 @@ export const analyticsRoutes = new Elysia({
actorUserId: query.actorUserId ?? null,
action: query.action ?? null,
issueIds,
+ from: instantParam('from', query.from),
+ to: instantParam('to', query.to),
});
},
{
@@ -192,7 +195,8 @@ export const analyticsRoutes = new Elysia({
response: { 200: ActivityPage, ...commonErrors },
detail: {
summary: 'Get project activity',
- description: 'Project-wide feed of issue activity.',
+ description:
+ 'Project-wide feed of issue activity, newest first: comments and changes such as creation and state moves. `from` and `to` limit it to one period.',
...mcpTool('get_project_activity'),
},
},
diff --git a/apps/api/src/modules/analytics/model.ts b/apps/api/src/modules/analytics/model.ts
index 423b3f19..c82f4681 100644
--- a/apps/api/src/modules/analytics/model.ts
+++ b/apps/api/src/modules/analytics/model.ts
@@ -1,6 +1,7 @@
import { t } from 'elysia';
import { ActivityPayloadResponse } from '#shared/activity';
import { agentRunTrigger } from '#modules/agents/model';
+import { instantQuery } from '#shared/schemas';
export const StatsDto = t.Object({
open: t.Number(),
@@ -148,10 +149,16 @@ export const burnupQuery = t.Object({
});
export const activityQuery = t.Object({
- limit: t.Optional(t.Numeric()),
- cursor: t.Optional(t.String()),
+ limit: t.Optional(t.Numeric({ description: 'Max entries (1-100). Default 25.' })),
+ cursor: t.Optional(
+ t.String({ description: 'nextCursor of the previous page, as a JSON string.' }),
+ ),
actorUserId: t.Optional(t.String()),
- action: t.Optional(t.String()),
+ action: t.Optional(
+ t.String({ description: "Change-log action, such as 'created' or 'status'." }),
+ ),
+ from: instantQuery('Inclusive earliest entry time.'),
+ to: instantQuery('Exclusive latest entry time.'),
// Comma-separated issue ids the client resolved from the widget's work items
// filter; absent means no issue-scope restriction.
issueIds: t.Optional(t.String()),
diff --git a/apps/api/src/modules/analytics/service.ts b/apps/api/src/modules/analytics/service.ts
index ac4832eb..91e7f4c1 100644
--- a/apps/api/src/modules/analytics/service.ts
+++ b/apps/api/src/modules/analytics/service.ts
@@ -13,7 +13,7 @@ import {
initiative,
type ActivityPayload,
} from '@repo/db';
-import { and, desc, eq, inArray, isNull, isNotNull, sql } from 'drizzle-orm';
+import { and, desc, eq, gte, inArray, isNull, isNotNull, lt, sql } from 'drizzle-orm';
import { HttpError, iso } from '#shared/lib';
import type { AgentRunTrigger } from '#modules/agents/model';
@@ -547,6 +547,8 @@ export async function listActivity(
actorUserId?: string | null;
action?: string | null;
issueIds?: number[] | null;
+ from?: Date;
+ to?: Date;
} = {},
): Promise<ActivityPage> {
const limit = Math.min(Math.max(opts.limit ?? 25, 1), 100);
@@ -558,6 +560,8 @@ export async function listActivity(
if (opts.issueIds) conds.push(inArray(issueActivity.issueId, opts.issueIds));
if (opts.actorUserId != null) conds.push(eq(issueActivity.actorUserId, opts.actorUserId));
if (opts.action) conds.push(eq(issueActivity.action, opts.action));
+ if (opts.from) conds.push(gte(issueActivity.createdAt, opts.from));
+ if (opts.to) conds.push(lt(issueActivity.createdAt, opts.to));
if (before)
conds.push(
sql`(${issueActivity.createdAt}, ${issueActivity.id}) < (${before.ts}::timestamptz, ${before.id}::integer)`,
diff --git a/apps/api/src/modules/issues/__tests__/integration/issues.test.ts b/apps/api/src/modules/issues/__tests__/integration/issues.test.ts
index 2a98770c..02845efa 100644
--- a/apps/api/src/modules/issues/__tests__/integration/issues.test.ts
+++ b/apps/api/src/modules/issues/__tests__/integration/issues.test.ts
@@ -1302,6 +1302,43 @@ describe('issues', () => {
expect(res.data!.map((i) => i.id)).toContain(one.id);
});
+ it('returns the dates, with completedAt set once the issue is completed', async () => {
+ const { asOwner, columnId } = await setupProject();
+ const one = (await createIssue(asOwner, columnId, { title: 'Dated' })).data!;
+
+ const before = (await list(asOwner)).data!.find((i) => i.id === one.id)!;
+ expect(before.createdAt).toBeInstanceOf(Date);
+ expect(before.updatedAt).toBeInstanceOf(Date);
+ expect(before.completedAt).toBeNull();
+
+ const view = await asOwner.projects({ projectKey: 'MKT' }).get();
+ const done = view.data!.columns.find((c) => c.stateType === 'completed')!.id;
+ await asOwner.issues({ issueId: one.id }).patch({ columnId: done });
+
+ const after = (await list(asOwner)).data!.find((i) => i.id === one.id)!;
+ expect(after.completedAt).toBeInstanceOf(Date);
+ });
+
+ it('filters by created and updated time', async () => {
+ const { asOwner, columnId } = await setupProject();
+ const one = (await createIssue(asOwner, columnId, { title: 'Timed' })).data!;
+ const past = new Date(Date.now() - 60_000).toISOString();
+ const future = new Date(Date.now() + 60_000).toISOString();
+
+ const ids = async (query: Record<string, string>) =>
+ (await list(asOwner, query)).data!.map((i) => i.id);
+ expect(await ids({ createdFrom: past, createdTo: future })).toContain(one.id);
+ expect(await ids({ createdFrom: future })).not.toContain(one.id);
+ expect(await ids({ updatedFrom: past })).toContain(one.id);
+ expect(await ids({ updatedTo: past })).not.toContain(one.id);
+ expect(await ids({ updatedFrom: '' })).toContain(one.id);
+ });
+
+ it('rejects a time filter that does not parse', async () => {
+ const { asOwner } = await setupProject();
+ expect((await list(asOwner, { updatedFrom: 'last week' })).status).toBe(400);
+ });
+
it('denies a non-member', async () => {
const { asOwner, columnId } = await setupProject();
await createIssue(asOwner, columnId, { title: 'Secret' });
diff --git a/apps/api/src/modules/issues/index.ts b/apps/api/src/modules/issues/index.ts
index 4f51276e..3a688f13 100644
--- a/apps/api/src/modules/issues/index.ts
+++ b/apps/api/src/modules/issues/index.ts
@@ -12,7 +12,7 @@ import {
requireUser,
} from '#shared/access';
import { getProjectById } from '#modules/projects/service';
-import { HttpError } from '#shared/lib';
+import { HttpError, instantParam } from '#shared/lib';
import { accessErrors, commonErrors, errors } from '#shared/responses';
import { deleteObject } from '@repo/storage';
import {
@@ -472,6 +472,10 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
labelIds: labelIds && labelIds.length ? labelIds : undefined,
dueFrom: str(query.dueFrom),
dueTo: str(query.dueTo),
+ createdFrom: instantParam('createdFrom', query.createdFrom),
+ createdTo: instantParam('createdTo', query.createdTo),
+ updatedFrom: instantParam('updatedFrom', query.updatedFrom),
+ updatedTo: instantParam('updatedTo', query.updatedTo),
limit,
},
{ includeArchived: query.includeArchived === 'true' },
@@ -484,7 +488,8 @@ export const issueRoutes = new Elysia({ name: 'issues', detail: { tags: ['Issues
response: { 200: t.Array(IssueSearchHitResponse), ...commonErrors },
detail: {
summary: 'List issues by filters',
- description: "List a project's issues by field filters.",
+ description:
+ "List a project's issues by field filters, most recently updated first. Each issue carries createdAt, updatedAt and completedAt.",
...mcpTool('list_issues'),
},
},
diff --git a/apps/api/src/modules/issues/model.ts b/apps/api/src/modules/issues/model.ts
index 4eeabcdc..0099276f 100644
--- a/apps/api/src/modules/issues/model.ts
+++ b/apps/api/src/modules/issues/model.ts
@@ -3,7 +3,7 @@ import { agentExecutionState } from '#modules/agents/model';
import { ActivityPayloadResponse } from '#shared/activity';
import { DevelopmentLinkResponse } from '#modules/git/model';
import { AgentTraceDetailResponse } from '#modules/agents/core/model';
-import { isoDate } from '#shared/schemas';
+import { instantQuery, isoDate } from '#shared/schemas';
// Ceiling of every markdown text written on an issue: the description, a comment
// and a custom field value. Each of them is scanned for mentions.
@@ -330,6 +330,9 @@ export const IssueSearchHitResponse = t.Object({
dueDate: t.Nullable(t.String()),
labelIds: t.Array(t.Number()),
archived: t.Boolean(),
+ createdAt: t.String(),
+ updatedAt: t.String(),
+ completedAt: t.Nullable(t.String()),
});
// FeedItemRow from activity.ts: one timeline entry (comment or change-log).
@@ -543,6 +546,10 @@ export const listIssuesQuery = t.Object({
labelIds: t.Optional(t.String({ description: 'CSV of label ids; the issue must carry all.' })),
dueFrom: t.Optional(t.String({ description: "Inclusive earliest due date 'YYYY-MM-DD'." })),
dueTo: t.Optional(t.String({ description: "Inclusive latest due date 'YYYY-MM-DD'." })),
+ createdFrom: instantQuery('Inclusive earliest creation time.'),
+ createdTo: instantQuery('Exclusive latest creation time.'),
+ updatedFrom: instantQuery('Inclusive earliest last-update time.'),
+ updatedTo: instantQuery('Exclusive latest last-update time.'),
includeArchived: t.Optional(
t.String({ description: "'true' to include archived issues. Default false." }),
),
diff --git a/apps/api/src/modules/issues/service.ts b/apps/api/src/modules/issues/service.ts
index 39ff2057..ddaac867 100644
--- a/apps/api/src/modules/issues/service.ts
+++ b/apps/api/src/modules/issues/service.ts
@@ -25,6 +25,7 @@ import {
inArray,
isNotNull,
isNull,
+ lt,
lte,
ne,
notInArray,
@@ -274,8 +275,23 @@ export interface IssueSearchHit {
dueDate: string | null;
labelIds: number[];
archived: boolean;
+ createdAt: string;
+ updatedAt: string;
+ completedAt: string | null;
}
+// When an issue entered the completed state it is still in, read the way the
+// analytics closings() read it: moves between completed columns are one stretch.
+const completedAt = sql<Date | null>`(
+ SELECT min(s.entered_at) FROM ${issueStatus} s
+ WHERE s.issue_id = ${issue}.id
+ AND s.state_type = 'completed'
+ AND NOT EXISTS (
+ SELECT 1 FROM ${issueStatus} p
+ WHERE p.issue_id = s.issue_id
+ AND p.state_type IS DISTINCT FROM 'completed'
+ AND (p.entered_at, p.id) > (s.entered_at, s.id)))`.mapWith(issueStatus.enteredAt);
+
// Escapes LIKE metacharacters so the query is matched literally (Postgres LIKE uses
// '\' as the default escape character).
function escapeLike(value: string): string {
@@ -291,7 +307,12 @@ function escapeLike(value: string): string {
// sets it; list defaults to active only).
export async function searchIssues(
project: ProjectRow,
- filters: IssueQuery,
+ filters: IssueQuery & {
+ createdFrom?: Date;
+ createdTo?: Date;
+ updatedFrom?: Date;
+ updatedTo?: Date;
+ },
opts: { includeArchived?: boolean } = {},
): Promise<IssueSearchHit[]> {
const conds: SQL[] = [eq(issue.projectId, project.id)];
@@ -383,6 +404,10 @@ export async function searchIssues(
// A null due date never falls in a range, so gte/lte alone exclude it.
if (filters.dueFrom !== undefined) conds.push(gte(issue.dueDate, filters.dueFrom));
if (filters.dueTo !== undefined) conds.push(lte(issue.dueDate, filters.dueTo));
+ if (filters.createdFrom) conds.push(gte(issue.createdAt, filters.createdFrom));
+ if (filters.createdTo) conds.push(lt(issue.createdAt, filters.createdTo));
+ if (filters.updatedFrom) conds.push(gte(issue.updatedAt, filters.updatedFrom));
+ if (filters.updatedTo) conds.push(lt(issue.updatedAt, filters.updatedTo));
// Exact number match first (if any), then most recently updated.
const orderBy =
@@ -408,6 +433,9 @@ export async function searchIssues(
priority: issue.priority,
dueDate: issue.dueDate,
archivedAt: issue.archivedAt,
+ createdAt: issue.createdAt,
+ updatedAt: issue.updatedAt,
+ completedAt,
})
.from(issue)
.where(and(...conds))
@@ -430,6 +458,9 @@ export async function searchIssues(
dueDate: r.dueDate,
labelIds: [],
archived: r.archivedAt !== null,
+ createdAt: iso(r.createdAt),
+ updatedAt: iso(r.updatedAt),
+ completedAt: r.completedAt ? iso(r.completedAt) : null,
}));
await attachLabels(hits);
return hits;
diff --git a/apps/api/src/shared/lib.ts b/apps/api/src/shared/lib.ts
index 5aca5aad..5627fb79 100644
--- a/apps/api/src/shared/lib.ts
+++ b/apps/api/src/shared/lib.ts
@@ -23,6 +23,15 @@ export class HttpError extends Error {
// (Drizzle's default mode for date), so no timezone is ever applied to them.
export const iso = (value: Date): string => value.toISOString();
+// A timestamp from a query string. Empty means not set: a tool-calling model fills
+// optional fields with "".
+export function instantParam(name: string, value: string | undefined): Date | undefined {
+ if (!value) return undefined;
+ const at = new Date(value);
+ if (Number.isNaN(at.getTime())) throw new HttpError(400, `${name} is not a valid ISO timestamp`);
+ return at;
+}
+
// numeric columns come back as strings; coerce to a JS number.
export const num = (value: unknown): number => (value == null ? 0 : Number(value));
diff --git a/apps/api/src/shared/schemas.ts b/apps/api/src/shared/schemas.ts
index dc4f5d4f..49c90610 100644
--- a/apps/api/src/shared/schemas.ts
+++ b/apps/api/src/shared/schemas.ts
@@ -3,3 +3,7 @@ import { t } from 'elysia';
// A calendar day, as the `date` columns hold it.
export const isoDate = (description: string) =>
t.String({ pattern: '^\\d{4}-\\d{2}-\\d{2}$', format: 'date', description });
+
+// A query bound on a timestamptz column, parsed with instantParam.
+export const instantQuery = (description: string) =>
+ t.Optional(t.String({ description: `${description} ISO timestamp or YYYY-MM-DD.` }));