feat: automation rules

Owners and admins can set rules of the kind «when a ticket is created,
moves, gets assigned, gets a comment or its pull request merges; if it is
of this type, priority, area or label; then move it, assign it, label it,
change its priority, comment or put it in the active sprint». Rules act as
TaskStream within the workflow, run once per event and trigger no others.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-10-08 15:53:31 +02:00
parent 1076205acc
commit 8994590b54
30 changed files with 2543 additions and 4 deletions

View File

@@ -0,0 +1,83 @@
import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import {
Automation,
AutomationsRepository,
} from '@task-stream/api/tracker/application';
import { Model } from 'mongoose';
import {
AutomationDoc,
AutomationRunDoc,
ReadModels,
fromDoc,
} from './read-model.schemas';
const DUPLICATE_KEY = 11000;
@Injectable()
export class MongoAutomationsRepository extends AutomationsRepository {
constructor(
@InjectModel(ReadModels.Automation)
private readonly automations: Model<AutomationDoc>,
@InjectModel(ReadModels.AutomationRun)
private readonly runs: Model<AutomationRunDoc>,
) {
super();
}
async findByProject(projectId: string): Promise<Automation[]> {
const docs = await this.automations
.find({ projectId })
.sort({ createdAt: 1 })
.lean<AutomationDoc[]>();
return docs.map((doc) => fromDoc(doc) as Automation);
}
async findActive(projectId: string): Promise<Automation[]> {
const docs = await this.automations
.find({ projectId, active: true })
.lean<AutomationDoc[]>();
return docs.map((doc) => fromDoc(doc) as Automation);
}
async findById(id: string): Promise<Automation | null> {
const doc = await this.automations.findById(id).lean<AutomationDoc>();
return doc ? (fromDoc(doc) as Automation) : null;
}
async insert({ id, ...rest }: Automation): Promise<void> {
await this.automations.create({ _id: id, ...rest });
}
async update(
id: string,
changes: Partial<Pick<Automation, 'name' | 'active'>>,
): Promise<void> {
if (Object.keys(changes).length)
await this.automations.updateOne({ _id: id }, { $set: changes });
}
async delete(id: string): Promise<void> {
await this.automations.deleteOne({ _id: id });
}
async claimRun(ruleId: string, eventKey: string): Promise<boolean> {
try {
await this.runs.create({ _id: `${ruleId}:${eventKey}`, at: new Date() });
return true;
} catch (error) {
if ((error as { code?: number }).code === DUPLICATE_KEY) return false;
throw error;
}
}
async recordRun(id: string, error: string | null): Promise<void> {
await this.automations.updateOne(
{ _id: id },
{
$inc: { runs: 1 },
$set: { lastRunAt: new Date().toISOString(), lastError: error },
},
);
}
}

View File

@@ -1,4 +1,7 @@
import { OutgoingWebhook } from '@task-stream/api/tracker/application';
import {
Automation,
OutgoingWebhook,
} from '@task-stream/api/tracker/application';
import {
ActivityReadModel,
CommentReadModel,
@@ -32,6 +35,12 @@ export type TimelineDoc = Doc<IssueTimelineEntry>;
export type NotificationDoc = Doc<NotificationReadModel>;
export type SavedFilterDoc = Doc<SavedFilterReadModel>;
export type OutgoingWebhookDoc = Omit<OutgoingWebhook, 'id'> & { _id: string };
export type AutomationDoc = Omit<Automation, 'id'> & { _id: string };
export interface AutomationRunDoc {
/** `ruleId:eventKey`: a rule runs once per event. */
_id: string;
at: Date;
}
export interface GitIntegrationDoc {
_id: string;
secret: string;
@@ -55,6 +64,8 @@ export const ReadModels = {
Sprint: 'SprintReadModel',
GitIntegration: 'GitIntegration',
OutgoingWebhook: 'OutgoingWebhook',
Automation: 'Automation',
AutomationRun: 'AutomationRun',
} as const;
const userRef = { _id: false, id: String, name: String };
@@ -218,6 +229,24 @@ export const OutgoingWebhookSchema = new Schema<OutgoingWebhookDoc>(
{ ...loose, collection: 'outgoing_webhooks' },
);
export const AutomationSchema = new Schema<AutomationDoc>(
{
_id: String,
projectId: { type: String, index: true },
active: Boolean,
createdBy: userRef,
createdAt: String,
},
{ ...loose, collection: 'automations' },
);
export const AutomationRunSchema = new Schema<AutomationRunDoc>(
{ _id: String, at: Date },
{ ...loose, collection: 'automation_runs' },
);
// Redeliveries happen within minutes; a month of memory is plenty.
AutomationRunSchema.index({ at: 1 }, { expireAfterSeconds: 30 * 86_400 });
export const READ_MODEL_SCHEMAS = [
{ name: ReadModels.Project, schema: ProjectSchema },
{ name: ReadModels.Issue, schema: IssueSchema },
@@ -226,6 +255,8 @@ export const READ_MODEL_SCHEMAS = [
{ name: ReadModels.Sprint, schema: SprintSchema },
{ name: ReadModels.GitIntegration, schema: GitIntegrationSchema },
{ name: ReadModels.OutgoingWebhook, schema: OutgoingWebhookSchema },
{ name: ReadModels.Automation, schema: AutomationSchema },
{ name: ReadModels.AutomationRun, schema: AutomationRunSchema },
{ name: ReadModels.Activity, schema: ActivitySchema },
{ name: ReadModels.Timeline, schema: TimelineSchema },
{ name: ReadModels.Notification, schema: NotificationSchema },

View File

@@ -34,6 +34,7 @@ import {
SavedFilterDoc,
GitIntegrationDoc,
OutgoingWebhookDoc,
AutomationDoc,
TimelineDoc,
} from './read-model.schemas';
import { upsertIfNewer } from './upsert-if-newer';
@@ -55,6 +56,8 @@ export class MongoUpsertMaterializedProjectRepository extends UpsertMaterialized
private readonly gitIntegrations: Model<GitIntegrationDoc>,
@InjectModel(ReadModels.OutgoingWebhook)
private readonly outgoingWebhooks: Model<OutgoingWebhookDoc>,
@InjectModel(ReadModels.Automation)
private readonly automations: Model<AutomationDoc>,
) {
super();
}
@@ -68,6 +71,7 @@ export class MongoUpsertMaterializedProjectRepository extends UpsertMaterialized
this.savedFilters.deleteMany({ projectId }),
this.gitIntegrations.deleteOne({ _id: projectId }),
this.outgoingWebhooks.deleteMany({ projectId }),
this.automations.deleteMany({ projectId }),
]);
}