@chatwarden/core 0.1.8 → 0.1.10

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 (115) hide show
  1. package/README.md +189 -5
  2. package/dist/src/ai/case.d.ts +2 -1
  3. package/dist/src/ai/case.d.ts.map +1 -1
  4. package/dist/src/ai/case.js +1 -1
  5. package/dist/src/ai/case.js.map +1 -1
  6. package/dist/src/ai/hash.d.ts +1 -1
  7. package/dist/src/ai/hash.js +3 -3
  8. package/dist/src/ai/hash.js.map +1 -1
  9. package/dist/src/ai/prompt.d.ts +8 -1
  10. package/dist/src/ai/prompt.d.ts.map +1 -1
  11. package/dist/src/ai/prompt.js +20 -1
  12. package/dist/src/ai/prompt.js.map +1 -1
  13. package/dist/src/ai/service.d.ts +16 -5
  14. package/dist/src/ai/service.d.ts.map +1 -1
  15. package/dist/src/ai/service.js +12 -7
  16. package/dist/src/ai/service.js.map +1 -1
  17. package/dist/src/ai/types.d.ts +17 -2
  18. package/dist/src/ai/types.d.ts.map +1 -1
  19. package/dist/src/ai/types.js +3 -2
  20. package/dist/src/ai/types.js.map +1 -1
  21. package/dist/src/ai/worker.d.ts +5 -0
  22. package/dist/src/ai/worker.d.ts.map +1 -1
  23. package/dist/src/ai/worker.js +9 -2
  24. package/dist/src/ai/worker.js.map +1 -1
  25. package/dist/src/appealService.d.ts +105 -0
  26. package/dist/src/appealService.d.ts.map +1 -0
  27. package/dist/src/appealService.js +548 -0
  28. package/dist/src/appealService.js.map +1 -0
  29. package/dist/src/appeals.d.ts +194 -0
  30. package/dist/src/appeals.d.ts.map +1 -0
  31. package/dist/src/appeals.js +107 -0
  32. package/dist/src/appeals.js.map +1 -0
  33. package/dist/src/audit.d.ts +7 -3
  34. package/dist/src/audit.d.ts.map +1 -1
  35. package/dist/src/audit.js +18 -3
  36. package/dist/src/audit.js.map +1 -1
  37. package/dist/src/chatwarden.d.ts +129 -9
  38. package/dist/src/chatwarden.d.ts.map +1 -1
  39. package/dist/src/chatwarden.js +94 -19
  40. package/dist/src/chatwarden.js.map +1 -1
  41. package/dist/src/decide.d.ts +2 -0
  42. package/dist/src/decide.d.ts.map +1 -1
  43. package/dist/src/decide.js +12 -7
  44. package/dist/src/decide.js.map +1 -1
  45. package/dist/src/documents.d.ts +1 -1
  46. package/dist/src/documents.d.ts.map +1 -1
  47. package/dist/src/documents.js +3 -1
  48. package/dist/src/documents.js.map +1 -1
  49. package/dist/src/events.d.ts +38 -0
  50. package/dist/src/events.d.ts.map +1 -1
  51. package/dist/src/events.js +3 -0
  52. package/dist/src/events.js.map +1 -1
  53. package/dist/src/index.d.ts +9 -5
  54. package/dist/src/index.d.ts.map +1 -1
  55. package/dist/src/index.js +5 -2
  56. package/dist/src/index.js.map +1 -1
  57. package/dist/src/nameService.d.ts +90 -0
  58. package/dist/src/nameService.d.ts.map +1 -0
  59. package/dist/src/nameService.js +224 -0
  60. package/dist/src/nameService.js.map +1 -0
  61. package/dist/src/names.d.ts +68 -0
  62. package/dist/src/names.d.ts.map +1 -0
  63. package/dist/src/names.js +87 -0
  64. package/dist/src/names.js.map +1 -0
  65. package/dist/src/notices.d.ts +53 -5
  66. package/dist/src/notices.d.ts.map +1 -1
  67. package/dist/src/notices.js +93 -8
  68. package/dist/src/notices.js.map +1 -1
  69. package/dist/src/policy.d.ts +9 -0
  70. package/dist/src/policy.d.ts.map +1 -1
  71. package/dist/src/policy.js +20 -2
  72. package/dist/src/policy.js.map +1 -1
  73. package/dist/src/profile.d.ts +23 -1
  74. package/dist/src/profile.d.ts.map +1 -1
  75. package/dist/src/profile.js +14 -2
  76. package/dist/src/profile.js.map +1 -1
  77. package/dist/src/retention.d.ts +31 -1
  78. package/dist/src/retention.d.ts.map +1 -1
  79. package/dist/src/retention.js +41 -3
  80. package/dist/src/retention.js.map +1 -1
  81. package/dist/src/sanctions.d.ts +29 -1
  82. package/dist/src/sanctions.d.ts.map +1 -1
  83. package/dist/src/sanctions.js +52 -9
  84. package/dist/src/sanctions.js.map +1 -1
  85. package/dist/src/staffViews.d.ts +18 -0
  86. package/dist/src/staffViews.d.ts.map +1 -1
  87. package/dist/src/staffViews.js +14 -0
  88. package/dist/src/staffViews.js.map +1 -1
  89. package/dist/src/types.d.ts +198 -6
  90. package/dist/src/types.d.ts.map +1 -1
  91. package/dist/src/types.js.map +1 -1
  92. package/package.json +2 -2
  93. package/src/ai/case.ts +4 -2
  94. package/src/ai/hash.ts +3 -3
  95. package/src/ai/prompt.ts +23 -1
  96. package/src/ai/service.ts +21 -12
  97. package/src/ai/types.ts +14 -2
  98. package/src/ai/worker.ts +10 -2
  99. package/src/appealService.ts +584 -0
  100. package/src/appeals.ts +256 -0
  101. package/src/audit.ts +18 -3
  102. package/src/chatwarden.ts +199 -21
  103. package/src/decide.ts +13 -7
  104. package/src/documents.ts +6 -3
  105. package/src/events.ts +23 -1
  106. package/src/index.ts +12 -1
  107. package/src/nameService.ts +255 -0
  108. package/src/names.ts +121 -0
  109. package/src/notices.ts +112 -14
  110. package/src/policy.ts +20 -3
  111. package/src/profile.ts +34 -2
  112. package/src/retention.ts +63 -3
  113. package/src/sanctions.ts +72 -9
  114. package/src/staffViews.ts +30 -0
  115. package/src/types.ts +210 -7
package/src/notices.ts CHANGED
@@ -22,6 +22,31 @@ export const NOTICE_LOOKUP_CACHE_MAX = 10_000;
22
22
  // A `note` is deliberately absent: it is on the record for staff and never makes a notice (see `DecisionService`).
23
23
  const SANCTION_NOTICE_KINDS: readonly NoticeKind[] = ['warning', 'chat', 'area', 'ban'];
24
24
 
25
+ /**
26
+ * The four notices that are messages, not sanctions: a rename is required, an appeal was upheld, reduced or revoked. They have no
27
+ * group, no end and no excerpt, show in `pending` and `announce` and never on "My record", and never need an acknowledgement. Made by
28
+ * {@link NoticeService.createMessage}. A seen one is purged like a seen report outcome; an unseen one is kept until seen or withdrawn.
29
+ * @experimental
30
+ */
31
+ export const MESSAGE_NOTICE_KINDS = ['rename_required', 'appeal_upheld', 'appeal_reduced', 'appeal_revoked'] as const;
32
+ export type MessageNoticeKind = (typeof MESSAGE_NOTICE_KINDS)[number];
33
+
34
+ /** Every kind this build can show. A stored row of any other kind (written by a newer kit) is skipped, never thrown on. */
35
+ /**
36
+ * Whether a notice row is on "My record" now: not withdrawn, one of the four sanction kinds, and either made within 90 days or (not a
37
+ * warning) permanent or still running. The one definition `record` uses and an appeal is filed against.
38
+ */
39
+ export function appliesInRecord(r: Pick<NoticeRow, 'withdrawnAt' | 'kind' | 'createdAt' | 'until'>, now: number): boolean {
40
+ return (
41
+ r.withdrawnAt === null &&
42
+ SANCTION_NOTICE_KINDS.includes(r.kind) &&
43
+ (r.createdAt >= now - NOTICE_RECORD_WINDOW_MS || (r.kind !== 'warning' && (r.until === null || r.until > now)))
44
+ );
45
+ }
46
+
47
+ const KNOWN_KINDS: readonly string[] = [...SANCTION_NOTICE_KINDS, 'report_outcome', ...MESSAGE_NOTICE_KINDS];
48
+ const isMessageKind = (kind: unknown): kind is MessageNoticeKind => (MESSAGE_NOTICE_KINDS as readonly unknown[]).includes(kind);
49
+
25
50
  /**
26
51
  * What a player is shown about a sanction taken against them, or about a report they filed. The ONLY shape that
27
52
  * leaves the kit for a player. It carries no subject, key, hash, room, seat or handle, no moderator reason or
@@ -31,13 +56,13 @@ export interface PlayerNotice {
31
56
  /** Random; the handle for `ack`. */
32
57
  id: string;
33
58
  kind: NoticeKind;
34
- /** The Community Rule cited; null for a report outcome. */
59
+ /** The Community Rule cited; null for a report outcome (and for a message that cites none). */
35
60
  rule: RuleRef | null;
36
61
  /** The player-facing name of the rule. */
37
62
  ruleLabel: string | null;
38
- /** Epoch ms the sanction ends; null = no end (permanent, a warning, or a report outcome). */
63
+ /** Epoch ms the sanction ends; null = no end (permanent, a warning, a report outcome or a message). */
39
64
  until: number | null;
40
- /** The reference code to quote to a moderator; null for a report outcome. */
65
+ /** The reference code to quote to a moderator; null for a report outcome (a message carries the original sanction's, or none). */
41
66
  refCode: string | null;
42
67
  /** At most five of the player's own lines. `day` is UTC `YYYY-MM-DD`. A blocked line has its matched terms masked. */
43
68
  excerpt: Array<{ text: string; day: string }>;
@@ -134,6 +159,14 @@ export interface NoticeCreateOptions {
134
159
  notify?: boolean;
135
160
  }
136
161
 
162
+ /** What a message notice may cite: the rule and the reference code of the decision it is about. Never a name, a reason or an excerpt. */
163
+ export interface MessageNoticeOptions extends NoticeCreateOptions {
164
+ /** The Community Rule the original decision cited. Default null. */
165
+ rule?: RuleRef | null;
166
+ /** The reference code of the original sanction, to quote to a moderator. Default null. */
167
+ refCode?: string | null;
168
+ }
169
+
137
170
  /** What a notice is told about a sanction. `excerptLines` come through {@link ownLines}. */
138
171
  export interface SanctionNoticeInput {
139
172
  groupId: string;
@@ -241,6 +274,28 @@ export class NoticeService {
241
274
  );
242
275
  }
243
276
 
277
+ /**
278
+ * Write a message notice (a rename is required, an appeal was upheld, reduced or revoked) for a person and tell their client.
279
+ * Returns the notice id. It carries the kind, an optional rule and reference code and the time, and nothing else: no excerpt, no name,
280
+ * no reason. It has no sanction group, so `withdrawGroup` never touches it. Throws for any other kind, a malformed rule or code, or a
281
+ * bad subject (nothing is written). Pass `{ notify: false }` inside a larger transaction, then call {@link announce} after the commit.
282
+ * @experimental
283
+ */
284
+ createMessage(subject: SubjectId, kind: MessageNoticeKind, opts: MessageNoticeOptions = {}): string {
285
+ if (!isMessageKind(kind)) throw new Error('createMessage: invalid kind');
286
+ if (!nonEmpty(subject)) throw new Error('createMessage: invalid subject');
287
+ const rule = opts.rule ?? null;
288
+ const refCode = opts.refCode ?? null;
289
+ if (refCode !== null && typeof refCode !== 'string') throw new Error('createMessage: invalid code');
290
+ if (rule !== null) parseRuleRef(String(rule)); // refuses a value the store could not read back
291
+ const canonical = this.subjects.canonical(subject);
292
+ return this.insert(
293
+ { subject: canonical, groupId: null, kind, rule: rule === null ? null : String(rule), until: null, refCode, excerpt: [] },
294
+ canonical,
295
+ opts.notify !== false,
296
+ );
297
+ }
298
+
244
299
  /** Tell a reporter that their report led to action. No rule, code, end or excerpt: nothing about the other player. */
245
300
  createReportOutcome(reporter: SubjectId, opts: NoticeCreateOptions = {}): string {
246
301
  if (!nonEmpty(reporter)) throw new Error('createReportOutcome: invalid subject');
@@ -284,22 +339,62 @@ export class NoticeService {
284
339
  /**
285
340
  * "My record": the person's sanction notices (seen or not) that are not withdrawn and still apply. A warning
286
341
  * applies for 90 days from when it was made (the ladder lookback). Any other kind applies while it is permanent
287
- * (until it is withdrawn), still running, or made within 90 days. Report outcomes are never included. Decided from
342
+ * (until it is withdrawn), still running, or made within 90 days. Report outcomes and the four message kinds are never included. Decided from
288
343
  * the notice row alone; `purgeNotices` agrees with this, so a row that applies is never purged.
289
344
  */
290
345
  record(subject: SubjectId): PlayerNotice[] {
291
346
  const now = this.clock.now();
292
347
  return this.rowsOf(subject)
293
- .filter(
294
- (r) =>
295
- r.withdrawnAt === null &&
296
- r.kind !== 'report_outcome' &&
297
- (r.createdAt >= now - NOTICE_RECORD_WINDOW_MS ||
298
- (r.kind !== 'warning' && (r.until === null || r.until > now))),
299
- )
348
+ .filter((r) => appliesInRecord(r, now))
300
349
  .map((r) => this.toPlayer(r));
301
350
  }
302
351
 
352
+ /**
353
+ * The stored notice `id` when it belongs to this person (across their merged aliases), whatever its kind or state; null otherwise.
354
+ * Staff-side: the row names its sanction group. For the appeals service, which decides from the row whether it can be appealed.
355
+ */
356
+ ownRow(subject: SubjectId, id: string): NoticeRow | null {
357
+ if (!nonEmpty(id)) return null;
358
+ return this.rowsOf(subject).find((r) => r.id === id) ?? null;
359
+ }
360
+
361
+ /**
362
+ * Does the person have a required rename they have not been released from: a `rename_required` notice not withdrawn, seen or not, on any of
363
+ * their merged subjects. Staff-side; the game reads it through `names.pendingRename`.
364
+ */
365
+ renamePending(subject: SubjectId): boolean {
366
+ return this.rowsOf(subject).some((r) => r.kind === 'rename_required' && r.withdrawnAt === null);
367
+ }
368
+
369
+ /** A person's `rename_required` notices, newest first, withdrawn ones included, across their merged subjects. Staff-side. */
370
+ renameRows(subject: SubjectId): NoticeRow[] {
371
+ return this.rowsOf(subject)
372
+ .filter((r) => r.kind === 'rename_required')
373
+ .sort((a, b) => b.createdAt - a.createdAt || (a.id < b.id ? 1 : -1));
374
+ }
375
+
376
+ /** Can this build's store withdraw one notice by id? Without it a rename could never be released. */
377
+ canWithdrawOne(): boolean {
378
+ return typeof this.store.withdrawNotice === 'function';
379
+ }
380
+
381
+ /**
382
+ * Withdraw every pending `rename_required` notice of the person, in one transaction, and tell their client the new count when any was.
383
+ * Returns how many it withdrew (0 when none was pending, or the store cannot withdraw one). Other kinds are never touched.
384
+ */
385
+ withdrawRenames(subject: SubjectId): number {
386
+ const withdraw = this.store.withdrawNotice;
387
+ if (typeof withdraw !== 'function') return 0;
388
+ const ids = this.rowsOf(subject)
389
+ .filter((r) => r.kind === 'rename_required' && r.withdrawnAt === null)
390
+ .map((r) => r.id);
391
+ if (ids.length === 0) return 0;
392
+ const at = this.clock.now();
393
+ const done = this.store.transaction(() => ids.filter((id) => withdraw.call(this.store, id, at)).length);
394
+ if (done > 0) this.announce(subject);
395
+ return done;
396
+ }
397
+
303
398
  /** Withdraw the notices of a sanction group (it was revoked). Returns how many were withdrawn. */
304
399
  withdrawGroup(groupId: string): number {
305
400
  if (!nonEmpty(groupId)) return 0;
@@ -385,13 +480,16 @@ export class NoticeService {
385
480
  private rowsOf(subject: SubjectId): NoticeRow[] {
386
481
  if (!nonEmpty(subject)) return [];
387
482
  const person = this.subjects.canonical(subject);
388
- return this.store.loadNotices(this.subjects.aliasesOf(person)).filter((r) => this.subjects.canonical(r.subject) === person);
483
+ return this.store
484
+ .loadNotices(this.subjects.aliasesOf(person))
485
+ .filter((r) => KNOWN_KINDS.includes(r.kind) && this.subjects.canonical(r.subject) === person);
389
486
  }
390
487
 
391
488
  private toPlayer(r: NoticeRow): PlayerNotice {
392
489
  if (r.kind === 'report_outcome') {
393
490
  return { id: r.id, kind: r.kind, rule: null, ruleLabel: null, until: null, refCode: null, excerpt: [], createdAt: r.createdAt, mustAcknowledge: false };
394
491
  }
492
+ const message = isMessageKind(r.kind);
395
493
  let rule: RuleRef | null = null;
396
494
  if (r.rule !== null) {
397
495
  try {
@@ -405,9 +503,9 @@ export class NoticeService {
405
503
  kind: r.kind,
406
504
  rule,
407
505
  ruleLabel: rule === null ? null : this.rules.label(rule),
408
- until: r.until,
506
+ until: message ? null : r.until,
409
507
  refCode: r.refCode,
410
- excerpt: r.excerpt.map((l) => ({ text: l.text, day: l.day })),
508
+ excerpt: message ? [] : r.excerpt.map((l) => ({ text: l.text, day: l.day })),
411
509
  createdAt: r.createdAt,
412
510
  mustAcknowledge: r.kind === 'warning',
413
511
  };
package/src/policy.ts CHANGED
@@ -6,7 +6,7 @@ import type { PolicyLayer, PolicySection, ResolvedProfile } from './profile.js';
6
6
  import { playerReporting } from './reporting.js';
7
7
  import type { PlayerReporting } from './reporting.js';
8
8
  import type { RuleRef } from './rules.js';
9
- import { errorClass, safeWarn } from './log.js';
9
+ import { errorClass, safeWarn, ThrottledWarn } from './log.js';
10
10
  import { RETENTION_DEFAULTS } from './retention.js';
11
11
  import { checkSignalFeeds, pruneSignalFeeds, SIGNAL_FEED_NAMES } from './signals.js';
12
12
  import type { SignalDropReason } from './signals.js';
@@ -141,8 +141,13 @@ export class PolicyService {
141
141
  private readonly signalsMs: () => number;
142
142
  /** The chat rate in force (`limits.chatRate`), for `get().limits`. */
143
143
  private readonly chatRate: { count: number; windowMs: number };
144
+ /** Whether the store has the appeal methods. Without them a layer cannot turn appeals on: it is refused when saved, and kept off when read. */
145
+ private readonly appealsKept: boolean;
146
+ private readonly appealsWarn: ThrottledWarn;
144
147
 
145
- constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile; signalsMs?: () => number; chatRate?: { count: number; windowMs: number } }) {
148
+ constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile; signalsMs?: () => number; chatRate?: { count: number; windowMs: number }; appealsKept?: boolean }) {
149
+ this.appealsKept = deps.appealsKept ?? true;
150
+ this.appealsWarn = new ThrottledWarn(deps.logger, deps.clock);
146
151
  this.signalsMs = deps.signalsMs ?? (() => RETENTION_DEFAULTS.signalsMs);
147
152
  this.chatRate = Object.freeze({ count: deps.chatRate?.count ?? RATE_LIMIT, windowMs: deps.chatRate?.windowMs ?? RATE_WINDOW_MS });
148
153
  this.store = deps.store;
@@ -163,6 +168,16 @@ export class PolicyService {
163
168
  this.adopt(this.store.loadPolicyLayer?.() ?? null);
164
169
  }
165
170
 
171
+ /**
172
+ * The profile as the store can serve it: a layer that turned appeals on over a store without the appeal methods leaves them off
173
+ * (a code profile that asked for them is refused at creation, never here). Warned by class only, throttled.
174
+ */
175
+ private served(effective: ResolvedProfile): ResolvedProfile {
176
+ if (this.appealsKept || !effective.appeals.enabled || this.base.appeals.enabled) return effective;
177
+ this.appealsWarn.warn('chatwarden.appeals_unsupported_store', {});
178
+ return Object.freeze({ ...effective, appeals: Object.freeze({ ...effective.appeals, enabled: false }) });
179
+ }
180
+
166
181
  /** Make `stored` the layer in force: the effective profile is rebuilt, or the base kept when the layer cannot be used. */
167
182
  private adopt(stored: { layer: PolicyLayer; version: number } | null): void {
168
183
  const version = stored?.version ?? 0;
@@ -173,7 +188,7 @@ export class PolicyService {
173
188
  // What is read and shown is the layer in force: the stale feeds are out of it, so a save that sends it back is never refused for them.
174
189
  const { layer: inForce, dropped } = this.withoutStaleFeeds(layer);
175
190
  const shown = dropped.length === 0 ? layer : frozenCopy(inForce);
176
- this.state = { effective: applyPolicyLayer(this.base, shown), layer: shown, version, ...(dropped.length === 0 ? {} : { dropped: Object.freeze(dropped.map((d) => Object.freeze(d))) }) };
191
+ this.state = { effective: this.served(applyPolicyLayer(this.base, shown)), layer: shown, version, ...(dropped.length === 0 ? {} : { dropped: Object.freeze(dropped.map((d) => Object.freeze(d))) }) };
177
192
  } catch (err) {
178
193
  if (!(err instanceof ProfileError)) throw err;
179
194
  // What `get()` shows is always an object: an unreadable layer reads as empty, with the error beside it.
@@ -311,6 +326,8 @@ export class PolicyService {
311
326
  const effective = applyPolicyLayer(this.base, layer);
312
327
  // The windows are checked against the retention here, where it is known: a window longer than it could never be met.
313
328
  checkSignalFeeds(effective.signals.feeds, effective.signals.kinds, { signalsMs: this.signalsMs() }, 'layer.signals.feeds');
329
+ // A switch that would do nothing is refused, so the owner is not shown "on" over a store that cannot keep appeals.
330
+ if (!this.appealsKept && effective.appeals.enabled && !this.base.appeals.enabled) return { ok: false, error: 'invalid', path: 'layer.appeals.enabled' };
314
331
  } catch (err) {
315
332
  if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
316
333
  throw err;
package/src/profile.ts CHANGED
@@ -21,6 +21,10 @@ import type { ReportingSettings, ResolvedReporting } from './reporting.js';
21
21
  import { deepFreeze } from './freeze.js';
22
22
  import { mergePace, resolvePace } from './pace.js';
23
23
  import type { PaceSettings, ResolvedPace } from './pace.js';
24
+ import { resolveAppeals } from './appeals.js';
25
+ import type { AppealSettings, ResolvedAppeals } from './appeals.js';
26
+ import { resolveNames } from './names.js';
27
+ import type { NameSettings, ResolvedNames } from './names.js';
24
28
  import { checkSignalFeeds, resolveSignals } from './signals.js';
25
29
  import type { ResolvedSignals, SignalFeeds, SignalSettings } from './signals.js';
26
30
  import { ProfileError } from './profileError.js';
@@ -170,6 +174,18 @@ export interface ModerationProfile extends ModerationProfileBase {
170
174
  * @experimental
171
175
  */
172
176
  signals?: SignalSettings;
177
+ /**
178
+ * Appeals: whether players may appeal a sanction from its notice, how many a week, and whether the moderator who made the original
179
+ * decision may decide its appeal. Off until set, so a profile without `appeals` changes nothing. See {@link AppealSettings}.
180
+ * @experimental
181
+ */
182
+ appeals?: AppealSettings;
183
+ /**
184
+ * Names: a profanity pass on the name check, kept evidence of blocked names, required renames, and masking a flagged name in the
185
+ * hub (on by default; it changes only what the hub shows). See {@link NameSettings}.
186
+ * @experimental
187
+ */
188
+ names?: NameSettings;
173
189
  }
174
190
 
175
191
  /**
@@ -217,6 +233,10 @@ export interface ResolvedProfile extends ModerationProfileBase {
217
233
  pace: ResolvedPace;
218
234
  /** The signal settings in force: the declared kinds merged over the built-ins, the guards filled in, the feeds as given. @experimental */
219
235
  signals: ResolvedSignals;
236
+ /** The appeal settings in force, every field filled in. @experimental */
237
+ appeals: ResolvedAppeals;
238
+ /** The name settings in force, every field filled in. @experimental */
239
+ names: ResolvedNames;
220
240
  }
221
241
 
222
242
  /** @deprecated The same as {@link ModerationProfile}, which now has the two fields optional. */
@@ -256,12 +276,14 @@ const TOP_KEYS = [
256
276
  'ai',
257
277
  'pace',
258
278
  'signals',
279
+ 'appeals',
280
+ 'names',
259
281
  'levels',
260
282
  'guidelines',
261
283
  ] as const;
262
284
  /** Top-level keys that may be left out (the kit falls back to its defaults). */
263
285
  const RULE_LIST_KEYS: readonly string[] = ['areaRules', 'severeRules'];
264
- const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai', 'pace', 'signals'];
286
+ const OPTIONAL_TOP_KEYS: readonly string[] = [...RULE_LIST_KEYS, 'durations', 'customDuration', 'reporting', 'ai', 'pace', 'signals', 'appeals', 'names'];
265
287
  const AI_KEYS = ['level', 'learn', 'dailyCalls'] as const;
266
288
  /** The most rule numbers `areaRules` or `severeRules` may list. */
267
289
  export const MAX_RULE_LIST = 100;
@@ -543,6 +565,8 @@ export function validateProfile(value: unknown): asserts value is ModerationProf
543
565
  if (Object.hasOwn(p, 'ai')) validateAI(p['ai'], 'profile.ai');
544
566
  if (Object.hasOwn(p, 'pace')) resolvePace(p['pace'] as PaceSettings, 'profile.pace');
545
567
  if (Object.hasOwn(p, 'signals')) resolveSignals(p['signals'] as SignalSettings, 'profile.signals');
568
+ if (Object.hasOwn(p, 'appeals')) resolveAppeals(p['appeals'] as AppealSettings, 'profile.appeals');
569
+ if (Object.hasOwn(p, 'names')) resolveNames(p['names'] as NameSettings, 'profile.names');
546
570
 
547
571
  const prof = obj(p['profanity'], 'profile.profanity', PROFANITY_KEYS);
548
572
  oneOf(prof['mode'], 'profile.profanity.mode', PROFANITY_MODES, "must be 'allow', 'star' or 'refuse'");
@@ -657,6 +681,8 @@ function finalize(value: unknown): ResolvedProfile {
657
681
  if (isPlain(copy)) {
658
682
  setOwn(copy, 'pace', resolvePace(copy['pace'] as PaceSettings | undefined, 'profile.pace'));
659
683
  setOwn(copy, 'signals', resolveSignals(copy['signals'] as SignalSettings | undefined, 'profile.signals'));
684
+ setOwn(copy, 'appeals', resolveAppeals(copy['appeals'] as AppealSettings | undefined, 'profile.appeals'));
685
+ setOwn(copy, 'names', resolveNames(copy['names'] as NameSettings | undefined, 'profile.names'));
660
686
  }
661
687
  return deepFreeze(copy as ResolvedProfile);
662
688
  }
@@ -674,6 +700,8 @@ export function withDurationDefaults(p: ModerationProfile): ResolvedProfile {
674
700
  ai: { level: 0, learn: true, dailyCalls: AI_DAILY_CALLS_DEFAULT, ...p.ai },
675
701
  pace: resolvePace(p.pace),
676
702
  signals: resolveSignals(p.signals),
703
+ appeals: resolveAppeals(p.appeals),
704
+ names: resolveNames(p.names),
677
705
  };
678
706
  }
679
707
 
@@ -994,7 +1022,7 @@ export function defineProfile(p: ModerationProfile): ResolvedProfile {
994
1022
  * The parts of a profile the hub may edit, and the order they are listed in. Everything else (identity, the written
995
1023
  * levels, the AI context, profanity handling) stays in code: changing profanity means rebuilding the filter.
996
1024
  */
997
- export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai', 'pace', 'signals'] as const;
1025
+ export const POLICY_SECTIONS = ['durations', 'customDuration', 'ladder', 'firstOffense', 'repeat', 'areaRules', 'severeRules', 'guidelines', 'reporting', 'ai', 'pace', 'signals', 'appeals', 'names'] as const;
998
1026
  export type PolicySection = (typeof POLICY_SECTIONS)[number];
999
1027
 
1000
1028
  /** One ladder cell as the editor sends it: the label may be left out and is then generated ("Restrict chat 6 hours"). */
@@ -1040,6 +1068,10 @@ export interface PolicyLayer {
1040
1068
  * profile's wholesale, like every other section: a feed left out is off. A feed names declared kinds only. @experimental
1041
1069
  */
1042
1070
  signals?: { feeds?: SignalFeeds };
1071
+ /** The appeal settings: `enabled`, `perPlayerPerWeek` (1 to 20) and `allowSelfReview`. Each is optional and merges onto the profile's. @experimental */
1072
+ appeals?: AppealSettings;
1073
+ /** The name settings: `profanity`, `keepBlocked`, `renames` and `maskInHub`. Each is optional and merges onto the profile's. @experimental */
1074
+ names?: NameSettings;
1043
1075
  }
1044
1076
 
1045
1077
  /** The longest outcome text a layer may set on a guideline tier. */
package/src/retention.ts CHANGED
@@ -40,6 +40,20 @@ export interface RetentionPolicy {
40
40
  * days: a counting window needs at least two weeks of rows. A feed window longer than this is refused.
41
41
  */
42
42
  signalsMs: number;
43
+ /**
44
+ * The statement of a decided (or closed) appeal is set to nothing this long after the decision. It is the one new free text a player
45
+ * writes, so it is the shortest of the three. An open appeal's statement is kept until it is decided. 0 clears it at the next purge
46
+ * (and at the decision itself); no floor.
47
+ */
48
+ appealStatementsMs: number;
49
+ /**
50
+ * A decided appeal row is deleted this long after its decision. At least 90 days: the per-rule counts and the false-positive rate read
51
+ * these rows over a 90 day window. An appeal on a permanent sanction that is still in force is kept regardless (it stops a second appeal
52
+ * against it), and an open appeal is never deleted.
53
+ */
54
+ appealsMs: number;
55
+ /** A blocked name kept as evidence (`names.keepBlocked`) is deleted once it is older than this. The same clock as strikes. No floor. */
56
+ blockedNamesMs: number;
43
57
  }
44
58
 
45
59
  export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
@@ -52,12 +66,15 @@ export const RETENTION_DEFAULTS: Readonly<RetentionPolicy> = {
52
66
  aiOutcomesMs: 365 * DAY_MS,
53
67
  aiExamplesMs: 180 * DAY_MS,
54
68
  signalsMs: 90 * DAY_MS,
69
+ appealStatementsMs: 90 * DAY_MS,
70
+ appealsMs: 365 * DAY_MS,
71
+ blockedNamesMs: 30 * DAY_MS,
55
72
  };
56
73
 
57
74
  /** The ladder looks back 90 days and "My record" shows 90 days, so the rows behind them must outlive that. */
58
75
  const RECORD_FLOOR_MS = 90 * DAY_MS;
59
76
 
60
- const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs', 'signalsMs'] as const;
77
+ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'badFaithMs', 'auditMs', 'aiOutcomesMs', 'aiExamplesMs', 'signalsMs', 'appealStatementsMs', 'appealsMs', 'blockedNamesMs'] as const;
61
78
 
62
79
  /**
63
80
  * Refuse a retention policy that would delete rows the kit still reads. Only the fields present are checked (an
@@ -69,6 +86,8 @@ const FIELDS = ['reportsMs', 'sanctionAfterEndMs', 'strikesMs', 'noticesMs', 'ba
69
86
  * - `aiOutcomesMs` at least 90 days: the agree-or-override record is the data the AI's later gates read
70
87
  * - `aiExamplesMs` at least 0 (0 keeps no example text at all)
71
88
  * - `signalsMs` at least 14 days: a counting window needs at least two weeks of rows
89
+ * - `appealsMs` at least 90 days: the per-rule appeal counts read that far back
90
+ * - `appealStatementsMs` and `blockedNamesMs` at least 0 (0 keeps the text only until the next purge)
72
91
  *
73
92
  * Every field present must also be a finite number (`reportsMs` and `strikesMs` have no floor, only this).
74
93
  *
@@ -106,6 +125,15 @@ export function checkRetentionFloors(policy: Partial<RetentionPolicy>, suspendWi
106
125
  if (below(policy.signalsMs, 14 * DAY_MS)) {
107
126
  throw new ProfileError('retention.signalsMs', 'must be at least 14 days: a counting window needs at least two weeks of rows');
108
127
  }
128
+ if (below(policy.appealsMs, RECORD_FLOOR_MS)) {
129
+ throw new ProfileError('retention.appealsMs', 'must be at least 90 days: the per-rule appeal counts read that far back');
130
+ }
131
+ if (below(policy.appealStatementsMs, 0)) {
132
+ throw new ProfileError('retention.appealStatementsMs', 'must be 0 or more: 0 clears a statement as soon as its appeal is decided');
133
+ }
134
+ if (below(policy.blockedNamesMs, 0)) {
135
+ throw new ProfileError('retention.blockedNamesMs', 'must be 0 or more');
136
+ }
109
137
  if (below(policy.badFaithMs, suspendWindowMs)) {
110
138
  throw new ProfileError(
111
139
  'retention.badFaithMs',
@@ -130,6 +158,14 @@ export interface PurgeResult {
130
158
  aiOutcomes: number;
131
159
  /** Signal rows deleted (flood_triggered included). 0 for a store without the signal methods. */
132
160
  signals: number;
161
+ /** Decided appeal rows deleted. 0 for a store without the appeal methods. */
162
+ appeals: number;
163
+ /** Appeal statements set to nothing (the row stays). A statement counted here may belong to a row deleted in the same pass. 0 for a store without the appeal methods. */
164
+ appealStatements: number;
165
+ /** Kept blocked names deleted. 0 for a store without the blocked-name methods. */
166
+ blockedNames: number;
167
+ /** Open appeals mooted because retention removed their sanction rows. 0 for a store without the appeal methods. */
168
+ appealsClosed: number;
133
169
  }
134
170
 
135
171
  function checkWindow(name: string, ms: number): void {
@@ -154,9 +190,15 @@ function checkWindow(name: string, ms: number): void {
154
190
  * record, no chat text): `decidedAt < now - aiOutcomesMs`; the pseudonymised example kept with an outcome:
155
191
  * `decidedAt < now - aiExamplesMs`, the row stays with its counts. A store without the AI methods has none of these.
156
192
  * - signals: `at < now - signalsMs` (90 days by default, never less than 14); a store without the signal methods has none
193
+ * - appeals: the statement of an appeal decided (or closed) before `now - appealStatementsMs` is set to nothing, the row stays; then a
194
+ * decided row with `decidedAt < now - appealsMs` is deleted (365 days by default, never less than 90), EXCEPT one whose sanction is
195
+ * permanent, or timed and not yet ended before that cutoff, and not revoked (that row stops a second appeal). An open appeal is never
196
+ * deleted or cleared; but one whose sanction rows this pass removed (or that has none) is first mooted, so it ends up decided-like. Blocked names: `at < now - blockedNamesMs` (30 days by default).
197
+ * A store without the appeal or blocked-name methods has none of these.
157
198
  * - notices: withdrawn, or a seen warning / report outcome, with `createdAt < now - noticesMs`; or
158
199
  * `until < now - noticesMs`. A notice for a permanent or running sanction is kept while it applies (agrees with
159
- * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn.
200
+ * `NoticeService.record`), and an unseen warning is kept until it is seen or withdrawn. The four message kinds: seen, as a report outcome;
201
+ * unseen, kept until the longer of `noticesMs` and `appealsMs` (appeal outcomes) or of `noticesMs` and `auditMs` (a required rename).
160
202
  *
161
203
  * Every cutoff is strict: a row exactly on the line is kept. Subjects and terms are never touched. The in-memory
162
204
  * indexes need no update: they already ignore everything this removes.
@@ -176,6 +218,9 @@ export async function purge(
176
218
  aiOutcomesMs: policy.aiOutcomesMs ?? RETENTION_DEFAULTS.aiOutcomesMs,
177
219
  aiExamplesMs: policy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
178
220
  signalsMs: policy.signalsMs ?? RETENTION_DEFAULTS.signalsMs,
221
+ appealStatementsMs: policy.appealStatementsMs ?? RETENTION_DEFAULTS.appealStatementsMs,
222
+ appealsMs: policy.appealsMs ?? RETENTION_DEFAULTS.appealsMs,
223
+ blockedNamesMs: policy.blockedNamesMs ?? RETENTION_DEFAULTS.blockedNamesMs,
179
224
  };
180
225
  if (!Number.isFinite(now)) throw new Error('purge: invalid now');
181
226
  checkWindow('reportsMs', p.reportsMs);
@@ -187,6 +232,9 @@ export async function purge(
187
232
  checkWindow('aiOutcomesMs', p.aiOutcomesMs);
188
233
  checkWindow('aiExamplesMs', p.aiExamplesMs);
189
234
  checkWindow('signalsMs', p.signalsMs);
235
+ checkWindow('appealStatementsMs', p.appealStatementsMs);
236
+ checkWindow('appealsMs', p.appealsMs);
237
+ checkWindow('blockedNamesMs', p.blockedNamesMs);
190
238
  return store.transaction(() => {
191
239
  const reports = store.purgeReports(now - p.reportsMs, now - p.badFaithMs);
192
240
  const ai = store.purgeAi?.(now - p.reportsMs, now - p.aiOutcomesMs, now - p.aiExamplesMs) ?? { reads: 0, outcomes: 0 };
@@ -195,12 +243,24 @@ export async function purge(
195
243
  sanctions: store.purgeSanctions(now - p.sanctionAfterEndMs),
196
244
  strikes: store.purgeStrikes(now - p.strikesMs),
197
245
  mutes: store.purgeMutes(now - MUTE_TTL_MS),
198
- notices: store.purgeNotices(now - p.noticesMs),
246
+ // An unseen message notice is kept until seen, but not for ever: an appeal outcome goes with the appeal row it describes, a required
247
+ // rename with the audit trail. Never earlier than a seen one would go (`noticesMs`).
248
+ notices: store.purgeNotices(now - p.noticesMs, {
249
+ appealBefore: now - Math.max(p.noticesMs, p.appealsMs),
250
+ renameBefore: now - Math.max(p.noticesMs, p.auditMs),
251
+ }),
199
252
  audit: store.purgeAudit(now - p.auditMs),
200
253
  webhookKeys: store.purgeWebhookKeys(now - WEBHOOK_KEY_TTL_MS),
201
254
  aiReads: ai.reads,
202
255
  aiOutcomes: ai.outcomes,
203
256
  signals: store.purgeSignals?.(now - p.signalsMs) ?? 0,
257
+ // An open appeal whose sanction rows were just removed can never be decided (`gone`): moot it, so it leaves the inbox and its statement
258
+ // goes on the decided clock (cleared at once when `appealStatementsMs` is 0).
259
+ appealsClosed: store.closeOrphanAppeals?.('retention', now, p.appealStatementsMs === 0) ?? 0,
260
+ // Statements first: a statement is player text and goes on its own, shorter clock even when its row stays (or goes in the next call).
261
+ appealStatements: store.clearAppealStatements?.(now - p.appealStatementsMs) ?? 0,
262
+ appeals: store.purgeAppeals?.(now - p.appealsMs) ?? 0,
263
+ blockedNames: store.purgeBlockedNames?.(now - p.blockedNamesMs) ?? 0,
204
264
  };
205
265
  });
206
266
  }
package/src/sanctions.ts CHANGED
@@ -49,6 +49,13 @@ const REF_ATTEMPTS = 5;
49
49
  /** No I, L, O, 0 or 1: a player reads the code aloud or types it from a screenshot. */
50
50
  const REF_ALPHABET = 'ABCDEFGHJKMNPQRSTUVWXYZ23456789';
51
51
 
52
+ /**
53
+ * The key to `SanctionInput.startsAt`. It is exported from this module only, never from the package index, so only code inside the kit (the
54
+ * appeals service) can hold it; a public caller passing a start time is refused with a `RangeError`.
55
+ * @internal
56
+ */
57
+ export const APPEALS_START_TOKEN: unique symbol = Symbol('chatwarden.appeals.startsAt');
58
+
52
59
  export interface SanctionInput {
53
60
  kind: SanctionKind;
54
61
  /** The person to sanction; stored as its canonical (surviving) subject. */
@@ -77,6 +84,22 @@ export interface SanctionInput {
77
84
  * otherwise. Private; the ladder reads it to count notes from distinct games.
78
85
  */
79
86
  roomId?: string | null;
87
+ /**
88
+ * The report whose decision made this sanction: a non-empty string, kept on the subject row so a granted appeal can mark that decision
89
+ * reversed. Absent stores nothing (an automatic or direct sanction). Private. For the kit's own decision path only, like `startsAt`: it
90
+ * is accepted only with `startsAtToken`, because a wrong id would corrupt the casebook; any other caller passing it gets a `RangeError`.
91
+ * @internal
92
+ */
93
+ reportId?: string;
94
+ /**
95
+ * The start time to write instead of "now", epoch ms, never after "now". For the appeals service only, so a reduced sanction keeps the
96
+ * original start (the ladder reads sanctions by start). The end is `startsAt + durationMs`. Honoured only with `startsAtToken`; any other
97
+ * caller passing it gets a `RangeError`.
98
+ * @internal
99
+ */
100
+ startsAt?: number;
101
+ /** @internal The key to `startsAt` and `reportId`: {@link APPEALS_START_TOKEN}. */
102
+ startsAtToken?: symbol;
80
103
  }
81
104
 
82
105
  /** What `active` tells the chat path. No reason, rule, actor or identifier. */
@@ -108,10 +131,16 @@ export function refCode(): string {
108
131
  return out;
109
132
  }
110
133
 
111
- /** What `validate` settles: the rule as stored text, and the trimmed gap note (null when there is none). */
134
+ /**
135
+ * What `validate` settles: the rule as stored text, the trimmed gap note (null when there is none), and the two internal values it read
136
+ * ONCE (`start` and `reportId`, undefined when not given). The writer uses these, never a second read of the input, so what was checked
137
+ * is what is stored even for an object with getters or an inherited property.
138
+ */
112
139
  interface Checked {
113
140
  rule: string;
114
141
  gapNote: string | null;
142
+ start: number | undefined;
143
+ reportId: string | undefined;
115
144
  }
116
145
 
117
146
  /**
@@ -123,7 +152,21 @@ export function validateSanctionInput(input: SanctionInput): void {
123
152
  validate(input);
124
153
  }
125
154
 
126
- function validate(input: SanctionInput): Checked {
155
+ function validate(input: SanctionInput, now?: number): Checked {
156
+ // A start time and a report id are the kit's own (the appeals service and the decision): refused for everyone else before any other
157
+ // check, naming nothing of the input. Each is read ONCE, as an ordinary property read (an inherited value counts, so a prototype cannot
158
+ // smuggle one past the guard), and the writer uses this read.
159
+ const start: unknown = input.startsAt;
160
+ const report: unknown = input.reportId;
161
+ const token: unknown = input.startsAtToken;
162
+ if ((start !== undefined || report !== undefined) && token !== APPEALS_START_TOKEN) {
163
+ throw new RangeError('applySanction: startsAt and reportId are not accepted');
164
+ }
165
+ if (start !== undefined) {
166
+ if (typeof start !== 'number' || !Number.isSafeInteger(start) || start < 0) throw new SanctionError('applySanction: invalid start');
167
+ if (now !== undefined && start > now) throw new SanctionError('applySanction: a start cannot be in the future');
168
+ }
169
+ if (report !== undefined && (typeof report !== 'string' || report === '')) throw new SanctionError('applySanction: invalid report id');
127
170
  const d = input.durationMs;
128
171
  if (isRecordKind(input.kind)) {
129
172
  // A warning or a note has no end and no IP: it is a record, not a restriction.
@@ -151,12 +194,17 @@ function validate(input: SanctionInput): Checked {
151
194
  const note: unknown = input.gapNote;
152
195
  if (ref === 'uncovered' && input.source === 'moderator') {
153
196
  const trimmed = typeof note === 'string' ? note.trim() : '';
197
+ // The kit's own writers (the decision, the appeals service: `token`) may leave the note out: a replacement under no rule has its gap
198
+ // recorded on the sanction it replaces, so it does not open a second one.
199
+ if (trimmed === '' && token === APPEALS_START_TOKEN && note === undefined) {
200
+ return { rule: 'uncovered', gapNote: null, start: start as number | undefined, reportId: report as string | undefined };
201
+ }
154
202
  if (trimmed === '') throw new SanctionError('applySanction: a rule-gap note is required when no rule is cited');
155
203
  if (trimmed.length > GAP_NOTE_MAX) throw new SanctionError('applySanction: the rule-gap note is too long');
156
- return { rule: 'uncovered', gapNote: trimmed };
204
+ return { rule: 'uncovered', gapNote: trimmed, start: start as number | undefined, reportId: report as string | undefined };
157
205
  }
158
206
  if (note !== undefined) throw new SanctionError('applySanction: a rule-gap note is only for an uncovered moderator sanction');
159
- return { rule: String(ref), gapNote: null };
207
+ return { rule: String(ref), gapNote: null, start: start as number | undefined, reportId: report as string | undefined };
160
208
  }
161
209
 
162
210
  /** What {@link writeSanction} wrote: the group's handle and the rows, for the caller to hand to the index. */
@@ -175,11 +223,13 @@ function applyNow(
175
223
  now: number,
176
224
  pending: boolean,
177
225
  ): WrittenSanction {
178
- const { rule, gapNote } = validate(input);
226
+ const { rule, gapNote, start: given, reportId } = validate(input, now);
179
227
  const subject = subjects.canonical(input.subject);
228
+ // The start is "now" unless the appeals service gave the original one (validate has refused anyone else).
229
+ const start = given ?? now;
180
230
  // A warning or note has no end: it ends where it starts, so it is never "still running".
181
- const endsAt = isRecordKind(input.kind) ? now : input.durationMs === null ? null : now + input.durationMs;
182
- const ipEndsAt = endsAt === null ? now + IP_MAX_MS : Math.min(endsAt, now + IP_MAX_MS);
231
+ const endsAt = isRecordKind(input.kind) ? start : input.durationMs === null ? null : start + input.durationMs;
232
+ const ipEndsAt = endsAt === null ? start + IP_MAX_MS : Math.min(endsAt, start + IP_MAX_MS);
183
233
  const ip = input.includeIp ? subjects.latestIp(subject) : null;
184
234
  const groupId = newId();
185
235
 
@@ -188,7 +238,7 @@ function applyNow(
188
238
  groupId,
189
239
  refCode: code,
190
240
  kind: input.kind,
191
- startsAt: now,
241
+ startsAt: start,
192
242
  reason: input.reason,
193
243
  rule,
194
244
  roomId: input.roomId ?? null,
@@ -206,6 +256,8 @@ function applyNow(
206
256
  endsAt,
207
257
  gapNote,
208
258
  gapStatus: gapNote === null ? null : 'open',
259
+ // Only a sanction a report decision made carries one; the key is absent otherwise, so every other row keeps its shape.
260
+ ...(reportId === undefined ? {} : { reportId }),
209
261
  };
210
262
  const rows: SanctionRow[] = [subjectRow];
211
263
  if (ip !== null) {
@@ -271,6 +323,10 @@ export function writeSanction(
271
323
  * when given, the index are updated before the promise is returned. Resolves
272
324
  * true when this call revoked something, false for an unknown or already
273
325
  * revoked group.
326
+ *
327
+ * An appeal still open against the group is made moot in the same transaction. `opts.clearStatement` also clears that appeal's statement
328
+ * (what `retention.appealStatementsMs: 0` asks for); `cw.sanctions.revoke` passes it from the retention options the kit was CREATED with,
329
+ * so a one-off `cw.purge(policy)` with another `appealStatementsMs` does not change it, and the text then waits for the next purge.
274
330
  */
275
331
  export function revokeSanction(
276
332
  store: Store,
@@ -279,9 +335,16 @@ export function revokeSanction(
279
335
  now: number,
280
336
  reason: string,
281
337
  index?: SanctionIndex,
338
+ opts: { clearStatement?: boolean } = {},
282
339
  ): Promise<boolean> {
283
340
  try {
284
- const n = store.transaction(() => store.revokeSanctionGroup(groupId, actor, now, reason));
341
+ const n = store.transaction(() => {
342
+ const revoked = store.revokeSanctionGroup(groupId, actor, now, reason);
343
+ // An appeal still open against this group is moot now: nobody ruled on it. In the same transaction, so both land or neither.
344
+ // `clearStatement` (retention.appealStatementsMs 0) clears its text at once, as a decision would.
345
+ if (revoked > 0) store.closeAppealsForGroup?.(groupId, actor, now, opts.clearStatement === true);
346
+ return revoked;
347
+ });
285
348
  index?.remove(groupId);
286
349
  return Promise.resolve(n > 0);
287
350
  } catch (err) {