@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/pacing.ts ADDED
@@ -0,0 +1,242 @@
1
+ import { sha256Hex } from './crypto.js';
2
+ import { DUPLICATE_MIN_CHARS, DUPLICATE_RECENT, PACE_KEYS_MAX } from './pace.js';
3
+ import type { PaceReason, ResolvedPace } from './pace.js';
4
+ import type { Clock } from './types.js';
5
+
6
+ // The pacer: the in-memory limiter behind slow mode, the burst limit and repeat refusal. Pure and clocked: it reads the settings
7
+ // through a function on every call, holds no line text (a repeat is remembered as a short digest of the normalized line), and its
8
+ // `check` is timing-pure: a refusal changes nothing the next check reads. The one write `check` makes is the `floodSignalAt`
9
+ // bookkeeping, set when it returns `signalFlood: true`, so a flood is reported at most once per burst window.
10
+ //
11
+ // State is per process, a map of maps by room (so a room goes in one delete), swept every SWEEP_EVERY checks against the longest
12
+ // window the room has configured, and capped at PACE_KEYS_MAX keys (the oldest go).
13
+
14
+ /** Sweep quiet keys after this many `check` calls (the same cadence as `slidingWindow`). */
15
+ const SWEEP_EVERY = 256;
16
+ /** When the cap is hit, this many of the oldest keys go at once, so the scan is paid for once per batch and not once per new key. */
17
+ const EVICT_BATCH = Math.ceil(PACE_KEYS_MAX / 8);
18
+ /** Hex characters of the digest kept for a repeat: enough that two different lines do not meet, far too few to recover a line. */
19
+ const DIGEST_CHARS = 16;
20
+
21
+ /** Who a line is paced as: the room, and the canonical subject (or `seat:<seatId>` for a guest). */
22
+ export interface PaceKey {
23
+ roomId: string;
24
+ who: string;
25
+ }
26
+
27
+ /** The answer to one line. `retryAfterMs` is a whole number from 1 up to the window of the check that refused. */
28
+ export type PaceVerdict = { ok: true } | { ok: false; reason: PaceReason; retryAfterMs: number; signalFlood: boolean };
29
+
30
+ export interface Pacer {
31
+ /** Should this line be refused? Reads state, changes no timing state. Order: `slow_mode`, `flood`, `duplicate`. */
32
+ check(key: PaceKey, line: string): PaceVerdict;
33
+ /** Record that a line was accepted: it now counts toward the next check. A no-op while every check is off. */
34
+ commit(key: PaceKey, line: string): void;
35
+ /** Is any check on for this room right now? When not, `check` and `commit` do nothing and the caller need not build a key. */
36
+ active(roomId: string): boolean;
37
+ /** The line `check` accepted will not be committed (the fixed rate refused it): drop the digest memo that holds its text. */
38
+ discard(): void;
39
+ /** Is a line's text held in the digest memo (between a `check` that passed and its `commit` or `discard`)? A diagnostic. */
40
+ holdsText(): boolean;
41
+ /** Forget every key of a room in one step. */
42
+ dropRoom(roomId: string): void;
43
+ /** Keys held. A diagnostic: it stays at or under {@link PACE_KEYS_MAX}. */
44
+ size(): number;
45
+ }
46
+
47
+ /** What the pacer keeps for one player in one room. @internal */
48
+ export interface KeyState {
49
+ /** When the last committed line was accepted. */
50
+ lastAt: number;
51
+ /** The times of the last committed lines, oldest first (at most the burst's `lines`). */
52
+ stamps: number[];
53
+ /** Digests of the last {@link DUPLICATE_RECENT} committed lines of enough length, oldest first. */
54
+ recent: Array<{ h: string; at: number }>;
55
+ /** When `check` last reported a flood for this key, or null. */
56
+ floodSignalAt: number | null;
57
+ }
58
+
59
+ /**
60
+ * NFKC, lower-case, then only letters, digits and the combining marks that belong to them: what "the same line again" means. Marks stay
61
+ * because in many scripts (Devanagari, Thai) the vowel signs are marks, and without them different words look alike. Variation
62
+ * selectors (U+FE00 to U+FE0F, which pick text or emoji presentation) are marks too but carry no meaning of their own, so they go
63
+ * first: `1\uFE0F\u20E3` and `1\u20E3` are one line, and an emoji line leaves nothing to count. Never stored.
64
+ */
65
+ export function normalizeForRepeat(text: string): string {
66
+ return text.normalize('NFKC').toLowerCase().replace(/[\uFE00-\uFE0F]/g, '').replace(/[^\p{L}\p{N}\p{M}]/gu, '');
67
+ }
68
+
69
+ /** Letters and digits in a normalized line: marks do not count toward the minimum length, so a line of marks alone is never a repeat. */
70
+ const baseChars = (normalized: string): number => Array.from(normalized.replace(/\p{M}/gu, '')).length;
71
+
72
+ const OK: PaceVerdict = Object.freeze({ ok: true }) as PaceVerdict;
73
+
74
+ const allOff = (p: ResolvedPace): boolean => p.slowModeMs === null && p.burst === null && p.duplicateWindowMs === null;
75
+
76
+ /** A refusal with a whole-number wait of at least 1 and at most the refusing check's own window (a clock that stepped back cannot exceed it). */
77
+ function refusal(reason: PaceReason, waitMs: number, windowMs: number, signalFlood: boolean): PaceVerdict {
78
+ const wait = Number.isFinite(waitMs) ? Math.min(windowMs, Math.max(1, Math.ceil(waitMs))) : windowMs;
79
+ return { ok: false, reason, retryAfterMs: wait, signalFlood };
80
+ }
81
+
82
+ /** The longest window a room has configured, or 0 when every check is off. */
83
+ function longestWindow(p: ResolvedPace): number {
84
+ return Math.max(p.slowModeMs ?? 0, p.burst?.windowMs ?? 0, p.duplicateWindowMs ?? 0);
85
+ }
86
+
87
+ const touchedAt = (s: KeyState): number => (s.floodSignalAt !== null && s.floodSignalAt > s.lastAt ? s.floodSignalAt : s.lastAt);
88
+
89
+ /**
90
+ * `tap` is a test seam: it is handed the state (rooms by key) once, so a test can look at what a pacer holds. Nothing in the kit passes it.
91
+ * @internal
92
+ */
93
+ export function createPacer(opts: { clock: Clock; settings: (roomId: string) => ResolvedPace; tap?: (rooms: ReadonlyMap<string, ReadonlyMap<string, Readonly<KeyState>>>) => void }): Pacer {
94
+ const { clock, settings } = opts;
95
+ const rooms = new Map<string, Map<string, KeyState>>();
96
+ opts.tap?.(rooms);
97
+ let keys = 0;
98
+ let calls = 0;
99
+
100
+ const sweep = (now: number): void => {
101
+ for (const [roomId, room] of rooms) {
102
+ let longest: number;
103
+ try {
104
+ longest = longestWindow(settings(roomId));
105
+ } catch {
106
+ continue;
107
+ }
108
+ if (longest === 0) {
109
+ keys -= room.size;
110
+ rooms.delete(roomId);
111
+ continue;
112
+ }
113
+ for (const [who, state] of room) {
114
+ if (now - touchedAt(state) >= longest) {
115
+ room.delete(who);
116
+ keys -= 1;
117
+ }
118
+ }
119
+ if (room.size === 0) rooms.delete(roomId);
120
+ }
121
+ };
122
+
123
+ /** Over the cap: drop the oldest keys, a batch at a time. */
124
+ const evict = (): void => {
125
+ const all: Array<{ roomId: string; who: string; at: number }> = [];
126
+ for (const [roomId, room] of rooms) for (const [who, state] of room) all.push({ roomId, who, at: touchedAt(state) });
127
+ all.sort((a, b) => a.at - b.at);
128
+ const drop = Math.min(all.length, keys - PACE_KEYS_MAX + EVICT_BATCH);
129
+ for (let i = 0; i < drop; i += 1) {
130
+ const { roomId, who } = all[i]!;
131
+ const room = rooms.get(roomId);
132
+ if (room?.delete(who) === true) keys -= 1;
133
+ if (room !== undefined && room.size === 0) rooms.delete(roomId);
134
+ }
135
+ };
136
+
137
+ const digest = (normalized: string): string => sha256Hex(normalized).slice(0, DIGEST_CHARS);
138
+ /**
139
+ * The digest `check` made of the line it just accepted, so `commit` of the same line does not hash it again. It holds that one line
140
+ * only from the check to the commit that follows it in the same call (and is replaced or cleared by the next call): the keyed state
141
+ * below never holds text.
142
+ */
143
+ let memo: { line: string; h: string | null } | null = null;
144
+ /** A normalized line long enough to be called a repeat, as its digest; null for one that is not. */
145
+ const repeatHash = (line: string): string | null => {
146
+ if (memo !== null && memo.line === line) return memo.h;
147
+ const normalized = normalizeForRepeat(line);
148
+ return baseChars(normalized) < DUPLICATE_MIN_CHARS ? null : digest(normalized);
149
+ };
150
+
151
+ const pacer: Pacer = {
152
+ active: (roomId) => !allOff(settings(roomId)),
153
+
154
+ check(key, line) {
155
+ const now = clock.now();
156
+ memo = null;
157
+ if (++calls % SWEEP_EVERY === 0) sweep(now);
158
+ const pace = settings(key.roomId);
159
+ if (allOff(pace)) return OK;
160
+ const state = rooms.get(key.roomId)?.get(key.who);
161
+ if (state === undefined) return OK;
162
+
163
+ const { slowModeMs, burst, duplicateWindowMs } = pace;
164
+ // State stamped after `now` (the clock stepped back) is stale, not "in the future": it never refuses, so a step back cannot lock
165
+ // a player out. The refusal clamp below is then a guard only.
166
+ if (slowModeMs !== null && state.lastAt <= now && now - state.lastAt < slowModeMs) {
167
+ return refusal('slow_mode', state.lastAt + slowModeMs - now, slowModeMs, false);
168
+ }
169
+
170
+ if (burst !== null) {
171
+ const live = state.stamps.filter((t) => t <= now && now - t < burst.windowMs).sort((a, b) => a - b);
172
+ if (live.length >= burst.lines) {
173
+ // Enough must age out to leave room for one more: with exactly `lines` live that is the oldest, with more (a burst
174
+ // narrowed after the lines were sent) it is the one that leaves `lines - 1`.
175
+ const oldest = live[live.length - burst.lines]!;
176
+ const signal = state.floodSignalAt === null || now < state.floodSignalAt || now - state.floodSignalAt >= burst.windowMs;
177
+ if (signal) state.floodSignalAt = now;
178
+ return refusal('flood', oldest + burst.windowMs - now, burst.windowMs, signal);
179
+ }
180
+ }
181
+
182
+ if (duplicateWindowMs !== null && state.recent.length > 0) {
183
+ const h = repeatHash(line);
184
+ if (h !== null) {
185
+ const seen = state.recent.find((e) => e.h === h && e.at <= now && now - e.at < duplicateWindowMs);
186
+ if (seen !== undefined) return refusal('duplicate', seen.at + duplicateWindowMs - now, duplicateWindowMs, false);
187
+ memo = { line, h };
188
+ } else memo = { line, h: null };
189
+ }
190
+ return OK;
191
+ },
192
+
193
+ commit(key, line) {
194
+ const now = clock.now();
195
+ const pace = settings(key.roomId);
196
+ if (allOff(pace)) return;
197
+ let room = rooms.get(key.roomId);
198
+ let state = room?.get(key.who);
199
+ if (state === undefined) {
200
+ if (keys >= PACE_KEYS_MAX) evict();
201
+ if (room === undefined || !rooms.has(key.roomId)) {
202
+ room = new Map();
203
+ rooms.set(key.roomId, room);
204
+ }
205
+ state = { lastAt: now, stamps: [], recent: [], floodSignalAt: null };
206
+ room.set(key.who, state);
207
+ keys += 1;
208
+ }
209
+ state.lastAt = now;
210
+
211
+ const { burst, duplicateWindowMs } = pace;
212
+ if (burst === null) state.stamps = [];
213
+ else state.stamps = [...state.stamps.filter((t) => t <= now && now - t < burst.windowMs), now].slice(-burst.lines);
214
+
215
+ if (duplicateWindowMs === null) state.recent = [];
216
+ else {
217
+ const h = repeatHash(line);
218
+ const kept = state.recent.filter((e) => e.h !== h && e.at <= now && now - e.at < duplicateWindowMs);
219
+ if (h !== null) kept.push({ h, at: now });
220
+ state.recent = kept.slice(-DUPLICATE_RECENT);
221
+ }
222
+ memo = null;
223
+ },
224
+
225
+ discard() {
226
+ memo = null;
227
+ },
228
+
229
+ holdsText: () => memo !== null,
230
+
231
+ dropRoom(roomId) {
232
+ const room = rooms.get(roomId);
233
+ if (room === undefined) return;
234
+ keys -= room.size;
235
+ rooms.delete(roomId);
236
+ },
237
+
238
+ size: () => keys,
239
+ };
240
+
241
+ return pacer;
242
+ }
package/src/policy.ts CHANGED
@@ -6,7 +6,11 @@ import type { PolicyLayer, PolicySection, ResolvedProfile } from './profile.js';
6
6
  import { playerReporting } from './reporting.js';
7
7
  import type { PlayerReporting } from './reporting.js';
8
8
  import type { RuleRef } from './rules.js';
9
- import { errorClass, safeWarn } from './log.js';
9
+ import { errorClass, safeWarn, ThrottledWarn } 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,23 @@ 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
+ /** Whether the store has the appeal methods. Without them a layer cannot turn appeals on: it is refused when saved, and kept off when read. */
145
+ private readonly appealsKept: boolean;
146
+ private readonly appealsWarn: ThrottledWarn;
147
+
148
+ constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile; signalsMs?: () => number; chatRate?: { count: number; windowMs: number }; appealsKept?: boolean }) {
149
+ this.appealsKept = deps.appealsKept ?? true;
150
+ this.appealsWarn = new ThrottledWarn(deps.logger, deps.clock);
151
+ this.signalsMs = deps.signalsMs ?? (() => RETENTION_DEFAULTS.signalsMs);
152
+ this.chatRate = Object.freeze({ count: deps.chatRate?.count ?? RATE_LIMIT, windowMs: deps.chatRate?.windowMs ?? RATE_WINDOW_MS });
99
153
  this.store = deps.store;
100
154
  this.clock = deps.clock;
101
155
  this.logger = deps.logger;
@@ -114,6 +168,16 @@ export class PolicyService {
114
168
  this.adopt(this.store.loadPolicyLayer?.() ?? null);
115
169
  }
116
170
 
171
+ /**
172
+ * The profile as the store can serve it: a layer that turned appeals on over a store without the appeal methods leaves them off
173
+ * (a code profile that asked for them is refused at creation, never here). Warned by class only, throttled.
174
+ */
175
+ private served(effective: ResolvedProfile): ResolvedProfile {
176
+ if (this.appealsKept || !effective.appeals.enabled || this.base.appeals.enabled) return effective;
177
+ this.appealsWarn.warn('chatwarden.appeals_unsupported_store', {});
178
+ return Object.freeze({ ...effective, appeals: Object.freeze({ ...effective.appeals, enabled: false }) });
179
+ }
180
+
117
181
  /** Make `stored` the layer in force: the effective profile is rebuilt, or the base kept when the layer cannot be used. */
118
182
  private adopt(stored: { layer: PolicyLayer; version: number } | null): void {
119
183
  const version = stored?.version ?? 0;
@@ -121,7 +185,10 @@ export class PolicyService {
121
185
  const raw: unknown = stored === null ? {} : stored.layer;
122
186
  const layer = frozenCopy(raw as PolicyLayer);
123
187
  try {
124
- this.state = { effective: applyPolicyLayer(this.base, layer), layer, version };
188
+ // 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.
189
+ const { layer: inForce, dropped } = this.withoutStaleFeeds(layer);
190
+ const shown = dropped.length === 0 ? layer : frozenCopy(inForce);
191
+ this.state = { effective: this.served(applyPolicyLayer(this.base, shown)), layer: shown, version, ...(dropped.length === 0 ? {} : { dropped: Object.freeze(dropped.map((d) => Object.freeze(d))) }) };
125
192
  } catch (err) {
126
193
  if (!(err instanceof ProfileError)) throw err;
127
194
  // What `get()` shows is always an object: an unreadable layer reads as empty, with the error beside it.
@@ -133,6 +200,36 @@ export class PolicyService {
133
200
  }
134
201
  }
135
202
 
203
+ /**
204
+ * 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
205
+ * longer than the retention now allows), and what was taken out. Without this one stale feed would make the whole layer unusable and
206
+ * silently drop the owner's other edits too. Logged by feed name only. Anything else wrong with the layer is left for
207
+ * `applyPolicyLayer` to refuse; a layer with nothing to drop comes back as it is.
208
+ */
209
+ private withoutStaleFeeds(layer: PolicyLayer): { layer: PolicyLayer; dropped: PolicyDropped[] } {
210
+ const dropped: PolicyDropped[] = [];
211
+ const signals: unknown = typeof layer === 'object' && layer !== null && !Array.isArray(layer) ? (layer as { signals?: unknown }).signals : undefined;
212
+ const feeds: unknown = typeof signals === 'object' && signals !== null && !Array.isArray(signals) ? (signals as { feeds?: unknown }).feeds : undefined;
213
+ if (typeof feeds !== 'object' || feeds === null || Array.isArray(feeds)) return { layer, dropped };
214
+ const pruned = pruneSignalFeeds(feeds, this.base.signals.kinds, {
215
+ signalsMs: this.signalsMs(),
216
+ onDrop: (name, reason) => {
217
+ const feed = SIGNAL_FEED_NAMES.includes(name) ? name : 'unknown';
218
+ safeWarn(this.logger, 'chatwarden.signal_feed_dropped', { feed });
219
+ dropped.push({ feed, reason });
220
+ },
221
+ });
222
+ if (dropped.length === 0) return { layer, dropped };
223
+ // 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`
224
+ // key replaces them wholesale, and an empty one would keep them off for a reason nobody can see).
225
+ const { feeds: _gone, ...others } = signals as { feeds?: unknown };
226
+ void _gone;
227
+ const rest = { ...layer } as Record<string, unknown>;
228
+ if (Object.keys(pruned).length === 0 && Object.keys(others).length === 0) delete rest['signals'];
229
+ else rest['signals'] = Object.keys(pruned).length === 0 ? others : { ...others, feeds: pruned };
230
+ return { layer: rest as PolicyLayer, dropped };
231
+ }
232
+
136
233
  /** 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
234
  private reload(): void {
138
235
  const stored = this.store.loadPolicyLayer?.() ?? null;
@@ -166,8 +263,17 @@ export class PolicyService {
166
263
 
167
264
  get(): PolicyState {
168
265
  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 } }) };
266
+ const { effective, layer, version, layerError, dropped } = this.state;
267
+ return {
268
+ effective,
269
+ base: this.base,
270
+ layer,
271
+ version,
272
+ canSave: this.supported,
273
+ ...(layerError === undefined ? {} : { layerError: { ...layerError } }),
274
+ ...(dropped === undefined ? {} : { dropped }),
275
+ limits: Object.freeze({ chatRate: this.chatRate, signalsMs: this.signalsMs() }),
276
+ };
171
277
  }
172
278
 
173
279
  /** Look at the store now, whatever the interval. A store failure throws. */
@@ -191,6 +297,11 @@ export class PolicyService {
191
297
  return { ok: false, error: 'conflict' };
192
298
  }
193
299
  const changed = changedSections(before, layer);
300
+ // The layer this save was judged against had feeds taken out of it (`dropped`): the stored row loses them now, so `signals` changed.
301
+ if (this.state.version === expected && this.state.dropped !== undefined && !changed.includes('signals')) {
302
+ changed.push('signals');
303
+ changed.sort((a, b) => POLICY_SECTIONS.indexOf(a) - POLICY_SECTIONS.indexOf(b));
304
+ }
194
305
  this.lastCheck = this.clock.now();
195
306
  this.adopt({ layer, version: next });
196
307
  return { ok: true, version: next, changed };
@@ -212,7 +323,11 @@ export class PolicyService {
212
323
  return { ok: false, error: 'invalid', path: 'reason' };
213
324
  }
214
325
  try {
215
- applyPolicyLayer(this.base, layer);
326
+ const effective = applyPolicyLayer(this.base, layer);
327
+ // The windows are checked against the retention here, where it is known: a window longer than it could never be met.
328
+ checkSignalFeeds(effective.signals.feeds, effective.signals.kinds, { signalsMs: this.signalsMs() }, 'layer.signals.feeds');
329
+ // A switch that would do nothing is refused, so the owner is not shown "on" over a store that cannot keep appeals.
330
+ if (!this.appealsKept && effective.appeals.enabled && !this.base.appeals.enabled) return { ok: false, error: 'invalid', path: 'layer.appeals.enabled' };
216
331
  } catch (err) {
217
332
  if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
218
333
  throw err;
@@ -264,6 +379,8 @@ export class PolicyService {
264
379
  let candidate: ResolvedProfile;
265
380
  try {
266
381
  candidate = applyPolicyLayer(this.base, layer);
382
+ // 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.
383
+ checkSignalFeeds(candidate.signals.feeds, candidate.signals.kinds, { signalsMs: this.signalsMs() }, 'layer.signals.feeds');
267
384
  } catch (err) {
268
385
  if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
269
386
  throw err;