@chatwarden/core 0.1.7 → 0.1.9

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 (176) hide show
  1. package/README.md +306 -7
  2. package/dist/src/ai/case.d.ts +4 -3
  3. package/dist/src/ai/case.d.ts.map +1 -1
  4. package/dist/src/ai/case.js +1 -1
  5. package/dist/src/ai/case.js.map +1 -1
  6. package/dist/src/ai/hash.d.ts +3 -1
  7. package/dist/src/ai/hash.d.ts.map +1 -1
  8. package/dist/src/ai/hash.js +5 -2
  9. package/dist/src/ai/hash.js.map +1 -1
  10. package/dist/src/ai/prompt.d.ts +13 -2
  11. package/dist/src/ai/prompt.d.ts.map +1 -1
  12. package/dist/src/ai/prompt.js +31 -1
  13. package/dist/src/ai/prompt.js.map +1 -1
  14. package/dist/src/ai/service.d.ts +21 -6
  15. package/dist/src/ai/service.d.ts.map +1 -1
  16. package/dist/src/ai/service.js +14 -7
  17. package/dist/src/ai/service.js.map +1 -1
  18. package/dist/src/ai/types.d.ts +33 -2
  19. package/dist/src/ai/types.d.ts.map +1 -1
  20. package/dist/src/ai/types.js +3 -2
  21. package/dist/src/ai/types.js.map +1 -1
  22. package/dist/src/ai/worker.d.ts +8 -1
  23. package/dist/src/ai/worker.d.ts.map +1 -1
  24. package/dist/src/ai/worker.js +17 -3
  25. package/dist/src/ai/worker.js.map +1 -1
  26. package/dist/src/appealService.d.ts +105 -0
  27. package/dist/src/appealService.d.ts.map +1 -0
  28. package/dist/src/appealService.js +548 -0
  29. package/dist/src/appealService.js.map +1 -0
  30. package/dist/src/appeals.d.ts +194 -0
  31. package/dist/src/appeals.d.ts.map +1 -0
  32. package/dist/src/appeals.js +107 -0
  33. package/dist/src/appeals.js.map +1 -0
  34. package/dist/src/audit.d.ts +7 -3
  35. package/dist/src/audit.d.ts.map +1 -1
  36. package/dist/src/audit.js +18 -3
  37. package/dist/src/audit.js.map +1 -1
  38. package/dist/src/chat.d.ts +39 -1
  39. package/dist/src/chat.d.ts.map +1 -1
  40. package/dist/src/chat.js +85 -6
  41. package/dist/src/chat.js.map +1 -1
  42. package/dist/src/chatwarden.d.ts +197 -10
  43. package/dist/src/chatwarden.d.ts.map +1 -1
  44. package/dist/src/chatwarden.js +212 -23
  45. package/dist/src/chatwarden.js.map +1 -1
  46. package/dist/src/decide.d.ts +2 -0
  47. package/dist/src/decide.d.ts.map +1 -1
  48. package/dist/src/decide.js +12 -7
  49. package/dist/src/decide.js.map +1 -1
  50. package/dist/src/documents.d.ts +1 -1
  51. package/dist/src/documents.d.ts.map +1 -1
  52. package/dist/src/documents.js +5 -1
  53. package/dist/src/documents.js.map +1 -1
  54. package/dist/src/events.d.ts +38 -0
  55. package/dist/src/events.d.ts.map +1 -1
  56. package/dist/src/events.js +3 -0
  57. package/dist/src/events.js.map +1 -1
  58. package/dist/src/freeze.d.ts +3 -0
  59. package/dist/src/freeze.d.ts.map +1 -0
  60. package/dist/src/freeze.js +10 -0
  61. package/dist/src/freeze.js.map +1 -0
  62. package/dist/src/index.d.ts +20 -9
  63. package/dist/src/index.d.ts.map +1 -1
  64. package/dist/src/index.js +11 -3
  65. package/dist/src/index.js.map +1 -1
  66. package/dist/src/ladder.d.ts +28 -0
  67. package/dist/src/ladder.d.ts.map +1 -1
  68. package/dist/src/ladder.js +37 -1
  69. package/dist/src/ladder.js.map +1 -1
  70. package/dist/src/nameService.d.ts +90 -0
  71. package/dist/src/nameService.d.ts.map +1 -0
  72. package/dist/src/nameService.js +224 -0
  73. package/dist/src/nameService.js.map +1 -0
  74. package/dist/src/names.d.ts +68 -0
  75. package/dist/src/names.d.ts.map +1 -0
  76. package/dist/src/names.js +87 -0
  77. package/dist/src/names.js.map +1 -0
  78. package/dist/src/notices.d.ts +53 -5
  79. package/dist/src/notices.d.ts.map +1 -1
  80. package/dist/src/notices.js +93 -8
  81. package/dist/src/notices.js.map +1 -1
  82. package/dist/src/pace.d.ts +66 -0
  83. package/dist/src/pace.d.ts.map +1 -0
  84. package/dist/src/pace.js +111 -0
  85. package/dist/src/pace.js.map +1 -0
  86. package/dist/src/pacing.d.ts +63 -0
  87. package/dist/src/pacing.d.ts.map +1 -0
  88. package/dist/src/pacing.js +198 -0
  89. package/dist/src/pacing.js.map +1 -0
  90. package/dist/src/policy.d.ts +66 -1
  91. package/dist/src/policy.d.ts.map +1 -1
  92. package/dist/src/policy.js +86 -5
  93. package/dist/src/policy.js.map +1 -1
  94. package/dist/src/profile.d.ts +57 -8
  95. package/dist/src/profile.d.ts.map +1 -1
  96. package/dist/src/profile.js +69 -25
  97. package/dist/src/profile.js.map +1 -1
  98. package/dist/src/profileError.d.ts +10 -0
  99. package/dist/src/profileError.d.ts.map +1 -0
  100. package/dist/src/profileError.js +17 -0
  101. package/dist/src/profileError.js.map +1 -0
  102. package/dist/src/retention.d.ts +40 -1
  103. package/dist/src/retention.d.ts.map +1 -1
  104. package/dist/src/retention.js +50 -3
  105. package/dist/src/retention.js.map +1 -1
  106. package/dist/src/sanctions.d.ts +29 -1
  107. package/dist/src/sanctions.d.ts.map +1 -1
  108. package/dist/src/sanctions.js +52 -9
  109. package/dist/src/sanctions.js.map +1 -1
  110. package/dist/src/signalCounts.d.ts +37 -0
  111. package/dist/src/signalCounts.d.ts.map +1 -0
  112. package/dist/src/signalCounts.js +117 -0
  113. package/dist/src/signalCounts.js.map +1 -0
  114. package/dist/src/signalInert.d.ts +10 -0
  115. package/dist/src/signalInert.d.ts.map +1 -0
  116. package/dist/src/signalInert.js +28 -0
  117. package/dist/src/signalInert.js.map +1 -0
  118. package/dist/src/signalService.d.ts +101 -0
  119. package/dist/src/signalService.d.ts.map +1 -0
  120. package/dist/src/signalService.js +383 -0
  121. package/dist/src/signalService.js.map +1 -0
  122. package/dist/src/signals.d.ts +186 -0
  123. package/dist/src/signals.d.ts.map +1 -0
  124. package/dist/src/signals.js +361 -0
  125. package/dist/src/signals.js.map +1 -0
  126. package/dist/src/staffViews.d.ts +18 -0
  127. package/dist/src/staffViews.d.ts.map +1 -1
  128. package/dist/src/staffViews.js +14 -0
  129. package/dist/src/staffViews.js.map +1 -1
  130. package/dist/src/subjects.d.ts +2 -0
  131. package/dist/src/subjects.d.ts.map +1 -1
  132. package/dist/src/subjects.js +4 -0
  133. package/dist/src/subjects.js.map +1 -1
  134. package/dist/src/team.d.ts +27 -0
  135. package/dist/src/team.d.ts.map +1 -1
  136. package/dist/src/team.js +92 -4
  137. package/dist/src/team.js.map +1 -1
  138. package/dist/src/types.d.ts +254 -7
  139. package/dist/src/types.d.ts.map +1 -1
  140. package/dist/src/types.js.map +1 -1
  141. package/package.json +2 -2
  142. package/src/ai/case.ts +6 -4
  143. package/src/ai/hash.ts +5 -2
  144. package/src/ai/prompt.ts +39 -2
  145. package/src/ai/service.ts +29 -14
  146. package/src/ai/types.ts +31 -2
  147. package/src/ai/worker.ts +20 -4
  148. package/src/appealService.ts +584 -0
  149. package/src/appeals.ts +256 -0
  150. package/src/audit.ts +18 -3
  151. package/src/chat.ts +109 -8
  152. package/src/chatwarden.ts +382 -27
  153. package/src/decide.ts +13 -7
  154. package/src/documents.ts +8 -3
  155. package/src/events.ts +23 -1
  156. package/src/freeze.ts +8 -0
  157. package/src/index.ts +52 -3
  158. package/src/ladder.ts +59 -1
  159. package/src/nameService.ts +255 -0
  160. package/src/names.ts +121 -0
  161. package/src/notices.ts +112 -14
  162. package/src/pace.ts +139 -0
  163. package/src/pacing.ts +242 -0
  164. package/src/policy.ts +125 -8
  165. package/src/profile.ts +115 -25
  166. package/src/profileError.ts +17 -0
  167. package/src/retention.ts +79 -3
  168. package/src/sanctions.ts +72 -9
  169. package/src/signalCounts.ts +133 -0
  170. package/src/signalInert.ts +31 -0
  171. package/src/signalService.ts +406 -0
  172. package/src/signals.ts +489 -0
  173. package/src/staffViews.ts +30 -0
  174. package/src/subjects.ts +5 -0
  175. package/src/team.ts +93 -5
  176. package/src/types.ts +275 -8
package/src/appeals.ts ADDED
@@ -0,0 +1,256 @@
1
+ import { ProfileError } from './profileError.js';
2
+ import type { RuleRef } from './rules.js';
3
+ import type { SanctionKind, SubjectId } from './types.js';
4
+
5
+ // The appeal settings: whether players may appeal a sanction, how many a week, and whether the moderator who made a decision may
6
+ // decide its appeal. Pure data and validation, no state and no clock; the service that acts on them comes later. Off until set, so a
7
+ // kit that sets nothing behaves exactly as before.
8
+
9
+ /** The longest statement, in characters. A constant, not a setting: it bounds what is stored. @experimental */
10
+ export const APPEAL_STATEMENT_MAX = 1000;
11
+
12
+ /** The allowed whole-number range of `perPlayerPerWeek`, and its default. */
13
+ const PER_WEEK_MIN = 1;
14
+ const PER_WEEK_MAX = 20;
15
+ const PER_WEEK_DEFAULT = 3;
16
+
17
+ const KEYS = ['enabled', 'perPlayerPerWeek', 'allowSelfReview'] as const;
18
+
19
+ /** What a moderator may rule on an appeal: the sanction stands, is made lighter, or is lifted. @experimental */
20
+ export const APPEAL_OUTCOMES = ['uphold', 'reduce', 'revoke'] as const;
21
+ export type AppealOutcome = (typeof APPEAL_OUTCOMES)[number];
22
+
23
+ /**
24
+ * Where an appeal stands. `open` until decided; `upheld`, `reduced` and `revoked` are the three outcomes; `moot` means the sanction was
25
+ * revoked by someone else while the appeal was open, so nobody ruled on it.
26
+ * @experimental
27
+ */
28
+ export type AppealStatus = 'open' | 'upheld' | 'reduced' | 'revoked' | 'moot';
29
+
30
+ /**
31
+ * How appeals run. Every field is optional; a profile without `appeals` has them off.
32
+ * @experimental
33
+ */
34
+ export interface AppealSettings {
35
+ /** Default false. */
36
+ enabled?: boolean;
37
+ /** Appeals one player may file in any rolling 7 days. 1 to 20, default 3. */
38
+ perPlayerPerWeek?: number;
39
+ /** May the moderator who made the original decision decide the appeal? Default false. For a team of one. */
40
+ allowSelfReview?: boolean;
41
+ }
42
+
43
+ /**
44
+ * What the kit reads: every field filled in.
45
+ * @experimental
46
+ */
47
+ export interface ResolvedAppeals {
48
+ enabled: boolean;
49
+ perPlayerPerWeek: number;
50
+ allowSelfReview: boolean;
51
+ }
52
+
53
+ function isPlain(v: unknown): v is Record<string, unknown> {
54
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
55
+ const proto: unknown = Object.getPrototypeOf(v);
56
+ return proto === Object.prototype || proto === null;
57
+ }
58
+
59
+ /** An own, defined value: a key left out, `undefined` and an inherited property all read as "not given". */
60
+ function given(o: Record<string, unknown>, key: string): unknown {
61
+ return Object.hasOwn(o, key) ? o[key] : undefined;
62
+ }
63
+
64
+ /**
65
+ * Validate and fill. Throws ProfileError naming the field (`appeals.perPlayerPerWeek`), never echoing the value. `path` names the
66
+ * settings in the error (default `appeals`). The result is a new object that shares nothing with the input; each value is read from
67
+ * `input` once.
68
+ * @experimental
69
+ */
70
+ export function resolveAppeals(input: AppealSettings | undefined, path = 'appeals'): ResolvedAppeals {
71
+ if (input === undefined) return { enabled: false, perPlayerPerWeek: PER_WEEK_DEFAULT, allowSelfReview: false };
72
+ if (!isPlain(input)) throw new ProfileError(path, 'must be an object');
73
+ for (const k of Object.keys(input)) if (!(KEYS as readonly string[]).includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
74
+ const enabled = given(input, 'enabled');
75
+ const perWeek = given(input, 'perPlayerPerWeek');
76
+ const self = given(input, 'allowSelfReview');
77
+ if (enabled !== undefined && typeof enabled !== 'boolean') throw new ProfileError(`${path}.enabled`, 'must be true or false');
78
+ if (perWeek !== undefined && (typeof perWeek !== 'number' || !Number.isSafeInteger(perWeek) || perWeek < PER_WEEK_MIN || perWeek > PER_WEEK_MAX)) {
79
+ throw new ProfileError(`${path}.perPlayerPerWeek`, `must be a whole number from ${PER_WEEK_MIN} to ${PER_WEEK_MAX}`);
80
+ }
81
+ if (self !== undefined && typeof self !== 'boolean') throw new ProfileError(`${path}.allowSelfReview`, 'must be true or false');
82
+ return {
83
+ enabled: enabled ?? false,
84
+ perPlayerPerWeek: (perWeek as number | undefined) ?? PER_WEEK_DEFAULT,
85
+ allowSelfReview: self ?? false,
86
+ };
87
+ }
88
+
89
+ /** What a player sees of an appeal. No staff field, no reason, no id of a sanction or a person. @experimental */
90
+ export interface PlayerAppeal {
91
+ id: string;
92
+ /** The notice it was filed from. */
93
+ noticeId: string;
94
+ status: 'open' | 'upheld' | 'reduced' | 'revoked';
95
+ createdAt: number;
96
+ decidedAt: number | null;
97
+ }
98
+
99
+ /**
100
+ * Why a filing was refused. `not_found` is one answer for "not yours", "no such notice" and "malformed", so notice ids cannot be probed.
101
+ * @experimental
102
+ */
103
+ export type AppealRefusal =
104
+ | 'off' // appeals are not enabled
105
+ | 'not_found' // not the caller's notice, or no such notice (the same answer, so ids cannot be probed)
106
+ | 'not_appealable' // the caller's notice, but not a sanction in their record
107
+ | 'statement_invalid' // empty after cleaning, or over APPEAL_STATEMENT_MAX characters
108
+ | 'already_appealed' // this sanction has had its appeal
109
+ | 'rate'; // perPlayerPerWeek reached
110
+
111
+ /** @experimental */
112
+ export type AppealFileResult = { ok: true; appeal: PlayerAppeal } | { ok: false; refused: AppealRefusal; retryAfterMs?: number }; // retryAfterMs on 'rate'
113
+
114
+ /** The most UTF-16 units of raw text the cleaner will look at: far past the cap, so a huge paste is refused without being worked through. */
115
+ const STATEMENT_RAW_MAX = APPEAL_STATEMENT_MAX * 20;
116
+
117
+ // Line and paragraph separators and the C1 next-line become a newline; a tab becomes a space.
118
+ const NEWLINES = /\r\n|[\r\u0085\u2028\u2029]/g;
119
+ // Control characters other than newline (tab is handled before), bidirectional controls and marks, zero-width and invisible format
120
+ // characters, the soft hyphen, the Mongolian vowel separator, the Hangul fillers (U+115F, U+1160, U+3164, U+FFA0), the braille blank
121
+ // (U+2800), the combining grapheme joiner (U+034F), the variation selectors (U+FE00 to U+FE0E; U+FE0F, the emoji presentation selector, is kept: it is common and harmless) and the interlinear annotation marks
122
+ // (U+FFF9 to U+FFFB). Each draws nothing, so a statement made of them would look blank to the staff reader.
123
+ // eslint-disable-next-line no-control-regex, no-misleading-character-class
124
+ const STRIPPED = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2069\u2800\u3164\ufe00-\ufe0e\ufeff\uffa0\ufff9-\ufffb]/g;
125
+ // Beyond the BMP (so this one needs the `u` flag): the tag characters (U+E0000 to U+E007F), which can carry hidden text, and the
126
+ // variation selectors supplement (U+E0100 to U+E01EF).
127
+ // eslint-disable-next-line no-misleading-character-class
128
+ const STRIPPED_ASTRAL = /[\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]/gu;
129
+ // A surrogate with no partner: it cannot be stored as UTF-8 (SQLite writes U+FFFD, the memory store keeps it), so both are removed first.
130
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
131
+
132
+ /**
133
+ * Clean a statement before it is counted or stored: line and paragraph separators become newlines and tabs spaces; control, bidirectional
134
+ * and zero-width characters, the soft hyphen, the Hangul fillers, the braille blank, the grapheme joiner, variation selectors, annotation
135
+ * marks, tag characters, NUL and lone surrogates are removed; every line loses its trailing space; runs of blank lines
136
+ * collapse to one; the whole is trimmed. Pure, idempotent, never throws; anything that is not a string, and a string longer than twenty times
137
+ * the cap, gives an empty string (which the filing refuses). Count the result in code points, not UTF-16 units.
138
+ * @experimental
139
+ */
140
+ export function normalizeStatement(input: unknown): string {
141
+ if (typeof input !== 'string' || input.length > STATEMENT_RAW_MAX) return '';
142
+ const text = input
143
+ .replace(NEWLINES, '\n')
144
+ .replace(/\t/g, ' ')
145
+ .replace(LONE_SURROGATE, '')
146
+ .replace(STRIPPED, '')
147
+ .replace(STRIPPED_ASTRAL, '')
148
+ .split('\n')
149
+ .map((line) => line.trimEnd())
150
+ .join('\n')
151
+ .replace(/\n{3,}/g, '\n\n')
152
+ .trim();
153
+ // U+FE0F is kept inside a text, but it draws nothing: a statement of nothing else is as blank as any other invisible one.
154
+ return /^[\s️]*$/.test(text) ? '' : text;
155
+ }
156
+
157
+ /** The length of a cleaned statement in characters (code points), the unit {@link APPEAL_STATEMENT_MAX} counts in. */
158
+ export function statementLength(text: string): number {
159
+ return [...text].length;
160
+ }
161
+
162
+ /** The four sanction kinds an appeal can concern, lightest first: a reduction must go to a lower kind, or to the same kind and shorter. */
163
+ export const SANCTION_KIND_ORDER = ['warning', 'chat', 'area', 'ban'] as const;
164
+
165
+ /**
166
+ * A moderator's ruling on an appeal.
167
+ * @experimental
168
+ */
169
+ export interface AppealDecision {
170
+ appealId: string;
171
+ outcome: AppealOutcome;
172
+ /** A staff ref the audit trail accepts. */
173
+ actor: string;
174
+ /** Private, 1 to 500 characters after trimming. Never shown to the player. */
175
+ reason: string;
176
+ /** `reduce` only: the lighter outcome that replaces the sanction. A warning has no length (`null`). */
177
+ to?: { kind: 'warning' | 'chat' | 'area' | 'ban'; durationMs: number | null };
178
+ }
179
+
180
+ /** @experimental */
181
+ export type AppealDecideResult =
182
+ | { ok: true; status: 'upheld' | 'reduced' | 'revoked'; replacementGroupId?: string }
183
+ | { ok: false; error: 'not_found' | 'already_decided' | 'invalid' | 'same_decider' | 'gone' };
184
+
185
+ /** Below this many sanctions in the window a rule has no rate. */
186
+ export const APPEAL_STATS_MIN_SANCTIONS = 10;
187
+ /** A rule whose rate is at or above this is `elevated`. */
188
+ export const APPEAL_RATE_ELEVATED = 0.15;
189
+ /** A rule whose rate is at or above this is `high`. */
190
+ export const APPEAL_RATE_HIGH = 0.3;
191
+
192
+ /**
193
+ * One appeal as staff see it in a list. The statement is NOT here (see {@link AppealDetail}); `statementFlagged` says whether it trips the
194
+ * term filter, so the hub can mask it. Carries a staff ref: staff channels only, never send to a player.
195
+ * @experimental
196
+ */
197
+ export interface AppealSummary {
198
+ id: string;
199
+ createdAt: number;
200
+ status: AppealStatus;
201
+ /** A staff ref. */
202
+ person: SubjectId;
203
+ /** The sanction. `decidedBy` is who made the original decision (the actor on its row); `''` and the appeal's own times when its rows are gone. */
204
+ sanction: { groupId: string; refCode: string; kind: SanctionKind; rule: RuleRef | null; startsAt: number; endsAt: number | null; decidedBy: string; automated: boolean };
205
+ statementFlagged: boolean;
206
+ }
207
+
208
+ /**
209
+ * One appeal in full, for one staff read (audited by the route).
210
+ * @experimental
211
+ */
212
+ export interface AppealDetail extends AppealSummary {
213
+ /** The player's words. Staff only. Null once purged. Masked by the hub when `statementFlagged`. */
214
+ statement: string | null;
215
+ /** Who decided (or, for a moot appeal, who revoked the sanction), when, and why (private; empty for a moot appeal), once it is no longer open. */
216
+ decided: { by: string; at: number; reason: string; replacementGroupId: string | null } | null;
217
+ /** The report whose decision made the sanction, when known. */
218
+ reportId: string | null;
219
+ /** What the player was shown with the sanction: their own lines, as the notice kept them (already masked where blocked). */
220
+ shown: Array<{ text: string; day: string }>;
221
+ }
222
+
223
+ /** @experimental */
224
+ export interface AppealPage {
225
+ items: AppealSummary[];
226
+ /** An opaque cursor for the next page, or null when this page was not full. */
227
+ next: string | null;
228
+ }
229
+
230
+ /**
231
+ * The appeal counts of one rule over a window. `granted` is REVOKED appeals only: a reduction is a severity dispute, not a false positive,
232
+ * so it is `lightened`, shown beside the rate and never in it.
233
+ * @experimental
234
+ */
235
+ export interface AppealRuleStats {
236
+ rule: number | 'uncovered';
237
+ /** Sanctions given under the rule in the window (warning, chat, area, ban; notes are not counted, a reduction counts once). */
238
+ sanctions: number;
239
+ /** Appeals filed in the window (any outcome, a moot one included). */
240
+ appealed: number;
241
+ /** Revoked on appeal. */
242
+ granted: number;
243
+ /** Reduced on appeal. */
244
+ lightened: number;
245
+ /** granted / sanctions, or null below {@link APPEAL_STATS_MIN_SANCTIONS} sanctions. */
246
+ rate: number | null;
247
+ band: 'normal' | 'elevated' | 'high' | null;
248
+ }
249
+
250
+ /** @experimental */
251
+ export interface AppealStats {
252
+ windowDays: number;
253
+ /** By rule number, `'uncovered'` last. */
254
+ perRule: AppealRuleStats[];
255
+ overall: { sanctions: number; appealed: number; granted: number; lightened: number; rate: number | null };
256
+ }
package/src/audit.ts CHANGED
@@ -16,6 +16,10 @@ export type Role = (typeof ROLES)[number];
16
16
  * The three `ai.*` actions target a report and carry no detail: `ai.read` is written by the AI itself (an `ai:` actor, no role)
17
17
  * when a read finishes, `ai.rerun` by a moderator who asked for another read, `ai.outcome` by a moderator whose decision was
18
18
  * recorded against a read.
19
+ *
20
+ * The three appeal and name actions (0.1.9): `appeal.view` is a staff read of the inbox, one appeal or the numbers (its target is the
21
+ * `appeal`, or none for the list and the numbers); `appeal.decide` points at the `appeal` decided and needs it; `name.rename_required`
22
+ * points at the `person` asked to rename and needs it. None of them carries a detail: a statement, a reason or a name never reaches the trail.
19
23
  */
20
24
  export const AUDIT_ACTIONS = [
21
25
  'report.view',
@@ -44,6 +48,9 @@ export const AUDIT_ACTIONS = [
44
48
  'ai.read',
45
49
  'ai.rerun',
46
50
  'ai.outcome',
51
+ 'appeal.view',
52
+ 'appeal.decide',
53
+ 'name.rename_required',
47
54
  ] as const;
48
55
  export type AuditAction = (typeof AUDIT_ACTIONS)[number];
49
56
 
@@ -63,14 +70,20 @@ export const AUDIT_REASON_MAX = 2000;
63
70
  /** The actions that point at a report (and only at one), and carry nothing else. */
64
71
  const AI_ACTIONS: readonly string[] = ['ai.read', 'ai.rerun', 'ai.outcome'];
65
72
 
73
+ /** The actions that point at an appeal (and only at one). `appeal.view` may point at none: the list and the numbers are not about one. */
74
+ const APPEAL_ACTIONS: readonly string[] = ['appeal.view', 'appeal.decide'];
75
+
76
+ /** The actions that cannot be recorded without a target. */
77
+ const TARGET_REQUIRED: readonly string[] = [...AI_ACTIONS, 'appeal.decide', 'name.rename_required'];
78
+
66
79
  /** An actor that is the AI itself, not a person: `ai:` and the adapter's id (`ai:anthropic:claude-haiku-5-5`). */
67
80
  const AI_ACTOR_PREFIX = 'ai:';
68
81
 
69
82
  /** The actions whose row carries an {@link AuditDetail}, and the only ones that may. */
70
83
  const DETAIL_ACTIONS: readonly string[] = ['policy.update', 'policy.reset'];
71
84
 
72
- /** What an entry points at: a report id, a sanction group id, a person (a staff ref), a term id, an exception id or a saved reason id. */
73
- export const AUDIT_TARGET_TYPES = ['report', 'sanction', 'person', 'term', 'exception', 'reason'] as const;
85
+ /** What an entry points at: a report id, a sanction group id, a person (a staff ref), a term id, an exception id, a saved reason id or an appeal id. */
86
+ export const AUDIT_TARGET_TYPES = ['report', 'sanction', 'person', 'term', 'exception', 'reason', 'appeal'] as const;
74
87
  export type AuditTargetType = (typeof AUDIT_TARGET_TYPES)[number];
75
88
 
76
89
  export interface AuditTarget {
@@ -236,11 +249,13 @@ function parse(input: unknown): AuditRecordInput | null {
236
249
  return null;
237
250
  }
238
251
  const extra = parsedDetail === undefined ? {} : { detail: parsedDetail };
239
- if (target === undefined) return AI_ACTIONS.includes(action) ? null : { actor, role: roleOut, action, ...extra };
252
+ if (target === undefined) return TARGET_REQUIRED.includes(action) ? null : { actor, role: roleOut, action, ...extra };
240
253
  if (typeof target !== 'object' || target === null) return null;
241
254
  const { type, ref } = target as Record<string, unknown>;
242
255
  if (!isTargetType(type) || typeof ref !== 'string' || !REF_RE.test(ref)) return null;
243
256
  if (AI_ACTIONS.includes(action) && type !== 'report') return null;
257
+ if (APPEAL_ACTIONS.includes(action) && type !== 'appeal') return null;
258
+ if (action === 'name.rename_required' && type !== 'person') return null;
244
259
  return { actor, role: roleOut, action, target: { type, ref }, ...extra };
245
260
  }
246
261
 
package/src/chat.ts CHANGED
@@ -1,7 +1,10 @@
1
1
  import type { EvidenceBuffer, RoomRoster } from './evidence.js';
2
- import { safeWarn, ThrottledWarn } from './log.js';
2
+ import { errorClass, safeWarn, ThrottledWarn } from './log.js';
3
3
  import type { MuteService } from './mutes.js';
4
4
  import type { NoticeService } from './notices.js';
5
+ import type { PaceReason, ResolvedPace } from './pace.js';
6
+ import { createPacer } from './pacing.js';
7
+ import type { PaceKey, Pacer } from './pacing.js';
5
8
  import type { Limits } from './limits.js';
6
9
  import { slidingWindow } from './rateLimit.js';
7
10
  import type { SlidingWindow } from './rateLimit.js';
@@ -28,11 +31,14 @@ import type {
28
31
  // 2. the seat's occupant, then the gate hook
29
32
  // 3. active restriction -> 'restricted' (chat, ban, or the in-memory automatic one)
30
33
  // 4. length > 200 -> 'length'
31
- // 5. rate, 3 per 5 s per room:seat -> 'rate' (spent even when the line is then blocked)
32
- // 6. matcher hit -> buffered as blocked, one strike, maybe an automatic timeout, 'blocked'
33
- // 7. profanity, by the profile's mode -> allow: untouched; star: masked; refuse: 'profanity' (never a strike,
34
+ // 5. pacing, when configured -> 'slow_mode' | 'flood' | 'duplicate' (read only: a refusal writes nothing and
35
+ // spends nothing; it carries `retryAfterMs`)
36
+ // 6. rate, 3 per 5 s per room:seat -> 'rate' (spent even when the line is then blocked)
37
+ // 7. pacing commit -- only now does the line count toward the next pacing check
38
+ // 8. matcher hit -> buffered as blocked, one strike, maybe an automatic timeout, 'blocked'
39
+ // 9. profanity, by the profile's mode -> allow: untouched; star: masked; refuse: 'profanity' (never a strike,
34
40
  // never buffered, never a notice: swearing is not a rule violation)
35
- // 8. buffer the delivered line -> its lineId
41
+ // 10. buffer the delivered line -> its lineId
36
42
  // It never throws. Everything on this path reads in-memory state; the only store writes are the strike
37
43
  // (inside StrikeService) and the automatic timeout, and a failure of either is logged and absorbed.
38
44
 
@@ -64,8 +70,12 @@ interface BlockedLine {
64
70
  * automatic-filter rule (`autoRestrictRule`, CR 1 by default) for `blocked`, and for `restricted` the sanction's
65
71
  * own rule (omitted when it is `'uncovered'` or unknown; the in-memory fallback cites the automatic-filter rule). `noticeId` is the player's notice that explains a restriction, when one
66
72
  * exists. Never an identifier, a rule's private note or the matched term. `'empty'` means stay silent.
73
+ *
74
+ * `'slow_mode'`, `'flood'` and `'duplicate'` are pacing refusals and only ever appear once pacing is configured (`profile.pace`, a
75
+ * stored layer or `cw.rooms.setPace`). They carry `retryAfterMs` and nothing else: a pause, not a sanction, so no rule, notice or end
76
+ * time, and never the line.
67
77
  */
68
- export type RefuseReason = 'empty' | 'length' | 'rate' | 'gate' | 'restricted' | 'blocked' | 'profanity';
78
+ export type RefuseReason = 'empty' | 'length' | 'rate' | 'gate' | 'restricted' | 'blocked' | 'profanity' | PaceReason;
69
79
 
70
80
  export type ChatResult =
71
81
  | { deliver: { lineId: string; text: string } }
@@ -76,6 +86,8 @@ export type ChatResult =
76
86
  byModerator?: boolean;
77
87
  rule?: number;
78
88
  noticeId?: string;
89
+ /** Present for `slow_mode`, `flood` and `duplicate`: when the same player may try again, in ms from now (a whole number, at least 1). @experimental */
90
+ retryAfterMs?: number;
79
91
  };
80
92
  };
81
93
 
@@ -136,13 +148,32 @@ export interface ChatServiceDeps {
136
148
  * `roomId:seatId`. The service trusts the numbers; the facade validates them.
137
149
  */
138
150
  limits?: { maxLength: Limits['chatMaxLength']; rate: Limits['chatRate'] };
151
+ /**
152
+ * Pacing: slow mode, a burst limit and repeat refusal. `settings` is read on every line (so a saved change applies at once) and
153
+ * answers every check off for a room that is not paced: such a line builds no key and makes no `canonical` call, and keeps no state.
154
+ * `canonical` folds a merged subject into the person the state is kept under. `onFlood` is told once per burst window when a known person trips the burst
155
+ * limit; a throw from it is logged by class and absorbed. Without `pace` nothing is paced.
156
+ * @experimental
157
+ */
158
+ pace?: {
159
+ settings: (roomId: string) => ResolvedPace;
160
+ canonical: (subject: SubjectId) => SubjectId;
161
+ onFlood?: (info: { roomId: string; subject: SubjectId }) => void;
162
+ };
163
+ }
164
+
165
+ /** What pacing says about a line: a refusal, or the key to commit under; neither when nothing is paced. */
166
+ interface Paced {
167
+ refusal: ChatResult | null;
168
+ key: PaceKey | null;
139
169
  }
170
+ const NOT_PACED: Paced = Object.freeze({ refusal: null, key: null });
140
171
 
141
172
  const errName = (err: unknown): string => (err instanceof Error ? err.name : typeof err);
142
173
 
143
174
  const refuse = (
144
175
  reason: RefuseReason,
145
- extra?: { until?: number | null; byModerator?: boolean; rule?: number; noticeId?: string },
176
+ extra?: { until?: number | null; byModerator?: boolean; rule?: number; noticeId?: string; retryAfterMs?: number },
146
177
  ): ChatResult => ({ refuse: extra === undefined ? { reason } : { reason, ...extra } });
147
178
 
148
179
  interface Restriction {
@@ -203,6 +234,10 @@ export class ChatService {
203
234
  private readonly rate: SlidingWindow;
204
235
  /** The typing lookup runs at keystroke rate: its failure line is limited to one a minute. */
205
236
  private readonly typingWarn: ThrottledWarn;
237
+ /** Pacing runs on every line: a failure of it is limited to one log line a minute. */
238
+ private readonly paceWarn: ThrottledWarn;
239
+ private readonly pacer: Pacer | undefined;
240
+ private readonly pace: ChatServiceDeps['pace'];
206
241
 
207
242
  /**
208
243
  * Automatic restrictions that could not be stored (no subject to put a row on, or the write failed), by
@@ -229,6 +264,9 @@ export class ChatService {
229
264
  this.onAutoRestricted = deps.onAutoRestricted;
230
265
  this.logger = deps.logger;
231
266
  this.typingWarn = new ThrottledWarn(deps.logger, deps.clock);
267
+ this.paceWarn = new ThrottledWarn(deps.logger, deps.clock);
268
+ this.pace = deps.pace;
269
+ this.pacer = deps.pace === undefined ? undefined : createPacer({ clock: deps.clock, settings: deps.pace.settings });
232
270
  this.notices = deps.notices;
233
271
  this.autoRestrictRule = deps.autoRestrictRule ?? DEFAULT_AUTO_RESTRICT_RULE;
234
272
  this.maxLength = deps.limits?.maxLength ?? MAX_LEN;
@@ -309,6 +347,11 @@ export class ChatService {
309
347
  }
310
348
  }
311
349
 
350
+ /** Forget a room's pacing state (the room is closing). */
351
+ dropPaceRoom(roomId: string): void {
352
+ this.pacer?.dropRoom(roomId);
353
+ }
354
+
312
355
  // --- internals -----------------------------------------------------------
313
356
 
314
357
  private run(roomId: string, seatId: string, text: string, opts?: { audience?: string[] }): ChatResult {
@@ -335,9 +378,20 @@ export class ChatService {
335
378
  }
336
379
 
337
380
  if (trimmed.length > this.maxLength) return refuse('length');
381
+
382
+ // Pacing asks before `rate` so the specific, retryable message wins over the blunt one; it only reads, so a refusal spends nothing.
383
+ // With every check off it builds nothing (no key, no canonical lookup) and there is nothing to commit.
384
+ const paced = this.pacer === undefined ? NOT_PACED : this.paceCheck(this.pacer, roomId, seatId, subject, trimmed);
385
+ if (paced.refusal !== null) return paced.refusal;
338
386
  // Spent even when the line is then blocked, so a flood of slurs is throttled like any flood and cannot
339
387
  // probe the term list faster than ordinary chat.
340
- if (!this.rate.check(rateKey)) return refuse('rate');
388
+ if (!this.rate.check(rateKey)) {
389
+ // The line passed pacing but never commits: the pacer must not keep its text.
390
+ this.paceDiscard(this.pacer);
391
+ return refuse('rate');
392
+ }
393
+ // Past `rate` the line has happened as far as pacing is concerned (a blocked or profane line has spent its slot too).
394
+ if (this.pacer !== undefined && paced.key !== null) this.paceCommit(this.pacer, paced.key, trimmed);
341
395
 
342
396
  const audience = opts?.audience === undefined ? null : [...opts.audience];
343
397
 
@@ -389,6 +443,53 @@ export class ChatService {
389
443
  return { deliver: { lineId, text: delivered } };
390
444
  }
391
445
 
446
+ /**
447
+ * Ask pacing about a line: a refusal to return, or the key to commit under once `rate` passes. Everything that can throw is in the
448
+ * fence (the settings, the canonical lookup, the pacer), and it fails open: a broken pacer must not silence chat, so the line goes on
449
+ * with nothing to commit and the class is logged (at most once a minute).
450
+ */
451
+ private paceCheck(pacer: Pacer, roomId: string, seatId: string, subject: SubjectId | null, text: string): Paced {
452
+ try {
453
+ if (!pacer.active(roomId)) return NOT_PACED;
454
+ const key: PaceKey = { roomId, who: subject === null ? `seat:${seatId}` : (this.pace?.canonical(subject) ?? subject) };
455
+ const verdict = pacer.check(key, text);
456
+ if (verdict.ok) return { refusal: null, key };
457
+ if (verdict.reason === 'flood' && verdict.signalFlood && subject !== null) this.tellFlood(roomId, key.who);
458
+ return { refusal: refuse(verdict.reason, { retryAfterMs: verdict.retryAfterMs }), key: null };
459
+ } catch (err) {
460
+ this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
461
+ return NOT_PACED;
462
+ }
463
+ }
464
+
465
+ private paceDiscard(pacer: Pacer | undefined): void {
466
+ try {
467
+ pacer?.discard();
468
+ } catch (err) {
469
+ this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
470
+ }
471
+ }
472
+
473
+ private paceCommit(pacer: Pacer, key: PaceKey, text: string): void {
474
+ try {
475
+ pacer.commit(key, text);
476
+ } catch (err) {
477
+ this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
478
+ }
479
+ }
480
+
481
+ /** Tell the facade a known person tripped the burst limit. Never changes the verdict: a throw or a rejection is logged by class and dropped. */
482
+ private tellFlood(roomId: string, subject: SubjectId): void {
483
+ const onFlood = this.pace?.onFlood;
484
+ if (onFlood === undefined) return;
485
+ try {
486
+ const out: unknown = onFlood({ roomId, subject });
487
+ if (isThenable(out)) out.then(undefined, (err: unknown) => this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) }));
488
+ } catch (err) {
489
+ this.paceWarn.warn('chatwarden.pace_failed', { error: errorClass(err) });
490
+ }
491
+ }
492
+
392
493
  /** The gate hook; a throw is a refusal (it is access control, so it fails closed). */
393
494
  private gateAllows(roomId: string, subject: SubjectId | null): boolean {
394
495
  if (this.gate === undefined) return true;