@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/signals.ts ADDED
@@ -0,0 +1,489 @@
1
+ import { deepFreeze } from './freeze.js';
2
+ import { ProfileError } from './profileError.js';
3
+ import type { RawWho, SubjectId } from './types.js';
4
+
5
+ // Signals: what a game records about a player (muted by others, kicked, left mid-game), declared in code, counted by distinct source and
6
+ // read by three feeds only because a profile rule says so. A signal never acts. This file has the declarations and their validation
7
+ // (`kinds`, `guards`, `feeds`) and the shapes the rest of the feature shares; counting is signalCounts.ts, the store is types.ts.
8
+ //
9
+ // Kind ids are the adopter's strings, so every lookup here uses OWN properties only: `constructor` and `toString` never resolve from
10
+ // the prototype. Nothing a validator throws echoes a value.
11
+
12
+ const DAY_MS = 86_400_000;
13
+
14
+ export type SignalPolarity = 'negative' | 'positive';
15
+
16
+ /**
17
+ * One kind a game declares. The key in `kinds` is the id the game passes to `record`.
18
+ * @experimental
19
+ */
20
+ export interface SignalKindSpec {
21
+ /** What staff read: "Muted by other players". Plain text, 1 to 60 characters, no markup. Also the label the AI feed sends. */
22
+ label: string;
23
+ polarity: SignalPolarity;
24
+ /** Default weight of one source, 0 to 10, default 1. A record may override it per call. */
25
+ weight?: number;
26
+ }
27
+
28
+ /** @experimental */
29
+ export interface SignalGuards {
30
+ /**
31
+ * At most one row per (kind, subject, source) per this many ms. Default 86 400 000 (one day). 60 000 to 30 days. The cap is a calendar bucket
32
+ * (`floor(at / perByWindowMs)`), not a rolling window: two rows a millisecond apart across a bucket edge both insert, and changing this later
33
+ * re-buckets the rows already stored.
34
+ */
35
+ perByWindowMs?: number;
36
+ /** Used ONLY when the adopter supplies `signals.accountAgeDays` to createChatwarden. Default: not set (no weighting). */
37
+ newAccount?: { belowDays: number; factor: number } | null;
38
+ }
39
+
40
+ /**
41
+ * One threshold, over distinct sources, in a window.
42
+ * @experimental
43
+ */
44
+ export interface SignalThreshold {
45
+ /** Declared kinds, 1 to 8. */
46
+ kinds: string[];
47
+ /** 1 to 50 distinct sources with weight above 0. */
48
+ minDistinct: number;
49
+ /** 1 to 90, and not above retention.signalsMs. */
50
+ windowDays: number;
51
+ /** The sum of those sources' weights must also reach this. */
52
+ minWeight?: number;
53
+ }
54
+
55
+ /**
56
+ * The feeds. Absent means that feed is off.
57
+ * @experimental
58
+ */
59
+ export interface SignalFeeds {
60
+ /** Lines on the Person page record. `'*'` means every declared kind. */
61
+ record?: { kinds: string[] | '*'; windowDays: number };
62
+ /** Queue ordering: a person who meets the threshold ranks ahead of older ordinary cases, capped. Negative kinds only. */
63
+ queue?: SignalThreshold;
64
+ /** The ladder. `note` adds a sentence to the suggestion; `raise` moves it up one step. `raise` takes negative kinds only. */
65
+ ladder?: Array<SignalThreshold & { id: string; effect: 'note' | 'raise' }>;
66
+ /** The AI read's case context. */
67
+ ai?: { kinds: string[] | '*'; windowDays: number };
68
+ }
69
+
70
+ /** @experimental */
71
+ export interface SignalSettings {
72
+ /** Code only. */
73
+ kinds?: Record<string, SignalKindSpec>;
74
+ /** Code only. */
75
+ guards?: SignalGuards;
76
+ /** Editable in the hub. */
77
+ feeds?: SignalFeeds;
78
+ }
79
+
80
+ /** The kind with every field filled in. */
81
+ export interface ResolvedSignalKind {
82
+ label: string;
83
+ polarity: SignalPolarity;
84
+ weight: number;
85
+ }
86
+
87
+ /** The guards with every field filled in; `newAccount` is null when not set. */
88
+ export interface ResolvedSignalGuards {
89
+ perByWindowMs: number;
90
+ newAccount: { belowDays: number; factor: number } | null;
91
+ }
92
+
93
+ /**
94
+ * What the kit reads: the declared kinds merged over the built-ins, the guards filled in, the feeds as given. Look kinds up with
95
+ * {@link kindSpecOf}, never with `kinds[id]`.
96
+ * @experimental
97
+ */
98
+ export interface ResolvedSignals {
99
+ kinds: Readonly<Record<string, ResolvedSignalKind>>;
100
+ guards: ResolvedSignalGuards;
101
+ feeds: SignalFeeds;
102
+ }
103
+
104
+ /** Who a signal is about or from: a staff-side subject id (`cw.rooms.subjectAt`), or the raw identity the game already passes to the doors. */
105
+ export type SignalParty = SubjectId | RawWho;
106
+
107
+ /** @experimental */
108
+ export interface SignalInput {
109
+ /** A declared kind (or a built-in). */
110
+ kind: string;
111
+ /** Whom it is about. */
112
+ subject: SignalParty;
113
+ /** Who produced it (the player who muted, the player who left). Omit (or `null`) for a source the game itself is, such as a timeout. */
114
+ by?: SignalParty | null;
115
+ /** The game's own room id: 1 to 64 characters of A-Z a-z 0-9 _ . : - . Not player text. `null` is the same as leaving it out. */
116
+ roomId?: string | null;
117
+ /** When it happened, epoch ms. Default: now (also for `null`). Not more than 5 minutes ahead, not older than retention.signalsMs. */
118
+ at?: number | null;
119
+ /** Overrides the kind's default weight for this one record. 0 to 10. */
120
+ weight?: number;
121
+ }
122
+
123
+ /** @experimental */
124
+ export interface SignalCount {
125
+ kind: string;
126
+ label: string;
127
+ polarity: SignalPolarity;
128
+ /** Distinct sources with weight above 0 in the window. */
129
+ distinct: number;
130
+ /** The sum of those sources' weights. */
131
+ weight: number;
132
+ windowDays: number;
133
+ firstAt: number;
134
+ lastAt: number;
135
+ }
136
+
137
+ /** @experimental */
138
+ export interface SignalKindView {
139
+ kind: string;
140
+ label: string;
141
+ polarity: SignalPolarity;
142
+ weight: number;
143
+ builtin: boolean;
144
+ }
145
+
146
+ /**
147
+ * Kinds the kit declares itself. An adopter may relabel or re-weight one by declaring the same key; the polarity must stay negative.
148
+ * @experimental
149
+ */
150
+ export const BUILTIN_SIGNAL_KINDS: Readonly<Record<'flood_triggered', Readonly<SignalKindSpec>>> = deepFreeze({
151
+ flood_triggered: { label: 'Flooded the chat', polarity: 'negative' as const },
152
+ });
153
+
154
+ /** A kind id: a lower-case slug. */
155
+ export const SIGNAL_KIND_PATTERN = /^[a-z][a-z0-9_]{0,39}$/;
156
+ /** The most kinds a game may declare. */
157
+ export const SIGNAL_KINDS_MAX = 40;
158
+ /** The longest window a feed may name, in days. */
159
+ export const SIGNAL_WINDOW_DAYS_MAX = 90;
160
+
161
+ const LABEL_MAX = 60;
162
+ const WEIGHT_MAX = 10;
163
+ const THRESHOLD_KINDS_MAX = 8;
164
+ const MIN_DISTINCT_MAX = 50;
165
+ const MIN_WEIGHT_MAX = MIN_DISTINCT_MAX * WEIGHT_MAX;
166
+ const LADDER_RULES_MAX = 20;
167
+ const RULE_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,39}$/;
168
+ const PER_BY_MIN_MS = 60_000;
169
+ const PER_BY_MAX_MS = 30 * DAY_MS;
170
+ const PER_BY_DEFAULT_MS = DAY_MS;
171
+ const NEW_ACCOUNT_DAYS_MAX = 365;
172
+ const BUILTIN_IDS: readonly string[] = Object.keys(BUILTIN_SIGNAL_KINDS);
173
+
174
+ const KIND_KEYS: readonly string[] = ['label', 'polarity', 'weight'];
175
+ const GUARD_KEYS: readonly string[] = ['perByWindowMs', 'newAccount'];
176
+ const NEW_ACCOUNT_KEYS: readonly string[] = ['belowDays', 'factor'];
177
+ const SETTINGS_KEYS: readonly string[] = ['kinds', 'guards', 'feeds'];
178
+ /** The feeds, in the order a settings screen lists them. */
179
+ export const SIGNAL_FEED_NAMES: readonly string[] = ['record', 'queue', 'ladder', 'ai'];
180
+ const THRESHOLD_KEYS: readonly string[] = ['kinds', 'minDistinct', 'windowDays', 'minWeight'];
181
+ const RULE_KEYS: readonly string[] = ['id', 'effect', ...THRESHOLD_KEYS];
182
+ const WINDOW_FEED_KEYS: readonly string[] = ['kinds', 'windowDays'];
183
+
184
+ function fail(path: string, reason: string, code?: SignalDropReason): never {
185
+ throw new ProfileError(path, reason, code);
186
+ }
187
+
188
+ function isPlain(v: unknown): v is Record<string, unknown> {
189
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
190
+ const proto: unknown = Object.getPrototypeOf(v);
191
+ return proto === Object.prototype || proto === null;
192
+ }
193
+
194
+ /** An own value, or undefined. A key left out and an inherited property both read as "not given". */
195
+ function given(o: Record<string, unknown>, key: string): unknown {
196
+ return Object.hasOwn(o, key) ? o[key] : undefined;
197
+ }
198
+
199
+ function setOwn(target: Record<string, unknown>, key: string, value: unknown): void {
200
+ // defineProperty, so a `__proto__` key becomes a plain own key.
201
+ Object.defineProperty(target, key, { value, enumerable: true, writable: true, configurable: true });
202
+ }
203
+
204
+ function onlyKeys(o: Record<string, unknown>, allowed: readonly string[], path: string): void {
205
+ for (const k of Object.keys(o)) if (!allowed.includes(k)) fail(`${path}.${k}`, 'is not a known setting');
206
+ }
207
+
208
+ /**
209
+ * The declared spec of a kind, from the kinds `resolveSignals` returned, or undefined. Reads own properties only, so `constructor`,
210
+ * `toString` and `__proto__` are never found unless a game declared them.
211
+ */
212
+ export function kindSpecOf(kinds: Readonly<Record<string, ResolvedSignalKind>>, id: string): ResolvedSignalKind | undefined {
213
+ return typeof id === 'string' && Object.hasOwn(kinds, id) ? kinds[id] : undefined;
214
+ }
215
+
216
+ // ---------------------------------------------------------------------------------------------------------------
217
+ // Kinds and guards
218
+
219
+ function whole(v: unknown, min: number, max: number): v is number {
220
+ return typeof v === 'number' && Number.isSafeInteger(v) && v >= min && v <= max;
221
+ }
222
+
223
+ /** Plain text on one line: no angle brackets (markup) and no control characters. */
224
+ function plainLabel(v: unknown): v is string {
225
+ return typeof v === 'string' && v.length >= 1 && v.length <= LABEL_MAX && v.trim() !== '' && !/[<>\p{C}\p{Zl}\p{Zp}]/u.test(v);
226
+ }
227
+
228
+ function kindSpec(id: string, v: unknown, path: string): ResolvedSignalKind {
229
+ if (!isPlain(v)) return fail(path, 'must be an object with a label and a polarity');
230
+ onlyKeys(v, KIND_KEYS, path);
231
+ const label = given(v, 'label');
232
+ if (!plainLabel(label)) fail(`${path}.label`, `must be plain text of 1 to ${LABEL_MAX} characters, on one line, with no markup`);
233
+ const polarity = given(v, 'polarity');
234
+ if (polarity !== 'negative' && polarity !== 'positive') fail(`${path}.polarity`, "must be 'negative' or 'positive'");
235
+ if (BUILTIN_IDS.includes(id) && polarity !== 'negative') fail(`${path}.polarity`, "must stay 'negative': the kit records this kind itself");
236
+ const weight = given(v, 'weight');
237
+ if (weight !== undefined && !(typeof weight === 'number' && Number.isFinite(weight) && weight >= 0 && weight <= WEIGHT_MAX)) {
238
+ fail(`${path}.weight`, `must be a number from 0 to ${WEIGHT_MAX}`);
239
+ }
240
+ return { label, polarity, weight: weight ?? 1 };
241
+ }
242
+
243
+ function resolveKinds(v: unknown, path: string): Record<string, ResolvedSignalKind> {
244
+ // No prototype, so a plain `kinds['constructor']` finds nothing unless a game declared it.
245
+ const out: Record<string, ResolvedSignalKind> = Object.create(null) as Record<string, ResolvedSignalKind>;
246
+ for (const id of BUILTIN_IDS) {
247
+ const b = BUILTIN_SIGNAL_KINDS[id as 'flood_triggered'];
248
+ setOwn(out, id, { label: b.label, polarity: b.polarity, weight: 1 });
249
+ }
250
+ if (v === undefined) return out;
251
+ if (!isPlain(v)) return fail(path, 'must be an object of kinds');
252
+ const ids = Object.keys(v);
253
+ if (ids.length > SIGNAL_KINDS_MAX) fail(path, `must declare at most ${SIGNAL_KINDS_MAX} kinds`);
254
+ for (const id of ids) {
255
+ if (!SIGNAL_KIND_PATTERN.test(id)) fail(path, 'has a kind id that is not a lower-case slug of 1 to 40 letters, digits and _, starting with a letter');
256
+ }
257
+ for (const id of ids) setOwn(out, id, kindSpec(id, v[id], `${path}.${id}`));
258
+ return out;
259
+ }
260
+
261
+ function resolveGuards(v: unknown, path: string): ResolvedSignalGuards {
262
+ if (v === undefined) return { perByWindowMs: PER_BY_DEFAULT_MS, newAccount: null };
263
+ if (!isPlain(v)) return fail(path, 'must be an object');
264
+ onlyKeys(v, GUARD_KEYS, path);
265
+ const per = given(v, 'perByWindowMs');
266
+ if (per !== undefined && !whole(per, PER_BY_MIN_MS, PER_BY_MAX_MS)) {
267
+ fail(`${path}.perByWindowMs`, `must be a whole number of milliseconds from ${PER_BY_MIN_MS} to ${PER_BY_MAX_MS}`);
268
+ }
269
+ const na = given(v, 'newAccount');
270
+ let newAccount: ResolvedSignalGuards['newAccount'] = null;
271
+ if (na !== undefined && na !== null) {
272
+ const p = `${path}.newAccount`;
273
+ if (!isPlain(na)) return fail(p, 'must be an object with belowDays and factor, or null');
274
+ onlyKeys(na, NEW_ACCOUNT_KEYS, p);
275
+ const belowDays = given(na, 'belowDays');
276
+ if (!whole(belowDays, 1, NEW_ACCOUNT_DAYS_MAX)) fail(`${p}.belowDays`, `must be a whole number of days from 1 to ${NEW_ACCOUNT_DAYS_MAX}`);
277
+ const factor = given(na, 'factor');
278
+ if (!(typeof factor === 'number' && Number.isFinite(factor) && factor > 0 && factor <= 1)) fail(`${p}.factor`, 'must be a number above 0 and at most 1');
279
+ newAccount = { belowDays, factor };
280
+ }
281
+ return { perByWindowMs: per ?? PER_BY_DEFAULT_MS, newAccount };
282
+ }
283
+
284
+ // ---------------------------------------------------------------------------------------------------------------
285
+ // Feeds
286
+
287
+ interface FeedContext {
288
+ kinds: Readonly<Record<string, ResolvedSignalKind>>;
289
+ signalsMs: number;
290
+ }
291
+
292
+ function windowDays(v: unknown, path: string, ctx: FeedContext): void {
293
+ if (!whole(v, 1, SIGNAL_WINDOW_DAYS_MAX)) fail(path, `must be a whole number of days from 1 to ${SIGNAL_WINDOW_DAYS_MAX}`, 'window');
294
+ if (v * DAY_MS > ctx.signalsMs) fail(path, 'must not be longer than retention.signalsMs: rows older than that are deleted, so the window could never be met', 'window');
295
+ }
296
+
297
+ /** A list of declared kinds: 1 to `max`, each declared, no repeats; `negativeOnly` also refuses a positive kind. */
298
+ function kindList(v: unknown, path: string, ctx: FeedContext, max: number, negativeOnly: boolean): void {
299
+ if (!Array.isArray(v) || v.length < 1 || v.length > max) fail(path, `must list 1 to ${max} declared kinds`);
300
+ const seen = new Set<string>();
301
+ v.forEach((id: unknown, i) => {
302
+ const p = `${path}[${i}]`;
303
+ const spec = typeof id === 'string' ? kindSpecOf(ctx.kinds, id) : undefined;
304
+ if (spec === undefined) fail(p, 'is not a kind this game declared', 'unknown_kind');
305
+ if (negativeOnly && spec.polarity !== 'negative') fail(p, 'is a positive kind: positive kinds may inform but never raise or boost', 'positive_kind');
306
+ if (seen.has(id as string)) fail(p, 'is listed twice');
307
+ seen.add(id as string);
308
+ });
309
+ }
310
+
311
+ function windowFeed(v: unknown, path: string, ctx: FeedContext): void {
312
+ if (!isPlain(v)) return fail(path, 'must be an object with kinds and windowDays');
313
+ onlyKeys(v, WINDOW_FEED_KEYS, path);
314
+ const kinds = given(v, 'kinds');
315
+ if (kinds === undefined) fail(`${path}.kinds`, 'is required');
316
+ if (kinds !== '*') kindList(kinds, `${path}.kinds`, ctx, SIGNAL_KINDS_MAX + 1, false);
317
+ const days = given(v, 'windowDays');
318
+ if (days === undefined) fail(`${path}.windowDays`, 'is required');
319
+ windowDays(days, `${path}.windowDays`, ctx);
320
+ }
321
+
322
+ function threshold(v: Record<string, unknown>, path: string, ctx: FeedContext, negativeOnly: boolean): void {
323
+ if (given(v, 'kinds') === undefined) fail(`${path}.kinds`, 'is required');
324
+ kindList(v['kinds'], `${path}.kinds`, ctx, THRESHOLD_KINDS_MAX, negativeOnly);
325
+ const minDistinct = given(v, 'minDistinct');
326
+ if (minDistinct === undefined) fail(`${path}.minDistinct`, 'is required');
327
+ if (!whole(minDistinct, 1, MIN_DISTINCT_MAX)) fail(`${path}.minDistinct`, `must be a whole number from 1 to ${MIN_DISTINCT_MAX}`);
328
+ const days = given(v, 'windowDays');
329
+ if (days === undefined) fail(`${path}.windowDays`, 'is required');
330
+ windowDays(days, `${path}.windowDays`, ctx);
331
+ const minWeight = given(v, 'minWeight');
332
+ if (minWeight !== undefined && !(typeof minWeight === 'number' && Number.isFinite(minWeight) && minWeight > 0 && minWeight <= MIN_WEIGHT_MAX)) {
333
+ fail(`${path}.minWeight`, `must be a number above 0 and at most ${MIN_WEIGHT_MAX}`);
334
+ }
335
+ }
336
+
337
+ function queueFeed(v: unknown, path: string, ctx: FeedContext): void {
338
+ if (!isPlain(v)) return fail(path, 'must be an object with kinds, minDistinct and windowDays');
339
+ onlyKeys(v, THRESHOLD_KEYS, path);
340
+ threshold(v, path, ctx, true);
341
+ }
342
+
343
+ function ladderRule(v: unknown, path: string, ctx: FeedContext): string {
344
+ if (!isPlain(v)) return fail(path, 'must be an object with an id, an effect and a threshold');
345
+ onlyKeys(v, RULE_KEYS, path);
346
+ const id = given(v, 'id');
347
+ if (typeof id !== 'string' || !RULE_ID_PATTERN.test(id)) fail(`${path}.id`, 'must be a lower-case id of 1 to 40 letters, digits, - and _');
348
+ const effect = given(v, 'effect');
349
+ if (effect !== 'note' && effect !== 'raise') fail(`${path}.effect`, "must be 'note' or 'raise'");
350
+ threshold(v, path, ctx, effect === 'raise');
351
+ return id;
352
+ }
353
+
354
+ function ladderFeed(v: unknown, path: string, ctx: FeedContext): void {
355
+ if (!Array.isArray(v)) return fail(path, 'must be a list of rules');
356
+ if (v.length > LADDER_RULES_MAX) fail(path, `must list at most ${LADDER_RULES_MAX} rules`);
357
+ const ids = new Set<string>();
358
+ v.forEach((rule: unknown, i) => {
359
+ const id = ladderRule(rule, `${path}[${i}]`, ctx);
360
+ if (ids.has(id)) fail(`${path}[${i}].id`, 'is used by another rule');
361
+ ids.add(id);
362
+ });
363
+ }
364
+
365
+ /**
366
+ * Check the feeds against the declared `kinds` and `opts.signalsMs` (the retention of signal rows, ms), throwing {@link ProfileError}
367
+ * whose path starts with `path` (`path.queue.kinds[0]`). A feed names declared kinds only; `queue` and a `raise` rule name negative
368
+ * kinds only; a count and a window are in range; a window is not longer than `signalsMs` (rows older than that are gone) or 90 days.
369
+ * @experimental
370
+ */
371
+ export function checkSignalFeeds(
372
+ feeds: SignalFeeds | undefined,
373
+ kinds: Readonly<Record<string, ResolvedSignalKind>>,
374
+ opts: { signalsMs: number },
375
+ path: string,
376
+ ): void {
377
+ if (feeds === undefined) return;
378
+ if (!isPlain(feeds)) return fail(path, 'must be an object');
379
+ onlyKeys(feeds, SIGNAL_FEED_NAMES, path);
380
+ const ctx: FeedContext = { kinds, signalsMs: opts.signalsMs };
381
+ for (const name of SIGNAL_FEED_NAMES) {
382
+ const feed = given(feeds, name);
383
+ if (feed === undefined) continue;
384
+ const p = `${path}.${name}`;
385
+ if (name === 'record' || name === 'ai') windowFeed(feed, p, ctx);
386
+ else if (name === 'queue') queueFeed(feed, p, ctx);
387
+ else ladderFeed(feed, p, ctx);
388
+ }
389
+ }
390
+
391
+ /** Why a stored feed was dropped: a code, never a value. */
392
+ export type SignalDropReason = 'unknown_feed' | 'unknown_kind' | 'positive_kind' | 'window' | 'invalid';
393
+
394
+ /** The code for a failed check: the code the check itself put on its error (never the wording of a message), else `invalid`. */
395
+ function dropReason(err: unknown): SignalDropReason {
396
+ const code = err instanceof ProfileError ? err.code : undefined;
397
+ return code === 'unknown_kind' || code === 'positive_kind' || code === 'window' ? code : 'invalid';
398
+ }
399
+
400
+ /**
401
+ * The feeds minus anything that can no longer be used: a feed (or a ladder rule) naming a kind the code stopped declaring, a positive
402
+ * kind where only negative ones are allowed, a window longer than `opts.signalsMs` or 90 days, or any other shape the checks refuse.
403
+ * Applied to a STORED layer at start-up, so one stale feed is dropped on its own and the rest of the layer (the ladder edits too) stays
404
+ * in force. Never throws: garbage in gives `{}`. `opts.onDrop` is told the name of each feed that lost something, once per feed, with
405
+ * the reason code of the first thing lost (a name that is not one of the four feeds is passed as it was stored, with `unknown_feed`: do
406
+ * not log it). The result passes {@link checkSignalFeeds}.
407
+ * @experimental
408
+ */
409
+ export function pruneSignalFeeds(
410
+ feeds: unknown,
411
+ kinds: Readonly<Record<string, ResolvedSignalKind>>,
412
+ opts: { signalsMs: number; onDrop?: (feed: string, reason: SignalDropReason) => void },
413
+ ): SignalFeeds {
414
+ const out: Record<string, unknown> = {};
415
+ if (!isPlain(feeds)) return out as SignalFeeds;
416
+ const ctx = { signalsMs: opts.signalsMs };
417
+ const drop = (name: string, reason: SignalDropReason): void => {
418
+ try {
419
+ opts.onDrop?.(name, reason);
420
+ } catch {
421
+ // A broken callback must not stop the prune.
422
+ }
423
+ };
424
+ /** Null when the feed is usable, else the reason it is not. */
425
+ const unusable = (name: string, value: unknown): SignalDropReason | null => {
426
+ try {
427
+ checkSignalFeeds({ [name]: value } as SignalFeeds, kinds, ctx, 'feeds');
428
+ return null;
429
+ } catch (err) {
430
+ return dropReason(err);
431
+ }
432
+ };
433
+ for (const name of Object.keys(feeds)) {
434
+ const value = feeds[name];
435
+ if (!SIGNAL_FEED_NAMES.includes(name)) {
436
+ drop(name, 'unknown_feed');
437
+ continue;
438
+ }
439
+ if (name !== 'ladder') {
440
+ const why = unusable(name, value);
441
+ if (why === null) setOwn(out, name, JSON.parse(JSON.stringify(value)));
442
+ else drop(name, why);
443
+ continue;
444
+ }
445
+ if (!Array.isArray(value)) {
446
+ drop(name, 'invalid');
447
+ continue;
448
+ }
449
+ const kept: unknown[] = [];
450
+ const ids = new Set<string>();
451
+ let lost: SignalDropReason | null = value.length > LADDER_RULES_MAX ? 'invalid' : null;
452
+ for (const rule of value.slice(0, LADDER_RULES_MAX)) {
453
+ const id = isPlain(rule) && typeof rule['id'] === 'string' ? rule['id'] : null;
454
+ const why = id === null || ids.has(id) ? 'invalid' : unusable(name, [rule]);
455
+ if (why === null) {
456
+ ids.add(id!);
457
+ kept.push(JSON.parse(JSON.stringify(rule)));
458
+ } else lost ??= why;
459
+ }
460
+ if (lost !== null) drop(name, lost);
461
+ if (kept.length > 0) setOwn(out, name, kept);
462
+ }
463
+ return out as SignalFeeds;
464
+ }
465
+
466
+ // ---------------------------------------------------------------------------------------------------------------
467
+
468
+ /** A deep copy of validated feeds (plain data: strings, numbers, arrays and objects). */
469
+ function copyFeeds(feeds: SignalFeeds): SignalFeeds {
470
+ return JSON.parse(JSON.stringify(feeds)) as SignalFeeds;
471
+ }
472
+
473
+ /**
474
+ * Validate the `signals` section and fill it in: the declared kinds merged over the built-ins, the guards with their defaults, the
475
+ * feeds as given. Throws {@link ProfileError} naming the field (`signals.kinds.x.label`), never echoing the value. The feeds are
476
+ * checked against the declared kinds and the 90 day cap here; the cross-check with `retention.signalsMs` is {@link checkSignalFeeds}'s
477
+ * job, called where the retention is known. The result shares nothing with the input, and resolving it again gives the same value.
478
+ * @experimental
479
+ */
480
+ export function resolveSignals(input: SignalSettings | undefined, path = 'signals'): ResolvedSignals {
481
+ if (input === undefined) return { kinds: resolveKinds(undefined, `${path}.kinds`), guards: resolveGuards(undefined, `${path}.guards`), feeds: {} };
482
+ if (!isPlain(input)) return fail(path, 'must be an object');
483
+ onlyKeys(input, SETTINGS_KEYS, path);
484
+ const kinds = resolveKinds(given(input, 'kinds'), `${path}.kinds`);
485
+ const guards = resolveGuards(given(input, 'guards'), `${path}.guards`);
486
+ const feeds = given(input, 'feeds') as SignalFeeds | undefined;
487
+ checkSignalFeeds(feeds, kinds, { signalsMs: Infinity }, `${path}.feeds`);
488
+ return { kinds, guards, feeds: feeds === undefined ? {} : copyFeeds(feeds) };
489
+ }
package/src/staffViews.ts CHANGED
@@ -9,6 +9,7 @@ import { parseRuleRef } from './rules.js';
9
9
  import type { RuleRef } from './rules.js';
10
10
  import { SANCTION_SOURCES } from './sanctions.js';
11
11
  import { b64urlDecode, b64urlEncode } from './staffReports.js';
12
+ import type { NameReason } from './names.js';
12
13
  import type { SubjectIndex } from './subjects.js';
13
14
  import type { SanctionKind, SanctionRow, Source, Store, SubjectId } from './types.js';
14
15
 
@@ -290,6 +291,8 @@ export function reporterRecord(
290
291
 
291
292
  /** The most blocked messages one call lists. */
292
293
  export const BLOCKED_MAX = 500;
294
+ /** The most kept blocked names `blocked.names` lists: what the store will return in one read (a store clamps its limit to 200). */
295
+ export const BLOCKED_NAMES_MAX = 200;
293
296
 
294
297
  /** The look-back windows of the blocked list, in days. */
295
298
  export const BLOCKED_DAYS = [1, 7, 30] as const;
@@ -336,3 +339,30 @@ export function blockedCountsByTerm(store: Store, days: unknown, now: number): R
336
339
  for (const r of store.countStrikesByTerm(sinceOf(days, now))) out[r.termId] = r.count;
337
340
  return out;
338
341
  }
342
+
343
+ /**
344
+ * One kept blocked name (`names.keepBlocked`): the name as it was typed, the term the matcher reported (null for a profanity hit), why it was
345
+ * refused, and the person when the caller was found (a staff ref; null for a caller the kit did not hold). Carries a name and a subject id: staff
346
+ * channels only, never send to a player.
347
+ */
348
+ export interface BlockedNameItem {
349
+ id: string;
350
+ at: number;
351
+ person: SubjectId | null;
352
+ name: string;
353
+ termId: string | null;
354
+ reason: NameReason;
355
+ }
356
+
357
+ /** The kept blocked names of the last `days` days (1, 7 or 30; `RangeError` otherwise), newest first, at most {@link BLOCKED_NAMES_MAX}. Empty for a store that keeps none. */
358
+ export function blockedNameItems(store: Store, subjects: SubjectIndex, days: unknown, now: number): BlockedNameItem[] {
359
+ const since = sinceOf(days, now);
360
+ return (store.listBlockedNames?.(since, BLOCKED_NAMES_MAX) ?? []).map((r) => ({
361
+ id: r.id,
362
+ at: r.at,
363
+ person: r.subject === null ? null : subjects.canonical(r.subject),
364
+ name: r.name,
365
+ termId: r.termId,
366
+ reason: r.reason,
367
+ }));
368
+ }
package/src/subjects.ts CHANGED
@@ -201,6 +201,11 @@ export class SubjectIndex {
201
201
  return keyWins ? keyRoot : accountRoot;
202
202
  }
203
203
 
204
+ /** Has this index ever seen the subject id (a merged-away one included)? A pure read: it creates nothing. */
205
+ knows(id: SubjectId): boolean {
206
+ return typeof id === 'string' && this.created.has(id);
207
+ }
208
+
204
209
  /**
205
210
  * The surviving subject `id` was merged into, following the chain to the
206
211
  * root. An id the index has never seen is returned unchanged.