@chatwarden/core 0.1.6 → 0.1.8

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 (196) hide show
  1. package/README.md +173 -3
  2. package/dist/src/ai/agreement.d.ts +46 -0
  3. package/dist/src/ai/agreement.d.ts.map +1 -0
  4. package/dist/src/ai/agreement.js +71 -0
  5. package/dist/src/ai/agreement.js.map +1 -0
  6. package/dist/src/ai/breaker.d.ts +31 -0
  7. package/dist/src/ai/breaker.d.ts.map +1 -0
  8. package/dist/src/ai/breaker.js +62 -0
  9. package/dist/src/ai/breaker.js.map +1 -0
  10. package/dist/src/ai/budget.d.ts +26 -0
  11. package/dist/src/ai/budget.d.ts.map +1 -0
  12. package/dist/src/ai/budget.js +57 -0
  13. package/dist/src/ai/budget.js.map +1 -0
  14. package/dist/src/ai/case.d.ts +37 -0
  15. package/dist/src/ai/case.d.ts.map +1 -0
  16. package/dist/src/ai/case.js +30 -0
  17. package/dist/src/ai/case.js.map +1 -0
  18. package/dist/src/ai/casebook.d.ts +59 -0
  19. package/dist/src/ai/casebook.d.ts.map +1 -0
  20. package/dist/src/ai/casebook.js +47 -0
  21. package/dist/src/ai/casebook.js.map +1 -0
  22. package/dist/src/ai/ceilings.d.ts +42 -0
  23. package/dist/src/ai/ceilings.d.ts.map +1 -0
  24. package/dist/src/ai/ceilings.js +59 -0
  25. package/dist/src/ai/ceilings.js.map +1 -0
  26. package/dist/src/ai/fake.d.ts +41 -0
  27. package/dist/src/ai/fake.d.ts.map +1 -0
  28. package/dist/src/ai/fake.js +75 -0
  29. package/dist/src/ai/fake.js.map +1 -0
  30. package/dist/src/ai/hash.d.ts +15 -0
  31. package/dist/src/ai/hash.d.ts.map +1 -0
  32. package/dist/src/ai/hash.js +22 -0
  33. package/dist/src/ai/hash.js.map +1 -0
  34. package/dist/src/ai/inert.d.ts +5 -0
  35. package/dist/src/ai/inert.d.ts.map +1 -0
  36. package/dist/src/ai/inert.js +22 -0
  37. package/dist/src/ai/inert.js.map +1 -0
  38. package/dist/src/ai/injection.d.ts +8 -0
  39. package/dist/src/ai/injection.d.ts.map +1 -0
  40. package/dist/src/ai/injection.js +30 -0
  41. package/dist/src/ai/injection.js.map +1 -0
  42. package/dist/src/ai/lines.d.ts +64 -0
  43. package/dist/src/ai/lines.d.ts.map +1 -0
  44. package/dist/src/ai/lines.js +172 -0
  45. package/dist/src/ai/lines.js.map +1 -0
  46. package/dist/src/ai/prompt.d.ts +48 -0
  47. package/dist/src/ai/prompt.d.ts.map +1 -0
  48. package/dist/src/ai/prompt.js +196 -0
  49. package/dist/src/ai/prompt.js.map +1 -0
  50. package/dist/src/ai/redact.d.ts +29 -0
  51. package/dist/src/ai/redact.d.ts.map +1 -0
  52. package/dist/src/ai/redact.js +160 -0
  53. package/dist/src/ai/redact.js.map +1 -0
  54. package/dist/src/ai/schema.d.ts +6 -0
  55. package/dist/src/ai/schema.d.ts.map +1 -0
  56. package/dist/src/ai/schema.js +50 -0
  57. package/dist/src/ai/schema.js.map +1 -0
  58. package/dist/src/ai/service.d.ts +332 -0
  59. package/dist/src/ai/service.d.ts.map +1 -0
  60. package/dist/src/ai/service.js +751 -0
  61. package/dist/src/ai/service.js.map +1 -0
  62. package/dist/src/ai/types.d.ts +196 -0
  63. package/dist/src/ai/types.d.ts.map +1 -0
  64. package/dist/src/ai/types.js +23 -0
  65. package/dist/src/ai/types.js.map +1 -0
  66. package/dist/src/ai/validate.d.ts +30 -0
  67. package/dist/src/ai/validate.d.ts.map +1 -0
  68. package/dist/src/ai/validate.js +160 -0
  69. package/dist/src/ai/validate.js.map +1 -0
  70. package/dist/src/ai/worker.d.ts +76 -0
  71. package/dist/src/ai/worker.d.ts.map +1 -0
  72. package/dist/src/ai/worker.js +293 -0
  73. package/dist/src/ai/worker.js.map +1 -0
  74. package/dist/src/audit.d.ts +12 -3
  75. package/dist/src/audit.d.ts.map +1 -1
  76. package/dist/src/audit.js +30 -4
  77. package/dist/src/audit.js.map +1 -1
  78. package/dist/src/chat.d.ts +39 -1
  79. package/dist/src/chat.d.ts.map +1 -1
  80. package/dist/src/chat.js +85 -6
  81. package/dist/src/chat.js.map +1 -1
  82. package/dist/src/chatwarden.d.ts +84 -1
  83. package/dist/src/chatwarden.d.ts.map +1 -1
  84. package/dist/src/chatwarden.js +168 -6
  85. package/dist/src/chatwarden.js.map +1 -1
  86. package/dist/src/decide.d.ts +36 -1
  87. package/dist/src/decide.d.ts.map +1 -1
  88. package/dist/src/decide.js +62 -2
  89. package/dist/src/decide.js.map +1 -1
  90. package/dist/src/documents.d.ts +1 -1
  91. package/dist/src/documents.d.ts.map +1 -1
  92. package/dist/src/documents.js +6 -1
  93. package/dist/src/documents.js.map +1 -1
  94. package/dist/src/freeze.d.ts +3 -0
  95. package/dist/src/freeze.d.ts.map +1 -0
  96. package/dist/src/freeze.js +10 -0
  97. package/dist/src/freeze.js.map +1 -0
  98. package/dist/src/index.d.ts +37 -8
  99. package/dist/src/index.d.ts.map +1 -1
  100. package/dist/src/index.js +23 -3
  101. package/dist/src/index.js.map +1 -1
  102. package/dist/src/ladder.d.ts +28 -0
  103. package/dist/src/ladder.d.ts.map +1 -1
  104. package/dist/src/ladder.js +37 -1
  105. package/dist/src/ladder.js.map +1 -1
  106. package/dist/src/pace.d.ts +66 -0
  107. package/dist/src/pace.d.ts.map +1 -0
  108. package/dist/src/pace.js +111 -0
  109. package/dist/src/pace.js.map +1 -0
  110. package/dist/src/pacing.d.ts +63 -0
  111. package/dist/src/pacing.d.ts.map +1 -0
  112. package/dist/src/pacing.js +198 -0
  113. package/dist/src/pacing.js.map +1 -0
  114. package/dist/src/policy.d.ts +57 -1
  115. package/dist/src/policy.d.ts.map +1 -1
  116. package/dist/src/policy.js +67 -4
  117. package/dist/src/policy.js.map +1 -1
  118. package/dist/src/profile.d.ts +64 -8
  119. package/dist/src/profile.d.ts.map +1 -1
  120. package/dist/src/profile.js +98 -27
  121. package/dist/src/profile.js.map +1 -1
  122. package/dist/src/profileError.d.ts +10 -0
  123. package/dist/src/profileError.d.ts.map +1 -0
  124. package/dist/src/profileError.js +17 -0
  125. package/dist/src/profileError.js.map +1 -0
  126. package/dist/src/retention.d.ts +28 -0
  127. package/dist/src/retention.d.ts.map +1 -1
  128. package/dist/src/retention.js +42 -10
  129. package/dist/src/retention.js.map +1 -1
  130. package/dist/src/signalCounts.d.ts +37 -0
  131. package/dist/src/signalCounts.d.ts.map +1 -0
  132. package/dist/src/signalCounts.js +117 -0
  133. package/dist/src/signalCounts.js.map +1 -0
  134. package/dist/src/signalInert.d.ts +10 -0
  135. package/dist/src/signalInert.d.ts.map +1 -0
  136. package/dist/src/signalInert.js +28 -0
  137. package/dist/src/signalInert.js.map +1 -0
  138. package/dist/src/signalService.d.ts +101 -0
  139. package/dist/src/signalService.d.ts.map +1 -0
  140. package/dist/src/signalService.js +383 -0
  141. package/dist/src/signalService.js.map +1 -0
  142. package/dist/src/signals.d.ts +186 -0
  143. package/dist/src/signals.d.ts.map +1 -0
  144. package/dist/src/signals.js +361 -0
  145. package/dist/src/signals.js.map +1 -0
  146. package/dist/src/subjects.d.ts +2 -0
  147. package/dist/src/subjects.d.ts.map +1 -1
  148. package/dist/src/subjects.js +4 -0
  149. package/dist/src/subjects.js.map +1 -1
  150. package/dist/src/team.d.ts +27 -0
  151. package/dist/src/team.d.ts.map +1 -1
  152. package/dist/src/team.js +92 -4
  153. package/dist/src/team.js.map +1 -1
  154. package/dist/src/types.d.ts +324 -2
  155. package/dist/src/types.d.ts.map +1 -1
  156. package/dist/src/types.js.map +1 -1
  157. package/package.json +2 -2
  158. package/src/ai/agreement.ts +106 -0
  159. package/src/ai/breaker.ts +73 -0
  160. package/src/ai/budget.ts +65 -0
  161. package/src/ai/case.ts +74 -0
  162. package/src/ai/casebook.ts +75 -0
  163. package/src/ai/ceilings.ts +68 -0
  164. package/src/ai/fake.ts +105 -0
  165. package/src/ai/hash.ts +23 -0
  166. package/src/ai/inert.ts +26 -0
  167. package/src/ai/injection.ts +32 -0
  168. package/src/ai/lines.ts +216 -0
  169. package/src/ai/prompt.ts +223 -0
  170. package/src/ai/redact.ts +174 -0
  171. package/src/ai/schema.ts +51 -0
  172. package/src/ai/service.ts +961 -0
  173. package/src/ai/types.ts +182 -0
  174. package/src/ai/validate.ts +173 -0
  175. package/src/ai/worker.ts +372 -0
  176. package/src/audit.ts +31 -5
  177. package/src/chat.ts +109 -8
  178. package/src/chatwarden.ts +248 -8
  179. package/src/decide.ts +97 -4
  180. package/src/documents.ts +7 -2
  181. package/src/freeze.ts +8 -0
  182. package/src/index.ts +91 -2
  183. package/src/ladder.ts +59 -1
  184. package/src/pace.ts +139 -0
  185. package/src/pacing.ts +242 -0
  186. package/src/policy.ts +107 -7
  187. package/src/profile.ts +149 -27
  188. package/src/profileError.ts +17 -0
  189. package/src/retention.ts +63 -10
  190. package/src/signalCounts.ts +133 -0
  191. package/src/signalInert.ts +31 -0
  192. package/src/signalService.ts +406 -0
  193. package/src/signals.ts +489 -0
  194. package/src/subjects.ts +5 -0
  195. package/src/team.ts +93 -5
  196. package/src/types.ts +358 -2
package/src/chatwarden.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { createInertAi } from './ai/inert.js';
2
+ import type { AiFacade, AiOptions, AiService } from './ai/service.js';
1
3
  import { AuditService } from './audit.js';
2
4
  import type { AuditPage, AuditQuery, AuditRecordInput } from './audit.js';
3
5
  import { ChatService } from './chat.js';
@@ -21,7 +23,13 @@ import { dismissMany } from './dismissMany.js';
21
23
  import type { DismissManyInput, DismissManyResult } from './dismissMany.js';
22
24
  import { PolicyService } from './policy.js';
23
25
  import type { PolicyPreview, PolicySaveContext, PolicySaveResult, PolicyState } from './policy.js';
24
- import { resolveProfile } from './profile.js';
26
+ import { checkPace, mergePace } from './pace.js';
27
+ import { createInertSignals } from './signalInert.js';
28
+ import type { SignalRuntime } from './signalService.js';
29
+ import { BUILTIN_SIGNAL_KINDS, checkSignalFeeds } from './signals.js';
30
+ import type { SignalCount, SignalInput, SignalKindView } from './signals.js';
31
+ import type { PaceSettings, ResolvedPace } from './pace.js';
32
+ import { ProfileError, resolveProfile } from './profile.js';
25
33
  import type { ModerationProfile, PolicyLayer, PolicySection, PresetName, ProfanityConfig, ProfileOverrides, ResolvedProfile } from './profile.js';
26
34
  import { MuteService } from './mutes.js';
27
35
  import { NoticeService } from './notices.js';
@@ -194,6 +202,30 @@ export interface ChatwardenOptions {
194
202
  * `RangeError`; set it when your registry numbers slurs differently.
195
203
  */
196
204
  autoRestrictRule?: number;
205
+ /**
206
+ * AI levels 1 and 2 (read, and recommend). Off unless you give an adapter; the level itself is a moderator setting
207
+ * (`profile.ai.level`, default 0) held to at most `maxLevel`. Needs a store with the AI methods (SQLite has them; the
208
+ * in-memory store has them through `withMemoryAi`). A store without them leaves the AI inert and logs `chatwarden.ai_store_unsupported`
209
+ * once at creation, as with any optional Store method; a bad option still throws. The adapter runs on the server only; see `ModerationAI`.
210
+ * @experimental
211
+ */
212
+ ai?: AiOptions;
213
+ /**
214
+ * Signals: what the game records about a player. The kinds, the guards and the feeds are in the profile (`profile.signals`); this
215
+ * holds the one hook the profile cannot. Signals need a store with the three signal methods (SQLite has them; the in-memory store has them
216
+ * through `withMemorySignals`): declaring kinds or feeds over a store without them is refused at creation, and the kit loads its signal
217
+ * service only for a store that has them.
218
+ * @experimental
219
+ */
220
+ signals?: {
221
+ /**
222
+ * How old is this player's account, in days, from the account ids the kit has for them (the strings your game gave it as
223
+ * `RawWho.accountId`)? Return null or undefined when unknown. Called synchronously at record time for `by`, and only for a player with
224
+ * at least one account id; a throw reads as unknown (logged by error class). Without this hook the new-account guard is not used,
225
+ * whatever the profile says.
226
+ */
227
+ accountAgeDays?: (accountIds: readonly string[]) => number | null | undefined;
228
+ };
197
229
  }
198
230
 
199
231
  /** The moderation kit as an adopter uses it. Nothing here returns an identifier meant for a player. */
@@ -216,6 +248,17 @@ export interface Chatwarden {
216
248
  * Carries subject ids: staff channels only, never send to a player.
217
249
  */
218
250
  subjectAt(roomId: string, seatId: string): SubjectId | null;
251
+ /**
252
+ * Pace this room differently from the defaults until it closes. Per field: absent inherits, `null` turns that check off, a value sets
253
+ * it. `null` instead of an object removes the override (`{}` is the same: nothing to override). A second call replaces the room's earlier
254
+ * override whole; it is not merged into it. The object is read once, so changing it afterwards changes nothing. Throws `ProfileError` for an invalid
255
+ * value (a setup mistake, not a hot-path call), and changes nothing when it does. In memory, this process only: `rooms.close(roomId)`
256
+ * drops it, and a game that runs several processes calls it in each process that serves the room. The override sits on top of the
257
+ * stored layer, which sits on top of the profile in code. @experimental
258
+ */
259
+ setPace(roomId: string, pace: PaceSettings | null): void;
260
+ /** The pace in force for the room: the profile's (code, then the stored layer) with the room's override applied. Every field filled, `null` is off. @experimental */
261
+ pace(roomId: string): ResolvedPace;
219
262
  };
220
263
  chat: {
221
264
  accept(roomId: string, seatId: string, text: string, opts?: { audience?: string[] }): ChatResult;
@@ -372,9 +415,14 @@ export interface Chatwarden {
372
415
  * (see `cw.reports.reporterAccuracy`) and none of which has waited 24 hours (`REPORTER_RANK_LAPSE_MS`) is served after the ordinary
373
416
  * ones, oldest first; it is never skipped, so a queue holding only such cases still serves them. One ordinary reporter, or no
374
417
  * accuracy data (a store without `reporterOutcomes`), keeps a case normal. A non-boolean value is a `RangeError`.
375
- * @experimental (the `rankDownHabitual` filter)
418
+ *
419
+ * With `signalBoost` (default false: behaviour unchanged; use it when the queue signal feed, `feeds.queue`, is on), the scan stays oldest
420
+ * first but a case is claimed only when it is overdue (its oldest open report has waited 24 hours) or boosted (the person meets the
421
+ * feed's threshold); the first such case wins. If the queue, or the first 200 people, hold neither, the oldest free case is claimed as
422
+ * usual, so nothing is ever left out. A boosted case is never ranked down. A non-boolean value is a `RangeError`.
423
+ * @experimental (the `rankDownHabitual` and `signalBoost` filters)
376
424
  */
377
- next(actor: string, filter?: { category?: ReportCategory; reason?: string | null; rankDownHabitual?: boolean }): NextCase | null;
425
+ next(actor: string, filter?: { category?: ReportCategory; reason?: string | null; rankDownHabitual?: boolean; signalBoost?: boolean }): NextCase | null;
378
426
  /**
379
427
  * `actor` has the person's case open now. A hint for 30 seconds (`VIEWING_TTL_MS`), in this process's memory only.
380
428
  * Only a person with an open report is tracked (false otherwise, nothing recorded); one actor keeps at most 20 cases
@@ -460,6 +508,42 @@ export interface Chatwarden {
460
508
  */
461
509
  check(text: string): { ok: true } | { ok: false; reason: 'name_not_allowed'; rule: number };
462
510
  };
511
+ /**
512
+ * 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
513
+ * read is made after the report is stored and never delays the player's ack; a failing, slow or refusing provider changes nothing
514
+ * for players or moderators. Staff only: a read describes chat lines.
515
+ * @experimental
516
+ */
517
+ ai: AiFacade;
518
+ /**
519
+ * Signals: what the game records about a player (muted by others, kicked, left mid-game), counted by distinct source. A signal never
520
+ * acts: it is read only where a profile rule says so (the Person page record, the ladder suggestion, the AI read, the queue order).
521
+ * Staff-side data: never send any of this to a player.
522
+ * @experimental
523
+ */
524
+ signals: {
525
+ /**
526
+ * Record one signal. Synchronous, fenced, never throws: it returns false (and logs `chatwarden.signal_refused` with a reason code,
527
+ * at most once a minute) for an undeclared or malformed kind, a party it cannot resolve (an unknown subject id, or a `RawWho` the kit
528
+ * has never seen: nobody is created), `subject` equal to `by` (also across a merge), a time out of range, the per-source cap, a
529
+ * store without signals, or a store failure. True means a row was written. One small write: record events, not every chat line.
530
+ */
531
+ record(input: SignalInput): boolean;
532
+ /**
533
+ * The counts for a person now: one entry per declared kind that has at least one source in the window (default 30 days, held to
534
+ * the retention and to 90), aliases folded. Never throws; a store failure reads []. Never send to a player.
535
+ */
536
+ counts(subject: SubjectId, opts?: { windowDays?: number; kinds?: readonly string[] }): SignalCount[];
537
+ /** The declared kinds, built-ins included, for building a form. */
538
+ kinds(): SignalKindView[];
539
+ /**
540
+ * Which of these people meet the queue feed (`feeds.queue`), as canonical ids, from one grouped read. Empty, with no store read,
541
+ * when the feed is off. Never throws.
542
+ */
543
+ boosted(people: readonly SubjectId[]): Set<SubjectId>;
544
+ /** The lines the Person page record shows (`feeds.record`: its kinds and window). `[]` when the feed is off. Never throws. */
545
+ forRecord(subject: SubjectId): SignalCount[];
546
+ };
463
547
  /** The registry in use (the one given, or the starter rules for the profile). Retired rules stay listed. */
464
548
  rules: CommunityRules;
465
549
  /**
@@ -625,6 +709,9 @@ export interface Chatwarden {
625
709
  * The profanity filter for the profile, or undefined. Mode `allow` builds nothing; a ready filter wins over the
626
710
  * package; a package that throws fails creation and one that returns a non-filter is a TypeError.
627
711
  */
712
+ /** Does the store keep signals (all three optional methods)? */
713
+ const storeKeepsSignals = (s: Store): boolean => typeof s.insertSignal === 'function' && typeof s.listSignalSources === 'function' && typeof s.purgeSignals === 'function';
714
+
628
715
  function buildProfanityFilter(opts: ChatwardenOptions, config: ProfanityConfig): ProfanityFilter | undefined {
629
716
  if (config.mode === 'allow') return undefined;
630
717
  if (opts.profanity !== undefined) return opts.profanity;
@@ -665,6 +752,28 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
665
752
  badFaithMs: givenRetention.badFaithMs ?? Math.max(RETENTION_DEFAULTS.badFaithMs, limits.reports.suspendWindowMs),
666
753
  };
667
754
  checkRetentionFloors(retentionPolicy, limits.reports.suspendWindowMs);
755
+ // A feed window longer than the signal retention could never be met (rows older than that are deleted): refuse it in code too.
756
+ checkSignalFeeds(baseProfile.signals.feeds, baseProfile.signals.kinds, { signalsMs: retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs }, 'profile.signals.feeds');
757
+ // Declaring kinds or feeds is an explicit opt-in that a store without the signal methods would silently turn into nothing: refuse it.
758
+ // (Only the built-in `flood_triggered` and pacing: nothing declared, so the kit starts and skips that record, logged once.)
759
+ const declaresSignals =
760
+ Object.keys(baseProfile.signals.feeds).length > 0 ||
761
+ Object.keys(baseProfile.signals.kinds).some((id) => {
762
+ const k = baseProfile.signals.kinds[id]!;
763
+ const builtin = Object.hasOwn(BUILTIN_SIGNAL_KINDS, id) ? BUILTIN_SIGNAL_KINDS[id as 'flood_triggered'] : undefined;
764
+ return builtin === undefined || builtin.label !== k.label || k.weight !== 1;
765
+ });
766
+ if (declaresSignals && !storeKeepsSignals(opts.store)) {
767
+ throw new Error(
768
+ 'createChatwarden: the profile declares signal kinds or feeds, but the store has no signal methods (insertSignal, listSignalSources, purgeSignals); use the memory or SQLite store, or leave "signals" out of the profile',
769
+ );
770
+ }
771
+ if (opts.signals?.accountAgeDays !== undefined && typeof opts.signals.accountAgeDays !== 'function') {
772
+ throw new TypeError('createChatwarden: signals.accountAgeDays must be a function');
773
+ }
774
+ // The signal service (and the counting under it) is loaded only for a store that can keep signals, so a bundler can leave it out of a build
775
+ // that never has one (the in-memory store has the methods only through `withMemorySignals`). Without it `cw.signals` is inert.
776
+ const signalModule = storeKeepsSignals(opts.store) ? await import('./signalService.js') : undefined;
668
777
  const purgeEveryMs = everyMs ?? DEFAULT_PURGE_EVERY_MS;
669
778
  if (opts.retention !== false && (!Number.isFinite(purgeEveryMs) || purgeEveryMs <= 0)) {
670
779
  throw new Error('createChatwarden: retention.everyMs must be a positive finite number');
@@ -672,6 +781,12 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
672
781
  if (opts.retention !== false && purgeEveryMs > MAX_PURGE_EVERY_MS) {
673
782
  throw new RangeError(`retention.everyMs must be at most ${MAX_PURGE_EVERY_MS}`);
674
783
  }
784
+ // The AI service is loaded only when an adapter is given, so a bundler can leave it (about 40 KB minified) out of a build that never passes one.
785
+ const aiModule = opts.ai === undefined ? undefined : await import('./ai/service.js');
786
+ // A bad option throws here. A store without the AI methods (the in-memory store has them only through `withMemoryAi`) does not: the AI stays
787
+ // inert and the kit says so once, like any optional Store method it cannot use.
788
+ const aiMissing = opts.ai !== undefined && aiModule !== undefined ? aiModule.checkAiSetup(store, opts.ai) : [];
789
+ if (aiMissing.length > 0) safeWarn(logger, 'chatwarden.ai_store_unsupported', { missing: aiMissing.join(',') });
675
790
  const rules = opts.rules ?? defineRules(starterRules(baseProfile.rules));
676
791
  const autoRestrictRule = opts.autoRestrictRule ?? 1;
677
792
  const autoRule = rules.get(autoRestrictRule);
@@ -695,7 +810,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
695
810
  await mutes.load();
696
811
  await strikes.load();
697
812
  // The stored edits to the profile. Read last, so a store that fails here has not left anything half built.
698
- const policy = new PolicyService({ store, clock, logger, base: baseProfile });
813
+ const policy = new PolicyService({ store, clock, logger, base: baseProfile, signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs, chatRate: limits.chatRate });
699
814
  policy.load();
700
815
 
701
816
  // ONE notice service for the whole kit: chat (the automatic timeout), the doors (the refusal's pointer) and
@@ -711,6 +826,30 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
711
826
  notify: typeof platformNotify === 'function' ? (who, event) => platformNotify.call(platform, who, event) : undefined,
712
827
  });
713
828
 
829
+ /** The signal service, set once `personOf` exists (the chat path above it only calls it later, never during creation). */
830
+ const signalRef: { service?: SignalRuntime } = {};
831
+
832
+ // Room overrides of the pace: this process only, dropped by `rooms.close`. Each is the validated sparse override as given (a field
833
+ // left out inherits), kept as a frozen copy so the caller's object cannot change it later.
834
+ const paceOverrides = new Map<string, Readonly<PaceSettings>>();
835
+ /** The merged pace of a room with an override, with the profile pace it was merged onto: valid while that object is the one in force. */
836
+ const paceMerged = new Map<string, { base: ResolvedPace; merged: ResolvedPace }>();
837
+ /**
838
+ * The pace in force for a room: the override over the profile's (the layer over the code). A room without an override gets the
839
+ * profile's own object; one with an override is merged once per change of the profile's pace (it is a new object on every layer
840
+ * change), not once per line.
841
+ */
842
+ const paceOf = (roomId: string): ResolvedPace => {
843
+ const base = policy.profileNow().pace;
844
+ const over = paceOverrides.get(roomId);
845
+ if (over === undefined) return base;
846
+ const cached = paceMerged.get(roomId);
847
+ if (cached !== undefined && cached.base === base) return cached.merged;
848
+ const merged = mergePace(base, over);
849
+ paceMerged.set(roomId, { base, merged });
850
+ return merged;
851
+ };
852
+
714
853
  const chat = new ChatService({
715
854
  roster,
716
855
  buffer,
@@ -732,6 +871,21 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
732
871
  notices,
733
872
  autoRestrictRule,
734
873
  limits: { maxLength: limits.chatMaxLength, rate: limits.chatRate },
874
+ pace: {
875
+ settings: paceOf,
876
+ canonical: (subject) => subjects.canonical(subject),
877
+ // A flood trip records the built-in kind, deferred so the verdict is returned first. `flood` never throws and logs its own
878
+ // refusals; a room id the signal rules do not accept is left out (the trip is then a day source, not dropped).
879
+ onFlood: ({ roomId, subject }) => {
880
+ queueMicrotask(() => {
881
+ try {
882
+ signalRef.service?.flood(subject, roomId);
883
+ } catch (err) {
884
+ safeWarn(logger, 'chatwarden.pace_failed', { error: err instanceof Error ? err.name : typeof err });
885
+ }
886
+ });
887
+ },
888
+ },
735
889
  });
736
890
  const reports = new ReportService({
737
891
  roster,
@@ -746,6 +900,8 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
746
900
  limits: limits.reports,
747
901
  });
748
902
  const doors = new DoorService({ hasher, subjects, sanctions, clock, logger, notices });
903
+ // The AI service is built after the audit trail it writes to; a decision reaches it through this late binding.
904
+ const aiRef: { service?: AiService } = {};
749
905
  const decisions = new DecisionService({
750
906
  store,
751
907
  subjects,
@@ -755,6 +911,7 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
755
911
  index: sanctions,
756
912
  logger,
757
913
  reporterFeedback: limits.reporterFeedback,
914
+ aiOutcome: (args) => aiRef.service?.outcomeOf(args) ?? null,
758
915
  });
759
916
 
760
917
  // The person behind a player's connection details, FOUND and never created. An IP alone finds nobody.
@@ -762,6 +919,17 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
762
919
  const ids = hashWho(hasher, who);
763
920
  return subjects.lookup({ clientKey: ids.clientKey, accountId: ids.accountId, ipHash: null });
764
921
  };
922
+ signalRef.service = signalModule === undefined ? createInertSignals(logger, () => policy.profileNow().signals) : new signalModule.SignalService({
923
+ store,
924
+ clock,
925
+ logger,
926
+ subjects,
927
+ personOf,
928
+ settings: () => policy.profileNow().signals,
929
+ signalsMs: () => retentionPolicy.signalsMs ?? RETENTION_DEFAULTS.signalsMs,
930
+ ...(opts.signals?.accountAgeDays === undefined ? {} : { accountAgeDays: opts.signals.accountAgeDays }),
931
+ });
932
+ const signals = signalRef.service;
765
933
  /** A player-facing read: a store failure is logged (class only) and reads as `fallback`. */
766
934
  const forPlayer = <T>(who: RawWho, fallback: T, read: (subject: SubjectId) => T): T => {
767
935
  try {
@@ -846,6 +1014,15 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
846
1014
  } catch (err) {
847
1015
  eventFailed(err);
848
1016
  }
1017
+ // A decision recorded against an AI read leaves one audit row, written by the moderator (best effort: it never fails the decision).
1018
+ const recorded = committed.aiOutcome;
1019
+ if (recorded !== null && recorded.role !== null) {
1020
+ try {
1021
+ audit.record({ actor: recorded.actor, role: recorded.role, action: 'ai.outcome', target: { type: 'report', ref: committed.reportId } });
1022
+ } catch (err) {
1023
+ eventFailed(err);
1024
+ }
1025
+ }
849
1026
  }
850
1027
  return result;
851
1028
  };
@@ -857,10 +1034,40 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
857
1034
  clock,
858
1035
  reasons: () => policy.profileNow().reporting.reasons,
859
1036
  accuracy: (people) => reporterAccuracyFor(store, subjects, people, clock.now()),
1037
+ boosted: (people) => signals.boosted(people),
860
1038
  });
861
1039
  const reasonBook = new ReasonBook(store);
862
1040
 
1041
+ // The AI read service. It listens for new reports and only enqueues; with no adapter it is a facade that is always off.
1042
+ const aiService =
1043
+ opts.ai === undefined || aiModule === undefined || aiMissing.length > 0
1044
+ ? undefined
1045
+ : new aiModule.AiService({
1046
+ options: opts.ai,
1047
+ store,
1048
+ clock,
1049
+ logger,
1050
+ profile: () => policy.profileNow(),
1051
+ rules,
1052
+ suggest: (subject, level, rule, context) => suggest(policy.profileNow(), historyOf(store, subjects, subject, clock.now()), level, rule, clock.now(), context),
1053
+ subscribe: bus.on,
1054
+ audit: (input) => audit.record(input),
1055
+ exampleRetentionMs: () => retentionPolicy.aiExamplesMs ?? RETENTION_DEFAULTS.aiExamplesMs,
1056
+ // The counts about the reported person the feed allows (`feeds.ai`), as label, polarity, distinct and window: nothing else leaves.
1057
+ signals: (subject) => signals.forAi(subject).map((c) => ({ label: c.label, polarity: c.polarity, distinct: c.distinct, windowDays: c.windowDays })),
1058
+ });
1059
+ aiRef.service = aiService;
1060
+ const ai: AiFacade = aiService ?? createInertAi();
1061
+
863
1062
  return {
1063
+ ai,
1064
+ signals: {
1065
+ record: (input) => signals.record(input),
1066
+ counts: (subject, o) => signals.counts(subject, o),
1067
+ kinds: () => signals.kinds(),
1068
+ boosted: (people) => signals.boosted(people),
1069
+ forRecord: (subject) => signals.forRecord(subject),
1070
+ },
864
1071
  rooms: {
865
1072
  seat,
866
1073
  seatConnection: (roomId, seatId, ctx, handle, tags) => {
@@ -872,11 +1079,29 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
872
1079
  close: (roomId) => {
873
1080
  roster.close(roomId);
874
1081
  buffer.drop(roomId);
1082
+ paceOverrides.delete(roomId);
1083
+ paceMerged.delete(roomId);
1084
+ chat.dropPaceRoom(roomId);
875
1085
  },
876
1086
  subjectAt: (roomId, seatId) => {
877
1087
  const subject = roster.occupant(roomId, seatId)?.subject ?? null;
878
1088
  return subject === null ? null : subjects.canonical(subject);
879
1089
  },
1090
+ setPace: (roomId, pace) => {
1091
+ if (typeof roomId !== 'string' || roomId === '') throw new ProfileError('roomId', 'must be a non-empty string');
1092
+ paceMerged.delete(roomId);
1093
+ if (pace === null) {
1094
+ paceOverrides.delete(roomId);
1095
+ return;
1096
+ }
1097
+ // The caller's object is read once, into a validated snapshot of the fields it gave (a field left out inherits); that
1098
+ // snapshot is what is kept, so nothing about it can change after the check.
1099
+ const kept = checkPace(pace);
1100
+ if (kept.burst !== undefined && kept.burst !== null) Object.freeze(kept.burst);
1101
+ if (Object.keys(kept).length === 0) paceOverrides.delete(roomId);
1102
+ else paceOverrides.set(roomId, Object.freeze(kept));
1103
+ },
1104
+ pace: (roomId) => paceOf(roomId),
880
1105
  },
881
1106
  chat: {
882
1107
  accept: (roomId, seatId, text, o) => chat.accept(roomId, seatId, text, o),
@@ -914,7 +1139,12 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
914
1139
  if (res.ok) announceReport(res.reportId);
915
1140
  return res;
916
1141
  },
917
- addDetail: (reportId, reporterSeat, detail) => reports.addDetail(reportId, reporterSeat, detail),
1142
+ addDetail: async (reportId, reporterSeat, detail) => {
1143
+ const res = await reports.addDetail(reportId, reporterSeat, detail);
1144
+ // The follow-up changes what the AI would read: queue one new read (it only enqueues; the reporter's ack never waits).
1145
+ if (res.ok) aiService?.caseChanged(reportId);
1146
+ return res;
1147
+ },
918
1148
  list: (q) => listStaffReports(store, subjects, q, policy.profileNow().reporting.reasons),
919
1149
  get: (id) => {
920
1150
  const record = typeof id === 'string' ? store.loadReport(id) : null;
@@ -1054,7 +1284,11 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1054
1284
  history: (subject) => historyOf(store, subjects, subject, clock.now()),
1055
1285
  suggest: (subject, level, rule, context) => {
1056
1286
  const now = clock.now();
1057
- return suggest(policy.profileNow(), historyOf(store, subjects, subject, now), level, rule, now, context);
1287
+ // The signal hits are the kit's to compute: a list the caller passes is dropped, the real one set when a ladder rule is met.
1288
+ const { signals: _ignored, ...given } = (context ?? {}) as SuggestContext;
1289
+ void _ignored;
1290
+ const hits = signals.ladderHits(subject);
1291
+ return suggest(policy.profileNow(), historyOf(store, subjects, subject, now), level, rule, now, hits.length === 0 ? given : { ...given, signals: hits });
1058
1292
  },
1059
1293
  gaps: {
1060
1294
  list: () =>
@@ -1091,10 +1325,13 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1091
1325
  get: (subject) => store.transaction(() => store.getDiscordThread(subject)),
1092
1326
  put: (row) => store.transaction(() => store.putDiscordThread(row)),
1093
1327
  },
1094
- purge: async (policy) => {
1328
+ purge: async (override) => {
1095
1329
  const merged: Partial<RetentionPolicy> = { ...retentionPolicy };
1096
- for (const [k, v] of Object.entries(policy ?? {})) if (v !== undefined) (merged as Record<string, unknown>)[k] = v;
1330
+ for (const [k, v] of Object.entries(override ?? {})) if (v !== undefined) (merged as Record<string, unknown>)[k] = v;
1097
1331
  checkRetentionFloors(merged, limits.reports.suspendWindowMs);
1332
+ // A feed window longer than the signal retention could never be met: refuse the purge that would make it so, deleting nothing.
1333
+ const { kinds, feeds } = policy.profileNow().signals;
1334
+ checkSignalFeeds(feeds, kinds, { signalsMs: merged.signalsMs ?? RETENTION_DEFAULTS.signalsMs }, 'profile.signals.feeds');
1098
1335
  return await purge(store, clock.now(), merged);
1099
1336
  },
1100
1337
  ready: () => {
@@ -1110,6 +1347,9 @@ export async function createChatwarden(opts: ChatwardenOptions): Promise<Chatwar
1110
1347
  close: async () => {
1111
1348
  if (timer !== undefined) clearInterval(timer);
1112
1349
  timer = undefined;
1350
+ // Stop reading and abort calls in flight, and let them end before the store goes.
1351
+ ai.close();
1352
+ await ai.idle();
1113
1353
  await subjects.flush();
1114
1354
  store.close();
1115
1355
  },
package/src/decide.ts CHANGED
@@ -1,3 +1,6 @@
1
+ import type { AiOutcomeHook } from './ai/casebook.js';
2
+ import { ROLES } from './audit.js';
3
+ import type { Role } from './audit.js';
1
4
  import { sha256Hex } from './crypto.js';
2
5
  import { safeWarn } from './log.js';
3
6
  import { ownLines } from './notices.js';
@@ -6,7 +9,8 @@ import type { CommunityRules, RuleRef } from './rules.js';
6
9
  import { SANCTION_KINDS, SANCTION_SOURCES, validateSanctionInput, writeSanction } from './sanctions.js';
7
10
  import type { SanctionIndex } from './sanctions.js';
8
11
  import type { SubjectIndex } from './subjects.js';
9
- import type { Clock, Logger, ReportExcerptLine, ReportRecord, SanctionKind, SanctionRow, Source, Store, SubjectId } from './types.js';
12
+ import { CONDUCT_LEVELS } from './types.js';
13
+ import type { AiOutcomeInsert, Clock, ConductLevel, Logger, ReportExcerptLine, ReportRecord, SanctionKind, SanctionRow, Source, Store, SubjectId } from './types.js';
10
14
 
11
15
  // The one path every moderator decision on a report takes. A decision closes the report, writes each sanction and
12
16
  // its player notice, and records itself, all in ONE store transaction: it lands whole or not at all. The same
@@ -82,6 +86,29 @@ export interface DecisionInput {
82
86
  reason?: string;
83
87
  /** Defaults to `'moderator'`. */
84
88
  source?: Source;
89
+ /**
90
+ * AI levels 1 and 2. Optional: the casebook records how every decision compared with the report's AI read whether or not this is
91
+ * given (the server decides, from the stored read and the decision). It only tells the casebook which read the moderator saw, whether
92
+ * they clicked accept, the conduct level of their form and their role. It never changes the decision, its key or its answer, and a
93
+ * part that is not well formed is ignored. Agreement is computed from the stored read and the decision, never from this echo.
94
+ * @experimental
95
+ */
96
+ ai?: DecisionAiEcho;
97
+ }
98
+
99
+ /**
100
+ * What a decision tells the casebook about the AI. `readId` (with `accepted`) is the echo of the read the moderator saw: an id that is
101
+ * not one of this report's finished reads falls back to the newest. `accepted` is a claim that they accepted the pre-fill in one click:
102
+ * it counts only when the decision is the pre-fill. `severity` is the conduct level their form settled on: it counts only when it fits
103
+ * the verdict. Without the echo no example text is kept. `role` is the moderator's, for the `ai.outcome` audit row (without it none is
104
+ * written).
105
+ * @experimental
106
+ */
107
+ export interface DecisionAiEcho {
108
+ readId?: string;
109
+ accepted?: boolean;
110
+ severity?: ConductLevel;
111
+ role?: Role;
85
112
  }
86
113
 
87
114
  /**
@@ -120,6 +147,8 @@ export interface DecisionServiceDeps {
120
147
  * nothing, and the people acted on are still told.
121
148
  */
122
149
  reporterFeedback?: boolean;
150
+ /** AI casebook: the outcome row for a decision made with an AI echo. Fenced; null records nothing. */
151
+ aiOutcome?: AiOutcomeHook;
123
152
  }
124
153
 
125
154
  /**
@@ -146,7 +175,14 @@ export interface AppliedGroup {
146
175
  */
147
176
  export interface DecisionOutcome {
148
177
  result: DecisionResult;
149
- committed: { reportId: string; verdict: DecisionInput['verdict']; at: number; applied: AppliedGroup[] } | null;
178
+ committed: {
179
+ reportId: string;
180
+ verdict: DecisionInput['verdict'];
181
+ at: number;
182
+ applied: AppliedGroup[];
183
+ /** The casebook recorded an outcome with this decision; `role` is the moderator's, for the audit row (null when the echo had none). */
184
+ aiOutcome: { agreement: AiOutcomeInsert['agreement']; role: Role | null; actor: string } | null;
185
+ } | null;
150
186
  }
151
187
 
152
188
  const VERDICTS: readonly DecisionInput['verdict'][] = ['upheld', 'noted', 'no_action', 'bad_faith'];
@@ -191,6 +227,26 @@ interface Normal {
191
227
  source: Source;
192
228
  /** Sorted by canonical subject, then kind. */
193
229
  actions: NormalAction[];
230
+ /** The AI echo, or null when absent or not well formed. Not part of the key. */
231
+ ai: { readId: string | null; accepted: boolean; severity: ConductLevel | null; role: Role | null };
232
+ }
233
+
234
+ /** The longest read id an echo may carry. */
235
+ const AI_READ_ID_MAX = 128;
236
+
237
+ /**
238
+ * The AI echo of an input. Anything that is not well formed is ignored, never an error (the decision matters more): a malformed echo
239
+ * (a bad read id, or an `accepted` that is not a boolean) is as if there were none, but a good role is kept for the audit row.
240
+ */
241
+ function normalizeAi(v: unknown): Normal['ai'] {
242
+ const none: Normal['ai'] = { readId: null, accepted: false, severity: null, role: null };
243
+ if (typeof v !== 'object' || v === null) return none;
244
+ const o = v as Record<string, unknown>;
245
+ const role = (ROLES as readonly unknown[]).includes(o['role']) ? (o['role'] as Role) : null;
246
+ const readId = o['readId'];
247
+ if (typeof readId !== 'string' || readId === '' || readId.length > AI_READ_ID_MAX || typeof o['accepted'] !== 'boolean') return { ...none, role };
248
+ const severity = (CONDUCT_LEVELS as readonly unknown[]).includes(o['severity']) ? (o['severity'] as ConductLevel) : null;
249
+ return { readId, accepted: o['accepted'], severity, role };
194
250
  }
195
251
 
196
252
  const byText = (a: string, b: string): number => (a < b ? -1 : a > b ? 1 : 0);
@@ -265,6 +321,7 @@ function normalize(subjects: SubjectIndex, input: DecisionInput): Normal {
265
321
  evidence,
266
322
  source: source as Source,
267
323
  actions,
324
+ ai: normalizeAi(input.ai),
268
325
  };
269
326
  }
270
327
 
@@ -330,6 +387,7 @@ export class DecisionService {
330
387
  private readonly index: SanctionIndex | undefined;
331
388
  private readonly logger: Logger | undefined;
332
389
  private readonly reporterFeedback: boolean;
390
+ private readonly aiOutcome: AiOutcomeHook | undefined;
333
391
 
334
392
  constructor(deps: DecisionServiceDeps) {
335
393
  this.store = deps.store;
@@ -340,6 +398,7 @@ export class DecisionService {
340
398
  this.index = deps.index;
341
399
  this.logger = deps.logger;
342
400
  this.reporterFeedback = deps.reporterFeedback ?? true;
401
+ this.aiOutcome = deps.aiOutcome;
343
402
  }
344
403
 
345
404
  /**
@@ -442,6 +501,7 @@ export class DecisionService {
442
501
  const pending = this.index !== undefined && !this.index.isEnabled();
443
502
  const reporter = this.subjects.canonical(report.reporterSubject);
444
503
  const status = isDismissal(norm.verdict) ? 'dismissed' : 'actioned';
504
+ const outcome = this.outcomeFor(norm, report, now);
445
505
 
446
506
  const done = this.store.transaction(() => {
447
507
  if (!this.store.closeReport(report.id, status, norm.verdict === 'bad_faith', norm.actor, now, norm.reason, norm.evidence)) {
@@ -491,7 +551,16 @@ export class DecisionService {
491
551
  told.add(reporter);
492
552
  }
493
553
  this.store.insertDecision(key, report.id, now, JSON.stringify({ groups }));
494
- return { groups, applied, rows, told };
554
+ // The casebook row lands with the decision or not at all. A casebook that cannot be written never fails the decision.
555
+ let recorded: AiOutcomeInsert['agreement'] | null = null;
556
+ if (outcome !== null) {
557
+ try {
558
+ if (this.store.insertAiOutcome?.(outcome) === true) recorded = outcome.agreement;
559
+ } catch (err) {
560
+ this.warn('decide.ai_outcome_failed', { error: errName(err) });
561
+ }
562
+ }
563
+ return { groups, applied, rows, told, recorded };
495
564
  });
496
565
 
497
566
  if (done === null) {
@@ -515,10 +584,34 @@ export class DecisionService {
515
584
  }
516
585
  return {
517
586
  result: { ok: true, groups: done.groups, replay: false },
518
- committed: { reportId: report.id, verdict: norm.verdict, at: now, applied: done.applied },
587
+ committed: {
588
+ reportId: report.id,
589
+ verdict: norm.verdict,
590
+ at: now,
591
+ applied: done.applied,
592
+ aiOutcome: done.recorded === null ? null : { agreement: done.recorded, role: norm.ai.role, actor: norm.actor },
593
+ },
519
594
  };
520
595
  }
521
596
 
597
+ /** The casebook row for this decision, or null: no echo, no hook, no AI store method, or the hook declines or fails. */
598
+ private outcomeFor(norm: Normal, report: ReportRecord, now: number): AiOutcomeInsert | null {
599
+ if (this.aiOutcome === undefined || typeof this.store.insertAiOutcome !== 'function') return null;
600
+ try {
601
+ return this.aiOutcome({
602
+ report,
603
+ target: this.subjects.canonical(report.targetSubject),
604
+ verdict: norm.verdict,
605
+ actions: norm.actions.map((a) => ({ subject: a.subject, kind: a.kind, durationMs: a.durationMs, rule: a.rule, lineIds: a.lineIds })),
606
+ ai: { readId: norm.ai.readId, accepted: norm.ai.accepted, severity: norm.ai.severity },
607
+ now,
608
+ });
609
+ } catch (err) {
610
+ this.warn('decide.ai_outcome_failed', { error: errName(err) });
611
+ return null;
612
+ }
613
+ }
614
+
522
615
  private replayOf(resultJson: string): DecisionResult {
523
616
  const parsed: unknown = JSON.parse(resultJson);
524
617
  const groups = (parsed as { groups?: unknown } | null)?.groups;
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: ResolvedProfile;
56
+ profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'>;
57
57
  /** Every rule, retired ones included, in number order. */
58
58
  rules: CommunityRule[];
59
59
  }
@@ -705,7 +705,12 @@ export function agentBrief(policy: DocumentPolicy): string {
705
705
  */
706
706
  export function policyJson(policy: DocumentPolicy): PolicyJson {
707
707
  const snapshot = checkPolicy(policy);
708
- return { version: 1, profile: structuredClone(snapshot.profile), rules: snapshot.rules.all() };
708
+ // The AI settings, the pace settings and the signal settings are runtime switches, not policy text: the document tools never carry them.
709
+ const profile: Omit<ResolvedProfile, 'ai' | 'pace' | 'signals'> & { ai?: unknown; pace?: unknown; signals?: unknown } = structuredClone(snapshot.profile);
710
+ delete profile.ai;
711
+ delete profile.pace;
712
+ delete profile.signals;
713
+ return { version: 1, profile, rules: snapshot.rules.all() };
709
714
  }
710
715
 
711
716
  /** The four documents bound to one policy, as `cw.documents` exposes them. */
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
+ }