@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/appeals.ts ADDED
@@ -0,0 +1,256 @@
1
+ import { ProfileError } from './profileError.js';
2
+ import type { RuleRef } from './rules.js';
3
+ import type { SanctionKind, SubjectId } from './types.js';
4
+
5
+ // The appeal settings: whether players may appeal a sanction, how many a week, and whether the moderator who made a decision may
6
+ // decide its appeal. Pure data and validation, no state and no clock; the service that acts on them comes later. Off until set, so a
7
+ // kit that sets nothing behaves exactly as before.
8
+
9
+ /** The longest statement, in characters. A constant, not a setting: it bounds what is stored. @experimental */
10
+ export const APPEAL_STATEMENT_MAX = 1000;
11
+
12
+ /** The allowed whole-number range of `perPlayerPerWeek`, and its default. */
13
+ const PER_WEEK_MIN = 1;
14
+ const PER_WEEK_MAX = 20;
15
+ const PER_WEEK_DEFAULT = 3;
16
+
17
+ const KEYS = ['enabled', 'perPlayerPerWeek', 'allowSelfReview'] as const;
18
+
19
+ /** What a moderator may rule on an appeal: the sanction stands, is made lighter, or is lifted. @experimental */
20
+ export const APPEAL_OUTCOMES = ['uphold', 'reduce', 'revoke'] as const;
21
+ export type AppealOutcome = (typeof APPEAL_OUTCOMES)[number];
22
+
23
+ /**
24
+ * Where an appeal stands. `open` until decided; `upheld`, `reduced` and `revoked` are the three outcomes; `moot` means the sanction was
25
+ * revoked by someone else while the appeal was open, so nobody ruled on it.
26
+ * @experimental
27
+ */
28
+ export type AppealStatus = 'open' | 'upheld' | 'reduced' | 'revoked' | 'moot';
29
+
30
+ /**
31
+ * How appeals run. Every field is optional; a profile without `appeals` has them off.
32
+ * @experimental
33
+ */
34
+ export interface AppealSettings {
35
+ /** Default false. */
36
+ enabled?: boolean;
37
+ /** Appeals one player may file in any rolling 7 days. 1 to 20, default 3. */
38
+ perPlayerPerWeek?: number;
39
+ /** May the moderator who made the original decision decide the appeal? Default false. For a team of one. */
40
+ allowSelfReview?: boolean;
41
+ }
42
+
43
+ /**
44
+ * What the kit reads: every field filled in.
45
+ * @experimental
46
+ */
47
+ export interface ResolvedAppeals {
48
+ enabled: boolean;
49
+ perPlayerPerWeek: number;
50
+ allowSelfReview: boolean;
51
+ }
52
+
53
+ function isPlain(v: unknown): v is Record<string, unknown> {
54
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) return false;
55
+ const proto: unknown = Object.getPrototypeOf(v);
56
+ return proto === Object.prototype || proto === null;
57
+ }
58
+
59
+ /** An own, defined value: a key left out, `undefined` and an inherited property all read as "not given". */
60
+ function given(o: Record<string, unknown>, key: string): unknown {
61
+ return Object.hasOwn(o, key) ? o[key] : undefined;
62
+ }
63
+
64
+ /**
65
+ * Validate and fill. Throws ProfileError naming the field (`appeals.perPlayerPerWeek`), never echoing the value. `path` names the
66
+ * settings in the error (default `appeals`). The result is a new object that shares nothing with the input; each value is read from
67
+ * `input` once.
68
+ * @experimental
69
+ */
70
+ export function resolveAppeals(input: AppealSettings | undefined, path = 'appeals'): ResolvedAppeals {
71
+ if (input === undefined) return { enabled: false, perPlayerPerWeek: PER_WEEK_DEFAULT, allowSelfReview: false };
72
+ if (!isPlain(input)) throw new ProfileError(path, 'must be an object');
73
+ for (const k of Object.keys(input)) if (!(KEYS as readonly string[]).includes(k)) throw new ProfileError(`${path}.${k}`, 'is not a known setting');
74
+ const enabled = given(input, 'enabled');
75
+ const perWeek = given(input, 'perPlayerPerWeek');
76
+ const self = given(input, 'allowSelfReview');
77
+ if (enabled !== undefined && typeof enabled !== 'boolean') throw new ProfileError(`${path}.enabled`, 'must be true or false');
78
+ if (perWeek !== undefined && (typeof perWeek !== 'number' || !Number.isSafeInteger(perWeek) || perWeek < PER_WEEK_MIN || perWeek > PER_WEEK_MAX)) {
79
+ throw new ProfileError(`${path}.perPlayerPerWeek`, `must be a whole number from ${PER_WEEK_MIN} to ${PER_WEEK_MAX}`);
80
+ }
81
+ if (self !== undefined && typeof self !== 'boolean') throw new ProfileError(`${path}.allowSelfReview`, 'must be true or false');
82
+ return {
83
+ enabled: enabled ?? false,
84
+ perPlayerPerWeek: (perWeek as number | undefined) ?? PER_WEEK_DEFAULT,
85
+ allowSelfReview: self ?? false,
86
+ };
87
+ }
88
+
89
+ /** What a player sees of an appeal. No staff field, no reason, no id of a sanction or a person. @experimental */
90
+ export interface PlayerAppeal {
91
+ id: string;
92
+ /** The notice it was filed from. */
93
+ noticeId: string;
94
+ status: 'open' | 'upheld' | 'reduced' | 'revoked';
95
+ createdAt: number;
96
+ decidedAt: number | null;
97
+ }
98
+
99
+ /**
100
+ * Why a filing was refused. `not_found` is one answer for "not yours", "no such notice" and "malformed", so notice ids cannot be probed.
101
+ * @experimental
102
+ */
103
+ export type AppealRefusal =
104
+ | 'off' // appeals are not enabled
105
+ | 'not_found' // not the caller's notice, or no such notice (the same answer, so ids cannot be probed)
106
+ | 'not_appealable' // the caller's notice, but not a sanction in their record
107
+ | 'statement_invalid' // empty after cleaning, or over APPEAL_STATEMENT_MAX characters
108
+ | 'already_appealed' // this sanction has had its appeal
109
+ | 'rate'; // perPlayerPerWeek reached
110
+
111
+ /** @experimental */
112
+ export type AppealFileResult = { ok: true; appeal: PlayerAppeal } | { ok: false; refused: AppealRefusal; retryAfterMs?: number }; // retryAfterMs on 'rate'
113
+
114
+ /** The most UTF-16 units of raw text the cleaner will look at: far past the cap, so a huge paste is refused without being worked through. */
115
+ const STATEMENT_RAW_MAX = APPEAL_STATEMENT_MAX * 20;
116
+
117
+ // Line and paragraph separators and the C1 next-line become a newline; a tab becomes a space.
118
+ const NEWLINES = /\r\n|[\r\u0085\u2028\u2029]/g;
119
+ // Control characters other than newline (tab is handled before), bidirectional controls and marks, zero-width and invisible format
120
+ // characters, the soft hyphen, the Mongolian vowel separator, the Hangul fillers (U+115F, U+1160, U+3164, U+FFA0), the braille blank
121
+ // (U+2800), the combining grapheme joiner (U+034F), the variation selectors (U+FE00 to U+FE0E; U+FE0F, the emoji presentation selector, is kept: it is common and harmless) and the interlinear annotation marks
122
+ // (U+FFF9 to U+FFFB). Each draws nothing, so a statement made of them would look blank to the staff reader.
123
+ // eslint-disable-next-line no-control-regex, no-misleading-character-class
124
+ const STRIPPED = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f-\u009f\u00ad\u034f\u061c\u115f\u1160\u180e\u200b-\u200f\u202a-\u202e\u2060-\u2069\u2800\u3164\ufe00-\ufe0e\ufeff\uffa0\ufff9-\ufffb]/g;
125
+ // Beyond the BMP (so this one needs the `u` flag): the tag characters (U+E0000 to U+E007F), which can carry hidden text, and the
126
+ // variation selectors supplement (U+E0100 to U+E01EF).
127
+ // eslint-disable-next-line no-misleading-character-class
128
+ const STRIPPED_ASTRAL = /[\u{e0000}-\u{e007f}\u{e0100}-\u{e01ef}]/gu;
129
+ // A surrogate with no partner: it cannot be stored as UTF-8 (SQLite writes U+FFFD, the memory store keeps it), so both are removed first.
130
+ const LONE_SURROGATE = /[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/g;
131
+
132
+ /**
133
+ * Clean a statement before it is counted or stored: line and paragraph separators become newlines and tabs spaces; control, bidirectional
134
+ * and zero-width characters, the soft hyphen, the Hangul fillers, the braille blank, the grapheme joiner, variation selectors, annotation
135
+ * marks, tag characters, NUL and lone surrogates are removed; every line loses its trailing space; runs of blank lines
136
+ * collapse to one; the whole is trimmed. Pure, idempotent, never throws; anything that is not a string, and a string longer than twenty times
137
+ * the cap, gives an empty string (which the filing refuses). Count the result in code points, not UTF-16 units.
138
+ * @experimental
139
+ */
140
+ export function normalizeStatement(input: unknown): string {
141
+ if (typeof input !== 'string' || input.length > STATEMENT_RAW_MAX) return '';
142
+ const text = input
143
+ .replace(NEWLINES, '\n')
144
+ .replace(/\t/g, ' ')
145
+ .replace(LONE_SURROGATE, '')
146
+ .replace(STRIPPED, '')
147
+ .replace(STRIPPED_ASTRAL, '')
148
+ .split('\n')
149
+ .map((line) => line.trimEnd())
150
+ .join('\n')
151
+ .replace(/\n{3,}/g, '\n\n')
152
+ .trim();
153
+ // U+FE0F is kept inside a text, but it draws nothing: a statement of nothing else is as blank as any other invisible one.
154
+ return /^[\s️]*$/.test(text) ? '' : text;
155
+ }
156
+
157
+ /** The length of a cleaned statement in characters (code points), the unit {@link APPEAL_STATEMENT_MAX} counts in. */
158
+ export function statementLength(text: string): number {
159
+ return [...text].length;
160
+ }
161
+
162
+ /** The four sanction kinds an appeal can concern, lightest first: a reduction must go to a lower kind, or to the same kind and shorter. */
163
+ export const SANCTION_KIND_ORDER = ['warning', 'chat', 'area', 'ban'] as const;
164
+
165
+ /**
166
+ * A moderator's ruling on an appeal.
167
+ * @experimental
168
+ */
169
+ export interface AppealDecision {
170
+ appealId: string;
171
+ outcome: AppealOutcome;
172
+ /** A staff ref the audit trail accepts. */
173
+ actor: string;
174
+ /** Private, 1 to 500 characters after trimming. Never shown to the player. */
175
+ reason: string;
176
+ /** `reduce` only: the lighter outcome that replaces the sanction. A warning has no length (`null`). */
177
+ to?: { kind: 'warning' | 'chat' | 'area' | 'ban'; durationMs: number | null };
178
+ }
179
+
180
+ /** @experimental */
181
+ export type AppealDecideResult =
182
+ | { ok: true; status: 'upheld' | 'reduced' | 'revoked'; replacementGroupId?: string }
183
+ | { ok: false; error: 'not_found' | 'already_decided' | 'invalid' | 'same_decider' | 'gone' };
184
+
185
+ /** Below this many sanctions in the window a rule has no rate. */
186
+ export const APPEAL_STATS_MIN_SANCTIONS = 10;
187
+ /** A rule whose rate is at or above this is `elevated`. */
188
+ export const APPEAL_RATE_ELEVATED = 0.15;
189
+ /** A rule whose rate is at or above this is `high`. */
190
+ export const APPEAL_RATE_HIGH = 0.3;
191
+
192
+ /**
193
+ * One appeal as staff see it in a list. The statement is NOT here (see {@link AppealDetail}); `statementFlagged` says whether it trips the
194
+ * term filter, so the hub can mask it. Carries a staff ref: staff channels only, never send to a player.
195
+ * @experimental
196
+ */
197
+ export interface AppealSummary {
198
+ id: string;
199
+ createdAt: number;
200
+ status: AppealStatus;
201
+ /** A staff ref. */
202
+ person: SubjectId;
203
+ /** The sanction. `decidedBy` is who made the original decision (the actor on its row); `''` and the appeal's own times when its rows are gone. */
204
+ sanction: { groupId: string; refCode: string; kind: SanctionKind; rule: RuleRef | null; startsAt: number; endsAt: number | null; decidedBy: string; automated: boolean };
205
+ statementFlagged: boolean;
206
+ }
207
+
208
+ /**
209
+ * One appeal in full, for one staff read (audited by the route).
210
+ * @experimental
211
+ */
212
+ export interface AppealDetail extends AppealSummary {
213
+ /** The player's words. Staff only. Null once purged. Masked by the hub when `statementFlagged`. */
214
+ statement: string | null;
215
+ /** Who decided (or, for a moot appeal, who revoked the sanction), when, and why (private; empty for a moot appeal), once it is no longer open. */
216
+ decided: { by: string; at: number; reason: string; replacementGroupId: string | null } | null;
217
+ /** The report whose decision made the sanction, when known. */
218
+ reportId: string | null;
219
+ /** What the player was shown with the sanction: their own lines, as the notice kept them (already masked where blocked). */
220
+ shown: Array<{ text: string; day: string }>;
221
+ }
222
+
223
+ /** @experimental */
224
+ export interface AppealPage {
225
+ items: AppealSummary[];
226
+ /** An opaque cursor for the next page, or null when this page was not full. */
227
+ next: string | null;
228
+ }
229
+
230
+ /**
231
+ * The appeal counts of one rule over a window. `granted` is REVOKED appeals only: a reduction is a severity dispute, not a false positive,
232
+ * so it is `lightened`, shown beside the rate and never in it.
233
+ * @experimental
234
+ */
235
+ export interface AppealRuleStats {
236
+ rule: number | 'uncovered';
237
+ /** Sanctions given under the rule in the window (warning, chat, area, ban; notes are not counted, a reduction counts once). */
238
+ sanctions: number;
239
+ /** Appeals filed in the window (any outcome, a moot one included). */
240
+ appealed: number;
241
+ /** Revoked on appeal. */
242
+ granted: number;
243
+ /** Reduced on appeal. */
244
+ lightened: number;
245
+ /** granted / sanctions, or null below {@link APPEAL_STATS_MIN_SANCTIONS} sanctions. */
246
+ rate: number | null;
247
+ band: 'normal' | 'elevated' | 'high' | null;
248
+ }
249
+
250
+ /** @experimental */
251
+ export interface AppealStats {
252
+ windowDays: number;
253
+ /** By rule number, `'uncovered'` last. */
254
+ perRule: AppealRuleStats[];
255
+ overall: { sanctions: number; appealed: number; granted: number; lightened: number; rate: number | null };
256
+ }
package/src/audit.ts CHANGED
@@ -16,6 +16,10 @@ export type Role = (typeof ROLES)[number];
16
16
  * The three `ai.*` actions target a report and carry no detail: `ai.read` is written by the AI itself (an `ai:` actor, no role)
17
17
  * when a read finishes, `ai.rerun` by a moderator who asked for another read, `ai.outcome` by a moderator whose decision was
18
18
  * recorded against a read.
19
+ *
20
+ * The three appeal and name actions (0.1.9): `appeal.view` is a staff read of the inbox, one appeal or the numbers (its target is the
21
+ * `appeal`, or none for the list and the numbers); `appeal.decide` points at the `appeal` decided and needs it; `name.rename_required`
22
+ * points at the `person` asked to rename and needs it. None of them carries a detail: a statement, a reason or a name never reaches the trail.
19
23
  */
20
24
  export const AUDIT_ACTIONS = [
21
25
  'report.view',
@@ -44,6 +48,9 @@ export const AUDIT_ACTIONS = [
44
48
  'ai.read',
45
49
  'ai.rerun',
46
50
  'ai.outcome',
51
+ 'appeal.view',
52
+ 'appeal.decide',
53
+ 'name.rename_required',
47
54
  ] as const;
48
55
  export type AuditAction = (typeof AUDIT_ACTIONS)[number];
49
56
 
@@ -63,14 +70,20 @@ export const AUDIT_REASON_MAX = 2000;
63
70
  /** The actions that point at a report (and only at one), and carry nothing else. */
64
71
  const AI_ACTIONS: readonly string[] = ['ai.read', 'ai.rerun', 'ai.outcome'];
65
72
 
73
+ /** The actions that point at an appeal (and only at one). `appeal.view` may point at none: the list and the numbers are not about one. */
74
+ const APPEAL_ACTIONS: readonly string[] = ['appeal.view', 'appeal.decide'];
75
+
76
+ /** The actions that cannot be recorded without a target. */
77
+ const TARGET_REQUIRED: readonly string[] = [...AI_ACTIONS, 'appeal.decide', 'name.rename_required'];
78
+
66
79
  /** An actor that is the AI itself, not a person: `ai:` and the adapter's id (`ai:anthropic:claude-haiku-5-5`). */
67
80
  const AI_ACTOR_PREFIX = 'ai:';
68
81
 
69
82
  /** The actions whose row carries an {@link AuditDetail}, and the only ones that may. */
70
83
  const DETAIL_ACTIONS: readonly string[] = ['policy.update', 'policy.reset'];
71
84
 
72
- /** What an entry points at: a report id, a sanction group id, a person (a staff ref), a term id, an exception id or a saved reason id. */
73
- export const AUDIT_TARGET_TYPES = ['report', 'sanction', 'person', 'term', 'exception', 'reason'] as const;
85
+ /** What an entry points at: a report id, a sanction group id, a person (a staff ref), a term id, an exception id, a saved reason id or an appeal id. */
86
+ export const AUDIT_TARGET_TYPES = ['report', 'sanction', 'person', 'term', 'exception', 'reason', 'appeal'] as const;
74
87
  export type AuditTargetType = (typeof AUDIT_TARGET_TYPES)[number];
75
88
 
76
89
  export interface AuditTarget {
@@ -236,11 +249,13 @@ function parse(input: unknown): AuditRecordInput | null {
236
249
  return null;
237
250
  }
238
251
  const extra = parsedDetail === undefined ? {} : { detail: parsedDetail };
239
- if (target === undefined) return AI_ACTIONS.includes(action) ? null : { actor, role: roleOut, action, ...extra };
252
+ if (target === undefined) return TARGET_REQUIRED.includes(action) ? null : { actor, role: roleOut, action, ...extra };
240
253
  if (typeof target !== 'object' || target === null) return null;
241
254
  const { type, ref } = target as Record<string, unknown>;
242
255
  if (!isTargetType(type) || typeof ref !== 'string' || !REF_RE.test(ref)) return null;
243
256
  if (AI_ACTIONS.includes(action) && type !== 'report') return null;
257
+ if (APPEAL_ACTIONS.includes(action) && type !== 'appeal') return null;
258
+ if (action === 'name.rename_required' && type !== 'person') return null;
244
259
  return { actor, role: roleOut, action, target: { type, ref }, ...extra };
245
260
  }
246
261
 
package/src/chatwarden.ts CHANGED
@@ -24,6 +24,10 @@ import type { DismissManyInput, DismissManyResult } from './dismissMany.js';
24
24
  import { PolicyService } from './policy.js';
25
25
  import type { PolicyPreview, PolicySaveContext, PolicySaveResult, PolicyState } from './policy.js';
26
26
  import { checkPace, mergePace } from './pace.js';
27
+ import { AppealService, hasAppealMethods } from './appealService.js';
28
+ import { NameService } from './nameService.js';
29
+ import type { NameCheckResult } from './names.js';
30
+ import type { AppealDecideResult, AppealDecision, AppealDetail, AppealFileResult, AppealPage, AppealStats, AppealSummary, PlayerAppeal } from './appeals.js';
27
31
  import { createInertSignals } from './signalInert.js';
28
32
  import type { SignalRuntime } from './signalService.js';
29
33
  import { BUILTIN_SIGNAL_KINDS, checkSignalFeeds } from './signals.js';
@@ -46,6 +50,7 @@ import { StrikeService } from './strikes.js';
46
50
  import {
47
51
  blockedCountsByTerm,
48
52
  blockedItems,
53
+ blockedNameItems,
49
54
  listSanctionGroups,
50
55
  reporterRecord,
51
56
  sanctionsOfPerson,
@@ -55,6 +60,7 @@ import type { ReporterAccuracy } from './reporterAccuracy.js';
55
60
  import type {
56
61
  BlockedDays,
57
62
  BlockedItem,
63
+ BlockedNameItem,
58
64
  ReporterRecord,
59
65
  SanctionGroupView,
60
66
  SanctionListInput,
@@ -159,7 +165,8 @@ export interface ChatwardenOptions {
159
165
  *
160
166
  * Floors, checked at creation (and on every `purge(policy)`), each a `ProfileError` naming the field:
161
167
  * `sanctionAfterEndMs` and `noticesMs` at least 90 days (the ladder and "My record" reach back that far),
162
- * `auditMs` at least 90 days (default 365), `badFaithMs` at least `limits.reports.suspendWindowMs`. Every field
168
+ * `auditMs` at least 90 days (default 365), `appealsMs` at least 90 days (default 365), `badFaithMs` at least
169
+ * `limits.reports.suspendWindowMs`. `appealStatementsMs` (default 90 days) and `blockedNamesMs` (default 30 days) may be 0. Every field
163
170
  * must be a finite number (Infinity and NaN are refused). Not enforced, but `strikesMs` should be at least
164
171
  * `limits.strikes.windowMs`, or strikes are deleted before the window that counts them closes. When you leave
165
172
  * `badFaithMs` out it follows a longer suspension window.
@@ -372,6 +379,13 @@ export interface Chatwarden {
372
379
  list(q: { days: BlockedDays }): BlockedItem[];
373
380
  /** Strikes per term id over the same window; a term with none is absent. */
374
381
  countsByTerm(q: { days: BlockedDays }): Record<string, number>;
382
+ /**
383
+ * The blocked NAMES kept as evidence (`names.keepBlocked`) over the last `days` days (1, 7 or 30, else `RangeError`), newest first, at most
384
+ * 200: `{ id, at, person, name, termId, reason }`, the person a staff ref or null. Empty when none was kept, or the store keeps none. A name
385
+ * is a player's text and `person` a subject id: staff channels only, never send either to a player.
386
+ * @experimental
387
+ */
388
+ names(q: { days: BlockedDays }): BlockedNameItem[];
375
389
  };
376
390
  /**
377
391
  * The team workbench: soft claims on a person's case, take next, and who has a case open. Staff only; every `person` is
@@ -501,12 +515,45 @@ export interface Chatwarden {
501
515
  on: Subscribe;
502
516
  names: {
503
517
  /**
504
- * May a player use this as a name (a handle, a table or deck name)? Reads it with the matcher's name rules
505
- * (`Zorbak_99` is caught, not only `zorbak`). `rule` is the Community Rule the slur filter cites
506
- * (`autoRestrictRule`). No matcher, and a matcher that fails (logged, class only), both let the name through.
507
- * Throws a TypeError for a value that is not a string.
518
+ * May a player use this as a name (a handle, a table or deck name)? Synchronous, never echoes the name, never throws for a string (a
519
+ * non-string is still a TypeError). Reads it with the matcher's name rules (`Zorbak_99` is caught, not only `zorbak`); with
520
+ * `names.profanity` it also runs the profanity filter on the name and on the name with underscores and digits turned into spaces, and a
521
+ * hit is `name_profane` (a matcher hit wins). `rule` is the Community Rule the slur filter cites (`autoRestrictRule`) for both. No
522
+ * matcher, a matcher that fails (logged, class only) and a filter that fails (`chatwarden.names_filter_failed`) all let the name through.
523
+ *
524
+ * `opts.who` is the caller, as the doors take it. It is used ONLY to tie kept evidence to a person (found, never created); it never
525
+ * changes the answer. A blocked name is kept (`kit_blocked_names`) only when `names.keepBlocked` is on: at most 5 an hour per person
526
+ * (per `who`, or per name when there is none) and 200 an hour overall, in memory per process; past that the check still answers and
527
+ * nothing more is stored. An allowed name is never stored, and a name is never logged.
528
+ */
529
+ check(text: string, opts?: { who?: RawWho }): NameCheckResult;
530
+ /**
531
+ * Would the matcher refuse this as a name? The evidence-free read for staff screens and routes (a list of handles): the matcher only,
532
+ * no profanity pass, nothing stored whatever `names.keepBlocked` says, no person looked up. False for no matcher, for a non-string and
533
+ * when the matcher throws (logged once a minute, class only). Never throws.
534
+ */
535
+ flagged(text: string): boolean;
536
+ /**
537
+ * Ask a player to choose a new name. Writes one notice of kind `rename_required` (it names no name, no excerpt, no reason) and, after
538
+ * the write, tells the player's client and emits `rename.required`. Staff only. `{ ok: false, error: 'off' }` while `names.renames` is
539
+ * false (or the store cannot release a rename); `invalid` for a reason that is not 1 to 500 characters or a rule that is not an active
540
+ * integer rule; `not_found` for a person the kit does not hold; `pending` while a request is already waiting. `rule` defaults to the
541
+ * slur filter's (`autoRestrictRule`) and is shown to the player as a rule label. A store failure is logged (class only) and thrown.
542
+ * @experimental
543
+ */
544
+ requireRename(input: { subject: SubjectId; actor: string; reason: string; rule?: number }): { ok: true; noticeId: string } | { ok: false; error: 'off' | 'not_found' | 'pending' | 'invalid' };
545
+ /** True while the person has a rename request they have not been released from. For the game, to hold a player at a rename screen. Never creates a person. @experimental */
546
+ pendingRename(who: RawWho): boolean;
547
+ /** The game calls this once the player has a new name. Withdraws their pending rename notices. True when it withdrew one. The kit never learns the name. @experimental */
548
+ renamed(who: RawWho): boolean;
549
+ /**
550
+ * Whether `requireRename` can work right now: `names.renames` is on AND the store can release a rename (the test `requireRename` applies
551
+ * first). A live read. For a staff screen, so it never offers a rename that always answers `off`.
552
+ * @experimental
508
553
  */
509
- check(text: string): { ok: true } | { ok: false; reason: 'name_not_allowed'; rule: number };
554
+ renamesEnabled(): boolean;
555
+ /** A person's rename requests, newest first, at most 20: `{ at, pending }` each. No reason, actor, rule or name. Staff only: never send to a player. @experimental */
556
+ renamesOf(subject: SubjectId): Array<{ at: number; pending: boolean }>;
510
557
  };
511
558
  /**
512
559
  * The AI read and recommend service. Always present: without an `ai` option (or at level 0) it answers as if there were no AI. A
@@ -605,6 +652,55 @@ export interface Chatwarden {
605
652
  /** True while the person has a warning they have not acknowledged. */
606
653
  pendingWarning(who: RawWho): boolean;
607
654
  };
655
+ /**
656
+ * Appeals (0.1.9, `profile.appeals`, off until turned on). The player side takes the same `RawWho` as `notices` and FINDS the person
657
+ * (never creates one); every answer is a reason or a rule number, never an identifier, a staff ref or a reason a moderator gave.
658
+ * @experimental
659
+ */
660
+ appeals: {
661
+ /** Whether appeals are on right now: the profile in force says so (a live read) and the store can keep them. */
662
+ enabled(): boolean;
663
+ /**
664
+ * File an appeal from one of the caller's own sanction notices, with a statement of at most `APPEAL_STATEMENT_MAX` (1000) characters.
665
+ * Checks in this order: off, not_found, not_appealable, statement_invalid, already_appealed, rate. One store transaction; a refusal
666
+ * writes nothing. The statement is cleaned first (`normalizeStatement`) and refused, not cut, over the cap. Never throws for a bad
667
+ * input; a store failure is logged (`chatwarden.appeal_failed`, the error class only) and answers `not_found`. `appeal.created` is
668
+ * emitted after the commit.
669
+ */
670
+ file(who: RawWho, input: { noticeId: string; statement: string }): AppealFileResult;
671
+ /** The caller's own appeals, newest first, at most 50, without any that was made moot. Empty for an unknown person or with appeals off. */
672
+ mine(who: RawWho): PlayerAppeal[];
673
+ /**
674
+ * Decide an open appeal: `uphold` (the sanction stands), `reduce` (to a lighter kind, or the same kind and shorter, keeping the original
675
+ * start so the ladder does not restart, never ending later than the original) or `revoke`. A moderator may not decide an appeal of
676
+ * their own decision unless `appeals.allowSelfReview` is on (`same_decider`); an automatic sanction has no such decider. `reason` is
677
+ * private (1 to 500 characters). One transaction; the player is told through a notice; `appeal.decided` is emitted after the commit.
678
+ * Staff-side: the permission and the audit row belong to the route. A store failure rejects and writes nothing.
679
+ */
680
+ decide(input: AppealDecision): Promise<AppealDecideResult>;
681
+ /**
682
+ * The inbox, oldest first: `open` (default), `decided` or `all`; `limit` 1 to 200 (default 50); an opaque `cursor`. A summary carries a
683
+ * staff ref and never the statement (`statementFlagged` says whether it trips the term filter). `RangeError` for a bad query. Empty with
684
+ * appeals off. Carries subject ids: staff channels only, never send to a player.
685
+ */
686
+ list(q: { status?: 'open' | 'decided' | 'all'; limit?: number; cursor?: string | null }): AppealPage;
687
+ /** One appeal in full, the statement included (null once purged), or null for an unknown id. The route audits this read. Staff only. */
688
+ get(id: string): AppealDetail | null;
689
+ /** How many appeals are waiting. */
690
+ openCount(): number;
691
+ /**
692
+ * The per-rule counts over the last 30, 90 (default) or 365 days. The rate is revoked appeals over sanctions given, null below 10
693
+ * sanctions; a reduction is `lightened`, shown beside the rate and never in it. `RangeError` for another window.
694
+ */
695
+ stats(q?: { days?: 30 | 90 | 365 }): AppealStats;
696
+ /**
697
+ * One person's appeals (across their merged subjects) as summaries, newest first, at most 50; a moot appeal is left out. For the person's
698
+ * page. Still listed after appeals are switched off (what was filed stays visible until retention removes it); empty for a store that cannot keep
699
+ * appeals or a person the kit does not hold. Carries a staff ref and never the statement: staff channels only.
700
+ * @experimental
701
+ */
702
+ forPerson(subject: SubjectId): AppealSummary[];
703
+ };
608
704
  /**
609
705
  * Decide a report: close it, write each sanction and its notice, and tell the people involved, in one
610
706
  * transaction. Idempotent (the same decision again is a replay). A malformed or disallowed decision resolves
@@ -679,6 +775,13 @@ export interface Chatwarden {
679
775
  people: {
680
776
  canonical(subject: SubjectId): SubjectId;
681
777
  aliases(subject: SubjectId): SubjectId[];
778
+ /**
779
+ * The account ids the kit holds for this person across their merged aliases, sorted: exactly the strings the game passed as
780
+ * `RawWho.accountId` (no client key, no IP, no hash). A guest has none; so does an unknown id. For the game to find the player to rename
781
+ * after `rename.required`. Server side only: never send to a player.
782
+ * @experimental
783
+ */
784
+ accountIds(subject: SubjectId): string[];
682
785
  };
683
786
  /**
684
787
  * The Discord feed's thread map (`@chatwarden/discord`): the forum thread kept per person (`kit_discord_threads`). A
@@ -716,7 +819,12 @@ function buildProfanityFilter(opts: ChatwardenOptions, config: ProfanityConfig):
716
819
  if (config.mode === 'allow') return undefined;
717
820
  if (opts.profanity !== undefined) return opts.profanity;
718
821
  if (opts.profanityPackage === undefined) return undefined;
719
- const built = opts.profanityPackage.createProfanityFilter(config);
822
+ return buildPackageFilter(opts.profanityPackage, config);
823
+ }
824
+
825
+ /** The filter a profanity package builds from the resolved config; a non-filter is a TypeError. */
826
+ function buildPackageFilter(pkg: NonNullable<ChatwardenOptions['profanityPackage']>, config: ProfanityConfig): ProfanityFilter {
827
+ const built = pkg.createProfanityFilter(config);
720
828
  if (typeof built !== 'object' || built === null || typeof built.apply !== 'function') {
721
829
  throw new TypeError('profanityPackage.createProfanityFilter must return a filter with an apply(text) method');
722
830
  }
@@ -810,7 +918,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
810
918
  await mutes.load();
811
919
  await strikes.load();
812
920
  // The stored edits to the profile. Read last, so a store that fails here has not left anything half built.
813
- const policy = new PolicyService({ store, clock, logger, base: baseProfile, signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs, chatRate: limits.chatRate });
921
+ const policy = new PolicyService({ store, clock, logger, base: baseProfile, signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs, chatRate: limits.chatRate, appealsKept: hasAppealMethods(store) });
814
922
  policy.load();
815
923
 
816
924
  // ONE notice service for the whole kit: chat (the automatic timeout), the doors (the refusal's pointer) and
@@ -919,6 +1027,13 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
919
1027
  const ids = hashWho(hasher, who);
920
1028
  return subjects.lookup({ clientKey: ids.clientKey, accountId: ids.accountId, ipHash: null });
921
1029
  };
1030
+ // Appeals. Turning them on in code (the profile or its overrides) over a store that cannot keep them is a plain mistake, refused here
1031
+ // before anything is started. A stored layer that does it is data, not code: the policy keeps appeals off and warns (see PolicyService).
1032
+ if (baseProfile.appeals.enabled && !hasAppealMethods(store)) {
1033
+ throw new Error('createChatwarden: appeals are enabled, but this store has no appeal methods (SqliteStore has them from schema 22; the in-memory store needs its opt-in appeals wrapper)');
1034
+ }
1035
+ /** The one answer to "does a moot or a decision clear the statement at once": the retention the kit was created with. */
1036
+ const clearAppealStatements = (): boolean => (retentionPolicy.appealStatementsMs ?? RETENTION_DEFAULTS.appealStatementsMs) === 0;
922
1037
  signalRef.service = signalModule === undefined ? createInertSignals(logger, () => policy.profileNow().signals) : new signalModule.SignalService({
923
1038
  store,
924
1039
  clock,
@@ -1054,10 +1169,60 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1054
1169
  audit: (input) => audit.record(input),
1055
1170
  exampleRetentionMs: () => retentionPolicy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
1056
1171
  // The counts about the reported person the feed allows (`feeds.ai`), as label, polarity, distinct and window: nothing else leaves.
1172
+ // The rules cautioned for by the appeals the moderators lost (revokes only), as bands and rule numbers: never a rate, a count or a person.
1173
+ cautions: () => appealService.cautions(),
1057
1174
  signals: (subject) => signals.forAi(subject).map((c) => ({ label: c.label, polarity: c.polarity, distinct: c.distinct, windowDays: c.windowDays })),
1058
1175
  });
1059
1176
  aiRef.service = aiService;
1060
1177
  const ai: AiFacade = aiService ?? createInertAi();
1178
+ const appealService = new AppealService({
1179
+ store,
1180
+ subjects,
1181
+ notices,
1182
+ clock,
1183
+ logger,
1184
+ settings: () => policy.profileNow().appeals,
1185
+ personOf,
1186
+ emit: (event) => bus.emit(event),
1187
+ matcher: opts.matcher,
1188
+ index: sanctions,
1189
+ clearStatements: clearAppealStatements,
1190
+ // A granted appeal marks the original decision reversed in the casebook; with no AI this is the inert facade and does nothing.
1191
+ // A REVOKE teaches the opposite sign and counts as a false positive; a REDUCE only keeps the decision from teaching (the rule applied).
1192
+ onGranted: (appeal, outcome) => void (outcome === 'revoke' ? ai.markReversed(appeal.reportId as string, { corrective: true }) : ai.markReversed(appeal.reportId as string)),
1193
+ });
1194
+
1195
+ // Names. The profanity filter for a name is the kit's own when the profile has one; otherwise (a profile that allows swearing in chat) it is
1196
+ // built from the package on first use, so `names.profanity` works whatever the chat profile does with swearing. A package that cannot build
1197
+ // one fails once and is remembered: the name check lets names through and logs the class.
1198
+ let nameFilter: { filter: ProfanityFilter | undefined } | { error: unknown } | undefined;
1199
+ const filterForNames = (): ProfanityFilter | undefined => {
1200
+ if (profanity !== undefined) return profanity;
1201
+ if (nameFilter === undefined) {
1202
+ try {
1203
+ nameFilter = { filter: opts.profanity ?? (opts.profanityPackage === undefined ? undefined : buildPackageFilter(opts.profanityPackage, baseProfile.profanity)) };
1204
+ } catch (error) {
1205
+ nameFilter = { error };
1206
+ }
1207
+ }
1208
+ if ('error' in nameFilter) throw nameFilter.error;
1209
+ return nameFilter.filter;
1210
+ };
1211
+ const nameService = new NameService({
1212
+ store,
1213
+ clock,
1214
+ logger,
1215
+ hasher,
1216
+ rule: autoRestrictRule,
1217
+ matcher: opts.matcher,
1218
+ settings: () => policy.profileNow().names,
1219
+ filter: filterForNames,
1220
+ personOf,
1221
+ notices,
1222
+ subjects,
1223
+ rules,
1224
+ emit: (event) => bus.emit(event),
1225
+ });
1061
1226
 
1062
1227
  return {
1063
1228
  ai,
@@ -1157,6 +1322,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1157
1322
  blocked: {
1158
1323
  list: (q) => blockedItems(store, subjects, q?.days, clock.now()),
1159
1324
  countsByTerm: (q) => blockedCountsByTerm(store, q?.days, clock.now()),
1325
+ names: (q) => blockedNameItems(store, subjects, q?.days, clock.now()),
1160
1326
  },
1161
1327
  cases: {
1162
1328
  holder: (person) => desk.holder(person),
@@ -1207,7 +1373,12 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1207
1373
  revoke: async (groupId, actor, reason) => {
1208
1374
  // One instant for the stored revokedAt and the event, so a consumer correlating the two sees the same time.
1209
1375
  const at = clock.now();
1210
- const { revoked } = await revokeAndWithdraw(store, groupId, actor, reason, { notices, clock: { now: () => at }, index: sanctions });
1376
+ const { revoked } = await revokeAndWithdraw(store, groupId, actor, reason, {
1377
+ notices,
1378
+ clock: { now: () => at },
1379
+ index: sanctions,
1380
+ clearAppealStatements,
1381
+ });
1211
1382
  if (revoked) {
1212
1383
  try {
1213
1384
  const code = store.sanctionRefCode(groupId);
@@ -1240,18 +1411,13 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1240
1411
  },
1241
1412
  on: bus.on,
1242
1413
  names: {
1243
- check: (text) => {
1244
- if (typeof text !== 'string') throw new TypeError('names.check: the name must be a string');
1245
- const m = opts.matcher;
1246
- if (m === undefined) return { ok: true };
1247
- try {
1248
- const hit = typeof m.matchName === 'function' ? m.matchName(text) : m.match(text);
1249
- return hit === null ? { ok: true } : { ok: false, reason: 'name_not_allowed', rule: autoRestrictRule };
1250
- } catch (err) {
1251
- safeWarn(logger, 'chatwarden.names_matcher_failed', { error: err instanceof Error ? err.name : typeof err });
1252
- return { ok: true };
1253
- }
1254
- },
1414
+ check: (text, o) => nameService.check(text, o),
1415
+ flagged: (text) => nameService.flagged(text),
1416
+ requireRename: (input) => nameService.requireRename(input),
1417
+ pendingRename: (who) => nameService.pendingRename(who),
1418
+ renamed: (who) => nameService.renamed(who),
1419
+ renamesEnabled: () => nameService.renamesEnabled(),
1420
+ renamesOf: (subject) => nameService.renamesOf(subject),
1255
1421
  },
1256
1422
  rules,
1257
1423
  get profile() {
@@ -1280,6 +1446,17 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1280
1446
  record: (who) => forPlayer<PlayerNotice[]>(who, [], (s) => notices.record(s)),
1281
1447
  pendingWarning: (who) => forPlayer(who, false, (s) => notices.pendingWarning(s)),
1282
1448
  },
1449
+ appeals: {
1450
+ enabled: () => appealService.enabled(),
1451
+ file: (who, input) => appealService.file(who, input),
1452
+ mine: (who) => appealService.mine(who),
1453
+ decide: (input) => appealService.decide(input),
1454
+ list: (q) => appealService.list(q),
1455
+ get: (id) => appealService.get(id),
1456
+ openCount: () => appealService.openCount(),
1457
+ stats: (q) => appealService.stats(q),
1458
+ forPerson: (subject) => appealService.forPerson(subject),
1459
+ },
1283
1460
  decide: (input) => decideAnnounced(input),
1284
1461
  history: (subject) => historyOf(store, subjects, subject, clock.now()),
1285
1462
  suggest: (subject, level, rule, context) => {
@@ -1320,6 +1497,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1320
1497
  people: {
1321
1498
  canonical: (subject) => subjects.canonical(subject),
1322
1499
  aliases: (subject) => subjects.aliasesOf(subject),
1500
+ accountIds: (subject) => (typeof subject === 'string' ? subjects.identifiersOf(subject).accounts : []),
1323
1501
  },
1324
1502
  discordThreads: {
1325
1503
  get: (subject) => store.transaction(() => store.getDiscordThread(subject)),