Repository navigation
Expand file tree
/
Copy pathruntime.ts
More file actions
4096 lines (3892 loc) · 185 KB
/
Copy pathruntime.ts
File metadata and controls
4096 lines (3892 loc) · 185 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Runtime: wires trace, state, learn, situation and decide together (CONTRACT §2-§9).
import type {
TelemetryStatus,
AnalyticsStatus,
ActionContext,
ActionDef,
AdapterHandle,
AdapterIO,
ActionRecord,
Answer,
AnswerOf,
AskOptions,
Atom,
ChoiceAnswer,
Clock,
CreateOptions,
LearnOptions,
Decision,
DecisionProvider,
EvaluateRequest,
Explanation,
Guarded,
Mode,
ModelStatus,
Op,
OpKind,
OpStatus,
Plugin,
PluginApi,
Question,
Report,
RtEvent,
Runtime,
StoreInfo,
RuntimeEvents,
RuntimeHooks,
Situation,
SituationDraft,
StandingQuestion,
StoreIO,
StoreOptions,
Tier,
TriggerKind,
UserAction,
Vocabulary,
EffectiveGates,
Aggressiveness,
ActionRequest,
ModeOrOff,
OpScope,
RouteRule,
RequestScope,
SessionSummary,
SinkRecord,
SinkKind,
EnabledSource,
AuditEntry,
AuditKind,
AuditModel,
Expectation,
Learned,
LearnedFlow,
CheckFinding,
} from "./types.js";
import type { VisualStub } from "./visual/start.js";
import { AuditLog, type AuditDraft } from "./decide/audit.js";
import { expandPresets } from "./presets.js";
import { Breaker, breakerConfig } from "./decide/breaker.js";
import { SinkDispatcher, SummaryTracker } from "./decide/summary.js";
import { compileMatchers, compileValued, hash32, normalizeRoute, routeMatches, sanitizeLabel, type CompiledMatcher, type MatchInput } from "./util/match.js";
import { browserClock } from "./clock.js";
import { GenClassUnavailableError } from "./errors.js";
import { EventLog } from "./trace/events.js";
import { OpRegistry, type OpRec, type StartOpts } from "./trace/ops.js";
import { Context, LazyOp } from "./trace/context.js";
import { StoreHub, toChanges, type MutationRec, type StoreRec, type Verdict } from "./state/hub.js";
import { cloneValue, flatten, normalizeLeafKind, type FieldChange, type Leaf } from "./state/fields.js";
import { InvariantMiner } from "./state/invariants.js";
import { Baselines } from "./learn/baselines.js";
import { Cadence } from "./learn/cadence.js";
import { analyzeBody, createdIds, vhash } from "./situation/content.js";
import { commitAmbiguity, failureOf, hostOfSig } from "./situation/evidence.js";
import { Profiles, shapeOf } from "./learn/profiles.js";
// flow expectations: opt-in (learn.expectations) and loaded with a dynamic import only then, so they cost no first-load
// bytes; only their types are imported here
import type { FlowEnv, FlowProfiles } from "./learn/flows.js";
import { RUNTIME_VERSION } from "./version.js";
import { buildSituation, deliveryDroppable, relatedInFlight, type BuildOptions, type BuiltSituation } from "./situation/build.js";
import { computeFacts, NO_BASELINE_STALL_MS } from "./situation/facts.js";
import type { ChainWriteInfo, CreateRec, DeliverySpec, ErrorInfo, OutcomeRec, ReqMeta, SitEnv, SubjectSpec, Violation } from "./situation/env.js";
import { conflictsOn, matchFields, predictedWrites } from "./situation/conflicts.js";
import { installEventSource } from "./observe/eventsource.js";
import { opLabel } from "./situation/describe.js";
import { BUILTIN_ACTIONS, diagnosisVocabulary, PASSIVE, TRIGGER_ACTIONS } from "./situation/questions.js";
import { STATE_CHAR_BUDGET, stateText } from "./situation/serialize.js";
import { DeciderQueue, typicalLatency, type DecideResult } from "./decide/decider.js";
import { aggressivenessLevel, detectionTier, effectiveGates, gate, holdBudget, parseGate, permittedActions, policyConfig, possibleGate, RateLimiter, restriction, type PolicyConfig } from "./decide/policy.js";
import { decisionLine, detectionLine, interventionLine, Reporter } from "./decide/report.js";
import type { ActionEffect, Controller, EndOpts, NetHost, TriggerOpts } from "./decide/exec.js";
import { ResponseCache } from "./observe/cache.js";
import { installFetch } from "./observe/fetch.js";
import { installXHR } from "./observe/xhr.js";
import { installDomUser } from "./observe/dom-user.js";
import { installErrors } from "./observe/errors.js";
import { installNav } from "./observe/nav.js";
import { installStorage } from "./observe/storage.js";
import { installPerf } from "./observe/perf.js";
import { installWebSocket } from "./observe/websocket.js";
import { deviceEnv, memoryFloor, skippedMessage } from "./model/device.js";
import { installTimers } from "./observe/timers.js";
import { defaultRedact, normalizeFieldPath, normalizePath, plural, ratio, secs, truncate, type Redactor } from "./util.js";
import { blockedMessage } from "./model/blocked.js";
import type { ReactDiscovery } from "./discover/react.js";
import type { ReduxDiscovery } from "./discover/redux.js";
import { discoveryRegistry } from "./discover/registry.js";
import type { Captured, DiscoveryHost, ObservedStore, WalkStats } from "./discover/types.js";
const DECISIONS_KEPT = 200;
/**
* A write that applied before its decision arrived (not held, or its hold budget expired) can still be reverted this
* long after it applied. 800 ms (the hold budget's ceiling, HOLD_MAX_MS) since heal/overnight, was 2,000 ms: in the
* demos benchmark every late revert decided ≥ 0.88 s after its write ended in a user-visible bug (5 of 5, two of
* them on clean runs where the reverted write was the right answer), while those decided ≤ 0.65 s were mostly fixes.
* After about a second the user has been looking at the new value; reverting it is a second visible change.
*/
export const LATE_REVERT_MS = 800;
/**
* Non-held triggers (stall, inconsistency, transition, error) are not worth answering after this long, and a held
* subject's answer arriving this long after it was asked is no longer recorded.
*/
export const BACKGROUND_DEADLINE_MS = 5000;
/** A delivery `discard` keeps dropping the chain's writes over newer data for this long. */
const DISCARD_MARK_MS = 10_000;
/** A salient delivery waits at most this long for its body (a buffered clone) before deciding without it. */
const BODY_WAIT_MS = 100;
/**
* Observe: situations built while the model loads (or reloads after model.unloadAfterIdleMs) or while the tab is
* hidden, kept to be decided once the model is ready and the tab visible (oldest dropped beyond this many).
*/
export const DEFERRED_MAX = 32;
/**
* A deferred situation's deadline once it is submitted (one at a time, after the model is ready). Its decision can
* only detect and report (observe never acts), so it may wait behind fresh ones.
*/
export const DEFERRED_DEADLINE_MS = 30_000;
/** Stores the user wrote this recently are not checked for relations at a settled point (typing bursts). */
const TYPING_BURST_SETTLE_MS = 1000;
const STALL_MIN_MS = 500;
const LONG_RUNNING_MS = 10_000;
const PROFILED: ReadonlySet<OpKind> = new Set<OpKind>(["fetch", "xhr", "user", "task", "ws"]);
const TYPING_BURST_MS = 1000;
/** Format of the stored learned state; a value of another format (or runtime version) is discarded, never migrated. */
const LEARN_FORMAT = 2;
/** learn.maxBytes default: the stored learned state (profiles and flows) is trimmed to this many characters. */
const LEARN_MAX_BYTES = 200_000;
/**
* With learn.expectations on, src/learn/flows.ts is imported this long after init, on the injected clock: a 0 ms timer,
* so the next task after init (not an idle callback; the import itself is asynchronous).
*/
const FLOWS_LOAD_MS = 0;
/** An observe-mode situation built while it could not be decided yet (DEFERRED_MAX): decided later, never acting. */
interface Deferred {
spec: SubjectSpec;
built: BuiltSituation;
ctl: Controller;
/** Already ran (observe never holds). */
passive: () => void;
opts: TriggerOpts;
subjectOp: OpRec | null;
block: "protected" | "cross-origin" | "scope" | null;
fn: string | undefined;
/** A delivery whose chain's writes it covers while it waits (see trigger: deliveryPending). */
delivery: OpRec | null;
/** What it waited for, and the counter a drop goes to: failOpen "not-ready", or summary.model.hiddenSkipped. */
why: "not-ready" | "hidden";
/** The page path at the trigger: its decision record's route (telemetry), not the page it is decided on. */
route?: string;
}
interface ExplainRec {
decision: Decision;
situationText: string;
facts: string[];
timeline: string[];
answers: Record<string, Answer>;
action?: ActionRecord;
gates: EffectiveGates;
/** The subject waited for this decision (false: decided in the background). */
held: boolean;
budget: number;
compact: boolean;
/** Automatically discovered state had been recorded when this situation was built (telemetry leaves its text out). */
autoState: boolean;
/** A deferred situation's page path at its trigger (Deferred.route). */
route?: string;
}
/** Internal observation points for telemetry (src/telemetry): counts only, never input to a decision. */
export interface RuntimeTap {
modelError?(e: unknown): void;
/** A salient situation ran the passive action without an answer: "not-ready", "no-answer", "error". */
failOpen?(reason: string, trigger: TriggerKind): void;
}
type Listeners = { [K in keyof RuntimeEvents]: Set<(v: RuntimeEvents[K]) => void> };
const MODE_RANK: Record<ModeOrOff, number> = { off: 0, observe: 1, guard: 2, heal: 3 };
function minMode(a: ModeOrOff, b: ModeOrOff): ModeOrOff {
return MODE_RANK[a] <= MODE_RANK[b] ? a : b;
}
/** Actions this recent can still be rolled back by rt.disable({ undo: true }). */
const UNDO_WINDOW_MS = 60_000;
/** Query and fragment values of URLs in free text → "…" (sink evidence, OPTIONS-SPEC §4.10). */
export function redactUrlText(t: string): string {
return String(t).replace(/([?&#][^=&#\s"]+)=([^&#\s"]*)/g, (_m, k: string) => `${k}=…`);
}
/** The queue request for a built situation (fresh in trigger, or deferred in drainDeferred). */
function evalRequest(built: BuiltSituation, priority: number): EvaluateRequest {
const sit = built.situation;
return { trigger: built.spec.trigger, state: sit.state, questions: sit.questions, priority, subject: built.subjectRef, ...(sit.notOffered ? { notOffered: { ...sit.notOffered } } : {}) };
}
/** The op a decision's subject is about (its trigger op, a write's cause, an error's ambient op). */
function subjectOpOf(spec: SubjectSpec): OpRec | null {
switch (spec.trigger) {
case "mutation":
return spec.m.cause ?? null;
case "request":
case "failure":
case "stall":
case "delivery":
case "transition":
return spec.op;
case "error":
return spec.op ?? null;
default:
return null;
}
}
export interface RuntimeInternals {
readonly hub: StoreHub;
readonly ops: OpRegistry;
readonly events: EventLog;
readonly base: Baselines;
readonly profiles: Profiles;
readonly miner: InvariantMiner;
readonly ctx: Context;
readonly clock: Clock;
}
/** Fan-out siblings start within this window of each other (one callback issuing several requests). */
export const FANOUT_WINDOW_MS = 100;
/**
* A writer that is x's fan-out sibling: a request of the same kind (fetch, xhr) started by the same direct cause
* within FANOUT_WINDOW_MS of x (one timer tick or user action fetching several items at once). See runDelivery.
*/
export function fanOutSibling(
x: { cause?: number | null; kind: string; start: number },
w: { cause?: number | null; kind: string; start: number } | undefined,
): boolean {
return !!w && x.cause !== undefined && x.cause !== null && w.cause === x.cause && w.kind === x.kind && Math.abs(w.start - x.start) <= FANOUT_WINDOW_MS;
}
export class RuntimeImpl implements Runtime {
readonly clock: Clock;
readonly global: Record<string, unknown>;
readonly events: EventLog;
readonly ops = new OpRegistry();
readonly ctx: Context;
readonly hub: StoreHub;
readonly base = new Baselines();
readonly profiles = new Profiles();
/**
* Flow expectations (src/learn/flows.ts; reporting only): null until loaded, and never loaded unless
* learn.expectations is true (opt-in until their false-report rate is measured).
*/
flows: FlowProfiles | null = null;
/** Settles once the flow expectations are loaded (or failed to load, or are off): tests, devtools. */
readonly flowsReady: Promise<void>;
private flowsReadyResolve: () => void = () => undefined;
/** learn.expectations: true. */
private readonly flowsWanted: boolean;
private flowsLoading = false;
private flowsTimer: unknown = null;
/** The learn options the flow layer is configured from when it loads. */
private readonly learnOpts: LearnOptions | undefined;
/** This page load's session ordinal on the origin (the flow layer gets it when it loads). */
private flowSession = 1;
/** Flows read from storage before the flow layer loaded (it takes them then; a save before that keeps them). */
private storedFlows: unknown = undefined;
readonly miner: InvariantMiner;
readonly cache: ResponseCache;
private readonly queue: DeciderQueue;
private readonly reporter: Reporter;
private readonly policy: PolicyConfig;
private readonly rate: RateLimiter;
private readonly redactFn: Redactor;
private readonly triage: "salient" | "always";
private readonly vocab: Vocabulary | undefined;
private readonly hooks: RuntimeHooks;
private readonly settleMs: number;
private readonly budgetOpt: number | "auto";
private budgetScale = 1;
private uniq = 0;
private rateWarnedAt = -Infinity;
private readonly appFn: (() => { title?: string; route?: string }) | undefined;
private readonly debug: boolean;
/** InitOptions.scope: "functions" raises decisions only for activity inside protect()ed functions. */
readonly scope: "app" | "functions";
/** Transition profiles are stored too (an explicit learn.persist; they feed the model, CONTRACT §4). */
private readonly persistProfiles: boolean;
/** Sessions the stored learned state counted when it was loaded. */
private storedSessions = 0;
/** Signatures with a `response` expectation reported and no answer since (one line per run of hangs). */
private readonly respMissed = new Set<string>();
private _mode: Mode;
private paused = false;
private destroyed = false;
/** Automatic state discovery (InitOptions.autoState; src/discover). */
private discovered: { react: ReactDiscovery | null; redux: ReduxDiscovery | null } | null = null;
private captureSeq = 0;
private decider: DecisionProvider | null;
private _ready: Promise<void> | null = null;
private readonly ownsDecider: boolean;
private listeners: Listeners = {
detect: new Set(),
decide: new Set(),
act: new Set(),
event: new Set(),
status: new Set(),
report: new Set(),
shadow: new Set(),
breaker: new Set(),
limit: new Set(),
modelBudget: new Set(),
expectation: new Set(),
check: new Set(),
};
// ---- configuration extensions (OPTIONS-SPEC)
/** "on", "pending" (an async enabled predicate: pass-through), "off" (an EnabledSource flipped off), "disabled". */
private enabledState: "on" | "pending" | "off" | "disabled" = "on";
private sampled = true;
private routes: RouteRule[] = [];
private routeScope: { route?: string; rule?: number; mode: ModeOrOff; aggressiveness: number } = { mode: "heal", aggressiveness: 1 };
private requestsOpt: RequestScope = {};
private mIgnore!: CompiledMatcher<true>;
private mProtect!: CompiledMatcher<true>;
private mLabels!: CompiledMatcher<string>;
private breakerImpl: Breaker | null = null;
private shadowMode: "guard" | "heal" | false = false;
private onBeforeAction: ((a: ActionRequest) => boolean | void) | undefined;
private vetoMode: "enforce" | "report" = "enforce";
private hookWarnedAt = -Infinity;
private limitWarned = new Map<string, number>();
private sinks!: SinkDispatcher;
private auditLog!: AuditLog;
private sum!: SummaryTracker;
private sessionId = "";
private sessionTags: Record<string, string | number | boolean> = {};
/** Held subjects' passive callbacks: released unchanged on disable, breaker trip, hidden tab. */
private heldPassives = new Set<() => void>();
private learnStore: "local" | "session" | null = null;
private learnKey = "genclass:learn";
private learnVersion: string | undefined;
private learnMaxBytes = LEARN_MAX_BYTES;
/**
* The runtime is writing its own state (learned state; the analytics chunk's visit flag, src/analytics/index.ts): the
* storage observer must not record it. Internal.
*/
selfStorage = false;
private reportMode: "console" | "interventions" | "silent" | "fn" = "console";
private uninstall: (() => void)[] = [];
private teardowns: (() => void)[] = [];
/** Telemetry observation points (src/telemetry). */
tap: RuntimeTap | null = null;
/** Measured visual checks (src/visual/start.ts), set by createRuntime when InitOptions.visual allows them. Internal. */
vis: VisualStub | null = null;
/** runtime.telemetry (set by createRuntime). */
telemetry?: TelemetryStatus;
/** runtime.analytics (set by createRuntime; src/analytics/start.ts). */
analytics?: AnalyticsStatus;
private plugins = new Map<Plugin, { cleanup?: () => void }>();
private customActions: ActionDef[] = [];
private standing: StandingQuestion[] = [];
private decisionsBuf: Decision[] = [];
private actionsBuf: ActionRecord[] = [];
private explainMap = new Map<string, ExplainRec>();
private lastBuilt: Partial<Record<TriggerKind, BuiltSituation>> = {};
private storeWriters = new Map<string, Map<string, number>>();
private lastChainMap = new Map<string, string[]>();
private identicalMap = new Map<string, OpRec[]>();
private errorsRecent: { key: string; t: number; op?: number }[] = [];
private settleTimer: unknown = null;
private toProfile: OpRec[] = [];
/** Recent snapshots at which every learned invariant held (newest last). */
private snaps: { t: number; seq: number; values: Map<string, unknown> }[] = [];
private get lastConsistentSnap(): { t: number; seq: number; values: Map<string, unknown> } | null {
return this.snaps.length ? this.snaps[this.snaps.length - 1] : null;
}
private snapshotBefore(seq: number): { t: number; seq: number; values: Map<string, unknown> } | null {
for (let i = this.snaps.length - 1; i >= 0; i--) if (this.snaps[i].seq <= seq) return this.snaps[i];
return null;
}
private episode = new Set<string>();
/** Violations whose rollback the developer undid: not raised again until they hold at a settled point. */
private muted = new Set<string>();
private nextDecision = 0;
private nextAction = 0;
private lastTyping: { e: RtEvent; target: string; t: number } | null = null;
private persistTimer: unknown = null;
private readonly env: SitEnv;
/** Learned schedules / debounces of request signatures (F6). */
private readonly cadence = new Cadence();
/** Create responses of the last 10 s (read-your-writes). */
private createsBuf: CreateRec[] = [];
/** Completed requests of the last 30 s across signatures (failure scope, F5). */
private outcomesBuf: OutcomeRec[] = [];
/** Live channels that went down: path -> when and why (F9 marks when they come back). */
private channelsDown = new Map<string, { t: number; code: number | string; channel: "websocket" | "eventsource" }>();
/** Deliveries released without waiting whose background decision is pending: it covers their chain's writes. */
private deliveryPending = new WeakSet<OpRec>();
/** Deliveries released without a hold whose content analysis waits for the body: cut short at their chain's first write. */
private deliveryAnalysis = new Map<OpRec, () => void>();
/** InitOptions.detect (undefined: "possible" in observe without policy.thresholds.report, else "likely"). */
private readonly detectOpt: "likely" | "possible" | undefined;
/** Observe: situations waiting for the model (loading, reloading) or a visible tab, oldest first (DEFERRED_MAX). */
private deferred: Deferred[] = [];
/** A deferred situation is being decided (they are submitted one at a time). */
private deferring = false;
/** A `ready` subscription that drains the deferred situations is pending. */
private deferWait = false;
constructor(o: CreateOptions & { decider?: DecisionProvider | null; ownsDecider?: boolean } = {}) {
this.clock = o.clock ?? browserClock;
this.global = (o.global ?? globalThis) as Record<string, unknown>;
this.events = new EventLog(o.historySize ?? 500);
this.ctx = new Context(this.clock);
// built-in secret-name redaction always runs first; a custom function can only redact further (OPTIONS-SPEC §4.10)
const custom = o.redact;
this.redactFn = custom
? (path: string, value: unknown, kind?: "state" | "url" | "header" | "input") => {
const b = defaultRedact(path, value);
try {
return custom(path, b, kind);
} catch {
return "[redacted]";
}
}
: defaultRedact;
this.hub = new StoreHub(this.clock, this.ctx, this.events, () => this.redactFn);
this.miner = new InvariantMiner(
() => this.redactFn,
(p) => this.hub.busy(p),
);
this.cache = new ResponseCache(this.clock);
this.policy = policyConfig(o.policy);
this.hub.holdUserWrites = this.policy.holdUserWrites;
this.hub.holdWrites = this.policy.holdWrites;
this.rate = new RateLimiter(() => this.policy.actionLimits);
this.debug = !!o.debug;
this.scope = o.scope === "functions" ? "functions" : "app";
// URL overrides only lower, on every host (OPTIONS-SPEC §3); `debug` is console logging only and never raises them
const url = this.urlParams();
// the mode option itself is validated: anything but the three modes runs as observe (an unknown value used to fall
// through minMode and modeAllows as heal)
const om = o.mode as unknown;
this._mode = om === "observe" || om === "guard" || om === "heal" ? om : "observe";
if (om !== undefined && om !== this._mode) this.warn(`mode must be "observe", "guard" or "heal" (got ${typeof om === "string" ? JSON.stringify(om) : typeof om}); running in observe.`);
const um = url.get("genclass-mode");
if (um === "observe" || um === "guard" || um === "heal") if (MODE_RANK[um] <= MODE_RANK[this._mode]) this._mode = um;
if (o.policy?.maxActionsPerMinute !== undefined && o.policy?.actionLimits?.perMinute !== undefined) this.warn("policy.maxActionsPerMinute is deprecated and ignored when actionLimits.perMinute is set.");
this.triage = o.triage ?? "salient";
// anything but "likely" / "possible" means the default
this.detectOpt = o.detect === "likely" || o.detect === "possible" ? o.detect : undefined;
this.vocab = o.vocabulary;
this.hooks = o.hooks ?? {};
this.settleMs = o.settleMs ?? 60;
// aggressiveness: the URL override (?genclass-aggr=…) may only lower it, on every host
this._aggr = aggressivenessLevel(o.aggressiveness);
const ua = url.get("genclass-aggr");
if (ua) {
const v = aggressivenessLevel(ua);
if (v <= this._aggr) this._aggr = v;
}
this.budgetOpt = o.situation?.budget ?? "auto";
this.appFn = o.app;
// learned state (EXPECTATIONS.md §4): by default nothing is stored. With learn.expectations on (opt-in), the flows
// (reporting only) are stored in localStorage; transition profiles, which feed the model, only with an explicit
// learn.persist (CONTRACT §4); false stores nothing. A DOM test environment (by default) or storage that does not
// work keeps everything in memory.
const lp = o.learn?.persist;
if (o.learn?.key) this.learnKey = o.learn.key;
this.learnOpts = o.learn;
this.flowsWanted = o.learn?.expectations === true && o.enabled !== false;
this.flowsReady = new Promise<void>((r) => (this.flowsReadyResolve = r));
if (!this.flowsWanted) this.flowsReadyResolve();
const want = lp === false || o.enabled === false || (lp === undefined && (!this.flowsWanted || testDom(this.global))) ? null : lp === "session" ? "session" : "local";
this.learnStore = want && this.storageWorks(want) ? want : null;
if (want && !this.learnStore) this.log("learned state is kept in memory: storage is unavailable");
this.persistProfiles = this.learnStore !== null && lp !== undefined;
if (typeof o.learn?.maxBytes === "number" && o.learn.maxBytes > 0) this.learnMaxBytes = Math.floor(o.learn.maxBytes);
const rel = o.session?.tags?.release;
this.learnVersion = o.learn?.version ?? (rel !== undefined ? String(rel) : undefined);
this.decider = o.decider ?? null;
this.ownsDecider = !!o.ownsDecider;
this.queue = new DeciderQueue(this.clock, () => this.decider, (e) => {
// the model could not fit the situation: use smaller automatic budgets from now on
if ((e as { code?: string })?.code === "max_tokens_exceeded") this.budgetScale = Math.max(0.5, this.budgetScale * 0.8);
this.log("model error", e);
try {
this.tap?.modelError?.(e);
} catch {
/* telemetry never breaks the runtime */
}
});
// model.maxDecisionsPerMinute: default 30 for the built-in model; custom providers only when set
const mo = o.model && typeof o.model === "object" ? o.model : undefined;
const mdpm = mo?.maxDecisionsPerMinute ?? (mo && o.ownsDecider ? 30 : undefined);
if (typeof mdpm === "number" && mdpm > 0) this.queue.perMinute = mdpm;
// items may be held only in guard and heal: in observe the queue computes superseded items and ages priorities
this.queue.holds = () => {
const m = this.sessionMode();
return m === "guard" || m === "heal";
};
this.queue.onBudget = (b) => {
this.sum.s.model.dropped = b.dropped;
this.fire("modelBudget", b);
};
this.reportMode = typeof o.report === "function" ? "fn" : (o.report ?? "console");
this.reporter = new Reporter(o.report === "interventions" ? "console" : o.report ?? "console", this.clock, (id) => this.explain(id), (r) => this.fire("report", r));
// session, sinks, summary
this.sum = new SummaryTracker(this.clock);
this.sessionId = typeof o.session?.id === "string" && o.session.id ? o.session.id.slice(0, 128) : this.newSessionId();
this.sessionTags = this.cleanTags(o.session?.tags ?? {});
this.sinks = new SinkDispatcher(o.sinks, this.clock, this.global, (m) => this.warn(m));
this.auditLog = new AuditLog(o.audit, this.clock, (m) => this.warn(m));
// sample: the session's bucket is decided once and frozen (sessionStorage)
this.sampled = this.sampleBucket(o.sample, url.get("genclass-sample"));
// routes, requests
this.routes = Array.isArray(o.routes) ? o.routes : [];
this.requestsOpt = o.requests ?? {};
this.mIgnore = compileMatchers(this.requestsOpt.ignore as never, "nomatch");
// "preset:payments" / "preset:auth" strings stand for those presets' matchers (src/presets.ts)
this.mProtect = compileMatchers(expandPresets(this.requestsOpt.protect, (m) => this.warn(m)) as never, "match");
const labels: { match: never; value: string }[] = [];
let labelWarned = false;
for (const l of this.requestsOpt.labels ?? []) {
const { label, changed } = sanitizeLabel(l?.label ?? "");
if (changed && !labelWarned) {
labelWarned = true;
this.warn("requests.labels: labels are names only ([A-Za-z0-9 _-], ≤ 5 words, ≤ 40 chars); other characters were stripped.");
}
if (label) labels.push({ match: l.match as never, value: label });
}
this.mLabels = compileValued(labels, "nomatch");
// breaker, shadow, veto
const bc = breakerConfig(o.breaker);
if (bc)
this.breakerImpl = new Breaker(bc, this.clock, () => this.storage("session"), (t, counts) => this.onBreakerTrip(t.reason, t.decisionIds, counts));
this.shadowMode = o.shadow === "guard" || o.shadow === "heal" ? o.shadow : false;
this.onBeforeAction = typeof o.onBeforeAction === "function" ? o.onBeforeAction : undefined;
this.vetoMode = o.vetoMode === "report" ? "report" : "enforce";
this.computeScope();
this.env = this.makeEnv();
this.hub.hooks = {
gate: (m) => this.gateMutation(m),
mayHold: () => this.hub.holdWrites && this._mode !== "observe" && this.consultable(null, this._mode),
observeWrite: (m) => this.observeWrite(m),
filter: (m) => this.dropFilter(m),
dropped: (m, dropped, applied) => this.onDropped(m, dropped, applied),
appError: (e, source) => this.reportError(e, { source }),
waitRelated: (m) => this.waitRelated(m),
applied: (m, s, changes, writer) => this.onApplied(m, s, changes, writer),
discarded: () => this.scheduleSettle(),
proposed: (m) => {
if (this.deliveryAnalysis.size) this.finalizeDeliveries(m.cause);
// flow expectations: a response handler that wrote (even an unchanged value, or a write GenClass then held or
// dropped) handled its response; the fields it changed are added when the write applies
const by = m.cause;
if (by && !m.genclass && this.flows?.isOpen(by.root)) this.flow((f) => f.onWrite(by, [by, ...this.ops.ancestors(by, 8)], []));
try {
const h: { id: number; store: string; paths: string[]; cause?: number; changes: ReturnType<typeof toChanges> } = {
id: m.id,
store: m.store,
paths: m.changes.map((c) => c.path),
changes: toChanges(m.changes),
};
if (m.cause) h.cause = m.cause.id;
this.hooks.mutationProposed?.(h);
} catch {
/* hooks never break the app */
}
},
};
this.events.onEvent((e) => this.fire("event", e));
if (this.decider?.onStatus) {
// the model host also notifies while it stays ready (latency stats after the first decision, then every 5 s):
// the "Model ready" line is printed when the model becomes ready, not on each of those updates
let wasReady = false;
const off = this.decider.onStatus((s) => {
this.fire("status", s);
const becameReady = s.state === "ready" && !wasReady;
wasReady = s.state === "ready";
if (becameReady)
this.emitReport({
kind: "status",
message: `[GenClass] Model ready (${[s.model, s.device, s.variant].filter(Boolean).join(", ")}${s.loadMs !== undefined ? `, ${secs(s.loadMs)}` : ""}${s.worker === false ? "; inline on the main thread" : ""}). Mode: ${this._mode}.`,
});
// deferred observe situations: decided once ready; dropped (counted) when the model will not come
// (after the notification: the host may still be finishing its own update)
if (becameReady) void Promise.resolve().then(() => this.drainDeferred());
else if (s.state === "error" || s.state === "skipped" || s.state === "disabled") this.dropDeferred();
// a blocked download (CSP, most often): one warning naming the origin and the fix, instead of the bare error
if (s.state === "error" && s.blocked) this.warnOnce("model-blocked", blockedMessage(s.blocked));
else if (s.state === "error") this.emitReport({ kind: "status", message: `[GenClass] Model unavailable (${s.error ?? "error"}); observing only.` });
else if (s.state === "skipped" && s.reason === "worker-unavailable") this.warnWorkerUnavailable(s);
});
this.uninstall.push(off);
}
// not loaded before the runtime could subscribe: the device floor (model.loadIf, src/model/device.ts) or, with
// preload "eager", a worker that could not be created under inlineFallback: false. Say so once.
const st0 = this.decider?.status;
if (this.ownsDecider && st0?.state === "skipped") {
if (st0.reason === "worker-unavailable") this.warnWorkerUnavailable(st0);
else this.emitReport({ kind: "status", message: skippedMessage(st0.reason, deviceEnv(this.global), memoryFloor(mo)) });
}
if (this.learnStore) this.loadLearn();
// enabled (OPTIONS-SPEC §4.1): false installs nothing; a predicate, Promise or flag runs pass-through until true
const en = o.enabled;
if (en === false) {
this.enabledState = "disabled";
return;
}
// flow expectations (opt-in): imported on the next task after init (a 0 ms timer), never on the first load
if (this.flowsWanted)
this.flowsTimer = this.clock.setTimeout(() => {
this.flowsTimer = null;
this.loadFlows();
}, FLOWS_LOAD_MS);
this.installObservers(o.observe ?? {});
if (o.autoState) this.installDiscovery(o.autoState);
for (const p of o.plugins ?? []) this.use(p);
if (en !== undefined && en !== true) this.followEnabled(en);
const g = this.global as { addEventListener?: (t: string, fn: () => void) => void; removeEventListener?: (t: string, fn: () => void) => void };
if (typeof g.addEventListener === "function") {
let sent = false;
const end = () => {
this.flushLearn();
if (sent) return;
sent = true;
this.emitSummary();
};
const vis = () => {
// visible again: observe situations deferred while hidden are decided now (a model unloaded meanwhile reloads)
if (!this.hidden()) return this.wake();
this.flow((f) => f.onHidden());
end();
};
try {
g.addEventListener("pagehide", end);
(this.global.document as EventTarget | undefined)?.addEventListener?.("visibilitychange", vis);
this.uninstall.push(() => {
g.removeEventListener?.("pagehide", end);
(this.global.document as EventTarget | undefined)?.removeEventListener?.("visibilitychange", vis);
});
} catch {
/* ignore */
}
}
}
// ------------------------------------------------------------------- configuration extensions (OPTIONS-SPEC)
private urlParams(): URLSearchParams {
try {
const search = (this.global.location as { search?: unknown } | undefined)?.search;
if (typeof search === "string" && search) return new URLSearchParams(search);
} catch {
/* no URL */
}
return new URLSearchParams();
}
private warn(msg: string): void {
const con = (this.global.console as Console | undefined) ?? (globalThis as { console?: Console }).console;
con?.warn?.(`[GenClass] ${msg}`);
}
private storage(kind: "local" | "session"): Storage | undefined {
try {
return (kind === "local" ? this.global.localStorage : this.global.sessionStorage) as Storage | undefined;
} catch {
return undefined;
}
}
private newSessionId(): string {
try {
const c = this.global.crypto as { randomUUID?: () => string } | undefined;
if (typeof c?.randomUUID === "function") return c.randomUUID();
} catch {
/* fall through */
}
return `s${hash32(`${this.clock.now()}:${String(this.global.location ? (this.global.location as { href?: string }).href : "")}`).toString(36)}`;
}
/** Session tags: redacted by name, ≤ 20 keys, keys and values ≤ 64 chars. */
private cleanTags(t: Record<string, string | number | boolean>): Record<string, string | number | boolean> {
const out: Record<string, string | number | boolean> = {};
for (const [k0, v] of Object.entries(t ?? {})) {
if (Object.keys(out).length >= 20) break;
if (typeof v !== "string" && typeof v !== "number" && typeof v !== "boolean") continue;
const k = k0.slice(0, 64);
const r = this.redactFn(`session.tags.${k}`, v, "state");
out[k] = typeof r === "string" ? r.slice(0, 64) : typeof r === "number" || typeof r === "boolean" ? r : "[redacted]";
}
return out;
}
/**
* The session's act/observe bucket (OPTIONS-SPEC §4.2): hash(session id) < sample, frozen in sessionStorage as
* `act@<sample>` / `observe@<sample>`, so a verdict drawn under another `sample` (a deploy changed it) is drawn again.
* `?genclass-sample=0` and `sample: 0` put it in the observe bucket without reading storage; no URL value puts it in
* the act bucket.
*/
private sampleBucket(sample: number | undefined, urlSample: string | null): boolean {
if (urlSample === "0") return false;
if (sample === undefined) return true;
let p = Number(sample);
if (!Number.isFinite(p) || p < 0 || p > 1) {
this.warn(`sample must be between 0 and 1 (got ${sample}); clamped.`);
p = Number.isFinite(p) ? Math.min(1, Math.max(0, p)) : 1;
}
if (p >= 1) return true;
if (p <= 0) return false;
const ss = this.storage("session");
const actAt = `act@${p}`;
const observeAt = `observe@${p}`;
try {
const saved = ss?.getItem("genclass:bucket");
if (saved === actAt || saved === observeAt) return saved === actAt;
} catch {
/* deterministic within the page */
}
const act = hash32(this.sessionId) / 4294967296 < p;
try {
ss?.setItem("genclass:bucket", act ? actAt : observeAt);
} catch {
/* ignore */
}
return act;
}
private currentRoute(): string {
const loc = this.global.location as { pathname?: string } | undefined;
return typeof loc?.pathname === "string" ? loc.pathname : "/";
}
/**
* Route scope (OPTIONS-SPEC §4.3): the first rule that matches the raw path or its normalised form (percent-decoded,
* no `;` parameters, dot segments and repeated slashes resolved, no trailing slash), demote only. Recomputed on
* navigation. `scope.route` stays the raw path.
*/
computeScope(): void {
const route = this.currentRoute();
const norm = normalizeRoute(route);
let mode: ModeOrOff = "heal";
let aggr = 1;
let rule: number | undefined;
for (let i = 0; i < this.routes.length; i++) {
const r = this.routes[i];
if (!r || !(routeMatches(r.match, route) || (norm !== route && routeMatches(r.match, norm)))) continue;
rule = i;
if (r.mode === "off" || r.mode === "observe" || r.mode === "guard" || r.mode === "heal") {
if (MODE_RANK[r.mode] > MODE_RANK[this._mode]) {
if (!this.routeWarned.has(i)) {
this.routeWarned.add(i);
this.warn(`routes[${i}] asks for mode ${r.mode} above the global mode ${this._mode}: route rules can only lower it.`);
}
} else mode = r.mode;
}
if (r.aggressiveness !== undefined) aggr = aggressivenessLevel(r.aggressiveness);
break;
}
this.routeScope = { route, ...(rule !== undefined ? { rule } : {}), mode, aggressiveness: aggr };
}
private routeWarned = new Set<number>();
/** min(global mode, sample cap, breaker cap): the session-wide part of the effective mode. */
private sessionMode(): ModeOrOff {
if (this.enabledState !== "on") return "off";
let m: ModeOrOff = this._mode;
if (!this.sampled) m = minMode(m, "observe");
if (this.breakerImpl?.tripped) m = minMode(m, this.breakerImpl.cfg.downgradeTo);
return m;
}
/** The effective mode for a subject: the session part and the op's snapshotted route scope. */
effectiveMode(op?: OpRec | null): ModeOrOff {
return minMode(this.sessionMode(), op?.scope?.mode ?? this.routeScope.mode);
}
/** The effective aggressiveness for a subject: min(global, route scope). */
private effectiveAggr(op?: OpRec | null): number {
return Math.min(this._aggr, op?.scope?.aggressiveness ?? this.routeScope.aggressiveness);
}
/** Scope of a new op (snapshotted). Network ops pass what their observer computed. */
private defaultScope(): OpScope {
const rs = this.routeScope;
return { mode: rs.mode, aggressiveness: rs.aggressiveness, protected: false, crossOrigin: false, ...(rs.route ? { route: rs.route } : {}) };
}
/** A network request's scope, or "ignore" (pass-through, OPTIONS-SPEC §4.4). */
scopeOf(r: MatchInput & { headers?: Record<string, string> }): OpScope | "ignore" {
const cross = this.isCrossOrigin(r.url);
if (cross && this.requestsOpt.crossOrigin === "ignore") return "ignore";
if (this.mIgnore.match(r)) return "ignore";
const sc = this.defaultScope();
sc.crossOrigin = cross;
sc.protected = !!this.mProtect.match(r);
const label = this.mLabels.match(r);
if (label) {
sc.label = label;
if (this.requestsOpt.labelsToModel === true) sc.labelToModel = true;
}
if (this.requestsOpt.correlate) {
try {
const v = this.requestsOpt.correlate({ url: r.url, method: r.method, headers: r.headers ?? {} });
if (typeof v === "string" && v) {
const red = this.redactFn("correlationId", v, "header");
sc.correlationId = String(red).slice(0, 128);
}
} catch {
/* undefined */
}
}
return sc;
}
private isCrossOrigin(url: string): boolean {
try {
const loc = this.global.location as { href?: string } | undefined;
if (!loc?.href) return false;
const base = new URL(loc.href);
const u = new URL(url, base);
if (/^wss?:$/.test(u.protocol)) return u.host !== base.host;
return u.origin !== base.origin;
} catch {
return false;
}
}
private hidden(): boolean {
try {
return (this.global.document as { visibilityState?: string } | undefined)?.visibilityState === "hidden";
} catch {
return false;
}
}
/** Release every held subject unchanged (disable, breaker trip, hidden tab). */
private releaseHolds(): void {
for (const p of [...this.heldPassives]) {
try {
p();
} catch {
/* ignore */
}
}
this.heldPassives.clear();
for (const s of this.hub.stores.values()) if (s.queue.length) this.hub.flushQueue(s);
}
private followEnabled(en: Exclude<NonNullable<CreateOptions["enabled"]>, boolean>): void {
const set = (on: boolean) => {
if (this.destroyed || this.enabledState === "disabled") return;
const from = this.enabledState;
if (on) {
this.enabledState = "on";
if (from !== "on") this.auditControl("enabled", from, "on");
this.fire("status", this.status);
return;
}
this.enabledState = "off";
if (from !== "off") this.auditControl("enabled", from, "off");
this.releaseHolds();
this.fire("status", this.status);
};
if (typeof en === "function") {
this.enabledState = "pending";
let r: boolean | Promise<boolean>;
try {
r = en();
} catch (e) {
this.warn(`enabled() threw (${(e as Error)?.message ?? e}); GenClass stays disabled.`);
this.enabledState = "off";
return;
}
if (r && typeof (r as Promise<boolean>).then === "function")
(r as Promise<boolean>).then(
(v) => set(!!v),
(e) => {
this.warn(`enabled() rejected (${(e as Error)?.message ?? e}); GenClass stays disabled.`);
set(false);
},
);
else set(!!r);
return;
}
const src = en as EnabledSource;
try {
set(!!src.get());
const off = src.subscribe((v) => set(!!v));
if (typeof off === "function") this.uninstall.push(off);
} catch (e) {
this.warn(`enabled source failed (${(e as Error)?.message ?? e}); GenClass stays disabled.`);
this.enabledState = "off";
}
}
// ------------------------------------------------------------------------------------------- audit trail
/** The model in force now, for audit entries (never throws). */
private auditModel(): AuditModel {
const st = this.decider?.status;
if (!st) return { name: "none", state: "off" };
const m: AuditModel = { name: st.model ?? st.variant ?? "custom", state: st.state };
if (st.version) m.version = st.version;
if (st.variant) m.variant = st.variant;
if (st.device) m.device = st.device;
if (st.sha256) m.sha256 = st.sha256;
return m;
}
/** The common part of an audit entry. */
private auditBase(kind: AuditKind, mode: ModeOrOff, aggr: number, op?: OpRec | null): AuditDraft {
const profile = aggr === 0 ? "cautious" : aggr === 0.5 ? "balanced" : aggr === 1 ? "eager" : undefined;
const d: AuditDraft = { at: this.clock.now(), kind, sessionId: this.sessionId, mode, requestedMode: this._mode, aggressiveness: aggr, model: this.auditModel() };
if (profile) d.profile = profile;
if (op?.scope?.label) d.label = op.scope.label;
if (op?.scope?.correlationId) d.correlationId = op.scope.correlationId;
return d;
}
/** Record an audit entry built by `make` (the audit trail never breaks the runtime). */
private pushAudit(make: () => AuditDraft): void {
try {
this.auditLog.push(make());
} catch (e) {
this.log("audit entry failed", e);
}
}
private auditControl(what: NonNullable<AuditEntry["control"]>["what"], from?: string | number, to?: string | number): void {
this.pushAudit(() => ({ ...this.auditBase("control", this.sessionMode(), this._aggr), control: { what, ...(from !== undefined ? { from } : {}), ...(to !== undefined ? { to } : {}) } }));
}
private onBreakerTrip(reason: "undos" | "errors", ids: string[], counts: { undos: number; errors: number }): void {
this.releaseHolds();
this.pushAudit(() => ({ ...this.auditBase("breaker", this.sessionMode(), this._aggr), breaker: { tripped: true, reason, decisionIds: [...ids], counts: { ...counts } } }));
this.fire("breaker", { tripped: true, reason, decisionIds: ids, counts });
const msg = `[GenClass] Circuit breaker tripped (${reason}: ${counts.undos} undos, ${counts.errors} errors after actions); mode capped at ${this.breakerImpl?.cfg.downgradeTo}. rt.breaker.reset() clears it.`;
this.warn(msg.replace(/^\[GenClass\] /, ""));
this.emitReport({ kind: "breaker", message: msg });
this.fire("status", this.status);
}
/** Subject keys an action or an error is attributed to (breaker, perSubject limits): op signatures and stores. */
private subjectKeys(spec: SubjectSpec): string[] {
const keys: string[] = [];
const op = subjectOpOf(spec);
if (op) keys.push(op.name);
if (spec.trigger === "mutation") keys.push(`store:${spec.m.store}`);
return keys;
}
/** Every report goes through here: decorated (mode, session, labels), printed, counted and sent to sinks. */
private emitReport(r: Report, op?: OpRec | null): void {
const sub = op ?? (r.decision ? this.opOfDecision(r.decision) : null);
const out: Report = { ...r, mode: r.decision?.effectiveMode ?? this.effectiveMode(sub), session: { id: this.sessionId, tags: { ...this.sessionTags } } };
if (sub?.scope?.correlationId) out.correlationId = sub.scope.correlationId;
if (sub?.scope?.label) out.label = sub.scope.label;
// a possible detection reaches "report" listeners and a report function only with detect: "possible" asked for
// (the console prints it with console.debug either way; sinks need possible: true)
const quiet = r.kind === "detect" && !this.loud(r.decision);
if (this.reportMode === "interventions" && !(r.kind === "intervene" || r.kind === "undo" || r.kind === "breaker" || r.kind === "error")) {
if (!quiet) this.fire("report", out);
} else this.reporter.emit(out, quiet);
if (r.kind === "detect" && r.decision) this.sum.inc(r.decision.detection === "possible" ? this.sum.s.possibleDetections : this.sum.s.detections, r.decision.diagnosis);
if (r.kind === "intervene" && r.action) {
this.sum.inc(this.sum.s.interventions, r.action.action);