@chatwarden/core 0.1.0 → 0.1.2

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 (105) hide show
  1. package/README.md +202 -6
  2. package/dist/src/audit.d.ts +27 -5
  3. package/dist/src/audit.d.ts.map +1 -1
  4. package/dist/src/audit.js +59 -8
  5. package/dist/src/audit.js.map +1 -1
  6. package/dist/src/chat.d.ts +48 -0
  7. package/dist/src/chat.d.ts.map +1 -1
  8. package/dist/src/chat.js +94 -10
  9. package/dist/src/chat.js.map +1 -1
  10. package/dist/src/chatwarden.d.ts +209 -12
  11. package/dist/src/chatwarden.d.ts.map +1 -1
  12. package/dist/src/chatwarden.js +77 -11
  13. package/dist/src/chatwarden.js.map +1 -1
  14. package/dist/src/crypto.d.ts +22 -0
  15. package/dist/src/crypto.d.ts.map +1 -0
  16. package/dist/src/crypto.js +193 -0
  17. package/dist/src/crypto.js.map +1 -0
  18. package/dist/src/decide.d.ts.map +1 -1
  19. package/dist/src/decide.js +2 -4
  20. package/dist/src/decide.js.map +1 -1
  21. package/dist/src/documents.d.ts +12 -2
  22. package/dist/src/documents.d.ts.map +1 -1
  23. package/dist/src/documents.js +56 -34
  24. package/dist/src/documents.js.map +1 -1
  25. package/dist/src/events.d.ts +3 -0
  26. package/dist/src/events.d.ts.map +1 -1
  27. package/dist/src/events.js.map +1 -1
  28. package/dist/src/hasher.js +2 -2
  29. package/dist/src/hasher.js.map +1 -1
  30. package/dist/src/index.d.ts +21 -12
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +11 -6
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/ladder.d.ts +2 -0
  35. package/dist/src/ladder.d.ts.map +1 -1
  36. package/dist/src/ladder.js +1 -1
  37. package/dist/src/ladder.js.map +1 -1
  38. package/dist/src/log.d.ts +16 -0
  39. package/dist/src/log.d.ts.map +1 -1
  40. package/dist/src/log.js +34 -0
  41. package/dist/src/log.js.map +1 -1
  42. package/dist/src/notices.js +2 -2
  43. package/dist/src/notices.js.map +1 -1
  44. package/dist/src/policy.d.ts +129 -0
  45. package/dist/src/policy.d.ts.map +1 -0
  46. package/dist/src/policy.js +242 -0
  47. package/dist/src/policy.js.map +1 -0
  48. package/dist/src/profile.d.ts +120 -7
  49. package/dist/src/profile.d.ts.map +1 -1
  50. package/dist/src/profile.js +295 -7
  51. package/dist/src/profile.js.map +1 -1
  52. package/dist/src/reporting.d.ts +127 -0
  53. package/dist/src/reporting.d.ts.map +1 -0
  54. package/dist/src/reporting.js +172 -0
  55. package/dist/src/reporting.js.map +1 -0
  56. package/dist/src/reports.d.ts +80 -4
  57. package/dist/src/reports.d.ts.map +1 -1
  58. package/dist/src/reports.js +122 -8
  59. package/dist/src/reports.js.map +1 -1
  60. package/dist/src/sanctions.js +3 -3
  61. package/dist/src/sanctions.js.map +1 -1
  62. package/dist/src/staffReports.d.ts +17 -5
  63. package/dist/src/staffReports.d.ts.map +1 -1
  64. package/dist/src/staffReports.js +22 -5
  65. package/dist/src/staffReports.js.map +1 -1
  66. package/dist/src/staffViews.d.ts +138 -0
  67. package/dist/src/staffViews.d.ts.map +1 -0
  68. package/dist/src/staffViews.js +205 -0
  69. package/dist/src/staffViews.js.map +1 -0
  70. package/dist/src/strikes.js +2 -2
  71. package/dist/src/strikes.js.map +1 -1
  72. package/dist/src/subjects.js +2 -2
  73. package/dist/src/subjects.js.map +1 -1
  74. package/dist/src/team.d.ts +149 -0
  75. package/dist/src/team.d.ts.map +1 -0
  76. package/dist/src/team.js +385 -0
  77. package/dist/src/team.js.map +1 -0
  78. package/dist/src/types.d.ts +245 -4
  79. package/dist/src/types.d.ts.map +1 -1
  80. package/dist/src/types.js +5 -0
  81. package/dist/src/types.js.map +1 -1
  82. package/package.json +4 -1
  83. package/src/audit.ts +73 -9
  84. package/src/chat.ts +109 -9
  85. package/src/chatwarden.ts +279 -22
  86. package/src/crypto.ts +206 -0
  87. package/src/decide.ts +2 -4
  88. package/src/documents.ts +70 -43
  89. package/src/events.ts +10 -1
  90. package/src/hasher.ts +2 -2
  91. package/src/index.ts +110 -5
  92. package/src/ladder.ts +1 -1
  93. package/src/log.ts +37 -0
  94. package/src/notices.ts +2 -2
  95. package/src/policy.ts +288 -0
  96. package/src/profile.ts +369 -14
  97. package/src/reporting.ts +251 -0
  98. package/src/reports.ts +165 -12
  99. package/src/sanctions.ts +3 -3
  100. package/src/staffReports.ts +33 -7
  101. package/src/staffViews.ts +325 -0
  102. package/src/strikes.ts +2 -2
  103. package/src/subjects.ts +2 -2
  104. package/src/team.ts +422 -0
  105. package/src/types.ts +257 -4
package/src/chatwarden.ts CHANGED
@@ -3,7 +3,7 @@ import type { AuditPage, AuditQuery, AuditRecordInput } from './audit.js';
3
3
  import { ChatService } from './chat.js';
4
4
  import { DecisionService, revokeAndWithdraw } from './decide.js';
5
5
  import type { DecisionInput, DecisionResult } from './decide.js';
6
- import type { ChatResult } from './chat.js';
6
+ import type { ChatResult, RestrictedAnswer } from './chat.js';
7
7
  import { bindDocuments } from './documents.js';
8
8
  import type { Documents } from './documents.js';
9
9
  import { DoorService } from './doors.js';
@@ -12,18 +12,20 @@ import { EvidenceBuffer, RoomRoster } from './evidence.js';
12
12
  import { EventBus } from './events.js';
13
13
  import type { Subscribe } from './events.js';
14
14
  import { hashWho, makeHasher } from './hasher.js';
15
- import { safeWarn } from './log.js';
15
+ import { safeWarn, ThrottledWarn } from './log.js';
16
16
  import { historyOf, suggest } from './ladder.js';
17
17
  import type { ActionRecord, Suggestion, SuggestContext } from './ladder.js';
18
18
  import { resolveLimits } from './limits.js';
19
19
  import type { Limits, LimitsInput } from './limits.js';
20
+ import { PolicyService } from './policy.js';
21
+ import type { PolicyPreview, PolicySaveContext, PolicySaveResult, PolicyState } from './policy.js';
20
22
  import { resolveProfile } from './profile.js';
21
- import type { ModerationProfile, PresetName, ProfanityConfig, ProfileOverrides } from './profile.js';
23
+ import type { ModerationProfile, PolicyLayer, PolicySection, PresetName, ProfanityConfig, ProfileOverrides, ResolvedProfile } from './profile.js';
22
24
  import { MuteService } from './mutes.js';
23
25
  import { NoticeService } from './notices.js';
24
26
  import type { PlayerNotice } from './notices.js';
25
27
  import { ReportService } from './reports.js';
26
- import type { ReportCounts, ReportInput, ReportResult } from './reports.js';
28
+ import type { ReportCounts, ReportDetailInput, ReportDetailResult, ReportInput, ReportResult } from './reports.js';
27
29
  import { checkRetentionFloors, purge, RETENTION_DEFAULTS } from './retention.js';
28
30
  import type { PurgeResult, RetentionPolicy } from './retention.js';
29
31
  import { defineRules, parseRuleRef, starterRules } from './rules.js';
@@ -31,9 +33,26 @@ import type { CommunityRules, RuleRef } from './rules.js';
31
33
  import { applySanction, SanctionIndex } from './sanctions.js';
32
34
  import type { SanctionInput } from './sanctions.js';
33
35
  import { StrikeService } from './strikes.js';
36
+ import {
37
+ blockedCountsByTerm,
38
+ blockedItems,
39
+ listSanctionGroups,
40
+ reporterRecord,
41
+ sanctionsOfPerson,
42
+ } from './staffViews.js';
43
+ import type {
44
+ BlockedDays,
45
+ BlockedItem,
46
+ ReporterRecord,
47
+ SanctionGroupView,
48
+ SanctionListInput,
49
+ SanctionPage,
50
+ } from './staffViews.js';
34
51
  import { listStaffReports, staffReport } from './staffReports.js';
35
52
  import type { ReportPage, ReportQuery, StaffReport } from './staffReports.js';
36
53
  import { SubjectIndex } from './subjects.js';
54
+ import { CaseDesk, ReasonBook } from './team.js';
55
+ import type { CaseClaim, ClaimOutcome, NextCase } from './team.js';
37
56
  import { WEBHOOK_KEY_TTL_MS } from './types.js';
38
57
  import type {
39
58
  Clock,
@@ -43,6 +62,8 @@ import type {
43
62
  Platform,
44
63
  ProfanityFilter,
45
64
  RawWho,
65
+ ReasonRow,
66
+ ReportCategory,
46
67
  ConductLevel,
47
68
  Store,
48
69
  StoredReport,
@@ -135,7 +156,8 @@ export interface ChatwardenOptions {
135
156
  /**
136
157
  * The moderation profile: a preset by name (`'relaxed'`, `'standard'` or `'strict'`) or a complete profile from
137
158
  * `defineProfile` / `resolveProfile`. Default `'standard'`. It drives `suggest`, the starter rules and the
138
- * summary; read the result back as `cw.profile`.
159
+ * summary. This is the BASE profile: a moderator's stored edits (`cw.policy`) are merged on top of it, and `cw.profile` reads
160
+ * the result.
139
161
  */
140
162
  profile?: PresetName | ModerationProfile;
141
163
  /**
@@ -195,6 +217,28 @@ export interface Chatwarden {
195
217
  accept(roomId: string, seatId: string, text: string, opts?: { audience?: string[] }): ChatResult;
196
218
  /** Should `viewerSeat` be shown a line `senderSeat` sent (mutes applied)? */
197
219
  visibleTo(roomId: string, viewerSeat: string, senderSeat: string): boolean;
220
+ /**
221
+ * Is this person chat-restricted right now (a chat restriction, a ban or an automatic timeout)? For a typing
222
+ * indicator: show none while `restricted` is true. It runs the same decision as `accept`, and equals what
223
+ * `accept` would answer for the seat when you pass BOTH `roomId` and `seatId`. Without them, an automatic
224
+ * timeout that was only kept in memory (it could not be stored, or a guest with no identity earned it) is looked
225
+ * up by person, over `roomId` or over every room, and a guest with no key and no account is never found: one
226
+ * guest cannot be told from another. The `gate` option is not consulted; a gate refusal is not a restriction.
227
+ * Synchronous and a pure read: no rate budget spent, no evidence, strike, event or notice written. Only a
228
+ * failure is logged (event and error class), at most once a minute with a count of those held back; a failure
229
+ * reads as `restricted: false`.
230
+ *
231
+ * Call it after `cw.rooms.seat`: the address checked is the one `seat` last recorded for the person, as in
232
+ * `accept`, not `who.ip`. Take `who` from your platform's `identify` on the server, never from what the client
233
+ * sends: a client-supplied key or account would let a caller look up another person's restriction.
234
+ *
235
+ * Safe to answer a player about THEMSELVES from their own client, because it reveals nothing about others:
236
+ * `until` (epoch ms, `null` = permanent) and `kind` (`'chat'`, `'ban'` or `'auto'`) are only given for the
237
+ * person's own sanction. When the restriction reaches them only through an address shared with someone else's
238
+ * sanction, the answer is `{ restricted: true, until: null, kind: null }`. `who` is found by key or account (an
239
+ * address alone finds nobody). An empty `roomId` or `seatId` counts as not given. Never carries an identifier.
240
+ */
241
+ restricted(who: RawWho, opts?: { roomId?: string | null; seatId?: string | null }): RestrictedAnswer;
198
242
  };
199
243
  mutes: {
200
244
  /** `viewerSeat`'s occupant mutes (`on`) or unmutes `targetSeat`'s occupant. Does nothing if either seat has no subject. */
@@ -203,12 +247,27 @@ export interface Chatwarden {
203
247
  mutedSeats(roomId: string, viewerSeat: string): string[];
204
248
  };
205
249
  reports: {
250
+ /**
251
+ * File a report. `input.reason` (or the 0.1.1 alias `category`) is optional: with the default `one_tap` flow a report with
252
+ * no reason is taken; with `reason_required` it is refused `reason_required`; an unknown or switched-off reason is
253
+ * `reason_unknown` in every flow. The reason is stored as `reportedReason`: a hint for the moderator, never the truth.
254
+ * See {@link ReportInput} and {@link ReportRefusal}. The kit has no player report route: your game's own route calls this.
255
+ */
206
256
  submit(input: ReportInput): Promise<ReportResult>;
257
+ /**
258
+ * The reporter's one optional follow-up after a report: `{ reason?, note? }` attached to the same report. Only the original
259
+ * reporter (the same seat, still in the report's room), once, within ten minutes, and while the report is open; it never
260
+ * changes the target or the excerpt. Refusals: `off`, `not_found`, `not_reporter`, `too_late`, `already_added`,
261
+ * `reason_unknown`. Never rejects. The kit has no player report route: expose this from your own, the way you expose
262
+ * `submit`, with the seat taken from your own session and never from the request body.
263
+ */
264
+ addDetail(reportId: string, reporterSeat: string, detail: ReportDetailInput): Promise<ReportDetailResult>;
207
265
  /**
208
266
  * The staff report queue, newest first (ties broken by id), one page at a time. Filter with `status`; pass the
209
267
  * previous page's `next` as `before` for the next page; `limit` defaults to 50 and is clamped to 1..200. Each item
210
268
  * is a {@link StaffReport}: the whole record plus the canonical staff refs and the own line ids of every person.
211
- * Throws `ReportQueryError` for an unknown status or a cursor that is not one of ours, and the store's own error
269
+ * `reason` keeps only the reports filed under that reported reason (`null`: none given). Throws `ReportQueryError` for an
270
+ * unknown status, a malformed reason or a cursor that is not one of ours, and the store's own error
212
271
  * if it fails, so a route handler should catch both.
213
272
  * Carries subject ids: staff channels only, never send to a player.
214
273
  */
@@ -218,6 +277,98 @@ export interface Chatwarden {
218
277
  * Carries subject ids: staff channels only, never send to a player.
219
278
  */
220
279
  get(id: string): StaffReport | null;
280
+ /**
281
+ * How the reports this person FILED stand (total, open, actioned, dismissed, bad faith) and when their reporting
282
+ * suspension ends (null if none), under the same rule intake uses, and how often their reported reason was borne out
283
+ * (`reasonMatched` of `reasonDecided`). Folds in the person's merged aliases. Staff only:
284
+ * never send to a player (a player is not told who reported or how often).
285
+ */
286
+ reporterRecord(subject: SubjectId): ReporterRecord;
287
+ };
288
+ /**
289
+ * Blocked chat lines, from the slur filter's strikes (purged after 30 days). Staff only: the lines are raw chat text
290
+ * and `person` is a subject id; never send either to a player.
291
+ */
292
+ blocked: {
293
+ /** The last `days` days (1, 7 or 30, else `RangeError`), newest first, at most 500. */
294
+ list(q: { days: BlockedDays }): BlockedItem[];
295
+ /** Strikes per term id over the same window; a term with none is absent. */
296
+ countsByTerm(q: { days: BlockedDays }): Record<string, number>;
297
+ };
298
+ /**
299
+ * The team workbench: soft claims on a person's case, take next, and who has a case open. Staff only; every `person` is
300
+ * a staff ref (an alias is folded into the surviving person) and every `actor` a staff ref the audit trail accepts
301
+ * (`RangeError` otherwise). Claims live in the store and last 10 minutes from the last beat (`CLAIM_TTL_MS`), on the
302
+ * injected clock; an expired claim reads as absent everywhere. They are a courtesy, not a security boundary: nothing
303
+ * in the core refuses a decision because of one (`@chatwarden/http` does, with a 409 `claimed`).
304
+ * Carries subject ids: staff channels only, never send to a player.
305
+ */
306
+ cases: {
307
+ /** The live claim on the person's case, or null. */
308
+ holder(person: SubjectId): CaseClaim | null;
309
+ /** The live claims among these people in one read, keyed by their canonical person. */
310
+ holders(people: readonly SubjectId[]): Map<SubjectId, CaseClaim>;
311
+ /**
312
+ * Claim the person's case, or beat the claim `actor` already holds (the claim then lasts 10 minutes from now; `since`
313
+ * is kept). Needs an open report against the person (`no_case` otherwise). Somebody else's live claim answers
314
+ * `claimed` with it, unless `takeOver` is true, which moves it to `actor` (`tookOverFrom` names the previous holder).
315
+ * `takeOver` is not permission-checked here: the caller decides who may use it. The write is one atomic conditional
316
+ * statement, so two moderators racing for one case never both win, even from two processes on one database. A
317
+ * process that loses the database lock race in between (SQLite BUSY) is retried up to `CLAIM_BUSY_TRIES` times with
318
+ * a fresh read, so it answers `claimed` with the winner, not an error.
319
+ */
320
+ claim(person: SubjectId, actor: string, opts?: { takeOver?: boolean }): ClaimOutcome;
321
+ /** End `actor`'s own claim. True only when it ended a live one; never touches another moderator's. */
322
+ release(person: SubjectId, actor: string): boolean;
323
+ /**
324
+ * What a decision does to the claim: end `actor`'s own claim only when the person has no other open report (one case per
325
+ * person: deciding one report of several keeps the claim, and the last one releases it). While reports remain the claim is
326
+ * not touched at all. True only when it ended a live claim.
327
+ */
328
+ releaseWhenDone(person: SubjectId, actor: string): boolean;
329
+ /**
330
+ * Claim and return the oldest OPEN case nobody holds, optionally only cases with an open report of `category`
331
+ * or that gave `reason` (an id, the old `disruption` reading as `griefing`; `null`: none given; `RangeError` for an unknown category or a
332
+ * malformed id), or null. A case is a person, ranked by their oldest open report and opened on
333
+ * their newest. A case anyone holds is skipped without a write (held cases are read once per page of reports). `category` and
334
+ * `reason` are the only filters: the order is already oldest first. A candidate lost to a rival in between is retried like `claim`.
335
+ */
336
+ next(actor: string, filter?: { category?: ReportCategory; reason?: string | null }): NextCase | null;
337
+ /**
338
+ * `actor` has the person's case open now. A hint for 30 seconds (`VIEWING_TTL_MS`), in this process's memory only.
339
+ * Only a person with an open report is tracked (false otherwise, nothing recorded); one actor keeps at most 20 cases
340
+ * (`VIEWING_PER_ACTOR_MAX`), a newer beat dropping their oldest. True when the beat was recorded.
341
+ */
342
+ view(person: SubjectId, actor: string): boolean;
343
+ /** Who has the person's case open now (sorted), leaving `except` out. In this process's memory: other processes are not seen. */
344
+ viewers(person: SubjectId, except?: string): string[];
345
+ /** `viewers` for several people at once; people nobody is viewing are absent. */
346
+ viewersOf(people: readonly SubjectId[], except?: string): Map<SubjectId, string[]>;
347
+ };
348
+ /** A cheap "did anything change?" for the moderator queue. */
349
+ changes: {
350
+ /**
351
+ * An opaque token, persisted in the store (the in-memory store starts again at "0" when the process restarts), that is different after any report filed or decided, sanction applied or
352
+ * revoked, rule gap closed, claim taken, taken over or released, or saved reason changed, and the same otherwise
353
+ * (a claim heartbeat, a refused claim, viewing and every read leave it alone). A claim that merely expires does not
354
+ * move it. Compare it for equality only; one read of one row, no audit, no other reads.
355
+ */
356
+ token(): string;
357
+ };
358
+ /**
359
+ * Saved decision reasons (label up to 40 characters, text up to 500, at most 200 of them), shared by the team and
360
+ * kept in the store. Text is staff-written and may be quoted into a decision; it is not player-facing by itself.
361
+ * `ReasonError` for a label, text or id outside its limits, or when the list is full.
362
+ */
363
+ reasons: {
364
+ /** Every reason, active or not, in the order they were added. */
365
+ list(): ReasonRow[];
366
+ /** Add an active reason (trimmed). */
367
+ add(input: { label: string; text: string }): ReasonRow;
368
+ /** Change the label and/or text (at least one). Null for an unknown id. */
369
+ update(id: string, patch: { label?: string; text?: string }): ReasonRow | null;
370
+ /** Switch a reason on or off. Null for an unknown id. */
371
+ setActive(id: string, active: boolean): ReasonRow | null;
221
372
  };
222
373
  doors: { check(kind: DoorKind, who: RawWho): DoorRefusal | null };
223
374
  sanctions: {
@@ -231,6 +382,18 @@ export interface Chatwarden {
231
382
  * a seen one leaves "My record". Resolves true when this call revoked something.
232
383
  */
233
384
  revoke(groupId: string, actor: string, reason: string): Promise<boolean>;
385
+ /**
386
+ * A person's sanctions as staff see them, newest first: the last 90 days plus every unrevoked permanent one, across
387
+ * the aliases merged into them, at most 200. Each is a {@link SanctionGroupView} built from the group's subject row
388
+ * (never an IP row, never a hashed identifier). Carries staff-only text (reason, actor): never send to a player.
389
+ */
390
+ forPerson(subject: SubjectId): SanctionGroupView[];
391
+ /**
392
+ * Every person's sanctions, newest first, one page at a time (`limit` default 50, clamped to 1..200; `cursor` is the
393
+ * previous `next`; `source` filters). Not windowed. Throws {@link SanctionQueryError} for a cursor that is not ours or an
394
+ * unknown source. Carries subject ids and staff-only text: never send to a player.
395
+ */
396
+ list(q?: SanctionListInput): SanctionPage;
234
397
  };
235
398
  /**
236
399
  * Subscribe to what happens in the kit: `'report.created'`, `'report.closed'`, `'sanction.applied'`,
@@ -258,15 +421,47 @@ export interface Chatwarden {
258
421
  };
259
422
  /** The registry in use (the one given, or the starter rules for the profile). Retired rules stay listed. */
260
423
  rules: CommunityRules;
261
- /** The profile in force: the preset, the overrides and the validation applied. Deep-frozen. */
262
- profile: ModerationProfile;
424
+ /**
425
+ * The profile in force: the preset, the code overrides and the stored layer from `cw.policy`, validated. Deep-frozen. A
426
+ * getter, read live: after a save (or a change another process saved, within 10 seconds) it is a new object, so never keep
427
+ * one across calls. Everything in the kit that reads the profile reads it through this.
428
+ */
429
+ readonly profile: ResolvedProfile;
430
+ /**
431
+ * The editable profile. The profile from code is the base; a moderator's edits to the durations offered, the ladder, the first
432
+ * offences, the repeat rule, the area and severe rules and the guideline outcome texts are stored in your store as a
433
+ * versioned layer. Needs a store with `loadPolicyLayer` and `savePolicyLayer` (the memory and SQLite stores have them);
434
+ * without them `save` and `reset` answer `{ ok: false, error: 'unsupported' }` and everything else works from code.
435
+ */
436
+ policy: {
437
+ /** `{ effective, base, layer, version, canSave }`, plus `layerError` when the stored layer cannot be used (it is then ignored). */
438
+ get(): PolicyState;
439
+ /**
440
+ * Replace the stored layer (the whole layer: a section left out goes back to the base) if `version` is still the stored
441
+ * one. `{ ok: true, version, changed }`, or `{ ok: false, error: 'conflict' | 'unsupported' }`, or `{ ok: false, error:
442
+ * 'invalid', path }` for a layer that touches anything outside the editable sections (profanity stays in code) or would
443
+ * make the profile invalid. `actor` and `reason` are checked (path `actor` / `reason`); the staff routes write them to
444
+ * the audit trail. Takes effect at once here, and within 10 seconds in other processes on the same store.
445
+ */
446
+ save(layer: PolicyLayer, ctx: PolicySaveContext): PolicySaveResult;
447
+ /**
448
+ * What `layer` would suggest for four sample records (`clean`, `oneWarning`, `chat24h`, `ban7d`) and each conduct level,
449
+ * without saving. Pass `rule` to see an area or severe rule take effect.
450
+ */
451
+ preview(layer: PolicyLayer, rule?: RuleRef): PolicyPreview;
452
+ /** Put one section (or all of them) back to the base. Stores the layer without it; a no-op when nothing is stored for it. */
453
+ reset(section?: PolicySection, o?: { version?: number }): PolicySaveResult;
454
+ /** Look at the store now, instead of waiting for the 10 second interval. */
455
+ refresh(): void;
456
+ };
263
457
  /** The limits in force, defaults filled in. Deep-frozen. */
264
458
  limits: Limits;
265
- /** The profile's one-line summary, for the report dialog and the rules page. Same as `profile.summary`. */
266
- summary: string;
459
+ /** The profile's one-line summary, for the report dialog and the rules page. Same as `profile.summary`. A getter, read live. */
460
+ readonly summary: string;
267
461
  /**
268
462
  * Generated policy documents, bound to the profile and rules in force: a player code of conduct, a moderator guide,
269
- * an agent brief and the policy as JSON. Pure text; nothing here reads the store.
463
+ * an agent brief and the policy as JSON. Each call is generated from the effective profile at that moment, so a save shows
464
+ * in the very next call.
270
465
  */
271
466
  documents: Documents;
272
467
  /**
@@ -315,7 +510,7 @@ export interface Chatwarden {
315
510
  };
316
511
  /**
317
512
  * The staff audit trail: who (actor and role) did what to which id, and when. Staff only. Stores ids and the action
318
- * name, never chat text, a reason or a note. Rows from the term editor and from `gaps.close` read here too (role
513
+ * name, never chat text or a note (a `policy.update` / `policy.reset` row also holds the sections changed and the owner's reason). Rows from the term editor and from `gaps.close` read here too (role
319
514
  * null). Kept `retention.auditMs` (default 365 days, at least 90).
320
515
  */
321
516
  audit: {
@@ -412,7 +607,10 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
412
607
  const hasher = makeHasher(opts.secret);
413
608
 
414
609
  // Everything an adopter configures is checked before the store is touched or a timer started.
415
- const profile = resolveProfile(opts.profile ?? 'standard', opts.overrides);
610
+ // The BASE profile: the preset and the code overrides. What is in force is `policy.profileNow()` (the base with the stored layer
611
+ // on top); never keep that in a closure. The base itself is read here only for what a layer cannot edit: the rules flavour
612
+ // and the profanity handling, which are code-only.
613
+ const baseProfile = resolveProfile(opts.profile ?? 'standard', opts.overrides);
416
614
  const limits = resolveLimits(opts.limits);
417
615
 
418
616
  const { everyMs, ...givenRetention } = opts.retention === false ? {} : (opts.retention ?? {});
@@ -429,15 +627,15 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
429
627
  if (opts.retention !== false && purgeEveryMs > MAX_PURGE_EVERY_MS) {
430
628
  throw new RangeError(`retention.everyMs must be at most ${MAX_PURGE_EVERY_MS}`);
431
629
  }
432
- const rules = opts.rules ?? defineRules(starterRules(profile.rules));
630
+ const rules = opts.rules ?? defineRules(starterRules(baseProfile.rules));
433
631
  const autoRestrictRule = opts.autoRestrictRule ?? 1;
434
632
  const autoRule = rules.get(autoRestrictRule);
435
633
  if (autoRule === undefined || autoRule.retired === true) {
436
634
  throw new RangeError('autoRestrictRule must be the number of an active rule in the registry');
437
635
  }
438
636
  if (opts.matcher === undefined) safeWarn(logger, 'chatwarden.no_matcher');
439
- const profanity = buildProfanityFilter(opts, profile.profanity);
440
- if (profanity === undefined && profile.profanity.mode !== 'allow') safeWarn(logger, 'chatwarden.no_profanity_filter');
637
+ const profanity = buildProfanityFilter(opts, baseProfile.profanity);
638
+ if (profanity === undefined && baseProfile.profanity.mode !== 'allow') safeWarn(logger, 'chatwarden.no_profanity_filter');
441
639
 
442
640
  const bus = new EventBus(logger);
443
641
  const subjects = new SubjectIndex(store, clock, { logger });
@@ -451,6 +649,9 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
451
649
  await sanctions.load(store, clock.now());
452
650
  await mutes.load();
453
651
  await strikes.load();
652
+ // The stored edits to the profile. Read last, so a store that fails here has not left anything half built.
653
+ const policy = new PolicyService({ store, clock, logger, base: baseProfile });
654
+ policy.load();
454
655
 
455
656
  // ONE notice service for the whole kit: chat (the automatic timeout), the doors (the refusal's pointer) and
456
657
  // decisions all write to and read from it, and `platform.notify` hears of every new notice through it.
@@ -476,7 +677,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
476
677
  clock,
477
678
  matcher: opts.matcher,
478
679
  profanity,
479
- profanityMode: profile.profanity.mode,
680
+ profanityMode: baseProfile.profanity.mode,
480
681
  gate: opts.gate,
481
682
  onAutoRestrict: opts.onAutoRestrict,
482
683
  onAutoRestricted: ({ groupId, refCode, second, subject }) => {
@@ -494,6 +695,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
494
695
  store,
495
696
  clock,
496
697
  enabled,
698
+ reporting: () => policy.profileNow().reporting,
497
699
  onReport: opts.onReport,
498
700
  logger,
499
701
  limits: limits.reports,
@@ -526,6 +728,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
526
728
  }
527
729
  };
528
730
 
731
+ /** The typing lookup runs at keystroke rate: a failing store logs once a minute, not once a keystroke. */
732
+ const restrictedWarn = new ThrottledWarn(logger, clock);
529
733
  const eventFailed = (err: unknown): void => {
530
734
  safeWarn(logger, 'chatwarden.event_failed', { error: err instanceof Error ? err.name : typeof err });
531
735
  };
@@ -539,6 +743,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
539
743
  reportId: stored.id,
540
744
  createdAt: stored.createdAt,
541
745
  category: stored.category,
746
+ reportedReason: stored.reportedReason,
542
747
  roomTags: { ...stored.tags },
543
748
  });
544
749
  } catch (err) {
@@ -571,6 +776,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
571
776
  }
572
777
 
573
778
  const audit = new AuditService({ store, clock, logger });
779
+ const desk = new CaseDesk({ store, subjects, clock, reasons: () => policy.profileNow().reporting.reasons });
780
+ const reasonBook = new ReasonBook(store);
574
781
 
575
782
  return {
576
783
  rooms: {
@@ -593,6 +800,14 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
593
800
  chat: {
594
801
  accept: (roomId, seatId, text, o) => chat.accept(roomId, seatId, text, o),
595
802
  visibleTo: (roomId, viewerSeat, senderSeat) => chat.visibleTo(roomId, viewerSeat, senderSeat),
803
+ restricted: (who, o) => {
804
+ try {
805
+ return chat.restricted(personOf(who), o?.roomId, o?.seatId);
806
+ } catch (err) {
807
+ restrictedWarn.warn('chatwarden.restricted_failed', { error: err instanceof Error ? err.name : typeof err });
808
+ return { restricted: false, until: null, kind: null };
809
+ }
810
+ },
596
811
  },
597
812
  mutes: {
598
813
  set: (roomId, viewerSeat, targetSeat, on) => {
@@ -609,11 +824,35 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
609
824
  if (res.ok) announceReport(res.reportId);
610
825
  return res;
611
826
  },
612
- list: (q) => listStaffReports(store, subjects, q),
827
+ addDetail: (reportId, reporterSeat, detail) => reports.addDetail(reportId, reporterSeat, detail),
828
+ list: (q) => listStaffReports(store, subjects, q, policy.profileNow().reporting.reasons),
613
829
  get: (id) => {
614
830
  const record = typeof id === 'string' ? store.loadReport(id) : null;
615
831
  return record === null ? null : staffReport(record, subjects);
616
832
  },
833
+ reporterRecord: (subject) => reporterRecord(store, subjects, limits.reports, subject, clock.now(), policy.profileNow().reporting.reasons),
834
+ },
835
+ blocked: {
836
+ list: (q) => blockedItems(store, subjects, q?.days, clock.now()),
837
+ countsByTerm: (q) => blockedCountsByTerm(store, q?.days, clock.now()),
838
+ },
839
+ cases: {
840
+ holder: (person) => desk.holder(person),
841
+ holders: (people) => desk.holders(people),
842
+ claim: (person, actor, o) => desk.claim(person, actor, o),
843
+ release: (person, actor) => desk.release(person, actor),
844
+ releaseWhenDone: (person, actor) => desk.releaseWhenDone(person, actor),
845
+ next: (actor, filter) => desk.next(actor, filter),
846
+ view: (person, actor) => desk.view(person, actor),
847
+ viewers: (person, except) => desk.viewers(person, except),
848
+ viewersOf: (people, except) => desk.viewersOf(people, except),
849
+ },
850
+ changes: { token: () => store.changeToken() },
851
+ reasons: {
852
+ list: () => reasonBook.list(),
853
+ add: (input) => reasonBook.add(input),
854
+ update: (id, patch) => reasonBook.update(id, patch),
855
+ setActive: (id, active) => reasonBook.setActive(id, active),
617
856
  },
618
857
  doors: { check: (kind, who) => doors.check(kind, who) },
619
858
  sanctions: {
@@ -674,6 +913,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
674
913
  }
675
914
  return revoked;
676
915
  },
916
+ forPerson: (subject) => sanctionsOfPerson(store, subjects, subject, clock.now()),
917
+ list: (q) => listSanctionGroups(store, subjects, q ?? {}, clock.now()),
677
918
  },
678
919
  on: bus.on,
679
920
  names: {
@@ -691,10 +932,26 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
691
932
  },
692
933
  },
693
934
  rules,
694
- profile,
935
+ get profile() {
936
+ return policy.profileNow();
937
+ },
938
+ policy: {
939
+ get: () => policy.get(),
940
+ save: (layer, ctx) => policy.save(layer, ctx),
941
+ preview: (layer, rule) => policy.preview(layer, rule),
942
+ reset: (section, o) => policy.reset(section, o),
943
+ refresh: () => policy.refresh(),
944
+ },
695
945
  limits,
696
- summary: profile.summary,
697
- documents: bindDocuments({ profile, rules }),
946
+ get summary() {
947
+ return policy.profileNow().summary;
948
+ },
949
+ documents: bindDocuments({
950
+ get profile() {
951
+ return policy.profileNow();
952
+ },
953
+ rules,
954
+ }),
698
955
  notices: {
699
956
  pending: (who) => forPlayer<PlayerNotice[]>(who, [], (s) => notices.pending(s)),
700
957
  ack: (who, id) => forPlayer(who, false, (s) => notices.ack(s, id)),
@@ -731,7 +988,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
731
988
  history: (subject) => historyOf(store, subjects, subject, clock.now()),
732
989
  suggest: (subject, level, rule, context) => {
733
990
  const now = clock.now();
734
- return suggest(profile, historyOf(store, subjects, subject, now), level, rule, now, context);
991
+ return suggest(policy.profileNow(), historyOf(store, subjects, subject, now), level, rule, now, context);
735
992
  },
736
993
  gaps: {
737
994
  list: () =>