@chatwarden/core 0.1.1 → 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 (71) hide show
  1. package/README.md +128 -4
  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 +57 -6
  5. package/dist/src/audit.js.map +1 -1
  6. package/dist/src/chatwarden.d.ts +183 -11
  7. package/dist/src/chatwarden.d.ts.map +1 -1
  8. package/dist/src/chatwarden.js +65 -10
  9. package/dist/src/chatwarden.js.map +1 -1
  10. package/dist/src/documents.d.ts +12 -2
  11. package/dist/src/documents.d.ts.map +1 -1
  12. package/dist/src/documents.js +56 -34
  13. package/dist/src/documents.js.map +1 -1
  14. package/dist/src/events.d.ts +3 -0
  15. package/dist/src/events.d.ts.map +1 -1
  16. package/dist/src/events.js.map +1 -1
  17. package/dist/src/index.d.ts +20 -11
  18. package/dist/src/index.d.ts.map +1 -1
  19. package/dist/src/index.js +11 -6
  20. package/dist/src/index.js.map +1 -1
  21. package/dist/src/ladder.d.ts +2 -0
  22. package/dist/src/ladder.d.ts.map +1 -1
  23. package/dist/src/ladder.js +1 -1
  24. package/dist/src/ladder.js.map +1 -1
  25. package/dist/src/policy.d.ts +129 -0
  26. package/dist/src/policy.d.ts.map +1 -0
  27. package/dist/src/policy.js +242 -0
  28. package/dist/src/policy.js.map +1 -0
  29. package/dist/src/profile.d.ts +120 -7
  30. package/dist/src/profile.d.ts.map +1 -1
  31. package/dist/src/profile.js +295 -7
  32. package/dist/src/profile.js.map +1 -1
  33. package/dist/src/reporting.d.ts +127 -0
  34. package/dist/src/reporting.d.ts.map +1 -0
  35. package/dist/src/reporting.js +172 -0
  36. package/dist/src/reporting.js.map +1 -0
  37. package/dist/src/reports.d.ts +80 -4
  38. package/dist/src/reports.d.ts.map +1 -1
  39. package/dist/src/reports.js +120 -6
  40. package/dist/src/reports.js.map +1 -1
  41. package/dist/src/staffReports.d.ts +17 -5
  42. package/dist/src/staffReports.d.ts.map +1 -1
  43. package/dist/src/staffReports.js +22 -5
  44. package/dist/src/staffReports.js.map +1 -1
  45. package/dist/src/staffViews.d.ts +138 -0
  46. package/dist/src/staffViews.d.ts.map +1 -0
  47. package/dist/src/staffViews.js +205 -0
  48. package/dist/src/staffViews.js.map +1 -0
  49. package/dist/src/team.d.ts +149 -0
  50. package/dist/src/team.d.ts.map +1 -0
  51. package/dist/src/team.js +385 -0
  52. package/dist/src/team.js.map +1 -0
  53. package/dist/src/types.d.ts +245 -4
  54. package/dist/src/types.d.ts.map +1 -1
  55. package/dist/src/types.js +5 -0
  56. package/dist/src/types.js.map +1 -1
  57. package/package.json +2 -2
  58. package/src/audit.ts +71 -7
  59. package/src/chatwarden.ts +245 -20
  60. package/src/documents.ts +70 -43
  61. package/src/events.ts +10 -1
  62. package/src/index.ts +109 -4
  63. package/src/ladder.ts +1 -1
  64. package/src/policy.ts +288 -0
  65. package/src/profile.ts +369 -14
  66. package/src/reporting.ts +251 -0
  67. package/src/reports.ts +163 -10
  68. package/src/staffReports.ts +33 -7
  69. package/src/staffViews.ts +325 -0
  70. package/src/team.ts +422 -0
  71. package/src/types.ts +257 -4
package/src/chatwarden.ts CHANGED
@@ -17,13 +17,15 @@ 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
  /**
@@ -225,12 +247,27 @@ export interface Chatwarden {
225
247
  mutedSeats(roomId: string, viewerSeat: string): string[];
226
248
  };
227
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
+ */
228
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>;
229
265
  /**
230
266
  * The staff report queue, newest first (ties broken by id), one page at a time. Filter with `status`; pass the
231
267
  * previous page's `next` as `before` for the next page; `limit` defaults to 50 and is clamped to 1..200. Each item
232
268
  * is a {@link StaffReport}: the whole record plus the canonical staff refs and the own line ids of every person.
233
- * 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
234
271
  * if it fails, so a route handler should catch both.
235
272
  * Carries subject ids: staff channels only, never send to a player.
236
273
  */
@@ -240,6 +277,98 @@ export interface Chatwarden {
240
277
  * Carries subject ids: staff channels only, never send to a player.
241
278
  */
242
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;
243
372
  };
244
373
  doors: { check(kind: DoorKind, who: RawWho): DoorRefusal | null };
245
374
  sanctions: {
@@ -253,6 +382,18 @@ export interface Chatwarden {
253
382
  * a seen one leaves "My record". Resolves true when this call revoked something.
254
383
  */
255
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;
256
397
  };
257
398
  /**
258
399
  * Subscribe to what happens in the kit: `'report.created'`, `'report.closed'`, `'sanction.applied'`,
@@ -280,15 +421,47 @@ export interface Chatwarden {
280
421
  };
281
422
  /** The registry in use (the one given, or the starter rules for the profile). Retired rules stay listed. */
282
423
  rules: CommunityRules;
283
- /** The profile in force: the preset, the overrides and the validation applied. Deep-frozen. */
284
- 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
+ };
285
457
  /** The limits in force, defaults filled in. Deep-frozen. */
286
458
  limits: Limits;
287
- /** The profile's one-line summary, for the report dialog and the rules page. Same as `profile.summary`. */
288
- 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;
289
461
  /**
290
462
  * Generated policy documents, bound to the profile and rules in force: a player code of conduct, a moderator guide,
291
- * 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.
292
465
  */
293
466
  documents: Documents;
294
467
  /**
@@ -337,7 +510,7 @@ export interface Chatwarden {
337
510
  };
338
511
  /**
339
512
  * The staff audit trail: who (actor and role) did what to which id, and when. Staff only. Stores ids and the action
340
- * 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
341
514
  * null). Kept `retention.auditMs` (default 365 days, at least 90).
342
515
  */
343
516
  audit: {
@@ -434,7 +607,10 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
434
607
  const hasher = makeHasher(opts.secret);
435
608
 
436
609
  // Everything an adopter configures is checked before the store is touched or a timer started.
437
- 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);
438
614
  const limits = resolveLimits(opts.limits);
439
615
 
440
616
  const { everyMs, ...givenRetention } = opts.retention === false ? {} : (opts.retention ?? {});
@@ -451,15 +627,15 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
451
627
  if (opts.retention !== false && purgeEveryMs > MAX_PURGE_EVERY_MS) {
452
628
  throw new RangeError(`retention.everyMs must be at most ${MAX_PURGE_EVERY_MS}`);
453
629
  }
454
- const rules = opts.rules ?? defineRules(starterRules(profile.rules));
630
+ const rules = opts.rules ?? defineRules(starterRules(baseProfile.rules));
455
631
  const autoRestrictRule = opts.autoRestrictRule ?? 1;
456
632
  const autoRule = rules.get(autoRestrictRule);
457
633
  if (autoRule === undefined || autoRule.retired === true) {
458
634
  throw new RangeError('autoRestrictRule must be the number of an active rule in the registry');
459
635
  }
460
636
  if (opts.matcher === undefined) safeWarn(logger, 'chatwarden.no_matcher');
461
- const profanity = buildProfanityFilter(opts, profile.profanity);
462
- 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');
463
639
 
464
640
  const bus = new EventBus(logger);
465
641
  const subjects = new SubjectIndex(store, clock, { logger });
@@ -473,6 +649,9 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
473
649
  await sanctions.load(store, clock.now());
474
650
  await mutes.load();
475
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();
476
655
 
477
656
  // ONE notice service for the whole kit: chat (the automatic timeout), the doors (the refusal's pointer) and
478
657
  // decisions all write to and read from it, and `platform.notify` hears of every new notice through it.
@@ -498,7 +677,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
498
677
  clock,
499
678
  matcher: opts.matcher,
500
679
  profanity,
501
- profanityMode: profile.profanity.mode,
680
+ profanityMode: baseProfile.profanity.mode,
502
681
  gate: opts.gate,
503
682
  onAutoRestrict: opts.onAutoRestrict,
504
683
  onAutoRestricted: ({ groupId, refCode, second, subject }) => {
@@ -516,6 +695,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
516
695
  store,
517
696
  clock,
518
697
  enabled,
698
+ reporting: () => policy.profileNow().reporting,
519
699
  onReport: opts.onReport,
520
700
  logger,
521
701
  limits: limits.reports,
@@ -563,6 +743,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
563
743
  reportId: stored.id,
564
744
  createdAt: stored.createdAt,
565
745
  category: stored.category,
746
+ reportedReason: stored.reportedReason,
566
747
  roomTags: { ...stored.tags },
567
748
  });
568
749
  } catch (err) {
@@ -595,6 +776,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
595
776
  }
596
777
 
597
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);
598
781
 
599
782
  return {
600
783
  rooms: {
@@ -641,11 +824,35 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
641
824
  if (res.ok) announceReport(res.reportId);
642
825
  return res;
643
826
  },
644
- 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),
645
829
  get: (id) => {
646
830
  const record = typeof id === 'string' ? store.loadReport(id) : null;
647
831
  return record === null ? null : staffReport(record, subjects);
648
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),
649
856
  },
650
857
  doors: { check: (kind, who) => doors.check(kind, who) },
651
858
  sanctions: {
@@ -706,6 +913,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
706
913
  }
707
914
  return revoked;
708
915
  },
916
+ forPerson: (subject) => sanctionsOfPerson(store, subjects, subject, clock.now()),
917
+ list: (q) => listSanctionGroups(store, subjects, q ?? {}, clock.now()),
709
918
  },
710
919
  on: bus.on,
711
920
  names: {
@@ -723,10 +932,26 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
723
932
  },
724
933
  },
725
934
  rules,
726
- 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
+ },
727
945
  limits,
728
- summary: profile.summary,
729
- 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
+ }),
730
955
  notices: {
731
956
  pending: (who) => forPlayer<PlayerNotice[]>(who, [], (s) => notices.pending(s)),
732
957
  ack: (who, id) => forPlayer(who, false, (s) => notices.ack(s, id)),
@@ -763,7 +988,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
763
988
  history: (subject) => historyOf(store, subjects, subject, clock.now()),
764
989
  suggest: (subject, level, rule, context) => {
765
990
  const now = clock.now();
766
- 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);
767
992
  },
768
993
  gaps: {
769
994
  list: () =>
package/src/documents.ts CHANGED
@@ -1,7 +1,7 @@
1
- import { DEFAULT_SEVERE_RULES, lengthLabel, outcomeLabel } from './ladder.js';
1
+ import { DEFAULT_AREA_RULES, DEFAULT_SEVERE_RULES, lengthLabel, outcomeLabel } from './ladder.js';
2
2
  import type { LadderCell } from './ladder.js';
3
- import { validateProfile } from './profile.js';
4
- import type { GuidelineCover, GuidelineTier, ModerationProfile, Outcome } from './profile.js';
3
+ import { validateProfile, withDurationDefaults } from './profile.js';
4
+ import type { GuidelineCover, GuidelineTier, ModerationProfile, Outcome, ResolvedProfile } from './profile.js';
5
5
  import type { CommunityRule, CommunityRules } from './rules.js';
6
6
  import { CONDUCT_LEVELS } from './types.js';
7
7
  import type { ConductLevel } from './types.js';
@@ -34,15 +34,26 @@ export interface CodeOfConductOptions {
34
34
  contactUrl?: string;
35
35
  }
36
36
 
37
+ /**
38
+ * The sections of the moderator guide a caller may leave out: `rules` (the Community Rules list) and `ladder` (the escalation
39
+ * ladder: its heading, the step note, the table and the notes on area and severe rules). The moderator hub draws both from data
40
+ * and asks for the rest of the guide.
41
+ */
42
+ export const GUIDE_SECTIONS = ['rules', 'ladder'] as const;
43
+ export type GuideSection = (typeof GUIDE_SECTIONS)[number];
44
+
37
45
  /** Options for {@link moderatorGuide}. */
38
46
  export interface ModeratorGuideOptions {
39
47
  format: DocumentFormat;
48
+ /** Sections to leave out. Default none: the whole guide. The rest keeps its order. */
49
+ omitSections?: readonly GuideSection[];
40
50
  }
41
51
 
42
52
  /** The policy as data, for tools that import it. */
43
53
  export interface PolicyJson {
44
54
  version: 1;
45
- profile: ModerationProfile;
55
+ /** With `durations` and `customDuration` filled in, so a profile written for 0.1.1 reads back with the two new keys. */
56
+ profile: ResolvedProfile;
46
57
  /** Every rule, retired ones included, in number order. */
47
58
  rules: CommunityRule[];
48
59
  }
@@ -207,6 +218,14 @@ function render(blocks: readonly Block[], format: DocumentFormat): string {
207
218
  // ---------------------------------------------------------------------------------------------------------------
208
219
  // Checks
209
220
 
221
+ function checkSections(sections: unknown): ReadonlySet<GuideSection> {
222
+ if (sections === undefined) return new Set();
223
+ if (!Array.isArray(sections) || !sections.every((x) => typeof x === 'string' && (GUIDE_SECTIONS as readonly string[]).includes(x))) {
224
+ throw new RangeError(`omitSections must be a list of: ${GUIDE_SECTIONS.join(', ')}`);
225
+ }
226
+ return new Set(sections as GuideSection[]);
227
+ }
228
+
210
229
  function checkFormat(format: unknown): DocumentFormat {
211
230
  if (typeof format !== 'string' || !FORMATS.includes(format)) {
212
231
  throw new RangeError("A document format must be 'markdown', 'html' or 'text'");
@@ -214,15 +233,21 @@ function checkFormat(format: unknown): DocumentFormat {
214
233
  return format as DocumentFormat;
215
234
  }
216
235
 
217
- /** The policy must be one the kit could enforce: the profile is validated (a `ProfileError` names the field). */
218
- function checkPolicy(policy: DocumentPolicy): void {
236
+ /**
237
+ * The policy must be one the kit could enforce: the profile is validated (a `ProfileError` names the field). Returns the snapshot
238
+ * the document is built from: the profile read ONCE (it may be a live getter) with `durations` and `customDuration` filled in
239
+ * for a profile written before they existed, and the rules.
240
+ */
241
+ function checkPolicy(policy: DocumentPolicy): { profile: ResolvedProfile; rules: CommunityRules } {
219
242
  const p: unknown = policy;
220
243
  if (typeof p !== 'object' || p === null) throw new TypeError('A document policy needs a profile and rules');
221
244
  const rules = (p as { rules?: unknown }).rules;
222
245
  if (typeof rules !== 'object' || rules === null || typeof (rules as { active?: unknown }).active !== 'function') {
223
246
  throw new TypeError('A document policy needs a profile and rules');
224
247
  }
225
- validateProfile((p as { profile?: unknown }).profile);
248
+ const profile = (p as { profile?: unknown }).profile;
249
+ validateProfile(profile);
250
+ return { profile: withDurationDefaults(profile), rules: rules as CommunityRules };
226
251
  }
227
252
 
228
253
  /**
@@ -325,8 +350,6 @@ function ruleLabels(rules: CommunityRules, numbers: readonly number[] | undefine
325
350
  const RECORD_STEPS =
326
351
  '0 is notes only, 1 is a warning, 2 is a chat or area restriction under 7 days (or two warnings), 3 is a restriction of 7 days or more or a ban under 7 days, 4 is a ban of 7 to 29 days, 5 is a ban of 30 days or more or anything permanent';
327
352
 
328
- const DEFAULT_AREA_RULES: readonly number[] = [5, 6];
329
-
330
353
  function areaRuleList(policy: DocumentPolicy): Array<{ number: number; title: string }> {
331
354
  return ruleLabels(policy.rules, policy.profile.areaRules ?? DEFAULT_AREA_RULES);
332
355
  }
@@ -427,12 +450,12 @@ function swearingForPlayer(profile: ModerationProfile): string {
427
450
  * name and `ProfileError` for an invalid profile.
428
451
  */
429
452
  export function codeOfConduct(policy: DocumentPolicy, options: CodeOfConductOptions): string {
430
- checkPolicy(policy);
453
+ const snapshot = checkPolicy(policy);
431
454
  const format = checkFormat(options.format);
432
455
  const gameName = typeof options.gameName === 'string' ? clean(options.gameName) : '';
433
456
  if (gameName === '') throw new RangeError('A code of conduct needs a game name');
434
457
  const href = safeLink(options.contactUrl);
435
- const { profile, rules } = policy;
458
+ const { profile, rules } = snapshot;
436
459
  const firstRule = rules.active()[0];
437
460
  const example = firstRule === undefined ? '' : ` (for example, CR ${firstRule.number})`;
438
461
 
@@ -446,8 +469,8 @@ export function codeOfConduct(policy: DocumentPolicy, options: CodeOfConductOpti
446
469
  ];
447
470
  for (const tier of profile.guidelines) blocks.push(...playerTierBlocks(profile, tier));
448
471
 
449
- const area = areaRuleList(policy);
450
- const severe = severeRuleList(policy);
472
+ const area = areaRuleList(snapshot);
473
+ const severe = severeRuleList(snapshot);
451
474
  if (area.length > 0 || severe.length > 0) blocks.push({ k: 'h', level: 3, text: 'Some rules work differently' });
452
475
  if (area.length > 0) {
453
476
  const names = area.map((r) => `CR ${r.number} (${r.title})`).join(' or ');
@@ -518,9 +541,10 @@ function aiForModerators(profile: ModerationProfile): string {
518
541
  * Retired rules are omitted. Throws `RangeError` for an unknown format and `ProfileError` for an invalid profile.
519
542
  */
520
543
  export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOptions): string {
521
- checkPolicy(policy);
544
+ const snapshot = checkPolicy(policy);
522
545
  const format = checkFormat(options.format);
523
- const { profile, rules } = policy;
546
+ const omit = checkSections(options.omitSections);
547
+ const { profile, rules } = snapshot;
524
548
 
525
549
  const blocks: Block[] = [
526
550
  { k: 'h', level: 1, text: `Moderator guide: ${profile.name}` },
@@ -529,8 +553,7 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
529
553
  k: 'p',
530
554
  text: 'This guide is generated from the moderation profile and the Community Rules in force, so it matches what the kit enforces. It is for the moderation team: do not publish it.',
531
555
  },
532
- { k: 'h', level: 2, text: 'Community Rules' },
533
- { k: 'ul', items: ruleItems(rules) },
556
+ ...(omit.has('rules') ? [] : ([{ k: 'h', level: 2, text: 'Community Rules' }, { k: 'ul', items: ruleItems(rules) }] as Block[])),
534
557
  { k: 'h', level: 2, text: 'Conduct levels' },
535
558
  {
536
559
  k: 'table',
@@ -562,27 +585,31 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
562
585
  k: 'p',
563
586
  text: 'Repeated applies while the person has no warning or restriction on record; once they do, the ladder below applies. At least one earlier note is always needed. Revoked notes, and notes older than the window, do not count. An escalation is never milder than the first-offense outcome.',
564
587
  },
565
- { k: 'h', level: 2, text: 'Escalation ladder' },
566
- {
567
- k: 'p',
568
- text: `A person's step is the heaviest action on their record in the last 90 days. Step ${RECORD_STEPS}.`,
569
- },
570
- {
571
- k: 'table',
572
- head: ['Step', 'Low / medium (banter, rude)', 'High (hostile with a record, severe)'],
573
- rows: profile.ladder.map((row) => [String(row.step), clean(row.lowMedium.label), clean(row.high.label)]),
574
- },
575
588
  );
576
- const area = areaRuleList(policy);
577
- if (area.length > 0) {
578
- blocks.push({
579
- k: 'p',
580
- text: `Rules that turn a chat restriction into a ban from public rooms and matchmaking at the same length: ${area.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.`,
581
- });
582
- }
583
- const severe = severeRuleList(policy);
584
- if (severe.length > 0) {
585
- blocks.push({ k: 'p', text: `Rules that always read the High column: ${severe.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.` });
589
+ if (!omit.has('ladder')) {
590
+ blocks.push(
591
+ { k: 'h', level: 2, text: 'Escalation ladder' },
592
+ {
593
+ k: 'p',
594
+ text: `A person's step is the heaviest action on their record in the last 90 days. Step ${RECORD_STEPS}.`,
595
+ },
596
+ {
597
+ k: 'table',
598
+ head: ['Step', 'Low / medium (banter, rude)', 'High (hostile with a record, severe)'],
599
+ rows: profile.ladder.map((row) => [String(row.step), clean(row.lowMedium.label), clean(row.high.label)]),
600
+ },
601
+ );
602
+ const area = areaRuleList(snapshot);
603
+ if (area.length > 0) {
604
+ blocks.push({
605
+ k: 'p',
606
+ text: `Rules that turn a chat restriction into a ban from public rooms and matchmaking at the same length: ${area.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.`,
607
+ });
608
+ }
609
+ const severe = severeRuleList(snapshot);
610
+ if (severe.length > 0) {
611
+ blocks.push({ k: 'p', text: `Rules that always read the High column: ${severe.map((r) => `CR ${r.number}. ${r.title}`).join('; ')}.` });
612
+ }
586
613
  }
587
614
 
588
615
  blocks.push(
@@ -624,8 +651,8 @@ export function moderatorGuide(policy: DocumentPolicy, options: ModeratorGuideOp
624
651
  * team-written value cannot add a line of policy. Retired rules are omitted.
625
652
  */
626
653
  export function agentBrief(policy: DocumentPolicy): string {
627
- checkPolicy(policy);
628
- const { profile, rules } = policy;
654
+ const snapshot = checkPolicy(policy);
655
+ const { profile, rules } = snapshot;
629
656
  const lines: string[] = [
630
657
  `Moderation policy for ${clean(profile.name)} (generated by Chatwarden)`,
631
658
  `Summary: ${clean(profile.summary)}`,
@@ -648,11 +675,11 @@ export function agentBrief(policy: DocumentPolicy): string {
648
675
  'Escalation after the first offense. Step = heaviest action on the record in the last 90 days. Low = banter and rude; high = hostile once the record has a warning or restriction, and severe:',
649
676
  ...profile.ladder.map((row) => `- step ${row.step}: low ${clean(row.lowMedium.label)} | high ${clean(row.high.label)}`),
650
677
  ];
651
- const area = areaRuleList(policy);
678
+ const area = areaRuleList(snapshot);
652
679
  if (area.length > 0) {
653
680
  lines.push(`A chat restriction becomes a ban from public rooms and matchmaking (same length) for: ${area.map((r) => `CR ${r.number}`).join(', ')}.`);
654
681
  }
655
- const severe = severeRuleList(policy);
682
+ const severe = severeRuleList(snapshot);
656
683
  if (severe.length > 0) lines.push(`Always read the high column for: ${severe.map((r) => `CR ${r.number}`).join(', ')}.`);
657
684
  lines.push(
658
685
  'Guidelines:',
@@ -677,8 +704,8 @@ export function agentBrief(policy: DocumentPolicy): string {
677
704
  * into `defineProfile` and `defineRules`. Throws `ProfileError` for an invalid profile.
678
705
  */
679
706
  export function policyJson(policy: DocumentPolicy): PolicyJson {
680
- checkPolicy(policy);
681
- return { version: 1, profile: structuredClone(policy.profile), rules: policy.rules.all() };
707
+ const snapshot = checkPolicy(policy);
708
+ return { version: 1, profile: structuredClone(snapshot.profile), rules: snapshot.rules.all() };
682
709
  }
683
710
 
684
711
  /** The four documents bound to one policy, as `cw.documents` exposes them. */