@chatwarden/core 0.1.6 → 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 (196) hide show
  1. package/README.md +173 -3
  2. package/dist/src/ai/agreement.d.ts +46 -0
  3. package/dist/src/ai/agreement.d.ts.map +1 -0
  4. package/dist/src/ai/agreement.js +71 -0
  5. package/dist/src/ai/agreement.js.map +1 -0
  6. package/dist/src/ai/breaker.d.ts +31 -0
  7. package/dist/src/ai/breaker.d.ts.map +1 -0
  8. package/dist/src/ai/breaker.js +62 -0
  9. package/dist/src/ai/breaker.js.map +1 -0
  10. package/dist/src/ai/budget.d.ts +26 -0
  11. package/dist/src/ai/budget.d.ts.map +1 -0
  12. package/dist/src/ai/budget.js +57 -0
  13. package/dist/src/ai/budget.js.map +1 -0
  14. package/dist/src/ai/case.d.ts +37 -0
  15. package/dist/src/ai/case.d.ts.map +1 -0
  16. package/dist/src/ai/case.js +30 -0
  17. package/dist/src/ai/case.js.map +1 -0
  18. package/dist/src/ai/casebook.d.ts +59 -0
  19. package/dist/src/ai/casebook.d.ts.map +1 -0
  20. package/dist/src/ai/casebook.js +47 -0
  21. package/dist/src/ai/casebook.js.map +1 -0
  22. package/dist/src/ai/ceilings.d.ts +42 -0
  23. package/dist/src/ai/ceilings.d.ts.map +1 -0
  24. package/dist/src/ai/ceilings.js +59 -0
  25. package/dist/src/ai/ceilings.js.map +1 -0
  26. package/dist/src/ai/fake.d.ts +41 -0
  27. package/dist/src/ai/fake.d.ts.map +1 -0
  28. package/dist/src/ai/fake.js +75 -0
  29. package/dist/src/ai/fake.js.map +1 -0
  30. package/dist/src/ai/hash.d.ts +15 -0
  31. package/dist/src/ai/hash.d.ts.map +1 -0
  32. package/dist/src/ai/hash.js +22 -0
  33. package/dist/src/ai/hash.js.map +1 -0
  34. package/dist/src/ai/inert.d.ts +5 -0
  35. package/dist/src/ai/inert.d.ts.map +1 -0
  36. package/dist/src/ai/inert.js +22 -0
  37. package/dist/src/ai/inert.js.map +1 -0
  38. package/dist/src/ai/injection.d.ts +8 -0
  39. package/dist/src/ai/injection.d.ts.map +1 -0
  40. package/dist/src/ai/injection.js +30 -0
  41. package/dist/src/ai/injection.js.map +1 -0
  42. package/dist/src/ai/lines.d.ts +64 -0
  43. package/dist/src/ai/lines.d.ts.map +1 -0
  44. package/dist/src/ai/lines.js +172 -0
  45. package/dist/src/ai/lines.js.map +1 -0
  46. package/dist/src/ai/prompt.d.ts +48 -0
  47. package/dist/src/ai/prompt.d.ts.map +1 -0
  48. package/dist/src/ai/prompt.js +196 -0
  49. package/dist/src/ai/prompt.js.map +1 -0
  50. package/dist/src/ai/redact.d.ts +29 -0
  51. package/dist/src/ai/redact.d.ts.map +1 -0
  52. package/dist/src/ai/redact.js +160 -0
  53. package/dist/src/ai/redact.js.map +1 -0
  54. package/dist/src/ai/schema.d.ts +6 -0
  55. package/dist/src/ai/schema.d.ts.map +1 -0
  56. package/dist/src/ai/schema.js +50 -0
  57. package/dist/src/ai/schema.js.map +1 -0
  58. package/dist/src/ai/service.d.ts +332 -0
  59. package/dist/src/ai/service.d.ts.map +1 -0
  60. package/dist/src/ai/service.js +751 -0
  61. package/dist/src/ai/service.js.map +1 -0
  62. package/dist/src/ai/types.d.ts +196 -0
  63. package/dist/src/ai/types.d.ts.map +1 -0
  64. package/dist/src/ai/types.js +23 -0
  65. package/dist/src/ai/types.js.map +1 -0
  66. package/dist/src/ai/validate.d.ts +30 -0
  67. package/dist/src/ai/validate.d.ts.map +1 -0
  68. package/dist/src/ai/validate.js +160 -0
  69. package/dist/src/ai/validate.js.map +1 -0
  70. package/dist/src/ai/worker.d.ts +76 -0
  71. package/dist/src/ai/worker.d.ts.map +1 -0
  72. package/dist/src/ai/worker.js +293 -0
  73. package/dist/src/ai/worker.js.map +1 -0
  74. package/dist/src/audit.d.ts +12 -3
  75. package/dist/src/audit.d.ts.map +1 -1
  76. package/dist/src/audit.js +30 -4
  77. package/dist/src/audit.js.map +1 -1
  78. package/dist/src/chat.d.ts +39 -1
  79. package/dist/src/chat.d.ts.map +1 -1
  80. package/dist/src/chat.js +85 -6
  81. package/dist/src/chat.js.map +1 -1
  82. package/dist/src/chatwarden.d.ts +84 -1
  83. package/dist/src/chatwarden.d.ts.map +1 -1
  84. package/dist/src/chatwarden.js +168 -6
  85. package/dist/src/chatwarden.js.map +1 -1
  86. package/dist/src/decide.d.ts +36 -1
  87. package/dist/src/decide.d.ts.map +1 -1
  88. package/dist/src/decide.js +62 -2
  89. package/dist/src/decide.js.map +1 -1
  90. package/dist/src/documents.d.ts +1 -1
  91. package/dist/src/documents.d.ts.map +1 -1
  92. package/dist/src/documents.js +6 -1
  93. package/dist/src/documents.js.map +1 -1
  94. package/dist/src/freeze.d.ts +3 -0
  95. package/dist/src/freeze.d.ts.map +1 -0
  96. package/dist/src/freeze.js +10 -0
  97. package/dist/src/freeze.js.map +1 -0
  98. package/dist/src/index.d.ts +37 -8
  99. package/dist/src/index.d.ts.map +1 -1
  100. package/dist/src/index.js +23 -3
  101. package/dist/src/index.js.map +1 -1
  102. package/dist/src/ladder.d.ts +28 -0
  103. package/dist/src/ladder.d.ts.map +1 -1
  104. package/dist/src/ladder.js +37 -1
  105. package/dist/src/ladder.js.map +1 -1
  106. package/dist/src/pace.d.ts +66 -0
  107. package/dist/src/pace.d.ts.map +1 -0
  108. package/dist/src/pace.js +111 -0
  109. package/dist/src/pace.js.map +1 -0
  110. package/dist/src/pacing.d.ts +63 -0
  111. package/dist/src/pacing.d.ts.map +1 -0
  112. package/dist/src/pacing.js +198 -0
  113. package/dist/src/pacing.js.map +1 -0
  114. package/dist/src/policy.d.ts +57 -1
  115. package/dist/src/policy.d.ts.map +1 -1
  116. package/dist/src/policy.js +67 -4
  117. package/dist/src/policy.js.map +1 -1
  118. package/dist/src/profile.d.ts +64 -8
  119. package/dist/src/profile.d.ts.map +1 -1
  120. package/dist/src/profile.js +98 -27
  121. package/dist/src/profile.js.map +1 -1
  122. package/dist/src/profileError.d.ts +10 -0
  123. package/dist/src/profileError.d.ts.map +1 -0
  124. package/dist/src/profileError.js +17 -0
  125. package/dist/src/profileError.js.map +1 -0
  126. package/dist/src/retention.d.ts +28 -0
  127. package/dist/src/retention.d.ts.map +1 -1
  128. package/dist/src/retention.js +42 -10
  129. package/dist/src/retention.js.map +1 -1
  130. package/dist/src/signalCounts.d.ts +37 -0
  131. package/dist/src/signalCounts.d.ts.map +1 -0
  132. package/dist/src/signalCounts.js +117 -0
  133. package/dist/src/signalCounts.js.map +1 -0
  134. package/dist/src/signalInert.d.ts +10 -0
  135. package/dist/src/signalInert.d.ts.map +1 -0
  136. package/dist/src/signalInert.js +28 -0
  137. package/dist/src/signalInert.js.map +1 -0
  138. package/dist/src/signalService.d.ts +101 -0
  139. package/dist/src/signalService.d.ts.map +1 -0
  140. package/dist/src/signalService.js +383 -0
  141. package/dist/src/signalService.js.map +1 -0
  142. package/dist/src/signals.d.ts +186 -0
  143. package/dist/src/signals.d.ts.map +1 -0
  144. package/dist/src/signals.js +361 -0
  145. package/dist/src/signals.js.map +1 -0
  146. package/dist/src/subjects.d.ts +2 -0
  147. package/dist/src/subjects.d.ts.map +1 -1
  148. package/dist/src/subjects.js +4 -0
  149. package/dist/src/subjects.js.map +1 -1
  150. package/dist/src/team.d.ts +27 -0
  151. package/dist/src/team.d.ts.map +1 -1
  152. package/dist/src/team.js +92 -4
  153. package/dist/src/team.js.map +1 -1
  154. package/dist/src/types.d.ts +324 -2
  155. package/dist/src/types.d.ts.map +1 -1
  156. package/dist/src/types.js.map +1 -1
  157. package/package.json +2 -2
  158. package/src/ai/agreement.ts +106 -0
  159. package/src/ai/breaker.ts +73 -0
  160. package/src/ai/budget.ts +65 -0
  161. package/src/ai/case.ts +74 -0
  162. package/src/ai/casebook.ts +75 -0
  163. package/src/ai/ceilings.ts +68 -0
  164. package/src/ai/fake.ts +105 -0
  165. package/src/ai/hash.ts +23 -0
  166. package/src/ai/inert.ts +26 -0
  167. package/src/ai/injection.ts +32 -0
  168. package/src/ai/lines.ts +216 -0
  169. package/src/ai/prompt.ts +223 -0
  170. package/src/ai/redact.ts +174 -0
  171. package/src/ai/schema.ts +51 -0
  172. package/src/ai/service.ts +961 -0
  173. package/src/ai/types.ts +182 -0
  174. package/src/ai/validate.ts +173 -0
  175. package/src/ai/worker.ts +372 -0
  176. package/src/audit.ts +31 -5
  177. package/src/chat.ts +109 -8
  178. package/src/chatwarden.ts +248 -8
  179. package/src/decide.ts +97 -4
  180. package/src/documents.ts +7 -2
  181. package/src/freeze.ts +8 -0
  182. package/src/index.ts +91 -2
  183. package/src/ladder.ts +59 -1
  184. package/src/pace.ts +139 -0
  185. package/src/pacing.ts +242 -0
  186. package/src/policy.ts +107 -7
  187. package/src/profile.ts +149 -27
  188. package/src/profileError.ts +17 -0
  189. package/src/retention.ts +63 -10
  190. package/src/signalCounts.ts +133 -0
  191. package/src/signalInert.ts +31 -0
  192. package/src/signalService.ts +406 -0
  193. package/src/signals.ts +489 -0
  194. package/src/subjects.ts +5 -0
  195. package/src/team.ts +93 -5
  196. package/src/types.ts +358 -2
@@ -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
+ }
@@ -0,0 +1,31 @@
1
+ import { safeWarn } from './log.js';
2
+ import { BUILTIN_SIGNAL_KINDS } from './signals.js';
3
+ import type { ResolvedSignals } from './signals.js';
4
+ import type { SignalRuntime } from './signalService.js';
5
+ import type { Logger } from './types.js';
6
+
7
+ /**
8
+ * What `cw.signals` is when the store cannot keep signals (it lacks the three signal methods): `record` is false and said once, every reader
9
+ * is empty, and `kinds` still lists what the profile declares. The real service (`./signalService.js`) is loaded only for a store that can keep
10
+ * them, so a page that never records a signal does not carry it.
11
+ */
12
+ export function createInertSignals(logger: Logger | undefined, settings: () => ResolvedSignals): SignalRuntime {
13
+ let said = false;
14
+ const record = (): boolean => {
15
+ if (!said) {
16
+ said = true;
17
+ safeWarn(logger, 'chatwarden.signals_store_unsupported');
18
+ }
19
+ return false;
20
+ };
21
+ return {
22
+ record,
23
+ flood: record,
24
+ counts: () => [],
25
+ kinds: () => Object.entries(settings().kinds).map(([kind, k]) => ({ kind, label: k.label, polarity: k.polarity, weight: k.weight, builtin: Object.hasOwn(BUILTIN_SIGNAL_KINDS, kind) })),
26
+ boosted: () => new Set(),
27
+ forRecord: () => [],
28
+ forAi: () => [],
29
+ ladderHits: () => [],
30
+ };
31
+ }
@@ -0,0 +1,406 @@
1
+ import { randomId, sha256Hex } from './crypto.js';
2
+ import { errorClass, safeWarn, ThrottledWarn } from './log.js';
3
+ import type { SignalHit } from './ladder.js';
4
+ import { countSignals, evaluateThreshold } from './signalCounts.js';
5
+ import { BUILTIN_SIGNAL_KINDS, SIGNAL_WINDOW_DAYS_MAX } from './signals.js';
6
+ import type { ResolvedSignals, SignalCount, SignalInput, SignalKindView } from './signals.js';
7
+ import type { SubjectIndex } from './subjects.js';
8
+ import type { Clock, Logger, RawWho, Store, SubjectId } from './types.js';
9
+
10
+ // The signal service behind `cw.signals`: record (guarded), count, and the reads the feeds make. A signal never acts; this only keeps rows
11
+ // and counts them. Everything here is fenced: `record` returns false and the readers return empty, never throw. Logs carry event names and
12
+ // reason codes (and an error class), never a subject, a `by`, a room, a kind id or a label.
13
+
14
+ const DAY_MS = 86_400_000;
15
+ const MIN_MS = 60_000;
16
+ /** How far ahead of the clock a record may be dated. */
17
+ const AHEAD_MS = 5 * MIN_MS;
18
+ /** The window `counts` uses when it is not given one. */
19
+ const DEFAULT_WINDOW_DAYS = 30;
20
+ /** The most people one `boosted` call reads. */
21
+ const BOOSTED_MAX = 1000;
22
+ const ROOM_ID = /^[A-Za-z0-9_.:-]{1,64}$/;
23
+ const SUBJECT_ID_MAX = 128;
24
+ /** The longest connection detail (client key, account id, IP) a record may carry: longer is not a real one, and it would be hashed. */
25
+ const DETAIL_MAX = 512;
26
+ /** How long a player's account age is remembered, and for how many players. */
27
+ const AGE_MEMO_MS = MIN_MS;
28
+ const AGE_MEMO_MAX = 256;
29
+
30
+ /** Is this a room id a signal may carry (1 to 64 of A-Z a-z 0-9 _ . : -)? */
31
+ export const isSignalRoomId = (v: unknown): v is string => typeof v === 'string' && v.length <= 64 && ROOM_ID.test(v);
32
+
33
+ /**
34
+ * The room id a flood row carries: the id itself when the signal rules accept it, else a stable `h` plus 16 hex digits of its SHA-256 (so a
35
+ * game whose room ids hold a space or run long still gets one source per room, and only the digest is stored). Undefined for no room.
36
+ */
37
+ export const floodRoomId = (v: unknown): string | undefined => (typeof v !== 'string' || v === '' ? undefined : isSignalRoomId(v) ? v : `h${sha256Hex(v).slice(0, 16)}`);
38
+
39
+ export type SignalRefusal = 'undeclared' | 'malformed' | 'unknown_subject' | 'self' | 'time' | 'capped' | 'no_store' | 'store_failed';
40
+
41
+ /** Thrown inside `record` to end it with a reason; never leaves the service. */
42
+ class Refusal extends Error {
43
+ readonly reason: SignalRefusal;
44
+ readonly detail: string | undefined;
45
+ constructor(reason: SignalRefusal, detail?: string) {
46
+ super(reason);
47
+ this.reason = reason;
48
+ this.detail = detail;
49
+ }
50
+ }
51
+
52
+ export interface SignalServiceDeps {
53
+ store: Store;
54
+ clock: Clock;
55
+ logger: Logger | undefined;
56
+ subjects: SubjectIndex;
57
+ /** The person behind a player's connection details: FOUND and never created. */
58
+ personOf: (who: RawWho) => SubjectId | null;
59
+ /** The signal settings in force right now (kinds, guards, feeds). Read on every call. */
60
+ settings: () => ResolvedSignals;
61
+ /** How long signal rows are kept, ms. */
62
+ signalsMs: () => number;
63
+ /** How old is this player's account, in days? See `ChatwardenOptions.signals`. */
64
+ accountAgeDays?: (accountIds: readonly string[]) => number | null | undefined;
65
+ }
66
+
67
+ /** An own, defined field of a plain object, or undefined. */
68
+ function field(o: object, key: string): unknown {
69
+ return Object.hasOwn(o, key) ? (o as Record<string, unknown>)[key] : undefined;
70
+ }
71
+
72
+ function isPlainObject(v: unknown): v is object {
73
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
74
+ const proto: unknown = Object.getPrototypeOf(v);
75
+ return proto === Object.prototype || proto === null;
76
+ }
77
+
78
+ /** What the kit asks of the signal service: the real one, or the inert one (`./signalInert.js`) for a store that cannot keep signals. */
79
+ export interface SignalRuntime {
80
+ /** Record one signal; false for any refusal. Never throws. */
81
+ record(input: SignalInput): boolean;
82
+ /** The built-in `flood_triggered` for a person, with the room only when the signal rules accept its id. Never throws. */
83
+ flood(subject: SubjectId, roomId: string): void;
84
+ counts(subject: SubjectId, opts?: { windowDays?: number; kinds?: readonly string[] }): SignalCount[];
85
+ kinds(): SignalKindView[];
86
+ boosted(people: readonly SubjectId[]): Set<SubjectId>;
87
+ forRecord(subject: SubjectId): SignalCount[];
88
+ /** The counts the AI read may be shown (`feeds.ai`): the feed's kinds and window. `[]` when the feed is off. Never throws. */
89
+ forAi(subject: SubjectId): SignalCount[];
90
+ ladderHits(subject: SubjectId): SignalHit[];
91
+ }
92
+
93
+ export class SignalService implements SignalRuntime {
94
+ private readonly deps: SignalServiceDeps;
95
+ /** One throttle per refusal reason, so a burst of `malformed` cannot hide a `store_failed` for a minute. */
96
+ private readonly refusedWarn = new Map<string, ThrottledWarn>();
97
+ private readonly readWarn: ThrottledWarn;
98
+ private readonly ageWarn: ThrottledWarn;
99
+ private unsupportedLogged = false;
100
+ /** The account age the game's hook gave for a player, and when (see `accountFactor`). */
101
+ private readonly ageMemo = new Map<SubjectId, { age: unknown; at: number }>();
102
+
103
+ constructor(deps: SignalServiceDeps) {
104
+ this.deps = deps;
105
+ this.readWarn = new ThrottledWarn(deps.logger, deps.clock);
106
+ this.ageWarn = new ThrottledWarn(deps.logger, deps.clock);
107
+ }
108
+
109
+ /** Does the store keep signals (the three methods)? */
110
+ private get supported(): boolean {
111
+ const s = this.deps.store;
112
+ return typeof s.insertSignal === 'function' && typeof s.listSignalSources === 'function' && typeof s.purgeSignals === 'function';
113
+ }
114
+
115
+ /** The store cannot keep signals: said once per kit, as the AI does for its own optional methods. */
116
+ private unsupported(): void {
117
+ if (this.unsupportedLogged) return;
118
+ this.unsupportedLogged = true;
119
+ safeWarn(this.deps.logger, 'chatwarden.signals_store_unsupported');
120
+ }
121
+
122
+ // --- record ---------------------------------------------------------------------------------------------------
123
+
124
+ /** Record one signal. Synchronous, fenced, never throws: false for any refusal (logged by reason code, at most once a minute). */
125
+ record(input: SignalInput): boolean {
126
+ return this.guarded(input, false);
127
+ }
128
+
129
+ /** `record`'s body. `quietCapped`: the cap refusing is the designed answer (a second flood trip the same day), so it is not logged. */
130
+ private guarded(input: unknown, quietCapped: boolean): boolean {
131
+ try {
132
+ if (!this.supported) {
133
+ this.unsupported();
134
+ return false;
135
+ }
136
+ return this.recordRow(input);
137
+ } catch (err) {
138
+ const reason = err instanceof Refusal ? err.reason : 'malformed';
139
+ if (quietCapped && reason === 'capped') return false;
140
+ try {
141
+ let throttle = this.refusedWarn.get(reason);
142
+ if (throttle === undefined) this.refusedWarn.set(reason, (throttle = new ThrottledWarn(this.deps.logger, this.deps.clock)));
143
+ throttle.warn('chatwarden.signal_refused', err instanceof Refusal && err.detail !== undefined ? { reason, error: err.detail } : { reason });
144
+ } catch {
145
+ // The log must never change the answer.
146
+ }
147
+ return false;
148
+ }
149
+ }
150
+
151
+ flood(subject: SubjectId, roomId: string): void {
152
+ const room = floodRoomId(roomId);
153
+ this.guarded({ kind: 'flood_triggered', subject, ...(room === undefined ? {} : { roomId: room }) }, true);
154
+ }
155
+
156
+ private recordRow(input: unknown): boolean {
157
+ if (!isPlainObject(input)) throw new Refusal('malformed');
158
+ const { kinds, guards } = this.deps.settings();
159
+ const kindId = field(input, 'kind');
160
+ if (typeof kindId !== 'string') throw new Refusal('malformed');
161
+ if (!Object.hasOwn(kinds, kindId)) throw new Refusal('undeclared');
162
+ const spec = kinds[kindId]!;
163
+
164
+ // null is "left out" for the optional fields a game fills from a maybe-null variable: by, roomId and at.
165
+ const given = (key: string): unknown => field(input, key) ?? undefined;
166
+ const roomId = given('roomId');
167
+ if (roomId !== undefined && !isSignalRoomId(roomId)) throw new Refusal('malformed');
168
+ const now = this.deps.clock.now();
169
+ const givenAt = given('at');
170
+ if (givenAt !== undefined && !(typeof givenAt === 'number' && Number.isFinite(givenAt))) throw new Refusal('malformed');
171
+ const at = givenAt ?? now;
172
+ if (at > now + AHEAD_MS || at < now - this.deps.signalsMs()) throw new Refusal('time');
173
+ const givenWeight = field(input, 'weight');
174
+ if (givenWeight !== undefined && !(typeof givenWeight === 'number' && Number.isFinite(givenWeight) && givenWeight >= 0 && givenWeight <= 10)) {
175
+ throw new Refusal('malformed');
176
+ }
177
+
178
+ const subject = this.party(field(input, 'subject'));
179
+ const rawBy = given('by');
180
+ const by = rawBy === undefined ? null : this.party(rawBy);
181
+ if (by !== null && by === subject) throw new Refusal('self');
182
+
183
+ const weight = (givenWeight ?? spec.weight) * this.accountFactor(by, guards.newAccount);
184
+ const sourceKey = by !== null ? `b:${by}` : roomId !== undefined ? `r:${roomId}` : `d:${new Date(at).toISOString().slice(0, 10)}`;
185
+ const wrote = this.insert({
186
+ id: randomId(16),
187
+ kind: kindId,
188
+ subject,
189
+ sourceKey,
190
+ bySubject: by,
191
+ roomId: roomId ?? null,
192
+ at,
193
+ weight,
194
+ capBucket: Math.floor(at / guards.perByWindowMs),
195
+ });
196
+ if (!wrote) throw new Refusal('capped');
197
+ return true;
198
+ }
199
+
200
+ private insert(row: Parameters<NonNullable<Store['insertSignal']>>[0]): boolean {
201
+ try {
202
+ return this.deps.store.insertSignal?.(row) ?? false;
203
+ } catch (err) {
204
+ throw new Refusal('store_failed', errorClass(err));
205
+ }
206
+ }
207
+
208
+ /** The canonical person a party names: a subject id the index knows, or a connection details object FOUND (never created). */
209
+ private party(p: unknown): SubjectId {
210
+ if (typeof p === 'string') {
211
+ if (p === '' || p.length > SUBJECT_ID_MAX || !this.deps.subjects.knows(p)) throw new Refusal('unknown_subject');
212
+ return this.deps.subjects.canonical(p);
213
+ }
214
+ if (!isPlainObject(p)) throw new Refusal('malformed');
215
+ const who: RawWho = {};
216
+ for (const key of ['clientKey', 'accountId'] as const) {
217
+ const v = field(p, key);
218
+ if (v === undefined) continue;
219
+ if (typeof v !== 'string' || v.length > DETAIL_MAX) throw new Refusal('malformed');
220
+ who[key] = v;
221
+ }
222
+ const ip = field(p, 'ip');
223
+ if (ip !== undefined && ip !== null) {
224
+ if (typeof ip !== 'string' || ip.length > DETAIL_MAX) throw new Refusal('malformed');
225
+ who.ip = ip;
226
+ }
227
+ const found = this.deps.personOf(who);
228
+ if (found === null) throw new Refusal('unknown_subject');
229
+ return this.deps.subjects.canonical(found);
230
+ }
231
+
232
+ /**
233
+ * The new-account factor for `by`: the guard's factor only when the game supplied the hook, it returned an age for the player's
234
+ * account ids, and the age is below `belowDays`; else 1. A hook that throws is unknown (logged by class). Computed once, at record time.
235
+ */
236
+ private accountFactor(by: SubjectId | null, rule: ResolvedSignals['guards']['newAccount']): number {
237
+ const hook = this.deps.accountAgeDays;
238
+ if (rule === null || hook === undefined || by === null) return 1;
239
+ const accounts = this.deps.subjects.identifiersOf(by).accounts;
240
+ if (accounts.length === 0) return 1;
241
+ // The game's hook is often a lookup: a player recording over and over is asked once a minute, not on every record.
242
+ const now = this.deps.clock.now();
243
+ const known = this.ageMemo.get(by);
244
+ let age: unknown;
245
+ if (known !== undefined && now >= known.at && now - known.at < AGE_MEMO_MS) age = known.age;
246
+ else {
247
+ try {
248
+ age = hook(accounts);
249
+ } catch (err) {
250
+ this.ageWarn.warn('chatwarden.signal_age_failed', { error: errorClass(err) });
251
+ return 1;
252
+ }
253
+ this.ageMemo.delete(by);
254
+ this.ageMemo.set(by, { age, at: now });
255
+ if (this.ageMemo.size > AGE_MEMO_MAX) this.ageMemo.delete(this.ageMemo.keys().next().value!);
256
+ }
257
+ return typeof age === 'number' && Number.isFinite(age) && age >= 0 && age < rule.belowDays ? rule.factor : 1;
258
+ }
259
+
260
+ /** A read that failed (a store fault) answers empty; it is said once a minute, by the error's class only. Never throws. */
261
+ private readFailed(err: unknown): void {
262
+ try {
263
+ this.readWarn.warn('chatwarden.signal_read_failed', { error: errorClass(err) });
264
+ } catch {
265
+ // The log must never change the answer.
266
+ }
267
+ }
268
+
269
+ // --- reads ----------------------------------------------------------------------------------------------------
270
+
271
+ /** The declared kinds, built-ins included. */
272
+ kinds(): SignalKindView[] {
273
+ const { kinds } = this.deps.settings();
274
+ return Object.keys(kinds).map((kind) => {
275
+ const k = kinds[kind]!;
276
+ return { kind, label: k.label, polarity: k.polarity, weight: k.weight, builtin: Object.hasOwn(BUILTIN_SIGNAL_KINDS, kind) };
277
+ });
278
+ }
279
+
280
+ /** The counts for a person (aliases folded): one entry per requested kind with a counted source. Never throws; a store failure reads []. */
281
+ counts(subject: SubjectId, opts?: { windowDays?: number; kinds?: readonly string[] }): SignalCount[] {
282
+ try {
283
+ if (!this.supported) return [];
284
+ const windowDays = this.windowOf(opts?.windowDays);
285
+ const asked = opts?.kinds;
286
+ const kinds = this.kindsFor(Array.isArray(asked) ? (asked as unknown[]) : undefined);
287
+ return this.countFor(subject, windowDays, kinds);
288
+ } catch (err) {
289
+ this.readFailed(err);
290
+ return [];
291
+ }
292
+ }
293
+
294
+ private windowOf(asked: unknown): number {
295
+ const cap = Math.max(1, Math.min(SIGNAL_WINDOW_DAYS_MAX, Math.floor(this.deps.signalsMs() / DAY_MS)));
296
+ if (typeof asked !== 'number' || !Number.isFinite(asked) || asked < 1) return Math.min(DEFAULT_WINDOW_DAYS, cap);
297
+ return Math.min(Math.floor(asked), cap);
298
+ }
299
+
300
+ /** The declared kinds (all, or those named, in declared order) as the counting context wants them. */
301
+ private kindsFor(only: readonly unknown[] | undefined): Record<string, { label: string; polarity: 'negative' | 'positive' }> {
302
+ const { kinds } = this.deps.settings();
303
+ const out: Record<string, { label: string; polarity: 'negative' | 'positive' }> = {};
304
+ for (const id of Object.keys(kinds)) {
305
+ if (only !== undefined && !only.includes(id)) continue;
306
+ Object.defineProperty(out, id, { value: { label: kinds[id]!.label, polarity: kinds[id]!.polarity }, enumerable: true, configurable: true, writable: true });
307
+ }
308
+ return out;
309
+ }
310
+
311
+ private countFor(subject: SubjectId, windowDays: number, kinds: Record<string, { label: string; polarity: 'negative' | 'positive' }>): SignalCount[] {
312
+ if (typeof subject !== 'string' || subject === '') return [];
313
+ const { subjects, store, clock } = this.deps;
314
+ const rows = store.listSignalSources?.(subjects.aliasesOf(subject), clock.now() - windowDays * DAY_MS) ?? [];
315
+ return countSignals(rows, { kinds, canonical: (s) => subjects.canonical(s), windowDays });
316
+ }
317
+
318
+ /**
319
+ * Who of these people meets `feeds.queue`, as canonical ids: one grouped store read for all of them. Empty (and no store read) when the
320
+ * feed is off. Never throws.
321
+ */
322
+ boosted(people: readonly SubjectId[]): Set<SubjectId> {
323
+ try {
324
+ const queue = this.deps.settings().feeds.queue;
325
+ if (queue === undefined || !this.supported || !Array.isArray(people)) return new Set();
326
+ const { subjects, store, clock } = this.deps;
327
+ const canon = [...new Set((people as unknown[]).filter((p): p is string => typeof p === 'string' && p !== '').slice(0, BOOSTED_MAX).map((p) => subjects.canonical(p)))];
328
+ if (canon.length === 0) return new Set();
329
+ const ofAlias = new Map<SubjectId, SubjectId>();
330
+ for (const person of canon) for (const alias of subjects.aliasesOf(person)) ofAlias.set(alias, person);
331
+ const rows = store.listSignalSources?.([...ofAlias.keys()], clock.now() - queue.windowDays * DAY_MS) ?? [];
332
+ const byPerson = new Map<SubjectId, typeof rows>();
333
+ for (const row of rows) {
334
+ const person = ofAlias.get(row.subject);
335
+ if (person === undefined) continue;
336
+ const list = byPerson.get(person);
337
+ if (list === undefined) byPerson.set(person, [row]);
338
+ else list.push(row);
339
+ }
340
+ const kinds = this.kindsFor(undefined);
341
+ const out = new Set<SubjectId>();
342
+ for (const [person, list] of byPerson) {
343
+ if (evaluateThreshold(list, { kinds, canonical: (s) => subjects.canonical(s) }, queue).met) out.add(person);
344
+ }
345
+ return out;
346
+ } catch (err) {
347
+ this.readFailed(err);
348
+ return new Set();
349
+ }
350
+ }
351
+
352
+ /**
353
+ * The ladder rules (`feeds.ladder`) this person meets, for `suggest`: each as its id, effect and the sentence ("Muted by other players:
354
+ * 5 players in 14 days"). Rows are read once per distinct window. `[]` (and no store read) when the feed is off. Never throws.
355
+ */
356
+ ladderHits(subject: SubjectId): SignalHit[] {
357
+ try {
358
+ const { feeds, kinds } = this.deps.settings();
359
+ const rules = feeds.ladder;
360
+ if (rules === undefined || rules.length === 0 || !this.supported || typeof subject !== 'string' || subject === '') return [];
361
+ const { subjects, store, clock } = this.deps;
362
+ const aliases = subjects.aliasesOf(subject);
363
+ const ctxKinds = this.kindsFor(undefined);
364
+ const byWindow = new Map<number, ReturnType<NonNullable<Store['listSignalSources']>>>();
365
+ const hits: SignalHit[] = [];
366
+ for (const rule of rules) {
367
+ let rows = byWindow.get(rule.windowDays);
368
+ if (rows === undefined) {
369
+ rows = store.listSignalSources?.(aliases, clock.now() - rule.windowDays * DAY_MS) ?? [];
370
+ byWindow.set(rule.windowDays, rows);
371
+ }
372
+ const res = evaluateThreshold(rows, { kinds: ctxKinds, canonical: (s) => subjects.canonical(s) }, rule);
373
+ if (!res.met) continue;
374
+ const labels = rule.kinds.map((k) => kinds[k]?.label ?? k).join(', ');
375
+ const players = `${res.distinct} player${res.distinct === 1 ? '' : 's'}`;
376
+ const days = `${rule.windowDays} day${rule.windowDays === 1 ? '' : 's'}`;
377
+ hits.push({ id: rule.id, effect: rule.effect, text: `${labels}: ${players} in ${days}` });
378
+ }
379
+ return hits;
380
+ } catch (err) {
381
+ this.readFailed(err);
382
+ return [];
383
+ }
384
+ }
385
+
386
+ /** The lines the Person page record shows: the `feeds.record` kinds and window. `[]` (and no store read) when the feed is off. Never throws. */
387
+ forRecord(subject: SubjectId): SignalCount[] {
388
+ return this.forFeed(subject, this.deps.settings().feeds.record);
389
+ }
390
+
391
+ /** The counts the AI read may be shown: the `feeds.ai` kinds and window. `[]` (and no store read) when the feed is off. Never throws. */
392
+ forAi(subject: SubjectId): SignalCount[] {
393
+ return this.forFeed(subject, this.deps.settings().feeds.ai);
394
+ }
395
+
396
+ private forFeed(subject: SubjectId, feed: { kinds: readonly string[] | '*'; windowDays: number } | undefined): SignalCount[] {
397
+ try {
398
+ if (feed === undefined || !this.supported) return [];
399
+ const kinds = this.kindsFor(feed.kinds === '*' ? undefined : feed.kinds);
400
+ return this.countFor(subject, this.windowOf(feed.windowDays), kinds);
401
+ } catch (err) {
402
+ this.readFailed(err);
403
+ return [];
404
+ }
405
+ }
406
+ }