@atproto/ozone 0.9.2 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (115) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +8 -0
  3. package/dist/api/index.d.ts.map +1 -1
  4. package/dist/api/index.js +2 -0
  5. package/dist/api/index.js.map +1 -1
  6. package/dist/api/queue/createQueue.d.ts.map +1 -1
  7. package/dist/api/queue/createQueue.js +5 -1
  8. package/dist/api/queue/createQueue.js.map +1 -1
  9. package/dist/api/queue/updateQueue.d.ts.map +1 -1
  10. package/dist/api/queue/updateQueue.js +2 -0
  11. package/dist/api/queue/updateQueue.js.map +1 -1
  12. package/dist/api/safelink/addRule.d.ts.map +1 -1
  13. package/dist/api/safelink/addRule.js +2 -1
  14. package/dist/api/safelink/addRule.js.map +1 -1
  15. package/dist/api/safelink/queryRules.d.ts.map +1 -1
  16. package/dist/api/safelink/queryRules.js +1 -0
  17. package/dist/api/safelink/queryRules.js.map +1 -1
  18. package/dist/api/safelink/removeRule.d.ts.map +1 -1
  19. package/dist/api/safelink/removeRule.js +2 -1
  20. package/dist/api/safelink/removeRule.js.map +1 -1
  21. package/dist/api/safelink/syncSource.d.ts +4 -0
  22. package/dist/api/safelink/syncSource.d.ts.map +1 -0
  23. package/dist/api/safelink/syncSource.js +24 -0
  24. package/dist/api/safelink/syncSource.js.map +1 -0
  25. package/dist/api/safelink/updateRule.d.ts.map +1 -1
  26. package/dist/api/safelink/updateRule.js +2 -1
  27. package/dist/api/safelink/updateRule.js.map +1 -1
  28. package/dist/assignment/index.d.ts +2 -0
  29. package/dist/assignment/index.d.ts.map +1 -1
  30. package/dist/assignment/index.js +10 -0
  31. package/dist/assignment/index.js.map +1 -1
  32. package/dist/context.js +1 -1
  33. package/dist/context.js.map +1 -1
  34. package/dist/daemon/context.js +1 -1
  35. package/dist/daemon/context.js.map +1 -1
  36. package/dist/daemon/scheduled-action-processor.d.ts.map +1 -1
  37. package/dist/daemon/scheduled-action-processor.js +1 -0
  38. package/dist/daemon/scheduled-action-processor.js.map +1 -1
  39. package/dist/db/migrations/20261016T000000000Z-add-report-queue-tag-criteria.d.ts +4 -0
  40. package/dist/db/migrations/20261016T000000000Z-add-report-queue-tag-criteria.d.ts.map +1 -0
  41. package/dist/db/migrations/20261016T000000000Z-add-report-queue-tag-criteria.js +15 -0
  42. package/dist/db/migrations/20261016T000000000Z-add-report-queue-tag-criteria.js.map +1 -0
  43. package/dist/db/migrations/20261016T174053481Z-add-safelink-rule-source.d.ts +4 -0
  44. package/dist/db/migrations/20261016T174053481Z-add-safelink-rule-source.d.ts.map +1 -0
  45. package/dist/db/migrations/20261016T174053481Z-add-safelink-rule-source.js +21 -0
  46. package/dist/db/migrations/20261016T174053481Z-add-safelink-rule-source.js.map +1 -0
  47. package/dist/db/migrations/index.d.ts +2 -0
  48. package/dist/db/migrations/index.d.ts.map +1 -1
  49. package/dist/db/migrations/index.js +2 -0
  50. package/dist/db/migrations/index.js.map +1 -1
  51. package/dist/db/schema/report_queue.d.ts +8 -0
  52. package/dist/db/schema/report_queue.d.ts.map +1 -1
  53. package/dist/db/schema/report_queue.js.map +1 -1
  54. package/dist/db/schema/safelink.d.ts +2 -0
  55. package/dist/db/schema/safelink.d.ts.map +1 -1
  56. package/dist/db/schema/safelink.js.map +1 -1
  57. package/dist/inbox/appeal.d.ts.map +1 -1
  58. package/dist/inbox/appeal.js +22 -9
  59. package/dist/inbox/appeal.js.map +1 -1
  60. package/dist/lexicons/social/grain/photo.defs.d.ts +11 -11
  61. package/dist/lexicons/social/grain/photo.defs.d.ts.map +1 -1
  62. package/dist/lexicons/social/grain/photo.defs.js +1 -1
  63. package/dist/lexicons/social/grain/photo.defs.js.map +1 -1
  64. package/dist/lexicons/tools/ozone/moderation/defs.defs.d.ts +4 -0
  65. package/dist/lexicons/tools/ozone/moderation/defs.defs.d.ts.map +1 -1
  66. package/dist/lexicons/tools/ozone/moderation/defs.defs.js +1 -1
  67. package/dist/lexicons/tools/ozone/moderation/defs.defs.js.map +1 -1
  68. package/dist/lexicons/tools/ozone/queue/createQueue.defs.d.ts +13 -1
  69. package/dist/lexicons/tools/ozone/queue/createQueue.defs.d.ts.map +1 -1
  70. package/dist/lexicons/tools/ozone/queue/createQueue.defs.js +2 -2
  71. package/dist/lexicons/tools/ozone/queue/createQueue.defs.js.map +1 -1
  72. package/dist/lexicons/tools/ozone/queue/defs.defs.d.ts +9 -1
  73. package/dist/lexicons/tools/ozone/queue/defs.defs.d.ts.map +1 -1
  74. package/dist/lexicons/tools/ozone/queue/defs.defs.js +1 -1
  75. package/dist/lexicons/tools/ozone/queue/defs.defs.js.map +1 -1
  76. package/dist/lexicons/tools/ozone/safelink/addRule.defs.d.ts +7 -1
  77. package/dist/lexicons/tools/ozone/safelink/addRule.defs.d.ts.map +1 -1
  78. package/dist/lexicons/tools/ozone/safelink/addRule.defs.js +2 -2
  79. package/dist/lexicons/tools/ozone/safelink/addRule.defs.js.map +1 -1
  80. package/dist/lexicons/tools/ozone/safelink/defs.defs.d.ts +10 -2
  81. package/dist/lexicons/tools/ozone/safelink/defs.defs.d.ts.map +1 -1
  82. package/dist/lexicons/tools/ozone/safelink/defs.defs.js +3 -3
  83. package/dist/lexicons/tools/ozone/safelink/defs.defs.js.map +1 -1
  84. package/dist/lexicons/tools/ozone/safelink/removeRule.defs.d.ts +6 -0
  85. package/dist/lexicons/tools/ozone/safelink/removeRule.defs.d.ts.map +1 -1
  86. package/dist/lexicons/tools/ozone/safelink/removeRule.defs.js +1 -1
  87. package/dist/lexicons/tools/ozone/safelink/removeRule.defs.js.map +1 -1
  88. package/dist/lexicons/tools/ozone/safelink/syncSource.d.ts +3 -0
  89. package/dist/lexicons/tools/ozone/safelink/syncSource.d.ts.map +1 -0
  90. package/dist/lexicons/tools/ozone/safelink/syncSource.defs.d.ts +50 -0
  91. package/dist/lexicons/tools/ozone/safelink/syncSource.defs.d.ts.map +1 -0
  92. package/dist/lexicons/tools/ozone/safelink/syncSource.defs.js +18 -0
  93. package/dist/lexicons/tools/ozone/safelink/syncSource.defs.js.map +1 -0
  94. package/dist/lexicons/tools/ozone/safelink/syncSource.js +6 -0
  95. package/dist/lexicons/tools/ozone/safelink/syncSource.js.map +1 -0
  96. package/dist/lexicons/tools/ozone/safelink/updateRule.defs.d.ts +7 -1
  97. package/dist/lexicons/tools/ozone/safelink/updateRule.defs.d.ts.map +1 -1
  98. package/dist/lexicons/tools/ozone/safelink/updateRule.defs.js +2 -2
  99. package/dist/lexicons/tools/ozone/safelink/updateRule.defs.js.map +1 -1
  100. package/dist/lexicons/tools/ozone/safelink.d.ts +1 -0
  101. package/dist/lexicons/tools/ozone/safelink.d.ts.map +1 -1
  102. package/dist/lexicons/tools/ozone/safelink.js +1 -0
  103. package/dist/lexicons/tools/ozone/safelink.js.map +1 -1
  104. package/dist/mod-service/views.d.ts.map +1 -1
  105. package/dist/mod-service/views.js +1 -4
  106. package/dist/mod-service/views.js.map +1 -1
  107. package/dist/queue/service.d.ts +23 -6
  108. package/dist/queue/service.d.ts.map +1 -1
  109. package/dist/queue/service.js +293 -166
  110. package/dist/queue/service.js.map +1 -1
  111. package/dist/safelink/service.d.ts +23 -4
  112. package/dist/safelink/service.d.ts.map +1 -1
  113. package/dist/safelink/service.js +179 -20
  114. package/dist/safelink/service.js.map +1 -1
  115. package/package.json +7 -7
@@ -1,5 +1,5 @@
1
1
  import { sql } from 'kysely';
2
- import { currentDatetimeString } from '@atproto/lex';
2
+ import { currentDatetimeString, isDidString } from '@atproto/lex';
3
3
  import { AtUri } from '@atproto/syntax';
4
4
  import { InvalidRequestError } from '@atproto/xrpc-server';
5
5
  import { TimeIdKeyset, paginate } from '../db/pagination.js';
@@ -51,16 +51,22 @@ function reportRowFromEvent({ event, reportType, assignment, priority, createdAt
51
51
  /**
52
52
  * Find queue to route a report to.
53
53
  */
54
- function resolveAssignment(subjectType, collection, reportType, queues, now, explicitQueueId) {
54
+ function resolveAssignment(subjectType, collection, reportType, queues, now, explicitQueueId, reporterTags, accountTags) {
55
55
  if (explicitQueueId !== undefined) {
56
56
  const target = queues.find((q) => q.id === explicitQueueId);
57
57
  if (target)
58
58
  return { queueId: target.id, queuedAt: now, status: 'queued' };
59
59
  return { queueId: -1, queuedAt: null, status: 'open' };
60
60
  }
61
- const matched = findMatchingQueue(queues, subjectType, collection, reportType);
62
- if (matched)
63
- return { queueId: matched.id, queuedAt: now, status: 'queued' };
61
+ const matched = findMatchingQueue(queues, subjectType, collection, reportType, reporterTags, accountTags);
62
+ if (matched) {
63
+ return {
64
+ queueId: matched.id,
65
+ queuedAt: now,
66
+ status: 'queued',
67
+ routingNote: getQueueRoutingNote(matched, reporterTags, accountTags),
68
+ };
69
+ }
64
70
  return { queueId: -1, queuedAt: null, status: 'open' };
65
71
  }
66
72
  /**
@@ -75,14 +81,15 @@ export function parseModTool(modTool) {
75
81
  return { queueId, isAutomated };
76
82
  }
77
83
  export class QueueService {
78
- constructor(db) {
84
+ constructor(db, serviceDid) {
79
85
  this.db = db;
86
+ this.serviceDid = serviceDid;
80
87
  }
81
- static creator() {
82
- return (db) => new QueueService(db);
88
+ static creator(serviceDid) {
89
+ return (db) => new QueueService(db, serviceDid);
83
90
  }
84
91
  /** Insert an immediately routed report in the caller's transaction. */
85
- async insertReportFromEvent({ event, reportType, queueId, queuedAt, actionEventIds, }) {
92
+ async insertReportFromEvent({ event, reportType, queueId, queuedAt, actionEventIds, routingNote, }) {
86
93
  this.db.assertTransaction();
87
94
  const priorities = await resolveReportPriorities(this.db, [reportType]);
88
95
  const assignment = {
@@ -102,8 +109,32 @@ export class QueueService {
102
109
  }))
103
110
  .returning('id')
104
111
  .executeTakeFirstOrThrow();
112
+ if (routingNote) {
113
+ await this.insertRoutingNotes([{ reportId: inserted.id, internalNote: routingNote }], event.createdAt);
114
+ }
105
115
  return inserted.id;
106
116
  }
117
+ /**
118
+ * Insert internal routing notes for reports.
119
+ */
120
+ async insertRoutingNotes(notes, createdAt) {
121
+ this.db.assertTransaction();
122
+ if (!notes.length)
123
+ return;
124
+ await this.db.db
125
+ .insertInto('report_activity')
126
+ .values(notes.map((note) => ({
127
+ ...note,
128
+ activityType: 'noteActivity',
129
+ previousStatus: null,
130
+ publicNote: null,
131
+ meta: null,
132
+ isAutomated: true,
133
+ createdBy: this.serviceDid,
134
+ createdAt,
135
+ })))
136
+ .execute();
137
+ }
107
138
  async assertRecommendedPolicies(recommendedPolicies) {
108
139
  const { options } = await new SettingService(this.db).query({
109
140
  limit: 1,
@@ -119,7 +150,7 @@ export class QueueService {
119
150
  throw new InvalidRequestError(`Unknown recommended policy keys: ${invalid.join(', ')}`, 'InvalidRecommendedPolicies');
120
151
  }
121
152
  }
122
- async checkConflict({ name, subjectTypes, collection, reportTypes, recommendedLabels = [], excludeId, }) {
153
+ async checkConflict({ name, subjectTypes, collection, reportTypes, reporterTags = [], accountTags = [], recommendedLabels = [], excludeId, }) {
123
154
  // It's not ideal to load all rows and perform in memory checks in case we end up with a LOT of queues
124
155
  // but we are not foreseeing a lot of queue rows so this should be fine for the
125
156
  let qb = this.db.db
@@ -138,15 +169,28 @@ export class QueueService {
138
169
  if (conflictingLabels.length) {
139
170
  throw new InvalidRequestError(`Recommended labels already belong to queue ${existing.name}: ${conflictingLabels.join(', ')}`, 'ConflictingQueue');
140
171
  }
141
- const subjectTypesOverlap = subjectTypes.some((st) => existing.subjectTypes.includes(st));
142
- const collectionMatch = (collection ?? null) === existing.collection;
172
+ // @NOTE Distinct tag roles may overlap; queue IDs determine routing order.
173
+ if (!!reporterTags?.length !== !!existing.reporterTags?.length ||
174
+ (!reporterTags?.length &&
175
+ !!accountTags?.length !== !!existing.accountTags?.length)) {
176
+ continue;
177
+ }
178
+ const tagged = !!(reporterTags?.length || accountTags?.length);
179
+ const subjectTypesOverlap = subjectTypes.some((st) => existing.subjectTypes.includes(st) &&
180
+ (!tagged ||
181
+ st !== 'record' ||
182
+ collection == null ||
183
+ existing.collection === null ||
184
+ collection === existing.collection));
185
+ const collectionMatch = tagged || (collection ?? null) === existing.collection;
143
186
  const reportTypesOverlap = reportTypes.some((rt) => existing.reportTypes.includes(rt));
187
+ // @NOTE Different tag criteria can still match the same accounts.
144
188
  if (subjectTypesOverlap && collectionMatch && reportTypesOverlap) {
145
189
  throw new InvalidRequestError(`Queue configuration conflicts with existing queue: ${existing.name}`, 'ConflictingQueue');
146
190
  }
147
191
  }
148
192
  }
149
- async create({ name, subjectTypes, collection, reportTypes, description, recommendedPolicies, recommendedLabels = [], createdBy, }) {
193
+ async create({ name, subjectTypes, collection, reportTypes, reporterTags = [], accountTags = [], description, recommendedPolicies, recommendedLabels = [], createdBy, }) {
150
194
  const now = currentDatetimeString();
151
195
  return await this.db.db
152
196
  .insertInto('report_queue')
@@ -155,6 +199,8 @@ export class QueueService {
155
199
  subjectTypes: jsonb(subjectTypes),
156
200
  collection: collection ?? null,
157
201
  reportTypes: jsonb(reportTypes),
202
+ reporterTags: jsonb(reporterTags),
203
+ accountTags: jsonb(accountTags),
158
204
  description: description ?? null,
159
205
  recommendedPolicies: jsonb(recommendedPolicies),
160
206
  recommendedLabels: jsonb(recommendedLabels),
@@ -275,6 +321,8 @@ export class QueueService {
275
321
  subjectTypes: queue.subjectTypes,
276
322
  collection: (queue.collection ?? undefined),
277
323
  reportTypes: queue.reportTypes,
324
+ reporterTags: queue.reporterTags ?? [],
325
+ accountTags: queue.accountTags ?? [],
278
326
  description: queue.description ?? undefined,
279
327
  recommendedPolicies: queue.recommendedPolicies,
280
328
  recommendedLabels: queue.recommendedLabels,
@@ -303,6 +351,25 @@ export class QueueService {
303
351
  return view;
304
352
  });
305
353
  }
354
+ /** Load account-level tags once for routing, skipping unused tag criteria. */
355
+ async loadAccountTags(queues, dids) {
356
+ const usesTags = queues.some((queue) => hasTagCriteria(queue) &&
357
+ queue.subjectTypes.length > 0 &&
358
+ queue.reportTypes.length > 0);
359
+ if (!usesTags)
360
+ return new Map();
361
+ const accountDids = [...new Set(dids.filter(isDidString))];
362
+ if (!accountDids.length)
363
+ return new Map();
364
+ const accounts = await this.db.db
365
+ .selectFrom('moderation_subject_status')
366
+ .select(['did', 'tags'])
367
+ .where('did', 'in', accountDids)
368
+ .where('recordPath', '=', '')
369
+ .where('convoId', '=', '')
370
+ .execute();
371
+ return new Map(accounts.map((account) => [account.did, account.tags ?? []]));
372
+ }
306
373
  /**
307
374
  * Re-route unassigned reports and refresh their priority from current settings.
308
375
  * Used by the manual `tools.ozone.queue.routeReports` endpoint to pick up
@@ -310,151 +377,168 @@ export class QueueService {
310
377
  * by the daemon via `insertReportsFromEvents`, not here.
311
378
  */
312
379
  async assignReportBatch(params, opts) {
313
- const { queues } = await this.list({ limit: 1000, enabled: true });
314
- let query = this.db.db
315
- .selectFrom('report as r')
316
- .innerJoin('moderation_event as me', 'me.id', 'r.eventId')
317
- .select([
318
- 'r.id',
319
- 'r.status',
320
- 'r.reportType',
321
- 'r.recordPath',
322
- 'r.subjectMessageId',
323
- 'r.subjectConvoId',
324
- 'me.modTool',
325
- ])
326
- .where('r.status', '!=', 'closed')
327
- .where('r.id', '>=', params.start)
328
- .where('r.id', '<=', params.end)
329
- .orderBy('r.id', 'asc')
330
- .limit(params.limit);
331
- if (opts?.includeUnmatched) {
332
- query = query.where((eb) => eb.or([eb('r.queueId', 'is', null), eb('r.queueId', '=', -1)]));
333
- }
334
- else {
335
- query = query.where('r.queueId', 'is', null);
336
- }
337
- const reports = await query.execute();
338
- if (!reports.length) {
339
- return { processed: 0, assigned: 0, unmatched: 0, maxId: 0 };
340
- }
341
- const priorities = await resolveReportPriorities(this.db, reports.map((report) => report.reportType));
342
- const prioritiesByType = jsonb(Object.fromEntries(priorities));
343
- const priorityUpdates = {
344
- priorityLevel: sql `${prioritiesByType} -> "reportType" ->> 'level'`,
345
- priorityScore: sql `(${prioritiesByType} -> "reportType" ->> 'score')::integer`,
346
- priorityTargetMinutes: sql `(${prioritiesByType} -> "reportType" ->> 'targetResolutionMinutes')::integer`,
347
- };
348
- const now = currentDatetimeString();
349
- const matchedByQueue = new Map();
350
- const unmatchedIds = [];
351
- let maxReportId = 0;
352
- for (const report of reports) {
353
- const subjectType = report.subjectMessageId
354
- ? 'message'
355
- : report.subjectConvoId
356
- ? 'conversation'
357
- : report.recordPath
358
- ? 'record'
359
- : 'account';
360
- // recordPath is 'collection/rkey' for records, '' for accounts
361
- const slashIdx = report.recordPath.indexOf('/');
362
- const collection = slashIdx > 0 ? report.recordPath.slice(0, slashIdx) : null;
363
- const tool = parseModTool(report.modTool);
364
- const assignment = resolveAssignment(subjectType, collection, report.reportType, queues, now, tool.queueId);
365
- if (assignment.queueId !== -1) {
366
- // Existing-row UPDATE path uses handleReportUpdate so that already
367
- // escalated/closed/etc. reports keep their status — only open → queued
368
- // transitions emit a status change and an activity row.
369
- const result = handleReportUpdate(report.status, { type: 'queue' });
370
- const group = matchedByQueue.get(assignment.queueId) ?? [];
371
- group.push({
372
- id: report.id,
373
- queueId: assignment.queueId,
374
- nextStatus: result.nextStatus,
375
- activity: result.activity,
376
- });
377
- matchedByQueue.set(assignment.queueId, group);
380
+ return this.db.transaction(async (dbTxn) => {
381
+ const queueService = new QueueService(dbTxn, this.serviceDid);
382
+ const { queues } = await queueService.list({ limit: 1000, enabled: true });
383
+ let query = dbTxn.db
384
+ .selectFrom('report as r')
385
+ .innerJoin('moderation_event as me', 'me.id', 'r.eventId')
386
+ .select([
387
+ 'r.id',
388
+ 'r.status',
389
+ 'r.reportType',
390
+ 'r.did',
391
+ 'r.reporterDid',
392
+ 'r.recordPath',
393
+ 'r.subjectMessageId',
394
+ 'r.subjectConvoId',
395
+ 'me.modTool',
396
+ 'me.createdBy as eventReporterDid',
397
+ ])
398
+ .where('r.status', '!=', 'closed')
399
+ .where('r.id', '>=', params.start)
400
+ .where('r.id', '<=', params.end)
401
+ .orderBy('r.id', 'asc')
402
+ .limit(params.limit)
403
+ .forUpdate('r');
404
+ if (opts?.includeUnmatched) {
405
+ query = query.where((eb) => eb.or([eb('r.queueId', 'is', null), eb('r.queueId', '=', -1)]));
378
406
  }
379
407
  else {
380
- unmatchedIds.push(report.id);
408
+ query = query.where('r.queueId', 'is', null);
381
409
  }
382
- if (report.id > maxReportId)
383
- maxReportId = report.id;
384
- }
385
- // Bulk UPDATE matched reports — split by whether status should change.
386
- // handleReportUpdate returns nextStatus only for open → queued;
387
- // other statuses keep their current status but still get routed.
388
- for (const [queueId, group] of matchedByQueue) {
389
- const withTransition = group
390
- .filter((r) => r.nextStatus !== null)
391
- .map((r) => r.id);
392
- const withoutTransition = group
393
- .filter((r) => r.nextStatus === null)
394
- .map((r) => r.id);
395
- if (withTransition.length) {
396
- await this.db.db
410
+ const reports = await query.execute();
411
+ if (!reports.length) {
412
+ return { processed: 0, assigned: 0, unmatched: 0, maxId: 0 };
413
+ }
414
+ const accountTags = await queueService.loadAccountTags(queues, reports.flatMap((report) => [
415
+ report.did,
416
+ report.reporterDid ?? report.eventReporterDid,
417
+ ]));
418
+ const priorities = await resolveReportPriorities(dbTxn, reports.map((report) => report.reportType));
419
+ const prioritiesByType = jsonb(Object.fromEntries(priorities));
420
+ const priorityUpdates = {
421
+ priorityLevel: sql `${prioritiesByType} -> "reportType" ->> 'level'`,
422
+ priorityScore: sql `(${prioritiesByType} -> "reportType" ->> 'score')::integer`,
423
+ priorityTargetMinutes: sql `(${prioritiesByType} -> "reportType" ->> 'targetResolutionMinutes')::integer`,
424
+ };
425
+ const now = currentDatetimeString();
426
+ const matchedByQueue = new Map();
427
+ const unmatchedIds = [];
428
+ let maxReportId = 0;
429
+ for (const report of reports) {
430
+ const subjectType = report.subjectMessageId
431
+ ? 'message'
432
+ : report.subjectConvoId
433
+ ? 'conversation'
434
+ : report.recordPath
435
+ ? 'record'
436
+ : 'account';
437
+ // recordPath is 'collection/rkey' for records, '' for accounts
438
+ const slashIdx = report.recordPath.indexOf('/');
439
+ const collection = slashIdx > 0 ? report.recordPath.slice(0, slashIdx) : null;
440
+ const tool = parseModTool(report.modTool);
441
+ const assignment = resolveAssignment(subjectType, collection, report.reportType, queues, now, tool.queueId, accountTags.get(report.reporterDid ?? report.eventReporterDid) ?? [], accountTags.get(report.did) ?? []);
442
+ if (assignment.queueId !== -1) {
443
+ // Existing-row UPDATE path uses handleReportUpdate so that already
444
+ // escalated/closed/etc. reports keep their status — only open → queued
445
+ // transitions emit a status change and an activity row.
446
+ const result = handleReportUpdate(report.status, { type: 'queue' });
447
+ const group = matchedByQueue.get(assignment.queueId) ?? [];
448
+ group.push({
449
+ id: report.id,
450
+ queueId: assignment.queueId,
451
+ nextStatus: result.nextStatus,
452
+ activity: result.activity,
453
+ routingNote: assignment.routingNote,
454
+ });
455
+ matchedByQueue.set(assignment.queueId, group);
456
+ }
457
+ else {
458
+ unmatchedIds.push(report.id);
459
+ }
460
+ if (report.id > maxReportId)
461
+ maxReportId = report.id;
462
+ }
463
+ // Bulk UPDATE matched reports — split by whether status should change.
464
+ // handleReportUpdate returns nextStatus only for open → queued;
465
+ // other statuses keep their current status but still get routed.
466
+ for (const [queueId, group] of matchedByQueue) {
467
+ const withTransition = group
468
+ .filter((r) => r.nextStatus !== null)
469
+ .map((r) => r.id);
470
+ const withoutTransition = group
471
+ .filter((r) => r.nextStatus === null)
472
+ .map((r) => r.id);
473
+ if (withTransition.length) {
474
+ await dbTxn.db
475
+ .updateTable('report')
476
+ .set({
477
+ ...priorityUpdates,
478
+ queueId,
479
+ queuedAt: now,
480
+ status: 'queued',
481
+ updatedAt: now,
482
+ })
483
+ .where('id', 'in', withTransition)
484
+ .execute();
485
+ }
486
+ if (withoutTransition.length) {
487
+ await dbTxn.db
488
+ .updateTable('report')
489
+ .set({ ...priorityUpdates, queueId, queuedAt: now, updatedAt: now })
490
+ .where('id', 'in', withoutTransition)
491
+ .execute();
492
+ }
493
+ }
494
+ // Bulk UPDATE unmatched reports — status stays unchanged
495
+ if (unmatchedIds.length) {
496
+ await dbTxn.db
397
497
  .updateTable('report')
398
498
  .set({
399
499
  ...priorityUpdates,
400
- queueId,
401
- queuedAt: now,
402
- status: 'queued',
500
+ queueId: -1,
501
+ queuedAt: null,
403
502
  updatedAt: now,
404
503
  })
405
- .where('id', 'in', withTransition)
504
+ .where('id', 'in', unmatchedIds)
406
505
  .execute();
407
506
  }
408
- if (withoutTransition.length) {
409
- await this.db.db
410
- .updateTable('report')
411
- .set({ ...priorityUpdates, queueId, queuedAt: now, updatedAt: now })
412
- .where('id', 'in', withoutTransition)
413
- .execute();
507
+ // Bulk INSERT activities for matched reports that changed status.
508
+ if (opts?.serviceDid) {
509
+ const withActivities = [...matchedByQueue.values()]
510
+ .flat()
511
+ .filter((r) => r.activity !== null);
512
+ if (withActivities.length) {
513
+ await dbTxn.db
514
+ .insertInto('report_activity')
515
+ .values(withActivities.map((r) => ({
516
+ reportId: r.id,
517
+ activityType: r.activity.activityType,
518
+ previousStatus: r.activity.previousStatus,
519
+ internalNote: null,
520
+ publicNote: null,
521
+ meta: null,
522
+ isAutomated: true,
523
+ createdBy: opts.serviceDid,
524
+ createdAt: now,
525
+ })))
526
+ .execute();
527
+ }
414
528
  }
415
- }
416
- // Bulk UPDATE unmatched reports — status stays unchanged
417
- if (unmatchedIds.length) {
418
- await this.db.db
419
- .updateTable('report')
420
- .set({
421
- ...priorityUpdates,
422
- queueId: -1,
423
- queuedAt: null,
424
- updatedAt: now,
425
- })
426
- .where('id', 'in', unmatchedIds)
427
- .execute();
428
- }
429
- // Bulk INSERT activities for matched reports that changed status.
430
- if (opts?.serviceDid) {
431
- const withActivities = [...matchedByQueue.values()]
529
+ await queueService.insertRoutingNotes([...matchedByQueue.values()]
432
530
  .flat()
433
- .filter((r) => r.activity !== null);
434
- if (withActivities.length) {
435
- await this.db.db
436
- .insertInto('report_activity')
437
- .values(withActivities.map((r) => ({
438
- reportId: r.id,
439
- activityType: r.activity.activityType,
440
- previousStatus: r.activity.previousStatus,
441
- internalNote: null,
442
- publicNote: null,
443
- meta: null,
444
- isAutomated: true,
445
- createdBy: opts.serviceDid,
446
- createdAt: now,
447
- })))
448
- .execute();
449
- }
450
- }
451
- const assigned = [...matchedByQueue.values()].reduce((sum, g) => sum + g.length, 0);
452
- return {
453
- processed: reports.length,
454
- assigned,
455
- unmatched: unmatchedIds.length,
456
- maxId: maxReportId,
457
- };
531
+ .flatMap((report) => report.routingNote
532
+ ? [{ reportId: report.id, internalNote: report.routingNote }]
533
+ : []), now);
534
+ const assigned = [...matchedByQueue.values()].reduce((sum, g) => sum + g.length, 0);
535
+ return {
536
+ processed: reports.length,
537
+ assigned,
538
+ unmatched: unmatchedIds.length,
539
+ maxId: maxReportId,
540
+ };
541
+ });
458
542
  }
459
543
  /**
460
544
  * Read newly-created modEventReport rows from `moderation_event` and
@@ -465,8 +549,10 @@ export class QueueService {
465
549
  * Even when no queues are configured, report rows are still inserted with
466
550
  * `queueId = -1` so the invariant "every modEventReport has a `report` row"
467
551
  * holds.
552
+ * Expected to be called within a database transaction.
468
553
  */
469
554
  async insertReportsFromEvents(params) {
555
+ this.db.assertTransaction();
470
556
  const { queues } = await this.list({ limit: 1000, enabled: true });
471
557
  let query = this.db.db
472
558
  .selectFrom('moderation_event')
@@ -491,6 +577,7 @@ export class QueueService {
491
577
  if (!events.length) {
492
578
  return { processed: 0, assigned: 0, unmatched: 0, maxEventId: 0 };
493
579
  }
580
+ const accountTags = await this.loadAccountTags(queues, events.flatMap((event) => [event.createdBy, event.subjectDid]));
494
581
  const now = currentDatetimeString();
495
582
  let maxEventId = 0;
496
583
  let assigned = 0;
@@ -498,6 +585,7 @@ export class QueueService {
498
585
  const reportTypes = events.map((event) => event.meta?.reportType ??
499
586
  com.atproto.moderation.defs.ReasonOther);
500
587
  const priorities = await resolveReportPriorities(this.db, reportTypes);
588
+ const routingNotes = new Map();
501
589
  const rows = events.map((event) => {
502
590
  const subjectType = subjectTypeFromEvent(event);
503
591
  let collection = null;
@@ -509,13 +597,16 @@ export class QueueService {
509
597
  com.atproto.moderation.defs.ReasonOther;
510
598
  const priority = priorities.get(reportType);
511
599
  const tool = parseModTool(event.modTool);
512
- const assignment = resolveAssignment(subjectType, collection, reportType, queues, now, tool.queueId);
600
+ const assignment = resolveAssignment(subjectType, collection, reportType, queues, now, tool.queueId, accountTags.get(event.createdBy) ?? [], accountTags.get(event.subjectDid) ?? []);
513
601
  if (assignment.queueId === -1)
514
602
  unmatched++;
515
603
  else
516
604
  assigned++;
517
605
  if (event.id > maxEventId)
518
606
  maxEventId = event.id;
607
+ if (assignment.routingNote) {
608
+ routingNotes.set(event.id, assignment.routingNote);
609
+ }
519
610
  return reportRowFromEvent({
520
611
  event,
521
612
  reportType,
@@ -524,21 +615,27 @@ export class QueueService {
524
615
  createdAt: now,
525
616
  });
526
617
  });
527
- // On conflict, repair a missing reporter DID without changing the report's
528
- // queue assignment or status.
529
- await this.db.db
618
+ const inserted = await this.db.db
530
619
  .insertInto('report')
531
620
  .values(rows)
532
- .onConflict((oc) => oc
533
- .column('eventId')
534
- .doUpdateSet({ reporterDid: sql `excluded."reporterDid"` })
535
- .where('report.reporterDid', 'is', null))
621
+ .onConflict((oc) => oc.column('eventId').doNothing())
622
+ .returning(['id', 'eventId'])
536
623
  .execute();
537
- // Activity rows are intentionally not emitted: a freshly-inserted report
538
- // has no prior state to "transition" from. Activity rows record state
539
- // changes, and being born already-queued is not a state change. This
540
- // matches `handleReportUpdate`'s design where activity is only emitted
541
- // on real transitions.
624
+ // @NOTE Keep repairs separate so only new reports receive routing notes.
625
+ if (inserted.length < rows.length) {
626
+ await this.db.db
627
+ .updateTable('report')
628
+ .from('moderation_event as event')
629
+ .set((eb) => ({ reporterDid: eb.ref('event.createdBy') }))
630
+ .whereRef('report.eventId', '=', 'event.id')
631
+ .where('report.eventId', 'in', events.map((event) => event.id))
632
+ .where('report.reporterDid', 'is', null)
633
+ .execute();
634
+ }
635
+ await this.insertRoutingNotes(inserted.flatMap((report) => {
636
+ const internalNote = routingNotes.get(report.eventId);
637
+ return internalNote ? [{ reportId: report.id, internalNote }] : [];
638
+ }), now);
542
639
  return {
543
640
  processed: events.length,
544
641
  assigned,
@@ -547,19 +644,49 @@ export class QueueService {
547
644
  };
548
645
  }
549
646
  }
550
- export function findMatchingQueue(queues, subjectType, collection, reportType) {
551
- if (!reportType)
552
- return null;
647
+ /** Whether a queue requires tags on the reporter or reported account. */
648
+ export function hasTagCriteria(queue) {
649
+ return !!(queue.reporterTags?.length || queue.accountTags?.length);
650
+ }
651
+ /** Snapshot the mutable tag values that matched an automatic destination. */
652
+ export function getQueueRoutingNote(queue, reporterTags, accountTags) {
653
+ const matches = [
654
+ ['reporterTags', queue.reporterTags ?? [], reporterTags],
655
+ ['accountTags', queue.accountTags ?? [], accountTags],
656
+ ];
657
+ const criteria = matches.flatMap(([field, required, actual]) => {
658
+ const matched = required.filter((tag) => actual.includes(tag));
659
+ return matched.length ? [`${field}: ${JSON.stringify(matched)}`] : [];
660
+ });
661
+ if (!criteria.length)
662
+ return undefined;
663
+ return `Automatically routed to queue ${JSON.stringify(queue.name)} (ID ${queue.id}). Matched ${criteria.join('; ')}.`;
664
+ }
665
+ export function findMatchingQueue(queues, subjectType, collection, reportType, reporterTags = [], accountTags = []) {
666
+ let matched = null;
553
667
  for (const queue of queues) {
668
+ if (!queue.enabled || queue.deletedAt !== null)
669
+ continue;
554
670
  const subjectTypeMatch = queue.subjectTypes.includes(subjectType);
555
671
  const collectionMatch = subjectType === 'record' && queue.collection !== null
556
672
  ? (collection ?? null) === queue.collection
557
673
  : true;
558
- const reportTypeMatch = queue.reportTypes.includes(reportType);
559
- if (subjectTypeMatch && collectionMatch && reportTypeMatch) {
560
- return queue;
674
+ const reportTypeMatch = reportType !== undefined && queue.reportTypes.includes(reportType);
675
+ const queueReporterTags = queue.reporterTags ?? [];
676
+ const queueAccountTags = queue.accountTags ?? [];
677
+ const reporterTagsMatch = queueReporterTags.length === 0 ||
678
+ queueReporterTags.some((tag) => reporterTags.includes(tag));
679
+ const accountTagsMatch = queueAccountTags.length === 0 ||
680
+ queueAccountTags.some((tag) => accountTags.includes(tag));
681
+ if (subjectTypeMatch &&
682
+ collectionMatch &&
683
+ reportTypeMatch &&
684
+ reporterTagsMatch &&
685
+ accountTagsMatch &&
686
+ (matched === null || queue.id < matched.id)) {
687
+ matched = queue;
561
688
  }
562
689
  }
563
- return null;
690
+ return matched;
564
691
  }
565
692
  //# sourceMappingURL=service.js.map