GenClass Options Reference

Every GenClass init option: activation, route scopes, protected endpoints, breaker, shadow mode, veto, action limits, hold budgets and sinks.

This page is the design spec for the configuration options of @genclass/runtime: why each option exists and how the options combine. The reference for each option is API.md and the JSDoc in packages/runtime/src/types.ts; where they differ from this spec, they describe the code. npm i @genclass/runtime@beta installs 0.3.0-beta.5 (npm's beta dist-tag, 2026-11-02); plain npm i @genclass/runtime installs the stable line, 0.2.3 (latest). Items marked 0.3.0 are not in 0.2.x.

Status: built. Most options here shipped in 0.1.0-beta.1 (the CHANGELOG's "Batch 12, 19 options") and are in every later release. New in 0.3.0, not in 0.2.x: detect (§4.19), visual (§4.20), learn.expectations (§4.14), observe's deferred situations (§5.1, §5.3), the model.loadIf device-floor default and inlineFallback: false skipping the model (§4.15; 0.2.x defaulted to { saveData: "lazy" } and ignored inlineFallback: false), the sink adapters, sinks by name and the sink possible flag (§4.11), and, from 0.3.0-beta.2 (2026-10-25, issue 94), rt.summary().requests (§4.11) and the request-stalled check with visual.checks.stallMs (§4.20). aggressiveness (0.1.0-beta.1, runtime batch 11) is specified in API.md, not here; its default is "balanced".

0. Design rules

  1. Every new option narrows behaviour or exports data. None of them widens it. A few defaults differ from today, and every difference makes things safer. They are all listed in §8: the breaker is on, per-subject and per-session limits exist, holdBudgetMs is a hard ceiling, model loading is skipped on small devices and Save-Data connections, hidden tabs skip background evaluation in guard and heal (observe decides those situations when the tab is visible again, §5.1), and query values are redacted in what the model sees. One default widens what is reported, never what is done: observe reports "possible" detections too (detect, §4.19), and decides situations raised while the model loads or the tab is hidden later, reporting them at the possible tier at most (§5.3); detect: "likely" turns both off. Three 0.3.0 fixes also widen what observe reports, with no option (the idle-unload reload §4.18, overwritten writes decided on slow devices, the 100 ms body wait): they can add likely reports, false ones included, at a rate not measured yet.
  2. There is no bug knowledge in config. Options control where the runtime watches or acts, how much it may do, and where findings go. The model alone decides what is wrong. Labels go to reports only by default (§4.4). Tags and correlation ids never reach the model or the gate.
  3. One effective-mode function, and every term can only demote:
effectiveMode(op) = state ∈ {disabled} ? off
                  : min( globalMode        // InitOptions.mode / rt.setMode / URL param (only demotes; ?genclass= / localStorage.genclass in GenClass.init may also raise on a development host, src/devhost.ts; debug:true raises nothing)
                       , sample cap        // 'observe' if sampled out
                       , breaker cap       // breaker.downgradeTo once tripped
                       , route rule.mode ) // first matching routes[] rule
order: off < observe < guard < heal

effectiveAggressiveness is the min of the global value (including ?genclass-aggr, which may only demote, with or without debug:true) and the route value. Explicit policy.thresholds still win. The scope is snapshotted when an op or mutation is created (OpRec.scope) and is never re-classified later. status.mode keeps reporting the requested mode. status.effectiveMode, Report.mode and SinkRecord.mode report the effective mode. 4. Gate order per decision (decide/policy.ts gate()). The first step that stops the action wins, and its reason goes into Decision.reason and explain(): 1. the subject, or the action's target op, is protected → passive, protected 2. the subject is cross-origin → passive, cross-origin (not configurable) 3. the target op's snapshotted scope is off/observe → not offered (notOffered), reason scope 4. modeAllows(effectiveMode, tier), then the existing allow/deny (restriction) and requireDiagnosis 5. thresholds (aggressiveness profile; explicit policy.thresholds win) 6. policy.actionLimits → limit:perMinute|perSubject|perSession 7. onBeforeAction veto → vetoed; if the hook's time pushes a held item past its hold budget → released unchanged, limit:hold 8. execute

shadow runs steps 1–6 at the shadow mode, with a dry-run limit check, against the same model answer. It skips steps 7 and 8.

1. Option summary

# Option Group Default New / extended
1 enabled (+ rt.disable()) activation true new
2 sample activation 1 new
3 routes scope [] new
4 requests {ignore, protect, crossOrigin, labels, labelsToModel, correlate} scope / safety {ignore:[], protect:[], crossOrigin:"observe", labels:[], labelsToModel:false} new
5 breaker (+ rt.breaker.reset()) safety on new
6 shadow safety false new
7 onBeforeAction, vetoMode safety unset, "enforce" new
8 policy.actionLimits (maxActionsPerMinute = deprecated alias) safety {perMinute:60, perSubject:10, perSession:200} new / extended
9 policy.holdBudgetMs safety "auto" semantics tightened
10 redact privacy built-in extended (kind arg)
11 sinks + rt.summary() telemetry [] new
12 session + rt.setSession() telemetry random id, {} new
13 report telemetry "console" extended ("interventions")
14 learn (+ rt.learn.clear(); rt.learned() and expectations 0.3.0) persistence {persist:unset, expectations:false}: nothing stored; with expectations: true, flows stored, profiles in memory (EXPECTATIONS.md §4) extended
15 model.loadIf, model.inlineFallback load {minDeviceMemoryGB:4, saveData:"skip"} (0.3.0; 0.2.x: {saveData:"lazy"}), true new
16 model.threads, model.timeoutMs load "auto", 10000 promoted from internal
17 model.maxDecisionsPerMinute load 30 new
18 model.unloadAfterIdleMs load false new
19 rt.on() typed events: shadow, breaker, limit, modelBudget API none extended
20 detect (0.3.0) reporting "possible" where the effective mode is observe and policy.thresholds.report is unset, else "likely" new
21 visual (0.3.0; + rt.checks(), rt.checkNow(), the check event) measured visual checks "local" in GenClass.init() in a browser, false in createRuntime() new (§4.20); checks.stallMs (0.3.0-beta.2, issue 94)
22 requestTimeoutMs heal off proposed only, not implemented (§4.21)

Built in, with no option: hidden tabs (§5.1): guard and heal skip background situations; observe defers them until the tab is visible. Observe also defers situations raised while the model loads (§5.3).

2. Types (add to types.ts)

export type ModeOrOff = Mode | "off";

export type RequestMatcher =
  | string   // URL prefix or glob ("*/v1/orders*"); strings starting with "/" also match the path
  | RegExp
  | ((r: { url: string; method: string; channel: "fetch" | "xhr" | "ws" | "sse" }) => boolean);

export interface RouteRule {
  match: string | RegExp | ((route: string) => boolean);  // string = exact path or glob ("/admin/*")
  mode?: ModeOrOff;                // demote only
  aggressiveness?: Aggressiveness; // demote only
}

export interface RequestScope {
  ignore?: RequestMatcher[];                    // pass-through, no OpRec
  protect?: RequestMatcher[];                   // never held/retried/replayed/cached/discarded
  crossOrigin?: "observe" | "ignore";           // default "observe"; always passive
  labels?: Array<{ match: RequestMatcher; label: string }>; // names only: [A-Za-z0-9 _-], ≤ 5 words, ≤ 40 chars
  labelsToModel?: boolean;                      // default false (labels only in reports/sinks)
  correlate?: (r: { url: string; method: string; headers: Record<string,string> }) => string | undefined;
}

export interface EnabledSource { get(): boolean; subscribe(cb: (on: boolean) => void): () => void; }

export interface BreakerOptions {
  undos?: number;              // default 2
  errorsAfterAction?: number;  // default 3
  attributionMs?: number;      // default 5000: window after an action in which subject errors count
  windowMs?: number;           // default 600_000
  downgradeTo?: "observe" | "guard"; // default "observe"
  persist?: "session" | false; // default "session"
}

export interface ActionLimits { perMinute?: number; perSubject?: number; perSession?: number; }

export interface ActionRequest {
  action: string; tier: "guard" | "heal"; trigger: TriggerKind;
  subject: string; diagnosis: string; p: number; decisionId: string;
  route?: string; label?: string;
}

export type SinkKind = "detection" | "intervention" | "undo" | "breaker" | "summary" | "error";

export interface SinkRecord {
  schema: 1;
  kind: SinkKind;
  id: string; ts: number;
  sessionId: string;
  tags: Record<string, string | number | boolean>;
  correlationId?: string;      // from requests.correlate; never model-visible
  mode: ModeOrOff;             // effective mode at decision
  route?: string;              // the path the subject's op was created on (else the current one), id-like and email segments as :id, <= 200 chars
  sampled: boolean;
  diagnosis?: string; p?: number;
  detection?: "likely" | "possible"; // kind "detection" (0.3.0, §4.19)
  action?: string; tier?: Tier;
  changed?: string[];          // paths only
  undone?: boolean;
  shadow?: { action: string; tier: Tier; wouldPass: boolean; reason?: string };
  reason?: string;             // protected | cross-origin | scope | vetoed | would-veto | limit:* | ...
  summary?: SessionSummary;
  evidence?: { message?: string; trigger?: TriggerKind; subject?: string; timeline?: string[] };
}

export type SinkFn = (r: SinkRecord) => void | Promise<void>;
export interface SinkObject {
  send: SinkFn;
  kinds?: SinkKind[];
  sampleRate?: number;   // session-deterministic; never drops intervention/undo/breaker
  evidence?: boolean;    // default false
  possible?: boolean;    // 0.3.0, default false: also "possible" detections (§4.19)
  flush?(): Promise<void>;
}
export type Sink = SinkFn | SinkObject;

export interface SessionSummary {
  startedAt: number; durationMs: number;
  detections: Record<string, number>;      // likely detections, by diagnosis
  possibleDetections: Record<string, number>; // 0.3.0: possible detections (§4.19), by diagnosis
  interventions: Record<string, number>;
  undos: number; lateReverts: number;
  denied: Record<string, number>;          // by reason
  shadow: Record<string, number>;
  model: { state: ModelStatus["state"]; p50Ms?: number; p95Ms?: number; decisions: number; dropped: number; hiddenSkipped: number };
  heldMs: { total: number; max: number };
  errors: number;
}

export interface DeviceEnv { deviceMemoryGB?: number; saveData?: boolean; effectiveType?: string; cores?: number; webgpu: boolean; }

export interface RuntimeEvents {
  detect: Detection; decide: Decision; act: ActionRecord;            // existing
  shadow: { decisionId: string; action: string; tier: Tier; wouldPass: boolean; reason?: string };
  breaker: { tripped: boolean; reason: "undos" | "errors" | "reset"; decisionIds: string[]; counts: { undos: number; errors: number } };
  limit: { kind: "perMinute" | "perSubject" | "perSession"; subject: string };
  modelBudget: { decisionsLastMinute: number; dropped: number };
}

Additions to existing interfaces:

export interface ModelOptions {
  // existing: baseUrl, device, worker, preload, ortWasmPaths, cacheName
  loadIf?: { minDeviceMemoryGB?: number; saveData?: "skip" | "lazy" | "ignore" }
         | ((env: DeviceEnv) => boolean | "lazy");
  inlineFallback?: boolean;           // default true
  threads?: number | "auto";          // default min(4, max(1, cores-1))
  timeoutMs?: number;                 // default 10000
  maxDecisionsPerMinute?: number;     // default 30
  unloadAfterIdleMs?: number | false; // default false
}

export interface PolicyOptions {
  // existing ...
  actionLimits?: ActionLimits;
  /** @deprecated use actionLimits.perMinute */
  maxActionsPerMinute?: number;
}

export interface InitOptions {
  // existing ...
  enabled?: boolean | (() => boolean | Promise<boolean>) | EnabledSource;
  sample?: number;
  routes?: RouteRule[];
  requests?: RequestScope;
  breaker?: BreakerOptions | false;
  shadow?: "guard" | "heal" | false;
  onBeforeAction?: (a: ActionRequest) => boolean | void;
  vetoMode?: "enforce" | "report";    // default "enforce"
  report?: "console" | "interventions" | "silent" | ((r: Report) => void);
  redact?: (path: string, value: unknown, kind?: "state" | "url" | "header" | "input") => unknown;
  sinks?: Sink[];
  session?: { id?: string; tags?: Record<string, string | number | boolean> };
  learn?: { persist?: boolean | "local" | "session"; key?: string; version?: string };
}

Runtime API: - New methods: rt.on<K extends keyof RuntimeEvents>(k, cb): () => void, rt.summary(), rt.setSession(p), rt.disable({ undo?: boolean }), rt.breaker.reset(), rt.learn.clear(). - New status fields: state: …|"disabled", effectiveMode, sampled, breaker: {tripped, at?, reason?}, scope: {route?, rule?, mode, aggressiveness}, model.state: …|"skipped"|"unloaded" (+reason), modelBudget: {decisionsLastMinute, dropped}.

3. Shared infrastructure

  • util/match.ts (new): compileMatchers(list, onThrow: "match" | "nomatch").
  • A string containing * is a glob. Any other string is a prefix, matched against the absolute URL and also against the path when it starts with /. A RegExp is used as given.
  • Predicates run inside try/catch. protect treats a throw as a match, while ignore, labels and routes treat it as no match.
  • Results go in an LRU cache keyed by method+" "+url, 256 entries. Matchers are compiled once, in the runtime.ts constructor.
  • OpRec.scope: { mode, aggressiveness, protected, crossOrigin, label?, route?, correlationId? }, set in NetHost.startOp.
  • runtime.ts computeScope() runs on init, on nav, on setMode/setAggressiveness, on a breaker trip or reset, and when enabled changes. It stores this.scope, which is snapshotted per op or mutation.
  • mode is validated in the runtime.ts constructor: any value but observe, guard or heal (from createRuntime, GenClass.init or window.GENCLASS_CONFIG, which cdn/config.ts readWindowConfig checks too, as fromPairs already did for the meta tag and the data attributes) runs as observe, with one warning (since 0.2.3 and 0.3.0-beta.5; before, an unknown value such as "HEAL" fell through minMode and the gate's modeAllows and ran as heal, and ?genclass-mode=observe could not lower it). modeAllows permits a non-passive tier only for guard and heal.
  • URL overrides (?genclass-mode, ?genclass-aggr, ?genclass-sample=0) may only demote, on every host, with or without debug:true (debug is console logging only). ?genclass-sample=1 has no effect: no URL value puts a session in the act cohort. Before 0.2.3 and 0.3.0-beta.2, debug:true let them raise the value and ?genclass-sample=1 under debug forced the act cohort; a link could then raise any site that left debug on in production. The page's own ?genclass= / localStorage.genclass (src/index.ts) may raise the mode only on a development host (src/devhost.ts: http(s) on a loopback name with an explicit port, or *.test). For QA on a staging or production host, set mode / sample per environment, call rt.setMode(), or use the devtools overlay.

4. Options

4.1 enabled and rt.disable()

Type boolean | (() => boolean|Promise<boolean>) | EnabledSource. Default true.

Semantics. - A false value means the model is not downloaded, observers are not installed, and status.state="disabled". All methods become no-ops that return empty values. - While a Promise is pending, the runtime runs in pure pass-through: OpRecs are recorded, but nothing is held, decided or acted on. A rejection or a throw counts as false. - An EnabledSource is read at init and then followed through subscribe. Flipping it to false behaves like rt.disable({ undo:false }). Flipping it back to true re-enables the runtime and loads the model lazily. - rt.disable({ undo }) releases every hold unchanged and uninstalls observers. With undo:true it also calls undo() on every ActionRecord still inside its undo window, newest first, and emits one undo record per action. The model is disposed. - pause()/resume() keep their existing meaning.

Precedence. It beats every other control, including the URL overrides.

Hooks. auto.ts, the runtime.ts constructor, and exec.ts gated(op).

Tests. - false → no model fetch, and app fetches are identical. - An async true after 200 ms → nothing is held in the first 200 ms. - A rejecting or throwing predicate → disabled, with a warning. - An EnabledSource flipped to false mid-session → holds released, mode off. - disable({undo:true}) reverts in-window actions and leaves expired ones alone.

4.2 sample

Type number in [0,1], clamped with a warning. Default 1.

Semantics. Sessions outside the fraction get an observe cap. The model still loads, so they form the comparison group. The bucket is decided once at init as hash(session.id)/2^32 < sample, then frozen and stored in sessionStorage["genclass:bucket"] as act@<sample> or observe@<sample> (wrapped in try/catch). A stored verdict is reused only under the sample it was drawn under, so a deploy that changes sample draws again, and sample: 0 (like 1) never reads or writes it (since 0.2.3 and 0.3.0-beta.5; before, a stored act overrode sample: 0 until the tab closed). A later setSession({id}) does not change it. An app that passes a stable user id gets the same bucket in every tab, which is the intended behaviour. ?genclass-sample=0 always forces observe, and =1 has no effect (since 0.2.3 and 0.3.0-beta.2; before, it forced the act cohort under debug).

Precedence. It is one term of the min. setMode cannot lift it.

Tests. - sample:0 → no actions, and detections are still reported. - 10k ids at 0.05 → 5% ± 0.5%. - Reload → same bucket. - Storage throws → deterministic within the page. - setSession({id}) → bucket unchanged. - sample:0 with a stored act verdict → observe, storage untouched. - A verdict stored under another sample (or in the bare pre-0.2.3 form) → drawn again.

4.3 routes

Type RouteRule[]. Default [].

Semantics. - Rules are evaluated at init and on every installNav callback. The first match wins. A rule can only demote, and a rule that asks for a higher mode is clamped, with one warning. - A string rule is an exact path or a glob, matched against the raw location.pathname and against its normalised form (percent-decoded, ; path parameters dropped, dot segments and repeated slashes resolved, no trailing slash except /; util/match.ts normalizeRoute), so /se%61rch, /search/, //search and /search;x=1 fall under a /search rule, as they reach the same page on most servers (since 0.2.3 and 0.3.0-beta.5; before, such a link escaped the rule and got the global mode). RegExp and predicate rules see both forms. Matching is case-sensitive (/Search is not /search; use a RegExp with the i flag), and /admin/* does not cover /admin itself (use /admin* or a RegExp). status.scope.route stays the raw path. - mode:"off" means ops created on that route are pass-through, though they are still recorded in the timeline. - Ops created under off or observe scope are never the target of an action later, even from another route (gate step 3). - The scope is snapshotted per op, so a write held under heal on route A is decided under heal after navigating to route B. - Per-route allow/deny is out of scope.

Hooks. observe/nav.ts → computeScope(). exec.ts startOp. policy.ts gate() reads g.scope. effectiveGates(c, raw, trigger, level).

Tests. - A /checkout observe rule under global heal → no actions on checkout ops. - A rule above the global mode is clamped and warns. - An op held on route A is decided with A's scope. - An op from an off route is not offered as a target from route B. - RegExp, glob and predicate rules all work, and a throwing predicate is skipped. - /se%61rch, /search/, //search and /search;x=1 fall under a /search rule; /Search does not; /admin/* does not cover /admin.

4.4 requests

Type RequestScope. Default { ignore:[], protect:[], crossOrigin:"observe", labels:[], labelsToModel:false }.

Semantics. - ignore: the request is pure pass-through. There is no OpRec, no hold, no budget count, and no added microtask before the native call. The docs must warn that an ignored request can no longer be seen as a cause. - protect: the request is observed and reported but, in every mode, it is never held, delayed, retried, replayed, hedged, coalesced, answered from cache or discarded. Its hold is skipped at the network boundary, so it adds zero latency. Any action that targets it goes in notOffered, and the gate reason is protected. A throwing predicate counts as protected. onBeforeAction is never called for it. Writes to the store caused by delivering its response are gated normally. (Changed 2026-10-10, SAFETY, pending the owner's confirmation; recorded deviation: ops created while a protected op is ambient inherit the protection, so the writes, timers and follow-up requests its response causes are never acted on either. Presets for money and identity flows: protectPreset("payments", "auth"), or "preset:payments" / "preset:auth" strings; see packages/runtime/INTERCEPTION.md.) - crossOrigin: cross-origin requests are always passive, and this is not configurable. "ignore" treats all of them as ignored. - labels: the first match is attached as scope.label. Labels are sanitised to [A-Za-z0-9 _-], at most 5 words and 40 chars. Anything else is stripped, with one warning. They appear in reports and sinks. They reach the model as label (METHOD /path) only when labelsToModel:true. Labels are names only. Only policy.idempotencyHeaders affects whether retry is offered, and no label text has any policy meaning. - correlate: it is called once per op. Its result is redacted with kind:"header", capped at 128 chars, and stored on SinkRecord.correlationId and Report.correlationId. It never reaches the model or the gate. A throw gives undefined.

Precedence. ignore comes first, then protect, then cross-origin. protect beats allow, heal, eager, thresholds and shadow (shadow records wouldPass:false). The hardcoded tracing-header skip list in fetch.ts stays.

Hooks. - observe/fetch.ts (parseRequest, installFetch), xhr.ts, websocket.ts, eventsource.ts: call host.scopeOf(req) before startOp, then skip the hold when the op is protected. - The situation op-label builder. - policy.ts gate steps 1–3 and permittedActions.

Tests. - An ignored URL → no OpRec and no added microtask. - A protected POST in heal with retry@0.99 → passive with protected, and timing equal to baseline ±1 ms. - A protected WS message is never discarded. - A throwing protect predicate → protected. - Cross-origin under heal → passive with cross-origin. - A label with a newline, punctuation or 8 words is sanitised. - With the default labelsToModel:false, the label is absent from the situation text. - correlate output is on sink records and never in the situation. - Same-origin relative URLs match /api/*. - The match cache is hit on the second call.

4.5 breaker and rt.breaker.reset()

Type BreakerOptions | false. Default { undos:2, errorsAfterAction:3, attributionMs:5000, windowMs:600000, downgradeTo:"observe", persist:"session" }. It is on by default.

Semantics. The breaker trips when either count is reached within windowMs: - undos counts app or user calls to ActionRecord.undo(), plus late reverts the runtime flags itself. Undos from rt.disable({undo:true}) and from the sim harness do not count. - errorsAfterAction counts uncaught errors, unhandled rejections and failed requests (≥500 or a network error) on the same subject within attributionMs after a non-passive action on it. It correlates by subject and time only, which is a demotion signal and not a bug rule.

On a trip: - The mode is capped at downgradeTo, and holds are released unchanged. - A breaker event and a breaker record are emitted, with the decision ids and counts, plus one console warning. - With persist:"session", the trip survives a reload (try/catch).

Only rt.breaker.reset() clears a trip. setMode does not.

Hooks. New decide/breaker.ts. The exec.ts undo wrapper, observe/errors.ts, and endOp for errors. computeScope().

Tests. - 2 undos → capped at observe, the event fires, and the cap survives a reload. - Errors on an unrelated subject → no trip. - An error at 6 s with the default attributionMs → not counted. - attributionMs:10000 → counted. - false → never trips. - reset() restores the mode. - downgradeTo:"guard" under heal → guard. - Storage throws → the trip is kept in memory only.

4.6 shadow

Type "guard" | "heal" | false. Default false.

Semantics. - For each decision, the gate re-runs steps 1–6 at the shadow mode on the same model answer, with no extra inference and a dry-run limit check. Step 7 (veto) and step 8 (execute) are skipped. - The result is stored on Decision.shadow and the SinkRecord.shadow field, and a shadow event fires. - It is a no-op when the shadow mode is not above the effective mode. - It ignores the sample, route and breaker caps on purpose, because it measures what the higher mode would do. It respects protect, cross-origin, op scope (step 3), allow/deny and thresholds. - It prints to the console only under debug.

Hooks. policy.ts gate(c, rate, g, { dryRun:true }), report.ts, summary.ts.