mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - Plugins subscribe to core domain events such as `issue.created` through the `events.subscribe` capability > - Issues created through `POST /issues/:id/children` or accepted-plan decompositions only log the `issue.child_created` activity action, and that action was not in the plugin event bridge in `activity-log.ts` > - Subscribers to `issue.created` therefore never observe child issues, so plugin workflows that track every new issue silently miss decompositions > - This pull request maps `issue.child_created` to the `issue.created` plugin event type > - The benefit is that plugin subscribers observe every new issue through one event type, and the bridged payload matches a top-level creation because the activity row already carries `entityType: "issue"` and the new child issue id ## Linked Issues or Issue Description Fixes: #13466 ## What Changed - Added `issue_child_created: "issue.created"` to `ACTIVITY_ACTION_TO_PLUGIN_EVENT` in `server/src/services/activity-log.ts`, with a comment explaining why the bridge is safe (same entity shape as top-level creation) - Added `server/src/__tests__/activity-plugin-event-bridge.test.ts` covering: - `issue.child_created` is bridged to `issue.created` with the child issue id as the event entity - a native `issue.created` action still passes through unchanged - unmapped actions still emit no plugin event ## Verification ```sh ./node_modules/.bin/vitest run server/src/__tests__/activity-plugin-event-bridge.test.ts ``` All 3 tests pass against an embedded Postgres instance. Also ran `git diff --check`. ## Risks Low risk. The change only adds a mapping entry; no existing activity action is remapped or removed. Plugins that already handle `issue.created` will now also receive child creations. The activity details payload carries an extra `parentId` field for child creations, which additive subscribers should tolerate. No migration or schema change. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used OpenAI Codex (GPT-5, coding-agent mode, repository tool use) — assisted with root-cause analysis, the mapping change, and the new test file. ## Checklist - [x] I have included a thinking path that traces from project context to this change - [x] I have specified the model used (with version and capability details) - [x] I have checked ROADMAP.md and confirmed this PR does not duplicate planned core work - [x] I have searched GitHub for duplicate or related PRs and linked them above - [x] I have either (a) linked existing issues with `Fixes: #` / `Closes #` / `Refs #` OR (b) described the issue in-PR following the relevant issue template - [x] I have not referenced internal/instance-local Paperclip issues or links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip` URLs) - [x] My branch name describes the change (e.g. `docs/...`, `fix/...`) and contains no internal Paperclip ticket id or instance-derived details - [x] I have run tests locally and they pass - [x] I have added or updated tests where applicable - [x] I have updated relevant documentation to reflect my changes - [x] I have considered and documented any risks above - [x] All Paperclip CI gates are green - [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups - [x] I will address all Greptile and reviewer comments before requesting merge Co-authored-by: 馨冉 <xinxincui239@gmail.com>
386 lines
13 KiB
TypeScript
386 lines
13 KiB
TypeScript
import { isDashboardActivity } from "./responsibility-privacy.js";
|
|
import { notifyActiveRunSilence } from "./live-run-recovery-notifications.js";
|
|
import { DELIVERY_QUEUES, notifyDeliveryWork } from "./delivery-work-notifications.js";
|
|
import { beginRunPhase } from "./execution-preparation-timing.js";
|
|
import type { ActivityPublication } from "../types/activity-publication.js";
|
|
export type { ActivityPublication } from "../types/activity-publication.js";
|
|
import { randomUUID } from "node:crypto";
|
|
import { and, eq, is } from "drizzle-orm";
|
|
import { PgTransaction } from "drizzle-orm/pg-core";
|
|
import type { Db } from "@paperclipai/db";
|
|
import { activityLog, agentApiKeys, companies, heartbeatRuns, issues } from "@paperclipai/db";
|
|
import { isUuidLike, PLUGIN_EVENT_TYPES, type PluginEventType } from "@paperclipai/shared";
|
|
import type { PluginEvent } from "@paperclipai/plugin-sdk";
|
|
import { publishLiveEvent } from "./live-events.js";
|
|
import { redactCurrentUserValue } from "../log-redaction.js";
|
|
import { sanitizeRecord } from "../redaction.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
import type { PluginEventBus } from "./plugin-event-bus.js";
|
|
import { instanceSettingsService } from "./instance-settings.js";
|
|
|
|
const PLUGIN_EVENT_SET: ReadonlySet<string> = new Set(PLUGIN_EVENT_TYPES);
|
|
const ACTIVITY_ACTION_TO_PLUGIN_EVENT: Readonly<Record<string, PluginEventType>> = {
|
|
// Child creation routes (POST /issues/:id/children, accepted-plan
|
|
// decompositions) log only `issue.child_created`. Bridge it so plugins
|
|
// subscribed to `issue.created` observe every new issue, not just top-level
|
|
// creations. The activity row carries entityType "issue" and the new child
|
|
// issue id, so the bridged payload matches a top-level creation.
|
|
issue_child_created: "issue.created",
|
|
issue_comment_added: "issue.comment.created",
|
|
issue_comment_created: "issue.comment.created",
|
|
issue_document_created: "issue.document.created",
|
|
issue_document_updated: "issue.document.updated",
|
|
issue_document_deleted: "issue.document.deleted",
|
|
issue_blockers_updated: "issue.relations.updated",
|
|
approval_approved: "approval.decided",
|
|
approval_rejected: "approval.decided",
|
|
approval_revision_requested: "approval.decided",
|
|
budget_soft_threshold_crossed: "budget.incident.opened",
|
|
budget_hard_threshold_crossed: "budget.incident.opened",
|
|
budget_incident_resolved: "budget.incident.resolved",
|
|
};
|
|
|
|
let _pluginEventBus: PluginEventBus | null = null;
|
|
|
|
/** Wire the plugin event bus so domain events are forwarded to plugins. */
|
|
export function setPluginEventBus(bus: PluginEventBus): void {
|
|
if (_pluginEventBus) {
|
|
logger.warn("setPluginEventBus called more than once, replacing existing bus");
|
|
}
|
|
_pluginEventBus = bus;
|
|
}
|
|
|
|
function eventTypeForActivityAction(action: string): PluginEventType | null {
|
|
if (PLUGIN_EVENT_SET.has(action)) return action as PluginEventType;
|
|
return ACTIVITY_ACTION_TO_PLUGIN_EVENT[action.replaceAll(".", "_")] ?? null;
|
|
}
|
|
|
|
export function publishPluginDomainEvent(event: PluginEvent): void {
|
|
if (!_pluginEventBus) return;
|
|
void _pluginEventBus.emit(event).then(({ errors }) => {
|
|
for (const { pluginId, error } of errors) {
|
|
logger.warn({ pluginId, eventType: event.eventType, err: error }, "plugin event handler failed");
|
|
}
|
|
}).catch(() => {});
|
|
}
|
|
|
|
export interface LogActivityInput {
|
|
companyId: string;
|
|
actorType: "agent" | "user" | "system" | "plugin";
|
|
actorId: string;
|
|
action: string;
|
|
entityType: string;
|
|
entityId: string;
|
|
agentId?: string | null;
|
|
runId?: string | null;
|
|
agentApiKeyId?: string | null;
|
|
issueId?: string | null;
|
|
details?: Record<string, unknown> | null;
|
|
responsibleUserIdOverride?: string | null;
|
|
authorization?: { action: string; operation: string; reason: string };
|
|
}
|
|
|
|
|
|
export type ActivityDetailsRedactor = (
|
|
details: Record<string, unknown> | null,
|
|
) => Record<string, unknown> | null;
|
|
|
|
export interface PersistActivityOptions {
|
|
redactor?: ActivityDetailsRedactor;
|
|
}
|
|
|
|
export async function createActivityDetailsRedactor(db: Db): Promise<ActivityDetailsRedactor> {
|
|
const currentUserRedactionOptions = {
|
|
enabled: (await instanceSettingsService(db).getGeneral()).censorUsernameInLogs,
|
|
};
|
|
return (details: Record<string, unknown> | null) => (
|
|
details ? redactCurrentUserValue(sanitizeRecord(details), currentUserRedactionOptions) : null
|
|
);
|
|
}
|
|
|
|
export async function redactActivityDetails(db: Db, details: Record<string, unknown> | null) {
|
|
if (!details) return null;
|
|
return (await createActivityDetailsRedactor(db))(details);
|
|
}
|
|
|
|
function readNonEmptyString(value: unknown) {
|
|
return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
|
|
}
|
|
|
|
export async function resolveResponsibleUserIdForActivity(db: Db, input: LogActivityInput) {
|
|
if (input.responsibleUserIdOverride !== undefined) {
|
|
return readNonEmptyString(input.responsibleUserIdOverride);
|
|
}
|
|
if (input.actorType === "user") return readNonEmptyString(input.actorId);
|
|
|
|
const runId = readNonEmptyString(input.runId);
|
|
if (runId && isUuidLike(runId)) {
|
|
const run = await db
|
|
.select({ responsibleUserId: heartbeatRuns.responsibleUserId })
|
|
.from(heartbeatRuns)
|
|
.where(and(eq(heartbeatRuns.companyId, input.companyId), eq(heartbeatRuns.id, runId)))
|
|
.then((rows) => rows[0] ?? null);
|
|
const runResponsibleUserId = readNonEmptyString(run?.responsibleUserId);
|
|
if (runResponsibleUserId) return runResponsibleUserId;
|
|
}
|
|
|
|
const issueIdCandidate = readNonEmptyString(input.issueId)
|
|
?? (input.entityType === "issue" ? readNonEmptyString(input.entityId) : null);
|
|
const issueId = isUuidLike(issueIdCandidate) ? issueIdCandidate : null;
|
|
if (issueId) {
|
|
const issue = await db
|
|
.select({
|
|
responsibleUserId: issues.responsibleUserId,
|
|
createdByUserId: issues.createdByUserId,
|
|
})
|
|
.from(issues)
|
|
.where(and(eq(issues.companyId, input.companyId), eq(issues.id, issueId)))
|
|
.then((rows) => rows[0] ?? null);
|
|
const issueResponsibleUserId = readNonEmptyString(issue?.responsibleUserId)
|
|
?? readNonEmptyString(issue?.createdByUserId);
|
|
if (issueResponsibleUserId) return issueResponsibleUserId;
|
|
}
|
|
|
|
const agentApiKeyId = readNonEmptyString(input.agentApiKeyId);
|
|
const agentId = readNonEmptyString(input.agentId);
|
|
if (agentApiKeyId && isUuidLike(agentApiKeyId)) {
|
|
const apiKey = await db
|
|
.select({ responsibleUserId: agentApiKeys.responsibleUserId })
|
|
.from(agentApiKeys)
|
|
.where(and(
|
|
eq(agentApiKeys.companyId, input.companyId),
|
|
eq(agentApiKeys.id, agentApiKeyId),
|
|
...(agentId && isUuidLike(agentId) ? [eq(agentApiKeys.agentId, agentId)] : []),
|
|
))
|
|
.then((rows) => rows[0] ?? null);
|
|
const apiKeyResponsibleUserId = readNonEmptyString(apiKey?.responsibleUserId);
|
|
if (apiKeyResponsibleUserId) return apiKeyResponsibleUserId;
|
|
}
|
|
|
|
const company = await db
|
|
.select({ defaultResponsibleUserId: companies.defaultResponsibleUserId })
|
|
.from(companies)
|
|
.where(eq(companies.id, input.companyId))
|
|
.then((rows) => rows[0] ?? null);
|
|
return readNonEmptyString(company?.defaultResponsibleUserId);
|
|
}
|
|
|
|
export function publishActivity(publication: ActivityPublication) {
|
|
const finish = beginRunPhase("execution.realtime");
|
|
try {
|
|
if (isDashboardActivity(publication.payload.entityType)) {
|
|
// The company bus carries only an invalidation. Each viewer fetches their own data.
|
|
publishLiveEvent({
|
|
companyId: publication.companyId,
|
|
type: "activity.logged",
|
|
payload: { action: "responsibility.dashboard_changed", entityType: "responsibility" },
|
|
});
|
|
return;
|
|
}
|
|
publishLiveEvent({
|
|
companyId: publication.companyId,
|
|
type: "activity.logged",
|
|
payload: publication.payload,
|
|
});
|
|
if (publication.pluginEvent) publishPluginDomainEvent(publication.pluginEvent);
|
|
} finally { finish(); }
|
|
}
|
|
|
|
async function prepareActivityRow(
|
|
db: Db,
|
|
input: LogActivityInput,
|
|
redactor?: ActivityDetailsRedactor,
|
|
) {
|
|
const rawDetails = input.authorization
|
|
? {
|
|
...input.details,
|
|
permissionDecision: input.authorization,
|
|
...(input.agentApiKeyId ? { agentApiKeyId: input.agentApiKeyId } : {}),
|
|
}
|
|
: (input.details ?? null);
|
|
const redactedDetails = redactor
|
|
? redactor(rawDetails)
|
|
: await redactActivityDetails(db, rawDetails);
|
|
const responsibleUserId = await resolveResponsibleUserIdForActivity(db, input);
|
|
return { input, redactedDetails, responsibleUserId };
|
|
}
|
|
|
|
async function notifyIssueActivitySideEffects(runner: Db, input: LogActivityInput) {
|
|
if (input.entityType !== "issue") return;
|
|
await notifyDeliveryWork(runner, DELIVERY_QUEUES.mcpEvents, `task:${input.entityId}`);
|
|
if (
|
|
input.runId &&
|
|
input.action === "issue.updated" &&
|
|
["done", "cancelled"].includes(String(input.details?.status))
|
|
) {
|
|
await notifyActiveRunSilence(runner, {
|
|
companyId: input.companyId,
|
|
runId: input.runId,
|
|
});
|
|
}
|
|
}
|
|
|
|
function buildActivityPublication(
|
|
input: LogActivityInput,
|
|
redactedDetails: Record<string, unknown> | null,
|
|
responsibleUserId: string | null,
|
|
): ActivityPublication {
|
|
const payload = {
|
|
issueId: input.issueId ?? (input.entityType === "issue" ? input.entityId : null),
|
|
actorType: input.actorType,
|
|
actorId: input.actorId,
|
|
action: input.action,
|
|
entityType: input.entityType,
|
|
entityId: input.entityId,
|
|
agentId: input.agentId ?? null,
|
|
runId: input.runId ?? null,
|
|
responsibleUserId,
|
|
details: redactedDetails,
|
|
};
|
|
const pluginEventType = eventTypeForActivityAction(input.action);
|
|
const pluginEvent: PluginEvent | null = pluginEventType
|
|
? {
|
|
eventId: randomUUID(),
|
|
eventType: pluginEventType,
|
|
occurredAt: new Date().toISOString(),
|
|
actorId: input.actorId,
|
|
actorType: input.actorType,
|
|
entityId: input.entityId,
|
|
entityType: input.entityType,
|
|
companyId: input.companyId,
|
|
payload: {
|
|
...redactedDetails,
|
|
agentId: input.agentId ?? null,
|
|
runId: input.runId ?? null,
|
|
responsibleUserId,
|
|
},
|
|
}
|
|
: null;
|
|
return {
|
|
companyId: input.companyId,
|
|
payload,
|
|
pluginEvent,
|
|
};
|
|
}
|
|
|
|
function buildActivityLogRow(
|
|
prepared: Awaited<ReturnType<typeof prepareActivityRow>>,
|
|
receipt?: { id: string },
|
|
) {
|
|
const { input, redactedDetails, responsibleUserId } = prepared;
|
|
return {
|
|
...(receipt ? { id: receipt.id } : {}),
|
|
companyId: input.companyId,
|
|
actorType: input.actorType,
|
|
actorId: input.actorId,
|
|
action: input.action,
|
|
entityType: input.entityType,
|
|
entityId: input.entityId,
|
|
agentId: input.agentId ?? null,
|
|
runId: input.runId ?? null,
|
|
responsibleUserId,
|
|
details: redactedDetails,
|
|
};
|
|
}
|
|
|
|
export async function persistActivity(
|
|
db: Db,
|
|
input: LogActivityInput,
|
|
receipt?: { id: string },
|
|
options?: PersistActivityOptions,
|
|
) {
|
|
const prepared = await prepareActivityRow(
|
|
db,
|
|
input,
|
|
options?.redactor,
|
|
);
|
|
const insert = (runner: Db) =>
|
|
runner
|
|
.insert(activityLog)
|
|
.values(buildActivityLogRow(prepared, receipt))
|
|
.returning({ id: activityLog.id });
|
|
const insertIssueActivity = async (runner: Db) => {
|
|
await notifyIssueActivitySideEffects(runner, input);
|
|
return insert(runner);
|
|
};
|
|
const [activity] =
|
|
input.entityType === "issue"
|
|
? is(db, PgTransaction)
|
|
? await insertIssueActivity(db)
|
|
: await db.transaction(async (tx) => insertIssueActivity(tx as unknown as Db))
|
|
: await insert(db);
|
|
|
|
return {
|
|
activity,
|
|
publication: buildActivityPublication(
|
|
input,
|
|
prepared.redactedDetails,
|
|
prepared.responsibleUserId,
|
|
),
|
|
};
|
|
}
|
|
|
|
export async function logActivity(
|
|
db: Db,
|
|
input: LogActivityInput,
|
|
postCommitPublications?: ActivityPublication[],
|
|
options?: PersistActivityOptions,
|
|
) {
|
|
const { activity, publication } = await persistActivity(db, input, undefined, options);
|
|
if (postCommitPublications) {
|
|
postCommitPublications.push(publication);
|
|
} else {
|
|
publishActivity(publication);
|
|
}
|
|
return activity;
|
|
}
|
|
|
|
export async function logActivitiesBatch(
|
|
db: Db,
|
|
inputs: LogActivityInput[],
|
|
postCommitPublications?: ActivityPublication[],
|
|
options?: PersistActivityOptions,
|
|
) {
|
|
if (inputs.length === 0) return [];
|
|
if (inputs.length === 1) {
|
|
const single = await logActivity(db, inputs[0]!, postCommitPublications, options);
|
|
return single ? [single] : [];
|
|
}
|
|
|
|
const redactor = options?.redactor ?? (await createActivityDetailsRedactor(db));
|
|
const preparedRows = await Promise.all(
|
|
inputs.map((input) => prepareActivityRow(db, input, redactor)),
|
|
);
|
|
|
|
const insertBatch = async (runner: Db) => {
|
|
for (const { input } of preparedRows) {
|
|
await notifyIssueActivitySideEffects(runner, input);
|
|
}
|
|
return runner
|
|
.insert(activityLog)
|
|
.values(preparedRows.map((prepared) => buildActivityLogRow(prepared)))
|
|
.returning({ id: activityLog.id });
|
|
};
|
|
|
|
const hasIssueEntity = preparedRows.some(({ input }) => input.entityType === "issue");
|
|
const insertedActivities =
|
|
hasIssueEntity && !is(db, PgTransaction)
|
|
? await db.transaction(async (tx) => insertBatch(tx as unknown as Db))
|
|
: await insertBatch(db);
|
|
|
|
for (const { input, redactedDetails, responsibleUserId } of preparedRows) {
|
|
const publication = buildActivityPublication(
|
|
input,
|
|
redactedDetails,
|
|
responsibleUserId,
|
|
);
|
|
if (postCommitPublications) {
|
|
postCommitPublications.push(publication);
|
|
} else {
|
|
publishActivity(publication);
|
|
}
|
|
}
|
|
|
|
return insertedActivities;
|
|
}
|