@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/names.ts ADDED
@@ -0,0 +1,121 @@
1
+ import { ProfileError } from './profileError.js';
2
+
3
+ // The name settings: a second check (profanity), optional kept evidence, a way to require a rename, and whether the hub masks a name
4
+ // the matcher flags. Pure data and validation. Off until set, except `maskInHub`, which is on: it changes only what the hub shows.
5
+
6
+ /** Why a name was refused. `name_profane` needs `names.profanity`. @experimental */
7
+ export type NameReason = 'name_not_allowed' | 'name_profane';
8
+
9
+ /** The answer of `cw.names.check`: allowed, or a reason id and the Community Rule it cites; never the text. @experimental */
10
+ export type NameCheckResult = { ok: true } | { ok: false; reason: NameReason; rule: number };
11
+
12
+ const KEYS = ['profanity', 'keepBlocked', 'renames', 'maskInHub'] as const;
13
+
14
+ /**
15
+ * How names are checked and shown. Every field is optional.
16
+ * @experimental
17
+ */
18
+ export interface NameSettings {
19
+ /** Also refuse a name the profanity filter flags. Default false (a swear word is not a slur; this is for a family game). */
20
+ profanity?: boolean;
21
+ /** Keep a blocked name, with the term it hit, as evidence. Default false: a name check stores nothing. */
22
+ keepBlocked?: boolean;
23
+ /** May a moderator require a rename from the Person page? Default false. */
24
+ renames?: boolean;
25
+ /** Mask a name the matcher flags in the hub until a moderator shows it. Default true. */
26
+ maskInHub?: boolean;
27
+ }
28
+
29
+ /**
30
+ * What the kit reads: every field filled in.
31
+ * @experimental
32
+ */
33
+ export interface ResolvedNames {
34
+ profanity: boolean;
35
+ keepBlocked: boolean;
36
+ renames: boolean;
37
+ maskInHub: boolean;
38
+ }
39
+
40
+ function isPlain(v: unknown): v is Record<string, unknown> {
41
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
42
+ const proto: unknown = Object.getPrototypeOf(v);
43
+ return proto === Object.prototype || proto === null;
44
+ }
45
+
46
+ /**
47
+ * Validate and fill. Throws ProfileError naming the field (`names.keepBlocked`), never echoing the value. `path` names the settings in
48
+ * the error (default `names`). The result is a new object that shares nothing with the input; each value is read from `input` once.
49
+ * @experimental
50
+ */
51
+ export function resolveNames(input: NameSettings | undefined, path = 'names'): ResolvedNames {
52
+ const out: ResolvedNames = { profanity: false, keepBlocked: false, renames: false, maskInHub: true };
53
+ if (input === undefined) return out;
54
+ if (!isPlain(input)) throw new ProfileError(path, 'must be an object');
55
+ for (const k of Object.keys(input)) if (!(KEYS as readonly string[]).includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
56
+ for (const k of KEYS) {
57
+ const v = Object.hasOwn(input, k) ? input[k] : undefined;
58
+ if (v === undefined) continue;
59
+ if (typeof v !== 'boolean') throw new ProfileError(`${path}.${k}`, 'must be true or false');
60
+ out[k] = v;
61
+ }
62
+ return out;
63
+ }
64
+
65
+ /** Most kept blocked names per person in an hour. */
66
+ export const NAME_EVIDENCE_PER_PERSON_HOUR = 5;
67
+ /** Most kept blocked names an hour, over everyone, in this process. */
68
+ export const NAME_EVIDENCE_PER_HOUR = 200;
69
+ /** The window both caps count over: a row leaves it exactly an hour after it was kept. */
70
+ export const NAME_EVIDENCE_WINDOW_MS = 3_600_000;
71
+ /** Most characters of a blocked name that are kept (a name is short; this bounds what a hostile caller can make the table hold). */
72
+ export const NAME_EVIDENCE_MAX_LENGTH = 200;
73
+
74
+ /** The name with underscores and digits turned into spaces: the second view the profanity filter reads (`big_snerp_99` is `big snerp `). */
75
+ export function profanityView(name: string): string {
76
+ return name.replace(/[_\p{Nd}]/gu, ' ');
77
+ }
78
+
79
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g;
80
+
81
+ /**
82
+ * The copy of a blocked name that is kept: NUL removed, a lone surrogate (which a database would not round-trip) replaced by U+FFFD, cut to
83
+ * {@link NAME_EVIDENCE_MAX_LENGTH} characters without leaving half an emoji. Only the first `2 * MAX` characters are even looked at.
84
+ */
85
+ export function evidenceName(name: string): string {
86
+ const head = name.slice(0, NAME_EVIDENCE_MAX_LENGTH * 2).replaceAll('\u0000', '').replace(LONE_SURROGATE, '\uFFFD');
87
+ if (head.length <= NAME_EVIDENCE_MAX_LENGTH) return head;
88
+ const cut = head.slice(0, NAME_EVIDENCE_MAX_LENGTH);
89
+ const last = cut.charCodeAt(cut.length - 1);
90
+ return last >= 0xd800 && last <= 0xdbff ? cut.slice(0, -1) : cut;
91
+ }
92
+
93
+ /**
94
+ * The hourly caps on kept blocked names: {@link NAME_EVIDENCE_PER_PERSON_HOUR} per key and {@link NAME_EVIDENCE_PER_HOUR} overall, in memory,
95
+ * over a sliding window. A key is whatever the caller counts a person by. `allow` only asks; `record` counts a row that really was kept, so a
96
+ * failed write never uses the cap. Holds at most 200 timestamps, however many names are probed. A time in the future (the clock moved back)
97
+ * no longer counts.
98
+ */
99
+ export class NameEvidenceLimiter {
100
+ private all: number[] = [];
101
+ private readonly by = new Map<string, number[]>();
102
+
103
+ allow(key: string, now: number): boolean {
104
+ this.all = this.all.filter((t) => live(t, now));
105
+ if (this.all.length >= NAME_EVIDENCE_PER_HOUR) return false;
106
+ const mine = (this.by.get(key) ?? []).filter((t) => live(t, now));
107
+ return mine.length < NAME_EVIDENCE_PER_PERSON_HOUR;
108
+ }
109
+
110
+ record(key: string, now: number): void {
111
+ this.all.push(now);
112
+ for (const [k, stamps] of this.by) {
113
+ const kept = stamps.filter((t) => live(t, now));
114
+ if (kept.length === 0) this.by.delete(k);
115
+ else this.by.set(k, kept);
116
+ }
117
+ this.by.set(key, [...(this.by.get(key) ?? []), now]);
118
+ }
119
+ }
120
+
121
+ const live = (t: number, now: number): boolean => t <= now && now - t < NAME_EVIDENCE_WINDOW_MS;
package/src/notices.ts CHANGED
@@ -22,6 +22,31 @@ export const NOTICE_LOOKUP_CACHE_MAX = 10_000;
22
22
  // A `note` is deliberately absent: it is on the record for staff and never makes a notice (see `DecisionService`).
23
23
  const SANCTION_NOTICE_KINDS: readonly NoticeKind[] = ['warning', 'chat', 'area', 'ban'];
24
24
 
25
+ /**
26
+ * The four notices that are messages, not sanctions: a rename is required, an appeal was upheld, reduced or revoked. They have no
27
+ * group, no end and no excerpt, show in `pending` and `announce` and never on "My record", and never need an acknowledgement. Made by
28
+ * {@link NoticeService.createMessage}. A seen one is purged like a seen report outcome; an unseen one is kept until seen or withdrawn.
29
+ * @experimental
30
+ */
31
+ export const MESSAGE_NOTICE_KINDS = ['rename_required', 'appeal_upheld', 'appeal_reduced', 'appeal_revoked'] as const;
32
+ export type MessageNoticeKind = (typeof MESSAGE_NOTICE_KINDS)[number];
33
+
34
+ /** Every kind this build can show. A stored row of any other kind (written by a newer kit) is skipped, never thrown on. */
35
+ /**
36
+ * Whether a notice row is on "My record" now: not withdrawn, one of the four sanction kinds, and either made within 90 days or (not a
37
+ * warning) permanent or still running. The one definition `record` uses and an appeal is filed against.
38
+ */
39
+ export function appliesInRecord(r: Pick<NoticeRow, 'withdrawnAt' | 'kind' | 'createdAt' | 'until'>, now: number): boolean {
40
+ return (
41
+ r.withdrawnAt === null &&
42
+ SANCTION_NOTICE_KINDS.includes(r.kind) &&
43
+ (r.createdAt >= now - NOTICE_RECORD_WINDOW_MS || (r.kind !== 'warning' && (r.until === null || r.until > now)))
44
+ );
45
+ }
46
+
47
+ const KNOWN_KINDS: readonly string[] = [...SANCTION_NOTICE_KINDS, 'report_outcome', ...MESSAGE_NOTICE_KINDS];
48
+ const isMessageKind = (kind: unknown): kind is MessageNoticeKind => (MESSAGE_NOTICE_KINDS as readonly unknown[]).includes(kind);
49
+
25
50
  /**
26
51
  * What a player is shown about a sanction taken against them, or about a report they filed. The ONLY shape that
27
52
  * leaves the kit for a player. It carries no subject, key, hash, room, seat or handle, no moderator reason or
@@ -31,13 +56,13 @@ export interface PlayerNotice {
31
56
  /** Random; the handle for `ack`. */
32
57
  id: string;
33
58
  kind: NoticeKind;
34
- /** The Community Rule cited; null for a report outcome. */
59
+ /** The Community Rule cited; null for a report outcome (and for a message that cites none). */
35
60
  rule: RuleRef | null;
36
61
  /** The player-facing name of the rule. */
37
62
  ruleLabel: string | null;
38
- /** Epoch ms the sanction ends; null = no end (permanent, a warning, or a report outcome). */
63
+ /** Epoch ms the sanction ends; null = no end (permanent, a warning, a report outcome or a message). */
39
64
  until: number | null;
40
- /** The reference code to quote to a moderator; null for a report outcome. */
65
+ /** The reference code to quote to a moderator; null for a report outcome (a message carries the original sanction's, or none). */
41
66
  refCode: string | null;
42
67
  /** At most five of the player's own lines. `day` is UTC `YYYY-MM-DD`. A blocked line has its matched terms masked. */
43
68
  excerpt: Array<{ text: string; day: string }>;
@@ -134,6 +159,14 @@ export interface NoticeCreateOptions {
134
159
  notify?: boolean;
135
160
  }
136
161
 
162
+ /** What a message notice may cite: the rule and the reference code of the decision it is about. Never a name, a reason or an excerpt. */
163
+ export interface MessageNoticeOptions extends NoticeCreateOptions {
164
+ /** The Community Rule the original decision cited. Default null. */
165
+ rule?: RuleRef | null;
166
+ /** The reference code of the original sanction, to quote to a moderator. Default null. */
167
+ refCode?: string | null;
168
+ }
169
+
137
170
  /** What a notice is told about a sanction. `excerptLines` come through {@link ownLines}. */
138
171
  export interface SanctionNoticeInput {
139
172
  groupId: string;
@@ -241,6 +274,28 @@ export class NoticeService {
241
274
  );
242
275
  }
243
276
 
277
+ /**
278
+ * Write a message notice (a rename is required, an appeal was upheld, reduced or revoked) for a person and tell their client.
279
+ * Returns the notice id. It carries the kind, an optional rule and reference code and the time, and nothing else: no excerpt, no name,
280
+ * no reason. It has no sanction group, so `withdrawGroup` never touches it. Throws for any other kind, a malformed rule or code, or a
281
+ * bad subject (nothing is written). Pass `{ notify: false }` inside a larger transaction, then call {@link announce} after the commit.
282
+ * @experimental
283
+ */
284
+ createMessage(subject: SubjectId, kind: MessageNoticeKind, opts: MessageNoticeOptions = {}): string {
285
+ if (!isMessageKind(kind)) throw new Error('createMessage: invalid kind');
286
+ if (!nonEmpty(subject)) throw new Error('createMessage: invalid subject');
287
+ const rule = opts.rule ?? null;
288
+ const refCode = opts.refCode ?? null;
289
+ if (refCode !== null && typeof refCode !== 'string') throw new Error('createMessage: invalid code');
290
+ if (rule !== null) parseRuleRef(String(rule)); // refuses a value the store could not read back
291
+ const canonical = this.subjects.canonical(subject);
292
+ return this.insert(
293
+ { subject: canonical, groupId: null, kind, rule: rule === null ? null : String(rule), until: null, refCode, excerpt: [] },
294
+ canonical,
295
+ opts.notify !== false,
296
+ );
297
+ }
298
+
244
299
  /** Tell a reporter that their report led to action. No rule, code, end or excerpt: nothing about the other player. */
245
300
  createReportOutcome(reporter: SubjectId, opts: NoticeCreateOptions = {}): string {
246
301
  if (!nonEmpty(reporter)) throw new Error('createReportOutcome: invalid subject');
@@ -284,22 +339,62 @@ export class NoticeService {
284
339
  /**
285
340
  * "My record": the person's sanction notices (seen or not) that are not withdrawn and still apply. A warning
286
341
  * applies for 90 days from when it was made (the ladder lookback). Any other kind applies while it is permanent
287
- * (until it is withdrawn), still running, or made within 90 days. Report outcomes are never included. Decided from
342
+ * (until it is withdrawn), still running, or made within 90 days. Report outcomes and the four message kinds are never included. Decided from
288
343
  * the notice row alone; `purgeNotices` agrees with this, so a row that applies is never purged.
289
344
  */
290
345
  record(subject: SubjectId): PlayerNotice[] {
291
346
  const now = this.clock.now();
292
347
  return this.rowsOf(subject)
293
- .filter(
294
- (r) =>
295
- r.withdrawnAt === null &&
296
- r.kind !== 'report_outcome' &&
297
- (r.createdAt >= now - NOTICE_RECORD_WINDOW_MS ||
298
- (r.kind !== 'warning' && (r.until === null || r.until > now))),
299
- )
348
+ .filter((r) => appliesInRecord(r, now))
300
349
  .map((r) => this.toPlayer(r));
301
350
  }
302
351
 
352
+ /**
353
+ * The stored notice `id` when it belongs to this person (across their merged aliases), whatever its kind or state; null otherwise.
354
+ * Staff-side: the row names its sanction group. For the appeals service, which decides from the row whether it can be appealed.
355
+ */
356
+ ownRow(subject: SubjectId, id: string): NoticeRow | null {
357
+ if (!nonEmpty(id)) return null;
358
+ return this.rowsOf(subject).find((r) => r.id === id) ?? null;
359
+ }
360
+
361
+ /**
362
+ * Does the person have a required rename they have not been released from: a `rename_required` notice not withdrawn, seen or not, on any of
363
+ * their merged subjects. Staff-side; the game reads it through `names.pendingRename`.
364
+ */
365
+ renamePending(subject: SubjectId): boolean {
366
+ return this.rowsOf(subject).some((r) => r.kind === 'rename_required' && r.withdrawnAt === null);
367
+ }
368
+
369
+ /** A person's `rename_required` notices, newest first, withdrawn ones included, across their merged subjects. Staff-side. */
370
+ renameRows(subject: SubjectId): NoticeRow[] {
371
+ return this.rowsOf(subject)
372
+ .filter((r) => r.kind === 'rename_required')
373
+ .sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? 1 : -1));
374
+ }
375
+
376
+ /** Can this build's store withdraw one notice by id? Without it a rename could never be released. */
377
+ canWithdrawOne(): boolean {
378
+ return typeof this.store.withdrawNotice === 'function';
379
+ }
380
+
381
+ /**
382
+ * Withdraw every pending `rename_required` notice of the person, in one transaction, and tell their client the new count when any was.
383
+ * Returns how many it withdrew (0 when none was pending, or the store cannot withdraw one). Other kinds are never touched.
384
+ */
385
+ withdrawRenames(subject: SubjectId): number {
386
+ const withdraw = this.store.withdrawNotice;
387
+ if (typeof withdraw !== 'function') return 0;
388
+ const ids = this.rowsOf(subject)
389
+ .filter((r) => r.kind === 'rename_required' && r.withdrawnAt === null)
390
+ .map((r) => r.id);
391
+ if (ids.length === 0) return 0;
392
+ const at = this.clock.now();
393
+ const done = this.store.transaction(() => ids.filter((id) => withdraw.call(this.store, id, at)).length);
394
+ if (done > 0) this.announce(subject);
395
+ return done;
396
+ }
397
+
303
398
  /** Withdraw the notices of a sanction group (it was revoked). Returns how many were withdrawn. */
304
399
  withdrawGroup(groupId: string): number {
305
400
  if (!nonEmpty(groupId)) return 0;
@@ -385,13 +480,16 @@ export class NoticeService {
385
480
  private rowsOf(subject: SubjectId): NoticeRow[] {
386
481
  if (!nonEmpty(subject)) return [];
387
482
  const person = this.subjects.canonical(subject);
388
- return this.store.loadNotices(this.subjects.aliasesOf(person)).filter((r) => this.subjects.canonical(r.subject) === person);
483
+ return this.store
484
+ .loadNotices(this.subjects.aliasesOf(person))
485
+ .filter((r) => KNOWN_KINDS.includes(r.kind) && this.subjects.canonical(r.subject) === person);
389
486
  }
390
487
 
391
488
  private toPlayer(r: NoticeRow): PlayerNotice {
392
489
  if (r.kind === 'report_outcome') {
393
490
  return { id: r.id, kind: r.kind, rule: null, ruleLabel: null, until: null, refCode: null, excerpt: [], createdAt: r.createdAt, mustAcknowledge: false };
394
491
  }
492
+ const message = isMessageKind(r.kind);
395
493
  let rule: RuleRef | null = null;
396
494
  if (r.rule !== null) {
397
495
  try {
@@ -405,9 +503,9 @@ export class NoticeService {
405
503
  kind: r.kind,
406
504
  rule,
407
505
  ruleLabel: rule === null ? null : this.rules.label(rule),
408
- until: r.until,
506
+ until: message ? null : r.until,
409
507
  refCode: r.refCode,
410
- excerpt: r.excerpt.map((l) => ({ text: l.text, day: l.day })),
508
+ excerpt: message ? [] : r.excerpt.map((l) => ({ text: l.text, day: l.day })),
411
509
  createdAt: r.createdAt,
412
510
  mustAcknowledge: r.kind === 'warning',
413
511
  };
package/src/pace.ts ADDED
@@ -0,0 +1,139 @@
1
+ import { deepFreeze } from './freeze.js';
2
+ import { ProfileError } from './profileError.js';
3
+
4
+ // The pace settings: how a room paces a player's lines (a gap, a burst limit, no repeats). Pure data and validation, no state and no
5
+ // clock; the limiter that applies them is pacing.ts. Every setting is off until set, so a kit that sets none behaves as before.
6
+
7
+ /** The reasons a line can be refused for pacing, in the order they are checked. */
8
+ export const PACE_REASONS = ['slow_mode', 'flood', 'duplicate'] as const;
9
+ export type PaceReason = (typeof PACE_REASONS)[number];
10
+
11
+ /**
12
+ * How a room paces a player's lines. Every field optional on input; `null` or absent is off.
13
+ * @experimental
14
+ */
15
+ export interface PaceSettings {
16
+ /** The least time between one player's lines in a room, ms. 500 to 600 000. */
17
+ slowModeMs?: number | null;
18
+ /** At most `lines` lines in any `windowMs`. `lines` 2 to 100, `windowMs` 1 000 to 600 000. */
19
+ burst?: { lines: number; windowMs: number } | null;
20
+ /** The same normalized line again inside this many ms is refused. 1 000 to 3 600 000. */
21
+ duplicateWindowMs?: number | null;
22
+ }
23
+
24
+ /**
25
+ * What the kit reads: every field filled, `null` meaning off.
26
+ * @experimental
27
+ */
28
+ export interface ResolvedPace {
29
+ slowModeMs: number | null;
30
+ burst: { lines: number; windowMs: number } | null;
31
+ duplicateWindowMs: number | null;
32
+ }
33
+
34
+ /** A normalized line shorter than this (in characters) is never a duplicate, so "gg" and "ok" stay free. */
35
+ export const DUPLICATE_MIN_CHARS = 3;
36
+ /** How many of a player's most recent line hashes a repeat is compared with. */
37
+ export const DUPLICATE_RECENT = 8;
38
+ /**
39
+ * The most (room, player) states the limiter holds; the oldest go. A state is small (a time, a digest or two) but a burst of 100 lines
40
+ * keeps up to 100 times and 8 digests per player, roughly 1.5 KB: at the cap with the largest settings that is about 70 MB, so a game
41
+ * that sets `burst.lines` high and has very many players in one process should budget for it.
42
+ */
43
+ export const PACE_KEYS_MAX = 50_000;
44
+
45
+ /** The allowed whole-number range of each number setting. */
46
+ const RANGES: Readonly<Record<string, readonly [number, number]>> = {
47
+ slowModeMs: [500, 600_000],
48
+ lines: [2, 100],
49
+ windowMs: [1000, 600_000],
50
+ duplicateWindowMs: [1000, 3_600_000],
51
+ };
52
+ const BURST_KEYS = ['lines', 'windowMs'] as const;
53
+ const PACE_KEYS = ['slowModeMs', 'burst', 'duplicateWindowMs'] as const;
54
+
55
+ /**
56
+ * Values the hub offers behind "Use suggested values". Never applied by themselves.
57
+ * @experimental
58
+ */
59
+ export const PACE_SUGGESTIONS: Readonly<Record<'relaxed' | 'standard' | 'strict', ResolvedPace>> = deepFreeze({
60
+ relaxed: { slowModeMs: null, burst: { lines: 10, windowMs: 10_000 }, duplicateWindowMs: 10_000 },
61
+ standard: { slowModeMs: null, burst: { lines: 6, windowMs: 10_000 }, duplicateWindowMs: 15_000 },
62
+ strict: { slowModeMs: 2000, burst: { lines: 5, windowMs: 10_000 }, duplicateWindowMs: 30_000 },
63
+ });
64
+
65
+ function isPlain(v: unknown): v is Record<string, unknown> {
66
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
67
+ const proto: unknown = Object.getPrototypeOf(v);
68
+ return proto === Object.prototype || proto === null;
69
+ }
70
+
71
+ /** An own, defined value: a key left out, `undefined` and an inherited property all read as "not given". */
72
+ function given(o: Record<string, unknown>, key: string): unknown {
73
+ return Object.hasOwn(o, key) ? o[key] : undefined;
74
+ }
75
+
76
+ /** `o` must be a plain object with no key outside `allowed`; a refusal names the key. */
77
+ function plain(o: unknown, allowed: readonly string[], path: string, what: string): Record<string, unknown> {
78
+ if (!isPlain(o)) throw new ProfileError(path, what);
79
+ for (const k of Object.keys(o)) if (!allowed.includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
80
+ return o;
81
+ }
82
+
83
+ function whole(v: unknown, key: string, path: string): number {
84
+ const [lo, hi] = RANGES[key]!;
85
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < lo || v > hi) throw new ProfileError(path, `must be a whole number from ${lo} to ${hi}`);
86
+ return v;
87
+ }
88
+
89
+ function checkBurst(v: unknown, path: string): { lines: number; windowMs: number } {
90
+ const o = plain(v, BURST_KEYS, path, 'must be an object with lines and windowMs, or null');
91
+ for (const k of BURST_KEYS) if (given(o, k) === undefined) throw new ProfileError(`${path}.${k}`, 'is required');
92
+ return { lines: whole(o['lines'], 'lines', `${path}.lines`), windowMs: whole(o['windowMs'], 'windowMs', `${path}.windowMs`) };
93
+ }
94
+
95
+ /**
96
+ * Check the shape and ranges of `input` and return what is set, as a new object that shares nothing with it: a key is present only
97
+ * when it was given a value (`null` included), and each value was read from `input` exactly once, so what was validated is what is
98
+ * returned even for an object with getters. Throws ProfileError like {@link resolvePace}. For a caller that must keep the override a
99
+ * room was given (`cw.rooms.setPace`).
100
+ * @experimental
101
+ */
102
+ export function checkPace(input: PaceSettings, path = 'pace'): PaceSettings {
103
+ return checked(input, path);
104
+ }
105
+
106
+ function checked(input: unknown, path: string): PaceSettings {
107
+ const o = plain(input, PACE_KEYS, path, 'must be an object');
108
+ const out: Record<string, unknown> = {};
109
+ for (const k of PACE_KEYS) {
110
+ const v = given(o, k);
111
+ if (v !== undefined) out[k] = v === null ? null : k === 'burst' ? checkBurst(v, `${path}.${k}`) : whole(v, k, `${path}.${k}`);
112
+ }
113
+ return out as PaceSettings;
114
+ }
115
+
116
+ /**
117
+ * Validate and fill. Throws ProfileError naming the field (`pace.burst.lines`), never echoing the value. `path` names the settings in
118
+ * the error (default `pace`). The result is a new object that shares nothing with the input.
119
+ * @experimental
120
+ */
121
+ export function resolvePace(input: PaceSettings | undefined, path = 'pace'): ResolvedPace {
122
+ if (input === undefined) return { slowModeMs: null, burst: null, duplicateWindowMs: null };
123
+ const set = checked(input, path);
124
+ return { slowModeMs: set.slowModeMs ?? null, burst: set.burst ?? null, duplicateWindowMs: set.duplicateWindowMs ?? null };
125
+ }
126
+
127
+ /**
128
+ * `over` on top of `base`: a field left out inherits, `null` turns it off, a value sets it. `burst` is replaced whole, never merged by
129
+ * member. `over` is validated (a ProfileError with the path `pace...`). Neither argument is changed or shared with the result.
130
+ * @experimental
131
+ */
132
+ export function mergePace(base: ResolvedPace, over: PaceSettings): ResolvedPace {
133
+ const set = checked(over, 'pace');
134
+ return {
135
+ slowModeMs: set.slowModeMs !== undefined ? set.slowModeMs : base.slowModeMs,
136
+ burst: set.burst !== undefined ? set.burst : base.burst === null ? null : { lines: base.burst.lines, windowMs: base.burst.windowMs },
137
+ duplicateWindowMs: set.duplicateWindowMs !== undefined ? set.duplicateWindowMs : base.duplicateWindowMs,
138
+ };
139
+ }