@chatwarden/core 0.1.4 → 0.1.6

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 (46) hide show
  1. package/README.md +6 -4
  2. package/dist/src/audit.d.ts +1 -1
  3. package/dist/src/audit.d.ts.map +1 -1
  4. package/dist/src/audit.js +2 -0
  5. package/dist/src/audit.js.map +1 -1
  6. package/dist/src/chatwarden.d.ts +47 -0
  7. package/dist/src/chatwarden.d.ts.map +1 -1
  8. package/dist/src/chatwarden.js +54 -30
  9. package/dist/src/chatwarden.js.map +1 -1
  10. package/dist/src/decide.d.ts +16 -2
  11. package/dist/src/decide.d.ts.map +1 -1
  12. package/dist/src/decide.js +19 -2
  13. package/dist/src/decide.js.map +1 -1
  14. package/dist/src/dismissMany.d.ts +83 -0
  15. package/dist/src/dismissMany.d.ts.map +1 -0
  16. package/dist/src/dismissMany.js +165 -0
  17. package/dist/src/dismissMany.js.map +1 -0
  18. package/dist/src/index.d.ts +7 -3
  19. package/dist/src/index.d.ts.map +1 -1
  20. package/dist/src/index.js +4 -2
  21. package/dist/src/index.js.map +1 -1
  22. package/dist/src/reporterAccuracy.d.ts +54 -0
  23. package/dist/src/reporterAccuracy.d.ts.map +1 -0
  24. package/dist/src/reporterAccuracy.js +69 -0
  25. package/dist/src/reporterAccuracy.js.map +1 -0
  26. package/dist/src/staffViews.d.ts +8 -0
  27. package/dist/src/staffViews.d.ts.map +1 -1
  28. package/dist/src/staffViews.js +4 -0
  29. package/dist/src/staffViews.js.map +1 -1
  30. package/dist/src/team.d.ts +19 -0
  31. package/dist/src/team.d.ts.map +1 -1
  32. package/dist/src/team.js +97 -18
  33. package/dist/src/team.js.map +1 -1
  34. package/dist/src/types.d.ts +26 -1
  35. package/dist/src/types.d.ts.map +1 -1
  36. package/dist/src/types.js.map +1 -1
  37. package/package.json +2 -2
  38. package/src/audit.ts +2 -0
  39. package/src/chatwarden.ts +95 -29
  40. package/src/decide.ts +25 -4
  41. package/src/dismissMany.ts +220 -0
  42. package/src/index.ts +25 -2
  43. package/src/reporterAccuracy.ts +104 -0
  44. package/src/staffViews.ts +13 -0
  45. package/src/team.ts +93 -19
  46. package/src/types.ts +29 -1
package/src/chatwarden.ts CHANGED
@@ -17,6 +17,8 @@ import { historyOf, suggest } from './ladder.js';
17
17
  import type { ActionRecord, Suggestion, SuggestContext } from './ladder.js';
18
18
  import { resolveLimits } from './limits.js';
19
19
  import type { Limits, LimitsInput } from './limits.js';
20
+ import { dismissMany } from './dismissMany.js';
21
+ import type { DismissManyInput, DismissManyResult } from './dismissMany.js';
20
22
  import { PolicyService } from './policy.js';
21
23
  import type { PolicyPreview, PolicySaveContext, PolicySaveResult, PolicyState } from './policy.js';
22
24
  import { resolveProfile } from './profile.js';
@@ -40,6 +42,8 @@ import {
40
42
  reporterRecord,
41
43
  sanctionsOfPerson,
42
44
  } from './staffViews.js';
45
+ import { reporterAccuracyFor } from './reporterAccuracy.js';
46
+ import type { ReporterAccuracy } from './reporterAccuracy.js';
43
47
  import type {
44
48
  BlockedDays,
45
49
  BlockedItem,
@@ -239,6 +243,15 @@ export interface Chatwarden {
239
243
  * address alone finds nobody). An empty `roomId` or `seatId` counts as not given. Never carries an identifier.
240
244
  */
241
245
  restricted(who: RawWho, opts?: { roomId?: string | null; seatId?: string | null }): RestrictedAnswer;
246
+ /**
247
+ * `restricted` for a person you already hold as a subject id (`cw.rooms.subjectAt`), so a server that keeps a seated player's
248
+ * connection open can ask again without keeping their raw client key, account or address in memory. The same answer, the same
249
+ * rules (a merge is followed, a failure reads as not restricted and is logged once a minute), the same shape; `opts` as in
250
+ * `restricted`. A value that is not a subject id, or a subject nobody holds, reads `{ restricted: false, until: null, kind: null }`.
251
+ * A subject id is an identifier: pass it from server code, never from what a client sent, and never send it to a player.
252
+ * @experimental
253
+ */
254
+ restrictedBySubject(subject: SubjectId, opts?: { roomId?: string | null; seatId?: string | null }): RestrictedAnswer;
242
255
  };
243
256
  mutes: {
244
257
  /** `viewerSeat`'s occupant mutes (`on`) or unmutes `targetSeat`'s occupant. Does nothing if either seat has no subject. */
@@ -284,6 +297,28 @@ export interface Chatwarden {
284
297
  * never send to a player (a player is not told who reported or how often).
285
298
  */
286
299
  reporterRecord(subject: SubjectId): ReporterRecord;
300
+ /**
301
+ * How each person's reports filed in the last 30 days turned out, keyed by canonical person (merged aliases folded in): one
302
+ * grouped store read for up to `REPORTER_ACCURACY_BATCH_MAX` (200) people, more is a `RangeError`. A person with no decided
303
+ * report in the window is absent; a store without `reporterOutcomes` gives an empty map. `falseRate` is null below
304
+ * `REPORTER_ACCURACY_MIN_DECIDED` decided reports. A ranking hint and a line on the case: it never refuses a report and never
305
+ * counts toward a suspension. Staff only: never send to a player.
306
+ * @experimental
307
+ */
308
+ reporterAccuracy(people: readonly SubjectId[]): Map<SubjectId, ReporterAccuracy>;
309
+ /**
310
+ * Dismiss ("nothing wrong here") every open report about one person (their case, merged aliases included) or filed by one
311
+ * reporter, in one call: at most `BULK_DISMISS_MAX` (200) reports, `more: true` when there are more. Each report is closed by the
312
+ * same path as `decide` (a `no_action` decision with no actions and the standard reason, source `moderator`, its own transaction,
313
+ * its own `report.closed` event), so a bulk never marks bad faith and never counts toward a suspension. A case another moderator
314
+ * holds is skipped and counted (`skipped.claimed`) unless `ignoreClaims` (for the staff layer, after it has checked who may take
315
+ * a case over). `dryRun` counts and writes nothing. Invalid input resolves `{ ok: false, error: 'invalid' }` with nothing written;
316
+ * a bad `actor` is a `RangeError`; a STORE failure rejects, the reports closed before it stay closed, and running it again
317
+ * finishes the rest. Writes no audit row: the staff layer records the sweep. Carries subject ids: staff channels only, never send
318
+ * to a player.
319
+ * @experimental
320
+ */
321
+ dismissMany(input: DismissManyInput): Promise<DismissManyResult>;
287
322
  };
288
323
  /**
289
324
  * Blocked chat lines, from the slur filter's strikes (purged after 30 days). Staff only: the lines are raw chat text
@@ -332,8 +367,14 @@ export interface Chatwarden {
332
367
  * malformed id), or null. A case is a person, ranked by their oldest open report and opened on
333
368
  * their newest. A case anyone holds is skipped without a write (held cases are read once per page of reports). `category` and
334
369
  * `reason` are the only filters: the order is already oldest first. A candidate lost to a rival in between is retried like `claim`.
370
+ *
371
+ * With `rankDownHabitual` (default false: behaviour unchanged), a case whose open reports ALL come from habitual false reporters
372
+ * (see `cw.reports.reporterAccuracy`) and none of which has waited 24 hours (`REPORTER_RANK_LAPSE_MS`) is served after the ordinary
373
+ * ones, oldest first; it is never skipped, so a queue holding only such cases still serves them. One ordinary reporter, or no
374
+ * accuracy data (a store without `reporterOutcomes`), keeps a case normal. A non-boolean value is a `RangeError`.
375
+ * @experimental (the `rankDownHabitual` filter)
335
376
  */
336
- next(actor: string, filter?: { category?: ReportCategory; reason?: string | null }): NextCase | null;
377
+ next(actor: string, filter?: { category?: ReportCategory; reason?: string | null; rankDownHabitual?: boolean }): NextCase | null;
337
378
  /**
338
379
  * `actor` has the person's case open now. A hint for 30 seconds (`VIEWING_TTL_MS`), in this process's memory only.
339
380
  * Only a person with an open report is tracked (false otherwise, nothing recorded); one actor keeps at most 20 cases
@@ -486,6 +527,10 @@ export interface Chatwarden {
486
527
  * `{ ok: false, error: 'invalid' }`; a STORE failure REJECTS with the store's own error and writes nothing, so a
487
528
  * route handler should catch it. Moderator-side: the result carries subject ids, so never forward it to a player.
488
529
  * Carries subject ids: staff channels only, never send to a player.
530
+ *
531
+ * `reason` is required, except for a `no_action` decision with no actions (a one-click "nothing wrong here"): an absent or
532
+ * blank reason is then stored as `NO_ACTION_DEFAULT_REASON`. A `no_action` that acts on someone, and every other verdict,
533
+ * still needs a real reason.
489
534
  */
490
535
  decide(input: DecisionInput): Promise<DecisionResult>;
491
536
  /**
@@ -775,8 +820,44 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
775
820
  (timer as { unref?: () => void }).unref?.();
776
821
  }
777
822
 
823
+ // The one place a decision is made AND announced: `decide` and `dismissMany` both go through it, so a report closed by a bulk
824
+ // emits exactly the events a single decision does.
825
+ const decideAnnounced: Chatwarden['decide'] = async (input) => {
826
+ const { result, committed } = await decisions.decideDetailed(input);
827
+ if (committed !== null) {
828
+ try {
829
+ bus.emit({ type: 'report.closed', reportId: committed.reportId, verdict: committed.verdict, at: committed.at });
830
+ for (const g of committed.applied) {
831
+ bus.emit({
832
+ type: 'sanction.applied',
833
+ groupId: g.groupId,
834
+ refCode: g.refCode,
835
+ kind: g.kind,
836
+ until: g.until,
837
+ rule: g.rule,
838
+ source: g.source,
839
+ automated: false,
840
+ target: g.target,
841
+ });
842
+ }
843
+ for (const g of committed.applied) {
844
+ if (g.gap) bus.emit({ type: 'gap.created', groupId: g.groupId, refCode: g.refCode, at: committed.at, subject: subjects.canonical(g.target) });
845
+ }
846
+ } catch (err) {
847
+ eventFailed(err);
848
+ }
849
+ }
850
+ return result;
851
+ };
852
+
778
853
  const audit = new AuditService({ store, clock, logger });
779
- const desk = new CaseDesk({ store, subjects, clock, reasons: () => policy.profileNow().reporting.reasons });
854
+ const desk = new CaseDesk({
855
+ store,
856
+ subjects,
857
+ clock,
858
+ reasons: () => policy.profileNow().reporting.reasons,
859
+ accuracy: (people) => reporterAccuracyFor(store, subjects, people, clock.now()),
860
+ });
780
861
  const reasonBook = new ReasonBook(store);
781
862
 
782
863
  return {
@@ -808,6 +889,15 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
808
889
  return { restricted: false, until: null, kind: null };
809
890
  }
810
891
  },
892
+ restrictedBySubject: (subject, o) => {
893
+ if (typeof subject !== 'string' || subject === '') return { restricted: false, until: null, kind: null };
894
+ try {
895
+ return chat.restricted(subject, o?.roomId, o?.seatId);
896
+ } catch (err) {
897
+ restrictedWarn.warn('chatwarden.restricted_failed', { error: err instanceof Error ? err.name : typeof err });
898
+ return { restricted: false, until: null, kind: null };
899
+ }
900
+ },
811
901
  },
812
902
  mutes: {
813
903
  set: (roomId, viewerSeat, targetSeat, on) => {
@@ -831,6 +921,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
831
921
  return record === null ? null : staffReport(record, subjects);
832
922
  },
833
923
  reporterRecord: (subject) => reporterRecord(store, subjects, limits.reports, subject, clock.now(), policy.profileNow().reporting.reasons),
924
+ reporterAccuracy: (people) => reporterAccuracyFor(store, subjects, people, clock.now()),
925
+ dismissMany: (input) => dismissMany({ store, subjects, holders: (people) => desk.holders(people), decide: decideAnnounced }, input),
834
926
  },
835
927
  blocked: {
836
928
  list: (q) => blockedItems(store, subjects, q?.days, clock.now()),
@@ -958,33 +1050,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
958
1050
  record: (who) => forPlayer<PlayerNotice[]>(who, [], (s) => notices.record(s)),
959
1051
  pendingWarning: (who) => forPlayer(who, false, (s) => notices.pendingWarning(s)),
960
1052
  },
961
- decide: async (input) => {
962
- const { result, committed } = await decisions.decideDetailed(input);
963
- if (committed !== null) {
964
- try {
965
- bus.emit({ type: 'report.closed', reportId: committed.reportId, verdict: committed.verdict, at: committed.at });
966
- for (const g of committed.applied) {
967
- bus.emit({
968
- type: 'sanction.applied',
969
- groupId: g.groupId,
970
- refCode: g.refCode,
971
- kind: g.kind,
972
- until: g.until,
973
- rule: g.rule,
974
- source: g.source,
975
- automated: false,
976
- target: g.target,
977
- });
978
- }
979
- for (const g of committed.applied) {
980
- if (g.gap) bus.emit({ type: 'gap.created', groupId: g.groupId, refCode: g.refCode, at: committed.at, subject: subjects.canonical(g.target) });
981
- }
982
- } catch (err) {
983
- eventFailed(err);
984
- }
985
- }
986
- return result;
987
- },
1053
+ decide: (input) => decideAnnounced(input),
988
1054
  history: (subject) => historyOf(store, subjects, subject, clock.now()),
989
1055
  suggest: (subject, level, rule, context) => {
990
1056
  const now = clock.now();
package/src/decide.ts CHANGED
@@ -16,6 +16,21 @@ import type { Clock, Logger, ReportExcerptLine, ReportRecord, SanctionKind, Sanc
16
16
  /** The longest moderator reason, after trimming. */
17
17
  export const DECISION_REASON_MAX = 500;
18
18
 
19
+ /**
20
+ * The reason stored for a `no_action` decision that has no actions and no typed reason (a one-click "nothing wrong
21
+ * here"). One recognisable value, so "a human dismissed it and gave no reason" is told apart from a considered note.
22
+ * @experimental
23
+ */
24
+ export const NO_ACTION_DEFAULT_REASON = 'No action needed';
25
+
26
+ /**
27
+ * True for the standard dismissal reason (trimmed); false for anything else, including null.
28
+ * @experimental
29
+ */
30
+ export function isDefaultNoActionReason(reason: string | null | undefined): boolean {
31
+ return typeof reason === 'string' && reason.trim() === NO_ACTION_DEFAULT_REASON;
32
+ }
33
+
19
34
  /** The longest bad-faith evidence note, after trimming. */
20
35
  export const DECISION_EVIDENCE_MAX = 500;
21
36
 
@@ -60,8 +75,11 @@ export interface DecisionInput {
60
75
  evidence?: string;
61
76
  actions: DecisionAction[];
62
77
  actor: string;
63
- /** Private; required, at most 500 characters after trimming. Never shown to a player. */
64
- reason: string;
78
+ /**
79
+ * Private; at most 500 characters after trimming. Never shown to a player. Required, except for a `no_action`
80
+ * decision with NO actions, where an absent or blank reason is stored as {@link NO_ACTION_DEFAULT_REASON}.
81
+ */
82
+ reason?: string;
65
83
  /** Defaults to `'moderator'`. */
66
84
  source?: Source;
67
85
  }
@@ -187,8 +205,11 @@ function normalize(subjects: SubjectIndex, input: DecisionInput): Normal {
187
205
  if (!VERDICTS.includes(input.verdict)) return bad();
188
206
  if (!Array.isArray(input.actions)) return bad();
189
207
  if (typeof input.actor !== 'string' || input.actor.trim() === '') return bad();
190
- if (typeof input.reason !== 'string') return bad();
191
- const reason = input.reason.trim();
208
+ // A reason that is neither absent nor a string is malformed for every verdict.
209
+ if (input.reason !== undefined && typeof input.reason !== 'string') return bad();
210
+ let reason = input.reason === undefined ? '' : input.reason.trim();
211
+ // The one-click dismissal: a no_action that acts on nobody may leave the reason out.
212
+ if (reason === '' && input.verdict === 'no_action' && input.actions.length === 0) reason = NO_ACTION_DEFAULT_REASON;
192
213
  if (reason === '' || reason.length > DECISION_REASON_MAX) return bad();
193
214
  // Evidence is required for bad_faith and forbidden otherwise (even an empty string): the verdict says what it is for.
194
215
  let evidence: string | null = null;
@@ -0,0 +1,220 @@
1
+ import { isValidAuditActor } from './audit.js';
2
+ import { DECISION_REASON_MAX } from './decide.js';
3
+ import type { DecisionInput, DecisionResult } from './decide.js';
4
+ import type { SubjectIndex } from './subjects.js';
5
+ import type { CaseClaim } from './team.js';
6
+ import type { ReportRecord, Store, SubjectId } from './types.js';
7
+
8
+ // Bulk dismissal: "nothing wrong here" for every open report about one person (their case) or from one reporter, in one call.
9
+ // Each report is closed by the same path as a single decision (`no_action`, no actions, the standard reason), each in its own
10
+ // transaction, so every invariant of `decide` holds and each report gets its `report.closed` event. A bulk never uses `bad_faith`:
11
+ // that needs written evidence and counts toward a reporting suspension. The staff layer writes the audit trail around this call.
12
+
13
+ /** The most reports one {@link dismissMany} call closes; the answer says `more: true` past it. @experimental */
14
+ export const BULK_DISMISS_MAX = 200;
15
+
16
+ /**
17
+ * Reports read when a store cannot list a reporter's open reports (no `listOpenReportsByReporter`) and the scan fallback is used.
18
+ * With more open reports than this in the whole store, a reporter's sweep from such a store may find only some of theirs.
19
+ * @experimental
20
+ */
21
+ export const BULK_REPORTER_SCAN_MAX = 5_000;
22
+
23
+ /** What to dismiss: every open report about a person, or every open report from a reporter. A staff ref; aliases are folded. @experimental */
24
+ export type DismissScope = { person: SubjectId } | { reporter: SubjectId };
25
+
26
+ /** @experimental */
27
+ export interface DismissManyInput {
28
+ scope: DismissScope;
29
+ /** The audit trail's actor rule (`RangeError` otherwise, as `cases.*`). */
30
+ actor: string;
31
+ /** Optional, at most 500 characters after trimming; absent or blank is `NO_ACTION_DEFAULT_REASON`. */
32
+ reason?: string;
33
+ /** Count only: nothing is written. */
34
+ dryRun?: boolean;
35
+ /** Default false. For the staff layer only, after it has checked who may take a case over. */
36
+ ignoreClaims?: boolean;
37
+ /** Default and maximum {@link BULK_DISMISS_MAX}; a non-integer or a value below 1 is invalid. */
38
+ limit?: number;
39
+ /**
40
+ * Called right after each report is closed (`replay` true when an identical dismissal had already closed it), in order, never for
41
+ * a skip or a dry run. The staff layer writes its per-report audit row here, so the trail has a row for every report closed even
42
+ * when a later one fails and the call rejects. A throw is swallowed: it never stops the sweep.
43
+ * @experimental
44
+ */
45
+ onClosed?: (reportId: string, replay: boolean) => void;
46
+ }
47
+
48
+ /**
49
+ * The answer to `dismissMany`. Carries subject ids: staff channels only, never send to a player.
50
+ * @experimental
51
+ */
52
+ export type DismissManyResult =
53
+ | {
54
+ ok: true;
55
+ dryRun: boolean;
56
+ /** Open reports in scope this call would close (after claim exclusion), up to `limit`. */
57
+ open: number;
58
+ /** Closed by THIS call. */
59
+ dismissed: number;
60
+ /** Already closed by an identical earlier dismissal. */
61
+ replayed: number;
62
+ /** `claimed`: held by another moderator; `decided`: closed meanwhile by a different decision. */
63
+ skipped: { claimed: number; decided: number };
64
+ /** More open reports in scope than `limit`. */
65
+ more: boolean;
66
+ /** Dismissed plus replayed, for the staff layer's audit rows. */
67
+ reportIds: string[];
68
+ /** The canonical people whose reports this call dismissed, for releasing the actor's claims. */
69
+ targets: SubjectId[];
70
+ }
71
+ | { ok: false; error: 'invalid' };
72
+
73
+ export interface DismissManyDeps {
74
+ store: Store;
75
+ subjects: SubjectIndex;
76
+ /** The live claims among these people, keyed by canonical person. */
77
+ holders: (people: readonly SubjectId[]) => Map<SubjectId, CaseClaim>;
78
+ /** One decision, announced exactly as `cw.decide` announces it. */
79
+ decide: (input: DecisionInput) => Promise<DecisionResult>;
80
+ }
81
+
82
+ const INVALID: DismissManyResult = Object.freeze({ ok: false, error: 'invalid' }) as DismissManyResult;
83
+ const nonEmpty = (v: unknown): v is string => typeof v === 'string' && v.trim() !== '';
84
+
85
+ /** Newest first, like `listOpenReportsByPerson`. */
86
+ const newestFirst = (a: ReportRecord, b: ReportRecord): number => b.createdAt - a.createdAt || (a.id < b.id ? 1 : a.id > b.id ? -1 : 0);
87
+
88
+ /** The reporter's open reports from a store that cannot list them directly: a bounded keyed scan of every open report. */
89
+ function scanForReporter(store: Store, subjects: SubjectIndex, root: SubjectId, want: number): ReportRecord[] {
90
+ const found: ReportRecord[] = [];
91
+ let read = 0;
92
+ let after: number | undefined;
93
+ let afterId: string | undefined;
94
+ while (read < BULK_REPORTER_SCAN_MAX) {
95
+ const asked = Math.min(200, BULK_REPORTER_SCAN_MAX - read);
96
+ const page = store.listOpenReports({
97
+ limit: asked,
98
+ ...(after === undefined ? {} : { after }),
99
+ ...(afterId === undefined ? {} : { afterId }),
100
+ });
101
+ for (const r of page) if (subjects.canonical(r.reporterSubject) === root) found.push(r);
102
+ read += page.length;
103
+ const last = page[page.length - 1];
104
+ if (last === undefined || page.length < asked) break;
105
+ after = last.createdAt;
106
+ afterId = last.id;
107
+ }
108
+ // The scan is oldest first; the by-reporter read is newest first, and so is this.
109
+ return found.sort(newestFirst).slice(0, want);
110
+ }
111
+
112
+ /**
113
+ * Close the open reports in `input.scope`. Validation runs completely before the first read or write: any problem answers
114
+ * `{ ok: false, error: 'invalid' }` (a bad actor is a `RangeError`). Then up to `limit + 1` open reports are read, the first `limit`
115
+ * are the candidates, those whose person another moderator holds are skipped (unless `ignoreClaims`), and each remaining report is
116
+ * decided in turn. A store failure rejects: reports closed before it stay closed, and running the call again finishes the rest.
117
+ */
118
+ export async function dismissMany(deps: DismissManyDeps, input: DismissManyInput): Promise<DismissManyResult> {
119
+ const { store, subjects } = deps;
120
+ if (typeof input !== 'object' || input === null) return INVALID;
121
+ if (!isValidAuditActor(input.actor)) throw new RangeError('reports: the actor is not a valid staff ref');
122
+ const actor = input.actor;
123
+
124
+ const scope: unknown = input.scope;
125
+ if (typeof scope !== 'object' || scope === null || Array.isArray(scope)) return INVALID;
126
+ const keys = Object.keys(scope);
127
+ const only = keys.length === 1 ? keys[0] : undefined;
128
+ if (only !== 'person' && only !== 'reporter') return INVALID;
129
+ const ref = (scope as Record<string, unknown>)[only];
130
+ if (!nonEmpty(ref)) return INVALID;
131
+
132
+ let reason: string | undefined;
133
+ if (input.reason !== undefined) {
134
+ if (typeof input.reason !== 'string') return INVALID;
135
+ reason = input.reason.trim();
136
+ if (reason.length > DECISION_REASON_MAX) return INVALID;
137
+ }
138
+ if (input.dryRun !== undefined && typeof input.dryRun !== 'boolean') return INVALID;
139
+ if (input.ignoreClaims !== undefined && typeof input.ignoreClaims !== 'boolean') return INVALID;
140
+ let limit = BULK_DISMISS_MAX;
141
+ if (input.limit !== undefined) {
142
+ if (typeof input.limit !== 'number' || !Number.isInteger(input.limit) || input.limit < 1) return INVALID;
143
+ limit = Math.min(input.limit, BULK_DISMISS_MAX);
144
+ }
145
+ if (input.onClosed !== undefined && typeof input.onClosed !== 'function') return INVALID;
146
+ const onClosed = input.onClosed;
147
+ const dryRun = input.dryRun === true;
148
+
149
+ // Read one more than asked for, to know whether there is more.
150
+ const root = subjects.canonical(ref);
151
+ let rows: ReportRecord[];
152
+ if (only === 'person') {
153
+ rows = store.listOpenReportsByPerson(subjects.aliasesOf(root), limit + 1);
154
+ } else if (store.listOpenReportsByReporter !== undefined) {
155
+ rows = store.listOpenReportsByReporter(subjects.aliasesOf(root), limit + 1);
156
+ } else {
157
+ rows = scanForReporter(store, subjects, root, limit + 1);
158
+ }
159
+ const more = rows.length > limit;
160
+ const candidates = rows.slice(0, limit);
161
+
162
+ // Another moderator's live claim keeps that case out of the sweep, counted so the caller can say so.
163
+ let claimed = 0;
164
+ let todo = candidates;
165
+ if (input.ignoreClaims !== true && candidates.length > 0) {
166
+ const held = deps.holders([...new Set(candidates.map((r) => subjects.canonical(r.targetSubject)))]);
167
+ todo = candidates.filter((r) => {
168
+ const claim = held.get(subjects.canonical(r.targetSubject));
169
+ if (claim !== undefined && claim.by !== actor) {
170
+ claimed += 1;
171
+ return false;
172
+ }
173
+ return true;
174
+ });
175
+ }
176
+
177
+ const result = {
178
+ ok: true as const,
179
+ dryRun,
180
+ open: todo.length,
181
+ dismissed: 0,
182
+ replayed: 0,
183
+ skipped: { claimed, decided: 0 },
184
+ more,
185
+ reportIds: [] as string[],
186
+ targets: [] as SubjectId[],
187
+ };
188
+ if (dryRun) return result;
189
+
190
+ const targets = new Set<SubjectId>();
191
+ for (const r of todo) {
192
+ const res = await deps.decide({
193
+ reportId: r.id,
194
+ verdict: 'no_action',
195
+ actions: [],
196
+ actor,
197
+ ...(reason === undefined || reason === '' ? {} : { reason }),
198
+ source: 'moderator',
199
+ });
200
+ if (res.ok) {
201
+ result.reportIds.push(r.id);
202
+ try {
203
+ onClosed?.(r.id, res.replay);
204
+ } catch {
205
+ // The caller's bookkeeping must never stop the sweep.
206
+ }
207
+ if (res.replay) {
208
+ result.replayed += 1;
209
+ } else {
210
+ result.dismissed += 1;
211
+ targets.add(subjects.canonical(r.targetSubject));
212
+ }
213
+ } else {
214
+ // already_decided / not_found: somebody closed (or purged) it between our read and our write.
215
+ result.skipped.decided += 1;
216
+ }
217
+ }
218
+ result.targets = [...targets];
219
+ return result;
220
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '0.1.4';
1
+ export const VERSION = '0.1.6';
2
2
 
3
3
  export type {
4
4
  Clock,
@@ -25,6 +25,7 @@ export type {
25
25
  SanctionRow,
26
26
  SanctionTargetType,
27
27
  ReporterDecision,
28
+ ReporterOutcomeRow,
28
29
  ReporterTally,
29
30
  ClaimAttempt,
30
31
  ClaimMode,
@@ -158,6 +159,20 @@ export {
158
159
  isSanctionActive,
159
160
  sanctionGroupView,
160
161
  } from './staffViews.js';
162
+ export { BULK_DISMISS_MAX, BULK_REPORTER_SCAN_MAX } from './dismissMany.js';
163
+ export type { DismissManyInput, DismissManyResult, DismissScope } from './dismissMany.js';
164
+ export {
165
+ RANK_DOWN_SCAN_MAX,
166
+ REPORTER_ACCURACY_BATCH_MAX,
167
+ REPORTER_ACCURACY_MIN_DECIDED,
168
+ REPORTER_ACCURACY_WINDOW_MS,
169
+ REPORTER_FALSE_RATE_HABITUAL,
170
+ REPORTER_FALSE_RATE_NOTICEABLE,
171
+ REPORTER_RANK_LAPSE_MS,
172
+ reporterAccuracyFor,
173
+ summarizeOutcomes,
174
+ } from './reporterAccuracy.js';
175
+ export type { ReporterAccuracy } from './reporterAccuracy.js';
161
176
  export type {
162
177
  BlockedDays,
163
178
  BlockedItem,
@@ -250,7 +265,15 @@ export {
250
265
  suggest,
251
266
  } from './ladder.js';
252
267
  export type { ActionRecord, LadderCell, LadderRow, LadderStep, Suggestion, SuggestContext } from './ladder.js';
253
- export { DECISION_EVIDENCE_MAX, DECISION_REASON_MAX, DecisionService, decisionKey, revokeAndWithdraw } from './decide.js';
268
+ export {
269
+ DECISION_EVIDENCE_MAX,
270
+ DECISION_REASON_MAX,
271
+ DecisionService,
272
+ NO_ACTION_DEFAULT_REASON,
273
+ decisionKey,
274
+ isDefaultNoActionReason,
275
+ revokeAndWithdraw,
276
+ } from './decide.js';
254
277
  export type {
255
278
  DecisionAction,
256
279
  DecisionGroup,
@@ -0,0 +1,104 @@
1
+ import type { SubjectIndex } from './subjects.js';
2
+ import type { Store, SubjectId } from './types.js';
3
+
4
+ // Reporter accuracy: how often the reports a person filed turned out to be unfounded, over a window, once there is a big enough
5
+ // sample to say. It is a RANKING hint and a line on the case (staff only). It never refuses a report, never counts toward a
6
+ // suspension and never reaches a player: the figure is built from decisions, and a player is not told who reported or how often.
7
+ // The window is on the FILING time (`created_at`), so the read uses the reporter index and needs no join. Computed from one
8
+ // grouped store query (`Store.reporterOutcomes`), so a queue page of 200 reporters is one statement.
9
+
10
+ /** The window the rate is read over: 30 days of filing time, the same as the reporting suspension window. @experimental */
11
+ export const REPORTER_ACCURACY_WINDOW_MS = 30 * 86_400_000;
12
+
13
+ /** Fewer decided reports than this and there is no rate: nobody is shown a line or ranked down. @experimental */
14
+ export const REPORTER_ACCURACY_MIN_DECIDED = 5;
15
+
16
+ /** From this false-report rate up, the case shows a line about the reporter. @experimental */
17
+ export const REPORTER_FALSE_RATE_NOTICEABLE = 0.6;
18
+
19
+ /** From this false-report rate up, the reporter's reports rank lower (never hidden). @experimental */
20
+ export const REPORTER_FALSE_RATE_HABITUAL = 0.8;
21
+
22
+ /** The most people one {@link reporterAccuracyFor} call reads; more is a `RangeError`. @experimental */
23
+ export const REPORTER_ACCURACY_BATCH_MAX = 200;
24
+
25
+ /**
26
+ * Take-next with `rankDownHabitual`: a case that has waited this long ranks normally whoever reported it (the hub's "overdue" line,
27
+ * 24 hours). The safety against burying a real report from a habitual reporter. @experimental
28
+ */
29
+ export const REPORTER_RANK_LAPSE_MS = 24 * 3_600_000;
30
+
31
+ /** Take-next with `rankDownHabitual`: open reports read, at most, while looking for a case that is not ranked down. @experimental */
32
+ export const RANK_DOWN_SCAN_MAX = 1_000;
33
+
34
+ /**
35
+ * How a reporter's decided reports (filed in the last `windowMs`) turned out. `decided` is `actioned + noAction + badFaith`;
36
+ * `unfounded` is `noAction + badFaith` (a dismissal, with or without the bad-faith mark: the strongest false report counts too).
37
+ * `noted` and `upheld` are both founded: something was found. `falseRate` is `unfounded / decided`, null below
38
+ * {@link REPORTER_ACCURACY_MIN_DECIDED} decided. Open reports are never counted.
39
+ * Staff only: never send to a player.
40
+ * @experimental
41
+ */
42
+ export interface ReporterAccuracy {
43
+ decided: number;
44
+ noAction: number;
45
+ badFaith: number;
46
+ unfounded: number;
47
+ falseRate: number | null;
48
+ /** `falseRate >= REPORTER_FALSE_RATE_NOTICEABLE`. */
49
+ noticeable: boolean;
50
+ /** `falseRate >= REPORTER_FALSE_RATE_HABITUAL`. */
51
+ habitual: boolean;
52
+ /** {@link REPORTER_ACCURACY_WINDOW_MS}, so a screen can say "in the last 30 days". */
53
+ windowMs: number;
54
+ }
55
+
56
+ /** The pure part: outcome counts in, the summary out. @experimental */
57
+ export function summarizeOutcomes(c: { actioned: number; noAction: number; badFaith: number }): ReporterAccuracy {
58
+ const decided = c.actioned + c.noAction + c.badFaith;
59
+ const unfounded = c.noAction + c.badFaith;
60
+ const falseRate = decided >= REPORTER_ACCURACY_MIN_DECIDED ? unfounded / decided : null;
61
+ return {
62
+ decided,
63
+ noAction: c.noAction,
64
+ badFaith: c.badFaith,
65
+ unfounded,
66
+ falseRate,
67
+ noticeable: falseRate !== null && falseRate >= REPORTER_FALSE_RATE_NOTICEABLE,
68
+ habitual: falseRate !== null && falseRate >= REPORTER_FALSE_RATE_HABITUAL,
69
+ windowMs: REPORTER_ACCURACY_WINDOW_MS,
70
+ };
71
+ }
72
+
73
+ /**
74
+ * The accuracy of each person as a reporter, keyed by canonical person. Each person is made canonical and expanded to every merged
75
+ * alias; ONE `store.reporterOutcomes` call reads them all; the rows are folded by `canonical(row.reporter)`. A person with no decided
76
+ * report in the window is absent from the map. A store without `reporterOutcomes` gives an empty map. More than
77
+ * {@link REPORTER_ACCURACY_BATCH_MAX} people (after removing duplicates) is a `RangeError`.
78
+ */
79
+ export function reporterAccuracyFor(
80
+ store: Store,
81
+ subjects: SubjectIndex,
82
+ people: readonly SubjectId[],
83
+ now: number,
84
+ ): Map<SubjectId, ReporterAccuracy> {
85
+ const roots = [...new Set(people.map((p) => subjects.canonical(p)))];
86
+ if (roots.length > REPORTER_ACCURACY_BATCH_MAX) throw new RangeError(`reporterAccuracy: at most ${REPORTER_ACCURACY_BATCH_MAX} people per call`);
87
+ const out = new Map<SubjectId, ReporterAccuracy>();
88
+ if (roots.length === 0 || store.reporterOutcomes === undefined) return out;
89
+ const all = [...new Set(roots.flatMap((p) => subjects.aliasesOf(p)))];
90
+ const folded = new Map<SubjectId, { actioned: number; noAction: number; badFaith: number }>();
91
+ for (const row of store.reporterOutcomes(all, now - REPORTER_ACCURACY_WINDOW_MS)) {
92
+ const root = subjects.canonical(row.reporter);
93
+ const c = folded.get(root) ?? { actioned: 0, noAction: 0, badFaith: 0 };
94
+ c.actioned += row.actioned;
95
+ c.noAction += row.noAction;
96
+ c.badFaith += row.badFaith;
97
+ folded.set(root, c);
98
+ }
99
+ for (const root of roots) {
100
+ const c = folded.get(root);
101
+ if (c !== undefined && c.actioned + c.noAction + c.badFaith > 0) out.set(root, summarizeOutcomes(c));
102
+ }
103
+ return out;
104
+ }
package/src/staffViews.ts CHANGED
@@ -3,6 +3,8 @@ import type { Limits } from './limits.js';
3
3
  import { reporterSuspendedUntil } from './reports.js';
4
4
  import { findReason } from './reporting.js';
5
5
  import type { ReportReason } from './reporting.js';
6
+ import { reporterAccuracyFor, summarizeOutcomes } from './reporterAccuracy.js';
7
+ import type { ReporterAccuracy } from './reporterAccuracy.js';
6
8
  import { parseRuleRef } from './rules.js';
7
9
  import type { RuleRef } from './rules.js';
8
10
  import { SANCTION_SOURCES } from './sanctions.js';
@@ -230,6 +232,13 @@ export interface ReporterRecord {
230
232
  suspendedUntil: number | null;
231
233
  reasonMatched: number;
232
234
  reasonDecided: number;
235
+ /**
236
+ * How their reports filed in the last 30 days turned out (see {@link ReporterAccuracy}): a ranking hint and a line on the case.
237
+ * Null when the store cannot tell (it has no `reporterOutcomes`); otherwise always set, with `falseRate` null below the minimum
238
+ * sample. Staff only: never send to a player.
239
+ * @experimental
240
+ */
241
+ accuracy?: ReporterAccuracy | null;
233
242
  }
234
243
 
235
244
  export function reporterRecord(
@@ -268,6 +277,10 @@ export function reporterRecord(
268
277
  suspendedUntil: reporterSuspendedUntil(marks, limits),
269
278
  reasonMatched,
270
279
  reasonDecided,
280
+ accuracy:
281
+ store.reporterOutcomes === undefined
282
+ ? null
283
+ : (reporterAccuracyFor(store, subjects, [root], now).get(root) ?? summarizeOutcomes({ actioned: 0, noAction: 0, badFaith: 0 })),
271
284
  };
272
285
  }
273
286