@chatwarden/core 0.1.7 → 0.1.8

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 (126) hide show
  1. package/README.md +124 -4
  2. package/dist/src/ai/case.d.ts +3 -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 +6 -2
  11. package/dist/src/ai/prompt.d.ts.map +1 -1
  12. package/dist/src/ai/prompt.js +11 -0
  13. package/dist/src/ai/prompt.js.map +1 -1
  14. package/dist/src/ai/service.d.ts +5 -1
  15. package/dist/src/ai/service.d.ts.map +1 -1
  16. package/dist/src/ai/service.js +2 -0
  17. package/dist/src/ai/service.js.map +1 -1
  18. package/dist/src/ai/types.d.ts +18 -2
  19. package/dist/src/ai/types.d.ts.map +1 -1
  20. package/dist/src/ai/types.js +2 -2
  21. package/dist/src/ai/types.js.map +1 -1
  22. package/dist/src/ai/worker.d.ts +3 -1
  23. package/dist/src/ai/worker.d.ts.map +1 -1
  24. package/dist/src/ai/worker.js +10 -3
  25. package/dist/src/ai/worker.js.map +1 -1
  26. package/dist/src/chat.d.ts +39 -1
  27. package/dist/src/chat.d.ts.map +1 -1
  28. package/dist/src/chat.js +85 -6
  29. package/dist/src/chat.js.map +1 -1
  30. package/dist/src/chatwarden.d.ts +68 -1
  31. package/dist/src/chatwarden.d.ts.map +1 -1
  32. package/dist/src/chatwarden.js +119 -5
  33. package/dist/src/chatwarden.js.map +1 -1
  34. package/dist/src/documents.d.ts +1 -1
  35. package/dist/src/documents.d.ts.map +1 -1
  36. package/dist/src/documents.js +3 -1
  37. package/dist/src/documents.js.map +1 -1
  38. package/dist/src/freeze.d.ts +3 -0
  39. package/dist/src/freeze.d.ts.map +1 -0
  40. package/dist/src/freeze.js +10 -0
  41. package/dist/src/freeze.js.map +1 -0
  42. package/dist/src/index.d.ts +13 -6
  43. package/dist/src/index.d.ts.map +1 -1
  44. package/dist/src/index.js +7 -2
  45. package/dist/src/index.js.map +1 -1
  46. package/dist/src/ladder.d.ts +28 -0
  47. package/dist/src/ladder.d.ts.map +1 -1
  48. package/dist/src/ladder.js +37 -1
  49. package/dist/src/ladder.js.map +1 -1
  50. package/dist/src/pace.d.ts +66 -0
  51. package/dist/src/pace.d.ts.map +1 -0
  52. package/dist/src/pace.js +111 -0
  53. package/dist/src/pace.js.map +1 -0
  54. package/dist/src/pacing.d.ts +63 -0
  55. package/dist/src/pacing.d.ts.map +1 -0
  56. package/dist/src/pacing.js +198 -0
  57. package/dist/src/pacing.js.map +1 -0
  58. package/dist/src/policy.d.ts +57 -1
  59. package/dist/src/policy.d.ts.map +1 -1
  60. package/dist/src/policy.js +67 -4
  61. package/dist/src/policy.js.map +1 -1
  62. package/dist/src/profile.d.ts +35 -8
  63. package/dist/src/profile.d.ts.map +1 -1
  64. package/dist/src/profile.js +57 -25
  65. package/dist/src/profile.js.map +1 -1
  66. package/dist/src/profileError.d.ts +10 -0
  67. package/dist/src/profileError.d.ts.map +1 -0
  68. package/dist/src/profileError.js +17 -0
  69. package/dist/src/profileError.js.map +1 -0
  70. package/dist/src/retention.d.ts +9 -0
  71. package/dist/src/retention.d.ts.map +1 -1
  72. package/dist/src/retention.js +10 -1
  73. package/dist/src/retention.js.map +1 -1
  74. package/dist/src/signalCounts.d.ts +37 -0
  75. package/dist/src/signalCounts.d.ts.map +1 -0
  76. package/dist/src/signalCounts.js +117 -0
  77. package/dist/src/signalCounts.js.map +1 -0
  78. package/dist/src/signalInert.d.ts +10 -0
  79. package/dist/src/signalInert.d.ts.map +1 -0
  80. package/dist/src/signalInert.js +28 -0
  81. package/dist/src/signalInert.js.map +1 -0
  82. package/dist/src/signalService.d.ts +101 -0
  83. package/dist/src/signalService.d.ts.map +1 -0
  84. package/dist/src/signalService.js +383 -0
  85. package/dist/src/signalService.js.map +1 -0
  86. package/dist/src/signals.d.ts +186 -0
  87. package/dist/src/signals.d.ts.map +1 -0
  88. package/dist/src/signals.js +361 -0
  89. package/dist/src/signals.js.map +1 -0
  90. package/dist/src/subjects.d.ts +2 -0
  91. package/dist/src/subjects.d.ts.map +1 -1
  92. package/dist/src/subjects.js +4 -0
  93. package/dist/src/subjects.js.map +1 -1
  94. package/dist/src/team.d.ts +27 -0
  95. package/dist/src/team.d.ts.map +1 -1
  96. package/dist/src/team.js +92 -4
  97. package/dist/src/team.js.map +1 -1
  98. package/dist/src/types.d.ts +56 -1
  99. package/dist/src/types.d.ts.map +1 -1
  100. package/dist/src/types.js.map +1 -1
  101. package/package.json +2 -2
  102. package/src/ai/case.ts +4 -4
  103. package/src/ai/hash.ts +5 -2
  104. package/src/ai/prompt.ts +16 -1
  105. package/src/ai/service.ts +8 -2
  106. package/src/ai/types.ts +19 -2
  107. package/src/ai/worker.ts +12 -4
  108. package/src/chat.ts +109 -8
  109. package/src/chatwarden.ts +184 -7
  110. package/src/documents.ts +5 -3
  111. package/src/freeze.ts +8 -0
  112. package/src/index.ts +41 -3
  113. package/src/ladder.ts +59 -1
  114. package/src/pace.ts +139 -0
  115. package/src/pacing.ts +242 -0
  116. package/src/policy.ts +107 -7
  117. package/src/profile.ts +83 -25
  118. package/src/profileError.ts +17 -0
  119. package/src/retention.ts +17 -1
  120. package/src/signalCounts.ts +133 -0
  121. package/src/signalInert.ts +31 -0
  122. package/src/signalService.ts +406 -0
  123. package/src/signals.ts +489 -0
  124. package/src/subjects.ts +5 -0
  125. package/src/team.ts +93 -5
  126. package/src/types.ts +65 -1
package/src/policy.ts CHANGED
@@ -7,6 +7,10 @@ import { playerReporting } from './reporting.js';
7
7
  import type { PlayerReporting } from './reporting.js';
8
8
  import type { RuleRef } from './rules.js';
9
9
  import { errorClass, safeWarn } from './log.js';
10
+ import { RETENTION_DEFAULTS } from './retention.js';
11
+ import { checkSignalFeeds, pruneSignalFeeds, SIGNAL_FEED_NAMES } from './signals.js';
12
+ import type { SignalDropReason } from './signals.js';
13
+ import { RATE_LIMIT, RATE_WINDOW_MS } from './chat.js';
10
14
  import { retryBusy } from './team.js';
11
15
  import { CONDUCT_LEVELS } from './types.js';
12
16
  import type { Clock, ConductLevel, Logger, Store } from './types.js';
@@ -22,13 +26,38 @@ import type { Clock, ConductLevel, Logger, Store } from './types.js';
22
26
  /** How often a read may look at the store for a newer version: 10 seconds. */
23
27
  export const POLICY_REFRESH_MS = 10_000;
24
28
 
29
+ /**
30
+ * A stored signal feed that was dropped when the layer was read: the feed (`record`, `queue`, `ladder`, `ai`, or `unknown` for a name the kit
31
+ * does not have) and why. A code only: never a kind id, a rule id, a label or a number from the stored layer.
32
+ * @experimental
33
+ */
34
+ export interface PolicyDropped {
35
+ feed: string;
36
+ reason: SignalDropReason;
37
+ }
38
+
39
+ /**
40
+ * The kit's own numbers the settings screens need, read only: they come from `createChatwarden` (`limits.chatRate`, `retention.signalsMs`), are
41
+ * never part of the stored layer, and a save cannot change them.
42
+ * @experimental
43
+ */
44
+ export interface PolicyLimits {
45
+ /** The chat rate the kit enforces per room and seat: at most `count` lines in any `windowMs` (default 3 per 5 000 ms). Slow mode and burst sit beside it. */
46
+ chatRate: { count: number; windowMs: number };
47
+ /** How long signal rows are kept, ms: the longest window a signal feed may look back (default 90 days, never less than 14). */
48
+ signalsMs: number;
49
+ }
50
+
25
51
  /** What {@link PolicyService.get} answers. */
26
52
  export interface PolicyState {
27
53
  /** The profile in force: base, then the stored layer. Deep-frozen. */
28
54
  effective: ResolvedProfile;
29
55
  /** The profile from code (preset and overrides), without the stored layer. Deep-frozen. */
30
56
  base: ResolvedProfile;
31
- /** The stored layer as last read (`{}` when none), deep-frozen. */
57
+ /**
58
+ * The layer in force, as last read (`{}` when none), deep-frozen: the stored layer with any signal feed that could no longer be used
59
+ * taken out (see `dropped`). Send it back to `save` and the save is accepted, and repairs the stored row.
60
+ */
32
61
  layer: PolicyLayer;
33
62
  /** The stored layer's version; 0 when nothing was ever saved. Pass it back to `save`. */
34
63
  version: number;
@@ -41,6 +70,19 @@ export interface PolicyState {
41
70
  * valid (a newer kit's field, a hand edit). Either way a save or a full `reset()` repairs it.
42
71
  */
43
72
  layerError?: { path: string; kind: 'unreadable' | 'invalid' };
73
+ /**
74
+ * Present only when the stored layer held signal feeds that could no longer be used (the code stopped declaring their kind, or a
75
+ * window is longer than the retention now allows) and were left out of `layer` and of what is in force. One entry per feed, with the
76
+ * reason of the first thing lost from it. The stored row itself is rewritten by the next save.
77
+ * @experimental
78
+ */
79
+ dropped?: readonly PolicyDropped[];
80
+ /**
81
+ * The chat rate limit actually in force and the signals retention window, so a settings screen can say what slow mode sits beside and how
82
+ * far back a feed may look. Read only, deep-frozen.
83
+ * @experimental
84
+ */
85
+ limits: PolicyLimits;
44
86
  }
45
87
 
46
88
  /** What {@link PolicyService.save} and {@link PolicyService.reset} answer. */
@@ -91,11 +133,18 @@ export class PolicyService {
91
133
  private readonly clock: Clock;
92
134
  private readonly logger: Logger | undefined;
93
135
  private readonly base: ResolvedProfile;
94
- private state: { effective: ResolvedProfile; layer: PolicyLayer; version: number; layerError?: PolicyState['layerError'] };
136
+ private state: { effective: ResolvedProfile; layer: PolicyLayer; version: number; layerError?: PolicyState['layerError']; dropped?: readonly PolicyDropped[] };
95
137
  /** When the store was last looked at (epoch ms), or null before the first read. */
96
138
  private lastCheck: number | null = null;
97
139
 
98
- constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile }) {
140
+ /** How long signal rows are kept, ms: a feed window longer than this could never be met. */
141
+ private readonly signalsMs: () => number;
142
+ /** The chat rate in force (`limits.chatRate`), for `get().limits`. */
143
+ private readonly chatRate: { count: number; windowMs: number };
144
+
145
+ constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile; signalsMs?: () => number; chatRate?: { count: number; windowMs: number } }) {
146
+ this.signalsMs = deps.signalsMs ?? (() => RETENTION_DEFAULTS.signalsMs);
147
+ this.chatRate = Object.freeze({ count: deps.chatRate?.count ?? RATE_LIMIT, windowMs: deps.chatRate?.windowMs ?? RATE_WINDOW_MS });
99
148
  this.store = deps.store;
100
149
  this.clock = deps.clock;
101
150
  this.logger = deps.logger;
@@ -121,7 +170,10 @@ export class PolicyService {
121
170
  const raw: unknown = stored === null ? {} : stored.layer;
122
171
  const layer = frozenCopy(raw as PolicyLayer);
123
172
  try {
124
- this.state = { effective: applyPolicyLayer(this.base, layer), layer, version };
173
+ // What is read and shown is the layer in force: the stale feeds are out of it, so a save that sends it back is never refused for them.
174
+ const { layer: inForce, dropped } = this.withoutStaleFeeds(layer);
175
+ const shown = dropped.length === 0 ? layer : frozenCopy(inForce);
176
+ this.state = { effective: applyPolicyLayer(this.base, shown), layer: shown, version, ...(dropped.length === 0 ? {} : { dropped: Object.freeze(dropped.map((d) => Object.freeze(d))) }) };
125
177
  } catch (err) {
126
178
  if (!(err instanceof ProfileError)) throw err;
127
179
  // What `get()` shows is always an object: an unreadable layer reads as empty, with the error beside it.
@@ -133,6 +185,36 @@ export class PolicyService {
133
185
  }
134
186
  }
135
187
 
188
+ /**
189
+ * The stored layer with any signal feed that can no longer be used taken out (it names a kind the code stopped declaring, or a window
190
+ * longer than the retention now allows), and what was taken out. Without this one stale feed would make the whole layer unusable and
191
+ * silently drop the owner's other edits too. Logged by feed name only. Anything else wrong with the layer is left for
192
+ * `applyPolicyLayer` to refuse; a layer with nothing to drop comes back as it is.
193
+ */
194
+ private withoutStaleFeeds(layer: PolicyLayer): { layer: PolicyLayer; dropped: PolicyDropped[] } {
195
+ const dropped: PolicyDropped[] = [];
196
+ const signals: unknown = typeof layer === 'object' && layer !== null && !Array.isArray(layer) ? (layer as { signals?: unknown }).signals : undefined;
197
+ const feeds: unknown = typeof signals === 'object' && signals !== null && !Array.isArray(signals) ? (signals as { feeds?: unknown }).feeds : undefined;
198
+ if (typeof feeds !== 'object' || feeds === null || Array.isArray(feeds)) return { layer, dropped };
199
+ const pruned = pruneSignalFeeds(feeds, this.base.signals.kinds, {
200
+ signalsMs: this.signalsMs(),
201
+ onDrop: (name, reason) => {
202
+ const feed = SIGNAL_FEED_NAMES.includes(name) ? name : 'unknown';
203
+ safeWarn(this.logger, 'chatwarden.signal_feed_dropped', { feed });
204
+ dropped.push({ feed, reason });
205
+ },
206
+ });
207
+ if (dropped.length === 0) return { layer, dropped };
208
+ // Nothing usable is left of the section: it is not shown at all, so the code's own feeds are what is in force (a section with a `feeds`
209
+ // key replaces them wholesale, and an empty one would keep them off for a reason nobody can see).
210
+ const { feeds: _gone, ...others } = signals as { feeds?: unknown };
211
+ void _gone;
212
+ const rest = { ...layer } as Record<string, unknown>;
213
+ if (Object.keys(pruned).length === 0 && Object.keys(others).length === 0) delete rest['signals'];
214
+ else rest['signals'] = Object.keys(pruned).length === 0 ? others : { ...others, feeds: pruned };
215
+ return { layer: rest as PolicyLayer, dropped };
216
+ }
217
+
136
218
  /** Look at the store now and adopt a strictly newer version (an older one, say a restored backup, never regresses what is in force). A store failure throws. */
137
219
  private reload(): void {
138
220
  const stored = this.store.loadPolicyLayer?.() ?? null;
@@ -166,8 +248,17 @@ export class PolicyService {
166
248
 
167
249
  get(): PolicyState {
168
250
  this.maybeRefresh();
169
- const { effective, layer, version, layerError } = this.state;
170
- return { effective, base: this.base, layer, version, canSave: this.supported, ...(layerError === undefined ? {} : { layerError: { ...layerError } }) };
251
+ const { effective, layer, version, layerError, dropped } = this.state;
252
+ return {
253
+ effective,
254
+ base: this.base,
255
+ layer,
256
+ version,
257
+ canSave: this.supported,
258
+ ...(layerError === undefined ? {} : { layerError: { ...layerError } }),
259
+ ...(dropped === undefined ? {} : { dropped }),
260
+ limits: Object.freeze({ chatRate: this.chatRate, signalsMs: this.signalsMs() }),
261
+ };
171
262
  }
172
263
 
173
264
  /** Look at the store now, whatever the interval. A store failure throws. */
@@ -191,6 +282,11 @@ export class PolicyService {
191
282
  return { ok: false, error: 'conflict' };
192
283
  }
193
284
  const changed = changedSections(before, layer);
285
+ // The layer this save was judged against had feeds taken out of it (`dropped`): the stored row loses them now, so `signals` changed.
286
+ if (this.state.version === expected && this.state.dropped !== undefined && !changed.includes('signals')) {
287
+ changed.push('signals');
288
+ changed.sort((a, b) => POLICY_SECTIONS.indexOf(a) - POLICY_SECTIONS.indexOf(b));
289
+ }
194
290
  this.lastCheck = this.clock.now();
195
291
  this.adopt({ layer, version: next });
196
292
  return { ok: true, version: next, changed };
@@ -212,7 +308,9 @@ export class PolicyService {
212
308
  return { ok: false, error: 'invalid', path: 'reason' };
213
309
  }
214
310
  try {
215
- applyPolicyLayer(this.base, layer);
311
+ const effective = applyPolicyLayer(this.base, layer);
312
+ // The windows are checked against the retention here, where it is known: a window longer than it could never be met.
313
+ checkSignalFeeds(effective.signals.feeds, effective.signals.kinds, { signalsMs: this.signalsMs() }, 'layer.signals.feeds');
216
314
  } catch (err) {
217
315
  if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
218
316
  throw err;
@@ -264,6 +362,8 @@ export class PolicyService {
264
362
  let candidate: ResolvedProfile;
265
363
  try {
266
364
  candidate = applyPolicyLayer(this.base, layer);
365
+ // As save: a window longer than the retention could never be met, so the candidate is refused here too, not only when it is saved.
366
+ checkSignalFeeds(candidate.signals.feeds, candidate.signals.kinds, { signalsMs: this.signalsMs() }, 'layer.signals.feeds');
267
367
  } catch (err) {
268
368
  if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
269
369
  throw err;
package/src/profile.ts CHANGED
@@ -18,6 +18,12 @@ 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 { checkSignalFeeds, resolveSignals } from './signals.js';
25
+ import type { ResolvedSignals, SignalFeeds, SignalSettings } from './signals.js';
26
+ import { ProfileError } from './profileError.js';
21
27
 
22
28
  /**
23
29
  * A moderation profile is a game's written standard: what each conduct level means, what happens on a first
@@ -150,6 +156,20 @@ export interface ModerationProfile extends ModerationProfileBase {
150
156
  * hub edits this section; the code-side AI option sets the adapter and the highest level it may reach. See {@link AISettings}.
151
157
  */
152
158
  ai?: Partial<AISettings>;
159
+ /**
160
+ * How a room paces a player's lines: a least gap between them (`slowModeMs`), a burst limit (`burst`) and no repeats
161
+ * (`duplicateWindowMs`). Every setting is off until set, so a profile without `pace` changes nothing. See {@link PaceSettings}.
162
+ * @experimental
163
+ */
164
+ pace?: PaceSettings;
165
+ /**
166
+ * Signals: what the game records about a player (muted by others, kicked, left mid-game). `kinds` and `guards` are declared in code
167
+ * only; `feeds` says where counts may be read (the Person page record, the ladder suggestion, the AI read's context, the queue
168
+ * boost) and is editable in the hub. Nothing is unset-only: a profile without `signals` declares no kinds and has no feeds. A signal
169
+ * never acts. See {@link SignalSettings}.
170
+ * @experimental
171
+ */
172
+ signals?: SignalSettings;
153
173
  }
154
174
 
155
175
  /**
@@ -193,6 +213,10 @@ export interface ResolvedProfile extends ModerationProfileBase {
193
213
  reporting: ResolvedReporting;
194
214
  /** The AI settings in force, every field filled in. */
195
215
  ai: AISettings;
216
+ /** The pace settings in force, every field filled in (`null` is off). @experimental */
217
+ pace: ResolvedPace;
218
+ /** The signal settings in force: the declared kinds merged over the built-ins, the guards filled in, the feeds as given. @experimental */
219
+ signals: ResolvedSignals;
196
220
  }
197
221
 
198
222
  /** @deprecated The same as {@link ModerationProfile}, which now has the two fields optional. */
@@ -208,18 +232,7 @@ export type DeepPartial<T> = T extends readonly unknown[]
208
232
  /** Overrides for {@link resolveProfile}. Any field; arrays replace the preset's array whole. */
209
233
  export type ProfileOverrides = DeepPartial<ModerationProfile>;
210
234
 
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
- }
235
+ export { ProfileError };
223
236
 
224
237
  // ---------------------------------------------------------------------------------------------------------------
225
238
  // Validation
@@ -241,12 +254,14 @@ const TOP_KEYS = [
241
254
  'customDuration',
242
255
  'reporting',
243
256
  'ai',
257
+ 'pace',
258
+ 'signals',
244
259
  'levels',
245
260
  'guidelines',
246
261
  ] as const;
247
262
  /** Top-level keys that may be left out (the kit falls back to its defaults). */
248
263
  const RULE_LIST_KEYS: readonly string[] = ['areaRules', 'severeRules'];
249
- const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai'];
264
+ const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai', 'pace', 'signals'];
250
265
  const AI_KEYS = ['level', 'learn', 'dailyCalls'] as const;
251
266
  /** The most rule numbers `areaRules` or `severeRules` may list. */
252
267
  export const MAX_RULE_LIST = 100;
@@ -526,6 +541,8 @@ export function validateProfile(value: unknown): asserts value is ModerationProf
526
541
  if (Object.hasOwn(p, 'customDuration') && typeof p['customDuration'] !== 'boolean') fail('profile.customDuration', 'must be true or false');
527
542
  if (Object.hasOwn(p, 'reporting')) validateReporting(p['reporting'], 'profile.reporting');
528
543
  if (Object.hasOwn(p, 'ai')) validateAI(p['ai'], 'profile.ai');
544
+ if (Object.hasOwn(p, 'pace')) resolvePace(p['pace'] as PaceSettings, 'profile.pace');
545
+ if (Object.hasOwn(p, 'signals')) resolveSignals(p['signals'] as SignalSettings, 'profile.signals');
529
546
 
530
547
  const prof = obj(p['profanity'], 'profile.profanity', PROFANITY_KEYS);
531
548
  oneOf(prof['mode'], 'profile.profanity.mode', PROFANITY_MODES, "must be 'allow', 'star' or 'refuse'");
@@ -587,14 +604,6 @@ function merge(base: unknown, over: unknown, depth = 0): unknown {
587
604
  return clone(over, depth);
588
605
  }
589
606
 
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
607
  /** Drop repeated numbers from `areaRules` and `severeRules` (first one wins, order kept) before they are validated. */
599
608
  function dedupeRuleLists(copy: unknown): void {
600
609
  if (!isPlain(copy)) return;
@@ -644,6 +653,11 @@ function finalize(value: unknown): ResolvedProfile {
644
653
  dedupeRuleLists(copy);
645
654
  fillDefaults(copy);
646
655
  validateProfile(copy);
656
+ // Checked above, so this cannot throw: every pace field is filled in, `null` meaning off.
657
+ if (isPlain(copy)) {
658
+ setOwn(copy, 'pace', resolvePace(copy['pace'] as PaceSettings | undefined, 'profile.pace'));
659
+ setOwn(copy, 'signals', resolveSignals(copy['signals'] as SignalSettings | undefined, 'profile.signals'));
660
+ }
647
661
  return deepFreeze(copy as ResolvedProfile);
648
662
  }
649
663
 
@@ -658,6 +672,8 @@ export function withDurationDefaults(p: ModerationProfile): ResolvedProfile {
658
672
  customDuration: p.customDuration ?? true,
659
673
  reporting: resolveReporting(p.reporting),
660
674
  ai: { level: 0, learn: true, dailyCalls: AI_DAILY_CALLS_DEFAULT, ...p.ai },
675
+ pace: resolvePace(p.pace),
676
+ signals: resolveSignals(p.signals),
661
677
  };
662
678
  }
663
679
 
@@ -978,7 +994,7 @@ export function defineProfile(p: ModerationProfile): ResolvedProfile {
978
994
  * The parts of a profile the hub may edit, and the order they are listed in. Everything else (identity, the written
979
995
  * levels, the AI context, profanity handling) stays in code: changing profanity means rebuilding the filter.
980
996
  */
981
- export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai'] as const;
997
+ export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai', 'pace', 'signals'] as const;
982
998
  export type PolicySection = (typeof POLICY_SECTIONS)[number];
983
999
 
984
1000
  /** One ladder cell as the editor sends it: the label may be left out and is then generated ("Restrict chat 6 hours"). */
@@ -1014,6 +1030,16 @@ export interface PolicyLayer {
1014
1030
  reporting?: ReportingSettings;
1015
1031
  /** 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
1032
  ai?: Partial<AISettings>;
1033
+ /**
1034
+ * 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
1035
+ * it); `burst` replaces whole. @experimental
1036
+ */
1037
+ pace?: PaceSettings;
1038
+ /**
1039
+ * The signal feeds: only `feeds` may be edited (the kinds and the guards are declared in code). The layer's `feeds` REPLACE the
1040
+ * profile's wholesale, like every other section: a feed left out is off. A feed names declared kinds only. @experimental
1041
+ */
1042
+ signals?: { feeds?: SignalFeeds };
1017
1043
  }
1018
1044
 
1019
1045
  /** The longest outcome text a layer may set on a guideline tier. */
@@ -1061,6 +1087,28 @@ function wholeOutcome(v: unknown, path: string): void {
1061
1087
  if (!Object.hasOwn(v, 'durationMs')) fail(`${path}.durationMs`, 'is required');
1062
1088
  }
1063
1089
 
1090
+ /**
1091
+ * A layer's `signals` may hold only `feeds`, and every feed must name kinds the profile declares. The feeds themselves are not put in
1092
+ * the overrides: they replace the profile's wholesale, which the deep merge would not do, so `applyPolicyLayer` sets them after it.
1093
+ */
1094
+ function layerSignals(base: ModerationProfile, value: unknown): void {
1095
+ if (!isPlain(value)) return fail('profile.signals', 'must be an object');
1096
+ for (const k of Object.keys(value)) {
1097
+ if (k !== 'feeds') fail(`profile.signals.${k}`, 'is not an editable setting: kinds and guards are declared in code');
1098
+ }
1099
+ const feeds = Object.hasOwn(value, 'feeds') ? value['feeds'] : undefined;
1100
+ checkSignalFeeds(feeds as SignalFeeds | undefined, resolveSignals(base.signals, 'profile.signals').kinds, { signalsMs: Infinity }, 'profile.signals.feeds');
1101
+ }
1102
+
1103
+ /** Put the layer's signal feeds in place of the merged profile's (a feed the layer leaves out is off). */
1104
+ function replaceSignalFeeds(merged: unknown, layer: unknown): void {
1105
+ if (!isPlain(merged) || !isPlain(layer) || !Object.hasOwn(layer, 'signals') || !isPlain(layer['signals'])) return;
1106
+ const feeds = Object.hasOwn(layer['signals'], 'feeds') ? layer['signals']['feeds'] : undefined;
1107
+ const section = isPlain(merged['signals']) ? merged['signals'] : {};
1108
+ setOwn(section, 'feeds', feeds === undefined ? {} : clone(feeds));
1109
+ setOwn(merged, 'signals', section);
1110
+ }
1111
+
1064
1112
  function layerToOverrides(base: ModerationProfile, layer: unknown): Record<string, unknown> {
1065
1113
  if (!isPlain(layer)) return fail('profile', 'must be an object');
1066
1114
  for (const key of Object.keys(layer)) {
@@ -1074,7 +1122,15 @@ function layerToOverrides(base: ModerationProfile, layer: unknown): Record<strin
1074
1122
  for (const level of Object.keys(value)) wholeOutcome(value[level], `profile.firstOffense.${level}`);
1075
1123
  }
1076
1124
  if (key === 'repeat' && isPlain(value)) wholeOutcome(value['outcome'], 'profile.repeat.outcome');
1077
- if (key === 'ladder') setOwn(out, key, ladderOverride(value));
1125
+ if (key === 'signals') {
1126
+ layerSignals(base, value);
1127
+ continue;
1128
+ }
1129
+ if (key === 'pace') {
1130
+ // Checked on its own so the error names layer.pace..., then merged here so `burst` replaces whole instead of merging by member.
1131
+ resolvePace(value as PaceSettings, 'profile.pace');
1132
+ setOwn(out, key, mergePace(resolvePace(base.pace, 'profile.pace'), value as PaceSettings));
1133
+ } else if (key === 'ladder') setOwn(out, key, ladderOverride(value));
1078
1134
  else if (key === 'guidelines') setOwn(out, key, guidelinesOverride(base, value));
1079
1135
  else setOwn(out, key, value);
1080
1136
  }
@@ -1084,7 +1140,7 @@ function layerToOverrides(base: ModerationProfile, layer: unknown): Record<strin
1084
1140
  /** The same error, with the path named from the layer the editor sent (`profile.ladder[2]` is `layer.ladder[2]`). */
1085
1141
  function inLayerTerms(err: ProfileError): ProfileError {
1086
1142
  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);
1143
+ return new ProfileError(path, err.reason, err.code);
1088
1144
  }
1089
1145
 
1090
1146
  /**
@@ -1095,7 +1151,9 @@ function inLayerTerms(err: ProfileError): ProfileError {
1095
1151
  */
1096
1152
  export function applyPolicyLayer(base: ModerationProfile, layer: PolicyLayer): ResolvedProfile {
1097
1153
  try {
1098
- return finalize(merge(base, layerToOverrides(base, layer)));
1154
+ const merged = merge(base, layerToOverrides(base, layer));
1155
+ replaceSignalFeeds(merged, layer);
1156
+ return finalize(merged);
1099
1157
  } catch (err) {
1100
1158
  throw err instanceof ProfileError ? inLayerTerms(err) : err;
1101
1159
  }
@@ -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,11 @@ 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;
38
43
  }
39
44
 
40
45
  export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
@@ -46,12 +51,13 @@ export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
46
51
  auditMs: 365 * DAY_MS,
47
52
  aiOutcomesMs: 365 * DAY_MS,
48
53
  aiExamplesMs: 180 * DAY_MS,
54
+ signalsMs: 90 * DAY_MS,
49
55
  };
50
56
 
51
57
  /** The ladder looks back 90 days and "My record" shows 90 days, so the rows behind them must outlive that. */
52
58
  const RECORD_FLOOR_MS = 90 * DAY_MS;
53
59
 
54
- const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs'] as const;
60
+ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs', 'signalsMs'] as const;
55
61
 
56
62
  /**
57
63
  * Refuse a retention policy that would delete rows the kit still reads. Only the fields present are checked (an
@@ -62,6 +68,7 @@ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'ba
62
68
  * - `auditMs` at least 90 days: the staff trail is how a community answers "who did that"
63
69
  * - `aiOutcomesMs` at least 90 days: the agree-or-override record is the data the AI's later gates read
64
70
  * - `aiExamplesMs` at least 0 (0 keeps no example text at all)
71
+ * - `signalsMs` at least 14 days: a counting window needs at least two weeks of rows
65
72
  *
66
73
  * Every field present must also be a finite number (`reportsMs` and `strikesMs` have no floor, only this).
67
74
  *
@@ -96,6 +103,9 @@ export function checkRetentionFloors(policy: Partial<RetentionPolicy>, suspendWi
96
103
  if (below(policy.aiExamplesMs, 0)) {
97
104
  throw new ProfileError('retention.aiExamplesMs', 'must be 0 or more: 0 keeps no example text at all');
98
105
  }
106
+ if (below(policy.signalsMs, 14 * DAY_MS)) {
107
+ throw new ProfileError('retention.signalsMs', 'must be at least 14 days: a counting window needs at least two weeks of rows');
108
+ }
99
109
  if (below(policy.badFaithMs, suspendWindowMs)) {
100
110
  throw new ProfileError(
101
111
  'retention.badFaithMs',
@@ -118,6 +128,8 @@ export interface PurgeResult {
118
128
  aiReads: number;
119
129
  /** AI casebook outcomes deleted. 0 for a store without the AI methods. */
120
130
  aiOutcomes: number;
131
+ /** Signal rows deleted (flood_triggered included). 0 for a store without the signal methods. */
132
+ signals: number;
121
133
  }
122
134
 
123
135
  function checkWindow(name: string, ms: number): void {
@@ -141,6 +153,7 @@ function checkWindow(name: string, ms: number): void {
141
153
  * - AI reads: `createdAt < now - reportsMs` (a read also goes with its report, in `purgeReports`); AI outcomes (agree-or-override
142
154
  * record, no chat text): `decidedAt < now - aiOutcomesMs`; the pseudonymised example kept with an outcome:
143
155
  * `decidedAt < now - aiExamplesMs`, the row stays with its counts. A store without the AI methods has none of these.
156
+ * - signals: `at < now - signalsMs` (90 days by default, never less than 14); a store without the signal methods has none
144
157
  * - notices: withdrawn, or a seen warning / report outcome, with `createdAt < now - noticesMs`; or
145
158
  * `until < now - noticesMs`. A notice for a permanent or running sanction is kept while it applies (agrees with
146
159
  * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn.
@@ -162,6 +175,7 @@ export async function purge(
162
175
  auditMs: policy.auditMs ?? RETENTION_DEFAULTS.auditMs,
163
176
  aiOutcomesMs: policy.aiOutcomesMs ?? RETENTION_DEFAULTS.aiOutcomesMs,
164
177
  aiExamplesMs: policy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
178
+ signalsMs: policy.signalsMs ?? RETENTION_DEFAULTS.signalsMs,
165
179
  };
166
180
  if (!Number.isFinite(now)) throw new Error('purge: invalid now');
167
181
  checkWindow('reportsMs', p.reportsMs);
@@ -172,6 +186,7 @@ export async function purge(
172
186
  checkWindow('auditMs', p.auditMs);
173
187
  checkWindow('aiOutcomesMs', p.aiOutcomesMs);
174
188
  checkWindow('aiExamplesMs', p.aiExamplesMs);
189
+ checkWindow('signalsMs', p.signalsMs);
175
190
  return store.transaction(() => {
176
191
  const reports = store.purgeReports(now - p.reportsMs, now - p.badFaithMs);
177
192
  const ai = store.purgeAi?.(now - p.reportsMs, now - p.aiOutcomesMs, now - p.aiExamplesMs) ?? { reads: 0, outcomes: 0 };
@@ -185,6 +200,7 @@ export async function purge(
185
200
  webhookKeys: store.purgeWebhookKeys(now - WEBHOOK_KEY_TTL_MS),
186
201
  aiReads: ai.reads,
187
202
  aiOutcomes: ai.outcomes,
203
+ signals: store.purgeSignals?.(now - p.signalsMs) ?? 0,
188
204
  };
189
205
  });
190
206
  }
@@ -0,0 +1,133 @@
1
+ import type { SignalCount, SignalPolarity, SignalThreshold } from './signals.js';
2
+ import type { SignalSourceRow, SubjectId } from './types.js';
3
+
4
+ // Counting signals by distinct source (design 5.3). Pure: it takes the grouped rows the store answered (`listSignalSources`) and counts
5
+ // them. A "count" is how many different sources said it, never how many times: a thousand mutes from one player are one source.
6
+
7
+ /** What counting needs to know. `kinds` is the request: only these kinds are counted, and only if they are own keys. */
8
+ export interface CountContext {
9
+ kinds: Readonly<Record<string, { label: string; polarity: SignalPolarity }>>;
10
+ /** Folds a merged subject into the person it became (`SubjectIndex.canonical`). */
11
+ canonical: (subject: SubjectId) => SubjectId;
12
+ /** The window the rows were read for, reported on each count. */
13
+ windowDays: number;
14
+ }
15
+
16
+ /** What one threshold evaluation answers. `firstAt` and `lastAt` are null when no source counted. */
17
+ export interface ThresholdResult {
18
+ met: boolean;
19
+ distinct: number;
20
+ weight: number;
21
+ firstAt: number | null;
22
+ lastAt: number | null;
23
+ }
24
+
25
+ interface Counted {
26
+ distinct: number;
27
+ weight: number;
28
+ firstAt: number;
29
+ lastAt: number;
30
+ }
31
+
32
+ /**
33
+ * The source of a row, with a player folded through `canonical` so two aliases of one person are one source: `b:<canonical by>` when
34
+ * the row has a `by` (the row's `bySubject`, or the id inside the key when the row has none), and the key as stored for a room
35
+ * (`r:`) or a day (`d:`).
36
+ */
37
+ function sourceOf(row: SignalSourceRow, canonical: (s: SubjectId) => SubjectId): string {
38
+ if (!row.sourceKey.startsWith('b:')) return row.sourceKey;
39
+ const by = row.bySubject ?? row.sourceKey.slice(2);
40
+ return `b:${canonical(by)}`;
41
+ }
42
+
43
+ /**
44
+ * Count one kind: group by source, take the highest weight in a source, drop sources whose weight is not above 0, then the number of
45
+ * sources left and the sum of their weights. The times span the sources that counted.
46
+ */
47
+ function countKind(rows: readonly SignalSourceRow[], canonical: (s: SubjectId) => SubjectId): Counted | null {
48
+ const sources = new Map<string, Counted>();
49
+ for (const row of rows) {
50
+ const w = row.weight;
51
+ if (!(typeof w === 'number' && w > 0 && Number.isFinite(w))) continue;
52
+ const key = sourceOf(row, canonical);
53
+ // A source that is the subject itself (an alt account linked to the main one after it signalled) is not a second opinion.
54
+ if (key === `b:${canonical(row.subject)}`) continue;
55
+ const s = sources.get(key);
56
+ if (s === undefined) sources.set(key, { distinct: 1, weight: w, firstAt: row.firstAt, lastAt: row.lastAt });
57
+ else {
58
+ if (w > s.weight) s.weight = w;
59
+ if (row.firstAt < s.firstAt) s.firstAt = row.firstAt;
60
+ if (row.lastAt > s.lastAt) s.lastAt = row.lastAt;
61
+ }
62
+ }
63
+ if (sources.size === 0) return null;
64
+ let weight = 0;
65
+ let firstAt = Infinity;
66
+ let lastAt = -Infinity;
67
+ for (const s of sources.values()) {
68
+ weight += s.weight;
69
+ if (s.firstAt < firstAt) firstAt = s.firstAt;
70
+ if (s.lastAt > lastAt) lastAt = s.lastAt;
71
+ }
72
+ return { distinct: sources.size, weight: round(weight), firstAt, lastAt };
73
+ }
74
+
75
+ /** Weights are floats: ten sources of 0.1 sum to 0.9999999999999999. Sums are rounded to 6 places and compared with a tolerance of 1e-9. */
76
+ const round = (n: number): number => Math.round(n * 1e6) / 1e6;
77
+
78
+ /** Rows by kind, for the kinds in the request only (own keys: a row of an undeclared or prototype-named kind is ignored). */
79
+ function byKind(rows: readonly SignalSourceRow[], kinds: CountContext['kinds'], only?: readonly string[]): Map<string, SignalSourceRow[]> {
80
+ const out = new Map<string, SignalSourceRow[]>();
81
+ for (const row of rows) {
82
+ if (!Object.hasOwn(kinds, row.kind) || (only !== undefined && !only.includes(row.kind))) continue;
83
+ const list = out.get(row.kind);
84
+ if (list === undefined) out.set(row.kind, [row]);
85
+ else list.push(row);
86
+ }
87
+ return out;
88
+ }
89
+
90
+ /**
91
+ * The counts for a person: one entry per requested kind that has at least one counted source, in the order of the request. `rows` are
92
+ * the store's grouped rows for the person and all their aliases, already limited to the window; aliases fold here. For staff tooling
93
+ * and your own game: never send the result to a player.
94
+ */
95
+ export function countSignals(rows: readonly SignalSourceRow[], ctx: CountContext): SignalCount[] {
96
+ const grouped = byKind(rows, ctx.kinds);
97
+ const out: SignalCount[] = [];
98
+ for (const kind of Object.keys(ctx.kinds)) {
99
+ const list = grouped.get(kind);
100
+ if (list === undefined) continue;
101
+ const counted = countKind(list, ctx.canonical);
102
+ if (counted === null) continue;
103
+ const spec = ctx.kinds[kind]!;
104
+ out.push({ kind, label: spec.label, polarity: spec.polarity, windowDays: ctx.windowDays, ...counted });
105
+ }
106
+ return out;
107
+ }
108
+
109
+ /**
110
+ * Does a person meet a threshold? Sources are counted per kind and the numbers added across the kinds, so one player who both muted and
111
+ * blocked counts twice for a two-kind threshold (use one kind per threshold when that matters). Met when `distinct >= minDistinct` and,
112
+ * if `minWeight` is given, `weight >= minWeight`. A kind that is not in `ctx.kinds` is ignored. The window is the caller's: `rows` are
113
+ * already limited to `t.windowDays`.
114
+ */
115
+ export function evaluateThreshold(rows: readonly SignalSourceRow[], ctx: Omit<CountContext, 'windowDays'> & { windowDays?: number }, t: SignalThreshold): ThresholdResult {
116
+ const grouped = byKind(rows, ctx.kinds, t.kinds);
117
+ let distinct = 0;
118
+ let weight = 0;
119
+ let firstAt: number | null = null;
120
+ let lastAt: number | null = null;
121
+ for (const kind of t.kinds) {
122
+ const list = grouped.get(kind);
123
+ if (list === undefined) continue;
124
+ const counted = countKind(list, ctx.canonical);
125
+ if (counted === null) continue;
126
+ distinct += counted.distinct;
127
+ weight = round(weight + counted.weight);
128
+ if (firstAt === null || counted.firstAt < firstAt) firstAt = counted.firstAt;
129
+ if (lastAt === null || counted.lastAt > lastAt) lastAt = counted.lastAt;
130
+ }
131
+ const met = distinct >= t.minDistinct && (t.minWeight === undefined || weight >= t.minWeight - 1e-9);
132
+ return { met, distinct, weight, firstAt, lastAt };
133
+ }