@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/profile.ts CHANGED
@@ -18,6 +18,16 @@ import {
18
18
  resolveReporting,
19
19
  } from './reporting.js';
20
20
  import type { ReportingSettings, ResolvedReporting } from './reporting.js';
21
+ import { deepFreeze } from './freeze.js';
22
+ import { mergePace, resolvePace } from './pace.js';
23
+ import type { PaceSettings, ResolvedPace } from './pace.js';
24
+ import { resolveAppeals } from './appeals.js';
25
+ import type { AppealSettings, ResolvedAppeals } from './appeals.js';
26
+ import { resolveNames } from './names.js';
27
+ import type { NameSettings, ResolvedNames } from './names.js';
28
+ import { checkSignalFeeds, resolveSignals } from './signals.js';
29
+ import type { ResolvedSignals, SignalFeeds, SignalSettings } from './signals.js';
30
+ import { ProfileError } from './profileError.js';
21
31
 
22
32
  /**
23
33
  * A moderation profile is a game's written standard: what each conduct level means, what happens on a first
@@ -150,6 +160,32 @@ export interface ModerationProfile extends ModerationProfileBase {
150
160
  * hub edits this section; the code-side AI option sets the adapter and the highest level it may reach. See {@link AISettings}.
151
161
  */
152
162
  ai?: Partial<AISettings>;
163
+ /**
164
+ * How a room paces a player's lines: a least gap between them (`slowModeMs`), a burst limit (`burst`) and no repeats
165
+ * (`duplicateWindowMs`). Every setting is off until set, so a profile without `pace` changes nothing. See {@link PaceSettings}.
166
+ * @experimental
167
+ */
168
+ pace?: PaceSettings;
169
+ /**
170
+ * Signals: what the game records about a player (muted by others, kicked, left mid-game). `kinds` and `guards` are declared in code
171
+ * only; `feeds` says where counts may be read (the Person page record, the ladder suggestion, the AI read's context, the queue
172
+ * boost) and is editable in the hub. Nothing is unset-only: a profile without `signals` declares no kinds and has no feeds. A signal
173
+ * never acts. See {@link SignalSettings}.
174
+ * @experimental
175
+ */
176
+ signals?: SignalSettings;
177
+ /**
178
+ * Appeals: whether players may appeal a sanction from its notice, how many a week, and whether the moderator who made the original
179
+ * decision may decide its appeal. Off until set, so a profile without `appeals` changes nothing. See {@link AppealSettings}.
180
+ * @experimental
181
+ */
182
+ appeals?: AppealSettings;
183
+ /**
184
+ * Names: a profanity pass on the name check, kept evidence of blocked names, required renames, and masking a flagged name in the
185
+ * hub (on by default; it changes only what the hub shows). See {@link NameSettings}.
186
+ * @experimental
187
+ */
188
+ names?: NameSettings;
153
189
  }
154
190
 
155
191
  /**
@@ -193,6 +229,14 @@ export interface ResolvedProfile extends ModerationProfileBase {
193
229
  reporting: ResolvedReporting;
194
230
  /** The AI settings in force, every field filled in. */
195
231
  ai: AISettings;
232
+ /** The pace settings in force, every field filled in (`null` is off). @experimental */
233
+ pace: ResolvedPace;
234
+ /** The signal settings in force: the declared kinds merged over the built-ins, the guards filled in, the feeds as given. @experimental */
235
+ signals: ResolvedSignals;
236
+ /** The appeal settings in force, every field filled in. @experimental */
237
+ appeals: ResolvedAppeals;
238
+ /** The name settings in force, every field filled in. @experimental */
239
+ names: ResolvedNames;
196
240
  }
197
241
 
198
242
  /** @deprecated The same as {@link ModerationProfile}, which now has the two fields optional. */
@@ -208,18 +252,7 @@ export type DeepPartial<T> = T extends readonly unknown[]
208
252
  /** Overrides for {@link resolveProfile}. Any field; arrays replace the preset's array whole. */
209
253
  export type ProfileOverrides = DeepPartial<ModerationProfile>;
210
254
 
211
- /** A profile that fails validation. `path` names the field (`'profile.firstOffense.banter'`); the message never echoes a value. */
212
- export class ProfileError extends Error {
213
- readonly path: string;
214
- /** The rule that was broken, without the path. Never a value. */
215
- readonly reason: string;
216
- constructor(path: string, reason: string) {
217
- super(`${path} ${reason}`);
218
- this.name = 'ProfileError';
219
- this.path = path;
220
- this.reason = reason;
221
- }
222
- }
255
+ export { ProfileError };
223
256
 
224
257
  // ---------------------------------------------------------------------------------------------------------------
225
258
  // Validation
@@ -241,12 +274,16 @@ const TOP_KEYS = [
241
274
  'customDuration',
242
275
  'reporting',
243
276
  'ai',
277
+ 'pace',
278
+ 'signals',
279
+ 'appeals',
280
+ 'names',
244
281
  'levels',
245
282
  'guidelines',
246
283
  ] as const;
247
284
  /** Top-level keys that may be left out (the kit falls back to its defaults). */
248
285
  const RULE_LIST_KEYS: readonly string[] = ['areaRules', 'severeRules'];
249
- const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai'];
286
+ const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai', 'pace', 'signals', 'appeals', 'names'];
250
287
  const AI_KEYS = ['level', 'learn', 'dailyCalls'] as const;
251
288
  /** The most rule numbers `areaRules` or `severeRules` may list. */
252
289
  export const MAX_RULE_LIST = 100;
@@ -526,6 +563,10 @@ export function validateProfile(value: unknown): asserts value is ModerationProf
526
563
  if (Object.hasOwn(p, 'customDuration') && typeof p['customDuration'] !== 'boolean') fail('profile.customDuration', 'must be true or false');
527
564
  if (Object.hasOwn(p, 'reporting')) validateReporting(p['reporting'], 'profile.reporting');
528
565
  if (Object.hasOwn(p, 'ai')) validateAI(p['ai'], 'profile.ai');
566
+ if (Object.hasOwn(p, 'pace')) resolvePace(p['pace'] as PaceSettings, 'profile.pace');
567
+ if (Object.hasOwn(p, 'signals')) resolveSignals(p['signals'] as SignalSettings, 'profile.signals');
568
+ if (Object.hasOwn(p, 'appeals')) resolveAppeals(p['appeals'] as AppealSettings, 'profile.appeals');
569
+ if (Object.hasOwn(p, 'names')) resolveNames(p['names'] as NameSettings, 'profile.names');
529
570
 
530
571
  const prof = obj(p['profanity'], 'profile.profanity', PROFANITY_KEYS);
531
572
  oneOf(prof['mode'], 'profile.profanity.mode', PROFANITY_MODES, "must be 'allow', 'star' or 'refuse'");
@@ -587,14 +628,6 @@ function merge(base: unknown, over: unknown, depth = 0): unknown {
587
628
  return clone(over, depth);
588
629
  }
589
630
 
590
- function deepFreeze<T>(v: T): T {
591
- if (typeof v === 'object' && v !== null && !Object.isFrozen(v)) {
592
- Object.freeze(v);
593
- for (const item of Object.values(v)) deepFreeze(item);
594
- }
595
- return v;
596
- }
597
-
598
631
  /** Drop repeated numbers from `areaRules` and `severeRules` (first one wins, order kept) before they are validated. */
599
632
  function dedupeRuleLists(copy: unknown): void {
600
633
  if (!isPlain(copy)) return;
@@ -644,6 +677,13 @@ function finalize(value: unknown): ResolvedProfile {
644
677
  dedupeRuleLists(copy);
645
678
  fillDefaults(copy);
646
679
  validateProfile(copy);
680
+ // Checked above, so this cannot throw: every pace field is filled in, `null` meaning off.
681
+ if (isPlain(copy)) {
682
+ setOwn(copy, 'pace', resolvePace(copy['pace'] as PaceSettings | undefined, 'profile.pace'));
683
+ setOwn(copy, 'signals', resolveSignals(copy['signals'] as SignalSettings | undefined, 'profile.signals'));
684
+ setOwn(copy, 'appeals', resolveAppeals(copy['appeals'] as AppealSettings | undefined, 'profile.appeals'));
685
+ setOwn(copy, 'names', resolveNames(copy['names'] as NameSettings | undefined, 'profile.names'));
686
+ }
647
687
  return deepFreeze(copy as ResolvedProfile);
648
688
  }
649
689
 
@@ -658,6 +698,10 @@ export function withDurationDefaults(p: ModerationProfile): ResolvedProfile {
658
698
  customDuration: p.customDuration ?? true,
659
699
  reporting: resolveReporting(p.reporting),
660
700
  ai: { level: 0, learn: true, dailyCalls: AI_DAILY_CALLS_DEFAULT, ...p.ai },
701
+ pace: resolvePace(p.pace),
702
+ signals: resolveSignals(p.signals),
703
+ appeals: resolveAppeals(p.appeals),
704
+ names: resolveNames(p.names),
661
705
  };
662
706
  }
663
707
 
@@ -978,7 +1022,7 @@ export function defineProfile(p: ModerationProfile): ResolvedProfile {
978
1022
  * The parts of a profile the hub may edit, and the order they are listed in. Everything else (identity, the written
979
1023
  * levels, the AI context, profanity handling) stays in code: changing profanity means rebuilding the filter.
980
1024
  */
981
- export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai'] as const;
1025
+ export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai', 'pace', 'signals', 'appeals', 'names'] as const;
982
1026
  export type PolicySection = (typeof POLICY_SECTIONS)[number];
983
1027
 
984
1028
  /** One ladder cell as the editor sends it: the label may be left out and is then generated ("Restrict chat 6 hours"). */
@@ -1014,6 +1058,20 @@ export interface PolicyLayer {
1014
1058
  reporting?: ReportingSettings;
1015
1059
  /** The AI settings: `level` (0 off, 1 read, 2 recommend), `learn` and `dailyCalls` (the owner's ceiling on calls in a UTC day, a whole number from 1 to 100 000). Each is optional and merges onto the profile's. Levels 3 and 4 are refused. */
1016
1060
  ai?: Partial<AISettings>;
1061
+ /**
1062
+ * The pace settings: each field is optional and merges onto the profile's (a field left out inherits, `null` turns it off, a value sets
1063
+ * it); `burst` replaces whole. @experimental
1064
+ */
1065
+ pace?: PaceSettings;
1066
+ /**
1067
+ * The signal feeds: only `feeds` may be edited (the kinds and the guards are declared in code). The layer's `feeds` REPLACE the
1068
+ * profile's wholesale, like every other section: a feed left out is off. A feed names declared kinds only. @experimental
1069
+ */
1070
+ signals?: { feeds?: SignalFeeds };
1071
+ /** The appeal settings: `enabled`, `perPlayerPerWeek` (1 to 20) and `allowSelfReview`. Each is optional and merges onto the profile's. @experimental */
1072
+ appeals?: AppealSettings;
1073
+ /** The name settings: `profanity`, `keepBlocked`, `renames` and `maskInHub`. Each is optional and merges onto the profile's. @experimental */
1074
+ names?: NameSettings;
1017
1075
  }
1018
1076
 
1019
1077
  /** The longest outcome text a layer may set on a guideline tier. */
@@ -1061,6 +1119,28 @@ function wholeOutcome(v: unknown, path: string): void {
1061
1119
  if (!Object.hasOwn(v, 'durationMs')) fail(`${path}.durationMs`, 'is required');
1062
1120
  }
1063
1121
 
1122
+ /**
1123
+ * A layer's `signals` may hold only `feeds`, and every feed must name kinds the profile declares. The feeds themselves are not put in
1124
+ * the overrides: they replace the profile's wholesale, which the deep merge would not do, so `applyPolicyLayer` sets them after it.
1125
+ */
1126
+ function layerSignals(base: ModerationProfile, value: unknown): void {
1127
+ if (!isPlain(value)) return fail('profile.signals', 'must be an object');
1128
+ for (const k of Object.keys(value)) {
1129
+ if (k !== 'feeds') fail(`profile.signals.${k}`, 'is not an editable setting: kinds and guards are declared in code');
1130
+ }
1131
+ const feeds = Object.hasOwn(value, 'feeds') ? value['feeds'] : undefined;
1132
+ checkSignalFeeds(feeds as SignalFeeds | undefined, resolveSignals(base.signals, 'profile.signals').kinds, { signalsMs: Infinity }, 'profile.signals.feeds');
1133
+ }
1134
+
1135
+ /** Put the layer's signal feeds in place of the merged profile's (a feed the layer leaves out is off). */
1136
+ function replaceSignalFeeds(merged: unknown, layer: unknown): void {
1137
+ if (!isPlain(merged) || !isPlain(layer) || !Object.hasOwn(layer, 'signals') || !isPlain(layer['signals'])) return;
1138
+ const feeds = Object.hasOwn(layer['signals'], 'feeds') ? layer['signals']['feeds'] : undefined;
1139
+ const section = isPlain(merged['signals']) ? merged['signals'] : {};
1140
+ setOwn(section, 'feeds', feeds === undefined ? {} : clone(feeds));
1141
+ setOwn(merged, 'signals', section);
1142
+ }
1143
+
1064
1144
  function layerToOverrides(base: ModerationProfile, layer: unknown): Record<string, unknown> {
1065
1145
  if (!isPlain(layer)) return fail('profile', 'must be an object');
1066
1146
  for (const key of Object.keys(layer)) {
@@ -1074,7 +1154,15 @@ function layerToOverrides(base: ModerationProfile, layer: unknown): Record<strin
1074
1154
  for (const level of Object.keys(value)) wholeOutcome(value[level], `profile.firstOffense.${level}`);
1075
1155
  }
1076
1156
  if (key === 'repeat' && isPlain(value)) wholeOutcome(value['outcome'], 'profile.repeat.outcome');
1077
- if (key === 'ladder') setOwn(out, key, ladderOverride(value));
1157
+ if (key === 'signals') {
1158
+ layerSignals(base, value);
1159
+ continue;
1160
+ }
1161
+ if (key === 'pace') {
1162
+ // Checked on its own so the error names layer.pace..., then merged here so `burst` replaces whole instead of merging by member.
1163
+ resolvePace(value as PaceSettings, 'profile.pace');
1164
+ setOwn(out, key, mergePace(resolvePace(base.pace, 'profile.pace'), value as PaceSettings));
1165
+ } else if (key === 'ladder') setOwn(out, key, ladderOverride(value));
1078
1166
  else if (key === 'guidelines') setOwn(out, key, guidelinesOverride(base, value));
1079
1167
  else setOwn(out, key, value);
1080
1168
  }
@@ -1084,7 +1172,7 @@ function layerToOverrides(base: ModerationProfile, layer: unknown): Record<strin
1084
1172
  /** The same error, with the path named from the layer the editor sent (`profile.ladder[2]` is `layer.ladder[2]`). */
1085
1173
  function inLayerTerms(err: ProfileError): ProfileError {
1086
1174
  const path = err.path === 'profile' ? 'layer' : err.path.startsWith('profile.') ? `layer.${err.path.slice('profile.'.length)}` : err.path;
1087
- return new ProfileError(path, err.reason);
1175
+ return new ProfileError(path, err.reason, err.code);
1088
1176
  }
1089
1177
 
1090
1178
  /**
@@ -1095,7 +1183,9 @@ function inLayerTerms(err: ProfileError): ProfileError {
1095
1183
  */
1096
1184
  export function applyPolicyLayer(base: ModerationProfile, layer: PolicyLayer): ResolvedProfile {
1097
1185
  try {
1098
- return finalize(merge(base, layerToOverrides(base, layer)));
1186
+ const merged = merge(base, layerToOverrides(base, layer));
1187
+ replaceSignalFeeds(merged, layer);
1188
+ return finalize(merged);
1099
1189
  } catch (err) {
1100
1190
  throw err instanceof ProfileError ? inLayerTerms(err) : err;
1101
1191
  }
@@ -0,0 +1,17 @@
1
+ // Kept apart from profile.ts so pace.ts (which profile.ts imports) can throw it without an import cycle.
2
+
3
+ /** A profile that fails validation. `path` names the field (`'profile.firstOffense.banter'`); the message never echoes a value. */
4
+ export class ProfileError extends Error {
5
+ readonly path: string;
6
+ /** The rule that was broken, without the path. Never a value. */
7
+ readonly reason: string;
8
+ /** A stable code for the few failures a caller tells apart (a signal feed's `unknown_kind`, `positive_kind` or `window`); undefined for the rest. */
9
+ readonly code: string | undefined;
10
+ constructor(path: string, reason: string, code?: string) {
11
+ super(`${path} ${reason}`);
12
+ this.name = 'ProfileError';
13
+ this.path = path;
14
+ this.reason = reason;
15
+ this.code = code;
16
+ }
17
+ }
package/src/retention.ts CHANGED
@@ -35,6 +35,25 @@ export interface RetentionPolicy {
35
35
  * outlives a report, so it is the shortest of the three; 0 keeps no text at all.
36
36
  */
37
37
  aiExamplesMs: number;
38
+ /**
39
+ * A signal row (what a game recorded about a player, `flood_triggered` included) is deleted once it is older than this. At least 14
40
+ * days: a counting window needs at least two weeks of rows. A feed window longer than this is refused.
41
+ */
42
+ signalsMs: number;
43
+ /**
44
+ * The statement of a decided (or closed) appeal is set to nothing this long after the decision. It is the one new free text a player
45
+ * writes, so it is the shortest of the three. An open appeal's statement is kept until it is decided. 0 clears it at the next purge
46
+ * (and at the decision itself); no floor.
47
+ */
48
+ appealStatementsMs: number;
49
+ /**
50
+ * A decided appeal row is deleted this long after its decision. At least 90 days: the per-rule counts and the false-positive rate read
51
+ * these rows over a 90 day window. An appeal on a permanent sanction that is still in force is kept regardless (it stops a second appeal
52
+ * against it), and an open appeal is never deleted.
53
+ */
54
+ appealsMs: number;
55
+ /** A blocked name kept as evidence (`names.keepBlocked`) is deleted once it is older than this. The same clock as strikes. No floor. */
56
+ blockedNamesMs: number;
38
57
  }
39
58
 
40
59
  export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
@@ -46,12 +65,16 @@ export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
46
65
  auditMs: 365 * DAY_MS,
47
66
  aiOutcomesMs: 365 * DAY_MS,
48
67
  aiExamplesMs: 180 * DAY_MS,
68
+ signalsMs: 90 * DAY_MS,
69
+ appealStatementsMs: 90 * DAY_MS,
70
+ appealsMs: 365 * DAY_MS,
71
+ blockedNamesMs: 30 * DAY_MS,
49
72
  };
50
73
 
51
74
  /** The ladder looks back 90 days and "My record" shows 90 days, so the rows behind them must outlive that. */
52
75
  const RECORD_FLOOR_MS = 90 * DAY_MS;
53
76
 
54
- const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs'] as const;
77
+ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs', 'signalsMs', 'appealStatementsMs', 'appealsMs', 'blockedNamesMs'] as const;
55
78
 
56
79
  /**
57
80
  * Refuse a retention policy that would delete rows the kit still reads. Only the fields present are checked (an
@@ -62,6 +85,9 @@ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'ba
62
85
  * - `auditMs` at least 90 days: the staff trail is how a community answers "who did that"
63
86
  * - `aiOutcomesMs` at least 90 days: the agree-or-override record is the data the AI's later gates read
64
87
  * - `aiExamplesMs` at least 0 (0 keeps no example text at all)
88
+ * - `signalsMs` at least 14 days: a counting window needs at least two weeks of rows
89
+ * - `appealsMs` at least 90 days: the per-rule appeal counts read that far back
90
+ * - `appealStatementsMs` and `blockedNamesMs` at least 0 (0 keeps the text only until the next purge)
65
91
  *
66
92
  * Every field present must also be a finite number (`reportsMs` and `strikesMs` have no floor, only this).
67
93
  *
@@ -96,6 +122,18 @@ export function checkRetentionFloors(policy: Partial<RetentionPolicy>, suspendWi
96
122
  if (below(policy.aiExamplesMs, 0)) {
97
123
  throw new ProfileError('retention.aiExamplesMs', 'must be 0 or more: 0 keeps no example text at all');
98
124
  }
125
+ if (below(policy.signalsMs, 14 * DAY_MS)) {
126
+ throw new ProfileError('retention.signalsMs', 'must be at least 14 days: a counting window needs at least two weeks of rows');
127
+ }
128
+ if (below(policy.appealsMs, RECORD_FLOOR_MS)) {
129
+ throw new ProfileError('retention.appealsMs', 'must be at least 90 days: the per-rule appeal counts read that far back');
130
+ }
131
+ if (below(policy.appealStatementsMs, 0)) {
132
+ throw new ProfileError('retention.appealStatementsMs', 'must be 0 or more: 0 clears a statement as soon as its appeal is decided');
133
+ }
134
+ if (below(policy.blockedNamesMs, 0)) {
135
+ throw new ProfileError('retention.blockedNamesMs', 'must be 0 or more');
136
+ }
99
137
  if (below(policy.badFaithMs, suspendWindowMs)) {
100
138
  throw new ProfileError(
101
139
  'retention.badFaithMs',
@@ -118,6 +156,16 @@ export interface PurgeResult {
118
156
  aiReads: number;
119
157
  /** AI casebook outcomes deleted. 0 for a store without the AI methods. */
120
158
  aiOutcomes: number;
159
+ /** Signal rows deleted (flood_triggered included). 0 for a store without the signal methods. */
160
+ signals: number;
161
+ /** Decided appeal rows deleted. 0 for a store without the appeal methods. */
162
+ appeals: number;
163
+ /** Appeal statements set to nothing (the row stays). A statement counted here may belong to a row deleted in the same pass. 0 for a store without the appeal methods. */
164
+ appealStatements: number;
165
+ /** Kept blocked names deleted. 0 for a store without the blocked-name methods. */
166
+ blockedNames: number;
167
+ /** Open appeals mooted because retention removed their sanction rows. 0 for a store without the appeal methods. */
168
+ appealsClosed: number;
121
169
  }
122
170
 
123
171
  function checkWindow(name: string, ms: number): void {
@@ -141,9 +189,16 @@ function checkWindow(name: string, ms: number): void {
141
189
  * - AI reads: `createdAt < now - reportsMs` (a read also goes with its report, in `purgeReports`); AI outcomes (agree-or-override
142
190
  * record, no chat text): `decidedAt < now - aiOutcomesMs`; the pseudonymised example kept with an outcome:
143
191
  * `decidedAt < now - aiExamplesMs`, the row stays with its counts. A store without the AI methods has none of these.
192
+ * - signals: `at < now - signalsMs` (90 days by default, never less than 14); a store without the signal methods has none
193
+ * - appeals: the statement of an appeal decided (or closed) before `now - appealStatementsMs` is set to nothing, the row stays; then a
194
+ * decided row with `decidedAt < now - appealsMs` is deleted (365 days by default, never less than 90), EXCEPT one whose sanction is
195
+ * permanent, or timed and not yet ended before that cutoff, and not revoked (that row stops a second appeal). An open appeal is never
196
+ * deleted or cleared; but one whose sanction rows this pass removed (or that has none) is first mooted, so it ends up decided-like. Blocked names: `at < now - blockedNamesMs` (30 days by default).
197
+ * A store without the appeal or blocked-name methods has none of these.
144
198
  * - notices: withdrawn, or a seen warning / report outcome, with `createdAt < now - noticesMs`; or
145
199
  * `until < now - noticesMs`. A notice for a permanent or running sanction is kept while it applies (agrees with
146
- * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn.
200
+ * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn. The four message kinds: seen, as a report outcome;
201
+ * unseen, kept until the longer of `noticesMs` and `appealsMs` (appeal outcomes) or of `noticesMs` and `auditMs` (a required rename).
147
202
  *
148
203
  * Every cutoff is strict: a row exactly on the line is kept. Subjects and terms are never touched. The in-memory
149
204
  * indexes need no update: they already ignore everything this removes.
@@ -162,6 +217,10 @@ export async function purge(
162
217
  auditMs: policy.auditMs ?? RETENTION_DEFAULTS.auditMs,
163
218
  aiOutcomesMs: policy.aiOutcomesMs ?? RETENTION_DEFAULTS.aiOutcomesMs,
164
219
  aiExamplesMs: policy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
220
+ signalsMs: policy.signalsMs ?? RETENTION_DEFAULTS.signalsMs,
221
+ appealStatementsMs: policy.appealStatementsMs ?? RETENTION_DEFAULTS.appealStatementsMs,
222
+ appealsMs: policy.appealsMs ?? RETENTION_DEFAULTS.appealsMs,
223
+ blockedNamesMs: policy.blockedNamesMs ?? RETENTION_DEFAULTS.blockedNamesMs,
165
224
  };
166
225
  if (!Number.isFinite(now)) throw new Error('purge: invalid now');
167
226
  checkWindow('reportsMs', p.reportsMs);
@@ -172,6 +231,10 @@ export async function purge(
172
231
  checkWindow('auditMs', p.auditMs);
173
232
  checkWindow('aiOutcomesMs', p.aiOutcomesMs);
174
233
  checkWindow('aiExamplesMs', p.aiExamplesMs);
234
+ checkWindow('signalsMs', p.signalsMs);
235
+ checkWindow('appealStatementsMs', p.appealStatementsMs);
236
+ checkWindow('appealsMs', p.appealsMs);
237
+ checkWindow('blockedNamesMs', p.blockedNamesMs);
175
238
  return store.transaction(() => {
176
239
  const reports = store.purgeReports(now - p.reportsMs, now - p.badFaithMs);
177
240
  const ai = store.purgeAi?.(now - p.reportsMs, now - p.aiOutcomesMs, now - p.aiExamplesMs) ?? { reads: 0, outcomes: 0 };
@@ -180,11 +243,24 @@ export async function purge(
180
243
  sanctions: store.purgeSanctions(now - p.sanctionAfterEndMs),
181
244
  strikes: store.purgeStrikes(now - p.strikesMs),
182
245
  mutes: store.purgeMutes(now - MUTE_TTL_MS),
183
- notices: store.purgeNotices(now - p.noticesMs),
246
+ // An unseen message notice is kept until seen, but not for ever: an appeal outcome goes with the appeal row it describes, a required
247
+ // rename with the audit trail. Never earlier than a seen one would go (`noticesMs`).
248
+ notices: store.purgeNotices(now - p.noticesMs, {
249
+ appealBefore: now - Math.max(p.noticesMs, p.appealsMs),
250
+ renameBefore: now - Math.max(p.noticesMs, p.auditMs),
251
+ }),
184
252
  audit: store.purgeAudit(now - p.auditMs),
185
253
  webhookKeys: store.purgeWebhookKeys(now - WEBHOOK_KEY_TTL_MS),
186
254
  aiReads: ai.reads,
187
255
  aiOutcomes: ai.outcomes,
256
+ signals: store.purgeSignals?.(now - p.signalsMs) ?? 0,
257
+ // An open appeal whose sanction rows were just removed can never be decided (`gone`): moot it, so it leaves the inbox and its statement
258
+ // goes on the decided clock (cleared at once when `appealStatementsMs` is 0).
259
+ appealsClosed: store.closeOrphanAppeals?.('retention', now, p.appealStatementsMs === 0) ?? 0,
260
+ // Statements first: a statement is player text and goes on its own, shorter clock even when its row stays (or goes in the next call).
261
+ appealStatements: store.clearAppealStatements?.(now - p.appealStatementsMs) ?? 0,
262
+ appeals: store.purgeAppeals?.(now - p.appealsMs) ?? 0,
263
+ blockedNames: store.purgeBlockedNames?.(now - p.blockedNamesMs) ?? 0,
188
264
  };
189
265
  });
190
266
  }
package/src/sanctions.ts CHANGED
@@ -49,6 +49,13 @@ const REF_ATTEMPTS = 5;
49
49
  /** No I, L, O, 0 or 1: a player reads the code aloud or types it from a screenshot. */
50
50
  const REF_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
51
51
 
52
+ /**
53
+ * The key to `SanctionInput.startsAt`. It is exported from this module only, never from the package index, so only code inside the kit (the
54
+ * appeals service) can hold it; a public caller passing a start time is refused with a `RangeError`.
55
+ * @internal
56
+ */
57
+ export const APPEALS_START_TOKEN: unique symbol = Symbol('chatwarden.appeals.startsAt');
58
+
52
59
  export interface SanctionInput {
53
60
  kind: SanctionKind;
54
61
  /** The person to sanction; stored as its canonical (surviving) subject. */
@@ -77,6 +84,22 @@ export interface SanctionInput {
77
84
  * otherwise. Private; the ladder reads it to count notes from distinct games.
78
85
  */
79
86
  roomId?: string | null;
87
+ /**
88
+ * The report whose decision made this sanction: a non-empty string, kept on the subject row so a granted appeal can mark that decision
89
+ * reversed. Absent stores nothing (an automatic or direct sanction). Private. For the kit's own decision path only, like `startsAt`: it
90
+ * is accepted only with `startsAtToken`, because a wrong id would corrupt the casebook; any other caller passing it gets a `RangeError`.
91
+ * @internal
92
+ */
93
+ reportId?: string;
94
+ /**
95
+ * The start time to write instead of "now", epoch ms, never after "now". For the appeals service only, so a reduced sanction keeps the
96
+ * original start (the ladder reads sanctions by start). The end is `startsAt + durationMs`. Honoured only with `startsAtToken`; any other
97
+ * caller passing it gets a `RangeError`.
98
+ * @internal
99
+ */
100
+ startsAt?: number;
101
+ /** @internal The key to `startsAt` and `reportId`: {@link APPEALS_START_TOKEN}. */
102
+ startsAtToken?: symbol;
80
103
  }
81
104
 
82
105
  /** What `active` tells the chat path. No reason, rule, actor or identifier. */
@@ -108,10 +131,16 @@ export function refCode(): string {
108
131
  return out;
109
132
  }
110
133
 
111
- /** What `validate` settles: the rule as stored text, and the trimmed gap note (null when there is none). */
134
+ /**
135
+ * What `validate` settles: the rule as stored text, the trimmed gap note (null when there is none), and the two internal values it read
136
+ * ONCE (`start` and `reportId`, undefined when not given). The writer uses these, never a second read of the input, so what was checked
137
+ * is what is stored even for an object with getters or an inherited property.
138
+ */
112
139
  interface Checked {
113
140
  rule: string;
114
141
  gapNote: string | null;
142
+ start: number | undefined;
143
+ reportId: string | undefined;
115
144
  }
116
145
 
117
146
  /**
@@ -123,7 +152,21 @@ export function validateSanctionInput(input: SanctionInput): void {
123
152
  validate(input);
124
153
  }
125
154
 
126
- function validate(input: SanctionInput): Checked {
155
+ function validate(input: SanctionInput, now?: number): Checked {
156
+ // A start time and a report id are the kit's own (the appeals service and the decision): refused for everyone else before any other
157
+ // check, naming nothing of the input. Each is read ONCE, as an ordinary property read (an inherited value counts, so a prototype cannot
158
+ // smuggle one past the guard), and the writer uses this read.
159
+ const start: unknown = input.startsAt;
160
+ const report: unknown = input.reportId;
161
+ const token: unknown = input.startsAtToken;
162
+ if ((start !== undefined || report !== undefined) && token !== APPEALS_START_TOKEN) {
163
+ throw new RangeError('applySanction: startsAt and reportId are not accepted');
164
+ }
165
+ if (start !== undefined) {
166
+ if (typeof start !== 'number' || !Number.isSafeInteger(start) || start < 0) throw new SanctionError('applySanction: invalid start');
167
+ if (now !== undefined && start > now) throw new SanctionError('applySanction: a start cannot be in the future');
168
+ }
169
+ if (report !== undefined && (typeof report !== 'string' || report === '')) throw new SanctionError('applySanction: invalid report id');
127
170
  const d = input.durationMs;
128
171
  if (isRecordKind(input.kind)) {
129
172
  // A warning or a note has no end and no IP: it is a record, not a restriction.
@@ -151,12 +194,17 @@ function validate(input: SanctionInput): Checked {
151
194
  const note: unknown = input.gapNote;
152
195
  if (ref === 'uncovered' && input.source === 'moderator') {
153
196
  const trimmed = typeof note === 'string' ? note.trim() : '';
197
+ // The kit's own writers (the decision, the appeals service: `token`) may leave the note out: a replacement under no rule has its gap
198
+ // recorded on the sanction it replaces, so it does not open a second one.
199
+ if (trimmed === '' && token === APPEALS_START_TOKEN && note === undefined) {
200
+ return { rule: 'uncovered', gapNote: null, start: start as number | undefined, reportId: report as string | undefined };
201
+ }
154
202
  if (trimmed === '') throw new SanctionError('applySanction: a rule-gap note is required when no rule is cited');
155
203
  if (trimmed.length > GAP_NOTE_MAX) throw new SanctionError('applySanction: the rule-gap note is too long');
156
- return { rule: 'uncovered', gapNote: trimmed };
204
+ return { rule: 'uncovered', gapNote: trimmed, start: start as number | undefined, reportId: report as string | undefined };
157
205
  }
158
206
  if (note !== undefined) throw new SanctionError('applySanction: a rule-gap note is only for an uncovered moderator sanction');
159
- return { rule: String(ref), gapNote: null };
207
+ return { rule: String(ref), gapNote: null, start: start as number | undefined, reportId: report as string | undefined };
160
208
  }
161
209
 
162
210
  /** What {@link writeSanction} wrote: the group's handle and the rows, for the caller to hand to the index. */
@@ -175,11 +223,13 @@ function applyNow(
175
223
  now: number,
176
224
  pending: boolean,
177
225
  ): WrittenSanction {
178
- const { rule, gapNote } = validate(input);
226
+ const { rule, gapNote, start: given, reportId } = validate(input, now);
179
227
  const subject = subjects.canonical(input.subject);
228
+ // The start is "now" unless the appeals service gave the original one (validate has refused anyone else).
229
+ const start = given ?? now;
180
230
  // A warning or note has no end: it ends where it starts, so it is never "still running".
181
- const endsAt = isRecordKind(input.kind) ? now : input.durationMs === null ? null : now + input.durationMs;
182
- const ipEndsAt = endsAt === null ? now + IP_MAX_MS : Math.min(endsAt, now + IP_MAX_MS);
231
+ const endsAt = isRecordKind(input.kind) ? start : input.durationMs === null ? null : start + input.durationMs;
232
+ const ipEndsAt = endsAt === null ? start + IP_MAX_MS : Math.min(endsAt, start + IP_MAX_MS);
183
233
  const ip = input.includeIp ? subjects.latestIp(subject) : null;
184
234
  const groupId = newId();
185
235
 
@@ -188,7 +238,7 @@ function applyNow(
188
238
  groupId,
189
239
  refCode: code,
190
240
  kind: input.kind,
191
- startsAt: now,
241
+ startsAt: start,
192
242
  reason: input.reason,
193
243
  rule,
194
244
  roomId: input.roomId ?? null,
@@ -206,6 +256,8 @@ function applyNow(
206
256
  endsAt,
207
257
  gapNote,
208
258
  gapStatus: gapNote === null ? null : 'open',
259
+ // Only a sanction a report decision made carries one; the key is absent otherwise, so every other row keeps its shape.
260
+ ...(reportId === undefined ? {} : { reportId }),
209
261
  };
210
262
  const rows: SanctionRow[] = [subjectRow];
211
263
  if (ip !== null) {
@@ -271,6 +323,10 @@ export function writeSanction(
271
323
  * when given, the index are updated before the promise is returned. Resolves
272
324
  * true when this call revoked something, false for an unknown or already
273
325
  * revoked group.
326
+ *
327
+ * An appeal still open against the group is made moot in the same transaction. `opts.clearStatement` also clears that appeal's statement
328
+ * (what `retention.appealStatementsMs: 0` asks for); `cw.sanctions.revoke` passes it from the retention options the kit was CREATED with,
329
+ * so a one-off `cw.purge(policy)` with another `appealStatementsMs` does not change it, and the text then waits for the next purge.
274
330
  */
275
331
  export function revokeSanction(
276
332
  store: Store,
@@ -279,9 +335,16 @@ export function revokeSanction(
279
335
  now: number,
280
336
  reason: string,
281
337
  index?: SanctionIndex,
338
+ opts: { clearStatement?: boolean } = {},
282
339
  ): Promise<boolean> {
283
340
  try {
284
- const n = store.transaction(() => store.revokeSanctionGroup(groupId, actor, now, reason));
341
+ const n = store.transaction(() => {
342
+ const revoked = store.revokeSanctionGroup(groupId, actor, now, reason);
343
+ // An appeal still open against this group is moot now: nobody ruled on it. In the same transaction, so both land or neither.
344
+ // `clearStatement` (retention.appealStatementsMs 0) clears its text at once, as a decision would.
345
+ if (revoked > 0) store.closeAppealsForGroup?.(groupId, actor, now, opts.clearStatement === true);
346
+ return revoked;
347
+ });
285
348
  index?.remove(groupId);
286
349
  return Promise.resolve(n > 0);
287
350
  } catch (err) {