@chatwarden/core 0.1.0 → 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. package/README.md +202 -6
  2. package/dist/src/audit.d.ts +27 -5
  3. package/dist/src/audit.d.ts.map +1 -1
  4. package/dist/src/audit.js +59 -8
  5. package/dist/src/audit.js.map +1 -1
  6. package/dist/src/chat.d.ts +48 -0
  7. package/dist/src/chat.d.ts.map +1 -1
  8. package/dist/src/chat.js +94 -10
  9. package/dist/src/chat.js.map +1 -1
  10. package/dist/src/chatwarden.d.ts +209 -12
  11. package/dist/src/chatwarden.d.ts.map +1 -1
  12. package/dist/src/chatwarden.js +77 -11
  13. package/dist/src/chatwarden.js.map +1 -1
  14. package/dist/src/crypto.d.ts +22 -0
  15. package/dist/src/crypto.d.ts.map +1 -0
  16. package/dist/src/crypto.js +193 -0
  17. package/dist/src/crypto.js.map +1 -0
  18. package/dist/src/decide.d.ts.map +1 -1
  19. package/dist/src/decide.js +2 -4
  20. package/dist/src/decide.js.map +1 -1
  21. package/dist/src/documents.d.ts +12 -2
  22. package/dist/src/documents.d.ts.map +1 -1
  23. package/dist/src/documents.js +56 -34
  24. package/dist/src/documents.js.map +1 -1
  25. package/dist/src/events.d.ts +3 -0
  26. package/dist/src/events.d.ts.map +1 -1
  27. package/dist/src/events.js.map +1 -1
  28. package/dist/src/hasher.js +2 -2
  29. package/dist/src/hasher.js.map +1 -1
  30. package/dist/src/index.d.ts +21 -12
  31. package/dist/src/index.d.ts.map +1 -1
  32. package/dist/src/index.js +11 -6
  33. package/dist/src/index.js.map +1 -1
  34. package/dist/src/ladder.d.ts +2 -0
  35. package/dist/src/ladder.d.ts.map +1 -1
  36. package/dist/src/ladder.js +1 -1
  37. package/dist/src/ladder.js.map +1 -1
  38. package/dist/src/log.d.ts +16 -0
  39. package/dist/src/log.d.ts.map +1 -1
  40. package/dist/src/log.js +34 -0
  41. package/dist/src/log.js.map +1 -1
  42. package/dist/src/notices.js +2 -2
  43. package/dist/src/notices.js.map +1 -1
  44. package/dist/src/policy.d.ts +129 -0
  45. package/dist/src/policy.d.ts.map +1 -0
  46. package/dist/src/policy.js +242 -0
  47. package/dist/src/policy.js.map +1 -0
  48. package/dist/src/profile.d.ts +120 -7
  49. package/dist/src/profile.d.ts.map +1 -1
  50. package/dist/src/profile.js +295 -7
  51. package/dist/src/profile.js.map +1 -1
  52. package/dist/src/reporting.d.ts +127 -0
  53. package/dist/src/reporting.d.ts.map +1 -0
  54. package/dist/src/reporting.js +172 -0
  55. package/dist/src/reporting.js.map +1 -0
  56. package/dist/src/reports.d.ts +80 -4
  57. package/dist/src/reports.d.ts.map +1 -1
  58. package/dist/src/reports.js +122 -8
  59. package/dist/src/reports.js.map +1 -1
  60. package/dist/src/sanctions.js +3 -3
  61. package/dist/src/sanctions.js.map +1 -1
  62. package/dist/src/staffReports.d.ts +17 -5
  63. package/dist/src/staffReports.d.ts.map +1 -1
  64. package/dist/src/staffReports.js +22 -5
  65. package/dist/src/staffReports.js.map +1 -1
  66. package/dist/src/staffViews.d.ts +138 -0
  67. package/dist/src/staffViews.d.ts.map +1 -0
  68. package/dist/src/staffViews.js +205 -0
  69. package/dist/src/staffViews.js.map +1 -0
  70. package/dist/src/strikes.js +2 -2
  71. package/dist/src/strikes.js.map +1 -1
  72. package/dist/src/subjects.js +2 -2
  73. package/dist/src/subjects.js.map +1 -1
  74. package/dist/src/team.d.ts +149 -0
  75. package/dist/src/team.d.ts.map +1 -0
  76. package/dist/src/team.js +385 -0
  77. package/dist/src/team.js.map +1 -0
  78. package/dist/src/types.d.ts +245 -4
  79. package/dist/src/types.d.ts.map +1 -1
  80. package/dist/src/types.js +5 -0
  81. package/dist/src/types.js.map +1 -1
  82. package/package.json +4 -1
  83. package/src/audit.ts +73 -9
  84. package/src/chat.ts +109 -9
  85. package/src/chatwarden.ts +279 -22
  86. package/src/crypto.ts +206 -0
  87. package/src/decide.ts +2 -4
  88. package/src/documents.ts +70 -43
  89. package/src/events.ts +10 -1
  90. package/src/hasher.ts +2 -2
  91. package/src/index.ts +110 -5
  92. package/src/ladder.ts +1 -1
  93. package/src/log.ts +37 -0
  94. package/src/notices.ts +2 -2
  95. package/src/policy.ts +288 -0
  96. package/src/profile.ts +369 -14
  97. package/src/reporting.ts +251 -0
  98. package/src/reports.ts +165 -12
  99. package/src/sanctions.ts +3 -3
  100. package/src/staffReports.ts +33 -7
  101. package/src/staffViews.ts +325 -0
  102. package/src/strikes.ts +2 -2
  103. package/src/subjects.ts +2 -2
  104. package/src/team.ts +422 -0
  105. package/src/types.ts +257 -4
package/src/index.ts CHANGED
@@ -1,4 +1,4 @@
1
- export const VERSION = '0.1.0';
1
+ export const VERSION = '0.1.2';
2
2
 
3
3
  export type {
4
4
  Clock,
@@ -21,8 +21,16 @@ export type {
21
21
  ReportListQuery,
22
22
  ReportRecord,
23
23
  SanctionKind,
24
+ SanctionListQuery,
24
25
  SanctionRow,
25
26
  SanctionTargetType,
27
+ ReporterDecision,
28
+ ReporterTally,
29
+ ClaimAttempt,
30
+ ClaimMode,
31
+ ClaimRow,
32
+ OpenReportQuery,
33
+ ReasonRow,
26
34
  ConductLevel,
27
35
  Source,
28
36
  Store,
@@ -33,7 +41,20 @@ export type {
33
41
  StrikeRow,
34
42
  SubjectRecord,
35
43
  } from './types.js';
36
- export { CONDUCT_LEVELS } from './types.js';
44
+ export { CLAIM_TTL_MS, CONDUCT_LEVELS } from './types.js';
45
+ export {
46
+ CaseDesk,
47
+ CLAIM_BUSY_TRIES,
48
+ VIEWING_PER_ACTOR_MAX,
49
+ REASON_LABEL_MAX,
50
+ REASON_TEXT_MAX,
51
+ REASONS_MAX,
52
+ ReasonBook,
53
+ ReasonError,
54
+ ViewingPresence,
55
+ VIEWING_TTL_MS,
56
+ } from './team.js';
57
+ export type { CaseClaim, ClaimOutcome, NextCase } from './team.js';
37
58
  export { hashWho, makeHasher } from './hasher.js';
38
59
  export { maskSpans, type MaskSpan } from './mask.js';
39
60
  export { SubjectIndex } from './subjects.js';
@@ -70,7 +91,7 @@ export type { StrikeDecision } from './strikes.js';
70
91
  export { slidingWindow } from './rateLimit.js';
71
92
  export type { SlidingWindow } from './rateLimit.js';
72
93
  export { ChatService } from './chat.js';
73
- export type { ChatResult, ChatServiceDeps, RefuseReason } from './chat.js';
94
+ export type { ChatResult, ChatServiceDeps, RefuseReason, RestrictedAnswer } from './chat.js';
74
95
  export {
75
96
  REPORT_CATEGORIES,
76
97
  REPORT_NOTE_MAX,
@@ -79,7 +100,44 @@ export {
79
100
  SUSPEND_AFTER,
80
101
  SUSPEND_WINDOW_MS,
81
102
  } from './reports.js';
82
- export type { ReportCounts, ReportInput, ReportRefusal, ReportResult, ReportServiceDeps } from './reports.js';
103
+ export { REPORT_DETAIL_WINDOW_MS } from './reports.js';
104
+ export type {
105
+ ReportCounts,
106
+ ReportDetailInput,
107
+ ReportDetailRefusal,
108
+ ReportDetailResult,
109
+ ReportInput,
110
+ ReportRefusal,
111
+ ReportResult,
112
+ ReportServiceDeps,
113
+ } from './reports.js';
114
+ export {
115
+ canonicalReasonId,
116
+ DEFAULT_REPORT_FLOW,
117
+ DEFAULT_REPORT_REASONS,
118
+ DEFAULT_REPORT_THANKS,
119
+ defaultReporting,
120
+ findReason,
121
+ isReasonId,
122
+ legacyCategoryOf,
123
+ LEGACY_REASON_ALIASES,
124
+ MAX_REASON_RULES,
125
+ MAX_REPORT_REASONS,
126
+ OTHER_REASON_ID,
127
+ playerReporting,
128
+ reasonLabel,
129
+ reasonOfCategory,
130
+ REPORT_FLOWS,
131
+ suggestedRule,
132
+ } from './reporting.js';
133
+ export type {
134
+ PlayerReporting,
135
+ ReportFlow,
136
+ ReportingSettings,
137
+ ReportReason,
138
+ ReportReasonInput,
139
+ ResolvedReporting,
140
+ } from './reporting.js';
83
141
  export {
84
142
  decodeReportCursor,
85
143
  encodeReportCursor,
@@ -90,9 +148,29 @@ export {
90
148
  staffReport,
91
149
  } from './staffReports.js';
92
150
  export type { ReportPage, ReportQuery, StaffReport } from './staffReports.js';
151
+ export {
152
+ BLOCKED_DAYS,
153
+ BLOCKED_MAX,
154
+ PERSON_SANCTIONS_MAX,
155
+ SANCTION_PAGE_DEFAULT,
156
+ SANCTION_PAGE_MAX,
157
+ SanctionQueryError,
158
+ isSanctionActive,
159
+ sanctionGroupView,
160
+ } from './staffViews.js';
161
+ export type {
162
+ BlockedDays,
163
+ BlockedItem,
164
+ PersonSanctionView,
165
+ ReporterRecord,
166
+ SanctionGroupView,
167
+ SanctionListInput,
168
+ SanctionPage,
169
+ } from './staffViews.js';
93
170
  export {
94
171
  AUDIT_ACTIONS,
95
172
  AUDIT_PAGE_MAX,
173
+ AUDIT_REASON_MAX,
96
174
  AUDIT_TARGET_TYPES,
97
175
  AuditQueryError,
98
176
  isValidAuditActor,
@@ -101,6 +179,7 @@ export {
101
179
  export type {
102
180
  AuditAction,
103
181
  AuditItem,
182
+ AuditDetail,
104
183
  AuditListQuery,
105
184
  AuditPage,
106
185
  AuditQuery,
@@ -146,12 +225,13 @@ export {
146
225
  starterRules,
147
226
  } from './rules.js';
148
227
  export type { CommunityRule, RuleRef } from './rules.js';
149
- export { agentBrief, bindDocuments, codeOfConduct, moderatorGuide, policyJson } from './documents.js';
228
+ export { GUIDE_SECTIONS, agentBrief, bindDocuments, codeOfConduct, moderatorGuide, policyJson } from './documents.js';
150
229
  export type {
151
230
  CodeOfConductOptions,
152
231
  DocumentFormat,
153
232
  DocumentPolicy,
154
233
  Documents,
234
+ GuideSection,
155
235
  ModeratorGuideOptions,
156
236
  PolicyJson,
157
237
  } from './documents.js';
@@ -159,6 +239,7 @@ export { LIMITS_DEFAULTS, resolveLimits } from './limits.js';
159
239
  export type { Limits, LimitsInput } from './limits.js';
160
240
  export {
161
241
  actionStep,
242
+ DEFAULT_AREA_RULES,
162
243
  DEFAULT_SEVERE_RULES,
163
244
  HISTORY_LOOKBACK_MS,
164
245
  historyOf,
@@ -179,23 +260,47 @@ export type {
179
260
  RevokeDeps,
180
261
  } from './decide.js';
181
262
  export {
263
+ applyPolicyLayer,
264
+ changedSections,
265
+ DEFAULT_DURATIONS,
182
266
  defineProfile,
267
+ layerSections,
183
268
  MAX_DURATION_MS,
269
+ MAX_DURATIONS,
270
+ MAX_GUIDELINE_OUTCOME,
271
+ MAX_RULE_LIST,
184
272
  MAX_WINDOW_DAYS,
273
+ POLICY_SECTIONS,
185
274
  PRESETS,
186
275
  ProfileError,
187
276
  resolveProfile,
188
277
  validateProfile,
189
278
  } from './profile.js';
279
+ export { POLICY_REFRESH_MS, PREVIEW_SAMPLES } from './policy.js';
280
+ export type {
281
+ PolicyPreview,
282
+ PolicySaveContext,
283
+ PolicySaveResult,
284
+ PolicyState,
285
+ PreviewOutcome,
286
+ PreviewSample,
287
+ } from './policy.js';
190
288
  export type {
191
289
  DeepPartial,
192
290
  GuidelineCover,
193
291
  GuidelineTier,
194
292
  LevelDescription,
195
293
  ModerationProfile,
294
+ ModerationProfileBase,
196
295
  Outcome,
296
+ PolicyCell,
297
+ PolicyLadderRow,
298
+ PolicyLayer,
299
+ PolicySection,
197
300
  PresetName,
198
301
  ProfanityConfig,
302
+ ProfileInput,
199
303
  ProfileOverrides,
304
+ ResolvedProfile,
200
305
  RulesFlavour,
201
306
  } from './profile.js';
package/src/ladder.ts CHANGED
@@ -138,7 +138,7 @@ export const LADDER_TABLE: readonly LadderRow[] = Object.freeze([
138
138
  ] as const satisfies readonly LadderRow[]);
139
139
 
140
140
  /** The rules that swap a chat restriction for a ban from public rooms, when a profile does not say. */
141
- const DEFAULT_AREA_RULES: readonly number[] = Object.freeze([5, 6]);
141
+ export const DEFAULT_AREA_RULES: readonly number[] = Object.freeze([5, 6]);
142
142
  /** The rules that always read the severe (high) column, when a profile does not say. */
143
143
  export const DEFAULT_SEVERE_RULES: readonly number[] = Object.freeze([1]);
144
144
 
package/src/log.ts CHANGED
@@ -39,3 +39,40 @@ export function errorClass(err: unknown): string {
39
39
  return 'unknown';
40
40
  }
41
41
  }
42
+
43
+ /**
44
+ * A warning for a path that can fail on every call at high frequency (a typing indicator during a store outage): the
45
+ * first failure is logged, then at most one more per `intervalMs`, which carries `suppressed`, the number of failures
46
+ * held back since the last line. The clock is the kit's, so a test or a replay controls it.
47
+ */
48
+ export class ThrottledWarn {
49
+ private last: number | null = null;
50
+ private held = 0;
51
+
52
+ private readonly logger: Logger | undefined;
53
+ private readonly clock: { now(): number };
54
+ private readonly intervalMs: number;
55
+
56
+ constructor(logger: Logger | undefined, clock: { now(): number }, intervalMs = 60_000) {
57
+ this.logger = logger;
58
+ this.clock = clock;
59
+ this.intervalMs = intervalMs;
60
+ }
61
+
62
+ warn(event: string, detail: Detail): void {
63
+ let now: number;
64
+ try {
65
+ now = this.clock.now();
66
+ } catch {
67
+ now = 0;
68
+ }
69
+ if (this.last !== null && now - this.last < this.intervalMs && now >= this.last) {
70
+ this.held++;
71
+ return;
72
+ }
73
+ const out: Detail = this.held > 0 ? { ...detail, suppressed: this.held } : detail;
74
+ this.last = now;
75
+ this.held = 0;
76
+ safeWarn(this.logger, event, out);
77
+ }
78
+ }
package/src/notices.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { randomBytes } from 'node:crypto';
1
+ import { randomId } from './crypto.js';
2
2
  import { safeWarn } from './log.js';
3
3
  import { maskSpans } from './mask.js';
4
4
  import { parseRuleRef } from './rules.js';
@@ -163,7 +163,7 @@ export interface NoticeServiceDeps {
163
163
  notify?: (subject: SubjectId, event: { type: 'notice_pending'; count: number }) => unknown;
164
164
  }
165
165
 
166
- const newId = (): string => randomBytes(16).toString('base64url');
166
+ const newId = (): string => randomId(16);
167
167
 
168
168
  const errName = (err: unknown): string => {
169
169
  try {
package/src/policy.ts ADDED
@@ -0,0 +1,288 @@
1
+ import { isValidAuditActor, AUDIT_REASON_MAX } from './audit.js';
2
+ import { suggest } from './ladder.js';
3
+ import type { ActionRecord } from './ladder.js';
4
+ import { applyPolicyLayer, changedSections, frozenCopy, layerSections, POLICY_SECTIONS, ProfileError } from './profile.js';
5
+ import type { PolicyLayer, PolicySection, ResolvedProfile } from './profile.js';
6
+ import { playerReporting } from './reporting.js';
7
+ import type { PlayerReporting } from './reporting.js';
8
+ import type { RuleRef } from './rules.js';
9
+ import { errorClass, safeWarn } from './log.js';
10
+ import { retryBusy } from './team.js';
11
+ import { CONDUCT_LEVELS } from './types.js';
12
+ import type { Clock, ConductLevel, Logger, Store } from './types.js';
13
+
14
+ /**
15
+ * The editable moderation profile at runtime. The profile given in code (a preset plus `overrides`) is the BASE. A moderator's
16
+ * edits are stored in the adopter's own store as a versioned {@link PolicyLayer}; the EFFECTIVE profile is the base with that
17
+ * layer merged on top, validated. Every consumer in the kit reads {@link PolicyService.profileNow} at call time, so a save is
18
+ * seen by the very next suggestion, document or check, and a change another process saved is seen within
19
+ * {@link POLICY_REFRESH_MS}. A stored layer the kit cannot use is ignored (the base stays in force) and reported, never thrown.
20
+ */
21
+
22
+ /** How often a read may look at the store for a newer version: 10 seconds. */
23
+ export const POLICY_REFRESH_MS = 10_000;
24
+
25
+ /** What {@link PolicyService.get} answers. */
26
+ export interface PolicyState {
27
+ /** The profile in force: base, then the stored layer. Deep-frozen. */
28
+ effective: ResolvedProfile;
29
+ /** The profile from code (preset and overrides), without the stored layer. Deep-frozen. */
30
+ base: ResolvedProfile;
31
+ /** The stored layer as last read (`{}` when none), deep-frozen. */
32
+ layer: PolicyLayer;
33
+ /** The stored layer's version; 0 when nothing was ever saved. Pass it back to `save`. */
34
+ version: number;
35
+ /** True when the store has the policy methods, so `save` and `reset` can work. */
36
+ canSave: boolean;
37
+ /**
38
+ * Present when the stored layer could not be used: it is ignored and `effective` is `base`. `path` names the field (`layer`
39
+ * itself for one that is not an object). `kind` is `'unreadable'` when the stored text could not be read at all (corrupted, not
40
+ * JSON, not an object): the owner's edits are gone until they save again; `'invalid'` when it was read but a setting is not
41
+ * valid (a newer kit's field, a hand edit). Either way a save or a full `reset()` repairs it.
42
+ */
43
+ layerError?: { path: string; kind: 'unreadable' | 'invalid' };
44
+ }
45
+
46
+ /** What {@link PolicyService.save} and {@link PolicyService.reset} answer. */
47
+ export type PolicySaveResult =
48
+ | { ok: true; version: number; /** The editable sections whose stored value changed. */ changed: PolicySection[] }
49
+ | { ok: false; error: 'conflict' | 'unsupported' }
50
+ | { ok: false; error: 'invalid'; path: string };
51
+
52
+ /** Who saved, and why. `actor` and `reason` are checked here; the routes record them in the audit trail. */
53
+ export interface PolicySaveContext {
54
+ /** The stored layer's version the editor started from (`get().version`). */
55
+ version: number;
56
+ actor: string;
57
+ reason: string;
58
+ }
59
+
60
+ /** The four fixed sample records a preview is computed for. */
61
+ export const PREVIEW_SAMPLES = ['clean', 'oneWarning', 'chat24h', 'ban7d'] as const;
62
+ export type PreviewSample = (typeof PREVIEW_SAMPLES)[number];
63
+
64
+ /** One suggested outcome in a preview. `durationMs` is null for permanent and for an outcome with no length. */
65
+ export interface PreviewOutcome {
66
+ label: string;
67
+ kind: 'none' | 'note' | 'warning' | 'chat' | 'area' | 'ban';
68
+ durationMs: number | null;
69
+ }
70
+
71
+ /** What {@link PolicyService.preview} answers: for each sample and each conduct level, what would be suggested. */
72
+ export type PolicyPreview =
73
+ | { ok: true; samples: Record<PreviewSample, Record<ConductLevel, PreviewOutcome>>; /** What players would read of the candidate's reporting settings (the enabled reasons, the flow and the thank-you). */ reporting: PlayerReporting }
74
+ | { ok: false; error: 'invalid'; path: string };
75
+
76
+ const HOUR_MS = 3_600_000;
77
+ const DAY_MS = 24 * HOUR_MS;
78
+
79
+ /** The records behind the samples, as of `now`: a clean record, one warning, a 24 hour chat restriction, a 7 day ban. */
80
+ function sampleRecords(now: number): Record<PreviewSample, ActionRecord[]> {
81
+ const one = (kind: ActionRecord['kind'], durationMs: number | null): ActionRecord[] => [
82
+ { kind, durationMs, startsAt: now - HOUR_MS, revoked: false, automated: false, roomId: null },
83
+ ];
84
+ return { clean: [], oneWarning: one('warning', null), chat24h: one('chat', DAY_MS), ban7d: one('ban', 7 * DAY_MS) };
85
+ }
86
+
87
+ const isRuleRef = (v: unknown): v is RuleRef => v === 'uncovered' || (typeof v === 'number' && Number.isSafeInteger(v) && v >= 1);
88
+
89
+ export class PolicyService {
90
+ private readonly store: Store;
91
+ private readonly clock: Clock;
92
+ private readonly logger: Logger | undefined;
93
+ private readonly base: ResolvedProfile;
94
+ private state: { effective: ResolvedProfile; layer: PolicyLayer; version: number; layerError?: PolicyState['layerError'] };
95
+ /** When the store was last looked at (epoch ms), or null before the first read. */
96
+ private lastCheck: number | null = null;
97
+
98
+ constructor(deps: { store: Store; clock: Clock; logger: Logger | undefined; base: ResolvedProfile }) {
99
+ this.store = deps.store;
100
+ this.clock = deps.clock;
101
+ this.logger = deps.logger;
102
+ this.base = deps.base;
103
+ this.state = { effective: applyPolicyLayer(deps.base, {}), layer: frozenCopy({}), version: 0 };
104
+ }
105
+
106
+ private get supported(): boolean {
107
+ return typeof this.store.loadPolicyLayer === 'function' && typeof this.store.savePolicyLayer === 'function';
108
+ }
109
+
110
+ /** Read the stored layer once, at creation. A store failure here is the caller's (like every other load). */
111
+ load(): void {
112
+ if (!this.supported) return;
113
+ this.lastCheck = this.clock.now();
114
+ this.adopt(this.store.loadPolicyLayer?.() ?? null);
115
+ }
116
+
117
+ /** Make `stored` the layer in force: the effective profile is rebuilt, or the base kept when the layer cannot be used. */
118
+ private adopt(stored: { layer: PolicyLayer; version: number } | null): void {
119
+ const version = stored?.version ?? 0;
120
+ // A row the store could not read as a layer arrives as null (or any non-object): it is a layerError like any unusable layer.
121
+ const raw: unknown = stored === null ? {} : stored.layer;
122
+ const layer = frozenCopy(raw as PolicyLayer);
123
+ try {
124
+ this.state = { effective: applyPolicyLayer(this.base, layer), layer, version };
125
+ } catch (err) {
126
+ if (!(err instanceof ProfileError)) throw err;
127
+ // What `get()` shows is always an object: an unreadable layer reads as empty, with the error beside it.
128
+ const shown = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? layer : frozenCopy({});
129
+ const kind = typeof raw === 'object' && raw !== null && !Array.isArray(raw) ? 'invalid' : 'unreadable';
130
+ this.state = { effective: this.base, layer: shown, version, layerError: { path: err.path, kind } };
131
+ // Once per version: `adopt` runs only when the stored version changed (or at start-up), never on a plain re-read.
132
+ safeWarn(this.logger, 'chatwarden.policy_layer_invalid', { version, path: err.path });
133
+ }
134
+ }
135
+
136
+ /** Look at the store now and adopt a strictly newer version (an older one, say a restored backup, never regresses what is in force). A store failure throws. */
137
+ private reload(): void {
138
+ const stored = this.store.loadPolicyLayer?.() ?? null;
139
+ if ((stored?.version ?? 0) > this.state.version) this.adopt(stored);
140
+ }
141
+
142
+ /** The cheap check every read does: at most one store look per {@link POLICY_REFRESH_MS}; a failure keeps what is in force. */
143
+ private maybeRefresh(): void {
144
+ if (!this.supported) return;
145
+ let now: number;
146
+ try {
147
+ now = this.clock.now();
148
+ } catch {
149
+ return;
150
+ }
151
+ // A clock that went backwards is not "recent": look again.
152
+ if (this.lastCheck !== null && now >= this.lastCheck && now - this.lastCheck < POLICY_REFRESH_MS) return;
153
+ this.lastCheck = now;
154
+ try {
155
+ this.reload();
156
+ } catch (err) {
157
+ safeWarn(this.logger, 'chatwarden.policy_refresh_failed', { error: errorClass(err) });
158
+ }
159
+ }
160
+
161
+ /** The profile in force right now. Every consumer calls this, at call time, and never keeps the result. */
162
+ profileNow(): ResolvedProfile {
163
+ this.maybeRefresh();
164
+ return this.state.effective;
165
+ }
166
+
167
+ get(): PolicyState {
168
+ this.maybeRefresh();
169
+ const { effective, layer, version, layerError } = this.state;
170
+ return { effective, base: this.base, layer, version, canSave: this.supported, ...(layerError === undefined ? {} : { layerError: { ...layerError } }) };
171
+ }
172
+
173
+ /** Look at the store now, whatever the interval. A store failure throws. */
174
+ refresh(): void {
175
+ if (!this.supported) return;
176
+ this.lastCheck = this.clock.now();
177
+ this.reload();
178
+ }
179
+
180
+ private persist(layer: PolicyLayer, expected: number): PolicySaveResult {
181
+ // What this save changes is judged against the layer at `expected`: ours when we are current, else read it.
182
+ const before = this.state.version === expected ? this.state.layer : (this.store.loadPolicyLayer?.()?.layer ?? {});
183
+ // One conditional write; when another process holds the database lock past the busy timeout it is tried again (as a claim is).
184
+ const next = retryBusy(() => this.store.savePolicyLayer?.(layer, expected) ?? null);
185
+ if (next === null) {
186
+ try {
187
+ this.refresh();
188
+ } catch (err) {
189
+ safeWarn(this.logger, 'chatwarden.policy_refresh_failed', { error: errorClass(err) });
190
+ }
191
+ return { ok: false, error: 'conflict' };
192
+ }
193
+ const changed = changedSections(before, layer);
194
+ this.lastCheck = this.clock.now();
195
+ this.adopt({ layer, version: next });
196
+ return { ok: true, version: next, changed };
197
+ }
198
+
199
+ /**
200
+ * Replace the stored layer. `layer` is the WHOLE layer wanted: a section left out goes back to the base. Checked in this
201
+ * order: the store must support it (`unsupported`), `version`, `actor` and `reason` (`invalid`, path `version`, `actor` or
202
+ * `reason`), then the layer itself (`invalid`, with a `layer...` path; a setting outside the editable sections, such as
203
+ * `profanity`, is refused). A `version` that is no longer the stored one is `conflict`, and nothing is written. On success
204
+ * the effective profile changes at once, in this process.
205
+ */
206
+ save(layer: PolicyLayer, ctx: PolicySaveContext): PolicySaveResult {
207
+ if (!this.supported) return { ok: false, error: 'unsupported' };
208
+ if (typeof ctx !== 'object' || ctx === null) return { ok: false, error: 'invalid', path: 'version' };
209
+ if (!Number.isSafeInteger(ctx.version) || ctx.version < 0) return { ok: false, error: 'invalid', path: 'version' };
210
+ if (!isValidAuditActor(ctx.actor)) return { ok: false, error: 'invalid', path: 'actor' };
211
+ if (typeof ctx.reason !== 'string' || ctx.reason.trim() === '' || ctx.reason.trim().length > AUDIT_REASON_MAX) {
212
+ return { ok: false, error: 'invalid', path: 'reason' };
213
+ }
214
+ try {
215
+ applyPolicyLayer(this.base, layer);
216
+ } catch (err) {
217
+ if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
218
+ throw err;
219
+ }
220
+ // Stored as plain JSON: exactly the sections given, nothing that is not data.
221
+ const clean = JSON.parse(JSON.stringify(layer)) as PolicyLayer;
222
+ return this.persist(clean, ctx.version);
223
+ }
224
+
225
+ /**
226
+ * Put one editable section (or, with no section, every section) back to the base, by storing the layer without it. It starts
227
+ * from the latest stored layer, so a reset never undoes another process's unrelated edit. With `version` it must still be
228
+ * the stored one (`conflict` otherwise). Nothing to reset is a no-op that writes nothing (`changed: []`).
229
+ */
230
+ reset(section?: PolicySection, o: { version?: number } = {}): PolicySaveResult {
231
+ if (!this.supported) return { ok: false, error: 'unsupported' };
232
+ if (section !== undefined && !(POLICY_SECTIONS as readonly string[]).includes(section)) return { ok: false, error: 'invalid', path: 'section' };
233
+ if (o.version !== undefined && (!Number.isSafeInteger(o.version) || o.version < 0)) return { ok: false, error: 'invalid', path: 'version' };
234
+ this.refresh();
235
+ if (o.version !== undefined && o.version !== this.state.version) return { ok: false, error: 'conflict' };
236
+ const { layer, version, layerError } = this.state;
237
+ let next: PolicyLayer = {};
238
+ if (section !== undefined) {
239
+ next = { ...layer };
240
+ delete next[section];
241
+ if (layerError !== undefined) {
242
+ // A layer we cannot use may need more than this section gone: it must still be valid, or it is the full reset's job.
243
+ try {
244
+ applyPolicyLayer(this.base, next);
245
+ } catch (err) {
246
+ if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
247
+ throw err;
248
+ }
249
+ }
250
+ }
251
+ const touches = section === undefined ? layerSections(layer).length > 0 : Object.hasOwn(layer, section);
252
+ if (!touches && layerError === undefined) return { ok: true, version, changed: [] };
253
+ return this.persist(JSON.parse(JSON.stringify(next)) as PolicyLayer, version);
254
+ }
255
+
256
+ /**
257
+ * What would be suggested under the candidate `layer` (the whole layer, applied over the base, exactly as a save would
258
+ * store it), for four fixed sample records and each conduct level, without saving anything or reading the store. `rule`
259
+ * (default `'uncovered'`) is the Community Rule the sample incident cites: pass a rule from `areaRules` or `severeRules` to
260
+ * see those rules take effect.
261
+ */
262
+ preview(layer: PolicyLayer, rule: RuleRef = 'uncovered'): PolicyPreview {
263
+ if (!isRuleRef(rule)) return { ok: false, error: 'invalid', path: 'rule' };
264
+ let candidate: ResolvedProfile;
265
+ try {
266
+ candidate = applyPolicyLayer(this.base, layer);
267
+ } catch (err) {
268
+ if (err instanceof ProfileError) return { ok: false, error: 'invalid', path: err.path };
269
+ throw err;
270
+ }
271
+ const now = this.clock.now();
272
+ const records = sampleRecords(now);
273
+ const samples = {} as Record<PreviewSample, Record<ConductLevel, PreviewOutcome>>;
274
+ for (const sample of PREVIEW_SAMPLES) {
275
+ const levels = {} as Record<ConductLevel, PreviewOutcome>;
276
+ for (const level of CONDUCT_LEVELS) {
277
+ const s = suggest(candidate, records[sample], level, rule, now);
278
+ const o = s.outcome;
279
+ levels[level] =
280
+ typeof o === 'string'
281
+ ? { label: s.label, kind: o, durationMs: null }
282
+ : { label: s.label, kind: o.kind, durationMs: o.durationMs };
283
+ }
284
+ samples[sample] = levels;
285
+ }
286
+ return { ok: true, samples, reporting: playerReporting(candidate.reporting) };
287
+ }
288
+ }