@chatwarden/core 0.1.5 → 0.1.7

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 (131) hide show
  1. package/README.md +51 -1
  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 +13 -0
  31. package/dist/src/ai/hash.d.ts.map +1 -0
  32. package/dist/src/ai/hash.js +19 -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 +44 -0
  47. package/dist/src/ai/prompt.d.ts.map +1 -0
  48. package/dist/src/ai/prompt.js +185 -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 +328 -0
  59. package/dist/src/ai/service.d.ts.map +1 -0
  60. package/dist/src/ai/service.js +749 -0
  61. package/dist/src/ai/service.js.map +1 -0
  62. package/dist/src/ai/types.d.ts +180 -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 +74 -0
  71. package/dist/src/ai/worker.d.ts.map +1 -0
  72. package/dist/src/ai/worker.js +286 -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/chatwarden.d.ts +28 -0
  79. package/dist/src/chatwarden.d.ts.map +1 -1
  80. package/dist/src/chatwarden.js +60 -1
  81. package/dist/src/chatwarden.js.map +1 -1
  82. package/dist/src/decide.d.ts +36 -1
  83. package/dist/src/decide.d.ts.map +1 -1
  84. package/dist/src/decide.js +62 -2
  85. package/dist/src/decide.js.map +1 -1
  86. package/dist/src/documents.d.ts +1 -1
  87. package/dist/src/documents.d.ts.map +1 -1
  88. package/dist/src/documents.js +4 -1
  89. package/dist/src/documents.js.map +1 -1
  90. package/dist/src/index.d.ts +27 -5
  91. package/dist/src/index.d.ts.map +1 -1
  92. package/dist/src/index.js +17 -2
  93. package/dist/src/index.js.map +1 -1
  94. package/dist/src/profile.d.ts +30 -1
  95. package/dist/src/profile.d.ts.map +1 -1
  96. package/dist/src/profile.js +43 -4
  97. package/dist/src/profile.js.map +1 -1
  98. package/dist/src/retention.d.ts +19 -0
  99. package/dist/src/retention.d.ts.map +1 -1
  100. package/dist/src/retention.js +33 -10
  101. package/dist/src/retention.js.map +1 -1
  102. package/dist/src/types.d.ts +269 -2
  103. package/dist/src/types.d.ts.map +1 -1
  104. package/dist/src/types.js.map +1 -1
  105. package/package.json +2 -2
  106. package/src/ai/agreement.ts +106 -0
  107. package/src/ai/breaker.ts +73 -0
  108. package/src/ai/budget.ts +65 -0
  109. package/src/ai/case.ts +74 -0
  110. package/src/ai/casebook.ts +75 -0
  111. package/src/ai/ceilings.ts +68 -0
  112. package/src/ai/fake.ts +105 -0
  113. package/src/ai/hash.ts +20 -0
  114. package/src/ai/inert.ts +26 -0
  115. package/src/ai/injection.ts +32 -0
  116. package/src/ai/lines.ts +216 -0
  117. package/src/ai/prompt.ts +208 -0
  118. package/src/ai/redact.ts +174 -0
  119. package/src/ai/schema.ts +51 -0
  120. package/src/ai/service.ts +955 -0
  121. package/src/ai/types.ts +165 -0
  122. package/src/ai/validate.ts +173 -0
  123. package/src/ai/worker.ts +364 -0
  124. package/src/audit.ts +31 -5
  125. package/src/chatwarden.ts +82 -1
  126. package/src/decide.ts +97 -4
  127. package/src/documents.ts +5 -2
  128. package/src/index.ts +52 -1
  129. package/src/profile.ts +68 -4
  130. package/src/retention.ts +47 -10
  131. package/src/types.ts +294 -2
@@ -0,0 +1,955 @@
1
+ import type { AuditRecordInput } from '../audit.js';
2
+ import type { Subscribe } from '../events.js';
3
+ import type { Suggestion } from '../ladder.js';
4
+ import { errorClass, safeWarn } from '../log.js';
5
+ import type { ResolvedProfile } from '../profile.js';
6
+ import { AI_DAILY_CALLS_DEFAULT } from '../profile.js';
7
+ import { suggestedRule } from '../reporting.js';
8
+ import type { CommunityRules, RuleRef } from '../rules.js';
9
+ import { CONDUCT_LEVELS } from '../types.js';
10
+ import type { AiReadRow } from '../types.js';
11
+ import type { AiOutcomeInsert, AiVerdict, Clock, ConductLevel, Logger, ReportRecord, SanctionKind, Store, SubjectId } from '../types.js';
12
+ import { agreementOf } from './agreement.js';
13
+ import type { StepLike } from './agreement.js';
14
+ import { Breaker } from './breaker.js';
15
+ import { emptyStats } from './inert.js';
16
+ import { CallWindow, startOfUtcDay, utcDayLabel } from './budget.js';
17
+ import { prepareCase } from './case.js';
18
+ import type { Prepared } from './case.js';
19
+ import { assertWithinCeilings, AICeilingError } from './ceilings.js';
20
+ import { actionsOnTarget, AI_EXAMPLES_MIN, pickExampleLines } from './casebook.js';
21
+ import type { AiOutcomeArgs } from './casebook.js';
22
+ import { aiPolicyText } from './prompt.js';
23
+ import { sha256Hex } from '../crypto.js';
24
+ import type { AIExampleInput, AIRead, ModerationAI } from './types.js';
25
+ import { isFinalRow, Meter, runRead } from './worker.js';
26
+ import type { AiStore, ReadEnd, WorkerEnv } from './worker.js';
27
+
28
+ // The AI service (design sections 4 and 6): listens for new reports and only enqueues; a small worker pool reads them off the ack
29
+ // path; a sweeper fills the gaps; the facade (`cw.ai`) answers the hub. Everything fails soft: any error here is logged by class and
30
+ // the caller gets what it would get with the AI off. This module never imports a sanction module: the AI advises, it cannot act.
31
+
32
+ /**
33
+ * What the code decides about the AI. The adapter and the ceilings on level and spend are code, never the hub's.
34
+ * @experimental
35
+ */
36
+ export interface AiOptions {
37
+ /** The model behind the reads. Runs on the server only. */
38
+ adapter: ModerationAI;
39
+ /** The highest level the hub may switch to. Default 2. */
40
+ maxLevel?: 1 | 2;
41
+ /** The most the AI may spend in a UTC day, in micro-dollars (1 = $0.000001). Default 1 000 000 ($1.00). Set in code: a hub cannot raise it. */
42
+ dailyBudgetMicros?: number;
43
+ /** The most calls in any minute. Default 30. */
44
+ perMinuteCalls?: number;
45
+ /** The most reads in flight at once. Default 2. */
46
+ concurrency?: number;
47
+ /** The hard deadline for one call, in milliseconds. Default 30 000. */
48
+ timeoutMs?: number;
49
+ /**
50
+ * `'raw'` (default) sends a line the filter touched (blocked, or starred in the room) as typed: the model needs the words to judge
51
+ * intent. `'mask'` sends it masked instead (a starred line as the room saw it, a blocked line as stars). Read the adapter's README
52
+ * before leaving the default: the provider receives abusive text.
53
+ */
54
+ blockedLines?: 'raw' | 'mask';
55
+ /** Reserved. No room tag, and no tag value, is ever sent to a provider in this release. */
56
+ contextTags?: string[];
57
+ }
58
+
59
+ /** Where the AI stands, for Settings. */
60
+ export interface AiStatus {
61
+ /** An adapter is configured. */
62
+ available: boolean;
63
+ /** The effective level: the lower of the hub's setting and `maxLevel`; 0 without an adapter. */
64
+ level: 0 | 1 | 2;
65
+ maxLevel: 0 | 1 | 2;
66
+ state: 'ok' | 'paused_budget' | 'unavailable' | 'off';
67
+ /** Today's spend (UTC), in micro-dollars, from the store. */
68
+ spentMicros: number;
69
+ capMicros: number;
70
+ /** The owner's ceiling on calls in a UTC day (`profile.ai.dailyCalls`); `reads` is counted against it. */
71
+ capCalls: number;
72
+ /** The UTC day the spend is for, `YYYY-MM-DD`. */
73
+ day: string;
74
+ /** Calls made today (UTC), from the store. */
75
+ reads: number;
76
+ /** The share of input tokens the provider served from its cache, over the calls this process made; null before any. */
77
+ cacheHitRate: number | null;
78
+ /** Answers core refused, by validator code, since this process started. Codes only, never text. */
79
+ invalid: Record<string, number>;
80
+ }
81
+
82
+ /** What the queue carries for a report: no summary, no line ids. */
83
+ export interface AiBrief {
84
+ severity: ConductLevel;
85
+ confidence: AIRead['confidence'];
86
+ rule: number | 'uncovered' | null;
87
+ /** The read was made from older rules or an older version of the case. */
88
+ stale: boolean;
89
+ injectionSuspected: boolean;
90
+ /** Level 2 and a recommendation that is not `unclear`. */
91
+ hasRecommendation: boolean;
92
+ }
93
+
94
+ /** The step the ladder gives for the AI's conduct level: what a one-click accept may fill. */
95
+ export interface SuggestionStep {
96
+ kind: SanctionKind;
97
+ durationMs: number | null;
98
+ label: string;
99
+ }
100
+
101
+ /** A stored read as the case page shows it. */
102
+ export interface AiReadView {
103
+ /** The read's id: what a decision echoes back. */
104
+ id: string;
105
+ severity: ConductLevel;
106
+ rule: number | 'uncovered' | null;
107
+ summary: string;
108
+ /** Real line ids, at most 5. */
109
+ evidenceLineIds: string[];
110
+ confidence: AIRead['confidence'];
111
+ /** From older rules, or from an older version of the case. */
112
+ stale: boolean;
113
+ injectionSuspected: boolean;
114
+ model: string | null;
115
+ /** When the read was started, epoch ms. */
116
+ at: number;
117
+ /** Level 2 only. */
118
+ recommendation: null | {
119
+ verdict: 'upheld' | 'noted' | 'no_action' | 'unclear';
120
+ severity: ConductLevel;
121
+ rule: number | 'uncovered' | null;
122
+ evidenceLineIds: string[];
123
+ /** `cw.suggest` for the AI's conduct level, now; null when it names no action. */
124
+ step: SuggestionStep | null;
125
+ /** `step` is within the ceilings (a warning, a note or a restriction of at most 24 hours, with a line by the reported person cited). */
126
+ stepWithinCeiling: boolean;
127
+ };
128
+ }
129
+
130
+ /** The casebook counts for one rule. */
131
+ export interface AiStatsRuleView {
132
+ rule: number | 'uncovered' | null;
133
+ decided: number;
134
+ agree: number;
135
+ override: number;
136
+ none: number;
137
+ falsePositives: number;
138
+ /** Decisions that were a one-click accept of the AI's pre-fill. */
139
+ oneClick: number;
140
+ }
141
+
142
+ /** The casebook, overall and per rule. */
143
+ export interface AiStatsView {
144
+ since: number;
145
+ decided: number;
146
+ agree: number;
147
+ override: number;
148
+ none: number;
149
+ falsePositives: number;
150
+ oneClick: number;
151
+ /** agree / (agree + override); null with neither. */
152
+ agreementRate: number | null;
153
+ /** falsePositives / (agree + override); null with neither. */
154
+ falsePositiveRate: number | null;
155
+ /** oneClick / (agree + override): how often a shown recommendation was accepted as it stood; null with none shown. */
156
+ oneClickRate: number | null;
157
+ rules: AiStatsRuleView[];
158
+ }
159
+
160
+ /** What `cw.ai.readAgain` answers. */
161
+ export type AiReadAgain =
162
+ | AiReadView
163
+ | 'pending'
164
+ | 'budget'
165
+ | 'off'
166
+ | 'rate'
167
+ /** The read for this input ended without an answer and a moderator already retook it once: there is nothing more to ask. */
168
+ | 'final'
169
+ /** The breaker is open or the call window is full: nothing can be called for `retryAfterMs`. */
170
+ | { unavailable: { retryAfterMs: number } };
171
+
172
+ /**
173
+ * `cw.ai`. Every method is safe to call at any time: with the AI off, without an adapter or with a failing provider or store it
174
+ * answers as if there were no AI (null, an empty map, `'off'`), and never throws.
175
+ * @experimental
176
+ */
177
+ export interface AiFacade {
178
+ /** The effective level now. */
179
+ level(): 0 | 1 | 2;
180
+ status(): AiStatus;
181
+ /**
182
+ * The newest finished read of a report as the case page shows it, or null. At level 0 nothing is read from the store. With
183
+ * `open: true` (the case page) a report with no read, or a stale one, is queued for a (re)read.
184
+ */
185
+ read(reportId: string, opts?: { open?: boolean }): AiReadView | null;
186
+ /**
187
+ * Whether a read of this report is on its way now, so the case page may wait for one: the effective level is 1 or 2, an adapter is
188
+ * configured, the breaker is closed, neither daily cap (money, calls) is reached, the report is open and its read has not ended
189
+ * without an answer. False otherwise, and on any failure; the page then renders exactly as with the AI off.
190
+ */
191
+ expected(reportId: string): boolean;
192
+ /**
193
+ * "Read again": the stored read when the input has not changed (no call), else a call is queued and the answer is `'pending'`.
194
+ * `'off'` at level 0 or for a report that is gone or decided, `'budget'` at the daily money or call cap, `'rate'` once `actor` has
195
+ * asked 10 times in a minute (counted in this process; every answer below uses an ask), `{ unavailable }` while the breaker is open or
196
+ * the call window is full, and `'final'` when the read for this input ended without an answer (declined, invalid twice, fatal, given
197
+ * up) and an explicit ask has already retaken it once. The first explicit ask on such a row retakes it (`'pending'`): it is charged
198
+ * to the spend and audited like any other read.
199
+ */
200
+ readAgain(reportId: string, actor: string): Promise<AiReadAgain>;
201
+ /** The queue's brief of each report that has a read. Reports without one are absent. */
202
+ briefs(reportIds: readonly string[]): Map<string, AiBrief>;
203
+ /** The casebook counts for decisions at or after `since` (default: the last 30 days). */
204
+ stats(q?: { since?: number }): AiStatsView;
205
+ /**
206
+ * The one function the appeals inbox calls when a decision is reversed (a granted appeal, a take-back): the report's casebook row can
207
+ * never teach again, loses its example text, and counts as an AI false positive when the AI had recommended action. True when the
208
+ * report has a row.
209
+ */
210
+ markReversed(reportId: string): boolean;
211
+ /** A senior's "don't teach" mark on a decided case: the row can never teach again and loses its example text. True when the report has a row. */
212
+ dontTeach(reportId: string): boolean;
213
+ /** Resolves when no read is queued or running (tests, graceful shutdown). */
214
+ idle(): Promise<void>;
215
+ /** Run the sweeper once. The timer does this every 60 seconds. */
216
+ sweep(): Promise<void>;
217
+ /** Stop the sweeper and abort the calls in flight. `cw.close()` does this. */
218
+ close(): void;
219
+ }
220
+
221
+ /** How often the sweeper runs. */
222
+ export const SWEEP_EVERY_MS = 60_000;
223
+ /** The most reports one sweep queues. */
224
+ export const SWEEP_BATCH = 20;
225
+ /** The most stale reads one idle sweep queues. */
226
+ export const STALE_PER_SWEEP = 5;
227
+ /** How many times one moderator may ask for a read again in a minute. */
228
+ export const READ_AGAIN_PER_MINUTE = 10;
229
+ /** The most reports the sweeper remembers as not to be queued (and the most final reads it remembers). */
230
+ export const PARKED_MAX = 2000;
231
+ /** How many recent open reports a sweep looks at. */
232
+ const SWEEP_SCAN = 200;
233
+ /** The audit trail takes an actor of at most 128 characters of `A-Za-z0-9_.:@+-`. */
234
+ const ACTOR_MAX = 128;
235
+ const PREPARED_CACHE_MAX = 500;
236
+ const STATS_DEFAULT_WINDOW_MS = 30 * 24 * 3_600_000;
237
+
238
+ const DEFAULTS = { maxLevel: 2, dailyBudgetMicros: 1_000_000, perMinuteCalls: 30, concurrency: 2, timeoutMs: 30_000 } as const;
239
+
240
+ /** The audit actor for the AI: `ai:` and the adapter's id with every character the trail refuses made an underscore, cut to fit. */
241
+ export function aiActorOf(adapterId: string): string {
242
+ const id = String(adapterId).replace(/[^A-Za-z0-9_.:@+-]/gu, '_').slice(0, ACTOR_MAX - 'ai:'.length);
243
+ return `ai:${id === '' ? 'adapter' : id}`;
244
+ }
245
+
246
+ const REQUIRED_STORE_METHODS = [
247
+ 'reserveAiRead',
248
+ 'completeAiRead',
249
+ 'failAiRead',
250
+ 'loadAiRead',
251
+ 'loadAiReads',
252
+ 'loadAiReadById',
253
+ 'loadAiReadFor',
254
+ 'listAiRetries',
255
+ 'aiSpendSince',
256
+ 'insertAiOutcome',
257
+ 'loadAiOutcome',
258
+ 'markAiOutcome',
259
+ 'aiExamples',
260
+ 'aiTeachableCount',
261
+ 'aiStats',
262
+ ] as const;
263
+
264
+ /** The store, typed with its AI methods; throws a plain error when it has not got them. */
265
+ export function requireAiStore(store: Store): AiStore {
266
+ const missing = REQUIRED_STORE_METHODS.filter((m) => typeof (store as unknown as Record<string, unknown>)[m] !== 'function');
267
+ if (missing.length > 0) {
268
+ throw new Error(`createChatwarden: the AI needs a store with the AI methods (${missing.join(', ')}); use the memory or SQLite store, or leave the "ai" option out`);
269
+ }
270
+ return store as AiStore;
271
+ }
272
+
273
+ /**
274
+ * Check the AI option before anything is started (throws a plain error for a bad one) and name the AI methods the store lacks. A store that
275
+ * lacks some leaves the AI inert: `createChatwarden` says so once and carries on, as it does for any optional Store method.
276
+ */
277
+ export function checkAiSetup(store: Store, options: AiOptions): string[] {
278
+ checkOptions(options);
279
+ return REQUIRED_STORE_METHODS.filter((m) => typeof (store as unknown as Record<string, unknown>)[m] !== 'function');
280
+ }
281
+
282
+ function checkOptions(o: AiOptions): Required<Omit<AiOptions, 'adapter' | 'contextTags'>> & { contextTags: string[] } {
283
+ const a: unknown = o?.adapter;
284
+ if (typeof a !== 'object' || a === null || typeof (a as ModerationAI).id !== 'string' || (a as ModerationAI).id === '' || typeof (a as ModerationAI).read !== 'function') {
285
+ throw new TypeError('createChatwarden: ai.adapter must be a ModerationAI ({ id, read })');
286
+ }
287
+ const maxLevel = o.maxLevel ?? DEFAULTS.maxLevel;
288
+ if (maxLevel !== 1 && maxLevel !== 2) throw new RangeError('createChatwarden: ai.maxLevel must be 1 or 2');
289
+ const whole = (v: unknown, name: string, min: number): number => {
290
+ if (typeof v !== 'number' || !Number.isFinite(v) || !Number.isInteger(v) || v < min) throw new RangeError(`createChatwarden: ai.${name} must be a whole number of at least ${min}`);
291
+ return v;
292
+ };
293
+ const dailyBudgetMicros = whole(o.dailyBudgetMicros ?? DEFAULTS.dailyBudgetMicros, 'dailyBudgetMicros', 0);
294
+ const perMinuteCalls = whole(o.perMinuteCalls ?? DEFAULTS.perMinuteCalls, 'perMinuteCalls', 1);
295
+ const concurrency = whole(o.concurrency ?? DEFAULTS.concurrency, 'concurrency', 1);
296
+ const timeoutMs = whole(o.timeoutMs ?? DEFAULTS.timeoutMs, 'timeoutMs', 1);
297
+ const blockedLines = o.blockedLines ?? 'raw';
298
+ if (blockedLines !== 'raw' && blockedLines !== 'mask') throw new RangeError("createChatwarden: ai.blockedLines must be 'raw' or 'mask'");
299
+ const contextTags = o.contextTags ?? [];
300
+ if (!Array.isArray(contextTags) || contextTags.some((t) => typeof t !== 'string')) throw new TypeError('createChatwarden: ai.contextTags must be a list of strings');
301
+ return { maxLevel, dailyBudgetMicros, perMinuteCalls, concurrency, timeoutMs, blockedLines, contextTags: [...contextTags] };
302
+ }
303
+
304
+ /** What the service needs from the kit around it. */
305
+ export interface AiServiceDeps {
306
+ options: AiOptions;
307
+ store: Store;
308
+ clock: Clock;
309
+ logger: Logger | undefined;
310
+ /** The profile in force now (never kept across calls). */
311
+ profile: () => ResolvedProfile;
312
+ rules: CommunityRules;
313
+ /** `cw.suggest`. */
314
+ suggest: (subject: SubjectId, level: ConductLevel | null, rule: RuleRef, ctx: { roomId: string | null }) => Suggestion;
315
+ subscribe: Subscribe;
316
+ /** `cw.audit.record`. */
317
+ audit: (input: AuditRecordInput) => boolean;
318
+ /** How long the text of a casebook example is kept (`retention.aiExamplesMs`); 0 keeps none. */
319
+ exampleRetentionMs: () => number;
320
+ }
321
+
322
+ const ruleOfText = (rule: string | null): number | 'uncovered' | null => (rule === null ? null : /^\d+$/.test(rule) ? Number(rule) : rule === 'uncovered' ? 'uncovered' : null);
323
+
324
+ /** A suggestion's outcome as a step: a note, a warning or a restriction; none is no step. */
325
+ function stepOf(s: Suggestion): SuggestionStep | null {
326
+ const o = s.outcome;
327
+ if (o === 'none') return null;
328
+ if (o === 'note' || o === 'warning') return { kind: o, durationMs: null, label: s.label };
329
+ return { kind: o.kind, durationMs: o.durationMs, label: s.label };
330
+ }
331
+
332
+ export class AiService implements AiFacade {
333
+ protected readonly store: AiStore;
334
+ protected readonly clock: Clock;
335
+ protected readonly adapter: ModerationAI;
336
+ protected readonly actor: string;
337
+ protected readonly opts: ReturnType<typeof checkOptions>;
338
+ protected readonly meter = new Meter();
339
+ protected readonly breaker: Breaker;
340
+ protected readonly window: CallWindow;
341
+
342
+ private readonly queue: string[] = [];
343
+ private readonly queued = new Set<string>();
344
+ private readonly running = new Map<string, { dirty: boolean }>();
345
+ private readonly parked = new Map<string, number>();
346
+ private readonly retakes = new Set<string>();
347
+ private readonly controllers = new Set<{ abort(): void }>();
348
+ private readonly cache = new Map<string, Prepared>();
349
+ private readonly asked = new Map<string, number[]>();
350
+ private pumpTimer: ReturnType<typeof setTimeout> | undefined;
351
+ private sweepTimer: ReturnType<typeof setInterval> | undefined;
352
+ private unsubscribe: (() => void) | undefined;
353
+ private waiters: Array<() => void> = [];
354
+ private policyText: { profile: ResolvedProfile; text: string } | null = null;
355
+ private lastStable = '';
356
+ private stableKey = '';
357
+ private isClosed = false;
358
+
359
+ protected readonly deps: AiServiceDeps;
360
+
361
+ constructor(deps: AiServiceDeps) {
362
+ this.deps = deps;
363
+ this.store = requireAiStore(deps.store);
364
+ this.clock = deps.clock;
365
+ this.opts = checkOptions(deps.options);
366
+ this.adapter = deps.options.adapter;
367
+ this.actor = aiActorOf(this.adapter.id);
368
+ this.breaker = new Breaker(deps.clock);
369
+ this.window = new CallWindow(this.opts.perMinuteCalls);
370
+ // Only enqueue: no await, no store read, so the player's ack never waits for the AI.
371
+ this.unsubscribe = deps.subscribe('report.created', (e) => {
372
+ this.enqueue(e.reportId);
373
+ });
374
+ this.sweepTimer = setInterval(() => void this.sweep(), SWEEP_EVERY_MS);
375
+ (this.sweepTimer as { unref?: () => void }).unref?.();
376
+ }
377
+
378
+ // --- the facade ------------------------------------------------------------------------------------------------------------
379
+
380
+ level(): 0 | 1 | 2 {
381
+ try {
382
+ return Math.min(this.deps.profile().ai.level, this.opts.maxLevel) as 0 | 1 | 2;
383
+ } catch (err) {
384
+ this.warn('ai.level_failed', err);
385
+ return 0;
386
+ }
387
+ }
388
+
389
+ status(): AiStatus {
390
+ const level = this.level();
391
+ let spent = { micros: 0, calls: 0 };
392
+ try {
393
+ spent = this.store.aiSpendSince(startOfUtcDay(this.clock.now()));
394
+ } catch (err) {
395
+ this.warn('ai.status_failed', err);
396
+ }
397
+ const cap = this.opts.dailyBudgetMicros;
398
+ const capCalls = this.dailyCalls();
399
+ let state: AiStatus['state'] = 'ok';
400
+ if (level === 0) state = 'off';
401
+ else if (this.breaker.state() !== 'closed') state = 'unavailable';
402
+ else if (spent.micros >= cap || spent.calls >= capCalls) state = 'paused_budget';
403
+ return {
404
+ available: true,
405
+ level,
406
+ maxLevel: this.opts.maxLevel,
407
+ state,
408
+ spentMicros: spent.micros,
409
+ capMicros: cap,
410
+ capCalls,
411
+ day: utcDayLabel(this.clock.now()),
412
+ reads: spent.calls,
413
+ cacheHitRate: this.meter.cacheHitRate(),
414
+ invalid: { ...this.meter.invalid },
415
+ };
416
+ }
417
+
418
+ read(reportId: string, o?: { open?: boolean }): AiReadView | null {
419
+ try {
420
+ const level = this.level();
421
+ if (level === 0 || typeof reportId !== 'string') return null;
422
+ const report = this.store.loadReport(reportId);
423
+ if (report === null) return null;
424
+ const row = this.store.loadAiRead(reportId);
425
+ const open = o?.open === true && report.status === 'open';
426
+ if (row === null || row.read === null) {
427
+ if (open) this.enqueue(reportId);
428
+ return null;
429
+ }
430
+ const prepared = this.prepare(report);
431
+ const view = this.view(row, report, prepared, level);
432
+ if (open && view.stale) this.enqueue(reportId);
433
+ return view;
434
+ } catch (err) {
435
+ this.warn('ai.read_view_failed', err);
436
+ return null;
437
+ }
438
+ }
439
+
440
+ expected(reportId: string): boolean {
441
+ try {
442
+ if (this.level() === 0 || typeof reportId !== 'string') return false;
443
+ if (this.status().state !== 'ok') return false;
444
+ const report = this.store.loadReport(reportId);
445
+ if (report === null || report.status !== 'open') return false;
446
+ const own = this.store.loadAiReadFor(reportId, this.prepare(report).hash);
447
+ return !(own !== null && isFinalRow(own));
448
+ } catch (err) {
449
+ this.warn('ai.expected_failed', err);
450
+ return false;
451
+ }
452
+ }
453
+
454
+ readAgain(reportId: string, actor: string): Promise<AiReadAgain> {
455
+ try {
456
+ const level = this.level();
457
+ if (level === 0 || typeof reportId !== 'string') return Promise.resolve('off');
458
+ const report = this.store.loadReport(reportId);
459
+ if (report === null || report.status !== 'open') return Promise.resolve('off');
460
+ if (!this.allowAsk(actor)) return Promise.resolve('rate');
461
+ const prepared = this.prepare(report);
462
+ const row = this.store.loadAiRead(reportId);
463
+ if (row !== null && row.read !== null && row.inputHash === prepared.hash) return Promise.resolve(this.view(row, report, prepared, level));
464
+ const own = this.store.loadAiReadFor(reportId, prepared.hash);
465
+ const now = this.clock.now();
466
+ const today = this.store.aiSpendSince(startOfUtcDay(now));
467
+ if (today.micros >= this.opts.dailyBudgetMicros || today.calls >= this.dailyCalls()) return Promise.resolve('budget');
468
+ // Nothing can be called now: say so, with the wait, rather than queue a job that cannot run.
469
+ if (!this.breaker.available()) {
470
+ const reopens = this.breaker.reopensAt() ?? now;
471
+ return Promise.resolve({ unavailable: { retryAfterMs: Math.max(1000, reopens - now) } });
472
+ }
473
+ if (!this.window.peek(now)) return Promise.resolve({ unavailable: { retryAfterMs: Math.max(1000, this.window.nextFree(now) - now) } });
474
+ // A moderator's explicit ask retakes a FINAL row (one that ended without an answer and will not be tried again by itself) once;
475
+ // the store keeps that on the row, so asking again has nothing left to try, whichever process or restart comes between. A row
476
+ // still waiting for its own retry is not retaken: the ask just makes sure it is queued, and the call waits for its time.
477
+ if (own !== null && isFinalRow(own)) {
478
+ if (own.retaken) return Promise.resolve('final');
479
+ this.retakes.add(reportId);
480
+ } else if (own?.status === 'skipped') {
481
+ // A skipped read made no call: the ask takes it now instead of at its retry time (the caps were checked above).
482
+ this.retakes.add(reportId);
483
+ }
484
+ this.enqueue(reportId, { force: true });
485
+ return Promise.resolve('pending');
486
+ } catch (err) {
487
+ this.warn('ai.read_again_failed', err);
488
+ return Promise.resolve('off');
489
+ }
490
+ }
491
+
492
+ /** A sliding minute per actor. Held in memory: it guards the provider's bill from one eager hand, not a security boundary. */
493
+ private allowAsk(actor: string): boolean {
494
+ const now = this.clock.now();
495
+ const key = String(actor);
496
+ const recent = (this.asked.get(key) ?? []).filter((t) => t > now - 60_000);
497
+ if (recent.length >= READ_AGAIN_PER_MINUTE) {
498
+ this.asked.set(key, recent);
499
+ return false;
500
+ }
501
+ recent.push(now);
502
+ this.asked.set(key, recent);
503
+ if (this.asked.size > 1000) this.asked.delete(this.asked.keys().next().value as string);
504
+ return true;
505
+ }
506
+
507
+ briefs(reportIds: readonly string[]): Map<string, AiBrief> {
508
+ const out = new Map<string, AiBrief>();
509
+ try {
510
+ const level = this.level();
511
+ if (level === 0 || !Array.isArray(reportIds) || reportIds.length === 0) return out;
512
+ for (const row of this.store.loadAiReads(reportIds)) {
513
+ const read = row.read;
514
+ if (read === null) continue;
515
+ const report = this.store.loadReport(row.reportId);
516
+ if (report === null) continue;
517
+ const rec = read.recommendation;
518
+ out.set(row.reportId, {
519
+ severity: read.severity,
520
+ confidence: read.confidence,
521
+ rule: read.rule,
522
+ stale: this.prepare(report).hash !== row.inputHash,
523
+ injectionSuspected: read.injectionSuspected,
524
+ hasRecommendation: level >= 2 && rec !== null && rec.verdict !== 'unclear',
525
+ });
526
+ }
527
+ } catch (err) {
528
+ this.warn('ai.briefs_failed', err);
529
+ return new Map();
530
+ }
531
+ return out;
532
+ }
533
+
534
+ stats(q?: { since?: number }): AiStatsView {
535
+ const since = typeof q?.since === 'number' && Number.isFinite(q.since) ? q.since : this.clock.now() - STATS_DEFAULT_WINDOW_MS;
536
+ try {
537
+ const rows = this.store.aiStats(since);
538
+ const view = emptyStats(since);
539
+ for (const r of rows) {
540
+ view.decided += r.decided;
541
+ view.agree += r.agree;
542
+ view.override += r.override;
543
+ view.none += r.none;
544
+ view.falsePositives += r.falsePositives;
545
+ view.oneClick += r.oneClick;
546
+ view.rules.push({ rule: ruleOfText(r.rule), decided: r.decided, agree: r.agree, override: r.override, none: r.none, falsePositives: r.falsePositives, oneClick: r.oneClick });
547
+ }
548
+ const shown = view.agree + view.override;
549
+ view.agreementRate = shown === 0 ? null : view.agree / shown;
550
+ view.falsePositiveRate = shown === 0 ? null : view.falsePositives / shown;
551
+ view.oneClickRate = shown === 0 ? null : view.oneClick / shown;
552
+ return view;
553
+ } catch (err) {
554
+ this.warn('ai.stats_failed', err);
555
+ return emptyStats(since);
556
+ }
557
+ }
558
+
559
+ markReversed(reportId: string): boolean {
560
+ return this.mark(reportId, { reversed: true });
561
+ }
562
+
563
+ dontTeach(reportId: string): boolean {
564
+ return this.mark(reportId, { dontTeach: true });
565
+ }
566
+
567
+ private mark(reportId: string, patch: { reversed?: true; dontTeach?: true }): boolean {
568
+ try {
569
+ return typeof reportId === 'string' && this.store.markAiOutcome(reportId, patch);
570
+ } catch (err) {
571
+ this.warn('ai.mark_failed', err);
572
+ return false;
573
+ }
574
+ }
575
+
576
+ idle(): Promise<void> {
577
+ if (this.isIdle()) return Promise.resolve();
578
+ return new Promise<void>((resolve) => void this.waiters.push(resolve));
579
+ }
580
+
581
+ close(): void {
582
+ this.isClosed = true;
583
+ if (this.sweepTimer !== undefined) clearInterval(this.sweepTimer);
584
+ this.sweepTimer = undefined;
585
+ if (this.pumpTimer !== undefined) clearTimeout(this.pumpTimer);
586
+ this.pumpTimer = undefined;
587
+ this.unsubscribe?.();
588
+ this.unsubscribe = undefined;
589
+ this.queue.length = 0;
590
+ this.queued.clear();
591
+ for (const c of this.controllers) c.abort();
592
+ this.settleIdle();
593
+ }
594
+
595
+ // --- the queue -------------------------------------------------------------------------------------------------------------
596
+
597
+ /**
598
+ * Put a report on the queue. Synchronous and cheap: no store read, no await. Does nothing at level 0. `force` is for a case that
599
+ * changed or was asked for (it forgets any wait the sweeper was keeping).
600
+ */
601
+ enqueue(reportId: string, o?: { force?: boolean }): boolean {
602
+ try {
603
+ if (this.isClosed || typeof reportId !== 'string' || this.level() === 0) return false;
604
+ if (o?.force === true) this.parked.delete(reportId);
605
+ const job = this.running.get(reportId);
606
+ if (job !== undefined) {
607
+ // A change arrived while it was being read: read once more when this one ends.
608
+ job.dirty = true;
609
+ return false;
610
+ }
611
+ if (this.queued.has(reportId)) return false;
612
+ this.queued.add(reportId);
613
+ this.queue.push(reportId);
614
+ this.schedulePump();
615
+ return true;
616
+ } catch (err) {
617
+ this.warn('ai.enqueue_failed', err);
618
+ return false;
619
+ }
620
+ }
621
+
622
+ /** The reporter's follow-up changed the case: read it again once. Called by the facade's `reports.addDetail`. */
623
+ caseChanged(reportId: string): void {
624
+ this.enqueue(reportId, { force: true });
625
+ }
626
+
627
+ private schedulePump(): void {
628
+ if (this.pumpTimer !== undefined || this.isClosed) return;
629
+ this.pumpTimer = setTimeout(() => {
630
+ this.pumpTimer = undefined;
631
+ this.pump();
632
+ }, 0);
633
+ (this.pumpTimer as { unref?: () => void }).unref?.();
634
+ }
635
+
636
+ private pump(): void {
637
+ while (!this.isClosed && this.running.size < this.opts.concurrency && this.queue.length > 0) {
638
+ const id = this.queue.shift() as string;
639
+ this.queued.delete(id);
640
+ this.running.set(id, { dirty: false });
641
+ void this.runOne(id);
642
+ }
643
+ this.settleIdle();
644
+ }
645
+
646
+ private async runOne(id: string): Promise<void> {
647
+ try {
648
+ const retake = this.retakes.delete(id);
649
+ const end: ReadEnd = await runRead(this.env(), id, retake ? { retake: true } : undefined);
650
+ if (end.park !== null) this.park(id, end.park);
651
+ else this.parked.delete(id);
652
+ } catch (err) {
653
+ this.warn('ai.job_failed', err);
654
+ } finally {
655
+ const job = this.running.get(id);
656
+ this.running.delete(id);
657
+ if (job?.dirty === true && !this.isClosed) this.enqueue(id, { force: true });
658
+ this.pump();
659
+ }
660
+ }
661
+
662
+ /** Remember not to queue `reportId` before `until`. Bounded: the oldest entry goes when the list is full. */
663
+ private park(reportId: string, until: number): void {
664
+ this.parked.delete(reportId);
665
+ if (this.parked.size >= PARKED_MAX) this.parked.delete(this.parked.keys().next().value as string);
666
+ this.parked.set(reportId, until);
667
+ }
668
+
669
+ /** How many reports the sweeper is holding back (tests). */
670
+ parkedSize(): number {
671
+ return this.parked.size;
672
+ }
673
+
674
+ private isIdle(): boolean {
675
+ return this.queue.length === 0 && this.running.size === 0 && this.pumpTimer === undefined;
676
+ }
677
+
678
+ private settleIdle(): void {
679
+ if (!this.isIdle()) return;
680
+ const waiting = this.waiters;
681
+ this.waiters = [];
682
+ for (const resolve of waiting) resolve();
683
+ }
684
+
685
+ // --- the sweeper -----------------------------------------------------------------------------------------------------------
686
+
687
+ async sweep(): Promise<void> {
688
+ try {
689
+ if (this.isClosed || this.level() === 0 || !this.breaker.available()) return;
690
+ const now = this.clock.now();
691
+ const quiet = this.isIdle();
692
+ let added = 0;
693
+ const room = (): number => SWEEP_BATCH - added;
694
+
695
+ // 1. Reads whose retry has come, and reads whose owner died.
696
+ for (const row of this.store.listAiRetries(now, 200)) {
697
+ if (room() <= 0) break;
698
+ const report = this.store.loadReport(row.reportId);
699
+ if (report === null || report.status !== 'open' || this.prepare(report).hash !== row.inputHash) continue;
700
+ if (this.enqueue(row.reportId, { force: true })) added += 1;
701
+ }
702
+
703
+ // 2. Open reports with no usable read, newest first.
704
+ const page = this.store.listReports({ status: 'open', limit: SWEEP_SCAN });
705
+ const ids = page.map((r) => r.id);
706
+ const read = new Map(this.store.loadAiReads(ids).map((r) => [r.reportId, r]));
707
+ // Forget what is held back for reports that are decided or no longer open: the list only keeps the live ones.
708
+ const open = new Set(ids);
709
+ for (const id of [...this.parked.keys()]) if (!open.has(id)) this.parked.delete(id);
710
+ for (const report of page) {
711
+ if (room() <= 0) break;
712
+ if (read.has(report.id) || this.isParked(report.id, now)) continue;
713
+ if (this.enqueue(report.id)) added += 1;
714
+ }
715
+
716
+ // 3. When there is nothing new, bring a few stale reads up to date (rules or case changed), at the pace of the budget.
717
+ if (added === 0 && quiet) {
718
+ let stale = 0;
719
+ for (const report of page) {
720
+ if (stale >= STALE_PER_SWEEP) break;
721
+ const row = read.get(report.id);
722
+ if (row === undefined || this.isParked(report.id, now)) continue;
723
+ if (this.prepare(report).hash !== row.inputHash && this.enqueue(report.id)) stale += 1;
724
+ }
725
+ }
726
+ } catch (err) {
727
+ this.warn('ai.sweep_failed', err);
728
+ }
729
+ }
730
+
731
+ private isParked(reportId: string, now: number): boolean {
732
+ const until = this.parked.get(reportId);
733
+ return until !== undefined && until > now;
734
+ }
735
+
736
+ // --- views -----------------------------------------------------------------------------------------------------------------
737
+
738
+ /** A report made ready for a read, cached by what it is made from. */
739
+ protected prepare(report: ReportRecord): Prepared {
740
+ const profile = this.deps.profile();
741
+ const policy = { profile, rules: this.deps.rules };
742
+ // The text is rendered once per profile in force (the resolved profile is deep-frozen and replaced, never edited, on a change; the rules
743
+ // are fixed for the kit's life): a queue poll asks about 200 reports and each call would otherwise validate and render the policy again.
744
+ let stable: string;
745
+ if (this.policyText !== null && this.policyText.profile === profile) stable = this.policyText.text;
746
+ else {
747
+ stable = aiPolicyText(policy);
748
+ this.policyText = { profile, text: stable };
749
+ }
750
+ if (stable !== this.lastStable) {
751
+ // The rules, the level meanings or the standard changed: what was waiting for a retry may now read differently.
752
+ this.lastStable = stable;
753
+ this.stableKey = sha256Hex(stable);
754
+ this.parked.clear();
755
+ }
756
+ const reasons = profile.reporting.reasons;
757
+ const label = report.reportedReason === null || report.reportedReason === undefined ? '' : (reasons.find((r) => r.id === report.reportedReason)?.label ?? '');
758
+ const key = [report.id, report.detailAt ?? 0, this.stableKey, label].join('|');
759
+ const hit = this.cache.get(key);
760
+ if (hit !== undefined) return hit;
761
+ const made = prepareCase({ report, policy, reasons, adapterId: this.adapter.id, mask: this.opts.blockedLines === 'mask' });
762
+ if (this.cache.size >= PREPARED_CACHE_MAX) this.cache.delete(this.cache.keys().next().value as string);
763
+ this.cache.set(key, made);
764
+ return made;
765
+ }
766
+
767
+ private view(row: { id: string; read: AIRead | null; inputHash: string; model: string | null; createdAt: number }, report: ReportRecord, prepared: Prepared, level: number): AiReadView {
768
+ const read = row.read as AIRead;
769
+ const rec = read.recommendation;
770
+ return {
771
+ id: row.id,
772
+ severity: read.severity,
773
+ rule: read.rule,
774
+ summary: read.summary,
775
+ evidenceLineIds: [...read.evidence],
776
+ confidence: read.confidence,
777
+ stale: row.inputHash !== prepared.hash,
778
+ injectionSuspected: read.injectionSuspected,
779
+ model: row.model,
780
+ at: row.createdAt,
781
+ recommendation: level >= 2 && rec !== null ? { verdict: rec.verdict, severity: rec.severity, rule: rec.rule, evidenceLineIds: [...rec.evidence], ...this.stepFor(report, prepared, rec) } : null,
782
+ };
783
+ }
784
+
785
+ /** The step the ladder gives for the recommendation, and whether it is within the ceilings. */
786
+ private stepFor(report: ReportRecord, prepared: Prepared, rec: NonNullable<AIRead['recommendation']>): { step: SuggestionStep | null; stepWithinCeiling: boolean } {
787
+ if (rec.verdict === 'no_action' || rec.verdict === 'unclear') return { step: null, stepWithinCeiling: true };
788
+ try {
789
+ const profile = this.deps.profile();
790
+ const ruleRef = typeof rec.rule === 'number' ? rec.rule : suggestedRule(profile.reporting.reasons, report.reportedReason ?? null, this.deps.rules);
791
+ const step =
792
+ rec.verdict === 'noted'
793
+ ? ({ kind: 'note', durationMs: null, label: 'Note' } satisfies SuggestionStep)
794
+ : stepOf(this.deps.suggest(report.targetSubject, rec.severity, ruleRef, { roomId: report.roomId === '' ? null : report.roomId }));
795
+ if (step === null) return { step: null, stepWithinCeiling: true };
796
+ try {
797
+ assertWithinCeilings(step, { cited: rec.evidence, ownRefs: prepared.ownLineIds });
798
+ return { step, stepWithinCeiling: true };
799
+ } catch (err) {
800
+ if (!(err instanceof AICeilingError)) throw err;
801
+ return { step, stepWithinCeiling: false };
802
+ }
803
+ } catch (err) {
804
+ this.warn('ai.step_failed', err);
805
+ return { step: null, stepWithinCeiling: false };
806
+ }
807
+ }
808
+
809
+ // --- the worker's environment ----------------------------------------------------------------------------------------------
810
+
811
+ private env(): WorkerEnv {
812
+ return {
813
+ store: this.store,
814
+ clock: this.clock,
815
+ adapter: this.adapter,
816
+ timeoutMs: this.opts.timeoutMs,
817
+ capMicros: this.opts.dailyBudgetMicros,
818
+ breaker: this.breaker,
819
+ window: this.window,
820
+ meter: this.meter,
821
+ level: () => this.level(),
822
+ dailyCalls: () => this.dailyCalls(),
823
+ closed: () => this.isClosed,
824
+ prepare: (report) => this.prepare(report),
825
+ examplesFor: (report, prepared) => this.examplesFor(report, prepared),
826
+ track: (c) => void this.controllers.add(c),
827
+ untrack: (c) => void this.controllers.delete(c),
828
+ auditRead: (reportId) => {
829
+ try {
830
+ this.deps.audit({ actor: this.actor, role: null, action: 'ai.read', target: { type: 'report', ref: reportId } });
831
+ } catch (err) {
832
+ this.warn('ai.audit_failed', err);
833
+ }
834
+ },
835
+ warn: (event, detail) => safeWarn(this.deps.logger, event, detail),
836
+ };
837
+ }
838
+
839
+ /**
840
+ * Casebook examples for a read: none unless learning is on, example text is kept at all, the case names a reason that maps to a rule,
841
+ * and at least 30 teachable decisions exist. Then the two newest of that rule at the conduct level the AI gave this report before
842
+ * (or, for a first read, at any level), newest first. Each is pseudonymised already; the row's report id is its id.
843
+ */
844
+ protected examplesFor(report: ReportRecord, prepared: Prepared): AIExampleInput[] {
845
+ void prepared;
846
+ const profile = this.deps.profile();
847
+ const keepMs = this.deps.exampleRetentionMs();
848
+ if (!profile.ai.learn || !(keepMs > 0)) return [];
849
+ const rule = suggestedRule(profile.reporting.reasons, report.reportedReason ?? null, this.deps.rules);
850
+ if (typeof rule !== 'number') return [];
851
+ const since = this.clock.now() - keepMs;
852
+ if (this.store.aiTeachableCount(since) < AI_EXAMPLES_MIN) return [];
853
+ const known = this.store.loadAiRead(report.id)?.read?.severity;
854
+ const levels: readonly ConductLevel[] = known === undefined ? CONDUCT_LEVELS : [known];
855
+ return levels
856
+ .flatMap((level) => this.store.aiExamples(String(rule), level, 2, since))
857
+ .sort((a, b) => b.decidedAt - a.decidedAt || (a.reportId < b.reportId ? 1 : -1))
858
+ .slice(0, 2)
859
+ .map((row): AIExampleInput => ({ ...row.example, id: row.reportId }));
860
+ }
861
+
862
+ // --- the casebook ----------------------------------------------------------------------------------------------------------
863
+
864
+ /**
865
+ * The casebook row for a decision (the hook `DecisionService` calls inside its transaction), computed here from the stored read and
866
+ * the decision. The server always records it when a read exists at level 1 or 2, whichever way the decision came (the hub, `cw.decide`,
867
+ * a webhook, a bulk dismissal); the echo, when there is one, only names the read the moderator saw, says whether they clicked accept
868
+ * (kept only when the decision is the pre-fill) and gives the conduct level of their form (kept only when it fits the verdict).
869
+ * With no echo there is no example text. Null at level 0 and when the report has no read. Fenced by the caller.
870
+ */
871
+ outcomeOf(args: AiOutcomeArgs): AiOutcomeInsert | null {
872
+ const level = this.level();
873
+ if (level === 0) return null;
874
+ const { report, verdict, ai } = args;
875
+ // The read the moderator saw when the echo names one of this report's finished reads, else the newest.
876
+ const named = ai.readId === null ? null : this.store.loadAiReadById(ai.readId);
877
+ const row: AiReadRow | null = named !== null && named.reportId === report.id && named.status === 'ok' && named.read !== null ? named : this.store.loadAiRead(report.id);
878
+ if (row === null) return null;
879
+ const read = row.read;
880
+ const rec = read?.recommendation ?? null;
881
+ const own = actionsOnTarget(args.actions, args.target);
882
+
883
+ // What the ladder would have pre-filled for the AI's conduct level: the step the human's is compared with.
884
+ let prefill: StepLike | null = null;
885
+ if (level >= 2 && rec !== null && (rec.verdict === 'upheld' || rec.verdict === 'noted')) {
886
+ const step = this.stepFor(report, this.prepare(report), rec).step;
887
+ prefill = step === null ? null : { kind: step.kind, durationMs: step.durationMs };
888
+ }
889
+ const verdictClass: AiVerdict = verdict === 'bad_faith' ? 'no_action' : verdict;
890
+ const result = agreementOf(
891
+ read,
892
+ { verdict, rule: own.rule, lineIds: own.lineIds, step: own.step, prefill, others: own.others, oneClick: ai.accepted },
893
+ level,
894
+ );
895
+
896
+ // The conduct level the human settled on: their form's when it fits the verdict (a dismissal carries none; an action is not
897
+ // banter), else the AI's on an agreement, else banter for a dismissal.
898
+ const claimed = verdict === 'upheld' || verdict === 'noted' ? (ai.severity !== null && ai.severity !== 'banter' ? ai.severity : null) : null;
899
+ const severity: ConductLevel | null =
900
+ claimed ?? (result.agreement === 'agree' && rec !== null ? rec.severity : verdict === 'no_action' ? 'banter' : null);
901
+ const badFaith = verdict === 'bad_faith';
902
+ // The row is filed under the rule the human cited; a dismissal cites none, so it goes under the rule the AI cited (that is where its
903
+ // false positive belongs), else the rule of the reporter's reason.
904
+ const reasonRule = suggestedRule(this.deps.profile().reporting.reasons, report.reportedReason ?? null, this.deps.rules);
905
+ const filedUnder: number | 'uncovered' | null = own.rule ?? rec?.rule ?? read?.rule ?? (typeof reasonRule === 'number' ? reasonRule : null);
906
+
907
+ const profile = this.deps.profile();
908
+ const teachable =
909
+ ai.readId !== null &&
910
+ (result.agreement === 'agree' || result.agreement === 'override') &&
911
+ !badFaith &&
912
+ profile.ai.learn &&
913
+ this.deps.exampleRetentionMs() > 0 &&
914
+ severity !== null &&
915
+ own.rule !== null;
916
+ let example: AiOutcomeInsert['example'] = null;
917
+ // A case whose read flagged an injection, or whose chat tripped the tripwire, is never taught: its lines would be replayed into later prompts.
918
+ const injected = read?.injectionSuspected === true || this.prepare(report).injection;
919
+ if (teachable && !injected && severity !== null && own.rule !== null) {
920
+ const cited = new Set([...own.lineIds, ...(rec?.evidence ?? []), ...(read?.evidence ?? [])]);
921
+ const lines = pickExampleLines(this.prepare(report).chosen, cited);
922
+ if (lines.length > 0) example = { rule: own.rule, severity, verdict: verdictClass, lines };
923
+ }
924
+
925
+ return {
926
+ reportId: report.id,
927
+ readId: row.id,
928
+ decidedAt: args.now,
929
+ level,
930
+ verdict: verdictClass,
931
+ rule: filedUnder === null ? null : String(filedUnder),
932
+ severity,
933
+ aiVerdict: result.aiVerdict,
934
+ agreement: result.agreement,
935
+ detail: result.detail,
936
+ badFaith,
937
+ example,
938
+ };
939
+ }
940
+
941
+ /** The owner's most calls in a UTC day, read live from the profile. */
942
+ private dailyCalls(): number {
943
+ try {
944
+ return this.deps.profile().ai.dailyCalls;
945
+ } catch (err) {
946
+ this.warn('ai.level_failed', err);
947
+ return AI_DAILY_CALLS_DEFAULT;
948
+ }
949
+ }
950
+
951
+ protected warn(event: string, err: unknown): void {
952
+ safeWarn(this.deps.logger, event, { error: errorClass(err) });
953
+ }
954
+ }
955
+