@chatwarden/core 0.1.7 → 0.1.9

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 (176) hide show
  1. package/README.md +306 -7
  2. package/dist/src/ai/case.d.ts +4 -3
  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 +3 -1
  7. package/dist/src/ai/hash.d.ts.map +1 -1
  8. package/dist/src/ai/hash.js +5 -2
  9. package/dist/src/ai/hash.js.map +1 -1
  10. package/dist/src/ai/prompt.d.ts +13 -2
  11. package/dist/src/ai/prompt.d.ts.map +1 -1
  12. package/dist/src/ai/prompt.js +31 -1
  13. package/dist/src/ai/prompt.js.map +1 -1
  14. package/dist/src/ai/service.d.ts +21 -6
  15. package/dist/src/ai/service.d.ts.map +1 -1
  16. package/dist/src/ai/service.js +14 -7
  17. package/dist/src/ai/service.js.map +1 -1
  18. package/dist/src/ai/types.d.ts +33 -2
  19. package/dist/src/ai/types.d.ts.map +1 -1
  20. package/dist/src/ai/types.js +3 -2
  21. package/dist/src/ai/types.js.map +1 -1
  22. package/dist/src/ai/worker.d.ts +8 -1
  23. package/dist/src/ai/worker.d.ts.map +1 -1
  24. package/dist/src/ai/worker.js +17 -3
  25. package/dist/src/ai/worker.js.map +1 -1
  26. package/dist/src/appealService.d.ts +105 -0
  27. package/dist/src/appealService.d.ts.map +1 -0
  28. package/dist/src/appealService.js +548 -0
  29. package/dist/src/appealService.js.map +1 -0
  30. package/dist/src/appeals.d.ts +194 -0
  31. package/dist/src/appeals.d.ts.map +1 -0
  32. package/dist/src/appeals.js +107 -0
  33. package/dist/src/appeals.js.map +1 -0
  34. package/dist/src/audit.d.ts +7 -3
  35. package/dist/src/audit.d.ts.map +1 -1
  36. package/dist/src/audit.js +18 -3
  37. package/dist/src/audit.js.map +1 -1
  38. package/dist/src/chat.d.ts +39 -1
  39. package/dist/src/chat.d.ts.map +1 -1
  40. package/dist/src/chat.js +85 -6
  41. package/dist/src/chat.js.map +1 -1
  42. package/dist/src/chatwarden.d.ts +197 -10
  43. package/dist/src/chatwarden.d.ts.map +1 -1
  44. package/dist/src/chatwarden.js +212 -23
  45. package/dist/src/chatwarden.js.map +1 -1
  46. package/dist/src/decide.d.ts +2 -0
  47. package/dist/src/decide.d.ts.map +1 -1
  48. package/dist/src/decide.js +12 -7
  49. package/dist/src/decide.js.map +1 -1
  50. package/dist/src/documents.d.ts +1 -1
  51. package/dist/src/documents.d.ts.map +1 -1
  52. package/dist/src/documents.js +5 -1
  53. package/dist/src/documents.js.map +1 -1
  54. package/dist/src/events.d.ts +38 -0
  55. package/dist/src/events.d.ts.map +1 -1
  56. package/dist/src/events.js +3 -0
  57. package/dist/src/events.js.map +1 -1
  58. package/dist/src/freeze.d.ts +3 -0
  59. package/dist/src/freeze.d.ts.map +1 -0
  60. package/dist/src/freeze.js +10 -0
  61. package/dist/src/freeze.js.map +1 -0
  62. package/dist/src/index.d.ts +20 -9
  63. package/dist/src/index.d.ts.map +1 -1
  64. package/dist/src/index.js +11 -3
  65. package/dist/src/index.js.map +1 -1
  66. package/dist/src/ladder.d.ts +28 -0
  67. package/dist/src/ladder.d.ts.map +1 -1
  68. package/dist/src/ladder.js +37 -1
  69. package/dist/src/ladder.js.map +1 -1
  70. package/dist/src/nameService.d.ts +90 -0
  71. package/dist/src/nameService.d.ts.map +1 -0
  72. package/dist/src/nameService.js +224 -0
  73. package/dist/src/nameService.js.map +1 -0
  74. package/dist/src/names.d.ts +68 -0
  75. package/dist/src/names.d.ts.map +1 -0
  76. package/dist/src/names.js +87 -0
  77. package/dist/src/names.js.map +1 -0
  78. package/dist/src/notices.d.ts +53 -5
  79. package/dist/src/notices.d.ts.map +1 -1
  80. package/dist/src/notices.js +93 -8
  81. package/dist/src/notices.js.map +1 -1
  82. package/dist/src/pace.d.ts +66 -0
  83. package/dist/src/pace.d.ts.map +1 -0
  84. package/dist/src/pace.js +111 -0
  85. package/dist/src/pace.js.map +1 -0
  86. package/dist/src/pacing.d.ts +63 -0
  87. package/dist/src/pacing.d.ts.map +1 -0
  88. package/dist/src/pacing.js +198 -0
  89. package/dist/src/pacing.js.map +1 -0
  90. package/dist/src/policy.d.ts +66 -1
  91. package/dist/src/policy.d.ts.map +1 -1
  92. package/dist/src/policy.js +86 -5
  93. package/dist/src/policy.js.map +1 -1
  94. package/dist/src/profile.d.ts +57 -8
  95. package/dist/src/profile.d.ts.map +1 -1
  96. package/dist/src/profile.js +69 -25
  97. package/dist/src/profile.js.map +1 -1
  98. package/dist/src/profileError.d.ts +10 -0
  99. package/dist/src/profileError.d.ts.map +1 -0
  100. package/dist/src/profileError.js +17 -0
  101. package/dist/src/profileError.js.map +1 -0
  102. package/dist/src/retention.d.ts +40 -1
  103. package/dist/src/retention.d.ts.map +1 -1
  104. package/dist/src/retention.js +50 -3
  105. package/dist/src/retention.js.map +1 -1
  106. package/dist/src/sanctions.d.ts +29 -1
  107. package/dist/src/sanctions.d.ts.map +1 -1
  108. package/dist/src/sanctions.js +52 -9
  109. package/dist/src/sanctions.js.map +1 -1
  110. package/dist/src/signalCounts.d.ts +37 -0
  111. package/dist/src/signalCounts.d.ts.map +1 -0
  112. package/dist/src/signalCounts.js +117 -0
  113. package/dist/src/signalCounts.js.map +1 -0
  114. package/dist/src/signalInert.d.ts +10 -0
  115. package/dist/src/signalInert.d.ts.map +1 -0
  116. package/dist/src/signalInert.js +28 -0
  117. package/dist/src/signalInert.js.map +1 -0
  118. package/dist/src/signalService.d.ts +101 -0
  119. package/dist/src/signalService.d.ts.map +1 -0
  120. package/dist/src/signalService.js +383 -0
  121. package/dist/src/signalService.js.map +1 -0
  122. package/dist/src/signals.d.ts +186 -0
  123. package/dist/src/signals.d.ts.map +1 -0
  124. package/dist/src/signals.js +361 -0
  125. package/dist/src/signals.js.map +1 -0
  126. package/dist/src/staffViews.d.ts +18 -0
  127. package/dist/src/staffViews.d.ts.map +1 -1
  128. package/dist/src/staffViews.js +14 -0
  129. package/dist/src/staffViews.js.map +1 -1
  130. package/dist/src/subjects.d.ts +2 -0
  131. package/dist/src/subjects.d.ts.map +1 -1
  132. package/dist/src/subjects.js +4 -0
  133. package/dist/src/subjects.js.map +1 -1
  134. package/dist/src/team.d.ts +27 -0
  135. package/dist/src/team.d.ts.map +1 -1
  136. package/dist/src/team.js +92 -4
  137. package/dist/src/team.js.map +1 -1
  138. package/dist/src/types.d.ts +254 -7
  139. package/dist/src/types.d.ts.map +1 -1
  140. package/dist/src/types.js.map +1 -1
  141. package/package.json +2 -2
  142. package/src/ai/case.ts +6 -4
  143. package/src/ai/hash.ts +5 -2
  144. package/src/ai/prompt.ts +39 -2
  145. package/src/ai/service.ts +29 -14
  146. package/src/ai/types.ts +31 -2
  147. package/src/ai/worker.ts +20 -4
  148. package/src/appealService.ts +584 -0
  149. package/src/appeals.ts +256 -0
  150. package/src/audit.ts +18 -3
  151. package/src/chat.ts +109 -8
  152. package/src/chatwarden.ts +382 -27
  153. package/src/decide.ts +13 -7
  154. package/src/documents.ts +8 -3
  155. package/src/events.ts +23 -1
  156. package/src/freeze.ts +8 -0
  157. package/src/index.ts +52 -3
  158. package/src/ladder.ts +59 -1
  159. package/src/nameService.ts +255 -0
  160. package/src/names.ts +121 -0
  161. package/src/notices.ts +112 -14
  162. package/src/pace.ts +139 -0
  163. package/src/pacing.ts +242 -0
  164. package/src/policy.ts +125 -8
  165. package/src/profile.ts +115 -25
  166. package/src/profileError.ts +17 -0
  167. package/src/retention.ts +79 -3
  168. package/src/sanctions.ts +72 -9
  169. package/src/signalCounts.ts +133 -0
  170. package/src/signalInert.ts +31 -0
  171. package/src/signalService.ts +406 -0
  172. package/src/signals.ts +489 -0
  173. package/src/staffViews.ts +30 -0
  174. package/src/subjects.ts +5 -0
  175. package/src/team.ts +93 -5
  176. package/src/types.ts +275 -8
package/src/decide.ts CHANGED
@@ -6,7 +6,7 @@ import { safeWarn } from './log.js';
6
6
  import { ownLines } from './notices.js';
7
7
  import type { NoticeService } from './notices.js';
8
8
  import type { CommunityRules, RuleRef } from './rules.js';
9
- import { SANCTION_KINDS, SANCTION_SOURCES, validateSanctionInput, writeSanction } from './sanctions.js';
9
+ import { APPEALS_START_TOKEN, SANCTION_KINDS, SANCTION_SOURCES, validateSanctionInput, writeSanction } from './sanctions.js';
10
10
  import type { SanctionIndex } from './sanctions.js';
11
11
  import type { SubjectIndex } from './subjects.js';
12
12
  import { CONDUCT_LEVELS } from './types.js';
@@ -480,7 +480,7 @@ export class DecisionService {
480
480
  });
481
481
  }
482
482
 
483
- private sanctionInput(norm: Normal, a: NormalAction, roomId: string) {
483
+ private sanctionInput(norm: Normal, a: NormalAction, roomId: string, reportId?: string) {
484
484
  return {
485
485
  kind: a.kind,
486
486
  subject: a.subject,
@@ -493,6 +493,8 @@ export class DecisionService {
493
493
  rule: a.rule,
494
494
  roomId: roomId === '' ? null : roomId,
495
495
  ...(a.gapNote === undefined ? {} : { gapNote: a.gapNote }),
496
+ // The report this decision closes: a granted appeal against the sanction marks that decision reversed.
497
+ ...(reportId === undefined ? {} : { reportId, startsAtToken: APPEALS_START_TOKEN }),
496
498
  };
497
499
  }
498
500
 
@@ -513,7 +515,7 @@ export class DecisionService {
513
515
  const told = new Set<SubjectId>();
514
516
  for (const { action: a, lines } of plan) {
515
517
  // No index here: the rows reach it only after the transaction has committed.
516
- const written = writeSanction(this.store, this.subjects, this.sanctionInput(norm, a, report.roomId), now, pending);
518
+ const written = writeSanction(this.store, this.subjects, this.sanctionInput(norm, a, report.roomId, report.id), now, pending);
517
519
  // A note is on the record and tells the player nothing: no notice, so nobody to announce to either.
518
520
  const noticeId =
519
521
  a.kind === 'note'
@@ -629,6 +631,8 @@ export interface RevokeDeps {
629
631
  clock: Clock;
630
632
  /** Dropped from once the revoke has committed. */
631
633
  index?: SanctionIndex;
634
+ /** True when `retention.appealStatementsMs` is 0: the statement of an appeal this revoke makes moot is cleared with it. */
635
+ clearAppealStatements?: () => boolean;
632
636
  }
633
637
 
634
638
  /**
@@ -646,10 +650,12 @@ export function revokeAndWithdraw(
646
650
  ): Promise<{ revoked: boolean; withdrawn: number }> {
647
651
  try {
648
652
  const now = deps.clock.now();
649
- const out = store.transaction(() => ({
650
- revoked: store.revokeSanctionGroup(groupId, actor, now, reason) > 0,
651
- withdrawn: deps.notices.withdrawGroup(groupId),
652
- }));
653
+ const out = store.transaction(() => {
654
+ const revoked = store.revokeSanctionGroup(groupId, actor, now, reason) > 0;
655
+ // An appeal still open against this group is moot now (same transaction: both land or neither).
656
+ if (revoked) store.closeAppealsForGroup?.(groupId, actor, now, deps.clearAppealStatements?.() === true);
657
+ return { revoked, withdrawn: deps.notices.withdrawGroup(groupId) };
658
+ });
653
659
  deps.index?.remove(groupId);
654
660
  return Promise.resolve(out);
655
661
  } catch (err) {
package/src/documents.ts CHANGED
@@ -53,7 +53,7 @@ export interface ModeratorGuideOptions {
53
53
  export interface PolicyJson {
54
54
  version: 1;
55
55
  /** With `durations` and `customDuration` filled in, so a profile written for 0.1.1 reads back with the two new keys. */
56
- profile: Omit<ResolvedProfile, 'ai'>;
56
+ profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals' | 'appeals' | 'names'>;
57
57
  /** Every rule, retired ones included, in number order. */
58
58
  rules: CommunityRule[];
59
59
  }
@@ -705,9 +705,14 @@ export function agentBrief(policy: DocumentPolicy): string {
705
705
  */
706
706
  export function policyJson(policy: DocumentPolicy): PolicyJson {
707
707
  const snapshot = checkPolicy(policy);
708
- // The AI settings are the moderator's runtime switch, not policy text: the document tools never carry them.
709
- const profile: Omit<ResolvedProfile, 'ai'> & { ai?: unknown } = structuredClone(snapshot.profile);
708
+ // The AI, pace, signal, appeal and name settings are runtime switches, not policy text: the document tools never carry them.
709
+ const profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals' | 'appeals' | 'names'> & { ai?: unknown; pace?: unknown; signals?: unknown; appeals?: unknown; names?: unknown } =
710
+ structuredClone(snapshot.profile);
710
711
  delete profile.ai;
712
+ delete profile.pace;
713
+ delete profile.signals;
714
+ delete profile.appeals;
715
+ delete profile.names;
711
716
  return { version: 1, profile, rules: snapshot.rules.all() };
712
717
  }
713
718
 
package/src/events.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import { safeWarn } from './log.js';
2
+ import type { AppealOutcome } from './appeals.js';
2
3
  import type { RuleRef } from './rules.js';
3
4
  import type { Logger, ReportCategory, SanctionKind, Source, SubjectId } from './types.js';
4
5
 
@@ -67,7 +68,25 @@ export type KitEvent =
67
68
  * person who was timed out (canonical at emit time).
68
69
  * Carries subject ids: staff channels only, never send to a player.
69
70
  */
70
- | { type: 'auto.restricted'; groupId: string; refCode: string; second: boolean; subject: StaffRef };
71
+ | { type: 'auto.restricted'; groupId: string; refCode: string; second: boolean; subject: StaffRef }
72
+ /**
73
+ * A player filed an appeal against a sanction. `target` is the person (canonical at emit time), `kind` the sanction's kind and `rule`
74
+ * the Community Rule it cited. Like `report.created` it carries ids, codes and times, never the statement or the player's handle.
75
+ * Carries subject ids: staff channels only, never send to a player. @experimental
76
+ */
77
+ | { type: 'appeal.created'; appealId: string; createdAt: number; target: StaffRef; kind: SanctionKind; rule: RuleRef | null }
78
+ /**
79
+ * A moderator decided an appeal: `outcome` is uphold, reduce or revoke. Never the reason, the statement or a handle; an appeal made
80
+ * moot by someone else's revoke announces nothing.
81
+ * Carries subject ids: staff channels only, never send to a player. @experimental
82
+ */
83
+ | { type: 'appeal.decided'; appealId: string; at: number; target: StaffRef; outcome: AppealOutcome; rule: RuleRef | null }
84
+ /**
85
+ * A moderator required a rename. It names no name and no reason: the game learns who to rename through `cw.people.accountIds(target)`
86
+ * or a webhook that opted in to accounts.
87
+ * Carries subject ids: staff channels only, never send to a player. @experimental
88
+ */
89
+ | { type: 'rename.required'; at: number; target: StaffRef; rule: RuleRef | null };
71
90
 
72
91
  /** Every event type, for checking a subscription. */
73
92
  export const KIT_EVENT_TYPES: readonly KitEvent['type'][] = [
@@ -77,6 +96,9 @@ export const KIT_EVENT_TYPES: readonly KitEvent['type'][] = [
77
96
  'sanction.revoked',
78
97
  'gap.created',
79
98
  'auto.restricted',
99
+ 'appeal.created',
100
+ 'appeal.decided',
101
+ 'rename.required',
80
102
  ];
81
103
 
82
104
  /** The event of a type. */
package/src/freeze.ts ADDED
@@ -0,0 +1,8 @@
1
+ /** Freeze a value and everything inside it (plain data: objects, arrays, numbers, strings). Returns the same value. */
2
+ export function deepFreeze<T>(v: T): T {
3
+ if (typeof v === 'object' && v !== null && !Object.isFrozen(v)) {
4
+ Object.freeze(v);
5
+ for (const item of Object.values(v)) deepFreeze(item);
6
+ }
7
+ return v;
8
+ }
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '0.1.7';
1
+ export const VERSION = '0.1.9';
2
2
 
3
3
  export type {
4
4
  Clock,
@@ -45,6 +45,10 @@ export type {
45
45
  ClaimRow,
46
46
  OpenReportQuery,
47
47
  ReasonRow,
48
+ SignalRow,
49
+ SignalSourceRow,
50
+ AppealRow,
51
+ BlockedNameRow,
48
52
  ConductLevel,
49
53
  Source,
50
54
  Store,
@@ -65,6 +69,7 @@ export {
65
69
  REASONS_MAX,
66
70
  ReasonBook,
67
71
  ReasonError,
72
+ SIGNAL_BOOST_SCAN_MAX,
68
73
  ViewingPresence,
69
74
  VIEWING_TTL_MS,
70
75
  } from './team.js';
@@ -189,6 +194,7 @@ export type { ReporterAccuracy } from './reporterAccuracy.js';
189
194
  export type {
190
195
  BlockedDays,
191
196
  BlockedItem,
197
+ BlockedNameItem,
192
198
  PersonSanctionView,
193
199
  ReporterRecord,
194
200
  SanctionGroupView,
@@ -225,6 +231,7 @@ export { WEBHOOK_KEY_TTL_MS } from './types.js';
225
231
  export type { PurgeResult, RetentionPolicy } from './retention.js';
226
232
  export {
227
233
  ExcerptError,
234
+ MESSAGE_NOTICE_KINDS,
228
235
  NOTICE_EXCERPT_MAX,
229
236
  NOTICE_RECORD_WINDOW_MS,
230
237
  NoticeService,
@@ -233,6 +240,8 @@ export {
233
240
  } from './notices.js';
234
241
  export type {
235
242
  ExcerptErrorCode,
243
+ MessageNoticeKind,
244
+ MessageNoticeOptions,
236
245
  NoticeCreateOptions,
237
246
  NoticeServiceDeps,
238
247
  PlayerNotice,
@@ -277,7 +286,7 @@ export {
277
286
  recordStep,
278
287
  suggest,
279
288
  } from './ladder.js';
280
- export type { ActionRecord, LadderCell, LadderRow, LadderStep, Suggestion, SuggestContext } from './ladder.js';
289
+ export type { ActionRecord, LadderCell, LadderRow, LadderStep, Suggestion, SuggestContext, SignalHit } from './ladder.js';
281
290
  export {
282
291
  DECISION_EVIDENCE_MAX,
283
292
  DECISION_REASON_MAX,
@@ -315,8 +324,48 @@ export {
315
324
  resolveProfile,
316
325
  validateProfile,
317
326
  } from './profile.js';
327
+ // Pace settings (@experimental): slow mode, burst limit and repeat refusal, all off until set.
328
+ export { DUPLICATE_MIN_CHARS, DUPLICATE_RECENT, mergePace, PACE_KEYS_MAX, PACE_REASONS, PACE_SUGGESTIONS, resolvePace } from './pace.js';
329
+ export type { PaceReason, PaceSettings, ResolvedPace } from './pace.js';
330
+ // Appeals and names settings (@experimental): off until set (names masking in the hub is the one default-on setting).
331
+ export { APPEAL_OUTCOMES, APPEAL_RATE_ELEVATED, APPEAL_RATE_HIGH, APPEAL_STATEMENT_MAX, APPEAL_STATS_MIN_SANCTIONS, normalizeStatement, resolveAppeals, SANCTION_KIND_ORDER, statementLength } from './appeals.js';
332
+ export type { AppealDecideResult, AppealDecision, AppealDetail, AppealFileResult, AppealOutcome, AppealPage, AppealRuleStats, AppealStats, AppealSummary, AppealRefusal, AppealSettings, AppealStatus, PlayerAppeal, ResolvedAppeals } from './appeals.js';
333
+ export { resolveNames } from './names.js';
334
+ export type { NameCheckResult, NameReason, NameSettings, ResolvedNames } from './names.js';
335
+ // Signals (@experimental): kinds a game declares, the guards, and the feeds that say where counts may be read.
336
+ export {
337
+ BUILTIN_SIGNAL_KINDS,
338
+ checkSignalFeeds,
339
+ kindSpecOf,
340
+ pruneSignalFeeds,
341
+ resolveSignals,
342
+ SIGNAL_KIND_PATTERN,
343
+ SIGNAL_KINDS_MAX,
344
+ SIGNAL_WINDOW_DAYS_MAX,
345
+ } from './signals.js';
346
+ export { countSignals, evaluateThreshold } from './signalCounts.js';
347
+ export type { SignalRefusal } from './signalService.js';
348
+ export type { CountContext, ThresholdResult } from './signalCounts.js';
349
+ export type {
350
+ ResolvedSignalGuards,
351
+ ResolvedSignalKind,
352
+ ResolvedSignals,
353
+ SignalCount,
354
+ SignalDropReason,
355
+ SignalFeeds,
356
+ SignalGuards,
357
+ SignalInput,
358
+ SignalKindSpec,
359
+ SignalKindView,
360
+ SignalParty,
361
+ SignalPolarity,
362
+ SignalSettings,
363
+ SignalThreshold,
364
+ } from './signals.js';
318
365
  export { POLICY_REFRESH_MS, PREVIEW_SAMPLES } from './policy.js';
319
366
  export type {
367
+ PolicyDropped,
368
+ PolicyLimits,
320
369
  PolicyPreview,
321
370
  PolicySaveContext,
322
371
  PolicySaveResult,
@@ -347,7 +396,7 @@ export type {
347
396
 
348
397
  // AI levels 1 and 2: the provider-free contract (@experimental). Kept apart from the rest so a bundler can drop it.
349
398
  export { AI_PROMPT_VERSION, AIError } from './ai/types.js';
350
- export type { AbortSignalLike, AIExample, AIExampleInput, AIPerson, AIRead, AIReadInput, AIReadResult, AIStoredRead, AIUsage, ModerationAI } from './ai/types.js';
399
+ export type { AbortSignalLike, AIExample, AIExampleInput, AIPerson, AIRead, AIReadInput, AIReadResult, AISignal, AIStoredRead, AIUsage, ModerationAI } from './ai/types.js';
351
400
  export { AI_OUTPUT_SCHEMA } from './ai/schema.js';
352
401
  export { validateAIOutput } from './ai/validate.js';
353
402
  export type { AIValidation, AIValidationContext } from './ai/validate.js';
package/src/ladder.ts CHANGED
@@ -153,6 +153,30 @@ export interface SuggestContext {
153
153
  * escalation never fires: without it this incident cannot count as a different game.
154
154
  */
155
155
  roomId?: string | null;
156
+ /**
157
+ * The signal rules that fired for the reported person (design 5.6). Set by the facade (`cw.suggest` computes them from
158
+ * `feeds.ladder` and ignores a list passed to it); a rule only adds to the suggestion, never starts one: banter returns before any
159
+ * of this, and nothing here applies a sanction.
160
+ * @experimental
161
+ */
162
+ signals?: readonly SignalHit[];
163
+ /**
164
+ * Leave the signal rules' sentences and the `signals` key out of the suggestion (the outcome still moves, which is the part a decider must
165
+ * see). For a caller who may not read the person's record: the sentence is a count of what other players did. Set by a route; default false.
166
+ * @experimental
167
+ */
168
+ hideSignalText?: boolean;
169
+ }
170
+
171
+ /**
172
+ * One signal rule that fired: its id, what it does and the sentence for the moderator ("Muted by other players: 5 players in 14
173
+ * days"). Carries no identifier.
174
+ * @experimental
175
+ */
176
+ export interface SignalHit {
177
+ id: string;
178
+ effect: 'note' | 'raise';
179
+ text: string;
156
180
  }
157
181
 
158
182
  /** One suggested next action, with the plain reason a moderator can read out. Carries no identifier. */
@@ -162,6 +186,8 @@ export interface Suggestion {
162
186
  label: string;
163
187
  /** One plain sentence naming the profile and the reason. */
164
188
  why: string;
189
+ /** Present only when a signal rule fired: the ids of the rules, and whether one of them raised the suggestion by a step. @experimental */
190
+ signals?: { raised: boolean; ids: string[] };
165
191
  }
166
192
 
167
193
  function plural(n: number, unit: string): string {
@@ -353,6 +379,24 @@ export function suggest(
353
379
  }
354
380
  }
355
381
 
382
+ // Signal rules (the ladder feed): a `raise` rule takes the ladder cell one step further down the column this suggestion read, only when
383
+ // it is stronger than the pick and not permanent; every other hit (and a raise that did nothing) is a sentence. Before the area swap.
384
+ const hits = usableHits(context.signals);
385
+ const sentences: string[] = [];
386
+ let raised = false;
387
+ if (hits.length > 0) {
388
+ const nextRow = step < 5 ? profile.ladder[step + 1] : undefined;
389
+ const cell = nextRow === undefined ? undefined : severe || read === 'hostile' ? nextRow.high : nextRow.lowMedium;
390
+ const target = cell === undefined || (cell.kind !== 'warning' && cell.durationMs === null) ? undefined : cellPick(cell);
391
+ for (const hit of hits) {
392
+ if (hit.effect === 'raise' && !raised && target !== undefined && !atLeast(pick.outcome, target.outcome)) {
393
+ pick = target;
394
+ raised = true;
395
+ if (context.hideSignalText !== true) sentences.push(`Raised one step: ${hit.text}.`);
396
+ } else if (context.hideSignalText !== true) sentences.push(`Also: ${hit.text}.`);
397
+ }
398
+ }
399
+
356
400
  let outcome = copyOutcome(pick.outcome);
357
401
  let label = pick.label ?? outcomeLabel(outcome);
358
402
  let areaNote = '';
@@ -361,5 +405,19 @@ export function suggest(
361
405
  label = outcomeLabel(outcome);
362
406
  areaNote = ' (this rule bans from public rooms instead of restricting chat)';
363
407
  }
364
- return { outcome, label, why: `${name} profile: ${reason}${areaNote}.` };
408
+ const why = `${name} profile: ${reason}${areaNote}.${sentences.map((s) => ` ${s}`).join('')}`;
409
+ return hits.length === 0 || context.hideSignalText === true ? { outcome, label, why } : { outcome, label, why, signals: { raised, ids: hits.map((h) => h.id) } };
410
+ }
411
+
412
+ /** The hits `suggest` will use: well-formed ones only (a string id and text, a known effect), at most 20. Never throws. */
413
+ function usableHits(v: unknown): SignalHit[] {
414
+ if (!Array.isArray(v)) return [];
415
+ const out: SignalHit[] = [];
416
+ for (const h of v.slice(0, 20) as unknown[]) {
417
+ if (typeof h !== 'object' || h === null) continue;
418
+ const { id, effect, text } = h as Record<string, unknown>;
419
+ if (typeof id !== 'string' || typeof text !== 'string' || (effect !== 'note' && effect !== 'raise')) continue;
420
+ out.push({ id, effect, text });
421
+ }
422
+ return out;
365
423
  }
@@ -0,0 +1,255 @@
1
+ import { isValidAuditActor } from './audit.js';
2
+ import { randomId } from './crypto.js';
3
+ import type { KitEvent } from './events.js';
4
+ import { hashWho } from './hasher.js';
5
+ import { safeWarn, ThrottledWarn } from './log.js';
6
+ import { DECISION_REASON_MAX } from './decide.js';
7
+ import { evidenceName, NameEvidenceLimiter, profanityView } from './names.js';
8
+ import type { NameCheckResult, NameReason, ResolvedNames } from './names.js';
9
+ import type { NoticeService } from './notices.js';
10
+ import type { CommunityRules } from './rules.js';
11
+ import type { SubjectIndex } from './subjects.js';
12
+ import type { Clock, Hasher, Logger, Matcher, ProfanityFilter, RawWho, Store, SubjectId } from './types.js';
13
+
14
+ // The name check behind `cw.names`: the matcher, an optional profanity pass, optional kept evidence (capped), and the evidence-free
15
+ // `flagged` read for staff paths. A name is never logged and never echoed; the answer carries a reason id and a rule number.
16
+
17
+ export interface NameServiceDeps {
18
+ store: Store;
19
+ clock: Clock;
20
+ logger: Logger | undefined;
21
+ hasher: Hasher;
22
+ /** The slur filter's rule (`autoRestrictRule`): what a refusal cites. */
23
+ rule: number;
24
+ matcher: Matcher | undefined;
25
+ /** The settings in force now (read on every call: a policy change takes effect at once). */
26
+ settings: () => ResolvedNames;
27
+ /** The profanity filter for names, or undefined when there is none. May throw (a package that cannot build one). */
28
+ filter: () => ProfanityFilter | undefined;
29
+ /** The person behind a caller, FOUND and never created. */
30
+ personOf: (who: RawWho) => SubjectId | null;
31
+ /** Required renames are notices of kind `rename_required`. */
32
+ notices: NoticeService;
33
+ /** Who is who: a person the kit holds, and the surviving id of an alias. */
34
+ subjects: SubjectIndex;
35
+ /** The rule a rename may cite must be active here. */
36
+ rules: CommunityRules;
37
+ /** Raise an event after the write has committed. */
38
+ emit: (event: KitEvent) => void;
39
+ }
40
+
41
+ /** What `requireRename` answers. */
42
+ export type RenameResult = { ok: true; noticeId: string } | { ok: false; error: 'off' | 'not_found' | 'pending' | 'invalid' };
43
+
44
+ /** The shape of a rename request, once checked. */
45
+ interface CheckedRename {
46
+ subject: SubjectId;
47
+ rule: number;
48
+ }
49
+
50
+ /**
51
+ * The longest private reason a required rename takes, in characters: the decision's limit, one constant for every private reason. (Defined here,
52
+ * not in `names.ts`: the profile imports that file and the decision module imports the profile, so the other way round is a cycle.)
53
+ */
54
+ export const RENAME_REASON_MAX = DECISION_REASON_MAX;
55
+
56
+ /** The most rename requests `renamesOf` lists. */
57
+ const RENAMES_OF_MAX = 20;
58
+
59
+ const errName = (err: unknown): string => (err instanceof Error ? err.name : typeof err);
60
+
61
+ /** Why a name is refused, and the matcher's term id for a `name_not_allowed`. */
62
+ interface Verdict {
63
+ reason: NameReason;
64
+ termId: string | null;
65
+ }
66
+
67
+ export class NameService {
68
+ private readonly d: NameServiceDeps;
69
+ private readonly limiter = new NameEvidenceLimiter();
70
+ private readonly flaggedWarn: ThrottledWarn;
71
+ private readonly evidenceWarn: ThrottledWarn;
72
+
73
+ constructor(deps: NameServiceDeps) {
74
+ this.d = deps;
75
+ this.flaggedWarn = new ThrottledWarn(deps.logger, deps.clock);
76
+ this.evidenceWarn = new ThrottledWarn(deps.logger, deps.clock);
77
+ }
78
+
79
+ check(text: string, opts?: { who?: RawWho }): NameCheckResult {
80
+ if (typeof text !== 'string') throw new TypeError('names.check: the name must be a string');
81
+ const verdict = this.verdict(text);
82
+ if (verdict === null) return { ok: true };
83
+ this.keep(text, verdict, opts);
84
+ return { ok: false, reason: verdict.reason, rule: this.d.rule };
85
+ }
86
+
87
+ /** The matcher's reading alone: no profanity, no store, no person. False for anything it cannot read. Never throws. */
88
+ flagged(text: string): boolean {
89
+ if (typeof text !== 'string') return false;
90
+ try {
91
+ return this.matched(text) !== null;
92
+ } catch (err) {
93
+ this.flaggedWarn.warn('chatwarden.names_matcher_failed', { error: errName(err) });
94
+ return false;
95
+ }
96
+ }
97
+
98
+ /** The matcher's term id for a name it refuses, or null. Throws what the matcher throws. */
99
+ private matched(text: string): { termId: string | null } | null {
100
+ const m = this.d.matcher;
101
+ if (m === undefined) return null;
102
+ const hit = typeof m.matchName === 'function' ? m.matchName(text) : m.match(text);
103
+ if (hit === null || hit === undefined) return null;
104
+ return { termId: typeof hit.termId === 'string' ? hit.termId : null };
105
+ }
106
+
107
+ private verdict(text: string): Verdict | null {
108
+ try {
109
+ const hit = this.matched(text);
110
+ if (hit !== null) return { reason: 'name_not_allowed', termId: hit.termId };
111
+ } catch (err) {
112
+ safeWarn(this.d.logger, 'chatwarden.names_matcher_failed', { error: errName(err) });
113
+ }
114
+ if (!this.d.settings().profanity) return null;
115
+ try {
116
+ const filter = this.d.filter();
117
+ if (filter === undefined) return null;
118
+ if (filter.apply(text).hit) return { reason: 'name_profane', termId: null };
119
+ const spaced = profanityView(text);
120
+ if (spaced !== text && filter.apply(spaced).hit) return { reason: 'name_profane', termId: null };
121
+ } catch (err) {
122
+ safeWarn(this.d.logger, 'chatwarden.names_filter_failed', { error: errName(err) });
123
+ }
124
+ return null;
125
+ }
126
+
127
+ /** Keep a blocked name as evidence, when the adopter opted in and the hourly caps allow. Fenced: nothing in here reaches the caller. */
128
+ private keep(text: string, verdict: Verdict, opts: { who?: RawWho } | undefined): void {
129
+ try {
130
+ if (!this.d.settings().keepBlocked) return;
131
+ const store = this.d.store;
132
+ if (typeof store.insertBlockedName !== 'function') {
133
+ this.evidenceWarn.warn('chatwarden.names_evidence_unavailable', {});
134
+ return;
135
+ }
136
+ const now = this.d.clock.now();
137
+ const name = evidenceName(text);
138
+ const who = this.whoOf(opts);
139
+ const subject = who === undefined ? null : this.d.personOf(who);
140
+ const key = this.keyOf(subject, who, name);
141
+ if (!this.limiter.allow(key, now)) return;
142
+ store.transaction(() => store.insertBlockedName?.({ id: randomId(), subject, name, termId: verdict.termId, reason: verdict.reason, at: now }));
143
+ this.limiter.record(key, now);
144
+ } catch (err) {
145
+ safeWarn(this.d.logger, 'chatwarden.names_evidence_failed', { error: errName(err) });
146
+ }
147
+ }
148
+
149
+ /** The caller, as far as it is usable: an object. A getter that throws is the caller's fault and is absorbed by `keep`'s fence. */
150
+ private whoOf(opts: { who?: RawWho } | undefined): RawWho | undefined {
151
+ if (typeof opts !== 'object' || opts === null) return undefined;
152
+ const who: unknown = opts.who;
153
+ return typeof who === 'object' && who !== null ? (who as RawWho) : undefined;
154
+ }
155
+
156
+ /** What the hourly cap counts a person by: the person found, else the caller's own identifiers, else the name. Never the raw values. */
157
+ private keyOf(subject: SubjectId | null, who: RawWho | undefined, name: string): string {
158
+ if (subject !== null) return `s:${subject}`;
159
+ if (who !== undefined) {
160
+ const ids = hashWho(this.d.hasher, who);
161
+ if (ids.clientKey !== null || ids.accountId !== null || ids.ipHash !== null) {
162
+ return `w:${ids.clientKey ?? ''}|${typeof ids.accountId === 'string' ? this.d.hasher.clientKey(`account:${ids.accountId}`) : ''}|${ids.ipHash ?? ''}`;
163
+ }
164
+ }
165
+ return `n:${this.d.hasher.clientKey(`name:${name.toLowerCase()}`)}`;
166
+ }
167
+
168
+ /**
169
+ * Ask a player to choose a new name: one `rename_required` notice (no name, no excerpt, no reason) and, after the write, the player's
170
+ * client is told and `rename.required` goes out. Answers, in this order: `off` (`names.renames` is false, or the store cannot release a
171
+ * rename), `invalid` (a malformed input, a reason that is not 1 to 500 characters once trimmed, a rule that is not an active integer rule),
172
+ * `not_found` (a person the kit does not hold), `pending` (an unreleased request exists, seen or not). A store failure is logged by class
173
+ * and thrown, with nothing written. The reason and the actor are validated here and kept by the staff layer's audit row, not by the notice.
174
+ */
175
+ requireRename(input: { subject: SubjectId; actor: string; reason: string; rule?: number }): RenameResult {
176
+ const d = this.d;
177
+ if (!this.renamesEnabled()) return { ok: false, error: 'off' };
178
+ const checked = this.checkRename(input);
179
+ if (checked === null) return { ok: false, error: 'invalid' };
180
+ let noticeId: string;
181
+ let person: SubjectId;
182
+ let at: number;
183
+ try {
184
+ person = d.subjects.canonical(checked.subject);
185
+ if (!d.subjects.knows(person)) return { ok: false, error: 'not_found' };
186
+ if (d.notices.renamePending(person)) return { ok: false, error: 'pending' };
187
+ at = d.clock.now();
188
+ noticeId = d.notices.createMessage(person, 'rename_required', { rule: checked.rule, notify: false });
189
+ } catch (err) {
190
+ safeWarn(d.logger, 'chatwarden.rename_failed', { error: errName(err) });
191
+ throw err;
192
+ }
193
+ // After the write: the client is told (fenced inside `announce`), then the event (a listener that throws is not the caller's problem).
194
+ d.notices.announce(person);
195
+ try {
196
+ d.emit({ type: 'rename.required', at, target: person, rule: checked.rule });
197
+ } catch (err) {
198
+ safeWarn(d.logger, 'chatwarden.event_failed', { error: errName(err) });
199
+ }
200
+ return { ok: true, noticeId };
201
+ }
202
+
203
+ /** Can a moderator ask for a rename now: the setting is on and the store can release one (the test `requireRename` applies first). */
204
+ renamesEnabled(): boolean {
205
+ return this.d.settings().renames && this.d.notices.canWithdrawOne();
206
+ }
207
+
208
+ /** A person's rename requests, newest first (at most {@link RENAMES_OF_MAX}): when, and whether one still waits. No reason, actor or rule. Staff only. */
209
+ renamesOf(subject: SubjectId): Array<{ at: number; pending: boolean }> {
210
+ if (typeof subject !== 'string' || subject === '') return [];
211
+ try {
212
+ return this.d.notices
213
+ .renameRows(subject)
214
+ .slice(0, RENAMES_OF_MAX)
215
+ .map((r) => ({ at: r.createdAt, pending: r.withdrawnAt === null }));
216
+ } catch (err) {
217
+ safeWarn(this.d.logger, 'chatwarden.rename_failed', { error: errName(err) });
218
+ return [];
219
+ }
220
+ }
221
+
222
+ /** True while the person has a required rename they have not been released from. False for anyone the kit cannot find (never creates one). */
223
+ pendingRename(who: RawWho): boolean {
224
+ return this.releaseOrRead(who, (subject) => this.d.notices.renamePending(subject));
225
+ }
226
+
227
+ /** The game says the player has a new name: withdraws their pending rename notices. True when it withdrew one. */
228
+ renamed(who: RawWho): boolean {
229
+ return this.releaseOrRead(who, (subject) => this.d.notices.withdrawRenames(subject) > 0);
230
+ }
231
+
232
+ private releaseOrRead(who: RawWho, read: (subject: SubjectId) => boolean): boolean {
233
+ if (typeof who !== 'object' || who === null) return false;
234
+ try {
235
+ const subject = this.d.personOf(who);
236
+ return subject === null ? false : read(subject);
237
+ } catch (err) {
238
+ safeWarn(this.d.logger, 'chatwarden.rename_failed', { error: errName(err) });
239
+ return false;
240
+ }
241
+ }
242
+
243
+ private checkRename(input: unknown): CheckedRename | null {
244
+ if (typeof input !== 'object' || input === null) return null;
245
+ const { subject, actor, reason, rule } = input as Record<string, unknown>;
246
+ if (typeof subject !== 'string' || subject === '') return null;
247
+ if (!isValidAuditActor(actor)) return null;
248
+ if (typeof reason !== 'string') return null;
249
+ const why = reason.trim();
250
+ if (why === '' || why.length > RENAME_REASON_MAX) return null;
251
+ if (rule === undefined) return { subject, rule: this.d.rule };
252
+ if (typeof rule !== 'number' || !Number.isSafeInteger(rule) || !this.d.rules.isCitable(rule)) return null;
253
+ return { subject, rule };
254
+ }
255
+ }